Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#15258·rocksdb

SstFileManager's reserved disk buffer grows by write_buffer_size on every DB::Open and is never released, so after enough reopens the DB can no longer recover from a NoSpace error

Author: hanke580Created Sep 23, 2026Updated Sep 23, 2026

Summary

Every successful DB::Open with a user-supplied SstFileManager calls ReserveDiskBuffer(max_write_buffer_size), which does reserved_disk_buffer_ += size. Nothing ever subtracts it: not Close(), not ~DBImpl(), nothing in the tree. A manager that outlives one DB instance, i.e. reopened or shared across instances (which is what SstFileManager is for), accumulates one write buffer per open, forever.

SstFileManagerImpl::ClearError() refuses to clear a hard NoSpace error while free_space < reserved_disk_buffer_, with free_space capped at max_allowed_space. Once enough opens have pushed the counter past the cap, a DB that hits a transient out-of-space condition can never auto-recover, however much disk is actually free.

Root cause

Reserve, once per open (db/db_impl/db_impl_open.cc:2925-2931):

cpp
    // Reserve some disk buffer space. This is a heuristic - when we run out
    // of disk space, this ensures that there is at least write_buffer_size
    // amount of free space before we resume DB writes. In low disk space
    // conditions, we want to avoid a lot of small L0 files due to frequent
    // WAL write failures and resultant forced flushes
    sfm->ReserveDiskBuffer(max_write_buffer_size,
                           impl->immutable_db_options_.db_paths[0].path);

Accumulate (file/sst_file_manager_impl.cc:254-262):

cpp
void SstFileManagerImpl::ReserveDiskBuffer(uint64_t size,
                                           const std::string& path) {
  MutexLock l(&mu_);

  reserved_disk_buffer_ += size;
  if (path_.empty()) {
    path_ = path;
  }
}

Gate recovery (file/sst_file_manager_impl.cc:272-292, abridged):

