{"record":{"id":"0a0623a680dd8d88","repo":"Hmbown/CodeWhale","slug":"select-an-existing-trace-id-when-input-contains-multiple","errorCode":null,"errorMessage":"Select an existing --trace ID when input contains multiple traces.","messagePattern":"Select an existing --trace ID when input contains multiple traces\\.","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"pet/scripts/pet.mjs","lineNumber":31,"sourceCode":"const option = name => args.find(a => a.startsWith(`--${name}=`))?.slice(name.length + 3);\nif (args.includes('--help')) {\n  console.log('node scripts/pet.mjs --input=trace.jsonl --output=pet.jsonl [--trace=ID] [--format=jsonl|tsv] [--watch]\\nnode scripts/pet.mjs --runtime=http://127.0.0.1:7878 --thread=ID --output=pet.jsonl [--segment-buckets=216000] [--resume]\\nUse --demo instead of --input for synthetic telemetry. Output must not already exist unless --resume is used for live recording. A resumed recorder preserves the previous segment and starts unknown at the same path.\\nLive recording rotates at 216000 buckets or 64 MiB into OUTPUT.segment-NNNNNN.jsonl and continues at the same live path. All archives are retained.\\nRuntime reads only the existing local event journal. Optional authentication comes from CODEWHALE_RUNTIME_TOKEN; never put a token in the URL. No agent or provider is started.');\n  process.exit(0);\n}\nlet output, recorder, monitor, timer, runtime;\ntry {\n  for (const a of args) if (!['--demo', '--watch', '--resume'].includes(a) && !/^--(input|output|trace|format|runtime|thread|segment-buckets)=.+/.test(a)) throw new Error('Unknown or empty option. Use --help.');\n  const input = option('input'), runtimeURL = option('runtime'), path = option('output'), format = option('format') ?? 'jsonl', live = args.includes('--watch') || !!runtimeURL;\n  if (!path || [!!input, args.includes('--demo'), !!runtimeURL].filter(Boolean).length !== 1\n    || !['jsonl', 'tsv'].includes(format) || live && format !== 'jsonl' || args.includes('--watch') && !input\n    || !!runtimeURL !== !!option('thread') || option('trace') && !input || option('segment-buckets') && !live || args.includes('--resume') && !live)\n    throw new Error('Choose one input source, an unused --output path (or --resume), and JSONL for live recording. Runtime requires --thread.');\n  const load = async () => {\n    if (!input) return { events: petDemoEvents(), duration: 80_000 };\n    if ((await stat(input)).size > 64 * 1024 * 1024) throw new Error('Input exceeds 64 MiB.');\n    const traces = importTrace(await readFile(input, 'utf8'), input, { privacy: 'metadata' });\n    const trace = option('trace') ? traces.find(t => t.id === option('trace')) : traces.length === 1 ? traces[0] : undefined;\n    if (!trace) throw new Error('Select an existing --trace ID when input contains multiple traces.');\n    return trace;\n  };\n  let trace = runtimeURL ? undefined : await load(), buckets = compilePetTelemetry(trace?.events ?? [], trace?.duration ?? 0);\n  if (live) recorder = await createPetRecorder(path, { resume: args.includes('--resume'), maxBuckets: option('segment-buckets') === undefined ? 216_000 : Number(option('segment-buckets')), report: text => console.error(text) });\n  else output = await open(path, 'wx', 0o600);\n  if (runtimeURL) runtime = await followRuntime({ baseUrl: runtimeURL, threadId: option('thread'),\n    token: process.env.CODEWHALE_RUNTIME_TOKEN, report: text => console.error(text) });\n  if (!live) {\n    await output.writeFile(format === 'tsv' ? encodePetTSV(buckets) : encodePetJSONL(buckets));\n    await output.close(); output = undefined;\n    console.log(`Wrote ${buckets.length} pet buckets (${args.includes('--demo') ? 'demo' : 'trace replay'}).`);\n  } else {\n    // The driver owns wall time. The core only sees recorded relative timestamps.\n    const started = performance.now(), startedWall = Date.now();\n    const origin = trace && 'originTime' in trace && trace.originTime ? Date.parse(trace.originTime) : NaN;\n    const offset = Number.isFinite(origin) ? Math.max(0, Date.now() - origin) : trace?.duration ?? 0;\n    let dirty = false, running = false, sequence = 0, failed = false, stopping = false, lastBin = -1;\n    const empty = compilePetTelemetry([])[0];","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/433685b2024e7bc4c99e1e2e326bcad39b4d9d65/pet/scripts/pet.mjs#L13-L49","documentation":"After importing traces from the --input file, load() selects which trace to convert: if --trace=<id> was given it finds that ID; otherwise a single-trace file is auto-selected. If no trace is selected — the file contains multiple traces and no --trace was passed, or the given --trace ID doesn't exist — the script throws this error because conversion needs exactly one trace.","triggerScenarios":"--input file contains two or more traces and the command omits --trace; or --trace=<id> is passed but no imported trace has that exact ID (typo, stale ID, wrong file).","commonSituations":"Merged or concatenated trace exports containing several sessions; reusing a --trace ID from a previous recording against a new export; case-sensitive ID mismatch; assuming auto-selection works on multi-trace files.","solutions":["Pass --trace=<id> with an ID that actually exists in the input file (list IDs by importing the file and inspecting traces[].id).","Copy-paste the trace ID exactly, including case, from the source trace metadata.","Verify you're converting the intended input file — an ID from a different export won't match.","Split the export so each file holds one trace, then convert without --trace."],"exampleFix":"// before\nnode scripts/pet.mjs --input=multi-trace.jsonl --output=pet.jsonl\n// after\nnode scripts/pet.mjs --input=multi-trace.jsonl --trace=tr_01J9XK... --output=pet.jsonl","handlingStrategy":"validation","validationCode":"// confirm the ID exists before converting\nconst traces = importTrace(await readFile(inputFile, 'utf8'), inputFile, { privacy: 'metadata' });\nif (traces.length > 1 && !traces.some(t => t.id === wantedTraceId)) {\n  console.error('available IDs:', traces.map(t => t.id));\n}","typeGuard":null,"tryCatchPattern":"try {\n  await runPetCli(['--input=' + f, '--trace=' + id, '--output=' + out]);\n} catch (err) {\n  if (err.message.startsWith('Select an existing --trace')) {\n    console.error('list trace IDs in the file and pass --trace=<id> exactly');\n  }\n  throw err;\n}","preventionTips":["Always pass --trace when the input may contain more than one trace.","Copy trace IDs exactly (case-sensitive) from the trace metadata.","Check the ID exists in the same file you're converting, not a previous export.","Keep one trace per export file to allow auto-selection."],"tags":["cli","selection","trace-id","validation"],"backgroundTag":"record-not-found","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"}