fix(ai): reject inferred weekly credits when monthly config has positive limit but malformed fields

- Differentiate explicit zero monthly limit from malformed positive monthly configurations.
- Reject inferred weekly credits when monthly config has a positive limit that fails parsing, preserving the retain-last-good fallback.
- Add unit test verifying rejection of malformed positive monthly payloads.
This commit is contained in:
bubua12
2026-08-12 16:21:55 +08:00
parent 31c77339c2
commit d4832c8c04
2 changed files with 42 additions and 2 deletions
+12 -2
View File
@@ -202,6 +202,10 @@ function parseMonthlyBillingConfig(raw: Record<string, unknown>): XaiMonthlyBill
onDemandUsed: parseOnDemandAmount(raw.onDemandUsed),
};
}
function hasPositiveMonthlyLimit(raw: Record<string, unknown>): boolean {
const limit = parseOnDemandAmount(raw.monthlyLimit);
return limit !== undefined && limit > 0;
}
function buildOnDemandLimit(
onDemandCap: number | undefined,
@@ -384,8 +388,14 @@ export const xaiOauthUsageProvider: UsageProvider = {
if (weekly?.inferredPercent && creditsLooksUnified) {
if (monthly) {
effectiveWeekly = null;
} else if (!monthlyPayload || !isRecord(monthlyPayload) || !isRecord(monthlyPayload.config)) {
effectiveWeekly = null;
} else {
const monthlyConfig =
monthlyPayload && isRecord(monthlyPayload) && isRecord(monthlyPayload.config)
? monthlyPayload.config
: null;
if (!monthlyConfig || hasPositiveMonthlyLimit(monthlyConfig)) {
effectiveWeekly = null;
}
}
}
if (!effectiveWeekly && !monthly) return null;
+30
View File
@@ -305,6 +305,36 @@ describe("xai-oauth usage provider", () => {
expect(report).toBeNull();
});
it("rejects inferred unified weekly usage when monthly config has a positive limit but malformed fields", async () => {
const periodEnd = new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).toISOString();
const periodStart = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const report = await xaiOauthUsageProvider.fetchUsage(
{ provider: "xai-oauth", credential: makeCredential() },
{
fetch: dualBillingFetch(
{
config: {
currentPeriod: {
end: periodEnd,
start: periodStart,
type: "USAGE_PERIOD_TYPE_WEEKLY",
},
isUnifiedBillingUser: true,
},
},
{
config: {
isUnifiedBillingUser: true,
monthlyLimit: { val: 15000 },
// Missing 'used' and billingPeriod dates
},
},
).fetch,
},
);
expect(report).toBeNull();
});
it("falls back to monthly included quota when credits has no percent fields", async () => {
const { fetch, calls } = dualBillingFetch(makeUnifiedCreditsPayload(), makeUnifiedMonthlyPayload());