{"record":{"id":"9f72307fb29bebbd","repo":"clockworklabs/SpacetimeDB","slug":"repo-segment-already-exists-and-is-non-empt-9f7230","errorCode":null,"errorMessage":"repo {}: segment {} already exists and is non-empty: {}","messagePattern":"repo (.+?): segment (.+?) already exists and is non-empty: (.+?)","errorType":"exception","errorClass":"io::Error","httpStatus":null,"severity":"error","filePath":"crates/commitlog/src/stream/writer.rs","lineNumber":466,"sourceCode":"    let segment_offset = last_written_tx_range\n        .as_ref()\n        .map(|range| range.end)\n        .unwrap_or_default();\n    let mut segment = loop {\n        match repo.create_segment(segment_offset, header) {\n            Ok(segment) => break segment,\n            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {\n                trace!(\"segment already exists\");\n                let mut s = repo.open_segment_writer(segment_offset)?;\n                let len = s.segment_len()?;\n                trace!(\"segment len: {len}\");\n                if len <= segment::Header::LEN as _ {\n                    trace!(\"overwriting existing segment\");\n                    repo.remove_segment(segment_offset)?;\n                    continue;\n                }\n\n                return Err(io::Error::new(\n                    e.kind(),\n                    format!(\n                        \"repo {}: segment {} already exists and is non-empty: {}\",\n                        repo, segment_offset, e\n                    ),\n                ));\n            }\n            Err(e) => return Err(e),\n        }\n    };\n    fallocate(&mut segment, &commitlog_options)?;\n\n    let index_writer = repo\n        .create_offset_index(segment_offset, commitlog_options.offset_index_len())\n        .inspect_err(|e| warn!(\"unable to create offset index segment={segment_offset} err={e:?}\"))\n        .map(|index| OffsetIndexWriter::new(index, commitlog_options))\n        .ok();\n","sourceCodeStart":448,"sourceCodeEnd":484,"githubUrl":"https://github.com/clockworklabs/SpacetimeDB/blob/9e0d92412ff2248f401a8ad12d535f2b5ac30912/crates/commitlog/src/stream/writer.rs#L448-L484","documentation":"When the mirrored stream presents a segment header, StreamWriter tries create_segment. On io::ErrorKind::AlreadyExists it opens the existing segment and only overwrites when its length is at most segment::Header::LEN (a stub). An existing segment with real data is refused with AlreadyExists 'segment N already exists and is non-empty', protecting the destination from being overwritten.","triggerScenarios":"Replaying a mirror stream into a repo directory that already contains data for those segment offsets: restarting a restore from an earlier point without clearing the target; pointing a second mirror job at the same repo; wrong destination directory that already holds a commitlog.","commonSituations":"Re-running restore jobs over partially populated directories; misconfigured destination paths in automation; concurrent mirror writers targeting one repo.","solutions":["Replay into a fresh, empty repo/directory when starting a stream from the beginning","If resuming, align the stream start with the destination's existing content instead of replaying already-written segments","Verify the existing segment's data is disposable (it matches the stream's earlier content) before removing it","Ensure only one StreamWriter writes to a repo at a time"],"exampleFix":null,"handlingStrategy":"validation","validationCode":"// Ensure the destination is empty (or absent) before replaying from the start\nlet offsets = repo.existing_offsets()?;\nif !offsets.is_empty() {\n    return Err(io::Error::new(\n        io::ErrorKind::AlreadyExists,\n        format!(\"destination repo not empty: {offsets:?}\"),\n    ));\n}\nlet writer = StreamWriter::create(repo, opts, OnTrailingData::Trim)?;","typeGuard":"fn is_nonempty_segment_exists(err: &io::Error) -> bool {\n    err.kind() == io::ErrorKind::AlreadyExists && err.to_string().contains(\"already exists and is non-empty\")\n}","tryCatchPattern":"match writer.append_all(&mut stream, &mut progress).await {\n    Ok(done) => Ok(done),\n    Err(e) if is_nonempty_segment_exists(&e) => {\n        // stop; a human must decide whether existing data is disposable\n        Err(e)\n    }\n    Err(e) => Err(e),\n}","preventionTips":["Replay into a fresh empty directory when starting a stream from the beginning","Resume streams from the destination's actual last offset rather than replaying old segments","Enforce one StreamWriter per repo; guard with a lock file if jobs may overlap"],"tags":["rust","commitlog","streaming","already-exists","mirror"],"backgroundTag":"file-already-exists","analyzedSha":"9e0d92412ff2248f401a8ad12d535f2b5ac30912","analyzedAt":"2026-08-20T06:08:37.179Z","contentChangedAt":"2026-08-20T06:08:37.179Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}