Skip to content

refactor: split mutable_id_tracker.rs into a module - #8795

Merged
generall merged 2 commits into
devfrom
refactor/mutable-id-tracker-module
Apr 27, 2026
Merged

generall merged 2 commits into
devfrom
refactor/mutable-id-tracker-module

Conversation

@generall

Copy link
Copy Markdown
Member

Summary

  • Break the 1630-line lib/segment/src/id_tracker/mutable_id_tracker.rs into a directory module with logical separation.
  • New layout under lib/segment/src/id_tracker/mutable_id_tracker/:
    • mod.rs — MutableIdTracker struct + IdTracker impl (incl. flusher closures)
    • change.rs — MappingChange / MappingChangeType + read_entry/write_entry codec
    • mappings_storage.rs — mappings_path, load_mappings, store_mapping_changes, read_mappings*, write_mapping_changes, reconcile_persisted_mapping_changes
    • versions_storage.rs — versions_path, load_versions, store_version_changes, write_version_changes, reconcile_persisted_version_changes, VERSION_ELEMENT_SIZE
    • tests.rs — all unit tests, with explicit submodule imports
  • Pure code-move refactor: no logic changes, no public API changes. Visibility was preserved (pub(super) mod tests, pub(crate) fn mappings_path, pub(super) mappings field).

Test plan

  • cargo +nightly fmt --all -- --check passes (verified locally via pre-push hook)
  • cargo check -p segment --lib --tests introduces no new errors vs. dev (the pre-existing null_index::for_each_payload_block build errors on dev are unrelated to this change)
  • cargo test -p segment id_tracker::mutable_id_tracker passes once the unrelated null_index errors are resolved on dev
  • Manual review of the per-file diff to confirm only moves/imports changed

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3c4447ae-8c20-4831-8d0c-420722c3fe57

📥 Commits

Reviewing files that changed from the base of the PR and between c102ac0 and 78358c5.

📒 Files selected for processing (6)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/change.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mappings_storage.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mod.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/tests.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/versions_storage.rs
💤 Files with no reviewable changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker/versions_storage.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker/tests.rs

📝 Walkthrough

Walkthrough

The PR adds a new modular, file-backed implementation of a mutable ID tracker. New modules: change.rs (mapping-change binary format, read/write), mappings_storage.rs (append-only WAL for mapping entries with load/append/truncate/reconcile logic), versions_storage.rs (fixed-width on-disk version vector with partial-tail handling and batch writes), and mod.rs (tracker coordinating in-memory state, pending queues, and two-phase flush with mapping/versions persistors). It also adds a comprehensive test suite covering encoding, persistence, recovery, truncation, and iteration behavior, and removes the prior monolithic MutableIdTracker implementation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • deep memory reporting #8606: Touches the same MutableIdTracker surface (adds memory-reporting / ram_usage_bytes) and overlaps with the tracker refactor and API.

