From 79b4062f1b19416d21d528da547a09851c48317c Mon Sep 17 00:00:00 2001 From: Luca Ongaro Date: Wed, 2 Oct 2024 15:36:10 +0200 Subject: [PATCH] Fix dirt calculation across restarts --- CHANGELOG.md | 4 ++++ lib/cubdb/btree.ex | 2 +- test/cubdb_test.exs | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdd556f..f41c076 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ reports changes here. - Add function `CubDB.writes_since_compaction/1` to get the number of writes since the last successful compaction +Bug fixes: + + - Fix dirt calculation upon restart of `CubDB` + ## v2.0.2 (2023-01-01) Bug fixes: diff --git a/lib/cubdb/btree.ex b/lib/cubdb/btree.ex index b02f4c7..403e943 100644 --- a/lib/cubdb/btree.ex +++ b/lib/cubdb/btree.ex @@ -244,7 +244,7 @@ defmodule CubDB.Btree do # updates won't be committed to the database and will be lost in case of a # restart. def commit(tree = %Btree{store: store, size: size, root_loc: root_loc, dirt: dirt}) do - Store.put_header(store, header(size: size, location: root_loc, dirt: dirt + 1)) + Store.put_header(store, header(size: size, location: root_loc, dirt: dirt)) tree end diff --git a/test/cubdb_test.exs b/test/cubdb_test.exs index 160087d..64b2143 100644 --- a/test/cubdb_test.exs +++ b/test/cubdb_test.exs @@ -1003,6 +1003,24 @@ defmodule CubDBTest do refute_received :compaction_started end + test "dirt calculation is consistent after restart", %{tmp_dir: tmp_dir} do + {:ok, db} = CubDB.start_link(data_dir: tmp_dir, auto_compact: false) + + CubDB.put(db, "foo", 123) + CubDB.put(db, "bar", 234) + CubDB.delete(db, "foo") + CubDB.clear(db) + + original_dirt_factor = CubDB.dirt_factor(db) + original_writes_since_compaction = CubDB.dirt_factor(db) + + CubDB.stop(db) + + {:ok, db} = CubDB.start_link(data_dir: tmp_dir, auto_compact: false) + assert original_dirt_factor == CubDB.dirt_factor(db) + assert original_writes_since_compaction == CubDB.dirt_factor(db) + end + test "auto compaction is active by default", %{tmp_dir: tmp_dir} do {:ok, db} = CubDB.start_link(tmp_dir)