{"record":{"id":"f07ce57f2e4f0b1e","repo":"Hmbown/CodeWhale","slug":"record-index-1-endtime-precedes-starttime","errorCode":null,"errorMessage":"Record ${index + 1}: endTime precedes startTime.","messagePattern":"Record (.+?): endTime precedes startTime\\.","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/src/core/ingest.ts","lineNumber":130,"sourceCode":"  return Object.fromEntries(value.filter(x => typeof x?.key === 'string').map(x => [x.key, decodeAnyValue(x.value)]));\n}\nfunction ns(v: unknown, field: string): bigint {\n  if (typeof v === 'number' && !Number.isSafeInteger(v)) throw new Error(`${field} lost precision: encode OTLP nanoseconds as a decimal string.`);\n  const s = String(v ?? '');\n  if (!/^\\d{1,20}$/.test(s) || BigInt(s) > 18446744073709551615n) throw new Error(`Invalid ${field}: expected an OTLP nanosecond integer string.`);\n  return BigInt(s);\n}\nfunction otelStatus(v: unknown): Status {\n  const c = obj(v).code;\n  return c === 2 || c === 'STATUS_CODE_ERROR' ? 'error' : c === 1 || c === 'STATUS_CODE_OK' ? 'success' : 'unknown';\n}\nfunction normalizedEvent(v: unknown, index: number): WhaleEvent {\n  const a = obj(v), id = str(a.id), traceId = str(a.traceId), name = str(a.name);\n  if (!id || !traceId || !name) throw new Error(`Record ${index + 1} requires nonempty id, traceId, and name.`);\n  if (a.schemaVersion !== undefined && a.schemaVersion !== 1) throw new Error(`Record ${index + 1}: unsupported schemaVersion ${a.schemaVersion}.`);\n  const startTime = number(a.startTime, 'startTime', false)!;\n  const endTime = number(a.endTime, 'endTime') ?? startTime;\n  if (endTime < startTime) throw new Error(`Record ${index + 1}: endTime precedes startTime.`);\n  if (a.category !== undefined && !CATEGORIES.includes(a.category)) throw new Error(`Unknown category \"${a.category}\". Use \"other\" plus subtype for extensions.`);\n  const allowed: Status[] = ['pending', 'running', 'success', 'error', 'unknown'];\n  if (a.status !== undefined && !allowed.includes(a.status)) throw new Error(`Record ${index + 1}: invalid status.`);\n  const at = obj(a.attributes);\n  return {\n    schemaVersion: 1, id, traceId, name, parentId: str(a.parentId), startTime, endTime,\n    openEnded: a.endTime === undefined || a.openEnded === true,\n    agentId: str(a.agentId) ?? 'unattributed', agentType: str(a.agentType), parentAgentId: str(a.parentAgentId),\n    category: a.category ?? categoryFor(name, at), subtype: str(a.subtype),\n    model: str(a.model), provider: str(a.provider), tool: str(a.tool),\n    inputTokens: nonnegative(a.inputTokens, 'inputTokens'), outputTokens: nonnegative(a.outputTokens, 'outputTokens'),\n    cachedTokens: nonnegative(a.cachedTokens, 'cachedTokens'), cost: nonnegative(a.cost, 'cost'),\n    costCurrency: str(a.costCurrency), latency: nonnegative(a.latency, 'latency'),\n    contextTokens: nonnegative(a.contextTokens, 'contextTokens'), contextLimit: nonnegative(a.contextLimit, 'contextLimit'),\n    retry: nonnegative(a.retry, 'retry'), status: a.status ?? 'unknown',\n    sourceId: str(a.sourceId), targetId: str(a.targetId), targetType: str(a.targetType),\n    links: list(a.links).filter(x => typeof x?.traceId === 'string' && typeof x?.spanId === 'string'),\n    attributes: at, payload: a.payload, raw: a.raw ?? v,","sourceCodeStart":112,"sourceCodeEnd":148,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/src/core/ingest.ts#L112-L148","documentation":"normalizedEvent validates each ingested trace event record. When an explicit endTime is present, it must be greater than or equal to startTime; otherwise the event's interval is nonsensical. The library throws this error to reject the malformed record rather than silently normalizing the timestamps.","triggerScenarios":"Calling ingest with a JSON record where a.endTime is defined and numeric but strictly less than a.startTime, e.g. {id:'1', traceId:'t', name:'span', startTime:100, endTime:50}. endTime may come from number(a.endTime,'endTime') or default to startTime (which never trips this).","commonSituations":"Producers emitting relative vs absolute clocks inconsistently; unit mismatch (seconds vs milliseconds) between the two timestamps; clocks resynchronized mid-span on the emitting host; hand-written test fixtures with swapped values.","solutions":["Fix the source record so endTime >= startTime (or omit endTime to inherit startTime and mark it open-ended).","Check producer units: convert seconds to milliseconds (or ns) so both timestamps share one unit.","Clamp or drop offending records upstream before calling ingest, if you want lenient importing."],"exampleFix":"// before\n{ \"id\": \"a1\", \"traceId\": \"t1\", \"name\": \"db.query\", \"startTime\": 1712345678900, \"endTime\": 1712345678800 }\n// after\n{ \"id\": \"a1\", \"traceId\": \"t1\", \"name\": \"db.query\", \"startTime\": 1712345678800, \"endTime\": 1712345678900 }","handlingStrategy":"validation","validationCode":"function validInterval(rec) {\n  if (typeof rec.startTime !== 'number' || typeof rec.endTime !== 'number') return true; // endTime optional\n  return rec.endTime >= rec.startTime;\n}\nif (!validInterval(record)) throw new Error('endTime must be >= startTime');","typeGuard":"const hasValidInterval = (r: { startTime?: unknown; endTime?: unknown }): r is { startTime: number; endTime: number } =>\n  typeof r.startTime === 'number' && typeof r.endTime === 'number' && r.endTime >= r.startTime;","tryCatchPattern":"try {\n  traces = importTrace(text, file);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('endTime precedes startTime')) {\n    console.error(`Bad interval: ${e.message}`); // drop/fix the record\n  } else throw e;\n}","preventionTips":["Use a single clock source and one time unit across producer code paths.","Add a producer-side assertion endTime >= startTime at span close.","Sanity-check exports for NTP/clock-jump effects before import."],"tags":["validation","timestamps","ingest"],"backgroundTag":"invalid-argument-value","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"}