This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 3b87b37d0af [fix](spill) Move physical spill cleanup off query
teardown (#71234)
3b87b37d0af is described below
commit 3b87b37d0afd7b095041b981a48e1eb64d6233da
Author: Jerry Hu <[email protected]>
AuthorDate: Thu Dec 3 18:07:13 2026 +0800
[fix](spill) Move physical spill cleanup off query teardown (#71234)
### Background
Spill files can live on local disks or in object-storage vaults. Query
teardown currently attempts filesystem deletion before handing a failed
deletion to the spill manager.
### What problem does this PR solve?
Issue Number: None
Related PR: #70474 (original combined patch), #71048 (preparatory
refactor)
PR Type: Bugfix
Problem Summary:
Physical deletion and remote delete reconciliation can stall query
teardown. Queue local and remote cleanup instead, and ensure that local
files left at shutdown can be isolated and collected on the next start.
### Details
- **Change map:** Production +127/-165, tests +344/-20. BE production
code and targeted BE tests only. Startup/metrics and the physical
deletion queue are the two parts of this fix.
- **Frequency:** Query or spill-file teardown during slow local or
remote deletion; shutdown can leave new cleanup work after the GC loop
stops.
- **Root cause:** Teardown called the filesystem directly; moving all
deletes to the old queue would also make normal producers repeatedly
scan the backlog under the shared mutex.
- **Why existing tests missed it:** They generally expected synchronous
deletion or only put failed deletes in the queue.
- **Fix:** Enqueue without scanning; drain and coalesce
duplicate/ancestor requests outside the queue lock, preserving the
filesystem snapshot, reservations, layouts and per-file log context.
Quarantine stale local roots at startup and reject a failed rename. Own
the metrics entity even when initialization fails.
- **Other paths and branches:** Keep external directory leases, the
retry time slice and synchronous writer teardown. No upload admission,
remote config, FE, or protocol change.
### Testing
- Clang-format 16, build hygiene and `git diff --check` passed.
- Clang `-fsyntax-only` passed for 7/7 changed BE translation units with
code or test edits using flags from this worktree's ASAN compilation
database. This is not link or runtime validation.
- ASAN BE UT is not yet complete; Ninja is building the test binary and
cases have not run. The first attempt stopped at CMake because the local
install lacked libbson/libmongoc 2.0 headers; the missing dependency was
built locally and the command retried. Command: `ENABLE_PCH=off
USE_LIBCPP=OFF BUILD_TYPE_UT=ASAN ./run-be-ut.sh --run
--filter=SpillGcQueueTest.*:SpillFileTest.*:SpillFileManagerTest.*:SpillFileS3Test.*:SpillRepartitionerTest.*:SpillSortSourceOperatorTest.*
-j20`.
- No live-object-storage or SQL regression result is claimed here.
### Notes for Reviewers
Start with `SpillFile::gc()` and
`SpillFileManager::_coalesce_pending_directories()`. A queued item keeps
its charged bytes until deletion succeeds; the retained-object metric
can separately reconcile a partial remote delete. Shutdown does not
start another pass, but joins the one already running. A pending remote
object can survive restart, so the bucket's existing spill lifecycle
rule remains necessary.
### Release note
Physical spill deletion and its retries no longer run on query teardown
threads. Unfinished uploads may still delay writer teardown, and local
leftovers are recovered after restart.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: Yes; separate remote-spill user
documentation is deferred.
- Pre-submission status: Partially verified; see Testing.
### AI Disclosure
- Tool: Codex
- Generated: Patch extraction, targeted adaptations, and description.
- Human review: Pending author review.
---
be/src/exec/spill/remote_spill_data_dir.h | 3 +-
be/src/exec/spill/spill_data_dir.cpp | 2 +
be/src/exec/spill/spill_data_dir.h | 6 +-
be/src/exec/spill/spill_file.cpp | 50 +-----
be/src/exec/spill/spill_file_manager.cpp | 193 ++++++++++----------
be/src/exec/spill/spill_file_manager.h | 31 ++--
be/src/exec/spill/spill_file_writer.cpp | 4 +-
be/src/exec/spill/spill_file_writer.h | 3 +-
.../partitioned_hash_join_probe_operator_test.cpp | 6 +
be/test/vec/spill/spill_file_remote_test.cpp | 45 ++++-
be/test/vec/spill/spill_file_test.cpp | 123 +++++++++++--
be/test/vec/spill/spill_gc_queue_test.cpp | 196 +++++++++++++++++++++
12 files changed, 477 insertions(+), 185 deletions(-)
diff --git a/be/src/exec/spill/remote_spill_data_dir.h
b/be/src/exec/spill/remote_spill_data_dir.h
index 10dfd3278dc..396684ef41a 100644
--- a/be/src/exec/spill/remote_spill_data_dir.h
+++ b/be/src/exec/spill/remote_spill_data_dir.h
@@ -36,7 +36,8 @@ class RemoteFileSystem;
/// gets a new root; old remote objects remain subject to the bucket lifecycle
rule.
/// The objects of a spill file are deleted when its SpillFile is destroyed,
which happens
/// when the query is done with it; a deletion that failed is retried by the
GC thread. Nothing
-/// else deletes spill objects: what a BE that crashed left behind stays until
an object
+/// else deletes spill objects. Destruction only queues the request; GC does
the physical deletion.
+/// What a BE that crashed left behind stays until an object
/// lifecycle rule of the bucket (expiring keys under <vault prefix>/spill/
and aborting
/// incomplete multipart uploads) removes it.
///
diff --git a/be/src/exec/spill/spill_data_dir.cpp
b/be/src/exec/spill/spill_data_dir.cpp
index ef57f489d59..0f23769d516 100644
--- a/be/src/exec/spill/spill_data_dir.cpp
+++ b/be/src/exec/spill/spill_data_dir.cpp
@@ -103,6 +103,8 @@ void SpillDataDir::reserve(int64_t bytes) {
void SpillDataDir::release(int64_t bytes) {
std::lock_guard<std::mutex> l(_mutex);
+ DCHECK_GE(bytes, 0);
+ DCHECK_GE(_spill_data_bytes, bytes);
_update_usage_unlocked(-bytes, l);
}
diff --git a/be/src/exec/spill/spill_data_dir.h
b/be/src/exec/spill/spill_data_dir.h
index 656982c1a2e..f2ebfdffe78 100644
--- a/be/src/exec/spill/spill_data_dir.h
+++ b/be/src/exec/spill/spill_data_dir.h
@@ -83,10 +83,12 @@ public:
/// DISK_REACH_CAPACITY_LIMIT without accounting when the limit would be
exceeded.
Status try_reserve(int64_t bytes);
- /// Account bytes without checking capacity (a part footer must allow
closing an open part).
+ /// Account bytes without checking capacity (part footers must allow
closing an open part).
void reserve(int64_t bytes);
- /// Return bytes charged by try_reserve() or reserve().
+ /// Return bytes charged by try_reserve()/reserve(); callers own the
reservation lifetime.
+ /// This changes capacity accounting, not persisted-object accounting or
filesystem state.
+ /// SpillFile keeps its reservation until background deletion succeeds.
void release(int64_t bytes);
int64_t get_spill_data_bytes();
diff --git a/be/src/exec/spill/spill_file.cpp b/be/src/exec/spill/spill_file.cpp
index 19aee26cdda..d3d06e71fdd 100644
--- a/be/src/exec/spill/spill_file.cpp
+++ b/be/src/exec/spill/spill_file.cpp
@@ -36,7 +36,6 @@
#include "runtime/query_context.h"
#include "runtime/runtime_profile.h"
#include "runtime/runtime_state.h"
-#include "util/debug_points.h"
namespace doris {
SpillFile::SpillFile(SpillDataDir* data_dir, io::FileSystemSPtr fs,
std::string relative_path)
@@ -73,9 +72,8 @@ void SpillFile::gc() {
return;
}
_gc_started = true;
- // The writer may outlive this file (e.g. when an error unwinds the file's
owner first).
- // Drop its unfinished part now: closing it later would charge a footer to
no owner and
- // could publish an object after the prefix below was deleted.
+ // Preserve synchronous writer teardown: uploads must finish before
queuing deletion.
+ // Only physical cleanup and deletion retries are moved to the GC thread.
if (_active_writer != nullptr) {
_active_writer->_discard(this);
}
@@ -88,47 +86,11 @@ void SpillFile::gc() {
return;
}
_dir_created = false;
- // Delete the spill directory (or object key prefix) directly instead of
moving it to a
- // GC directory. No existence check: for object storage a "directory"
never exists as an
- // object, while deleting a missing local directory or an empty prefix is
a no-op.
- // The filesystem is pinned when the file is created; later files may use
another vault.
- auto fs = _fs;
- DORIS_CHECK(fs != nullptr) << "spill store " << _data_dir->path() << " is
not ready";
- Status status = fs->delete_directory(_spill_dir);
- DBUG_EXECUTE_IF("fault_inject::spill_file::gc", {
- status = Status::Error<INTERNAL_ERROR>("fault_inject spill_file gc
failed");
- });
- if (status.ok()) {
- _data_dir->release(written_bytes);
- _data_dir->release_persisted_bytes(std::exchange(_persisted_bytes, 0));
- _data_dir->record_spill_file_deleted();
- LOG(INFO) << "[spill][delete] " << file_context
- << ", cleanup=" << (_data_dir->is_remote() ? "object_prefix"
: "directory")
- << ", status=OK";
- return;
- }
- if (_data_dir->is_remote()) {
- auto reconcile_status =
- reconcile_remote_spill_bytes(_data_dir, _fs, _spill_dir,
&_persisted_bytes);
- if (!reconcile_status.ok()) {
- LOG_EVERY_T(WARNING, 60)
- << "failed to reconcile remote spill bytes after deletion:
" << file_context
- << ", status=" << reconcile_status;
- }
- }
- const int64_t persisted_bytes = std::exchange(_persisted_bytes, 0);
- // The data is still stored: keep it charged until a retry of the manager
deletes it.
auto* manager = ExecEnv::GetInstance()->spill_file_mgr();
- LOG(WARNING) << "[spill][delete] " << file_context
- << ", persisted_bytes_remaining=" << persisted_bytes
- << ", retry_queued=" << (manager != nullptr ? "true" :
"false")
- << ", status=" << status;
- if (manager == nullptr) {
- _data_dir->release(written_bytes);
- return;
- }
- manager->retry_spill_directory_deletion(_data_dir, _fs, _spill_dir,
written_bytes,
- persisted_bytes, _query_id,
{file_context});
+ DORIS_CHECK(manager != nullptr);
+ manager->queue_spill_directory_deletion(_data_dir, _fs, _spill_dir,
written_bytes,
+ std::exchange(_persisted_bytes,
0), _query_id,
+ {file_context});
}
std::string SpillFile::_log_context() const {
diff --git a/be/src/exec/spill/spill_file_manager.cpp
b/be/src/exec/spill/spill_file_manager.cpp
index 015dd8e7506..d74975a71e4 100644
--- a/be/src/exec/spill/spill_file_manager.cpp
+++ b/be/src/exec/spill/spill_file_manager.cpp
@@ -25,8 +25,11 @@
#include <filesystem>
#include <iterator>
#include <limits>
+#include <list>
#include <memory>
#include <string>
+#include <string_view>
+#include <unordered_map>
#include <utility>
#include <vector>
@@ -44,7 +47,6 @@
#include "storage/options.h"
#include "util/debug_points.h"
#include "util/pretty_printer.h"
-#include "util/time.h"
#include "util/uid_util.h"
namespace doris {
@@ -181,12 +183,8 @@ void ExternalSpillSession::update_accounting(const
std::string& path, int64_t cu
}
SpillFileManager::~SpillFileManager() {
- // QueryContext destruction can still queue failed deletions after stop(),
for example while
- // VDataStreamMgr is being destroyed. Retry them once more before dropping
the in-memory state.
- // A local directory that still cannot be deleted remains under the active
spill root and is
- // moved to the GC root by init() after restart; remote objects are left
to the lifecycle rule
- // of the bucket.
- _retry_pending_local_spill_directories();
+ // Do not start another cleanup pass during shutdown. Local leftovers are
moved to
+ // spill_gc by init() after restart; remote leftovers require a bucket
lifecycle rule.
DorisMetrics::instance()->metric_registry()->deregister_entity(_entity);
}
@@ -208,6 +206,9 @@ SpillFileManager::SpillFileManager(
_local_stores.push_back(local);
}
}
+ // init() may fail before starting GC. Every constructed manager must
still own a
+ // valid metric entity, including on that failure path when its destructor
deregisters it.
+ _init_metrics();
}
void SpillFileManager::stop() {
@@ -215,12 +216,6 @@ void SpillFileManager::stop() {
if (_spill_gc_thread) {
_spill_gc_thread->join();
}
- // The GC thread may observe the stop latch before processing a recently
queued failed deletion.
- // Retry the pending directories after the thread exits; later failures
get one final retry in
- // the destructor. Neither retries remote directories, so that an
unavailable object store does
- // not delay shutdown; they stay queued for a later gc() and are otherwise
left to the
- // lifecycle rule of the bucket.
- _retry_pending_local_spill_directories();
}
Status SpillFileManager::init() {
@@ -248,8 +243,6 @@ Status SpillFileManager::init() {
&_spill_gc_thread));
LOG(INFO) << "spill gc thread started";
- _init_metrics();
-
return Status::OK();
}
@@ -267,12 +260,11 @@ Status SpillFileManager::_init_local_spill_directories() {
if (!exists) {
RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
} else {
- auto suffix = ToStringFromUnixMillis(UnixMillis());
+ auto suffix = UniqueId::gen_uid().to_string();
auto gc_dir = store->get_spill_data_gc_path(suffix);
- if (std::filesystem::exists(gc_dir)) {
- LOG(WARNING) << "gc dir already exists: " << gc_dir;
- }
- (void)io::global_local_filesystem()->rename(spill_dir, gc_dir);
+ // Failure to quarantine the old root must fail startup; silently
reusing it
+ // would mix stale files with new queries. A UUID avoids GC-name
collisions.
+ RETURN_IF_ERROR(io::global_local_filesystem()->rename(spill_dir,
gc_dir));
RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
}
}
@@ -343,11 +335,9 @@ void SpillFileManager::_spill_gc_thread_callback() {
std::chrono::milliseconds(config::spill_gc_interval_ms))) {
gc(config::spill_gc_work_time_ms);
for (auto& [path, dir] : _spill_store_map) {
- static_cast<void>(dir->update_capacity());
- }
- if (_spill_pending_delete_dir_count_gauge != nullptr) {
-
_spill_pending_delete_dir_count_gauge->set_value(pending_delete_dir_count());
+ WARN_IF_ERROR(dir->update_capacity(), "failed to refresh spill
store capacity");
}
+
_spill_pending_delete_dir_count_gauge->set_value(pending_delete_dir_count());
}
}
@@ -471,8 +461,8 @@ void
SpillFileManager::_release_external_spill_session(ExternalSpillSession* spi
}
if (spill_session->_accounted_bytes > 0) {
- // Match SpillFile::gc(): QueryContext owns physical cleanup and its
retry path, while the
- // writer releases logical usage when its lifetime ends.
+ // External implementations own their logical reservations;
query-directory GC cleans
+ // any files they leave behind after their callbacks release the
directory lease.
spill_session->_data_dir->release(spill_session->_accounted_bytes);
spill_session->_accounted_bytes = 0;
}
@@ -517,27 +507,20 @@ void SpillFileManager::delete_query_spill_directory(const
std::string& query_id,
.dir = data_dir->get_spill_data_path(query_id),
.query_id = query_id,
.data_dir = data_dir,
- .fs = nullptr,
+ .fs = data_dir->fs(),
.charged_bytes = 0,
.persisted_bytes = 0,
.file_log_contexts = {},
};
- auto status = _try_delete_spill_directory(pending_directory);
- if (!status.ok()) {
- LOG(WARNING) << "[spill][delete_query] query_id=" << query_id
- << ", storage=local, path=" << pending_directory.dir
- << ", retry_queued=true, status=" << status;
- ++pending_directory.failed_count;
- _add_pending_directory(std::move(pending_directory));
- }
+ _add_pending_directory(std::move(pending_directory));
}
-void SpillFileManager::retry_spill_directory_deletion(SpillDataDir* data_dir,
io::FileSystemSPtr fs,
+void SpillFileManager::queue_spill_directory_deletion(SpillDataDir* data_dir,
io::FileSystemSPtr fs,
std::string dir, int64_t
charged_bytes,
int64_t persisted_bytes,
std::string query_id,
std::vector<std::string>
file_log_contexts) {
- _add_pending_directory({.failed_count = 1,
+ _add_pending_directory({.failed_count = 0,
.dir = std::move(dir),
.query_id = std::move(query_id),
.data_dir = data_dir,
@@ -548,38 +531,63 @@ void
SpillFileManager::retry_spill_directory_deletion(SpillDataDir* data_dir, io
}
void SpillFileManager::_add_pending_directory(PendingSpillDirectory
pending_directory) {
- auto is_under = [](const std::string& dir, const std::string& ancestor) {
- return dir.size() > ancestor.size() && dir.starts_with(ancestor) &&
- dir[ancestor.size()] == '/';
- };
+ // Normal SpillFile teardown uses this path too. A sibling-heavy backlog
must not make
+ // each producer scan all earlier entries while holding the shared queue
mutex.
std::lock_guard lock(_pending_spill_directories_mutex);
- for (auto& pending : _pending_spill_directories) {
- if (pending.data_dir == pending_directory.data_dir && pending.fs ==
pending_directory.fs &&
- (pending.dir == pending_directory.dir ||
- is_under(pending_directory.dir, pending.dir))) {
- // Deleting the pending ancestor deletes these objects too.
- pending.charged_bytes += pending_directory.charged_bytes;
- pending.persisted_bytes += pending_directory.persisted_bytes;
- pending.file_log_contexts.insert(
- pending.file_log_contexts.end(),
-
std::make_move_iterator(pending_directory.file_log_contexts.begin()),
-
std::make_move_iterator(pending_directory.file_log_contexts.end()));
- return;
+ _pending_spill_directories.emplace_back(std::move(pending_directory));
+}
+
+std::list<SpillFileManager::PendingSpillDirectory>
SpillFileManager::_coalesce_pending_directories(
+ std::list<PendingSpillDirectory> pending_directories) {
+ using DirectoryIterator = std::list<PendingSpillDirectory>::iterator;
+ struct IndexedDirectory {
+ DirectoryIterator entry;
+ bool emitted = false;
+ };
+ using DirectoryIndex = std::unordered_map<std::string_view,
IndexedDirectory>;
+ std::list<PendingSpillDirectory> coalesced;
+ // Keep absorbed nodes alive until the index is destroyed: its
string_views borrow dir.
+ std::list<PendingSpillDirectory> absorbed;
+ std::unordered_map<SpillDataDir*, std::unordered_map<io::FileSystem*,
DirectoryIndex>> indices;
+ for (auto it = pending_directories.begin(); it !=
pending_directories.end(); ++it) {
+ indices[it->data_dir][it->fs.get()].try_emplace(it->dir,
IndexedDirectory {.entry = it});
+ }
+ while (!pending_directories.empty()) {
+ auto current = pending_directories.begin();
+ auto& index = indices.at(current->data_dir).at(current->fs.get());
+ const std::string_view dir = current->dir;
+ auto* root = &index.at(dir);
+ // Search component-boundary ancestors, not the backlog. Indexing the
whole batch
+ // first also finds a parent enqueued after its children. For q/run-1
and q/run-10,
+ // neither is an ancestor; only an indexed q can absorb both.
+ for (auto slash = dir.find('/'); slash != std::string_view::npos;
+ slash = dir.find('/', slash + 1)) {
+ if (auto it = index.find(dir.substr(0, slash)); it != index.end())
{
+ root = &it->second;
+ break;
+ }
}
- }
- std::erase_if(_pending_spill_directories, [&](const PendingSpillDirectory&
pending) {
- if (pending.data_dir == pending_directory.data_dir && pending.fs ==
pending_directory.fs &&
- is_under(pending.dir, pending_directory.dir)) {
- pending_directory.charged_bytes += pending.charged_bytes;
- pending_directory.persisted_bytes += pending.persisted_bytes;
-
pending_directory.file_log_contexts.insert(pending_directory.file_log_contexts.end(),
-
pending.file_log_contexts.begin(),
-
pending.file_log_contexts.end());
- return true;
+ if (!root->emitted) {
+ // Emit groups at their first encountered member, not in path/hash
order, so a
+ // time-sliced retry still puts untried directories before earlier
failures.
+ coalesced.splice(coalesced.end(), pending_directories,
root->entry);
+ root->emitted = true;
}
- return false;
- });
- _pending_spill_directories.emplace_back(std::move(pending_directory));
+ auto& ancestor = *root->entry;
+ // A duplicate/descendant contributes its metadata once; the root
already carries
+ // its own charge and must not add itself after being spliced to
coalesced.
+ if (&ancestor != &*current) {
+ ancestor.charged_bytes += current->charged_bytes;
+ ancestor.persisted_bytes += current->persisted_bytes;
+ ancestor.failed_count = std::max(ancestor.failed_count,
current->failed_count);
+ ancestor.file_log_contexts.insert(
+ ancestor.file_log_contexts.end(),
+
std::make_move_iterator(current->file_log_contexts.begin()),
+ std::make_move_iterator(current->file_log_contexts.end()));
+ absorbed.splice(absorbed.end(), pending_directories, current);
+ }
+ }
+ return coalesced;
}
Status SpillFileManager::_try_delete_spill_directory(
@@ -600,6 +608,8 @@ Status SpillFileManager::_try_delete_spill_directory(
:
pending_directory.data_dir->fs();
DORIS_CHECK(fs != nullptr) << "spill store " <<
pending_directory.data_dir->path()
<< " is not ready";
+ DBUG_EXECUTE_IF("fault_inject::spill_file::gc",
+ { return Status::Error<INTERNAL_ERROR>("fault_inject
spill_file gc failed"); });
auto status = fs->delete_directory(pending_directory.dir);
if (status.ok()) {
pending_directory.data_dir->record_spill_file_deleted(
@@ -620,17 +630,9 @@ Status SpillFileManager::_try_delete_spill_directory(
return status;
}
-void SpillFileManager::_retry_pending_local_spill_directories() {
- MonotonicStopWatch watch;
- watch.start();
- _retry_pending_spill_directories(watch,
std::numeric_limits<int64_t>::max(),
- /*retry_remote=*/false);
-}
-
void SpillFileManager::_retry_pending_spill_directories(const
MonotonicStopWatch& watch,
- int64_t
max_work_time_ns,
- bool retry_remote) {
- std::vector<PendingSpillDirectory> pending_directories;
+ int64_t
max_work_time_ns) {
+ std::list<PendingSpillDirectory> pending_directories;
{
std::lock_guard lock(_pending_spill_directories_mutex);
pending_directories.swap(_pending_spill_directories);
@@ -638,25 +640,29 @@ void
SpillFileManager::_retry_pending_spill_directories(const MonotonicStopWatch
DBUG_EXECUTE_IF("fault_inject::spill_file_manager::retry_pending_spill_directories_after_drain",
{ DBUG_RUN_CALLBACK(); });
+ // Index/coalesce only the owned batch, outside the producer mutex.
+ pending_directories =
_coalesce_pending_directories(std::move(pending_directories));
// Limit repeated warnings for a persistently unavailable directory while
retaining it for
// every subsequent retry.
- std::vector<PendingSpillDirectory> untried_directories;
- std::vector<PendingSpillDirectory> failed_directories;
+ std::list<PendingSpillDirectory> untried_directories;
+ std::list<PendingSpillDirectory> failed_directories;
size_t tried = 0;
- for (auto& pending_directory : pending_directories) {
+ while (!pending_directories.empty()) {
+ auto current = pending_directories.begin();
+ auto& pending_directory = *current;
// A remote deletion can wait for a request timeout: after the time
slice is used up the
// remaining directories are queued again without being tried, ahead
of the ones that
// just failed, so that a slow failing directory cannot starve the
others.
- if ((!retry_remote && pending_directory.data_dir->is_remote()) ||
- (tried > 0 && watch.elapsed_time() >= max_work_time_ns)) {
- untried_directories.emplace_back(std::move(pending_directory));
- continue;
+ if (tried > 0 && watch.elapsed_time() >= max_work_time_ns) {
+ untried_directories.splice(untried_directories.end(),
pending_directories);
+ break;
}
++tried;
auto status = _try_delete_spill_directory(pending_directory);
if (status.ok()) {
pending_directory.data_dir->release(pending_directory.charged_bytes);
pending_directory.data_dir->release_persisted_bytes(pending_directory.persisted_bytes);
+ pending_directories.erase(current);
continue;
}
@@ -686,24 +692,15 @@ void
SpillFileManager::_retry_pending_spill_directories(const MonotonicStopWatch
<< ", files=" <<
pending_directory.file_log_contexts.size()
<< ", failed_attempts=" <<
pending_directory.failed_count
<< ", status=" << status;
- failed_directories.emplace_back(std::move(pending_directory));
+ failed_directories.splice(failed_directories.end(),
pending_directories, current);
}
- // The directories kept are already merged with each other, so they go
back as one batch;
- // only the ones queued while this pass ran are merged into them one by
one. A backlog of
- // many spill-file prefixes (an outage during a partitioned spill) thus
costs one rescan
- // per new entry, not one per kept entry.
- std::vector<PendingSpillDirectory> queued_meanwhile;
+ // Return complete batches in constant time under the mutex. Requests
enqueued while
+ // GC was doing I/O remain intact and will coalesce with these retries on
the next pass.
+ untried_directories.splice(untried_directories.end(), failed_directories);
{
std::lock_guard lock(_pending_spill_directories_mutex);
- queued_meanwhile.swap(_pending_spill_directories);
- _pending_spill_directories = std::move(untried_directories);
- _pending_spill_directories.insert(_pending_spill_directories.end(),
-
std::make_move_iterator(failed_directories.begin()),
-
std::make_move_iterator(failed_directories.end()));
- }
- for (auto& pending_directory : queued_meanwhile) {
- _add_pending_directory(std::move(pending_directory));
+ _pending_spill_directories.splice(_pending_spill_directories.begin(),
untried_directories);
}
}
@@ -726,7 +723,7 @@ void SpillFileManager::gc(int32_t max_work_time_ms) {
LOG(INFO) << msg;
}
}};
- _retry_pending_spill_directories(watch, max_work_time_ns,
/*retry_remote=*/true);
+ _retry_pending_spill_directories(watch, max_work_time_ns);
for (auto* store_dir : _local_stores) {
SpillGcStats stats;
_gc_spill_store(store_dir, watch, max_work_time_ns, &stats);
diff --git a/be/src/exec/spill/spill_file_manager.h
b/be/src/exec/spill/spill_file_manager.h
index 1c894c2955e..02fbdc99f4f 100644
--- a/be/src/exec/spill/spill_file_manager.h
+++ b/be/src/exec/spill/spill_file_manager.h
@@ -18,6 +18,7 @@
#pragma once
#include <atomic>
+#include <list>
#include <memory>
#include <mutex>
#include <string>
@@ -113,18 +114,18 @@ public:
/// Get a unique ID for constructing spill file paths.
uint64_t next_id() { return id_++; }
- // Delete SpillFile data synchronously.
+ // Enqueue SpillFile data for background deletion.
void delete_spill_file(SpillFileSPtr spill_file);
- // Recursively delete a per-query spill directory of a local store during
query teardown.
- // Failed deletions are retained by the manager and retried by its GC and
shutdown paths.
+ // Enqueue a per-query local directory during query teardown, without
filesystem I/O.
+ // This also removes empty query directories and residual files left by
external writers.
// A no-op for the remote store: its spill is deleted per spill file only.
void delete_query_spill_directory(const std::string& query_id,
SpillDataDir* data_dir);
- // Take over a spill file directory whose deletion failed. Its objects are
still stored, so
+ // Take over a spill file directory for background deletion. Its objects
are still stored, so
// `charged_bytes` stay charged to `data_dir` until a retry deletes them;
otherwise a
// deletion outage would free capacity that is still in use.
- void retry_spill_directory_deletion(SpillDataDir* data_dir,
io::FileSystemSPtr fs,
+ void queue_spill_directory_deletion(SpillDataDir* data_dir,
io::FileSystemSPtr fs,
std::string dir, int64_t charged_bytes,
int64_t persisted_bytes, std::string
query_id,
std::vector<std::string>
file_log_contexts = {});
@@ -141,7 +142,7 @@ public:
/// Bytes and GET requests issued by spill against object storage.
void update_spill_remote_read(int64_t bytes, int64_t get_requests);
- /// Number of spill directories whose deletion failed and is being retried.
+ /// Queued cleanup requests, coalesced when GC drains a batch.
size_t pending_delete_dir_count();
/// Bytes of completed spill objects this process currently holds in
object storage;
@@ -180,19 +181,15 @@ private:
Status _init_local_spill_directories();
void _spill_gc_thread_callback();
Status _try_delete_spill_directory(const PendingSpillDirectory&
pending_directory);
- /// Retry the queued failed deletions, at least one, until
`max_work_time_ns` has passed on
- /// `watch`; a remote one can take longer, since it waits for the object
store. Remote ones
- /// are only retried when `retry_remote` is set. The rest stay queued for
the next round.
- void _retry_pending_spill_directories(const MonotonicStopWatch& watch,
int64_t max_work_time_ns,
- bool retry_remote);
- /// Retry every queued failed deletion of a local store, for shutdown: it
does not wait for
- /// the object store.
- void _retry_pending_local_spill_directories();
+ /// Process queued deletions within the GC work budget, retaining failures
for retry.
+ void _retry_pending_spill_directories(const MonotonicStopWatch& watch,
+ int64_t max_work_time_ns);
void _gc_spill_store(LocalSpillDataDir* store_dir, const
MonotonicStopWatch& watch,
int64_t max_work_time_ns, SpillGcStats* stats);
- /// Queue a failed deletion, merged with a pending ancestor or absorbing
pending descendants
- /// of the same store so that an outage keeps about one entry per query.
+ /// Append without scanning the backlog; coalescing runs only on a drained
GC batch.
void _add_pending_directory(PendingSpillDirectory pending_directory);
+ static std::list<PendingSpillDirectory> _coalesce_pending_directories(
+ std::list<PendingSpillDirectory> pending_directories);
Status _initialize_external_spill_session(ExternalSpillSession*
spill_session);
void _release_external_spill_session(ExternalSpillSession* spill_session);
std::vector<SpillDataDir*> _get_stores_for_spill(TStorageMedium::type
storage_medium);
@@ -211,7 +208,7 @@ private:
// External spill leases defer query-directory deletion until native
callbacks finish.
// Filesystem I/O never holds this mutex.
std::mutex _pending_spill_directories_mutex;
- std::vector<PendingSpillDirectory> _pending_spill_directories;
+ std::list<PendingSpillDirectory> _pending_spill_directories;
std::unordered_map<std::string, size_t> _external_spill_directory_leases;
std::atomic_uint64_t id_ = 0;
diff --git a/be/src/exec/spill/spill_file_writer.cpp
b/be/src/exec/spill/spill_file_writer.cpp
index 885182d67bf..8e8d1691ca1 100644
--- a/be/src/exec/spill/spill_file_writer.cpp
+++ b/be/src/exec/spill/spill_file_writer.cpp
@@ -90,8 +90,8 @@ void SpillFileWriter::_discard(SpillFile* spill_file) {
return;
}
// Drop the part without a footer or close(). Destruction waits for
in-flight uploads
- // without publishing the object, before the SpillFile deletes its prefix.
Incomplete
- // multipart uploads are left to the bucket lifecycle rule.
+ // without publishing the object, before queuing the SpillFile's prefix
for deletion.
+ // Incomplete multipart uploads are left to the bucket lifecycle rule.
std::unique_ptr<io::FileWriter> writer = std::move(_file_writer);
writer.reset();
_on_part_closed(nullptr, /*closed=*/false, /*close_ns=*/0);
diff --git a/be/src/exec/spill/spill_file_writer.h
b/be/src/exec/spill/spill_file_writer.h
index 6de9e2acfce..facb101ae82 100644
--- a/be/src/exec/spill/spill_file_writer.h
+++ b/be/src/exec/spill/spill_file_writer.h
@@ -107,7 +107,8 @@ private:
/// Called by SpillFile::gc() when the SpillFile goes away before this
writer was closed
/// (e.g. an error unwound the owner of the file first). Drops the current
part without
/// a footer and without publishing it, and unregisters from the
SpillFile, so that nothing
- /// is charged to or written under a SpillFile that no longer exists.
+ /// is charged to or written under a SpillFile that no longer exists.
Destruction of the
+ /// underlying writer waits for in-flight uploads before directory
deletion is queued.
void _discard(SpillFile* spill_file);
/// If current part size >= _max_part_size, close it.
diff --git
a/be/test/exec/operator/partitioned_hash_join_probe_operator_test.cpp
b/be/test/exec/operator/partitioned_hash_join_probe_operator_test.cpp
index 4e782713b91..976621cb5e9 100644
--- a/be/test/exec/operator/partitioned_hash_join_probe_operator_test.cpp
+++ b/be/test/exec/operator/partitioned_hash_join_probe_operator_test.cpp
@@ -365,6 +365,12 @@ TEST_F(PartitionedHashJoinProbeOperatorTest,
CloseReleasesSpillResources) {
ASSERT_TRUE(local_state->_queue_probe_blocks.empty());
ASSERT_TRUE(local_state->_closed);
+ // close() queues physical deletion; stop the periodic GC thread and drain
its queue
+ // before checking that the files are gone.
+ auto* spill_file_manager = ExecEnv::GetInstance()->spill_file_mgr();
+ spill_file_manager->stop();
+ spill_file_manager->gc(10000);
+
expect_spill_file_deleted(queued_build_file);
expect_spill_file_deleted(queued_probe_file);
expect_spill_file_deleted(current_build_file);
diff --git a/be/test/vec/spill/spill_file_remote_test.cpp
b/be/test/vec/spill/spill_file_remote_test.cpp
index 50df422e91f..ee2681f69dc 100644
--- a/be/test/vec/spill/spill_file_remote_test.cpp
+++ b/be/test/vec/spill/spill_file_remote_test.cpp
@@ -558,6 +558,7 @@ protected:
ExecEnv::GetInstance()->_spill_file_mgr = _manager;
auto st = _manager->init();
ASSERT_TRUE(st.ok()) << st;
+ _manager->stop(); // Tests drive GC explicitly, without
timing-dependent background passes.
}
void _destroy_manager() {
@@ -565,6 +566,7 @@ protected:
return;
}
_manager->stop();
+ _manager->gc(10000);
SAFE_DELETE(_manager);
ExecEnv::GetInstance()->_spill_file_mgr = nullptr;
_data_dir = nullptr;
@@ -599,7 +601,7 @@ protected:
auto queue_ancestor = [&]() {
// A directory entry has no logical-file count of its own, but
must retain the
// individual file contexts when it absorbs children (or children
join it).
- _manager->retry_spill_directory_deletion(_data_dir, _s3_fs,
query_path, 0, 0, query_id);
+ _manager->queue_spill_directory_deletion(_data_dir, _s3_fs,
query_path, 0, 0, query_id);
};
if (ancestor_first) {
queue_ancestor();
@@ -609,12 +611,13 @@ protected:
if (!ancestor_first) {
queue_ancestor();
}
- EXPECT_EQ(_manager->pending_delete_dir_count(), 1);
+ EXPECT_EQ(_manager->pending_delete_dir_count(), 3); // Coalescing is
deferred to GC.
for (int i = 0; i < 10; ++i) {
_manager->gc(1000);
}
+ EXPECT_EQ(_manager->pending_delete_dir_count(), 1);
_expect_file_counts(created + 2, deleted);
- EXPECT_EQ(logs.count(google::WARNING, "[spill][delete] query_id=" +
query_id + ','), 2);
+ EXPECT_EQ(logs.count(google::WARNING, "[spill][delete] query_id=" +
query_id + ','), 0);
EXPECT_LE(logs.count(google::WARNING, "[spill][delete_retry]
query_id=" + query_id + ','),
1);
mock_store().fail_deletes = false;
@@ -829,6 +832,7 @@ TEST_F(SpillFileRemoteTest,
WriterFactoryUsesRemoteSubclass) {
ASSERT_TRUE(writer->close().ok());
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
}
TEST_F(SpillFileRemoteTest, ReaderFactoryUsesRemoteSubclass) {
@@ -870,6 +874,7 @@ TEST_F(SpillFileRemoteTest,
ImplicitClosePreservesRemoteAccounting) {
ASSERT_EQ(_data_dir->get_spill_data_bytes(), object_bytes);
ASSERT_EQ(_read_all(spill_file), _column_values(block));
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->remote_spill_data_bytes(), 0);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -1040,6 +1045,7 @@ TEST_F(SpillFileRemoteTest,
VaultChangeKeepsExistingFilesAndPendingDeletesPinned
mock_store().fail_deletes = true;
first.reset();
second.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->pending_delete_dir_count(), 2);
ASSERT_GT(_manager->remote_spill_data_bytes(), 0);
mock_store().fail_deletes = false;
@@ -1069,6 +1075,7 @@ TEST_F(SpillFileRemoteTest,
RemoteBillingExcludesOpenPartReservations) {
ASSERT_EQ(_manager->remote_spill_data_bytes(),
_data_dir->get_spill_data_bytes());
writer.reset();
file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->remote_spill_data_bytes(), 0);
}
@@ -1095,6 +1102,7 @@ TEST_F(SpillFileRemoteTest,
PublishedPartRemainsBillableWhenCloseAndCleanupFail)
_manager->stop();
mock_store().fail_deletes = true;
file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->pending_delete_dir_count(), 1);
ASSERT_EQ(_manager->remote_spill_data_bytes(), object_bytes);
// After the failed deletion: still there, retried by the GC.
@@ -1169,8 +1177,8 @@ TEST_F(SpillFileRemoteTest,
PendingRemoteDeletesAreBoundedByGcWorkTime) {
}
// The directories a time-sliced pass did not get to are queued again as one
batch, in order,
-// and the ones queued while the pass ran are merged into them: a duplicate of
a queued
-// directory adds no entry, a new directory does.
+// and requests queued while the pass ran remain untouched until the next GC
batch. A duplicate
+// is merged only after the next drain, without scanning the producer queue.
TEST_F(SpillFileRemoteTest, PendingRemoteDeleteBacklogIsRequeuedInBulk) {
_create_manager();
std::mt19937 rng(129);
@@ -1204,10 +1212,10 @@ TEST_F(SpillFileRemoteTest,
PendingRemoteDeleteBacklogIsRequeuedInBulk) {
after_drain_debug_point->execute_limit = 1;
after_drain_debug_point->callback = std::function<void()>([&]() {
const std::string spill_path = _data_dir->get_spill_data_path();
- _manager->retry_spill_directory_deletion(_data_dir, _data_dir->fs(),
+ _manager->queue_spill_directory_deletion(_data_dir, _data_dir->fs(),
spill_path +
"/query_bulk_requeue_5/sort-1", 0, 0,
"query_bulk_requeue_5");
- _manager->retry_spill_directory_deletion(_data_dir, _data_dir->fs(),
+ _manager->queue_spill_directory_deletion(_data_dir, _data_dir->fs(),
spill_path +
"/query_bulk_requeue_new/sort-1", 0,
0, "query_bulk_requeue_new");
});
@@ -1217,7 +1225,7 @@ TEST_F(SpillFileRemoteTest,
PendingRemoteDeleteBacklogIsRequeuedInBulk) {
mock_store().delete_delay_ms = 20;
_manager->gc(1);
ASSERT_EQ(after_drain_debug_point->execute_num.load(), 1);
- ASSERT_EQ(_manager->pending_delete_dir_count(), kFiles + 1);
+ ASSERT_EQ(_manager->pending_delete_dir_count(), kFiles + 2);
for (int i = 0; i < kFiles; ++i) {
ASSERT_FALSE(_query_objects(fmt::format("query_bulk_requeue_{}",
i)).empty());
}
@@ -1263,6 +1271,7 @@ TEST_F(SpillFileRemoteTest,
PartialDeleteReconcilesOnlyRemainingObjectBytes) {
}
_manager->stop();
file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->pending_delete_dir_count(), 1);
ASSERT_EQ(_manager->remote_spill_data_bytes(), remaining_bytes);
ASSERT_EQ(
@@ -1434,6 +1443,7 @@ TEST_F(SpillFileRemoteTest, RoundtripAcrossParts) {
// After deleting: nothing is left of the query.
spill_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_1").empty());
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
ASSERT_EQ(_manager->remote_spill_data_bytes(), 0);
@@ -1461,6 +1471,7 @@ TEST_F(SpillFileRemoteTest, SmallPartIsOnePutObject) {
ASSERT_EQ(mock_store().head_requests, check_after_upload ? 1 : 0);
ASSERT_EQ(_counter(profile::SPILL_REMOTE_UPLOAD_BYTES) - bytes_before,
object_bytes);
spill_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_small").empty());
_destroy_manager();
}
@@ -1721,6 +1732,7 @@ TEST_F(SpillFileRemoteTest, GcDeletesObjects) {
ASSERT_GT(_data_dir->get_spill_data_bytes(), 0);
heads_after_write = mock_store().head_requests;
}
+ _manager->gc(10000);
// No exists() probe is needed: the prefix is deleted directly (LIST +
DELETE, no HEAD).
ASSERT_TRUE(mock_store().keys_with_prefix(kBucket, spill_root() +
"/query_3/").empty());
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
@@ -1758,6 +1770,7 @@ TEST_F(SpillFileRemoteTest,
FailedDeletionKeepsCapacityCharged) {
mock_store().fail_deletes = true;
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_query_objects("query_8"), written);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), charged);
ASSERT_EQ(_manager->remote_spill_data_bytes(), charged);
@@ -1803,6 +1816,7 @@ TEST_F(SpillFileRemoteTest, StorageLimitIsEnforced) {
// Nothing was accounted for the rejected block; the store is still
usable. Closing the
// writer published a part without blocks, deleted with its file.
spill_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_5").empty());
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
@@ -1900,6 +1914,7 @@ TEST_F(SpillFileRemoteTest, UploadQueueBoundsWriter) {
ASSERT_TRUE(_no_open_multipart_uploads());
ASSERT_EQ(_read_all(spill_file), _values_of(blocks));
spill_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_6").empty());
}
@@ -1990,6 +2005,7 @@ TEST_F(SpillFileRemoteTest,
PendingBuffersDoNotBlockWriters) {
ASSERT_EQ(_query_objects("query_10"), expected);
idle_files.clear();
active_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_10").empty());
}
@@ -2058,6 +2074,7 @@ TEST_F(SpillFileRemoteTest, UploadQueueWaitIsCancellable)
{
ASSERT_EQ(mock_store().complete_multipart_requests, 0);
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2096,6 +2113,7 @@ TEST_F(SpillFileRemoteTest,
CancelledQueryCloseLeavesIncompleteMultipart) {
ASSERT_FALSE(_no_open_multipart_uploads());
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2121,6 +2139,8 @@ TEST_F(SpillFileRemoteTest,
SpillFileDestroyedBeforeWriterDiscardsPart) {
ASSERT_GT(_data_dir->get_spill_data_bytes(), 0);
spill_file.reset();
+
+ _manager->gc(10000);
ASSERT_EQ(mock_store().complete_multipart_requests, 0);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
ASSERT_FALSE(_no_open_multipart_uploads());
@@ -2156,8 +2176,10 @@ TEST_F(SpillFileRemoteTest,
FailedCloseThenSpillFileDestroyed) {
if (writer_first) {
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
} else {
spill_file.reset();
+ _manager->gc(10000);
writer.reset();
}
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
@@ -2189,6 +2211,7 @@ TEST_F(SpillFileRemoteTest,
CancelledQueryCloseIssuesNoUpload) {
ASSERT_TRUE(_query_objects("query_13").empty());
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2213,6 +2236,7 @@ TEST_F(SpillFileRemoteTest,
UploadFailureIsReportedAndReconciled) {
ASSERT_TRUE(_query_objects("query_8").empty());
mock_store().fail_uploads = false;
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_manager->remote_spill_data_bytes(), 0);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2248,6 +2272,7 @@ TEST_F(SpillFileRemoteTest,
FailedRotationDoesNotFinishFile) {
ASSERT_TRUE(_no_open_multipart_uploads());
writer.reset();
spill_file.reset();
+ _manager->gc(10000);
ASSERT_TRUE(_query_objects("query_18").empty());
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
ASSERT_EQ(_manager->remote_spill_data_bytes(), 0);
@@ -2292,6 +2317,7 @@ TEST_F(SpillFileRemoteTest, LateUploadFailureDrainsPart) {
ASSERT_FALSE(_no_open_multipart_uploads());
ASSERT_TRUE(_query_objects("query_11").empty());
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2316,6 +2342,7 @@ TEST_F(SpillFileRemoteTest, CreateMultipartFailureIsSafe)
{
ASSERT_GE(mock_store().create_multipart_requests, 1);
ASSERT_TRUE(_query_objects("query_12").empty());
spill_file.reset();
+ _manager->gc(10000);
ASSERT_EQ(_data_dir->get_spill_data_bytes(), 0);
}
@@ -2351,6 +2378,7 @@ TEST_F(SpillFileRemoteTest,
LifecycleLogsCountLogicalFilesNotParts) {
file->gc();
file->gc();
file.reset();
+ _manager->gc(10000);
writer.reset();
_expect_file_counts(created + 1, deleted + 1);
EXPECT_EQ(logs.count(google::INFO, "[spill][delete]
query_id=query_lifecycle,"), 1);
@@ -2374,6 +2402,7 @@ TEST_F(SpillFileRemoteTest,
FailedCloseHasWarningLifecycleLog) {
EXPECT_EQ(_counter(profile::SPILL_REMOTE_UPLOAD_BYTES), 0);
_expect_file_counts(created + 1, deleted);
file.reset();
+ _manager->gc(10000);
_expect_file_counts(created + 1, deleted + 1);
EXPECT_EQ(logs.count(google::INFO, "[spill][delete]
query_id=query_lifecycle_failed,"), 1);
}
diff --git a/be/test/vec/spill/spill_file_test.cpp
b/be/test/vec/spill/spill_file_test.cpp
index b486dd4a7f9..10301b9eeb2 100644
--- a/be/test/vec/spill/spill_file_test.cpp
+++ b/be/test/vec/spill/spill_file_test.cpp
@@ -21,6 +21,7 @@
#include <sys/statvfs.h>
#include <algorithm>
+#include <atomic>
#include <filesystem>
#include <functional>
#include <memory>
@@ -28,6 +29,7 @@
#include <set>
#include <string>
#include <typeinfo>
+#include <unordered_map>
#include <vector>
#include "common/config.h"
@@ -59,6 +61,16 @@
namespace doris::vectorized {
+namespace {
+Status create_empty_spill_test_file(const std::string& path) {
+ auto* fs = io::global_local_filesystem().get();
+
RETURN_IF_ERROR(fs->create_directory(std::filesystem::path(path).parent_path(),
false));
+ io::FileWriterPtr writer;
+ RETURN_IF_ERROR(fs->create_file(path, &writer));
+ return writer->close();
+}
+} // namespace
+
class SpillFileTest : public testing::Test {
protected:
void SetUp() override {
@@ -113,11 +125,13 @@ protected:
ExecEnv::GetInstance()->_spill_file_mgr = spill_file_manager;
st = spill_file_manager->init();
ASSERT_TRUE(st.ok()) << "init spill file manager failed: " <<
st.to_string();
+ spill_file_manager->stop();
}
void TearDown() override {
ExecEnv::GetInstance()->spill_file_mgr()->stop();
_runtime_state.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
SAFE_DELETE(ExecEnv::GetInstance()->_spill_file_mgr);
// Clean up test directory
auto st = io::global_local_filesystem()->delete_directory(_spill_dir);
@@ -161,14 +175,8 @@ protected:
}
void _create_residual_file(const std::string& file_path) {
- auto st = io::global_local_filesystem()->create_directory(
- std::filesystem::path(file_path).parent_path(), false);
- ASSERT_TRUE(st.ok()) << st.to_string();
- io::FileWriterPtr writer;
- st = io::global_local_filesystem()->create_file(file_path, &writer);
- ASSERT_TRUE(st.ok()) << st.to_string();
- st = writer->close();
- ASSERT_TRUE(st.ok()) << st.to_string();
+ auto status = create_empty_spill_test_file(file_path);
+ ASSERT_TRUE(status.ok()) << status;
}
std::set<std::string> _gc_subdirectories(LocalSpillDataDir* data_dir) {
@@ -266,6 +274,7 @@ TEST_F(SpillFileTest,
LocalLifecycleCountsWrittenAndUnwrittenFilesOnce) {
auto unwritten = std::make_shared<SpillFile>(_data_dir_ptr,
"query_local_lifecycle/sort-2");
unwritten->gc();
unwritten.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
EXPECT_EQ(_data_dir_ptr->spill_file_created_total->value(), created + 2);
EXPECT_EQ(_data_dir_ptr->spill_file_deleted_total->value(), deleted + 2);
EXPECT_EQ(logs.count(google::INFO, "[spill][create]
query_id=query_local_lifecycle,"), 2);
@@ -299,9 +308,14 @@ TEST_F(SpillFileTest,
LocalFailedDeletionCountsOnlySuccessfulRetry) {
DebugPoints::instance()->add(gc_error, debug_point);
file->gc();
file->gc();
+ manager->gc(1000);
EXPECT_EQ(_data_dir_ptr->spill_file_deleted_total->value(), deleted);
EXPECT_EQ(manager->pending_delete_dir_count(), 1);
- EXPECT_EQ(logs.count(google::WARNING, "[spill][delete]
query_id=query_local_retry,"), 1);
+ // Retry warnings share a process-wide rate limit; the retained path and
counters prove
+ // the failed deletion even when another store used this warning's log
slot first.
+ EXPECT_TRUE(std::filesystem::exists(_data_dir_ptr->get_spill_data_path() +
+ "/query_local_retry/sort-1"));
+ EXPECT_LE(logs.count(google::WARNING, "[spill][delete_retry]
query_id=query_local_retry,"), 1);
DebugPoints::instance()->remove(gc_error);
manager->gc(1000);
file.reset();
@@ -1033,7 +1047,8 @@ TEST_F(SpillFileTest, GCCleansUpFiles) {
// spill_file goes out of scope here, destructor calls gc()
}
- // After SpillFile is destroyed, the directory should be cleaned up
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
+ // GC deletes the directory after the file has been released
bool exists = false;
auto st = io::global_local_filesystem()->exists(spill_file_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1163,6 +1178,7 @@ TEST_F(SpillFileTest,
QueryContextDeletesEmptySpillDirectory) {
ASSERT_TRUE(exists);
query_ctx.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(query_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1194,6 +1210,7 @@ TEST_F(SpillFileTest,
QueryContextCleansUpNestedSpillDirectory) {
ASSERT_TRUE(exists);
query_ctx.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(query_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1222,6 +1239,7 @@ TEST_F(SpillFileTest,
QueryContextDeletesResidualSpillDirectory) {
ASSERT_TRUE(exists);
query_ctx.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(query_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1254,6 +1272,7 @@ TEST_F(SpillFileTest,
QueryContextCleansUpAllTouchedSpillDirectories) {
ASSERT_TRUE(second_exists);
query_ctx.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(first_query_dir, &first_exists);
ASSERT_TRUE(st.ok());
@@ -1309,6 +1328,7 @@ TEST_F(SpillFileTest,
QueryContextContinuesCleanupAfterRootFailure) {
DebugPoints::instance()->add(debug_point_name, debug_point);
query_ctx.reset();
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(first_query_dir, &first_exists);
ASSERT_TRUE(st.ok());
@@ -1368,7 +1388,7 @@ TEST_F(SpillFileTest,
QueryContextRetriesSpillDirectoryDeletionUntilSuccess) {
ASSERT_TRUE(st.ok());
ASSERT_TRUE(exists);
- for (int i = 0; i < 4; ++i) {
+ for (int i = 0; i < 5; ++i) {
ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(query_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1529,6 +1549,7 @@ TEST_F(SpillFileTest,
FinalCloseReleasesRerunnableQueryContextAndDeletesSpillDir
EXPECT_TRUE(fragment_mgr->_rerunnable_params_map.empty());
}
EXPECT_TRUE(weak_query_ctx.expired());
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(query_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1557,7 +1578,7 @@ TEST_F(SpillFileTest,
QueryContextSkipsCleanupWithoutSpill) {
ASSERT_TRUE(exists);
}
-TEST_F(SpillFileTest, DeleteSpillFileThroughManagerSynchronously) {
+TEST_F(SpillFileTest, DeleteSpillFileThroughManagerAsynchronously) {
SpillFileSPtr spill_file;
auto st =
ExecEnv::GetInstance()->spill_file_mgr()->create_spill_file("test_query/mgr_delete",
spill_file);
@@ -1588,6 +1609,10 @@ TEST_F(SpillFileTest,
DeleteSpillFileThroughManagerSynchronously) {
ASSERT_TRUE(exists);
ExecEnv::GetInstance()->spill_file_mgr()->delete_spill_file(spill_file);
+ st = io::global_local_filesystem()->exists(spill_file_dir, &exists);
+ ASSERT_TRUE(st.ok());
+ ASSERT_TRUE(exists); // Query teardown only queues work; it does no
filesystem I/O.
+ ExecEnv::GetInstance()->spill_file_mgr()->gc(10000);
st = io::global_local_filesystem()->exists(spill_file_dir, &exists);
ASSERT_TRUE(st.ok());
@@ -1992,4 +2017,78 @@ TEST_F(SpillFileTest, DataDirCapacityTracking) {
ASSERT_GT(after_write_bytes, initial_bytes);
}
+TEST_F(SpillFileTest, QueryTeardownOnlyQueuesCleanup) {
+ const TUniqueId query_id = UniqueId::gen_uid().to_thrift();
+ auto query = MockQueryContext::create(query_id);
+ std::weak_ptr<QueryContext> weak_query = query;
+ const auto query_dir =
_data_dir_ptr->get_spill_data_path(print_id(query_id));
+ _write_and_release_spill_file(query_id, query.get(), _data_dir_ptr,
"sort-1");
+ _create_residual_file(query_dir + "/residual");
+ const auto charged = _data_dir_ptr->get_spill_data_bytes();
+ ASSERT_GT(charged, 0);
+ query.reset();
+ EXPECT_TRUE(weak_query.expired());
+ EXPECT_TRUE(std::filesystem::exists(query_dir + "/sort-1"));
+ EXPECT_TRUE(std::filesystem::exists(query_dir + "/residual"));
+ EXPECT_EQ(_data_dir_ptr->get_spill_data_bytes(), charged);
+ auto* manager = ExecEnv::GetInstance()->spill_file_mgr();
+ manager->stop();
+ EXPECT_TRUE(std::filesystem::exists(query_dir));
+ manager->gc(10000);
+ EXPECT_FALSE(std::filesystem::exists(query_dir));
+ EXPECT_EQ(_data_dir_ptr->get_spill_data_bytes(), 0);
+}
+
+TEST(SpillFileManagerTest, ShutdownLeavesPendingLocalDirectoriesForStartupGc) {
+ const std::string root = "./ut_dir/spill_shutdown_test";
+ Defer cleanup {[&]() {
+ WARN_IF_ERROR(io::global_local_filesystem()->delete_directory(root),
"clean shutdown test");
+ }};
+ auto make_manager = [&]() {
+ std::unordered_map<std::string, std::unique_ptr<SpillDataDir>> stores;
+ stores.emplace(root, std::make_unique<LocalSpillDataDir>(root, 128L *
1024 * 1024));
+ return std::make_unique<SpillFileManager>(std::move(stores));
+ };
+ ASSERT_TRUE(io::global_local_filesystem()->create_directory(root,
false).ok());
+ auto manager = make_manager();
+ ASSERT_TRUE(manager->init().ok());
+ manager->stop();
+ auto* store = manager->_local_stores.front();
+ const auto directory = store->get_spill_data_path("shutdown_query");
+ ASSERT_TRUE(create_empty_spill_test_file(directory + "/data").ok());
+ manager->delete_query_spill_directory("shutdown_query", store);
+ manager->stop();
+ EXPECT_TRUE(std::filesystem::exists(directory + "/data"));
+ manager.reset();
+ EXPECT_TRUE(std::filesystem::exists(directory + "/data"));
+ manager = make_manager();
+ ASSERT_TRUE(manager->init().ok());
+ manager->stop();
+ EXPECT_FALSE(std::filesystem::exists(directory));
+ const auto gc_root =
manager->_local_stores.front()->get_spill_data_gc_path();
+ EXPECT_FALSE(std::filesystem::is_empty(gc_root));
+ manager->gc(10000);
+ // The first pass removes query directories; the next prunes their
now-empty GC parent.
+ manager->gc(10000);
+ EXPECT_TRUE(std::filesystem::is_empty(gc_root));
+}
+
+TEST(SpillFileManagerTest, StartupDoesNotReuseRootWhenQuarantineFails) {
+ const std::string root = "./ut_dir/spill_startup_rename_failure";
+ auto* fs = io::global_local_filesystem().get();
+ ASSERT_TRUE(fs->delete_directory(root).ok());
+ ASSERT_TRUE(fs->create_directory(root + "/spill", false).ok());
+ Defer cleanup {
+ [&]() { WARN_IF_ERROR(fs->delete_directory(root), "clean rename
failure test"); }};
+ // spill_gc is a file, so renaming the active root underneath it must fail
with ENOTDIR.
+ ASSERT_TRUE(create_empty_spill_test_file(root + "/spill_gc").ok());
+ std::unordered_map<std::string, std::unique_ptr<SpillDataDir>> stores;
+ stores.emplace(root, std::make_unique<LocalSpillDataDir>(root, 128L * 1024
* 1024));
+ auto manager = std::make_unique<SpillFileManager>(std::move(stores));
+ auto status = manager->init();
+ EXPECT_FALSE(status.ok())
+ << "startup must not silently reuse a spill root it could not
quarantine";
+ EXPECT_TRUE(std::filesystem::exists(root + "/spill"));
+}
+
} // namespace doris::vectorized
diff --git a/be/test/vec/spill/spill_gc_queue_test.cpp
b/be/test/vec/spill/spill_gc_queue_test.cpp
new file mode 100644
index 00000000000..5b46495645a
--- /dev/null
+++ b/be/test/vec/spill/spill_gc_queue_test.cpp
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <list>
+#include <memory>
+#include <string>
+#include <thread>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "exec/spill/local_spill_data_dir.h"
+#include "exec/spill/spill_file_manager.h"
+#include "io/fs/local_file_system.h"
+
+namespace doris {
+
+class SpillGcQueueTest : public testing::Test {
+protected:
+ using Pending = SpillFileManager::PendingSpillDirectory;
+ using PendingList = std::list<Pending>;
+
+ Pending _entry(std::string dir) {
+ return {.failed_count = 0,
+ .dir = dir,
+ .query_id = dir.substr(0, dir.find('/')),
+ .data_dir = &_store,
+ .fs = _fs,
+ .charged_bytes = 1,
+ .persisted_bytes = 2,
+ .file_log_contexts = {std::move(dir)}};
+ }
+
+ std::unique_ptr<SpillFileManager> _manager() {
+ return std::make_unique<SpillFileManager>(
+ std::unordered_map<std::string, std::unique_ptr<SpillDataDir>>
{});
+ }
+
+ static PendingList _coalesce(PendingList entries) {
+ return
SpillFileManager::_coalesce_pending_directories(std::move(entries));
+ }
+
+ PendingList _parent_batch(bool parent_first) {
+ PendingList batch;
+ auto parent = _entry("query/run-1");
+ parent.failed_count = 7;
+ if (parent_first) {
+ batch.emplace_back(parent);
+ }
+ batch.emplace_back(_entry("query/run-1/part"));
+ batch.emplace_back(_entry("query/run-10")); // Not under run-1.
+ batch.emplace_back(_entry("query/run-1/part/nested"));
+ if (!parent_first) {
+ batch.emplace_back(std::move(parent));
+ }
+ batch.emplace_back(_entry("query/run-1")); // Exact duplicate.
+ return batch;
+ }
+
+ static void _expect_parent_metadata(const PendingList& batch) {
+ ASSERT_EQ(batch.size(), 2);
+ EXPECT_EQ(batch.front().dir, "query/run-1");
+ EXPECT_EQ(batch.front().charged_bytes, 4);
+ EXPECT_EQ(batch.front().persisted_bytes, 8);
+ EXPECT_EQ(batch.front().failed_count, 7);
+ EXPECT_EQ(batch.front().file_log_contexts.size(), 4);
+ EXPECT_EQ(batch.back().dir, "query/run-10");
+ EXPECT_EQ(batch.back().charged_bytes, 1);
+ }
+
+ LocalSpillDataDir _store {"spill_gc_queue_test_store", 0};
+ io::FileSystemSPtr _fs = io::global_local_filesystem();
+};
+
+TEST_F(SpillGcQueueTest, EnqueueDefersCoalescingUntilGc) {
+ auto manager = _manager();
+ for (const auto& dir : {"query/run", "query", "query/run"}) {
+ manager->queue_spill_directory_deletion(&_store, _fs, dir, 1, 2,
"query", {dir});
+ }
+ // Producer code preserves raw requests, even when a parent or duplicate
is queued.
+ EXPECT_EQ(manager->pending_delete_dir_count(), 3);
+ EXPECT_EQ(manager->_pending_spill_directories.front().dir, "query/run");
+ auto batch = _coalesce(std::move(manager->_pending_spill_directories));
+ ASSERT_EQ(batch.size(), 1);
+ EXPECT_EQ(batch.front().dir, "query");
+ EXPECT_EQ(batch.front().charged_bytes, 3);
+ EXPECT_EQ(batch.front().persisted_bytes, 6);
+ EXPECT_EQ(batch.front().file_log_contexts.size(), 3);
+}
+
+TEST_F(SpillGcQueueTest, SiblingBacklogKeepsFifoOrder) {
+ PendingList batch;
+ constexpr int kFiles = 8192;
+ for (int i = kFiles; i > 0; --i) {
+ batch.emplace_back(_entry("query/run-" + std::to_string(i)));
+ }
+ batch = _coalesce(std::move(batch));
+ ASSERT_EQ(batch.size(), kFiles);
+ int expected = kFiles;
+ for (const auto& entry : batch) {
+ EXPECT_EQ(entry.dir, "query/run-" + std::to_string(expected--));
+ EXPECT_EQ(entry.charged_bytes, 1);
+ EXPECT_EQ(entry.persisted_bytes, 2);
+ }
+}
+
+TEST_F(SpillGcQueueTest, ParentBeforeOrAfterChildrenRetainsAllMetadata) {
+ for (bool parent_first : {true, false}) {
+ _expect_parent_metadata(_coalesce(_parent_batch(parent_first)));
+ }
+}
+
+TEST_F(SpillGcQueueTest, DifferentStoresAndFileSystemObjectsStaySeparate) {
+ LocalSpillDataDir other_store {"spill_gc_queue_other_store", 0};
+ // These have the same filesystem ID; identity must still be the pinned
object.
+ io::FileSystemSPtr other_fs(new io::LocalFileSystem());
+ EXPECT_EQ(other_fs->id(), _fs->id());
+ PendingList batch;
+ batch.emplace_back(_entry("query"));
+ auto other_disk = _entry("query/run");
+ other_disk.data_dir = &other_store;
+ batch.emplace_back(std::move(other_disk));
+ auto other_vault = _entry("query/run");
+ other_vault.fs = other_fs;
+ batch.emplace_back(std::move(other_vault));
+ batch.emplace_back(_entry("query/run"));
+ batch = _coalesce(std::move(batch));
+ ASSERT_EQ(batch.size(), 3);
+ auto it = batch.begin();
+ EXPECT_EQ(it->dir, "query");
+ EXPECT_EQ(it->charged_bytes, 2);
+ EXPECT_EQ((++it)->data_dir, &other_store);
+ EXPECT_EQ((++it)->fs, other_fs);
+ EXPECT_EQ(it->charged_bytes, 1);
+}
+
+TEST_F(SpillGcQueueTest, EmptyAndDuplicateBatches) {
+ EXPECT_TRUE(_coalesce({}).empty());
+ PendingList batch;
+ for (int i = 0; i < 1024; ++i) {
+ batch.emplace_back(_entry("query/run"));
+ }
+ batch = _coalesce(std::move(batch));
+ ASSERT_EQ(batch.size(), 1);
+ EXPECT_EQ(batch.front().charged_bytes, 1024);
+ EXPECT_EQ(batch.front().persisted_bytes, 2048);
+ EXPECT_EQ(batch.front().file_log_contexts.size(), 1024);
+}
+
+TEST_F(SpillGcQueueTest, ConcurrentProducersPreserveEveryRequest) {
+ auto manager = _manager();
+ constexpr int kQueries = 4;
+ constexpr int kFiles = 2048;
+ std::vector<std::thread> producers;
+ for (int query = 0; query < kQueries; ++query) {
+ producers.emplace_back([&, query]() {
+ const auto query_id = "query-" + std::to_string(query);
+ for (int file = 0; file < kFiles; ++file) {
+ manager->queue_spill_directory_deletion(&_store, _fs,
+ query_id + "/run-" +
std::to_string(file),
+ 1, 2, query_id,
{"file-context"});
+ }
+ manager->queue_spill_directory_deletion(&_store, _fs, query_id, 0,
0, query_id);
+ });
+ }
+ for (auto& producer : producers) {
+ producer.join();
+ }
+ EXPECT_EQ(manager->pending_delete_dir_count(), kQueries * (kFiles + 1));
+ auto batch = _coalesce(std::move(manager->_pending_spill_directories));
+ ASSERT_EQ(batch.size(), kQueries);
+ for (const auto& entry : batch) {
+ EXPECT_EQ(entry.charged_bytes, kFiles);
+ EXPECT_EQ(entry.persisted_bytes, 2 * kFiles);
+ EXPECT_EQ(entry.file_log_contexts.size(), kFiles);
+ }
+}
+
+} // namespace doris
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]