volume: vacuum keeps a needle's own unexpired TTL and checks against an independent index tally (#12987)

* volume: vacuum keeps a needle's own unexpired TTL on a volume without TTL

Vacuum measured a needle's expiry against the volume TTL. On a volume
without TTL that is zero, so every needle carrying its own TTL was
dropped by the first vacuum while reads still served it. Fall back to
the needle's own TTL and append time, the rule reads use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): vacuum applies a needle's own TTL on a volume without TTL

Rust vacuum kept every needle with its own TTL on a volume without TTL,
even long after reads stopped serving it. Use the read path's expiry
rule there, matching the Go vacuum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check vacuum against a tally taken while loading the index

The compacted-size check summed its expected bytes inside the loop that
copies, so an entry the traversal never visited was missing from both
sides and the check could not see it. Tally the live entries while
replaying the .idx rows, count every copied, expired and unreadable
needle, and fail when they do not add up to the snapshot. The explicit
accounting also covers volumes with a TTL, so they are checked too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): check vacuum against a tally taken while loading the index

Mirror the Go change: tally the live entries while replaying the .idx
rows, count every copied, expired and unreadable needle, and fail when
they do not add up to the snapshot, on volumes with a TTL too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: treat a TTL flag without TTL bytes as no TTL

A record can set the TTL flag and end before the TTL field, leaving
Ttl nil. Checking such a needle's own TTL panicked in reads and, now,
in vacuum on volumes without TTL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: log each TTL-expired needle vacuum drops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): log each TTL-expired needle vacuum drops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-25 13:20:37 -08:00
1 parent e13f36275b
commit 802be6dd7b
4 files changed
+523 -89

No files matched your search

