Hmbown/CodeWhale · error · Error

Trace duration exceeds safely representable milliseconds.

Error message

Trace duration exceeds safely representable milliseconds.

What it means

For non-OTLP imports, event timestamps are re-based so the earliest event starts at 0 by subtracting a base startTime from every event. If any event's offset (endTime - base) exceeds Number.MAX_SAFE_INTEGER, the arithmetic would silently lose precision, so importTrace throws instead.

Solutions

  1. Fix the offending event timestamps so all events in a trace share a consistent epoch and unit (milliseconds).
  2. Detect outliers before import (e.g. events whose startTime differs from the trace median by years).
  3. Convert second-based timestamps to milliseconds at export time.
  4. Exclude events with sentinel/zero timestamps from the trace file.

Example fix

// before
{ "id": "a", "startTime": 0, "endTime": 1699999999999 } // mixed epoch and zero sentinel
// after
{ "id": "a", "startTime": 1699999999000, "endTime": 1699999999999 }
Defensive patterns

Strategy: validation

Validate before calling

const starts = events.map(e => e.startTime);
const base = Math.min(...starts);
if (events.some(e => Math.abs(e.endTime - base) > Number.MAX_SAFE_INTEGER)) {
  throw new Error('Unrepresentable duration: fix timestamp units/sentinels.');
}

Type guard

function hasSaneTimestamps(events: { startTime: number; endTime: number }[]): boolean {
  const base = Math.min(...events.map(e => e.startTime));
  return events.every(e => Math.abs(e.endTime - base) <= Number.MAX_SAFE_INTEGER);
}

Try / catch

try {
  importTrace(text);
} catch (e) {
  if (e instanceof Error && e.message.includes('safely representable')) {
    console.error('A trace has absurd timestamp spread; check units and sentinel values.');
  }
}

Prevention

When it happens

Trigger: A trace whose events span more than about 9e15 ms (~285,000 years) between the earliest startTime and some endTime — practically caused by corrupt or wildly wrong timestamps (e.g. epoch in different units, 0 or sentinel values mixed with real epoch millis).

Common situations: Mixing timestamps in seconds with milliseconds; sentinel timestamps like 0 or -1 in some events; clocks set to epoch while others use real dates; hand-edited JSONL.

Related errors


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

Appendix: source

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

  if (isOTLP) { const r = fromOTLP(root, maxEvents); all = r.events; origins = r.origins; warnings = r.warnings; }
  else {
    const incoming = records ?? [safe];
    if (incoming.length > maxEvents) throw new Error(`Import exceeds the ${maxEvents.toLocaleString()} event limit.`);
    all = incoming.map(normalizedEvent);
  }
  if (!all.length) throw new Error('The file contains no events.');
  const groups = new Map<string, WhaleEvent[]>(), ids = new Set<string>();
  for (const e of all) {
    const key = `${e.traceId}\0${e.id}`;
    if (ids.has(key)) throw new Error(`Duplicate event identity (${e.traceId}, ${e.id}). Import cancelled.`);
    ids.add(key);
    const group = groups.get(e.traceId) ?? []; group.push(privacyEvent(e, mode)); groups.set(e.traceId, group);
    if (groups.size > maxTraces) throw new Error(`This import contains more than ${maxTraces} traces. Split it by trace ID.`);
  }
  return [...groups].map(([id, events]) => {
    events.sort((a, b) => a.startTime - b.startTime || a.id.localeCompare(b.id));
    const base = isOTLP ? 0 : events[0].startTime;
    if (!isOTLP && events.some(e => Math.abs(e.endTime - base) > Number.MAX_SAFE_INTEGER)) throw new Error('Trace duration exceeds safely representable milliseconds.');
    for (const e of events) {
      if (e.attributes['whalesong.error_onset_ms'] !== undefined) e.attributes['whalesong.error_onset_ms'] = errorOnsetOf(e) - base;
      e.startTime -= base; e.endTime -= base;
    }
    const localIds = new Set(events.map(e => e.id)), missingParents = events.filter(e => e.parentId && !localIds.has(e.parentId)).length;
    const traceWarnings = [...warnings];
    if (missingParents) traceWarnings.push(`${missingParents} parent spans are absent from this trace; no parent relationship was invented.`);
    if (events.some(e => e.openEnded)) traceWarnings.push('Open spans have unknown duration and are displayed as onset-only, not extended into invented activity.');
    const currencies = new Set(events.filter(e => e.cost !== undefined).map(e => e.costCurrency ?? 'unspecified'));
    if (currencies.size > 1) traceWarnings.push('Mixed cost currencies: aggregate cost comparison is disabled.');
    return { id, name: groups.size > 1 ? `${filename} · ${id.slice(0, 8)}` : String(root.name ?? filename),
      events, duration: Math.max(1, events.reduce((m, e) => Math.max(m, e.endTime, e.startTime, e.status === 'error' ? errorOnsetOf(e) : 0), 0)),
      originTime: origins.get(id) ?? (root.originTime !== undefined && base === 0 ? str(root.originTime) : `${base} ms`),
      source: isOTLP ? 'otlp' as const : 'jsonl' as const, privacy: mode, warnings: [...new Set(traceWarnings)],
      metadata: { ...(mode === 'metadata' ? {} : obj(root.metadata)), timeUnit: 'ms', originUnit: isOTLP ? 'unix-nanoseconds' : 'milliseconds', sourceFilename: filename },
    };
  });
}

View on GitHub (pinned to 433685b202)