Skip to content
Merged
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
57 changes: 57 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ import { fileURLToPath } from "node:url";
import type { QuotaCurrentEntry, QuotaCurrentFile, QuotaGatherHeartbeat, SnapshotRecord } from "../src/model.ts";
import {
GATHERER_SOURCE,
CLAUDE_CROSS_TICK_STATE_KEY,
claudeCooldownMs,
isClaudeRateLimitFailure,
parseClaudeCrossTick,
serializeClaudeCrossTick,
type ClaudeCrossTickMemory,
canonicalProviderId,
entriesWithPoolSplits,
entryFromResult,
Expand Down Expand Up @@ -791,6 +797,50 @@ async function main(): Promise<number> {
// whole-fetch timeout). Preserve confirmed lapse rows alongside
// retained siblings: retention must never erase a terminal state
// reported by this tick.
// #5928: cross-tick memory for the _claude read. The fetcher's own
// 429 cooldown/cache live in the long-lived OpenChamber process; this
// oneshot carries its own across ticks (persisted in the state file,
// see quota-gather-map). A success refreshes the last-good entry and
// clears the cooldown; a fresh 429 sets the cooldown from
// Retry-After (fallback 5 min, cap 60 min) and the tick emits the
// last-good entry retained; a tick inside the cooldown likewise
// emits the last-good entry retained instead of surfacing the fresh
// failure. The bare error surfaces only when no read has ever
// succeeded. The 401 dead-token mapping never engages the cooldown.
// Claude only - every other provider flows into the #1268 retention
// below unchanged. (Seam note: the shared listing subcommand still
// performs its own fetch; what the cooldown governs is the
// gatherer's consumption of the claude result, which is the
// aggregator-side seam this fix owns.)
const claudeState = await readState();
let claudeMemory = parseClaudeCrossTick(claudeState.get(CLAUDE_CROSS_TICK_STATE_KEY));
let claudeMemoryDirty = false;
const claudeRun = runs.find((r) => r.id === "_claude");
if (claudeRun) {
const nowMs = Date.now();
const okEntry = claudeRun.entries.find((e) => e.state === "ok" && entryHasMeasuredWindow(e));
if (okEntry) {
const next: ClaudeCrossTickMemory = {
lastGoodEntry: JSON.parse(JSON.stringify(okEntry)) as QuotaCurrentEntry,
cooldownUntil: 0,
};
if (serializeClaudeCrossTick(next) !== serializeClaudeCrossTick(claudeMemory)) {
claudeMemory = next;
claudeMemoryDirty = true;
}
} else {
const failureText = claudeRun.error ?? claudeRun.entries.find((e) => e.error)?.error ?? "";
if (isClaudeRateLimitFailure(failureText) && nowMs >= claudeMemory.cooldownUntil) {
claudeMemory = { ...claudeMemory, cooldownUntil: nowMs + claudeCooldownMs(failureText) };
claudeMemoryDirty = true;
}
if (claudeMemory.lastGoodEntry && nowMs < claudeMemory.cooldownUntil) {
claudeRun.entries = markRetained([claudeMemory.lastGoodEntry], tickAt);
claudeRun.retained = true;
}
}
}

const prevEntries = await readPreviousEntries();
if (prevEntries.length) {
for (const run of runs) {
Expand Down Expand Up @@ -878,6 +928,7 @@ async function main(): Promise<number> {
// Snapshot records: append only what moved, to the aggregator's
// store directly (or the writers' outbox when explicitly routed).
const lastAppended = await readState();
if (claudeMemoryDirty) lastAppended.set(CLAUDE_CROSS_TICK_STATE_KEY, serializeClaudeCrossTick(claudeMemory));
const { records, appended } = recordsFromEntries(entries, lastAppended, OBSERVED_BY);
const valid = records.filter(isSnapshotRecord);
const seen = new Set<string>();
Expand All @@ -900,6 +951,12 @@ async function main(): Promise<number> {
);
}

if (!fresh.length && claudeMemoryDirty) {
await writeAtomic(statePath, JSON.stringify(Object.fromEntries(lastAppended), null, 2) + "\n").catch((err) =>
console.error(`quota-gatherer: state write failed (${err}); next tick may re-append`),
);
}

// Turso: the same readings land in agent_quota_records on the
// same tick (Drew's regular-basis rule). Fail-soft, after the file.
await writeTursoRecords(entries, tickAt);
Expand Down
73 changes: 73 additions & 0 deletions pm-stack/aggregator/src/quota-gather-map.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { describe, expect, test } from "bun:test";
import {
CLAUDE_COOLDOWN_CAP_MS,
CLAUDE_COOLDOWN_FALLBACK_MS,
CLAUDE_CROSS_TICK_STATE_KEY,
claudeCooldownMs,
isClaudeRateLimitFailure,
parseClaudeCrossTick,
retryAfterMsFromFailure,
serializeClaudeCrossTick,
type ClaudeCrossTickMemory,
} from "./quota-gather-map.ts";
import type { QuotaCurrentEntry } from "./model.ts";

const goodEntry = {
providerId: "_claude",
providerName: "Claude",
serviceId: "claude",
state: "ok",
windows: [{ name: "5h", pctOfLimit: 42, resetsAt: null }],
measuredAt: "2026-11-14T13:00:00.000Z",
} as unknown as QuotaCurrentEntry;

describe("claude cross-tick memory (#5928)", () => {
test("state key is the reserved v1 key", () => {
expect(CLAUDE_CROSS_TICK_STATE_KEY).toBe("claudeCrossTick:v1");
});

test("parse: missing or unreadable memory is an empty memory", () => {
expect(parseClaudeCrossTick(undefined)).toEqual({ lastGoodEntry: null, cooldownUntil: 0 });
expect(parseClaudeCrossTick("not json")).toEqual({ lastGoodEntry: null, cooldownUntil: 0 });
expect(parseClaudeCrossTick("{}")).toEqual({ lastGoodEntry: null, cooldownUntil: 0 });
expect(parseClaudeCrossTick('{"lastGoodEntry":42,"cooldownUntil":"soon"}')).toEqual({
lastGoodEntry: null,
cooldownUntil: 0,
});
});

test("serialize/parse round-trips a stored last-good entry and cooldown", () => {
const memory: ClaudeCrossTickMemory = { lastGoodEntry: goodEntry, cooldownUntil: 1760000000000 };
const parsed = parseClaudeCrossTick(serializeClaudeCrossTick(memory));
expect(parsed.cooldownUntil).toBe(1760000000000);
expect(parsed.lastGoodEntry?.providerId).toBe("_claude");
expect(parsed.lastGoodEntry?.windows[0]?.pctOfLimit).toBe(42);
});

test("rate-limit classification: 429 and rate_limit texts engage", () => {
expect(isClaudeRateLimitFailure("HTTP 429 from api.anthropic.com")).toBe(true);
expect(isClaudeRateLimitFailure('{"error":{"type":"rate_limit_error"}}')).toBe(true);
expect(isClaudeRateLimitFailure("Rate limited. Retrying soon.")).toBe(true);
});

test("rate-limit classification: the 401 dead-token mapping never engages", () => {
expect(isClaudeRateLimitFailure("Claude session expired")).toBe(false);
expect(isClaudeRateLimitFailure("Claude session expired (was rate limited earlier)")).toBe(false);
expect(isClaudeRateLimitFailure("connection reset by peer")).toBe(false);
});

test("retry-after parsing accepts header forms and rejects absence", () => {
expect(retryAfterMsFromFailure("Retry-After: 120")).toBe(120_000);
expect(retryAfterMsFromFailure("retry after 45s")).toBe(45_000);
expect(retryAfterMsFromFailure("Rate limited. Retrying soon.")).toBeNull();
expect(retryAfterMsFromFailure("Retry-After: soon")).toBeNull();
});

test("cooldown: Retry-After wins, fallback is 5 min, cap is 60 min", () => {
expect(claudeCooldownMs("Retry-After: 120")).toBe(120_000);
expect(claudeCooldownMs("Rate limited. Retrying soon.")).toBe(CLAUDE_COOLDOWN_FALLBACK_MS);
expect(CLAUDE_COOLDOWN_FALLBACK_MS).toBe(5 * 60_000);
expect(claudeCooldownMs("Retry-After: 7200")).toBe(CLAUDE_COOLDOWN_CAP_MS);
expect(CLAUDE_COOLDOWN_CAP_MS).toBe(60 * 60_000);
});
});
74 changes: 74 additions & 0 deletions pm-stack/aggregator/src/quota-gather-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1099,3 +1099,77 @@ export function markRetained(entries: readonly QuotaCurrentEntry[], failedTickIs
retainedFromFailedTick: failedTickIso,
}));
}
/** #5928: cross-tick memory for the _claude read. The quota fetcher's
* 429 cooldown + last-good cache live inside the long-lived OpenChamber
* process; the gatherer is a fresh oneshot every ~15 min, so both reset
* every tick. The gatherer therefore persists its own copy —
* { lastGoodEntry, cooldownUntil } — as one JSON string value in
* quota-gatherer-state.json under this reserved key (the state file is
* a flat string map; the key round-trips through readState/writeState
* untouched by the snapshot-append bookkeeping). Claude only: every
* other provider's finalize/retention behavior is unchanged. */
export const CLAUDE_CROSS_TICK_STATE_KEY = "claudeCrossTick:v1";

export interface ClaudeCrossTickMemory {
lastGoodEntry: QuotaCurrentEntry | null;
/** Epoch ms; 0 = no cooldown in force. */
cooldownUntil: number;
}

export const CLAUDE_COOLDOWN_FALLBACK_MS = 5 * 60_000;
export const CLAUDE_COOLDOWN_CAP_MS = 60 * 60_000;

export function parseClaudeCrossTick(raw: string | undefined): ClaudeCrossTickMemory {
if (raw) {
try {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed === "object" && parsed !== null) {
const rec = parsed as Record<string, unknown>;
const entry = rec.lastGoodEntry;
const until = rec.cooldownUntil;
return {
lastGoodEntry:
typeof entry === "object" && entry !== null && typeof (entry as QuotaCurrentEntry).providerId === "string"
? (entry as QuotaCurrentEntry)
: null,
cooldownUntil: typeof until === "number" && Number.isFinite(until) && until > 0 ? until : 0,
};
}
} catch {
// unreadable memory = no memory: the read behaves as a first tick
}
}
return { lastGoodEntry: null, cooldownUntil: 0 };
}

