Hmbown/CodeWhale · error · Error

maxEvents must be in [1, 250000].

Error message

maxEvents must be in [1, 250000].

What it means

importTrace bounds options.maxEvents to an integer in [1, 250000]. Values that are non-integers, zero, negative, or above 250000 would either make the import meaningless or exceed the designed memory budget, so they are rejected before parsing.

Solutions

  1. Pass an integer between 1 and 250000, e.g. maxEvents: 50000.
  2. Coerce and clamp user input: maxEvents: Math.min(250000, Math.max(1, Math.trunc(Number(raw)))).
  3. Omit maxEvents to use the default 250000.

Example fix

// before
importTrace(text, 't.json', { maxEvents: Number(process.env.MAX_EVENTS) });
// after
const n = Math.trunc(Number(process.env.MAX_EVENTS));
importTrace(text, 't.json', { maxEvents: Math.min(250000, Math.max(1, n || 250000)) });
Defensive patterns

Strategy: validation

Validate before calling

function clampMaxEvents(raw) {
  const n = Math.trunc(Number(raw));
  if (!Number.isInteger(n) || n < 1 || n > 250000) throw new Error(`maxEvents must be an integer in [1, 250000], got ${raw}`);
  return n;
}

Try / catch

try {
  traces = importTrace(text, file, { maxEvents: opts.maxEvents });
} catch (e) {
  if (e instanceof Error && e.message.includes('maxEvents must be in [1, 250000]')) {
    console.error('Coerce numeric strings via Number() and clamp to [1, 250000]');
  } else throw e;
}

Prevention

When it happens

Trigger: Calling importTrace with options.maxEvents = 0, -1, 1e9, 250000.5, NaN, or a numeric string like '1000' (fails Number.isInteger).

Common situations: Reading the limit from an env var or CLI flag without parsing to an integer; unit confusion (events vs bytes); copy-pasted values from another tool with a different cap.

Understand the failure class

Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@433685b202 (2026-09-15). Data as JSON: /api/errors/9fafd15d6dc3d86e. Report an issue: GitHub.

Appendix: source

Thrown at pet/src/core/ingest.ts:222

    events.push(e);
    for (const [i, record] of list(s.events).entries()) {
      const ea = attributes(record.attributes), time = Number(ns(record.timeUnixNano, 'event.timeUnixNano') - origin) / 1e6;
      const ename = String(record.name ?? 'span event');
      events.push({ schemaVersion: 1, id: `${s.spanId}/event/${i}`, traceId: s.traceId, parentId: s.spanId,
        startTime: time, endTime: time, agentId: e.agentId, name: ename, category: categoryFor(ename, ea),
        status: ename === 'exception' ? 'error' : 'unknown', attributes: ea, raw: { event: record, spanId: s.spanId, resource: rec.resource, scope: rec.scope } });
    }
    if (events.length > maxEvents) throw new Error(`Import exceeds the ${maxEvents.toLocaleString()} event limit, including span events.`);
  }
  return { events, origins: new Map([...bases].map(([k, v]) => [k, v.toString()])), warnings };
}

/** Parse strictly: malformed lines or duplicate identities never disappear silently. */
export function importTrace(text: string, filename = 'Imported trace', options: ImportOptions = {}): Trace[] {
  const mode = options.privacy ?? 'redact', maxEvents = options.maxEvents ?? 250_000;
  if (!['redact', 'metadata', 'retain'].includes(mode)) throw new Error('Unknown privacy mode.');
  const maxTraces = options.maxTraces ?? 8;
  if (!Number.isInteger(maxEvents) || maxEvents < 1 || maxEvents > 250_000) throw new Error('maxEvents must be in [1, 250000].');
  if (!Number.isInteger(maxTraces) || maxTraces < 1 || maxTraces > 64) throw new Error('maxTraces must be in [1, 64].');
  if (new TextEncoder().encode(text).length > (options.maxBytes ?? 64 * 1024 * 1024)) throw new Error('File exceeds the 64 MiB MVP import limit. Split the export by trace.');
  const trimmed = text.replace(/^\uFEFF/, '').trim();
  if (!trimmed) throw new Error('The trace file is empty.');
  let document: unknown;
  try { document = JSON.parse(trimmed); }
  catch {
    document = trimmed.split(/\r?\n/).filter(l => l.trim()).map((line, i) => {
      try { return JSON.parse(line); } catch { throw new Error(`Invalid JSON on nonempty line ${i + 1}. Import cancelled; no rows were skipped.`); }
    });
  }
  // Transform before both normalization and raw retention, so raw cannot bypass redaction.
  const safe = mode === 'retain' ? (options.redactor ? options.redactor(document, '') : document) : redact(document, '', options.redactor);
  const root = obj(safe);
  if(root.format === 'whalesong.evidence/v1') return [evidenceToTrace(validateBundle(root, Math.min(maxEvents, 100_000)))];
  if (isCodewhaleSession(safe)) {
    const trace = fromCodewhaleSession(safe, filename, maxEvents);
    trace.privacy = mode;

View on GitHub (pinned to 433685b202)