+264 -46
View File
@@ -122,6 +122,51 @@ fn exceeds_expected_compacted_size(expected_live_bytes: u64, dst_dat_size: u64)
expected_live_bytes > dst_dat_size
}
#[derive(Clone, Copy, Debug, Default)]
struct LiveTally {
count: u64,
bytes: u64,
}
impl LiveTally {
fn add(&mut self, size: Size) {
self.count += 1;
self.bytes += size.0.max(0) as u64;
}
}
fn is_live_index_entry(offset: Offset, size: Size) -> bool {
!offset.is_zero() && !size.is_deleted()
}
/// Fails when the copy did not account for every live entry of the snapshot,
/// or the compacted .dat is short of them.
fn check_compacted_against_snapshot(
id: VolumeId,
snapshot: LiveTally,
copied: LiveTally,
expired: LiveTally,
unreadable: LiveTally,
dst_dat_size: u64,
) -> Result<(), String> {
let accounted = copied.count + expired.count + unreadable.count;
let dropped_bytes = expired.bytes + unreadable.bytes;
if accounted != snapshot.count || dropped_bytes > snapshot.bytes {
return Err(format!(
"volume {} compaction accounted for {} of {} live index entries ({} copied, {} expired, {} unreadable)",
id.0, accounted, snapshot.count, copied.count, expired.count, unreadable.count
));
}
let expected_live_bytes = snapshot.bytes - dropped_bytes;
if exceeds_expected_compacted_size(expected_live_bytes, dst_dat_size) {
return Err(format!(
"volume {} unexpected new data size: {} does not match expected live content size {} from the pre-compaction snapshot",
id.0, dst_dat_size, expected_live_bytes
));
}
Ok(())
}
/// Read and parse the needle at `offset` through `read_at`.
fn read_needle_with(
read_at: impl Fn(&mut [u8], u64) -> Result<(), VolumeError>,
@@ -973,6 +1018,23 @@ fn needle_expired(n: &Needle) -> bool {
now_ns >= expire_at_ns
}
/// Applies the volume TTL when the volume has one, and otherwise the needle's
/// own TTL the way reads do.
fn vacuum_ttl_expired(
n: &Needle,
volume_ttl: &crate::storage::needle::ttl::TTL,
now_secs: u64,
) -> bool {
if !n.has_ttl() {
return false;
}
let ttl_minutes = volume_ttl.minutes();
if ttl_minutes == 0 {
return needle_expired(n);
}
n.last_modified > 0 && now_secs >= n.last_modified + (ttl_minutes as u64) * 60
}
/// Holds `Volume::is_compacting` set; dropping it clears the flag.
struct CompactionClaim(Arc<AtomicBool>);
@@ -1036,11 +1098,11 @@ impl CompactionJob {
.unwrap_or_default()
.as_secs();
let entries = self.live_entries()?;
let (entries, snapshot) = self.live_entries()?;
let mut skipped_needles: u64 = 0;
let mut skipped_data_bytes: u64 = 0;
let mut expected_live_bytes: u64 = 0;
let mut copied = LiveTally::default();
let mut expired = LiveTally::default();
let mut unreadable = LiveTally::default();
for (id, offset, size) in entries {
// Progress callback
if !progress_fn(offset.to_actual_offset()) {
@@ -1081,10 +1143,7 @@ impl CompactionJob {
e
))));
}
skipped_needles += 1;
if size.is_valid() {
skipped_data_bytes += size.0 as u64;
}
unreadable.add(size);
error!(
volume_id = self.id.0,
key = id.0,
@@ -1096,21 +1155,18 @@ impl CompactionJob {
continue;
}
// Skip TTL-expired needles using the volume's TTL (matches Go's volume_vacuum.go)
if n.has_ttl() {
let ttl_minutes = self.super_block.ttl.minutes();
if ttl_minutes > 0 && n.last_modified > 0 {
let expire_at = n.last_modified + (ttl_minutes as u64) * 60;
if now >= expire_at {
continue;
}
}
if vacuum_ttl_expired(&n, &self.super_block.ttl, now) {
expired.add(size);
debug!(
volume_id = self.id.0,
key = id.0,
offset = offset.to_actual_offset(),
size = size.0,
"vacuum: dropping TTL-expired needle"
);
continue;
}
// Tally the live bytes from the frozen snapshot this loop copied
// from, not the live needle map. Unreadable needles return before
// this point, so no further skipped-byte adjustment is needed.
expected_live_bytes += size.0 as u64;
copied.add(size);
// Write needle to destination
let bytes = n.write_bytes(version);
@@ -1121,38 +1177,48 @@ impl CompactionJob {
new_offset += bytes.len() as i64;
}
if skipped_needles > 0 {
if unreadable.count > 0 {
warn!(
volume_id = self.id.0,
skipped_needles,
skipped_data_bytes,
skipped_needles = unreadable.count,
skipped_data_bytes = unreadable.bytes,
"vacuum: dropped unreadable index entries during compaction"
);
}
if expired.count > 0 {
debug!(
volume_id = self.id.0,
expired_needles = expired.count,
expired_data_bytes = expired.bytes,
"vacuum: dropped TTL-expired needles"
);
}
dst.sync_all()?;
if self.super_block.ttl.is_empty() {
let dst_dat_size = dst.metadata()?.len();
if exceeds_expected_compacted_size(expected_live_bytes, dst_dat_size) {
let _ = fs::remove_file(cpd_path);
let _ = fs::remove_file(cpx_path);
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"volume {} unexpected new data size: {} does not match expected live content size {} from the pre-compaction snapshot",
self.id.0, dst_dat_size, expected_live_bytes
),
)));
}
let dst_dat_size = dst.metadata()?.len();
if let Err(msg) = check_compacted_against_snapshot(
self.id,
snapshot,
copied,
expired,
unreadable,
dst_dat_size,
) {
let _ = fs::remove_file(cpd_path);
let _ = fs::remove_file(cpx_path);
return Err(VolumeError::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
msg,
)));
}
// Save new index
new_nm.save_to_idx(cpx_path)?;
if skipped_needles > 0 {
if unreadable.count > 0 {
crate::metrics::VACUUMING_DROPPED_NEEDLES_COUNTER
.with_label_values(&[&self.collection])
.inc_by(skipped_needles);
.inc_by(unreadable.count);
}
Ok(())
@@ -1161,9 +1227,12 @@ impl CompactionJob {
/// Replay `.idx` up to the recorded size, as Go's `LoadFromIdx` does, and
/// return the live entries in `.dat` order. A short read fails: treating
/// it as the whole index would compact away every needle past it.
fn live_entries(&self) -> Result<Vec<(NeedleId, Offset, Size)>, VolumeError> {
/// Returns the live entries in offset order, and a tally of them taken
/// while replaying the rows, independently of the map traversal.
fn live_entries(&self) -> Result<(Vec<(NeedleId, Offset, Size)>, LiveTally), VolumeError> {
let rows = self.idx_size / NEEDLE_MAP_ENTRY_SIZE as u64;
let mut snapshot = CompactNeedleMap::new();
let mut live = LiveTally::default();
let mut seen = 0u64;
// Rows past the recorded size are makeup_diff's; do not read them.
let mut reader = io::BufReader::new((&self.src_idx).take(self.idx_size));
@@ -1175,10 +1244,17 @@ impl CompactionJob {
Err(e) => return Err(e.into()),
}
let (key, offset, size) = idx_entry_from_bytes(&buf);
if offset.is_zero() || size.is_deleted() {
snapshot.delete(key, offset)?;
} else {
if let Some(prior) = snapshot.get(key)
&& is_live_index_entry(prior.offset, prior.size)
{
live.count -= 1;
live.bytes -= prior.size.0.max(0) as u64;
}
if is_live_index_entry(offset, size) {
live.add(size);
snapshot.put(key, offset, size)?;
} else {
snapshot.delete(key, offset)?;
}
seen += 1;
}
@@ -1194,13 +1270,13 @@ impl CompactionJob {
let mut entries: Vec<(NeedleId, Offset, Size)> = Vec::new();
let _ = snapshot.ascending_visit(|id, nv| {
if !nv.offset.is_zero() && !nv.size.is_deleted() {
if is_live_index_entry(nv.offset, nv.size) {
entries.push((id, nv.offset, nv.size));
}
Ok::<(), std::convert::Infallible>(())
});
entries.sort_by_key(|(_, offset, _)| *offset);
Ok(entries)
Ok((entries, live))
}
}
@@ -11042,6 +11118,148 @@ mod tests {
assert_eq!(got.data, b"late-write");
}
#[test]
fn test_compact_by_index_keeps_unexpired_needle_ttl_on_plain_volume() {
use crate::storage::needle::ttl::TTL;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let v = make_test_volume(dir);
for i in 1..=8u64 {
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: format!("data-{}", i).into_bytes(),
data_size: format!("data-{}", i).len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true, false).unwrap();
}
let mut n = Needle {
id: NeedleId(100),
cookie: Cookie(100),
data: b"own-ttl".to_vec(),
data_size: 7,
ttl: Some(TTL::read("7d").unwrap()),
last_modified: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs(),
..Needle::default()
};
n.set_has_ttl();
n.set_has_last_modified_date();
v.write_needle(&mut n, true, false).unwrap();
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
let mut got = Needle {
id: NeedleId(100),
cookie: Cookie(100),
..Needle::default()
};
v.read_needle(&mut got).unwrap();
assert_eq!(got.data, b"own-ttl");
}
#[test]
fn test_vacuum_ttl_expired() {
use crate::storage::needle::ttl::TTL;
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let ttl_7d = TTL::read("7d").unwrap();
let ttl_1h = TTL::read("1h").unwrap();
let ttl_needle = |ttl: TTL, age_secs: u64| {
let mut n = Needle {
ttl: Some(ttl),
last_modified: now.as_secs() - age_secs,
append_at_ns: (now.as_nanos() as u64) - age_secs * 1_000_000_000,
..Needle::default()
};
n.set_has_ttl();
n.set_has_last_modified_date();
n
};
let secs = now.as_secs();
assert!(!vacuum_ttl_expired(&Needle::default(), &ttl_1h, secs));
assert!(!vacuum_ttl_expired(
&ttl_needle(ttl_7d, 3600),
&TTL::EMPTY,
secs
));
assert!(vacuum_ttl_expired(
&ttl_needle(ttl_1h, 7200),
&TTL::EMPTY,
secs
));
assert!(!vacuum_ttl_expired(
&ttl_needle(TTL::EMPTY, 172800),
&TTL::EMPTY,
secs
));
assert!(!vacuum_ttl_expired(
&ttl_needle(ttl_1h, 1800),
&ttl_1h,
secs
));
assert!(vacuum_ttl_expired(&ttl_needle(ttl_7d, 7200), &ttl_1h, secs));
}
#[test]
fn test_compact_by_index_checks_ttl_volume() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let ttl = crate::storage::needle::ttl::TTL::read("1h").unwrap();
let v = make_ttl_volume(dir, ttl);
for i in 1..=8u64 {
let mut n = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
data: format!("data-{}", i).into_bytes(),
data_size: format!("data-{}", i).len() as u32,
..Needle::default()
};
v.write_needle(&mut n, true, false).unwrap();
}
v.compact_by_index(0, 0, |_| true).unwrap();
v.commit_compact().unwrap();
for i in 1..=8u64 {
let mut got = Needle {
id: NeedleId(i),
cookie: Cookie(i as u32),
..Needle::default()
};
v.read_needle(&mut got).unwrap();
assert_eq!(got.data, format!("data-{}", i).into_bytes());
}
}
#[test]
fn test_check_compacted_against_snapshot() {
let tally = |count, bytes| LiveTally { count, bytes };
let none = LiveTally::default();
let snapshot = tally(4, 400);
let check = |copied, expired, unreadable, dst| {
check_compacted_against_snapshot(
VolumeId(1),
snapshot,
copied,
expired,
unreadable,
dst,
)
};
assert!(check(tally(4, 400), none, none, 500).is_ok());
assert!(check(tally(2, 200), tally(1, 100), tally(1, 100), 260).is_ok());
// A traversal that skipped entries.
assert!(check(tally(2, 200), none, none, 260).is_err());
// A short write.
assert!(check(tally(4, 400), none, none, 300).is_err());
assert!(check(none, tally(2, 300), tally(2, 300), 8).is_err());
}
#[test]
fn test_commit_compact_keeps_empty_needle_written_during_compaction() {
let tmp = TempDir::new().unwrap();
+13 -11
View File
@@ -128,22 +128,24 @@ func (v *Volume) readNeedle(n *needle.Needle, readOption *ReadOption, onReadSize
}
}
count = int(n.DataSize)
if !n.HasTtl() {
return
}
ttlMinutes := n.Ttl.Minutes()
if ttlMinutes == 0 {
return
}
if !n.HasLastModifiedDate() {
return
}
if time.Now().Before(time.Unix(0, int64(n.AppendAtNs)).Add(time.Duration(ttlMinutes) * time.Minute)) {
if !isNeedleTtlExpired(n, time.Now()) {
return
}
return -1, ErrorNotFound
}
// isNeedleTtlExpired applies the needle's own TTL, counted from its append time.
func isNeedleTtlExpired(n *needle.Needle, now time.Time) bool {
if !n.HasTtl() || n.Ttl == nil || !n.HasLastModifiedDate() {
return false
}
ttlMinutes := n.Ttl.Minutes()
if ttlMinutes == 0 {
return false
}
return !now.Before(time.Unix(0, int64(n.AppendAtNs)).Add(time.Duration(ttlMinutes) * time.Minute))
}
// LookupNeedle returns the needle map size of id without reading its record,
// so a needle past its TTL still counts as present.
func (v *Volume) LookupNeedle(id NeedleId) (size Size, found bool, err error) {
+88 -32
View File
@@ -40,12 +40,75 @@ func isSkippableNeedleReadError(err error) bool {
errors.Is(err, needle.ErrorCorrupted)
}
// isVacuumTtlExpired applies the volume TTL when the volume has one, and
// otherwise the needle's own TTL the way reads do.
func isVacuumTtlExpired(n *needle.Needle, volumeTtl *needle.TTL, now time.Time) bool {
if !n.HasTtl() {
return false
}
if volumeTtl == nil || volumeTtl.Minutes() == 0 {
return isNeedleTtlExpired(n, now)
}
return uint64(now.Unix()) >= n.LastModified+uint64(volumeTtl.Minutes())*60
}
// exceedsExpectedCompactedSize reports whether the compacted .dat is short of
// the live bytes the pre-compaction index snapshot expected.
func exceedsExpectedCompactedSize(expectedLiveBytes uint64, dstDatSize int64) bool {
return expectedLiveBytes > uint64(dstDatSize)
}
type liveTally struct {
count int
bytes uint64
}
func (t *liveTally) add(size Size) {
t.count++
t.bytes += uint64(size)
}
func isLiveIndexEntry(offset Offset, size Size) bool {
return !offset.IsZero() && !size.IsDeleted()
}
// loadIdxSnapshot loads idxPath into nm and tallies its live entries by
// replaying the rows, independently of any later traversal of nm.
func loadIdxSnapshot(nm *needle_map.MemDb, idxPath string) (live liveTally, err error) {
idxFile, err := os.Open(idxPath)
if err != nil {
return live, err
}
defer idxFile.Close()
err = idx2.WalkIndexFile(idxFile, 0, func(key NeedleId, offset Offset, size Size) error {
if prior, found := nm.Get(key); found && isLiveIndexEntry(prior.Offset, prior.Size) {
live.count--
live.bytes -= uint64(prior.Size)
}
if !isLiveIndexEntry(offset, size) {
return nm.Delete(key)
}
live.add(size)
return nm.Set(key, offset, size)
})
return live, err
}
// checkCompactedAgainstSnapshot fails when the copy did not account for
// every live entry of the snapshot, or the compacted .dat is short of them.
func checkCompactedAgainstSnapshot(vid needle.VolumeId, snapshot, copied, expired, unreadable liveTally, dstDatSize int64) error {
if copied.count+expired.count+unreadable.count != snapshot.count || expired.bytes+unreadable.bytes > snapshot.bytes {
return fmt.Errorf("volume %s compaction accounted for %d of %d live index entries (%d copied, %d expired, %d unreadable)",
vid, copied.count+expired.count+unreadable.count, snapshot.count, copied.count, expired.count, unreadable.count)
}
expectedLiveBytes := snapshot.bytes - expired.bytes - unreadable.bytes
if exceedsExpectedCompactedSize(expectedLiveBytes, dstDatSize) {
return fmt.Errorf("volume %s unexpected new data size: %d does not match expected live content size %d from the pre-compaction snapshot",
vid, dstDatSize, expectedLiveBytes)
}
return nil
}
type ProgressFunc func(processed int64) bool
func (v *Volume) garbageLevel() float64 {
@@ -715,7 +778,7 @@ func (scanner *VolumeFileScanner4Vacuum) VisitNeedle(n *needle.Needle, offset in
scanner.dropped[offset] = true
return nil
}
if n.HasTtl() && scanner.now >= n.LastModified+uint64(scanner.v.Ttl.Minutes()*60) {
if isVacuumTtlExpired(n, scanner.v.Ttl, time.Unix(int64(scanner.now), 0)) {
scanner.dropped[offset] = true
return nil
}
@@ -824,7 +887,8 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
var (
srcDatBackend, dstDatBackend backend.BackendStorageFile
dataFile *os.File
skippedNeedles int
snapshot liveTally
copied, expired, unreadable liveTally
)
if dstDatBackend, err = backend.CreateVolumeFile(opts.destDatPath, opts.PreallocateBytes, 0); err != nil {
return err
@@ -837,8 +901,8 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
if closeErr := dstDatBackend.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("close compacted dat %s: %v", opts.destDatPath, closeErr)
}
if err == nil && skippedNeedles > 0 {
stats.VolumeServerVacuumingDroppedNeedlesCounter.WithLabelValues(v.Collection).Add(float64(skippedNeedles))
if err == nil && unreadable.count > 0 {
stats.VolumeServerVacuumingDroppedNeedlesCounter.WithLabelValues(v.Collection).Add(float64(unreadable.count))
}
}()
@@ -846,7 +910,7 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
defer oldNm.Close()
newNm := needle_map.NewMemDb()
defer newNm.Close()
if err = oldNm.LoadFromIdx(opts.srcIdxPath); err != nil {
if snapshot, err = loadIdxSnapshot(oldNm, opts.srcIdxPath); err != nil {
return err
}
if dataFile, err = os.Open(opts.srcDatPath); err != nil {
@@ -855,7 +919,7 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
srcDatBackend = backend.NewDiskFile(dataFile)
defer srcDatBackend.Close()
now := uint64(time.Now().Unix())
now := time.Now()
opts.superBlock.CompactionRevision++
newOffset := int64(opts.superBlock.BlockSize())
@@ -864,15 +928,11 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
}
writeThrottler := util.NewWriteThrottler(opts.MaxBytesPerSecond)
var (
skippedDataBytes uint64
expectedLiveBytes uint64
)
err = oldNm.AscendingVisit(func(value needle_map.NeedleValue) error {
offset, size := value.Offset, value.Size
if offset.IsZero() || size.IsDeleted() {
if !isLiveIndexEntry(offset, size) {
return nil
}
@@ -893,20 +953,19 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
if !isSkippableNeedleReadError(err) {
return fmt.Errorf("cannot hydrate needle from file: %w", err)
}
skippedNeedles++
if size.IsValid() {
skippedDataBytes += uint64(size)
}
unreadable.add(size)
glog.Errorf("vacuum volume %d: dropping unreadable needle key=%d offset=%d size=%d: %v",
v.Id, value.Key, offset.ToActualOffset(), size, err)
return nil
}
if n.HasTtl() && now >= n.LastModified+uint64(opts.superBlock.Ttl.Minutes()*60) {
if isVacuumTtlExpired(n, opts.superBlock.Ttl, now) {
expired.add(size)
glog.V(1).Infof("vacuum volume %d: dropping TTL-expired needle key=%d offset=%d size=%d",
v.Id, value.Key, offset.ToActualOffset(), size)
return nil
}
expectedLiveBytes += uint64(size)
copied.add(size)
if err = newNm.Set(n.Id, ToOffset(newOffset), n.Size); err != nil {
return fmt.Errorf("cannot put needle: %s", err)
@@ -924,22 +983,19 @@ func (v *Volume) copyDataBasedOnIndexFile(opts *CompactOptions) (err error) {
if err != nil {
return err
}
if skippedNeedles > 0 {
if unreadable.count > 0 {
glog.Warningf("vacuum volume %d: dropped %d unreadable index entries (%d data bytes) during compaction",
v.Id, skippedNeedles, skippedDataBytes)
v.Id, unreadable.count, unreadable.bytes)
}
if v.Ttl.String() == "" {
dstDatSize, _, err := dstDatBackend.GetStat()
if err != nil {
return err
}
// expectedLiveBytes is tallied from oldNm (the frozen snapshot this
// loop copied from), not the live v.nm; unreadable needles already
// return before the tally, so no further skipped-byte adjustment.
if exceedsExpectedCompactedSize(expectedLiveBytes, dstDatSize) {
return fmt.Errorf("volume %s unexpected new data size: %d does not match expected live content size %d from the pre-compaction snapshot",
v.Id.String(), dstDatSize, expectedLiveBytes)
}
if expired.count > 0 {
glog.V(1).Infof("vacuum volume %d: dropped %d TTL-expired needles (%d data bytes)", v.Id, expired.count, expired.bytes)
}
dstDatSize, _, err := dstDatBackend.GetStat()
if err != nil {
return err
}
if err = checkCompactedAgainstSnapshot(v.Id, snapshot, copied, expired, unreadable, dstDatSize); err != nil {
return err
}
err = newNm.SaveToIdx(opts.destIdxPath)
if err != nil {
+158
View File
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -952,3 +953,160 @@ func TestCompactByVolumeData_SkipsRunOfDamagedIds(t *testing.T) {
t.Errorf("resumed scans made %d reads for a run of %d damaged headers", reads.readCount, run)
}
}
func TestVacuumKeepsUnexpiredNeedleTtlOnPlainVolume(t *testing.T) {
for _, method := range []string{"index", "data"} {
t.Run(method, func(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
for i := 1; i <= 8; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
}
n := newRandomNeedle(100)
n.Ttl, _ = needle.ReadTTL("7d")
n.SetHasTtl()
n.LastModified = uint64(time.Now().Unix())
n.SetHasLastModifiedDate()
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write ttl needle: %v", err)
}
compact := v.CompactByIndex
if method == "data" {
compact = v.CompactByVolumeData
}
if err := compact(nil); err != nil {
t.Fatalf("compact: %v", err)
}
if err := v.CommitCompact(); err != nil {
t.Fatalf("commit: %v", err)
}
if _, err := v.readNeedle(&needle.Needle{Id: 100}, nil, nil); err != nil {
t.Fatalf("needle with an unexpired 7d TTL was removed by vacuum: %v", err)
}
})
}
}
func TestIsVacuumTtlExpired(t *testing.T) {
now := time.Now()
ttl7d, _ := needle.ReadTTL("7d")
ttl1h, _ := needle.ReadTTL("1h")
newTtlNeedle := func(ttl *needle.TTL, age time.Duration) *needle.Needle {
n := &needle.Needle{Ttl: ttl}
n.SetHasTtl()
n.SetHasLastModifiedDate()
n.LastModified = uint64(now.Add(-age).Unix())
n.AppendAtNs = uint64(now.Add(-age).UnixNano())
return n
}
noTtl := &needle.TTL{}
tests := []struct {
name string
n *needle.Needle
volumeTtl *needle.TTL
want bool
}{
{"no ttl flag", &needle.Needle{}, ttl1h, false},
{"own ttl not expired on plain volume", newTtlNeedle(ttl7d, time.Hour), noTtl, false},
{"own ttl expired on plain volume", newTtlNeedle(ttl1h, 2*time.Hour), noTtl, true},
{"own ttl zero on plain volume", newTtlNeedle(noTtl, 48*time.Hour), noTtl, false},
{"ttl flag without ttl bytes", newTtlNeedle(nil, 48*time.Hour), noTtl, false},
{"nil volume ttl uses own ttl", newTtlNeedle(ttl1h, 2*time.Hour), nil, true},
{"volume ttl not expired", newTtlNeedle(ttl1h, 30*time.Minute), ttl1h, false},
{"volume ttl expired", newTtlNeedle(ttl7d, 2*time.Hour), ttl1h, true},
}
for _, tt := range tests {
if got := isVacuumTtlExpired(tt.n, tt.volumeTtl, now); got != tt.want {
t.Errorf("%s: isVacuumTtlExpired = %v, want %v", tt.name, got, tt.want)
}
}
}
func TestLoadIdxSnapshotTalliesLiveEntries(t *testing.T) {
idxPath := filepath.Join(t.TempDir(), "1.idx")
var rows []byte
appendRow := func(key uint64, offset int64, size types.Size) {
rows = append(rows, needle_map.ToBytes(types.Uint64ToNeedleId(key), types.ToOffset(offset), size)...)
}
appendRow(1, 8, 100)
appendRow(2, 200, 50)
appendRow(1, 400, 120) // overwrite
appendRow(2, 0, types.TombstoneFileSize)
appendRow(3, 600, 0) // empty needle stays live
appendRow(4, 800, 70)
appendRow(4, 800, -70)
appendRow(4, 900, 30) // re-put after delete
if err := os.WriteFile(idxPath, rows, 0644); err != nil {
t.Fatal(err)
}
nm := needle_map.NewMemDb()
defer nm.Close()
live, err := loadIdxSnapshot(nm, idxPath)
if err != nil {
t.Fatalf("loadIdxSnapshot: %v", err)
}
if live.count != 3 || live.bytes != 150 {
t.Fatalf("tally = %+v, want 3 entries, 150 bytes", live)
}
visited := 0
if err := nm.AscendingVisit(func(needle_map.NeedleValue) error { visited++; return nil }); err != nil {
t.Fatal(err)
}
if visited != live.count {
t.Fatalf("map holds %d entries, tally %d", visited, live.count)
}
}
func TestCheckCompactedAgainstSnapshot(t *testing.T) {
snapshot := liveTally{count: 4, bytes: 400}
tests := []struct {
name string
copied, expired, unreadable liveTally
dstDatSize int64
wantErr bool
}{
{"all copied", liveTally{4, 400}, liveTally{}, liveTally{}, 500, false},
{"expired and unreadable accounted", liveTally{2, 200}, liveTally{1, 100}, liveTally{1, 100}, 260, false},
{"traversal skipped entries", liveTally{2, 200}, liveTally{}, liveTally{}, 260, true},
{"short write", liveTally{4, 400}, liveTally{}, liveTally{}, 300, true},
{"drops exceed snapshot bytes", liveTally{0, 0}, liveTally{2, 300}, liveTally{2, 300}, 8, true},
}
for _, tt := range tests {
err := checkCompactedAgainstSnapshot(1, snapshot, tt.copied, tt.expired, tt.unreadable, tt.dstDatSize)
if (err != nil) != tt.wantErr {
t.Errorf("%s: err = %v, wantErr %v", tt.name, err, tt.wantErr)
}
}
}
func TestCompactByIndexChecksTtlVolume(t *testing.T) {
dir := t.TempDir()
ttl, _ := needle.ReadTTL("1h")
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, ttl, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
defer v.Close()
for i := 1; i <= 8; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
}
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("CompactByIndex: %v", err)
}
if err := v.CommitCompact(); err != nil {
t.Fatalf("commit: %v", err)
}
for i := 1; i <= 8; i++ {
if _, err := v.readNeedle(&needle.Needle{Id: types.Uint64ToNeedleId(uint64(i))}, nil, nil); err != nil {
t.Fatalf("read needle %d after compaction: %v", i, err)
}
}
}