export function serializeClaudeCrossTick(memory: ClaudeCrossTickMemory): string {
return JSON.stringify({ lastGoodEntry: memory.lastGoodEntry, cooldownUntil: memory.cooldownUntil });
}

/** A claude failure is a rate-limit failure when the failure text says
* so (HTTP 429 / rate_limit_error / "Rate limited"). The 401 dead-token
* mapping ("Claude session expired") is never a rate limit and must
* not engage the cooldown — it is a credential fault, not pressure. */
export function isClaudeRateLimitFailure(text: string): boolean {
if (/session expired/i.test(text)) return false;
return /\b429\b|rate.?limit/i.test(text);
}

/** Retry-After carried in a failure text, in ms. Accepts the header
* forms "Retry-After: 120" and "retry after 120s"; null when absent or
* unparseable (the caller then applies the fallback). */
export function retryAfterMsFromFailure(text: string): number | null {
const m = /retry[- ]after[:\s]*([0-9]+(?:\.[0-9]+)?)\s*(?:s|sec|secs|second|seconds)?\b/i.exec(text);
if (!m) return null;
const seconds = Number(m[1]);
if (!Number.isFinite(seconds) || seconds < 0) return null;
return Math.round(seconds * 1000);
}

/** Cooldown length for a fresh 429: Retry-After when the failure
* carries one, else the fetcher's 5-minute default; always capped at
* 60 minutes (the issue #5928 fix shape). */
export function claudeCooldownMs(failureText: string): number {
const fromHeader = retryAfterMsFromFailure(failureText);
return Math.min(fromHeader ?? CLAUDE_COOLDOWN_FALLBACK_MS, CLAUDE_COOLDOWN_CAP_MS);
}