Skip to content

[Reliability] Refcount underflow crashes vault during recovery — no bounds checking on reference counts #69

Description

@anshul23102

Executive Summary

When files are deleted or recovered concurrently, reference count can underflow, causing a panic and making the vault inaccessible. This is a data integrity issue.

Root Cause

Refcount operations don't check for underflow or concurrent modification.

Proposed Solution

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

pub struct BlockMetadata {
  refcount: Arc<AtomicU64>,
  size: u64,
}

impl BlockMetadata {
  pub fn decrement_safe(&self) -> Result<u64, &'static str> {
    loop {
      let current = self.refcount.load(Ordering::SeqCst);
      if current == 0 {
        return Err("Refcount underflow: cannot decrement below 0");
      }
      let result = self.refcount.compare_exchange(
        current,
        current - 1,
        Ordering::SeqCst,
        Ordering::SeqCst,
      );
      if result.is_ok() {
        return Ok(current - 1);
      }
    }
  }
  
  pub fn increment_safe(&self) -> Result<u64, &'static str> {
    let new_count = self.refcount.fetch_add(1, Ordering::SeqCst) + 1;
    if new_count > u64::MAX / 2 {
      self.refcount.fetch_sub(1, Ordering::SeqCst);
      return Err("Refcount overflow protection triggered");
    }
    Ok(new_count)
  }
}

Checklist

  • I have searched existing issues and confirmed this is not a duplicate
  • I have read the CONTRIBUTING.md guidelines
  • I have provided clear steps to reproduce the issue
  • I have described expected vs. actual behavior clearly
  • This issue title is clear and specific
  • This repository has been verified as NSOC on https://www.nsoc.in/projects

@Rakshat28 Could you please /assign this issue to me? I would like to implement safe refcount operations under NSOC '26.

/assign

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions