mastra-ai/mastra · error · Error

TokenCostControl requires maxCost to be a finite positive nu

Error message

TokenCostControl requires maxCost to be a finite positive number

What it means

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.

Source

Thrown at packages/core/src/processors/processors/token-cost-control.ts:261

export class TokenCostControl implements Processor<'token-cost-control', TokenCostControlTripwireMetadata> {
  public readonly id = 'token-cost-control';
  public readonly name = 'Token Cost Control';

  private maxCost: number | ((requestContext?: RequestContext) => number);
  private scope: CostScope;
  private window: CostWindow;
  private strategy: 'block' | 'warn';
  private messageTemplate: string;
  private warnAtPercent?: number;
  private includeBreakdown: boolean;
  private readonly instanceKey = tokenCostControlInstanceCounter++;
  public onViolation?: (violation: ProcessorViolation) => void | Promise<void>;
  private observabilityStorage?: ObservabilityStorage;
  private logger?: IMastraLogger;

  constructor(options: TokenCostControlOptions) {
    if (typeof options.maxCost === 'number' && (!Number.isFinite(options.maxCost) || options.maxCost <= 0)) {
      throw new Error('TokenCostControl requires maxCost to be a finite positive number');
    }

    if (options.warnAtPercent !== undefined) {
      if (!Number.isFinite(options.warnAtPercent) || options.warnAtPercent <= 0 || options.warnAtPercent >= 100) {
        throw new Error('TokenCostControl requires warnAtPercent to be a number between 0 and 100 (exclusive)');
      }
      this.warnAtPercent = options.warnAtPercent;
    }

    this.maxCost = options.maxCost;
    this.scope = options.scope ?? 'resource';
    this.window = options.window ?? '7d';
    this.strategy = options.strategy ?? 'block';
    this.messageTemplate = options.message ?? 'Cost control: estimated cost limit exceeded ({usage}/{limit})';
    this.includeBreakdown = options.includeBreakdown ?? false;
  }

  __registerMastra(mastra: Mastra<any, any, any, any, any, any, any, any, any, any>): void {

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Set `maxCost` to a positive finite number, e.g. `maxCost: 10` (dollars).
  2. Sanitize computed budgets: `Number.isFinite(v) && v > 0 ? v : fallback`.
  3. Parse env/config with `Number(...)` and validate before constructing.
  4. Omit `maxCost` if you only want warn-at-percent warnings (check which features require it).

Example fix

// before
new TokenCostControl({ maxCost: process.env.BUDGET as unknown as number });
// after
const budget = Number(process.env.BUDGET);
new TokenCostControl({ maxCost: Number.isFinite(budget) && budget > 0 ? budget : 10 });
Defensive patterns

Strategy: validation

Validate before calling

const v = options.maxCost;
if (v !== undefined && typeof v === 'number' && (!Number.isFinite(v) || v <= 0)) {
  throw new TypeError(`maxCost must be a finite positive number, got ${v}`);
}

Type guard

function isPositiveFinite(v: unknown): v is number {
  return typeof v === 'number' && Number.isFinite(v) && v > 0;
}

Try / catch

try {
  controller = new TokenCostControl(opts);
} catch (e) {
  if (e.message.includes('maxCost')) {
    controller = new TokenCostControl({ ...opts, maxCost: DEFAULT_BUDGET });
  } else throw e;
}

Prevention

When it happens

Trigger: `new TokenCostControl({ maxCost: Infinity })`, `maxCost: 0`, `maxCost: -5`, `maxCost: NaN`, or computed values like `budget / requestsPerMonth` when the denominator is 0 (yields Infinity/NaN).

Common situations: 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')`).

Understand the failure class

Background: "must be positive", "Invalid value": how libraries reject invalid parameter values (ValueError, ArgumentError, INVALID_PARAMETER_VALUE) — this error's family across 28 libraries.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/7bb2b798edc51fef. Report an issue: GitHub.