@@ -561,6 +561,8 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk
561561
562562void RadixPartitionedHashTable::Combine (ExecutionContext &context, GlobalSinkState &gstate_p,
563563 LocalSinkState &lstate_p) const {
564+ // There is some defensive programming in here to try to avoid spurious issues
565+ // See duckdblabs/duckdb-internal#6818 for more information
564566 auto &gstate = gstate_p.Cast <RadixHTGlobalSinkState>();
565567 auto &lstate = lstate_p.Cast <RadixHTLocalSinkState>();
566568 if (!lstate.ht ) {
@@ -584,17 +586,28 @@ void RadixPartitionedHashTable::Combine(ExecutionContext &context, GlobalSinkSta
584586 }
585587
586588 auto guard = gstate.Lock ();
589+ if (gstate.finalized ) {
590+ throw InternalException (" RadixPartitionedHashTable: Combine called after Finalize!" );
591+ }
592+
587593 if (gstate.uncombined_data ) {
588594 gstate.uncombined_data ->Combine (*lstate.abandoned_data );
589595 } else {
590596 gstate.uncombined_data = std::move (lstate.abandoned_data );
591597 }
592598 gstate.stored_allocators .emplace_back (ht.GetAggregateAllocator ());
593599 gstate.stored_allocators_size += gstate.stored_allocators .back ()->AllocationSize ();
600+
601+ // Eagerly destroy the HT
602+ lstate.ht .reset ();
594603}
595604
596605void RadixPartitionedHashTable::Finalize (ClientContext &context, GlobalSinkState &gstate_p) const {
597606 auto &gstate = gstate_p.Cast <RadixHTGlobalSinkState>();
607+ auto guard = gstate.Lock ();
608+ if (gstate.finalized ) {
609+ throw InternalException (" RadixPartitionedHashTable: Finalize called again!" );
610+ }
598611
599612 if (gstate.uncombined_data ) {
600613 auto &uncombined_data = *gstate.uncombined_data ;
0 commit comments