Repository navigation
Move github.com/qdrant/wal into lib/wal - #8185
Conversation
Commit: c07fb56ebc8120ebe4e3c602d31ce98f356f4676 2026-02-18
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (9)
lib/wal/src/segment_creator.rs (2)
116-121: Thread spawn failure panics unconditionally.
thread::Builder::new().spawn(...).unwrap()will panic if the OS cannot create a new thread (e.g., resource exhaustion). Since this runs in the WAL hot path (called fromnext()→schedule_creation()), propagating the error would be safer.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment_creator.rs` around lines 116 - 121, The current code unconditionally unwraps the result of thread::Builder::new().spawn(...) in the segment creator (setting self.thread) which can panic on spawn failure; change create_segments thread creation to handle the Result instead of unwrap: call thread::Builder::new().spawn(...) and match or map_err the Err case, return or propagate an error from the function that calls this code (update schedule_creation and its caller next() to accept/propagate a Result or appropriate error type), and only set self.thread = Some(handle) on Ok(handle); ensure the error path logs/contextualizes the spawn error and avoids panicking.
149-149:Vec::remove(0)is O(n); considerVecDequefor the pending queue.
pending_segmentsis always consumed from the front and extended at the back. AVecDequewould makepop_front()O(1) and is a more natural fit.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment_creator.rs` at line 149, The code uses Vec::remove(0) on pending_segments which is O(n); change pending_segments from Vec<T> to std::collections::VecDeque<T>, update its declaration and imports accordingly, replace remove(0) with pop_front() (handle the Option return or unwrap as appropriate), and replace any push/extend-at-back uses with push_back()/extend or compatible VecDeque methods; also scan for other places that relied on Vec indexing or length semantics and adjust them to work with VecDeque (e.g., iter(), len(), clear() remain available).lib/wal/src/bin/wal-ctl.rs (1)
65-74: Unhandled command branch silently does nothing.If none of
cmd_check,cmd_entry, orcmd_appendis true (e.g., due to a Docopt parsing edge case), the program silently exits with success. Consider adding anelsebranch that prints an error or is unreachable.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/bin/wal-ctl.rs` around lines 65 - 74, The current main command dispatch using args.cmd_check, args.cmd_entry, and args.cmd_append can silently do nothing if none are true; add a final else branch after the existing conditional that handles the unexpected case (e.g., log an error to stderr and exit with a non-zero code or call unreachable!()) so the program fails loudly; update the block that currently calls check(wal), entry(wal, args.arg_index), and append(wal, &buffer[..]) to include an else { eprintln!("Unknown command"); std::process::exit(1); } (or unreachable!()) to prevent silent success when no branch matches.lib/wal/Cargo.toml (1)
32-35: Binary-only dependencies (docopt,env_logger,serde) inflate the dependency tree for library consumers.These are only needed by
src/bin/wal-ctl.rs, but listing them under[dependencies]forces every crate that depends onwal(collection, shard, storage, edge) to compile them. Consider gating behind an optional feature (e.g.,cli) or moving the binary into a separate crate/workspace member.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/Cargo.toml` around lines 32 - 35, The crate currently lists docopt, env_logger, and serde as normal dependencies which forces all library consumers to build them; move these binary-only deps out of the default library dependencies by making them optional and gated behind a feature (e.g., add a "cli" feature in Cargo.toml and change docopt/env_logger/serde entries to optional = true and include them under [features] = { cli = ["docopt","env_logger","serde"] }), or alternatively extract src/bin/wal-ctl.rs into its own workspace member crate so only the CLI crate depends on docopt/env_logger/serde; update src/bin/wal-ctl.rs to enable the feature or depend on the new crate accordingly.lib/wal/benches/benchmark.rs (1)
9-10: Misleading function name:criterion_benchmark_4kbenchmarks an 8 KiB buffer.The function name suggests 4 KiB, but the buffer is
[0u8; 8192](8 KiB), and the group is correctly named"8k".Proposed rename
-pub fn criterion_benchmark_4k(c: &mut Criterion) { +pub fn criterion_benchmark_8k(c: &mut Criterion) {Also update line 53:
-criterion_group!(benches, criterion_benchmark_4k, criterion_benchmark_1024k); +criterion_group!(benches, criterion_benchmark_8k, criterion_benchmark_1024k);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/benches/benchmark.rs` around lines 9 - 10, The function name criterion_benchmark_4k is misleading because the local buffer is [0u8; 8192] (8 KiB) and the benchmark group is named "8k"; rename the function to criterion_benchmark_8k and update any references (e.g., in criterion_group! or criterion_main! registrations and test calls) to the new name so the symbol matches the actual buffer size and the "8k" group name; ensure the buffer variable stays [0u8; 8192] and any comments or strings referencing "4k" are changed to "8k".lib/wal/src/segment.rs (1)
685-694:copy_memorycan be replaced with safecopy_from_slice.The manual
ptr::copy_nonoverlappingwith an assert is equivalent to the safecopy_from_slice, which performs the same bounds check and copy. Since this is a new file being brought into the repo, consider simplifying.Proposed fix
pub fn copy_memory(src: &[u8], dst: &mut [u8]) { - let len_src = src.len(); - assert!(dst.len() >= len_src); - unsafe { - ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len_src); - } + dst[..src.len()].copy_from_slice(src); }This also allows removing the
ptrimport from line 7 if unused elsewhere.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment.rs` around lines 685 - 694, The function copy_memory manually uses unsafe ptr::copy_nonoverlapping with an assert; replace its body with the safe dst.copy_from_slice(src) call to perform the same bounds-checked copy and remove the unsafe block, and if ptr was only imported for this function, remove the ptr import as well; update references to copy_memory only if its signature changes (keep signature same).lib/wal/src/lib.rs (3)
177-181: Redundant..— all fields ofClosedSegmentare already bound.
ClosedSegmentonly hasstart_indexandsegment, both of which are explicitly matched here. The trailing..is a no-op and can be removed to keep the destructuring precise. As per coding guidelines, "Prefer explicit field ignoring using: _over using..in Rust struct destructuring."♻️ Suggested diff
for &ClosedSegment { start_index, ref segment, - .. } in &closed_segments🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 177 - 181, The pattern match over ClosedSegment in the for-loop binds start_index and segment explicitly but includes a redundant ".."; remove the trailing ".." from the destructuring in the for loop (the binding for ClosedSegment { start_index, ref segment } inside the iteration over closed_segments) so only the explicit fields are matched, keeping the pattern precise and following the guideline to avoid unnecessary .. in struct destructuring.
183-200:unimplemented!()in theOrdering::Lessarm will panic in production on overlapping segments.If the WAL directory ever contains overlapping closed segments (e.g., after a partial crash during rename), this code path crashes the process. Consider replacing with an explicit error return or the truncation logic the TODO alludes to.
♻️ Minimal safe replacement: return an error instead of panicking
Ordering::Less => { - // TODO: figure out what to do here. - // Current thinking is the previous segment should be truncated. - unimplemented!() + // TODO: figure out what to do here. + // Current thinking is the previous segment should be truncated. + return Err(Error::new( + ErrorKind::InvalidData, + format!( + "overlapping closed segments detected at index {start_index} \ + (expected {next_start_index})" + ), + )); }Do you want me to open a follow-up issue to track implementing the truncation recovery strategy mentioned in the TODO?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 183 - 200, The Ordering::Less arm currently calls unimplemented!() which will panic on overlapping closed segments; replace this with an explicit error return (Err(Error::new(...))) rather than panicking, using ErrorKind::InvalidData and a clear message that includes next_start_index, start_index and the segment identifier/length (e.g., segment.len()) so the caller can handle/diagnose overlaps; keep the TODO about truncation if you want to implement recovery later but do not leave a panic in the Ordering::Less branch of the match on start_index.cmp(&next_start_index).
486-490:last_index()is misleading when the WAL is empty.When
num_entries() == 0,saturating_sub(1)yields 0 andlast_index()returnsfirst_index(), which may be a non-zero value (e.g., 11 aftergenerate_empty_wal_starting_at_index(..., 10)). This suggests a valid entry exists at that index when none does.The codebase is aware of this behavior—lib/shard/src/wal.rs explicitly documents the issue in a comment explaining why
read()usesfirst_index() + len()instead oflast_index()for range bounds. Some callers properly guard withis_empty()checks (e.g., lib/collection/src/wal_delta.rs), while others may not consistently do so.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 486 - 490, last_index() incorrectly returns a concrete index when the WAL is empty; change its signature to return Option<u64> and implement it as: if self.num_entries() == 0 return None else return Some(self.first_index() + self.num_entries() - 1); update all callers to handle None (e.g., adjust range calculations in functions like read() in lib/shard/src/wal.rs to use first_index() + len() when last_index() is None, and add is_empty()/match handling in callers such as lib/collection/src/wal_delta.rs) so no code assumes a valid index when the WAL is empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/wal/Cargo.toml`:
- Line 12: The repository URL in the Cargo.toml (the repository field) is stale;
update the repository = "https://github.com/qdrant/wal" entry to point to the
crate's new location in the monorepo (e.g. repository =
"https://github.com/qdrant/qdrant") so the manifest reflects the current
qdrant/qdrant monorepo; edit the repository value in Cargo.toml accordingly.
In `@lib/wal/examples/bench.rs`:
- Around line 117-119: The sync histogram measurements are meaningless because
the actual flush/sync futures are commented out; update the benchmark in
lib::wal::examples::bench.rs by either (A) re-enabling the actual sync/flush
call where start_sync is taken (uncomment and await the real future used
previously, e.g., the future.await() / flush/sync method that performs disk
sync) so sync_hist records real latency for the operation, or (B) if you don’t
want to perform syncs in this benchmark, remove sync_hist and the printed sync
percentile output (the sync_hist.record call and the percentile prints) to avoid
misleading metrics; locate code around the start_sync variable,
sync_hist.record(...) and the percentile print block to make the change.
In `@lib/wal/examples/wal.rs`:
- Around line 13-15: The for-loop currently uses the range 1..100 which iterates
99 times, so change the loop to iterate exactly 100 times (e.g. 0..100 or
0..=99) so wal.append(&entry).unwrap() is called 100 times; update the loop that
calls wal.append and keep the same body and variables (wal and entry) but
replace the range expression to 0..100 (or 0..=99) to fix the off-by-one.
In `@lib/wal/src/lib.rs`:
- Around line 602-606: The inconsistent_struct_constructor warning comes from
constructing OpenSegment with fields in the wrong order; change the constructor
in the match arm that currently has WalSegment::Open(OpenSegment { segment, id
}) to use the same field order as the OpenSegment definition (id first, then
segment) — i.e., construct OpenSegment as OpenSegment { id, segment } so field
order matches the struct definition and resolves the Clippy lint.
In `@lib/wal/src/mmap_view_sync.rs`:
- Around line 32-48: In both constructors from_file and anonymous, replace the
implicit conversion call mmap.into() with the explicit constructor
MmapViewSync::from(mmap); update the return expressions in fn from_file and fn
anonymous to call MmapViewSync::from(mmap) so the code uses the explicit
conversion method rather than .into().
- Around line 238-278: The test `view_write` fails because it constructs a
std::fs::File but `MmapViewSync::from_file` expects an `&fs_err::File`; fix by
creating the file with `fs_err::OpenOptions` (or otherwise ensuring the `file`
variable is an `fs_err::File`) instead of `std::fs::OpenOptions`, and update
imports accordingly (remove or change `use std::{fs, thread};` to `use
std::thread;` and either `use fs_err;` or fully qualify `fs_err::OpenOptions`)
so the `file` passed to `MmapViewSync::from_file` is the correct `fs_err::File`
type.
In `@lib/wal/src/segment.rs`:
- Around line 599-609: The destructuring in delete_windows currently uses `..`
which hides fields like `crc`; update the `let Segment { mmap, path, index,
flush_offset, .. } = self;` pattern to explicitly ignore the CRC field with
`crc: _` (i.e., `let Segment { mmap, path, index, flush_offset, crc: _, } =
self;`) so future added fields that require cleanup will be surfaced by the
compiler; keep the same used field names (`mmap`, `path`, `index`,
`flush_offset`) and explicitly ignore only `crc`.
---
Nitpick comments:
In `@lib/wal/benches/benchmark.rs`:
- Around line 9-10: The function name criterion_benchmark_4k is misleading
because the local buffer is [0u8; 8192] (8 KiB) and the benchmark group is named
"8k"; rename the function to criterion_benchmark_8k and update any references
(e.g., in criterion_group! or criterion_main! registrations and test calls) to
the new name so the symbol matches the actual buffer size and the "8k" group
name; ensure the buffer variable stays [0u8; 8192] and any comments or strings
referencing "4k" are changed to "8k".
In `@lib/wal/Cargo.toml`:
- Around line 32-35: The crate currently lists docopt, env_logger, and serde as
normal dependencies which forces all library consumers to build them; move these
binary-only deps out of the default library dependencies by making them optional
and gated behind a feature (e.g., add a "cli" feature in Cargo.toml and change
docopt/env_logger/serde entries to optional = true and include them under
[features] = { cli = ["docopt","env_logger","serde"] }), or alternatively
extract src/bin/wal-ctl.rs into its own workspace member crate so only the CLI
crate depends on docopt/env_logger/serde; update src/bin/wal-ctl.rs to enable
the feature or depend on the new crate accordingly.
In `@lib/wal/src/bin/wal-ctl.rs`:
- Around line 65-74: The current main command dispatch using args.cmd_check,
args.cmd_entry, and args.cmd_append can silently do nothing if none are true;
add a final else branch after the existing conditional that handles the
unexpected case (e.g., log an error to stderr and exit with a non-zero code or
call unreachable!()) so the program fails loudly; update the block that
currently calls check(wal), entry(wal, args.arg_index), and append(wal,
&buffer[..]) to include an else { eprintln!("Unknown command");
std::process::exit(1); } (or unreachable!()) to prevent silent success when no
branch matches.
In `@lib/wal/src/lib.rs`:
- Around line 177-181: The pattern match over ClosedSegment in the for-loop
binds start_index and segment explicitly but includes a redundant ".."; remove
the trailing ".." from the destructuring in the for loop (the binding for
ClosedSegment { start_index, ref segment } inside the iteration over
closed_segments) so only the explicit fields are matched, keeping the pattern
precise and following the guideline to avoid unnecessary .. in struct
destructuring.
- Around line 183-200: The Ordering::Less arm currently calls unimplemented!()
which will panic on overlapping closed segments; replace this with an explicit
error return (Err(Error::new(...))) rather than panicking, using
ErrorKind::InvalidData and a clear message that includes next_start_index,
start_index and the segment identifier/length (e.g., segment.len()) so the
caller can handle/diagnose overlaps; keep the TODO about truncation if you want
to implement recovery later but do not leave a panic in the Ordering::Less
branch of the match on start_index.cmp(&next_start_index).
- Around line 486-490: last_index() incorrectly returns a concrete index when
the WAL is empty; change its signature to return Option<u64> and implement it
as: if self.num_entries() == 0 return None else return Some(self.first_index() +
self.num_entries() - 1); update all callers to handle None (e.g., adjust range
calculations in functions like read() in lib/shard/src/wal.rs to use
first_index() + len() when last_index() is None, and add is_empty()/match
handling in callers such as lib/collection/src/wal_delta.rs) so no code assumes
a valid index when the WAL is empty.
In `@lib/wal/src/segment_creator.rs`:
- Around line 116-121: The current code unconditionally unwraps the result of
thread::Builder::new().spawn(...) in the segment creator (setting self.thread)
which can panic on spawn failure; change create_segments thread creation to
handle the Result instead of unwrap: call thread::Builder::new().spawn(...) and
match or map_err the Err case, return or propagate an error from the function
that calls this code (update schedule_creation and its caller next() to
accept/propagate a Result or appropriate error type), and only set self.thread =
Some(handle) on Ok(handle); ensure the error path logs/contextualizes the spawn
error and avoids panicking.
- Line 149: The code uses Vec::remove(0) on pending_segments which is O(n);
change pending_segments from Vec<T> to std::collections::VecDeque<T>, update its
declaration and imports accordingly, replace remove(0) with pop_front() (handle
the Option return or unwrap as appropriate), and replace any push/extend-at-back
uses with push_back()/extend or compatible VecDeque methods; also scan for other
places that relied on Vec indexing or length semantics and adjust them to work
with VecDeque (e.g., iter(), len(), clear() remain available).
In `@lib/wal/src/segment.rs`:
- Around line 685-694: The function copy_memory manually uses unsafe
ptr::copy_nonoverlapping with an assert; replace its body with the safe
dst.copy_from_slice(src) call to perform the same bounds-checked copy and remove
the unsafe block, and if ptr was only imported for this function, remove the ptr
import as well; update references to copy_memory only if its signature changes
(keep signature same).
713104c to
152343c
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (7)
lib/wal/Cargo.toml (1)
30-33: Binary-only dependencies (docopt,env_logger,serde) inflate the dependency tree for all consumers.These are only needed by the
wal-ctlbinary but sit in[dependencies], so every crate that depends onwaltransitively pulls them in. Consider either moving the binary into a separate crate (e.g.,lib/wal-ctl) or gating these behind an optional feature.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/Cargo.toml` around lines 30 - 33, The dependencies docopt, env_logger and serde are declared as regular dependencies which pulls them into every consumer; move them out of the main crate dependencies by either (A) creating a separate binary crate (e.g., a new wal-ctl crate) and placing docopt/env_logger/serde in that crate's Cargo.toml, or (B) making them optional and gated behind a feature (e.g., a "cli" feature) in this Cargo.toml and enabling that feature for the wal-ctl binary; update the wal-ctl binary target to depend on the new crate or enable the feature accordingly so the main wal library no longer forces these binary-only crates on consumers.lib/wal/src/test_utils.rs (1)
10-22:seedasusizemeans test seeds aren't portable across 32/64-bit platforms.
seedis stored asusizeand cast tou64on line 44. A seed value >u32::MAXfrom a 64-bit host would silently truncate on a 32-bit target, producing different test data. If cross-platform reproducibility matters, consider usingu64throughout.Also applies to: 40-48
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/test_utils.rs` around lines 10 - 22, The EntryGenerator struct's seed field should be changed from usize to u64 to ensure test seeds are portable across 32/64-bit platforms; update the EntryGenerator definition (seed: u64) and all places that construct or use the seed (e.g., the constructor/initializer that currently casts seed to u64, and any call sites) to accept and propagate a u64 seed, and initialize the rng with the u64 seed via SeedableRng::seed_from_u64 (or equivalent) so no implicit truncation/casting from usize occurs.lib/wal/benches/benchmark.rs (1)
9-10: Misleading function name:criterion_benchmark_4kuses an 8 KiB buffer.The function is named
_4kbut allocates[0u8; 8192]and the group is labeled"8k". Consider renaming tocriterion_benchmark_8kfor consistency.Proposed rename
-pub fn criterion_benchmark_4k(c: &mut Criterion) { +pub fn criterion_benchmark_8k(c: &mut Criterion) {and at line 53:
-criterion_group!(benches, criterion_benchmark_4k, criterion_benchmark_1024k); +criterion_group!(benches, criterion_benchmark_8k, criterion_benchmark_1024k);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/benches/benchmark.rs` around lines 9 - 10, The function name criterion_benchmark_4k is misleading because it allocates an 8192-byte buffer and the Criterion group is labeled "8k"; rename the function from criterion_benchmark_4k to criterion_benchmark_8k and update any references/tests that call it so the symbol matches the buffer size and group label, ensuring consistency between the function name, the buffer allocation ([0u8; 8192]) and the benchmark group name "8k".lib/wal/src/lib.rs (2)
487-490:last_index()returnsfirst_index()when the WAL is empty, which may mislead callers.When
num_entries() == 0,last_index()returnsfirst_index() + 0 = first_index(), which is a valid-looking index that doesn't actually exist. Callers doingfor i in first_index..=last_indexwould attempt to read a nonexistent entry. The tests at line 814 handle this (if entries.is_empty() { assert_eq!(wal.last_index(), 0) }), but the semantics could surprise new callers. This is pre-existing behavior from the external repo, so just flagging for awareness.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 487 - 490, The current last_index() computes self.first_index() + num_entries.saturating_sub(1) which yields first_index() when num_entries() == 0 and thus returns a non-existent-looking index; change last_index() to explicitly handle the empty-WAL case by checking if self.num_entries() == 0 and returning 0 (or another explicit sentinel) in that branch, otherwise compute first_index() + num_entries.saturating_sub(1); update the last_index() implementation (and any callers that rely on the old behavior) so callers can reliably detect an empty WAL via last_index() == 0.
498-540:copy_to_pathmay skip segments whose files were renamed between directory listing and lookup.The method reads the directory (line 521), then tries to match each file against the in-memory segment paths (lines 530-532). If a segment was retired between the directory read and the lookup (e.g., a concurrent append from another thread — though
Walrequires&selfhere so it's immutable), the file won't match any known segment and will befs::copy'd, potentially missing mmap coherence. Since&selfprevents concurrent mutation, this is safe in the current design, but worth noting if the API ever becomes concurrent.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 498 - 540, copy_to_path can mis-classify files if names changed between the directory read and matching by file_name; to fix, key the lookups by a stable identifier (full PathBuf or file metadata like device+inode) instead of just file_name: build close_segment_files as a HashMap keyed by segment.segment.path().to_path_buf() or by (dev,ino) from segment.segment.path().metadata(), then for each directory entry compare entry.path() (or entry.metadata() dev+ino) against those keys and call open_segment.segment.copy_to_path or segment.copy_to_path accordingly (falling back to fs::copy only when no stable match is found). Ensure you update the open_segment comparison to use the same stable key (open_segment.segment.path()) so renames won't cause loss of mmap/lock-aware copies.lib/wal/src/segment_creator.rs (2)
149-149:Vec::remove(0)is O(n); considerVecDequefor O(1) front removal.
pending_segmentsis always consumed from the front. With the current small queue lengths this is negligible, but aVecDequewould be a more natural fit and avoid the shift.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment_creator.rs` at line 149, Change pending_segments from a Vec to a std::collections::VecDeque and replace the front removal call self.pending_segments.remove(0) with self.pending_segments.pop_front(). Update the field declaration (e.g., pending_segments in the SegmentCreator struct), any initializations (use VecDeque::new()), and places that append segments to use push_back() instead of push() so the queue operates as a true deque with O(1) front removals.
107-123: Thread spawnunwrap()will panic on resource exhaustion.
thread::Builder::new().spawn(…).unwrap()at line 120 will panic if the OS cannot create a new thread. While rare, this could cascade in constrained environments. Propagating the error via?would be more resilient.Proposed fix
This would require
schedule_creationto returnstd::io::Result<()>and callers (new,next) to propagate the error. Sincenewcurrently doesn't returnResult, this would be a larger change — flagging for awareness.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment_creator.rs` around lines 107 - 123, The schedule_creation function currently calls thread::Builder::spawn(...).unwrap(), which will panic on OS thread creation failure; change schedule_creation to return std::io::Result<()> and replace unwrap() with the ? operator when assigning self.thread (so the spawn error is propagated), then update callers of schedule_creation (e.g., the constructor/new and next methods) to propagate or handle the Result accordingly; ensure the create_segments closure and the type of self.thread (Option<JoinHandle<...>>) remain consistent when propagated.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/wal/src/lib.rs`:
- Around line 177-181: The destructuring of ClosedSegment in the for loop
currently uses a redundant trailing `..`; update the pattern to remove `..` and
explicitly bind only the needed fields (`start_index` and `segment`) when
iterating over `closed_segments` (i.e., `for &ClosedSegment { start_index, ref
segment } in &closed_segments`), or if there are other fields you intend to
ignore, switch to explicit ignores (e.g., `other_field: _`) rather than `..`.
- Around line 183-200: The match arm for Ordering::Less currently calls
unimplemented!(), which would panic on overlapping closed segments; replace it
with an explicit Err return (e.g., Err(Error::new(ErrorKind::InvalidData, ...)))
so the caller can handle the condition. Produce an error message referencing the
involved values (start_index, next_start_index and segment.len()) and describe
the overlap (e.g., "overlapping closed segments: segment start {start_index} <
expected {next_start_index}"), and ensure this change is applied in the same
function/code block where start_index, next_start_index, and segment.len() are
compared.
- Line 20: Gate the test-only module by changing the public, always-compiled
declaration `pub mod test_utils;` to a test-only, non-public declaration like
`#[cfg(test)] mod test_utils;` in lib.rs so it isn't exposed in the crate's
public API; also move `rand_distr` from regular dependencies to dev-dependencies
in Cargo.toml (leaving `rand` as a normal dependency for `segment.rs`) so
`rand_distr` is only compiled for tests.
---
Nitpick comments:
In `@lib/wal/benches/benchmark.rs`:
- Around line 9-10: The function name criterion_benchmark_4k is misleading
because it allocates an 8192-byte buffer and the Criterion group is labeled
"8k"; rename the function from criterion_benchmark_4k to criterion_benchmark_8k
and update any references/tests that call it so the symbol matches the buffer
size and group label, ensuring consistency between the function name, the buffer
allocation ([0u8; 8192]) and the benchmark group name "8k".
In `@lib/wal/Cargo.toml`:
- Around line 30-33: The dependencies docopt, env_logger and serde are declared
as regular dependencies which pulls them into every consumer; move them out of
the main crate dependencies by either (A) creating a separate binary crate
(e.g., a new wal-ctl crate) and placing docopt/env_logger/serde in that crate's
Cargo.toml, or (B) making them optional and gated behind a feature (e.g., a
"cli" feature) in this Cargo.toml and enabling that feature for the wal-ctl
binary; update the wal-ctl binary target to depend on the new crate or enable
the feature accordingly so the main wal library no longer forces these
binary-only crates on consumers.
In `@lib/wal/src/lib.rs`:
- Around line 487-490: The current last_index() computes self.first_index() +
num_entries.saturating_sub(1) which yields first_index() when num_entries() == 0
and thus returns a non-existent-looking index; change last_index() to explicitly
handle the empty-WAL case by checking if self.num_entries() == 0 and returning 0
(or another explicit sentinel) in that branch, otherwise compute first_index() +
num_entries.saturating_sub(1); update the last_index() implementation (and any
callers that rely on the old behavior) so callers can reliably detect an empty
WAL via last_index() == 0.
- Around line 498-540: copy_to_path can mis-classify files if names changed
between the directory read and matching by file_name; to fix, key the lookups by
a stable identifier (full PathBuf or file metadata like device+inode) instead of
just file_name: build close_segment_files as a HashMap keyed by
segment.segment.path().to_path_buf() or by (dev,ino) from
segment.segment.path().metadata(), then for each directory entry compare
entry.path() (or entry.metadata() dev+ino) against those keys and call
open_segment.segment.copy_to_path or segment.copy_to_path accordingly (falling
back to fs::copy only when no stable match is found). Ensure you update the
open_segment comparison to use the same stable key (open_segment.segment.path())
so renames won't cause loss of mmap/lock-aware copies.
In `@lib/wal/src/segment_creator.rs`:
- Line 149: Change pending_segments from a Vec to a std::collections::VecDeque
and replace the front removal call self.pending_segments.remove(0) with
self.pending_segments.pop_front(). Update the field declaration (e.g.,
pending_segments in the SegmentCreator struct), any initializations (use
VecDeque::new()), and places that append segments to use push_back() instead of
push() so the queue operates as a true deque with O(1) front removals.
- Around line 107-123: The schedule_creation function currently calls
thread::Builder::spawn(...).unwrap(), which will panic on OS thread creation
failure; change schedule_creation to return std::io::Result<()> and replace
unwrap() with the ? operator when assigning self.thread (so the spawn error is
propagated), then update callers of schedule_creation (e.g., the constructor/new
and next methods) to propagate or handle the Result accordingly; ensure the
create_segments closure and the type of self.thread (Option<JoinHandle<...>>)
remain consistent when propagated.
In `@lib/wal/src/test_utils.rs`:
- Around line 10-22: The EntryGenerator struct's seed field should be changed
from usize to u64 to ensure test seeds are portable across 32/64-bit platforms;
update the EntryGenerator definition (seed: u64) and all places that construct
or use the seed (e.g., the constructor/initializer that currently casts seed to
u64, and any call sites) to accept and propagate a u64 seed, and initialize the
rng with the u64 seed via SeedableRng::seed_from_u64 (or equivalent) so no
implicit truncation/casting from usize occurs.
152343c to
0d5a2c9
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (6)
lib/wal/src/segment_creator.rs (1)
142-152:pending_segments.remove(0)is O(n); considerVecDequeif queue grows.Currently the queue is small (bounded by
segment_queue_len, which defaults to a handful), so this is fine. Just noting that ifsegment_queue_lenever becomes larger, switchingpending_segmentstoVecDequewithpop_front()would be more efficient.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment_creator.rs` around lines 142 - 152, The current implementation of OpenSegmentIterator::next() uses self.pending_segments.remove(0) which is O(n); to make this scalable change the type of pending_segments to std::collections::VecDeque and replace remove(0) with pop_front() in next(), keeping the surrounding logic (call to self.refill_pending()?, scheduling via schedule_creation(), and error handling) the same; update any constructors or initializations that populate pending_segments and adjust uses in refill_pending() and tests to work with VecDeque, and ensure segment_queue_len semantics remain unchanged.lib/wal/src/lib.rs (1)
486-489:last_index()returns a misleading value when the WAL is empty.When
num_entries() == 0,last_index()returnsfirst_index()(which could be non-zero aftergenerate_empty_wal_starting_at_index). This points to an index with no actual entry. The tests account for this, so it's a known semantic, but callers must guard against it. A doc comment clarifying this edge case would help.Proposed doc clarification
/// The index of the last entry + /// + /// Note: When the WAL is empty (`num_entries() == 0`), this returns + /// `first_index()` which does not correspond to an actual entry. pub fn last_index(&self) -> u64 {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/lib.rs` around lines 486 - 489, The method last_index() currently computes self.first_index() + self.num_entries().saturating_sub(1) which returns first_index() when num_entries() == 0, leading callers to a misleading index that has no entry (this can happen after generate_empty_wal_starting_at_index); add a clear doc comment on the last_index() method explaining that when the WAL is empty (num_entries() == 0) last_index() will equal first_index() but does not correspond to an actual entry and callers must check num_entries() or handle the empty-WAL case accordingly; reference last_index(), num_entries(), first_index(), and generate_empty_wal_starting_at_index in the comment for discoverability.lib/wal/src/segment.rs (1)
688-694:copy_memorycould be replaced with safecopy_from_slice.This function wraps
ptr::copy_nonoverlappingwith a manual length assertion. The standard library'sdst[..len_src].copy_from_slice(src)does the same thing safely with equivalent performance. Since this is newly imported code, it's a good opportunity to remove the unnecessaryunsafe.Proposed fix
-pub fn copy_memory(src: &[u8], dst: &mut [u8]) { - let len_src = src.len(); - assert!(dst.len() >= len_src); - unsafe { - ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len_src); - } -} +pub fn copy_memory(src: &[u8], dst: &mut [u8]) { + dst[..src.len()].copy_from_slice(src); +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment.rs` around lines 688 - 694, The helper copy_memory currently uses unsafe ptr::copy_nonoverlapping with a manual length assertion; replace its body with a safe slice copy by calling dst[..src.len()].copy_from_slice(src) (keeping the same signature copy_memory(src: &[u8], dst: &mut [u8]) ), remove the unsafe block and the explicit ptr import and the manual assert (or keep an assert! if you want the same panic behavior) so the operation is safe and idiomatic.lib/wal/src/mmap_view_sync.rs (1)
184-186:Sendis unconditionally implemented whileSyncis test-only — verify this is intentional.
unsafe impl Syncis gated behind#[cfg(test)](line 185), butunsafe impl Send(line 186) applies unconditionally. This split is needed for production code (e.g.,Segment::flush_asyncsends cloned views to spawned threads), but the asymmetry is easy to overlook. A brief comment clarifying the rationale would help future maintainers.Proposed clarifying comment
#[cfg(test)] unsafe impl Sync for MmapViewSync {} +// Send is always needed: flush_async and other operations transfer views across threads. unsafe impl Send for MmapViewSync {}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/mmap_view_sync.rs` around lines 184 - 186, The impls for MmapViewSync are asymmetric (unsafe impl Sync is #[cfg(test)] but unsafe impl Send is unconditional); verify this is intentional and add a brief clarifying comment above the impls explaining why Send must be unconditional (e.g., Segment::flush_async sends/clones MmapViewSync to spawned threads) and why Sync is only enabled for tests (testing utilities need Sync), so future maintainers understand the rationale and the thread-safety assumptions for MmapViewSync.lib/wal/src/test_segment_recovery.rs (2)
55-61: Test relies on a specific segment file name ("open-2") which is an implementation detail.The test hardcodes the assumption that the empty open segment after creating 5 entries with capacity 1024 will be named "open-2" (and that "open-3" won't exist). If segment naming or capacity changes, this test will break silently. Consider finding the empty segment dynamically instead.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/test_segment_recovery.rs` around lines 55 - 61, The test currently hardcodes segment names ("open-2"/"open-3") and uses last_segment_file = dir.path().join("open-2"), which is brittle; instead locate the empty/open segment dynamically by scanning dir.path() for files matching the segment pattern (e.g., names starting with "open-") and selecting the one with zero length (use std::fs::read_dir and metadata().len()), then remove that discovered path and assert that the discovered file no longer exists; update references to last_segment_file and any existence assertions to use the dynamically found PathBuf rather than hardcoded "open-2"/"open-3".
70-73: Timing-dependentsleepfor background segment creation.The 100ms sleep on line 72 could be flaky on slow CI. Acceptable for now, but a more robust approach would be to drop the WAL (which joins the creator thread in
SegmentCreatorV2::drop) before reopening.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/test_segment_recovery.rs` around lines 70 - 73, Replace the timing-dependent std::thread::sleep in test_segment_recovery with an explicit drop of the WAL (or the SegmentCreatorV2 owner) so the background segment-creation thread is joined before reopening; specifically, ensure the WAL instance is dropped (or call drop(wal)) so SegmentCreatorV2::drop runs and joins the creator thread, then proceed to reopen—this removes the flaky sleep and guarantees deterministic cleanup before the reopen step.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/wal/src/mmap_view_sync.rs`:
- Around line 80-94: The doc comment for the restrict method is inaccurate: it
states the provided range must satisfy `offset + len < view.len()` but the
implementation allows `offset + len == self.len`; update the documentation on
the restrict function to state the correct constraint (i.e., the provided range
must be a subset of the current range allowing equality: `offset + len <=
self.len` or "a subset including the end boundary") so the comment matches the
check on self.len in restrict.
- Around line 50-60: The documentation and error message for
MmapViewSync::split_at incorrectly state the offset "must be less than the
view's length" while the code permits offset == self.len; update the doc comment
and the ErrorKind message to say "must be less than or equal to the view's
length" (or equivalent wording) to match the current behavior, and optionally
make the guard clearer by using a direct check like if offset > self.len instead
of if self.len < offset to improve readability.
---
Duplicate comments:
In `@lib/wal/src/lib.rs`:
- Line 20: The test_utils module is currently exported publicly as `pub mod
test_utils`; change it to a test-only module to avoid exposing test-only
code/deps in production by replacing the declaration with a cfg-gated,
non-public module (e.g. add `#[cfg(test)]` and remove `pub` so it becomes
`#[cfg(test)] mod test_utils;`) or, if you need cross-crate test access, gate it
behind a testing feature (`#[cfg(feature = "testing")] pub mod test_utils;`) and
update Cargo.toml accordingly; update any internal test imports to match the new
visibility.
- Around line 182-187: The match arm handling Ordering::Less for
start_index.cmp(&next_start_index) currently panics with unimplemented!() when
overlapping closed segments are detected; replace that panic with an explicit
error return (e.g., Err(WalError::OverlappingClosedSegments { start_index,
next_start_index }) or an appropriate io::Error) and add or reuse a clear error
variant/message so callers can handle it; update the function that contains the
match (the block comparing start_index and next_start_index in
lib/wal/src/lib.rs) to return a Result and propagate the error upward instead of
panicking.
In `@lib/wal/src/mmap_view_sync.rs`:
- Around line 40-47: Replace the use of generic .into() with the explicit
conversion MmapViewSync::from(...) in the functions that construct and return a
MmapViewSync (specifically in the anonymous(...) function and the other function
returning Ok(mmap.into())); locate where Ok(mmap.into()) is returned and change
it to Ok(MmapViewSync::from(mmap)) to follow the coding guideline preferring
explicit conversions.
---
Nitpick comments:
In `@lib/wal/src/lib.rs`:
- Around line 486-489: The method last_index() currently computes
self.first_index() + self.num_entries().saturating_sub(1) which returns
first_index() when num_entries() == 0, leading callers to a misleading index
that has no entry (this can happen after generate_empty_wal_starting_at_index);
add a clear doc comment on the last_index() method explaining that when the WAL
is empty (num_entries() == 0) last_index() will equal first_index() but does not
correspond to an actual entry and callers must check num_entries() or handle the
empty-WAL case accordingly; reference last_index(), num_entries(),
first_index(), and generate_empty_wal_starting_at_index in the comment for
discoverability.
In `@lib/wal/src/mmap_view_sync.rs`:
- Around line 184-186: The impls for MmapViewSync are asymmetric (unsafe impl
Sync is #[cfg(test)] but unsafe impl Send is unconditional); verify this is
intentional and add a brief clarifying comment above the impls explaining why
Send must be unconditional (e.g., Segment::flush_async sends/clones MmapViewSync
to spawned threads) and why Sync is only enabled for tests (testing utilities
need Sync), so future maintainers understand the rationale and the thread-safety
assumptions for MmapViewSync.
In `@lib/wal/src/segment_creator.rs`:
- Around line 142-152: The current implementation of OpenSegmentIterator::next()
uses self.pending_segments.remove(0) which is O(n); to make this scalable change
the type of pending_segments to std::collections::VecDeque and replace remove(0)
with pop_front() in next(), keeping the surrounding logic (call to
self.refill_pending()?, scheduling via schedule_creation(), and error handling)
the same; update any constructors or initializations that populate
pending_segments and adjust uses in refill_pending() and tests to work with
VecDeque, and ensure segment_queue_len semantics remain unchanged.
In `@lib/wal/src/segment.rs`:
- Around line 688-694: The helper copy_memory currently uses unsafe
ptr::copy_nonoverlapping with a manual length assertion; replace its body with a
safe slice copy by calling dst[..src.len()].copy_from_slice(src) (keeping the
same signature copy_memory(src: &[u8], dst: &mut [u8]) ), remove the unsafe
block and the explicit ptr import and the manual assert (or keep an assert! if
you want the same panic behavior) so the operation is safe and idiomatic.
In `@lib/wal/src/test_segment_recovery.rs`:
- Around line 55-61: The test currently hardcodes segment names
("open-2"/"open-3") and uses last_segment_file = dir.path().join("open-2"),
which is brittle; instead locate the empty/open segment dynamically by scanning
dir.path() for files matching the segment pattern (e.g., names starting with
"open-") and selecting the one with zero length (use std::fs::read_dir and
metadata().len()), then remove that discovered path and assert that the
discovered file no longer exists; update references to last_segment_file and any
existence assertions to use the dynamically found PathBuf rather than hardcoded
"open-2"/"open-3".
- Around line 70-73: Replace the timing-dependent std::thread::sleep in
test_segment_recovery with an explicit drop of the WAL (or the SegmentCreatorV2
owner) so the background segment-creation thread is joined before reopening;
specifically, ensure the WAL instance is dropped (or call drop(wal)) so
SegmentCreatorV2::drop runs and joins the creator thread, then proceed to
reopen—this removes the flaky sleep and guarantees deterministic cleanup before
the reopen step.
0d5a2c9 to
f411be3
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
lib/wal/Cargo.toml (2)
30-33: Binary-only deps (docopt,env_logger,serde) should be feature-gated, not unconditional.Every crate that depends on
wal(currentlylib/collection,lib/shard,lib/storage,lib/edge) transitively inheritsdocoptand its dependency graph. Additionally,docoptis unlikely to see significant future evolution, the wider docopt project is mostly unmaintained, and it has known significant bugs — the crates.io README itself suggests usingclapinstead. The rest of the Qdrant codebase usesclap; introducingdocoptvia an unconditional library dependency is inconsistent.Consider either:
- Gating the CLI binary deps behind a Cargo feature (e.g.,
cli), or- Replacing
docoptwithclapto align with the existing conventions in the workspace.♻️ Example: feature-gate the binary dependencies
+[features] +cli = ["dep:docopt", "dep:env_logger"] + [dependencies] -# Binary dependencies -docopt = "1.1" -env_logger = { workspace = true } -serde = { workspace = true } +docopt = { version = "1.1", optional = true } +env_logger = { workspace = true, optional = true } +serde = { workspace = true }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/Cargo.toml` around lines 30 - 33, The Cargo.toml currently lists binary-only deps (docopt, env_logger, serde) unconditionally which forces all dependent crates to inherit them; change this by moving these dependencies under an optional feature (e.g., add a feature named "cli") and mark the dependencies as optional and feature-gated (referring to docopt, env_logger, serde in Cargo.toml and the features table), or alternatively replace docopt with the workspace-standard clap by updating the dependency name from docopt to clap and adjusting any CLI code using docopt to use clap APIs; ensure the feature name ("cli") is documented in Cargo.toml and that other crates only enable it when building the wal CLI.
18-19: Consider movingcrc32candcrossbeam-channelto the workspace for consistency.Both are pinned locally while other dependencies in this crate use the
{ workspace = true }pattern. Consolidating them into the workspace would simplify version management across the project.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/Cargo.toml` around lines 18 - 19, The crc32c and crossbeam-channel dependencies are pinned locally in this crate's Cargo.toml while other deps use the workspace-managed versions; move their version declarations into the top-level workspace (add crc32c and crossbeam-channel with the desired versions under the workspace's dependency table) and in this crate's Cargo.toml replace the explicit version strings with crc32c = { workspace = true } and crossbeam-channel = { workspace = true } so they follow the same workspace-managed pattern.lib/wal/src/bin/wal-ctl.rs (1)
106-108: Redundant&onentry:entryis already&[u8].
entry: &[u8], so&entryis&&[u8].Wal::appendacceptsT: Deref<Target = [u8]>and works through double-deref, but passingentrydirectly is cleaner.♻️ Proposed fix
fn append(mut wal: Wal, entry: &[u8]) { - println!("{}", wal.append(&entry).unwrap()); + println!("{}", wal.append(entry).unwrap()); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/bin/wal-ctl.rs` around lines 106 - 108, The append helper function is passing a redundant reference to entry (making it &&[u8]); update the function append(mut wal: Wal, entry: &[u8]) to call Wal::append with entry directly: replace the call to wal.append(&entry).unwrap() with wal.append(entry).unwrap(); this targets the append function and the Wal::append invocation so the borrow is corrected without changing signatures.lib/wal/src/segment.rs (1)
371-380:_read_seed_crcand_read_entry_crccarry a misleading_prefix — they are actively used.The
_prefix on a method name conventionally signals that it is dead/intentionally-unused (to suppress the compiler warning). Both methods are called intruncate()at lines 400 and 403. Renaming them removes the false signal.♻️ Proposed rename
- fn _read_seed_crc(&self) -> u32 { + fn read_seed_crc(&self) -> u32 { LittleEndian::read_u32(&self.as_slice()[4..]) } - fn _read_entry_crc(&self, entry_id: usize) -> u32 { + fn read_entry_crc(&self, entry_id: usize) -> u32 {And update the call sites in
truncate:- self.crc = self._read_seed_crc(); + self.crc = self.read_seed_crc(); } else { - self.crc = self._read_entry_crc(self.index.len() - 1); + self.crc = self.read_entry_crc(self.index.len() - 1);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/segment.rs` around lines 371 - 380, The methods named _read_seed_crc and _read_entry_crc are not unused — the leading underscore misleadingly suggests they're dead; rename them to read_seed_crc and read_entry_crc and update all call sites (notably the calls inside truncate) to the new names, preserving signature/visibility and ensuring imports/uses of self.read_seed_crc and self.read_entry_crc compile correctly.lib/wal/src/test_segment_recovery.rs (1)
71-72: Sleep is now redundant —SegmentCreatorV2::dropalready joins the background thread.The comment explains the sleep exists to ensure background segment creation completes, but
SegmentCreatorV2'sDropimpl joins the background thread before returning fromdrop. The 4th WAL open will always see the pre-created segment regardless of this sleep.♻️ Proposed removal
- // sleep, to account for background process creating more segments - std::thread::sleep(std::time::Duration::from_millis(100)); - drop(wal);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/wal/src/test_segment_recovery.rs` around lines 71 - 72, Remove the redundant sleep and its comment from the test: the temporary pause (std::thread::sleep(std::time::Duration::from_millis(100))) in lib/wal/src/test_segment_recovery.rs is unnecessary because SegmentCreatorV2::drop already joins the background thread before returning, so delete that sleep call and its explanatory comment to avoid flaky waits and rely on the Drop synchronization provided by SegmentCreatorV2.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/wal/src/lib.rs`:
- Around line 257-284: Wal currently drops without joining the pending async
flush thread, so add a Drop impl on the Wal type that takes self.flush (the
JoinHandle stored by retire_open_segment), calls join(), and logs any
Err/Ok(Err) cases similarly to SegmentCreatorV2::drop; specifically implement
impl Drop for Wal { fn drop(&mut self) { if let Some(flush) = self.flush.take()
{ match flush.join() { Ok(Ok(())) => {}, Ok(Err(e)) => log::warn!("{self:?}:
flush thread error on drop: {e:?}"), Err(p) => log::warn!("{self:?}: flush
thread panicked on drop: {p:?}") } } } } to ensure the last segment’s flush is
awaited instead of being detached (refer to retire_open_segment, the flush
field, and SegmentCreatorV2 Drop behavior).
In `@lib/wal/src/segment_creator.rs`:
- Around line 116-121: The current use of
thread::Builder::new().spawn(...).unwrap() inside schedule_creation causes a
panic on thread creation failure; change schedule_creation (and callers like
refill_pending) to return Result and propagate the spawn error instead of
unwrapping, replace the unwrap on thread::Builder::spawn in the assignment to
self.thread with error handling that maps the spawn Err into an io::Error (or
the crate's error type) and returns it, and ensure callers handle the Result so
thread creation failures flow through the existing error propagation path rather
than panicking.
---
Duplicate comments:
In `@lib/wal/src/lib.rs`:
- Around line 182-199: The match arm for Ordering::Less currently calls
unimplemented!() which will panic; replace it with a proper Err return so the
function fails gracefully when a closed segment overlaps (use Error::new with
ErrorKind::InvalidData). In the error message include the relevant variables
(start_index, next_start_index and the offending segment's identifier/len via
segment.len()) so the caller can diagnose the overlapping closed segment instead
of crashing; ensure this change is made in the same match handling logic around
start_index and next_start_index.
- Line 20: The pub mod test_utils is exposed in the public API but only used in
tests; change its declaration to be compiled only for tests (use #[cfg(test)] on
the module declaration and remove public exposure) so test utilities aren't part
of the library API, and move any crates used solely by test_utils (e.g.,
rand_distr) from dependencies to dev-dependencies in Cargo.toml; locate the
module named test_utils in lib.rs and the rand_distr entry in Cargo.toml to make
these edits.
In `@lib/wal/src/mmap_view_sync.rs`:
- Around line 80-94: The doc comment for mmap_view_sync::restrict incorrectly
describes the allowed range as `offset + len < view.len()` while the
implementation permits equality; update the docstring for pub fn restrict(&mut
self, offset: usize, len: usize) -> Result<()> to state the correct constraint
`offset + len <= view.len()` (or `<= self.len`) so it matches the guard that
checks `if offset + len > self.len`, ensuring the comment and the implementation
are consistent.
- Around line 50-60: The split_at method's validation is wrong: change the guard
in MmapViewSync::split_at so it rejects offsets that are greater than or equal
to the view length (use offset >= self.len) and update the Error/errmsg to
reflect that offsets must be strictly less than the view length, preventing a
zero-length second view; locate and modify the check and the Error::new call
inside the split_at function to enforce this.
- Around line 40-47: Replace implicit conversions using .into() with the
explicit constructor MmapViewSync::from to follow the guideline; specifically,
in the functions that currently return Ok(mmap.into()) (the anonymous(...)
function and the other constructor that creates mmap via
MmapOptions::new().len(...).map_anon()?), change those returns to
Ok(MmapViewSync::from(mmap)) so both places use explicit
MmapViewSync::from(mmap) instead of mmap.into().
---
Nitpick comments:
In `@lib/wal/Cargo.toml`:
- Around line 30-33: The Cargo.toml currently lists binary-only deps (docopt,
env_logger, serde) unconditionally which forces all dependent crates to inherit
them; change this by moving these dependencies under an optional feature (e.g.,
add a feature named "cli") and mark the dependencies as optional and
feature-gated (referring to docopt, env_logger, serde in Cargo.toml and the
features table), or alternatively replace docopt with the workspace-standard
clap by updating the dependency name from docopt to clap and adjusting any CLI
code using docopt to use clap APIs; ensure the feature name ("cli") is
documented in Cargo.toml and that other crates only enable it when building the
wal CLI.
- Around line 18-19: The crc32c and crossbeam-channel dependencies are pinned
locally in this crate's Cargo.toml while other deps use the workspace-managed
versions; move their version declarations into the top-level workspace (add
crc32c and crossbeam-channel with the desired versions under the workspace's
dependency table) and in this crate's Cargo.toml replace the explicit version
strings with crc32c = { workspace = true } and crossbeam-channel = { workspace =
true } so they follow the same workspace-managed pattern.
In `@lib/wal/src/bin/wal-ctl.rs`:
- Around line 106-108: The append helper function is passing a redundant
reference to entry (making it &&[u8]); update the function append(mut wal: Wal,
entry: &[u8]) to call Wal::append with entry directly: replace the call to
wal.append(&entry).unwrap() with wal.append(entry).unwrap(); this targets the
append function and the Wal::append invocation so the borrow is corrected
without changing signatures.
In `@lib/wal/src/segment.rs`:
- Around line 371-380: The methods named _read_seed_crc and _read_entry_crc are
not unused — the leading underscore misleadingly suggests they're dead; rename
them to read_seed_crc and read_entry_crc and update all call sites (notably the
calls inside truncate) to the new names, preserving signature/visibility and
ensuring imports/uses of self.read_seed_crc and self.read_entry_crc compile
correctly.
In `@lib/wal/src/test_segment_recovery.rs`:
- Around line 71-72: Remove the redundant sleep and its comment from the test:
the temporary pause (std::thread::sleep(std::time::Duration::from_millis(100)))
in lib/wal/src/test_segment_recovery.rs is unnecessary because
SegmentCreatorV2::drop already joins the background thread before returning, so
delete that sleep call and its explanatory comment to avoid flaky waits and rely
on the Drop synchronization provided by SegmentCreatorV2.
This PR moves https://github.com/qdrant/wal into this repository.
Main reason: simplify single-crate-edge build process. #8173
The first commit copies all files verbatim without any changes. Subsequent commits are cleanings/linting/fixups/etc and integration.