Skip to content

fix: free removed versions after releasing the keyspaces lock - #352

Open
jsmey7 wants to merge 1 commit into
fjall-rs:mainfrom
eliosai:free-versions-off-lock
Open

jsmey7 wants to merge 1 commit into
fjall-rs:mainfrom
eliosai:free-versions-off-lock

Conversation

@jsmey7

@jsmey7 jsmey7 commented Nov 12, 2026 •

Copy link
Copy Markdown

When a keyspace rotates its memtable, inner_rotate_memtable runs version history GC for every keyspace while it holds the keyspaces read lock. The GC can drop the last reference to a flushed memtable, so a full memtable gets freed under that lock (and, inside lsm-tree, under the version history write lock, which every insert reads).

This PR collects what maintenance returns and drops it after the loop, when the keyspaces guard is gone. It depends on fjall-rs/lsm-tree#328, which makes maintenance return the removed versions. Against the released lsm-tree 3.1.10 the call returns (), so this still compiles and behaves as before until that change is released.

Repro, with fjall as the only dependency: four keyspaces with 32 MiB memtables and one writer doing 100 synced commits a second of 1,000 small entries each, for 60 seconds. The write buffer limit is raised so write stalls do not hide the effect.

main.rs
use fjall::{KeyspaceCreateOptions, PersistMode, SingleWriterTxDatabase};
use std::time::{Duration, Instant};

const KEYSPACES: u64 = 4;
const COMMITS_PER_SEC: u64 = 100;
const ENTRIES_PER_COMMIT: u64 = 1_000;
const MEMTABLE_BYTES: u64 = 32 * 1_024 * 1_024;
const RUN: Duration = Duration::from_secs(60);

fn main() -> fjall::Result<()> {
    let db = SingleWriterTxDatabase::builder(".repro_data")
        .temporary(true)
        .max_write_buffer_size(Some(1 << 30))
        .open()?;
    let options = || KeyspaceCreateOptions::default().max_memtable_size(MEMTABLE_BYTES);
    let keyspaces = (0..KEYSPACES)
        .map(|i| db.keyspace(&format!("ks{i}"), options))
        .collect::<fjall::Result<Vec<_>>>()?;

    let interval = Duration::from_secs(1) / COMMITS_PER_SEC as u32;
    let start = Instant::now();
    let (mut latencies, mut counter) = (Vec::new(), 0_u32);
    let mut key = 0_u64;
    while start.elapsed() < RUN {
        let due = start + interval * counter;
        std::thread::sleep(due.saturating_duration_since(Instant::now()));
        let began = Instant::now();
        let mut tx = db.write_tx().durability(Some(PersistMode::SyncAll));
        for _ in 0..ENTRIES_PER_COMMIT {
            key += 1;
            let keyspace = &keyspaces[(key % KEYSPACES) as usize];
            tx.insert(keyspace, key.to_be_bytes(), [0_u8; 32]);
        }
        counter += 1;
        tx.commit()?;
        latencies.push(began.elapsed());
    }

    latencies.sort();
    let slow = latencies
        .iter()
        .filter(|x| **x > Duration::from_millis(50))
        .count();
    println!(
        "commits={} p99={:?} max={:?} over_50ms={slow}",
        latencies.len(),
        latencies[latencies.len() * 99 / 100],
        latencies[latencies.len() - 1],
    );
    Ok(())
}

Three runs each on aarch64 Linux with the default allocator. "Before" is fjall main with lsm-tree main, "after" is both branches together:

p99 max commits over 50 ms
before 6.6 / 5.7 / 6.4 ms 191 / 141 / 176 ms 7 / 9 / 7
after 7.6 / 6.8 / 8.3 ms 93 / 93 / 87 ms 5 / 4 / 7

The worst commit goes from between 141 and 191 ms to between 87 and 93 ms. p99 and the number of slow commits do not improve. As a check I leaked the removed versions instead of dropping them, and the max fell to between 47 and 60 ms with 0 to 3 slow commits, so what is left looks like the free itself competing with the writer in the allocator. I have not looked further into that.

The test suite passes with the lsm-tree change (on main) and without it (on 3.1.13).

Summary by CodeRabbit

  • Bug Fixes
    • Version-history maintenance results are now released after keyspace iteration, helping prevent resource cleanup from occurring while keyspaces are being read.

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

During memtable rotation, successful version-history maintenance results are collected and dropped after the keyspaces read lock is released. Errors continue to be logged without stopping processing of other keyspaces.

Changes: Rotation Cleanup

Layer / File(s) Summary
Defer dropping maintenance results
src/keyspace/mod.rs
Successful maintenance results are retained in a vector and dropped after keyspace iteration releases the read lock. Errors are logged, and processing continues for other keyspaces.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Suggested labels: fix

Suggested reviewers: marvin-j97

Merge Risk: Minimal · up to 9574c

This change defers freeing removed versions until the keyspaces lock is released, which reduces the maximum commit latency. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix: free removed versions after releasing the keyspaces lock" matches the main change. The summary shows that maintenance results are now collected and dropped after the keyspaces read loc…
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.
Full details: Title check

Explanation

The title "fix: free removed versions after releasing the keyspaces lock" matches the main change. The summary shows that maintenance results are now collected and dropped after the keyspaces read lock is released. The title is concise, specific, and names the lock-ordering reason for the change.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: eb2cf6c6-6095-44d9-96e0-32efa849017f
Commits

Reviewing files that changed from the base of the PR and between 8700604 and 9574c83.

Files selected for processing: 1

  • src/keyspace/mod.rs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@codecov

codecov Bot commented Nov 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/keyspace/mod.rs 85.71% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
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.

1 participant