{"record":{"id":"8e037c708aabf12f","repo":"Hmbown/CodeWhale","slug":"maxtraces-must-be-in-1-64","errorCode":null,"errorMessage":"maxTraces must be in [1, 64].","messagePattern":"maxTraces must be in \\[1, 64\\]\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/src/core/ingest.ts","lineNumber":223,"sourceCode":"    for (const [i, record] of list(s.events).entries()) {\n      const ea = attributes(record.attributes), time = Number(ns(record.timeUnixNano, 'event.timeUnixNano') - origin) / 1e6;\n      const ename = String(record.name ?? 'span event');\n      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));","sourceCodeStart":205,"sourceCodeEnd":241,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/src/core/ingest.ts#L205-L241","documentation":"importTrace validates every option up front so malformed imports fail before any parsing work. maxTraces controls how many distinct trace IDs a single import may contain, and must be an integer between 1 and 64. Passing a non-integer, zero, negative, or >64 value throws this error immediately.","triggerScenarios":"Calling importTrace(text, name, { maxTraces: 0 }) or { maxTraces: 100 } or a non-integer like 2.5; maxTraces defaults to 8 so only explicit options trigger it.","commonSituations":"Config derived from user input or environment variables without clamping; computing maxTraces from another count (e.g. traces.length) that can exceed 64; arithmetic producing fractional values.","solutions":["Pass an integer maxTraces between 1 and 64, e.g. importTrace(text, name, { maxTraces: 32 }).","Clamp or round user-supplied values before calling: Math.min(64, Math.max(1, Math.round(value))).","Omit maxTraces entirely to use the default of 8."],"exampleFix":"// before\nimportTrace(text, name, { maxTraces: userInput });\n// after\nconst maxTraces = Math.min(64, Math.max(1, Math.round(userInput ?? 8)));\nimportTrace(text, name, { maxTraces });","handlingStrategy":"validation","validationCode":"const n = opts.maxTraces;\nif (n !== undefined && (!Number.isInteger(n) || n < 1 || n > 64)) throw new Error('maxTraces must be an integer in [1, 64]');","typeGuard":"function isValidMaxTraces(v: unknown): v is number {\n  return typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 64;\n}","tryCatchPattern":"try {\n  importTrace(text, name, { maxTraces });\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('maxTraces must be')) {\n    console.error(`Bad option maxTraces=${maxTraces}: use an integer 1-64`);\n  }\n}","preventionTips":["Clamp user/config input: Math.min(64, Math.max(1, Math.round(value))).","Omit maxTraces unless you need to change the default of 8.","Type the option as number and validate at the config boundary.","Never compute maxTraces from unbounded counts like traces.length."],"tags":["validation","options","ingest"],"backgroundTag":"value-out-of-range","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"}