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
34 changes: 26 additions & 8 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ async function runMetaRenewal(tickAt: string): Promise<void> {

interface ProviderRun {
id: string;
state: "ok" | "error";
state: "ok" | "error" | "lapsed";
ms: number;
entries: QuotaCurrentEntry[];
error?: string;
Expand Down Expand Up @@ -376,13 +376,18 @@ function finalizeRun(id: string, entries: QuotaCurrentEntry[], t0: number): Prov
}
return { id, state: "error", ms: Date.now() - t0, entries, error: reason };
}
const firstBad = entries.find((e) => e.state !== "ok");
const firstFailure = entries.find((e) => e.state !== "ok" && e.state !== "lapsed");
// A run whose only non-ok rows are planned lapses is terminal, not
// failed: reporting it as "error" would trip #1268 retention and
// replace the lapsed rows with last-known ok readings, hiding the
// lapse the hub must show.
const onlyLapsed = entries.length > 0 && entries.every((e) => e.state === "lapsed");
return {
id,
state: anyOk ? "ok" : "error",
state: anyOk ? "ok" : onlyLapsed ? "lapsed" : "error",
Comment thread
dezren39 marked this conversation as resolved.
Resolved
ms: Date.now() - t0,
entries,
...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}),
...(!anyOk && !onlyLapsed && firstFailure?.error ? { error: firstFailure.error } : {}),
};
}

