{"record":{"id":"7db9e970cd423a81","repo":"Hmbown/CodeWhale","slug":"the-trace-file-is-empty","errorCode":null,"errorMessage":"The trace file is empty.","messagePattern":"The trace file is empty\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/src/core/ingest.ts","lineNumber":226,"sourceCode":"      events.push({ schemaVersion: 1, id: `${s.spanId}/event/${i}`, traceId: s.traceId, parentId: s.spanId,\n        startTime: time, endTime: time, agentId: e.agentId, name: ename, category: categoryFor(ename, ea),\n        status: ename === 'exception' ? 'error' : 'unknown', attributes: ea, raw: { event: record, spanId: s.spanId, resource: rec.resource, scope: rec.scope } });\n    }\n    if (events.length > maxEvents) throw new Error(`Import exceeds the ${maxEvents.toLocaleString()} event limit, including span events.`);\n  }\n  return { events, origins: new Map([...bases].map(([k, v]) => [k, v.toString()])), warnings };\n}\n\n/** Parse strictly: malformed lines or duplicate identities never disappear silently. */\nexport function importTrace(text: string, filename = 'Imported trace', options: ImportOptions = {}): Trace[] {\n  const mode = options.privacy ?? 'redact', maxEvents = options.maxEvents ?? 250_000;\n  if (!['redact', 'metadata', 'retain'].includes(mode)) throw new Error('Unknown privacy mode.');\n  const maxTraces = options.maxTraces ?? 8;\n  if (!Number.isInteger(maxEvents) || maxEvents < 1 || maxEvents > 250_000) throw new Error('maxEvents must be in [1, 250000].');\n  if (!Number.isInteger(maxTraces) || maxTraces < 1 || maxTraces > 64) throw new Error('maxTraces must be in [1, 64].');\n  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.');\n  const trimmed = text.replace(/^\\uFEFF/, '').trim();\n  if (!trimmed) throw new Error('The trace file is empty.');\n  let document: unknown;\n  try { document = JSON.parse(trimmed); }\n  catch {\n    document = trimmed.split(/\\r?\\n/).filter(l => l.trim()).map((line, i) => {\n      try { return JSON.parse(line); } catch { throw new Error(`Invalid JSON on nonempty line ${i + 1}. Import cancelled; no rows were skipped.`); }\n    });\n  }\n  // Transform before both normalization and raw retention, so raw cannot bypass redaction.\n  const safe = mode === 'retain' ? (options.redactor ? options.redactor(document, '') : document) : redact(document, '', options.redactor);\n  const root = obj(safe);\n  if(root.format === 'whalesong.evidence/v1') return [evidenceToTrace(validateBundle(root, Math.min(maxEvents, 100_000)))];\n  if (isCodewhaleSession(safe)) {\n    const trace = fromCodewhaleSession(safe, filename, maxEvents);\n    trace.privacy = mode;\n    trace.events = trace.events.map(e => privacyEvent(e, mode));\n    return [trace];\n  }\n  const records = Array.isArray(safe) ? safe : Array.isArray(root.events) ? root.events : null;","sourceCodeStart":208,"sourceCodeEnd":244,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/src/core/ingest.ts#L208-L244","documentation":"After stripping a BOM and trimming whitespace, importTrace requires non-empty input; an empty (or whitespace-only) file cannot yield a trace so it is rejected up front rather than producing zero traces silently.","triggerScenarios":"Calling importTrace(''), importTrace('   \\n'), or a file containing only a BOM (\\uFEFF) — after trim() the text is empty and this throws.","commonSituations":"Export process crashed mid-write leaving a 0-byte file; reading a path that resolves to an empty placeholder; the UI passing an unset variable concatenated into an empty string.","solutions":["Check the file has content before importing (byte length > 0 after trimming whitespace/BOM).","Re-export the trace; an empty file usually means the original export failed.","Guard the call site: skip import when text.trim() is empty and show a friendlier message."],"exampleFix":"// before\nconst traces = importTrace(text);\n// after\nif (!text.replace(/^\\uFEFF/, '').trim()) throw new Error('Please select a non-empty trace file.');\nconst traces = importTrace(text);","handlingStrategy":"validation","validationCode":"const trimmed = text.replace(/^\\uFEFF/, '').trim();\nif (!trimmed) throw new Error('Trace file is empty; select a valid export.');","typeGuard":null,"tryCatchPattern":"try {\n  importTrace(text);\n} catch (e) {\n  if (e instanceof Error && e.message === 'The trace file is empty.') {\n    console.error('The selected file has no content; re-export the trace.');\n  }\n}","preventionTips":["Check file.size > 0 before importing.","Re-export if the file is 0 bytes — it usually means the export crashed.","Trim and BOM-strip before the emptiness check so BOM-only files are caught.","Fail fast in the UI when a user selects an empty file."],"tags":["validation","empty-input","ingest"],"backgroundTag":"empty-required-field","analyzedSha":"433685b2024e7bc4c99e1e2e326bcad39b4d9d65","analyzedAt":"2026-09-15T12:24:24.634Z","contentChangedAt":"2026-09-15T12:24:24.634Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}