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
80 changes: 80 additions & 0 deletions pm-stack/aggregator/src/quota-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,83 @@ export function overlayTursoUsage(services: SaasService[], file: QuotaCurrentFil
out[idx] = { ...svc, conflicts: [...svc.conflicts, flag] };
return out;
}

/**
* Pause between the two quota-current reads (#10816).
*/
export const QUOTA_CURRENT_RETRY_PAUSE_MS = 250;

/** How a quota-current.json read resolved (#10816). */
export type QuotaCurrentReadVerdict = "ok" | "missing" | "unparseable" | "transport";

export interface QuotaCurrentReadResult {
verdict: QuotaCurrentReadVerdict;
file: QuotaCurrentFile | null;
/** Human-readable detail for the transport/unparseable warnings. */
error?: string;
}

const isEnoent = (err: unknown): boolean =>
typeof err === "object" && err !== null && (err as { code?: unknown }).code === "ENOENT";

/**
* Read + parse quota-current.json with one retry (#10816): a single
* failed read is retried once after QUOTA_CURRENT_RETRY_PAUSE_MS, so a
* transient sandbox→laptop transport stall does not collapse into a
* "file missing" verdict. Verdicts:
* - ok: parsed file attached.
* - missing: ENOENT on BOTH attempts (the path never goes absent on
* the writer side — gather-quota.ts writes tmp + rename — so this
* means the gatherer genuinely never wrote).
* - transport: the read failed non-ENOENT at least once and never
* succeeded (wait/retry, not a gatherer investigation).
* - unparseable: the bytes landed but JSON.parse or parseQuotaCurrent
* rejected them (gatherer investigation).
*/
export async function readQuotaCurrentFile(
path: string,
deps?: {
readFile?: (path: string, encoding: "utf8") => Promise<string>;
sleep?: (ms: number) => Promise<void>;
},
): Promise<QuotaCurrentReadResult> {
const read = deps?.readFile ?? ((await import("node:fs/promises")).readFile as typeof import("node:fs/promises").readFile);
const sleep = deps?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
let raw: string | null = null;
let firstErr: unknown = null;
let lastErr: unknown = null;
try {
raw = await read(path, "utf8");
} catch (err) {
firstErr = err;
await sleep(QUOTA_CURRENT_RETRY_PAUSE_MS);
try {
raw = await read(path, "utf8");
} catch (err2) {
lastErr = err2;
}
}
if (raw === null) {
const first = firstErr ?? lastErr;
if (first !== null && lastErr !== null && isEnoent(first) && isEnoent(lastErr)) {
return { verdict: "missing", file: null };
}
const detail = lastErr ?? firstErr;
return {
verdict: "transport",
file: null,
error: detail instanceof Error ? detail.message : String(detail),
};
}
try {
const file = parseQuotaCurrent(JSON.parse(raw));
if (file) return { verdict: "ok", file };
return { verdict: "unparseable", file: null, error: "parseQuotaCurrent rejected the document" };
} catch (err) {
return {
verdict: "unparseable",
file: null,
error: err instanceof Error ? err.message : String(err),
};
}
}
39 changes: 23 additions & 16 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import { poolItemToGhItem } from "../projects.ts";
import { createNeedsDrewSweeper, type NeedsDrewCensus } from "../needs-drew.ts";
import { INITIAL_STANDING_AUTO, sanitizeTierItemExtensions, withUserFallbacks } from "../tier-items.ts";
import { assembleWorkItems } from "../work-items.ts";
import { overlayQuotaCurrent, overlayTursoUsage, parseQuotaCurrent } from "../quota-current.ts";
import { overlayQuotaCurrent, overlayTursoUsage, readQuotaCurrentFile } from "../quota-current.ts";
import { SnapshotStore, type SnapshotsRemote } from "../snapshots.ts";
import { gristDocUrl, kaneoTaskUrl } from "../service-links.ts";
import { fixtureSource } from "./fixtures.ts";
Expand Down Expand Up @@ -848,12 +848,12 @@ export function inFlightBoardItems(section: OrchestrationSection, existing: Boar
* leaves the base services untouched.
*/
async function tursoOverlay(cfg: Config, services: SaasService[]): Promise<SaasService[]> {
try {
const raw = await readFile(cfg.quotaCurrentFile, "utf8");
const file = parseQuotaCurrent(JSON.parse(raw));
if (file) return overlayTursoUsage(services, file);
} catch {
/* no gatherer file (or unreadable): base services stand */
const res = await readQuotaCurrentFile(cfg.quotaCurrentFile);
if (res.verdict === "ok" && res.file) return overlayTursoUsage(services, res.file);
if (res.verdict === "transport") {
console.error(`[quota] WARNING: quota-current read transport failure (${res.error ?? "unknown"}) — base services stand (#10816)`);
} else if (res.verdict === "unparseable") {
console.error(`[quota] WARNING: quota-current file unparseable (${res.error ?? "unknown"}) — base services stand (#10816)`);
}
return services;
}
Expand Down Expand Up @@ -1481,12 +1481,12 @@ export function liveSource(
// PR #4695): a pool the gatherer now reports healthy must clear its
// walled/high-usage actions on the usage strip too.
async function overlayCurrent(base: QuotaView): Promise<QuotaView> {
try {
const raw = await readFile(cfg.quotaCurrentFile, "utf8");
const file = parseQuotaCurrent(JSON.parse(raw));
if (file) return overlayQuotaCurrent(base, file);
} catch {
/* no gatherer file (or unreadable): base view stands */
const res = await readQuotaCurrentFile(cfg.quotaCurrentFile);
if (res.verdict === "ok" && res.file) return overlayQuotaCurrent(base, res.file);
if (res.verdict === "transport") {
console.error(`[quota] WARNING: quota-current read transport failure (${res.error ?? "unknown"}) — base view stands (#10816)`);
} else if (res.verdict === "unparseable") {
console.error(`[quota] WARNING: quota-current file unparseable (${res.error ?? "unknown"}) — base view stands (#10816)`);
}
return base;
}
Expand Down Expand Up @@ -1845,16 +1845,23 @@ export function liveSource(
view = await fix.quota();
}
try {
const raw = await readFile(cfg.quotaCurrentFile, "utf8");
const file = parseQuotaCurrent(JSON.parse(raw));
if (file) {
const res = await readQuotaCurrentFile(cfg.quotaCurrentFile);
if (res.verdict === "ok" && res.file) {
const file = res.file;
provenance.quota += ` · gatherer ${file.generatedAt}`;
const sanitized = file.sanitized;
if (sanitized && sanitized.droppedProviders + sanitized.droppedWindows > 0) {
provenance.quota += ` · sanitized quota-current: dropped ${sanitized.droppedProviders} provider(s), ${sanitized.droppedWindows} window(s)`;
}
return overlayQuotaCurrent(view, file);
}
if (res.verdict === "transport") {
provenance.quota += " · gatherer read transport failure (retry exhausted)";
console.error(`[quota] WARNING: quota-current read transport failure (${res.error ?? "unknown"}) — base view stands (#10816)`);
} else if (res.verdict === "unparseable") {
provenance.quota += " · gatherer file unparseable";
console.error(`[quota] WARNING: quota-current file unparseable (${res.error ?? "unknown"}) — base view stands (#10816)`);
}
} catch {
/* no gatherer file (or unreadable): base view stands */
}
Expand Down
129 changes: 129 additions & 0 deletions pm-stack/aggregator/test/quota-current.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
overlayQuotaCurrent,
overlayTursoUsage,
parseQuotaCurrent,
readQuotaCurrentFile,
QUOTA_CURRENT_FRESH_MS,
QUOTA_CURRENT_FUTURE_SKEW_MS,
} from "../src/quota-current.ts";
Expand Down Expand Up @@ -1524,3 +1525,131 @@ describe("intentionally uninstrumented pools keep their window state (#10684)",
expect(poolOut.freshness?.state).toBe("error");
});
});

describe("readQuotaCurrentFile retry + verdicts (#10816)", () => {
const doc = JSON.stringify({
version: 1,
generatedAt: iso(4 * 60_000),
source: "openchamber-quota",
heartbeat: { tickAt: iso(4 * 60_000), ok: true, durationMs: 900, perProvider: {} },
providers: [
{
providerId: "openai",
providerName: "openai",
serviceId: "openai",
state: "ok",
measuredAt: iso(5 * 60_000),
source: "openchamber-quota",
windows: [],
},
],
});
const noSleep = () => Promise.resolve();
const enoent = () => {
const e = new Error("no such file") as Error & { code: string };
e.code = "ENOENT";
return e;
};
const econn = () => {
const e = new Error("connection reset") as Error & { code: string };
e.code = "ECONNRESET";
return e;
};

test("ok on first read: no retry, file attached", async () => {
let calls = 0;
const res = await readQuotaCurrentFile("/x", {
readFile: async () => {
calls++;
return doc;
},
sleep: noSleep,
});
expect(res.verdict).toBe("ok");
expect(res.file?.providers).toHaveLength(1);
expect(calls).toBe(1);
});

test("transient transport failure recovers on retry", async () => {
let calls = 0;
let sleeps = 0;
const res = await readQuotaCurrentFile("/x", {
readFile: async () => {
calls++;
if (calls === 1) throw econn();
return doc;
},
sleep: async () => {
sleeps++;
},
});
expect(res.verdict).toBe("ok");
expect(calls).toBe(2);
expect(sleeps).toBe(1);
});

test("ENOENT on both attempts is missing", async () => {
const res = await readQuotaCurrentFile("/x", {
readFile: async () => {
throw enoent();
},
sleep: noSleep,
});
expect(res.verdict).toBe("missing");
expect(res.file).toBeNull();
});

test("transport failure on both attempts is transport, not missing", async () => {
const res = await readQuotaCurrentFile("/x", {
readFile: async () => {
throw econn();
},
sleep: noSleep,
});
expect(res.verdict).toBe("transport");
expect(res.error).toContain("connection reset");
});

test("mixed ENOENT then transport is transport (missing needs ENOENT twice)", async () => {
let calls = 0;
const res = await readQuotaCurrentFile("/x", {
readFile: async () => {
calls++;
throw calls === 1 ? enoent() : econn();
},
sleep: noSleep,
});
expect(res.verdict).toBe("transport");
});

test("first success followed by nothing: unparseable on bad JSON", async () => {
const res = await readQuotaCurrentFile("/x", {
readFile: async () => "{not json",
sleep: noSleep,
});
expect(res.verdict).toBe("unparseable");
});

test("structurally rejected document is unparseable", async () => {
const res = await readQuotaCurrentFile("/x", {
readFile: async () => JSON.stringify({ version: 1 }),
sleep: noSleep,
});
expect(res.verdict).toBe("unparseable");
});

test("transport then success still parses", async () => {
const res = await readQuotaCurrentFile("/x", {
readFile: (() => {
let n = 0;
return async () => {
n++;
if (n === 1) throw econn();
return doc;
};
})(),
sleep: noSleep,
});
expect(res.verdict).toBe("ok");
});
});