Expand Down Expand Up @@ -687,16 +692,29 @@ async function main(): Promise<number> {
// #1268: an errored run with no ok row of its own retains the
// provider's last-known ok entries from the previous tick instead
// of replacing them with fresh error rows (or with nothing, on a
// whole-fetch timeout). The heartbeat below still reports the run
// as an error, with its reason and the retained row count.
// whole-fetch timeout). Preserve confirmed lapse rows alongside
// retained siblings: retention must never erase a terminal state
// reported by this tick.
const prevEntries = await readPreviousEntries();
if (prevEntries.length) {
for (const run of runs) {
if (run.state !== "error" || run.entries.some((e) => e.state === "ok")) continue;
const retained = lastKnownEntries(prevEntries, run.id);
if (retained.length) {
run.entries = markRetained(retained, tickAt);
run.retained = true;
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()),
),
);
run.entries = [...markRetained(retainedSiblings, tickAt), ...lapsed];
run.retained = retainedSiblings.length > 0;
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions pm-stack/aggregator/src/assets/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -5130,6 +5130,11 @@ pre {
border-color: #d29922;
color: #e3b341;
}
.badge.lapsed {
background: #6e768133;
border-color: #6e7681;
color: #8b949e;
}
.badge.conflict {
background: #bc8cff33;
border-color: #bc8cff;
Expand Down
5 changes: 4 additions & 1 deletion pm-stack/aggregator/src/credential-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type CredentialLifecycleState =
| "ok"
| "expiring"
| "expired"
| "lapsed"
| "rejected"
| "provider-error"
| "not-configured"
Expand Down Expand Up @@ -58,7 +59,8 @@ export function lifecycleForEntry(entry: QuotaCurrentEntry, now = new Date()): C
const error = entry.error ? safeProviderReason(entry.error) : undefined;
let state: CredentialLifecycleState;

if (entry.state === "unconfigured") state = "not-configured";
if (entry.state === "lapsed") state = "lapsed";
else if (entry.state === "unconfigured") state = "not-configured";
else if (entry.state === "error" && /\bClaude session expired\b/i.test(error ?? "")) state = "expired";
else if (
entry.state === "error" &&
Expand Down Expand Up @@ -107,6 +109,7 @@ export function isCredentialLifecycleRow(value: unknown): value is CredentialLif
"ok",
"expiring",
"expired",
"lapsed",
"rejected",
"provider-error",
"not-configured",
Expand Down
14 changes: 11 additions & 3 deletions pm-stack/aggregator/src/digest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,11 @@ export function buildDigest(inputs: DigestInputs): Digest {
}
const cappedQ = cap(items);
const degradedProviders = inputs.quota.pools
.filter((p) => (p.freshness?.state ?? p.state) === "error" || (p.freshness?.state ?? p.state) === "stale")
.filter(
(p) =>
(p.freshness?.state ?? p.state) === "error" ||
(p.freshness?.state ?? p.state) === "stale",

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional, not an omission: the digest's degradedProviders list is the error/stale set — providers whose reads are failing or aging. A lapsed pool is a terminal, successfully-read state (the subscription ended; the read worked), so it surfaces through its pool state and the explicit lapsed pool note rather than the degraded list, the same way it is not counted in the renderer's error-pool count. Keeping it out of "degraded" is what makes the lapsed state distinct from error, which is the point of this PR.

)
.map((p) => p.provider);
quotaSection = {
id: "quota",
Expand Down Expand Up @@ -337,15 +341,19 @@ function quotaPoolNote(pool: QuotaPool, now: Date): string | null {
const worst = pool.windows.reduce((m, w) => Math.max(m, windowPercent(w)), 0);
const parts: string[] = [];
// Provider freshness (#5279 Codex): quota-current marks a pool
// error/stale while retaining its historical windows, but poolState()
// error/stale/lapsed while retaining its historical windows, but poolState()
// derives only utilization — without this, a failed pool with low
// windows would vanish from the outlook and a stale high reading
// would read as a current forecast.
const degraded = pool.freshness?.state ?? (pool.state === "error" || pool.state === "stale" ? pool.state : null);
const degraded = pool.freshness?.state ?? (pool.state === "error" || pool.state === "stale" || pool.state === "lapsed" ? pool.state : null);
if (degraded === "error") {
parts.push(
`provider read error${pool.freshness?.error ? `: ${pool.freshness.error}` : ""} — current readings unavailable; any figures below are the last successful read`,
);
} else if (degraded === "lapsed") {
parts.push(
`provider lapsed${pool.freshness?.error ? `: ${pool.freshness.error}` : ""} — plan cancelled; no current readings`,
);
} else if (degraded === "stale") {
parts.push(
`provider read stale${pool.freshness?.measuredAt ? ` (measured ${pool.freshness.measuredAt})` : ""} — figures are the last read, not current`,
Expand Down
4 changes: 2 additions & 2 deletions pm-stack/aggregator/src/feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ export function isQuotaWindow(v: unknown): v is QuotaWindow {
);
}

const QUOTA_STATES = ["healthy", "near", "walled", "error", "stale"];
const QUOTA_STATES = ["healthy", "near", "walled", "error", "stale", "lapsed"];

/** One quota pool whose own shape is safe to hand to the renderers
* (#2429): an object with a `windows` ARRAY — a non-array windows value
Expand All @@ -583,7 +583,7 @@ export function isQuotaPool(v: unknown): v is QuotaPool {
return true;
}

const QUOTA_FRESHNESS_STATES = ["ok", "stale", "error"];
const QUOTA_FRESHNESS_STATES = ["ok", "stale", "error", "lapsed"];

function isQuotaFreshness(v: unknown): v is PoolFreshness {
return (
Expand Down
17 changes: 9 additions & 8 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,9 @@ export type ProvenanceDetail = Record<keyof Provenance, ProvenanceFacet>;

/** "error"/"stale" are gatherer-overlay states (#1151): the gatherer
* could not read the pool, or its read is past the freshness bound.
* They are never rendered as healthy, and never as zero usage. */
export type QuotaState = "healthy" | "near" | "walled" | "error" | "stale";
* "lapsed" is a confirmed terminal subscription state, not a provider
* failure. None are rendered as healthy or as zero usage. */
export type QuotaState = "healthy" | "near" | "walled" | "error" | "stale" | "lapsed";

/** One usage window a provider exposes (5-hour, weekly, monthly, ...). */
export interface QuotaWindow {
Expand Down Expand Up @@ -322,8 +323,8 @@ export interface QuotaCredentialRow {
export interface PoolFreshness {
measuredAt: string;
source: string;
state: "ok" | "stale" | "error";
/** Why the gatherer could not read the pool, when state is "error". */
state: "ok" | "stale" | "error" | "lapsed";
/** Why the gatherer could not read the pool, when state is "error" or "lapsed". */
error?: string;
}

Expand All @@ -332,7 +333,7 @@ export interface GathererProviderFreshness {
providerId: string;
serviceId: string;
credentialLabel?: string;
state: "ok" | "stale" | "error";
state: "ok" | "stale" | "error" | "lapsed";
measuredAt: string;
source: string;
error?: string;
Expand Down Expand Up @@ -1386,7 +1387,7 @@ export interface QuotaCurrentWindow {
resetsAt: string | null;
measuredAt: string;
source: string;
state: "ok" | "error";
state: "ok" | "error" | "lapsed";
}

export interface QuotaCurrentEntry {
Expand All @@ -1409,7 +1410,7 @@ export interface QuotaCurrentEntry {
/** ISO time of the provider's last successful read, when the quota
* module carries one; lets readers age a degraded row honestly. */
lastSuccessAt?: string;
state: "ok" | "error" | "unconfigured";
state: "ok" | "error" | "lapsed" | "unconfigured";
measuredAt: string;
/** #1268: ISO time of the tick that retained this entry from the
* previous tick after the provider's run errored. The data is
Expand All @@ -1430,7 +1431,7 @@ export interface QuotaGatherHeartbeat {
tickAt: string;
ok: boolean;
durationMs: number;
perProvider: Record<string, { state: "ok" | "error"; ms: number; rows: number; error?: string }>;
perProvider: Record<string, { state: "ok" | "error" | "lapsed"; ms: number; rows: number; error?: string }>;
/** Set when the tick itself failed before any provider ran (import / credential store). */
error?: string;
}
Expand Down
3 changes: 2 additions & 1 deletion pm-stack/aggregator/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now
// #7193 Codex: a pool whose quota read errored or went stale keeps its
// last windows, but the measurement is marked unavailable — never
// derive wall notifications from retained windows in that state.
if (pool.state === "error" || pool.state === "stale") continue;
// A lapsed pool clears its windows at overlay, but still never burns.
if (pool.state === "error" || pool.state === "stale" || pool.state === "lapsed") continue;
const soleDoor = snapshot.soleDoorPoolIds?.has(pool.id) ?? false;
const windows = pool.windows.filter((w) => w.limit !== null);
const percentOf = (w: (typeof windows)[number]) => w.percent ?? (w.used / (w.limit || 1)) * 100;
Expand Down
31 changes: 21 additions & 10 deletions pm-stack/aggregator/src/quota-current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ function isQuotaCurrentWindow(value: unknown): value is QuotaCurrentFile["provid
(value.resetsAt === null || isIsoDate(value.resetsAt)) &&
isIsoDate(value.measuredAt) &&
typeof value.source === "string" &&
(value.state === "ok" || value.state === "error")
(value.state === "ok" || value.state === "error" || value.state === "lapsed")
);
}

Expand All @@ -72,7 +72,7 @@ function isQuotaCurrentEntry(value: unknown): value is QuotaCurrentEntry {
typeof value.providerId === "string" &&
typeof value.providerName === "string" &&
typeof value.serviceId === "string" &&
(value.state === "ok" || value.state === "error" || value.state === "unconfigured") &&
(value.state === "ok" || value.state === "error" || value.state === "lapsed" || value.state === "unconfigured") &&
isIsoDate(value.measuredAt) &&
typeof value.source === "string" &&
(value.credentialWatch === undefined || typeof value.credentialWatch === "boolean") &&
Expand Down Expand Up @@ -138,6 +138,7 @@ export function parseQuotaCurrent(doc: unknown): QuotaCurrentFile | null {
type FreshState = PoolFreshness["state"];

function entryState(entry: QuotaCurrentEntry, nowMs: number): FreshState {
if (entry.state === "lapsed") return "lapsed";
if (entry.state === "ok") {
// #1268: retained last-known entries are stale by definition —
// the provider's latest run failed, however recent the retained
Expand Down Expand Up @@ -271,12 +272,22 @@ function applyEntry(pool: QuotaPool, entry: QuotaCurrentEntry, state: FreshState
state,
};
if (state === "error") freshness.error = !entry.error && legError ? legError : errorText(entry);
if (state === "lapsed") freshness.error = errorText(entry);
pool.freshness = freshness;
if (state === "error") {
pool.state = "error";
adoptEntryWindows(pool, entry);
return false;
}
if (state === "lapsed") {
// A known subscription lapse is not a provider failure. The dated
// quota has no current meaning, so clear it instead of leaving old
// percentages beside a terminal lapsed badge.
pool.state = "lapsed";
pool.windows = [];
delete pool.wallLiftsAt;
return true;
}
if (state === "stale") {
// #6942: a retained entry whose gatherer leg errored is that
// read error surfacing, not mere staleness — but only a pool
Expand Down Expand Up @@ -387,7 +398,7 @@ function credentialRows(entries: QuotaCurrentEntry[], nowMs: number): QuotaCrede
const rows: QuotaCredentialRow[] = [...byCred.values()].map((e) => {
const state = entryState(e, nowMs);
const freshness: PoolFreshness = { measuredAt: e.measuredAt, source: e.source, state };
if (state === "error") freshness.error = errorText(e);
if (state === "error" || state === "lapsed") freshness.error = errorText(e);
return {
label: e.credentialLabel ?? e.providerName ?? e.providerId,
...(e.credentialId ? { credentialId: e.credentialId } : {}),
Expand Down Expand Up @@ -415,7 +426,7 @@ function summarize(file: QuotaCurrentFile, nowMs: number): GathererSummary {
source: e.source,
};
if (e.credentialLabel) s.credentialLabel = e.credentialLabel;
if (s.state === "error") s.error = errorText(e);
if (s.state === "error" || s.state === "lapsed") s.error = errorText(e);
return s;
}),
};
Expand Down Expand Up @@ -448,20 +459,20 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now
else byService.set(e.serviceId, [e]);
}

let anyFreshWindows = false;
let recomputeChoices = false;
const pools = view.pools.map((orig) => {
const entries = byService.get(orig.id);
if (!entries || entries.length === 0) return orig;
const pool: QuotaPool = { ...orig, windows: [...orig.windows] };
const freshOk = entries.filter((e) => entryState(e, nowMs) === "ok").sort(newestFirst(nowMs));
if (freshOk.length > 0) {
if (applyEntry(pool, freshOk[0], "ok")) anyFreshWindows = true;
if (applyEntry(pool, freshOk[0], "ok")) recomputeChoices = true;
const rows = credentialRows(entries, nowMs);
if (rows) pool.credentials = rows;
return pool;
}
const newest = [...entries].sort(newestFirst(nowMs))[0];
applyEntry(pool, newest, entryState(newest, nowMs), legErrorFor(file, newest));
if (applyEntry(pool, newest, entryState(newest, nowMs), legErrorFor(file, newest))) recomputeChoices = true;
return pool;
});

Expand Down Expand Up @@ -491,11 +502,11 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now
};
const freshOk = entries.filter((e) => entryState(e, nowMs) === "ok").sort(newestFirst(nowMs));
if (freshOk.length > 0) {
if (applyEntry(pool, freshOk[0], "ok")) anyFreshWindows = true;
if (applyEntry(pool, freshOk[0], "ok")) recomputeChoices = true;
const rows = credentialRows(entries, nowMs);
if (rows) pool.credentials = rows;
} else {
applyEntry(pool, newest, entryState(newest, nowMs), legErrorFor(file, newest));
if (applyEntry(pool, newest, entryState(newest, nowMs), legErrorFor(file, newest))) recomputeChoices = true;
}
synthesized.push(pool);
}
Expand All @@ -510,7 +521,7 @@ export function overlayQuotaCurrent(view: QuotaView, file: QuotaCurrentFile, now
.filter((entry) => entry.credentialWatch === true)
.map((entry) => lifecycleForEntry(entry, now));
if (credentialLifecycle.length) out.credentialLifecycle = credentialLifecycle;
if (anyFreshWindows) out.choices = computeChoices(allPools, nowMs);
if (recomputeChoices) out.choices = computeChoices(allPools, nowMs);
return out;
}

Expand Down
Loading
Loading