Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 58 additions & 9 deletions loopx/control_plane/quota/settlement_readback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, readonly JsonObject[]>;
readonly runsByEffectRef: ReadonlyMap<string, readonly JsonObject[]>;
readonly runPositions: ReadonlyMap<JsonObject, number>;
}

const eventsByTurnCache = new WeakMap<
readonly JsonObject[],
ReadonlyMap<string, readonly JsonObject[]>
>();
const runsIndexCache = new WeakMap<
readonly JsonObject[],
CachedRunsIndex
>();

function freezeIndexedBuckets(index: Map<string, JsonObject[]>): void {
for (const bucket of index.values()) Object.freeze(bucket);
}

function indexEventsByTurn(events: readonly JsonObject[]): ReadonlyMap<string, readonly JsonObject[]> {
const frozen = Object.isFrozen(events);
if (frozen) {
const cached = eventsByTurnCache.get(events);
if (cached !== undefined) return cached;
}
const eventsByTurn = new Map<string, JsonObject[]>();
const runsByTurn = new Map<string, JsonObject[]>();
const runsByEffectRef = new Map<string, JsonObject[]>();
const runPositions = new Map<JsonObject, number>();
for (const event of events) {
appendIndexed(
eventsByTurn,
Expand All @@ -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<string, JsonObject[]>();
const runsByEffectRef = new Map<string, JsonObject[]>();
const runPositions = new Map<JsonObject, number>();
for (const [position, run] of runs.entries()) {
runPositions.set(run, position);
appendIndexed(
Expand All @@ -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,
Expand Down
76 changes: 60 additions & 16 deletions loopx/control_plane/runtime/receipt_log_snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Prefix>();
let retainedBytes = 0;
const decoding = new Map<string, { bytes: Buffer; result: Promise<ReceiptLogSnapshot> }>();

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");
}
Expand All @@ -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);
Expand Down Expand Up @@ -297,7 +314,9 @@ export async function readReceiptLogSnapshotWithStat(
path: string,
schemaVersion?: string,
recoveryKeys: readonly string[] = [],
options?: ReadReceiptLogSnapshotOptions,
): Promise<ReceiptLogSnapshotWithStat> {
const maxRetainedBytes = resolveMaxRetainedBytes(options);
const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]);
const pre = await safePathStat(path);
let bytes: Buffer;
Expand All @@ -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 };
}

Expand All @@ -332,15 +358,16 @@ async function decodeReceiptLogBytes(
schemaVersion: string | undefined,
recoveryKeys: readonly string[],
stable: boolean,
maxRetainedBytes: number = DEFAULT_MAX_RETAINED_BYTES,
): Promise<ReceiptLogSnapshot> {
// 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 {
Expand All @@ -354,7 +381,9 @@ export async function readReceiptLogSnapshot(
path: string,
schemaVersion?: string,
recoveryKeys: readonly string[] = [],
options?: ReadReceiptLogSnapshotOptions,
): Promise<ReceiptLogSnapshot | null> {
const maxRetainedBytes = resolveMaxRetainedBytes(options);
const key = JSON.stringify([resolve(path), schemaVersion ?? null, recoveryKeys]);
let bytes: Buffer;
try {
Expand All @@ -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<ReceiptLogSnapshot> {
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) {
Expand All @@ -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));
Expand Down
31 changes: 22 additions & 9 deletions loopx/control_plane/todos/resume_condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<readonly unknown[], readonly PrMergedEvent[]>();

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 {
Expand Down Expand Up @@ -399,7 +412,7 @@ function resolvePrRepositoryBinding(
}

function matchingPrMerge(
events: PrMergedEvent[],
events: readonly PrMergedEvent[],
targetRef: PrRef,
targetRepo: string,
): JsonObject | null {
Expand Down Expand Up @@ -438,7 +451,7 @@ export function compactTodoResumeMergeEvidence(items: unknown[], events: readonl
}
const facts = new Map<string, JsonObject>();
const diagnostics = new Map<number, Map<string, JsonObject>>();
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"]) {
Expand Down
54 changes: 54 additions & 0 deletions tests/control_plane_ts/quota_settlement_readback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
});
Loading
Loading