{"record":{"id":"7bb2b798edc51fef","repo":"mastra-ai/mastra","slug":"tokencostcontrol-requires-maxcost-to-be-a-finite-p","errorCode":null,"errorMessage":"TokenCostControl requires maxCost to be a finite positive number","messagePattern":"TokenCostControl requires maxCost to be a finite positive number","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/processors/processors/token-cost-control.ts","lineNumber":261,"sourceCode":"export class TokenCostControl implements Processor<'token-cost-control', TokenCostControlTripwireMetadata> {\n  public readonly id = 'token-cost-control';\n  public readonly name = 'Token Cost Control';\n\n  private maxCost: number | ((requestContext?: RequestContext) => number);\n  private scope: CostScope;\n  private window: CostWindow;\n  private strategy: 'block' | 'warn';\n  private messageTemplate: string;\n  private warnAtPercent?: number;\n  private includeBreakdown: boolean;\n  private readonly instanceKey = tokenCostControlInstanceCounter++;\n  public onViolation?: (violation: ProcessorViolation) => void | Promise<void>;\n  private observabilityStorage?: ObservabilityStorage;\n  private logger?: IMastraLogger;\n\n  constructor(options: TokenCostControlOptions) {\n    if (typeof options.maxCost === 'number' && (!Number.isFinite(options.maxCost) || options.maxCost <= 0)) {\n      throw new Error('TokenCostControl requires maxCost to be a finite positive number');\n    }\n\n    if (options.warnAtPercent !== undefined) {\n      if (!Number.isFinite(options.warnAtPercent) || options.warnAtPercent <= 0 || options.warnAtPercent >= 100) {\n        throw new Error('TokenCostControl requires warnAtPercent to be a number between 0 and 100 (exclusive)');\n      }\n      this.warnAtPercent = options.warnAtPercent;\n    }\n\n    this.maxCost = options.maxCost;\n    this.scope = options.scope ?? 'resource';\n    this.window = options.window ?? '7d';\n    this.strategy = options.strategy ?? 'block';\n    this.messageTemplate = options.message ?? 'Cost control: estimated cost limit exceeded ({usage}/{limit})';\n    this.includeBreakdown = options.includeBreakdown ?? false;\n  }\n\n  __registerMastra(mastra: Mastra<any, any, any, any, any, any, any, any, any, any>): void {","sourceCodeStart":243,"sourceCodeEnd":279,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/processors/processors/token-cost-control.ts#L243-L279","documentation":"TokenCostControl caps spend per scope using `maxCost`. When `maxCost` is provided as a number it must be finite and strictly greater than 0; NaN, Infinity, 0, and negative values are rejected in the constructor. This early validation avoids building a cost controller with an unusable budget.","triggerScenarios":"`new TokenCostControl({ maxCost: Infinity })`, `maxCost: 0`, `maxCost: -5`, `maxCost: NaN`, or computed values like `budget / requestsPerMonth` when the denominator is 0 (yields Infinity/NaN).","commonSituations":"Budget read from config/env as a string that fails numeric coercion, dividing by a zero request count, using nullish-coalescing that lets NaN through, or typos producing NaN (`Number('abc')`).","solutions":["Set `maxCost` to a positive finite number, e.g. `maxCost: 10` (dollars).","Sanitize computed budgets: `Number.isFinite(v) && v > 0 ? v : fallback`.","Parse env/config with `Number(...)` and validate before constructing.","Omit `maxCost` if you only want warn-at-percent warnings (check which features require it)."],"exampleFix":"// before\nnew TokenCostControl({ maxCost: process.env.BUDGET as unknown as number });\n// after\nconst budget = Number(process.env.BUDGET);\nnew TokenCostControl({ maxCost: Number.isFinite(budget) && budget > 0 ? budget : 10 });","handlingStrategy":"validation","validationCode":"const v = options.maxCost;\nif (v !== undefined && typeof v === 'number' && (!Number.isFinite(v) || v <= 0)) {\n  throw new TypeError(`maxCost must be a finite positive number, got ${v}`);\n}","typeGuard":"function isPositiveFinite(v: unknown): v is number {\n  return typeof v === 'number' && Number.isFinite(v) && v > 0;\n}","tryCatchPattern":"try {\n  controller = new TokenCostControl(opts);\n} catch (e) {\n  if (e.message.includes('maxCost')) {\n    controller = new TokenCostControl({ ...opts, maxCost: DEFAULT_BUDGET });\n  } else throw e;\n}","preventionTips":["Sanitize any computed budget (guard divisions by zero) before passing it.","Coerce env/config strings with Number() and validate finiteness.","Define budgets as named constants rather than inline arithmetic."],"tags":["configuration","validation","cost-control","constructor"],"backgroundTag":"invalid-parameter-value","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}