Suggested reviewers

  • coszio
  • xzfc
  • timvisee
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: split mutable_id_tracker.rs into a module' accurately and concisely describes the main change: breaking a single 1,630-line file into a modular directory structure with logical separation of concerns.
Description check ✅ Passed The description clearly explains the refactoring objective, new module layout, preservation of visibility/API, and provides comprehensive test verification steps, all directly related to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/mutable-id-tracker-module

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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/segment/src/id_tracker/mutable_id_tracker/mod.rs`:
- Around line 67-156: The mappings_path function is unnecessarily pub(crate)
while versions_path is pub(super); change mappings_path's visibility to
pub(super) so both helpers used only by sibling modules under mutable_id_tracker
have the same, narrower scope—locate mappings_path in mappings_storage.rs
(symbol: mappings_path) and update its declaration from pub(crate) fn
mappings_path(...) to pub(super) fn mappings_path(...), then run cargo check to
ensure no external callers rely on the wider visibility.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4df23c42-d0c6-461d-9d39-016a0d5d8f74

📥 Commits

Reviewing files that changed from the base of the PR and between 068fbc1 and a24bbcb.

📒 Files selected for processing (6)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/change.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mappings_storage.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mod.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/tests.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/versions_storage.rs
💤 Files with no reviewable changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs

Comment on lines +67 to +156

impl MutableIdTracker {
pub fn open(segment_path: impl Into<PathBuf>) -> OperationResult<Self> {
let segment_path = segment_path.into();

let (mappings_path, versions_path) =
(mappings_path(&segment_path), versions_path(&segment_path));
let (has_mappings, has_versions) = (mappings_path.is_file(), versions_path.is_file());

// Warn or error about unlikely or problematic scenarios
if !has_mappings && has_versions {
debug_assert!(
false,
"Missing mappings file for ID tracker while versions file exists, storage may be corrupted!",
);
log::error!(
"Missing mappings file for ID tracker while versions file exists, storage may be corrupted!",
);
}
if has_mappings && !has_versions {
log::warn!(
"Missing versions file for ID tracker, assuming automatic point mappings and version recovery by WAL",
);
}

let (mappings, mappings_expected_len) = if has_mappings {
load_mappings(&mappings_path).map_err(|err| {
OperationError::service_error(format!("Failed to load ID tracker mappings: {err}"))
})?
} else {
(PointMappings::default(), 0)
};

let internal_to_version = if has_versions {
load_versions(&versions_path).map_err(|err| {
OperationError::service_error(format!("Failed to load ID tracker versions: {err}"))
})?
} else {
vec![]
};

// Compare internal point mappings and versions count, report warning if we don't
debug_assert!(
mappings.total_point_count() >= internal_to_version.len(),
"can never have more versions than internal point mappings",
);
if mappings.total_point_count() != internal_to_version.len() {
log::warn!(
"Mutable ID tracker mappings and versions count mismatch, could have been partially flushed, assuming automatic recovery by WAL ({} mappings, {} versions)",
mappings.total_point_count(),
internal_to_version.len(),
);
}

#[cfg(debug_assertions)]
mappings.assert_mappings();

Ok(Self {
segment_path,
internal_to_version,
mappings,
pending_versions: Default::default(),
pending_mappings: Default::default(),
is_alive_lock: IsAliveLock::new(),
mappings_expected_len: Arc::new(AtomicU64::new(mappings_expected_len)),
})
}

/// Approximate RAM usage in bytes for in-memory data structures.
pub fn ram_usage_bytes(&self) -> usize {
let Self {
segment_path: _,
internal_to_version,
mappings,
pending_versions: _, // transient, small
pending_mappings: _, // transient, small
is_alive_lock: _,
mappings_expected_len: _,
} = self;

internal_to_version.capacity() * std::mem::size_of::<SeqNumberType>()
+ mappings.ram_usage_bytes()
}

pub fn segment_files(segment_path: &Path) -> Vec<PathBuf> {
[mappings_path(segment_path), versions_path(segment_path)]
.into_iter()
.filter(|path| path.is_file())
.collect()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find call sites of mappings_path and versions_path outside the new module to
# confirm pub(crate) vs pub(super) visibilities are still appropriate.
rg -nP --type=rust -C2 '\b(mappings_path|versions_path)\s*\(' \
  -g '!lib/segment/src/id_tracker/mutable_id_tracker/**'

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# First, find where mappings_path and versions_path are defined
rg -nP --type=rust '(pub\(.*\)\s+)?fn\s+(mappings_path|versions_path)' \
  lib/segment/src/id_tracker/

Repository: qdrant/qdrant

Length of output: 319


🏁 Script executed:

# Also search for all uses of these functions across the entire codebase
rg -nP --type=rust '(mappings_path|versions_path)' \
  lib/segment/src/id_tracker/ | head -40

Repository: qdrant/qdrant

Length of output: 4828


🏁 Script executed:

# Check specifically in the mod.rs file to see the current visibility
cat -n lib/segment/src/id_tracker/mutable_id_tracker/mod.rs | grep -A5 -B5 'fn mappings_path\|fn versions_path'

Repository: qdrant/qdrant

Length of output: 39


Align mappings_path visibility with versions_path: Change pub(crate) fn mappings_path to pub(super) in mappings_storage.rs:22. Both functions are only used by sibling modules within mutable_id_tracker (verified: no external callers outside this module), so narrower visibility is appropriate and aligns with the codebase preference for avoiding unnecessary broader exposure.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/id_tracker/mutable_id_tracker/mod.rs` around lines 67 - 156,
The mappings_path function is unnecessarily pub(crate) while versions_path is
pub(super); change mappings_path's visibility to pub(super) so both helpers used
only by sibling modules under mutable_id_tracker have the same, narrower
scope—locate mappings_path in mappings_storage.rs (symbol: mappings_path) and
update its declaration from pub(crate) fn mappings_path(...) to pub(super) fn
mappings_path(...), then run cargo check to ensure no external callers rely on
the wider visibility.

