{"record":{"id":"200a2094ee9cfc88","repo":"Hmbown/CodeWhale","slug":"every-otlp-span-requires-traceid-and-spanid","errorCode":null,"errorMessage":"Every OTLP span requires traceId and spanId.","messagePattern":"Every OTLP span requires traceId and spanId\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/src/core/ingest.ts","lineNumber":167,"sourceCode":"    observation: a.observation === undefined ? undefined : validateObservation(a.observation),\n  };\n}\ninterface OtlpRecord { span: Obj; resource: Obj; scope: Obj; resourceSchema?: string; scopeSchema?: string }\nfunction otlpRecords(doc: Obj): OtlpRecord[] {\n  const out: OtlpRecord[] = [];\n  for (const r of list(doc.resourceSpans)) {\n    for (const s of list(r.scopeSpans ?? r.instrumentationLibrarySpans)) {\n      for (const span of list(s.spans)) out.push({ span: obj(span), resource: obj(r.resource), scope: obj(s.scope ?? s.instrumentationLibrary), resourceSchema: r.schemaUrl, scopeSchema: s.schemaUrl });\n    }\n  }\n  return out;\n}\nfunction fromOTLP(doc: Obj, maxEvents: number): { events: WhaleEvent[]; origins: Map<string, string>; warnings: string[] } {\n  const records = otlpRecords(doc), bases = new Map<string, bigint>(), warnings: string[] = [];\n  if (!records.length) throw new Error('No spans found in resourceSpans[].scopeSpans[].spans[].');\n  if (records.length > maxEvents) throw new Error(`Import exceeds the ${maxEvents.toLocaleString()} event limit.`);\n  for (const { span: s } of records) {\n    if (!str(s.traceId) || !str(s.spanId)) throw new Error('Every OTLP span requires traceId and spanId.');\n    const start = ns(s.startTimeUnixNano, 'startTimeUnixNano');\n    const end = s.endTimeUnixNano === undefined ? start : ns(s.endTimeUnixNano, 'endTimeUnixNano');\n    if (end < start) throw new Error(`OTLP span ${s.spanId}: end precedes start.`);\n    let earliest = start;\n    for (const e of list(s.events)) { const t = ns(e.timeUnixNano, 'event.timeUnixNano'); if (t < earliest) earliest = t; }\n    if (!bases.has(s.traceId) || earliest < bases.get(s.traceId)!) bases.set(s.traceId, earliest);\n    if ((s.droppedEventsCount ?? 0) > 0) warnings.push(`Span ${s.spanId} reports ${s.droppedEventsCount} dropped events; coverage is incomplete.`);\n  }\n  const events: WhaleEvent[] = [];\n  for (const rec of records) {\n    const s = rec.span, a = { ...attributes(rec.resource.attributes), ...attributes(s.attributes) };\n    const origin = bases.get(s.traceId)!, start = ns(s.startTimeUnixNano, 'startTimeUnixNano');\n    const end = s.endTimeUnixNano === undefined ? start : ns(s.endTimeUnixNano, 'endTimeUnixNano');\n    const name = String(s.name ?? 'unnamed span');\n    const e: WhaleEvent = {\n      schemaVersion: 1, id: s.spanId, traceId: s.traceId, parentId: str(s.parentSpanId),\n      name, startTime: Number(start - origin) / 1e6, endTime: Number(end - origin) / 1e6,\n      openEnded: s.endTimeUnixNano === undefined,","sourceCodeStart":149,"sourceCodeEnd":185,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/src/core/ingest.ts#L149-L185","documentation":"Every OTLP span must carry non-empty traceId and spanId fields, since the importer keys spans, builds parent-child links, and derives per-trace origins from them. A span missing either identity is rejected strictly — malformed lines or duplicate identities never disappear silently.","triggerScenarios":"Importing an OTLP JSON document where any span object lacks traceId or spanId, has them as empty strings, or where the fields failed hex/string validation in str().","commonSituations":"Hand-rolled exporters omitting IDs for synthetic spans; collector transformations that strip attributes; partial/truncated exports; fixtures written by hand without valid 16/8-byte hex IDs.","solutions":["Fix the exporter to always set traceId (16-byte hex) and spanId (8-byte hex) on every span.","Repair the specific span record in the JSON before importing.","Re-export from the original source instead of editing intermediate files, if truncation stripped fields."],"exampleFix":"// before\n{ \"name\": \"op\", \"startTimeUnixNano\": \"1\", \"endTimeUnixNano\": \"2\" }\n// after\n{ \"traceId\": \"5b8efff798038103d269b633813fc60c\", \"spanId\": \"eee19b7ec3c1b174\", \"name\": \"op\", \"startTimeUnixNano\": \"1\", \"endTimeUnixNano\": \"2\" }","handlingStrategy":"validation","validationCode":"const hex = (s, len) => typeof s === 'string' && s.length === len && /^[0-9a-f]+$/.test(s);\nfor (const span of allSpans(doc)) {\n  if (!hex(span.traceId, 32) || !hex(span.spanId, 16))\n    throw new Error(`Span missing valid traceId/spanId: ${JSON.stringify(span).slice(0, 80)}`);\n}","typeGuard":"const hasIds = (s: unknown): s is { traceId: string; spanId: string } =>\n  typeof s === 'object' && s !== null &&\n  typeof (s as any).traceId === 'string' && (s as any).traceId.length > 0 &&\n  typeof (s as any).spanId === 'string' && (s as any).spanId.length > 0;","tryCatchPattern":"try {\n  traces = importTrace(text, file);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('requires traceId and spanId')) {\n    console.error('A span lacks IDs — re-export or fix the exporter');\n  } else throw e;\n}","preventionTips":["Never strip traceId/spanId in collector processors or export transforms.","Validate exporter output against the OTLP traces JSON schema in CI.","Generate synthetic fixtures with real 32/16-char lowercase hex IDs."],"tags":["otlp","missing-field","ingest"],"backgroundTag":"missing-required-argument","analyzedSha":"433685b2024e7bc4c99e1e2e326bcad39b4d9d65","analyzedAt":"2026-09-15T12:24:24.634Z","contentChangedAt":"2026-09-15T12:24:24.634Z","schemaVersion":2},"datasetVersion":"2026-09-22T11:17:16.035Z"}