From 695f022068acc85001e04a06741a9cbdc7e2368d Mon Sep 17 00:00:00 2001 From: DuckLabs GitHub Bot Date: Mon, 23 Nov 2026 15:29:42 +0000 Subject: [PATCH] Update vendored DuckDB sources to 620752ed3cb --- .../aggregate/holistic/approx_top_k.cpp | 48 +++---- .../extension/parquet/parquet_reader.cpp | 30 ++++- .../extension/parquet/parquet_statistics.cpp | 5 +- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/common/cgroups.cpp | 124 ++++++------------ src/duckdb/src/common/enum_util.cpp | 25 ++++ src/duckdb/src/common/local_file_system.cpp | 2 +- .../src/common/operator/cast_operators.cpp | 112 ++++++++-------- src/duckdb/src/common/process_util.cpp | 35 +++-- .../src/function/cast/cast_statistics.cpp | 6 + .../function/table/version/pragma_version.cpp | 6 +- .../src/include/duckdb/common/cgroups.hpp | 5 +- .../src/include/duckdb/common/enum_util.hpp | 8 ++ .../include/duckdb/common/process_util.hpp | 2 +- src/duckdb/src/include/duckdb/main/config.hpp | 8 +- .../src/include/duckdb/main/os_util.hpp | 23 ++++ src/duckdb/src/main/config.cpp | 28 ++-- src/duckdb/src/main/database.cpp | 4 +- .../src/main/http/http_transport_manager.cpp | 3 +- src/duckdb/src/main/os_util.cpp | 78 +++++++++++ .../src/main/settings/custom_settings.cpp | 4 +- .../src/optimizer/projection_placement.cpp | 9 +- 22 files changed, 341 insertions(+), 232 deletions(-) diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp index c5115fcd0..ee5d8fa92 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/approx_top_k.cpp @@ -172,22 +172,8 @@ struct InternalApproxTopKState { } auto &value = values.back().get(); if (value.count > 0) { - // the capacity is reached - we need to replace an entry - - // we use the filter as an early out - // based on the hash - we find a slot in the filter - // instead of monitoring the value immediately, we add to the slot in the filter - // ONLY when the value in the filter exceeds the current min value, we start monitoring the value - // this speeds up the algorithm as switching monitor values means we need to erase/insert in the hash table - auto &filter_value = filter[input.hash & filter_mask]; - if (filter_value + increment < value.count) { - // if the filter has a lower count than the current min count - // we can skip adding this entry (for now) - filter_value += increment; - return; - } - // the filter exceeds the min value - start monitoring this value - // erase the existing entry from the lookup table (before CopyValue overwrites its hash and data) + // the capacity is reached - replace the entry with the lowest count + // erase it from the lookup table (before CopyValue overwrites its hash and data) // and set the filter for the minimum value back to the current minimum value filter[value.str_val.hash & filter_mask] = value.count; Erase(value); @@ -197,6 +183,22 @@ struct InternalApproxTopKState { IncrementCount(value, increment); } + //! Returns true if an unmonitored input is only counted in the filter + bool FilterInput(const ApproxTopKString &input) { + if (values.size() < capacity) { + return false; + } + // instead of monitoring the value immediately, we add to its slot in the filter + // ONLY when the filter slot reaches the current min count, we start monitoring the value + // this speeds up the algorithm as switching monitor values means we need to erase/insert in the hash table + auto &filter_value = filter[input.hash & filter_mask]; + if (filter_value + 1 < values.back().get().count) { + filter_value++; + return true; + } + return false; + } + void IncrementCount(ApproxTopKValue &value, idx_t increment = 1) { value.count += increment; // maintain sortedness of "values" @@ -266,8 +268,8 @@ struct ApproxTopKOperation { if (entry) { // the input is monitored - increment the count state.IncrementCount(*entry); - } else { - // the input is not monitored - replace the first entry with the current entry and increment + } else if (!state.FilterInput(topk_string)) { + // the input is not monitored and passes the filter - start monitoring it state.InsertOrReplaceEntry(topk_string, aggr_input); } } @@ -311,6 +313,11 @@ struct ApproxTopKOperation { } target.IncrementCount(val, increment); } + // copy over the filter before evicting, so an evicted value sets its slot to its merged count + D_ASSERT(source.filter.size() == target.filter.size()); + for (idx_t filter_idx = 0; filter_idx < source.filter.size(); filter_idx++) { + target.filter[filter_idx] += source.filter[filter_idx]; + } // now for each entry in source, if it is not tracked by the target, at the target minimum for (auto &source_entry : source.values) { auto &source_val = source_entry.get(); @@ -337,11 +344,6 @@ struct ApproxTopKOperation { } target.InsertOrReplaceEntry(source_val.str_val, aggr_input, increment); } - // copy over the filter - D_ASSERT(source.filter.size() == target.filter.size()); - for (idx_t filter_idx = 0; filter_idx < source.filter.size(); filter_idx++) { - target.filter[filter_idx] += source.filter[filter_idx]; - } target.Verify(); } diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 8e493a0b9..893f490b0 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -2656,18 +2656,42 @@ struct ParquetPartitionRowGroup : public PartitionRowGroup { D_ASSERT(metadata.row_groups.size() > row_group_idx); // Special handle generated columns. - const auto &column_schema = root_schema->children[primary_index]; - if (column_schema.schema_type == ParquetColumnSchemaType::FILE_ROW_NUMBER) { + reference column_schema = root_schema->children[primary_index]; + if (column_schema.get().schema_type == ParquetColumnSchemaType::FILE_ROW_NUMBER) { return true; } + // resolve an extracted struct field to the leaf column it reads + if (storage_index.IsPushdownExtract()) { + reference index = storage_index; + while (index.get().HasChildren() && column_schema.get().type.id() == LogicalTypeId::STRUCT) { + if (column_schema.get().children.empty()) { + // INT96 can be exposed as a struct without physical child columns. + return false; + } + index = index.get().GetChildIndex(0); + column_schema = column_schema.get().children[index.get().GetPrimaryIndex()]; + } + } + // row_group.columns is indexed by leaf column, so only leaf columns map to a column chunk + auto &leaf_schema = column_schema.get(); + if (leaf_schema.schema_type != ParquetColumnSchemaType::COLUMN || !leaf_schema.children.empty()) { + return false; + } const auto &row_group = metadata.row_groups[row_group_idx]; - const auto &column_chunk = row_group.columns[primary_index]; + const auto &column_chunk = row_group.columns[leaf_schema.column_index]; if (column_chunk.__isset.meta_data && column_chunk.meta_data.__isset.statistics && column_chunk.meta_data.statistics.__isset.is_min_value_exact && column_chunk.meta_data.statistics.__isset.is_max_value_exact) { const auto &stats = column_chunk.meta_data.statistics; + const auto type_id = leaf_schema.type.id(); + const bool is_floating_point = type_id == LogicalTypeId::FLOAT || type_id == LogicalTypeId::DOUBLE; + const bool can_have_nan = parquet_options->can_have_nan && stats.__isset.nan_count == 0; + if (is_floating_point && can_have_nan) { + // the max is replaced by NaN as an upper bound, as the stored max leaves out NaN values + return false; + } return stats.is_min_value_exact && stats.is_max_value_exact; } return false; diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 2a4c547c5..c977788a4 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -783,7 +783,10 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch row_group_stats->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); } if (parquet_stats.__isset.null_count && parquet_stats.null_count == column_chunk.meta_data.num_values) { - row_group_stats->Set(StatsInfo::CANNOT_HAVE_VALID_VALUES); + row_group_stats = BaseStatistics::CreateEmpty(type).ToUnique(); + if (parquet_stats.null_count > 0) { + row_group_stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES); + } } } return row_group_stats; diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 99438ab47..5be930010 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-alpha57096"; + descriptor->api_version = "v2.1.0-alpha57135"; 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-alpha57096"; + descriptor->api_version = "v2.1.0-alpha57135"; 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-alpha57096"; + descriptor->api_version = "v2.1.0-alpha57135"; 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-alpha57096"; + descriptor->api_version = "v2.1.0-alpha57135"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/cgroups.cpp b/src/duckdb/src/common/cgroups.cpp index bfb39610c..b360b942b 100644 --- a/src/duckdb/src/common/cgroups.cpp +++ b/src/duckdb/src/common/cgroups.cpp @@ -1,7 +1,7 @@ #include "duckdb/common/cgroups.hpp" #include "duckdb/common/string_util.hpp" -#include "duckdb/common/file_system.hpp" +#include "duckdb/main/os_util.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -15,9 +15,6 @@ namespace duckdb { namespace { -static constexpr const char *CGROUP_PATH = "/proc/self/cgroup"; -static constexpr const int64_t DEFAULT_CGROUP_FILE_BUFFER_SIZE = 1024; - struct CGroupEntry { public: CGroupEntry(idx_t hierarchy_id, vector &&controller_list, const string &cgroup_path) @@ -41,23 +38,13 @@ struct CGroupEntry { string cgroup_path; }; -static vector ParseGroupEntries(FileSystem &fs) { +static vector ParseGroupEntries() { vector result; - if (!fs.FileExists(CGROUP_PATH)) { + string cgroup_file_content; + if (!OSUtil::TryReadSystemFile(SystemFile::PROCESS_CGROUPS, string(), cgroup_file_content)) { return result; } - auto handle = fs.OpenFile(CGROUP_PATH, FileFlags::FILE_FLAGS_READ); - - char buffer[DEFAULT_CGROUP_FILE_BUFFER_SIZE]; - int64_t bytes_read; - string cgroup_file_content; - do { - bytes_read = fs.Read(*handle, buffer, DEFAULT_CGROUP_FILE_BUFFER_SIZE - 1); - buffer[bytes_read] = '\0'; - cgroup_file_content += string(buffer); - } while (bytes_read >= DEFAULT_CGROUP_FILE_BUFFER_SIZE - 1); - auto lines = StringUtil::Split(cgroup_file_content, "\n"); for (auto &line : lines) { //! NOTE: this can not use StringUtil::Split, as it counts '::' as a single delimiter @@ -87,27 +74,19 @@ static vector ParseGroupEntries(FileSystem &fs) { return result; } -static optional_idx GetCPUCountV2(const string &cgroup_path, FileSystem &fs) { - static constexpr const char *CPU_MAX = "/sys/fs/cgroup%s/cpu.max"; - - auto cpu_max = StringUtil::Format(CPU_MAX, cgroup_path); - +static optional_idx GetCPUCountV2(const string &cgroup_path) { //! See https://docs.kernel.org/scheduler/sched-bwc.html //! run-time replenished within a period (in microseconds) int64_t quota; //! the length of a period (in microseconds) int64_t period; - if (!fs.FileExists(cpu_max)) { + // cgroup v2 + string cpu_max; + if (!OSUtil::TryReadSystemFile(SystemFile::CGROUP_V2_CPU_MAX, cgroup_path, cpu_max)) { return optional_idx(); } - - // cgroup v2 - char byte_buffer[1000]; - auto handle = fs.OpenFile(cpu_max, FileFlags::FILE_FLAGS_READ); - int64_t read_bytes = fs.Read(*handle, (void *)byte_buffer, 999); - byte_buffer[read_bytes] = '\0'; - if (std::sscanf(byte_buffer, "%" SCNd64 " %" SCNd64 "", "a, &period) != 2) { + if (std::sscanf(cpu_max.c_str(), "%" SCNd64 " %" SCNd64 "", "a, &period) != 2) { return optional_idx(); } @@ -117,17 +96,7 @@ static optional_idx GetCPUCountV2(const string &cgroup_path, FileSystem &fs) { return optional_idx(); } -static optional_idx GetCPUCountV1(const string &cgroup_path, FileSystem &fs) { - static constexpr const char *CFS_QUOTA = "/sys/fs/cgroup/cpu%s/cpu.cfs_quota_us"; - static constexpr const char *CFS_PERIOD = "/sys/fs/cgroup/cpu%s/cpu.cfs_period_us"; - - auto cfs_quota = StringUtil::Format(CFS_QUOTA, cgroup_path); - auto cfs_period = StringUtil::Format(CFS_PERIOD, cgroup_path); - - if (!fs.FileExists(cfs_quota) || !fs.FileExists(cfs_period)) { - return optional_idx(); - } - +static optional_idx GetCPUCountV1(const string &cgroup_path) { //! See https://docs.kernel.org/scheduler/sched-bwc.html //! run-time replenished within a period (in microseconds) int64_t quota; @@ -135,22 +104,17 @@ static optional_idx GetCPUCountV1(const string &cgroup_path, FileSystem &fs) { int64_t period; // cgroup v1 - char byte_buffer[1000]; - { - auto handle = fs.OpenFile(cfs_quota, FileFlags::FILE_FLAGS_READ); - int64_t read_bytes = fs.Read(*handle, (void *)byte_buffer, 999); - byte_buffer[read_bytes] = '\0'; - if (std::sscanf(byte_buffer, "%" SCNd64 "", "a) != 1) { - return optional_idx(); - } + string cfs_quota; + string cfs_period; + if (!OSUtil::TryReadSystemFile(SystemFile::CGROUP_V1_CPU_QUOTA, cgroup_path, cfs_quota) || + !OSUtil::TryReadSystemFile(SystemFile::CGROUP_V1_CPU_PERIOD, cgroup_path, cfs_period)) { + return optional_idx(); } - { - auto handle = fs.OpenFile(cfs_period, FileFlags::FILE_FLAGS_READ); - int64_t read_bytes = fs.Read(*handle, (void *)byte_buffer, 999); - byte_buffer[read_bytes] = '\0'; - if (std::sscanf(byte_buffer, "%" SCNd64 "", &period) != 1) { - return optional_idx(); - } + if (std::sscanf(cfs_quota.c_str(), "%" SCNd64 "", "a) != 1) { + return optional_idx(); + } + if (std::sscanf(cfs_period.c_str(), "%" SCNd64 "", &period) != 1) { + return optional_idx(); } if (quota > 0 && period > 0) { @@ -159,19 +123,14 @@ static optional_idx GetCPUCountV1(const string &cgroup_path, FileSystem &fs) { return optional_idx(); } -static optional_idx ReadMemoryLimit(FileSystem &fs, const string &file_path) { - if (!fs.FileExists(file_path)) { +static optional_idx ReadMemoryLimit(SystemFile file, const string &cgroup_path) { + string contents; + if (!OSUtil::TryReadSystemFile(file, cgroup_path, contents)) { return optional_idx(); } - auto handle = fs.OpenFile(file_path, FileFlags::FILE_FLAGS_READ); - char buffer[100]; - auto bytes_read = fs.Read(*handle, buffer, 99); - buffer[bytes_read] = '\0'; - - auto contents = string_t(buffer); idx_t value; - if (TryCast::Operation(contents, value)) { + if (TryCast::Operation(string_t(contents.c_str()), value)) { return optional_idx(value); } return optional_idx(); @@ -179,14 +138,11 @@ static optional_idx ReadMemoryLimit(FileSystem &fs, const string &file_path) { } // namespace -optional_idx CGroups::GetMemoryLimit(FileSystem &fs) { - static constexpr const char *MEMORY_LIMIT_IN_BYTES = "/sys/fs/cgroup/memory%s/memory.limit_in_bytes"; - static constexpr const char *MEMORY_MAX = "/sys/fs/cgroup%s/memory.max"; - +optional_idx CGroups::GetMemoryLimit() { optional_idx root_entry; optional_idx memory_entry; - auto cgroup_entries = ParseGroupEntries(fs); + auto cgroup_entries = ParseGroupEntries(); for (idx_t i = 0; i < cgroup_entries.size(); i++) { auto &entry = cgroup_entries[i]; auto &controller_list = entry.controller_list; @@ -207,28 +163,24 @@ optional_idx CGroups::GetMemoryLimit(FileSystem &fs) { // To properly handle this, we should parse and use the mapping in `/proc/self/mountinfo` if (memory_entry.IsValid()) { auto &entry = cgroup_entries[memory_entry.GetIndex()]; - auto path = StringUtil::Format(MEMORY_LIMIT_IN_BYTES, entry.cgroup_path); - auto memory_limit = ReadMemoryLimit(fs, path.c_str()); + auto memory_limit = ReadMemoryLimit(SystemFile::CGROUP_V1_MEMORY_LIMIT, entry.cgroup_path); if (memory_limit.IsValid()) { return memory_limit; } //! try falling back to the root directory - path = StringUtil::Format(MEMORY_LIMIT_IN_BYTES, ""); - memory_limit = ReadMemoryLimit(fs, path.c_str()); + memory_limit = ReadMemoryLimit(SystemFile::CGROUP_V1_MEMORY_LIMIT, string()); if (memory_limit.IsValid()) { return memory_limit; } } if (root_entry.IsValid()) { auto &entry = cgroup_entries[root_entry.GetIndex()]; - auto path = StringUtil::Format(MEMORY_MAX, entry.cgroup_path); - auto memory_limit = ReadMemoryLimit(fs, path.c_str()); + auto memory_limit = ReadMemoryLimit(SystemFile::CGROUP_V2_MEMORY_MAX, entry.cgroup_path); if (memory_limit.IsValid()) { return memory_limit; } //! try falling back to the root directory - path = StringUtil::Format(MEMORY_MAX, ""); - memory_limit = ReadMemoryLimit(fs, path.c_str()); + memory_limit = ReadMemoryLimit(SystemFile::CGROUP_V2_MEMORY_MAX, string()); if (memory_limit.IsValid()) { return memory_limit; } @@ -236,11 +188,11 @@ optional_idx CGroups::GetMemoryLimit(FileSystem &fs) { return optional_idx(); } -idx_t CGroups::GetCPULimit(FileSystem &fs, idx_t physical_cores) { +idx_t CGroups::GetCPULimit(idx_t physical_cores) { optional_idx root_entry; optional_idx cpu_entry; - auto cgroup_entries = ParseGroupEntries(fs); + auto cgroup_entries = ParseGroupEntries(); for (idx_t i = 0; i < cgroup_entries.size(); i++) { auto &entry = cgroup_entries[i]; auto &controller_list = entry.controller_list; @@ -261,24 +213,24 @@ idx_t CGroups::GetCPULimit(FileSystem &fs, idx_t physical_cores) { // To properly handle this, we should parse and use the mapping in `/proc/self/mountinfo` if (cpu_entry.IsValid()) { auto &entry = cgroup_entries[cpu_entry.GetIndex()]; - auto res = GetCPUCountV1(entry.cgroup_path, fs); + auto res = GetCPUCountV1(entry.cgroup_path); if (res.IsValid()) { return res.GetIndex(); } //! try falling back to the root directory - res = GetCPUCountV1("", fs); + res = GetCPUCountV1(string()); if (res.IsValid()) { return res.GetIndex(); } } if (root_entry.IsValid()) { auto &entry = cgroup_entries[root_entry.GetIndex()]; - auto res = GetCPUCountV2(entry.cgroup_path, fs); + auto res = GetCPUCountV2(entry.cgroup_path); if (res.IsValid()) { return res.GetIndex(); } //! try falling back to the root directory - res = GetCPUCountV2("", fs); + res = GetCPUCountV2(string()); if (res.IsValid()) { return res.GetIndex(); } @@ -288,11 +240,11 @@ idx_t CGroups::GetCPULimit(FileSystem &fs, idx_t physical_cores) { #else -optional_idx CGroups::GetMemoryLimit(FileSystem &fs) { +optional_idx CGroups::GetMemoryLimit() { return optional_idx(); } -idx_t CGroups::GetCPULimit(FileSystem &fs, idx_t physical_cores) { +idx_t CGroups::GetCPULimit(idx_t physical_cores) { return physical_cores; } diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 99143a05c..2f2c0b1f8 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -170,6 +170,7 @@ #include "duckdb/main/extension_install_info.hpp" #include "duckdb/main/http/http_retry_budget.hpp" #include "duckdb/main/http/http_util.hpp" +#include "duckdb/main/os_util.hpp" #include "duckdb/main/profiler/gathered_metrics.hpp" #include "duckdb/main/secret/secret.hpp" #include "duckdb/main/setting_info.hpp" @@ -7023,6 +7024,30 @@ SuggestionState EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetSuggestionStateValues(), 15, "SuggestionState", value)); } +const StringUtil::EnumStringLiteral *GetSystemFileValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(SystemFile::PROCESS_CGROUPS), "PROCESS_CGROUPS" }, + { static_cast(SystemFile::PROCESS_CMDLINE), "PROCESS_CMDLINE" }, + { static_cast(SystemFile::PROCESS_LOGINUID), "PROCESS_LOGINUID" }, + { static_cast(SystemFile::CGROUP_V1_CPU_QUOTA), "CGROUP_V1_CPU_QUOTA" }, + { static_cast(SystemFile::CGROUP_V1_CPU_PERIOD), "CGROUP_V1_CPU_PERIOD" }, + { static_cast(SystemFile::CGROUP_V2_CPU_MAX), "CGROUP_V2_CPU_MAX" }, + { static_cast(SystemFile::CGROUP_V1_MEMORY_LIMIT), "CGROUP_V1_MEMORY_LIMIT" }, + { static_cast(SystemFile::CGROUP_V2_MEMORY_MAX), "CGROUP_V2_MEMORY_MAX" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(SystemFile value) { + return StringUtil::EnumToString(GetSystemFileValues(), 8, "SystemFile", static_cast(value)); +} + +template<> +SystemFile EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetSystemFileValues(), 8, "SystemFile", value)); +} + const StringUtil::EnumStringLiteral *GetTableColumnTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(TableColumnType::STANDARD), "STANDARD" }, diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index e4ba75798..f6b973a7e 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -337,7 +337,7 @@ static void TryAcquireFileLock(FileSystem &fs, int fd, const string &path, FileO } else if (fl.l_pid == ProcessUtil::CurrentProcessId()) { extended_error = "Lock is already held in current process, likely another DuckDB instance"; } else { - auto process = ProcessUtil::GetProcessDescription(fs, fl.l_pid); + auto process = ProcessUtil::GetProcessDescription(fl.l_pid); if (!process.empty()) { extended_error = "Conflicting lock is held in " + process; } diff --git a/src/duckdb/src/common/operator/cast_operators.cpp b/src/duckdb/src/common/operator/cast_operators.cpp index af8d86d41..21c9dcf19 100644 --- a/src/duckdb/src/common/operator/cast_operators.cpp +++ b/src/duckdb/src/common/operator/cast_operators.cpp @@ -27,6 +27,7 @@ #include "fast_float/fast_float.h" #include "duckdb/common/types/bit.hpp" #include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/bignum_limbs.hpp" #include "duckdb/common/types/decimal_helper.hpp" #include "duckdb/common/operator/integer_cast_operator.hpp" #include "duckdb/common/operator/double_cast_operator.hpp" @@ -3329,74 +3330,65 @@ static bool CanUseDecimalFloatingPointFastPath(SRC input, uint32_t scale) { IsRepresentableExactly(input, DST(0.0)); } -template -static void FillDecimalDigits(UNSIGNED input, duckdb_fast_float::decimal &decimal) { - uint8_t digits[DecimalWidth::max]; - while (input > 0) { - digits[decimal.num_digits++] = UnsafeNumericCast(input % 10); - input /= 10; - } +//! Rounds magnitude * 10^-scale to the nearest float from its full decimal digits +template +static duckdb_fast_float::adjusted_mantissa ComputeFloatFromDigits(hugeint_t magnitude, uint32_t scale) { + char buffer[DecimalWidth::max + 1]; + auto end = buffer + sizeof(buffer); + auto begin = NumericHelper::FormatUnsigned(magnitude, end); + + duckdb_fast_float::decimal decimal; + decimal.num_digits = UnsafeNumericCast(end - begin); for (uint32_t i = 0; i < decimal.num_digits; i++) { - decimal.digits[i] = digits[decimal.num_digits - i - 1]; + decimal.digits[i] = UnsafeNumericCast(begin[i] - '0'); } -} - -template -static void FillDecimalDigits(SRC input, duckdb_fast_float::decimal &decimal, bool &negative) { - using UNSIGNED = typename MakeUnsigned::type; - if (input < 0) { - negative = true; - auto unsigned_input = UnsafeNumericCast(-(input + 1)); - FillDecimalDigits(unsigned_input + 1, decimal); - } else { - negative = false; - FillDecimalDigits(UnsafeNumericCast(input), decimal); + decimal.decimal_point = UnsafeNumericCast(decimal.num_digits) - UnsafeNumericCast(scale); + while (decimal.num_digits > 0 && decimal.digits[decimal.num_digits - 1] == 0) { + decimal.num_digits--; } -} - -static void FillDecimalDigits(hugeint_t input, duckdb_fast_float::decimal &decimal, bool &negative) { - negative = false; - if (input == 0) { - return; + for (uint32_t i = decimal.num_digits; i < duckdb_fast_float::max_digit_without_overflow; i++) { + decimal.digits[i] = 0; } + return duckdb_fast_float::compute_float>(decimal); +} - if (input < 0) { - negative = true; +template +static void CastDecimalToFloatingPointRounded(hugeint_t input, DST &result, uint32_t scale) { + using binary = duckdb_fast_float::binary_format; + const bool negative = input < 0; + if (negative) { Hugeint::NegateInPlace(input); } - - // a hugeint can have one more digit than the maximum decimal width - char buffer[DecimalWidth::max + 1]; - auto end = buffer + sizeof(buffer); - auto begin = NumericHelper::FormatUnsigned(input, end); - - decimal.num_digits = UnsafeNumericCast(end - begin); - for (uint32_t i = 0; i < decimal.num_digits; i++) { - decimal.digits[i] = UnsafeNumericCast(begin[i] - '0'); + int64_t exponent = -int64_t(scale); + uint64_t mantissa = input.lower; + uint64_t remainder = 0; + if (input.upper != 0) { + // drop the fewest low digits that make the rest fit a uint64_t: as many as upper has, at most 19 + const auto upper = static_cast(input.upper); + const auto dropped_digits = NumericHelper::UnsignedLength(upper); + mantissa = + BignumLimb::DivRemPortable(upper, input.lower, Uhugeint::POWERS_OF_TEN[dropped_digits].lower, remainder); + exponent += dropped_digits; } + // Eisel-Lemire; a truncated mantissa is only usable if mantissa + 1 rounds to the same float + auto rounded = duckdb_fast_float::compute_float(exponent, mantissa); + const bool truncation_matters = + remainder != 0 && (mantissa == NumericLimits::Maximum() || + rounded != duckdb_fast_float::compute_float(exponent, mantissa + 1)); + if (truncation_matters || rounded.power2 < 0) { + rounded = ComputeFloatFromDigits(input, scale); + } + duckdb_fast_float::detail::to_float(negative, rounded, result); } template -bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint32_t width, uint32_t scale) { +bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint32_t scale) { if (scale == 0 || CanUseDecimalFloatingPointFastPath(input, scale)) { // Fast path, integer and decimal exponent are representable exactly as a float/double result = Cast::Operation(input) / DST(NumericHelper::DOUBLE_POWERS_OF_TEN[scale]); return true; } - - duckdb_fast_float::decimal decimal; - bool negative = false; - FillDecimalDigits(input, decimal, negative); - decimal.decimal_point = UnsafeNumericCast(decimal.num_digits) - UnsafeNumericCast(scale); - while (decimal.num_digits > 0 && decimal.digits[decimal.num_digits - 1] == 0) { - decimal.num_digits--; - } - for (uint32_t i = decimal.num_digits; i < duckdb_fast_float::max_digit_without_overflow; i++) { - decimal.digits[i] = 0; - } - - auto adjusted_mantissa = duckdb_fast_float::compute_float>(decimal); - duckdb_fast_float::detail::to_float(negative, adjusted_mantissa, result); + CastDecimalToFloatingPointRounded(hugeint_t(input), result, scale); return true; } @@ -3404,50 +3396,50 @@ bool TryCastDecimalToFloatingPoint(SRC input, DST &result, uint32_t width, uint3 template <> bool TryCastFromDecimal::Operation(int16_t input, float &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(int32_t input, float &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(int64_t input, float &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(hugeint_t input, float &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } // DECIMAL -> DOUBLE template <> bool TryCastFromDecimal::Operation(int16_t input, double &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(int32_t input, double &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(int64_t input, double &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } template <> bool TryCastFromDecimal::Operation(hugeint_t input, double &result, CastParameters ¶meters, uint32_t width, uint32_t scale) { - return TryCastDecimalToFloatingPoint(input, result, width, scale); + return TryCastDecimalToFloatingPoint(input, result, scale); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/process_util.cpp b/src/duckdb/src/common/process_util.cpp index 41083666e..c4fe10987 100644 --- a/src/duckdb/src/common/process_util.cpp +++ b/src/duckdb/src/common/process_util.cpp @@ -1,9 +1,9 @@ #include "duckdb/common/process_util.hpp" #include "duckdb/common/file_system.hpp" -#include "duckdb/common/query_context.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/windows.hpp" +#include "duckdb/main/os_util.hpp" #ifdef _WIN32 #include "duckdb/common/windows_util.hpp" @@ -78,7 +78,7 @@ string FormatProcessDescription(const string &process_name, const string &proces #if defined(__APPLE__) && !TARGET_OS_IPHONE -string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { +string ProcessUtil::GetProcessDescription(int64_t pid) { string process_name, process_owner; // macOS >= 10.7 has PROC_PIDT_SHORTBSDINFO #ifdef PROC_PIDT_SHORTBSDINFO @@ -104,15 +104,13 @@ string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { #elif defined(__linux__) -string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { +string ProcessUtil::GetProcessDescription(int64_t pid) { string process_name, process_owner; - try { - auto cmdline_file = fs.OpenFile(StringUtil::Format("/proc/%d/cmdline", pid), FileFlags::FILE_FLAGS_READ); - auto cmdline = cmdline_file->ReadLine(QueryContext()); + string cmdline; + if (OSUtil::TryReadSystemFile(SystemFile::PROCESS_CMDLINE, std::to_string(pid), cmdline)) { + cmdline = cmdline.substr(0, cmdline.find('\n')); process_name = basename(const_cast(cmdline.c_str())); // NOLINT: old C API does not take const - } catch (std::exception &) { - // ignore } // we would like to provide a full path to the executable if possible but we might not have rights @@ -127,15 +125,16 @@ string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { } // try to find out who created that process - try { - auto loginuid_file = fs.OpenFile(StringUtil::Format("/proc/%d/loginuid", pid), FileFlags::FILE_FLAGS_READ); - auto uid = std::stoi(loginuid_file->ReadLine(QueryContext())); - auto pw = getpwuid(uid); - if (pw) { - process_owner = pw->pw_name; + string loginuid; + if (OSUtil::TryReadSystemFile(SystemFile::PROCESS_LOGINUID, std::to_string(pid), loginuid)) { + try { + auto pw = getpwuid(std::stoi(loginuid)); + if (pw) { + process_owner = pw->pw_name; + } + } catch (std::exception &) { + // ignore } - } catch (std::exception &) { - // ignore } return FormatProcessDescription(process_name, process_owner, pid); @@ -143,7 +142,7 @@ string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { #elif defined(_WIN32) -string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { +string ProcessUtil::GetProcessDescription(int64_t pid) { auto process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, static_cast(pid)); if (!process) { return string(); @@ -161,7 +160,7 @@ string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { #else -string ProcessUtil::GetProcessDescription(FileSystem &fs, int64_t pid) { +string ProcessUtil::GetProcessDescription(int64_t pid) { return string(); } diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index 753e5c662..c5de33e71 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -198,9 +198,15 @@ bool CastStatistics::CanPropagate(const LogicalType &source, const LogicalType & // (the ICU extension overrides them at execution time) but Value::DefaultTryCastAs // uses the static, UTC-only operator, so propagated min/max would diverge from // runtime values. See issue #22235. + // The time of day of every timestamp wraps at midnight, as for TIME and TIME_NS above switch (source.id()) { case LogicalTypeId::TIME: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP_NS: case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: return false; default: break; diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index b6d8643d7..e355d501a 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-alpha57096" +#define DUCKDB_PATCH_VERSION "0-alpha57135" #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-alpha57096" +#define DUCKDB_VERSION "v2.1.0-alpha57135" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "e11756ae3a" +#define DUCKDB_SOURCE_ID "620752ed3c" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/common/cgroups.hpp b/src/duckdb/src/include/duckdb/common/cgroups.hpp index 7f2bc6e98..edc5b5391 100644 --- a/src/duckdb/src/include/duckdb/common/cgroups.hpp +++ b/src/duckdb/src/include/duckdb/common/cgroups.hpp @@ -10,14 +10,13 @@ #include "duckdb/common/common.hpp" #include "duckdb/common/optional_idx.hpp" -#include "duckdb/common/file_system.hpp" namespace duckdb { class CGroups { public: - static optional_idx GetMemoryLimit(FileSystem &fs); - static idx_t GetCPULimit(FileSystem &fs, idx_t physical_cores); + static optional_idx GetMemoryLimit(); + static idx_t GetCPULimit(idx_t physical_cores); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 64e90067f..3cb1c14f3 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -636,6 +636,8 @@ enum class SubqueryType : uint8_t; enum class SuggestionState : uint8_t; +enum class SystemFile : uint8_t; + enum class TableColumnType : uint8_t; enum class TableFilterType : uint8_t; @@ -1627,6 +1629,9 @@ const char* EnumUtil::ToChars(SubqueryType value); template<> const char* EnumUtil::ToChars(SuggestionState value); +template<> +const char* EnumUtil::ToChars(SystemFile value); + template<> const char* EnumUtil::ToChars(TableColumnType value); @@ -2660,6 +2665,9 @@ SubqueryType EnumUtil::FromString(const char *value); template<> SuggestionState EnumUtil::FromString(const char *value); +template<> +SystemFile EnumUtil::FromString(const char *value); + template<> TableColumnType EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/process_util.hpp b/src/duckdb/src/include/duckdb/common/process_util.hpp index d046fc1a1..ae676add4 100644 --- a/src/duckdb/src/include/duckdb/common/process_util.hpp +++ b/src/duckdb/src/include/duckdb/common/process_util.hpp @@ -23,7 +23,7 @@ struct ProcessUtil { DUCKDB_API static bool ProcessIsRunning(int64_t pid); //! Best-effort description of a process - its name, and its owner where we can get it - for //! error messages. Empty when the platform cannot say. - DUCKDB_API static string GetProcessDescription(FileSystem &fs, int64_t pid); + DUCKDB_API static string GetProcessDescription(int64_t pid); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 8da914318..54ffc68a2 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -316,9 +316,9 @@ struct DBConfig { DUCKDB_API TypeManager &GetTypeManager(); DUCKDB_API CollationBinding &GetCollationBinding(); DUCKDB_API IndexTypeSet &GetIndexTypes(); - static idx_t GetSystemMaxThreads(FileSystem &fs); - static idx_t GetSystemMaxAsyncThreads(FileSystem &fs); - static idx_t GetSystemAvailableMemory(FileSystem &fs); + static idx_t GetSystemMaxThreads(); + static idx_t GetSystemMaxAsyncThreads(); + static idx_t GetSystemAvailableMemory(); static optional_idx ParseMemoryLimitSlurm(const string &arg); idx_t GetDefaultMaxMemory() const; //! The number of threads used when the threads setting is not set @@ -386,7 +386,7 @@ struct DBConfig { atomic has_disabled_optimizers {false}; //! Cache of GetDefaultThreads, which reads the cgroup CPU limit mutable atomic default_threads {0}; - //! Cache of GetDefaultMaxMemory, which reads the cgroup memory limit through the file system + //! Cache of GetDefaultMaxMemory, which reads the cgroup memory limit mutable atomic default_max_memory {0}; unique_ptr compression_functions; unique_ptr arrow_extensions; diff --git a/src/duckdb/src/include/duckdb/main/os_util.hpp b/src/duckdb/src/include/duckdb/main/os_util.hpp index 95ae40c4f..42bb97946 100644 --- a/src/duckdb/src/include/duckdb/main/os_util.hpp +++ b/src/duckdb/src/include/duckdb/main/os_util.hpp @@ -9,12 +9,31 @@ #pragma once #include "duckdb/common/string.hpp" +#include "duckdb/common/typedefs.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/winapi.hpp" namespace duckdb { class DatabaseInstance; +//! The system files the engine reads to probe the host. Only these can be read through OSUtil::TryReadSystemFile. +enum class SystemFile : uint8_t { + //! /proc/self/cgroup + PROCESS_CGROUPS, + //! /proc//cmdline - the argument is the pid + PROCESS_CMDLINE, + //! /proc//loginuid - the argument is the pid + PROCESS_LOGINUID, + //! cgroup v1 CPU quota and period - the argument is the cgroup path + CGROUP_V1_CPU_QUOTA, + CGROUP_V1_CPU_PERIOD, + //! cgroup v2 CPU quota and period + CGROUP_V2_CPU_MAX, + //! cgroup v1 and v2 memory limits + CGROUP_V1_MEMORY_LIMIT, + CGROUP_V2_MEMORY_MAX +}; + //! Reads process-level state, such as environment variables, on behalf of a database class OSUtil { public: @@ -41,6 +60,10 @@ class OSUtil { //! As above, returning an empty string if the variable is unset DUCKDB_API static string GetConfigurationEnv(const string &name); + //! Reads one of the known system files, regardless of settings. The argument fills in the pid or cgroup path of + //! the file and must be empty for files that have none. Returns false if the file cannot be read. + DUCKDB_API static bool TryReadSystemFile(SystemFile file, const string &argument, string &contents); + private: //! Reads a variable from the process environment, without any checks static bool ReadEnv(const string &name, string &value); diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index aae1fdb15..7fc2fe478 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -698,7 +698,7 @@ idx_t DBConfig::GetDefaultMaxMemory() const { if (default_memory != 0) { return default_memory; } - auto memory = GetSystemAvailableMemory(*file_system); + auto memory = GetSystemAvailableMemory(); if (memory == DBConfigOptions().maximum_memory) { // If GetSystemAvailableMemory returned the default, use it as is default_memory = memory; @@ -706,10 +706,7 @@ idx_t DBConfig::GetDefaultMaxMemory() const { // Otherwise, use 80% of the available memory default_memory = memory * 8 / 10; } - // a user config does not have its final file system yet - if (!is_user_config) { - default_max_memory = default_memory; - } + default_max_memory = default_memory; return default_memory; } @@ -750,7 +747,7 @@ void DBConfig::CheckLock(const Identifier &name) { throw InvalidInputException("Cannot change configuration option %s - the configuration has been locked", name); } -idx_t DBConfig::GetSystemMaxThreads(FileSystem &fs) { +idx_t DBConfig::GetSystemMaxThreads() { #ifdef DUCKDB_NO_THREADS return 1; #else @@ -762,7 +759,7 @@ idx_t DBConfig::GetSystemMaxThreads(FileSystem &fs) { return MaxValue(slurm_threads, 1); } } - return MaxValue(CGroups::GetCPULimit(fs, physical_cores), 1); + return MaxValue(CGroups::GetCPULimit(physical_cores), 1); #else return MaxValue(physical_cores, 1); #endif @@ -777,8 +774,8 @@ static idx_t AsyncThreadsForThreads(idx_t threads) { #endif } -idx_t DBConfig::GetSystemMaxAsyncThreads(FileSystem &fs) { - return AsyncThreadsForThreads(GetSystemMaxThreads(fs)); +idx_t DBConfig::GetSystemMaxAsyncThreads() { + return AsyncThreadsForThreads(GetSystemMaxThreads()); } idx_t DBConfig::GetDefaultThreads() const { @@ -786,11 +783,8 @@ idx_t DBConfig::GetDefaultThreads() const { if (threads != 0) { return threads; } - threads = GetSystemMaxThreads(*file_system); - // a user config does not have its final file system yet - if (!is_user_config) { - default_threads = threads; - } + threads = GetSystemMaxThreads(); + default_threads = threads; return threads; } @@ -798,7 +792,7 @@ idx_t DBConfig::GetDefaultAsyncThreads() const { return AsyncThreadsForThreads(GetDefaultThreads()); } -idx_t DBConfig::GetSystemAvailableMemory(FileSystem &fs) { +idx_t DBConfig::GetSystemAvailableMemory() { // System memory detection auto memory = FileSystem::GetAvailableMemory(); auto available_memory = memory.IsValid() ? memory.GetIndex() : DBConfigOptions().maximum_memory; @@ -816,13 +810,13 @@ idx_t DBConfig::GetSystemAvailableMemory(FileSystem &fs) { } else if (slurm_mem_per_cpu) { auto mem_per_cpu = ParseMemoryLimitSlurm(slurm_mem_per_cpu); if (mem_per_cpu.IsValid()) { - idx_t num_threads = GetSystemMaxThreads(fs); + idx_t num_threads = GetSystemMaxThreads(); return mem_per_cpu.GetIndex() * num_threads; } } // Check cgroup memory limit - auto cgroup_memory_limit = CGroups::GetMemoryLimit(fs); + auto cgroup_memory_limit = CGroups::GetMemoryLimit(); if (cgroup_memory_limit.IsValid()) { auto cgroup_memory_limit_value = cgroup_memory_limit.GetIndex(); return std::min(cgroup_memory_limit_value, available_memory); diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index d04e109ea..88085e2b8 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -568,8 +568,8 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path config.block_allocator = std::move(new_config.block_allocator); if (!config.block_allocator) { auto default_block_size = Settings::Get(config); - config.block_allocator = make_uniq(*config.allocator, default_block_size, - DBConfig::GetSystemAvailableMemory(*config.file_system)); + config.block_allocator = + make_uniq(*config.allocator, default_block_size, DBConfig::GetSystemAvailableMemory()); } config.block_allocator->SetEnabled(config.options.enable_block_allocator); config.replacement_scans = std::move(new_config.replacement_scans); diff --git a/src/duckdb/src/main/http/http_transport_manager.cpp b/src/duckdb/src/main/http/http_transport_manager.cpp index ccedb156c..695b3b6d8 100644 --- a/src/duckdb/src/main/http/http_transport_manager.cpp +++ b/src/duckdb/src/main/http/http_transport_manager.cpp @@ -261,11 +261,10 @@ void HTTPTransportManager::Initialize(const DBConfig &config) { } idx_t HTTPTransportManager::AutomaticCapacity(const DBConfig &config, optional_idx async_threads) { - auto &fs = *config.file_system; if (!async_threads.IsValid()) { async_threads = NumericCast(Settings::Get(config)); } - return CalculateCapacity(DBConfig::GetSystemMaxThreads(fs), FileSystem::GetFileDescriptorLimit(), + return CalculateCapacity(DBConfig::GetSystemMaxThreads(), FileSystem::GetFileDescriptorLimit(), async_threads.GetIndex()); } diff --git a/src/duckdb/src/main/os_util.cpp b/src/duckdb/src/main/os_util.cpp index 6ba4f13ac..7f493359a 100644 --- a/src/duckdb/src/main/os_util.cpp +++ b/src/duckdb/src/main/os_util.cpp @@ -1,10 +1,12 @@ #include "duckdb/main/os_util.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" #include "duckdb/common/windows_util.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/settings.hpp" +#include #include namespace duckdb { @@ -17,6 +19,82 @@ OSUtil &OSUtil::Get(DatabaseInstance &db) { return db.GetOSUtil(); } +static constexpr idx_t MAX_SYSTEM_FILE_SIZE = 65536; + +namespace { + +enum class SystemFileArgument : uint8_t { NONE, PID, CGROUP_PATH }; + +struct SystemFileInfo { + const char *path_format; + SystemFileArgument argument; +}; + +SystemFileInfo GetSystemFileInfo(SystemFile file) { + switch (file) { + case SystemFile::PROCESS_CGROUPS: + return {"/proc/self/cgroup", SystemFileArgument::NONE}; + case SystemFile::PROCESS_CMDLINE: + return {"/proc/%s/cmdline", SystemFileArgument::PID}; + case SystemFile::PROCESS_LOGINUID: + return {"/proc/%s/loginuid", SystemFileArgument::PID}; + case SystemFile::CGROUP_V1_CPU_QUOTA: + return {"/sys/fs/cgroup/cpu%s/cpu.cfs_quota_us", SystemFileArgument::CGROUP_PATH}; + case SystemFile::CGROUP_V1_CPU_PERIOD: + return {"/sys/fs/cgroup/cpu%s/cpu.cfs_period_us", SystemFileArgument::CGROUP_PATH}; + case SystemFile::CGROUP_V2_CPU_MAX: + return {"/sys/fs/cgroup%s/cpu.max", SystemFileArgument::CGROUP_PATH}; + case SystemFile::CGROUP_V1_MEMORY_LIMIT: + return {"/sys/fs/cgroup/memory%s/memory.limit_in_bytes", SystemFileArgument::CGROUP_PATH}; + case SystemFile::CGROUP_V2_MEMORY_MAX: + return {"/sys/fs/cgroup%s/memory.max", SystemFileArgument::CGROUP_PATH}; + default: + throw InternalException("Unknown system file"); + } +} + +bool IsValidSystemFileArgument(SystemFileArgument type, const string &argument) { + switch (type) { + case SystemFileArgument::NONE: + return argument.empty(); + case SystemFileArgument::PID: + return !argument.empty() && argument.find_first_not_of("0123456789") == string::npos; + case SystemFileArgument::CGROUP_PATH: + // empty (the root) or an absolute path that cannot leave the cgroup directory + return argument.empty() || (argument[0] == '/' && argument.find("..") == string::npos); + default: + throw InternalException("Unknown system file argument"); + } +} + +} // namespace + +bool OSUtil::TryReadSystemFile(SystemFile file, const string &argument, string &contents) { + auto info = GetSystemFileInfo(file); + if (!IsValidSystemFileArgument(info.argument, argument)) { + return false; + } + auto path = info.argument == SystemFileArgument::NONE ? string(info.path_format) + : StringUtil::Format(info.path_format, argument); + auto handle = fopen(path.c_str(), "rb"); + if (!handle) { + return false; + } + contents.clear(); + char buffer[4096]; + while (contents.size() < MAX_SYSTEM_FILE_SIZE) { + auto to_read = MinValue(sizeof(buffer), MAX_SYSTEM_FILE_SIZE - contents.size()); + auto bytes_read = fread(buffer, 1, to_read, handle); + contents.append(buffer, bytes_read); + if (bytes_read < to_read) { + break; + } + } + const bool failed = ferror(handle) != 0; + fclose(handle); + return !failed; +} + bool OSUtil::IsConfigurationEnv(const string &name) { // the home directory, the resource limits of the job the database runs in, its proxy and its time zone static const char *CONFIGURATION_ENV[] = { diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index de702a828..517f096d8 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -1277,8 +1277,8 @@ void MaxMemorySetting::OnSet(SettingCallbackInfo &info, Value &input) { throw InvalidInputException("%s setting cannot be NULL", MaxMemorySetting::Name); } // a percentage is relative to the system memory, since resolving it against maximum_memory would be circular - maximum_memory = ParseMemoryLimitOrPercentage( - input.ToString(), [&]() { return DBConfig::GetSystemAvailableMemory(*info.config.file_system); }); + maximum_memory = + ParseMemoryLimitOrPercentage(input.ToString(), [&]() { return DBConfig::GetSystemAvailableMemory(); }); } if (info.db) { BufferManager::GetBufferManager(*info.db).SetMemoryLimit(maximum_memory); diff --git a/src/duckdb/src/optimizer/projection_placement.cpp b/src/duckdb/src/optimizer/projection_placement.cpp index e2023d486..51fc9b934 100644 --- a/src/duckdb/src/optimizer/projection_placement.cpp +++ b/src/duckdb/src/optimizer/projection_placement.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/projection_placement.hpp" +#include "duckdb/function/scalar/compressed_materialization_utils.hpp" #include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/optimizer/expression_heuristics.hpp" #include "duckdb/optimizer/optimizer.hpp" @@ -289,8 +290,10 @@ static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_in const column_binding_map_t> &statistics_map, const column_binding_map_t &reading_expressions, LiftPlacement &result) { auto &expression = *projection.expressions[expression_index]; + // Preserve the placement chosen by compressed materialization. if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || expression.IsVolatile() || - expression.CanThrow() || !projection.children[0]->has_estimated_cardinality) { + expression.CanThrow() || CMUtils::GetWrappedInput(expression) || + !projection.children[0]->has_estimated_cardinality) { return false; } @@ -767,8 +770,10 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, const column_binding_map_t> &statistics_map, const column_binding_map_t &reading_expressions, ExpressionPlacement &result) { auto &expression = *projection.expressions[expression_index]; + // Preserve the placement chosen by compressed materialization. if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || expression.IsVolatile() || - expression.CanThrow() || !projection.children[0]->has_estimated_cardinality) { + expression.CanThrow() || CMUtils::GetWrappedInput(expression) || + !projection.children[0]->has_estimated_cardinality) { return false; }