@qdrant-cloud-bot
qdrant-cloud-bot force-pushed the refactor/mutable-id-tracker-module branch from a24bbcb to ad77b06 Compare April 27, 2026 13:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/segment/src/id_tracker/mutable_id_tracker/tests.rs (1)

32-41: Use explicit PointIdType::from(...) here.

These new test calls use implicit .into(), which goes against the repository Rust style rule. Please make the conversion explicit in setup and assertions.

♻️ Suggested cleanup
-    id_tracker.set_link(200.into(), 0).unwrap();
-    id_tracker.set_link(100.into(), 1).unwrap();
-    id_tracker.set_link(150.into(), 2).unwrap();
-    id_tracker.set_link(120.into(), 3).unwrap();
-    id_tracker.set_link(180.into(), 4).unwrap();
-    id_tracker.set_link(110.into(), 5).unwrap();
-    id_tracker.set_link(115.into(), 6).unwrap();
-    id_tracker.set_link(190.into(), 7).unwrap();
-    id_tracker.set_link(177.into(), 8).unwrap();
-    id_tracker.set_link(118.into(), 9).unwrap();
+    id_tracker.set_link(PointIdType::from(200), 0).unwrap();
+    id_tracker.set_link(PointIdType::from(100), 1).unwrap();
+    id_tracker.set_link(PointIdType::from(150), 2).unwrap();
+    id_tracker.set_link(PointIdType::from(120), 3).unwrap();
+    id_tracker.set_link(PointIdType::from(180), 4).unwrap();
+    id_tracker.set_link(PointIdType::from(110), 5).unwrap();
+    id_tracker.set_link(PointIdType::from(115), 6).unwrap();
+    id_tracker.set_link(PointIdType::from(190), 7).unwrap();
+    id_tracker.set_link(PointIdType::from(177), 8).unwrap();
+    id_tracker.set_link(PointIdType::from(118), 9).unwrap();
@@
-    assert_eq!(first_four[0].0, 100.into());
+    assert_eq!(first_four[0].0, PointIdType::from(100));

