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
35 changes: 25 additions & 10 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,11 @@ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): Prov
// error from the heartbeat — 2026-11-10 the codex run read "ok"
// with no error while the openai.main and _openai credentials were
// both failing token_expired at the provider.
...(firstFailure?.error ? { error: firstFailure.error } : {}),
...(firstFailure?.error
? { error: firstFailure.error }
: onlyLapsed
? { error: entries.find((e) => e.state === "lapsed")?.error }
: {}),
};
}

Expand Down Expand Up @@ -704,21 +708,32 @@ async function main(): Promise<number> {
const prevEntries = await readPreviousEntries();
if (prevEntries.length) {
for (const run of runs) {
if (run.state !== "error" || run.entries.some((e) => e.state === "ok")) continue;
// #8294: a Meta session lapse is temporary (remedy: re-auth on
// the hub), unlike the terminal Go lapse — the pool keeps its
// last good windows visible as stale rows while lapsed, so a
// lapsed Meta run engages retention exactly like an error run,
// and its own credential's readings are retained too.
const metaLapsed = run.state === "lapsed" && run.id === "meta";
if ((run.state !== "error" && !metaLapsed) || run.entries.some((e) => e.state === "ok")) continue;
const retained = lastKnownEntries(prevEntries, run.id);
if (retained.length) {
const lapsed = run.entries.filter((e) => e.state === "lapsed");
// Do not retain the previous ok reading for the same credential
// that has just reported a lapse. Other credentials in the same
// provider run may still retain their last-known readings.
const retainedSiblings = retained.filter(
(previous) =>
!lapsed.some((current) =>
(current.credentialId && previous.credentialId === current.credentialId) ||
(current.credentialLabel &&
previous.credentialLabel?.trim().toLowerCase() === current.credentialLabel.trim().toLowerCase()),
),
);
// (Meta is the exception, per the #8294 note above: its lapse
// is the pool's own session, and retaining its last good
// windows beside the lapsed row is the point.)
const retainedSiblings = metaLapsed
? retained
: retained.filter(
(previous) =>
!lapsed.some((current) =>
(current.credentialId && previous.credentialId === current.credentialId) ||
(current.credentialLabel &&
previous.credentialLabel?.trim().toLowerCase() === current.credentialLabel.trim().toLowerCase()),
),
);
run.entries = [...markRetained(retainedSiblings, tickAt), ...lapsed];
run.retained = retainedSiblings.length > 0;
}
Expand Down
34 changes: 33 additions & 1 deletion pm-stack/aggregator/src/quota-gather-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,32 @@ export function isGoLapseResult(result: QuotaProviderResult): boolean {
);
}

/** The remedy every Meta session-lapse surface must name (#8294). */
export const META_SESSION_LAPSE_REMEDY =
"dev.meta.ai portal session is logged out; re-auth (re-login) in the hub browser profile to restore Meta quota reads";

/**
* A configured Meta result that failed because the dev.meta.ai portal
* session lapsed (#8294). The Meta read rides a live browser session
* on the hub (there is no stored credential — see meta-renewal.ts);
* when that session expires, the provider leg fails session-class
* ("unauthorized", or the exporter's "session-expired" shape) rather
* than with a provider error. A lapsed session has a known remedy
* (re-auth on the hub) and is not a provider failure, so — following
* the OpenCode Go lapse template (#1161 / PR #7898) — it classifies
* as "lapsed", never "error". Unlike the Go lapse this one is
* temporary: the gatherer retains the pool's last good windows as
* stale rows alongside the lapsed entry (see gather-quota.ts).
*/
export function isMetaSessionLapseResult(result: QuotaProviderResult): boolean {
if (canonicalProviderId(result.providerId) !== "_muse" || result.ok || !result.configured) {
return false;
}
if (result.failureClass === "unauthorized") return true;
const error = typeof result.error === "string" ? result.error : "";
return /unauthorized|session-expired|session expired|logged out/i.test(error);
}

/** Map one provider result onto a quota-current entry. */
export function entryFromResult(result: QuotaProviderResult, tickIso: string): QuotaCurrentEntry {
let measuredAt = tickIso;
Expand All @@ -456,7 +482,7 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
}
const state: QuotaCurrentEntry["state"] = result.ok
? "ok"
: isGoLapseResult(result)
: isGoLapseResult(result) || isMetaSessionLapseResult(result)
? "lapsed"
: result.configured
? "error"
Expand Down Expand Up @@ -493,6 +519,12 @@ export function entryFromResult(result: QuotaProviderResult, tickIso: string): Q
if (result.credentialSource) entry.credentialSource = result.credentialSource;
if (result.planLabel) entry.planLabel = result.planLabel;
if (result.error) entry.error = safeProviderReason(result.error);
if (isMetaSessionLapseResult(result)) {
// Name the remedy on the entry itself: this text is what the pool
// note surfaces (quota-current freshness.error), so a lapsed Meta
// session reads as an actionable re-auth state, not a bare error.
entry.error = `session lapsed: ${entry.error ?? "unauthorized"} — ${META_SESSION_LAPSE_REMEDY}`;
}
if (typeof result.failureClass === "string" && result.failureClass !== "") entry.failureClass = result.failureClass;
if (typeof result.lastSuccessAt === "number" && Number.isFinite(result.lastSuccessAt) && result.lastSuccessAt > 0) {
entry.lastSuccessAt = new Date(result.lastSuccessAt).toISOString();
Expand Down
112 changes: 112 additions & 0 deletions pm-stack/aggregator/test/gather-quota.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,118 @@ test("an ok-but-null provider result retains the last good quota row", async ()
}
});

test("a lapsed Meta session retains the last good windows and reports lapsed, not error (#8294)", async () => {
const dir = await mkdtemp(join(tmpdir(), "gather-quota-meta-lapsed-"));

try {
const currentPath = join(dir, "quota-current.json");
const heartbeatPath = join(dir, "quota-gatherer-heartbeat.json");
const statePath = join(dir, "quota-gatherer-state.json");
const snapshotsDir = join(dir, "snapshots");
const outboxPath = join(dir, "snapshots.outbox.jsonl");
const subcommandPath = join(dir, "quota-subcommand.mjs");
const previousAt = "2026-11-06T04:00:00.000Z";
const lapsedResult = {
providerId: "meta",
providerName: "Meta",
ok: false,
configured: true,
fetchedAt: Date.parse("2026-11-06T04:30:00.000Z"),
failureClass: "unauthorized",
error: "unauthorized",
usage: null,
};

await writeFile(
currentPath,
`${JSON.stringify(
{
version: 1,
generatedAt: previousAt,
source: "opencode-quota",
heartbeat: {
tickAt: previousAt,
ok: true,
durationMs: 1,
perProvider: { meta: { state: "ok", ms: 1, rows: 1 } },
},
providers: [
{
providerId: "meta",
providerName: "Meta",
serviceId: "meta",
state: "ok",
measuredAt: previousAt,
source: "opencode-quota",
windows: [
{
name: "weekly",
value: 42,
pctOfLimit: 42,
valueLabel: null,
windowSeconds: 604800,
resetsAt: "2026-11-13T04:00:00.000Z",
measuredAt: previousAt,
source: "opencode-quota",
state: "ok",
},
],
},
],
},
null,
2,
)}\n`,
"utf8",
);
await writeFile(subcommandPath, `console.log(${JSON.stringify(JSON.stringify([lapsedResult]))});\n`, "utf8");

const result = spawnSync(process.execPath, [GATHERER_SCRIPT], {
cwd: dir,
encoding: "utf8",
timeout: 30_000,
env: {
PATH: process.env.PATH ?? "",
HOME: dir,
QUOTA_CURRENT_PATH: currentPath,
QUOTA_HEARTBEAT_PATH: heartbeatPath,
QUOTA_GATHERER_STATE_PATH: statePath,
QUOTA_SNAPSHOTS_DIR: snapshotsDir,
USAGE_SNAPSHOT_OUTBOX_PATH: outboxPath,
QUOTA_SUBCOMMAND: `${process.execPath} ${subcommandPath}`,
QUOTA_SUBCOMMAND_TIMEOUT_MS: "5000",
OPENDESIGN_RENEWAL_DISABLED: "1",
META_RENEWAL_DISABLED: "1",
SUPABASE_QUOTA_SINK: "0",
TURSO_QUOTA_SINK: "0",
},
});

if (result.error || result.status !== 0) {
throw new Error(`gatherer failed: ${result.error?.message ?? result.stderr}\n${result.stdout}`);
}

const output = JSON.parse(await readFile(currentPath, "utf8"));
// The run classifies as lapsed — distinctly from a provider error.
expect(output.heartbeat.perProvider.meta.state).toBe("lapsed");
expect(output.heartbeat.perProvider.meta.error).toContain("re-auth");
const metaRows = output.providers.filter((entry: { serviceId: string }) => entry.serviceId === "meta");
// The lapsed row itself is present and names the remedy.
const lapsedRow = metaRows.find((entry: { state: string }) => entry.state === "lapsed");
expect(lapsedRow).toBeDefined();
expect(lapsedRow.error).toContain("re-auth");
// The last good windows stay visible as a retained stale row
// instead of the pool dropping to a bare error.
const retainedRow = metaRows.find((entry: { retainedFromFailedTick?: string }) => entry.retainedFromFailedTick);
expect(retainedRow).toBeDefined();
expect(retainedRow.windows.map((w: { name: string; pctOfLimit: number }) => [w.name, w.pctOfLimit])).toEqual([
["weekly", 42],
]);
} finally {
await rm(dir, { recursive: true, force: true });
}
});

test("a lapsed Go workspace survives ingest instead of being replaced by last-known retention", async () => {
const dir = await mkdtemp(join(tmpdir(), "gather-quota-lapsed-"));

Expand Down
43 changes: 43 additions & 0 deletions pm-stack/aggregator/test/quota-gather-map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,49 @@ describe("pool splits (#1331)", () => {
expect(sameReason.state).toBe("error");
});

test("Meta session lapse (#8294): session-class failures map to lapsed with the re-auth remedy named", () => {
const base = {
providerId: "meta",
providerName: "Meta",
configured: true,
fetchedAt: Date.parse(TICK),
} as const;
// failureClass-carried unauthorized (the gatherer's session signal).
const byClass = entryFromResult(
{ ...base, ok: false, failureClass: "unauthorized", error: "unauthorized", usage: null },
TICK,
);
expect(byClass.state).toBe("lapsed");
expect(byClass.serviceId).toBe("meta");
expect(byClass.windows).toEqual([]);
expect(byClass.error).toContain("session lapsed");
expect(byClass.error).toContain("re-auth");
// The exporter's own shape: a session-expired error string.
const byError = entryFromResult(
{ ...base, ok: false, error: "session-expired: dev.meta.ai session is logged out", usage: null },
TICK,
);
expect(byError.state).toBe("lapsed");
expect(byError.error).toContain("re-auth");
// Control: a configured Meta failure without the session signal
// stays a provider error.
const failed = entryFromResult({ ...base, ok: false, error: "timeout", usage: null }, TICK);
expect(failed.state).toBe("error");
// Control: the session words on a different provider stay an error.
const other = entryFromResult(
{ providerId: "claude", ok: false, configured: true, error: "unauthorized", usage: null },
TICK,
);
expect(other.state).toBe("error");
// Recovery shape: the next good read is a plain ok entry again.
const recovered = entryFromResult(
{ ...base, ok: true, usage: { windows: { weekly: { usedPercent: 42 } } } },
TICK,
);
expect(recovered.state).toBe("ok");
expect(recovered.error).toBeUndefined();
});

test("Go workspaces without a hub pool stay combined-only; labels match case-insensitively", () => {
expect(goPoolServiceId(entryFromResult(goResult("Home", "cred_home"), TICK))).toBeNull();
expect(goPoolServiceId(entryFromResult(goResult(undefined, "cred_x"), TICK))).toBeNull();
Expand Down
Loading