{"record":{"id":"9a0fba9530712995","repo":"clockworklabs/SpacetimeDB","slug":"repo-segment-already-exists-and-is-non-empt","errorCode":null,"errorMessage":"repo {}: segment {} already exists and is non-empty","messagePattern":"repo (.+?): segment (.+?) already exists and is non-empty","errorType":"exception","errorClass":"std::io::Error","httpStatus":null,"severity":"error","filePath":"crates/commitlog/src/repo/fs.rs","lineNumber":299,"sourceCode":"        let lock_path = path.0.with_extension(\"lock\");\n        let _lock = scopeguard::guard(\n            lockfile::advisory::LockedFile::lock(&lock_path)\n                .map_err(|e| io::Error::new(e.source.kind(), format!(\"repo {}: {}: {}\", self, e, e.source)))?,\n            |lockfile| {\n                if let Err(e) = lockfile.release(true) {\n                    // It's ok if removing the file fails, but print a warning\n                    // anyways.\n                    warn!(\"repo {}: failed to remove {}: {}\", self, lock_path.display(), e);\n                }\n            },\n        );\n\n        // Check whether the segment already exists.\n        // Overwrite it if its length is zero.\n        match fs::metadata(&path) {\n            Ok(stat) => {\n                if stat.len() > 0 {\n                    return Err(io::Error::new(\n                        io::ErrorKind::AlreadyExists,\n                        format!(\"repo {}: segment {} already exists and is non-empty\", self, offset),\n                    ));\n                }\n            }\n            Err(e) => {\n                if e.kind() != io::ErrorKind::NotFound {\n                    return Err(io::Error::new(\n                        e.kind(),\n                        format!(\n                            \"repo {}: error getting file metadata for segment {}: {}\",\n                            self, offset, e\n                        ),\n                    ));\n                }\n            }\n        }\n","sourceCodeStart":281,"sourceCodeEnd":317,"githubUrl":"https://github.com/clockworklabs/SpacetimeDB/blob/3653d2ed498fddbd83b7062aa6bf8970e18635ec/crates/commitlog/src/repo/fs.rs#L281-L317","documentation":"Filesystem Repo::create_segment permits re-creating a segment file only if it is zero-length (a leftover empty shell); if the target path already exists with bytes in it, creation is refused with AlreadyExists to avoid clobbering committed data. The message includes the repo path and the segment offset.","triggerScenarios":"Calling create_segment for an offset that already has a populated file - e.g. re-initializing a log at an offset computed from stale state, epoch/truncation bookkeeping out of sync with the directory contents, or a second writer creating the segment first (the lock serializes but does not silence the second attempt).","commonSituations":"Restarting after a restore with mismatched segment files left in the directory; running two nodes on one directory; tools that recreate segments from an old offset map.","solutions":["Use a fresh data directory when initializing a new log instead of reusing one with existing segment files.","If intentional re-initialization is required, remove the old segment (and its .lock and index files) first.","Check for and stop any concurrent writer on the same data directory."],"exampleFix":null,"handlingStrategy":"validation","validationCode":"// Only attempt creation when the segment file is absent or empty\nmatch std::fs::metadata(&segment_path) {\n    Err(e) if e.kind() == std::io::ErrorKind::NotFound => repo.create_segment(off, hdr),\n    Ok(m) if m.len() == 0 => repo.create_segment(off, hdr),\n    _ => repo.open_segment_writer(off), // existing non-empty segment: open instead\n}","typeGuard":null,"tryCatchPattern":"match repo.create_segment(off, hdr) {\n    Ok(seg) => seg,\n    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => repo.open_segment_writer(off)?,\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Treat the data directory as owned by a single log instance; never re-initialize in place.","Compute new segment offsets from the log head, not from a cached or constant value.","After restores, start with a clean directory or verify existing segments match the bookkeeping."],"tags":["rust","commitlog","filesystem","segments","already-exists"],"backgroundTag":"segment-already-exists","analyzedSha":"3653d2ed498fddbd83b7062aa6bf8970e18635ec","analyzedAt":"2026-08-20T06:08:37.179Z","contentChangedAt":"2026-08-20T06:08:37.179Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}