As per coding guidelines, **/*.rs: Prefer explicit SomeType::from(x) over implicit x.into() in Rust.

Also applies to: 50-50

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/id_tracker/mutable_id_tracker/tests.rs` around lines 32 - 41,
Replace implicit `.into()` conversions in the test setup with explicit
PointIdType::from(...) calls: update each id_tracker.set_link(... .into(), ...)
call (function set_link in tests.rs) to pass PointIdType::from(200),
PointIdType::from(100), etc., and apply the same explicit conversion pattern
anywhere else in the file where ids are converted implicitly (e.g., assertions
or additional set_link invocations) to comply with the repository style.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/segment/src/id_tracker/mutable_id_tracker/tests.rs`:
- Around line 32-41: Replace implicit `.into()` conversions in the test setup
with explicit PointIdType::from(...) calls: update each id_tracker.set_link(...
.into(), ...) call (function set_link in tests.rs) to pass
PointIdType::from(200), PointIdType::from(100), etc., and apply the same
explicit conversion pattern anywhere else in the file where ids are converted
implicitly (e.g., assertions or additional set_link invocations) to comply with
the repository style.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8fe3e27d-565c-4f93-874e-7d795c8e0cf7

📥 Commits

Reviewing files that changed from the base of the PR and between ad77b06 and 600be35.

📒 Files selected for processing (1)
  • lib/segment/src/id_tracker/mutable_id_tracker/tests.rs

@qdrant-cloud-bot
qdrant-cloud-bot force-pushed the refactor/mutable-id-tracker-module branch from 600be35 to c102ac0 Compare April 27, 2026 14:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/segment/src/id_tracker/mutable_id_tracker/tests.rs (1)

243-243: Typo: intetrnal_id → internal_id.

Minor typo carried over in the moved test. Optional cleanup while you're touching this file.

♻️ Proposed nit fix
-        let intetrnal_id = id_tracker
+        let internal_id = id_tracker
             .internal_id(point_to_delete)
             .expect("Point to delete exists.");
-        assert!(!id_tracker.is_deleted_point(intetrnal_id));
+        assert!(!id_tracker.is_deleted_point(internal_id));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/id_tracker/mutable_id_tracker/tests.rs` at line 243, Rename
the misspelled local variable intetrnal_id to internal_id in the test that uses
id_tracker (identify the occurrence where the test assigns from id_tracker to
intetrnal_id) so the variable name is correct; update all references to that
variable within the same test function to match the new name.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/segment/src/id_tracker/mutable_id_tracker/tests.rs`:
- Line 243: Rename the misspelled local variable intetrnal_id to internal_id in
the test that uses id_tracker (identify the occurrence where the test assigns
from id_tracker to intetrnal_id) so the variable name is correct; update all
references to that variable within the same test function to match the new name.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a99dd078-1c69-4bfa-b9e4-49bc75b84bc8

📥 Commits

Reviewing files that changed from the base of the PR and between 600be35 and c102ac0.

📒 Files selected for processing (6)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/change.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mappings_storage.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/mod.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/tests.rs
  • lib/segment/src/id_tracker/mutable_id_tracker/versions_storage.rs
💤 Files with no reviewable changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/id_tracker/mutable_id_tracker/versions_storage.rs

generall and others added 2 commits April 27, 2026 15:06
Break the 1630-line file into a directory module with logically separated
components: change.rs (MappingChange + entry codec), mappings_storage.rs
(mappings file IO), versions_storage.rs (versions file IO), tests.rs (all
unit tests), and mod.rs (struct + IdTracker impl). No logic changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Import std::io::Seek so Cursor::stream_position resolves
- Drop unused PointMappingsRefEnum import
@qdrant-cloud-bot
qdrant-cloud-bot force-pushed the refactor/mutable-id-tracker-module branch from c102ac0 to 78358c5 Compare April 27, 2026 15:07
@generall
generall merged commit f04d8ae into dev Apr 27, 2026
20 of 21 checks passed
@generall
generall deleted the refactor/mutable-id-tracker-module branch April 27, 2026 16:34
timvisee pushed a commit that referenced this pull request May 8, 2026
* refactor: split mutable_id_tracker.rs into a module

Break the 1630-line file into a directory module with logically separated
components: change.rs (MappingChange + entry codec), mappings_storage.rs
(mappings file IO), versions_storage.rs (versions file IO), tests.rs (all
unit tests), and mod.rs (struct + IdTracker impl). No logic changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: clippy errors in mutable_id_tracker tests

- Import std::io::Seek so Cursor::stream_position resolves
- Drop unused PointMappingsRefEnum import

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants