From 7ed90dace35e86f4c5f277b2807254fabe94c0aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 06:09:41 +0200 Subject: [PATCH] fix: keep model file handles open between tensor loads The loader opened the model file again for every batch of tensors, in every worker thread: once per component at startup (text encoder, UNet, VAE) and then again each time weights are loaded back from disk (per segment, per residency swap, per request). Each open is a chance to fail, and on Windows it can fail exactly when the system is short of memory or handles ("failed to open '...safetensors'" at VAE decode, after RAM hit 100%). A new FileHandlePool keeps the read streams open and hands them out to the workers one at a time. ModelLoader owns one; copies and the per-file readers used for LoRA tensors share it. A stream is dropped when the file's size or modification time changes, when it is in an error state, or when its source is removed. If a read fails the worker reopens the file once and repeats the read, so a stream that went bad while idle (removable or network storage) no longer fails the whole generation. The open retry with errno/doserrno logging moves into the pool and now also covers .ckpt (zip) files. Measured with a synthetic SD 1.5 checkpoint on CPU: the file is opened 5 times for three server requests instead of 9 per request; an injected EIO is absorbed and the image is pixel-identical; persistent read errors end in a clean error. test/file_handle_pool_test.cpp covers reuse, changed and replaced files, failed streams, limits and concurrent use, and passes under ASan/UBSan and ThreadSanitizer. Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC --- .gitignore | 1 + docs/integrazione_progetti.md | 20 +- src/model_io/file_handle_pool.cpp | 263 ++++++++++++++++++++++++ src/model_io/file_handle_pool.h | 99 +++++++++ src/model_loader.cpp | 60 +++--- src/model_loader.h | 3 + src/model_loader_files.cpp | 5 + test/README.md | 1 + test/file_handle_pool_test.cpp | 325 ++++++++++++++++++++++++++++++ 9 files changed, 740 insertions(+), 37 deletions(-) create mode 100644 src/model_io/file_handle_pool.cpp create mode 100644 src/model_io/file_handle_pool.h create mode 100644 test/file_handle_pool_test.cpp diff --git a/.gitignore b/.gitignore index d941ac1e..a953a836 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ test/* !test/security_smoke.sh !test/api_robustness.cpp !test/pe_imports_test.cpp +!test/file_handle_pool_test.cpp !test/fuzz_model_loader.py tests/ .vscode/ diff --git a/docs/integrazione_progetti.md b/docs/integrazione_progetti.md index 17971887..57c6a4a0 100644 --- a/docs/integrazione_progetti.md +++ b/docs/integrazione_progetti.md @@ -322,7 +322,8 @@ Che cosa è automatico e che cosa no: | `--list-devices` mostra solo `CPU` | build senza backend GPU, SDK assente in build, driver mancante, o DLL dei backend non accanto all'eseguibile | leggere il log (stderr): una riga `[W] CUDA backend: ggml-cuda.dll found in ... was not usable: ` dice perché il modulo GPU presente non si è caricato (su Windows elenca anche le DLL mancanti, per esempio `cublas64_12.dll`); `[I] no GPU backend module ... found in: ` significa che nessun modulo GPU è accanto all'eseguibile (pacchetto o build senza GPU). Poi: driver aggiornato, pacchetto giusto (`cuda12` per NVIDIA), cartella davvero usata dall'applicazione | | `auto-fit: no GPU devices` nei log | come sopra: il motore non vede acceleratori | stessa verifica; un'etichetta "GPU" nei log dell'applicazione non prova nulla | | HTTP **502** da un proxy durante una generazione lunga | il proxy ha un timeout (es. la `fetch` di Node abbandona dopo ~5 minuti senza risposta) mentre il motore sta ancora calcolando | non reinviare alla cieca; usare API a job asincroni con polling; controllare i log del servizio | -| Il motore si chiude durante il caricamento pesi con `read tensor data failed` | pressione di memoria estrema durante letture grandi, oppure file del modello incompleto | liberare RAM o usare `--params-backend disk`; verificare l'integrità del file (dimensione attesa vs reale) | +| Il motore si chiude durante il caricamento pesi con `read tensor data failed` | pressione di memoria estrema durante letture grandi, oppure file del modello incompleto | liberare RAM o usare `--params-backend disk`; verificare l'integrità del file (dimensione attesa vs reale). Prima di arrendersi il motore riapre il file e ripete la lettura una volta: se compare anche solo `read from '...' failed; reopening the file and trying again` il problema è stato assorbito, se subito dopo c'è `read tensor data failed` no | +| `open '...' failed (attempt N/5): errno=..., doserrno=...` | il sistema ha rifiutato l'apertura del file del modello (su Windows: blocco temporaneo di un antivirus o di un altro programma, risorse di sistema scarse) | il motore riprova da solo fino a 5 volte; se tutti i tentativi falliscono, inviare le righe `errno`/`doserrno`: indicano la causa reale | | Windows impedisce l'avvio dell'eseguibile (EACCES/EPERM) | policy di sicurezza, es. Smart App Control, o binario bloccato | controllare Sicurezza di Windows e i registri CodeIntegrity; usare binari attendibili; **non** disattivare le protezioni | | Generazione lentissima (minuti per passo) | esecuzione sulla CPU, risoluzione alta, o modello troppo grande per la memoria | verificare i device; ridurre risoluzione/passi; modello quantizzato; build GPU | | Avviso "memory guard: pressure" nei log | la memoria del device (su CPU: la RAM di sistema) ha superato la soglia `--memory-guard` | è un avviso con riduzione automatica della residenza: evitare nuove richieste finché non segnala il recupero | @@ -871,6 +872,23 @@ sincronizzazioni future. `src/core/pe_imports.{h,cpp}`) e un suggerimento. ggml li carica in silenzio nelle build Release e su Windows non riporta mai l'errore del sistema. Test del lettore: `test/pe_imports_test.cpp`. +13. **File del modello aperti una volta sola** — `src/model_io/file_handle_pool.{h,cpp}`: + `ModelLoader` tiene aperti i flussi di lettura dei file modello e li + riusa tra i caricamenti dei componenti (testo, UNet, VAE), tra i segmenti + e tra le richieste, invece di riaprire il file a ogni lotto di pesi e per + ogni thread (con i pesi su disco accadeva centinaia di volte, proprio + quando la RAM è piena). Un flusso viene scartato se il file cambia + (dimensione o data) o se una lettura fallisce; in quel caso il motore + riapre il file e ripete la lettura una volta (`read from '...' failed; + reopening the file and trying again`). Anche l'apertura dei `.ckpt` ha + ora i tentativi ripetuti. Misure con un modello sintetico (CPU, 2 thread): + 5 aperture del file per 3 richieste del server, invece di 9 per ciascuna; + un errore di lettura iniettato (EIO) viene assorbito e l'immagine resta + identica; errori persistenti terminano con un errore pulito. I file + restano aperti finché il modello è caricato: su Windows non si può + sostituire o cancellare il file del modello mentre il motore lo usa + (come già accadeva con `--mmap`). Test: `test/file_handle_pool_test.cpp` + (ASan/UBSan e ThreadSanitizer). Passaggi previsti e non ancora svolti: collaudo del workflow di release sui runner GitHub, generazione con un modello reale (inclusa la memory guard sotto diff --git a/src/model_io/file_handle_pool.cpp b/src/model_io/file_handle_pool.cpp new file mode 100644 index 00000000..eea0453e --- /dev/null +++ b/src/model_io/file_handle_pool.cpp @@ -0,0 +1,263 @@ +#include "model_io/file_handle_pool.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/util.h" + +namespace sd { + + bool open_with_retry(const std::string& path, const std::function& try_open) { + constexpr int kAttempts = 5; + for (int attempt = 1; attempt <= kAttempts; ++attempt) { + errno = 0; + if (try_open()) { + return true; + } + const int saved_errno = errno; +#ifdef _WIN32 + unsigned long win_err = 0; + _get_doserrno(&win_err); +#endif + const std::string reason = std::generic_category().message(saved_errno); +#ifdef _WIN32 + LOG_WARN("open '%s' failed (attempt %d/%d): errno=%d (%s), doserrno=%lu", + path.c_str(), attempt, kAttempts, saved_errno, reason.c_str(), win_err); +#else + LOG_WARN("open '%s' failed (attempt %d/%d): errno=%d (%s)", + path.c_str(), attempt, kAttempts, saved_errno, reason.c_str()); +#endif + if (saved_errno == ENOENT || attempt == kAttempts) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(200 * attempt)); + } + return false; + } + + struct FileHandlePool::State { + struct Idle { + std::unique_ptr stream; + Stamp stamp; + }; + + std::mutex mutex; + std::map> idle; + size_t max_idle = 8; + uint64_t generation = 0; + size_t open_streams = 0; + size_t opened = 0; + size_t reused = 0; + }; + + FileHandlePool::FileHandlePool() + : state_(std::make_shared()) { + } + + FileHandlePool::Stamp FileHandlePool::read_stamp(const std::string& path) { + Stamp stamp; + std::error_code error; + const auto file_path = std::filesystem::u8path(path); + stamp.time = std::filesystem::last_write_time(file_path, error); + if (error) { + return stamp; + } + stamp.size = std::filesystem::file_size(file_path, error); + stamp.valid = !error; + return stamp; + } + + FileHandlePool::Lease FileHandlePool::acquire(const std::string& path, bool fresh) { + const Stamp stamp = read_stamp(path); + + // Streams are closed after the lock is released; closing can block on slow storage. + std::vector> to_close; + std::unique_ptr stream; + uint64_t generation = 0; + { + std::lock_guard lock(state_->mutex); + generation = state_->generation; + auto found = state_->idle.find(path); + if (found != state_->idle.end()) { + auto& list = found->second; + // A handle opened before the file changed would keep serving the old content. + // When the file cannot be inspected right now (this can happen under resource + // pressure) there is nothing to compare, so an idle handle is kept and reused. + auto stale = std::stable_partition(list.begin(), list.end(), [&](const State::Idle& entry) { + return !fresh && (!stamp.valid || entry.stamp.same_as(stamp)); + }); + for (auto it = stale; it != list.end(); ++it) { + to_close.push_back(std::move(it->stream)); + --state_->open_streams; + } + list.erase(stale, list.end()); + if (!list.empty()) { + stream = std::move(list.back().stream); + list.pop_back(); + ++state_->reused; + } + if (list.empty()) { + state_->idle.erase(found); + } + } + } + to_close.clear(); + + if (!stream) { + auto opened = std::make_unique(); + const bool ok = open_with_retry(path, [&]() { + opened->clear(); + opened->open(path, std::ios::binary); + return opened->is_open(); + }); + if (!ok) { + LOG_ERROR("failed to open '%s'", path.c_str()); + return Lease(); + } + stream = std::move(opened); + std::lock_guard lock(state_->mutex); + ++state_->opened; + ++state_->open_streams; + } + + Lease lease; + lease.state_ = state_; + lease.stream_ = std::move(stream); + lease.path_ = path; + lease.stamp_ = stamp; + lease.generation_ = generation; + return lease; + } + + void FileHandlePool::set_max_idle(size_t max_idle_per_file) { + std::vector> to_close; + { + std::lock_guard lock(state_->mutex); + state_->max_idle = std::max(max_idle_per_file, 1); + for (auto it = state_->idle.begin(); it != state_->idle.end();) { + auto& list = it->second; + while (list.size() > state_->max_idle) { + to_close.push_back(std::move(list.back().stream)); + list.pop_back(); + --state_->open_streams; + } + it = list.empty() ? state_->idle.erase(it) : std::next(it); + } + } + } + + void FileHandlePool::close_idle() { + std::vector> to_close; + { + std::lock_guard lock(state_->mutex); + ++state_->generation; + for (auto& entry : state_->idle) { + for (auto& idle : entry.second) { + to_close.push_back(std::move(idle.stream)); + --state_->open_streams; + } + } + state_->idle.clear(); + } + } + + void FileHandlePool::close_idle(const std::string& path) { + std::vector> to_close; + { + std::lock_guard lock(state_->mutex); + auto found = state_->idle.find(path); + if (found == state_->idle.end()) { + return; + } + for (auto& idle : found->second) { + to_close.push_back(std::move(idle.stream)); + --state_->open_streams; + } + state_->idle.erase(found); + } + } + + size_t FileHandlePool::open_count() const { + std::lock_guard lock(state_->mutex); + return state_->open_streams; + } + + size_t FileHandlePool::opened_total() const { + std::lock_guard lock(state_->mutex); + return state_->opened; + } + + size_t FileHandlePool::reused_total() const { + std::lock_guard lock(state_->mutex); + return state_->reused; + } + + FileHandlePool::Lease::Lease(Lease&& other) noexcept + : state_(std::move(other.state_)), + stream_(std::move(other.stream_)), + path_(std::move(other.path_)), + stamp_(other.stamp_), + generation_(other.generation_), + discarded_(other.discarded_) { + } + + FileHandlePool::Lease& FileHandlePool::Lease::operator=(Lease&& other) noexcept { + if (this != &other) { + release(); + state_ = std::move(other.state_); + stream_ = std::move(other.stream_); + path_ = std::move(other.path_); + stamp_ = other.stamp_; + generation_ = other.generation_; + discarded_ = other.discarded_; + } + return *this; + } + + FileHandlePool::Lease::~Lease() { + release(); + } + + void FileHandlePool::Lease::discard() { + discarded_ = true; + release(); + } + + void FileHandlePool::Lease::release() { + if (!stream_) { + return; + } + std::unique_ptr stream = std::move(stream_); + std::shared_ptr state = std::move(state_); + const bool discarded = discarded_; + discarded_ = false; + + std::unique_ptr to_close; + { + std::lock_guard lock(state->mutex); + // Reaching the end of the file is normal; any other error leaves the stream unusable. + const bool healthy = !discarded && stream->is_open() && !stream->fail(); + auto& list = state->idle[path_]; + if (healthy && generation_ == state->generation && list.size() < state->max_idle) { + stream->clear(); + list.push_back({std::move(stream), stamp_}); + } else { + to_close = std::move(stream); + --state->open_streams; + if (list.empty()) { + state->idle.erase(path_); + } + } + } + } + +} // namespace sd diff --git a/src/model_io/file_handle_pool.h b/src/model_io/file_handle_pool.h new file mode 100644 index 00000000..e5535e80 --- /dev/null +++ b/src/model_io/file_handle_pool.h @@ -0,0 +1,99 @@ +#ifndef __SD_FILE_HANDLE_POOL_H__ +#define __SD_FILE_HANDLE_POOL_H__ + +#include +#include +#include +#include +#include +#include +#include + +namespace sd { + + // Calls try_open until it succeeds, a few times at most, and logs the OS error after each + // failure. Opening a file can fail for a moment on Windows (sharing violations, scarce + // system resources); a short wait usually turns that into a success. + bool open_with_retry(const std::string& path, const std::function& try_open); + + // Keeps read-only streams of model files open between tensor loads. Weights that live on + // disk are read again for every segment and every request; opening the file each time + // is a chance to fail exactly when the system is short of memory or handles. + // + // Copies of a pool share the same handles. All members are thread-safe; a stream is used + // by one lease at a time. + class FileHandlePool { + struct State; + struct Stamp { + bool valid = false; + uintmax_t size = 0; + std::filesystem::file_time_type time = {}; + + bool same_as(const Stamp& other) const { + return valid && other.valid && size == other.size && time == other.time; + } + }; + + public: + class Lease { + public: + Lease() = default; + Lease(Lease&& other) noexcept; + Lease& operator=(Lease&& other) noexcept; + Lease(const Lease&) = delete; + Lease& operator=(const Lease&) = delete; + ~Lease(); + + explicit operator bool() const { return stream_ != nullptr; } + std::ifstream& stream() { return *stream_; } + + // Closes the stream instead of giving it back, for a stream that failed or + // that may be stale. + void discard(); + + private: + friend class FileHandlePool; + + void release(); + + std::shared_ptr state_; + std::unique_ptr stream_; + std::string path_; + Stamp stamp_; + uint64_t generation_ = 0; + bool discarded_ = false; + }; + + FileHandlePool(); + // Copying shares the open streams. There is deliberately no move: a moved-from + // ModelLoader must stay usable. + FileHandlePool(const FileHandlePool&) = default; + FileHandlePool& operator=(const FileHandlePool&) = default; + + // Returns an open stream for path, reusing an idle one when the file has not changed + // since it was opened. With fresh set, idle streams of that path are closed and the + // file is opened again. The lease is empty when the file cannot be opened. + Lease acquire(const std::string& path, bool fresh = false); + + // At most this many idle streams are kept per file. + void set_max_idle(size_t max_idle_per_file); + + // Closes every idle stream; streams that are leased now are closed when returned. + void close_idle(); + + // Closes the idle streams of one file. + void close_idle(const std::string& path); + + size_t open_count() const; // streams that are open, idle or leased + size_t opened_total() const; // files opened since the pool was created + size_t reused_total() const; // acquisitions served by an idle stream + + private: + static Stamp read_stamp(const std::string& path); + + std::shared_ptr state_; + }; + +} // namespace sd + +#endif // __SD_FILE_HANDLE_POOL_H__ diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 70806c37..bf6b8cdd 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -167,6 +167,7 @@ void convert_tensor(void* src, ModelLoader::ModelLoader() : n_threads_(sd_get_num_physical_cores()) { + file_pool_.set_max_idle(static_cast(std::max(n_threads_, 1))); } size_t ModelLoader::add_file_path(const std::string& file_path) { @@ -188,6 +189,7 @@ void ModelLoader::add_tensor_storage(const TensorStorage& tensor_storage) { void ModelLoader::set_n_threads(int n_threads) { n_threads_ = n_threads > 0 ? n_threads : sd_get_num_physical_cores(); + file_pool_.set_max_idle(static_cast(std::max(n_threads_, 1))); LOG_VERBOSE("using %d threads for model loading", n_threads_); } @@ -1137,45 +1139,21 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, for (int i = 0; i < n_threads; ++i) { workers.emplace_back([&, file_path, is_zip]() { - std::ifstream file; + sd::FileHandlePool::Lease file; zip_t* zip = nullptr; if (is_zip) { - zip = zip_open(file_path.c_str(), 0, 'r'); + sd::open_with_retry(file_path, [&]() { + zip = zip_open(file_path.c_str(), 0, 'r'); + return zip != nullptr; + }); if (zip == nullptr) { LOG_ERROR("failed to open zip '%s'", file_path.c_str()); failed = true; return; } } else if (!mmapped) { - // Opening can fail transiently on Windows (e.g. sharing violations under - // load); retry and log the OS error so the cause is visible. - constexpr int kOpenAttempts = 5; - for (int attempt = 1; attempt <= kOpenAttempts; ++attempt) { - file.clear(); - errno = 0; - file.open(file_path, std::ios::binary); - if (file.is_open()) { - break; - } - int saved_errno = errno; -#ifdef _WIN32 - unsigned long win_err = 0; - _get_doserrno(&win_err); - LOG_WARN("open '%s' failed (attempt %d/%d): errno=%d (%s), doserrno=%lu", - file_path.c_str(), attempt, kOpenAttempts, - saved_errno, strerror(saved_errno), win_err); -#else - LOG_WARN("open '%s' failed (attempt %d/%d): errno=%d (%s)", - file_path.c_str(), attempt, kOpenAttempts, - saved_errno, strerror(saved_errno)); -#endif - if (saved_errno == ENOENT || attempt == kOpenAttempts) { - break; - } - std::this_thread::sleep_for(std::chrono::milliseconds(200 * attempt)); - } - if (!file.is_open()) { - LOG_ERROR("failed to open '%s'", file_path.c_str()); + file = file_pool_.acquire(file_path); + if (!file) { failed = true; return; } @@ -1273,11 +1251,21 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, return false; } } else { - file.seekg(tensor_storage.offset); - file.read(buf, n); - if (!file) { - LOG_ERROR("read tensor data failed: '%s'", file_path.c_str()); - return false; + auto read_from_file = [&]() { + file.stream().seekg(tensor_storage.offset); + file.stream().read(buf, n); + return static_cast(file.stream()); + }; + if (!read_from_file()) { + // A stream kept open for a long time can go bad (removable or + // network storage); try once more on a newly opened one. + LOG_WARN("read from '%s' failed; reopening the file and trying again", file_path.c_str()); + file.discard(); + file = file_pool_.acquire(file_path, true); + if (!file || !read_from_file()) { + LOG_ERROR("read tensor data failed: '%s'", file_path.c_str()); + return false; + } } } return true; diff --git a/src/model_loader.h b/src/model_loader.h index 63ecfb63..d3a94315 100644 --- a/src/model_loader.h +++ b/src/model_loader.h @@ -10,6 +10,7 @@ #include #include "model.h" +#include "model_io/file_handle_pool.h" TensorTypeRules parse_tensor_type_rules(const std::string& tensor_type_rules); @@ -70,6 +71,8 @@ private: std::string tensor_type_rules_; std::vector parsed_dependencies_; std::map> parsed_tensor_names_; + // Keeps model files open between tensor loads. Copies of a loader share it. + sd::FileHandlePool file_pool_; static bool read_file_stamp(const std::string& path, FileStamp& stamp); static bool file_unchanged(const FileStamp& stamp); diff --git a/src/model_loader_files.cpp b/src/model_loader_files.cpp index 8e838b11..3f1ef6ba 100644 --- a/src/model_loader_files.cpp +++ b/src/model_loader_files.cpp @@ -209,9 +209,13 @@ bool ModelLoader::del_file(FileId id) { if (it == files_.end()) { return false; } + const std::vector released = it->dependencies; files_.erase(it); ++revision_; rebuild_catalog(); + for (const auto& stamp : released) { + file_pool_.close_idle(stamp.path); + } return true; } @@ -311,6 +315,7 @@ ModelLoader ModelLoader::file_reader(FileId id, SDVersion version) const { ModelLoader reader; reader.file_paths_ = file_paths_; reader.n_threads_ = n_threads_; + reader.file_pool_ = file_pool_; reader.version_ = version; reader.names_converted_ = true; for (const auto& file : files_) { diff --git a/test/README.md b/test/README.md index 909e2f14..bd191d17 100644 --- a/test/README.md +++ b/test/README.md @@ -10,6 +10,7 @@ sezione "Sicurezza". | `security_smoke.sh` | file modello ostili + opzioni CLI estreme → mai crash (exit < 128) | `./test/security_smoke.sh build/bin/sd-cli` | | `api_robustness.cpp` | API C: puntatori nulli, indici fuori range, buffer piccoli, stress multi-thread (con ASan/UBSan) | vedi intestazione del file | | `pe_imports_test.cpp` | lettore della tabella di importazione dei file PE (diagnostica delle DLL mancanti su Windows): file validi, troncati e corrotti (con ASan/UBSan) | vedi intestazione del file | +| `file_handle_pool_test.cpp` | pool dei flussi aperti sui file modello: riuso, file modificato o sostituito, flussi in errore, limiti, uso concorrente (con ASan/UBSan e TSan) | vedi intestazione del file | | `fuzz_model_loader.py` | fuzzing a mutazione del caricamento modelli (safetensors/GGUF) | `python3 test/fuzz_model_loader.py --seconds 300` | Per il fuzzing è consigliata una build con AddressSanitizer: diff --git a/test/file_handle_pool_test.cpp b/test/file_handle_pool_test.cpp new file mode 100644 index 00000000..b507effa --- /dev/null +++ b/test/file_handle_pool_test.cpp @@ -0,0 +1,325 @@ +// Test for the pool of open model file handles (src/model_io/file_handle_pool.*). +// Build and run from the repository root; only the headers of this repository are needed: +// c++ -std=c++17 -g -fsanitize=address,undefined -Isrc -Iinclude -Iggml/include -pthread test/file_handle_pool_test.cpp src/model_io/file_handle_pool.cpp -o file_handle_pool_test +// ./file_handle_pool_test +// Use -fsanitize=thread instead of address,undefined to check the multi-thread cases. +// Exit code 0 = all checks passed. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/util.h" +#include "model_io/file_handle_pool.h" + +namespace fs = std::filesystem; + +static std::atomic warnings{0}; +static std::atomic errors{0}; + +// The pool logs through the library's logger; the test supplies its own. +void log_printf(sd_log_level_t level, const char*, int, const char*, ...) { + if (level == SD_LOG_WARN) { + ++warnings; + } else if (level == SD_LOG_ERROR) { + ++errors; + } +} + +static int failures = 0; +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + printf("FAIL: %s\n", msg); \ + failures++; \ + } else { \ + printf("ok: %s\n", msg); \ + } \ + } while (0) + +static constexpr size_t kFileSize = 1 << 20; + +static std::string content(uint8_t seed) { + std::string data(kFileSize, '\0'); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = static_cast((i * 31 + seed) & 0xff); + } + return data; +} + +static void write_file(const fs::path& path, const std::string& data) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + out.write(data.data(), static_cast(data.size())); +} + +// Number of descriptors of this process that refer to path; -1 where /proc is unavailable. +static int open_descriptors(const fs::path& path) { + std::error_code error; + if (!fs::exists("/proc/self/fd", error)) { + return -1; + } + const fs::path target = fs::canonical(path, error); + int count = 0; + for (const auto& entry : fs::directory_iterator("/proc/self/fd", error)) { + std::error_code link_error; + if (fs::read_symlink(entry.path(), link_error) == target) { + ++count; + } + } + return count; +} + +// True when the stream, positioned at offset, yields the bytes the file holds there. +static bool reads_expected(std::ifstream& stream, const std::string& expected, size_t offset, size_t length) { + std::string buffer(length, '\0'); + stream.seekg(static_cast(offset)); + stream.read(&buffer[0], static_cast(length)); + return stream && buffer.compare(0, length, expected, offset, length) == 0; +} + +int main() { + const fs::path dir = fs::temp_directory_path() / ("file_handle_pool_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(dir); + const std::string file_a = (dir / "a.bin").string(); + const std::string file_b = (dir / "b.bin").string(); + const std::string data_a = content(7); + const std::string data_b = content(99); + write_file(file_a, data_a); + write_file(file_b, data_b); + const bool have_proc = open_descriptors(file_a) >= 0; + + { + sd::FileHandlePool pool; + { + auto lease = pool.acquire(file_a); + CHECK(static_cast(lease), "opens an existing file"); + CHECK(reads_expected(lease.stream(), data_a, 1000, 64), "reads the right bytes"); + } + CHECK(pool.opened_total() == 1 && pool.open_count() == 1, "the stream stays open after the lease ends"); + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_a, 500000, 128), "reused stream reads the right bytes"); + } + CHECK(pool.opened_total() == 1 && pool.reused_total() == 1, "second acquisition reuses the stream"); + if (have_proc) { + CHECK(open_descriptors(file_a) == 1, "one descriptor in use after two acquisitions"); + } + + // A read past the end leaves the stream failed: it must not be handed out again. + { + auto lease = pool.acquire(file_a); + lease.stream().seekg(static_cast(kFileSize - 4)); + char buffer[64]; + lease.stream().read(buffer, sizeof(buffer)); + CHECK(!lease.stream(), "reading past the end fails"); + } + CHECK(pool.open_count() == 0, "a failed stream is closed, not pooled"); + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_a, 0, 16), "next acquisition opens a healthy stream"); + } + + // Reaching exactly the end of the file is not an error. + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_a, kFileSize - 16, 16), "reads the last bytes"); + } + CHECK(pool.open_count() == 1, "a stream that read up to the end is still pooled"); + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_a, 4096, 16), "pooled stream works after reading the end"); + } + + { + auto lease = pool.acquire(file_a); + lease.discard(); + CHECK(!lease, "a discarded lease is empty"); + } + CHECK(pool.open_count() == 0, "discard closes the stream"); + if (have_proc) { + CHECK(open_descriptors(file_a) == 0, "no descriptor left after discard"); + } + + { + auto first = pool.acquire(file_a); + } + const size_t opened_before = pool.opened_total(); + { + auto lease = pool.acquire(file_a, true); + CHECK(static_cast(lease), "fresh acquisition succeeds"); + } + CHECK(pool.opened_total() == opened_before + 1 && pool.open_count() == 1, "fresh acquisition replaces the idle stream"); + + // The file changes while its handle sits idle. + const auto old_time = fs::last_write_time(file_a); + write_file(file_a, data_b); + fs::last_write_time(file_a, old_time + std::chrono::seconds(5)); + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_b, 2000, 64), "a changed file is read from a new stream"); + } + CHECK(pool.open_count() == 1, "the stale stream was closed"); + if (have_proc) { + CHECK(open_descriptors(file_a) == 1, "only the new descriptor remains"); + } + write_file(file_a, data_a); + fs::last_write_time(file_a, old_time); + pool.close_idle(); + +#ifndef _WIN32 + // A file replaced by rename: the idle stream still points at the old content. + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_a, 10, 32), "reads before the replacement"); + } + write_file(dir / "replacement.bin", data_b); + fs::rename(dir / "replacement.bin", file_a); + { + auto lease = pool.acquire(file_a); + CHECK(reads_expected(lease.stream(), data_b, 10, 32), "a replaced file is read from a new stream"); + } + write_file(file_a, data_a); + pool.close_idle(); +#endif + } + + { + // Missing files fail fast: ENOENT is not retried. + sd::FileHandlePool pool; + const int warnings_before = warnings; + const int errors_before = errors; + const auto start = std::chrono::steady_clock::now(); + auto lease = pool.acquire((dir / "missing.bin").string()); + const auto elapsed = std::chrono::steady_clock::now() - start; + CHECK(!lease, "a missing file gives an empty lease"); + CHECK(elapsed < std::chrono::milliseconds(150), "a missing file is not retried"); + CHECK(warnings - warnings_before == 1 && errors - errors_before == 1, "the failure is logged once"); + CHECK(pool.open_count() == 0, "nothing is counted for a failed open"); + } + + { + sd::FileHandlePool pool; + pool.set_max_idle(4); + { + std::vector leases; + for (int i = 0; i < 6; ++i) { + leases.push_back(pool.acquire(file_a)); + } + CHECK(pool.open_count() == 6 && pool.opened_total() == 6, "concurrent leases get separate streams"); + for (auto& lease : leases) { + CHECK(reads_expected(lease.stream(), data_a, 777, 32), "each stream reads independently"); + } + } + CHECK(pool.open_count() == 4, "no more than the limit is kept idle"); + pool.set_max_idle(2); + CHECK(pool.open_count() == 2, "lowering the limit closes the extra streams"); + if (have_proc) { + CHECK(open_descriptors(file_a) == 2, "descriptors follow the limit"); + } + { + auto on_b = pool.acquire(file_b); + } + CHECK(pool.open_count() == 3, "limits apply per file"); + pool.close_idle(file_a); + CHECK(pool.open_count() == 1, "closing the idle streams of one file leaves the others"); + { + auto lease = pool.acquire(file_b); + pool.close_idle(); + CHECK(pool.open_count() == 1, "a leased stream survives close_idle"); + } + CHECK(pool.open_count() == 0, "a stream leased during close_idle is closed when returned"); + + sd::FileHandlePool::Lease a = pool.acquire(file_a); + sd::FileHandlePool::Lease b = std::move(a); + CHECK(!a && b, "moving a lease empties the source"); + b = pool.acquire(file_b); + CHECK(pool.open_count() == 2, "assigning over a lease returns its stream to the pool"); + sd::FileHandlePool::Lease c; + c = std::move(b); + CHECK(!b && c && reads_expected(c.stream(), data_b, 5, 8), "move assignment transfers the stream"); + } + + { + sd::FileHandlePool pool; + sd::FileHandlePool copy = pool; + { + auto lease = pool.acquire(file_a); + } + { + auto lease = copy.acquire(file_a); + } + CHECK(pool.opened_total() == 1 && copy.reused_total() == 1, "copies of a pool share their streams"); + sd::FileHandlePool moved = std::move(pool); + { + auto lease = pool.acquire(file_a); + CHECK(static_cast(lease), "a pool that was moved from is still usable"); + } + (void)moved; + } + + { + sd::FileHandlePool::Lease survivor; + { + sd::FileHandlePool pool; + survivor = pool.acquire(file_a); + } + CHECK(reads_expected(survivor.stream(), data_a, 123, 45), "a lease can outlive its pool object"); + } + + { + // Many threads sharing one pool, some of them discarding, refreshing or closing. + sd::FileHandlePool pool; + pool.set_max_idle(8); + std::atomic bad{0}; + std::vector threads; + for (int t = 0; t < 8; ++t) { + threads.emplace_back([&, t]() { + std::mt19937 random(1234 + t); + for (int i = 0; i < 300; ++i) { + const int roll = static_cast(random() % 100); + const bool other = random() % 2 == 0; + auto lease = pool.acquire(other ? file_b : file_a, roll < 5); + if (!lease) { + ++bad; + continue; + } + const size_t offset = random() % (kFileSize - 256); + if (!reads_expected(lease.stream(), other ? data_b : data_a, offset, 256)) { + ++bad; + } + if (roll >= 90) { + lease.discard(); + } else if (roll == 50) { + pool.close_idle(); + } + } + }); + } + for (auto& thread : threads) { + thread.join(); + } + CHECK(bad == 0, "concurrent use reads correct data every time"); + if (have_proc) { + CHECK(static_cast(pool.open_count()) == open_descriptors(file_a) + open_descriptors(file_b), + "the pool's count matches the open descriptors"); + } + pool.close_idle(); + CHECK(pool.open_count() == 0, "everything is closed in the end"); + if (have_proc) { + CHECK(open_descriptors(file_a) + open_descriptors(file_b) == 0, "no descriptor leaks"); + } + } + + std::error_code ignored; + fs::remove_all(dir, ignored); + printf("%s\n", failures == 0 ? "ALL OK" : "FAILURES"); + return failures == 0 ? 0 : 1; +}