Skip to content

Commit 3fb9657

Browse files
tanjialiangfacebook-github-bot
authored andcommitted
Fix hash build memory over use (facebookincubator#10534)
Summary: For duplicate rows memory usage, currently under parallel join build conditions, each build operator reserves memory big enough to accommodate total number of rows across all hash tables from all build operators. Instead each build operator should only reserve memory enough for its own hash table rows. This optimization reduced hash build operator memory usage by 10x and we see total memory reduction of some queries reduced by 70%. Pull Request resolved: facebookincubator#10534 Reviewed By: zacw7 Differential Revision: D60131886 Pulled By: tanjialiang fbshipit-source-id: a8c1c777df557dfcfc754ef31164a116fdb917c3
1 parent 256d700 commit 3fb9657

File tree

3 files changed

+97
-77
lines changed

3 files changed

+97
-77
lines changed

velox/exec/HashBuild.cpp

Lines changed: 85 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,6 @@ bool HashBuild::finishHashBuild() {
678678

679679
std::vector<HashBuild*> otherBuilds;
680680
otherBuilds.reserve(peers.size());
681-
uint64_t numRows = table_->rows()->numRows();
682681
for (auto& peer : peers) {
683682
auto op = peer->findOperator(planNodeId());
684683
HashBuild* build = dynamic_cast<HashBuild*>(op);
@@ -696,13 +695,10 @@ bool HashBuild::finishHashBuild() {
696695
!build->stateCleared_,
697696
"Internal state for a peer is empty. It might have already"
698697
" been closed.");
699-
numRows += build->table_->rows()->numRows();
700698
}
701699
otherBuilds.push_back(build);
702700
}
703701

704-
ensureTableFits(numRows);
705-
706702
std::vector<std::unique_ptr<BaseHashTable>> otherTables;
707703
otherTables.reserve(peers.size());
708704
SpillPartitionSet spillPartitions;
@@ -723,11 +719,19 @@ bool HashBuild::finishHashBuild() {
723719
spiller->finishSpill(spillPartitions);
724720
}
725721
}
726-
bool allowDuplicateRows = table_->rows()->nextOffset() != 0;
727-
if (allowDuplicateRows) {
728-
ensureNextRowVectorFits(numRows, otherBuilds);
722+
723+
if (spiller_ != nullptr) {
724+
spiller_->finishSpill(spillPartitions);
725+
removeEmptyPartitions(spillPartitions);
729726
}
730727

728+
// TODO: Get accurate signal if parallel join build is going to be applied
729+
// from hash table. Currently there is still a chance inside hash table that
730+
// it might decide it is not going to trigger parallel join build.
731+
const bool allowParallelJoinBuild =
732+
!otherTables.empty() && spillPartitions.empty();
733+
ensureTableFits(otherBuilds, otherTables, allowParallelJoinBuild);
734+
731735
SCOPE_EXIT {
732736
// Make a guard to release the unused memory reservation since we have
733737
// finished the merged table build. The guard makes sure we release the
@@ -736,22 +740,13 @@ bool HashBuild::finishHashBuild() {
736740
// because when exceptions are thrown, other operator's cleanup mechanism
737741
// might already have finished.
738742
pool()->release();
739-
if (allowDuplicateRows) {
740-
for (auto* build : otherBuilds) {
741-
build->pool()->release();
742-
}
743+
for (auto* build : otherBuilds) {
744+
build->pool()->release();
743745
}
744746
};
745747

746-
if (spiller_ != nullptr) {
747-
spiller_->finishSpill(spillPartitions);
748-
removeEmptyPartitions(spillPartitions);
749-
}
750-
751-
// TODO: re-enable parallel join build with spilling triggered after
752-
// https://github.com/facebookincubator/velox/issues/3567 is fixed.
753-
const bool allowParallelJoinBuild =
754-
!otherTables.empty() && spillPartitions.empty();
748+
// TODO: Re-enable parallel join build with spilling triggered after
749+
// https://github.com/facebookincubator/velox/issues/3567 is fixed.
755750
CpuWallTiming timing;
756751
{
757752
// If there is a chance the join build is parallel, we suspend the driver
@@ -785,13 +780,16 @@ bool HashBuild::finishHashBuild() {
785780
return true;
786781
}
787782

788-
void HashBuild::ensureTableFits(uint64_t numRows) {
783+
void HashBuild::ensureTableFits(
784+
const std::vector<HashBuild*>& otherBuilds,
785+
const std::vector<std::unique_ptr<BaseHashTable>>& otherTables,
786+
bool isParallelJoin) {
789787
// NOTE: we don't need memory reservation if all the partitions have been
790788
// spilled as nothing need to be built.
791-
if (!spillEnabled() || spiller_ == nullptr || spiller_->isAllSpilled() ||
792-
numRows == 0) {
789+
if (!spillEnabled() || spiller_ == nullptr || spiller_->isAllSpilled()) {
793790
return;
794791
}
792+
VELOX_CHECK_EQ(otherBuilds.size(), otherTables.size());
795793

796794
// Test-only spill path.
797795
if (testingTriggerSpill(pool()->name())) {
@@ -800,58 +798,82 @@ void HashBuild::ensureTableFits(uint64_t numRows) {
800798
return;
801799
}
802800

803-
// NOTE: reserve a bit more memory to consider the extra memory used for
804-
// parallel table build operation.
805-
const uint64_t bytesToReserve = table_->estimateHashTableSize(numRows) * 1.1;
801+
TestValue::adjust("facebook::velox::exec::HashBuild::ensureTableFits", this);
802+
803+
const auto dupRowOverheadBytes = sizeof(char*) + sizeof(NextRowVector);
804+
805+
uint64_t totalNumRows{0};
806+
uint64_t lastBuildBytesToReserve{0};
807+
bool allowDuplicateRows{false};
806808
{
807-
Operator::ReclaimableSectionGuard guard(this);
808-
TestValue::adjust(
809-
"facebook::velox::exec::HashBuild::ensureTableFits", this);
810-
if (pool()->maybeReserve(bytesToReserve)) {
811-
return;
809+
std::lock_guard<std::mutex> l(mutex_);
810+
const auto numRows = table_->rows()->numRows();
811+
totalNumRows += numRows;
812+
allowDuplicateRows = table_->rows()->nextOffset() != 0;
813+
if (allowDuplicateRows) {
814+
lastBuildBytesToReserve += numRows * dupRowOverheadBytes;
812815
}
813816
}
814817

815-
LOG(WARNING) << "Failed to reserve " << succinctBytes(bytesToReserve)
816-
<< " for memory pool " << pool()->name()
817-
<< ", usage: " << succinctBytes(pool()->usedBytes())
818-
<< ", reservation: " << succinctBytes(pool()->reservedBytes());
819-
}
818+
for (auto i = 0; i < otherTables.size(); i++) {
819+
auto& otherTable = otherTables[i];
820+
VELOX_CHECK_NOT_NULL(otherTable);
821+
auto& otherBuild = otherBuilds[i];
822+
const auto& rowContainer = otherTable->rows();
823+
int64_t numRows{0};
824+
{
825+
std::lock_guard<std::mutex> l(otherBuild->mutex_);
826+
numRows = rowContainer->numRows();
827+
}
828+
if (numRows == 0) {
829+
continue;
830+
}
820831

821-
void HashBuild::ensureNextRowVectorFits(
822-
uint64_t numRows,
823-
const std::vector<HashBuild*>& otherBuilds) {
824-
if (!spillEnabled()) {
825-
return;
832+
totalNumRows += numRows;
833+
if (!allowDuplicateRows) {
834+
continue;
835+
}
836+
837+
const auto dupRowBytesToReserve = numRows * dupRowOverheadBytes;
838+
if (!isParallelJoin) {
839+
lastBuildBytesToReserve += dupRowBytesToReserve;
840+
continue;
841+
}
842+
843+
Operator::ReclaimableSectionGuard guard(otherBuild);
844+
auto* otherPool = otherBuild->pool();
845+
846+
// Reserve memory for memory allocations for next-row-vectors in
847+
// otherBuild operators if it is parallel join build. Otherwise all
848+
// next-row-vectors shall be allocated from the last build operator.
849+
if (!otherPool->maybeReserve(dupRowBytesToReserve)) {
850+
LOG(WARNING)
851+
<< "Failed to reserve " << succinctBytes(dupRowBytesToReserve)
852+
<< " for for duplicate row memory allocation from non-last memory pool "
853+
<< otherPool->name()
854+
<< ", usage: " << succinctBytes(otherPool->usedBytes())
855+
<< ", reservation: " << succinctBytes(otherPool->reservedBytes());
856+
}
826857
}
827858

828-
TestValue::adjust(
829-
"facebook::velox::exec::HashBuild::ensureNextRowVectorFits", this);
859+
if (totalNumRows == 0) {
860+
return;
861+
}
830862

831-
// The memory allocation for next-row-vectors may stuck in
832-
// 'SharedArbitrator::growCapacity' when memory arbitrating is also
833-
// triggered. Reserve memory for next-row-vectors to prevent this issue.
834-
auto bytesToReserve = numRows * (sizeof(char*) + sizeof(NextRowVector));
863+
// NOTE: reserve a bit more memory to consider the extra memory used for
864+
// parallel table build operation.
865+
lastBuildBytesToReserve += table_->estimateHashTableSize(totalNumRows) * 1.1;
835866
{
836867
Operator::ReclaimableSectionGuard guard(this);
837-
if (!pool()->maybeReserve(bytesToReserve)) {
838-
LOG(WARNING) << "Failed to reserve " << succinctBytes(bytesToReserve)
839-
<< " for memory pool " << pool()->name()
840-
<< ", usage: " << succinctBytes(pool()->usedBytes())
841-
<< ", reservation: "
842-
<< succinctBytes(pool()->reservedBytes());
843-
}
844-
}
845-
for (auto* build : otherBuilds) {
846-
Operator::ReclaimableSectionGuard guard(build);
847-
if (!build->pool()->maybeReserve(bytesToReserve)) {
848-
LOG(WARNING) << "Failed to reserve " << succinctBytes(bytesToReserve)
849-
<< " for memory pool " << build->pool()->name()
850-
<< ", usage: " << succinctBytes(build->pool()->usedBytes())
851-
<< ", reservation: "
852-
<< succinctBytes(build->pool()->reservedBytes());
868+
if (pool()->maybeReserve(lastBuildBytesToReserve)) {
869+
return;
853870
}
854871
}
872+
873+
LOG(WARNING) << "Failed to reserve " << succinctBytes(lastBuildBytesToReserve)
874+
<< " for last build memory pool " << pool()->name()
875+
<< ", usage: " << succinctBytes(pool()->usedBytes())
876+
<< ", reservation: " << succinctBytes(pool()->reservedBytes());
855877
}
856878

857879
void HashBuild::postHashBuildProcess() {

velox/exec/HashBuild.h

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -141,17 +141,12 @@ class HashBuild final : public Operator {
141141
// enabled.
142142
void ensureInputFits(RowVectorPtr& input);
143143

144-
// Invoked to ensure there is sufficient memory to build the join table with
145-
// the specified 'numRows' if spilling is enabled. The function throws to fail
146-
// the query if the memory reservation fails.
147-
void ensureTableFits(uint64_t numRows);
148-
149-
// Invoked to ensure there is sufficient memory to build the next-row-vectors
150-
// with the specified 'numRows' if spilling is enabled. The function throws to
151-
// fail the query if the memory reservation fails.
152-
void ensureNextRowVectorFits(
153-
uint64_t numRows,
154-
const std::vector<HashBuild*>& otherBuilds);
144+
// Invoked to ensure there is sufficient memory to build the join table. The
145+
// function throws to fail the query if the memory reservation fails.
146+
void ensureTableFits(
147+
const std::vector<HashBuild*>& otherBuilds,
148+
const std::vector<std::unique_ptr<BaseHashTable>>& otherTables,
149+
bool isParallelJoin);
155150

156151
// Invoked to compute spill partitions numbers for each row 'input' and spill
157152
// rows to spiller directly if the associated partition(s) is spilling. The

velox/exec/tests/HashJoinTest.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7027,7 +7027,7 @@ DEBUG_ONLY_TEST_F(HashJoinTest, exceptionDuringFinishJoinBuild) {
70277027
// We rely on the driver suspension before parallel join build to throw
70287028
// exceptions (suspension on an already terminated task throws).
70297029
SCOPED_TESTVALUE_SET(
7030-
"facebook::velox::exec::HashBuild::ensureNextRowVectorFits",
7030+
"facebook::velox::exec::HashBuild::ensureTableFits",
70317031
std::function<void(HashBuild*)>([&](HashBuild* buildOp) {
70327032
try {
70337033
VELOX_FAIL("Simulated failure");
@@ -7222,8 +7222,11 @@ DEBUG_ONLY_TEST_F(HashJoinTest, arbitrationTriggeredByEnsureJoinTableFit) {
72227222
.injectSpill(false)
72237223
.verifier([&](const std::shared_ptr<Task>& task, bool /*unused*/) {
72247224
auto opStats = toOperatorStats(task->taskStats());
7225-
ASSERT_GT(opStats.at("HashProbe").spilledBytes, 0);
7226-
ASSERT_GT(opStats.at("HashBuild").spilledBytes, 0);
7225+
ASSERT_GT(
7226+
opStats.at("HashBuild")
7227+
.runtimeStats["memoryArbitrationWallNanos"]
7228+
.count,
7229+
0);
72277230
})
72287231
.run();
72297232
}

0 commit comments

Comments
 (0)