From 21393c3fdea4a3db8a3cf5bb3caf69d0e4236547 Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 23 Nov 2026 17:02:03 +0000 Subject: [PATCH] Update vendored DuckDB sources to 3b3e55925f1 --- .../extension/parquet/parquet_statistics.cpp | 17 ++++ ...nerated_extension_loader_package_build.cpp | 8 +- .../catalog_entry/duck_table_entry.cpp | 2 +- .../common/row_operations/row_aggregate.cpp | 8 +- src/duckdb/src/common/types/vector.cpp | 1 + src/duckdb/src/common/vector/array_vector.cpp | 2 +- .../src/common/vector/dictionary_vector.cpp | 6 +- src/duckdb/src/common/vector/flat_vector.cpp | 2 +- src/duckdb/src/common/vector/list_vector.cpp | 2 +- .../src/common/vector/struct_vector.cpp | 2 +- .../vector_operations/scalar_executor.cpp | 15 ++-- .../common/vector_operations/vector_hash.cpp | 39 +++++---- src/duckdb/src/execution/join_hashtable.cpp | 13 ++- .../scanner/string_value_scanner.cpp | 18 +++-- .../function/table/version/pragma_version.cpp | 6 +- .../include/duckdb/common/types/vector.hpp | 1 + .../vector_operations/scalar_executor.hpp | 2 +- .../function/function_serialization.hpp | 19 +++-- .../src/include/duckdb/logging/log_type.hpp | 16 ++++ .../include/duckdb/storage/block_manager.hpp | 7 +- .../caching_file_system.hpp | 1 + .../storage/in_memory_block_manager.hpp | 3 +- .../storage/metadata/metadata_manager.hpp | 7 +- .../storage/single_file_block_manager.hpp | 19 ++++- .../duckdb/transaction/commit_state.hpp | 8 ++ .../duckdb/transaction/duck_transaction.hpp | 5 +- .../transaction/duck_transaction_manager.hpp | 18 ++++- src/duckdb/src/logging/log_manager.cpp | 1 + src/duckdb/src/logging/log_types.cpp | 27 +++++++ .../planner/binder/statement/bind_drop.cpp | 12 ++- src/duckdb/src/storage/checkpoint_manager.cpp | 9 ++- .../caching_file_system.cpp | 27 +++++++ .../src/storage/metadata/metadata_manager.cpp | 35 ++++++-- .../src/storage/single_file_block_manager.cpp | 74 ++++++++++++++--- src/duckdb/src/storage/storage_manager.cpp | 21 ++--- src/duckdb/src/transaction/commit_state.cpp | 22 +++++- .../src/transaction/duck_transaction.cpp | 2 +- .../transaction/duck_transaction_manager.cpp | 79 ++++++++++++++++++- 38 files changed, 452 insertions(+), 104 deletions(-) diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index c977788a4..6af317a3b 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -135,6 +135,16 @@ static unique_ptr CreateFloatingPointStats(const LogicalType &ty return stats.ToUnique(); } +//! Whether every non-NULL value of the column chunk is NaN, according to its nan_count and null_count +static bool AllValuesAreNaN(const duckdb_parquet::Statistics &parquet_stats, + optional_ptr column_chunk) { + if (!column_chunk || !parquet_stats.__isset.nan_count || !parquet_stats.__isset.null_count) { + return false; + } + const auto nan_count = parquet_stats.nan_count; + return nan_count > 0 && nan_count == column_chunk->meta_data.num_values - parquet_stats.null_count; +} + bool ParquetStatisticsUtils::CanHaveNaN(const duckdb_parquet::Statistics &parquet_stats, bool can_have_nan) { if (parquet_stats.__isset.nan_count) { return parquet_stats.nan_count != 0; @@ -570,6 +580,13 @@ unique_ptr ParquetStatisticsUtils::TransformParquetStatistics( return CreateNumericStats(type, schema, parquet_stats); case LogicalTypeId::FLOAT: case LogicalTypeId::DOUBLE: + if (AllValuesAreNaN(parquet_stats, column_chunk)) { + auto nan_stats = NumericStats::CreateUnknown(type); + auto nan_value = Value("nan").DefaultCastAs(type); + NumericStats::SetMin(nan_stats, nan_value); + NumericStats::SetMax(nan_stats, nan_value); + return nan_stats.ToUnique(); + } if (CanHaveNaN(parquet_stats, can_have_nan)) { // The column can contain NaN values - create stats without an upper max value, as NaN compares larger than // anything else and is not included in the Parquet min/max diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 5be930010..1001ddaf9 100644 --- a/src/duckdb/generated_extension_loader_package_build.cpp +++ b/src/duckdb/generated_extension_loader_package_build.cpp @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de descriptor->version = 1; descriptor->name = "core_functions"; descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS; - descriptor->api_version = "v2.1.0-alpha57135"; + descriptor->api_version = "v2.1.0-alpha57181"; descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init; return 0; } @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto descriptor->version = 1; descriptor->name = "parquet"; descriptor->extension_version = EXT_VERSION_PARQUET; - descriptor->api_version = "v2.1.0-alpha57135"; + descriptor->api_version = "v2.1.0-alpha57181"; descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init; return 0; } @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) { descriptor->version = 1; descriptor->name = "icu"; descriptor->extension_version = EXT_VERSION_ICU; - descriptor->api_version = "v2.1.0-alpha57135"; + descriptor->api_version = "v2.1.0-alpha57181"; descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init; return 0; } @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor) descriptor->version = 1; descriptor->name = "json"; descriptor->extension_version = EXT_VERSION_JSON; - descriptor->api_version = "v2.1.0-alpha57135"; + descriptor->api_version = "v2.1.0-alpha57181"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp index ceecad0c2..0f8fdd313 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp @@ -1486,7 +1486,7 @@ void DuckTableEntry::CommitAlter(string &column_name, CommitDropState &drop_stat } void DuckTableEntry::CommitDrop(CommitDropState &drop_state) { - storage->CommitDropTable(drop_state); + drop_state.DropTable(storage); } DataTable &DuckTableEntry::GetStorage() { diff --git a/src/duckdb/src/common/row_operations/row_aggregate.cpp b/src/duckdb/src/common/row_operations/row_aggregate.cpp index e787fe2b3..918bd2f34 100644 --- a/src/duckdb/src/common/row_operations/row_aggregate.cpp +++ b/src/duckdb/src/common/row_operations/row_aggregate.cpp @@ -81,8 +81,12 @@ void RowOperations::UpdateFilteredStates(RowOperationsState &state, AggregateFil return; } - Vector filtered_addresses(addresses, filter_data.true_sel, count); - filtered_addresses.Flatten(); + if (!state.addresses) { + state.addresses = make_uniq(LogicalType::POINTER); + } + auto &filtered_addresses = *state.addresses; + VectorOperations::Copy(addresses, filtered_addresses, filter_data.true_sel, count, 0, 0); + FlatVector::SetSize(filtered_addresses, count_t(count)); UpdateStates(state, aggr, filtered_addresses, filter_data.filtered_payload, arg_idx); } diff --git a/src/duckdb/src/common/types/vector.cpp b/src/duckdb/src/common/types/vector.cpp index ee5ee166b..b69898306 100644 --- a/src/duckdb/src/common/types/vector.cpp +++ b/src/duckdb/src/common/types/vector.cpp @@ -466,6 +466,7 @@ void Vector::ToUnifiedFormat(idx_t count, UnifiedVectorFormat &format) const { void Vector::ToUnifiedFormat(UnifiedVectorFormat &format) const { format.physical_type = GetType().InternalType(); + format.owned_sel = SelectionVector(); auto vtype = GetVectorType(); if (vtype != VectorType::FLAT_VECTOR && vtype != VectorType::CONSTANT_VECTOR && vtype != VectorType::DICTIONARY_VECTOR) { diff --git a/src/duckdb/src/common/vector/array_vector.cpp b/src/duckdb/src/common/vector/array_vector.cpp index 48e5fc796..80553ac02 100644 --- a/src/duckdb/src/common/vector/array_vector.cpp +++ b/src/duckdb/src/common/vector/array_vector.cpp @@ -184,7 +184,7 @@ void VectorArrayBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { format.sel = FlatVector::IncrementalSelectionVector(); } format.data = nullptr; - format.validity = validity; + format.validity.Initialize(validity.GetData(), validity.Capacity()); } void VectorArrayBuffer::CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, diff --git a/src/duckdb/src/common/vector/dictionary_vector.cpp b/src/duckdb/src/common/vector/dictionary_vector.cpp index 1df01cc01..3dd3f7eda 100644 --- a/src/duckdb/src/common/vector/dictionary_vector.cpp +++ b/src/duckdb/src/common/vector/dictionary_vector.cpp @@ -65,8 +65,7 @@ void DictionaryBuffer::VerifyInternal(const LogicalType &type, const SelectionVe } void DictionaryBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { - format.owned_sel.Initialize(sel_vector); - format.sel = &format.owned_sel; + format.sel = &sel_vector; auto &child = entry->data; if (child.GetVectorType() != VectorType::FLAT_VECTOR) { @@ -74,7 +73,8 @@ void DictionaryBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { entry->data.Flatten(); } format.data = FlatVector::GetData(entry->data); - format.validity = FlatVector::Validity(entry->data); + const auto &validity = FlatVector::Validity(entry->data); + format.validity.Initialize(validity.GetData(), validity.Capacity()); } buffer_ptr DictionaryBuffer::SliceWithCache(SelCache &cache, const LogicalType &type, diff --git a/src/duckdb/src/common/vector/flat_vector.cpp b/src/duckdb/src/common/vector/flat_vector.cpp index 4714709bd..9202f9d9c 100644 --- a/src/duckdb/src/common/vector/flat_vector.cpp +++ b/src/duckdb/src/common/vector/flat_vector.cpp @@ -260,7 +260,7 @@ void StandardVectorBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { format.sel = FlatVector::IncrementalSelectionVector(); } format.data = data_ptr; - format.validity = validity; + format.validity.Initialize(validity.GetData(), validity.Capacity()); } template diff --git a/src/duckdb/src/common/vector/list_vector.cpp b/src/duckdb/src/common/vector/list_vector.cpp index c2e2ca786..fcf045b92 100644 --- a/src/duckdb/src/common/vector/list_vector.cpp +++ b/src/duckdb/src/common/vector/list_vector.cpp @@ -164,7 +164,7 @@ void VectorListBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { format.sel = FlatVector::IncrementalSelectionVector(); } format.data = data_ptr; - format.validity = validity; + format.validity.Initialize(validity.GetData(), validity.Capacity()); } buffer_ptr VectorListBuffer::CreateBuffer(AllocatedData &&new_data, count_t count) const { diff --git a/src/duckdb/src/common/vector/struct_vector.cpp b/src/duckdb/src/common/vector/struct_vector.cpp index 7a518e4e9..992547293 100644 --- a/src/duckdb/src/common/vector/struct_vector.cpp +++ b/src/duckdb/src/common/vector/struct_vector.cpp @@ -195,7 +195,7 @@ void VectorStructBuffer::ToUnifiedFormat(UnifiedVectorFormat &format) const { format.sel = FlatVector::IncrementalSelectionVector(); } format.data = nullptr; - format.validity = validity; + format.validity.Initialize(validity.GetData(), validity.Capacity()); } void VectorStructBuffer::SetValue(const LogicalType &type, idx_t index, const Value &val) { diff --git a/src/duckdb/src/common/vector_operations/scalar_executor.cpp b/src/duckdb/src/common/vector_operations/scalar_executor.cpp index f1e010885..937a8670d 100644 --- a/src/duckdb/src/common/vector_operations/scalar_executor.cpp +++ b/src/duckdb/src/common/vector_operations/scalar_executor.cpp @@ -7,18 +7,21 @@ void ScalarExecutor::PrepareConstantResult(Vector &result) { FlatVector::ValidityMutable(result).SetValid(0); } -bool ScalarExecutor::PrepareGenericResultValidity(const UnifiedVectorFormat *formats, idx_t format_count, - Vector &result, idx_t count, bool preserve_result_validity, - bool adds_nulls) { +bool ScalarExecutor::PrepareGenericResultValidity(UnifiedVectorFormat *formats, idx_t format_count, Vector &result, + idx_t count, bool preserve_result_validity, bool adds_nulls) { + auto &result_validity = FlatVector::ValidityMutable(result); bool inputs_can_have_null = false; for (idx_t input_idx = 0; input_idx < format_count; input_idx++) { - if (formats[input_idx].validity.CanHaveNull()) { + auto &input_validity = formats[input_idx].validity; + if (input_validity.CanHaveNull()) { inputs_can_have_null = true; - break; + if (input_validity.GetData() == result_validity.GetData()) { + // Keep aliased input validity alive when resetting the result below. + input_validity.Initialize(result_validity); + } } } - auto &result_validity = FlatVector::ValidityMutable(result); if (inputs_can_have_null || !preserve_result_validity) { result_validity.Reset(count); } else if (adds_nulls && result_validity.CanHaveNull()) { diff --git a/src/duckdb/src/common/vector_operations/vector_hash.cpp b/src/duckdb/src/common/vector_operations/vector_hash.cpp index 664a52015..82326e07f 100644 --- a/src/duckdb/src/common/vector_operations/vector_hash.cpp +++ b/src/duckdb/src/common/vector_operations/vector_hash.cpp @@ -69,20 +69,24 @@ void TightLoopHash(const T *__restrict ldata, hash_t *__restrict result_data, co template void TemplatedLoopHash(const Vector &input, Vector &result, const SelectionVector *rsel, idx_t count) { - if (input.GetVectorType() == VectorType::CONSTANT_VECTOR) { + const auto &source = INPUT_IS_ALREADY_HASH ? DictionaryVector::GetCachedHashes(input) : input; + if (source.GetVectorType() == VectorType::CONSTANT_VECTOR) { result.SetVectorType(VectorType::CONSTANT_VECTOR); FlatVector::SetSize(result, count_t(count)); - auto ldata = ConstantVector::GetData(input); + auto ldata = ConstantVector::GetData(source); auto result_data = ConstantVector::GetData(result); *result_data = INPUT_IS_ALREADY_HASH ? CachedHashOp::Operation(*ldata) - : HashOp::Operation(*ldata, ConstantVector::IsNull(input)); + : HashOp::Operation(*ldata, ConstantVector::IsNull(source)); } else { result.SetVectorType(VectorType::FLAT_VECTOR); FlatVector::SetSize(result, count_t(count)); UnifiedVectorFormat idata; - input.ToUnifiedFormat(idata); + source.ToUnifiedFormat(idata); + if constexpr (INPUT_IS_ALREADY_HASH) { + idata.sel = &DictionaryVector::SelVector(input); + } if (idata.sel->IsSet()) { TightLoopHash(UnifiedVectorFormat::GetData(idata), @@ -416,16 +420,23 @@ static inline void TightLoopCombineHash(const T *__restrict ldata, hash_t *__res template void TemplatedLoopCombineHash(const Vector &input, Vector &hashes, const SelectionVector *rsel, idx_t count) { - if (input.GetVectorType() == VectorType::CONSTANT_VECTOR && hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { - auto ldata = ConstantVector::GetData(input); + const auto &source = INPUT_IS_ALREADY_HASH ? DictionaryVector::GetCachedHashes(input) : input; + if (source.GetVectorType() == VectorType::CONSTANT_VECTOR && + hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { + auto ldata = ConstantVector::GetData(source); auto hash_data = ConstantVector::GetData(hashes); auto other_hash = INPUT_IS_ALREADY_HASH ? CachedHashOp::Operation(*ldata) - : HashOp::Operation(*ldata, ConstantVector::IsNull(input)); + : HashOp::Operation(*ldata, ConstantVector::IsNull(source)); *hash_data = CombineHashScalar(*hash_data, other_hash); } else { UnifiedVectorFormat idata; - input.ToUnifiedFormat(idata); + source.ToUnifiedFormat(idata); + if constexpr (INPUT_IS_ALREADY_HASH) { + idata.sel = source.GetVectorType() == VectorType::CONSTANT_VECTOR + ? ConstantVector::ZeroSelectionVector(input.size(), idata.owned_sel) + : &DictionaryVector::SelVector(input); + } if (hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { // mix constant with non-constant, first get the constant value auto constant_hash = *ConstantVector::GetData(hashes); @@ -515,8 +526,7 @@ void CombineHashTypeSwitch(Vector &hashes, const Vector &input, const SelectionV void VectorOperations::Hash(const Vector &input, Vector &result, idx_t count) { if (input.GetVectorType() == VectorType::DICTIONARY_VECTOR && DictionaryVector::CanCacheHashes(input)) { - Vector input_hashes(DictionaryVector::GetCachedHashes(input), DictionaryVector::SelVector(input), count); - TemplatedLoopHash(input_hashes, result, nullptr, count); + TemplatedLoopHash(input, result, nullptr, count); } else { HashTypeSwitch(input, result, nullptr, count); } @@ -524,8 +534,7 @@ void VectorOperations::Hash(const Vector &input, Vector &result, idx_t count) { void VectorOperations::Hash(const Vector &input, Vector &result, const SelectionVector &sel, idx_t count) { if (input.GetVectorType() == VectorType::DICTIONARY_VECTOR && DictionaryVector::CanCacheHashes(input)) { - Vector input_hashes(DictionaryVector::GetCachedHashes(input), DictionaryVector::SelVector(input), count); - TemplatedLoopHash(input_hashes, result, &sel, count); + TemplatedLoopHash(input, result, &sel, count); } else { HashTypeSwitch(input, result, &sel, count); } @@ -537,8 +546,7 @@ void VectorOperations::Hash(const Vector &input, Vector &result) { void VectorOperations::CombineHash(Vector &hashes, const Vector &input, idx_t count) { if (input.GetVectorType() == VectorType::DICTIONARY_VECTOR && DictionaryVector::CanCacheHashes(input)) { - Vector input_hashes(DictionaryVector::GetCachedHashes(input), DictionaryVector::SelVector(input), count); - TemplatedLoopCombineHash(input_hashes, hashes, nullptr, count); + TemplatedLoopCombineHash(input, hashes, nullptr, count); } else { CombineHashTypeSwitch(hashes, input, nullptr, count); } @@ -556,8 +564,7 @@ void VectorOperations::CombineHash(Vector &hashes, const Vector &input) { void VectorOperations::CombineHash(Vector &hashes, const Vector &input, const SelectionVector &rsel, idx_t count) { if (input.GetVectorType() == VectorType::DICTIONARY_VECTOR && DictionaryVector::CanCacheHashes(input)) { - Vector input_hashes(DictionaryVector::GetCachedHashes(input), DictionaryVector::SelVector(input), count); - TemplatedLoopCombineHash(input_hashes, hashes, &rsel, count); + TemplatedLoopCombineHash(input, hashes, &rsel, count); } else { CombineHashTypeSwitch(hashes, input, &rsel, count); } diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index bc52ae94e..781b63b05 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -675,8 +675,9 @@ void JoinHashTable::EncodeDictSurvivingColumn(const DictSurvivingColumn &column, static_cast(build_col_idx)); } -static bool MarkJoinNullRows(const UnifiedVectorFormat &format, idx_t count, - optional_ptr rows_with_null = nullptr) { +static bool MarkJoinNullRows(const Vector &input, idx_t count, optional_ptr rows_with_null = nullptr) { + UnifiedVectorFormat format; + input.ToUnifiedFormat(format); if (format.validity.CannotHaveNull()) { return false; } @@ -696,16 +697,12 @@ static bool MarkJoinNullRows(const UnifiedVectorFormat &format, idx_t count, static bool MarkJoinKeysHaveNull(DataChunk &keys, optional_ptr rows_with_null = nullptr) { bool has_null = false; for (idx_t col_idx = 0; col_idx < keys.ColumnCount(); col_idx++) { - UnifiedVectorFormat format; if (keys.data[col_idx].GetType().IsNested()) { Vector comparison(LogicalType::BOOLEAN, keys.size()); VectorOperations::Equals(keys.data[col_idx], keys.data[col_idx], comparison); - comparison.ToUnifiedFormat(format); + has_null |= MarkJoinNullRows(comparison, keys.size(), rows_with_null); } else { - keys.data[col_idx].ToUnifiedFormat(format); - } - if (MarkJoinNullRows(format, keys.size(), rows_with_null)) { - has_null = true; + has_null |= MarkJoinNullRows(keys.data[col_idx], keys.size(), rows_with_null); } } return has_null; diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp index a4f18cbd2..a4e073c42 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp @@ -1573,6 +1573,10 @@ void StringValueScanner::ProcessOverBufferValue() { // the file ended inside a quoted value: record that before the value itself is added result.current_errors.Insert(UNTERMINATED_QUOTES, result.cur_col_id, result.chunk_col_id, result.last_position); } + // With a single column, a record separator read right after a state reset is an empty line only when it does not + // end an open row or comment + const bool single_column_empty_line = states.EmptyLine() && state_machine->dialect_options.num_cols == 1; + const bool empty_line = single_column_empty_line && result.cur_col_id == 0 && !result.comment; bool skip_value = false; if (result.projecting_columns) { if (result.cur_col_id < result.number_of_columns && !result.projected_columns[result.cur_col_id]) { @@ -1662,8 +1666,10 @@ void StringValueScanner::ProcessOverBufferValue() { } } } - if (states.EmptyLine() && state_machine->dialect_options.num_cols == 1) { - result.EmptyLine(result, iterator.pos.buffer_pos); + if (single_column_empty_line) { + if (empty_line) { + result.EmptyLine(result, iterator.pos.buffer_pos); + } } else if (!states.IsNotSet() && (!result.comment || !value.Empty())) { idx_t value_size = value.GetSize(); if (!removed_extra_delimiter_bytes) { @@ -1675,16 +1681,14 @@ void StringValueScanner::ProcessOverBufferValue() { } result.AddValueToVector(value.GetData(), value_size, true); } - } else { - if (states.EmptyLine() && state_machine->dialect_options.num_cols == 1) { - result.EmptyLine(result, iterator.pos.buffer_pos); - } + } else if (empty_line) { + result.EmptyLine(result, iterator.pos.buffer_pos); } if (states.NewRow() && !states.IsNotSet()) { if (result.IsCommentSet(result)) { result.UnsetComment(result, iterator.pos.buffer_pos); - } else { + } else if (!empty_line) { result.AddRowInternal(); } lines_read++; diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index e355d501a..4adf25a93 100644 --- a/src/duckdb/src/function/table/version/pragma_version.cpp +++ b/src/duckdb/src/function/table/version/pragma_version.cpp @@ -1,5 +1,5 @@ #ifndef DUCKDB_PATCH_VERSION -#define DUCKDB_PATCH_VERSION "0-alpha57135" +#define DUCKDB_PATCH_VERSION "0-alpha57181" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 1 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.1.0-alpha57135" +#define DUCKDB_VERSION "v2.1.0-alpha57181" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "620752ed3c" +#define DUCKDB_SOURCE_ID "3b3e55925f" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/types/vector.hpp b/src/duckdb/src/include/duckdb/common/types/vector.hpp index cf53f3f5b..3af9aa308 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector.hpp @@ -123,6 +123,7 @@ class Vector { //! Access to the individual vector elements can be performed through data_pointer[sel_idx[i]]/validity[sel_idx[i]] //! The most common vector types (flat, constant & dictionary) can be converted to the canonical format "for free" //! ToUnifiedFormat was originally called Orrify, as a tribute to Orri Erling who came up with it + //! Borrows source data and metadata: keep their storage and selection alive and stable until the final read. DUCKDB_API void ToUnifiedFormat(UnifiedVectorFormat &data) const; [[deprecated("RecursiveToUnifiedFormat no longer requires a count - use RecursiveToUnifiedFormat(input, data) " diff --git a/src/duckdb/src/include/duckdb/common/vector_operations/scalar_executor.hpp b/src/duckdb/src/include/duckdb/common/vector_operations/scalar_executor.hpp index a50c8f996..6fc447780 100644 --- a/src/duckdb/src/include/duckdb/common/vector_operations/scalar_executor.hpp +++ b/src/duckdb/src/include/duckdb/common/vector_operations/scalar_executor.hpp @@ -130,7 +130,7 @@ struct ScalarExecutor { //! Makes a reused result ready for the one-row generic path: like the constant path, a stale NULL does not survive DUCKDB_API static void PrepareConstantResult(Vector &result); - DUCKDB_API static bool PrepareGenericResultValidity(const UnifiedVectorFormat *formats, idx_t format_count, + DUCKDB_API static bool PrepareGenericResultValidity(UnifiedVectorFormat *formats, idx_t format_count, Vector &result, idx_t count, bool preserve_result_validity, bool adds_nulls); diff --git a/src/duckdb/src/include/duckdb/function/function_serialization.hpp b/src/duckdb/src/include/duckdb/function/function_serialization.hpp index 393520f11..766c21bfd 100644 --- a/src/duckdb/src/include/duckdb/function/function_serialization.hpp +++ b/src/duckdb/src/include/duckdb/function/function_serialization.hpp @@ -21,16 +21,21 @@ class ClientContext; class FunctionSerializer { private: + //! The name a reader looks the function up with: a function that does not say where it lives is a built-in one + static QualifiedName ResolveQualifiedName(const QualifiedName &qname) { + if (qname.Schema().empty()) { + return QualifiedName(qname.Catalog().empty() ? Identifier::SystemCatalog() : qname.Catalog(), + Identifier::DefaultSchema(), qname.Name()); + } + return qname.Catalog().empty() ? qname.WithCatalog(Identifier::SystemCatalog()) : qname; + } + static QualifiedName DeserializeQualifiedName(Deserializer &deserializer, Identifier name) { auto catalog = deserializer.ReadPropertyWithDefault(505, "catalog_name"); auto schema = deserializer.ReadPropertyWithDefault(506, "schema_name"); auto qname = deserializer.ReadPropertyWithExplicitDefault(507, "qname", QualifiedName()); if (!qname.Name().empty()) { - if (qname.Schema().empty()) { - return QualifiedName(qname.Catalog().empty() ? Identifier::SystemCatalog() : qname.Catalog(), - Identifier::DefaultSchema(), qname.Name()); - } - return qname.Catalog().empty() ? qname.WithCatalog(Identifier::SystemCatalog()) : qname; + return ResolveQualifiedName(qname); } return QualifiedName(catalog.empty() ? Identifier::SystemCatalog() : catalog, schema.empty() ? Identifier::DefaultSchema() : schema, std::move(name)); @@ -89,7 +94,9 @@ class FunctionSerializer { } if (serializer.ShouldSerialize(StorageVersion::V2_0_0)) { - serializer.WriteProperty(507, "qname", function.GetQualifiedName()); + // Written the way it is read back, so that a function serializes to the same bytes before and after a + // round trip: a plan and its copy have to compare equal as common subplans + serializer.WriteProperty(507, "qname", ResolveQualifiedName(function.GetQualifiedName())); } else { serializer.WritePropertyWithDefault(505, "catalog_name", function.GetCatalogName(), Identifier()); serializer.WritePropertyWithDefault(506, "schema_name", function.GetSchemaName(), Identifier()); diff --git a/src/duckdb/src/include/duckdb/logging/log_type.hpp b/src/duckdb/src/include/duckdb/logging/log_type.hpp index c5333d82b..22dad84ac 100644 --- a/src/duckdb/src/include/duckdb/logging/log_type.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_type.hpp @@ -218,6 +218,22 @@ class ReadAheadBudgetLogType : public LogType { static string ConstructLogMessage(idx_t pending_bytes, idx_t budget_bytes, idx_t active_jobs); }; +class ExternalFileCacheLogType : public LogType { +public: + static constexpr const char *NAME = "ExternalFileCache"; + static constexpr LogLevel LEVEL = LogLevel::LOG_TRACE; + static constexpr const char *READ_EVENT = "READ"; + static constexpr const char *HIT_EVENT = "HIT"; + static constexpr const char *MISS_EVENT = "MISS"; + + ExternalFileCacheLogType(); + + static LogicalType GetLogType(); + + //! A read through the cache (READ), or one of its blocks served from the cache (HIT) or the file (MISS) + static string ConstructLogMessage(const string &path, const char *event, idx_t bytes, idx_t pos); +}; + class ProgressVerificationLogType : public LogType { public: static constexpr const char *NAME = "ProgressVerification"; diff --git a/src/duckdb/src/include/duckdb/storage/block_manager.hpp b/src/duckdb/src/include/duckdb/storage/block_manager.hpp index 96a790e67..0e73608f1 100644 --- a/src/duckdb/src/include/duckdb/storage/block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_manager.hpp @@ -85,7 +85,12 @@ class BlockManager { Write(block, block.id); } //! Write the header of a checkpoint with the given bound; should be the final step of a checkpoint - virtual void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) = 0; + //! What the header frees waits for the transactions that started before read_stamp, if any are active + virtual void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, + transaction_t read_stamp, transaction_t lowest_active_start) = 0; + //! Lets the blocks be reused that headers freed before every active transaction started + virtual void ReuseFreedBlocks(transaction_t lowest_active_start) { + } //! Returns the number of total blocks virtual idx_t TotalBlocks() = 0; diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index 80cc836b7..ff2872967 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -82,6 +82,7 @@ struct CachingFileHandle { DUCKDB_API bool IsCacheReuseProhibited(); //! Get some properties of the file DUCKDB_API string GetPath() const; + DUCKDB_API optional_ptr GetOpener() const; DUCKDB_API idx_t GetFileSize(); DUCKDB_API timestamp_t GetLastModifiedTime(); DUCKDB_API string GetVersionTag(); diff --git a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp index c46851c65..f07174786 100644 --- a/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/in_memory_block_manager.hpp @@ -65,7 +65,8 @@ class InMemoryBlockManager : public BlockManager { void Write(QueryContext context, FileBuffer &block, block_id_t block_id) override { throw InternalException("Cannot perform IO in in-memory database - Write with client context!"); } - void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) override { + void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, + transaction_t lowest_active_start) override { throw InternalException("Cannot perform IO in in-memory database - WriteHeader!"); } bool InMemory() override { diff --git a/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp b/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp index 932d0fbc5..ab92ae13d 100644 --- a/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/metadata/metadata_manager.hpp @@ -30,6 +30,8 @@ struct MetadataBlock { shared_ptr block; block_id_t block_id; vector free_blocks; + //! The blocks that are free on disk but cannot be reused yet, as a mask + idx_t pending_reuse; atomic dirty; void Write(WriteStream &sink); @@ -83,7 +85,10 @@ class MetadataManager { bool BlockIsModified(const MetaBlockPointer &ptr); bool BlockHasBeenCleared(const MetaBlockPointer &ptr); - void MarkBlocksAsModified(); + //! Frees the blocks the checkpoint no longer uses. With readers, returns them instead, for ReuseFreedBlocks + unordered_map MarkBlocksAsModified(bool has_readers); + //! Lets blocks that MarkBlocksAsModified returned be reused + void ReuseFreedBlocks(const unordered_map &freed_blocks); void ClearModifiedBlocks(const vector &pointers); //! Sets the storage version of the file, which decides whether keeping a block also keeps its next block void SetStorageVersion(StorageVersion storage_version); diff --git a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp index 9cd500b8d..3e2db79ba 100644 --- a/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/single_file_block_manager.hpp @@ -16,6 +16,8 @@ #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/set.hpp" +#include "duckdb/common/map.hpp" +#include "duckdb/common/atomic.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/main/config.hpp" #include "duckdb/common/encryption_functions.hpp" @@ -119,7 +121,9 @@ class SingleFileBlockManager : public BlockManager { //! Write the block to disk. void Write(QueryContext context, FileBuffer &buffer, block_id_t block_id) override; //! Write the header to disk, this is the final step of the checkpointing process - void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) override; + void WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, transaction_t read_stamp, + transaction_t lowest_active_start) override; + void ReuseFreedBlocks(transaction_t lowest_active_start) override; //! Sync changes to the underlying file void FileSync() override; //! Truncate the underlying database file after a checkpoint @@ -202,6 +206,13 @@ class SingleFileBlockManager : public BlockManager { //! Returns true, if the block is in the free list. Takes the lock (verification only). bool BlockIsFreeListed(block_id_t block_id); +private: + //! What a header freed: blocks, and metadata blocks as a mask per storage block + struct FreedByHeader { + vector blocks; + unordered_map metadata_blocks; + }; + private: AttachedDatabase &db; //! The active DatabaseHeader, either 0 (h1) or 1 (h2) @@ -224,6 +235,12 @@ class SingleFileBlockManager : public BlockManager { unordered_map multi_use_blocks; //! The list of blocks that are no longer in-use, but cannot be re-used until the next checkpoint unordered_set modified_blocks; + //! The list of blocks that a header freed, but cannot yet be re-used because an older transaction may read them + unordered_set free_blocks_pending_reuse; + //! What the headers freed, by the start time before which a transaction may still read it + map pending_reuse_batches; + //! The lowest stamp in pending_reuse_batches, MAX_TRANSACTION_ID if it is empty: readable without the lock + atomic lowest_pending_reuse_stamp {MAX_TRANSACTION_ID}; //! The current meta block id idx_t meta_block; //! The current maximum block id, this id will be given away first after the free_list runs out diff --git a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp index 8a081c1ce..4d394df9b 100644 --- a/src/duckdb/src/include/duckdb/transaction/commit_state.hpp +++ b/src/duckdb/src/include/duckdb/transaction/commit_state.hpp @@ -22,6 +22,7 @@ class CatalogEntry; class TableIndexList; class DataChunk; class DuckTransaction; +class DuckTransactionManager; class WriteAheadLog; class ClientContext; @@ -48,12 +49,18 @@ class CommitDropState { public: //! Register an on-disk block to mark as modified during FinalizeCommit. void DropBlock(block_id_t block_id); + //! Register a dropped table, whose on-disk blocks are registered when the commit is finalized. + void DropTable(shared_ptr table); + //! Registers the on-disk blocks of dropped tables. Marks nothing, so a failure leaves nothing freed + void FreeTables(const vector> &tables); //! Register an index to be removed from a table's index list during FinalizeCommit. Index removal will drop in //! memory index data and also marks all blocks on disk as free blocks allowing for reclamation. Block marking for //! indexes is handled implicitly along destruction paths for index memory. void RemoveIndex(TableIndexList &indexes, idx_t index_oid); //! Finalize accumulated block marks and index removals. void FinalizeCommit(); + //! Finalize a commit: also frees the dropped tables, or hands them over to a running checkpoint. + void FinalizeCommit(DuckTransactionManager &transaction_manager); //! True if no work has been queued. bool Empty() const; @@ -61,6 +68,7 @@ class CommitDropState { optional_ptr block_manager; vector dropped_block_ids; vector pending_index_removals; + vector> dropped_tables; }; struct IndexDataRemover { diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp index 28c86fab6..3b16e70f2 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction.hpp @@ -116,6 +116,9 @@ class DuckTransaction : public Transaction { void SetIsCheckpointTransaction() { is_checkpoint_transaction = true; } + bool IsCheckpointTransaction() const { + return is_checkpoint_transaction; + } private: //! The undo buffer is used to store old versions of rows that are updated @@ -132,7 +135,7 @@ class DuckTransaction : public Transaction { //! Map of all sequences that were used during the transaction and the value they had in this transaction reference_map_t> sequence_usage; //! Flag to prevent auto-checkpointing inside a checkpoint transaction. - bool is_checkpoint_transaction = false; + atomic is_checkpoint_transaction {false}; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp b/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp index 0a7912cfc..7123bc70c 100644 --- a/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp +++ b/src/duckdb/src/include/duckdb/transaction/duck_transaction_manager.hpp @@ -16,6 +16,7 @@ #include namespace duckdb { +class DataTable; class DuckTransactionManager; class DuckTransaction; struct UndoBufferProperties; @@ -67,7 +68,12 @@ class DuckTransactionManager : public TransactionManager { return ++next_checkpoint_id; } void SetActiveCheckpoint(idx_t checkpoint_id); - void ResetActiveCheckpoint(); + //! Ends the checkpoint. If it succeeded, frees the tables that drops handed over to it + void ResetActiveCheckpoint(bool checkpoint_succeeded); + //! Hands dropped tables over to the running checkpoint, which frees them. False if none runs: the commit does + bool DeferDroppedTables(const vector> &tables); + //! The next start time, and the earliest of the active transactions: the same if none, 0 if a cleanup waits + void GetStartTimes(transaction_t &next_start, transaction_t &lowest_active_start); bool IsDuckTransactionManager() override { return true; @@ -130,6 +136,10 @@ class DuckTransactionManager : public TransactionManager { bool HasOtherTransactions(DuckTransaction &transaction); void CleanupTransactions(); + //! Lets the block manager reuse the blocks that checkpoints freed before every active transaction started + void ReuseFreedBlocks(transaction_t lowest_start) noexcept; + //! The earliest start time of the active transactions, checkpoints aside. Caller holds the transaction lock + transaction_t LowestActiveStart(); //! Whether a commit that needed a WAL sync is still in its commit path, possibly inside SyncUpTo bool HasUnsyncedCommits(); @@ -150,6 +160,12 @@ class DuckTransactionManager : public TransactionManager { //! The lowest bound any active transaction reads at. A version preceding it is visible to //! every active transaction, so whatever it supersedes can be cleaned up or compacted atomic lowest_visibility_bound; + //! Guards the dropped tables that are handed over to a checkpoint + mutex deferred_tables_lock; + //! The dropped tables that the running checkpoint frees once it has written its header + vector> deferred_tables; + //! The lowest start time of the transactions that stayed active when the last one ended, checkpoints aside + atomic lowest_remaining_start; //! The last commit timestamp atomic last_commit; //! The currently active checkpoint, zero when none is running diff --git a/src/duckdb/src/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index 34b8abe9b..83e79c360 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -342,6 +342,7 @@ void LogManager::RegisterDefaultLogTypes() { RegisterLogType(make_uniq()); RegisterLogType(make_uniq()); RegisterLogType(make_uniq()); + RegisterLogType(make_uniq()); RegisterLogType(make_uniq()); RegisterLogType(make_uniq()); } diff --git a/src/duckdb/src/logging/log_types.cpp b/src/duckdb/src/logging/log_types.cpp index 21c5844b1..74a0bd9f6 100644 --- a/src/duckdb/src/logging/log_types.cpp +++ b/src/duckdb/src/logging/log_types.cpp @@ -25,6 +25,7 @@ constexpr LogLevel AdaptiveFilterLogType::LEVEL; constexpr LogLevel ParquetPrefetchLogType::LEVEL; constexpr LogLevel AsyncTaskScheduleLogType::LEVEL; constexpr LogLevel ReadAheadBudgetLogType::LEVEL; +constexpr LogLevel ExternalFileCacheLogType::LEVEL; constexpr LogLevel ProgressVerificationLogType::LEVEL; //===--------------------------------------------------------------------===// @@ -589,6 +590,32 @@ string ReadAheadBudgetLogType::ConstructLogMessage(idx_t pending_bytes, idx_t bu return Value::STRUCT(std::move(child_list)).ToString(); } +//===--------------------------------------------------------------------===// +// ExternalFileCacheLogType +//===--------------------------------------------------------------------===// +ExternalFileCacheLogType::ExternalFileCacheLogType() : LogType(NAME, LEVEL, GetLogType()) { +} + +LogicalType ExternalFileCacheLogType::GetLogType() { + child_list_t child_list = { + {"path", LogicalType::VARCHAR}, + {"event", LogicalType::VARCHAR}, + {"bytes", LogicalType::BIGINT}, + {"pos", LogicalType::BIGINT}, + }; + return LogicalType::STRUCT(child_list); +} + +string ExternalFileCacheLogType::ConstructLogMessage(const string &path, const char *event, idx_t bytes, idx_t pos) { + child_list_t child_list = { + {"path", Value(path)}, + {"event", Value(event)}, + {"bytes", Value::BIGINT(NumericCast(bytes))}, + {"pos", Value::BIGINT(NumericCast(pos))}, + }; + return Value::STRUCT(std::move(child_list)).ToString(); +} + //===--------------------------------------------------------------------===// // ProgressVerificationLogType //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/planner/binder/statement/bind_drop.cpp b/src/duckdb/src/planner/binder/statement/bind_drop.cpp index 2127c2e2b..6e578585b 100644 --- a/src/duckdb/src/planner/binder/statement/bind_drop.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_drop.cpp @@ -9,6 +9,7 @@ #include "duckdb/parser/parsed_data/extra_drop_info.hpp" #include "duckdb/parser/tableref/basetableref.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/storage/data_table.hpp" #include "duckdb/storage/storage_extension.hpp" namespace duckdb { @@ -99,7 +100,16 @@ BoundStatement Binder::Bind(DropStatement &stmt) { } // keep the entry's full (possibly nested) schema path so execution navigates the same schema stmt.info->SetQualifiedName(entry->ParentSchema().GetQualifiedName(stmt.info->GetQualifiedName().Name())); - properties.RegisterDBModify(entry->ParentCatalog(), context, stmt.info->GetModifications()); + auto modifications = stmt.info->GetModifications(); + // FIXME: temporary, until the drops that involve indexes run alongside checkpoints as well + if (entry->type == CatalogType::TABLE_ENTRY && !stmt.info->cascade) { + auto &table = entry->Cast(); + if (table.IsDuckTable() && !table.GetStorage().HasIndexes()) { + // no modification type: DuckTransaction::SetModifications then takes no checkpoint lock for the drop + modifications = DatabaseModificationType(); + } + } + properties.RegisterDBModify(entry->ParentCatalog(), context, modifications); break; } case CatalogType::SECRET_ENTRY: { diff --git a/src/duckdb/src/storage/checkpoint_manager.cpp b/src/duckdb/src/storage/checkpoint_manager.cpp index bbf7295b2..0d070b48e 100644 --- a/src/duckdb/src/storage/checkpoint_manager.cpp +++ b/src/duckdb/src/storage/checkpoint_manager.cpp @@ -52,7 +52,7 @@ ActiveCheckpointWrapper::ActiveCheckpointWrapper(optional_ptr che ActiveCheckpointWrapper::~ActiveCheckpointWrapper() { // This happens on failure before we commit the transaction. if (active) { - transaction_manager.ResetActiveCheckpoint(); + transaction_manager.ResetActiveCheckpoint(false); } if (checkpoint_transaction) { // only a checkpoint started by a connection has a checkpoint transaction @@ -85,7 +85,7 @@ void ActiveCheckpointWrapper::Begin(CheckpointOptions &options) { } void ActiveCheckpointWrapper::Commit() { - transaction_manager.ResetActiveCheckpoint(); + transaction_manager.ResetActiveCheckpoint(true); active = false; if (!checkpoint_transaction) { return; @@ -336,7 +336,10 @@ void SingleFileCheckpointWriter::CreateCheckpoint() { header.meta_block = meta_block.block_pointer; header.block_alloc_size = block_manager.GetBlockAllocSize(); header.vector_size = STANDARD_VECTOR_SIZE; - block_manager.WriteHeader(QueryContext(GetContext()), header, options.visibility_bound); + transaction_t read_stamp, lowest_active_start; + transaction_manager.GetStartTimes(read_stamp, lowest_active_start); + block_manager.WriteHeader(QueryContext(GetContext()), header, options.visibility_bound, read_stamp, + lowest_active_start); auto debug_verify_blocks = Settings::Get(db.GetDatabase()); if (debug_verify_blocks) { diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 017ccbc50..856d3aa5d 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -7,6 +7,8 @@ #include "duckdb/common/enums/memory_tag.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/file_system.hpp" +#include "duckdb/logging/log_type.hpp" +#include "duckdb/logging/logger.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/parallel/task_executor.hpp" @@ -69,6 +71,19 @@ void TightenCacheDeadline(optional &cached, const optionalnr_bytes) == block->checksum); #endif + const idx_t nr_bytes = block->nr_bytes; result_pin = std::move(pin); + lk.unlock(); + LogCacheEvent(context, buffer_manager.GetDatabase(), caching_file_handle, + ExternalFileCacheLogType::HIT_EVENT, nr_bytes, block->location); return; } // Evicted by buffer manager, need to re-fetch @@ -118,6 +137,8 @@ class FetchBlockTask : public BaseExecutorTask { auto buf = ExternalFileCache::AllocateCacheBuffer(buffer_manager, caching_file_handle.GetPath(), to_read); caching_file_handle.ReadAndRecord(context, buf.GetDataMutable(), to_read, offset); + LogCacheEvent(context, buffer_manager.GetDatabase(), caching_file_handle, + ExternalFileCacheLogType::MISS_EVENT, to_read, offset); const bool share_block = !caching_file_handle.IsCacheReuseProhibited(); lk.lock(); @@ -432,6 +453,8 @@ FileBufferHandleGroup CachingFileHandle::Read(const idx_t nr_bytes, const idx_t if (location >= file_size) { return FileBufferHandleGroup(); } + LogCacheEvent(context, db, *this, ExternalFileCacheLogType::READ_EVENT, MinValue(nr_bytes, file_size - location), + location); const idx_t max_block_size = external_file_cache.GetCacheMaxBlockSize(current_cached_file->path); const idx_t min_block_size = MinValue(external_file_cache.GetCacheMinBlockSize(current_cached_file->path), max_block_size); @@ -558,6 +581,10 @@ string CachingFileHandle::GetPath() const { return path.path; } +optional_ptr CachingFileHandle::GetOpener() const { + return opener; +} + idx_t CachingFileHandle::GetFileSize() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); diff --git a/src/duckdb/src/storage/metadata/metadata_manager.cpp b/src/duckdb/src/storage/metadata/metadata_manager.cpp index ac6ca4efe..ac38cf2bd 100644 --- a/src/duckdb/src/storage/metadata/metadata_manager.cpp +++ b/src/duckdb/src/storage/metadata/metadata_manager.cpp @@ -9,13 +9,14 @@ namespace duckdb { -MetadataBlock::MetadataBlock() : block_id(INVALID_BLOCK), dirty(false) { +MetadataBlock::MetadataBlock() : block_id(INVALID_BLOCK), pending_reuse(0), dirty(false) { } -MetadataBlock::MetadataBlock(MetadataBlock &&other) noexcept : dirty(false) { +MetadataBlock::MetadataBlock(MetadataBlock &&other) noexcept : pending_reuse(0), dirty(false) { std::swap(block, other.block); std::swap(block_id, other.block_id); std::swap(free_blocks, other.free_blocks); + std::swap(pending_reuse, other.pending_reuse); auto dirty_val = dirty.load(); dirty = other.dirty.load(); other.dirty = dirty_val; @@ -25,6 +26,7 @@ MetadataBlock &MetadataBlock::operator=(MetadataBlock &&other) noexcept { std::swap(block, other.block); std::swap(block_id, other.block_id); std::swap(free_blocks, other.free_blocks); + std::swap(pending_reuse, other.pending_reuse); auto dirty_val = dirty.load(); dirty = other.dirty.load(); other.dirty = dirty_val; @@ -328,6 +330,7 @@ void MetadataManager::Flush(QueryContext context) { } void MetadataManager::Write(WriteStream &sink) { + lock_guard guard(block_lock); sink.Write(blocks.size()); for (auto &kv : blocks) { kv.second.Write(sink); @@ -356,7 +359,8 @@ void MetadataManager::Read(ReadStream &source) { void MetadataBlock::Write(WriteStream &sink) { sink.Write(block_id); - sink.Write(FreeBlocksToInteger()); + // the blocks that wait for older transactions are free on disk + sink.Write(FreeBlocksToInteger() | pending_reuse); } idx_t MetadataManager::GetMetadataBlockSize() const { @@ -401,8 +405,9 @@ void MetadataBlock::FreeBlocksFromInteger(idx_t free_list) { free_blocks = BlocksFromInteger(free_list); } -void MetadataManager::MarkBlocksAsModified() { +unordered_map MetadataManager::MarkBlocksAsModified(bool has_readers) { unique_lock guard(block_lock); + unordered_map freed_blocks; // for any blocks that were modified in the last checkpoint - set them to free blocks currently for (auto &kv : modified_blocks) { auto block_id = kv.first; @@ -410,6 +415,12 @@ void MetadataManager::MarkBlocksAsModified() { auto entry = blocks.find(block_id); D_ASSERT(entry != blocks.end()); auto &block = entry->second; + if (has_readers && modified_list != 0) { + // free on disk only: reused once those transactions have ended + block.pending_reuse |= modified_list; + freed_blocks[block_id] = modified_list; + continue; + } idx_t current_free_blocks = block.FreeBlocksToInteger(); // merge the current set of free blocks with the modified blocks idx_t new_free_blocks = current_free_blocks | modified_list; @@ -430,10 +441,24 @@ void MetadataManager::MarkBlocksAsModified() { for (auto &kv : blocks) { auto &block = kv.second; - idx_t free_list = block.FreeBlocksToInteger(); + idx_t free_list = block.FreeBlocksToInteger() | block.pending_reuse; idx_t occupied_list = ~free_list; modified_blocks[block.block_id] = occupied_list; } + return freed_blocks; +} + +void MetadataManager::ReuseFreedBlocks(const unordered_map &freed_blocks) { + lock_guard guard(block_lock); + for (auto &freed : freed_blocks) { + auto entry = blocks.find(freed.first); + if (entry == blocks.end()) { + throw InternalException("ReuseFreedBlocks - Block id %llu not found in blocks", freed.first); + } + auto &block = entry->second; + block.FreeBlocksFromInteger(block.FreeBlocksToInteger() | freed.second); + block.pending_reuse &= ~freed.second; + } } void MetadataManager::ClearModifiedBlocks(const vector &pointers) { diff --git a/src/duckdb/src/storage/single_file_block_manager.cpp b/src/duckdb/src/storage/single_file_block_manager.cpp index 1a388e55b..df2b0a5c2 100644 --- a/src/duckdb/src/storage/single_file_block_manager.cpp +++ b/src/duckdb/src/storage/single_file_block_manager.cpp @@ -906,7 +906,7 @@ void SingleFileBlockManager::LoadFreeList(QueryContext context) { multi_use_blocks[block_id] = usage_count; } GetMetadataManager().Read(reader); - GetMetadataManager().MarkBlocksAsModified(); + GetMetadataManager().MarkBlocksAsModified(false); } bool SingleFileBlockManager::IsRootBlock(MetaBlockPointer root) { @@ -1011,7 +1011,8 @@ void SingleFileBlockManager::MarkBlockAsModified(block_id_t block_id) { if (modified_blocks.find(block_id) != modified_blocks.end()) { throw InternalException("MarkBlockAsModified called with already modified block id %d", block_id); } - if (free_list.find(block_id) != free_list.end()) { + if (free_list.find(block_id) != free_list.end() || + free_blocks_pending_reuse.find(block_id) != free_blocks_pending_reuse.end()) { throw InternalException("MarkBlockAsModified called with already freed block id %d", block_id); } auto newly_used_entry = newly_used_blocks.find(block_id); @@ -1055,6 +1056,9 @@ void SingleFileBlockManager::VerifyBlocks(const unordered_map max_block); } referenced_blocks.insert(block.first); + if (free_blocks_pending_reuse.find(block.first) != free_blocks_pending_reuse.end()) { + throw InternalException("Block %lld was used, but a header lists it as free", block.first); + } if (block.second > 1) { // multi-use block auto entry = multi_use_blocks.find(block.first); @@ -1084,6 +1088,9 @@ void SingleFileBlockManager::VerifyBlocks(const unordered_map for (auto &free_block : free_blocks_in_use) { referenced_blocks.insert(free_block); } + for (auto &free_block : free_blocks_pending_reuse) { + referenced_blocks.insert(free_block); + } if (referenced_blocks.size() != NumericCast(max_block)) { // not all blocks are accounted for string missing_blocks; @@ -1298,8 +1305,8 @@ vector SingleFileBlockManager::GetFreeListBlocks() { idx_t multi_use_blocks_count; { lock_guard guard(single_file_block_lock); - free_list_count = - free_list.size() + modified_blocks.size() + free_blocks_in_use.size() + newly_used_blocks.size(); + free_list_count = free_list.size() + modified_blocks.size() + free_blocks_in_use.size() + + newly_used_blocks.size() + free_blocks_pending_reuse.size(); multi_use_blocks_count = multi_use_blocks.size(); } auto free_list_size = sizeof(uint64_t) + sizeof(block_id_t) * free_list_count; @@ -1359,13 +1366,18 @@ bool SingleFileBlockManager::AddFreeBlock(unique_lock &lock, block_id_t b lock.lock(); return false; } -void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound) { +void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader header, VisibilityBound bound, + transaction_t read_stamp, transaction_t lowest_active_start) { auto free_list_blocks = GetFreeListBlocks(); // now handle the free list auto &metadata_manager = GetMetadataManager(); - // add all modified blocks to the free list: they can now be written to again - metadata_manager.MarkBlocksAsModified(); + // a transaction that started before the header can still read what the header frees + bool has_readers = lowest_active_start < read_stamp; + auto freed_metadata_blocks = metadata_manager.MarkBlocksAsModified(has_readers); + // serialized here: the metadata manager's lock is taken before the lock below, never under it + MemoryStream metadata_stream; + metadata_manager.Write(metadata_stream); unique_lock lock(single_file_block_lock); // set the iteration count @@ -1373,6 +1385,7 @@ void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader he set all_free_blocks = free_list; all_free_blocks.insert(free_blocks_in_use.begin(), free_blocks_in_use.end()); + all_free_blocks.insert(free_blocks_pending_reuse.begin(), free_blocks_pending_reuse.end()); auto checkpoint_freed_blocks = modified_blocks; for (auto &block : checkpoint_freed_blocks) { all_free_blocks.insert(block); @@ -1409,7 +1422,7 @@ void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader he writer.Write(entry.first); writer.Write(entry.second); } - GetMetadataManager().Write(writer); + writer.WriteData(metadata_stream.GetData(), metadata_stream.GetPosition()); writer.Flush(); } else { // no blocks in the free list @@ -1454,16 +1467,53 @@ void SingleFileBlockManager::WriteHeader(QueryContext context, DatabaseHeader he active_header = 1 - active_header; //! Ensure the header write ends up on disk handle->Sync(); - set fully_freed_blocks; - { - unique_lock release_lock(single_file_block_lock); + if (!checkpoint_freed_blocks.empty() || !freed_metadata_blocks.empty()) { + lock_guard release_lock(single_file_block_lock); + auto &freed = pending_reuse_batches[read_stamp]; for (auto &block : checkpoint_freed_blocks) { modified_blocks.erase(block); - if (AddFreeBlock(release_lock, block)) { + freed.blocks.push_back(block); + free_blocks_pending_reuse.insert(block); + } + for (auto &metadata_block : freed_metadata_blocks) { + freed.metadata_blocks[metadata_block.first] |= metadata_block.second; + } + lowest_pending_reuse_stamp = pending_reuse_batches.begin()->first; + } + // reused right away unless a transaction that started before the header is active + ReuseFreedBlocks(lowest_active_start); +} + +void SingleFileBlockManager::ReuseFreedBlocks(transaction_t lowest_active_start) { + if (lowest_pending_reuse_stamp > lowest_active_start) { + // nothing waits, or a transaction that started before the first batch is still active + return; + } + set fully_freed_blocks; + vector> metadata_blocks; + { + unique_lock lock(single_file_block_lock); + // the batches are ordered by stamp + auto end = pending_reuse_batches.upper_bound(lowest_active_start); + vector blocks; + for (auto entry = pending_reuse_batches.begin(); entry != end; entry++) { + blocks.insert(blocks.end(), entry->second.blocks.begin(), entry->second.blocks.end()); + metadata_blocks.push_back(std::move(entry->second.metadata_blocks)); + } + pending_reuse_batches.erase(pending_reuse_batches.begin(), end); + lowest_pending_reuse_stamp = + pending_reuse_batches.empty() ? MAX_TRANSACTION_ID : pending_reuse_batches.begin()->first; + // AddFreeBlock can give up the lock: no batch is looked at from here on + for (auto &block : blocks) { + free_blocks_pending_reuse.erase(block); + if (AddFreeBlock(lock, block)) { fully_freed_blocks.insert(block); } } } + for (auto &freed : metadata_blocks) { + GetMetadataManager().ReuseFreedBlocks(freed); + } // Release the free fully freed blocks to the filesystem. TrimFreeBlocks(fully_freed_blocks); } diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index f1e34384e..4595930f8 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -990,25 +990,26 @@ SingleFileStorageManager::CreateCheckpointWriter(QueryContext context, Checkpoin return make_uniq(context, db, *block_manager, options, checkpoint_context); } -static vector> GetCommittedTables(AttachedDatabase &db) { - vector> tables; +//! The storage of the tables, which outlives their catalog entries: a commit after the scan can destroy those. +static vector> GetCommittedTables(AttachedDatabase &db) { + vector> tables; auto &catalog = Catalog::GetCatalog(db).Cast(); auto bound = VisibilityBound::AllCommitted(); catalog.ScanSchemas(bound, [&](DuckSchemaEntry &schema) { schema.Scan(CatalogType::TABLE_ENTRY, bound, [&](CatalogEntry &entry) { if (!entry.internal && entry.type == CatalogType::TABLE_ENTRY) { - tables.push_back(entry.Cast()); + tables.push_back(entry.Cast().GetStorage().shared_from_this()); } }); }); return tables; } -static vector> GetTablesWithUnboundIndexes(AttachedDatabase &db) { +static vector> GetTablesWithUnboundIndexes(AttachedDatabase &db) { // Don't take index locks inside the catalog scan: concurrent binds take them in the opposite order. - vector> result; + vector> result; for (auto &table : GetCommittedTables(db)) { - if (table.get().GetStorage().GetDataTableInfo()->GetIndexes().HasUnbound()) { + if (table->GetDataTableInfo()->GetIndexes().HasUnbound()) { result.push_back(table); } } @@ -1028,9 +1029,9 @@ static ErrorData TryBindIndexes(DataTableInfo &info, ClientContext &context) { return ErrorData(); } -static bool HasBufferedReplays(const vector> &tables) { +static bool HasBufferedReplays(const vector> &tables) { for (auto &table : tables) { - if (table.get().GetStorage().GetDataTableInfo()->GetIndexes().HasBufferedReplays()) { + if (table->GetDataTableInfo()->GetIndexes().HasBufferedReplays()) { return true; } } @@ -1069,7 +1070,7 @@ bool SingleFileStorageManager::BindIndexesForCheckpoint(optional_ptrGetDataTableInfo(); if (!explicit_checkpoint && !info.GetIndexes().HasBufferedReplays()) { continue; } @@ -1177,7 +1178,7 @@ void SingleFileStorageManager::Destroy() { return; } for (auto &table : GetCommittedTables(db)) { - table.get().GetStorage().Destroy(); + table->Destroy(); } } diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index bf872d292..153b38b28 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -42,7 +42,27 @@ void CommitDropState::RemoveIndex(TableIndexList &indexes, idx_t index_oid) { pending_index_removals.push_back(PendingIndexRemoval {indexes, index_oid}); } +void CommitDropState::DropTable(shared_ptr table) { + dropped_tables.push_back(std::move(table)); +} + +void CommitDropState::FreeTables(const vector> &tables) { + for (auto &table : tables) { + table->CommitDropTable(*this); + } +} + +void CommitDropState::FinalizeCommit(DuckTransactionManager &transaction_manager) { + // a running checkpoint started before the drop and may still write the tables: it frees them after its header + if (!transaction_manager.DeferDroppedTables(dropped_tables)) { + FreeTables(dropped_tables); + } + dropped_tables.clear(); + FinalizeCommit(); +} + void CommitDropState::FinalizeCommit() { + D_ASSERT(dropped_tables.empty()); if (block_manager) { for (auto block_id : dropped_block_ids) { block_manager->MarkBlockAsModified(block_id); @@ -59,7 +79,7 @@ void CommitDropState::FinalizeCommit() { } bool CommitDropState::Empty() const { - return dropped_block_ids.empty() && pending_index_removals.empty(); + return dropped_block_ids.empty() && pending_index_removals.empty() && dropped_tables.empty(); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/transaction/duck_transaction.cpp b/src/duckdb/src/transaction/duck_transaction.cpp index e3587e7e4..7b4ec753a 100644 --- a/src/duckdb/src/transaction/duck_transaction.cpp +++ b/src/duckdb/src/transaction/duck_transaction.cpp @@ -306,7 +306,7 @@ ErrorData DuckTransaction::Commit(ClientContext &context, AttachedDatabase &db, bool sync_now = commit_info.active_transactions == ActiveTransactionState::NO_OTHER_TRANSACTIONS; commit_info.wal_sync_offset = commit_state->FlushCommit(commit_info.commit_id, sync_now); } - drop_state.FinalizeCommit(); + drop_state.FinalizeCommit(manager.Cast()); return ErrorData(); } catch (std::exception &ex) { // Record the error and run RevertCommit() outside this try-catch: RevertCommit() iterates the diff --git a/src/duckdb/src/transaction/duck_transaction_manager.cpp b/src/duckdb/src/transaction/duck_transaction_manager.cpp index 706c70211..e70351d14 100644 --- a/src/duckdb/src/transaction/duck_transaction_manager.cpp +++ b/src/duckdb/src/transaction/duck_transaction_manager.cpp @@ -11,6 +11,8 @@ #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/dependency_manager.hpp" #include "duckdb/storage/storage_manager.hpp" +#include "duckdb/storage/block_manager.hpp" +#include "duckdb/transaction/commit_state.hpp" #include "duckdb/transaction/duck_transaction.hpp" #include "duckdb/transaction/transaction_data.hpp" #include "duckdb/main/client_context.hpp" @@ -51,6 +53,7 @@ DuckTransactionManager::DuckTransactionManager(AttachedDatabase &db) : Transacti // the first timestamp a real transaction can draw: one past the bootstrap stamp, which is also // the bound the system transaction reads at current_start_timestamp = SYSTEM_TRANSACTION_TIMESTAMP + 1; + lowest_remaining_start = current_start_timestamp; last_commit = SYSTEM_TRANSACTION_TIMESTAMP; // transaction ID starts very high: // it should be much higher than the current start timestamp @@ -116,8 +119,69 @@ void DuckTransactionManager::SetActiveCheckpoint(idx_t checkpoint_id) { active_checkpoint = checkpoint_id; } -void DuckTransactionManager::ResetActiveCheckpoint() { - active_checkpoint = 0; +void DuckTransactionManager::ResetActiveCheckpoint(bool checkpoint_succeeded) { + vector> dropped; + { + lock_guard guard(deferred_tables_lock); + active_checkpoint = 0; + dropped = std::move(deferred_tables); + deferred_tables.clear(); + } + if (!checkpoint_succeeded || dropped.empty()) { + // a failed checkpoint invalidates the database: the WAL replays the drops when it is opened again + return; + } + // the checkpoint no longer writes them: the next checkpoint frees the blocks + CommitDropState drop_state(&db.GetStorageManager().GetBlockManager()); + drop_state.FreeTables(dropped); + drop_state.FinalizeCommit(); +} + +bool DuckTransactionManager::DeferDroppedTables(const vector> &tables) { + lock_guard guard(deferred_tables_lock); + if (active_checkpoint == 0) { + return false; + } + // the checkpoint started before the drops committed: its catalog still has the tables + deferred_tables.insert(deferred_tables.end(), tables.begin(), tables.end()); + return true; +} + +void DuckTransactionManager::GetStartTimes(transaction_t &next_start, transaction_t &lowest_active_start) { + lock_guard t_lock(transaction_lock); + next_start = current_start_timestamp; + lowest_active_start = LowestActiveStart(); + // a cleanup that has not run counts as a transaction older than all others: it comes before any reuse + lock_guard q_lock(cleanup_queue_lock); + if (!cleanup_queue.empty()) { + lowest_active_start = 0; + } +} + +transaction_t DuckTransactionManager::LowestActiveStart() { + transaction_t lowest_start = current_start_timestamp; + for (auto &transaction : active_transactions) { + if (transaction->IsCheckpointTransaction()) { + // reads nothing that its own header frees + continue; + } + lowest_start = MinValue(lowest_start, transaction->start_time); + } + return lowest_start; +} + +void DuckTransactionManager::ReuseFreedBlocks(transaction_t lowest_start) noexcept { + if (!db.HasStorageManager()) { + return; + } + try { + // transactions that started since then started later: the true lowest start is not below this + db.GetStorageManager().GetBlockManager().ReuseFreedBlocks(lowest_start); + } catch (std::exception &ex) { + // e.g. the file could not be trimmed: a rollback, which destructors run, must not throw + DUCKDB_LOG_WARNING(db.GetDatabase(), "Failed to release freed blocks of database %s for reuse: %s", + db.GetName(), ErrorData(ex).RawMessage()); + } } DuckTransactionManager::CheckpointDecision::CheckpointDecision(string reason_p) @@ -322,14 +386,16 @@ void DuckTransactionManager::WaitForDurability() { } void DuckTransactionManager::CleanupTransactions() { - lock_guard c_lock(cleanup_lock); + unique_lock c_lock(cleanup_lock); + // read before the cleanups run: every cleanup that this start time allows is queued by now + transaction_t lowest_start = lowest_remaining_start; while (true) { DuckCleanupInfo *top_cleanup_info = nullptr; { lock_guard q_lock(cleanup_queue_lock); if (cleanup_queue.empty()) { // all transactions have been cleaned up - done - return; + break; } top_cleanup_info = cleanup_queue.front().get(); } @@ -345,6 +411,9 @@ void DuckTransactionManager::CleanupTransactions() { cleanup_queue.pop(); } } + // after the cleanups, so that none of them reads a reused block, and outside the lock: it can trim the file + c_lock.unlock(); + ReuseFreedBlocks(lowest_start); } ErrorData DuckTransactionManager::CommitTransaction(ClientContext &context, Transaction &transaction_p) { @@ -725,6 +794,8 @@ void DuckTransactionManager::QueueCleanup(unique_ptr cleanup_in lock_guard q_lock(cleanup_queue_lock); cleanup_queue.emplace(std::move(cleanup_info)); } + // under the transaction lock, and only after the cleanup that this start time allows is queued + lowest_remaining_start = LowestActiveStart(); } idx_t DuckTransactionManager::GetCatalogVersion(Transaction &transaction_p) {