From 967d461c266d217e421010ca955d8a05e5bc080f Mon Sep 17 00:00:00 2001 From: Nitesh Date: Mon, 30 Nov 2026 23:45:46 +0545 Subject: [PATCH] perf(fs): count folder sizes with one stat per entry on several threads --- docs/design/architecture.md | 2 +- src/fs/folder_totals.h | 3 +- src/fs/folder_totals_walk.cpp | 510 ++++++++++++++++++++++----- src/fs/folder_totals_walk.h | 2 + src/operations/transfer_estimate.cpp | 3 +- tests/folder_totals_test.cpp | 52 +++ tools/bench/folder_totals_bench.cpp | 61 ++++ tools/bench/meson.build | 5 + 8 files changed, 539 insertions(+), 99 deletions(-) create mode 100644 tools/bench/folder_totals_bench.cpp diff --git a/docs/design/architecture.md b/docs/design/architecture.md index 79ebb18f..add3dd2c 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -147,7 +147,7 @@ After the selected item is deleted, selection moves to the next remaining item i Changing the sort field, direction, Folders First or Hidden Last scrolls to the beginning of the new order and keeps the selection, whether the change comes from list headings, the Sort menu or Settings. Hidden extra columns are not queried during ordinary large-folder browsing; enabling one loads its visible rows. In large folders names can appear before details: Reading… marks a pending value and Unknown a value that was unavailable after querying. Sorting by metadata or selecting many items can require facts from the rest of the folder, and file actions wait for the facts they need. Folder sizes never show Reading…. -Recursive folder sizes in the Size column are computed in the background for visible rows of local filesystems only, never for network locations. A size covers the folder's own filesystem; a mount point inside it is not traversed and the cell shows the ≥ marker, which also marks any partial result. Cached sizes refresh when the listing reports changes. Missing provider metadata stays unavailable instead of becoming a made-up value. +Recursive folder sizes in the Size column are computed in the background for visible rows of local filesystems only, never for network locations. A size covers the folder's own filesystem; a mount point inside it is not traversed and the cell shows the ≥ marker, which also marks any partial result. Cached sizes refresh when the listing reports changes. A walk reads each entry with a single `fstatat`, and once a tree passes a few thousand items it lists folders on up to one thread per physical core, like [diskus](https://github.com/sharkdp/diskus); more threads mostly add kernel lock contention. Missing provider metadata stays unavailable instead of becoming a made-up value. Per-folder view and sort settings are keyed by location, so a renamed or moved folder starts from the defaults. Columns is a window-wide default mode: folders' own view choices do not apply while it is on, but sorting a column there still changes only that column's folder. File picker windows ignore per-folder settings. Action messages in the status bar clear after five seconds or at the next action. Link icons and custom folder icon changes show after the next listing, such as Refresh. In Miller columns the application keeps a bounded set of live columns while deep navigation remains possible. diff --git a/src/fs/folder_totals.h b/src/fs/folder_totals.h index 81e4246b..79838134 100644 --- a/src/fs/folder_totals.h +++ b/src/fs/folder_totals.h @@ -18,7 +18,8 @@ namespace luciole { } }; // Read-only native traversal started by the preview pane, the Properties dialog and the list view's bound rows. - // One worker per instance, bounded progress delivery, no link following or content reads. + // One walk per instance, bounded progress delivery, no link following or content reads. A large tree is listed + // on up to one thread per physical core. // An injected network-filesystem check refuses the whole start before any traversal. // A new start supersedes a running traversal; the superseded result never publishes. class FolderTotalsService { diff --git a/src/fs/folder_totals_walk.cpp b/src/fs/folder_totals_walk.cpp index ba2f8364..b5c90c47 100644 --- a/src/fs/folder_totals_walk.cpp +++ b/src/fs/folder_totals_walk.cpp @@ -6,18 +6,36 @@ #include "i18n/i18n.h" #include +#include #include +#include #include +#include #include #include -#include -#include +#include +#include +#include +#include +#include #include +#include +#include namespace { - struct CloseDirectory { - void operator()(DIR* value) const { ::closedir(value); } - }; + // Callers see one snapshot per this many items, from whichever thread counted them. + constexpr std::uint64_t kProgressInterval = 64; + // Small folders finish before a helper thread could start, so only trees past this size are shared. + constexpr std::size_t kParallelAfterItems = 4096; + // Each queued folder pins its parent's descriptor; past this a thread walks the next folder itself, depth first. + constexpr std::size_t kMaxQueuedFolders = 256; + // Warm trees are bound by kernel CPU time. One thread per physical core (half the SMT siblings) keeps the total + // CPU time of a single-threaded walk; more threads mostly add lock contention in the kernel. + constexpr unsigned kMaxThreads = 8; + unsigned walkThreads() { return std::clamp(std::thread::hardware_concurrency() / 2, 1U, kMaxThreads); } + // Same size glibc's readdir() uses, but reused per depth instead of allocated per folder. + constexpr std::size_t kListingBufferBytes = 32 * 1024; + bool sameStamp(const struct stat& a, const struct stat& b) { return luciole::sameIdentity(a, b) && a.st_mtim.tv_sec == b.st_mtim.tv_sec @@ -26,46 +44,118 @@ namespace { && a.st_ctim.tv_nsec == b.st_ctim.tv_nsec && a.st_size == b.st_size; } + // Native path of `name` inside `parent`, the same text Location::child() would resolve to. + void appendChild(std::string& path, std::string_view name) { + if (!path.ends_with('/')) { + path += '/'; + } + path += name; + } + struct DirectoryKeyHash { + std::size_t operator()(const std::pair& key) const noexcept { + return std::hash{}(key.second ^ (static_cast(key.first) << 32U)); + } + }; + // A folder held open while it or any of its subfolders is being listed. Renaming or replacing a subfolder + // changes this folder's timestamps, so one check after the last subfolder finishes covers them all. + class OpenFolder { + public: + // A null `changes` only pins the descriptor, for a root that its caller checks by path instead. + OpenFolder(luciole::Fd fd, const struct stat& baseline, std::atomic* changes) + : m_fd(std::move(fd)), m_baseline(baseline), m_changes(changes) {} + OpenFolder(const OpenFolder&) = delete; + OpenFolder& operator=(const OpenFolder&) = delete; + ~OpenFolder() { + struct stat current{}; + if (m_changes && (::fstat(m_fd.get(), ¤t) != 0 || !sameStamp(m_baseline, current))) { + m_changes->fetch_add(1, std::memory_order_relaxed); + } + } + int get() const { return m_fd.get(); } + + private: + luciole::Fd m_fd; + struct stat m_baseline{}; + std::atomic* m_changes; + }; + // A folder still to be listed: `name` inside the pinned `parent`, opened only by the thread that lists it. + struct FolderTask { + std::shared_ptr parent; + std::string name; + struct stat baseline{}; + std::string path; + std::size_t depth = 0; + }; + // Counts one thread gathered since it last reported; merged into the shared snapshot under the report lock. + struct Tally { + std::uint64_t bytes = 0, files = 0, folders = 0, links = 0, other = 0; + std::uint64_t unavailable = 0, unsupported = 0, changed = 0, sinceReport = 0; + bool overflow = false; + std::string error; + }; + // One listing buffer per recursion depth, since a folder walked in place interrupts its parent's listing. + class ListingBuffers { + public: + std::byte* at(std::size_t level) { + while (m_buffers.size() <= level) { + m_buffers.push_back(std::make_unique(kListingBufferBytes)); + } + return m_buffers[level].get(); + } + + private: + std::vector> m_buffers; + }; + struct Worker { + Tally tally; + ListingBuffers buffers; + std::size_t level = 0; + }; + + // Every entry costs one fstatat(); folders are additionally opened once and listed with getdents64(). Folders + // past the first few thousand items go to a shared stack that helper threads drain, like diskus and gdu. Paths + // are plain strings built only while another selected root can lie below, so a single-root walk never names + // entries. class Walker { public: Walker( std::vector roots, const luciole::CancelToken& token, const std::function& progress, luciole::FolderTotalsLimits limits ) - : m_roots(std::move(roots)), m_token(token), m_progress(progress), m_limits(limits) { + : m_roots(std::move(roots)), m_token(token), m_progress(progress), m_limits(limits), + m_maxHelpers(limits.parallel ? walkThreads() - 1 : 0) { std::ranges::stable_sort(m_roots, {}, [](const auto& entry) { return entry.location().uri().size(); }); for (const auto& root : m_roots) { - m_selected.emplace(root.location().uri(), &root); + if (const auto path = root.location().nativePath()) { + m_selected.emplace(*path, &root); + } } m_result.phase = luciole::FolderTotalsPhase::Running; } + Walker(const Walker&) = delete; + Walker& operator=(const Walker&) = delete; + // An escaping exception still stops and joins the helpers before the state they use goes away. + ~Walker() { + m_failed.store(true); + stopHelpers(); + } luciole::FolderTotalsSnapshot run() { m_progress(m_result); + Worker worker; for (const auto& root : m_roots) { if (stopped()) { break; } - const auto location = root.location(); - if (m_seenRoots.contains(location.uri())) { - continue; - } - try { - if (!location.isNative() || location.isTrash()) { - ++m_result.unsupported; - continue; - } - const auto fd = luciole::checkedFd(::open(location.nativePath()->c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)); - const auto value = luciole::statFd(fd.get()); - m_scopeDevice = value.st_dev; - visit(fd.get(), value, location, 0); - struct stat current{}; - if (::lstat(location.nativePath()->c_str(), ¤t) != 0 || !sameStamp(value, current)) { - ++m_result.changed; - } - } catch (const luciole::FileErrorException& error) { - failed(error.error()); - } + walkRoot(root, worker); + report(worker.tally); + } + stopHelpers(); + if (m_failure) { + std::rethrow_exception(m_failure); } + const std::scoped_lock lock(m_reportMutex); + m_result.limited |= m_limited.load(); + m_result.changed += m_lateChanges.exchange(0); m_result.phase = m_token.cancelled() ? luciole::FolderTotalsPhase::Cancelled : luciole::FolderTotalsPhase::Complete; m_progress(m_result); @@ -73,27 +163,99 @@ namespace { } private: + void walkRoot(const luciole::DirectoryEntry& root, Worker& worker) { + const auto location = root.location(); + try { + if (!location.isNative() || location.isTrash()) { + ++worker.tally.unsupported; + return; + } + auto path = *location.nativePath(); + if (seenRoot(path)) { + return; + } + auto pinned = luciole::checkedFd(::open(path.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)); + const auto value = luciole::statFd(pinned.get()); + auto fd = std::make_shared(std::move(pinned), value, nullptr); + m_scopeDevice = value.st_dev; + // Helpers only read these per-root values while this root's stack drains below. + visit(worker, fd, ".", value, path, 0); + fd.reset(); + drain(worker); + struct stat current{}; + if (::lstat(path.c_str(), ¤t) != 0 || !sameStamp(value, current)) { + ++worker.tally.changed; + } + } catch (const luciole::FileErrorException& error) { + failed(worker.tally, error.error()); + } + } + bool seenRoot(const std::string& path) { + const std::scoped_lock lock(m_rootsMutex); + return m_seenRoots.contains(path); + } bool stopped() { - if (m_token.cancelled()) { + if (m_token.cancelled() || m_failed.load(std::memory_order_relaxed)) { return true; } - if (m_items >= m_limits.items || (m_limits.deadline && std::chrono::steady_clock::now() >= *m_limits.deadline)) { - m_result.limited = true; + if (m_items.load(std::memory_order_relaxed) >= m_limits.items + || (m_limits.deadline && std::chrono::steady_clock::now() >= *m_limits.deadline)) { + m_limited.store(true, std::memory_order_relaxed); + return true; + } + return false; + } + // Claims one item of the limit, so parallel threads together never count more than it allows. + bool reserveItem() { + if (m_items.fetch_add(1, std::memory_order_relaxed) < m_limits.items) { return true; } + m_limited.store(true, std::memory_order_relaxed); return false; } - void failed(const luciole::FileError& error) { + static void failed(Tally& tally, const luciole::FileError& error) { if (error.kind == luciole::FileErrorKind::Cancelled) { return; } if (error.kind == luciole::FileErrorKind::Changed) { - ++m_result.changed; + ++tally.changed; } else { - ++m_result.unavailable; + ++tally.unavailable; } // Retain only one bounded error regardless of the tree size. - m_result.error = error.message.substr(0, 256); + tally.error = error.message.substr(0, 256); + } + static void addBytes(std::uint64_t& total, std::uint64_t delta, bool& overflow) { + if (delta > std::numeric_limits::max() - total) { + overflow = true; + } else { + total += delta; + } + } + void report(Tally& tally) { + const std::scoped_lock lock(m_reportMutex); + addBytes(m_result.bytes, tally.bytes, m_result.overflow); + m_result.files += tally.files; + m_result.folders += tally.folders; + m_result.links += tally.links; + m_result.other += tally.other; + m_result.unavailable += tally.unavailable; + m_result.unsupported += tally.unsupported; + m_result.changed += tally.changed + m_lateChanges.exchange(0, std::memory_order_relaxed); + m_result.overflow |= tally.overflow; + m_result.limited |= m_limited.load(std::memory_order_relaxed); + if (!tally.error.empty()) { + m_result.error = std::move(tally.error); + } + tally = {}; + // Inside the lock so snapshots stay monotonic and callers never see two threads at once; a paused + // transfer parks here and every other thread waits behind it. + m_progress(m_result); + } + void counted(Tally& tally) { + if (++tally.sinceReport >= kProgressInterval) { + report(tally); + } } void validateRoot(const luciole::DirectoryEntry& root, const struct stat& value) const { const auto location = root.location(); @@ -118,7 +280,35 @@ namespace { ); } } - void visit(int fd, const struct stat& value, const luciole::Location& location, std::size_t depth) { + // Only the first root needs no path below it: every other selected root is longer, so it can only be nested. + bool tracksPaths(std::size_t depth) const { return depth == 0 || m_selected.size() > 1; } + // Returns false when `path` is a selected root another walk already counted. + bool claimSelected(const std::string& path, const struct stat& value) { + const luciole::DirectoryEntry* root = nullptr; + { + const std::scoped_lock lock(m_rootsMutex); + const auto found = m_selected.find(path); + if (found == m_selected.end()) { + return true; + } + if (!m_seenRoots.insert(path).second) { + return false; + } + root = found->second; + } + validateRoot(*root, value); + return true; + } + bool firstVisit(const struct stat& value) { + const std::scoped_lock lock(m_directoriesMutex); + return m_directories.emplace(value.st_dev, value.st_ino).second; + } + // `value` describes `name` inside `parent`; a folder is opened through that pair only when it is listed. + void visit( + Worker& worker, const std::shared_ptr& parent, std::string_view name, + const struct stat& value, const std::string& path, std::size_t depth + ) { + auto& tally = worker.tally; if (stopped()) { return; } @@ -127,117 +317,245 @@ namespace { // before the selected-roots bookkeeping below, so an explicitly selected nested mount is still // fully walked when its own depth-0 root is processed. if (depth != 0 && S_ISDIR(value.st_mode) && value.st_dev != m_rootDev) { - ++m_items; - ++m_result.folders; - if (m_items % 64 == 0) { - m_progress(m_result); + if (reserveItem()) { + ++tally.folders; + counted(tally); } return; } - if (const auto found = m_selected.find(location.uri()); found != m_selected.end()) { - if (!m_seenRoots.insert(location.uri()).second) { - return; - } - validateRoot(*found->second, value); + if (tracksPaths(depth) && !claimSelected(path, value)) { + return; } if (m_limits.sameDevice && S_ISDIR(value.st_mode) && value.st_dev != m_scopeDevice) { - ++m_result.unsupported; // Nested filesystem: its contents are never traversed or counted. + ++tally.unsupported; // Nested filesystem: its contents are never traversed or counted. + return; + } + if (!reserveItem()) { return; } - ++m_items; if (S_ISDIR(value.st_mode)) { if (depth == 0) { m_rootDev = value.st_dev; } - if (!m_directories.emplace(value.st_dev, value.st_ino).second) { - ++m_result.unavailable; // Directory alias/cycle: no duplicate subtree totals. + if (!firstVisit(value)) { + ++tally.unavailable; // Directory alias/cycle: no duplicate subtree totals. } else { - m_result.folders += depth != 0; // Contents exclude the selected root folders. + tally.folders += depth != 0; // Contents exclude the selected root folders. if (depth >= m_limits.depth) { - m_result.limited = true; + m_limited.store(true, std::memory_order_relaxed); } else { - children(fd, value, location, depth); + schedule(worker, FolderTask{parent, std::string(name), value, path, depth}); } } } else { if (S_ISLNK(value.st_mode)) { - ++m_result.links; + ++tally.links; } else if (S_ISREG(value.st_mode)) { - ++m_result.files; + ++tally.files; } else { - ++m_result.other; + ++tally.other; } // Special files have no meaningful content length and are never opened; link target lengths count only // when the caller asks, since a transfer recreates a link without writing them. if (S_ISREG(value.st_mode) || (S_ISLNK(value.st_mode) && m_limits.linkBytes)) { if (value.st_size < 0) { - ++m_result.unavailable; - } else if ( - static_cast(value.st_size) > std::numeric_limits::max() - m_result.bytes - ) { - m_result.overflow = true; + ++tally.unavailable; } else { - m_result.bytes += static_cast(value.st_size); + addBytes(tally.bytes, static_cast(value.st_size), tally.overflow); } } } - if (m_items % 64 == 0) { - m_progress(m_result); + counted(tally); + } + // Shares the folder once the tree has proven large, otherwise lists it in place. + void schedule(Worker& worker, FolderTask task) { + if (task.depth != 0 && m_items.load(std::memory_order_relaxed) >= kParallelAfterItems) { + std::unique_lock lock(m_queueMutex); + if (m_queue.size() < kMaxQueuedFolders) { + m_queue.push_back(std::move(task)); + addHelper(lock); + lock.unlock(); + m_queueChanged.notify_one(); + return; + } + } + list(worker, task); + } + void addHelper(const std::unique_lock&) { + if (m_finished || m_helpers.size() >= m_maxHelpers || m_queue.size() <= m_idleHelpers) { + return; + } + try { + m_helpers.emplace_back([this] { help(); }); + } catch (const std::system_error&) { + m_maxHelpers = m_helpers.size(); // No more threads available: the existing ones finish the walk. + } + } + void list(Worker& worker, const FolderTask& task) { + try { + listChildren(worker, task); + } catch (const luciole::FileErrorException& error) { + failed(worker.tally, error.error()); } } - void children(int fd, const struct stat& baseline, const luciole::Location& location, std::size_t depth) { - const int descriptor = ::openat(fd, ".", O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); - if (descriptor < 0) { - luciole::throwErrno(errno); + void listChildren(Worker& worker, const FolderTask& task) { + if (stopped()) { + return; } - const std::unique_ptr directory(::fdopendir(descriptor)); - if (!directory) { - const int code = errno; - ::close(descriptor); - luciole::throwErrno(code); + auto opened = luciole::checkedFd( + ::openat(task.parent->get(), task.name.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + ); + // The folder was stat'ed by name before opening; refuse to count whatever replaced it in between, which + // could even be another filesystem. + if (!luciole::sameIdentity(task.baseline, luciole::statFd(opened.get()))) { + ++worker.tally.changed; + return; } + const auto folder = std::make_shared(std::move(opened), task.baseline, &m_lateChanges); + const bool named = tracksPaths(task.depth + 1); + std::string childPath; + std::byte* buffer = worker.buffers.at(worker.level); + ++worker.level; + const struct LevelGuard { + std::size_t& level; + ~LevelGuard() { --level; } + } guard{worker.level}; while (!stopped()) { - errno = 0; - const auto* item = ::readdir(directory.get()); - if (!item) { - if (errno) { - failed(luciole::errnoError(errno)); + const auto filled = ::getdents64(folder->get(), buffer, kListingBufferBytes); + if (filled <= 0) { + if (filled < 0) { + failed(worker.tally, luciole::errnoError(errno)); } break; } - const std::string name(item->d_name); - if (name == "." || name == "..") { + for (ssize_t offset = 0; offset < filled && !stopped();) { + const auto* item = reinterpret_cast(buffer + offset); + offset += item->d_reclen; + const std::string_view childName(item->d_name); + if (childName == "." || childName == "..") { + continue; + } + struct stat value{}; + if (::fstatat(folder->get(), item->d_name, &value, AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT) != 0) { + failed(worker.tally, luciole::errnoError(errno)); + continue; + } + if (named) { + childPath = task.path; + appendChild(childPath, childName); + } + try { + visit(worker, folder, childName, value, childPath, task.depth + 1); + } catch (const luciole::FileErrorException& error) { + failed(worker.tally, error.error()); + } + } + } + } + // Lists queued folders until none are left and no thread can queue more. + void drain(Worker& worker) { + std::unique_lock lock(m_queueMutex); + while (true) { + if (m_queue.empty()) { + if (m_active == 0) { + m_queueChanged.notify_all(); + return; + } + ++m_idleHelpers; + m_queueChanged.wait(lock, [this] { return !m_queue.empty() || m_active == 0; }); + --m_idleHelpers; continue; } - try { - const auto child = - luciole::checkedFd(::openat(::dirfd(directory.get()), name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)); - const auto value = luciole::statFd(child.get()); - visit(child.get(), value, location.child(name), depth + 1); - struct stat current{}; - if (::fstatat(::dirfd(directory.get()), name.c_str(), ¤t, AT_SYMLINK_NOFOLLOW) != 0 - || !sameStamp(value, current)) { - ++m_result.changed; + auto task = std::move(m_queue.back()); + m_queue.pop_back(); + ++m_active; + lock.unlock(); + list(worker, task); + lock.lock(); + --m_active; + } + } + // A helper drains each root's stack and then waits for the next root, until the walk ends. + void help() { + Worker worker; + try { + std::unique_lock lock(m_queueMutex); + while (!m_finished) { + if (m_queue.empty()) { + ++m_idleHelpers; + m_queueChanged.wait(lock, [this] { return m_finished || !m_queue.empty(); }); + --m_idleHelpers; + continue; + } + auto task = std::move(m_queue.back()); + m_queue.pop_back(); + ++m_active; + lock.unlock(); + list(worker, task); + lock.lock(); + // Report before going idle: the walk may end as soon as no thread is active. + if (m_queue.empty()) { + lock.unlock(); + report(worker.tally); + lock.lock(); + } + if (--m_active == 0 && m_queue.empty()) { + m_queueChanged.notify_all(); } - } catch (const luciole::FileErrorException& error) { - failed(error.error()); } + } catch (...) { + // Anything but a file error is a bug or exhaustion; stop the walk and rethrow it on the caller's thread. + const std::scoped_lock lock(m_queueMutex); + if (!m_failure) { + m_failure = std::current_exception(); + } + m_failed.store(true); + --m_active; + m_queueChanged.notify_all(); } - if (!sameStamp(baseline, luciole::statFd(fd))) { - ++m_result.changed; + } + void stopHelpers() { + std::vector helpers; + { + const std::scoped_lock lock(m_queueMutex); + m_finished = true; + helpers = std::move(m_helpers); } + m_queueChanged.notify_all(); + // Joined outside the lock, which the finishing helpers still take. } + std::vector m_roots; const luciole::CancelToken& m_token; const std::function& m_progress; luciole::FolderTotalsLimits m_limits; - luciole::FolderTotalsSnapshot m_result; - std::size_t m_items = 0; dev_t m_rootDev = 0; - std::map m_selected; - std::set m_seenRoots; - std::set> m_directories; dev_t m_scopeDevice = 0; + std::atomic m_items = 0; + std::atomic m_limited = false; + std::atomic m_failed = false; + // Found by OpenFolder on whichever thread releases a folder last; declared before the queue that holds them. + std::atomic m_lateChanges = 0; + + std::mutex m_reportMutex; + luciole::FolderTotalsSnapshot m_result; + + std::mutex m_rootsMutex; + std::unordered_map m_selected; + std::unordered_set m_seenRoots; + + std::mutex m_directoriesMutex; + std::unordered_set, DirectoryKeyHash> m_directories; + + std::mutex m_queueMutex; + std::condition_variable m_queueChanged; + std::vector m_queue; + std::size_t m_active = 0, m_idleHelpers = 0; + bool m_finished = false; + std::exception_ptr m_failure; + std::size_t m_maxHelpers; + // Last member: joining on destruction happens before anything the helpers use is destroyed. + std::vector m_helpers; }; } // namespace diff --git a/src/fs/folder_totals_walk.h b/src/fs/folder_totals_walk.h index 3b1f43de..1dc154e1 100644 --- a/src/fs/folder_totals_walk.h +++ b/src/fs/folder_totals_walk.h @@ -15,6 +15,8 @@ namespace luciole { std::optional deadline = std::nullopt; // Adds link target lengths to `bytes`, as du does. bool linkBytes = true; + // Lists a large local tree on several threads; a network mount keeps one so the server sees no burst. + bool parallel = true; }; // Worker entry point. Progress is a bounded value, never a retained per-item result list. FolderTotalsSnapshot walkFolderTotals( diff --git a/src/operations/transfer_estimate.cpp b/src/operations/transfer_estimate.cpp index b1f4ac67..72d687ed 100644 --- a/src/operations/transfer_estimate.cpp +++ b/src/operations/transfer_estimate.cpp @@ -210,7 +210,8 @@ namespace { .depth = kMaxDepth, .deadline = isNetwork ? std::optional(probeStart + std::max(budget, std::chrono::milliseconds(0))) : std::nullopt, - .linkBytes = false} + .linkBytes = false, + .parallel = !isNetwork} ); const auto measured = fromWalk(walked, regularFilesOnly); estimate.bytes = measured.bytes; diff --git a/tests/folder_totals_test.cpp b/tests/folder_totals_test.cpp index 5c584541..d39f7d0d 100644 --- a/tests/folder_totals_test.cpp +++ b/tests/folder_totals_test.cpp @@ -120,6 +120,56 @@ namespace { fs::remove(tree); fs::rename(root / "held-tree", tree); } + // A subfolder renamed while it is listed changes its parent, which is checked after its last subfolder. + void nestedRename(const fs::path& root) { + const auto parent = root / "renamed" / "parent"; + fs::create_directories(parent / "inner"); + for (int i = 0; i < 1000; ++i) { + std::ofstream(parent / "inner" / std::to_string(i)) << 'x'; + } + bool moved = false; + const auto result = luciole::walkFolderTotals({entry(root / "renamed")}, {}, [&](const auto& progress) { + if (!moved && progress.files >= 64) { + moved = true; + fs::rename(parent / "inner", parent / "moved"); + } + }); + TEST_CHECK(moved && result.changed > 0 && result.partial() && result.files == 1000); + } + // Past the first few thousand items, folders are shared with helper threads; totals and the limit stay exact. + void parallelTree(const fs::path& root) { + const auto tree = root / "wide"; + constexpr int kFolders = 64; + constexpr int kFiles = 100; + for (int folder = 0; folder < kFolders; ++folder) { + const auto nested = tree / std::to_string(folder) / "inner"; + fs::create_directories(nested); + for (int file = 0; file < kFiles; ++file) { + std::ofstream(nested / std::to_string(file)) << std::string(file % 7, 'x'); + } + } + const auto source = entry(tree); + for (int run = 0; run < 5; ++run) { + std::uint64_t previous = 0; + bool monotonic = true; + const auto result = luciole::walkFolderTotals({source}, {}, [&](const auto& progress) { + monotonic = monotonic && progress.files >= previous; + previous = progress.files; + }); + TEST_CHECK(monotonic && result.phase == FolderTotalsPhase::Complete && !result.partial()); + // Each folder holds 14 cycles of 0..6 bytes (294) plus files 98 and 99 (0 and 1 bytes). + TEST_CHECK(result.files == 6400 && result.folders == 128 && result.bytes == 64 * 295); + } + const auto limited = walk({source}, {.items = 5000}); + TEST_CHECK(limited.limited && limited.files + limited.folders == 4999); // The root takes the first item. + luciole::CancelToken cancel; + const auto stopped = luciole::walkFolderTotals({source}, cancel, [&](const auto& progress) { + if (progress.files >= 4500) { + cancel.cancel(); + } + }); + TEST_CHECK(stopped.phase == FolderTotalsPhase::Cancelled && stopped.partial() && stopped.files < 6400); + } void unreadable(const fs::path& root) { const auto path = root / "unreadable"; fs::create_directory(path); @@ -250,6 +300,8 @@ int main() { const fs::path root(temporary.get()); basic(root); progressAndRaces(root); + nestedRename(root); + parallelTree(root); unreadable(root); lifecycle(root); serviceNetworkRefusal(root); diff --git a/tools/bench/folder_totals_bench.cpp b/tools/bench/folder_totals_bench.cpp new file mode 100644 index 00000000..6ad739ba --- /dev/null +++ b/tools/bench/folder_totals_bench.cpp @@ -0,0 +1,61 @@ +// Headless folder totals benchmark: one walkFolderTotals() call per measured run over a native folder. +// Prints one JSON object per measured run on stdout. Usage: luciole-folder-totals-bench [runs] + +#include "fs/file_query.h" +#include "fs/folder_totals_walk.h" + +#include +#include +#include +#include +#include +#include + +namespace { + using Clock = std::chrono::steady_clock; + + double processCpuMs() { + timespec value{}; + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &value); + return (static_cast(value.tv_sec) * 1e3) + (static_cast(value.tv_nsec) / 1e6); + } + + luciole::DirectoryEntry rootEntry(const char* path) { + luciole::DirectoryEntry entry{ + .place = luciole::Location::fromPath(path), .name = {}, .size = {}, .modifiedSeconds = {} + }; + const auto facts = luciole::readFileDetails(entry.location(), {}); + entry.type = facts.type; + entry.setIdentity(facts.identity); + return entry; + } +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::println(stderr, "usage: {} [runs]", argv[0]); + return EXIT_FAILURE; + } + int runs = 3; + if (argc > 2) { + const std::string_view text(argv[2]); + if (std::from_chars(text.data(), text.data() + text.size(), runs).ec != std::errc{} || runs < 1) { + std::println(stderr, "runs must be a positive number"); + return EXIT_FAILURE; + } + } + const auto root = rootEntry(argv[1]); + const luciole::FolderTotalsLimits unbounded{.items = static_cast(-1)}; + for (int run = 0; run < runs; ++run) { + const double cpuStart = processCpuMs(); + const auto start = Clock::now(); + const auto totals = luciole::walkFolderTotals({root}, {}, [](const auto&) {}, unbounded); + const double wallMs = std::chrono::duration(Clock::now() - start).count(); + std::println( + R"({{"run":{},"wall_ms":{:.1f},"cpu_ms":{:.1f},"bytes":{},"files":{},"folders":{},"links":{},"other":{},)" + R"("unavailable":{},"changed":{},"partial":{}}})", + run, wallMs, processCpuMs() - cpuStart, totals.bytes, totals.files, totals.folders, totals.links, totals.other, + totals.unavailable, totals.changed, totals.partial() + ); + } +} diff --git a/tools/bench/meson.build b/tools/bench/meson.build index d5166c07..23f789c0 100644 --- a/tools/bench/meson.build +++ b/tools/bench/meson.build @@ -9,3 +9,8 @@ executable('luciole-transfer-bench', include_directories: src_inc, dependencies: [operations_dep, event_loop_dep, noctalia_ui_dep, gio], ) +executable('luciole-folder-totals-bench', + 'folder_totals_bench.cpp', + include_directories: src_inc, + dependencies: [fs_dep, gio], +)