Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the race between memory release and task reclaim #8086

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion velox/exec/SharedArbitrator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,10 @@ bool SharedArbitrator::growMemory(
<< " capacity to "
<< succinctBytes(requestor->capacity() + targetBytes)
<< " which exceeds its max capacity "
<< succinctBytes(requestor->maxCapacity());
<< succinctBytes(requestor->maxCapacity())
<< ", current capacity "
<< succinctBytes(requestor->capacity()) << ", request "
<< succinctBytes(targetBytes);
return false;
}

Expand Down
10 changes: 9 additions & 1 deletion velox/exec/Task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2590,7 +2590,15 @@ uint64_t Task::MemoryReclaimer::reclaim(
if (task->isCancelled()) {
return 0;
}
return memory::MemoryReclaimer::reclaim(pool, targetBytes, maxWaitMs, stats);
// Before reclaiming from its operators, first to check if there is any free
// capacity in the root after stopping this task.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed because memory could have been freed while we waited for the task to pause?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, and we didn't check the free memory after that.

const uint64_t shrunkBytes = pool->shrink(targetBytes);
if (shrunkBytes >= targetBytes) {
return shrunkBytes;
}
return shrunkBytes +
memory::MemoryReclaimer::reclaim(
pool, targetBytes - shrunkBytes, maxWaitMs, stats);
}

void Task::MemoryReclaimer::abort(
Expand Down
8 changes: 6 additions & 2 deletions velox/exec/tests/AggregationTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3098,13 +3098,15 @@ DEBUG_ONLY_TEST_F(AggregationTest, reclaimEmptyInput) {
}
auto* driver = values->testingOperatorCtx()->driver();
auto task = values->testingOperatorCtx()->task();
// Shrink all the capacity before reclaim.
task->pool()->shrink();
{
MemoryReclaimer::Stats stats;
SuspendedSection suspendedSection(driver);
task->pool()->reclaim(kMaxBytes, 0, stats);
ASSERT_EQ(stats.numNonReclaimableAttempts, 0);
ASSERT_GT(stats.reclaimExecTimeUs, 0);
ASSERT_GT(stats.reclaimedBytes, 0);
ASSERT_EQ(stats.reclaimedBytes, 0);
ASSERT_GT(stats.reclaimWaitTimeUs, 0);
}
static_cast<memory::MemoryPoolImpl*>(task->pool())
Expand Down Expand Up @@ -3168,13 +3170,15 @@ DEBUG_ONLY_TEST_F(AggregationTest, reclaimEmptyOutput) {
}
auto* driver = op->testingOperatorCtx()->driver();
auto task = op->testingOperatorCtx()->task();
// Shrink all the capacity before reclaim.
task->pool()->shrink();
{
MemoryReclaimer::Stats stats;
SuspendedSection suspendedSection(driver);
task->pool()->reclaim(kMaxBytes, 0, stats);
ASSERT_EQ(stats.numNonReclaimableAttempts, 0);
ASSERT_GT(stats.reclaimExecTimeUs, 0);
ASSERT_GT(stats.reclaimedBytes, 0);
ASSERT_EQ(stats.reclaimedBytes, 0);
ASSERT_GT(stats.reclaimWaitTimeUs, 0);
}
// Sets back the memory capacity to proceed the test.
Expand Down
53 changes: 53 additions & 0 deletions velox/exec/tests/SharedArbitratorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,7 @@ class SharedArbitrationTest : public exec::test::HiveConnectorTestBase {
AssertQueryBuilder(plan)
.spillDirectory(spillDirectory->path)
.config(core::QueryConfig::kSpillEnabled, "true")
.config(core::QueryConfig::kAggregationSpillEnabled, "false")
.config(core::QueryConfig::kWriterSpillEnabled, "true")
// Set 0 file writer flush threshold to always trigger flush in
// test.
Expand All @@ -654,6 +655,11 @@ class SharedArbitrationTest : public exec::test::HiveConnectorTestBase {
connector::hive::HiveConfig::
kOrcWriterMaxDictionaryMemorySession,
"1GB")
.connectorSessionProperty(
kHiveConnectorId,
connector::hive::HiveConfig::
kOrcWriterMaxDictionaryMemorySession,
"1GB")
.queryCtx(queryCtx)
.maxDrivers(numDrivers)
.copyResults(pool(), result.task);
Expand Down Expand Up @@ -2745,6 +2751,52 @@ DEBUG_ONLY_TEST_F(SharedArbitrationTest, tableWriteReclaimOnClose) {
waitForAllTasksToBeDeleted();
}

DEBUG_ONLY_TEST_F(SharedArbitrationTest, raceBetweenWriterCloseAndTaskReclaim) {
const uint64_t memoryCapacity = 512 * MB;
setupMemory(memoryCapacity);
std::vector<RowVectorPtr> vectors = newVectors(1'000, memoryCapacity / 8);
const auto expectedResult = runWriteTask(vectors, nullptr, 1, false).data;

std::shared_ptr<core::QueryCtx> queryCtx = newQueryCtx(memoryCapacity);

std::atomic_bool writerCloseWaitFlag{true};
folly::EventCount writerCloseWait;
std::atomic_bool taskReclaimWaitFlag{true};
folly::EventCount taskReclaimWait;
SCOPED_TESTVALUE_SET(
"facebook::velox::dwrf::Writer::flushStripe",
std::function<void(dwrf::Writer*)>(([&](dwrf::Writer* writer) {
writerCloseWaitFlag = false;
writerCloseWait.notifyAll();
taskReclaimWait.await([&]() { return !taskReclaimWaitFlag.load(); });
})));

SCOPED_TESTVALUE_SET(
"facebook::velox::exec::Task::requestPauseLocked",
std::function<void(Task*)>(([&](Task* /*unused*/) {
taskReclaimWaitFlag = false;
taskReclaimWait.notifyAll();
})));

std::thread queryThread([&]() {
const auto result =
runWriteTask(vectors, queryCtx, 1, true, expectedResult);
});

writerCloseWait.await([&]() { return !writerCloseWaitFlag.load(); });

// Creates a fake pool to trigger memory arbitration.
auto fakePool = queryCtx->pool()->addLeafChild(
"fakePool", true, FakeMemoryReclaimer::create());
ASSERT_TRUE(memoryManager_->growPool(
fakePool.get(),
arbitrator_->stats().freeCapacityBytes +
queryCtx->pool()->capacity() / 2));

queryThread.join();
waitForAllTasksToBeDeleted();
}

DEBUG_ONLY_TEST_F(SharedArbitrationTest, tableFileWriteError) {
const uint64_t memoryCapacity = 32 * MB;
setupMemory(memoryCapacity);
Expand Down Expand Up @@ -3626,6 +3678,7 @@ DEBUG_ONLY_TEST_F(SharedArbitrationTest, raceBetweenRaclaimAndJoinFinish) {
// spill after hash table built.
memory::MemoryReclaimer::Stats stats;
const uint64_t oldCapacity = joinQueryCtx->pool()->capacity();
task.load()->pool()->shrink();
task.load()->pool()->reclaim(1'000, 0, stats);
// If the last build memory pool is first child of its parent memory pool,
// then memory arbitration (or join node memory pool) will reclaim from the
Expand Down
Loading