{"record":{"id":"73cb77f603189c0e","repo":"Hmbown/CodeWhale","slug":"trace-duration-exceeds-safely-representable-milliseconds","errorCode":null,"errorMessage":"Trace duration exceeds safely representable milliseconds.","messagePattern":"Trace duration exceeds safely representable milliseconds\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/src/core/ingest.ts","lineNumber":271,"sourceCode":"  if (isOTLP) { const r = fromOTLP(root, maxEvents); all = r.events; origins = r.origins; warnings = r.warnings; }\n  else {\n    const incoming = records ?? [safe];\n    if (incoming.length > maxEvents) throw new Error(`Import exceeds the ${maxEvents.toLocaleString()} event limit.`);\n    all = incoming.map(normalizedEvent);\n  }\n  if (!all.length) throw new Error('The file contains no events.');\n  const groups = new Map<string, WhaleEvent[]>(), ids = new Set<string>();\n  for (const e of all) {\n    const key = `${e.traceId}\\0${e.id}`;\n    if (ids.has(key)) throw new Error(`Duplicate event identity (${e.traceId}, ${e.id}). Import cancelled.`);\n    ids.add(key);\n    const group = groups.get(e.traceId) ?? []; group.push(privacyEvent(e, mode)); groups.set(e.traceId, group);\n    if (groups.size > maxTraces) throw new Error(`This import contains more than ${maxTraces} traces. Split it by trace ID.`);\n  }\n  return [...groups].map(([id, events]) => {\n    events.sort((a, b) => a.startTime - b.startTime || a.id.localeCompare(b.id));\n    const base = isOTLP ? 0 : events[0].startTime;\n    if (!isOTLP && events.some(e => Math.abs(e.endTime - base) > Number.MAX_SAFE_INTEGER)) throw new Error('Trace duration exceeds safely representable milliseconds.');\n    for (const e of events) {\n      if (e.attributes['whalesong.error_onset_ms'] !== undefined) e.attributes['whalesong.error_onset_ms'] = errorOnsetOf(e) - base;\n      e.startTime -= base; e.endTime -= base;\n    }\n    const localIds = new Set(events.map(e => e.id)), missingParents = events.filter(e => e.parentId && !localIds.has(e.parentId)).length;\n    const traceWarnings = [...warnings];\n    if (missingParents) traceWarnings.push(`${missingParents} parent spans are absent from this trace; no parent relationship was invented.`);\n    if (events.some(e => e.openEnded)) traceWarnings.push('Open spans have unknown duration and are displayed as onset-only, not extended into invented activity.');\n    const currencies = new Set(events.filter(e => e.cost !== undefined).map(e => e.costCurrency ?? 'unspecified'));\n    if (currencies.size > 1) traceWarnings.push('Mixed cost currencies: aggregate cost comparison is disabled.');\n    return { id, name: groups.size > 1 ? `${filename} · ${id.slice(0, 8)}` : String(root.name ?? filename),\n      events, duration: Math.max(1, events.reduce((m, e) => Math.max(m, e.endTime, e.startTime, e.status === 'error' ? errorOnsetOf(e) : 0), 0)),\n      originTime: origins.get(id) ?? (root.originTime !== undefined && base === 0 ? str(root.originTime) : `${base} ms`),\n      source: isOTLP ? 'otlp' as const : 'jsonl' as const, privacy: mode, warnings: [...new Set(traceWarnings)],\n      metadata: { ...(mode === 'metadata' ? {} : obj(root.metadata)), timeUnit: 'ms', originUnit: isOTLP ? 'unix-nanoseconds' : 'milliseconds', sourceFilename: filename },\n    };\n  });\n}","sourceCodeStart":253,"sourceCodeEnd":289,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/src/core/ingest.ts#L253-L289","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Fix the offending event timestamps so all events in a trace share a consistent epoch and unit (milliseconds).","Detect outliers before import (e.g. events whose startTime differs from the trace median by years).","Convert second-based timestamps to milliseconds at export time.","Exclude events with sentinel/zero timestamps from the trace file."],"exampleFix":"// before\n{ \"id\": \"a\", \"startTime\": 0, \"endTime\": 1699999999999 } // mixed epoch and zero sentinel\n// after\n{ \"id\": \"a\", \"startTime\": 1699999999000, \"endTime\": 1699999999999 }\n","handlingStrategy":"validation","validationCode":"const starts = events.map(e => e.startTime);\nconst base = Math.min(...starts);\nif (events.some(e => Math.abs(e.endTime - base) > Number.MAX_SAFE_INTEGER)) {\n  throw new Error('Unrepresentable duration: fix timestamp units/sentinels.');\n}","typeGuard":"function hasSaneTimestamps(events: { startTime: number; endTime: number }[]): boolean {\n  const base = Math.min(...events.map(e => e.startTime));\n  return events.every(e => Math.abs(e.endTime - base) <= Number.MAX_SAFE_INTEGER);\n}","tryCatchPattern":"try {\n  importTrace(text);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('safely representable')) {\n    console.error('A trace has absurd timestamp spread; check units and sentinel values.');\n  }\n}","preventionTips":["Emit all timestamps in epoch milliseconds from one consistent clock.","Avoid sentinel values (0, -1) in startTime/endTime.","Convert seconds-based timestamps to milliseconds at the producer.","Sanity-check outlier timestamps (differing by years) before export."],"tags":["timestamps","precision","ingest"],"backgroundTag":"invalid-date-format","analyzedSha":"433685b2024e7bc4c99e1e2e326bcad39b4d9d65","analyzedAt":"2026-09-15T12:24:24.634Z","contentChangedAt":"2026-09-15T12:24:24.634Z","schemaVersion":2},"datasetVersion":"2026-09-22T16:17:23.217Z"}