{"record":{"id":"38f4499a967e878a","repo":"JuliusBrussee/caveman","slug":"cave-runtime-segment-id-collision","errorCode":"cave_runtime_segment_id_collision","errorMessage":"cave_runtime_segment_id_collision","messagePattern":"cave_runtime_segment_id_collision","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent/src/context-ir.ts","lineNumber":287,"sourceCode":"\n  return { ir: { schemaVersion: 1, segments }, bodies };\n}\n\nexport function appendRuntimeContextSegment(\n  lowered: LoweredContext,\n  segment: RuntimeContextSegment,\n): ContextSegment {\n  const digest = sha256(segment.body);\n  const existing = lowered.ir.segments.find((item) => item.id === segment.id);\n  if (existing) {\n    // Segment identity is content-derived, so the same id must\n    // carry the same bytes. If it does not, the id has been reused for\n    // different content — the exact confusion that once let compaction\n    // substitute an OLD message's compressed body into a NEW message. Fail\n    // closed rather than returning the stale segment and poisoning the CCR\n    // restore map.\n    if (existing.provenanceDigest !== digest) {\n      throw new Error(\"cave_runtime_segment_id_collision\");\n    }\n    return existing;\n  }\n  const bodyHandle = `cave_local_sha256:${digest}`;\n  (lowered.bodies as Map<string, Uint8Array>).set(bodyHandle, segment.body.slice());\n  const appended: ContextSegment = {\n    id: segment.id,\n    kind: segment.kind,\n    stability: \"turn\",\n    safety: \"S4\",\n    priority: \"normal\",\n    recovery: \"exact_ccr\",\n    cacheRegion: \"live_zone\",\n    privacy: \"local_sensitive\",\n    opaque: opaquePayload(segment.body),\n    provenanceDigest: digest,\n    tokenCount: estimateTokens(segment.body),\n    bodyHandle,","sourceCodeStart":269,"sourceCodeEnd":305,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/agent/src/context-ir.ts#L269-L305","documentation":"appendRuntimeContextSegment detects when a runtime segment id already exists with a different provenance digest — i.e. the same id carries different bytes. Because that would let compaction substitute an old message's compressed body into a new message, it fails closed with cave_runtime_segment_id_collision instead of returning the stale segment.","triggerScenarios":"Reusing a segment id (e.g. message id) for new content with different bytes; generating ids non-uniquely across turns (e.g. 'user-turn' for every user message); content-addressed digest changing while the caller reuses a hand-picked id.","commonSituations":"Migrating from sequential counters to content hashes; replaying a session where the same id is appended with regenerated bodies; test fixtures that reuse ids across cases within one session.","solutions":["Generate a unique segment id per distinct content (include the digest, a uuid, or a monotonic counter)","If re-appending identical content, derive the id from the content digest so identical bytes collide safely and return the existing segment","Check for an existing segment before appending and create a new id when bytes differ"],"exampleFix":"// before\nappendRuntimeContextSegment(ir, { id: \"msg-1\", body: newBody, ... });\n// after\nconst digest = await sha256Hex(newBody);\nappendRuntimeContextSegment(ir, { id: `msg-1:${digest}`, body: newBody, ... });","handlingStrategy":"try-catch","validationCode":"const digest = await sha256Hex(body);\nif (ir.segments.some((s) => s.id === id)) {\n  const existing = ir.segments.find((s) => s.id === id)!;\n  if (existing.provenanceDigest !== digest) {\n    throw new Error(`id ${id} already used for different content; pick a new id`);\n  }\n}","typeGuard":"null","tryCatchPattern":"try {\n  appendRuntimeContextSegment(ir, segment);\n} catch (err) {\n  if ((err as Error).message === \"cave_runtime_segment_id_collision\") {\n    appendRuntimeContextSegment(ir, { ...segment, id: `${segment.id}:${Date.now()}` });\n  } else throw err;\n}","preventionTips":["Derive segment ids from the content digest or use uuids/monotonic counters — never reuse ids across different bytes","Reuse the same id only when content is byte-identical (the library then returns the existing segment)","Include a turn/message ordinal in runtime segment ids to guarantee uniqueness across a session"],"tags":["state","collision","integrity"],"backgroundTag":"internal-invariant-violation","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}