cpp
    Status s = fs_->GetFreeSpace(path_, IOOptions(), &free_space, nullptr);
    free_space = max_allowed_space_ > 0
                     ? std::min(max_allowed_space_, free_space)
                     : free_space;
    if (s.ok()) {
      if (bg_err_.severity() == Status::Severity::kHardError) {
        if (free_space < reserved_disk_buffer_) {
          ROCKS_LOG_ERROR(logger_, "free space [%" PRIu64 " bytes] is less than "
                          "required disk buffer [%" PRIu64 " bytes]\n",
                          free_space, reserved_disk_buffer_);
          ROCKS_LOG_ERROR(logger_, "Cannot clear hard error\n");
          s = Status::NoSpace();
        }
      ...

The comment at the call site asks for "at least write_buffer_size amount of free space", i.e. one buffer. The counter holds one per open, cumulatively. reserved_disk_buffer_ is written in exactly two places (constructor :39 and :258). It is also added to needed_headroom in EnoughRoomForCompaction() (:197-198) once a NoSpace has been seen, so the inflated value throttles compactions too.

DBImpl::CloseHelper() already undoes this DB's other effects on an unowned manager (db/db_impl/db_impl.cc:991-996, added by #13015):

cpp
  // Return an unowned SstFileManager to a consistent state
  if (immutable_db_options_.sst_file_manager && !own_sfm_) {
    mutex_.Unlock();
    UntrackDataFiles();
    mutex_.Lock();
  }

but not the disk buffer.

Reproduction

Self-contained, public API only. A FileSystemWrapper fails .sst/.log writes with IOStatus::NoSpace() for the duration of one flush, then stops, to simulate a transient disk-full. write_buffer_size is 64 MiB and SetMaxAllowedSpaceUsage(256 MiB), so the cap is crossed on the 5th open. The real volume has terabytes free throughout. A Logger passed to the SstFileManager captures ClearError()'s own log line, so the reserved value shown is read from RocksDB, not computed.

cpp
// SstFileManager's reserved disk buffer grows by write_buffer_size on every
// DB::Open and is never released, so after enough reopens on one manager the
// DB can no longer auto-recover from a transient out-of-space error.
// Public API only. Usage: ./sfm_disk_buffer_accumulates [scratch_dir]
#include <rocksdb/db.h>
#include <rocksdb/env.h>
#include <rocksdb/file_system.h>
#include <rocksdb/options.h>
#include <rocksdb/sst_file_manager.h>
#include <atomic>
#include <cinttypes>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <memory>
#include <string>
#include <unistd.h>
using namespace ROCKSDB_NAMESPACE;

static std::atomic<bool> g_disk_full{false};

// Fails .sst/.log writes with NoSpace while g_disk_full is set.
class FullFile : public FSWritableFileWrapper {
 public:
  FullFile(std::unique_ptr<FSWritableFile>&& f, bool watched)
      : FSWritableFileWrapper(f.get()), owned_(std::move(f)), watched_(watched) {}
  IOStatus Append(const Slice& d, const IOOptions& o, IODebugContext* g) override {
    if (g_disk_full && watched_) return IOStatus::NoSpace("injected");
    return FSWritableFileWrapper::Append(d, o, g);
  }
  IOStatus Append(const Slice& d, const IOOptions& o,
                  const DataVerificationInfo& v, IODebugContext* g) override {
    if (g_disk_full && watched_) return IOStatus::NoSpace("injected");
    return FSWritableFileWrapper::Append(d, o, v, g);
  }
  IOStatus Sync(const IOOptions& o, IODebugContext* g) override {
    if (g_disk_full && watched_) return IOStatus::NoSpace("injected");
    return FSWritableFileWrapper::Sync(o, g);
  }
 private:
  std::unique_ptr<FSWritableFile> owned_;
  bool watched_;
};

class FullFS : public FileSystemWrapper {
 public:
  using FileSystemWrapper::FileSystemWrapper;
  const char* Name() const override { return "FullFS"; }
  IOStatus NewWritableFile(const std::string& f, const FileOptions& fo,
                           std::unique_ptr<FSWritableFile>* r,
                           IODebugContext* g) override {
    std::unique_ptr<FSWritableFile> inner;
    IOStatus s = FileSystemWrapper::NewWritableFile(f, fo, &inner, g);
    if (!s.ok()) return s;
    auto ends = [&](const char* x) {
      return f.size() >= strlen(x) && f.compare(f.size() - strlen(x), strlen(x), x) == 0;
    };
    r->reset(new FullFile(std::move(inner), ends(".sst") || ends(".log")));
    return s;
  }
};

// Captures the SstFileManager's "required disk buffer [N bytes]" log line,
// which prints the internal reserved_disk_buffer_ value.
class CaptureLogger : public Logger {
 public:
  std::atomic<uint64_t> required{0};
  using Logger::Logv;
  void Logv(const char* fmt, va_list ap) override {
    char buf[512];
    vsnprintf(buf, sizeof buf, fmt, ap);
    const char* p = strstr(buf, "required disk buffer [");
    if (p) required = strtoull(p + strlen("required disk buffer ["), nullptr, 10);
  }
};

static const uint64_t kWriteBuffer = 64ull << 20;
static const uint64_t kMaxAllowed = 256ull << 20;

static void Run(const std::string& base, int opens, bool share_sfm) {
  std::string dir = base + "/sfm_buf_" + std::to_string(opens) + (share_sfm ? "s" : "f");
  auto fs = std::make_shared<FullFS>(FileSystem::Default());
  std::unique_ptr<Env> env = NewCompositeEnv(fs);
  auto logger = std::make_shared<CaptureLogger>();
  std::shared_ptr<SstFileManager> sfm;
  auto new_sfm = [&] {
    sfm.reset(NewSstFileManager(env.get(), logger));
    sfm->SetMaxAllowedSpaceUsage(kMaxAllowed);
  };
  new_sfm();

  Options o;
  o.create_if_missing = true;
  o.env = env.get();
  o.write_buffer_size = kWriteBuffer;
  DestroyDB(dir, o);

  // Open the same DB `opens` times, closing it in between.
  std::unique_ptr<DB> db;
  for (int i = 0; i < opens; i++) {
    db.reset();
    if (!share_sfm) new_sfm();  // control: a fresh manager per open
    o.sst_file_manager = sfm;
    Status s = DB::Open(o, dir, &db);
    if (!s.ok()) { printf("open: %s\n", s.ToString().c_str()); return; }
  }

  // Transient disk-full: the flush fails with NoSpace, a hard error.
  g_disk_full = true;
  db->Put(WriteOptions(), "k", std::string(4096, 'x'));
  Status flush = db->Flush(FlushOptions());
  g_disk_full = false;  // space is available again

  int waited = 0;
  bool recovered = false;
  for (; waited < 60 && !recovered; waited++) {
    recovered = db->Put(WriteOptions(), "after", "1").ok();
    if (!recovered) sleep(1);
  }
  printf("%d open(s), %-6s SstFileManager: flush -> \"%s\"; %s",
         opens, share_sfm ? "shared" : "fresh", flush.ToString().c_str(),
         recovered ? "recovered" : "NOT recovered after 60 s");
  if (logger->required)
    printf("; SFM log: required disk buffer = %" PRIu64 " MiB > %" PRIu64 " MiB",
           logger->required.load() >> 20, kMaxAllowed >> 20);
  printf("\n");
}

int main(int argc, char** argv) {
  std::string base = argc > 1 ? argv[1] : "/tmp";
  Run(base, 4, true);   // 4 x 64 MiB = 256 MiB reserved: not above the cap
  Run(base, 5, true);   // 5 x 64 MiB = 320 MiB reserved: above the cap
  Run(base, 5, false);  // control: same 5 opens, fresh manager each time
  return 0;
}

Build against a make static_lib tree. -fno-rtti is needed because the program subclasses FileSystemWrapper and Logger and a release librocksdb.a is built without RTTI. Add -lsnappy -llz4 -lzstd -lbz2 etc. if your library uses them:

bash
g++ -std=c++20 -O2 -fno-rtti -o sfm_disk_buffer_accumulates sfm_disk_buffer_accumulates.cc \
    -I rocksdb/include rocksdb/librocksdb.a -lpthread -ldl -lz -lnuma
./sfm_disk_buffer_accumulates /tmp

Output on main @ 507206e4:

4 open(s), shared SstFileManager: flush -> "IO error: No space left on device: injected"; recovered
5 open(s), shared SstFileManager: flush -> "IO error: No space left on device: injected"; NOT recovered after 60 s; SFM log: required disk buffer = 320 MiB > 256 MiB
5 open(s), fresh  SstFileManager: flush -> "IO error: No space left on device: injected"; recovered

Expected

The buffer is described as "at least write_buffer_size" of headroom, so it should be 64 MiB however many times the DB has been opened. A closed instance should not keep a reservation. All three runs should recover once the disk-full condition clears, as the 4-open and fresh-manager runs do.

Actual

After 5 opens on one manager, ClearError() reports a required buffer of 320 MiB (5 × 64 MiB) against the 256 MiB cap and logs Cannot clear hard error on every retry. The DB never leaves read-only mode. The boundary is exact and matches the source: 4 opens (256 MiB, not less than 256 MiB) still recover.

The fresh-manager control isolates the cause. It is the same 5 opens and the same injected fault, but nothing accumulates, and it recovers.

With the default max_allowed_space = 0, free_space is the volume's real free space, so the crossing takes correspondingly more opens. It is still reachable for a long-lived process that reopens DBs (or opens many instances) on one manager when the disk is moderately full. Any cap set with SetMaxAllowedSpaceUsage() brings it much closer.

Suggested fix

Give the reservation back when the DB that took it closes, e.g. from the same !own_sfm_ block in CloseHelper():

cpp
void SstFileManagerImpl::ReleaseDiskBuffer(uint64_t size) {
  MutexLock l(&mu_);
  assert(reserved_disk_buffer_ >= size);
  reserved_disk_buffer_ -= std::min(reserved_disk_buffer_, size);
}

This requires DBImpl to remember the max_write_buffer_size it reserved at open. Alternatively, track the buffer per registered DB instance and use the maximum (or sum) over live instances, which also gives a sensible figure when instances have different write_buffer_size values. A regression test can reopen a DB N times on one manager with max_allowed_space just above one buffer and assert that a transient NoSpace still auto-recovers.

Environment

RocksDB main @ 507206e46bdf876174532b8eb6b26f54f698b8dc (2026-09-21), version 11.11.0
built with `make static_lib` (DEBUG_LEVEL=0), g++ 11.4.0, -std=c++20
Ubuntu 22.04.2 LTS, Linux 5.15.0-187-generic, x86_64
also reproduced on the released 11.8.1; code unchanged since #4164 (2018)

Source: facebook/rocksdb

View original on GitHubView discussion on GitHub