diff --git a/ci/jobs/scripts/check_style/check_cpp.sh b/ci/jobs/scripts/check_style/check_cpp.sh index d8bfce5d2b5a..d07e285cb70b 100755 --- a/ci/jobs/scripts/check_style/check_cpp.sh +++ b/ci/jobs/scripts/check_style/check_cpp.sh @@ -94,6 +94,8 @@ EXTERN_TYPES_EXCLUDES=( ProfileEvents::ValueType ProfileEvents::dumpToMapColumn ProfileEvents::getProfileEvents + ProfileEvents::getSampleBlock + ProfileEvents::checkBlockStructure ProfileEvents::ThreadIdToCountersSnapshot ProfileEvents::LOCAL_NAME ProfileEvents::keeper_profile_events diff --git a/ci/jobs/scripts/integration_tests_configs.py b/ci/jobs/scripts/integration_tests_configs.py index a8a9184c849b..b768b53f10a5 100644 --- a/ci/jobs/scripts/integration_tests_configs.py +++ b/ci/jobs/scripts/integration_tests_configs.py @@ -425,7 +425,6 @@ def force_heavy_modules_sequential( test_jbod_ha/test.py 79681 test_remote_blobs_naming/test_backward_compatibility.py 79599 test_replicated_merge_tree_compatibility/test.py 79514 -test_store_cleanup/test.py 79320 test_paimon_incremental_read/test.py 79095 test_storage_iceberg_with_spark/test_metadata_file_format_with_uuid.py 78918 test_system_flush_logs/test.py 78482 diff --git a/ci/tests/data/integration_test_durations_sample.tsv b/ci/tests/data/integration_test_durations_sample.tsv index 55fbf44d0ff0..6d85307a7032 100644 --- a/ci/tests/data/integration_test_durations_sample.tsv +++ b/ci/tests/data/integration_test_durations_sample.tsv @@ -317,7 +317,6 @@ test_keeper_opentelemetry_tracing/test.py 82072 test_refreshable_mv_watch_fault/test.py 81637 test_always_fetch_merged/test.py 80848 test_system_flush_logs/test.py 80564 -test_store_cleanup/test.py 80458 test_rmv_access_denied_on_rename_race/test.py 80328 test_replicated_merge_tree_compatibility/test.py 79758 test_clickhouse_server_wait_server_pool/test.py 79623 diff --git a/cmake/autogenerated_versions.txt b/cmake/autogenerated_versions.txt index 4f1005f2919c..6111570a7bf2 100644 --- a/cmake/autogenerated_versions.txt +++ b/cmake/autogenerated_versions.txt @@ -2,13 +2,13 @@ # NOTE: VERSION_REVISION has nothing common with DBMS_TCP_PROTOCOL_VERSION, # only DBMS_TCP_PROTOCOL_VERSION should be incremented on protocol changes. -SET(VERSION_REVISION 54551) +SET(VERSION_REVISION 54566) SET(VERSION_MAJOR 26) SET(VERSION_MINOR 8) -SET(VERSION_PATCH 39) -SET(VERSION_GITHASH 71391c9b2bbc4d2c104996451586a396138a4785) -SET(VERSION_DESCRIBE v26.8.39.1-lts) -SET(VERSION_STRING 26.8.39.1) +SET(VERSION_PATCH 54) +SET(VERSION_GITHASH cb5e492e954c7689d2eb953a3a8665c160d8ac37) +SET(VERSION_DESCRIBE v26.8.54.1-lts) +SET(VERSION_STRING 26.8.54.1) # end of autochange # Note (strtgbb): diff --git a/contrib/chdig b/contrib/chdig index a28e1072f6e2..af4005a0dba2 160000 --- a/contrib/chdig +++ b/contrib/chdig @@ -1 +1 @@ -Subproject commit a28e1072f6e2aeb98116ae6f6ecda06d57e877ff +Subproject commit af4005a0dba22924bb295c0986d481f037e0d802 diff --git a/contrib/chdig-cmake/CMakeLists.txt b/contrib/chdig-cmake/CMakeLists.txt index 9dfb54411ba3..d5d45c612ab2 100644 --- a/contrib/chdig-cmake/CMakeLists.txt +++ b/contrib/chdig-cmake/CMakeLists.txt @@ -17,10 +17,10 @@ if (NOT ENABLE_CHDIG OR NOT ENABLE_RUST) return() endif() -clickhouse_import_crate(MANIFEST_PATH ../chdig/Cargo.toml FEATURES tls) -clickhouse_config_crate_flags(chdig) -add_library(ch_rust::chdig ALIAS chdig) +clickhouse_import_crate(MANIFEST_PATH Cargo.toml) +clickhouse_config_crate_flags(_ch_rust_chdig) +add_library(ch_rust::chdig ALIAS _ch_rust_chdig) if (OS_DARWIN) - target_link_libraries(chdig INTERFACE "-framework AppKit") + target_link_libraries(_ch_rust_chdig INTERFACE "-framework AppKit") endif() diff --git a/contrib/chdig-cmake/Cargo.lock b/contrib/chdig-cmake/Cargo.lock new file mode 100644 index 000000000000..26ec2ffdc050 --- /dev/null +++ b/contrib/chdig-cmake/Cargo.lock @@ -0,0 +1,2658 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "_ch_rust_chdig" +version = "0.1.0" +dependencies = [ + "chdig", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chdig" +version = "26.11.1" +dependencies = [ + "aes-gcm", + "anyhow", + "base64", + "chrono", + "chrono-tz", + "clap", + "clap_complete", + "clickhouse-rs", + "crossbeam-channel", + "crossterm", + "flamelens", + "flate2", + "flexi_logger", + "futures", + "futures-util", + "fuzzy-matcher", + "getrandom 0.2.17", + "humantime", + "libc", + "log", + "percent-encoding", + "perfetto_protos", + "protobuf", + "quick-xml", + "ratatui", + "regex", + "semver", + "serde", + "serde_json", + "serde_norway", + "signal-hook", + "size", + "strfmt", + "tempfile", + "tiny_http", + "tokio", + "unicode-width", + "url", + "uuid", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "chrono-tz" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59ae0466b83e838b81a54256c39d5d7c20b9d7daa10510a242d9b75abd5936e" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433e39f13c9a060046954e0592a8d0a4bcb1040125cbf91cb8ee58964cfb350f" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clickhouse-rs" +version = "1.1.0-alpha.1" +source = "git+https://github.com/azat-rust/clickhouse-rs?branch=next#50f683f0ae358d784c34eb0545c056fa3939c502" +dependencies = [ + "byteorder", + "cfg-if", + "chrono", + "chrono-tz", + "clickhouse-rs-cityhash-sys", + "combine", + "crossbeam-queue", + "either", + "futures-core", + "futures-sink", + "futures-util", + "hostname", + "lazy_static", + "log", + "lz4", + "percent-encoding", + "pin-project", + "rustls", + "thiserror 2.0.21", + "tokio", + "tokio-rustls", + "url", + "uuid", + "webpki-roots", +] + +[[package]] +name = "clickhouse-rs-cityhash-sys" +version = "0.1.2" +source = "git+https://github.com/azat-rust/clickhouse-rs?branch=next#50f683f0ae358d784c34eb0545c056fa3939c502" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags", + "crossterm_winapi", + "derive_more", + "document-features", + "filedescriptor", + "mio", + "parking_lot", + "rustix 1.1.6", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flamelens" +version = "0.4.0" +source = "git+https://github.com/azat-rust/flamelens?branch=chdig#40706414c879da3359acd432547c05938c47bad0" +dependencies = [ + "anyhow", + "cfg-if", + "clap", + "crossterm", + "ratatui", + "regex", + "serde", + "serde_json", + "tui-input", +] + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "flexi_logger" +version = "0.27.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469e584c031833564840fb0cdbce99bdfe946fd45480a188545e73a76f45461c" +dependencies = [ + "chrono", + "glob", + "lazy_static", + "log", + "thiserror 1.0.69", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fuzzy-matcher" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" +dependencies = [ + "thread_local", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867" +dependencies = [ + "libc", + "match_cfg", + "winapi", +] + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "lz4" +version = "1.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" +dependencies = [ + "lz4-sys", +] + +[[package]] +name = "lz4-sys" +version = "1.11.1+lz4-1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "match_cfg" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "perfetto_protos" +version = "0.51.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634f88ebef917643d9e470dbf99637fbfa8295f54525954d156641f06823f9ac" +dependencies = [ + "protobuf", + "protobuf-codegen", + "protoc-bin-vendored", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "protobuf" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d65a1d4ddae7d8b5de68153b48f6aa3bba8cb002b243dbdbc55a5afbc98f99f4" +dependencies = [ + "once_cell", + "protobuf-support", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-codegen" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d3976825c0014bbd2f3b34f0001876604fe87e0c86cd8fa54251530f1544ace" +dependencies = [ + "anyhow", + "once_cell", + "protobuf", + "protobuf-parse", + "regex", + "tempfile", + "thiserror 1.0.69", +] + +[[package]] +name = "protobuf-parse" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4aeaa1f2460f1d348eeaeed86aea999ce98c1bded6f089ff8514c9d9dbdc973" +dependencies = [ + "anyhow", + "indexmap", + "log", + "protobuf", + "protobuf-support", + "tempfile", + "thiserror 1.0.69", + "which", +] + +[[package]] +name = "protobuf-support" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e36c2f31e0a47f9280fb347ef5e461ffcd2c52dd520d8e216b52f93b0b0d7d6" +dependencies = [ + "thiserror 1.0.69", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8760a25b6ff9c620324822737e468478fa092234190d2e449760344354896ed9" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fa2624782ca04cd44f51554566717377acd240e4c0016d757dd74fccc9324f" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2417e9817fa237dab803ad4dda7357a111656e242959cc6b8f9a1a583367d42" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d189c34636356a46a7ed3188233dc8a88c431278cc54d4a19b096a2d270e985" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171e39f1e846e5f322ced1ac3b8d4cd3a3833ca24b6e5d58b3632574fe6204fa" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873cdcc097593432086661aa432b8078f1cd87bfb02847c332e98ae2c119e966" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb72df001783b8297847fe8f5f874ee400fd742c843d60583e8c23d96977c7f" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04652167eca899dda05f32f5481adeaf25c623a98ce2fc146a001cc59a2add7" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263a3f48f01e7309e857138bd47f785585b4a005e8e56c6d2824ce91195999c3" + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" +dependencies = [ + "bitflags", + "compact_str", + "critical-section", + "hashbrown", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", + "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags", + "hashbrown", + "indoc", + "instability", + "itertools", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_norway" +version = "0.9.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml-norway", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c48f464f8e2766494cb2223d1683ff6801dd56f0d07298500f9c970de2571cf0" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strfmt" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046d549b88a663d317cd04d39696fca5f77db4db44e1db65bfb9dee7f9e680bd" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tui-input" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4fa0cb7933d19f91eb3109781bf7297d5e4cba57e857d97a29b9465d3383f56" +dependencies = [ + "crossterm", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "unsafe-libyaml-norway" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/contrib/chdig-cmake/Cargo.toml b/contrib/chdig-cmake/Cargo.toml new file mode 100644 index 000000000000..d36786053af7 --- /dev/null +++ b/contrib/chdig-cmake/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "_ch_rust_chdig" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["staticlib"] + +[dependencies] +chdig = { path = "../chdig", default-features = false, features = ["tls"] } + +# Standalone, so that the lock in this directory is used instead of the one in `chdig` +[workspace] diff --git a/contrib/chdig-cmake/src/lib.rs b/contrib/chdig-cmake/src/lib.rs new file mode 100644 index 000000000000..4a18a6b2ef29 --- /dev/null +++ b/contrib/chdig-cmake/src/lib.rs @@ -0,0 +1 @@ +pub use chdig; diff --git a/contrib/delta-kernel-rs b/contrib/delta-kernel-rs index 3ae30627f181..32287c524706 160000 --- a/contrib/delta-kernel-rs +++ b/contrib/delta-kernel-rs @@ -1 +1 @@ -Subproject commit 3ae30627f181f4445b756d95ac1ad573d1c666a9 +Subproject commit 32287c524706da4114a624f652d70749efd8615c diff --git a/contrib/krb5 b/contrib/krb5 index 857c2d1edd7a..17f660ca561d 160000 --- a/contrib/krb5 +++ b/contrib/krb5 @@ -1 +1 @@ -Subproject commit 857c2d1edd7a4218b84594768587aa53fd63da9e +Subproject commit 17f660ca561db6716125041396ce2cdd8ebd594a diff --git a/contrib/krb5-cmake/autoconf_darwin.h b/contrib/krb5-cmake/autoconf_darwin.h index 64c28f90b41b..7c7ee22fa1ff 100644 --- a/contrib/krb5-cmake/autoconf_darwin.h +++ b/contrib/krb5-cmake/autoconf_darwin.h @@ -635,7 +635,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -644,7 +644,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ #define POSIX_SETJMP 1 diff --git a/contrib/krb5-cmake/autoconf_linux.h b/contrib/krb5-cmake/autoconf_linux.h index ec8e867eec38..efa76cd145fc 100644 --- a/contrib/krb5-cmake/autoconf_linux.h +++ b/contrib/krb5-cmake/autoconf_linux.h @@ -637,7 +637,7 @@ #define PACKAGE_NAME "Kerberos 5" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Kerberos 5 1.22.1" +#define PACKAGE_STRING "Kerberos 5 1.22.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "krb5" @@ -646,7 +646,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "1.22.1" +#define PACKAGE_VERSION "1.22.3" /* Define if setjmp indicates POSIX interface */ /* #undef POSIX_SETJMP */ diff --git a/contrib/lz4 b/contrib/lz4 index ebb370ca83af..aa4647fad575 160000 --- a/contrib/lz4 +++ b/contrib/lz4 @@ -1 +1 @@ -Subproject commit ebb370ca83af193212df4dcbadcc5d87bc0de2f0 +Subproject commit aa4647fad575d01a874aaaadcdbe8e6a40e072f5 diff --git a/contrib/mongo-c-driver b/contrib/mongo-c-driver index 58b4e1f39c6f..bc3a26beeb18 160000 --- a/contrib/mongo-c-driver +++ b/contrib/mongo-c-driver @@ -1 +1 @@ -Subproject commit 58b4e1f39c6f8bcf4da4204deb84f9b3527388d4 +Subproject commit bc3a26beeb18da7d0f8e1704618ac09ce74531c1 diff --git a/contrib/mongo-c-driver-cmake/CMakeLists.txt b/contrib/mongo-c-driver-cmake/CMakeLists.txt index 6d013bc450fa..815aa4451ea2 100644 --- a/contrib/mongo-c-driver-cmake/CMakeLists.txt +++ b/contrib/mongo-c-driver-cmake/CMakeLists.txt @@ -6,12 +6,12 @@ endif() set(libbson_VERSION_MAJOR 2) set(libbson_VERSION_MINOR 5) -set(libbson_VERSION_PATCH 8) -set(libbson_VERSION 2.5.8) +set(libbson_VERSION_PATCH 10) +set(libbson_VERSION 2.5.10) set(libmongoc_VERSION_MAJOR 2) set(libmongoc_VERSION_MINOR 5) -set(libmongoc_VERSION_PATCH 8) -set(libmongoc_VERSION 2.5.8) +set(libmongoc_VERSION_PATCH 10) +set(libmongoc_VERSION 2.5.10) set(LIBBSON_SOURCES_ROOT "${ClickHouse_SOURCE_DIR}/contrib/mongo-c-driver/src") set(LIBBSON_SOURCE_DIR "${LIBBSON_SOURCES_ROOT}/libbson/src") diff --git a/contrib/postgres b/contrib/postgres index ab6952af3ac8..c7649becd213 160000 --- a/contrib/postgres +++ b/contrib/postgres @@ -1 +1 @@ -Subproject commit ab6952af3ac8cdede654be4dc68f990b0352c213 +Subproject commit c7649becd213231466df7e679154e8ac0f744788 diff --git a/contrib/postgres-cmake/pg_config.h b/contrib/postgres-cmake/pg_config.h index 84e435838d41..9df1b95a3b33 100644 --- a/contrib/postgres-cmake/pg_config.h +++ b/contrib/postgres-cmake/pg_config.h @@ -593,7 +593,7 @@ #define PACKAGE_NAME "PostgreSQL" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "PostgreSQL 18.3" +#define PACKAGE_STRING "PostgreSQL 18.6" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "postgresql" @@ -602,7 +602,7 @@ #define PACKAGE_URL "https://www.postgresql.org/" /* Define to the version of this package. */ -#define PACKAGE_VERSION "18.3" +#define PACKAGE_VERSION "18.6" /* Define to the name of a signed 128-bit integer type. */ #define PG_INT128_TYPE __int128 @@ -618,7 +618,7 @@ #define PG_MAJORVERSION_NUM 18 /* PostgreSQL minor version number */ -#define PG_MINORVERSION_NUM 4 +#define PG_MINORVERSION_NUM 6 /* Define to best C++ printf format archetype, usually gnu_printf if available. */ @@ -629,13 +629,13 @@ #define PG_C_PRINTF_ATTRIBUTE gnu_printf /* PostgreSQL version as a string */ -#define PG_VERSION "18.4" +#define PG_VERSION "18.6" /* PostgreSQL version as a number */ -#define PG_VERSION_NUM 180004 +#define PG_VERSION_NUM 180006 /* A string containing the version number, platform, and C compiler */ -#define PG_VERSION_STR "PostgreSQL 18.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 15.2.1 20250813, 64-bit" +#define PG_VERSION_STR "PostgreSQL 18.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 15.2.1 20250813, 64-bit" /* Define to 1 to allow profiling output to be saved separately for each process. */ diff --git a/contrib/rust_vendor b/contrib/rust_vendor index c4fd435abe86..11cea4f35a9a 160000 --- a/contrib/rust_vendor +++ b/contrib/rust_vendor @@ -1 +1 @@ -Subproject commit c4fd435abe8696742d992306a2c6f48a2e57e3ae +Subproject commit 11cea4f35a9a6184e391d76333aea8662c6e3c1d diff --git a/contrib/wasmtime b/contrib/wasmtime index 561b224fd058..1c05b58b727c 160000 --- a/contrib/wasmtime +++ b/contrib/wasmtime @@ -1 +1 @@ -Subproject commit 561b224fd0589a02fc9e7bcef1aeb70d886d33c0 +Subproject commit 1c05b58b727cdb87dfdc8f076feef2b1666e6a53 diff --git a/contrib/zlib-ng b/contrib/zlib-ng index a2fbeffdc30a..a7943f5947a9 160000 --- a/contrib/zlib-ng +++ b/contrib/zlib-ng @@ -1 +1 @@ -Subproject commit a2fbeffdc30a8b0ce6d54ee31208e2688eac4c9f +Subproject commit a7943f5947a9533b4efbbf48915764ac73211431 diff --git a/contrib/zstd b/contrib/zstd index 5b3e9e8fd277..1663170820f4 160000 --- a/contrib/zstd +++ b/contrib/zstd @@ -1 +1 @@ -Subproject commit 5b3e9e8fd2779260101a07e6cc7b34fd8764617f +Subproject commit 1663170820f4825123ddfc4976223ad2c78b21cc diff --git a/docker/keeper/Dockerfile b/docker/keeper/Dockerfile index 85b7712ef4ac..2f044c8864cb 100644 --- a/docker/keeper/Dockerfile +++ b/docker/keeper/Dockerfile @@ -61,6 +61,10 @@ RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ ARG WGET_RETRIES=5 ARG WGET_RETRY_DELAY=1 +# `apk upgrade` runs first because `apk add` never bumps packages already in the base +# image, so without it the image keeps whatever (possibly vulnerable) libssl3 the +# `alpine` snapshot had at build time. +# # `apk` has no retry option, and it does not treat a failed repository index fetch # as fatal: it proceeds with an empty index, so every requested package is then # reported as `no such package`. @@ -83,7 +87,7 @@ RUN arch=${TARGETARCH:-amd64} \ && apk_add_with_retry() { \ local attempt=1; \ while [ "$attempt" -le "${APK_RETRIES}" ]; do \ - if apk add --no-cache "$@"; then return 0; fi; \ + if apk upgrade --no-cache && apk add --no-cache "$@"; then return 0; fi; \ echo "Attempt $attempt/${APK_RETRIES} failed for apk add $*, retrying in ${APK_RETRY_DELAY}s..."; \ sleep "${APK_RETRY_DELAY}"; \ attempt=$((attempt + 1)); \ diff --git a/docker/server/Dockerfile.alpine b/docker/server/Dockerfile.alpine index 3aaf63a034b4..4de58ea346fd 100644 --- a/docker/server/Dockerfile.alpine +++ b/docker/server/Dockerfile.alpine @@ -55,6 +55,10 @@ RUN addgroup -S -g "${DEFAULT_GID}" clickhouse && \ ARG WGET_RETRIES=5 ARG WGET_RETRY_DELAY=1 +# `apk upgrade` runs first because `apk add` never bumps packages already in the base +# image, so without it the image keeps whatever (possibly vulnerable) libssl3 the +# `alpine` snapshot had at build time. +# # `apk` has no retry option, and it does not treat a failed repository index fetch # as fatal: it proceeds with an empty index, so every requested package is then # reported as `no such package`. @@ -76,7 +80,7 @@ RUN arch=${TARGETARCH:-amd64} \ && apk_add_with_retry() { \ local attempt=1; \ while [ "$attempt" -le "${APK_RETRIES}" ]; do \ - if apk add --no-cache "$@"; then return 0; fi; \ + if apk upgrade --no-cache && apk add --no-cache "$@"; then return 0; fi; \ echo "Attempt $attempt/${APK_RETRIES} failed for apk add $*, retrying in ${APK_RETRY_DELAY}s..."; \ sleep "${APK_RETRY_DELAY}"; \ attempt=$((attempt + 1)); \ diff --git a/docs/concepts/features/interfaces/http.mdx b/docs/concepts/features/interfaces/http.mdx index ee87cf7216b6..0aad852e197a 100644 --- a/docs/concepts/features/interfaces/http.mdx +++ b/docs/concepts/features/interfaces/http.mdx @@ -644,7 +644,7 @@ curl -sS "http://localhost:8123?role=my_role&role=my_other_role" --data-binary " In this case, `?role=my_role&role=my_other_role` works similarly to executing `SET ROLE my_role, my_other_role` before the statement. -The `role` query parameter is not affected by the `access_control_improvements.readonly_restricts_set_role` server setting, which refuses only the `SET ROLE` statement. +The `role` query parameter is not affected by the `access_control_improvements.readonly_restricts_set_role` server setting, which refuses only the `SET ROLE` and `SET DEFAULT ROLE` statements. ## HTTP response codes caveats {#http_response_codes_caveats} diff --git a/docs/en/sql-reference/statements/create/handler.md b/docs/en/sql-reference/statements/create/handler.md index 5b1a2ebfc1fb..4707ae70eef7 100644 --- a/docs/en/sql-reference/statements/create/handler.md +++ b/docs/en/sql-reference/statements/create/handler.md @@ -48,7 +48,7 @@ The functions [`currentHandler`](/sql-reference/functions/other-functions#curren ## Access control {#access-control} -`CREATE HANDLER`, `DROP HANDLER` and `ALTER HANDLER` require the `CREATE HANDLER`, `DROP HANDLER` and `ALTER HANDLER` grants respectively. +`CREATE HANDLER`, `DROP HANDLER` and `ALTER HANDLER` require the `CREATE HANDLER`, `DROP HANDLER` and `ALTER HANDLER` grants respectively. These privileges and `SHOW HANDLERS` form the `HANDLER ADMIN` privilege group; they are not part of the `CREATE`, `ALTER` and `DROP` privilege groups. Reading the [`system.handlers`](/operations/system-tables/handlers) table requires the `SHOW HANDLERS` grant. Secrets that may be embedded in a handler's query are masked there unless the user is additionally allowed to see secrets (see [`system.handlers`](/operations/system-tables/handlers)). diff --git a/docs/reference/functions/regular-functions/ai-functions.mdx b/docs/reference/functions/regular-functions/ai-functions.mdx index 2cb7851fbf60..bb6ec61986ad 100644 --- a/docs/reference/functions/regular-functions/ai-functions.mdx +++ b/docs/reference/functions/regular-functions/ai-functions.mdx @@ -229,24 +229,49 @@ AI function activity is tracked through ClickHouse [ProfileEvents](/reference/sy | ProfileEvent | Description | |-------|-------------| | `AIAPICalls` | Number of HTTP requests made to the AI provider. | -| `AIInputTokens` | Total input tokens consumed. | +| `AIInputTokens` | Total input tokens consumed, including cache reads and writes. | | `AIOutputTokens` | Total output tokens consumed. | +| `AICacheReadTokens` | Input tokens read from the provider's prompt cache. | +| `AICacheWriteTokens` | Input tokens written to the provider's prompt cache. | +| `AIRequestMicroseconds` | Total time spent in AI provider calls (request serialization, HTTP round trip, response parsing), including failed attempts, excluding retry backoff. | +| `AIRetryBackoffMicroseconds` | Total time spent waiting before retries of failed AI provider calls. | | `AIRowsProcessed` | Number of rows that received a result. | | `AIRowsSkipped` | Number of rows skipped (quota exceeded, or error with `ai_function_throw_on_error = 0`). | +Times are summed across executions and threads, so they can exceed query wall-clock time. +Divide `AIRequestMicroseconds` by `AIAPICalls` to get mean request latency, including failed attempts. +These counters are per-query, they do not provide per-request latency information. +If a query calls multiple AI functions, their counts are added together. + +Cache counters are subsets of `AIInputTokens`, not additional tokens. They report provider-emitted cache reads/writes, not any internal ClickHouse caching. A provider that omits cache usage contributes +zero cache tokens. + Query these events: ```sql +SYSTEM FLUSH LOGS; + SELECT + query_duration_ms, ProfileEvents['AIAPICalls'] AS api_calls, + ProfileEvents['AIRequestMicroseconds'] / 1000 AS request_ms, + request_ms / nullIf(api_calls, 0) AS mean_request_ms, + ProfileEvents['AIRetryBackoffMicroseconds'] / 1000 AS retry_backoff_ms, + ProfileEvents['AIRowsProcessed'] AS rows_processed, + ProfileEvents['AIRowsSkipped'] AS rows_skipped, ProfileEvents['AIInputTokens'] AS input_tokens, - ProfileEvents['AIOutputTokens'] AS output_tokens + ProfileEvents['AIOutputTokens'] AS output_tokens, + ProfileEvents['AICacheReadTokens'] AS cache_read_tokens, + ProfileEvents['AICacheWriteTokens'] AS cache_write_tokens FROM system.query_log WHERE query_id = 'query_id' -AND type = 'QueryFinish' +AND type IN ('QueryFinish', 'ExceptionWhileProcessing') ORDER BY event_time DESC; ``` +`log_queries` and `log_profile_events` are enabled by default to record these events in `system.query_log`. +Server-wide totals are also available in `system.events`. + {/* The inner content of the tags below are replaced at doc framework build time with docs generated from system.functions. Please do not modify or remove the tags. diff --git a/docs/reference/interfaces/specs/NativeFormat.mdx b/docs/reference/interfaces/specs/NativeFormat.mdx index 301aaa82b489..6f24fb27d908 100644 --- a/docs/reference/interfaces/specs/NativeFormat.mdx +++ b/docs/reference/interfaces/specs/NativeFormat.mdx @@ -203,7 +203,8 @@ The `count` is the full stack length **including the leading `DEFAULT` entry** t Note that this order is not the order of the kind byte values above. Any other stack describes a column layout no writer builds and that no materialization step unwraps back to a full column of the declared type — a `ColumnSparse` whose values column is itself sparse or replicated, for instance, stays wrapped. -**Recursive `kind_stack` for `Tuple` columns.** The `kind_stack` payload above is the byte (or `COMBINATION` sequence) for one column's own serialization info. A `Tuple` carries a `SerializationInfoTuple`, which first writes the tuple's *own* kind-stack payload and then writes one full kind-stack payload for *each* element, in order; a decoder reads back the same recursive structure. So for `Tuple(A, B, C)` the field-4 bytes are `[tuple_kind][A_kind][B_kind][C_kind]`, and each element payload is itself recursive if that element is again a composite. The `has_custom_serialization` byte (field 3) is set whenever the tuple's own info *or any element's* info is non-default, so a `Tuple` whose only special element is sparse or replicated still triggers the kind-stack payload. A decoder that reads only the single leading enum byte for a `Tuple` will stop too early and misread the remaining element-kind bytes as column data. +**Recursive `kind_stack` for `Tuple` columns.** The `kind_stack` payload above is the byte (or `COMBINATION` sequence) for one column's own serialization info. A `Tuple` carries a `SerializationInfoTuple`, which first writes the tuple's *own* kind-stack payload and then writes one full kind-stack payload for *each* element, in order; a decoder reads back the same recursive structure. So for `Tuple(A, B, C)` the field-4 bytes are `[tuple_kind][A_kind][B_kind][C_kind]`, and each element payload is itself recursive if that element is again a composite. The `has_custom_serialization` byte (field 3) is set whenever the tuple's own info *or any element's* info is non-default, so a `Tuple` whose only special element is sparse still triggers the kind-stack payload. A decoder that reads only the single leading enum byte for a `Tuple` will stop too early and misread the remaining element-kind bytes as column data. +An element's stack never contains `REPLICATED` or `DETACHED`: both wrap a whole top-level column only, and a decoder rejects either of them in an element stack with `INCORRECT_DATA`. **Sparse wire format.** When `kind_stack = 0x01`, the column `data` is two streams written back-to-back in the single shared TCP stream: @@ -237,7 +238,10 @@ A decoder reconstructs a dense column by selecting `elements[indexes[i]]` for ea If the wrapped column was sparse, its stack is `{DEFAULT, SPARSE, DETACHED}`, which serializes as `DETACHED_OVER_SPARSE`. A client decoding such a column reads the blob length and bytes, then decompresses the blob to recover the inner column payload (see the [`ColumnBLOB` note](#compression-negotiation) under compression). -`DETACHED` is directional: it may appear only in result blocks sent by a server, and only for a whole top-level column — never as one of the element kinds of a `Tuple`. Unlike the other kinds, it makes the runtime column a `ColumnBLOB` instead of the column of the declared type, so a receiver accepts it only when its own pipeline converts the blob back. A server therefore rejects `DETACHED` in any block a client sends — external table data, scalars and insert data alike — with `INCORRECT_DATA`. +`DETACHED` is directional: it may appear only in result blocks sent by a server, and only for a whole top-level column — never as one of the element kinds of a `Tuple`. Unlike the other kinds, it makes the runtime column a `ColumnBLOB` instead of the column of the declared type, so a receiver accepts it only when its own pipeline converts the blob back. + +**Kinds in blocks sent to a server.** Every non-default kind is directional: it appears only in result blocks sent by a server. +A block sent to a server — insert data, the data of the `input` table function, external table data and scalars, whether it comes from a client or from another server — carries only `DEFAULT` stacks: senders convert the columns to full ones before sending, and a server rejects any other kind in such a block with `INCORRECT_DATA`. ### Block variants {#block-variants} diff --git a/docs/reference/interfaces/specs/NativeProtocol.mdx b/docs/reference/interfaces/specs/NativeProtocol.mdx index 55c8b3fc3447..42a4427a6fd7 100644 --- a/docs/reference/interfaces/specs/NativeProtocol.mdx +++ b/docs/reference/interfaces/specs/NativeProtocol.mdx @@ -779,6 +779,10 @@ The 8 columns, in this exact order: | 7 | source | String | Logger name | | 8 | text | String | Log message text | + +A server that receives the packet from another server of a distributed query forwards the rows to its own client only if the block has exactly this schema: the same number, order, names and types of the columns, each in the default [serialization kind](/reference/interfaces/specs/NativeFormat#kind-stack-and-sparse-encoding). It drops a block of any other structure and logs a warning. + + ### ProfileEvents (packet type 14) {#profileevents} Server → Client. Carries per-query performance counters. @@ -798,12 +802,14 @@ The 6 columns: | 1 | host_name | String | Server hostname | | 2 | current_time | DateTime | Event timestamp | | 3 | thread_id | UInt64 | Thread ID | -| 4 | type | Enum8 | Event type: 1 = Increment (counter), 2 = Gauge. The underlying storage is one signed byte. | +| 4 | type | Enum8 | Event type: 1 = Increment (counter), 2 = Gauge. The underlying storage is one signed byte. The full type is `Enum8('increment' = 1, 'gauge' = 2)`. | | 5 | name | String | Event name (e.g., `"Query"`, `"NetworkReceiveBytes"`) | | 6 | value | Int64 | Counter value or gauge reading | -The `value` column's element type is not fixed across packets — older servers emit `UInt64`, newer ones `Int64`. Read the column's type string from the block header rather than assuming one width. +A server at revision 54450 emits the `value` column as `UInt64` and fills it with the total values of the counters instead of their increments. ClickHouse reads such a packet and discards its contents. + +From revision 54451 the schema is exact. ClickHouse, both as a client and as a server that receives the packet from another server of a distributed query, refuses a block that differs from it in the number, the order, the names or the types of the columns, or that carries a column in a non-default [serialization kind](/reference/interfaces/specs/NativeFormat#kind-stack-and-sparse-encoding), with the `UNEXPECTED_PACKET_FROM_SERVER` error. ### TableColumns (packet type 11) {#tablecolumns} diff --git a/docs/reference/settings/server-settings/_server_settings_outside_source.mdx b/docs/reference/settings/server-settings/_server_settings_outside_source.mdx index f72dee549231..a8acfb984546 100644 --- a/docs/reference/settings/server-settings/_server_settings_outside_source.mdx +++ b/docs/reference/settings/server-settings/_server_settings_outside_source.mdx @@ -1820,7 +1820,7 @@ Settings for optional improvements in the access control system. | Setting | Description | Default | |-------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| | `on_cluster_queries_require_cluster_grant` | Sets whether `ON CLUSTER` queries require the `CLUSTER` grant. | `true` | -| `readonly_restricts_set_role` | Sets whether the `SET ROLE` statement is refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`. The `role` HTTP query parameter is not affected. | `false` | +| `readonly_restricts_set_role` | Sets whether the `SET ROLE` and `SET DEFAULT ROLE` statements are refused when the session or the query is readonly. When `false`, `readonly` does not restrict `SET ROLE`, nor `SET DEFAULT ROLE ... TO CURRENT_USER`. The `role` HTTP query parameter is not affected. | `false` | | `role_cache_expiration_time_seconds` | Sets the number of seconds since last access, that a role is stored in the Role Cache. | `600` | | `select_from_information_schema_requires_grant` | Sets whether `SELECT * FROM information_schema.` requires any grants and can be executed by any user. If set to true, then this query requires `GRANT SELECT ON information_schema.
`, just as for ordinary tables. | `true` | | `select_from_system_db_requires_grant` | Sets whether `SELECT * FROM system.
` requires any grants and can be executed by any user. If set to true then this query requires `GRANT SELECT ON system.
` just as for non-system tables. Exceptions: a few system tables (`tables`, `columns`, `databases`, and some constant tables like `one`, `contributors`) are still accessible for everyone; and if there is a `SHOW` privilege (e.g. `SHOW USERS`) granted then the corresponding system table (i.e. `system.users`) will be accessible. | `true` | diff --git a/programs/client/FuzzLoop.cpp b/programs/client/FuzzLoop.cpp index 58788361397d..583de7730397 100644 --- a/programs/client/FuzzLoop.cpp +++ b/programs/client/FuzzLoop.cpp @@ -358,7 +358,7 @@ bool Client::processWithASTFuzzer(std::string_view full_query) { /// Print insert data String bytes; - auto read_buf = getReadBufferFromASTInsertQuery(ast_to_process); + auto read_buf = getReadBufferFromASTInsertQuery(ast_to_process, client_context); WriteBufferFromString write_buf(bytes); copyData(*read_buf, write_buf); fmt::print(stdout, "{}\n", bytes); @@ -476,7 +476,7 @@ bool Client::processWithASTFuzzer(std::string_view full_query) { String bytes; { - auto read_buf = getReadBufferFromASTInsertQuery(query); + auto read_buf = getReadBufferFromASTInsertQuery(query, client_context); WriteBufferFromString write_buf(bytes); copyData(*read_buf, write_buf); } diff --git a/programs/format/Format.cpp b/programs/format/Format.cpp index 62bd0a43a3ff..e1d61418dbe6 100644 --- a/programs/format/Format.cpp +++ b/programs/format/Format.cpp @@ -286,7 +286,7 @@ int mainEntryClickHouseFormat(int argc, char ** argv) const char * this_query_end = find_first_symbols<'\n'>(insert_query->data, end); insert_query->end = this_query_end; pos = this_query_end; - insert_query_payload = getReadBufferFromASTInsertQuery(res); + insert_query_payload = getReadBufferFromASTInsertQuery(res, context); } if (!quiet) diff --git a/programs/server/binary.html b/programs/server/binary.html index 49330aa82b1c..7160582baeb6 100644 --- a/programs/server/binary.html +++ b/programs/server/binary.html @@ -267,15 +267,22 @@ `${url}&default_format=JSON`, { method: 'POST', - body: `SELECT encodeXMLComponent(demangle(addressToSymbol(${addr_int}::UInt64))) AS name, - encodeXMLComponent(addressToLine(${addr_int}::UInt64)) AS line` + body: `SELECT demangle(addressToSymbol(${addr_int}::UInt64)) AS name, + addressToLine(${addr_int}::UInt64) AS line` }).then(response => response.json().then(o => { let name = o.rows ? o.data[0].name : 'nothing'; let line = o.rows ? o.data[0].line : ''; if (addr_int == current_requested_addr) { - popup.setContent(`

${addr_hex}

${name}

${line}

`); + /// The response is untrusted (the server can be specified by the `host` parameter), + /// so it is inserted as text, never as HTML. + const content = document.createElement('div'); + const addr_elem = content.appendChild(document.createElement('p')).appendChild(document.createElement('b')); + addr_elem.textContent = addr_hex; + content.appendChild(document.createElement('p')).textContent = name; + content.appendChild(document.createElement('p')).textContent = line; + popup.setContent(content); } })); diff --git a/programs/server/config.xml b/programs/server/config.xml index 1eeb6521a564..90baa63db9cf 100644 --- a/programs/server/config.xml +++ b/programs/server/config.xml @@ -905,7 +905,7 @@ however you can change this behaviour by setting this to true --> false - false diff --git a/rust/vendor.sh b/rust/vendor.sh index ca7ca26457e6..e31032eb560a 100755 --- a/rust/vendor.sh +++ b/rust/vendor.sh @@ -37,7 +37,7 @@ cd "$CH_TOP_DIR"/contrib/delta-kernel-rs || exit 1 cargo vendor --no-delete --locked --versioned-dirs --manifest-path Cargo.toml "$CH_TOP_DIR"/contrib/rust_vendor # chdig -cd "$CH_TOP_DIR"/contrib/chdig || exit 1 +cd "$CH_TOP_DIR"/contrib/chdig-cmake || exit 1 cargo vendor --no-delete --locked --versioned-dirs --manifest-path Cargo.toml "$CH_TOP_DIR"/contrib/rust_vendor # wasmtime diff --git a/rust/workspace/Cargo.lock b/rust/workspace/Cargo.lock index 7b87c76d377d..2c297f7e81dd 100644 --- a/rust/workspace/Cargo.lock +++ b/rust/workspace/Cargo.lock @@ -179,7 +179,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -228,18 +228,18 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" dependencies = [ "allocator-api2", ] [[package]] name = "cc" -version = "1.11.0" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "shlex 2.0.1", @@ -325,7 +325,7 @@ dependencies = [ "proc-macro2", "pulldown-cmark", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -368,9 +368,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpp_demangle" -version = "0.4.5" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" dependencies = [ "cfg-if", ] @@ -386,21 +386,21 @@ dependencies = [ [[package]] name = "cranelift-assembler-x64" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-entity", "wasmtime-internal-core", @@ -408,7 +408,7 @@ dependencies = [ [[package]] name = "cranelift-bitset" -version = "0.132.1" +version = "0.137.1" dependencies = [ "serde", "serde_derive", @@ -417,7 +417,7 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.132.1" +version = "0.137.1" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -432,10 +432,13 @@ dependencies = [ "hashbrown 0.17.1", "libm", "log", + "postcard", "pulley-interpreter", "regalloc2", "rustc-hash", "serde", + "serde_derive", + "sha2", "smallvec", "target-lexicon", "wasmtime-internal-core", @@ -443,7 +446,7 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -454,18 +457,18 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.132.1" +version = "0.137.1" [[package]] name = "cranelift-control" -version = "0.132.1" +version = "0.137.1" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-bitset", "serde", @@ -475,9 +478,10 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-codegen", + "hashbrown 0.17.1", "log", "smallvec", "target-lexicon", @@ -485,26 +489,27 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.132.1" +version = "0.137.1" [[package]] name = "cranelift-native" -version = "0.132.1" +version = "0.137.1" dependencies = [ "cranelift-codegen", "libc", + "mach2", "target-lexicon", ] [[package]] name = "cranelift-srcgen" -version = "0.132.1" +version = "0.137.1" [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -623,7 +628,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -637,7 +642,7 @@ dependencies = [ "indexmap", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -655,7 +660,7 @@ dependencies = [ "indexmap", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -703,37 +708,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "defmt" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "defmt-parser" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "deranged" version = "0.5.9" @@ -875,9 +849,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys", @@ -907,12 +881,48 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -925,8 +935,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -1087,17 +1101,16 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.39" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ - "defmt", "jiff-core", "jiff-static", "log", @@ -1108,19 +1121,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.2" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" dependencies = [ - "defmt", "log", ] [[package]] name = "jiff-static" -version = "0.2.39" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ "jiff-core", "proc-macro2", @@ -1195,12 +1207,9 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "mach2" -version = "0.4.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" -dependencies = [ - "libc", -] +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" [[package]] name = "memchr" @@ -1255,9 +1264,9 @@ dependencies = [ [[package]] name = "object" -version = "0.39.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "crc32fast", "hashbrown 0.17.1", @@ -1401,7 +1410,7 @@ dependencies = [ [[package]] name = "pulley-interpreter" -version = "45.0.1" +version = "50.0.1" dependencies = [ "cranelift-bitset", "log", @@ -1411,11 +1420,11 @@ dependencies = [ [[package]] name = "pulley-macros" -version = "45.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -1510,7 +1519,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1524,6 +1533,7 @@ dependencies = [ "hashbrown 0.17.1", "log", "rustc-hash", + "serde", "smallvec", ] @@ -1615,7 +1625,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1661,7 +1671,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1672,7 +1682,7 @@ checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1782,9 +1792,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -1855,9 +1865,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1866,9 +1876,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "term" @@ -1936,7 +1946,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -2164,7 +2174,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -2179,12 +2189,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.248.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac92cf547bc18d27ecc521015c08c353b4f18b84ab388bb6d1b6b682c620d9b6" +checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" dependencies = [ "leb128fmt", - "wasmparser 0.248.0", + "wasmparser 0.261.0", ] [[package]] @@ -2199,9 +2209,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.248.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4439c5eee9df71ee0c6efb37f63b1fcb1fec38f85f5142c54e7ed05d33091a" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" dependencies = [ "bitflags 2.13.2", "hashbrown 0.17.1", @@ -2223,25 +2233,25 @@ dependencies = [ [[package]] name = "wasmprinter" -version = "0.248.0" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b264a5410b008d4d199a92bf536eae703cbd614482fc1ec53831cf19e1c183" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" dependencies = [ "anyhow", "termcolor", - "wasmparser 0.248.0", + "wasmparser 0.261.0", ] [[package]] name = "wasmtime" -version = "45.0.1" +version = "50.0.1" dependencies = [ "addr2line", "async-trait", "bitflags 2.13.2", "bumpalo", "cc", - "cfg-if", + "futures", "gimli", "libc", "log", @@ -2256,8 +2266,8 @@ dependencies = [ "serde_derive", "smallvec", "target-lexicon", - "wasm-encoder 0.248.0", - "wasmparser 0.248.0", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-core", "wasmtime-internal-cranelift", @@ -2266,14 +2276,13 @@ dependencies = [ "wasmtime-internal-jit-icache-coherence", "wasmtime-internal-unwinder", "wasmtime-internal-versioned-export-macros", - "wasmtime-internal-winch", "wat", "windows-sys", ] [[package]] name = "wasmtime-c-api-impl" -version = "45.0.1" +version = "50.0.1" dependencies = [ "log", "tracing", @@ -2284,7 +2293,7 @@ dependencies = [ [[package]] name = "wasmtime-environ" -version = "45.0.1" +version = "50.0.1" dependencies = [ "anyhow", "cpp_demangle", @@ -2298,28 +2307,33 @@ dependencies = [ "object", "postcard", "rustc-demangle", + "semver", "serde", "serde_derive", - "sha2", "smallvec", "target-lexicon", - "wasm-encoder 0.248.0", - "wasmparser 0.248.0", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmprinter", + "wasmtime-internal-component-util", "wasmtime-internal-core", ] [[package]] name = "wasmtime-internal-c-api-macros" -version = "45.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", ] +[[package]] +name = "wasmtime-internal-component-util" +version = "50.0.1" + [[package]] name = "wasmtime-internal-core" -version = "45.0.1" +version = "50.0.1" dependencies = [ "hashbrown 0.17.1", "libm", @@ -2328,9 +2342,8 @@ dependencies = [ [[package]] name = "wasmtime-internal-cranelift" -version = "45.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "cranelift-codegen", "cranelift-control", "cranelift-entity", @@ -2344,7 +2357,7 @@ dependencies = [ "smallvec", "target-lexicon", "thiserror 2.0.21", - "wasmparser 0.248.0", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-core", "wasmtime-internal-unwinder", @@ -2353,10 +2366,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-fiber" -version = "45.0.1" +version = "50.0.1" dependencies = [ "cc", - "cfg-if", "libc", "rustix", "wasmtime-environ", @@ -2366,7 +2378,7 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-debug" -version = "45.0.1" +version = "50.0.1" dependencies = [ "cc", "wasmtime-internal-versioned-export-macros", @@ -2374,9 +2386,8 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "45.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "libc", "wasmtime-internal-core", "windows-sys", @@ -2384,9 +2395,8 @@ dependencies = [ [[package]] name = "wasmtime-internal-unwinder" -version = "45.0.1" +version = "50.0.1" dependencies = [ - "cfg-if", "cranelift-codegen", "log", "object", @@ -2395,26 +2405,11 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "45.0.1" +version = "50.0.1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", -] - -[[package]] -name = "wasmtime-internal-winch" -version = "45.0.1" -dependencies = [ - "cranelift-codegen", - "gimli", - "log", - "object", - "target-lexicon", - "wasmparser 0.248.0", - "wasmtime-environ", - "wasmtime-internal-cranelift", - "winch-codegen", + "syn 3.0.10", ] [[package]] @@ -2482,23 +2477,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "winch-codegen" -version = "45.0.1" -dependencies = [ - "cranelift-assembler-x64", - "cranelift-codegen", - "gimli", - "regalloc2", - "smallvec", - "target-lexicon", - "thiserror 2.0.21", - "wasmparser 0.248.0", - "wasmtime-environ", - "wasmtime-internal-core", - "wasmtime-internal-cranelift", -] - [[package]] name = "windows-core" version = "0.62.2" diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index 8f81ddd0bc20..2af79fb0d493 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -264,6 +264,22 @@ AccessRestorerFromBackup::AccessRestorerFromBackup( { } +AccessRestorerFromBackup::AccessRestorerFromBackup( + const AccessRestorerFromBackup & src, RestoreAccessCreationMode creation_mode_, bool skip_unresolved_dependencies_) + : backup(src.backup) + , creation_mode(creation_mode_) + , skip_unresolved_dependencies(skip_unresolved_dependencies_) + , update_dependents(src.update_dependents) + , restore_with_current_grants(src.restore_with_current_grants) + , log(src.log) + , loaded(src.loaded) + , ids_assigned(src.ids_assigned) + , data_paths_in_backup(src.data_paths_in_backup) + , data_path_with_entities_to_restore(src.data_path_with_entities_to_restore) + , entity_infos(src.entity_infos) +{ +} + AccessRestorerFromBackup::~AccessRestorerFromBackup() = default; @@ -470,6 +486,7 @@ void AccessRestorerFromBackup::generateRandomIDsAndResolveDependencies(const Acc bool was_going_to_restore = entity_info.restore; entity_info.new_id = *existing_id; entity_info.restore = false; + entity_info.exists = was_going_to_restore; LOG_TRACE(log, "{}: Found with UUID {}{}", AccessEntityTypeInfo::get(type).formatEntityNameWithType(name), *existing_id, (was_going_to_restore ? ", will not restore" : "")); } @@ -521,7 +538,7 @@ void AccessRestorerFromBackup::generateRandomIDsAndResolveDependencies(const Acc /// Remap the UUIDs of dependencies in the access entities we're going to restore. for (auto & [id, entity_info] : entity_infos) { - if (entity_info.restore || entity_info.is_dependent) + if (entity_info.restore || entity_info.is_dependent || entity_info.exists) { auto new_entity = entity_info.entity->clone(); new_entity->replaceDependencies(old_to_new_ids); @@ -562,6 +579,31 @@ AccessEntitiesToRestore AccessRestorerFromBackup::getEntitiesToRestore(const Str } +std::vector> AccessRestorerFromBackup::getEntitiesFromBackup() const +{ + if (!ids_assigned) + throw Exception(ErrorCodes::LOGICAL_ERROR, "IDs not assigned"); + + std::vector> res; + for (const auto & [id, entity_info] : entity_infos) + { + if (entity_info.restore || entity_info.exists) + res.emplace_back(*entity_info.new_id, entity_info.entity); + } + return res; +} + + +AccessRestorerFromBackup AccessRestorerFromBackup::makeCopyForChecking() const +{ + if (!loaded || ids_assigned) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Access entities must be loaded and not resolved to make a copy for checking"); + + auto mode = (creation_mode == RestoreAccessCreationMode::kCreate) ? RestoreAccessCreationMode::kCreateIfNotExists : creation_mode; + return AccessRestorerFromBackup(*this, mode, /* skip_unresolved_dependencies_= */ true); +} + + void restoreAccessEntitiesFromBackup( IAccessStorage & destination_access_storage, const AccessEntitiesToRestore & entities_to_restore, diff --git a/src/Access/AccessBackup.h b/src/Access/AccessBackup.h index da0f3088a033..e4724c881be5 100644 --- a/src/Access/AccessBackup.h +++ b/src/Access/AccessBackup.h @@ -81,7 +81,17 @@ class AccessRestorerFromBackup /// Both functions loadFromBackup() and generateRandomIDsAndResolveDependencies() must be called before that. AccessEntitiesToRestore getEntitiesToRestore(const String & data_path_in_backup) const; + /// Returns every access entity selected from the backup, including the ones not restored because they exist, + /// with dependencies resolved. generateRandomIDsAndResolveDependencies() must be called before that. + [[nodiscard]] std::vector> getEntitiesFromBackup() const; + + /// Returns a copy which resolves without throwing on existing or missing entities. Call after loadFromBackup(), before resolving. + [[nodiscard]] AccessRestorerFromBackup makeCopyForChecking() const; + private: + AccessRestorerFromBackup( + const AccessRestorerFromBackup & src, RestoreAccessCreationMode creation_mode_, bool skip_unresolved_dependencies_); + const BackupPtr backup; const RestoreAccessCreationMode creation_mode; const bool skip_unresolved_dependencies; @@ -128,6 +138,10 @@ class AccessRestorerFromBackup /// This flags is set by generateRandomIDsAndResolveDependencies(). bool is_dependent = false; + /// Whether this entity was loaded to be restored but is not restored because it exists already. + /// This flag is set by generateRandomIDsAndResolveDependencies(). + bool exists = false; + /// New UUID for this entity - either randomly generated or copied from an existing entity. /// This UUID is assigned by generateRandomIDsAndResolveDependencies(). std::optional new_id = std::nullopt; diff --git a/src/Access/AccessRights.cpp b/src/Access/AccessRights.cpp index b664efc88321..472ea47bdb89 100644 --- a/src/Access/AccessRights.cpp +++ b/src/Access/AccessRights.cpp @@ -38,6 +38,10 @@ namespace if (left.full_name.size() != right.full_name.size()) return left.full_name.size() < right.full_name.size(); + /// Wildcards before exact names: `db*` covers `db`, so its element must be applied first. + if (left.wildcard != right.wildcard) + return left.wildcard; + /// Grants before partial revokes. if (left.is_partial_revoke != right.is_partial_revoke) return right.is_partial_revoke; /// if left is grant, right is partial revoke, we assume left < right @@ -976,7 +980,9 @@ struct AccessRights::Node auto grants = flags - parent_fl - grants_go; /// Inserts into result only meaningful nodes (e.g. wildcards or leafs). - if (target_node && (target_node->isLeaf() || target_node->wildcard_grant)) + const bool node_meaningful = node && (node->isLeaf() || node->wildcard_grant); + const bool node_go_meaningful = node_go && (node_go->isLeaf() || node_go->wildcard_grant); + if (node_meaningful || node_go_meaningful) { boost::container::small_vector new_full_name = full_name; @@ -992,19 +998,27 @@ struct AccessRights::Node } } - if (node && revokes) + if (node_meaningful && revokes) res.push_back(ProtoElement{revokes, new_full_name, false, true, node->wildcard_grant}); - if (node_go && revokes_go) + if (node_go_meaningful && revokes_go) res.push_back(ProtoElement{revokes_go, new_full_name, true, true, node_go->wildcard_grant}); - if (node && grants) + if (node_meaningful && grants) res.push_back(ProtoElement{grants, new_full_name, false, false, node->wildcard_grant}); - if (node_go && grants_go) + if (node_go_meaningful && grants_go) res.push_back(ProtoElement{grants_go, new_full_name, true, false, node_go->wildcard_grant}); } + /// The two tries compress child names independently: a child of one can be a strict name + /// prefix of a child of the other, and only exactly-named pairs can be walked together. + if (node && node_go && node_go->children) + { + for (auto & child_go : *node_go->children) + node->getLeaf(child_go.node_name, child_go.level, !child_go.isLeaf()); + } + if (node && node->children) { for (auto & child : *node->children) @@ -1024,19 +1038,8 @@ struct AccessRights::Node { for (auto & child : *node_go->children) { - if (node && node->children) - { - auto starts_with = [&child](const Node & n) - { - if (child.isLeaf()) - return n.isLeaf(); - - return !n.isLeaf() && child.node_name[0] == n.node_name[0]; - }; - - if (auto it = std::find_if(node->children->begin(), node->children->end(), starts_with); it != node->children->end()) - continue; /// already processed - } + if (node && node->tryGetChildNode(child.node_name)) + continue; /// already processed String new_path = path; new_path.append(child.node_name); @@ -1564,7 +1567,11 @@ AccessRights AccessRights::getGrantableRights() const continue; if (element.is_partial_revoke) + { + /// A right with a revoked grant option is not grantable, so remove the right itself. + element.grant_option = false; result.revoke(element); + } else result.grant(element); } diff --git a/src/Access/Common/AccessType.h b/src/Access/Common/AccessType.h index ba14d5e58237..cf10af8cf047 100644 --- a/src/Access/Common/AccessType.h +++ b/src/Access/Common/AccessType.h @@ -227,7 +227,7 @@ enum class AccessType : uint16_t \ M(ALTER_DATABASE_SETTINGS, "ALTER DATABASE SETTING, ALTER MODIFY DATABASE SETTING, MODIFY DATABASE SETTING", DATABASE, ALTER_DATABASE) /* allows to execute ALTER MODIFY SETTING */\ M(ALTER_NAMED_COLLECTION, "", NAMED_COLLECTION, NAMED_COLLECTION_ADMIN) /* allows to execute ALTER NAMED COLLECTION */\ - M(ALTER_HANDLER, "", GLOBAL, ALTER) /* allows to execute ALTER HANDLER */\ + M(ALTER_HANDLER, "", GLOBAL, HANDLER_ADMIN) /* allows to execute ALTER HANDLER */\ \ M(ALTER_TABLE, "", GROUP, ALTER) \ M(ALTER_DATABASE, "", GROUP, ALTER) \ @@ -255,7 +255,7 @@ enum class AccessType : uint16_t M(CREATE_WORKLOAD, "", GLOBAL, CREATE) /* allows to execute CREATE WORKLOAD */ \ M(CREATE_RESOURCE, "", GLOBAL, CREATE) /* allows to execute CREATE RESOURCE */ \ M(CREATE_NAMED_COLLECTION, "", NAMED_COLLECTION, NAMED_COLLECTION_ADMIN) /* allows to execute CREATE NAMED COLLECTION */ \ - M(CREATE_HANDLER, "", GLOBAL, CREATE) /* allows to execute CREATE HANDLER */ \ + M(CREATE_HANDLER, "", GLOBAL, HANDLER_ADMIN) /* allows to execute CREATE HANDLER */ \ M(CREATE, "", GROUP, ALL) /* allows to execute {CREATE|ATTACH} */ \ \ M(DROP_DATABASE, "", DATABASE, DROP) /* allows to execute {DROP|DETACH|TRUNCATE} DATABASE */\ @@ -267,7 +267,7 @@ enum class AccessType : uint16_t M(DROP_WORKLOAD, "", GLOBAL, DROP) /* allows to execute DROP WORKLOAD */\ M(DROP_RESOURCE, "", GLOBAL, DROP) /* allows to execute DROP RESOURCE */\ M(DROP_NAMED_COLLECTION, "", NAMED_COLLECTION, NAMED_COLLECTION_ADMIN) /* allows to execute DROP NAMED COLLECTION */\ - M(DROP_HANDLER, "", GLOBAL, DROP) /* allows to execute DROP HANDLER */\ + M(DROP_HANDLER, "", GLOBAL, HANDLER_ADMIN) /* allows to execute DROP HANDLER */\ M(DROP, "", GROUP, ALL) /* allows to execute {DROP|DETACH} */\ \ M(UNDROP_TABLE, "", TABLE, ALL) /* allows to execute {UNDROP} TABLE */\ @@ -316,7 +316,8 @@ enum class AccessType : uint16_t M(SHOW_NAMED_COLLECTIONS_SECRETS, "SHOW NAMED COLLECTIONS SECRETS", NAMED_COLLECTION, NAMED_COLLECTION_ADMIN) \ M(NAMED_COLLECTION, "NAMED COLLECTION USAGE, USE NAMED COLLECTION", NAMED_COLLECTION, NAMED_COLLECTION_ADMIN) \ M(NAMED_COLLECTION_ADMIN, "NAMED COLLECTION CONTROL", NAMED_COLLECTION, ALL) \ - M(SHOW_HANDLERS, "SHOW HANDLER", GLOBAL, ALL) /* allows to see SQL-defined HTTP handlers in system.handlers */\ + M(SHOW_HANDLERS, "SHOW HANDLER", GLOBAL, HANDLER_ADMIN) /* allows to see SQL-defined HTTP handlers in system.handlers */\ + M(HANDLER_ADMIN, "", GROUP, ALL) /* allows to create, alter, drop and see SQL-defined HTTP handlers */\ M(SET_DEFINER, "", DEFINER, ALL) \ \ M(TABLE_ENGINE, "TABLE ENGINE", TABLE_ENGINE, ALL) \ diff --git a/src/Access/LDAPAccessStorage.cpp b/src/Access/LDAPAccessStorage.cpp index e464d5818b55..6f75afac42d3 100644 --- a/src/Access/LDAPAccessStorage.cpp +++ b/src/Access/LDAPAccessStorage.cpp @@ -401,37 +401,36 @@ String LDAPAccessStorage::getStorageParamsJSON() const } +/// The read-only methods below don't lock `mutex`: `memory_storage` is synchronized by itself, +/// and `mutex` is held by `authenticateImpl` during the network communication with the LDAP server. +/// Waiting for it here would make lookups (e.g. the check for a name collision in `MultipleAccessStorage`) +/// wait for unrelated LDAP authentications. std::optional LDAPAccessStorage::findImpl(AccessEntityType type, const String & name) const { - std::lock_guard lock(mutex); return memory_storage.find(type, name); } std::vector LDAPAccessStorage::findAllImpl(AccessEntityType type) const { - std::lock_guard lock(mutex); return memory_storage.findAll(type); } bool LDAPAccessStorage::exists(const UUID & id) const { - std::lock_guard lock(mutex); return memory_storage.exists(id); } AccessEntityPtr LDAPAccessStorage::readImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.read(id, throw_if_not_exists); } std::optional> LDAPAccessStorage::readNameWithTypeImpl(const UUID & id, bool throw_if_not_exists) const { - std::lock_guard lock(mutex); return memory_storage.readNameWithType(id, throw_if_not_exists); } diff --git a/src/Access/MultipleAccessStorage.cpp b/src/Access/MultipleAccessStorage.cpp index c7247900b1c2..40158681c287 100644 --- a/src/Access/MultipleAccessStorage.cpp +++ b/src/Access/MultipleAccessStorage.cpp @@ -17,6 +17,7 @@ namespace ErrorCodes extern const int ACCESS_ENTITY_ALREADY_EXISTS; extern const int ACCESS_STORAGE_FOR_INSERTION_NOT_FOUND; extern const int ACCESS_ENTITY_NOT_FOUND; + extern const int AUTHENTICATION_FAILED; } using Storage = IAccessStorage; @@ -256,6 +257,24 @@ void MultipleAccessStorage::moveAccessEntities(const std::vector & ids, co auto destination_storage = getStorageByName(destination_storage_name); auto to_move = source_storage->read(ids); + + /// The same name must not refer to entities in different storages, so a move is refused if any storage + /// other than the source one already holds the name (e.g. a user of the config with the same name). + /// This is checked before anything is removed from the source storage. + auto storages = getStoragesInternal(); + for (const auto & entity : to_move) + { + for (const auto & other_storage : *storages) + { + if (other_storage == source_storage) + continue; + if (other_storage->find(entity->getType(), entity->getName())) + throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot move to {} because {} already exists in {}", + entity->formatTypeWithName(), backQuote(destination_storage_name), entity->formatTypeWithName(), + backQuote(other_storage->getStorageName())); + } + } + bool need_rollback = false; try @@ -397,6 +416,22 @@ bool MultipleAccessStorage::insertImpl(const UUID & id, const AccessEntityPtr & getStorageName()); } + /// The same name must not refer to entities in different storages. + /// A replacement replaces only an entity of the destination storage, so it is refused too if another storage holds the name. + for (const auto & other_storage : *storages) + { + if (other_storage == storage_for_insertion) + continue; + if (auto existing_id = other_storage->find(entity->getType(), entity->getName())) + { + if (conflicting_id) + *conflicting_id = *existing_id; + if (throw_if_exists || replace_if_exists) + throwNameCollisionCannotInsert(entity->getType(), entity->getName(), other_storage->getStorageName()); + return false; + } + } + if (storage_for_insertion->insert(id, entity, replace_if_exists, throw_if_exists, conflicting_id)) { std::lock_guard lock{mutex}; @@ -431,9 +466,10 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat return false; } - /// If the updating involves renaming check that the renamed entity will be accessible by name. + /// If the updating involves renaming check that the new name is not used in another storage: + /// the same name must not refer to entities in different storages. auto storages = getStoragesInternal(); - if ((storages->size() > 1) && (storages->front() != storage_for_updating)) + if (storages->size() > 1) { if (auto old_entity = storage_for_updating->tryRead(id)) { @@ -443,7 +479,7 @@ bool MultipleAccessStorage::updateImpl(const UUID & id, const UpdateFunc & updat for (const auto & storage : *storages) { if (storage == storage_for_updating) - break; + continue; if (storage->find(new_entity->getType(), new_entity->getName())) { throw Exception(ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS, "{}: cannot rename to {} because {} already exists in {}", @@ -466,15 +502,62 @@ MultipleAccessStorage::authenticateImpl(const Credentials & credentials, const P bool allow_no_password, bool allow_plaintext_password) const { auto storages = getStoragesInternal(); - for (size_t i = 0; i != storages->size(); ++i) + + /// Users from different user directories are distinct entities, but some code identifies users by name, + /// so the same name must not refer to more than one user. + auto throw_name_collision = [&](const String & user_name, const StoragePtr & storage, const StoragePtr & other_storage) -> void + { + throw Exception(ErrorCodes::AUTHENTICATION_FAILED, + "User {} exists in {}, but a user with the same name also exists in {}", + backQuote(user_name), storage->getStorageName(), other_storage->getStorageName()); + }; + + /// If a user with this name already exists, only its storage may authenticate it. Otherwise an external directory + /// (e.g. LDAP) could introduce a second user with the same name on login, in particular with `AlwaysAllowCredentials`, + /// which LDAP accepts without contacting the LDAP server. + /// + /// The same name with the same ID in several storages is one identity, not a collision: external directories + /// which derive both the name and the ID of a user from the verified identity (e.g. several token-based directories, + /// one per signing key or identity provider) each keep their own copy of the same user, and any of them may authenticate it. + std::vector existing_user_storages; + if (storages->size() > 1 && credentials.isReady()) + { + std::optional existing_user_id; + for (const auto & storage : *storages) + { + auto user_id = storage->find(AccessEntityType::USER, credentials.getUserName()); + if (!user_id) + continue; + if (existing_user_id && *existing_user_id != *user_id) + throw_name_collision(credentials.getUserName(), existing_user_storages.front(), storage); + existing_user_id = user_id; + existing_user_storages.push_back(storage); + } + } + + /// The storages which may authenticate these credentials. + std::vector candidate_storages = existing_user_storages.empty() ? *storages : existing_user_storages; + + for (size_t i = 0; i != candidate_storages.size(); ++i) { - const auto & storage = (*storages)[i]; - bool is_last_storage = (i == storages->size() - 1); + const auto & storage = candidate_storages[i]; + bool is_last_storage = (i == candidate_storages.size() - 1); auto auth_result = storage->authenticate(credentials, address, external_authenticators, client_info, (throw_if_user_not_exists && is_last_storage), allow_no_password, allow_plaintext_password); if (auth_result) { + /// Check again: a user with the same name could have appeared in another storage concurrently, + /// or the storage could have just introduced the user. + for (const auto & other_storage : *storages) + { + if (other_storage == storage) + continue; + auto other_user_id = other_storage->find(AccessEntityType::USER, auth_result->user_name); + if (other_user_id && *other_user_id != auth_result->user_id) + throw_name_collision(auth_result->user_name, storage, other_storage); + } + std::lock_guard lock{mutex}; ids_cache.set(auth_result->user_id, storage); return auth_result; diff --git a/src/Access/tests/gtest_access_rights_ops.cpp b/src/Access/tests/gtest_access_rights_ops.cpp index ec4b2993ea5a..eed332d02a98 100644 --- a/src/Access/tests/gtest_access_rights_ops.cpp +++ b/src/Access/tests/gtest_access_rights_ops.cpp @@ -96,13 +96,13 @@ TEST(AccessRights, GrantWildcard) root.grantWildcard(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t"); root.revoke(AccessType::INSERT, "default", "t"); ASSERT_EQ(root.isGranted(AccessType::SELECT, "default", "t"), true); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "t"), false); ASSERT_EQ(root.isGranted(AccessType::INSERT, "default", "test"), true); - ASSERT_EQ(root.toString(), "GRANT SELECT ON default.t, GRANT INSERT ON default.t*, REVOKE INSERT ON default.t"); + ASSERT_EQ(root.toString(), "GRANT INSERT ON default.t*, GRANT SELECT ON default.t, REVOKE INSERT ON default.t"); root = {}; root.grant(AccessType::SELECT, "default", "t"); @@ -235,6 +235,51 @@ TEST(AccessRights, GrantWildcard) ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.* WITH GRANT OPTION, GRANT INSERT ON db.`table`"); } +TEST(AccessRights, WildcardBeforeExactNameInElements) +{ + /// The elements are applied in the order of `getElements`, so `REVOKE ... ON dbx*.*` must precede `GRANT ... ON dbx.*`. + AccessRights root; + root.grantWildcard(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "dbx"); + root.grant(AccessType::SELECT, "dbx"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db*.*, REVOKE SELECT ON dbx*.*, GRANT SELECT ON dbx.*"); + AccessRights restored{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "dbx")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "dbx1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grant(AccessType::SELECT, "db"); + root.revokeWildcard(AccessType::SELECT, "db", "t"); + root.grant(AccessType::SELECT, "db", "t"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON db.*, REVOKE SELECT ON db.t*, GRANT SELECT ON db.t"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.isGranted(AccessType::SELECT, "db", "t")); + ASSERT_FALSE(restored.isGranted(AccessType::SELECT, "db", "t1")); + ASSERT_EQ(restored, root); + + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + root.grantWithGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), + "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, GRANT SELECT ON db.* WITH GRANT OPTION"); + restored = AccessRights{root.getElements()}; + ASSERT_TRUE(restored.hasGrantOption(AccessType::SELECT, "db")); + ASSERT_FALSE(restored.hasGrantOption(AccessType::SELECT, "db1")); + ASSERT_EQ(restored, root); + + /// The same after a union, like the rights of two roles. + AccessRights lhs; + AccessRights rhs; + lhs.grant(AccessType::SELECT); + lhs.revokeWildcard(AccessType::SELECT, "db"); + rhs.grant(AccessType::SELECT, "db"); + lhs.makeUnion(rhs); + ASSERT_EQ(lhs.toString(), "GRANT SELECT ON *.*, REVOKE SELECT ON db*.*, GRANT SELECT ON db.*"); + ASSERT_TRUE(AccessRights{lhs.getElements()}.isGranted(AccessType::SELECT, "db")); +} + TEST(AccessRights, Union) { AccessRights lhs; @@ -638,6 +683,55 @@ TEST(AccessRights, ParialRevokeWithGrantOption) ASSERT_TRUE(root.isGranted(AccessType::SELECT, "default", "zoo")); } +TEST(AccessRights, PartialRevokeGrantOptionWithSharedPrefix) +{ + /// Each arm pairs a grant-option-only revoke whose name shares a prefix with a plain revoke + /// (the shape that used to be dropped) with a control name that shares nothing. + + /// Database level. + AccessRights root; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "db1"); + root.revokeGrantOption(AccessType::SELECT, "db2"); + root.revokeGrantOption(AccessType::SELECT, "zdb2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON db1.*, " + "REVOKE GRANT OPTION SELECT ON db2.*, REVOKE GRANT OPTION SELECT ON zdb2.*"); + + /// Database level, grant-option name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx"); + root.revokeGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db.*, " + "REVOKE SELECT ON dbx.*"); + + /// Table level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t2"); + root.revokeGrantOption(AccessType::SELECT, "d", "zt2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON d.t1, " + "REVOKE GRANT OPTION SELECT ON d.t2, REVOKE GRANT OPTION SELECT ON d.zt2"); + + /// Column level. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "d", "t", "c1"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "c2"); + root.revokeGrantOption(AccessType::SELECT, "d", "t", "zc2"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT(c1) ON d.t, " + "REVOKE GRANT OPTION SELECT(c2, zc2) ON d.t"); + + /// Wildcard grant-option revoke whose name is a strict prefix of the plain one. + root = {}; + root.grantWithGrantOption(AccessType::SELECT); + root.revoke(AccessType::SELECT, "dbx1"); + root.revokeWildcardGrantOption(AccessType::SELECT, "db"); + ASSERT_EQ(root.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE GRANT OPTION SELECT ON db*.*, " + "REVOKE SELECT ON dbx1.*"); +} + TEST(AccessRights, WildcardGrantEdgeCases) { AccessRights root; @@ -751,6 +845,46 @@ TEST(AccessRights, PartialRevokeWithWildcard) ASSERT_EQ(root.toString(), "GRANT SELECT ON *.*, REVOKE SELECT ON internal*.*, GRANT SELECT ON internal_public.*"); } +TEST(AccessRights, GrantableRightsWithoutRevokedGrantOption) +{ + /// `getGrantableRights` is what GRANT CURRENT GRANTS and RESTORE may hand out. + AccessRights root; + root.grantWithGrantOption(AccessType::SELECT); + root.revokeGrantOption(AccessType::SELECT, "db", "secret"); + ASSERT_TRUE(root.isGranted(AccessType::SELECT, "db", "secret")); + ASSERT_FALSE(root.hasGrantOption(AccessType::SELECT, "db", "secret")); + + AccessRights grantable = root.getGrantableRights(); + ASSERT_FALSE(grantable.isGranted(AccessType::SELECT, "db", "secret")); + ASSERT_FALSE(grantable.hasGrantOption(AccessType::SELECT, "db", "secret")); + ASSERT_TRUE(grantable.hasGrantOption(AccessType::SELECT, "db", "other")); + ASSERT_EQ(grantable.toString(), "GRANT SELECT ON *.* WITH GRANT OPTION, REVOKE SELECT ON db.secret"); + + /// GRANT CURRENT GRANTS(SELECT ON *.*) + AccessRights rights; + rights.grant(AccessType::SELECT); + rights.makeIntersection(grantable); + ASSERT_FALSE(rights.isGranted(AccessType::SELECT, "db", "secret")); + ASSERT_TRUE(rights.isGranted(AccessType::SELECT, "db", "other")); + + root = {}; + root.grantWildcardWithGrantOption(AccessType::SELECT, "db"); + root.revokeWildcardGrantOption(AccessType::SELECT, "dbx"); + grantable = root.getGrantableRights(); + ASSERT_FALSE(grantable.isGranted(AccessType::SELECT, "dbx1")); + ASSERT_TRUE(grantable.hasGrantOption(AccessType::SELECT, "db1")); + + /// A right granted again without the grant option is not grantable either. + root = {}; + root.grantWithGrantOption(AccessType::INSERT); + root.revoke(AccessType::INSERT, "db", "t"); + root.grant(AccessType::INSERT, "db"); + grantable = root.getGrantableRights(); + ASSERT_TRUE(root.isGranted(AccessType::INSERT, "db", "t")); + ASSERT_FALSE(grantable.isGranted(AccessType::INSERT, "db", "t")); + ASSERT_TRUE(grantable.hasGrantOption(AccessType::INSERT, "db", "other")); +} + TEST(AccessRights, WildcardGrantOptionInteractions) { AccessRights root; diff --git a/src/AggregateFunctions/AggregateFunctionGroupFormat.cpp b/src/AggregateFunctions/AggregateFunctionGroupFormat.cpp index 8cfc7d9ad6ab..6350d8afdf7d 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupFormat.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupFormat.cpp @@ -96,11 +96,12 @@ class AggregateFunctionGroupFormat final : public IAggregateFunctionDataHelpercreateColumn()); + columns.emplace_back(type->createColumn()); + new (place) GroupFormatData{std::move(columns)}; } void add(AggregateDataPtr __restrict place, const IColumn ** columns, size_t row_num, Arena *) const override diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp index f73eed07a9ab..2008623631da 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp @@ -33,6 +33,10 @@ struct AggregateFunctionCombinatorArgMinArgMaxData SingleValueDataBase & data() { return v_data.get(); } const SingleValueDataBase & data() const { return v_data.get(); } + + /// False after the nested state is destroyed until it is created again, so a throwing nested `create` does not lead + /// to a second nested `destroy`. + bool nested_created = true; }; template @@ -57,6 +61,19 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH return *reinterpret_cast(place + key_offset); } + /// Replaces the nested state with an empty one. + void resetNested(AggregateDataPtr __restrict place) const + { + auto & key = data(place); + if (key.nested_created) + { + nested_function->destroy(place); + key.nested_created = false; + } + nested_function->create(place); + key.nested_created = true; + } + public: AggregateFunctionCombinatorArgMinArgMax(AggregateFunctionPtr nested_function_, const DataTypes & arguments, const Array & params) : IAggregateFunctionHelper>{arguments, params, nested_function_->getResultType()} @@ -120,8 +137,7 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH if ((isMin && data(place).data().setIfSmaller(rhs_key.data(), arena)) || (!isMin && data(place).data().setIfGreater(rhs_key.data(), arena))) { - nested_function->destroy(place); - nested_function->create(place); + resetNested(place); nested_function->mergeStateFromDifferentVariant(place, *rhs_nested, rhs_place, arena); } else if (data(place).data().isEqualTo(rhs_key.data())) @@ -155,19 +171,31 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH void create(AggregateDataPtr __restrict place) const override { nested_function->create(place); - new (place + key_offset) Key(key_type); + try + { + new (place + key_offset) Key(key_type); + } + catch (...) + { + nested_function->destroy(place); + throw; + } } void destroy(AggregateDataPtr __restrict place) const noexcept override { + const bool nested_created = data(place).nested_created; data(place).~Key(); - nested_function->destroy(place); + if (nested_created) + nested_function->destroy(place); } void destroyUpToState(AggregateDataPtr __restrict place) const noexcept override { + const bool nested_created = data(place).nested_created; data(place).~Key(); - nested_function->destroyUpToState(place); + if (nested_created) + nested_function->destroyUpToState(place); } void add(AggregateDataPtr __restrict place, const IColumn ** columns, size_t row_num, Arena * arena) const override @@ -175,8 +203,7 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH if ((isMin && data(place).data().setIfSmaller(*columns[key_col], row_num, arena)) || (!isMin && data(place).data().setIfGreater(*columns[key_col], row_num, arena))) { - nested_function->destroy(place); - nested_function->create(place); + resetNested(place); nested_function->add(place, columns, row_num, arena); } else if (data(place).data().isEqualTo(*columns[key_col], row_num)) @@ -190,8 +217,7 @@ class AggregateFunctionCombinatorArgMinArgMax final : public IAggregateFunctionH if ((isMin && data(place).data().setIfSmaller(data(rhs).data(), arena)) || (!isMin && data(place).data().setIfGreater(data(rhs).data(), arena))) { - nested_function->destroy(place); - nested_function->create(place); + resetNested(place); nested_function->merge(place, rhs, arena); } else if (data(place).data().isEqualTo(data(rhs).data())) diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h index 036884376681..c8f56845a9c4 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h +++ b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.h @@ -309,7 +309,15 @@ class AggregateFunctionDistinct final : public IAggregateFunctionDataHelpercreate(getNestedPlace(place)); + try + { + nested_func->create(getNestedPlace(place)); + } + catch (...) + { + this->data(place).~Data(); + throw; + } } void destroy(AggregateDataPtr __restrict place) const noexcept override diff --git a/src/AggregateFunctions/WindowFunction.h b/src/AggregateFunctions/WindowFunction.h index efa447f8f20e..e1dece457011 100644 --- a/src/AggregateFunctions/WindowFunction.h +++ b/src/AggregateFunctions/WindowFunction.h @@ -53,6 +53,10 @@ struct WindowFunctionWorkspace // Will not be initialized for a pure window function. mutable AlignedBuffer aggregate_function_state; + /// False after the state is destroyed until it is created again, so a throwing `create` does not lead to a second + /// `destroy`. + bool aggregate_function_state_created = false; + // Argument columns. Be careful, this is a per-block cache. VectorWithMemoryTracking argument_columns; UInt64 cached_block_number = std::numeric_limits::max(); diff --git a/src/Analyzer/FunctionNode.h b/src/Analyzer/FunctionNode.h index 396991a9d860..1835426d4aa1 100644 --- a/src/Analyzer/FunctionNode.h +++ b/src/Analyzer/FunctionNode.h @@ -203,6 +203,9 @@ class FunctionNode final : public IQueryTreeNode wrap_with_nullable = true; } + /// Whether `convertToNullable` was called, also when the result type cannot be `Nullable` and did not change. + bool isConvertedToNullable() const { return wrap_with_nullable; } + void dumpTreeImpl(WriteBuffer & buffer, FormatState & format_state, size_t indent) const override; protected: diff --git a/src/Analyzer/Passes/IfChainToMultiIfPass.cpp b/src/Analyzer/Passes/IfChainToMultiIfPass.cpp index 83ae67a64919..31388d1e2f42 100644 --- a/src/Analyzer/Passes/IfChainToMultiIfPass.cpp +++ b/src/Analyzer/Passes/IfChainToMultiIfPass.cpp @@ -3,9 +3,13 @@ #include #include +#include +#include #include #include +#include + namespace DB { namespace Setting @@ -19,6 +23,39 @@ namespace Setting namespace { +/// The `if` nodes of the query, outside of its subqueries, that are `GROUP BY` keys, collected before any of them is rewritten. +std::unordered_set collectGroupByKeyIfNodes(const QueryNode & query_node) +{ + auto is_if = [](const QueryTreeNodePtr & node) + { + const auto * function_node = node->as(); + return function_node && function_node->getFunctionName() == "if" && function_node->getArguments().getNodes().size() == 3; + }; + + auto if_keys = getGroupByKeys(query_node); + std::erase_if(if_keys, [&](const auto & key) { return !is_if(key); }); + + std::unordered_set result; + if (if_keys.empty()) + return result; + + std::vector nodes{&query_node}; + while (!nodes.empty()) + { + const auto * node = nodes.back(); + nodes.pop_back(); + for (const auto & child : node->getChildren()) + { + if (!child || child->getNodeType() == QueryTreeNodeType::QUERY || child->getNodeType() == QueryTreeNodeType::UNION) + continue; + if (is_if(child) && isGroupByKeyAfterAggregation(child, if_keys)) + result.insert(child); + nodes.push_back(child.get()); + } + } + return result; +} + class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContext { public: @@ -28,10 +65,19 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextas()) + { + group_by_key_if_nodes_stack.push_back( + getSettings()[Setting::optimize_if_chain_to_multiif] ? collectGroupByKeyIfNodes(*query_node) : std::unordered_set{}); + return; + } + if (!getSettings()[Setting::optimize_if_chain_to_multiif]) return; @@ -53,6 +99,10 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextgetFunctionName() != "if" || if_chain_function_node->getArguments().getNodes().size() != 3) break; + /// A `GROUP BY` key is read from the aggregation result, so it is not spliced into the chain. + if (if_chain_function_node->isConvertedToNullable() || group_by_key_if_nodes_stack.back().contains(if_chain_node)) + break; + /// Replace last `multiIf` argument with `if` function arguments multi_if_arguments.pop_back(); @@ -74,14 +124,27 @@ class IfChainToMultiIfPassVisitor : public InDepthQueryTreeVisitorWithContextgetResultType()->equals(*function_node->getResultType())) + if (!multi_if_function->getResultType()->equals(*function_node->getFunctionOrThrow()->getResultType())) return; + /// A `group_by_use_nulls` copy of a GROUP BY key is the key made Nullable: rewrite it like the key and keep it Nullable. + if (function_node->isConvertedToNullable()) + multi_if_function->convertToNullable(); + node = std::move(multi_if_function); } + void leaveImpl(QueryTreeNodePtr & node) + { + if (node->getNodeType() == QueryTreeNodeType::QUERY) + group_by_key_if_nodes_stack.pop_back(); + } + private: FunctionOverloadResolverPtr multi_if_function_ptr; + + /// For each enclosing query, its `if` nodes that are `GROUP BY` keys; the first set is for an expression outside of any query. + std::vector> group_by_key_if_nodes_stack; }; } diff --git a/src/Analyzer/Passes/IfConstantConditionPass.cpp b/src/Analyzer/Passes/IfConstantConditionPass.cpp index 6b24eb1d5391..dd1f7366c79f 100644 --- a/src/Analyzer/Passes/IfConstantConditionPass.cpp +++ b/src/Analyzer/Passes/IfConstantConditionPass.cpp @@ -3,8 +3,11 @@ #include #include +#include #include #include +#include +#include #include namespace DB @@ -13,6 +16,41 @@ namespace DB namespace { +/// The planner tells GROUP BY keys apart by expression and by column source, not by the aliases in the expression. +/// A column is named after the unique alias of its source instead, so that comparing keys does not compare sources. +QueryTreeNodePtr cloneForComparison(const QueryTreeNodePtr & node) +{ + auto name_after_source = [](QueryTreeNodePtr & current) + { + const auto * column_node = current->as(); + if (!column_node) + return; + auto source = column_node->getColumnSourceOrNull(); + if (source && source->hasAlias()) + current = std::make_shared( + NameAndTypePair{source->getAlias() + "." + column_node->getColumnName(), column_node->getColumnType()}, + TableExpressionNodeWeakPtr{}); + }; + + auto result = node->clone(); + name_after_source(result); + std::vector nodes{result.get()}; + while (!nodes.empty()) + { + auto * current = nodes.back(); + nodes.pop_back(); + current->removeAlias(); + for (auto & child : current->getChildren()) + { + if (!child || child->getNodeType() == QueryTreeNodeType::QUERY || child->getNodeType() == QueryTreeNodeType::UNION) + continue; + name_after_source(child); + nodes.push_back(child.get()); + } + } + return result; +} + class IfConstantConditionVisitor : public InDepthQueryTreeVisitorWithContext { public: @@ -21,6 +59,22 @@ class IfConstantConditionVisitor : public InDepthQueryTreeVisitorWithContextas()) + skip_query_folding.push_back(ifConstantConditionFoldingMergesGroupingKeys(*query_node, getContext())); + } + + /// After the arguments, so that a chain collapses in one visit and visiting a shared node again is a no-op. + void leaveImpl(QueryTreeNodePtr & node) + { + if (node->getNodeType() == QueryTreeNodeType::QUERY) + { + skip_query_folding.pop_back(); + return; + } + + if (!skip_query_folding.empty() && skip_query_folding.back()) + return; + auto * function_node = node->as(); if (!function_node || (function_node->getFunctionName() != "if" && function_node->getFunctionName() != "multiIf")) return; @@ -51,12 +105,72 @@ class IfConstantConditionVisitor : public InDepthQueryTreeVisitorWithContextgetArguments().getNodes()[2]; if (node->getResultType()->equals(*argument_node->getResultType())) + { node = argument_node; + return; + } + + /// A `group_by_use_nulls` copy of a GROUP BY key is the key made Nullable: fold it like the key and keep it Nullable. + const auto argument_node_type = argument_node->getNodeType(); + const bool argument_can_be_nullable = argument_node_type == QueryTreeNodeType::COLUMN + || (argument_node_type == QueryTreeNodeType::FUNCTION && argument_node->as().isOrdinaryFunction()); + if (argument_can_be_nullable && function_node->getFunctionOrThrow()->getResultType()->equals(*argument_node->getResultType())) + { + auto nullable_argument_node = argument_node->clone(); + nullable_argument_node->convertToNullable(); + node = std::move(nullable_argument_node); + } } + +private: + /// Whether folding is skipped in the expressions of each enclosing query; nested queries decide for themselves. + std::vector skip_query_folding; }; } +/// ROLLUP, CUBE and GROUPING SETS take their grouping sets from the distinct keys, so folding may make two keys +/// equal only if they are in the same grouping sets; a ROLLUP or CUBE key is told apart by its position. +bool ifConstantConditionFoldingMergesGroupingKeys(const QueryNode & query_node, const ContextPtr & context) +{ + if (!query_node.isGroupByWithRollup() && !query_node.isGroupByWithCube() && !query_node.isGroupByWithGroupingSets()) + return false; + + QueryTreeNodePtrWithHashMap> key_grouping_sets; + auto add_key = [&](const QueryTreeNodePtr & key, size_t grouping_set) + { + auto & grouping_sets = key_grouping_sets[cloneForComparison(key)]; + if (grouping_sets.empty() || grouping_sets.back() != grouping_set) + grouping_sets.push_back(grouping_set); + }; + + const auto & group_by_nodes = query_node.getGroupBy().getNodes(); + for (size_t i = 0; i < group_by_nodes.size(); ++i) + { + if (query_node.isGroupByWithGroupingSets()) + { + for (const auto & key : group_by_nodes[i]->as().getNodes()) + add_key(key, i); + } + else + { + add_key(group_by_nodes[i], i); + } + } + + QueryTreeNodePtrWithHashMap *> folded_key_grouping_sets; + for (const auto & [key, grouping_sets] : key_grouping_sets) + { + auto folded_key = key.node->clone(); + IfConstantConditionVisitor(context).visit(folded_key); + auto [it, inserted] = folded_key_grouping_sets.emplace(std::move(folded_key), &grouping_sets); + if (!inserted && *it->second != grouping_sets) + return true; + } + + return false; +} + void IfConstantConditionPass::run(QueryTreeNodePtr & query_tree_node, ContextPtr context) { IfConstantConditionVisitor visitor(std::move(context)); diff --git a/src/Analyzer/Passes/IfConstantConditionPass.h b/src/Analyzer/Passes/IfConstantConditionPass.h index 7548fc702bc6..e880c0284520 100644 --- a/src/Analyzer/Passes/IfConstantConditionPass.h +++ b/src/Analyzer/Passes/IfConstantConditionPass.h @@ -5,6 +5,8 @@ namespace DB { +class QueryNode; + /** Convert `if` with constant condition or `multiIf` with single constant condition into true condition argument value * or false condition argument value. * @@ -25,4 +27,8 @@ class IfConstantConditionPass final : public IQueryTreePass }; +/// Whether `IfConstantConditionPass` leaves the expressions of `query_node` unfolded, because folding them would merge +/// ROLLUP, CUBE or GROUPING SETS keys of different grouping sets. +bool ifConstantConditionFoldingMergesGroupingKeys(const QueryNode & query_node, const ContextPtr & context); + } diff --git a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp index 2eebf5cc6be0..7a997118f8bf 100644 --- a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp +++ b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp @@ -1,9 +1,13 @@ #include +#include #include #include #include +#include +#include +#include #include #include #include @@ -181,4 +185,32 @@ QueryTreeNodes unwrapInjectiveFunctionsInKeys(const QueryTreeNodes & keys, bool return new_keys; } +QueryTreeNodes getGroupByKeys(const QueryNode & query_node) +{ + QueryTreeNodes keys; + if (!query_node.hasGroupBy()) + return keys; + + for (const auto & node : query_node.getGroupBy().getNodes()) + { + if (query_node.isGroupByWithGroupingSets()) + { + const auto & grouping_set_keys = node->as().getNodes(); + keys.insert(keys.end(), grouping_set_keys.begin(), grouping_set_keys.end()); + } + else + { + keys.push_back(node); + } + } + return keys; +} + +bool isGroupByKeyAfterAggregation(const QueryTreeNodePtr & node, const QueryTreeNodes & group_by_keys) +{ + if (const auto * function_node = node->as(); function_node && function_node->isConvertedToNullable()) + return true; + return std::ranges::any_of(group_by_keys, [&](const auto & key) { return compareGroupByKeys(node, key); }); +} + } diff --git a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h index 63b59f76fc97..a429af960a71 100644 --- a/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h +++ b/src/Analyzer/Passes/OptimizeKeyExpressionsUtils.h @@ -6,6 +6,8 @@ namespace DB { +class QueryNode; + /** Shared helpers for cleaning up the key list of `GROUP BY` and `LIMIT BY`. Both group rows by * the distinct combinations of their key values. A key is dropped or rewritten only when this * grouping stays the same and the old value can still be computed from the keys that remain, so @@ -26,4 +28,11 @@ void removeKeysThatAreFunctionsOfOtherKeys(QueryTreeNodes & keys); /// `Dynamic` or `Variant` argument into a key. QueryTreeNodes unwrapInjectiveFunctionsInKeys(const QueryTreeNodes & keys, bool allow_suspicious_types); +/// The `GROUP BY` keys of `query_node`, of all grouping sets. +QueryTreeNodes getGroupByKeys(const QueryNode & query_node); + +/// Returns true if `node`, in an expression computed after `GROUP BY`, is a key, read from the aggregation result. +/// Under `group_by_use_nulls` the analyzer replaces a key there with a copy converted to `Nullable`, not equal to the key. +bool isGroupByKeyAfterAggregation(const QueryTreeNodePtr & node, const QueryTreeNodes & group_by_keys); + } diff --git a/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp b/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp index 7c1060821240..e346bbea180d 100644 --- a/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp +++ b/src/Analyzer/Passes/OrderByTupleEliminationPass.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -21,13 +22,17 @@ class OrderByTupleEliminationVisitor : public InDepthQueryTreeVisitorhasOrderBy()) return; + const auto group_by_keys = getGroupByKeys(*query_node); + QueryTreeNodes result_nodes; for (auto & sort_node : query_node->getOrderBy().getNodes()) { auto & sort_node_typed = sort_node->as(); auto * function_expression = sort_node_typed.getExpression()->as(); - if (sort_node_typed.withFill() || !function_expression || function_expression->getFunctionName() != "tuple") + /// Splitting a key would read its arguments, which do not exist after aggregation. + if (sort_node_typed.withFill() || !function_expression || function_expression->getFunctionName() != "tuple" + || isGroupByKeyAfterAggregation(sort_node_typed.getExpression(), group_by_keys)) { result_nodes.push_back(sort_node); continue; diff --git a/src/Analyzer/Resolve/IdentifierResolveScope.h b/src/Analyzer/Resolve/IdentifierResolveScope.h index 33609d26a3ae..82dbf5b4dcbe 100644 --- a/src/Analyzer/Resolve/IdentifierResolveScope.h +++ b/src/Analyzer/Resolve/IdentifierResolveScope.h @@ -185,6 +185,9 @@ struct IdentifierResolveScope */ QueryTreeNodePtrWithHashIgnoreAliasesMap nullable_group_by_keys; + /// With `group_by_use_nulls`, the columns that `if`/`multiIf` GROUP BY keys may collapse to; used only for correlated references. + QueryTreeNodePtrWithHashIgnoreAliasesSet nullable_collapsed_group_by_key_columns; + /** It's possible that after a JOIN, a column in the projection has a type different from the column in the source table. * (For example, after join_use_nulls or USING column cast to supertype) * However, the column in the projection still refers to the table as its source. diff --git a/src/Analyzer/Resolve/QueryAnalyzer.cpp b/src/Analyzer/Resolve/QueryAnalyzer.cpp index 8022ac36e3aa..d694ef5a85d1 100644 --- a/src/Analyzer/Resolve/QueryAnalyzer.cpp +++ b/src/Analyzer/Resolve/QueryAnalyzer.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -3777,6 +3778,12 @@ ProjectionNames QueryAnalyzer::resolveExpressionNode( } break; } + + if (is_correlated_column_node && scope_ptr->nullable_collapsed_group_by_key_columns.contains(node)) + { + node->convertToNullable(); + break; + } } /// For local references stop at the first surrounding QUERY scope. @@ -4146,6 +4153,32 @@ void registerNullableGroupByKeys(const QueryTreeNodes & group_by_keys, Identifie } } +/// The columns `IfConstantConditionPass` may collapse `node` to: the branches of nested `if`/`multiIf`, whatever their conditions. +void registerConstantConditionBranchColumns(const QueryTreeNodePtr & node, IdentifierResolveScope & scope) +{ + const auto * function_node = node->as(); + if (!function_node || (function_node->getFunctionName() != "if" && function_node->getFunctionName() != "multiIf")) + return; + + const auto & arguments = function_node->getArguments().getNodes(); + if (arguments.size() != 3) + return; + + for (size_t i = 1; i < 3; ++i) + { + if (arguments[i]->getNodeType() == QueryTreeNodeType::COLUMN) + scope.nullable_collapsed_group_by_key_columns.insert(arguments[i]->clone()); + else + registerConstantConditionBranchColumns(arguments[i], scope); + } +} + +void registerCollapsedGroupByKeyColumns(const QueryTreeNodes & group_by_keys, IdentifierResolveScope & scope) +{ + for (const auto & key : group_by_keys) + registerConstantConditionBranchColumns(key, scope); +} + } /** Resolve GROUP BY clause. @@ -4203,7 +4236,12 @@ void QueryAnalyzer::resolveGroupByNode(QueryNode & query_node_typed, IdentifierR } if (!nullable_group_by_keys.empty()) + { registerNullableGroupByKeys(nullable_group_by_keys, scope); + /// Only if `IfConstantConditionPass` folds the keys of this query, so that the collapsed columns exist after aggregation. + if (!ifConstantConditionFoldingMergesGroupingKeys(query_node_typed, scope.context)) + registerCollapsedGroupByKeyColumns(nullable_group_by_keys, scope); + } /// With group_by_use_nulls the projection (and the other clauses) are re-resolved after GROUP BY /// so that expressions equal to a key become Nullable via the scope.nullable_group_by_keys diff --git a/src/Analyzer/Resolve/resolveFunction.cpp b/src/Analyzer/Resolve/resolveFunction.cpp index 750246027f42..dbfa57e5c7ce 100644 --- a/src/Analyzer/Resolve/resolveFunction.cpp +++ b/src/Analyzer/Resolve/resolveFunction.cpp @@ -1298,7 +1298,10 @@ ProjectionNames QueryAnalyzer::resolveFunction(QueryTreeNodePtr & node, Identifi if (is_special_function_dict_get) { - scope.context->getExternalDictionariesLoader().assertDictionaryStructureExists(identifier.getFullName(), scope.context); + /// Check access before reading the dictionary definition, so that a user without access learns nothing + /// about the dictionary. + const auto & external_loader = scope.context->getExternalDictionariesLoader(); + (void)external_loader.getDictionaryStructure(external_loader.resolveDictionaryCheckingAccess(identifier.getFullName(), scope.context)); } else { diff --git a/src/Backups/BackupFactory.cpp b/src/Backups/BackupFactory.cpp index 6bf331ce6fa8..8fb65ebb537e 100644 --- a/src/Backups/BackupFactory.cpp +++ b/src/Backups/BackupFactory.cpp @@ -1,10 +1,8 @@ -#include #include #include +#include #include -#include - #include #include @@ -25,24 +23,6 @@ namespace { fmt::format_to(std::back_inserter(identity), ":{}:{}", component.size(), component); } - - /// Must normalize identically to `ITableFunction::getFunctionURINormalized`, or the same regex - /// grant matches a table function and not a backup. An empty result requires a whole-source grant. - String normalizeAccessURI(const String & uri) - { - if (uri.empty()) - return uri; - try - { - Poco::URI parsed(uri); - parsed.normalize(); - return parsed.toString(); - } - catch (const Poco::Exception &) - { - return ""; - } - } } @@ -81,8 +61,7 @@ void BackupFactory::checkSourceAccess(const BackupInfo & backup_info, ContextPtr return; if (auto target = it->second.source_access(backup_info, context, open_mode)) - context->getAccess()->checkAccessWithFilter( - target->flags, AccessTypeObjects::toStringSource(target->source), normalizeAccessURI(target->uri)); + ITableFunction::checkSourceAccessForURI(context, target->flags, target->source, target->uri); } BackupMutablePtr BackupFactory::createBackup(const CreateParams & params) const diff --git a/src/Backups/RestorerFromBackup.cpp b/src/Backups/RestorerFromBackup.cpp index a047b66a4ff5..8972133d7200 100644 --- a/src/Backups/RestorerFromBackup.cpp +++ b/src/Backups/RestorerFromBackup.cpp @@ -1,8 +1,11 @@ #include +#include #include #include #include #include +#include +#include #include #include #include @@ -149,6 +152,7 @@ void RestorerFromBackup::run(Mode mode_) setStage(Stage::CHECKING_ACCESS_RIGHTS); loadSystemAccessTables(); checkAccessForObjectsFoundInBackup(); + checkSettingsOfAccessEntitiesToRestore(); if (mode == Mode::CHECK_ACCESS_ONLY) return; @@ -436,6 +440,31 @@ AccessEntitiesToRestore RestorerFromBackup::getAccessEntitiesToRestore(const Str return entities; } +void RestorerFromBackup::checkSettingsOfAccessEntitiesToRestore() const +{ + std::lock_guard lock{mutex}; + if (!access_restorer) + return; + + auto & access_control = context->getAccessControl(); + + /// References must be resolved by name first: the backup's UUIDs are unknown here, and a profile the check cannot read is skipped. + auto restorer_copy = access_restorer->makeCopyForChecking(); + restorer_copy.generateRandomIDsAndResolveDependencies(access_control); + + /// An entity existing here may not exist on another host of `RESTORE ON CLUSTER`, so it is checked too. + auto entities = restorer_copy.getEntitiesFromBackup(); + for (const auto & [id, entity] : entities) + { + if (const auto * user = typeid_cast(entity.get())) + context->checkSettingsConstraints(AlterSettingsProfileElements{user->settings}, SettingSource::USER); + else if (const auto * role = typeid_cast(entity.get())) + context->checkSettingsConstraints(AlterSettingsProfileElements{role->settings}, SettingSource::ROLE); + else if (const auto * profile = typeid_cast(entity.get())) + context->checkSettingsConstraints(AlterSettingsProfileElements{profile->elements}, SettingSource::PROFILE); + } +} + void RestorerFromBackup::createAndCheckDatabases() { Strings database_names; diff --git a/src/Backups/RestorerFromBackup.h b/src/Backups/RestorerFromBackup.h index aad3d2eb4232..4ee0bc1530af 100644 --- a/src/Backups/RestorerFromBackup.h +++ b/src/Backups/RestorerFromBackup.h @@ -86,6 +86,9 @@ class RestorerFromBackup : public BackupMetadataFinder void loadSystemAccessTables(); void checkAccessForObjectsFoundInBackup() const; + /// Applies the settings constraints check of `CREATE [OR REPLACE] USER/ROLE/SETTINGS PROFILE` to the entities to restore. + void checkSettingsOfAccessEntitiesToRestore() const; + void createAndCheckDatabases(); void createAndCheckDatabase(const String & database_name); void createAndCheckDatabaseImpl(const String & database_name); diff --git a/src/Backups/registerBackupEngineAzureBlobStorage.cpp b/src/Backups/registerBackupEngineAzureBlobStorage.cpp index d3d4afa57d65..5d9753324c20 100644 --- a/src/Backups/registerBackupEngineAzureBlobStorage.cpp +++ b/src/Backups/registerBackupEngineAzureBlobStorage.cpp @@ -18,6 +18,8 @@ #include +#include + #endif @@ -44,8 +46,6 @@ namespace AzureBlobStorage::ConnectionParams connection_params; String blob_path; String archive_name; - /// `blob_path` before a trailing archive filename is stripped off it. - String blob_path_with_archive; }; String removeFileNameFromURL(String & url) @@ -178,7 +178,6 @@ namespace "(storage account URL, container, path, account name, account key)"); } - location.blob_path_with_archive = location.blob_path; if (hasRegisteredArchiveFileExtension(location.blob_path)) location.archive_name = removeFileNameFromURL(location.blob_path); return location; @@ -198,7 +197,11 @@ namespace return target; } - target.uri = resolveAzureBackupLocation(backup_info, context).blob_path_with_archive; + /// The key that is accessed: an archive is opened under the split-off `blob_path`. + const auto location = resolveAzureBackupLocation(backup_info, context); + target.uri = location.archive_name.empty() + ? location.blob_path + : String(std::filesystem::path(location.blob_path) / location.archive_name); return target; } diff --git a/src/Client/Connection.cpp b/src/Client/Connection.cpp index c268c0545e7f..a7773d4aea8c 100644 --- a/src/Client/Connection.cpp +++ b/src/Client/Connection.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -83,6 +84,7 @@ namespace FailPoints namespace ErrorCodes { + extern const int AUTHENTICATION_FAILED; extern const int NETWORK_ERROR; extern const int SOCKET_TIMEOUT; extern const int UNEXPECTED_PACKET_FROM_SERVER; @@ -701,7 +703,8 @@ void Connection::receiveHello() if (server_revision >= DBMS_MIN_REVISION_WITH_SERVER_SETTINGS) { Settings settings; - settings.read(*in, SettingsWriteFormat::STRINGS_WITH_FLAGS); + /// A server of another version may send values that this version rejects. + settings.read(*in, SettingsWriteFormat::STRINGS_WITH_FLAGS, /* skip_invalid_values= */ true); settings_from_server = settings.changes(); } @@ -1057,6 +1060,20 @@ void Connection::sendQuery( disconnect(); }); + /// Over the cluster secret a shard authenticates as `initial_user` without a password, so forward + /// only an `initial_user` equal to the authenticated `current_user`. Skip the check when + /// `current_user` is empty -- server-internal paths (async `Distributed` insert, buffer flush) have none. + if (!cluster_secret.empty() && client_info && !client_info->current_user.empty() + && client_info->initial_user != client_info->current_user) + { + /// A mismatch means a forged SECONDARY_QUERY impersonating another user -- including an empty + /// initial_user, which the shard would otherwise run with full access -- so refuse it. + throw Exception(ErrorCodes::AUTHENTICATION_FAILED, + "Refusing to forward a query over the cluster secret: its initial_user '{}' differs " + "from the authenticated user '{}'.", + client_info->initial_user, client_info->current_user); + } + writeVarUInt(Protocol::Client::Query, *out); writeStringBinary(query_id, *out); @@ -1669,7 +1686,16 @@ Block Connection::receiveDataImpl(NativeReader & reader) Block Connection::receiveProfileEvents() { initBlockProfileEventsInput(); - return receiveDataImpl(*block_profile_events_in); + Block block = receiveDataImpl(*block_profile_events_in); + + /// The servers before this revision report the counters in another form (total values instead of + /// increments, in a block of another structure), which nothing reads: what they have sent is skipped. + if (server_revision < DBMS_MIN_PROTOCOL_VERSION_WITH_INCREMENTAL_PROFILE_EVENTS) + return ProfileEvents::getSampleBlock(); + + /// The structure of the block is chosen by the server, and the consumers of the packet rely on it. + ProfileEvents::checkBlockStructure(block); + return block; } diff --git a/src/Columns/ColumnObject.cpp b/src/Columns/ColumnObject.cpp index af2242c747b2..be42aee89024 100644 --- a/src/Columns/ColumnObject.cpp +++ b/src/Columns/ColumnObject.cpp @@ -20,6 +20,7 @@ namespace DB namespace ErrorCodes { extern const int ATTEMPT_TO_READ_AFTER_EOF; + extern const int INCORRECT_DATA; extern const int NOT_IMPLEMENTED; extern const int LOGICAL_ERROR; extern const int PARAMETER_OUT_OF_BOUND; @@ -431,6 +432,11 @@ UInt64 ColumnObject::getNumberOfDefaultRows() const if (num_non_default == num_rows) return; + /// The indices of the non-default rows of a subcolumn index the bitmap of `num_rows` entries. + if (column.size() != num_rows) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "Subcolumn of a JSON column has {} rows, but the column has {} rows", column.size(), num_rows); + const size_t num_defaults_in_column = column.getNumberOfDefaultRows(); if (num_defaults_in_column == num_rows) return; @@ -1188,6 +1194,7 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in readBinaryLittleEndian(num_paths, in); const auto [shared_data_paths, shared_data_values] = getSharedDataPathsAndValues(); + const size_t shared_data_row_start = shared_data_paths->size(); for (size_t i = 0; i != num_paths; ++i) { size_t path_size = 0; @@ -1206,9 +1213,17 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in size_t value_size = 0; readBinaryLittleEndian(value_size, in); + /// `serializeDynamicPathsAndSharedDataIntoArena` writes every path of a row once. A path repeated + /// in the row would get several values in a column of a dynamic path, or break the order of shared data. + /// Typed paths are deserialized before, so a typed path here would be a second value of it. + if (typed_paths.contains(path)) + throw Exception(ErrorCodes::INCORRECT_DATA, "Typed path '{}' in dynamic paths of a serialized value of JSON column", path); + /// Check if we have this path in dynamic paths. if (auto dynamic_it = dynamic_paths.find(path); dynamic_it != dynamic_paths.end()) { + if (dynamic_it->second->size() != current_size) + throw Exception(ErrorCodes::INCORRECT_DATA, "Duplicate path '{}' in a serialized value of JSON column", path); getDynamicSerialization()->deserializeBinary(*dynamic_it->second, in, getFormatSettings()); } /// Try to add a new dynamic path. @@ -1226,6 +1241,9 @@ void ColumnObject::deserializeDynamicPathsAndSharedDataFromArena(ReadBuffer & in "Attempt to read {} bytes for the value size, but only {} bytes are available", value_size, in.available()); + if (shared_data_paths->size() > shared_data_row_start && shared_data_paths->getDataAt(shared_data_paths->size() - 1) >= path) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Paths of a serialized value of JSON column are not sorted or have duplicates (at path '{}')", path); std::string_view value(in.position(), value_size); in.ignore(value_size); shared_data_paths->insertData(path.data(), path.size()); diff --git a/src/Columns/ColumnUnique.h b/src/Columns/ColumnUnique.h index 447a52cdbe0c..7aa83411a6f1 100644 --- a/src/Columns/ColumnUnique.h +++ b/src/Columns/ColumnUnique.h @@ -28,6 +28,7 @@ namespace DB namespace ErrorCodes { extern const int ATTEMPT_TO_READ_AFTER_EOF; + extern const int INCORRECT_DATA; extern const int LOGICAL_ERROR; extern const int ILLEGAL_COLUMN; extern const int NOT_IMPLEMENTED; @@ -616,6 +617,9 @@ size_t ColumnUnique::uniqueDeserializeAndInsertFromArena(ReadBuffer if (in.available() < string_size) throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize string value in ColumnUnique."); + if (unlikely(string_size < serialize_string_with_zero_byte)) + throw Exception(ErrorCodes::INCORRECT_DATA, "String size is smaller than its zero-byte terminator"); + size_t ret = uniqueInsertData(in.position(), string_size - serialize_string_with_zero_byte); in.ignore(string_size); return ret; @@ -624,39 +628,8 @@ size_t ColumnUnique::uniqueDeserializeAndInsertFromArena(ReadBuffer template size_t ColumnUnique::uniqueDeserializeAndInsertAggregationStateValueFromArena(ReadBuffer & in) { - if (is_nullable) - { - UInt8 val = 0; - readBinaryLittleEndian(val, in); - - if (val) - return getNullValueIndex(); - - } - - /// Numbers, FixedString - if (size_of_value_if_fixed) - { - if (in.available() < size_of_value_if_fixed) - throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize fixed size value in ColumnUnique."); - - size_t ret = uniqueInsertData(in.position(), size_of_value_if_fixed); - in.ignore(size_of_value_if_fixed); - return ret; - - } - - /// String - /// For compatibility, serialized string value contains zero byte at the end, we just ignore this byte. - size_t string_size_with_zero_byte = 0; - readBinaryLittleEndian(string_size_with_zero_byte, in); - if (in.available() < string_size_with_zero_byte) - throw Exception(ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF, "Not enough data to deserialize string value in ColumnUnique."); - - size_t ret = uniqueInsertData(in.position(), string_size_with_zero_byte - 1); - in.ignore(string_size_with_zero_byte); - - return ret; + const auto settings = IColumn::SerializationSettings::createForAggregationState(); + return uniqueDeserializeAndInsertFromArena(in, &settings); } template diff --git a/src/Common/AsynchronousMetrics.cpp b/src/Common/AsynchronousMetrics.cpp index db8f1d6f6fca..0e92766461b3 100644 --- a/src/Common/AsynchronousMetrics.cpp +++ b/src/Common/AsynchronousMetrics.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include #include +#include #include "config.h" @@ -153,6 +155,7 @@ AsynchronousMetrics::AsynchronousMetrics( /// CGroups v2 openCgroupv2MetricFile("memory.max", cgroupmem_limit_in_bytes); openCgroupv2MetricFile("cpu.max", cgroupcpu_max); + openCgroupv2MetricFile("cpuset.cpus.effective", cgroupcpuset); openCgroupv2MetricFile("cpu.stat", cgroupcpu_stat); /// CGroups v1 @@ -165,6 +168,8 @@ AsynchronousMetrics::AsynchronousMetrics( } if (!cgroupcpu_stat) openFileIfExists("/sys/fs/cgroup/cpuacct/cpuacct.stat", cgroupcpuacct_stat); + if (!cgroupcpuset) + openFileIfExists("/sys/fs/cgroup/cpuset/cpuset.effective_cpus", cgroupcpuset); try { @@ -1683,9 +1688,37 @@ void AsynchronousMetrics::update(TimePoint update_time, bool force_update) } } + /// With exclusive CPUs (e.g. the static CPU manager of Kubernetes) there is no CFS quota (`cpu.max` is `max`), + /// and the limit is only visible in the cpuset. + if (cgroupcpuset) + { + try + { + cgroupcpuset->rewind(); + + String cpu_list; + readString(cpu_list, *cgroupcpuset); + if (auto cpuset_cpus = countCPUsInList(cpu_list)) + { + const auto cpuset_cores = static_cast(*cpuset_cpus); + if (max_cpu_cgroups > 0) + max_cpu_cgroups = std::min(max_cpu_cgroups, cpuset_cores); + /// Without a quota, a cpuset with all online CPUs is not a limit. + else if (*cpuset_cpus < std::thread::hardware_concurrency()) + max_cpu_cgroups = cpuset_cores; + } + } + catch (...) + { + tryLogCurrentException(__PRETTY_FUNCTION__); + } + } + if (max_cpu_cgroups > 0) { - new_values["CGroupMaxCPU"] = { max_cpu_cgroups, "The maximum number of CPU cores according to CGroups."}; + new_values["CGroupMaxCPU"] = { max_cpu_cgroups, + "The maximum number of CPU cores according to CGroups: the minimum of the CPU quota divided by its period " + "and the number of CPUs in the effective cpuset."}; } if (cgroupcpu_stat || cgroupcpuacct_stat) diff --git a/src/Common/AsynchronousMetrics.h b/src/Common/AsynchronousMetrics.h index cd7c9b6706a2..01124fb45e8b 100644 --- a/src/Common/AsynchronousMetrics.h +++ b/src/Common/AsynchronousMetrics.h @@ -190,6 +190,7 @@ class AsynchronousMetrics std::optional cgroupcpu_cfs_period TSA_GUARDED_BY(data_mutex); std::optional cgroupcpu_cfs_quota TSA_GUARDED_BY(data_mutex); std::optional cgroupcpu_max TSA_GUARDED_BY(data_mutex); + std::optional cgroupcpuset TSA_GUARDED_BY(data_mutex); std::optional cgroupcpu_stat TSA_GUARDED_BY(data_mutex); std::optional cgroupcpuacct_stat TSA_GUARDED_BY(data_mutex); diff --git a/src/Common/DateLUTImpl.cpp b/src/Common/DateLUTImpl.cpp index 305e2b1f277a..6688f0ccc7f6 100644 --- a/src/Common/DateLUTImpl.cpp +++ b/src/Common/DateLUTImpl.cpp @@ -324,6 +324,14 @@ DateLUTImpl::Time DateLUTImpl::timezoneOffsetOutOfRange(Time t) const return cctz_time_zone->lookup(std::chrono::system_clock::from_time_t(t)).offset; } +DateLUTImpl::Time DateLUTImpl::timezoneOffsetAtLocalTimeOutOfRange(Time t) const +{ + t = std::clamp(t, min_representable_time, max_representable_time); + const auto local = cctz::civil_second{1970, 1, 1} + t; + return t - std::chrono::system_clock::to_time_t( + cctz_time_zone->lookup(local).post); +} + DateLUTImpl::Time DateLUTImpl::addDaysOutOfRange(Time t, Int64 delta) const { /// Keep the same wall-clock time of day, but on the day that is `delta` days away. diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 26cf5f97e2df..465b469ca03a 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -872,11 +872,7 @@ class DateLUTImpl return res <= 23 ? res : 23; } - /** Calculating offset from UTC in seconds. - * which means Using the same literal time of "t" to get the corresponding timestamp in UTC, - * then subtract the former from the latter to get the offset result. - * The boundaries when meets DST(daylight saving time) change should be handled very carefully. - */ + /// The offset from UTC at the instant `t`. Time timezoneOffset(Time t) const { if (unlikely(isOutOfLUTRange(t))) @@ -895,6 +891,29 @@ class DateLUTImpl return res; } + /// The offset from UTC at the local time `t`, which is a wall clock read as seconds since the epoch, so that + /// `t - timezoneOffsetAtLocalTime(t)` is its UTC time. A repeated or skipped local time is resolved as in `makeDateTime`. + Time timezoneOffsetAtLocalTime(Time t) const + { + Int64 day = t / 86400; + Time time_of_day = t % 86400; + if (time_of_day < 0) + { + --day; + time_of_day += 86400; + } + + const Int64 index = day + daynum_offset_epoch; + if (unlikely(static_cast(index) >= DATE_LUT_SIZE)) + return timezoneOffsetAtLocalTimeOutOfRange(t); + + const Values & values = lut[index]; + Time res = day * 86400 - values.date; + if (values.amount_of_offset_change() != 0 && time_of_day >= values.time_at_offset_change()) + res += values.amount_of_offset_change(); + return res; + } + unsigned toSecond(Time t) const { @@ -1914,6 +1933,7 @@ class DateLUTImpl DateTimeComponents toDateTimeComponentsOutOfRange(Time t) const; Time toTimeOutOfRange(Time t) const; Time timezoneOffsetOutOfRange(Time t) const; + Time timezoneOffsetAtLocalTimeOutOfRange(Time t) const; Time addDaysOutOfRange(Time t, Int64 delta) const; Time addMonthsOutOfRange(Time t, Int64 delta) const; Time addYearsOutOfRange(Time t, Int64 delta) const; diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index ecbd7f6d9d05..f6a1d98856f6 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -294,6 +294,8 @@ static struct InitFiu REGULAR(rmt_merge_selecting_task_max_part_size) \ REGULAR(merge_tree_load_statistics_throw) \ REGULAR(merge_tree_load_outdated_parts_retryable_error) \ + REGULAR(merge_tree_load_outdated_parts_schedule_error) \ + PAUSEABLE_ONCE(mt_pause_before_loading_outdated_part) \ PAUSEABLE(merge_tree_load_outdated_parts_pause) \ PAUSEABLE(smt_mutate_task_pause_in_prepare) \ PAUSEABLE(smt_merge_selecting_task_pause_when_scheduled) \ diff --git a/src/Common/HTTPHeaderFilter.cpp b/src/Common/HTTPHeaderFilter.cpp index 2285f8f6ab02..59e0e5948e0d 100644 --- a/src/Common/HTTPHeaderFilter.cpp +++ b/src/Common/HTTPHeaderFilter.cpp @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include #include @@ -53,6 +55,37 @@ void HTTPHeaderFilter::checkAndNormalizeHeaders(HTTPHeaderEntries & entries) con } } +void HTTPHeaderFilter::checkBasicCredentials(const Poco::Net::HTTPBasicCredentials & credentials) const +{ + if (credentials.getUsername().empty()) + return; + + checkAuthorizationHeader("Basic authentication credentials, for example the userinfo of a URL, are sent in this header"); +} + +void HTTPHeaderFilter::checkURIUserInfo(const Poco::URI & uri) const +{ + if (uri.getUserInfo().empty()) + return; + + checkAuthorizationHeader("The userinfo of the URL is sent in this header as Basic authentication credentials"); +} + +void HTTPHeaderFilter::checkAuthorizationHeader(const std::string & reason) const +{ + /// A forbidden header is matched by name, and a Base64 value has no CR or LF, so a placeholder value suffices. + HTTPHeaderEntries entries{{"Authorization", "Basic"}}; + try + { + checkAndNormalizeHeaders(entries); + } + catch (Exception & e) + { + e.addMessage(reason); + throw; + } +} + void HTTPHeaderFilter::setValuesFromConfig(const Poco::Util::AbstractConfiguration & config) { std::lock_guard guard(mutex); diff --git a/src/Common/HTTPHeaderFilter.h b/src/Common/HTTPHeaderFilter.h index b6232b40b932..4d3a034320fc 100644 --- a/src/Common/HTTPHeaderFilter.h +++ b/src/Common/HTTPHeaderFilter.h @@ -8,6 +8,8 @@ #include namespace re2 { class RE2; } +namespace Poco { class URI; } +namespace Poco::Net { class HTTPBasicCredentials; } namespace DB { @@ -19,7 +21,14 @@ class HTTPHeaderFilter void setValuesFromConfig(const Poco::Util::AbstractConfiguration & config); void checkAndNormalizeHeaders(HTTPHeaderEntries & entries) const; + /// Throws if the `Authorization` header that sends these credentials is forbidden. An empty username sends no header. + void checkBasicCredentials(const Poco::Net::HTTPBasicCredentials & credentials) const; + /// The same for a sender that sends any non-empty userinfo of `uri` as Basic credentials, even without a username. + void checkURIUserInfo(const Poco::URI & uri) const; + private: + void checkAuthorizationHeader(const std::string & reason) const; + /// Header names are case-insensitive (RFC 7230 3.2): entries are stored /// lower-cased and the incoming name is lower-cased before lookup. std::unordered_set forbidden_headers; diff --git a/src/Common/MemoryWorker.cpp b/src/Common/MemoryWorker.cpp index 178c878a770a..92661dec6085 100644 --- a/src/Common/MemoryWorker.cpp +++ b/src/Common/MemoryWorker.cpp @@ -978,14 +978,28 @@ void MemoryWorker::updateResidentMemoryThread() } } - /// update MemoryTracker with `allocated` information from jemalloc when: + /// update MemoryTracker with `allocated` (the maximum of resident and jemalloc `stats.allocated`) when: /// - it's a first run of MemoryWorker (MemoryTracker could've missed some allocation before its initialization) /// - MemoryTracker stores a negative value /// - `correct_tracker` is set to true - if (first_run || total_memory_tracker.get() < 0) [[unlikely]] - MemoryTracker::updateAllocated(resident, /*log_change=*/true); - else if (correct_tracker) - MemoryTracker::updateAllocated(resident, /*log_change=*/false); + if (first_run || total_memory_tracker.get() < 0 || correct_tracker) + { + /// Every allocation of `Allocator` goes through jemalloc, and `stats.allocated` counts the bytes + /// handed out to the application even if their pages are not touched yet, while the resident + /// memory does not include such pages. Correcting the tracker down to the resident memory alone + /// would forget memory that is allocated but not yet used and admit allocations past + /// `max_server_memory_usage` until the process is killed by the OOM killer. Correcting it down to + /// `stats.allocated` still removes the drift: bytes counted in the tracker without any allocation + /// behind them. + if (source != MemoryUsageSource::Jemalloc) + epoch_mib.setValue(0); + const Int64 allocated = std::max(resident, allocated_mib.getValue()); + + if (first_run || total_memory_tracker.get() < 0) [[unlikely]] + MemoryTracker::updateAllocated(allocated, /*log_change=*/true); + else + MemoryTracker::updateAllocated(allocated, /*log_change=*/false); + } #else /// we don't update in the first run if we don't have jemalloc /// because we can only use resident memory information diff --git a/src/Common/MemoryWorker.h b/src/Common/MemoryWorker.h index 45ccdb315038..4132ff1e7ce2 100644 --- a/src/Common/MemoryWorker.h +++ b/src/Common/MemoryWorker.h @@ -267,6 +267,7 @@ class MemoryWorker Jemalloc::MibCache epoch_mib{"epoch"}; Jemalloc::MibCache resident_mib{"stats.resident"}; + Jemalloc::MibCache allocated_mib{"stats.allocated"}; Jemalloc::MibCache pagesize_mib{"arenas.page"}; Jemalloc::MibCache dirty_decay_ms_mib{"arenas.dirty_decay_ms"}; diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index 76ff1b08cd0a..9a393b53a16c 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -1660,12 +1660,16 @@ The server successfully detected this situation and will download merged part fr \ M(JoinBuildPostProcessingMicroseconds, "Elapsed time of post-processing steps after building the right JOIN side.", ValueType::Microseconds) \ \ - M(AIInputTokens, "Total prompt tokens consumed across all AI function calls in the query.", ValueType::Number) \ + M(AIInputTokens, "Total prompt tokens consumed across all AI function calls in the query, including cache reads and writes.", ValueType::Number) \ M(AIOutputTokens, "Total completion tokens consumed across all AI function calls in the query.", ValueType::Number) \ + M(AICacheReadTokens, "Prompt tokens read from the provider cache, as reported by AI chat providers. Included in AIInputTokens.", ValueType::Number) \ + M(AICacheWriteTokens, "Prompt tokens written to the provider cache, as reported by AI chat providers. Included in AIInputTokens.", ValueType::Number) \ M(AIAPICalls, "Number of HTTP requests dispatched to AI providers.", ValueType::Number) \ M(AIAPICallsRetried, "Number of AI provider requests retried after a transient failure.", ValueType::Number) \ M(AIAPICallsFailed, "Number of AI provider requests that failed after all retries.", ValueType::Number) \ M(AIAPICallsThrottled, "Number of AI provider requests rejected with HTTP 429 (Too Many Requests).", ValueType::Number) \ + M(AIRequestMicroseconds, "Total time spent in AI provider requests, including failed attempts and response parsing, excluding retry backoff. Summed across threads.", ValueType::Microseconds) \ + M(AIRetryBackoffMicroseconds, "Total time spent waiting before retries of failed AI provider requests. Summed across threads.", ValueType::Microseconds) \ M(AIRowsProcessed, "Number of rows that received an AI result.", ValueType::Number) \ M(AIRowsSkipped, "Number of rows that received a default value due to quota or error.", ValueType::Number) \ \ diff --git a/src/Common/RemoteHostFilter.cpp b/src/Common/RemoteHostFilter.cpp index 5b5da5ec7c6b..a5f8b81e1220 100644 --- a/src/Common/RemoteHostFilter.cpp +++ b/src/Common/RemoteHostFilter.cpp @@ -17,13 +17,15 @@ namespace ErrorCodes bool RemoteHostFilter::checkURL(const Poco::URI & uri, bool throw_on_error) const { - if (checkForDirectEntry(uri.getHost()) || checkForDirectEntry(uri.getHost() + ":" + toString(uri.getPort()))) + const std::string host_and_port = uri.getHost() + ":" + toString(uri.getPort()); + if (checkForDirectEntry(uri.getHost()) || checkForDirectEntry(host_and_port)) return true; if (!throw_on_error) return false; + /// Only the host and port are checked. The rest of the URL can carry secrets and is not printed. throw Exception(ErrorCodes::UNACCEPTABLE_URL, "URL \"{}\" is not allowed in configuration file, " - "see ", uri.toString()); + "see ", host_and_port); } void RemoteHostFilter::checkHostAndPort(const std::string & host, const std::string & port) const diff --git a/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp b/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp index aff81eaa2faa..a97080a7d961 100644 --- a/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp +++ b/src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp @@ -184,8 +184,12 @@ WorkloadEntityStorageBase::OperationResult WorkloadEntityKeeperStorage::storeEnt auto component_guard = Coordination::setCurrentComponent("WorkloadEntityKeeperStorage::storeEntityImpl"); LOG_DEBUG(log, "Storing workload entity {}", backQuote(entity_name)); - String new_data = serializeLocalEntities(Event{entity_type, entity_name, create_entity_query}); + Int32 validated_version = current_version; auto zookeeper = getZooKeeper(); + if (current_version != validated_version) + return OperationResult::Retry; /// A new session has refreshed the entities, so the caller's validation is stale + + String new_data = serializeLocalEntities(Event{entity_type, entity_name, create_entity_query}); Coordination::Stat stat; auto code = zookeeper->trySet(zookeeper_path, new_data, current_version, &stat); @@ -212,8 +216,12 @@ WorkloadEntityStorageBase::OperationResult WorkloadEntityKeeperStorage::removeEn auto component_guard = Coordination::setCurrentComponent("WorkloadEntityKeeperStorage::removeEntityImpl"); LOG_DEBUG(log, "Removing workload entity {}", backQuote(entity_name)); - String new_data = serializeLocalEntities(Event{entity_type, entity_name, {}}); + Int32 validated_version = current_version; auto zookeeper = getZooKeeper(); + if (current_version != validated_version) + return OperationResult::Retry; /// A new session has refreshed the entities, so the caller's validation is stale + + String new_data = serializeLocalEntities(Event{entity_type, entity_name, {}}); Coordination::Stat stat; auto code = zookeeper->trySet(zookeeper_path, new_data, current_version, &stat); diff --git a/src/Common/ThreadPool.cpp b/src/Common/ThreadPool.cpp index 40e24478ffa6..c2c2e8b1cb32 100644 --- a/src/Common/ThreadPool.cpp +++ b/src/Common/ThreadPool.cpp @@ -334,6 +334,7 @@ void ThreadPoolImpl::setMaxThreads(size_t value) /// We have to also adjust queue size, because it limits the number of scheduled and already running jobs in total. queue_size = queue_size ? std::max(queue_size, max_threads) : 0; jobs.reserve(std::min(queue_size, MAX_JOBS_TO_RESERVE)); + slot_freed.notify_all(); if (need_start_threads) { @@ -397,6 +398,8 @@ void ThreadPoolImpl::setQueueSize(size_t value) queue_size = value ? std::max(value, max_threads) : 0; /// Reserve memory to get rid of allocations jobs.reserve(std::min(queue_size, MAX_JOBS_TO_RESERVE)); + /// A larger queue can admit the schedulers waiting for a slot. + slot_freed.notify_all(); } template @@ -427,6 +430,7 @@ ReturnType ThreadPoolImpl::scheduleImpl(Job job, Priority priority, std: ScopedDecrement available_threads_decrement(available_threads); std::unique_ptr new_thread; + std::shared_ptr idle_thread_cv; // Load the current capacity int64_t capacity = remaining_pool_capacity.load(std::memory_order_relaxed); int64_t currently_available_threads = available_threads.load(std::memory_order_relaxed); @@ -467,11 +471,18 @@ ReturnType ThreadPoolImpl::scheduleImpl(Job job, Priority priority, std: /// Wait for available threads or timeout if (wait_microseconds) /// Check for optional. Condition is true if the optional is set. Even if the value is zero. { - if (!job_finished.wait_for(lock, std::chrono::microseconds(*wait_microseconds), pred)) + if (!slot_freed.wait_for(lock, std::chrono::microseconds(*wait_microseconds), pred)) return on_error(fmt::format("no free thread (timeout={})", *wait_microseconds)); } else - job_finished.wait(lock, pred); + slot_freed.wait(lock, pred); + + /// A freed slot wakes only one scheduler, so pass the wakeup on while slots remain free. + /// This covers a scheduler that fails without taking the slot. + SCOPE_EXIT( + if (queue_size && scheduled_jobs < queue_size) + slot_freed.notify_one(); + ); if (finished) return on_error("finished"); @@ -567,14 +578,19 @@ ReturnType ThreadPoolImpl::scheduleImpl(Job job, Priority priority, std: /// avoids a thundering herd where every idle thread wakes, contends for the /// mutex, and goes back to sleep on every job schedule. /// - /// Notify while still holding `mutex`: once `idle_wakeup_flag` is set, a - /// spurious wakeup is enough for the worker to run and remove itself from - /// the pool, so the raw `ThreadFromThreadPool` pointer must not be used - /// after the lock is released. + /// Notify after releasing `mutex`, otherwise the woken thread blocks on it right away. + /// Once `idle_wakeup_flag` is set, a spurious wakeup is enough for the thread to run + /// and remove itself from the pool, so only its CV, not the thread, is used after unlock. if (ThreadFromThreadPool * thread_to_wake = popNewestIdleThreadNoLock()) - wakeIdleThreadNoLock(thread_to_wake); + { + thread_to_wake->idle_wakeup_flag = true; + idle_thread_cv = thread_to_wake->cv; + } } + if (idle_thread_cv) + idle_thread_cv->notify_one(); + ProfileEvents::increment(std::is_same_v ? ProfileEvents::GlobalThreadPoolJobs : ProfileEvents::LocalThreadPoolJobs); return static_cast(true); @@ -669,7 +685,7 @@ void ThreadPoolImpl::wait() /// first worker-loop iteration, or a busy thread that will see the queued /// job when it finishes its current one). Waking all idle threads would /// destroy LIFO ordering — the whole point of this pool design. - job_finished.wait(lock, [this] { return scheduled_jobs == 0; }); + all_jobs_finished.wait(lock, [this] { return scheduled_jobs == 0; }); if (first_exception) { @@ -687,7 +703,7 @@ bool ThreadPoolImpl::waitUntil(std::chrono::steady_clock::time_point dea ProfileEvents::increment( std::is_same_v ? ProfileEvents::GlobalThreadPoolLockWaitMicroseconds : ProfileEvents::LocalThreadPoolLockWaitMicroseconds, watch.elapsedMicroseconds()); - return job_finished.wait_until(lock, deadline, [this] { return scheduled_jobs == 0; }); + return all_jobs_finished.wait_until(lock, deadline, [this] { return scheduled_jobs == 0; }); } template @@ -714,7 +730,7 @@ void ThreadPoolImpl::finishNoLock(const std::lock_guard &) /// Wake up all idle threads so they can see it and exit gracefully. wakeUpAllIdleThreadsNoLock(); - job_finished.notify_all(); + slot_freed.notify_all(); } template @@ -831,7 +847,7 @@ template void ThreadPoolImpl::wakeIdleThreadNoLock(ThreadFromThreadPool * thread) { thread->idle_wakeup_flag = true; - thread->cv.notify_one(); + thread->cv->notify_one(); } template @@ -1025,9 +1041,15 @@ void ThreadPoolImpl::ThreadFromThreadPool::worker() --parent_pool.scheduled_jobs; - parent_pool.job_finished.notify_all(); + if (parent_pool.scheduled_jobs == 0) + parent_pool.all_jobs_finished.notify_all(); if (parent_pool.finished) + { + parent_pool.slot_freed.notify_all(); parent_pool.wakeUpAllIdleThreadsNoLock(); /// `finished` was set, wake up other threads so they can finish themselves. + } + else + parent_pool.slot_freed.notify_one(); } /// LIFO idle thread scheduling: link this thread into the intrusive @@ -1058,7 +1080,7 @@ void ThreadPoolImpl::ThreadFromThreadPool::worker() { idle_wakeup_flag = false; parent_pool.pushIdleThreadNoLock(this); - cv.wait(lock, [this] + cv->wait(lock, [this] { return idle_wakeup_flag || !parent_pool.jobs.empty() diff --git a/src/Common/ThreadPool.h b/src/Common/ThreadPool.h index 502f2430fc66..fb8bb9340efd 100644 --- a/src/Common/ThreadPool.h +++ b/src/Common/ThreadPool.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -92,7 +93,9 @@ class ThreadPoolImpl /// Each idle thread waits on its own CV, so the scheduler can wake the /// LIFO-selected thread directly without disturbing other idle threads. /// This avoids the thundering herd that a shared CV with `notify_all` creates. - std::condition_variable cv; + /// Shared, so that `scheduleImpl` can notify it after releasing the pool mutex, + /// when the thread may already have left the pool. + std::shared_ptr cv = std::make_shared(); /// LIFO idle thread scheduling flag. /// When a new job is scheduled, the most recently idle thread is popped @@ -201,7 +204,9 @@ class ThreadPoolImpl friend class GlobalThreadPool; mutable std::mutex mutex; - std::condition_variable job_finished; + /// A finished job frees one slot, so it wakes only one scheduler waiting for a slot. + std::condition_variable slot_freed; + std::condition_variable all_jobs_finished; Metric metric_threads; Metric metric_active_threads; diff --git a/src/Common/getNumberOfCPUCoresToUse.cpp b/src/Common/getNumberOfCPUCoresToUse.cpp index cd87fca568ba..9092b995c8a2 100644 --- a/src/Common/getNumberOfCPUCoresToUse.cpp +++ b/src/Common/getNumberOfCPUCoresToUse.cpp @@ -13,8 +13,42 @@ #include #include #include +#include +#include #include +#if defined(OS_LINUX) +std::optional countCPUsInList(const std::string & cpu_list) +{ + if (cpu_list.empty()) + return std::nullopt; + + auto parse = [](const std::string & text, int & value) + { + return std::from_chars(text.data(), text.data() + text.size(), value).ec == std::errc{}; + }; + + std::vector cpu_ranges; + boost::split(cpu_ranges, cpu_list, boost::is_any_of(",")); + uint32_t cpus_count = 0; + for (const std::string & cpu_number_or_range : cpu_ranges) + { + std::vector cpu_range; + boost::split(cpu_range, cpu_number_or_range, boost::is_any_of("-")); + + int start = 0; + int end = 0; + if (cpu_range.size() == 1 && parse(cpu_range[0], start)) + end = start; + else if (cpu_range.size() != 2 || !parse(cpu_range[0], start) || !parse(cpu_range[1], end) || end < start) + return std::nullopt; + + cpus_count += static_cast(end - start) + 1; + } + return cpus_count; +} +#endif + namespace { diff --git a/src/Common/getNumberOfCPUCoresToUse.h b/src/Common/getNumberOfCPUCoresToUse.h index e17400328583..08a5635c279b 100644 --- a/src/Common/getNumberOfCPUCoresToUse.h +++ b/src/Common/getNumberOfCPUCoresToUse.h @@ -1,6 +1,14 @@ #pragma once +#include +#include +#include + /// Get the number of CPU cores to use. Depending on the machine size we choose /// between the number of physical and logical cores. /// Also under cgroups we respect possible cgroups limits. unsigned getNumberOfCPUCoresToUse(); + +/// Parse a kernel cpu-list such as "0-15" or "0,2-4,7" (the format of /sys/devices/system/cpu/* and +/// cgroup cpuset files) and return the number of CPUs in it, or nullopt if the text is not a cpu-list. +std::optional countCPUsInList(const std::string & cpu_list); diff --git a/src/Common/maskURIPassword.h b/src/Common/maskURIPassword.h index 81559987db59..bb12e94c48c2 100644 --- a/src/Common/maskURIPassword.h +++ b/src/Common/maskURIPassword.h @@ -159,10 +159,11 @@ inline bool maskURIUserinfo(std::string & url) } /** Mask the values of the query parameters that carry credentials in a presigned URL, so that - * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`. Every occurrence - * is masked. Returns whether anything was masked. + * `...?X-Amz-Signature=abc&foo=1` becomes `...?X-Amz-Signature=[HIDDEN]&foo=1`, and of the + * `connection_string` parameter of an ODBC/JDBC bridge request. Every occurrence is masked. + * Returns whether anything was masked. * - * This used to be the regular expression + * Apart from `connection_string`, this used to be the regular expression * `([?&](?:AWSAccessKeyId|Signature|Expires|GoogleAccessId|X-Amz-[A-Za-z0-9\-]*|X-Goog-[A-Za-z0-9\-]*)=)[^&#]*` * rewritten to `\1[HIDDEN]` globally. The parameter set mirrors * `BackupInfo::removeCredentialsFromS3URL`. Matching is case-sensitive, as in the expression, and @@ -175,6 +176,9 @@ inline bool maskPresignedURLParameters(std::string & url) auto is_secret_parameter = [](std::string_view name) { + if (name == "connection_string") + return true; + for (auto exact : exact_names) if (name == exact) return true; diff --git a/src/Common/mysqlxx/Connection.cpp b/src/Common/mysqlxx/Connection.cpp index 281f8f33c9be..e54f286ab7b1 100644 --- a/src/Common/mysqlxx/Connection.cpp +++ b/src/Common/mysqlxx/Connection.cpp @@ -112,6 +112,12 @@ void Connection::connect(const char* db, if (mysql_options(driver.get(), MYSQL_OPT_RECONNECT, reinterpret_cast(&opt_reconnect))) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Generated queries escape string literals with backslashes, so `NO_BACKSLASH_ESCAPES` must be off: with it, a quote + /// escaped as `\'` ends the literal. The library runs this command on every connect, including automatic reconnects. + if (mysql_options(driver.get(), MYSQL_INIT_COMMAND, + "SET sql_mode = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', @@sql_mode, ','), ',NO_BACKSLASH_ESCAPES,', ','))")) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// Enable classic MySQL protocol compression if requested. if (enable_compression && mysql_options(driver.get(), MYSQL_OPT_COMPRESS, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); @@ -120,6 +126,15 @@ void Connection::connect(const char* db, if (mysql_ssl_set(driver.get(), ifNotEmpty(ssl_key), ifNotEmpty(ssl_cert), ifNotEmpty(ssl_ca), nullptr, nullptr)) throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + /// With a CA the server certificate is verified anyway. This also makes the library refuse a server that does not + /// offer TLS before it sends the credentials, instead of going on without TLS. + if (ifNotEmpty(ssl_ca)) + { + my_bool verify_server_cert = 1; + if (mysql_options(driver.get(), MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &verify_server_cert)) + throw ConnectionFailed(errorMessage(driver.get()), mysql_errno(driver.get())); + } + /// Without an explicit socket, use TCP to the given port: otherwise `localhost` goes to the library's default socket. if (!ifNotEmpty(socket)) { diff --git a/src/Common/mysqlxx/Query.cpp b/src/Common/mysqlxx/Query.cpp index babfc8c7c41d..1079c9c7789c 100644 --- a/src/Common/mysqlxx/Query.cpp +++ b/src/Common/mysqlxx/Query.cpp @@ -52,6 +52,10 @@ void Query::executeImpl() { MYSQL* mysql_driver = conn->getDriver(); + /// See `Connection::connect`: the session reports `NO_BACKSLASH_ESCAPES` if something turned it on again. + if (mysql_driver->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES) + throw Exception("The MySQL session has NO_BACKSLASH_ESCAPES in sql_mode, which is not supported"); + LOG_TRACE(getLogger("mysqlxx::Query"), "Running MySQL query using connection {}", mysql_thread_id(mysql_driver)); if (mysql_real_query(mysql_driver, query.data(), query.size())) { diff --git a/src/Common/tests/gtest_thread_pool_lifo.cpp b/src/Common/tests/gtest_thread_pool_lifo.cpp index 268ed6df1da2..5a66d136a1cb 100644 --- a/src/Common/tests/gtest_thread_pool_lifo.cpp +++ b/src/Common/tests/gtest_thread_pool_lifo.cpp @@ -160,7 +160,7 @@ TEST(ThreadPool, LIFOSchedulesOnMostRecentlyIdleThread) /// `pool.wait` returns only after the worker that completed the last job /// has pushed itself onto the idle stack: the worker holds `pool.mutex` - /// continuously from notifying `job_finished` through the idle push, and + /// continuously from notifying `all_jobs_finished` through the idle push, and /// `pool.wait` reacquires that mutex before returning. So once `pool.wait` /// returns, both workers are parked in the idle stack. pool.wait(); diff --git a/src/Common/tests/gtest_thread_pool_many_schedulers.cpp b/src/Common/tests/gtest_thread_pool_many_schedulers.cpp new file mode 100644 index 000000000000..0cc3fbcc2e3d --- /dev/null +++ b/src/Common/tests/gtest_thread_pool_many_schedulers.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +#include +#include + +#include + +namespace CurrentMetrics +{ + extern const Metric LocalThread; + extern const Metric LocalThreadActive; + extern const Metric LocalThreadScheduled; +} + +/// Many threads wait in `scheduleImpl` for a slot of a full pool, and a finished job wakes only one of them. +/// Every job must still be scheduled and run. +TEST(ThreadPool, ManySchedulersOnFullPool) +{ + constexpr size_t num_schedulers = 32; + constexpr size_t jobs_per_scheduler = 1000; + + ThreadPool pool(CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, CurrentMetrics::LocalThreadScheduled, + /* max_threads */ 2, /* max_free_threads */ 0, /* queue_size */ 2); + + /// The global pool is created lazily without synchronization, so create it before the schedulers start threads in it. + GlobalThreadPool::instance(); + + std::atomic counter = 0; + std::vector schedulers; + for (size_t i = 0; i < num_schedulers; ++i) + { + schedulers.emplace_back([&] + { + for (size_t j = 0; j < jobs_per_scheduler; ++j) + pool.scheduleOrThrowOnError([&] { ++counter; }); + }); + } + + for (auto & scheduler : schedulers) + scheduler.join(); + pool.wait(); + + EXPECT_EQ(counter, num_schedulers * jobs_per_scheduler); +} diff --git a/src/Compression/CachedCompressedReadBuffer.cpp b/src/Compression/CachedCompressedReadBuffer.cpp index e2f6b87b43f8..7b15fd9117eb 100644 --- a/src/Compression/CachedCompressedReadBuffer.cpp +++ b/src/Compression/CachedCompressedReadBuffer.cpp @@ -30,6 +30,10 @@ void CachedCompressedReadBuffer::initInput() void CachedCompressedReadBuffer::prefetch(Priority priority) { + /// The next block is served from the cache without touching the file, see `nextImpl`. + if (cache->contains(UncompressedCache::hash(path, file_pos))) + return; + initInput(); file_in->prefetch(priority); } diff --git a/src/Core/BaseSettings.cpp b/src/Core/BaseSettings.cpp index 01c77b06e63d..cf09441e91a7 100644 --- a/src/Core/BaseSettings.cpp +++ b/src/Core/BaseSettings.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -127,6 +128,15 @@ void BaseSettingsHelpers::warningSettingNotFound(std::string_view name) } } +bool BaseSettingsHelpers::skipInvalidSettingValue(std::string_view name, const Exception & e) +{ + if (e.code() != ErrorCodes::BAD_ARGUMENTS && !isParseError(e.code())) + return false; + + LOG_WARNING(getLogger("Settings"), "Cannot parse the value of setting `{}`, skipping it: {}", name, e.message()); + return true; +} + void BaseSettingsHelpers::flushWarnings() { unknown_settings.clear(); diff --git a/src/Core/BaseSettings.h b/src/Core/BaseSettings.h index c3028b8eb6d1..929d1bdccb3b 100644 --- a/src/Core/BaseSettings.h +++ b/src/Core/BaseSettings.h @@ -60,6 +60,8 @@ struct BaseSettingsHelpers [[noreturn]] static void throwValuelessSettingIsNotBool(std::string_view name); [[noreturn]] static void throwValuelessSettingHasValue(std::string_view name); static void warningSettingNotFound(std::string_view name); + /// Returns true (and logs a warning) if `e` is `BAD_ARGUMENTS` or a parse error (`isParseError`); other errors are not skipped. + static bool skipInvalidSettingValue(std::string_view name, const Exception & e); static void flushWarnings(); /// Serialization helpers @@ -306,8 +308,9 @@ class BaseSettings : public TTraits::Data /// Write all settings (or only changed ones depending on format) void write(WriteBuffer & out, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT) const; - /// Read settings from a buffer - void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT); + /// Read settings from a buffer. + /// With `skip_invalid_values`, a non-important setting whose value is rejected keeps its default instead of failing the read. + void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT, bool skip_invalid_values = false); /// Write only changed settings in binary format void writeChangedBinary(WriteBuffer & out) const; @@ -773,7 +776,7 @@ void BaseSettings::readBinary(ReadBuffer & in) } template -void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format) +void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format, bool skip_invalid_values) { resetToDefault(); const auto & accessor = Traits::Accessor::instance(); @@ -810,7 +813,20 @@ void BaseSettings::read(ReadBuffer & in, SettingsWriteFormat format) accessor.setValue(*this, index, static_cast(temp)); } else if (format >= SettingsWriteFormat::STRINGS_WITH_FLAGS) - accessor.setValueString(*this, index, BaseSettingsHelpers::readString(in)); + { + String value = BaseSettingsHelpers::readString(in); + try + { + accessor.setValueString(*this, index, value); + } + catch (const Exception & e) + { + if (!skip_invalid_values || is_important || !BaseSettingsHelpers::skipInvalidSettingValue(name, e)) + throw; + /// A failed parse may have assigned the field already. + accessor.resetValueToDefault(*this, index); + } + } else accessor.readBinary(*this, index, in); } diff --git a/src/Core/Block.cpp b/src/Core/Block.cpp index 78ca84e6bb16..ac629ef763f4 100644 --- a/src/Core/Block.cpp +++ b/src/Core/Block.cpp @@ -993,6 +993,27 @@ bool blocksHaveEqualStructure(const Block & lhs, const Block & rhs) } +bool blocksHaveIdenticalStructure(const Block & lhs, const Block & rhs) +{ + size_t columns = lhs.columns(); + if (rhs.columns() != columns) + return false; + + for (size_t i = 0; i < columns; ++i) + { + const auto & left = lhs.getByPosition(i); + const auto & right = rhs.getByPosition(i); + + if (left.name != right.name + || !left.type || !right.type || !left.type->equals(*right.type) + || !left.column || !right.column || !left.column->structureEquals(*right.column)) + return false; + } + + return true; +} + + void assertBlocksHaveEqualStructure(const Block & lhs, const Block & rhs, std::string_view context_description) { checkBlockStructure(lhs, rhs, context_description, false); diff --git a/src/Core/Block.h b/src/Core/Block.h index 8c98ef05694d..e34d34924bcd 100644 --- a/src/Core/Block.h +++ b/src/Core/Block.h @@ -205,6 +205,13 @@ void assertBlocksHaveEqualStructure(const Block & lhs, const Block & rhs, std::s void assertBlocksHaveEqualStructureAllowReplicated(const Block & lhs, const Block & rhs, std::string_view context_description); +/// Compare the number, the names and the types of the columns, and the columns themselves with `IColumn::structureEquals`, +/// so, unlike for `blocksHaveEqualStructure`, a column in a special representation (e.g. sparse) differs from an +/// ordinary column of the same type. It is the check for a block from an untrusted source (e.g. another server) +/// before its columns are appended to the columns of another block or cast to their classes. +/// Both blocks must have the columns. +bool blocksHaveIdenticalStructure(const Block & lhs, const Block & rhs); + /// Actual header is compatible to desired if block have equal structure except constants. /// It is allowed when column from actual header is constant, but in desired is not. /// If both columns are constant, it is checked that they have the same value. diff --git a/src/Core/Field.cpp b/src/Core/Field.cpp index 6e3de2b8dbe5..bdb48c55848b 100644 --- a/src/Core/Field.cpp +++ b/src/Core/Field.cpp @@ -632,29 +632,40 @@ void writeText(const CustomType & x, WriteBuffer & buf) template void readQuoted(DecimalField & x, ReadBuffer & buf) { - assertChar('\'', buf); + String text; + readQuotedString(text, buf); + ReadBufferFromString in(text); T value{}; - UInt32 scale = 0; int32_t exponent = 0; uint32_t max_digits = static_cast(-1); - readDigits(buf, value, max_digits, exponent, true); - if (exponent > 0) + bool has_digits = false; + if (!text.empty()) + readDigits(in, value, max_digits, exponent, true, &has_digits); + if (!has_digits || !in.eof()) + throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot parse decimal dump '{}'", text); + + /// `readDigits` drops trailing fractional zeroes, but the dump writes them to keep the scale. + size_t mantissa_end = std::min(text.find_first_of("eE"), text.size()); + uint32_t trailing_zeroes = 0; + if (text.find('.') < mantissa_end) + while (text[mantissa_end - 1 - trailing_zeroes] == '0') + ++trailing_zeroes; + if (!mulPow10AddChecked(value.value, trailing_zeroes, typename T::NativeType(0))) + throw Exception(ErrorCodes::DECIMAL_OVERFLOW, "Decimal math overflow"); + + /// An out-of-range scale overruns the decimal text writer. + Int64 total_exponent = static_cast(exponent) - trailing_zeroes; + UInt32 scale = 0; + if (total_exponent > 0) { - scale = 0; - if (common::mulOverflow(value.value, DecimalUtils::scaleMultiplier(exponent), value.value)) + if (!mulPow10AddChecked(value.value, static_cast(std::min(total_exponent, UINT32_MAX)), typename T::NativeType(0))) throw Exception(ErrorCodes::DECIMAL_OVERFLOW, "Decimal math overflow"); } - else - scale = -exponent; - /// The scale comes from untrusted text: `restoreFromDump` is reached from the pre-auth native - /// settings reader for a `CUSTOM`-flagged setting (`SettingFieldCustom::parseFromString`), and an - /// exponent-form value such as `Decimal64_'1e-1000'` builds a scale that bypasses the binary - /// reader's check. An out-of-range scale later overruns a fixed-size buffer in the decimal text - /// writer, so reject it here, matching `readDecimalFieldBinary` and `DataTypeDecimalBase`. - if (scale > DecimalUtils::max_precision) + else if (-total_exponent > static_cast(DecimalUtils::max_precision)) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Scale {} is out of bounds (max scale: {})", - scale, DecimalUtils::max_precision); - assertChar('\'', buf); + -total_exponent, DecimalUtils::max_precision); + else + scale = static_cast(-total_exponent); x = DecimalField{value, scale}; } diff --git a/src/Core/ServerSettings.cpp b/src/Core/ServerSettings.cpp index 8aeef728f2cb..1758fd476bc6 100644 --- a/src/Core/ServerSettings.cpp +++ b/src/Core/ServerSettings.cpp @@ -120,6 +120,13 @@ namespace #define LIST_OF_SERVER_SETTINGS_WITHOUT_PATH(DECLARE, ALIAS) \ DECLARE(String, insert_deduplication_version, "new_unified_hash", R"(Deprecated migration guard. This version supports only the unified insert deduplication hash (`new_unified_hash`); the server refuses to start if this setting is present with any other value (such as `old_separate_hashes` or `compatible_double_hashes`). Complete the deduplication migration on the previous version before upgrading by running `compatible_double_hashes` (which writes both the legacy and unified hashes). For replicated tables run it for at least `replicated_deduplication_window_seconds` (one hour by default); the default windows retain the unified hashes of all inserts for that window, which is considered enough to cover an insert retry loop. For non-replicated tables with `non_replicated_deduplication_window` > 0 the window is count-based rather than time-based, so run `compatible_double_hashes` for at least that many inserts before upgrading.)", 0) \ DECLARE(UInt64, dictionary_background_reconnect_interval, 1000, "Interval in milliseconds for reconnection attempts of failed MySQL and Postgres dictionaries having `background_reconnect` enabled.", 0) \ + DECLARE(Bool, dictionaries_external_source_queries_select_only, true, R"( +Check that the queries a MySQL, PostgreSQL or ODBC source of a dictionary created by `CREATE DICTIONARY` sends to the database (the load query, the update query and `invalidate_query`) are `SELECT` queries. + +The database receives the queries with the credentials of the source, which can come from a named collection, and the dictionary is loaded with the global context. So without the check, the author of the dictionary can run any statement in the database with these credentials. + +The queries are checked with the ClickHouse parser, so a valid query that the ClickHouse parser does not accept, or that contains comments, heredocs, typographic quotes, backslashes in quoted tokens, `INTO OUTFILE`, `FORMAT` or `SETTINGS`, is rejected too. Disable the setting to load such dictionaries as before, without the check and without its protection. Dictionaries from the server configuration are not checked. +)", 0) \ DECLARE(Bool, show_addresses_in_stack_traces, true, R"(If it is set true will show addresses in stack traces)", 0) \ DECLARE(Bool, shutdown_wait_unfinished_queries, false, R"(If set true ClickHouse will wait for running queries finish before shutdown.)", 0) \ DECLARE(UInt64, shutdown_wait_unfinished, 120, R"(Delay in seconds to wait for unfinished queries)", 0) \ @@ -512,38 +519,9 @@ A value of `0` means all cores. The delay during which a dropped table can be restored using the [`UNDROP`](/reference/statements/undrop) statement. If `DROP TABLE` ran with a `SYNC` modifier, the setting is ignored. The default for this setting is `480` (8 minutes). )", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_hide_timeout_sec, 60 * 60, R"( -Parameter of a task that cleans up garbage from `store/` directory. -If some subdirectory is not used by clickhouse-server and this directory was not modified for last -[`database_catalog_unused_dir_hide_timeout_sec`](/reference/settings/server-settings/settings/database-catalog#database_catalog_unused_dir_hide_timeout_sec) seconds, the task will "hide" this directory by -removing all access rights. It also works for directories that clickhouse-server does not -expect to see inside `store/`. - -:::note -A value of `0` means "immediately". -::: -)", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_rm_timeout_sec, 30 * 24 * 60 * 60, R"( -Parameter of a task that cleans up garbage from `store/` directory. -If some subdirectory is not used by clickhouse-server and it was previously "hidden" -(see [database_catalog_unused_dir_hide_timeout_sec](/reference/settings/server-settings/settings/database-catalog#database_catalog_unused_dir_hide_timeout_sec)) -and this directory was not modified for last -[`database_catalog_unused_dir_rm_timeout_sec`](/reference/settings/server-settings/settings/database-catalog#database_catalog_unused_dir_rm_timeout_sec) seconds, the task will remove this directory. -It also works for directories that clickhouse-server does not -expect to see inside `store/`. - -:::note -A value of `0` means "never". The default value corresponds to 30 days. -::: -)", 0) \ - DECLARE(UInt64, database_catalog_unused_dir_cleanup_period_sec, 24 * 60 * 60, R"( -Parameter of a task that cleans up garbage from `store/` directory. -Sets scheduling period of the task. - -:::note -A value of `0` means "never". The default value corresponds to 1 day. -::: -)", 0) \ + DECLARE(UInt64, database_catalog_unused_dir_hide_timeout_sec, 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the time after which the task revoked all access rights from an unused directory. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, database_catalog_unused_dir_rm_timeout_sec, 30 * 24 * 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the time after which the task removed an unused directory. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ + DECLARE(UInt64, database_catalog_unused_dir_cleanup_period_sec, 24 * 60 * 60, R"(Parameter of the background task that cleaned up garbage from the `store/` directory: the scheduling period of the task. The setting is deprecated and has no effect: the task was removed, and ClickHouse never hides or removes unused directories in `store/` automatically.)", SettingsTierType::OBSOLETE) \ DECLARE(UInt64, database_catalog_drop_error_cooldown_sec, 5, R"(In case of a failed table drop, ClickHouse will wait for this time-out before retrying the operation.)", 0) \ DECLARE(UInt64, database_catalog_drop_table_concurrency, 16, R"(The size of the threadpool used for dropping tables.)", 0) \ \ @@ -1345,7 +1323,7 @@ The threshold ratio for purging jemalloc relative to the memory available to Cli Duration in milliseconds that memory pressure must persist before dynamically adjusting jemalloc's `dirty_decay_ms`. When memory usage remains above the purge threshold for this period, automatic dirty page decay is disabled (`dirty_decay_ms=0`) to aggressively reclaim memory. When usage stays below the threshold for this period, the default decay behavior is restored. Set to 0 to disable dynamic adjustment and use jemalloc's default decay settings. )", 0) \ DECLARE(Bool, memory_worker_correct_memory_tracker, 0, R"( -Whether background memory worker should correct internal memory tracker based on the information from external sources like jemalloc and cgroups +Whether background memory worker should correct internal memory tracker based on the information from external sources like jemalloc and cgroups. The tracker is set to the maximum of this measurement and jemalloc's `stats.allocated`, so that memory which is allocated but not touched yet, and therefore not resident, stays accounted, and concurrent queries cannot be admitted past `max_server_memory_usage` before their pages are touched. )", 0) \ DECLARE(Bool, memory_worker_use_cgroup, true, "Use current cgroup memory usage information to correct memory tracking.", 0) \ DECLARE(Double, memory_worker_rss_speculative_reserve_ratio, getDefaultMemoryWorkerRssSpeculativeReserveRatio(), R"( @@ -3528,6 +3506,10 @@ ChangeableSettingsMap collectChangeableServerSettings(ContextPtr context) { using ChangeableWithoutRestart = ServerSettings::ChangeableWithoutRestart; + /// A process may lack a cache, e.g. `clickhouse-client` evaluating `getServerSetting` in `INSERT ... VALUES`. + auto cache_max_size = [](const auto & cache) { return std::to_string(cache ? cache->maxSizeInBytes() : 0); }; + const auto query_result_cache = context->getQueryResultCache(); + ChangeableSettingsMap changeable_settings = { {"max_server_memory_usage", {std::to_string(total_memory_tracker.getHardLimit()), ChangeableWithoutRestart::Yes}}, @@ -3586,19 +3568,19 @@ ChangeableSettingsMap collectChangeableServerSettings(ContextPtr context) {"background_streaming_schedule_pool_size", {std::to_string(CurrentMetrics::get(CurrentMetrics::BackgroundStreamingSchedulePoolSize)), ChangeableWithoutRestart::IncreaseOnly}}, - {"mark_cache_size", {std::to_string(context->getMarkCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"uncompressed_cache_size", {std::to_string(context->getUncompressedCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"index_mark_cache_size", {std::to_string(context->getIndexMarkCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"index_uncompressed_cache_size", {std::to_string(context->getIndexUncompressedCache(/*only_if_enabled=*/ false)->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"mmap_cache_size", {std::to_string(context->getMMappedFileCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"query_condition_cache_size", {std::to_string(context->getQueryConditionCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"encryption_header_cache_size", {std::to_string(context->getEncryptionHeaderCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"primary_index_cache_size", {std::to_string(context->getPrimaryIndexCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"vector_similarity_index_cache_size", {std::to_string(context->getVectorSimilarityIndexCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"text_index_tokens_cache_size", {std::to_string(context->getTextIndexTokensCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"text_index_header_cache_size", {std::to_string(context->getTextIndexHeaderCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"text_index_postings_cache_size", {std::to_string(context->getTextIndexPostingsCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, - {"query_cache_max_size_in_bytes", {std::to_string(context->getQueryResultCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}, + {"mark_cache_size", {cache_max_size(context->getMarkCache()), ChangeableWithoutRestart::Yes}}, + {"uncompressed_cache_size", {cache_max_size(context->getUncompressedCache()), ChangeableWithoutRestart::Yes}}, + {"index_mark_cache_size", {cache_max_size(context->getIndexMarkCache()), ChangeableWithoutRestart::Yes}}, + {"index_uncompressed_cache_size", {cache_max_size(context->getIndexUncompressedCache(/*only_if_enabled=*/ false)), ChangeableWithoutRestart::Yes}}, + {"mmap_cache_size", {cache_max_size(context->getMMappedFileCache()), ChangeableWithoutRestart::Yes}}, + {"query_condition_cache_size", {cache_max_size(context->getQueryConditionCache()), ChangeableWithoutRestart::Yes}}, + {"encryption_header_cache_size", {cache_max_size(context->getEncryptionHeaderCache()), ChangeableWithoutRestart::Yes}}, + {"primary_index_cache_size", {cache_max_size(context->getPrimaryIndexCache()), ChangeableWithoutRestart::Yes}}, + {"vector_similarity_index_cache_size", {cache_max_size(context->getVectorSimilarityIndexCache()), ChangeableWithoutRestart::Yes}}, + {"text_index_tokens_cache_size", {cache_max_size(context->getTextIndexTokensCache()), ChangeableWithoutRestart::Yes}}, + {"text_index_header_cache_size", {cache_max_size(context->getTextIndexHeaderCache()), ChangeableWithoutRestart::Yes}}, + {"text_index_postings_cache_size", {cache_max_size(context->getTextIndexPostingsCache()), ChangeableWithoutRestart::Yes}}, + {"query_cache_max_size_in_bytes", {cache_max_size(query_result_cache), ChangeableWithoutRestart::Yes}}, {"point_in_polygon_cache_size", {std::to_string(CurrentMetrics::get(CurrentMetrics::PointInPolygonCacheSizeLimit)), ChangeableWithoutRestart::Yes}}, {"unique_key_bitmap_cache_size_bytes", {std::to_string(context->getDeleteBitmapCache() ? context->getDeleteBitmapCache()->maxSizeInBytes() : 0), ChangeableWithoutRestart::Yes}}, @@ -3737,10 +3719,10 @@ ChangeableSettingsMap collectChangeableServerSettings(ContextPtr context) } #endif #if USE_PARQUET - if (context->getParquetMetadataCache()) + if (const auto parquet_metadata_cache = context->tryGetParquetMetadataCache()) changeable_settings.insert( {"parquet_metadata_cache_size", - {std::to_string(context->getParquetMetadataCache()->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}); + {std::to_string(parquet_metadata_cache->maxSizeInBytes()), ChangeableWithoutRestart::Yes}}); #endif /// `keeper_hosts` is not a regular config setting; it is derived from the `` config and follows diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp index 5f562acb7198..65855638b06a 100644 --- a/src/Core/Settings.cpp +++ b/src/Core/Settings.cpp @@ -7259,6 +7259,9 @@ Timeout for polling data from asynchronous insert queue )", 0) \ DECLARE(Bool, async_insert_use_adaptive_busy_timeout, true, R"( If it is set to true, use adaptive busy timeout for asynchronous inserts +)", 0) \ + DECLARE(Bool, async_insert_use_deduplication_cache, true, R"( +If true, an asynchronous insert into a table first checks the deduplication hashes of the inserted block against the in-memory cache of the hashes stored in ClickHouse Keeper. The cache of a replica can be stale after `TRUNCATE` or a partition drop on another replica, so the block can be wrongly treated as a duplicate and not inserted. If false, the cache is not used and duplicates are detected only by ClickHouse Keeper. )", 0) \ DECLARE(Milliseconds, async_insert_busy_timeout_min_ms, 50, R"( If auto-adjusting is enabled through async_insert_use_adaptive_busy_timeout, minimum time to wait before dumping collected data per query since the first data appeared. It also serves as the initial value for the adaptive algorithm @@ -8824,7 +8827,7 @@ Initial delay in milliseconds before the first retry of a failed AI function API If true (default), an AI function call that fails permanently after exhausting all retries aborts the query with an exception. If false, the failed row receives the default value for the column type (empty string for String) and processing continues. )", BETA) \ DECLARE(UInt64, ai_function_max_input_tokens_per_query, 0, R"( -Maximum total input (prompt) tokens across all AI function API calls in a single query. 0 (default) disables the limit. Tracked cumulatively from provider responses. Note that this limit may be exceeded by up to one call's worth of input tokens per in-flight request, since a call's input tokens are not known until its response arrives. Like the other AI quotas, it is enforced per server / query fragment, not summed across a distributed query, and must be set in the top-level query - a sub-query `SETTINGS` override is ignored. +Maximum total input (prompt) tokens across all AI function API calls in a single query including cache reads and writes. 0 (default) disables the limit. Tracked cumulatively from provider responses. Note that this limit may be exceeded by up to one call's worth of input tokens per in-flight request, since a call's input tokens are not known until its response arrives. Like the other AI quotas, it is enforced per server / query fragment, not summed across a distributed query, and must be set in the top-level query - a sub-query `SETTINGS` override is ignored. This limit is only enforced for providers that report a `usage` object in their response (OpenAI, Anthropic, vLLM). Providers that omit token usage (notably HuggingFace TEI) cause the counter to stay at 0 — use `ai_function_max_api_calls_per_query` instead to bound such calls. )", BETA) \ @@ -10031,9 +10034,9 @@ void Settings::write(WriteBuffer & out, SettingsWriteFormat format) const impl->write(out, format); } -void Settings::read(ReadBuffer & in, SettingsWriteFormat format) +void Settings::read(ReadBuffer & in, SettingsWriteFormat format, bool skip_invalid_values) { - impl->read(in, format); + impl->read(in, format, skip_invalid_values); } void Settings::writeEmpty(WriteBuffer & out) diff --git a/src/Core/Settings.h b/src/Core/Settings.h index 18f53168d541..976087c926b3 100644 --- a/src/Core/Settings.h +++ b/src/Core/Settings.h @@ -192,7 +192,7 @@ struct Settings std::map changedToMap(bool show_secrets) const; void write(WriteBuffer & out, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT) const; - void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT); + void read(ReadBuffer & in, SettingsWriteFormat format = SettingsWriteFormat::DEFAULT, bool skip_invalid_values = false); /// Equivalent to Settings().write(out, ) but faster. static void writeEmpty(WriteBuffer & out); diff --git a/src/Core/SettingsChangesHistory.cpp b/src/Core/SettingsChangesHistory.cpp index 194abc3ffd6c..42824064429d 100644 --- a/src/Core/SettingsChangesHistory.cpp +++ b/src/Core/SettingsChangesHistory.cpp @@ -47,6 +47,7 @@ const VersionToSettingsChangesMap & getSettingsChangesHistory() }); addSettingsChanges(settings_changes_history, "26.8", { + {"async_insert_use_deduplication_cache", true, true, "New setting to disable the deduplication cache for asynchronous inserts."}, {"json_extract_use_cast_string_to_date_time_mode", false, true, "`JSONExtract` parses `DateTime` values according to `cast_string_to_date_time_mode` instead of `date_time_input_format`. `compatibility` with versions before 26.8 restores the previous behavior."}, {"backup_s3_expired_token_retry_timeout_ms", 0, 120000, "Retry S3 backup and restore requests after an expired token; 0 restores the previous behavior."}, {"allow_named_collection_override_by_default", true, true, "Obsolete. Overriding named collection keys requires `SHOW NAMED COLLECTIONS SECRETS`."}, diff --git a/src/Core/tests/gtest_field.cpp b/src/Core/tests/gtest_field.cpp index 68bfc3db544e..0f764a311fa8 100644 --- a/src/Core/tests/gtest_field.cpp +++ b/src/Core/tests/gtest_field.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -10,6 +11,8 @@ namespace DB::ErrorCodes { extern const int TOO_DEEP_RECURSION; extern const int ARGUMENT_OUT_OF_BOUND; + extern const int CANNOT_PARSE_NUMBER; + extern const int DECIMAL_OVERFLOW; } using namespace DB; @@ -321,3 +324,76 @@ GTEST_TEST(Field, RestoreFromDumpDecimalOutOfRangeScaleThrows) Field restored = Field::restoreFromDump("Decimal64_'1e-5'"); ASSERT_EQ(restored.safeGet>().getScale(), 5u); } + +static void expectRestoreFromDumpError(const std::string & dump, int code) +{ + try + { + Field::restoreFromDump(dump); + FAIL() << "expected error " << code << " for " << dump; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), code) << dump; + } +} + +GTEST_TEST(Field, RestoreFromDumpDecimalExtremeExponent) +{ + /// Negating `INT32_MIN` must not be reached. + expectRestoreFromDumpError("Decimal64_'1e-2147483648'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + /// The exponent sum overflows `int32_t` (only digits after the point decrease it). + expectRestoreFromDumpError("Decimal64_'0.1e-2147483648'", ErrorCodes::CANNOT_PARSE_NUMBER); + /// `scaleMultiplier` saturates beyond the precision, so `1 * max` must not be accepted as the value. + expectRestoreFromDumpError("Decimal64_'1e100'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal32_'1e2147483647'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'1e100'", ErrorCodes::DECIMAL_OVERFLOW); + /// No digits at all. + expectRestoreFromDumpError("Decimal64_'.'", ErrorCodes::CANNOT_PARSE_NUMBER); + expectRestoreFromDumpError("Decimal64_'-'", ErrorCodes::CANNOT_PARSE_NUMBER); + expectRestoreFromDumpError("Decimal64_''", ErrorCodes::CANNOT_PARSE_NUMBER); + + /// The largest exponents that fit still work, and zero takes any positive exponent. + ASSERT_EQ(Field::restoreFromDump("Decimal64_'1e18'").safeGet>().getValue(), Decimal64(1000000000000000000LL)); + ASSERT_EQ(Field::restoreFromDump("Decimal64_'1e-18'").safeGet>().getScale(), 18u); + ASSERT_EQ(Field::restoreFromDump("Decimal64_'0e2147483647'").safeGet>().getValue(), Decimal64(0)); +} + +GTEST_TEST(Field, RestoreFromDumpDecimalMantissaOverflow) +{ + /// A mantissa that does not fit the native integer must not wrap (here to zero, skipping the exponent check). + expectRestoreFromDumpError("Decimal32_'4294967296e2147483647'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal64_'18446744073709551616e2147483647'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal32_'2147483648'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal128_'170141183460469231731687303715884105728'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + expectRestoreFromDumpError("Decimal256_'-57896044618658097711785492504343953926634992332820282019728792003956564819969'", ErrorCodes::ARGUMENT_OUT_OF_BOUND); + + /// The exponent must not wrap the wide types either. + expectRestoreFromDumpError("Decimal128_'2e38'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal128_'-18e37'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'6e76'", ErrorCodes::DECIMAL_OVERFLOW); + expectRestoreFromDumpError("Decimal256_'-58e75'", ErrorCodes::DECIMAL_OVERFLOW); + ASSERT_EQ(Field::restoreFromDump("Decimal128_'17e37'").safeGet>().getValue(), Decimal128(Int128(17) * DecimalUtils::scaleMultiplier(37))); + ASSERT_EQ(Field::restoreFromDump("Decimal256_'-57e75'").safeGet>().getValue().value, Int256(-57) * DecimalUtils::scaleMultiplier(75)); + + /// The full native range and the scale (trailing zeroes) round-trip through a dump. + auto round_trip = [](const DecimalField & decimal) + { + const String dump = Field(decimal).dump(); + const auto restored = Field::restoreFromDump(dump).safeGet>(); + EXPECT_EQ(restored.getValue(), decimal.getValue()) << dump; + EXPECT_EQ(restored.getScale(), decimal.getScale()) << dump; + }; + round_trip(DecimalField(std::numeric_limits::max(), 0)); + round_trip(DecimalField(std::numeric_limits::min(), 3)); + round_trip(DecimalField(std::numeric_limits::max(), 18)); + round_trip(DecimalField(std::numeric_limits::min(), 0)); + round_trip(DecimalField(std::numeric_limits::max(), 38)); + round_trip(DecimalField(std::numeric_limits::min(), 1)); + round_trip(DecimalField(std::numeric_limits::max(), 0)); + round_trip(DecimalField(std::numeric_limits::min(), 76)); + round_trip(DecimalField(100, 2)); + round_trip(DecimalField(100, 1)); + round_trip(DecimalField(0, 3)); + round_trip(DecimalField(-1000, 18)); +} diff --git a/src/Core/tests/gtest_settings.cpp b/src/Core/tests/gtest_settings.cpp index 83fd74c4e82e..14228b029915 100644 --- a/src/Core/tests/gtest_settings.cpp +++ b/src/Core/tests/gtest_settings.cpp @@ -16,6 +16,7 @@ #include #include +#include #include namespace DB::ErrorCodes @@ -25,6 +26,8 @@ namespace DB::ErrorCodes extern const int INCORRECT_DATA; extern const int BAD_ARGUMENTS; extern const int ARGUMENT_OUT_OF_BOUND; + extern const int CANNOT_PARSE_BOOL; + extern const int UNKNOWN_LOAD_BALANCING; } namespace @@ -307,6 +310,63 @@ GTEST_TEST(Settings, SecondsOnTheWireRejectNegativeAndOverflowingValues) ASSERT_EQ(settings.get("max_execution_time"), Field(Float64(60))); } +GTEST_TEST(Settings, SkipInvalidValuesKeepsTheDefaultsAndReadsTheRest) +{ + /// The settings a server of an older version sends in `Hello` may hold values this version rejects. + using Entry = std::tuple; + auto wire = [](std::initializer_list entries) + { + WriteBufferFromOwnString out; + for (const auto & [name, flags, value] : entries) + { + BaseSettingsHelpers::writeString(name, out); + BaseSettingsHelpers::writeFlags(flags, out); + BaseSettingsHelpers::writeString(value, out); + } + BaseSettingsHelpers::writeString("", out); /// end of settings + return out.str(); + }; + + auto read_error_code = [](const String & bytes, bool skip_invalid_values) + { + ReadBufferFromString in(bytes); + Settings settings; + try + { + settings.read(in, SettingsWriteFormat::STRINGS_WITH_FLAGS, skip_invalid_values); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; + }; + + const String bytes = wire({ + {"max_execution_time", {}, "-1"}, + {"max_block_size", {}, "0"}, /// `NonZeroUInt64` assigns the value before it rejects it. + {"log_queries", {}, "maybe"}, + {"max_threads", {}, "4"}, + }); + ReadBufferFromString in(bytes); + Settings settings; + settings.read(in, SettingsWriteFormat::STRINGS_WITH_FLAGS, /* skip_invalid_values= */ true); + const SettingsChanges changes = settings.changes(); + ASSERT_EQ(changes.size(), 1u); + ASSERT_EQ(changes[0].name, "max_threads"); + ASSERT_EQ(changes[0].value, Field(UInt64(4))); + ASSERT_FALSE(settings.isChanged("max_execution_time")); + ASSERT_FALSE(settings.isChanged("max_block_size")); + ASSERT_EQ(settings.get("max_block_size"), Settings().get("max_block_size")); + ASSERT_FALSE(settings.isChanged("log_queries")); + + /// The default read stays strict; an important setting and other error codes are not skipped. + ASSERT_EQ(read_error_code(bytes, false), ErrorCodes::BAD_ARGUMENTS); + ASSERT_EQ(read_error_code(wire({{"log_queries", {}, "maybe"}}), false), ErrorCodes::CANNOT_PARSE_BOOL); + ASSERT_EQ(read_error_code(wire({{"max_execution_time", BaseSettingsHelpers::Flags::IMPORTANT, "-1"}}), true), ErrorCodes::BAD_ARGUMENTS); + ASSERT_EQ(read_error_code(wire({{"load_balancing", {}, "nonsense"}}), true), ErrorCodes::UNKNOWN_LOAD_BALANCING); +} + GTEST_TEST(SettingsTier, GetTierDecodesEveryEncoding) { using Flags = BaseSettingsHelpers::Flags; diff --git a/src/DataTypes/DataTypeArray.cpp b/src/DataTypes/DataTypeArray.cpp index ebba3d987495..df50484520d1 100644 --- a/src/DataTypes/DataTypeArray.cpp +++ b/src/DataTypes/DataTypeArray.cpp @@ -87,7 +87,7 @@ void DataTypeArray::forEachChild(const ChildCallback & callback) const std::unique_ptr DataTypeArray::getDynamicSubcolumnData(std::string_view subcolumn_name, const SubstreamData & data, size_t initial_array_level, bool throw_if_null) const { auto nested_type = assert_cast(*data.type).nested; - const auto & array_serialization = assert_cast(*removeNamedSerialization(data.serialization)); + const auto & array_serialization = removeNamedSerializationAndCast(data.serialization); auto nested_data = std::make_unique(array_serialization.getNestedSerialization()); nested_data->type = nested_type; nested_data->column = data.column ? assert_cast(*data.column).getDataPtr() : nullptr; diff --git a/src/DataTypes/DataTypeDynamic.cpp b/src/DataTypes/DataTypeDynamic.cpp index f66b4bec1c79..5af89c966c85 100644 --- a/src/DataTypes/DataTypeDynamic.cpp +++ b/src/DataTypes/DataTypeDynamic.cpp @@ -899,7 +899,7 @@ std::unique_ptr DataTypeDynamic::getDynamicSubcolumnDa return nullptr; } - const auto & dynamic_serialization = assert_cast(*removeNamedSerialization(data.serialization)); + const auto & dynamic_serialization = removeNamedSerializationAndCast(data.serialization); auto subcolumn_serialization = dynamic_serialization.createSerializationForType(subcolumn_type); std::unique_ptr res = std::make_unique(subcolumn_serialization); res->type = subcolumn_type; diff --git a/src/DataTypes/DataTypeLowCardinalityHelpers.cpp b/src/DataTypes/DataTypeLowCardinalityHelpers.cpp index c9e04ed51715..0e8bd7ac61bb 100644 --- a/src/DataTypes/DataTypeLowCardinalityHelpers.cpp +++ b/src/DataTypes/DataTypeLowCardinalityHelpers.cpp @@ -251,7 +251,8 @@ ColumnPtr recursiveLowCardinalityTypeConversion(const ColumnPtr & column, const if (const auto * from_tuple_type = typeid_cast(from_type.get())) { - if (const auto * to_tuple_type = typeid_cast(to_type.get())) + if (const auto * to_tuple_type = typeid_cast(to_type.get()); + to_tuple_type && to_tuple_type->getElements().size() == from_tuple_type->getElements().size()) { const auto * column_tuple = typeid_cast(column.get()); if (!column_tuple) diff --git a/src/DataTypes/DataTypeMap.cpp b/src/DataTypes/DataTypeMap.cpp index 3e8346cae644..6b500f63c3aa 100644 --- a/src/DataTypes/DataTypeMap.cpp +++ b/src/DataTypes/DataTypeMap.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -211,7 +212,7 @@ std::unique_ptr DataTypeMap::getDynamicSubcolumnData(s } /// Create a serialization that reads only the bucket containing the requested key. - const auto & map_serialization = assert_cast(*removeNamedSerialization(data.serialization)); + const auto & map_serialization = removeNamedSerializationAndCast(data.serialization); auto key_value_serialization = SerializationMapKeyValue::create( map_serialization.getValueSerialization(), map_serialization.getNestedSerialization(), diff --git a/src/DataTypes/DataTypeNullable.cpp b/src/DataTypes/DataTypeNullable.cpp index 7e06c3df9d44..975b90dc370b 100644 --- a/src/DataTypes/DataTypeNullable.cpp +++ b/src/DataTypes/DataTypeNullable.cpp @@ -112,7 +112,7 @@ void DataTypeNullable::forEachChild(const ChildCallback & callback) const std::unique_ptr DataTypeNullable::getDynamicSubcolumnData(std::string_view subcolumn_name, const SubstreamData & data, size_t initial_array_level, bool throw_if_null) const { auto nested_type = assert_cast(*data.type).nested_data_type; - const auto & nullable_serialization = assert_cast(*removeNamedSerialization(data.serialization)); + const auto & nullable_serialization = removeNamedSerializationAndCast(data.serialization); ISerialization::SubstreamData nested_data(nullable_serialization.getNested()); nested_data.type = nested_type; nested_data.column = data.column ? assert_cast(*data.column).getNestedColumnPtr() : nullptr; diff --git a/src/DataTypes/DataTypeObject.cpp b/src/DataTypes/DataTypeObject.cpp index dea6b4e61e3b..16db2a8db9ff 100644 --- a/src/DataTypes/DataTypeObject.cpp +++ b/src/DataTypes/DataTypeObject.cpp @@ -599,7 +599,7 @@ std::unique_ptr DataTypeObject::getDynamicSubcolu return res; } - const auto & object_serialization = dynamic_cast(*removeNamedSerialization(data.serialization)); + const auto & object_serialization = removeNamedSerializationAndCast(data.serialization); const auto & typed_paths_serializations = object_serialization.getTypedPathsSerializations(); const auto & dynamic_path_serialization = object_serialization.getDynamicPathSerialization(); diff --git a/src/DataTypes/IDataType.cpp b/src/DataTypes/IDataType.cpp index c573881c5083..aa532cdc68ae 100644 --- a/src/DataTypes/IDataType.cpp +++ b/src/DataTypes/IDataType.cpp @@ -86,10 +86,7 @@ MutableColumnPtr IDataType::createUninitializedColumnWithSize(size_t size) const MutableColumnPtr IDataType::createColumn(const ISerialization & serialization) const { - /// Let the serialization wrap the base column into the layout it deserializes into: ColumnSparse for the - /// Sparse kind, ColumnReplicated for Replicated, ColumnBLOB for Detached, and any custom wrapping such as - /// the ColumnConst produced by the quantized-vector codebook serialization. - return serialization.wrapColumnForDeserialization(createColumn()); + return serialization.createColumnForDeserialization(*this); } MutableColumnConstPtr IDataType::createColumnConst(size_t size, const Field & field) const @@ -361,6 +358,9 @@ SerializationPtr IDataType::getDefaultSerialization() const SerializationPtr IDataType::wrapSerializationBasedOnKindStack(SerializationPtr serialization, const ISerialization::KindStack & kind_stack, const SerializationInfoSettings & settings) const { + /// The loop below builds a wrapper for each kind. A stack with a wrong order or a repeat gives wrappers that no reader can unwrap. + ISerialization::checkKindStack(kind_stack, ISerialization::KindSet::all()); + for (auto kind : kind_stack) { if (settings.canUseSparseSerialization(*this) && kind == ISerialization::Kind::SPARSE) diff --git a/src/DataTypes/Serializations/ISerialization.cpp b/src/DataTypes/Serializations/ISerialization.cpp index 7194ada0ee5c..5ca5d2d4e713 100644 --- a/src/DataTypes/Serializations/ISerialization.cpp +++ b/src/DataTypes/Serializations/ISerialization.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,8 @@ #include #include +#include + namespace DB { @@ -36,6 +39,8 @@ namespace ErrorCodes extern const int MULTIPLE_STREAMS_REQUIRED; extern const int UNEXPECTED_DATA_AFTER_PARSED_VALUE; extern const int LOGICAL_ERROR; + extern const int CORRUPTED_DATA; + extern const int INCORRECT_DATA; extern const int NOT_IMPLEMENTED; } @@ -71,6 +76,11 @@ SerializationPtr ISerialization::pooled(UInt128 hash, absl::FunctionRef(&column)) @@ -142,7 +152,8 @@ static ISerialization::Kind stringToKind(std::string_view str) return ISerialization::Kind::DETACHED; else if (str == "Replicated") return ISerialization::Kind::REPLICATED; - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown serialization kind '{}'", str); + /// The name comes from stored data, so an unknown name is a data error. + throw Exception(ErrorCodes::CORRUPTED_DATA, "Unknown serialization kind '{}'", str); } ISerialization::KindStack ISerialization::stringToKindStack(const String & str) @@ -166,6 +177,47 @@ bool ISerialization::hasKind(const KindStack & kind_stack, Kind kind) return std::find(kind_stack.begin(), kind_stack.end(), kind) != kind_stack.end(); } +/// The order in which the kinds wrap each other, innermost first: `ColumnSparse` can sit inside +/// `ColumnReplicated` but not the other way round (see `removeSpecialRepresentations`), and nothing +/// wraps a `ColumnBLOB`. Not the order of the enum, whose values are part of the Native format. +static constexpr std::array canonical_kind_order +{ + ISerialization::Kind::DEFAULT, + ISerialization::Kind::SPARSE, + ISerialization::Kind::REPLICATED, + ISerialization::Kind::DETACHED, +}; + +void ISerialization::checkKindStack(const KindStack & kind_stack, KindSet allowed_kinds) +{ + if (kind_stack.empty() || kind_stack.front() != Kind::DEFAULT) + throw Exception(ErrorCodes::INCORRECT_DATA, "Serialization kind stack must start with Default"); + + /// A stack describes nested wrappers, so it must be a subsequence of the canonical order — and + /// therefore free of repeats. Any other stack is a layout no writer builds and nothing unwraps. + auto expected = canonical_kind_order.begin(); + + for (auto kind : kind_stack) + { + expected = std::find(expected, canonical_kind_order.end(), kind); + if (expected == canonical_kind_order.end()) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Serialization kind {} is out of order in a kind stack", + kindToString(kind)); + + ++expected; + } + + /// A well-formed stack is checked from the outermost kind, the first one a consumer would have to unwrap. + for (auto it = kind_stack.rbegin(); it != kind_stack.rend(); ++it) + if (!allowed_kinds.contains(*it)) + throw Exception( + ErrorCodes::INCORRECT_DATA, + "Unexpected serialization kind {} in the received data", + kindToString(*it)); +} + const std::set ISerialization::Substream::named_types { StringSizes, diff --git a/src/DataTypes/Serializations/ISerialization.h b/src/DataTypes/Serializations/ISerialization.h index b6e854b79912..b4eb222e5e67 100644 --- a/src/DataTypes/Serializations/ISerialization.h +++ b/src/DataTypes/Serializations/ISerialization.h @@ -122,11 +122,10 @@ class ISerialization : private boost::noncopyable, public std::enable_shared_fro virtual KindStack getKindStack() const { return {Kind::DEFAULT}; } SerializationPtr getPtr() const { return shared_from_this(); } - /// Wrap the base (`type->createColumn()`) column into the column layout this serialization deserializes - /// into. Each layer composes on top of the nested one, so this reproduces the serialization's kind stack - /// (Sparse/Replicated/Detached) and any custom wrapping (e.g. a per-part value broadcast as a ColumnConst). - /// Default: identity. - virtual MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const { return column; } + /// Create an empty column of `type` in the layout this serialization deserializes into. Each layer composes on + /// top of the nested one, so this reproduces the serialization's kind stack (Sparse/Replicated/Detached) and any + /// custom layout (e.g. a per-part value broadcast as a `ColumnConst`). Default: `type.createColumn()`. + virtual MutableColumnPtr createColumnForDeserialization(const IDataType & type) const; static KindStack getKindStack(const IColumn & column); static String kindToString(Kind kind); @@ -134,6 +133,9 @@ class ISerialization : private boost::noncopyable, public std::enable_shared_fro static KindStack stringToKindStack(const String & str); /// Check if provided kind stack contains specific kind. static bool hasKind(const KindStack & kind_stack, Kind kind); + /// Throws INCORRECT_DATA if the stack does not start with Default, is not in the canonical order + /// (repeats are not in this order), or has a kind that is not in `allowed_kinds`. + static void checkKindStack(const KindStack & kind_stack, KindSet allowed_kinds); /** Binary serialization for range of values in column - for writing to disk/network, etc. * diff --git a/src/DataTypes/Serializations/SerializationArray.h b/src/DataTypes/Serializations/SerializationArray.h index 9e7fbd013c33..b40dcedf8f47 100644 --- a/src/DataTypes/Serializations/SerializationArray.h +++ b/src/DataTypes/Serializations/SerializationArray.h @@ -9,13 +9,16 @@ class SerializationArray final : public SimpleTextSerialization { private: SerializationPtr nested; + /// Cached `nested->supportsPooling`, so that the check is O(1) instead of a walk over the whole nested + /// chain: `create` asks it of every level, which is quadratic in the depth for a deeply nested `Array`. + bool nested_supports_pooling; - explicit SerializationArray(const SerializationPtr & nested_) : nested(nested_) {} + explicit SerializationArray(const SerializationPtr & nested_) : nested(nested_), nested_supports_pooling(nested->supportsPooling()) {} public: static UInt128 getHash(const SerializationPtr & nested_); static SerializationPtr create(const SerializationPtr & nested_); - bool supportsPooling() const override { return nested->supportsPooling(); } + bool supportsPooling() const override { return nested_supports_pooling; } void serializeBinary(const Field & field, WriteBuffer & ostr, const FormatSettings & settings) const override; void deserializeBinary(Field & field, ReadBuffer & istr, const FormatSettings & settings) const override; diff --git a/src/DataTypes/Serializations/SerializationDetached.cpp b/src/DataTypes/Serializations/SerializationDetached.cpp index ee1299b617fe..7421ec9933f4 100644 --- a/src/DataTypes/Serializations/SerializationDetached.cpp +++ b/src/DataTypes/Serializations/SerializationDetached.cpp @@ -36,9 +36,9 @@ ISerialization::KindStack SerializationDetached::getKindStack() const return kind_stack; } -MutableColumnPtr SerializationDetached::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationDetached::createColumnForDeserialization(const IDataType & type) const { - return ColumnBLOB::create(nested->wrapColumnForDeserialization(std::move(column))); + return ColumnBLOB::create(nested->createColumnForDeserialization(type)); } diff --git a/src/DataTypes/Serializations/SerializationDetached.h b/src/DataTypes/Serializations/SerializationDetached.h index 2d9286262a2a..fc934f8f2f5e 100644 --- a/src/DataTypes/Serializations/SerializationDetached.h +++ b/src/DataTypes/Serializations/SerializationDetached.h @@ -20,7 +20,7 @@ class SerializationDetached final : public ISerialization const SerializationPtr & getNested() const { return nested; } KindStack getKindStack() const override; - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void serializeBinaryBulk(const IColumn & column, WriteBuffer & ostr, size_t offset, size_t limit) const override; diff --git a/src/DataTypes/Serializations/SerializationDynamicElement.cpp b/src/DataTypes/Serializations/SerializationDynamicElement.cpp index 27f266b0ec8a..90be976a91de 100644 --- a/src/DataTypes/Serializations/SerializationDynamicElement.cpp +++ b/src/DataTypes/Serializations/SerializationDynamicElement.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -286,23 +287,19 @@ size_t SerializationDynamicElement::allocatedBytes() const return sizeof(*this) + dynamic_element_name.capacity() + nested_subcolumn.capacity(); } -MutableColumnPtr SerializationDynamicElement::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationDynamicElement::createColumnForDeserialization(const IDataType & type) const { /// The null map subcolumn is a UInt8 column read through SerializationVariantElementNullMap; /// nested_serialization serializes the requested type, which is not what is read here. if (is_null_map_subcolumn) - return column; + return type.createColumn(); /// Same level ownership as in SerializationVariantElement, which this delegates to at read time. - if (isColumnNullable(*column)) - { - const auto & nullable = assert_cast(*column); + if (const auto * nullable_type = typeid_cast(&type)) return ColumnNullable::create( - nested_serialization->wrapColumnForDeserialization(nullable.getNestedColumnPtr()->cloneEmpty()), - nullable.getNullMapColumnPtr()->cloneEmpty()); - } + nested_serialization->createColumnForDeserialization(*nullable_type->getNestedType()), ColumnUInt8::create()); - return nested_serialization->wrapColumnForDeserialization(std::move(column)); + return nested_serialization->createColumnForDeserialization(type); } } diff --git a/src/DataTypes/Serializations/SerializationDynamicElement.h b/src/DataTypes/Serializations/SerializationDynamicElement.h index 1f1f726c6b59..7035daa606f9 100644 --- a/src/DataTypes/Serializations/SerializationDynamicElement.h +++ b/src/DataTypes/Serializations/SerializationDynamicElement.h @@ -34,7 +34,7 @@ class SerializationDynamicElement final : public SerializationWrapper static SerializationPtr create(const SerializationPtr & nested_, const SerializationPtr & shared_variant_serialization_, const String & dynamic_element_name_, const String & nested_subcolumn_, bool is_null_map_subcolumn_, bool nullable_added_by_extraction_); size_t allocatedBytes() const override; bool supportsPooling() const override { return SerializationWrapper::supportsPooling() && shared_variant_serialization->supportsPooling(); } - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void enumerateStreams( EnumerateStreamsSettings & settings, diff --git a/src/DataTypes/Serializations/SerializationInfo.cpp b/src/DataTypes/Serializations/SerializationInfo.cpp index 4a83ab59a5ab..cf0b6af38e11 100644 --- a/src/DataTypes/Serializations/SerializationInfo.cpp +++ b/src/DataTypes/Serializations/SerializationInfo.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include @@ -258,46 +257,18 @@ void SerializationInfo::serialializeKindStackBinary(WriteBuffer & out) const } } -/// The order in which the kinds wrap each other, innermost first: `ColumnSparse` can sit inside -/// `ColumnReplicated` but not the other way round (see `removeSpecialRepresentations`), and nothing -/// wraps a `ColumnBLOB`. Not the order of the enum, whose values are part of the Native format. -static constexpr std::array canonical_kind_order +void SerializationInfo::deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds) { - ISerialization::Kind::DEFAULT, - ISerialization::Kind::SPARSE, - ISerialization::Kind::REPLICATED, - ISerialization::Kind::DETACHED, -}; + readKindStacksBinary(in); + checkKindStacks(allowed_kinds); +} -void SerializationInfo::checkKindStack(ISerialization::KindSet allowed_kinds) const +void SerializationInfo::checkKindStacks(ISerialization::KindSet allowed_kinds) const { - if (kind_stack.empty() || kind_stack.front() != ISerialization::Kind::DEFAULT) - throw Exception(ErrorCodes::INCORRECT_DATA, "Serialization kind stack must start with Default"); - - /// A stack describes nested wrappers, so it must be a subsequence of the canonical order — and - /// therefore free of repeats. Any other stack is a layout no writer builds and nothing unwraps. - auto expected = canonical_kind_order.begin(); - - for (auto kind : kind_stack) - { - if (!allowed_kinds.contains(kind)) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "Unexpected serialization kind {} in the received data", - ISerialization::kindToString(kind)); - - expected = std::find(expected, canonical_kind_order.end(), kind); - if (expected == canonical_kind_order.end()) - throw Exception( - ErrorCodes::INCORRECT_DATA, - "Serialization kind {} is out of order in a kind stack", - ISerialization::kindToString(kind)); - - ++expected; - } + ISerialization::checkKindStack(kind_stack, allowed_kinds); } -void SerializationInfo::deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds) +void SerializationInfo::readKindStacksBinary(ReadBuffer & in) { UInt8 type = 0; readBinary(type, in); @@ -327,7 +298,7 @@ void SerializationInfo::deserializeFromKindsBinary(ReadBuffer & in, ISerializati size_t num_kinds = 0; readVarUInt(num_kinds, in); /// Refuse an impossible peer-declared count before reading that many kinds; - /// `checkKindStack` rejects the same stacks afterwards by their shape. + /// `checkKindStacks` rejects the same stacks afterwards by their shape. if (num_kinds > magic_enum::enum_count()) throw Exception(ErrorCodes::INCORRECT_DATA, "Too many serialization kinds in a kind stack: {}", num_kinds); @@ -345,8 +316,6 @@ void SerializationInfo::deserializeFromKindsBinary(ReadBuffer & in, ISerializati break; } } - - checkKindStack(allowed_kinds); } void SerializationInfo::writeJSONFields(WriteBuffer & out, const String * name) const @@ -699,6 +668,17 @@ SerializationInfoByName SerializationInfoByName::readJSONFromString(const NamesA auto info = it->second->createSerializationInfo(infos.settings); info->fromJSON(*elem_object); + + try + { + info->checkKindStacks(SerializationInfo::persistent_kinds); + } + catch (Exception & e) + { + e.addMessage("While checking serialization info of column '{}'", name); + throw; + } + infos.emplace(name, std::move(info)); } } diff --git a/src/DataTypes/Serializations/SerializationInfo.h b/src/DataTypes/Serializations/SerializationInfo.h index f120bd62d778..3aed1ac6fe7d 100644 --- a/src/DataTypes/Serializations/SerializationInfo.h +++ b/src/DataTypes/Serializations/SerializationInfo.h @@ -77,11 +77,18 @@ class SerializationInfo virtual void serialializeKindStackBinary(WriteBuffer & out) const; - /// Rejects a kind outside of `allowed_kinds` as invalid data. - virtual void deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds); + /// Reads the kind stacks, then checks them with `checkKindStacks`. + void deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds); + + /// Only reads the kind stacks, without a check. Use `deserializeFromKindsBinary` to read and check. + virtual void readKindStacksBinary(ReadBuffer & in); + + /// Checks the kind stack with `ISerialization::checkKindStack`. Subclasses also check the stacks of their elements. + virtual void checkKindStacks(ISerialization::KindSet allowed_kinds) const; virtual void writeJSON(WriteBuffer & out, const String * name) const; virtual void toJSON(Poco::JSON::Object & object) const; + /// Only parses the object and does not check the kind stacks. To read a stored info, use `SerializationInfoByName::readJSON`. virtual void fromJSON(const Poco::JSON::Object & object); void setKindStack(ISerialization::KindStack kind_stack_) { kind_stack = kind_stack_; } @@ -92,12 +99,12 @@ class SerializationInfo static ISerialization::KindStack chooseKindStack(const Data & data, const SerializationInfoSettings & settings); + /// The kinds that MergeTree writes to the disk. Other kinds are only for data in memory and Native. + static constexpr ISerialization::KindSet persistent_kinds{ISerialization::Kind::DEFAULT, ISerialization::Kind::SPARSE}; + protected: virtual void writeJSONFields(WriteBuffer & out, const String * name) const; - /// Rejects a kind stack that no writer can produce, or that selects a kind the reader does not accept. - void checkKindStack(ISerialization::KindSet allowed_kinds) const; - const SerializationInfoSettings settings; ISerialization::KindStack kind_stack; @@ -145,6 +152,7 @@ class SerializationInfoByName : public std::mapserialializeKindStackBinary(out); } -void SerializationInfoTuple::deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds) +void SerializationInfoTuple::readKindStacksBinary(ReadBuffer & in) { - SerializationInfo::deserializeFromKindsBinary(in, allowed_kinds); + SerializationInfo::readKindStacksBinary(in); + for (const auto & elem : elems) + elem->readKindStacksBinary(in); +} + +void SerializationInfoTuple::checkKindStacks(ISerialization::KindSet allowed_kinds) const +{ + SerializationInfo::checkKindStacks(allowed_kinds); - /// A detached blob always covers a whole column, never a single tuple element. - auto elements_allowed_kinds = allowed_kinds.without(ISerialization::Kind::DETACHED); + /// `Detached` and `Replicated` always wrap a whole column, never a single tuple element: + /// no writer builds such an element, and both are unwrapped only at the top level of a column. + auto elements_allowed_kinds = allowed_kinds.without(ISerialization::Kind::DETACHED).without(ISerialization::Kind::REPLICATED); for (const auto & elem : elems) - elem->deserializeFromKindsBinary(in, elements_allowed_kinds); + elem->checkKindStacks(elements_allowed_kinds); } void SerializationInfoTuple::writeJSONFields(WriteBuffer & out, const String * name) const diff --git a/src/DataTypes/Serializations/SerializationInfoTuple.h b/src/DataTypes/Serializations/SerializationInfoTuple.h index 9c5a1401260b..036bbd7ac444 100644 --- a/src/DataTypes/Serializations/SerializationInfoTuple.h +++ b/src/DataTypes/Serializations/SerializationInfoTuple.h @@ -27,7 +27,8 @@ class SerializationInfoTuple : public SerializationInfo const Settings & new_settings) const override; void serialializeKindStackBinary(WriteBuffer & out) const override; - void deserializeFromKindsBinary(ReadBuffer & in, ISerialization::KindSet allowed_kinds) override; + void readKindStacksBinary(ReadBuffer & in) override; + void checkKindStacks(ISerialization::KindSet allowed_kinds) const override; void toJSON(Poco::JSON::Object & object) const override; void fromJSON(const Poco::JSON::Object & object) override; diff --git a/src/DataTypes/Serializations/SerializationNamed.cpp b/src/DataTypes/Serializations/SerializationNamed.cpp index 25e20cc13f53..8c4ecd861689 100644 --- a/src/DataTypes/Serializations/SerializationNamed.cpp +++ b/src/DataTypes/Serializations/SerializationNamed.cpp @@ -1,6 +1,7 @@ #include #include #include +#include namespace DB { @@ -8,6 +9,7 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int ILLEGAL_COLUMN; } SerializationNamed::SerializationNamed( @@ -124,4 +126,13 @@ SerializationPtr removeNamedSerialization(const SerializationPtr & serialization return serialization; } +void throwUnexpectedSerialization(const ISerialization & serialization, const std::type_info & expected) +{ + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Unexpected serialization {}, expected {}", + demangle(typeid(serialization).name()), + demangle(expected.name())); +} + } diff --git a/src/DataTypes/Serializations/SerializationNamed.h b/src/DataTypes/Serializations/SerializationNamed.h index 62d241e6956b..73b59fc401d6 100644 --- a/src/DataTypes/Serializations/SerializationNamed.h +++ b/src/DataTypes/Serializations/SerializationNamed.h @@ -1,5 +1,8 @@ #pragma once #include +#include + +#include namespace DB { @@ -81,4 +84,21 @@ class SerializationNamed final : public SerializationWrapper SerializationPtr removeNamedSerialization(const SerializationPtr & serialization); +[[noreturn]] void throwUnexpectedSerialization(const ISerialization & serialization, const std::type_info & expected); + +/// Removes `SerializationNamed` and casts the result to `T`. +/// Throws ILLEGAL_COLUMN if the result is not a `T`, for example if it is a Sparse or Detached wrapper. +template +const T & removeNamedSerializationAndCast(const SerializationPtr & serialization) +{ + const ISerialization * nested = serialization.get(); + if (const auto * named = typeid_cast(nested)) + nested = named->getNested().get(); + + if (const auto * result = dynamic_cast(nested)) + return *result; + + throwUnexpectedSerialization(*nested, typeid(T)); +} + } diff --git a/src/DataTypes/Serializations/SerializationNullable.h b/src/DataTypes/Serializations/SerializationNullable.h index da138dff783c..7fe224c2c9f2 100644 --- a/src/DataTypes/Serializations/SerializationNullable.h +++ b/src/DataTypes/Serializations/SerializationNullable.h @@ -14,9 +14,13 @@ class SerializationNullable final : public ISerialization /// Used in Sparse columns where the null map is implicitly derived from sparse offsets. bool use_default_null_map; + /// Cached `nested->supportsPooling`, see `SerializationArray`. + bool nested_supports_pooling; + explicit SerializationNullable(const SerializationPtr & nested_, bool use_default_null_map_ = false) : nested(nested_) , use_default_null_map(use_default_null_map_) + , nested_supports_pooling(nested->supportsPooling()) { } @@ -24,7 +28,7 @@ class SerializationNullable final : public ISerialization static UInt128 getHash(const SerializationPtr & nested_, bool use_default_null_map_); static SerializationPtr create(const SerializationPtr & nested_, bool use_default_null_map_ = false); - bool supportsPooling() const override { return nested->supportsPooling(); } + bool supportsPooling() const override { return nested_supports_pooling; } const SerializationPtr & getNested() const { return nested; } diff --git a/src/DataTypes/Serializations/SerializationQuantizedVector.cpp b/src/DataTypes/Serializations/SerializationQuantizedVector.cpp index 341774813efc..dc72f28c25f5 100644 --- a/src/DataTypes/Serializations/SerializationQuantizedVector.cpp +++ b/src/DataTypes/Serializations/SerializationQuantizedVector.cpp @@ -110,11 +110,11 @@ class SerializationProductQuantizationCodebook final : public SerializationWrapp state = std::make_shared(); } - /// The codebook is a single per-part value broadcast to the whole range. Wrap the base column as an empty - /// ColumnConst; deserialize sets its value and grows its size, so the (large) codebook is never materialized - /// per row. - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override + /// The codebook is a single per-part value broadcast to the whole range. Create it as an empty `ColumnConst`; + /// deserialize sets its value and grows its size, so the (large) codebook is never materialized per row. + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override { + auto column = type.createColumn(); column->insertDefault(); /// placeholder single value; the real one is set during deserialization return ColumnConst::create(std::move(column), 0); } diff --git a/src/DataTypes/Serializations/SerializationReplicated.cpp b/src/DataTypes/Serializations/SerializationReplicated.cpp index 9c117459c902..df343d5ab20a 100644 --- a/src/DataTypes/Serializations/SerializationReplicated.cpp +++ b/src/DataTypes/Serializations/SerializationReplicated.cpp @@ -80,9 +80,9 @@ ISerialization::KindStack SerializationReplicated::getKindStack() const return kind_stack; } -MutableColumnPtr SerializationReplicated::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationReplicated::createColumnForDeserialization(const IDataType & type) const { - return ColumnReplicated::create(nested->wrapColumnForDeserialization(std::move(column)), ColumnUInt8::create()); + return ColumnReplicated::create(nested->createColumnForDeserialization(type), ColumnUInt8::create()); } SerializationPtr SerializationReplicated::SubcolumnCreator::create(const SerializationPtr & prev, const DataTypePtr &) const diff --git a/src/DataTypes/Serializations/SerializationReplicated.h b/src/DataTypes/Serializations/SerializationReplicated.h index 3a886863d093..1eccf247b8c7 100644 --- a/src/DataTypes/Serializations/SerializationReplicated.h +++ b/src/DataTypes/Serializations/SerializationReplicated.h @@ -21,7 +21,7 @@ class SerializationReplicated final : public ISerialization bool supportsPooling() const override { return nested->supportsPooling(); } KindStack getKindStack() const override; - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void enumerateStreams( EnumerateStreamsSettings & settings, diff --git a/src/DataTypes/Serializations/SerializationSparse.cpp b/src/DataTypes/Serializations/SerializationSparse.cpp index b6d431c6c629..769248a74124 100644 --- a/src/DataTypes/Serializations/SerializationSparse.cpp +++ b/src/DataTypes/Serializations/SerializationSparse.cpp @@ -230,9 +230,9 @@ ISerialization::KindStack SerializationSparse::getKindStack() const return kind_stack; } -MutableColumnPtr SerializationSparse::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationSparse::createColumnForDeserialization(const IDataType & type) const { - return ColumnSparse::create(nested->wrapColumnForDeserialization(std::move(column))); + return ColumnSparse::create(nested->createColumnForDeserialization(type)); } SerializationPtr SerializationSparse::SubcolumnCreator::create(const SerializationPtr & prev, const DataTypePtr &) const diff --git a/src/DataTypes/Serializations/SerializationSparse.h b/src/DataTypes/Serializations/SerializationSparse.h index 28c9ad56bf24..3f609140cb16 100644 --- a/src/DataTypes/Serializations/SerializationSparse.h +++ b/src/DataTypes/Serializations/SerializationSparse.h @@ -35,7 +35,7 @@ class SerializationSparse final : public ISerialization bool supportsPooling() const override { return nested->supportsPooling(); } KindStack getKindStack() const override; - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void enumerateStreams( EnumerateStreamsSettings & settings, diff --git a/src/DataTypes/Serializations/SerializationTuple.cpp b/src/DataTypes/Serializations/SerializationTuple.cpp index 2341a6e8044a..ab3d406d2aaf 100644 --- a/src/DataTypes/Serializations/SerializationTuple.cpp +++ b/src/DataTypes/Serializations/SerializationTuple.cpp @@ -13,6 +13,8 @@ #include #include +#include + namespace DB { @@ -162,6 +164,13 @@ void SerializationTuple::readElementsSafe(DB::IColumn & column, std::function(assert_cast(column).getColumns().size(), column, [&](){ read_func(); return true; }); } +SerializationTuple::SerializationTuple(ElementSerializations elems_, bool has_explicit_names_) + : elems(std::move(elems_)) + , has_explicit_names(has_explicit_names_) + , elems_support_pooling(std::ranges::all_of(elems, [](const auto & elem) { return elem->supportsPooling(); })) +{ +} + SerializationPtr SerializationTuple::create(ElementSerializations elems_, bool has_explicit_names_) { for (const auto & elem : elems_) @@ -919,26 +928,20 @@ size_t SerializationTuple::allocatedBytes() const bool SerializationTuple::supportsPooling() const { - for (const auto & elem : elems) - if (!elem->supportsPooling()) - return false; - return true; + return elems_support_pooling; } -MutableColumnPtr SerializationTuple::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationTuple::createColumnForDeserialization(const IDataType & type) const { - /// Rebuild the tuple with each element wrapped by its own serialization (element serializations are - /// SerializationNamed wrappers that forward to the real element serialization, so kinds compose). - const auto & tuple = assert_cast(*column); + const auto & tuple_type = assert_cast(type); if (elems.empty()) - return column; + return tuple_type.createColumn(); - MutableColumns wrapped; - wrapped.reserve(elems.size()); + /// Element serializations are `SerializationNamed` wrappers that forward to the real element serialization, so kinds compose. + MutableColumns tuple_columns(elems.size()); for (size_t i = 0; i != elems.size(); ++i) - wrapped.push_back(elems[i]->wrapColumnForDeserialization(tuple.getColumn(i).cloneEmpty())); - - return ColumnTuple::create(std::move(wrapped)); + tuple_columns[i] = elems[i]->createColumnForDeserialization(*tuple_type.getElement(i)); + return ColumnTuple::create(std::move(tuple_columns)); } } diff --git a/src/DataTypes/Serializations/SerializationTuple.h b/src/DataTypes/Serializations/SerializationTuple.h index 9b702fb27944..67a42ad37aab 100644 --- a/src/DataTypes/Serializations/SerializationTuple.h +++ b/src/DataTypes/Serializations/SerializationTuple.h @@ -13,10 +13,7 @@ class SerializationTuple final : public SimpleTextSerialization using ElementSerializations = std::vector; private: - SerializationTuple(ElementSerializations elems_, bool has_explicit_names_) - : elems(std::move(elems_)), has_explicit_names(has_explicit_names_) - { - } + SerializationTuple(ElementSerializations elems_, bool has_explicit_names_); public: static UInt128 getHash(const ElementSerializations & elems_, bool has_explicit_names_); @@ -24,8 +21,8 @@ class SerializationTuple final : public SimpleTextSerialization size_t allocatedBytes() const override; bool supportsPooling() const override; - /// Wrap each tuple element into the layout its serialization deserializes into (e.g. a sparse element). - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + /// Create each tuple element in the layout its serialization deserializes into (e.g. a sparse element). + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void serializeBinary(const Field & field, WriteBuffer & ostr, const FormatSettings & settings) const override; void deserializeBinary(Field & field, ReadBuffer & istr, const FormatSettings & settings) const override; @@ -89,6 +86,8 @@ class SerializationTuple final : public SimpleTextSerialization private: ElementSerializations elems; bool has_explicit_names; + /// Cached result of `supportsPooling` of all elements, see `SerializationArray`. + bool elems_support_pooling; size_t getPositionByName(const String & name) const; diff --git a/src/DataTypes/Serializations/SerializationVariantElement.cpp b/src/DataTypes/Serializations/SerializationVariantElement.cpp index 48af83d42da9..6341adfdf6e2 100644 --- a/src/DataTypes/Serializations/SerializationVariantElement.cpp +++ b/src/DataTypes/Serializations/SerializationVariantElement.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -446,20 +447,16 @@ size_t SerializationVariantElement::allocatedBytes() const return sizeof(*this) + variant_element_name.capacity(); } -MutableColumnPtr SerializationVariantElement::wrapColumnForDeserialization(MutableColumnPtr column) const +MutableColumnPtr SerializationVariantElement::createColumnForDeserialization(const IDataType & type) const { /// The Nullable level is either one the extraction added, which deserializeBinaryBulkWithMultipleStreams /// fills from the discriminators and peels off before recursing, or nested_serialization's own, which this - /// rebuild reproduces unchanged. A LowCardinality(Nullable) result is deserialized whole and keeps it. - if (isColumnNullable(*column)) - { - const auto & nullable = assert_cast(*column); + /// reproduces unchanged. A `LowCardinality(Nullable)` result is deserialized whole and keeps it. + if (const auto * nullable_type = typeid_cast(&type)) return ColumnNullable::create( - nested_serialization->wrapColumnForDeserialization(nullable.getNestedColumnPtr()->cloneEmpty()), - nullable.getNullMapColumnPtr()->cloneEmpty()); - } + nested_serialization->createColumnForDeserialization(*nullable_type->getNestedType()), ColumnUInt8::create()); - return nested_serialization->wrapColumnForDeserialization(std::move(column)); + return nested_serialization->createColumnForDeserialization(type); } } diff --git a/src/DataTypes/Serializations/SerializationVariantElement.h b/src/DataTypes/Serializations/SerializationVariantElement.h index 184e29421664..dcfae50f070e 100644 --- a/src/DataTypes/Serializations/SerializationVariantElement.h +++ b/src/DataTypes/Serializations/SerializationVariantElement.h @@ -50,7 +50,7 @@ class SerializationVariantElement final : public SerializationWrapper size_t num_variants_, bool nullable_added_by_extraction_); size_t allocatedBytes() const override; - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override; + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override; void enumerateStreams( EnumerateStreamsSettings & settings, diff --git a/src/DataTypes/Serializations/SerializationWrapper.h b/src/DataTypes/Serializations/SerializationWrapper.h index c4efd7a0b73d..47a969236f8d 100644 --- a/src/DataTypes/Serializations/SerializationWrapper.h +++ b/src/DataTypes/Serializations/SerializationWrapper.h @@ -12,14 +12,23 @@ class SerializationWrapper : public ISerialization protected: SerializationPtr nested_serialization; +private: + /// Cached `nested_serialization->supportsPooling`, so that the check does not walk the whole nested chain, + /// which is quadratic in the depth of deeply nested types (e.g. a `Tuple` element is a `SerializationNamed`). + bool nested_supports_pooling; + public: - explicit SerializationWrapper(const SerializationPtr & nested_serialization_) : nested_serialization(nested_serialization_) {} + explicit SerializationWrapper(const SerializationPtr & nested_serialization_) + : nested_serialization(nested_serialization_) + , nested_supports_pooling(nested_serialization->supportsPooling()) + { + } const SerializationPtr & getNested() const { return nested_serialization; } KindStack getKindStack() const override { return nested_serialization->getKindStack(); } - bool supportsPooling() const override { return nested_serialization->supportsPooling(); } - MutableColumnPtr wrapColumnForDeserialization(MutableColumnPtr column) const override { return nested_serialization->wrapColumnForDeserialization(std::move(column)); } + bool supportsPooling() const override { return nested_supports_pooling; } + MutableColumnPtr createColumnForDeserialization(const IDataType & type) const override { return nested_serialization->createColumnForDeserialization(type); } void enumerateStreams( EnumerateStreamsSettings & settings, diff --git a/src/DataTypes/Serializations/tests/gtest_serialization_info.cpp b/src/DataTypes/Serializations/tests/gtest_serialization_info.cpp index bb648614bb18..db2c70950b03 100644 --- a/src/DataTypes/Serializations/tests/gtest_serialization_info.cpp +++ b/src/DataTypes/Serializations/tests/gtest_serialization_info.cpp @@ -4,19 +4,26 @@ #include #include #include +#include +#include #include +#include #include #include #include #include #include +#include +#include namespace DB { namespace ErrorCodes { -extern const int LOGICAL_ERROR; +extern const int CORRUPTED_DATA; +extern const int ILLEGAL_COLUMN; +extern const int INCORRECT_DATA; } namespace @@ -55,29 +62,80 @@ Poco::JSON::Object makeKindObj(const std::string & kind, size_t num_rows, size_t return obj; } -void expectMalformedKindFails([[maybe_unused]] const std::string & kind) +template +void expectErrorCode(F && f, int code, const std::string & message_part = "") { -#ifdef DEBUG_OR_SANITIZER_BUILD - GTEST_SKIP() << "this test trigger LOGICAL_ERROR, runs only if DEBUG_OR_SANITIZER_BUILD is not defined"; -#else - EXPECT_THROW( - { - try - { - SerializationInfo info({ISerialization::Kind::DEFAULT}, defaultSettings()); - auto obj = makeKindObj(kind, 100, 10); - info.fromJSON(obj); - } - catch (const DB::Exception & e) - { - ASSERT_EQ(DB::ErrorCodes::LOGICAL_ERROR, e.code()); - EXPECT_THAT(e.what(), testing::HasSubstr("Unknown serialization kind")); - throw; - } - }, - DB::Exception); -#endif + try + { + f(); + ADD_FAILURE() << "Expected an exception with code " << code; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), code) << e.message(); + if (!message_part.empty()) + EXPECT_THAT(e.message(), testing::HasSubstr(message_part)); + } +} + +void expectMalformedKindFails(const std::string & kind) +{ + SerializationInfo info({ISerialization::Kind::DEFAULT}, defaultSettings()); + auto obj = makeKindObj(kind, 100, 10); + expectErrorCode([&] { info.fromJSON(obj); }, ErrorCodes::CORRUPTED_DATA, "Unknown serialization kind"); +} + +/// Makes a `serialization.json` of version 0 with one column entry. +std::string makeInfosJSON(const std::string & column_entry) +{ + return R"({"columns":[)" + column_entry + R"(],"version":0})"; +} + +std::string makeColumnEntry(const std::string & name, const std::string & kind) +{ + return R"({"kind":")" + kind + R"(","name":")" + name + R"(","num_defaults":5,"num_rows":10})"; +} + +std::string makeTupleElementEntry(const std::string & kind) +{ + return R"({"kind":")" + kind + R"(","num_defaults":5,"num_rows":10})"; +} + +ISerialization::KindStack readKindStackFromJSON(const NamesAndTypesList & columns, const std::string & json, const std::string & name) +{ + auto infos = SerializationInfoByName::readJSONFromString(columns, json); + auto info = infos.tryGet(name); + EXPECT_NE(info, nullptr); + return info ? info->getKindStack() : ISerialization::KindStack{}; +} + +void expectJSONRejected(const NamesAndTypesList & columns, const std::string & json) +{ + expectErrorCode([&] { SerializationInfoByName::readJSONFromString(columns, json); }, ErrorCodes::INCORRECT_DATA); +} + +DataTypePtr uint64Type() +{ + return std::make_shared(); +} + +DataTypePtr mapType() +{ + return std::make_shared(std::make_shared(), uint64Type()); +} + +DataTypePtr tupleType() +{ + return std::make_shared(DataTypes{uint64Type(), uint64Type()}, Strings{"a", "b"}); +} + +/// Tuple(a Tuple(x UInt64, y UInt64), b UInt64). +DataTypePtr nestedTupleType() +{ + auto inner = std::make_shared(DataTypes{uint64Type(), uint64Type()}, Strings{"x", "y"}); + return std::make_shared(DataTypes{inner, uint64Type()}, Strings{"a", "b"}); } + } TEST(SerializationInfoJSON, RoundTripDefault) @@ -238,9 +296,7 @@ TEST(SerializationInfoByNameJSON, WriteJSONCanBeReadBack) EXPECT_NE(restored.tryGet("tuple"), nullptr); } -/// Malformed kind tests. -/// stringToKind throws LOGICAL_ERROR which aborts in debug builds -/// but throws a catchable exception in release builds. +/// Malformed kind tests. The kind name comes from stored data, so stringToKind throws CORRUPTED_DATA. TEST(SerializationInfoJSON, FromJSONEmptyKind) { @@ -356,4 +412,193 @@ TEST(SerializationInfoBinary, AcceptsDetachedOverReplicatedOverSparse) EXPECT_EQ(info.getKindStack(), expected); } +/// The binary path reads all stacks first, then checks them. The rules for tuple elements must stay the same. +TEST(SerializationInfoBinary, TupleRejectsDetachedElement) +{ + /// Tuple stack {Default}, then the element stacks {Default, Detached} and {Default}. + const char kinds[] = {0, 2, 0}; + ReadBufferFromMemory in(kinds, sizeof(kinds)); + + auto info = tupleType()->createSerializationInfo(defaultSettings()); + expectErrorCode([&] { info->deserializeFromKindsBinary(in, ISerialization::KindSet::all()); }, ErrorCodes::INCORRECT_DATA); +} + +TEST(SerializationInfoBinary, TupleAcceptsDetachedTupleWithSparseElement) +{ + /// Tuple stack {Default, Detached}, then the element stacks {Default, Sparse} and {Default}. + const char kinds[] = {2, 1, 0}; + ReadBufferFromMemory in(kinds, sizeof(kinds)); + + auto info = tupleType()->createSerializationInfo(defaultSettings()); + info->deserializeFromKindsBinary(in, ISerialization::KindSet::all()); + + const auto & tuple_info = assert_cast(*info); + EXPECT_EQ(info->getKindStack(), (ISerialization::KindStack{ISerialization::Kind::DEFAULT, ISerialization::Kind::DETACHED})); + EXPECT_EQ(tuple_info.getElementKindStack(0), (ISerialization::KindStack{ISerialization::Kind::DEFAULT, ISerialization::Kind::SPARSE})); + EXPECT_EQ(tuple_info.getElementKindStack(1), ISerialization::KindStack{ISerialization::Kind::DEFAULT}); +} + +TEST(SerializationKindStack, CheckKindStack) +{ + using Kind = ISerialization::Kind; + const auto all = ISerialization::KindSet::all(); + + ISerialization::checkKindStack({Kind::DEFAULT}, all); + ISerialization::checkKindStack({Kind::DEFAULT, Kind::SPARSE}, SerializationInfo::persistent_kinds); + ISerialization::checkKindStack({Kind::DEFAULT, Kind::SPARSE, Kind::REPLICATED, Kind::DETACHED}, all); + + auto expect_rejected = [](const ISerialization::KindStack & stack, ISerialization::KindSet allowed) + { + expectErrorCode([&] { ISerialization::checkKindStack(stack, allowed); }, ErrorCodes::INCORRECT_DATA); + }; + + expect_rejected({}, all); + expect_rejected({Kind::SPARSE}, all); + expect_rejected({Kind::DEFAULT, Kind::SPARSE, Kind::SPARSE}, all); + expect_rejected({Kind::DEFAULT, Kind::DEFAULT}, all); + expect_rejected({Kind::DEFAULT, Kind::DETACHED, Kind::SPARSE}, all); + expect_rejected({Kind::DEFAULT, Kind::REPLICATED, Kind::SPARSE}, all); + expect_rejected({Kind::DEFAULT, Kind::DETACHED}, SerializationInfo::persistent_kinds); + expect_rejected({Kind::DEFAULT, Kind::REPLICATED}, SerializationInfo::persistent_kinds); +} + +TEST(SerializationInfoByNameJSON, AcceptsPersistentKinds) +{ + using Kind = ISerialization::Kind; + NamesAndTypesList columns{{"x", uint64Type()}}; + + EXPECT_EQ(readKindStackFromJSON(columns, makeInfosJSON(makeColumnEntry("x", "Default")), "x"), ISerialization::KindStack{Kind::DEFAULT}); + EXPECT_EQ( + readKindStackFromJSON(columns, makeInfosJSON(makeColumnEntry("x", "Sparse")), "x"), + (ISerialization::KindStack{Kind::DEFAULT, Kind::SPARSE})); +} + +/// Old versions can write Sparse for a Tuple itself and an entry for a column of any type. Such parts must stay readable. +TEST(SerializationInfoByNameJSON, AcceptsSparseOnTupleAndMap) +{ + using Kind = ISerialization::Kind; + NamesAndTypesList columns{{"t", tupleType()}, {"m", mapType()}}; + + auto tuple_entry = R"({"kind":"Sparse","name":"t","num_defaults":5,"num_rows":10,"subcolumns":[)" + + makeTupleElementEntry("Sparse") + "," + makeTupleElementEntry("Default") + "]}"; + auto json = R"({"columns":[)" + tuple_entry + "," + makeColumnEntry("m", "Sparse") + R"(],"version":0})"; + + auto infos = SerializationInfoByName::readJSONFromString(columns, json); + ASSERT_NE(infos.tryGet("t"), nullptr); + ASSERT_NE(infos.tryGet("m"), nullptr); + EXPECT_EQ(infos.tryGet("t")->getKindStack(), (ISerialization::KindStack{Kind::DEFAULT, Kind::SPARSE})); + EXPECT_EQ(infos.tryGet("m")->getKindStack(), (ISerialization::KindStack{Kind::DEFAULT, Kind::SPARSE})); + + /// The Sparse kind of the Tuple itself is ignored, so the Tuple gets its usual serialization. + auto serialization = tupleType()->getSerialization(*infos.tryGet("t")); + EXPECT_EQ(serialization->getKindStack(), ISerialization::KindStack{Kind::DEFAULT}); +} + +TEST(SerializationInfoByNameJSON, AcceptsWrittenSparseColumns) +{ + SerializationInfoSettings settings; + settings.ratio_of_defaults_for_sparse = 0.5; + settings.choose_kind = true; + + NamesAndTypesList columns{{"x", uint64Type()}, {"t", tupleType()}}; + SerializationInfoByName infos(columns, settings); + auto x_column = uint64Type()->createColumn(); + x_column->insertManyDefaults(10); + auto t_column = tupleType()->createColumn(); + t_column->insertManyDefaults(10); + infos.add(Block{ColumnWithTypeAndName(std::move(x_column), uint64Type(), "x"), ColumnWithTypeAndName(std::move(t_column), tupleType(), "t")}); + + WriteBufferFromOwnString out; + infos.writeJSON(out); + auto json = out.str(); + EXPECT_THAT(json, testing::HasSubstr(R"("kind":"Sparse")")); + + auto restored = SerializationInfoByName::readJSONFromString(columns, json); + ASSERT_NE(restored.tryGet("x"), nullptr); + EXPECT_EQ(restored.tryGet("x")->getKindStack(), infos.tryGet("x")->getKindStack()); +} + +TEST(SerializationInfoByNameJSON, RejectsKindsThatAreNotPersistent) +{ + NamesAndTypesList columns{{"x", uint64Type()}, {"m", mapType()}}; + + for (const auto * kind : {"SparseOverSparse", "SparseOverSparseOverSparse", "Detached", "Replicated", "DetachedOverSparse", "SparseOverDetached", "SparseOverDefault"}) + expectJSONRejected(columns, makeInfosJSON(makeColumnEntry("x", kind))); + + expectJSONRejected(columns, makeInfosJSON(makeColumnEntry("m", "Detached"))); + expectJSONRejected(columns, makeInfosJSON(makeColumnEntry("m", "Replicated"))); + expectJSONRejected(columns, makeInfosJSON(makeColumnEntry("m", "SparseOverSparse"))); +} + +TEST(SerializationInfoByNameJSON, ErrorShowsColumnName) +{ + NamesAndTypesList columns{{"some_column", uint64Type()}}; + expectErrorCode( + [&] { SerializationInfoByName::readJSONFromString(columns, makeInfosJSON(makeColumnEntry("some_column", "SparseOverSparse"))); }, + ErrorCodes::INCORRECT_DATA, + "some_column"); +} + +TEST(SerializationInfoByNameJSON, RejectsBadTupleStacks) +{ + NamesAndTypesList columns{{"t", tupleType()}, {"n", nestedTupleType()}}; + + auto make_tuple = [](const std::string & kind, const std::string & first, const std::string & second) + { + return R"({"kind":")" + kind + R"(","name":"t","num_defaults":5,"num_rows":10,"subcolumns":[)" + + makeTupleElementEntry(first) + "," + makeTupleElementEntry(second) + "]}"; + }; + + expectJSONRejected(columns, makeInfosJSON(make_tuple("Detached", "Default", "Default"))); + expectJSONRejected(columns, makeInfosJSON(make_tuple("Default", "Detached", "Default"))); + expectJSONRejected(columns, makeInfosJSON(make_tuple("Default", "Default", "Replicated"))); + expectJSONRejected(columns, makeInfosJSON(make_tuple("Default", "SparseOverSparse", "Default"))); + + /// A bad stack in an element of a nested tuple. + auto make_nested = [](const std::string & inner_kind) + { + auto inner = R"({"kind":"Default","num_defaults":5,"num_rows":10,"subcolumns":[)" + + makeTupleElementEntry(inner_kind) + "," + makeTupleElementEntry("Default") + "]}"; + return R"({"kind":"Default","name":"n","num_defaults":5,"num_rows":10,"subcolumns":[)" + + inner + "," + makeTupleElementEntry("Default") + "]}"; + }; + + EXPECT_EQ(readKindStackFromJSON(columns, makeInfosJSON(make_nested("Sparse")), "n"), ISerialization::KindStack{ISerialization::Kind::DEFAULT}); + expectJSONRejected(columns, makeInfosJSON(make_nested("SparseOverSparse"))); + expectJSONRejected(columns, makeInfosJSON(make_nested("Detached"))); +} + +/// `fromJSON` only parses. A caller that skips `SerializationInfoByName::readJSON` must not get a double Sparse wrapper. +TEST(SerializationKindStack, WrapRejectsBadStack) +{ + using Kind = ISerialization::Kind; + auto info = uint64Type()->createSerializationInfo(defaultSettings()); + + info->setKindStack({Kind::DEFAULT, Kind::SPARSE, Kind::SPARSE}); + expectErrorCode([&] { uint64Type()->getSerialization(*info); }, ErrorCodes::INCORRECT_DATA); + + info->setKindStack({Kind::DEFAULT, Kind::DETACHED, Kind::SPARSE}); + expectErrorCode([&] { uint64Type()->getSerialization(*info); }, ErrorCodes::INCORRECT_DATA); + + info->setKindStack({Kind::DEFAULT, Kind::SPARSE}); + EXPECT_EQ(uint64Type()->getSerialization(*info)->getKindStack(), (ISerialization::KindStack{Kind::DEFAULT, Kind::SPARSE})); +} + +/// A dynamic subcolumn of a Map needs `SerializationMap`. Another serialization gives an error, not a bad cast. +TEST(SerializationKindStack, MapKeySubcolumnOfWrappedMap) +{ + using Kind = ISerialization::Kind; + auto type = mapType(); + NameAndTypePair subcolumn("m", "key_a", type, uint64Type()); + + auto info = type->createSerializationInfo(defaultSettings()); + EXPECT_NE(IDataType::getSerialization(subcolumn, *info), nullptr); + + for (const auto & stack : {ISerialization::KindStack{Kind::DEFAULT, Kind::DETACHED}, ISerialization::KindStack{Kind::DEFAULT, Kind::REPLICATED}}) + { + info->setKindStack(stack); + expectErrorCode([&] { IDataType::getSerialization(subcolumn, *info); }, ErrorCodes::ILLEGAL_COLUMN, "SerializationMap"); + } +} + } diff --git a/src/Databases/DataLake/Common.cpp b/src/Databases/DataLake/Common.cpp index 3046f73b115b..86f9c75f19cc 100644 --- a/src/Databases/DataLake/Common.cpp +++ b/src/Databases/DataLake/Common.cpp @@ -16,6 +16,8 @@ #include +#include + namespace DB::ErrorCodes { extern const int BAD_ARGUMENTS; @@ -32,9 +34,23 @@ String trim(const String & str) return (start == String::npos || end == String::npos) ? "" : str.substr(start, end - start + 1); } -std::vector splitTypeArguments(const String & type_str) +namespace +{ + +std::string_view trimView(std::string_view str) { - std::vector args; + size_t start = str.find_first_not_of(' '); + size_t end = str.find_last_not_of(' '); + if (start == std::string_view::npos || end == std::string_view::npos) + return {}; + return str.substr(start, end - start + 1); +} + +} + +std::vector splitTypeArguments(std::string_view type_str) +{ + std::vector args; int angle_depth = 0; int paren_depth = 0; size_t start = 0; @@ -52,28 +68,31 @@ std::vector splitTypeArguments(const String & type_str) paren_depth--; else if (c == ',' && angle_depth == 0 && paren_depth == 0) { - args.push_back(trim(type_str.substr(start, i - start))); + args.push_back(trimView(type_str.substr(start, i - start))); start = i + 1; } } - args.push_back(trim(type_str.substr(start))); + args.push_back(trimView(type_str.substr(start))); return args; } -DB::DataTypePtr getType(const String & type_name, bool nullable, const String & prefix) +DB::DataTypePtr getType(std::string_view type_name, bool nullable, const String & prefix) { - String name = trim(type_name); + checkStackSize(); + + /// Views keep memory linear in nesting depth. + std::string_view name = trimView(type_name); if (name.starts_with("array<") && name.ends_with(">")) { - String inner = name.substr(6, name.size() - 7); + std::string_view inner = name.substr(6, name.size() - 7); return std::make_shared(getType(inner, nullable)); } if (name.starts_with("map<") && name.ends_with(">")) { - String inner = name.substr(4, name.size() - 5); + std::string_view inner = name.substr(4, name.size() - 5); auto args = splitTypeArguments(inner); if (args.size() != 2) @@ -84,7 +103,7 @@ DB::DataTypePtr getType(const String & type_name, bool nullable, const String & if (name.starts_with("struct<") && name.ends_with(">")) { - String inner = name.substr(7, name.size() - 8); + std::string_view inner = name.substr(7, name.size() - 8); auto args = splitTypeArguments(inner); std::vector field_names; @@ -93,11 +112,11 @@ DB::DataTypePtr getType(const String & type_name, bool nullable, const String & for (const auto & arg : args) { size_t colon = arg.find(':'); - if (colon == String::npos) + if (colon == std::string_view::npos) throw DB::Exception(DB::ErrorCodes::DATALAKE_DATABASE_ERROR, "Invalid data type {}", type_name); - String field_name = trim(arg.substr(0, colon)); - String field_type = trim(arg.substr(colon + 1)); + String field_name(trimView(arg.substr(0, colon))); + std::string_view field_type = arg.substr(colon + 1); String full_field_name = prefix.empty() ? field_name : prefix + "." + field_name; field_names.push_back(full_field_name); @@ -106,8 +125,8 @@ DB::DataTypePtr getType(const String & type_name, bool nullable, const String & return std::make_shared(field_types, field_names); } - return nullable ? DB::makeNullable(DB::Iceberg::IcebergSchemaProcessor::getSimpleType(name)) - : DB::Iceberg::IcebergSchemaProcessor::getSimpleType(name); + auto type = DB::Iceberg::IcebergSchemaProcessor::getSimpleType(String(name)); + return nullable ? DB::makeNullable(type) : type; } std::pair parseTableName(const std::string & name) diff --git a/src/Databases/DataLake/Common.h b/src/Databases/DataLake/Common.h index cd4b6214e343..35990fe652aa 100644 --- a/src/Databases/DataLake/Common.h +++ b/src/Databases/DataLake/Common.h @@ -3,14 +3,17 @@ #include #include +#include + namespace DataLake { String trim(const String & str); -std::vector splitTypeArguments(const String & type_str); +/// Returned views point into `type_str`. +std::vector splitTypeArguments(std::string_view type_str); -DB::DataTypePtr getType(const String & type_name, bool nullable, const String & prefix = ""); +DB::DataTypePtr getType(std::string_view type_name, bool nullable, const String & prefix = ""); /// Parse a string, containing at least one dot, into a two substrings: /// A.B.C.D.E -> A.B.C.D and E, where diff --git a/src/Databases/DataLake/tests/gtest_glue_nested_type_depth.cpp b/src/Databases/DataLake/tests/gtest_glue_nested_type_depth.cpp new file mode 100644 index 000000000000..09d746836f7d --- /dev/null +++ b/src/Databases/DataLake/tests/gtest_glue_nested_type_depth.cpp @@ -0,0 +1,37 @@ +#include "config.h" + +#if USE_AWS_S3 && USE_AVRO + +#include + +#include +#include + +namespace DB::ErrorCodes +{ + extern const int TOO_DEEP_RECURSION; +} + +/// Glue returns type string as is, so its nesting depth is not bounded by ClickHouse. +TEST(GlueSchemaColumns, DeeplyNestedTypeThrows) +{ + const size_t depth = 500000; + + std::string glue_type; + for (size_t i = 0; i < depth; ++i) + glue_type += "array<"; + glue_type += "int"; + glue_type.append(depth, '>'); + + try + { + DataLake::getType(glue_type, /*nullable=*/true); + FAIL() << "expected TOO_DEEP_RECURSION"; + } + catch (const DB::Exception & e) + { + ASSERT_EQ(e.code(), DB::ErrorCodes::TOO_DEEP_RECURSION); + } +} + +#endif diff --git a/src/Databases/DatabaseFactory.cpp b/src/Databases/DatabaseFactory.cpp index 3f2f6669b63c..6b9a449297ed 100644 --- a/src/Databases/DatabaseFactory.cpp +++ b/src/Databases/DatabaseFactory.cpp @@ -59,8 +59,8 @@ static void cckMetadataPathForOrdinary(const ASTCreateQuery & create, const Stri /// Between 20.7 and 22.7 metadata/db_name.sql was created in this case as well. /// Since 20.7 `default` database is created with Atomic engine on the very first server run. /// The problem is that if server crashed during the very first run and metadata/db_name/ -> store/whatever symlink was created - /// then it's considered as Ordinary database. And it even works somehow - /// until background task tries to remove unused dir from store/... + /// then it's considered as Ordinary database. And it even worked somehow + /// until the background task (which no longer exists) tried to remove the unused dir from store/... throw Exception(ErrorCodes::CANNOT_CREATE_DATABASE, "Metadata directory {} for Ordinary database {} is a symbolic link to {}. " "It may be a result of manual intervention, crash on very first server start or a bug. " diff --git a/src/Databases/DatabaseFilesystem.cpp b/src/Databases/DatabaseFilesystem.cpp index be29fb035d2e..f8279cbd8a56 100644 --- a/src/Databases/DatabaseFilesystem.cpp +++ b/src/Databases/DatabaseFilesystem.cpp @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include @@ -42,6 +44,31 @@ namespace ErrorCodes extern const int FILE_DOESNT_EXIST; } +namespace +{ + +/// Whether `table_path`, already normalized, stays inside `directory`. The `file` table function +/// expands `{a,b}` groups before it walks the filesystem and does not normalize the result, so an +/// alternative carrying a `..` is refused instead of being resolved against a possible symlink. +bool isInsideDirectory(const String & table_path, const String & directory) +{ + if (!containsGlobs(table_path)) + return fileOrSymlinkPathStartsWith(table_path, directory); + + for (const auto & expanded_path : expandSelectionGlob(table_path)) + { + for (const auto & component : fs::path(expanded_path)) + if (component == "..") + return false; + + if (!fileOrSymlinkPathStartsWith(expanded_path, directory)) + return false; + } + return true; +} + +} + DatabaseFilesystem::DatabaseFilesystem( const String & name_, const String & path_, ContextPtr context_, bool is_internal_metadata_replay) : IDatabase(name_), WithContext(context_->getGlobalContext()), path(path_), log(getLogger("DatabaseFileSystem(" + name_ + ")")) @@ -102,6 +129,10 @@ bool DatabaseFilesystem::checkTableFilePath(const std::string & table_path, Cont throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside {}", user_files_path); } + /// A table of this database is a file under its own directory, not anywhere in `user_files`. + if (check_path && !isInsideDirectory(table_path, path)) + throw Exception(ErrorCodes::PATH_ACCESS_DENIED, "File is not inside the database directory {}", path); + if (!containsGlobs(table_path)) { /// Check if the corresponding file exists. diff --git a/src/Databases/DatabaseOnDisk.cpp b/src/Databases/DatabaseOnDisk.cpp index 42ca6871a68e..6fc36907935e 100644 --- a/src/Databases/DatabaseOnDisk.cpp +++ b/src/Databases/DatabaseOnDisk.cpp @@ -506,11 +506,9 @@ void DatabaseOnDisk::renameTable( if (auto * target_db = dynamic_cast(&to_database)) target_db->checkMetadataFilenameAvailability(to_table_name); - /// This place is actually quite dangerous. Since data directory is moved to store/ - /// DatabaseCatalog may try to clean it up as unused. We add UUID mapping to avoid this. - /// However, we may fail after data directory move, but before metadata file creation in the destination db. - /// In this case nothing will protect data directory (except 30-days timeout). - /// But this situation (when table in Ordinary database is partially renamed) require manual intervention anyway. + /// The data directory is moved to store/, so the UUID must be marked as used first (see `DatabaseCatalog::addUUIDMapping`). + /// We may fail after data directory move, but before metadata file creation in the destination db. + /// This situation (when table in Ordinary database is partially renamed) requires manual intervention. if (from_ordinary_to_atomic) { DatabaseCatalog::instance().addUUIDMapping(create.uuid); diff --git a/src/Databases/DatabaseOrdinary.cpp b/src/Databases/DatabaseOrdinary.cpp index 76494aab7b0e..530bcff9ed86 100644 --- a/src/Databases/DatabaseOrdinary.cpp +++ b/src/Databases/DatabaseOrdinary.cpp @@ -160,12 +160,20 @@ void DatabaseOrdinary::checkReplicaPathIsSafe(const ASTCreateQuery & create_quer /*validate_substitutions=*/true); } +String DatabaseOrdinary::getConvertedMergeTreeEngineName(const String & engine_name, bool replicated) +{ + if (replicated) + return "Replicated" + engine_name; + chassert(engine_name.starts_with("Replicated")); + return engine_name.substr(strlen("Replicated")); +} + void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, ContextPtr local_context, bool replicated) { auto * storage = create_query.storage; auto args = make_intrusive(); auto engine = make_intrusive(); - String engine_name; + const String engine_name = getConvertedMergeTreeEngineName(storage->engine->name, replicated); if (replicated) { @@ -182,8 +190,6 @@ void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, Context for (size_t i = 0; i < storage->engine->arguments->children.size(); ++i) args->children.push_back(storage->engine->arguments->children[i]->clone()); } - - engine_name = "Replicated" + storage->engine->name; } else { @@ -193,8 +199,6 @@ void DatabaseOrdinary::setMergeTreeEngine(ASTCreateQuery & create_query, Context for (size_t i = 2; i < storage->engine->arguments->children.size(); ++i) args->children.push_back(storage->engine->arguments->children[i]->clone()); } - - engine_name = storage->engine->name.substr(strlen("Replicated")); } /// Set new engine for the old query diff --git a/src/Databases/DatabaseOrdinary.h b/src/Databases/DatabaseOrdinary.h index 73956b751a10..70e1ff84768e 100644 --- a/src/Databases/DatabaseOrdinary.h +++ b/src/Databases/DatabaseOrdinary.h @@ -88,6 +88,10 @@ class DatabaseOrdinary : public DatabaseOnDisk static void setMergeTreeEngine(ASTCreateQuery & create_query, ContextPtr context, bool replicated); + /// The name of the engine that `setMergeTreeEngine` sets for a table of the engine `engine_name`. + /// For `replicated = false`, `engine_name` must start with `Replicated`. + static String getConvertedMergeTreeEngineName(const String & engine_name, bool replicated); + /// Rejects a conversion to a replicated engine whose Keeper path would not be a safe one. /// Contacts nothing and mutates nothing, so a caller can run it before its own side effects. static void checkReplicaPathIsSafe(const ASTCreateQuery & create_query, ContextPtr context); diff --git a/src/Dictionaries/ClickHouseDictionarySource.cpp b/src/Dictionaries/ClickHouseDictionarySource.cpp index 12a897ba958d..dd8aa6a5f6af 100644 --- a/src/Dictionaries/ClickHouseDictionarySource.cpp +++ b/src/Dictionaries/ClickHouseDictionarySource.cpp @@ -19,8 +19,6 @@ #include #include #include -#include -#include #include #include #include @@ -34,7 +32,6 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; - extern const int INCORRECT_QUERY; } namespace @@ -162,26 +159,6 @@ std::string ClickHouseDictionarySource::toString() const return "ClickHouse: " + configuration.db + '.' + configuration.table + (where.empty() ? "" : ", where: " + where); } -namespace -{ - -/// The query text comes from the dictionary definition (possibly a `CREATE DICTIONARY` written by a user -/// who has no other privileges), and for a local source it is executed as an `internal` query on behalf -/// of the configured user. So only a `SELECT` is allowed: any other statement (`CREATE TABLE`, ...) -/// would run with the access checks of `internal` queries skipped. -void checkQueryIsSelect(const String & query, const char * description, const char * error_message) -{ - const char * query_begin = query.data(); - const char * query_end = query.data() + query.size(); - ParserQuery parser(query_end); - ASTPtr ast = parseQuery(parser, query_begin, query_end, description, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); - - if (!ast || ast->getQueryKind() != IAST::QueryKind::Select) - throw Exception(ErrorCodes::INCORRECT_QUERY, "{}", error_message); -} - -} - BlockIO ClickHouseDictionarySource::createStreamForQuery(const String & query) { BlockIO io; @@ -193,7 +170,7 @@ BlockIO ClickHouseDictionarySource::createStreamForQuery(const String & query) auto context_copy = Context::createCopy(context); context_copy->makeQueryContext(); - checkQueryIsSelect(query, "Query for ClickHouse dictionary", "Only SELECT query can be used as a dictionary source"); + checkDictionaryQueryIsSelect(query, "Query for ClickHouse dictionary", "Only SELECT query can be used as a dictionary source"); if (configuration.is_local) { @@ -219,7 +196,7 @@ std::string ClickHouseDictionarySource::doInvalidateQuery(const std::string & re { LOG_TRACE(log, "Performing invalidate query"); - checkQueryIsSelect(request, "Invalidate query for ClickHouse dictionary", "Only SELECT query can be used as a dictionary invalidate query"); + checkDictionaryQueryIsSelect(request, "Invalidate query for ClickHouse dictionary", "Only SELECT query can be used as a dictionary invalidate query"); /// Copy context because results of scalar subqueries potentially could be cached auto context_copy = Context::createCopy(context); diff --git a/src/Dictionaries/DictionarySourceHelpers.cpp b/src/Dictionaries/DictionarySourceHelpers.cpp index 95b88185b1a2..22ac937ea2eb 100644 --- a/src/Dictionaries/DictionarySourceHelpers.cpp +++ b/src/Dictionaries/DictionarySourceHelpers.cpp @@ -5,16 +5,147 @@ #include #include #include +#include #include +#include +#include +#include +#include +#include +#include +#include #include #include namespace DB { +namespace ServerSetting +{ + extern const ServerSettingsBool dictionaries_external_source_queries_select_only; +} + namespace ErrorCodes { extern const int SIZES_OF_COLUMNS_DOESNT_MATCH; + extern const int INCORRECT_QUERY; + extern const int SYNTAX_ERROR; +} + +namespace +{ + +/// The errors of the checks below do not contain the text of the query: the query can come from a named collection, whose values +/// are hidden from a user without `SHOW NAMED COLLECTIONS SECRETS`, and the error reaches the caller of `dictGet` and +/// `system.dictionaries`. +size_t positionInQuery(const String & query, const char * pos) +{ + return pos - query.data() + 1; +} + +ASTPtr parseDictionaryQueryAsSelect(const String & query, const String & description, const char * error_message) +{ + const char * pos = query.data(); + const char * query_end = query.data() + query.size(); + ParserQuery parser(query_end); + String parser_error_message; /// Contains the text of the query from the error, so it is not shown. + ASTPtr ast = tryParseQuery( + parser, pos, query_end, parser_error_message, /* hilite = */ false, description, /* allow_multi_statements = */ false, + /* max_query_size = */ 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS, /* skip_insignificant = */ true); + if (!ast) + throw Exception( + ErrorCodes::SYNTAX_ERROR, + "Syntax error ({}): the query is not a SELECT that the ClickHouse parser reads. " + "The query is not shown, because it can come from a named collection", + description); + + if (!ast || ast->getQueryKind() != IAST::QueryKind::Select) + throw Exception(ErrorCodes::INCORRECT_QUERY, "{}", error_message); + + return ast; +} + +bool hasSettings(const IAST & ast) +{ + if (ast.as()) + return true; + for (const auto & child : ast.children) + if (hasSettings(*child)) + return true; + return false; +} + +} + +void checkDictionaryQueryIsSelect(const String & query, const String & description, const char * error_message) +{ + parseDictionaryQueryAsSelect(query, description, error_message); +} + +void checkExternalDictionaryQueryIsSelect(const String & query, const String & source_description, const char * error_message) +{ + /// A query valid for the database can be rejected by the ClickHouse parser, so the errors say which check rejected it. + const String description = source_description + + " (checked as a ClickHouse SELECT query, see the server setting `dictionaries_external_source_queries_select_only`)"; + + Lexer lexer(query.data(), query.data() + query.size()); + for (Token token = lexer.nextToken(); !token.isEnd() && !token.isError(); token = lexer.nextToken()) + { + const std::string_view text(token.begin, token.size()); + const bool is_quoted = token.type == TokenType::StringLiteral || token.type == TokenType::QuotedIdentifier; + const bool is_ascii_quoted = is_quoted && (text.starts_with('\'') || text.starts_with('"') || text.starts_with('`')); + const char * kind = nullptr; + if (token.type == TokenType::Comment) + kind = "a comment"; + else if (token.type == TokenType::HereDoc) + kind = "a heredoc"; + else if (is_quoted && !is_ascii_quoted) + kind = "a typographic quote"; + else if (is_quoted && text.contains('\\')) + kind = "a backslash in a quoted token"; + + if (kind) + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "{} cannot contain comments, heredocs, typographic quotes or backslashes, because the database may read them differently: " + "{} at position {}", + description, + kind, + positionInQuery(query, token.begin)); + } + + ASTPtr ast = parseDictionaryQueryAsSelect(query, description, error_message); + const auto * query_with_output = dynamic_cast(ast.get()); + if (hasSettings(*ast) || (query_with_output && (query_with_output->out_file || query_with_output->format_ast))) + throw Exception(ErrorCodes::INCORRECT_QUERY, "{}", error_message); +} + +bool shouldCheckExternalDictionaryQueries(const ContextPtr & context, bool created_from_ddl) +{ + return created_from_ddl && context->getServerSettings()[ServerSetting::dictionaries_external_source_queries_select_only]; +} + +void checkExternalDictionaryQueryConditionPlaceholder(const String & query, const String & source_name) +{ + const String description = "Query for " + source_name + " dictionary"; + + Lexer lexer(query.data(), query.data() + query.size()); + for (Token token = lexer.nextToken(); !token.isEnd() && !token.isError(); token = lexer.nextToken()) + { + if ((token.type == TokenType::StringLiteral || token.type == TokenType::QuotedIdentifier) + && std::string_view(token.begin, token.size()).contains(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE)) + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "{} cannot contain {} in a string literal or a quoted identifier, because it is replaced by a condition with quotes", + description, + CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); + } +} + +void checkExternalDictionaryLoadQueryIsSelect(const String & load_all_query, const String & source_name) +{ + checkExternalDictionaryQueryIsSelect( + load_all_query, "Query for " + source_name + " dictionary", "Only SELECT query can be used as a dictionary source"); } /// For simple key diff --git a/src/Dictionaries/DictionarySourceHelpers.h b/src/Dictionaries/DictionarySourceHelpers.h index 32d0128d0475..bf45f24af3df 100644 --- a/src/Dictionaries/DictionarySourceHelpers.h +++ b/src/Dictionaries/DictionarySourceHelpers.h @@ -27,6 +27,35 @@ Block blockForKeys( SettingsChanges readSettingsFromDictionaryConfig(const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix); ContextMutablePtr copyContextAndApplySettingsFromDictionaryConfig(const ContextPtr & context, const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix); +/// The query text comes from the dictionary definition (possibly a `CREATE DICTIONARY` written by a user +/// who has no other privileges) and is executed with privileges that user may not have: as an `internal` +/// query for a local ClickHouse source, or with the credentials of the source for an external database +/// (possibly taken from a named collection). So only a `SELECT` is allowed. +void checkDictionaryQueryIsSelect(const String & query, const String & description, const char * error_message); + +/// The same for a query sent to an external database (MySQL, PostgreSQL, ODBC). It is parsed by ClickHouse, +/// so what the database can read differently is rejected too: comments (MySQL executes `/*! ... */`), heredocs, +/// typographic quotes, backslashes in quoted tokens (PostgreSQL and SQL Server read them literally), and `INTO OUTFILE`, +/// `FORMAT` and `SETTINGS`, which are a part of a `SELECT` only for ClickHouse. +void checkExternalDictionaryQueryIsSelect(const String & query, const String & source_description, const char * error_message); + +/// Whether a source of an external database checks its queries with `checkExternalDictionaryQueryIsSelect` and +/// `checkExternalDictionaryLoadQueryIsSelect`: for a dictionary created by `CREATE DICTIONARY`, unless the server setting +/// `dictionaries_external_source_queries_select_only` is disabled. A dictionary from the server configuration is written +/// by the administrator, so it is not checked. +bool shouldCheckExternalDictionaryQueries(const ContextPtr & context, bool created_from_ddl); + +/// Checks the load query of a source of an external database, see `checkExternalDictionaryQueryIsSelect`. It is checked once, +/// when the source is created. The lookups of `direct` and `cache` layouts add to it a condition on the requested keys, which +/// comes from the caller of `dictGet`, not from the definition, so it is not checked here: the escaping of the keys is unchanged. +void checkExternalDictionaryLoadQueryIsSelect(const String & load_all_query, const String & source_name); + +/// The condition on the requested keys replaces `{condition}` in `query`, so `{condition}` cannot be in a string literal or +/// a quoted identifier: there, the quotes of the condition would end the quoted token of the definition, and the keys, which +/// come from the caller of `dictGet`, would become a part of the query. It is checked together with +/// `checkExternalDictionaryLoadQueryIsSelect`, which rejects comments and heredocs, where `{condition}` would be quoted too. +void checkExternalDictionaryQueryConditionPlaceholder(const String & query, const String & source_name); + /** A stream, adds additional columns to each block that it will read from inner stream. * * block_to_add rows size must be equal to final sum rows size of all inner stream blocks. diff --git a/src/Dictionaries/HTTPDictionarySource.cpp b/src/Dictionaries/HTTPDictionarySource.cpp index 6d7970523bef..394f3e10ea8e 100644 --- a/src/Dictionaries/HTTPDictionarySource.cpp +++ b/src/Dictionaries/HTTPDictionarySource.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -118,9 +119,17 @@ void HTTPDictionarySource::getUpdateFieldAndDate(Poco::URI & uri) } } +void HTTPDictionarySource::checkCredentials() const +{ + /// Per request: a loaded source is kept and cloned across updates, and can change meanwhile. + if (configuration.created_from_ddl) + context->getHTTPHeaderFilter().checkBasicCredentials(credentials); +} + BlockIO HTTPDictionarySource::loadAll() { LOG_TRACE(log, "loadAll {}", toString()); + checkCredentials(); Poco::URI uri(configuration.url); @@ -138,9 +147,12 @@ BlockIO HTTPDictionarySource::loadAll() BlockIO HTTPDictionarySource::loadUpdatedAll() { + checkCredentials(); Poco::URI uri(configuration.url); getUpdateFieldAndDate(uri); - LOG_TRACE(log, "loadUpdatedAll {}", uri.toString()); + String masked_uri = uri.toString(); + maskURICredentials(masked_uri); + LOG_TRACE(log, "loadUpdatedAll {}", masked_uri); auto buf = BuilderRWBufferFromHTTP(uri) .withConnectionGroup(HTTPConnectionGroupType::STORAGE) @@ -158,6 +170,7 @@ BlockIO HTTPDictionarySource::loadUpdatedAll() BlockIO HTTPDictionarySource::loadIds(const VectorWithMemoryTracking & ids) { LOG_TRACE(log, "loadIds {} size = {}", toString(), ids.size()); + checkCredentials(); auto block = blockForIds(dict_struct, ids); @@ -189,6 +202,7 @@ BlockIO HTTPDictionarySource::loadIds(const VectorWithMemoryTracking & i BlockIO HTTPDictionarySource::loadKeys(const Columns & key_columns, const VectorWithMemoryTracking & requested_rows) { LOG_TRACE(log, "loadKeys {} size = {}", toString(), requested_rows.size()); + checkCredentials(); auto block = blockForKeys(dict_struct, key_columns, requested_rows); @@ -239,8 +253,10 @@ DictionarySourcePtr HTTPDictionarySource::clone() const std::string HTTPDictionarySource::toString() const { - Poco::URI uri(configuration.url); - return uri.toString(); + /// Shown in `system.dictionaries` and in the logs. + String uri = Poco::URI(configuration.url).toString(); + maskURICredentials(uri); + return uri; } void registerDictionarySourceHTTP(DictionarySourceFactory & factory); @@ -345,7 +361,8 @@ void registerDictionarySourceHTTP(DictionarySourceFactory & factory) .format = format, .update_field = config.getString(settings_config_prefix + ".update_field", ""), .update_lag = config.getUInt64(settings_config_prefix + ".update_lag", 1), - .header_entries = std::move(header_entries) + .header_entries = std::move(header_entries), + .created_from_ddl = created_from_ddl }; return std::make_unique(dict_struct, configuration, credentials, sample_block, context); diff --git a/src/Dictionaries/HTTPDictionarySource.h b/src/Dictionaries/HTTPDictionarySource.h index b3638051ec24..2a9b845846f6 100644 --- a/src/Dictionaries/HTTPDictionarySource.h +++ b/src/Dictionaries/HTTPDictionarySource.h @@ -31,6 +31,8 @@ class HTTPDictionarySource final : public IDictionarySource const std::string update_field; const UInt64 update_lag; const HTTPHeaderEntries header_entries; + /// Whether the dictionary was created via DDL (`CREATE DICTIONARY`). + const bool created_from_ddl = false; }; HTTPDictionarySource( @@ -64,6 +66,8 @@ class HTTPDictionarySource final : public IDictionarySource private: void getUpdateFieldAndDate(Poco::URI & uri); + void checkCredentials() const; + // wrap buffer using encoding from made request QueryPipeline createWrappedBuffer(std::unique_ptr http_buffer); diff --git a/src/Dictionaries/IDictionary.h b/src/Dictionaries/IDictionary.h index b027d31eabcf..0b6105f8c451 100644 --- a/src/Dictionaries/IDictionary.h +++ b/src/Dictionaries/IDictionary.h @@ -103,7 +103,12 @@ class IDictionary : public IExternalLoadable, public IKeyValueEntity std::string getDatabaseOrNoDatabaseTag() const { std::lock_guard lock{mutex}; + return getDatabaseOrNoDatabaseTag(dictionary_id); + } + /// The database name used for access checks of the dictionary with the given ID. + static std::string getDatabaseOrNoDatabaseTag(const StorageID & dictionary_id) + { if (!dictionary_id.database_name.empty()) return dictionary_id.database_name; @@ -371,17 +376,12 @@ class IDictionary : public IExternalLoadable, public IKeyValueEntity key_types.emplace_back(key.type); } - /// Normalize wrapper-compatible key columns to the declared key schema via `convertKeyColumns`. - /// Track NULL rows and unwrap the outer `Nullable` first: casting a real NULL to a - /// non-Nullable declared type would throw. + /// Prepare probe keys as `HashJoin` does: dictionary sources read key columns as plain columns, so drop + /// `Const`/`Sparse`/`ColumnReplicated` and `LowCardinality`. Track NULL rows and unwrap the outer `Nullable` + /// before `convertKeyColumns`: casting a real NULL to a non-Nullable declared type would throw. PaddedPODArray key_row_is_null; for (size_t i = 0; i < key_columns.size(); ++i) { - if (!isNullableOrLowCardinalityNullable(key_types[i])) - continue; - - /// Drop `Const`/`Sparse`/`ColumnReplicated` and `LowCardinality` (as `HashJoin` prepares - /// probe keys) so the null map is exposed, then peel off the outer `Nullable`. ColumnPtr full_column = recursiveRemoveLowCardinality(removeSpecialRepresentations(key_columns[i]->convertToFullColumnIfConst())); DataTypePtr full_type = recursiveRemoveLowCardinality(key_types[i]); diff --git a/src/Dictionaries/MongoDBDictionarySource.cpp b/src/Dictionaries/MongoDBDictionarySource.cpp index 6ff705c680eb..dbbaa9ee214e 100644 --- a/src/Dictionaries/MongoDBDictionarySource.cpp +++ b/src/Dictionaries/MongoDBDictionarySource.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -293,7 +294,10 @@ BlockIO MongoDBDictionarySource::loadKeys(const Columns & key_columns, const Vec std::string MongoDBDictionarySource::toString() const { - return fmt::format("MongoDB: {}", configuration->uri->to_string()); + /// Shown in `system.dictionaries` and in the logs. + String uri = configuration->uri->to_string(); + maskURIPassword(&uri); + return fmt::format("MongoDB: {}", uri); } #endif diff --git a/src/Dictionaries/MySQLDictionarySource.cpp b/src/Dictionaries/MySQLDictionarySource.cpp index 391d4de23300..dd141de3969c 100644 --- a/src/Dictionaries/MySQLDictionarySource.cpp +++ b/src/Dictionaries/MySQLDictionarySource.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -173,6 +174,7 @@ void registerDictionarySourceMysql(DictionarySourceFactory & factory) .update_field = named_collection->getOrDefault("update_field", ""), .update_lag = named_collection->getOrDefault("update_lag", 1), .bg_reconnect = named_collection->getOrDefault("background_reconnect", false), + .check_queries_are_select = shouldCheckExternalDictionaryQueries(global_context, created_from_ddl), }); const auto & settings = global_context->getSettingsRef(); @@ -203,6 +205,7 @@ void registerDictionarySourceMysql(DictionarySourceFactory & factory) .update_field = config.getString(settings_config_prefix + ".update_field", ""), .update_lag = config.getUInt64(settings_config_prefix + ".update_lag", 1), .bg_reconnect = config.getBool(settings_config_prefix + ".background_reconnect", false), + .check_queries_are_select = shouldCheckExternalDictionaryQueries(global_context, created_from_ddl), }); if (created_from_ddl) @@ -426,6 +429,11 @@ MySQLDictionarySource::MySQLDictionarySource( , load_all_query(query_builder.composeLoadAllQuery()) , settings(settings_) { + if (configuration.check_queries_are_select) + { + checkExternalDictionaryQueryConditionPlaceholder(configuration.query, "MySQL"); + checkExternalDictionaryLoadQueryIsSelect(load_all_query, "MySQL"); + } } /// copy-constructor is provided in order to support cloneability @@ -474,6 +482,8 @@ BlockIO MySQLDictionarySource::loadAll() BlockIO MySQLDictionarySource::loadUpdatedAll() { std::string load_update_query = getUpdateFieldAndDate(); + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(load_update_query, "Update query for MySQL dictionary", "Only SELECT query can be used as a dictionary source"); LOG_TRACE(log, fmt::runtime(load_update_query)); BlockIO io; io.pipeline = loadFromQuery(load_update_query); @@ -550,6 +560,9 @@ std::string MySQLDictionarySource::quoteForLike(const std::string & value) std::string MySQLDictionarySource::doInvalidateQuery(const std::string & request) const { + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(request, "Invalidate query for MySQL dictionary", "Only SELECT query can be used as a dictionary invalidate query"); + Block invalidate_sample_block; ColumnPtr column(ColumnString::create()); invalidate_sample_block.insert(ColumnWithTypeAndName(column, std::make_shared(), "Sample Block")); diff --git a/src/Dictionaries/MySQLDictionarySource.h b/src/Dictionaries/MySQLDictionarySource.h index b0aba4353f85..5264460f3d99 100644 --- a/src/Dictionaries/MySQLDictionarySource.h +++ b/src/Dictionaries/MySQLDictionarySource.h @@ -40,6 +40,8 @@ class MySQLDictionarySource final : public IDictionarySource const std::string update_field; const UInt64 update_lag; const bool bg_reconnect; + /// See `shouldCheckExternalDictionaryQueries`. + const bool check_queries_are_select; }; MySQLDictionarySource( diff --git a/src/Dictionaries/PostgreSQLDictionarySource.cpp b/src/Dictionaries/PostgreSQLDictionarySource.cpp index 569130c092ac..890a1e1278aa 100644 --- a/src/Dictionaries/PostgreSQLDictionarySource.cpp +++ b/src/Dictionaries/PostgreSQLDictionarySource.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -98,6 +99,11 @@ PostgreSQLDictionarySource::PostgreSQLDictionarySource( , query_builder(makeExternalQueryBuilder(dict_struct, configuration.schema, configuration.table, configuration.query, configuration.where)) , load_all_query(query_builder.composeLoadAllQuery()) { + if (configuration.check_queries_are_select) + { + checkExternalDictionaryQueryConditionPlaceholder(configuration.query, "PostgreSQL"); + checkExternalDictionaryLoadQueryIsSelect(load_all_query, "PostgreSQL"); + } } @@ -128,6 +134,8 @@ BlockIO PostgreSQLDictionarySource::loadAll() BlockIO PostgreSQLDictionarySource::loadUpdatedAll() { auto load_update_query = getUpdateFieldAndDate(); + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(load_update_query, "Update query for PostgreSQL dictionary", "Only SELECT query can be used as a dictionary source"); LOG_TRACE(log, fmt::runtime(load_update_query)); BlockIO io; io.pipeline = loadBase(load_update_query); @@ -171,6 +179,9 @@ bool PostgreSQLDictionarySource::isModified() const std::string PostgreSQLDictionarySource::doInvalidateQuery(const std::string & request) const { + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(request, "Invalidate query for PostgreSQL dictionary", "Only SELECT query can be used as a dictionary invalidate query"); + Block invalidate_sample_block; ColumnPtr column(ColumnString::create()); invalidate_sample_block.insert(ColumnWithTypeAndName(column, std::make_shared(), "Sample Block")); @@ -284,6 +295,7 @@ void registerDictionarySourcePostgreSQL(DictionarySourceFactory & factory) .invalidate_query = named_collection->getOrDefault("invalidate_query", ""), .update_field = named_collection->getOrDefault("update_field", ""), .update_lag = named_collection->getOrDefault("update_lag", 1), + .check_queries_are_select = shouldCheckExternalDictionaryQueries(context, created_from_ddl), }); bg_reconnect = named_collection->getOrDefault("background_reconnect", false); @@ -319,7 +331,8 @@ void registerDictionarySourcePostgreSQL(DictionarySourceFactory & factory) .where = config.getString(fmt::format("{}.where", settings_config_prefix), ""), .invalidate_query = config.getString(fmt::format("{}.invalidate_query", settings_config_prefix), ""), .update_field = config.getString(fmt::format("{}.update_field", settings_config_prefix), ""), - .update_lag = config.getUInt64(fmt::format("{}.update_lag", settings_config_prefix), 1) + .update_lag = config.getUInt64(fmt::format("{}.update_lag", settings_config_prefix), 1), + .check_queries_are_select = shouldCheckExternalDictionaryQueries(context, created_from_ddl), }); bg_reconnect = config.getBool(fmt::format("{}.background_reconnect", settings_config_prefix), false); diff --git a/src/Dictionaries/PostgreSQLDictionarySource.h b/src/Dictionaries/PostgreSQLDictionarySource.h index 8e72c3e82ebc..91efa61999e2 100644 --- a/src/Dictionaries/PostgreSQLDictionarySource.h +++ b/src/Dictionaries/PostgreSQLDictionarySource.h @@ -29,6 +29,8 @@ class PostgreSQLDictionarySource final : public IDictionarySource const String invalidate_query; const String update_field; const UInt64 update_lag; + /// See `shouldCheckExternalDictionaryQueries`. + const bool check_queries_are_select; }; PostgreSQLDictionarySource( diff --git a/src/Dictionaries/RegExpTreeDictionary.cpp b/src/Dictionaries/RegExpTreeDictionary.cpp index 2c7bc18843b4..6fc76c3f74a2 100644 --- a/src/Dictionaries/RegExpTreeDictionary.cpp +++ b/src/Dictionaries/RegExpTreeDictionary.cpp @@ -225,6 +225,13 @@ void RegExpTreeDictionary::initRegexNodes(Block & block) Array keys = (*keys_column)[i].safeGet(); Array values = (*values_column)[i].safeGet(); + + /// Unlike the YAML source, a source table does not guarantee that every key has a value. + if (keys.size() != values.size()) + throw Exception(ErrorCodes::INCORRECT_DICTIONARY_DEFINITION, + "The sizes of `keys` ({}) and `values` ({}) are different for the regexp tree node with id {}", + keys.size(), values.size(), id); + size_t keys_size = keys.size(); for (size_t j = 0; j < keys_size; j++) { @@ -1190,7 +1197,7 @@ The schema of dumped file is: - `parent_id UInt64`: the id of the parent of a node. - `regexp String`: the regular expression string. - `keys Array(String)`: the names of user-defined attributes. -- `values Array(String)`: the values of user-defined attributes. +- `values Array(String)`: the values of user-defined attributes, in the same order as `keys`. Both arrays must have the same size. To create the dictionary in ClickHouse Cloud, first create a table `regexp_dictionary_source_table` with below table structure: diff --git a/src/Dictionaries/XDBCDictionarySource.cpp b/src/Dictionaries/XDBCDictionarySource.cpp index a2e10a216b5a..b96956639666 100644 --- a/src/Dictionaries/XDBCDictionarySource.cpp +++ b/src/Dictionaries/XDBCDictionarySource.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -90,6 +91,12 @@ XDBCDictionarySource::XDBCDictionarySource( auto url_params = bridge_helper->getURLParams(max_block_size); for (const auto & [name, value] : url_params) bridge_url.addQueryParameter(name, value); + + if (configuration.check_queries_are_select) + { + checkExternalDictionaryQueryConditionPlaceholder(configuration.query, "ODBC"); + checkExternalDictionaryLoadQueryIsSelect(load_all_query, "ODBC"); + } } /// copy-constructor is provided in order to support cloneability @@ -137,6 +144,8 @@ BlockIO XDBCDictionarySource::loadAll() BlockIO XDBCDictionarySource::loadUpdatedAll() { std::string load_query_update = getUpdateFieldAndDate(); + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(load_query_update, "Update query for ODBC dictionary", "Only SELECT query can be used as a dictionary source"); LOG_TRACE(log, fmt::runtime(load_query_update)); BlockIO io; @@ -201,6 +210,9 @@ bool XDBCDictionarySource::isModified() const std::string XDBCDictionarySource::doInvalidateQuery(const std::string & request) const { + if (configuration.check_queries_are_select) + checkExternalDictionaryQueryIsSelect(request, "Invalidate query for ODBC dictionary", "Only SELECT query can be used as a dictionary invalidate query"); + Block invalidate_sample_block; ColumnPtr column(ColumnString::create()); invalidate_sample_block.insert(ColumnWithTypeAndName(column, std::make_shared(), "Sample Block")); @@ -251,7 +263,7 @@ void registerDictionarySourceXDBC(DictionarySourceFactory & factory) Block & sample_block, ContextPtr global_context, const std::string & /* default_database */, - bool /* check_config */) -> DictionarySourcePtr { + bool created_from_ddl) -> DictionarySourcePtr { if (global_context->getSettingsRef()[Setting::cloud_mode]) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Dictionary source of type `odbc` is disabled"); @@ -274,7 +286,8 @@ void registerDictionarySourceXDBC(DictionarySourceFactory & factory) .where = config.getString(settings_config_prefix + ".where", ""), .invalidate_query = config.getString(settings_config_prefix + ".invalidate_query", ""), .update_field = config.getString(settings_config_prefix + ".update_field", ""), - .update_lag = config.getUInt64(settings_config_prefix + ".update_lag", 1) + .update_lag = config.getUInt64(settings_config_prefix + ".update_lag", 1), + .check_queries_are_select = shouldCheckExternalDictionaryQueries(global_context, created_from_ddl), }; return std::make_unique(dict_struct, configuration, sample_block, global_context, bridge); diff --git a/src/Dictionaries/XDBCDictionarySource.h b/src/Dictionaries/XDBCDictionarySource.h index 7de694e9c715..61a517114366 100644 --- a/src/Dictionaries/XDBCDictionarySource.h +++ b/src/Dictionaries/XDBCDictionarySource.h @@ -37,6 +37,8 @@ class XDBCDictionarySource final : public IDictionarySource, WithContext const std::string invalidate_query; const std::string update_field; const UInt64 update_lag; + /// See `shouldCheckExternalDictionaryQueries`. + const bool check_queries_are_select; }; XDBCDictionarySource( diff --git a/src/Disks/DiskEncrypted.cpp b/src/Disks/DiskEncrypted.cpp index 5b275eec0cdb..655fd2d4fdb5 100644 --- a/src/Disks/DiskEncrypted.cpp +++ b/src/Disks/DiskEncrypted.cpp @@ -2,6 +2,7 @@ #if USE_SSL #include +#include #include #include #include @@ -16,10 +17,14 @@ #include #include #include + #if CLICKHOUSE_CLOUD #include #endif +#include +#include + namespace DB { @@ -188,6 +193,16 @@ namespace return parseAlgorithmFromString(config.getString(path)); } + void checkCustomDiskPathIsInsideWrappedDisk(const String & path) + { + std::filesystem::path fs_path(path); + if (fs_path.is_absolute() || std::ranges::any_of(fs_path, [](const auto & component) { return component == ".."; })) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Path of the encrypted custom disk must be relative to the wrapped disk and must not contain `..`, but got {}", + quoteString(path)); + } + /// Reads the name of a wrapped disk & the path on the wrapped disk and then finds that disk in a disk map. void getDiskAndPathFromConfig(const Poco::Util::AbstractConfiguration & config, const String & config_prefix, const DisksMap & map, DiskPtr & out_disk, String & out_path) @@ -532,11 +547,24 @@ void registerDiskEncrypted(DiskFactory & factory, bool global_skip_access_check) const String & name, const Poco::Util::AbstractConfiguration & config, const String & config_prefix, - ContextPtr, + ContextPtr context, const DisksMap & map, - bool, bool) -> DiskPtr + bool attach, + bool custom_disk) -> DiskPtr { bool skip_access_check = global_skip_access_check || config.getBool(config_prefix + ".skip_access_check", false); + + if (custom_disk && !attach) + { + DiskPtr wrapped_disk; + String path; + getDiskAndPathFromConfig(config, config_prefix, map, wrapped_disk, path); + + checkCustomDiskPathIsInsideWrappedDisk(path); + if (!wrapped_disk->isRemote()) + checkCustomLocalDiskPath(wrapped_disk->getPath() + path, context); + } + DiskPtr disk = std::make_shared(name, config, config_prefix, map); disk->startup(skip_access_check); return disk; diff --git a/src/Disks/DiskEncrypted.h b/src/Disks/DiskEncrypted.h index d7e445961a5c..feda11d2e0dc 100644 --- a/src/Disks/DiskEncrypted.h +++ b/src/Disks/DiskEncrypted.h @@ -322,6 +322,7 @@ class DiskEncrypted : public IDisk bool isBroken() const override { return delegate->isBroken(); } bool supportParallelWrite() const override { return delegate->supportParallelWrite(); } bool supportsHardLinks() const override { return delegate->supportsHardLinks(); } + bool prefersRecursiveRemoval() const override { return delegate->prefersRecursiveRemoval(); } bool supportsStat() const override { return delegate->supportsStat(); } bool supportsChmod() const override { return delegate->supportsChmod(); } bool isSymlinkSupported() const override { return delegate->isSymlinkSupported(); } diff --git a/src/Disks/DiskFromAST.cpp b/src/Disks/DiskFromAST.cpp index 4057e1092eed..e468875b1bcf 100644 --- a/src/Disks/DiskFromAST.cpp +++ b/src/Disks/DiskFromAST.cpp @@ -1,12 +1,11 @@ #include +#include +#include +#include #include #include -#include #include #include -#include -#include -#include #include #include #include @@ -19,6 +18,7 @@ #include #include +#include #include namespace DB @@ -157,6 +157,9 @@ static std::vector> getOrCreateCustomDisk( const auto disk_settings_hash = hashes[matches.front().first]; const auto & disk_name = matches.front().second; + if (!attach && (disk_name.empty() || disk_name == "." || disk_name == ".." || disk_name.contains('/'))) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Disk name cannot be empty, `.`, `..` or contain `/` ({})", disk_name); + auto disk = context->getOrCreateDisk(disk_name, [&](const DisksMap & disks_map) -> DiskPtr { /// A wrapper (`encrypted`, `cache`) names a disk another session may have created with the opt-in. It is looked up /// in the map the wrapper is created from, so that it cannot be registered in between. @@ -190,24 +193,6 @@ static std::vector> getOrCreateCustomDisk( "The disk `{}` is already configured as a custom disk in another table. It can't be redefined with different settings.", disk_name); - if (!attach && !disk->isRemote() && disk->getName() != "backup") - { - static constexpr auto custom_local_disks_base_dir_in_config = "custom_local_disks_base_directory"; - auto disk_path_expected_prefix = context->getConfigRef().getString(custom_local_disks_base_dir_in_config, ""); - - if (disk_path_expected_prefix.empty()) - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Base path for custom local disks must be defined in config file by `{}`", - custom_local_disks_base_dir_in_config); - - if (!pathStartsWith(disk->getPath(), disk_path_expected_prefix)) - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Path of the custom local disk must be inside `{}` directory", - disk_path_expected_prefix); - } - /// The disk may have been created by a session with the opt-in, from a configuration that resolved differently then /// (`include` or `from_zk` changed since), so the check of this session's definition does not cover it. if (restricted && disk->customDiskUsesServerCredentials()) diff --git a/src/Disks/DiskLocal.cpp b/src/Disks/DiskLocal.cpp index 777476bd061b..85d94e6de11c 100644 --- a/src/Disks/DiskLocal.cpp +++ b/src/Disks/DiskLocal.cpp @@ -802,12 +802,16 @@ void registerDiskLocal(DiskFactory & factory, bool global_skip_access_check) const String & config_prefix, ContextPtr context, const DisksMap & map, - bool, bool) -> DiskPtr + bool attach, + bool custom_disk) -> DiskPtr { String path; UInt64 keep_free_space_bytes = 0; loadDiskLocalConfig(name, config, config_prefix, context, path, keep_free_space_bytes); + if (custom_disk && !attach) + checkCustomLocalDiskPath(path, context); + for (const auto & [disk_name, disk_ptr] : map) if (path == disk_ptr->getPath()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Disk {} and disk {} cannot have the same path ({})", name, disk_name, path); diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp b/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp index b9da7ca786d6..f0fab90ea46c 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/DiskObjectStorage.cpp @@ -38,6 +38,7 @@ #include #include #include +#include namespace CurrentMetrics { @@ -522,6 +523,15 @@ time_t DiskObjectStorage::getLastChanged(const String & path) const return metadata_storage->getLastChanged(path); } +bool DiskObjectStorage::isRemote() const +{ + for (const auto & location : cluster->getEnabledLocations()) + if (object_storages->takePointingTo(location)->isRemote()) + return true; + + return metadata_storage->isRemote(); +} + struct stat DiskObjectStorage::stat(const String & path) const { return metadata_storage->stat(path); @@ -761,6 +771,13 @@ bool DiskObjectStorage::isWriteOnce() const return metadata_storage->isWriteOnce(); } +bool DiskObjectStorage::prefersRecursiveRemoval() const +{ + /// `plain_rewritable` copies the blob of every unlinked file so that the unlink can be undone, while its + /// recursive removal only rewrites the directory metadata and deletes all objects in bulk. + return metadata_storage->getType() == MetadataStorageType::PlainRewritable; +} + bool DiskObjectStorage::isSharedCompatible() const { switch (object_storages->takePointingTo(cluster->getLocalLocation())->getType()) diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorage.h b/src/Disks/DiskObjectStorage/DiskObjectStorage.h index 441ab98b6048..376d1820aac3 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorage.h +++ b/src/Disks/DiskObjectStorage/DiskObjectStorage.h @@ -148,7 +148,7 @@ friend class DiskObjectStorageReservation; time_t getLastChanged(const String & path) const override; - bool isRemote() const override { return true; } + bool isRemote() const override; void shutdown() override; @@ -216,6 +216,8 @@ friend class DiskObjectStorageReservation; /// MergeTree table on this disk. bool isWriteOnce() const override; + bool prefersRecursiveRemoval() const override; + /// Return true if the disk is "shared-compatible", i.e. does not uses local disks bool isSharedCompatible() const; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp index d5c308dc8bea..7fce1786caf8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp @@ -184,6 +184,11 @@ bool MetadataStorageFromCacheObjectStorage::isReadOnly() const return underlying->isReadOnly(); } +bool MetadataStorageFromCacheObjectStorage::isRemote() const +{ + return underlying->isRemote(); +} + bool MetadataStorageFromCacheObjectStorage::isTransactional() const { return underlying->isTransactional(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h index 3c0944561a01..ee22886472b1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.h @@ -66,6 +66,7 @@ class MetadataStorageFromCacheObjectStorage : public IMetadataStorage std::optional getStorageObjectsIfExist(const std::string & path) const override; bool isReadOnly() const override; + bool isRemote() const override; bool isTransactional() const override; bool isPlain() const override; bool isWriteOnce() const override; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h index 98ea21201c70..a98fbdb27c5b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h @@ -295,6 +295,7 @@ class IMetadataStorage : private boost::noncopyable } virtual bool isReadOnly() const = 0; + virtual bool isRemote() const = 0; /// True if transactions apply operations immediately instead of accumulating them until commit. virtual bool appliesOperationsEagerly() const diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h b/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h index 5b144e690b5f..2e34b122ae98 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h @@ -116,6 +116,7 @@ class MetadataStorageFromDisk final : public IMetadataStorage DiskObjectStorageMetadataPtr readMetadataUnlocked(const std::string & path, std::shared_lock & lock) const; bool isReadOnly() const override { return disk->isReadOnly(); } + bool isRemote() const override { return disk->isRemote(); } void startup() override; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Memory/MetadataStorageFromMemory.h b/src/Disks/DiskObjectStorage/MetadataStorages/Memory/MetadataStorageFromMemory.h index e3785499afc8..974e5ab56f52 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Memory/MetadataStorageFromMemory.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Memory/MetadataStorageFromMemory.h @@ -76,6 +76,7 @@ class MetadataStorageFromMemory final : public IMetadataStorage bool supportsChmod() const override { return false; } bool isReadOnly() const override { return false; } + bool isRemote() const override { return false; } bool areBlobPathsRandom() const override { return true; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp index 1b16157562b1..ed0117d1be1c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include @@ -101,7 +102,8 @@ MetadataStoragePtr MetadataStorageFactory::create( const std::string & config_prefix, const ClusterConfigurationPtr & cluster, const ObjectStorageRouterPtr & object_storages, - const std::string & compatibility_type_hint) const + const std::string & compatibility_type_hint, + bool run_local_paths_check) const { const auto type = getMetadataType(config, config_prefix, compatibility_type_hint); const auto it = registry.find(type); @@ -112,7 +114,7 @@ MetadataStoragePtr MetadataStorageFactory::create( "MetadataStorageFactory: unknown metadata storage type: {}", type); } - return it->second(name, config, config_prefix, cluster, object_storages); + return it->second(name, config, config_prefix, cluster, object_storages, run_local_paths_check); } static void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) @@ -122,7 +124,8 @@ static void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool run_local_paths_check) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -130,6 +133,9 @@ static void registerMetadataStorageFromDisk(MetadataStorageFactory & factory) fs::path(Context::getGlobalContextInstance()->getPath()) / "disks" / name / ""); auto metadata_keep_free_space_bytes = config.getUInt64(config_prefix + ".metadata_keep_free_space_bytes", 0); + if (run_local_paths_check && config.has(config_prefix + ".metadata_path")) + checkCustomLocalDiskPath(metadata_path, Context::getGlobalContextInstance()); + fs::create_directories(metadata_path); const auto db_disk = std::make_shared(name + "-metadata", metadata_path, metadata_keep_free_space_bytes, config, config_prefix); const auto local_object_storage = object_storages->takePointingTo(cluster->getLocalLocation()); @@ -150,7 +156,8 @@ static void registerMetadataStorageFromKeeper(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { auto component_guard = Coordination::setCurrentComponent("registerMetadataStorageFromKeeper"); LOG_INFO(getLogger("registerDiskS3"), "Using DiskS3 with metadata keeper"); @@ -176,7 +183,8 @@ static void registerPlainMetadataStorage(MetadataStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -195,7 +203,8 @@ static void registerPlainRewritableMetadataStorage(MetadataStorageFactory & fact const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -213,7 +222,8 @@ static void registerMetadataStorageFromStaticFilesWebServer(MetadataStorageFacto const Poco::Util::AbstractConfiguration & /* config */, const std::string & /* config_prefix */, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); @@ -230,7 +240,8 @@ static void registerMetadataStorageFromIndexPages(MetadataStorageFactory & facto const Poco::Util::AbstractConfiguration & /* config */, const std::string & /* config_prefix */, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages) -> MetadataStoragePtr + const ObjectStorageRouterPtr & object_storages, + bool /* run_local_paths_check */) -> MetadataStoragePtr { checkSingleLocation(cluster); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h index 687394a4357d..9aa72aa4eb74 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/MetadataStorageFactory.h @@ -17,7 +17,8 @@ class MetadataStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ClusterConfigurationPtr & cluster, - const ObjectStorageRouterPtr & object_storages)>; + const ObjectStorageRouterPtr & object_storages, + bool run_local_paths_check)>; static MetadataStorageFactory & instance(); @@ -29,7 +30,8 @@ class MetadataStorageFactory final : private boost::noncopyable const std::string & config_prefix, const ClusterConfigurationPtr & cluster, const ObjectStorageRouterPtr & object_storages, - const std::string & compatibility_type_hint) const; + const std::string & compatibility_type_hint, + bool run_local_paths_check) const; static std::string getMetadataType( const Poco::Util::AbstractConfiguration & config, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h index eb29e71341cf..e214f0bb6b2f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Plain/MetadataStorageFromPlainObjectStorage.h @@ -47,6 +47,7 @@ class MetadataStorageFromPlainObjectStorage : public IMetadataStorage bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return false; } + bool isRemote() const override { return object_storage->isRemote(); } bool areBlobPathsRandom() const override { return false; } bool isPlain() const override { return true; } bool isWriteOnce() const override { return true; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h index dc281e607536..2c68ba1d7cd4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.h @@ -51,6 +51,7 @@ class MetadataStorageFromPlainRewritableObjectStorage final : public IMetadataSt bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return false; } + bool isRemote() const override { return object_storage->isRemote(); } bool areBlobPathsRandom() const override { return false; } bool isPlain() const override { return true; } bool isWriteOnce() const override { return false; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp index 7199a17b15e0..919bcbae0fc4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp @@ -646,11 +646,8 @@ MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::MetadataStorageFr void MetadataStorageFromPlainObjectStorageRemoveRecursiveOperation::execute() { - /// Unfortunately we are able to create merge tree unlinked from database directory. - /// In this case during the dropAllData method removeRecursive can be called pointing to the root folder. - /// I don't know what to do in this case, so right now it is a no-op. if (normalizePath(path).empty()) - return; + throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't remove root folder"); if (fs_tree->existsDirectory(path)) { diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.cpp index fab68ee8262f..92d003995be4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -225,6 +226,13 @@ namespace return path; } + /// Listing URLs keep the source URL's userinfo for authentication, so only a masked copy may be formatted. + std::string maskedURL(std::string url) + { + maskURICredentials(url); + return url; + } + void rejectOriginChangingRedirect(const std::string & requested_url, const std::string & final_url) { const Poco::URI requested_uri(requested_url, false); @@ -233,8 +241,8 @@ namespace throw Exception( ErrorCodes::BAD_ARGUMENTS, "Index page '{}' was redirected to a different origin '{}'", - requested_url, - final_url); + maskedURL(requested_url), + maskedURL(final_url)); } using WebIndexPage::getEffectiveRelativePathForDeduplication; @@ -352,7 +360,8 @@ std::vector MetadataStorageFromIndexPages::makeListingURLs(const st return object_storage.buildURLs(ensureTrailingSlashInPath(stripLeadingSlash(path)), shard_index); } -MetadataStorageFromIndexPages::IndexPage MetadataStorageFromIndexPages::readIndexPage(const std::string & url) const +MetadataStorageFromIndexPages::IndexPage MetadataStorageFromIndexPages::readIndexPage( + const Poco::URI & uri, const Poco::Net::HTTPBasicCredentials & credentials) const { const auto request_context = object_storage.getRequestContext(); const auto & settings = request_context->getSettingsRef(); @@ -361,10 +370,6 @@ MetadataStorageFromIndexPages::IndexPage MetadataStorageFromIndexPages::readInde /// Carry the same HTTP request semantics as direct `url()` reads: honor `enable_url_encoding`, /// follow up to `max_http_get_redirects` redirects, and authenticate with credentials parsed from /// the URL's userinfo (e.g. `http://user:pass@host`). - Poco::URI uri(url, enable_url_encoding); - Poco::Net::HTTPBasicCredentials credentials; - setCredentialsFromURL(credentials, uri); - auto timeouts = ConnectionTimeouts::getHTTPTimeouts( settings, request_context->getServerSettings()); @@ -546,6 +551,9 @@ bool MetadataStorageFromIndexPages::tryListDirectory( bool has_listed_directory = false; + const auto request_context = object_storage.getRequestContext(); + const bool enable_url_encoding = request_context->getSettingsRef()[Setting::enable_url_encoding]; + const auto first_shard_index = requested_shard_index.value_or(0); const auto end_shard_index = requested_shard_index ? *requested_shard_index + 1 : url_shards.size(); @@ -560,9 +568,12 @@ bool MetadataStorageFromIndexPages::tryListDirectory( for (size_t i = 0; i != listing_urls.size(); ++i) { const auto & listing_url = listing_urls[i]; + const Poco::URI listing_uri(listing_url, enable_url_encoding); + Poco::Net::HTTPBasicCredentials credentials; + setCredentialsFromURL(credentials, listing_uri, request_context->getHTTPHeaderFilter()); try { - auto index_page = readIndexPage(listing_url); + auto index_page = readIndexPage(listing_uri, credentials); rejectOriginChangingRedirect(listing_url, index_page.final_url); const auto final_listing_prefix_url = getListingPrefixURLForMatching(index_page.final_url); const auto final_path_prefix = WebIndexPage::getPathPrefixRelativeToBase( @@ -609,7 +620,7 @@ bool MetadataStorageFromIndexPages::tryListDirectory( { if (e.code() == ErrorCodes::CANNOT_READ_ALL_DATA) shard_exception = std::make_exception_ptr( - Exception(ErrorCodes::BAD_ARGUMENTS, "Index page '{}' exceeds max_http_index_page_size", listing_url)); + Exception(ErrorCodes::BAD_ARGUMENTS, "Index page '{}' exceeds max_http_index_page_size", maskedURL(listing_url))); else shard_exception = std::current_exception(); } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.h b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.h index 2e70423c9694..6b3d7677d87a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromIndexPages.h @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -25,7 +26,7 @@ class MetadataStorageFromIndexPages final : public IMetadataStorage }; std::vector makeListingURLs(const std::string & path, size_t shard_index) const; - IndexPage readIndexPage(const std::string & url) const; + IndexPage readIndexPage(const Poco::URI & uri, const Poco::Net::HTTPBasicCredentials & credentials) const; std::vector extractURLs( const std::string & page_body, const std::string & listing_url, @@ -82,6 +83,7 @@ class MetadataStorageFromIndexPages final : public IMetadataStorage bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return true; } + bool isRemote() const override { return true; } bool areBlobPathsRandom() const override { return false; } }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h index 1f9f512d9c90..5b5e543d9369 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/Web/MetadataStorageFromStaticFilesWebServer.h @@ -113,6 +113,7 @@ class MetadataStorageFromStaticFilesWebServer final : public IMetadataStorage bool supportsChmod() const override { return false; } bool supportsStat() const override { return false; } bool isReadOnly() const override { return true; } + bool isRemote() const override { return true; } bool areBlobPathsRandom() const override { return false; } }; diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp index a1c63b02a460..21937ab19cb9 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.cpp @@ -79,7 +79,8 @@ ObjectStoragePtr ObjectStorageFactory::create( const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check) const { std::string type; @@ -100,7 +101,7 @@ ObjectStoragePtr ObjectStorageFactory::create( "ObjectStorageFactory: unknown object storage type: {}", type); } - return it->second(name, config, config_prefix, context, skip_access_check, remote_host_filter_check); + return it->second(name, config, config_prefix, context, run_access_check, run_local_paths_check, remote_host_filter_check); } /// A custom disk with an endpoint that remote_url_allow_hosts does not allow: a log line per disk @@ -176,7 +177,8 @@ static void registerS3ObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck remote_host_filter_check) -> ObjectStoragePtr { auto s3_capabilities = getCapabilitiesFromConfig(config, config_prefix); @@ -220,7 +222,8 @@ static void registerHDFSObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { auto uri = context->getMacros()->expand(config.getString(config_prefix + ".endpoint")); @@ -244,7 +247,8 @@ static void registerAzureObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck remote_host_filter_check) -> ObjectStoragePtr { auto azure_settings = AzureBlobStorage::getRequestSettings(config, config_prefix, context->getSettingsRef()); @@ -303,7 +307,8 @@ static void registerWebObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool /* run_local_paths_check */, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { auto uri = context->getMacros()->expand(config.getString(config_prefix + ".endpoint")); @@ -331,13 +336,17 @@ static void registerLocalObjectStorage(ObjectStorageFactory & factory) const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool /* skip_access_check */, + bool /* run_access_check */, + bool run_local_paths_check, RemoteHostFilterCheck /* remote_host_filter_check */) -> ObjectStoragePtr { String object_key_prefix; UInt64 keep_free_space_bytes = 0; loadDiskLocalConfig(name, config, config_prefix, context, object_key_prefix, keep_free_space_bytes); + if (run_local_paths_check) + checkCustomLocalDiskPath(object_key_prefix, context); + /// keys are mapped to the fs, object_key_prefix is a directory also fs::create_directories(object_key_prefix); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h index ace512c91f4c..c4dc7e1dc949 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h +++ b/src/Disks/DiskObjectStorage/ObjectStorages/ObjectStorageFactory.h @@ -24,7 +24,8 @@ class ObjectStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check)>; static ObjectStorageFactory & instance(); @@ -36,7 +37,8 @@ class ObjectStorageFactory final : private boost::noncopyable const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, const ContextPtr & context, - bool skip_access_check, + bool run_access_check, + bool run_local_paths_check, RemoteHostFilterCheck remote_host_filter_check) const; void clearRegistry(); diff --git a/src/Disks/DiskObjectStorage/ObjectStorages/Web/WebObjectStorage.cpp b/src/Disks/DiskObjectStorage/ObjectStorages/Web/WebObjectStorage.cpp index 25691872cd1f..96d2497e8d4e 100644 --- a/src/Disks/DiskObjectStorage/ObjectStorages/Web/WebObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/ObjectStorages/Web/WebObjectStorage.cpp @@ -320,13 +320,10 @@ std::optional WebObjectStorage::tryGetObjectMetadata(const Relat settings, request_context->getServerSettings()); - auto get_metadata_from_uri = [&](const Poco::URI & uri) -> std::optional + auto get_metadata_from_uri = [&](const Poco::URI & uri, const Poco::Net::HTTPBasicCredentials & credentials) -> std::optional { /// Carry the same HTTP request semantics as direct `url()` reads: credentials from the URL /// userinfo, `max_http_get_redirects`, and `enable_url_encoding`. - Poco::Net::HTTPBasicCredentials credentials; - setCredentialsFromURL(credentials, uri); - auto create_probe_buffer = [&](const String & method) { auto read_settings = request_context->getReadSettings(); @@ -426,9 +423,12 @@ std::optional WebObjectStorage::tryGetObjectMetadata(const Relat auto urls = path.read_source_index ? buildURLs(path.getPath(), *path.read_source_index) : buildURLs(path.getPath()); for (const auto & url : urls) { + const Poco::URI uri(url, enable_url_encoding); + Poco::Net::HTTPBasicCredentials credentials; + setCredentialsFromURL(credentials, uri, request_context->getHTTPHeaderFilter()); try { - auto metadata = get_metadata_from_uri(Poco::URI(url, enable_url_encoding)); + auto metadata = get_metadata_from_uri(uri, credentials); if (metadata) return metadata; has_not_found = true; diff --git a/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp b/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp index 2abdba9f0ce4..cf8d247a4c1c 100644 --- a/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp +++ b/src/Disks/DiskObjectStorage/RegisterDiskObjectStorage.cpp @@ -30,7 +30,8 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch bool attach, bool custom_disk) -> DiskPtr { - const bool skip_access_check = global_skip_access_check || config.getBool(config_prefix + ".skip_access_check", false); + const bool run_access_check = !global_skip_access_check && !config.getBool(config_prefix + ".skip_access_check", false); + const bool run_local_paths_check = custom_disk && !attach; /// Custom disk from a query: a rejection throws. Custom disk loaded from existing metadata (attach: /// server start, UNDROP): a rejection is reported. A user ATTACH, short or with a definition, is not attach here. const auto remote_host_filter_check = !custom_disk ? RemoteHostFilterCheck::None @@ -49,14 +50,14 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch const std::string object_storage_config_prefix = config_prefix + ".locations." + location; const bool local = config.getBool(object_storage_config_prefix + ".local"); const bool enabled = config.getBool(object_storage_config_prefix + ".enabled"); - const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(fmt::format("{}.{}", name, location), config, object_storage_config_prefix, context, /*skip_access_check=*/skip_access_check || !enabled, remote_host_filter_check); + const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(fmt::format("{}.{}", name, location), config, object_storage_config_prefix, context, run_access_check && enabled, run_local_paths_check, remote_host_filter_check); object_storage_registry[location] = object_storage; cluster_registry[location] = {enabled, local, object_storage_config_prefix}; } } else { - const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(name, config, config_prefix, context, skip_access_check, remote_host_filter_check); + const ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create(name, config, config_prefix, context, run_access_check, run_local_paths_check, remote_host_filter_check); object_storage_registry["main"] = object_storage; cluster_registry["main"] = { .enabled = true, .local = true, .config_prefix = config_prefix }; } @@ -80,7 +81,7 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch } LOG_DEBUG(getLogger("registerDiskObjectStorage"), "Metadata type hint: {}", compatibility_metadata_type_hint); - auto metadata_storage = MetadataStorageFactory::instance().create(name, config, config_prefix, cluster, object_storages, compatibility_metadata_type_hint); + auto metadata_storage = MetadataStorageFactory::instance().create(name, config, config_prefix, cluster, object_storages, compatibility_metadata_type_hint, run_local_paths_check); DiskPtr disk = std::make_shared( name, @@ -99,7 +100,7 @@ void registerDiskObjectStorage(DiskFactory & factory, bool global_skip_access_ch disk = std::make_shared(disk); } - disk->startup(skip_access_check); + disk->startup(/*skip_access_check=*/!run_access_check); return disk; }; diff --git a/src/Disks/DiskType.cpp b/src/Disks/DiskType.cpp index d60ef273e263..93494850353e 100644 --- a/src/Disks/DiskType.cpp +++ b/src/Disks/DiskType.cpp @@ -1,7 +1,10 @@ #include -#include +#include + #include +#include + namespace DB { namespace ErrorCodes @@ -88,4 +91,13 @@ String DataSourceDescription::toString() const name(), description, is_encrypted, is_cached, zookeeper_name); } +bool isDiskObjectStorage(std::shared_ptr disk) +{ + while (auto delegate_disk = disk->getDelegateDiskIfExists()) + disk = delegate_disk; + + return std::dynamic_pointer_cast(disk) != nullptr; + +} + } diff --git a/src/Disks/DiskType.h b/src/Disks/DiskType.h index 778435581500..422fa1126518 100644 --- a/src/Disks/DiskType.h +++ b/src/Disks/DiskType.h @@ -61,4 +61,7 @@ struct DataSourceDescription String toString() const; }; +class IDisk; +bool isDiskObjectStorage(std::shared_ptr disk); + } diff --git a/src/Disks/IDisk.h b/src/Disks/IDisk.h index b7ce685fdc3d..7e70d4266e24 100644 --- a/src/Disks/IDisk.h +++ b/src/Disks/IDisk.h @@ -476,6 +476,9 @@ class IDisk : public Space virtual bool supportsHardLinks() const { return true; } + /// Whether removing a directory with `removeSharedRecursive` is cheaper than removing its files one by one. + virtual bool prefersRecursiveRemoval() const { return false; } + /// Check if disk is broken. Broken disks will have 0 space and cannot be used. virtual bool isBroken() const { return false; } diff --git a/src/Disks/IO/ReadBufferFromWebServer.cpp b/src/Disks/IO/ReadBufferFromWebServer.cpp index 0b71e0e4456b..e425b481e287 100644 --- a/src/Disks/IO/ReadBufferFromWebServer.cpp +++ b/src/Disks/IO/ReadBufferFromWebServer.cpp @@ -119,7 +119,7 @@ std::unique_ptr ReadBufferFromWebServer::initialize() /// `credentials` is a member so that it outlives the buffer created below, which stores a /// reference to it. With delayed initialization the HTTP request — and thus the read of these /// credentials — happens in `nextImpl`, long after `initialize` returns. - setCredentialsFromURL(credentials, uri); + setCredentialsFromURL(credentials, uri, context->getHTTPHeaderFilter()); try { /// External buffer reads require `delay_initialization = true`, which defers the HTTP diff --git a/src/Disks/MetadataStorageWithPathWrapper.h b/src/Disks/MetadataStorageWithPathWrapper.h index 0a6fe08ee6b4..fcd485652c4b 100644 --- a/src/Disks/MetadataStorageWithPathWrapper.h +++ b/src/Disks/MetadataStorageWithPathWrapper.h @@ -279,6 +279,11 @@ class MetadataStorageWithPathWrapper final : public IMetadataStorage return delegate->isReadOnly(); } + bool isRemote() const override + { + return delegate->isRemote(); + } + void updateCache(const std::vector & paths, bool recursive, bool enforce_fresh, std::string * serialized_cache_update_description) override { delegate->updateCache(wrappedPaths(paths), recursive, enforce_fresh, serialized_cache_update_description); diff --git a/src/Disks/ReadOnlyDiskWrapper.h b/src/Disks/ReadOnlyDiskWrapper.h index 784d84b0655c..e07c1ab8c8cc 100644 --- a/src/Disks/ReadOnlyDiskWrapper.h +++ b/src/Disks/ReadOnlyDiskWrapper.h @@ -104,6 +104,8 @@ class ReadOnlyDiskWrapper : public IDisk bool supportsChmod() const override { return delegate->supportsChmod(); } void chmod(const String & path, mode_t mode) override { delegate->chmod(path, mode); } + DiskPtr getDelegateDiskIfExists() const override { return delegate; } + bool isReadOnly() const override { return true; } std::unique_ptr writeFile(const String &, size_t, WriteMode, const WriteSettings &) override { throwNotAllowed(); } void moveFile(const String &, const String &) override { throwNotAllowed(); } diff --git a/src/Disks/loadLocalDiskConfig.cpp b/src/Disks/loadLocalDiskConfig.cpp index d3e0bbdf888b..8afdefbb0c7e 100644 --- a/src/Disks/loadLocalDiskConfig.cpp +++ b/src/Disks/loadLocalDiskConfig.cpp @@ -3,6 +3,7 @@ #include #include #include +#include namespace DB { @@ -11,6 +12,7 @@ namespace ErrorCodes { extern const int UNKNOWN_ELEMENT_IN_CONFIG; extern const int EXCESSIVE_ELEMENT_IN_CONFIG; + extern const int BAD_ARGUMENTS; } void loadDiskLocalConfig(const String & name, @@ -61,4 +63,22 @@ void loadDiskLocalConfig(const String & name, } } +void checkCustomLocalDiskPath(const String & path, ContextPtr context) +{ + static constexpr auto custom_local_disks_base_dir_in_config = "custom_local_disks_base_directory"; + auto disk_path_expected_prefix = context->getConfigRef().getString(custom_local_disks_base_dir_in_config, ""); + + if (disk_path_expected_prefix.empty()) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Base path for custom local disks must be defined in config file by `{}`", + custom_local_disks_base_dir_in_config); + + if (!pathStartsWith(path, disk_path_expected_prefix)) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Path of the custom local disk must be inside `{}` directory", + disk_path_expected_prefix); +} + } diff --git a/src/Disks/loadLocalDiskConfig.h b/src/Disks/loadLocalDiskConfig.h index ba1ac5378a4c..7a5ae1a6f83e 100644 --- a/src/Disks/loadLocalDiskConfig.h +++ b/src/Disks/loadLocalDiskConfig.h @@ -6,6 +6,7 @@ namespace Poco::Util { class AbstractConfiguration; } namespace DB { + void loadDiskLocalConfig( const String & name, const Poco::Util::AbstractConfiguration & config, @@ -13,4 +14,7 @@ void loadDiskLocalConfig( ContextPtr context, String & path, UInt64 & keep_free_space_bytes); + +void checkCustomLocalDiskPath(const String & path, ContextPtr context); + } diff --git a/src/Disks/tests/gtest_disk_object_storage.cpp b/src/Disks/tests/gtest_disk_object_storage.cpp index ec796521af4c..ac74dafa07b3 100644 --- a/src/Disks/tests/gtest_disk_object_storage.cpp +++ b/src/Disks/tests/gtest_disk_object_storage.cpp @@ -237,7 +237,7 @@ class DiskObjectStorageTest : public testing::Test getContext().context, initialized_disks, /*attach*/ false, - /*custom_disk*/ true, + /*custom_disk*/ false, /*skip_types*/ {}); initialized_disks.emplace(name, disk); diff --git a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp index 28da9e2c1f03..294c8d3554cf 100644 --- a/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp +++ b/src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp @@ -870,12 +870,6 @@ TEST_F(MetadataPlainRewritableDiskTest, RemoveRoot) EXPECT_ANY_THROW(tx->commit(DB::NoCommitOptions{})); } - { - auto tx = metadata->createTransaction(); - tx->removeRecursive("/", /*should_remove_blob=*/nullptr); - tx->commit(DB::NoCommitOptions{}); - } - EXPECT_EQ(listAllBlobs("RemoveRecursiveRoot"), std::vector({ "./RemoveRecursiveRoot/__root/A", "./RemoveRecursiveRoot/__root/B" diff --git a/src/Formats/CapnProtoSerializer.cpp b/src/Formats/CapnProtoSerializer.cpp index 089a928c796f..9091d10d4622 100644 --- a/src/Formats/CapnProtoSerializer.cpp +++ b/src/Formats/CapnProtoSerializer.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int CAPN_PROTO_BAD_CAST; extern const int INCORRECT_DATA; extern const int ILLEGAL_COLUMN; + extern const int SIZES_OF_ARRAYS_DONT_MATCH; } namespace @@ -96,17 +97,38 @@ namespace std::vector> field_builders; }; + /// A group (or a named union) is stored inline in its parent struct: it has no slot and shares the parent's storage. + bool isGroup(const capnp::StructSchema & schema) + { + return schema.getProto().getStruct().getIsGroup(); + } + + UInt32 getFieldSlotOffset(const capnp::StructSchema::Field & field) + { + auto proto = field.getProto(); + return proto.isSlot() ? proto.getSlot().getOffset() : 0; + } + template std::unique_ptr initStructBuilder(ParentBuilder & parent_builder, UInt32 offset_or_index, const capnp::_::StructSize & struct_size, size_t elements, const capnp::StructSchema & schema) { capnp::DynamicStruct::Builder builder_impl; if constexpr (std::is_same_v) - builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getPointerField(offset_or_index).initStruct(struct_size)); + { + auto parent_impl = parent_builder.getBuilderImpl(); + builder_impl = capnp::DynamicStruct::Builder(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(offset_or_index).initStruct(struct_size)); + } else builder_impl = capnp::DynamicStruct::Builder(schema, parent_builder.getBuilderImpl().getStructElement(offset_or_index)); return std::make_unique(std::move(builder_impl), elements); } + capnp::DynamicStruct::Reader getStructReader(const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset, const capnp::StructSchema & schema) + { + auto parent_impl = parent_struct_reader.getReaderImpl(); + return capnp::DynamicStruct::Reader(schema, isGroup(schema) ? parent_impl : parent_impl.getPointerField(slot_offset).getStruct(nullptr)); + } + class ICapnProtoSerializer { public: @@ -927,15 +949,18 @@ namespace auto first = union_fields[0]; auto second = union_fields[1]; auto nested_type = assert_cast(data_type.get())->getNestedType(); - nested_slot_offset = first.getProto().getSlot().getOffset(); /// Both fields have the same offset. + /// The offset of the value is taken from the non-`Void` member: `Void` always has offset 0, + /// while the value of a union declared inline in a struct can be in any slot of that struct. if (first.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(second); nested_serializer = createSerializer(nested_type, column_name, second.getType(), settings); null_discriminant = 0; nested_discriminant = 1; } else if (second.getType().isVoid()) { + nested_slot_offset = getFieldSlotOffset(first); nested_serializer = createSerializer(nested_type, column_name, first.getType(), settings); null_discriminant = 1; nested_discriminant = 0; @@ -961,7 +986,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -983,9 +1008,8 @@ namespace const auto & nullable_column = assert_cast(*column); if (nullable_column.isNullAt(row_num)) { - auto struct_builder_impl = struct_builder.impl.getBuilderImpl(); - struct_builder_impl.setDataField(discriminant_offset, null_discriminant); - struct_builder_impl.setDataField(nested_slot_offset, capnp::Void()); + /// `Void` occupies no space, so only the discriminant is written. + struct_builder.impl.getBuilderImpl().setDataField(discriminant_offset, null_discriminant); } else { @@ -1078,6 +1102,14 @@ namespace field_builder = std::make_unique(capnp::DynamicList::Builder(list_schema, initListBuilder(parent_builder, offset_or_index, size)), size); auto & list_builder = assert_cast(*field_builder); + /// Several columns with flattened names (like `l.x` and `l.y`) write to the same list. + if (list_builder.nested_builders.size() != size) + throw Exception( + ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH, + "Arrays that are written to the same CapnProto list have different sizes: {} and {}", + list_builder.nested_builders.size(), + size); + for (UInt32 i = 0; i != size; ++i) nested_serializer->writeRow(nested_column, list_builder.nested_builders[i], list_builder.impl, i, offset + i); } @@ -1198,7 +1230,7 @@ namespace Names names = {"key", "value"}; auto entries_type = std::make_shared(std::make_shared(types, names)); nested_serializer = createSerializer(entries_type, column_name, field_type, settings); - entries_slot_offset = struct_schema.getFields()[0].getProto().getSlot().getOffset(); + entries_slot_offset = getFieldSlotOffset(struct_schema.getFields()[0]); } void writeRow(const ColumnPtr & column, std::unique_ptr & field_builder, capnp::DynamicStruct::Builder & parent_struct_builder, UInt32 slot_offset, size_t row_num) override @@ -1213,7 +1245,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1273,6 +1305,7 @@ namespace data_type->getName(), getCapnProtoFullTypeName(capnp_type)); + is_tuple = true; const auto * tuple_data_type = assert_cast(data_type.get()); auto nested_types = tuple_data_type->getElements(); Names nested_names; @@ -1328,7 +1361,7 @@ namespace void readRow(IColumn & column, const capnp::DynamicStruct::Reader & parent_struct_reader, UInt32 slot_offset) override { - auto struct_reader = capnp::DynamicStruct::Reader(struct_schema, parent_struct_reader.getReaderImpl().getPointerField(slot_offset).getStruct(nullptr)); + auto struct_reader = getStructReader(parent_struct_reader, slot_offset, struct_schema); readRowImpl(column, struct_reader); } @@ -1363,7 +1396,7 @@ namespace auto capnp_type = field->getType(); fields_serializers.push_back(createSerializer(data_types[i], names[i], capnp_type, settings)); - fields_offsets.push_back(field->getProto().getSlot().getOffset()); + fields_offsets.push_back(getFieldSlotOffset(*field)); fields_indexes.push_back(field->getIndex()); } } @@ -1375,9 +1408,9 @@ namespace field_builder = initStructBuilder(parent_builder, offset_or_index, struct_size, fields_count, struct_schema); auto & struct_builder = assert_cast(*field_builder); - if (const auto * tuple_column = typeid_cast(column.get())) + if (is_tuple) { - const auto & columns = tuple_column->getColumns(); + const auto & columns = assert_cast(*column).getColumns(); for (size_t i = 0; i != columns.size(); ++i) fields_serializers[i]->writeRow(columns[i], struct_builder.field_builders[fields_indexes[i]], struct_builder.impl, fields_offsets[i], row_num); } @@ -1389,8 +1422,9 @@ namespace void readRowImpl(IColumn & column, const capnp::DynamicStruct::Reader & struct_reader) { - if (auto * tuple_column = typeid_cast(&column)) + if (is_tuple) { + auto * tuple_column = assert_cast(&column); auto read_tuple = [&]() { for (size_t i = 0; i != tuple_column->tupleSize(); ++i) @@ -1406,6 +1440,10 @@ namespace capnp::StructSchema struct_schema; capnp::_::StructSize struct_size{}; size_t fields_count{}; + /// True if the struct is mapped to a `Tuple` column, one field per tuple element. + /// Otherwise the serializer is the root one or an adapter for a flattened column name (`a.b`) + /// with a single field, which gets the whole column, even if the column itself is a `Tuple`. + bool is_tuple = false; std::vector> fields_serializers; std::vector fields_offsets; std::vector fields_indexes; diff --git a/src/Formats/FormatSchemaInfo.cpp b/src/Formats/FormatSchemaInfo.cpp index a59ea6fe5d12..91c8a554acff 100644 --- a/src/Formats/FormatSchemaInfo.cpp +++ b/src/Formats/FormatSchemaInfo.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -301,12 +300,8 @@ void FormatSchemaInfo::storeSchemaOnDisk(const fs::path & file_path, const Strin out.sync(); out.close(); - if (fs::exists(file_path)) - DB::renameExchange(temp_path, file_path); - else - DB::renameNoReplace(temp_path, file_path); - - fs::remove(temp_path); + /// `rename` replaces the target atomically, so a concurrent writer of the same schema cannot make it fail. + fs::rename(temp_path, file_path); } catch (...) { diff --git a/src/Formats/JSONExtractTree.cpp b/src/Formats/JSONExtractTree.cpp index 4860888b0f71..133bbb4f7c43 100644 --- a/src/Formats/JSONExtractTree.cpp +++ b/src/Formats/JSONExtractTree.cpp @@ -1916,10 +1916,9 @@ class DynamicNode : public JSONExtractTreeNode return DataTypeFactory::instance().get("Bool"); case ElementType::INT64: { - auto type = std::make_shared(); if (element.getInt64() < 0) - json_inference_info.negative_integers.insert(type.get()); - return type; + return json_inference_info.getNegativeInt64(); + return std::make_shared(); } case ElementType::UINT64: return std::make_shared(); @@ -1935,10 +1934,7 @@ class DynamicNode : public JSONExtractTreeNode if (format_settings.json.try_infer_numbers_from_strings) { if (auto type = tryInferJSONNumberFromString(data, format_settings, &json_inference_info)) - { - json_inference_info.numbers_parsed_from_json_strings.insert(type.get()); - return type; - } + return json_inference_info.getNumberParsedFromString(type); } return std::make_shared(); diff --git a/src/Formats/NativeReader.cpp b/src/Formats/NativeReader.cpp index 53f7f911f0ba..e82be2469755 100644 --- a/src/Formats/NativeReader.cpp +++ b/src/Formats/NativeReader.cpp @@ -50,12 +50,14 @@ NativeReader::NativeReader( const Block & header_, UInt64 server_revision_, std::optional format_settings_, - BlockMissingValues * block_missing_values_) + BlockMissingValues * block_missing_values_, + ISerialization::KindSet allowed_kinds_) : istr(istr_) , header(header_) , server_revision(server_revision_) , format_settings(std::move(format_settings_)) , block_missing_values(block_missing_values_) + , allowed_kinds(allowed_kinds_) { } diff --git a/src/Formats/NativeReader.h b/src/Formats/NativeReader.h index 390efaed1592..c2c9448a96ea 100644 --- a/src/Formats/NativeReader.h +++ b/src/Formats/NativeReader.h @@ -44,7 +44,8 @@ class NativeReader const Block & header_, UInt64 server_revision_, std::optional format_settings_ = std::nullopt, - BlockMissingValues * block_missing_values_ = nullptr); + BlockMissingValues * block_missing_values_ = nullptr, + ISerialization::KindSet allowed_kinds_ = default_allowed_kinds); /// For cases when we have an index. It allows to skip columns. Only columns specified in the index will be read. NativeReader(ReadBuffer & istr_, UInt64 server_revision_, diff --git a/src/Formats/SchemaInferenceUtils.cpp b/src/Formats/SchemaInferenceUtils.cpp index 928068cf21b3..3c5c11d17fca 100644 --- a/src/Formats/SchemaInferenceUtils.cpp +++ b/src/Formats/SchemaInferenceUtils.cpp @@ -35,6 +35,7 @@ namespace ErrorCodes extern const int NOT_IMPLEMENTED; extern const int INCORRECT_DATA; extern const int ONLY_NULLS_WHILE_READING_SCHEMA; + extern const int LOGICAL_ERROR; } namespace @@ -274,10 +275,16 @@ namespace { if (WhichDataType(type).isInt64()) { - bool is_negative = json_info && json_info->negative_integers.contains(type.get()); + bool is_negative = json_info && json_info->isNegativeInteger(*type); have_negative_integers |= is_negative; if (!is_negative) - type = std::make_shared(); + { + auto new_type = std::make_shared(); + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; + } } } @@ -299,9 +306,10 @@ namespace if (which.isInt64() || which.isUInt64()) { auto new_type = std::make_shared(); - if (json_info && json_info->numbers_parsed_from_json_strings.erase(type.get())) - json_info->numbers_parsed_from_json_strings.insert(new_type.get()); - type = new_type; + if (json_info && json_info->isNumberParsedFromString(*type)) + type = json_info->getNumberParsedFromString(new_type); + else + type = new_type; } } @@ -392,7 +400,7 @@ namespace { if (isNumber(type) && (settings.json.read_numbers_as_strings || !json_info - || json_info->numbers_parsed_from_json_strings.contains(type.get()))) + || json_info->isNumberParsedFromString(*type))) type = std::make_shared(); } @@ -1043,8 +1051,7 @@ namespace /// type inference has always reported there, and the deserializers accept the same text. DataTypePtr tryInferNumberFromEmptyField(const FormatSettings & settings) { - /// The integer parsers read no sign either, so the type is never a negative integer and is not - /// registered in json_info->negative_integers. + /// The integer parsers read no sign either, so the type is never a negative integer. if (settings.try_infer_integers) return std::make_shared(); return std::make_shared(); @@ -1085,10 +1092,9 @@ namespace ReadBufferFromMemory int_buf(span); if (tryReadIntText(tmp_int, int_buf) && int_buf.eof()) { - auto type = std::make_shared(); if (json_info && tmp_int < 0) - json_info->negative_integers.insert(type.get()); - return type; + return json_info->getNegativeInt64(); + return std::make_shared(); } /// In case of Int64 overflow we can try to infer UInt64. @@ -1174,10 +1180,9 @@ namespace Int64 tmp_int = 0; if (tryReadIntText(tmp_int, buf) && buf.eof()) { - auto type = std::make_shared(); if (json_inference_info && tmp_int < 0) - json_inference_info->negative_integers.insert(type.get()); - return type; + return json_inference_info->getNegativeInt64(); + return std::make_shared(); } /// We can safely get back to the start of buffer, because we read from a string and we didn't reach eof. @@ -1196,7 +1201,7 @@ namespace bool has_fractional = false; /// The whole field is already in contiguous memory here, so validate it directly. /// Keep returning nullptr on rejection: the caller falls through to String, and a String - /// returned from here would be registered in json_info->numbers_parsed_from_json_strings. + /// returned from here would be marked as a number parsed from a string. if (tryReadFloat(tmp, buf, settings, has_fractional) && buf.eof() && preciseParserAcceptsWholeSpan(field)) return std::make_shared(); @@ -1233,10 +1238,7 @@ namespace if (settings.json.try_infer_numbers_from_strings) { if (auto number_type = tryInferNumberFromStringImpl(field, settings, json_info)) - { - json_info->numbers_parsed_from_json_strings.insert(number_type.get()); - return number_type; - } + return json_info->getNumberParsedFromString(number_type); } } @@ -1483,6 +1485,42 @@ namespace /// Number return tryInferNumber(buf, field_start_count, settings, json_info); } + + template + DataTypePtr getOrCreate(DataTypePtr & instance) + { + if (!instance) + instance = std::make_shared(); + return instance; + } +} + +DataTypePtr JSONInferenceInfo::getNegativeInt64() +{ + return getOrCreate(negative_int64); +} + +DataTypePtr JSONInferenceInfo::getNumberParsedFromString(const DataTypePtr & number_type) +{ + WhichDataType which(number_type); + if (which.isInt64()) + return getOrCreate(isNegativeInteger(*number_type) ? negative_int64_from_string : int64_from_string); + if (which.isUInt64()) + return getOrCreate(uint64_from_string); + if (which.isFloat64()) + return getOrCreate(float64_from_string); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected type {} of a number parsed from a string", number_type->getName()); +} + +bool JSONInferenceInfo::isNegativeInteger(const IDataType & type) const +{ + return &type == negative_int64.get() || &type == negative_int64_from_string.get(); +} + +bool JSONInferenceInfo::isNumberParsedFromString(const IDataType & type) const +{ + return &type == int64_from_string.get() || &type == negative_int64_from_string.get() || &type == uint64_from_string.get() + || &type == float64_from_string.get(); } bool canBeInsideNullableBySchemaSettings(const DataTypePtr & type, const FormatSettings & settings) diff --git a/src/Formats/SchemaInferenceUtils.h b/src/Formats/SchemaInferenceUtils.h index fee16ea7e107..0cb8a326929e 100644 --- a/src/Formats/SchemaInferenceUtils.h +++ b/src/Formats/SchemaInferenceUtils.h @@ -18,13 +18,13 @@ using NamesAndTypesLists = VectorWithMemoryTracking; /// Struct with some additional information about inferred types for JSON formats. struct JSONInferenceInfo { - /// We store numbers that were parsed from strings. - /// It's used in types transformation to change such numbers back to string if needed. - std::unordered_set numbers_parsed_from_json_strings; - /// Store integer types that were inferred from negative numbers. - /// It's used to determine common type for Int64 and UInt64 - /// TODO: check it not only in JSON formats. - std::unordered_set negative_integers; + /// Int64 inferred from a negative number and numbers parsed from JSON strings are marked by being one of + /// the instances owned below. + DataTypePtr getNegativeInt64(); + /// number_type is Int64, UInt64 or Float64. + DataTypePtr getNumberParsedFromString(const DataTypePtr & number_type); + [[nodiscard]] bool isNegativeInteger(const IDataType & type) const; + [[nodiscard]] bool isNumberParsedFromString(const IDataType & type) const; /// Indicates if currently we are inferring type for Map/Object key. bool is_object_key = false; @@ -33,6 +33,13 @@ struct JSONInferenceInfo /// because DataTypeJSONPaths was already finalized to named tuple. IN this case /// we can only merge named tuples from different files together. bool allow_merging_named_tuples = false; + +private: + DataTypePtr negative_int64; + DataTypePtr int64_from_string; + DataTypePtr negative_int64_from_string; + DataTypePtr uint64_from_string; + DataTypePtr float64_from_string; }; /// Check whether a type can be wrapped into Nullable according to schema inference settings. diff --git a/src/Functions/AI/AIRequestExecutor.cpp b/src/Functions/AI/AIRequestExecutor.cpp index 9dad0e2aad2b..05d448671b3c 100644 --- a/src/Functions/AI/AIRequestExecutor.cpp +++ b/src/Functions/AI/AIRequestExecutor.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -16,11 +17,16 @@ #include #include +#include namespace ProfileEvents { extern const Event AIInputTokens; extern const Event AIOutputTokens; + extern const Event AICacheReadTokens; + extern const Event AICacheWriteTokens; + extern const Event AIRequestMicroseconds; + extern const Event AIRetryBackoffMicroseconds; extern const Event AIAPICalls; extern const Event AIAPICallsRetried; extern const Event AIAPICallsFailed; @@ -163,6 +169,7 @@ std::optional runRequest(const AIRequestPolicy & policy, AIQuotaTracke if (attempt < policy.max_retries && isRetriableProviderError(std::current_exception())) { ProfileEvents::increment(ProfileEvents::AIAPICallsRetried); + ProfileEventTimeIncrement backoff_time(ProfileEvents::AIRetryBackoffMicroseconds); /// Exponential backoff. `makeRequestPolicy` bounds both settings, so the longest sleep is 160 seconds. /// Sleep in short steps, so the retry of a cancelled query does not hold the worker. using Clock = std::chrono::steady_clock; @@ -218,8 +225,14 @@ std::future> submit( my_quota->recordTokens(response.input_tokens, response.output_tokens); ProfileEvents::increment(ProfileEvents::AIInputTokens, response.input_tokens); ProfileEvents::increment(ProfileEvents::AIOutputTokens, response.output_tokens); + if constexpr (std::is_same_v) + { + ProfileEvents::increment(ProfileEvents::AICacheReadTokens, response.cache_read_tokens); + ProfileEvents::increment(ProfileEvents::AICacheWriteTokens, response.cache_write_tokens); + } }); + ProfileEventTimeIncrement request_time(ProfileEvents::AIRequestMicroseconds); runAttempt(*my_provider, my_request, my_policy.timeouts, response); return response; }); diff --git a/src/Functions/AI/AnthropicProvider.cpp b/src/Functions/AI/AnthropicProvider.cpp index 720f7af8fc8d..7d75e2f5661d 100644 --- a/src/Functions/AI/AnthropicProvider.cpp +++ b/src/Functions/AI/AnthropicProvider.cpp @@ -182,6 +182,11 @@ AIResponse AnthropicProvider::call(const AIChatRequest & ai_request, const Conne { ai_response.input_tokens = usage->optValue("input_tokens", 0); ai_response.output_tokens = usage->optValue("output_tokens", 0); + ai_response.cache_read_tokens = usage->optValue("cache_read_input_tokens", 0); + ai_response.cache_write_tokens = usage->optValue("cache_creation_input_tokens", 0); + + /// Anthropic reports uncached input separately from cache reads and writes. + ai_response.input_tokens += ai_response.cache_read_tokens + ai_response.cache_write_tokens; } } diff --git a/src/Functions/AI/IAIProvider.h b/src/Functions/AI/IAIProvider.h index bae33011fc9d..5eca721ddbbb 100644 --- a/src/Functions/AI/IAIProvider.h +++ b/src/Functions/AI/IAIProvider.h @@ -95,12 +95,16 @@ struct AIResponse /// The generated text content from the model. String result; - /// Number of tokens in the input (prompt + system prompt), as reported by the provider. Used for quota tracking. + /// Total input tokens, including cache reads and writes. Used for quota tracking. UInt64 input_tokens = 0; /// Number of tokens in the generated output, as reported by the provider. Used for quota tracking. UInt64 output_tokens = 0; + /// Input tokens read from or written to the provider's prompt cache. Subsets of `input_tokens`. + UInt64 cache_read_tokens = 0; + UInt64 cache_write_tokens = 0; + /// Canonical reason the model stopped generating, normalized from the provider's native value. FinishReason finish_reason = FinishReason::Complete; diff --git a/src/Functions/AI/OpenAIProvider.cpp b/src/Functions/AI/OpenAIProvider.cpp index 44ab7006c148..12bb5461185d 100644 --- a/src/Functions/AI/OpenAIProvider.cpp +++ b/src/Functions/AI/OpenAIProvider.cpp @@ -166,6 +166,8 @@ AIResponse OpenAIProvider::call(const AIChatRequest & ai_request, const Connecti { ai_response.input_tokens = usage->optValue("prompt_tokens", 0); ai_response.output_tokens = usage->optValue("completion_tokens", 0); + if (const auto details = usage->getObject("prompt_tokens_details")) + ai_response.cache_read_tokens = details->optValue("cached_tokens", 0); } } diff --git a/src/Functions/FunctionBaseAI.cpp b/src/Functions/FunctionBaseAI.cpp index b657fffb7731..37dfc168dcf4 100644 --- a/src/Functions/FunctionBaseAI.cpp +++ b/src/Functions/FunctionBaseAI.cpp @@ -300,7 +300,17 @@ FunctionBaseAI::AIParams FunctionBaseAI::resolveAIParams( if (params.collection.endpoint.empty()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "AI named collection '{}' must have 'endpoint'", credentials); - const Poco::URI endpoint_uri(params.collection.endpoint); + /// The endpoint can carry a secret, so the error below names only the collection. + Poco::URI endpoint_uri; + try + { + endpoint_uri = Poco::URI(params.collection.endpoint); + } + catch (const Poco::SyntaxException &) + { + throw Exception(ErrorCodes::BAD_ARGUMENTS, "AI named collection '{}' has a malformed endpoint", credentials); + } + context->getRemoteHostFilter().checkURL(endpoint_uri); /// Refuse to send prompts and API keys over an unencrypted connection to a remote host. @@ -309,10 +319,10 @@ FunctionBaseAI::AIParams FunctionBaseAI::resolveAIParams( && !isLoopbackHost(endpoint_uri.getHost()) && !context->getSettingsRef()[Setting::ai_function_allow_insecure_endpoint]) throw Exception(ErrorCodes::BAD_ARGUMENTS, - "AI named collection '{}' uses an insecure endpoint '{}': prompts and the API key would be sent to a " + "AI named collection '{}' uses an insecure endpoint: prompts and the API key would be sent to a " "remote host over an unencrypted connection. Use an 'https://' endpoint, or set " "'ai_function_allow_insecure_endpoint' to allow plaintext requests to remote hosts.", - credentials, params.collection.endpoint); + credentials); /// A function that does not declare `model` (i.e. `aiEmbed`, which takes it as an argument) must /// not silently ignore a `model` defined in the named collection: reject it instead. diff --git a/src/Functions/FunctionNaiveBayesClassifier.cpp b/src/Functions/FunctionNaiveBayesClassifier.cpp index 460c94ef01c7..0807c5c19ccc 100644 --- a/src/Functions/FunctionNaiveBayesClassifier.cpp +++ b/src/Functions/FunctionNaiveBayesClassifier.cpp @@ -1,7 +1,5 @@ -#include #include -#include #include #include #include @@ -63,7 +61,9 @@ void validateDictionaryIsNaiveBayes(const ContextPtr & context, const IFunction { const String dictionary_name{arguments[0].column->getDataAt(0)}; - const auto layout_type = context->getExternalDictionariesLoader().getDictionaryLayoutType(dictionary_name, context); + /// Check access before reading the definition, so that a user without access learns nothing about the dictionary. + const auto & external_loader = context->getExternalDictionariesLoader(); + const auto layout_type = external_loader.getDictionaryLayoutType(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context)); if (layout_type != "naive_bayes") throw Exception( ErrorCodes::BAD_ARGUMENTS, @@ -76,7 +76,6 @@ void validateDictionaryIsNaiveBayes(const ContextPtr & context, const IFunction template void executeNaiveBayes( const ContextPtr & context, - std::atomic & access_checked, const ColumnsWithTypeAndName & arguments, size_t input_rows_count, ClassifyRow && classify_row) @@ -86,13 +85,10 @@ void executeNaiveBayes( const String dictionary_name{arguments[0].column->getDataAt(0)}; - auto dictionary = context->getExternalDictionariesLoader().getDictionary(dictionary_name, context); - - if (!access_checked.load(std::memory_order_relaxed)) - { - context->checkAccess(AccessType::dictGet, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - access_checked.store(true, std::memory_order_relaxed); - } + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and load the dictionary that passed the check. + const auto & external_loader = context->getExternalDictionariesLoader(); + auto dictionary = external_loader.getDictionary(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context), context); const auto * nb_dict = typeid_cast(dictionary.get()); if (!nb_dict) @@ -128,7 +124,6 @@ class FunctionNaiveBayesBase : public IFunction { protected: ContextPtr context; - mutable std::atomic access_checked{false}; public: explicit FunctionNaiveBayesBase(ContextPtr context_) @@ -155,7 +150,7 @@ class FunctionNaiveBayesClassifier : public FunctionNaiveBayesBase static constexpr auto name = "naiveBayesClassifier"; static FunctionPtr create(ContextPtr context_) { return std::make_shared(context_); } - String getName() const override { return name; } + [[nodiscard]] String getName() const override { return name; } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override { @@ -165,7 +160,7 @@ class FunctionNaiveBayesClassifier : public FunctionNaiveBayesBase return arguments[1].type->isNullable() ? makeNullable(result_type) : result_type; } - ColumnPtr + [[nodiscard]] ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & /* result_type */, size_t input_rows_count) const override { auto result_column = ColumnUInt32::create(input_rows_count); @@ -182,7 +177,6 @@ class FunctionNaiveBayesClassifier : public FunctionNaiveBayesBase executeNaiveBayes( context, - access_checked, effective_arguments, input_rows_count, [&](const auto & model, NaiveBayesScratch & scratch, std::string_view text, size_t i) @@ -205,7 +199,7 @@ class FunctionNaiveBayesClassifierWithProb : public FunctionNaiveBayesBase static constexpr auto name = "naiveBayesClassifierWithProb"; static FunctionPtr create(ContextPtr context_) { return std::make_shared(context_); } - String getName() const override { return name; } + [[nodiscard]] String getName() const override { return name; } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override { @@ -215,7 +209,7 @@ class FunctionNaiveBayesClassifierWithProb : public FunctionNaiveBayesBase return arguments[1].type->isNullable() ? makeNullable(result_type) : result_type; } - ColumnPtr + [[nodiscard]] ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & /* result_type */, size_t input_rows_count) const override { auto class_col = ColumnUInt32::create(input_rows_count); @@ -234,7 +228,6 @@ class FunctionNaiveBayesClassifierWithProb : public FunctionNaiveBayesBase executeNaiveBayes( context, - access_checked, effective_arguments, input_rows_count, [&](const auto & model, NaiveBayesScratch & scratch, std::string_view text, size_t i) @@ -273,7 +266,7 @@ class FunctionNaiveBayesClassifierWithAllProbs : public FunctionNaiveBayesBase static constexpr auto name = "naiveBayesClassifierWithAllProbs"; static FunctionPtr create(ContextPtr context_) { return std::make_shared(context_); } - String getName() const override { return name; } + [[nodiscard]] String getName() const override { return name; } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override { @@ -283,7 +276,7 @@ class FunctionNaiveBayesClassifierWithAllProbs : public FunctionNaiveBayesBase return arguments[1].type->isNullable() ? makeNullableSafe(result_type) : result_type; } - ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override + [[nodiscard]] ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override { auto class_col = ColumnUInt32::create(); auto prob_col = ColumnFloat64::create(); @@ -303,7 +296,6 @@ class FunctionNaiveBayesClassifierWithAllProbs : public FunctionNaiveBayesBase executeNaiveBayes( context, - access_checked, effective_arguments, input_rows_count, [&](const auto & model, NaiveBayesScratch & scratch, std::string_view text, size_t i) diff --git a/src/Functions/FunctionsExternalDictionaries.h b/src/Functions/FunctionsExternalDictionaries.h index 838a8106b660..aa6070bc174c 100644 --- a/src/Functions/FunctionsExternalDictionaries.h +++ b/src/Functions/FunctionsExternalDictionaries.h @@ -95,15 +95,10 @@ class FunctionDictHelper std::shared_ptr getDictionary(const String & dictionary_name) { - auto dict = context->getExternalDictionariesLoader().getDictionary(dictionary_name, context); - - if (!access_checked) - { - context->checkAccess(AccessType::dictGet, dict->getDatabaseOrNoDatabaseTag(), dict->getDictionaryID().getTableName()); - access_checked = true; - } - - return dict; + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and load the dictionary that passed the check. + const auto & external_loader = context->getExternalDictionariesLoader(); + return external_loader.getDictionary(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context), context); } std::shared_ptr getDictionary(const ColumnPtr & column) @@ -163,17 +158,16 @@ class FunctionDictHelper return getDictionary(dictionary_name)->isInjective(attribute_name); } - DictionaryStructure getDictionaryStructure(const String & dictionary_name) const + DictionaryStructure getDictionaryStructure(const String & dictionary_name) { - return context->getExternalDictionariesLoader().getDictionaryStructure(dictionary_name, context); + /// Check access before reading the definition, so that a user without access learns nothing about the dictionary. + const auto & external_loader = context->getExternalDictionariesLoader(); + return external_loader.getDictionaryStructure(external_loader.resolveDictionaryCheckingAccess(dictionary_name, context)); } const ContextPtr context; private: - /// Access cannot be not granted, since in this case checkAccess() will throw and access_checked will not be updated. - std::atomic access_checked = false; - /// We must not cache dictionary or dictionary's structure here, because there are places /// where ExpressionActionsPtr is cached (StorageDistributed caching it for sharding_key_expr and /// optimize_skip_unused_shards), and if the dictionary will be cached within "query" then diff --git a/src/Functions/UTCTimestampTransform.cpp b/src/Functions/UTCTimestampTransform.cpp index 6d7f86b3c9c6..998d91e73bd3 100644 --- a/src/Functions/UTCTimestampTransform.cpp +++ b/src/Functions/UTCTimestampTransform.cpp @@ -107,7 +107,7 @@ namespace for (size_t i = 0; i < input_rows_count; ++i) { UInt32 date_time_val = date_time_col.getElement(i); - auto time_zone_offset = time_zone.timezoneOffset(date_time_val); + auto time_zone_offset = to_utc ? time_zone.timezoneOffsetAtLocalTime(date_time_val) : time_zone.timezoneOffset(date_time_val); UInt32 abs_offset = static_cast(std::abs(time_zone_offset)); if (to_utc) @@ -145,11 +145,11 @@ namespace DateTime64 date_time_val = date_time_col.getElement(i); Int64 seconds = date_time_val.value / scale_multiplier; /// Truncating division rounds toward zero, so a negative sub-second remainder - /// lands on the next second up. Floor it, otherwise timezoneOffset() reads the - /// wrong side of a DST/offset boundary. + /// lands on the next second up. Floor it, otherwise the offset is looked up for the + /// next second, which can be on the other side of an offset change. if (date_time_val.value % scale_multiplier < 0) seconds -= 1; - auto time_zone_offset = time_zone.timezoneOffset(seconds); + auto time_zone_offset = to_utc ? time_zone.timezoneOffsetAtLocalTime(seconds) : time_zone.timezoneOffset(seconds); /// Shifting the floored seconds by the offset and reassembling is the same as /// shifting the underlying value by `offset * scale_multiplier`. That product fits /// Int64 (|offset| < 2^18, scale_multiplier <= 10^9); only the shift can overflow. @@ -179,6 +179,7 @@ REGISTER_FUNCTION(UTCTimestampTransform) { FunctionDocumentation::Description description_toUTCTimestamp = R"( Converts a date or date with time value from one time zone to UTC timezone timestamp. This function is mainly included for compatibility with Apache Spark and similar frameworks. +A local time that happens twice or does not exist because of a daylight saving time change is converted as `toDateTime` does. )"; FunctionDocumentation::Syntax syntax_toUTCTimestamp = R"( toUTCTimestamp(datetime, time_zone) diff --git a/src/Functions/geometryConverters.h b/src/Functions/geometryConverters.h index 13de397d854d..83aa45b2a021 100644 --- a/src/Functions/geometryConverters.h +++ b/src/Functions/geometryConverters.h @@ -161,7 +161,7 @@ struct ColumnToMultiLineStringsConverter size_t prev_offset = 0; VectorWithMemoryTracking> answer(offsets.size()); auto all_linestrings = ColumnToLineStringsConverter::convert(typeid_cast(*col).getDataPtr()); - for (size_t iter = 0; iter < offsets.size() && iter < all_linestrings.size(); ++iter) + for (size_t iter = 0; iter < offsets.size(); ++iter) { for (size_t linestring_iter = prev_offset; linestring_iter < offsets[iter]; ++linestring_iter) answer[iter].emplace_back(std::move(all_linestrings[linestring_iter])); @@ -210,10 +210,7 @@ struct ColumnToPolygonsConverter { const auto current_array_size = offsets[iter] - prev_offset; if (current_array_size == 0) - { - answer.emplace_back(); continue; - } answer[iter].outer() = std::move(all_rings[prev_offset]); answer[iter].inners().reserve(current_array_size); @@ -240,7 +237,7 @@ struct ColumnToMultiPolygonsConverter auto all_polygons = ColumnToPolygonsConverter::convert(typeid_cast(*col).getDataPtr()); - for (size_t iter = 0; iter < offsets.size() && iter < all_polygons.size(); ++iter) + for (size_t iter = 0; iter < offsets.size(); ++iter) { for (size_t polygon_iter = prev_offset; polygon_iter < offsets[iter]; ++polygon_iter) answer[iter].emplace_back(std::move(all_polygons[polygon_iter])); diff --git a/src/Functions/if.cpp b/src/Functions/if.cpp index fb260969e34d..680fa3f4e603 100644 --- a/src/Functions/if.cpp +++ b/src/Functions/if.cpp @@ -705,7 +705,8 @@ class FunctionIf final : public FunctionIfBase temporary_columns[1] = {col1_contents[i], type1.getElements()[i], {}}; temporary_columns[2] = {col2_contents[i], type2.getElements()[i], {}}; - tuple_columns[i] = executeImpl(temporary_columns, tuple_result.getElements()[i], input_rows_count); + /// The result for one element can be constant (for example NULL in both branches), a tuple element cannot. + tuple_columns[i] = executeImpl(temporary_columns, tuple_result.getElements()[i], input_rows_count)->convertToFullColumnIfConst(); } return ColumnTuple::create(tuple_columns); diff --git a/src/Functions/stem.cpp b/src/Functions/stem.cpp index c8784dfdebfe..24b12289e7c0 100644 --- a/src/Functions/stem.cpp +++ b/src/Functions/stem.cpp @@ -29,6 +29,7 @@ namespace ErrorCodes extern const int BAD_ARGUMENTS; extern const int CANNOT_ALLOCATE_MEMORY; extern const int ILLEGAL_TYPE_OF_ARGUMENT; + extern const int TOO_LARGE_STRING_SIZE; } namespace @@ -49,6 +50,13 @@ bool isValidStemWordType(const IDataType & type) return false; } +/// Snowball keeps the length, the capacity and all offsets of a word as `int`, without overflow checks: +/// it takes the input length as `int`, adds a small constant to it when it allocates its buffer, +/// and a stemmer can make the word longer than the input (for example, the Serbian one transliterates +/// Cyrillic to Latin, which turns some two-byte letters into three bytes). +/// So a word has to be much shorter than `INT_MAX` bytes. This limit leaves a lot of headroom for the growth +/// and is far above the length of any real word. +constexpr size_t max_word_size = 64 * 1024 * 1024; /// RAII wrapper around sb_stemmer. Constructed from a language code; throws /// ILLEGAL_TYPE_OF_ARGUMENT in the constructor if the language is unsupported. @@ -72,11 +80,20 @@ class Stemmer /// Stem a single word given as a byte range. Returns a string_view over the /// stemmer's internal buffer (valid until the next call to stem). - /// Throws BAD_ARGUMENTS if the input contains whitespace, or + /// Throws TOO_LARGE_STRING_SIZE if the input is longer than max_word_size, + /// BAD_ARGUMENTS if the input contains whitespace, or /// CANNOT_ALLOCATE_MEMORY if the stemmer runs out of memory. /// Note: the input must be lowercase; passing uppercase characters produces undefined results. std::string_view stem(std::string_view word) { + /// This also makes the conversion of the length to `int` below lossless. + if (word.size() > max_word_size) + throw Exception( + ErrorCodes::TOO_LARGE_STRING_SIZE, + "Too long word for function stem: {} bytes, the maximum is {} bytes", + word.size(), + max_word_size); + if (std::any_of(word.begin(), word.end(), isWhitespaceASCII)) throw Exception( ErrorCodes::BAD_ARGUMENTS, @@ -231,6 +248,7 @@ REGISTER_FUNCTION(Stem) Performs stemming on a word or an array of words using the Snowball algorithms. Each input string must be a single, lowercase word — strings containing whitespace cause an exception. Passing uppercase characters produces undefined results. +Words longer than 64 MiB cause an exception. Returns String for scalar inputs (including FixedString) and Array(String) for array inputs. Nullable and LowCardinality variants of String and FixedString are supported. The list of supported language identifiers is available in [system.stemmers](/reference/system-tables/stemmers). diff --git a/src/IO/Lz4DeflatingWriteBuffer.cpp b/src/IO/Lz4DeflatingWriteBuffer.cpp index 18c9b5ceeb9e..4483d215d066 100644 --- a/src/IO/Lz4DeflatingWriteBuffer.cpp +++ b/src/IO/Lz4DeflatingWriteBuffer.cpp @@ -77,7 +77,8 @@ void Lz4DeflatingWriteBuffer::initialize(int compression_level) compression_level, /* compression level; 0 == default */ 1, /* autoflush */ 0, /* favor decompression speed */ - {0, 0, 0}, /* reserved, must be set to 0 */ + 0, /* nbWorkers: 0 == single-threaded */ + 0, 0, /* reserved, must be set to 0 */ }; size_t ret = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); @@ -95,30 +96,33 @@ Lz4DeflatingWriteBuffer::~Lz4DeflatingWriteBuffer() LZ4F_freeCompressionContext(ctx); } +void Lz4DeflatingWriteBuffer::writeFrameHeader() +{ + auto sink = SinkToOut(out, tmp_memory, LZ4F_HEADER_SIZE_MAX); + chassert(sink.getCapacity() >= LZ4F_HEADER_SIZE_MAX); + + /// write frame header and check for errors + size_t header_size = LZ4F_compressBegin( + ctx, sink.getPosition(), sink.getCapacity(), &kPrefs); + + if (LZ4F_isError(header_size)) + throw Exception( + ErrorCodes::LZ4_ENCODER_FAILED, + "LZ4 failed to start stream encoding. LZ4F version: {}, error: {}", + LZ4F_VERSION, LZ4F_getErrorName(header_size)); + + sink.advancePosition(header_size); + sink.finalize(); + first_time = false; +} + void Lz4DeflatingWriteBuffer::nextImpl() { if (!offset()) return; if (first_time) - { - auto sink = SinkToOut(out, tmp_memory, LZ4F_HEADER_SIZE_MAX); - chassert(sink.getCapacity() >= LZ4F_HEADER_SIZE_MAX); - - /// write frame header and check for errors - size_t header_size = LZ4F_compressBegin( - ctx, sink.getPosition(), sink.getCapacity(), &kPrefs); - - if (LZ4F_isError(header_size)) - throw Exception( - ErrorCodes::LZ4_ENCODER_FAILED, - "LZ4 failed to start stream encoding. LZ4F version: {}, error: {}", - LZ4F_VERSION, LZ4F_getErrorName(header_size)); - - sink.advancePosition(header_size); - sink.finalize(); - first_time = false; - } + writeFrameHeader(); auto * in_data = working_buffer.begin(); auto in_capacity = offset(); @@ -160,9 +164,15 @@ void Lz4DeflatingWriteBuffer::finalFlushBefore() { next(); - /// Don't write out if no data was ever compressed - if (!compress_empty && first_time) - return; + if (first_time) + { + /// Don't write out if no data was ever compressed + if (!compress_empty) + return; + + /// Write a valid empty frame. `LZ4F_compressEnd` requires a started frame since lz4 v1.11.0. + writeFrameHeader(); + } auto suffix_size = LZ4F_compressBound(0, &kPrefs); auto sink = SinkToOut(out, tmp_memory, suffix_size); diff --git a/src/IO/Lz4DeflatingWriteBuffer.h b/src/IO/Lz4DeflatingWriteBuffer.h index dc8f92a5fc81..a633a4578c85 100644 --- a/src/IO/Lz4DeflatingWriteBuffer.h +++ b/src/IO/Lz4DeflatingWriteBuffer.h @@ -34,6 +34,7 @@ class Lz4DeflatingWriteBuffer : public WriteBufferWithOwnMemoryDecorator private: void initialize(int compression_level); + void writeFrameHeader(); void nextImpl() override; void finalFlushBefore() override; diff --git a/src/IO/ReadBufferFromEncryptedFile.cpp b/src/IO/ReadBufferFromEncryptedFile.cpp index f18d38ec34da..60400a6743f1 100644 --- a/src/IO/ReadBufferFromEncryptedFile.cpp +++ b/src/IO/ReadBufferFromEncryptedFile.cpp @@ -272,6 +272,11 @@ void ReadBufferFromEncryptedFile::performSeekAndSetReadUntilPosition() void ReadBufferFromEncryptedFile::prefetch(Priority priority) { + /// Apply a pending seek or `read_until_position` before prefetching. Otherwise the inner buffer + /// prefetches with the old range, and applying the new one in `nextImpl` discards that prefetch. + if (need_seek || need_set_read_until_position) + performSeekAndSetReadUntilPosition(); + in->prefetch(priority); } diff --git a/src/IO/ReadPipeline.cpp b/src/IO/ReadPipeline.cpp index 0329c87d2a22..aaebdbd33360 100644 --- a/src/IO/ReadPipeline.cpp +++ b/src/IO/ReadPipeline.cpp @@ -24,6 +24,8 @@ #include #include +#include + #if ENABLE_DISTRIBUTED_CACHE #include #endif @@ -776,6 +778,14 @@ std::unique_ptr ReadPipeline::wrapDecryption(std::unique { /// -- Stage 6: Decryption (may have multiple layers for double encryption) -- #if USE_SSL + /// Bound the source before reading the headers. Every encryption layer adds a header in front of the data it wraps. + if (initial_read_until_position) + { + size_t layers = std::ranges::count_if(decryption_stages, [](const auto & dec) { return dec.key_finder != nullptr; }); + if (layers) + impl->setReadUntilPosition(*initial_read_until_position + layers * FileEncryption::Header::kSize); + } + for (const auto & dec : decryption_stages) { if (!dec.key_finder) diff --git a/src/IO/ReadPipeline.h b/src/IO/ReadPipeline.h index 24696be3774b..2738995d77f3 100644 --- a/src/IO/ReadPipeline.h +++ b/src/IO/ReadPipeline.h @@ -160,6 +160,11 @@ class ReadPipeline /// read from the encryption header. It must return the decryption key. void needDecryption(String path, size_t buffer_size, KeyFinderFunc key_finder); + /// The end of the first range the caller will read, in the coordinates of the decrypted file. The decryption + /// stage reads the header before the caller sets its range, so it bounds the source with this position first: + /// otherwise the source request starts unbounded and is reopened when the caller sets the range. + void setInitialReadUntilPosition(size_t position) { initial_read_until_position = position; } + /// Let the `ReaderExecutor` path reuse held source connections, bounded by this limit. When it is /// not set, the executor uses the stateless one-shot path. void needLongConnectionLimit(std::shared_ptr limit); @@ -235,6 +240,7 @@ class ReadPipeline std::optional distributed_cache; std::optional async_prefetch; VectorWithMemoryTracking decryption_stages; + std::optional initial_read_until_position; /// Global encryption-header cache for the executor; null unless a random-object-key disk set it. std::shared_ptr encryption_header_cache; diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 33ae4e0e9b6d..ca45bc8ab71f 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -880,7 +881,7 @@ ReadWriteBufferFromHTTPPtr BuilderRWBufferFromHTTP::createWithBearerToken( return ptr; } -void setCredentialsFromURL(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & uri) +void setCredentialsFromURL(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & uri, const HTTPHeaderFilter & header_filter) { credentials.clear(); @@ -898,6 +899,8 @@ void setCredentialsFromURL(Poco::Net::HTTPBasicCredentials & credentials, const { credentials.setUsername(user_info); } + + header_filter.checkBasicCredentials(credentials); } } diff --git a/src/IO/ReadWriteBufferFromHTTP.h b/src/IO/ReadWriteBufferFromHTTP.h index 7a2b4e624df1..9a4c6571421f 100644 --- a/src/IO/ReadWriteBufferFromHTTP.h +++ b/src/IO/ReadWriteBufferFromHTTP.h @@ -29,6 +29,8 @@ namespace DB { +class HTTPHeaderFilter; + class ReadWriteBufferFromHTTP : public SeekableReadBuffer, public WithFileName, public WithFileSize, public IReadBufferMetadataProvider { friend class BuilderRWBufferFromHTTP; @@ -276,6 +278,7 @@ class BuilderRWBufferFromHTTP }; /// Fills `credentials` from the userinfo component of `uri` (e.g. `http://user:pass@host`). -void setCredentialsFromURL(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & uri); +/// Throws if `header_filter` forbids the `Authorization` header, which sends them, and the userinfo has a username. +void setCredentialsFromURL(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & uri, const HTTPHeaderFilter & header_filter); } diff --git a/src/IO/readDecimalText.h b/src/IO/readDecimalText.h index d5b493411a58..4f252d026e48 100644 --- a/src/IO/readDecimalText.h +++ b/src/IO/readDecimalText.h @@ -2,6 +2,7 @@ #include #include +#include #include @@ -14,6 +15,28 @@ namespace ErrorCodes extern const int ARGUMENT_OUT_OF_BOUND; } +/// Sets `x = x * 10^power + addend` and returns false if the result does not fit `N`. `addend` must be zero or +/// have the sign of `x`, or `x` must be zero. Exact for the wide integer types too, unlike `common::mulOverflow`, +/// which never reports overflow for them. +template +inline bool mulPow10AddChecked(N & x, uint32_t power, N addend) +{ + if (x == 0) + { + x = addend; + return true; + } + /// A nonzero `x` times `10^(digits10 + 1)` does not fit. + if (power > static_cast(std::numeric_limits::digits10)) + return false; + const N multiplier = intExp10OfSize(static_cast(power)); + if (x > 0 ? x > (std::numeric_limits::max() - addend) / multiplier + : x < (std::numeric_limits::min() - addend) / multiplier) + return false; + x = x * multiplier + addend; + return true; +} + /// Try to read Decimal into underlying type T from ReadBuffer. Throws if 'digits_only' is set and there's unexpected symbol in input. /// Returns integer 'exponent' factor that x should be multiplied by to get correct Decimal value: result = x * 10^exponent. /// Use 'digits' input as max allowed meaning decimal digits in result. Place actual number of meaning digits in 'digits' output. @@ -30,6 +53,9 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp digits = 0; uint32_t places = 0; typename T::NativeType sign = 1; + /// When more digits are allowed than the native integer always holds (`Field` dumps allow any number), the + /// mantissa is accumulated with its sign and checked, so it does not wrap and keeps the full native range. + const bool check_overflow = max_digits > static_cast(std::numeric_limits::digits10); bool leading_zeroes = true; bool after_point = false; @@ -112,11 +138,21 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp if (after_point) exponent -= places; - // TODO: accurate shift10 for big integers - x *= intExp10OfSize(places); + if (check_overflow) + { + if (!mulPow10AddChecked(x.value, places, sign * static_cast(byte - '0'))) + { + if constexpr (_throw_on_error) + throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal value does not fit its native integer type"); + return false; + } + } + else + { + x *= intExp10OfSize(places); + x += (byte - '0'); + } places = 0; - - x += (byte - '0'); break; } case 'e': [[fallthrough]]; @@ -131,7 +167,14 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp else return false; } - exponent += addition_exp; + /// The exponent comes from the text, so the sum can be anything, e.g. `0.1e-2147483648`. + if (common::addOverflow(exponent, addition_exp, exponent)) + { + if constexpr (_throw_on_error) + throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Exponent is out of range while reading decimal"); + else + return false; + } stop = true; continue; } @@ -149,7 +192,8 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp ++buf.position(); } - x *= sign; + if (!check_overflow) + x *= sign; return true; } @@ -165,7 +209,8 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u if (!throw_exception && !ok) return ReturnType(false); - if (static_cast(digits) + exponent > static_cast(precision - scale)) + /// Compute in 64 bits: the exponent can be close to the `int32_t` limits. + if (static_cast(digits) + exponent > static_cast(precision) - static_cast(scale)) { if constexpr (throw_exception) { @@ -177,9 +222,9 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u return ReturnType(false); } - if (static_cast(scale) + exponent < 0) + if (static_cast(scale) + exponent < 0) { - auto divisor_exp = -exponent - static_cast(scale); + int64_t divisor_exp = -static_cast(exponent) - static_cast(scale); if (divisor_exp >= std::numeric_limits::digits10) { @@ -190,7 +235,7 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u } /// Too many digits after point. Just cut off excessive digits. - auto divisor = intExp10OfSize(divisor_exp); + auto divisor = intExp10OfSize(static_cast(divisor_exp)); chassert(divisor > 0); /// This is for Clang Static Analyzer. It is not smart enough to infer it automatically. x.value /= divisor; /// NOLINT(clang-analyzer-core.DivideZero) scale = 0; diff --git a/src/IO/tests/gtest_zlib_deflate_init_allocation_failure.cpp b/src/IO/tests/gtest_zlib_deflate_init_allocation_failure.cpp new file mode 100644 index 000000000000..99afa6407978 --- /dev/null +++ b/src/IO/tests/gtest_zlib_deflate_init_allocation_failure.cpp @@ -0,0 +1,63 @@ +#include + +#include + +#include + +namespace +{ + +struct FailingAllocator +{ + unsigned count = 0; + unsigned fail_at = 0; +}; + +void * failingAlloc(void * opaque, unsigned items, unsigned size) +{ + auto & allocator = *static_cast(opaque); + if (++allocator.count == allocator.fail_at) + return nullptr; + return malloc(static_cast(items) * size); +} + +void failingFree(void *, void * ptr) +{ + free(ptr); +} + +} + +/// Failing any single allocation made by `deflateInit2` must return `Z_MEM_ERROR`. +TEST(ZlibDeflate, InitReturnsMemErrorOnEveryFailedAllocation) +{ + for (int window_bits : {-15, 15, 31}) + { + unsigned failed_cases = 0; + unsigned allocations = 0; + for (unsigned fail_at = 1;; ++fail_at) + { + ASSERT_LT(fail_at, 64u); + + FailingAllocator allocator{.count = 0, .fail_at = fail_at}; + z_stream stream{}; + stream.zalloc = failingAlloc; + stream.zfree = failingFree; + stream.opaque = &allocator; + + int rc = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY); + if (rc == Z_OK) + { + deflateEnd(&stream); + allocations = allocator.count; + break; + } + + ASSERT_EQ(rc, Z_MEM_ERROR) << "window_bits " << window_bits << ", fail_at " << fail_at; + ++failed_cases; + } + + EXPECT_EQ(failed_cases, allocations) << "window_bits " << window_bits; + EXPECT_GE(allocations, 3u) << "window_bits " << window_bits; + } +} diff --git a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp index 1725f060561b..ef5b360e62d9 100644 --- a/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp @@ -164,10 +164,12 @@ BlockIO InterpreterCreateQuotaQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp index 0c85ea847591..64a47a49283a 100644 --- a/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRoleQuery.cpp @@ -96,10 +96,12 @@ BlockIO InterpreterCreateRoleQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp index ebc20f311930..da01d61751ed 100644 --- a/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp @@ -63,9 +63,13 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() for (const auto & [filter_type, filter] : query.filters) checkRowPolicyFilterExpression(filter); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) { query.replaceCurrentUserTag(getContext()->getUserName()); + required_access.replaceEmptyDatabase(getContext()->getCurrentDatabase()); DDLQueryOnClusterParams params; params.access_to_check = std::move(required_access); return executeDDLQueryOnCluster(updated_query_ptr, getContext(), params); @@ -75,8 +79,6 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(required_access); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::optional roles_from_query; if (query.roles) roles_from_query = RolesOrUsersSet{*query.roles, access_control, getContext()->getUserID()}; @@ -102,10 +104,12 @@ BlockIO InterpreterCreateRowPolicyQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp index 553b21995b01..5f364d56a678 100644 --- a/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateSettingsProfileQuery.cpp @@ -107,10 +107,12 @@ BlockIO InterpreterCreateSettingsProfileQuery::execute() if (query.if_exists) { auto ids = storage->find(query.names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(query.names), update_func); + access_control.update(storage->getIDs(query.names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp index 402448876f6d..f05d0ffb9317 100644 --- a/src/Interpreters/Access/InterpreterCreateUserQuery.cpp +++ b/src/Interpreters/Access/InterpreterCreateUserQuery.cpp @@ -393,10 +393,12 @@ BlockIO InterpreterCreateUserQuery::execute() if (query.if_exists) { auto ids = storage->find(names); - storage->tryUpdate(ids, update_func); + /// The IDs are resolved in the requested storage, but the update goes through `AccessControl`, + /// so a rename is checked against the names in the other storages too. + access_control.tryUpdate(ids, update_func); } else - storage->update(storage->getIDs(names), update_func); + access_control.update(storage->getIDs(names), update_func); } else { diff --git a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp index a0bbdd645ee9..313cfad6e8a7 100644 --- a/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterDropAccessEntityQuery.cpp @@ -39,11 +39,12 @@ BlockIO InterpreterDropAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(updated_query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - auto do_drop = [&](const Strings & names, const String & storage_name) { IAccessStorage * storage = &access_control; diff --git a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp index 8e1b8e4455c0..66cf45a24353 100644 --- a/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp +++ b/src/Interpreters/Access/InterpreterMoveAccessEntityQuery.cpp @@ -23,11 +23,12 @@ BlockIO InterpreterMoveAccessEntityQuery::execute() auto & access_control = getContext()->getAccessControl(); getContext()->checkAccess(getRequiredAccess()); + /// Must be done before replication: a DDL worker resolves a bare table name in its own current database. + query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); + if (!query.cluster.empty()) return executeDDLQueryOnCluster(query_ptr, getContext()); - query.replaceEmptyDatabase(getContext()->getCurrentDatabase()); - std::vector ids; if (query.type == AccessEntityType::ROW_POLICY) ids = access_control.getIDs(query.type, query.row_policy_names->toStrings()); diff --git a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp index b68fbd19f704..a36436b313c2 100644 --- a/src/Interpreters/Access/InterpreterSetRoleQuery.cpp +++ b/src/Interpreters/Access/InterpreterSetRoleQuery.cpp @@ -23,6 +23,26 @@ namespace ErrorCodes } +namespace +{ + +/// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a +/// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. +void throwIfReadonlyRestrictsSetRole(const ContextPtr & context, std::string_view statement) +{ + if (context->getAccessControl().doesReadonlyRestrictSetRole() && context->getSettingsRef()[Setting::readonly]) + { + throw Exception( + ErrorCodes::READONLY, + "Cannot execute {} in readonly mode. " + "This restriction is enabled by access_control_improvements.readonly_restricts_set_role", + statement); + } +} + +} + + BlockIO InterpreterSetRoleQuery::execute() { const auto & query = query_ptr->as(); @@ -38,14 +58,7 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) { auto session_context = getContext()->getSessionContext(); - /// `readonly` is read from the query context: a client `--readonly 1` raises it there only, while a - /// mid-session `SET readonly = 1` also reaches it because a query context inherits session settings. - if (getContext()->getAccessControl().doesReadonlyRestrictSetRole() - && getContext()->getSettingsRef()[Setting::readonly]) - throw Exception( - ErrorCodes::READONLY, - "Cannot execute SET ROLE in readonly mode. " - "This restriction is enabled by access_control_improvements.readonly_restricts_set_role"); + throwIfReadonlyRestrictsSetRole(getContext(), "SET ROLE"); if (query.kind == ASTSetRoleQuery::Kind::SET_ROLE_DEFAULT) session_context->setCurrentRolesDefault(); @@ -56,6 +69,11 @@ void InterpreterSetRoleQuery::setRole(const ASTSetRoleQuery & query) void InterpreterSetRoleQuery::setDefaultRole(const ASTSetRoleQuery & query) { + /// The default roles are what the next session of the user starts with, so changing them is a way around the + /// restriction of `SET ROLE` if it is not restricted as well. The access check below does not catch it for the + /// user's own default roles: `TO CURRENT_USER` requires no grant, so `readonly` has nothing to deny there. + throwIfReadonlyRestrictsSetRole(getContext(), "SET DEFAULT ROLE"); + getContext()->checkAccess(query.to_users->collectRequiredGrants(AccessType::ALTER_USER)); auto & access_control = getContext()->getAccessControl(); diff --git a/src/Interpreters/ActionsDAG.cpp b/src/Interpreters/ActionsDAG.cpp index e106fb126291..074fa010c029 100644 --- a/src/Interpreters/ActionsDAG.cpp +++ b/src/Interpreters/ActionsDAG.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -4046,11 +4047,136 @@ ActionsDAG::NodeRawConstPtrs ActionsDAG::extractConjunctionAtoms(const Node * pr } ActionsDAG ActionsDAG::restrictFilterDAGToInputs(const ActionsDAG::Node * filter_node, const NameSet & available_inputs) const +{ + /// The projection evaluates the filter on rows the main read may skip, and a weakened `AND` evaluates its later + /// operands on more rows, so the `OR` walk is kept only if no `OR` it weakened can throw or change on re-evaluation. + /// Outside such an `OR` the restriction is the same as without the walk. + std::unordered_set substitutes; + auto restricted = restrictFilterDAGToInputsImpl(filter_node, available_inputs, /*walk_or=*/true, &substitutes); + + auto is_number = [](const Node * node) { return isNativeNumber(removeLowCardinalityAndNullable(node->result_type)); }; + auto is_total = [&](const Node & node) + { + if (node.type == ActionType::INPUT || node.type == ActionType::COLUMN || node.type == ActionType::ALIAS) + return true; + if (node.type != ActionType::FUNCTION || !node.function_base) + return false; + const auto & name = node.function_base->getName(); + if (name == "and" || name == "or") + return true; + if (name == "equals" || name == "notEquals" || name == "less" || name == "greater" || name == "lessOrEquals" + || name == "greaterOrEquals") + return std::ranges::all_of(node.children, is_number); + if (name == "in" || name == "notIn") + return is_number(node.children.front()); + return false; + }; + + auto is_safe = [&](const Node & or_node) + { + bool weakened = false; + bool total = true; + std::vector to_visit{&or_node}; + std::unordered_set visited{&or_node}; + while (!to_visit.empty()) + { + const auto * node = to_visit.back(); + to_visit.pop_back(); + weakened |= substitutes.contains(node); + total &= is_total(*node); + for (const auto * child : node->children) + if (visited.insert(child).second) + to_visit.push_back(child); + } + return !weakened || total; + }; + + for (const auto & node : restricted.nodes) + if (node.type == ActionType::FUNCTION && node.function_base && node.function_base->getName() == "or" && !is_safe(node)) + return restrictFilterDAGToInputsImpl(filter_node, available_inputs, /*walk_or=*/false); + return restricted; +} + +ActionsDAG ActionsDAG::restrictFilterDAGToInputsImpl( + const ActionsDAG::Node * filter_node, + const NameSet & available_inputs, + bool walk_or, + std::unordered_set * substitutes) const { ActionsDAG actions; std::unordered_map copy_map; std::unordered_map can_compute; + /** Substituting a true constant for a non-computable conjunct weakens an `AND`, which is only sound + * where the predicate is used with positive polarity. Under a `NOT`, a comparison or a conditional's + * branch condition the weakened `AND` makes the whole predicate stronger - `NOT (a AND b)` becomes + * `NOT (a)` - and rows that do match the filter are then pruned away. + * + * So collect the `AND`s reached from the filter through `AND`s (and `OR`s with `walk_or`) only, which is where the + * polarity is known to be positive. A node with more than one parent may also be reachable through + * some other function, so require a single parent while descending. The substitution is recorded + * against the child, so the child must have a single parent too. + */ + std::unordered_map num_parents; + std::unordered_set conjuncts_safe_to_drop; + { + /// Count parents within the `filter_node` subgraph, not in `nodes`: the caller may pass a node of + /// another DAG of which this one is a clone. Only a parent inside the subgraph can observe a + /// substitution anyway, because that is all Phase 2 copies. + std::stack to_visit; + std::unordered_set visited{filter_node}; + to_visit.push(filter_node); + while (!to_visit.empty()) + { + const auto * node = to_visit.top(); + to_visit.pop(); + for (const auto * child : node->children) + { + ++num_parents[child]; + if (visited.insert(child).second) + to_visit.push(child); + } + } + + auto is_function = [](const Node * candidate, std::string_view name) + { + return candidate->type == ActionType::FUNCTION && candidate->function_base + && candidate->function_base->getName() == name; + }; + + /// `OR` is monotone in each operand like `AND`, also with NULLs, so an `AND` under it keeps the polarity. + auto is_and_or_or = [&](const Node * candidate) + { + return is_function(candidate, "and") || (walk_or && is_function(candidate, "or")); + }; + + /// An alias is the same value under a new name, so it keeps the polarity of what it wraps. A filter + /// often arrives wrapped in one, and an `AND` behind it is just as safe as an unwrapped one. + auto skip_aliases = [&](const Node * node) + { + while (node->type == ActionType::ALIAS && num_parents[node->children.front()] == 1) + node = node->children.front(); + return node; + }; + + if (const auto * root = skip_aliases(filter_node); is_and_or_or(root)) + to_visit.push(root); + + while (!to_visit.empty()) + { + const auto * node = to_visit.top(); + to_visit.pop(); + + if (is_function(node, "and")) + conjuncts_safe_to_drop.insert(node); + + for (const auto * child : node->children) + if (num_parents[child] == 1) + if (const auto * nested = skip_aliases(child); is_and_or_or(nested)) + to_visit.push(nested); + } + } + /// Phase 1: Traverse the DAG and determine which nodes can be computed { struct Frame @@ -4086,14 +4212,20 @@ ActionsDAG ActionsDAG::restrictFilterDAGToInputs(const ActionsDAG::Node * filter { const auto & name = frame.node->function_base->getName(); - /// Replace non-computable child in "and" with constant true. - if (name == "and") + /// Replace non-computable child in "and" with constant true. `Nullable(Nothing)` has no true value. + if (name == "and" && conjuncts_safe_to_drop.contains(frame.node) && num_parents[child] == 1) { - auto const_column = child->result_type->createColumnConst(0, 1); - copy_map[child] = &actions.addColumn(std::move(const_column), child->result_type, child->result_name); + Field true_value = convertFieldToType(Field(static_cast(1)), *child->result_type); + if (!true_value.isNull()) + { + auto const_column = child->result_type->createColumnConst(0, true_value); + copy_map[child] = &actions.addColumn(std::move(const_column), child->result_type, child->result_name); + if (substitutes) + substitutes->insert(copy_map[child]); - /// Mark as now computable (since we substituted it) - it->second = true; + /// Mark as now computable (since we substituted it) + it->second = true; + } } } } @@ -4114,6 +4246,17 @@ ActionsDAG ActionsDAG::restrictFilterDAGToInputs(const ActionsDAG::Node * filter } } + /// A non-computable conjunct was left in place, so the filter cannot be expressed over + /// `available_inputs`. An always-true filter keeps the contract that the result only widens the + /// original; reconstructing this one would reference an input that is not available. + if (auto it = can_compute.find(filter_node); it == can_compute.end() || !it->second) + { + ActionsDAG all_true; + auto uint8_type = std::make_shared(); + all_true.outputs.push_back(&all_true.addColumn(uint8_type->createColumnConst(0, 1), uint8_type, "true")); + return all_true; + } + /// Phase 2: Reconstruct the DAG using copy_map struct Frame { diff --git a/src/Interpreters/ActionsDAG.h b/src/Interpreters/ActionsDAG.h index 4a96af748b92..e7a557ed5c4e 100644 --- a/src/Interpreters/ActionsDAG.h +++ b/src/Interpreters/ActionsDAG.h @@ -328,7 +328,9 @@ class ActionsDAG void substituteInputForConsumersOnly(const std::string & input_name, const ColumnWithTypeAndName & replacement); /// Clone the DAG, retaining only the subgraph computable from the specified available input columns. - /// Special handling for logical AND: non-computable children are replaced with constant true. + /// The result only ever widens the filter: a non-computable child of a logical AND is replaced with + /// constant true where that AND is read with positive polarity, and a filter that cannot be expressed + /// at all becomes constant true. /// Useful for evaluating boolean filters in projection indices when some input columns are missing. ActionsDAG restrictFilterDAGToInputs(const ActionsDAG::Node * filter_node, const NameSet & available_inputs) const; @@ -575,6 +577,14 @@ class ActionsDAG private: NodeRawConstPtrs getParents(const Node * target) const; + /// See `restrictFilterDAGToInputs`; `walk_or` also weakens an `AND` under an `OR`, and `substitutes` receives + /// the constants that replace a conjunct. + ActionsDAG restrictFilterDAGToInputsImpl( + const Node * filter_node, + const NameSet & available_inputs, + bool walk_or, + std::unordered_set * substitutes = nullptr) const; + Node & addNode(Node node); const Node & addFunctionImpl( diff --git a/src/Interpreters/AggregateDescription.cpp b/src/Interpreters/AggregateDescription.cpp index 5b93ed3d9978..64c0e02ed9d9 100644 --- a/src/Interpreters/AggregateDescription.cpp +++ b/src/Interpreters/AggregateDescription.cpp @@ -2,9 +2,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include @@ -15,6 +18,7 @@ namespace DB namespace ErrorCodes { extern const int LOGICAL_ERROR; + extern const int INCORRECT_DATA; } void AggregateDescription::explain(WriteBuffer & out, const std::string & prefix, size_t additonal_indent) const @@ -285,4 +289,176 @@ void deserializeAggregateDescriptionsWithoutArguments(AggregateDescriptions & ag } } +void checkDeserializedAggregateArguments(const AggregateDescriptions & aggregates, const Block & header) +{ + for (const auto & aggregate : aggregates) + { + /// `AggregateFunctionFactory` resolves functions for the types without `LowCardinality`, + /// and the `Aggregator` removes it from the argument columns accordingly. + const auto & argument_types = aggregate.function->getArgumentTypes(); + if (argument_types.size() != aggregate.argument_names.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Aggregate function {} of a deserialized query plan step has {} argument types for {} arguments", + aggregate.column_name, argument_types.size(), aggregate.argument_names.size()); + + for (size_t i = 0; i < argument_types.size(); ++i) + { + const auto & name = aggregate.argument_names[i]; + const auto * column = header.findByName(name); + if (!column) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Argument {} of aggregate function {} is not in the input of a deserialized query plan step", + name, aggregate.column_name); + + if (!recursiveRemoveLowCardinality(column->type)->equals(*recursiveRemoveLowCardinality(argument_types[i]))) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Argument {} of aggregate function {} has type {} in the input of a deserialized query plan step, " + "but the function is resolved for {}", + name, aggregate.column_name, column->type->getName(), argument_types[i]->getName()); + } + } +} + +void checkDeserializedFinalizedAggregates(const AggregateDescriptions & aggregates, const Block & header) +{ + for (const auto & aggregate : aggregates) + { + const auto * column = header.findByName(aggregate.column_name); + if (!column) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} is not in the input of a deserialized query plan step", + aggregate.column_name); + + const auto * state_type = typeid_cast(column->type.get()); + if (!state_type || !state_type->getFunction()->haveSameStateRepresentation(*aggregate.function)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} has type {} in the input of a deserialized query plan step, " + "which is not a state of {}", + aggregate.column_name, column->type->getName(), aggregate.function->getName()); + } +} + +void checkDeserializedAggregateOutputNames(const Names & keys, const AggregateDescriptions & aggregates) +{ + /// The output header has a column for every key and aggregate, and the finalization finds the states by name, + /// so a repeated name would leave a state of the second occurrence unfinalized under a finalized type. + NameSet names; + for (const auto & key : keys) + if (!names.insert(key).second) + throw Exception(ErrorCodes::INCORRECT_DATA, "Duplicate key or aggregate function {} in a deserialized query plan step", key); + for (const auto & aggregate : aggregates) + if (!names.insert(aggregate.column_name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step", aggregate.column_name); +} + +void checkDeserializedMergedAggregatesLayout( + const Names & keys, const AggregateDescriptions & aggregates, const ColumnsWithTypeAndName & layout, bool exact) +{ + const size_t keys_size = keys.size(); + if (exact && layout.size() != keys_size + aggregates.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized query plan step merging aggregate states has {} columns " + "instead of {} keys and {} aggregate functions", + layout.size(), keys_size, aggregates.size()); + if (layout.size() < keys_size + aggregates.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized query plan step merging aggregate states has {} columns " + "for {} keys and {} aggregate functions", + layout.size(), keys_size, aggregates.size()); + + /// The `Aggregator` looks up the types of the keys and the states by name, but merges the columns + /// by position. With distinct names at the expected positions, both refer to the same columns. + NameSet names; + for (size_t i = 0; i < keys_size; ++i) + { + if (!names.insert(keys[i]).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", keys[i]); + if (layout[i].name != keys[i]) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} is expected at position {} of the input of a deserialized query plan step merging aggregate states, " + "but there is {}", + keys[i], i, layout[i].name); + } + + for (size_t i = 0; i < aggregates.size(); ++i) + { + const auto & aggregate = aggregates[i]; + const auto & column = layout[keys_size + i]; + if (!names.insert(aggregate.column_name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", + aggregate.column_name); + if (column.name != aggregate.column_name) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} is expected at position {} of the input of a deserialized query plan step, " + "but there is {}", + aggregate.column_name, keys_size + i, column.name); + + const auto * state_type = typeid_cast(column.type.get()); + if (!state_type || !state_type->getFunction()->haveSameStateRepresentation(*aggregate.function)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} has type {} in the input of a deserialized query plan step, " + "which is not a state of {}", + aggregate.column_name, column.type->getName(), aggregate.function->getName()); + } + + /// The headers of the merge-only steps are built from the whole input, so a later column with the name + /// of a key or a state would also be there, but not in the merged chunks. + for (size_t i = keys_size + aggregates.size(); i < layout.size(); ++i) + { + if (names.contains(layout[i].name)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Duplicate key or aggregate function {} in a deserialized query plan step merging aggregate states", + layout[i].name); + } +} + +namespace +{ + +/// A single chunk of a merge-only input is finalized as is, with the functions of its columns rather than those of the plan, +/// while the output header takes the result types from the plan. Functions with the same state representation +/// (like `quantile` and `quantiles`) may have different result types. `layout` is already checked to start with the keys and the states. +void checkDeserializedMergedStatesResultTypes( + const Names & keys, const AggregateDescriptions & aggregates, const ColumnsWithTypeAndName & layout) +{ + for (size_t i = 0; i < aggregates.size(); ++i) + { + const auto & aggregate = aggregates[i]; + const auto & column = layout[keys.size() + i]; + const auto & state_function = typeid_cast(*column.type).getFunction(); + if (!state_function->getResultType()->equals(*aggregate.function->getResultType())) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The state of aggregate function {} has type {} in the input of a deserialized query plan step, " + "which is finalized to {} instead of {}", + aggregate.column_name, column.type->getName(), state_function->getResultType()->getName(), + aggregate.function->getResultType()->getName()); + } +} + +} + +void checkDeserializedMergeOnlyInput(const Names & keys, const AggregateDescriptions & aggregates, const Block & header) +{ + /// The transforms address the whole input with a mask built for the keys and the states only. + const auto & layout = header.getColumnsWithTypeAndName(); + checkDeserializedMergedAggregatesLayout(keys, aggregates, layout, /*exact=*/ true); + /// Checked even without `final`: the step may be made final later (`setFinal`), and the states + /// of a legitimate plan come from the same functions anyway. + checkDeserializedMergedStatesResultTypes(keys, aggregates, layout); +} + +void checkDeserializedGroupByModifierInput( + const Names & keys, const AggregateDescriptions & aggregates, bool final, const Block & header) +{ + /// `RollupTransform` and `CubeTransform` always finalize the states (both planners build the steps with `final`), + /// so a step without it would advertise states in the output header but produce finalized values. + if (!final) + throw Exception(ErrorCodes::INCORRECT_DATA, "A deserialized `Rollup` or `Cube` step must finalize the aggregate states"); + + checkDeserializedMergeOnlyInput(keys, aggregates, header); +} + } diff --git a/src/Interpreters/AggregateDescription.h b/src/Interpreters/AggregateDescription.h index 1d42b76b7e6c..609181f8f1cc 100644 --- a/src/Interpreters/AggregateDescription.h +++ b/src/Interpreters/AggregateDescription.h @@ -1,7 +1,10 @@ #pragma once +#include + #include #include +#include #include #include #include @@ -39,4 +42,32 @@ void deserializeAggregateDescriptions(AggregateDescriptions & aggregates, ReadBu void serializeAggregateDescriptionsWithoutArguments(const AggregateDescriptions & aggregates, WriteBuffer & out); void deserializeAggregateDescriptionsWithoutArguments(AggregateDescriptions & aggregates, ReadBuffer & in, size_t max_type_complexity); +/// The aggregate functions of a deserialized query plan are resolved from the types written in the plan, +/// but they are executed on the columns of the step's input. The plan may come from an untrusted client, +/// so check that they agree, or a function would interpret a column of another type. Both throw `INCORRECT_DATA`. + +/// The arguments of the aggregates are found in the input by name and must have the types the functions are resolved for. +void checkDeserializedAggregateArguments(const AggregateDescriptions & aggregates, const Block & header); + +/// The steps finalizing the states (`TotalsHaving`) find them in the input by name: every aggregate must name +/// a column of the input holding a state of the same representation as its function. +void checkDeserializedFinalizedAggregates(const AggregateDescriptions & aggregates, const Block & header); + +/// The steps merging the states read the keys and then the states by position: `layout` (the input as it reaches +/// the `Aggregator`) must start with `keys` and then the states of `aggregates` (named by `column_name`), in order. +/// With `exact`, there must be no other columns. +void checkDeserializedMergedAggregatesLayout( + const Names & keys, const AggregateDescriptions & aggregates, const ColumnsWithTypeAndName & layout, bool exact = false); + +/// The names of the keys and the aggregates (the columns of the output) must be distinct. +void checkDeserializedAggregateOutputNames(const Names & keys, const AggregateDescriptions & aggregates); + +/// The input of the merge-only `Aggregating` step: exactly the keys and then the states, finalized to the types of the plan +/// (`AggregatingInOrderTransform` and the finalization of a single chunk keep the functions of the input). +void checkDeserializedMergeOnlyInput(const Names & keys, const AggregateDescriptions & aggregates, const Block & header); + +/// The input of `Rollup` and `Cube`: `final`, exactly the keys and then the states, finalized to the types of the plan. +void checkDeserializedGroupByModifierInput( + const Names & keys, const AggregateDescriptions & aggregates, bool final, const Block & header); + } diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index a68b1e466234..8a2dc138f80e 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -102,7 +102,6 @@ namespace Setting extern const SettingsString parallel_replicas_custom_key; extern const SettingsUInt64 parallel_replicas_custom_key_range_lower; extern const SettingsUInt64 parallel_replica_offset; - extern const SettingsSnappyMode snappy_mode; } namespace ErrorCodes @@ -502,7 +501,7 @@ AsynchronousInsertQueue::pushQueryWithInlinedData(ASTPtr query, ContextPtr query /// If limit is exceeded we will fallback to synchronous insert /// to avoid buffering of huge amount of data in memory. - auto read_buf = getReadBufferFromASTInsertQuery(query, query_context->getSettingsRef()[Setting::snappy_mode]); + auto read_buf = getReadBufferFromASTInsertQuery(query, query_context); LimitReadBuffer limit_buf( *read_buf, @@ -547,6 +546,17 @@ AsynchronousInsertQueue::pushQueryWithInlinedData(ASTPtr query, ContextPtr query AsynchronousInsertQueue::PushResult AsynchronousInsertQueue::pushQueryWithBlock(ASTPtr query, Block && block, ContextPtr query_context) { + /// The flush copies queued blocks into full columns with `insertRangeFrom`, whose `assert_cast` would misread a + /// wrapped column (`Sparse`, `Replicated`, ...) at any nesting depth. Every producer materializes before queuing. + /// An insert without data queues a block without columns. + for (const auto & elem : block) + if (elem.column && elem.column->convertToFullIfWrapped().get() != elem.column.get()) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Async insert block column '{}' must be materialized before queuing, but has a " + "non-default serialization representation: {}", + elem.name, elem.column->dumpStructure()); + query = query->clone(); preprocessInsertQuery(query, query_context); return pushDataChunk(std::move(query), std::move(block), std::move(query_context)); diff --git a/src/Interpreters/DatabaseCatalog.cpp b/src/Interpreters/DatabaseCatalog.cpp index dcb7839e0b61..bcdb55b44eea 100644 --- a/src/Interpreters/DatabaseCatalog.cpp +++ b/src/Interpreters/DatabaseCatalog.cpp @@ -69,9 +69,6 @@ namespace ServerSetting { extern const ServerSettingsUInt64 database_atomic_delay_before_drop_table_sec; extern const ServerSettingsUInt64 database_catalog_drop_error_cooldown_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_cleanup_period_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_hide_timeout_sec; - extern const ServerSettingsUInt64 database_catalog_unused_dir_rm_timeout_sec; } namespace ErrorCodes @@ -258,13 +255,6 @@ void DatabaseCatalog::initializeAndLoadTemporaryDatabase() void DatabaseCatalog::createBackgroundTasks() { /// It has to be done before databases are loaded (to avoid a race condition on initialization) - if (Context::getGlobalContextInstance()->getApplicationType() == Context::ApplicationType::SERVER && getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_cleanup_period_sec]) - { - auto cleanup_task_holder - = getContext()->getSchedulePool()->createTask(StorageID::createEmpty(), "DatabaseCatalogCleanupStoreDirectoryTask", [this]() { this->cleanupStoreDirectoryTask(); }); - cleanup_task = std::make_unique(std::move(cleanup_task_holder)); - } - auto drop_task_holder = getContext()->getSchedulePool()->createTask(StorageID::createEmpty(), "DatabaseCatalogDropTableTask", [this](){ this->dropTableDataTask(); }); drop_task = std::make_unique(std::move(drop_task_holder)); @@ -274,14 +264,6 @@ void DatabaseCatalog::createBackgroundTasks() void DatabaseCatalog::startupBackgroundTasks() { - /// And it has to be done after all databases are loaded, otherwise cleanup_task may remove something that should not be removed - if (cleanup_task) - { - (*cleanup_task)->activate(); - /// Do not start task immediately on server startup, it's not urgent. - (*cleanup_task)->scheduleAfter(static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_hide_timeout_sec]) * 1000); - } - (*drop_task)->activate(); std::lock_guard lock{tables_marked_dropped_mutex}; if (!tables_marked_dropped.empty()) @@ -293,9 +275,6 @@ void DatabaseCatalog::shutdownImpl(std::function shutdown_system_logs) is_shutting_down = true; wait_table_finally_dropped.notify_all(); - if (cleanup_task) - (*cleanup_task)->deactivate(); - if (drop_task) (*drop_task)->deactivate(); @@ -1278,8 +1257,6 @@ DatabaseAndTable DatabaseCatalog::tryGetDatabaseAndTable(const StorageID & table void DatabaseCatalog::loadMarkedAsDroppedTables() { - chassert(!cleanup_task); - auto component_guard = Coordination::setCurrentComponent("DatabaseCatalog::loadMarkedAsDroppedTables"); // Because some DBs might have a `disk` setting defining the disk to store the table metadata files, // we need to check the dropped metadata on these disks, not just the default database disk. @@ -2086,128 +2063,6 @@ void DatabaseCatalog::checkTablesCanBeExchangedWithNoCyclicDependencies(const St check(loading_dependencies); } -void DatabaseCatalog::cleanupStoreDirectoryTask() -{ - for (const auto & [disk_name, disk] : getContext()->getDisksMap()) - { - if (!disk->supportsStat() || !disk->supportsChmod()) - continue; - - size_t affected_dirs = 0; - size_t checked_dirs = 0; - for (auto it = disk->iterateDirectory("store"); it->isValid(); it->next()) - { - String prefix = it->name(); - bool expected_prefix_dir = disk->existsDirectory(it->path()) && prefix.size() == 3 && isHexDigit(prefix[0]) && isHexDigit(prefix[1]) - && isHexDigit(prefix[2]); - - if (!expected_prefix_dir) - { - LOG_WARNING(log, "Found invalid directory {} on disk {}, will try to remove it", it->path(), disk_name); - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, it->path()); - continue; - } - - for (auto jt = disk->iterateDirectory(it->path()); jt->isValid(); jt->next()) - { - String uuid_str = jt->name(); - UUID uuid; - bool parsed = tryParse(uuid, uuid_str); - - bool expected_dir = disk->existsDirectory(jt->path()) && parsed && uuid != UUIDHelpers::Nil && uuid_str.starts_with(prefix); - - if (!expected_dir) - { - LOG_WARNING(log, "Found invalid directory {} on disk {}, will try to remove it", jt->path(), disk_name); - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, jt->path()); - continue; - } - - /// Order is important - if (!hasUUIDMapping(uuid)) - { - /// We load uuids even for detached and permanently detached tables, - /// so it looks safe enough to remove directory if we don't have uuid mapping for it. - /// No table or database using this directory should concurrently appear, - /// because creation of new table would fail with "directory already exists". - checked_dirs += 1; - affected_dirs += maybeRemoveDirectory(disk_name, disk, jt->path()); - } - } - } - - if (affected_dirs) - LOG_INFO(log, "Cleaned up {} directories from store/ on disk {}", affected_dirs, disk_name); - if (checked_dirs == 0) - LOG_TEST(log, "Nothing to clean up from store/ on disk {}", disk_name); - } - - (*cleanup_task)->scheduleAfter(static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_cleanup_period_sec]) * 1000); -} - -bool DatabaseCatalog::maybeRemoveDirectory(const String & disk_name, const DiskPtr & disk, const String & unused_dir) -{ - /// "Safe" automatic removal of some directory. - /// At first we do not remove anything and only revoke all access right. - /// And remove only if nobody noticed it after, for example, one month. - - try - { - struct stat st = disk->stat(unused_dir); - - if (st.st_uid != geteuid()) - { - /// Directory is not owned by clickhouse, it's weird, let's ignore it (chmod will likely fail anyway). - LOG_WARNING(log, "Found directory {} with unexpected owner (uid={}) on disk {}", unused_dir, st.st_uid, disk_name); - return false; - } - - time_t max_modification_time = std::max({st.st_atime, st.st_mtime, st.st_ctime}); - time_t current_time = time(nullptr); - if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) - { - if (current_time <= max_modification_time + static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_hide_timeout_sec])) - return false; - - LOG_INFO(log, "Removing access rights for unused directory {} from disk {} (will remove it when timeout exceed)", unused_dir, disk_name); - - /// Explicitly update modification time just in case - - disk->setLastModified(unused_dir, Poco::Timestamp::fromEpochTime(current_time)); - - /// Remove all access right - disk->chmod(unused_dir, 0); - - return true; - } - - auto unused_dir_rm_timeout_sec = static_cast(getContext()->getServerSettings()[ServerSetting::database_catalog_unused_dir_rm_timeout_sec]); - - if (!unused_dir_rm_timeout_sec) - return false; - - if (current_time <= max_modification_time + unused_dir_rm_timeout_sec) - return false; - - LOG_INFO(log, "Removing unused directory {} from disk {}", unused_dir, disk_name); - - /// We have to set these access rights to make recursive removal work - disk->chmod(unused_dir, S_IRWXU); - - disk->removeRecursive(unused_dir); - - return true; - } - catch (...) - { - tryLogCurrentException(log, fmt::format("Failed to remove unused directory {} from disk {} ({})", - unused_dir, disk->getName(), disk->getPath())); - return false; - } -} - void DatabaseCatalog::reloadDisksTask() { std::set disks; diff --git a/src/Interpreters/DatabaseCatalog.h b/src/Interpreters/DatabaseCatalog.h index a2fbfb538c69..72031715c896 100644 --- a/src/Interpreters/DatabaseCatalog.h +++ b/src/Interpreters/DatabaseCatalog.h @@ -321,9 +321,6 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext void dropTablesParallel(TablesMarkedAsDropped tables); void rescheduleDropTableTask(); - void cleanupStoreDirectoryTask(); - bool maybeRemoveDirectory(const String & disk_name, const DiskPtr & disk, const String & unused_dir); - void reloadDisksTask(); static constexpr size_t reschedule_time_ms = 100; @@ -378,7 +375,6 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext std::unique_ptr drop_task; std::condition_variable wait_table_finally_dropped; - std::unique_ptr cleanup_task; std::unique_ptr reload_disks_task; std::mutex reload_disks_mutex; @@ -392,7 +388,8 @@ class DatabaseCatalog : boost::noncopyable, WithMutableContext /// This class is useful when creating a table or database. /// Usually we create IStorage/IDatabase object first and then add it to IDatabase/DatabaseCatalog. /// But such object may start using a directory in store/ since its creation. -/// To avoid race with cleanupStoreDirectoryTask() we have to mark UUID as used first. +/// To prevent another table or database from using the same UUID (and so the same directory) +/// concurrently, we have to mark UUID as used first. /// Then we can either add DatabasePtr/StoragePtr to the created UUID mapping /// or remove the lock if creation failed. /// See also addUUIDMapping(...) diff --git a/src/Interpreters/ExternalDictionariesLoader.cpp b/src/Interpreters/ExternalDictionariesLoader.cpp index 32671c5668eb..403aebdea6fe 100644 --- a/src/Interpreters/ExternalDictionariesLoader.cpp +++ b/src/Interpreters/ExternalDictionariesLoader.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -96,8 +97,16 @@ void ExternalDictionariesLoader::updateObjectFromConfigWithoutReloading(IExterna ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::getDictionary(const std::string & dictionary_name, ContextPtr local_context) const { - std::string resolved_dictionary_name = resolveDictionaryName(dictionary_name, local_context->getCurrentDatabase()); + return loadDictionary(resolveDictionaryName(dictionary_name, local_context->getCurrentDatabase()), local_context); +} + +ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::getDictionary(const ResolvedDictionary & dictionary, ContextPtr local_context) const +{ + return loadDictionary(dictionary.getKey(), local_context); +} +ExternalDictionariesLoader::DictPtr ExternalDictionariesLoader::loadDictionary(const std::string & resolved_dictionary_name, ContextPtr local_context) const +{ /// Check if we have a cancellable query context QueryStatusPtr process_list_element; if (local_context->hasQueryContext()) @@ -167,8 +176,16 @@ void ExternalDictionariesLoader::unloadAllDictionaries() const DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const std::string & dictionary_name, ContextPtr query_context) const { - std::string resolved_name = resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()); + return getDictionaryStructureByKey(resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()), dictionary_name); +} +DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const ResolvedDictionary & dictionary) const +{ + return getDictionaryStructureByKey(dictionary.getKey(), dictionary.name); +} + +DictionaryStructure ExternalDictionariesLoader::getDictionaryStructureByKey(const std::string & resolved_name, const std::string & dictionary_name) const +{ auto load_result = getLoadResult(resolved_name); if (load_result.object) @@ -183,10 +200,69 @@ DictionaryStructure ExternalDictionariesLoader::getDictionaryStructure(const std return ExternalDictionariesLoader::getDictionaryStructure(*load_result.config); } +const std::string & ExternalDictionariesLoader::ResolvedDictionary::getKey() const +{ + if (key.empty()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(name)); + return key; +} + +ExternalDictionariesLoader::ResolvedDictionary +ExternalDictionariesLoader::resolveDictionary(const std::string & dictionary_name, ContextPtr query_context) const +{ + return resolveDictionary(dictionary_name, query_context->getCurrentDatabase(), query_context); +} + +ExternalDictionariesLoader::ResolvedDictionary ExternalDictionariesLoader::resolveDictionary( + const std::string & dictionary_name, const std::string & current_database_name, ContextPtr /*query_context*/) const +{ + auto resolved = resolveDictionaryNameUnchecked(dictionary_name, current_database_name); + + /// One lookup decides whether the dictionary exists, so that a dictionary removed concurrently is reported like any + /// missing one, after the access check. + auto load_result = getLoadResult(resolved.key); + + if (!load_result.object && !load_result.config) + { + /// An empty name names no dictionary at all, so there is nothing to check access to. + if (resolved.qualified_name.table.empty()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(dictionary_name)); + + /// The read that follows the access check reports the missing dictionary to a user with access. + return {dictionary_name, {}, StorageID(resolved.qualified_name.database, resolved.qualified_name.table)}; + } + + if (load_result.object) + { + const auto dictionary = std::static_pointer_cast(load_result.object); + return {dictionary_name, std::move(resolved.key), dictionary->getDictionaryID()}; + } + + auto dictionary_id = StorageID::fromDictionaryConfig(*load_result.config->config, load_result.config->key_in_config); + return {dictionary_name, std::move(resolved.key), std::move(dictionary_id)}; +} + +ExternalDictionariesLoader::ResolvedDictionary +ExternalDictionariesLoader::resolveDictionaryCheckingAccess(const std::string & dictionary_name, ContextPtr query_context) const +{ + auto dictionary = resolveDictionary(dictionary_name, query_context); + query_context->checkAccess( + AccessType::dictGet, IDictionary::getDatabaseOrNoDatabaseTag(dictionary.id), dictionary.id.getTableName()); + return dictionary; +} + std::string ExternalDictionariesLoader::getDictionaryLayoutType(const std::string & dictionary_name, ContextPtr query_context) const { - std::string resolved_name = resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()); + return getDictionaryLayoutTypeByKey(resolveDictionaryName(dictionary_name, query_context->getCurrentDatabase()), dictionary_name); +} +std::string ExternalDictionariesLoader::getDictionaryLayoutType(const ResolvedDictionary & dictionary) const +{ + return getDictionaryLayoutTypeByKey(dictionary.getKey(), dictionary.name); +} + +std::string ExternalDictionariesLoader::getDictionaryLayoutTypeByKey(const std::string & resolved_name, const std::string & dictionary_name) const +{ auto load_result = getLoadResult(resolved_name); if (!load_result.config) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary {} config not found", backQuote(dictionary_name)); @@ -203,11 +279,6 @@ std::string ExternalDictionariesLoader::getDictionaryLayoutType(const std::strin return layout_keys.front(); } -void ExternalDictionariesLoader::assertDictionaryStructureExists(const std::string & dictionary_name, ContextPtr query_context) const -{ - getDictionaryStructure(dictionary_name, query_context); -} - QualifiedTableName ExternalDictionariesLoader::qualifyDictionaryNameWithDatabase(const std::string & dictionary_name, ContextPtr query_context) const { auto qualified_name = QualifiedTableName::tryParseFromString(dictionary_name); @@ -245,6 +316,23 @@ std::string ExternalDictionariesLoader::resolveDictionaryName(const std::string throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary ({}) not found", backQuote(dictionary_name)); } +ExternalDictionariesLoader::ResolvedDictionaryName ExternalDictionariesLoader::resolveDictionaryNameUnchecked(const std::string & dictionary_name, const std::string & current_database_name) const +{ + if (has(dictionary_name)) + return {dictionary_name, QualifiedTableName::tryParseFromString(dictionary_name).value_or(QualifiedTableName{.database = {}, .table = dictionary_name})}; + + /// The name with the database filled in, as `resolveDictionaryNameFromDatabaseCatalog` qualifies it. + auto key = resolveDictionaryNameFromDatabaseCatalog(dictionary_name, current_database_name); + auto qualified_name = QualifiedTableName::tryParseFromString(dictionary_name); + if (!qualified_name) + return {std::move(key), QualifiedTableName{.database = {}, .table = dictionary_name}}; + + if (qualified_name->database.empty()) + qualified_name->database = current_database_name; + + return {std::move(key), std::move(*qualified_name)}; +} + std::string ExternalDictionariesLoader::resolveDictionaryNameFromDatabaseCatalog(const std::string & name, const std::string & current_database_name) const { /// If it's dictionary from Atomic database, then we need to convert qualified name to UUID. @@ -269,6 +357,14 @@ std::string ExternalDictionariesLoader::resolveDictionaryNameFromDatabaseCatalog res = current_database_name + '.' + name; } + /// Only a database with its own tables can contain a DDL dictionary. Do not ask any other database for the table: + /// the name is resolved before access is checked, and e.g. a `PostgreSQL` database would query its remote server. + if (qualified_name->database.empty()) + return res; + auto database = DatabaseCatalog::instance().tryGetDatabase(qualified_name->database); + if (!database || database->isExternal()) + return res; + auto [db, table] = DatabaseCatalog::instance().tryGetDatabaseAndTable( {qualified_name->database, qualified_name->table}, const_pointer_cast(getContext())); diff --git a/src/Interpreters/ExternalDictionariesLoader.h b/src/Interpreters/ExternalDictionariesLoader.h index 5473a544d015..22477abc0c30 100644 --- a/src/Interpreters/ExternalDictionariesLoader.h +++ b/src/Interpreters/ExternalDictionariesLoader.h @@ -4,6 +4,7 @@ #include #include #include +#include #include @@ -40,7 +41,36 @@ class ExternalDictionariesLoader : public ExternalLoader, WithContext /// a definition whose layout element does not have exactly one child, like loading it would. std::string getDictionaryLayoutType(const std::string & dictionary_name, ContextPtr context) const; - void assertDictionaryStructureExists(const std::string & dictionary_name, ContextPtr context) const; + /// A dictionary name resolved once, so that an access check and the reads after it refer to the same dictionary. + /// The reads go by `key`, which for a dictionary in an `Atomic` database is its UUID and does not change on rename. + /// For an XML dictionary or one in an `Ordinary` database the key is the name. + struct ResolvedDictionary + { + /// The name as the query wrote it. + std::string name; + /// The key the loader stores the dictionary under, empty if there is no such dictionary. + std::string key; + /// The ID to check access rights with, taken from the loaded dictionary if there is one, otherwise from its + /// configuration. For a dictionary that does not exist, the ID it would have, so that a user without access + /// gets the access error and cannot tell a missing dictionary from an existing one. + StorageID id; + + /// Throws if there is no such dictionary. + [[nodiscard]] const std::string & getKey() const; + }; + + /// Resolves the name without loading the dictionary, so that access can be checked before loading. + [[nodiscard]] ResolvedDictionary resolveDictionary(const std::string & dictionary_name, ContextPtr query_context) const; + + /// The same, resolving an unqualified name against the given database rather than the current database of the query. + [[nodiscard]] ResolvedDictionary resolveDictionary(const std::string & dictionary_name, const std::string & current_database_name, ContextPtr query_context) const; + + /// The same, and checks that the user of `query_context` has `dictGet` on the dictionary. + [[nodiscard]] ResolvedDictionary resolveDictionaryCheckingAccess(const std::string & dictionary_name, ContextPtr query_context) const; + + [[nodiscard]] DictPtr getDictionary(const ResolvedDictionary & dictionary, ContextPtr local_context) const; + [[nodiscard]] DictionaryStructure getDictionaryStructure(const ResolvedDictionary & dictionary) const; + [[nodiscard]] std::string getDictionaryLayoutType(const ResolvedDictionary & dictionary) const; /// Reloads all previously tried-to-load dictionaries in topological order /// based on their source dependencies (dictionaries sourcing from other dictionaries). @@ -71,6 +101,21 @@ class ExternalDictionariesLoader : public ExternalLoader, WithContext std::string resolveDictionaryName(const std::string & dictionary_name, const std::string & current_database_name) const; + /// Both readings of one resolution: the key the loader stores the dictionary under, and the name as a query refers + /// to it with the database filled in. + struct ResolvedDictionaryName + { + std::string key; + QualifiedTableName qualified_name; + }; + + /// The same as `resolveDictionaryName`, but the key may name no dictionary. + ResolvedDictionaryName resolveDictionaryNameUnchecked(const std::string & dictionary_name, const std::string & current_database_name) const; + + DictPtr loadDictionary(const std::string & key, ContextPtr local_context) const; + DictionaryStructure getDictionaryStructureByKey(const std::string & key, const std::string & dictionary_name) const; + std::string getDictionaryLayoutTypeByKey(const std::string & key, const std::string & dictionary_name) const; + /// Try convert qualified dictionary name to persistent UUID std::string resolveDictionaryNameFromDatabaseCatalog(const std::string & name, const std::string & current_database_name) const; diff --git a/src/Interpreters/InternalTextLogsQueue.cpp b/src/Interpreters/InternalTextLogsQueue.cpp index 26dc14176d8e..e7a0da2ea75b 100644 --- a/src/Interpreters/InternalTextLogsQueue.cpp +++ b/src/Interpreters/InternalTextLogsQueue.cpp @@ -40,7 +40,10 @@ void InternalTextLogsQueue::pushBlock(Block && log_block) { static Block sample_block = getSampleBlock(); - if (blocksHaveEqualStructure(sample_block, log_block)) + /// The block is laid out by another server, and the columns of the queue are appended to each other + /// when they are sent to the client, so even the representation of every column has to be the expected + /// one. That is why it is not `blocksHaveEqualStructure`, for which a sparse column is equal to an ordinary one. + if (blocksHaveIdenticalStructure(sample_block, log_block)) (void)(emplace(log_block.mutateColumns())); else LOG_WARNING(getLogger("InternalTextLogsQueue"), "Log block have different structure"); diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index 74ad63632341..432df890aa7e 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -823,8 +823,9 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccess(const StoragePtr & for (const auto & child : alter.command_list->children) { const auto & command = child->as(); - required_access.append_range( - getRequiredAccessForCommand(command, alter.getDatabase(), alter.getTable(), row_exists_is_marker)); + required_access.append_range(getRequiredAccessForCommand( + command, alter.getDatabase(), alter.getTable(), row_exists_is_marker, + storage && alter.cluster.empty() ? storage->getName() : "")); if (command.type == ASTAlterCommand::MODIFY_QUERY && !sql_security_is_being_replaced) addRequiredAccessForModifyQuerySQLSecurity(required_access, storage); @@ -834,7 +835,11 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccess(const StoragePtr & } AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand( - const ASTAlterCommand & command, const String & database, const String & table, bool row_exists_is_lightweight_marker) + const ASTAlterCommand & command, + const String & database, + const String & table, + bool row_exists_is_lightweight_marker, + const String & engine) { AccessRightsElements required_access; @@ -1018,11 +1023,14 @@ AccessRightsElements InterpreterAlterQuery::getRequiredAccessForCommand( /// A setting that sends the table's data elsewhere, e.g. the move destination of a queue, is the same data flow as /// `INSERT INTO FUNCTION s3(...) SELECT * FROM
`. The creator of the table supplied its source and credentials, - /// so the reading part is `SELECT` on the table. The grants do not depend on the engine of the table, so the initiator - /// of `ON CLUSTER` can check them without the table. + /// so the reading part is `SELECT` on the table. For `ON CLUSTER`, `engine` is empty, so the grants can be checked + /// without the table. if (command.type == ASTAlterCommand::MODIFY_SETTING && command.settings_changes) { - auto export_access = StorageFactory::instance().getExportAccessOfAnyEngine(command.settings_changes->as().changes); + const auto & changes = command.settings_changes->as().changes; + auto export_access = engine.empty() + ? StorageFactory::instance().getExportAccessOfAnyEngine(changes) + : StorageFactory::instance().getExportAccess(changes, engine); if (!export_access.empty()) { required_access.append_range(std::move(export_access)); diff --git a/src/Interpreters/InterpreterAlterQuery.h b/src/Interpreters/InterpreterAlterQuery.h index ebb9deddba45..782bb3b18ebd 100644 --- a/src/Interpreters/InterpreterAlterQuery.h +++ b/src/Interpreters/InterpreterAlterQuery.h @@ -27,8 +27,13 @@ class InterpreterAlterQuery : public IInterpreter, WithMutableContext /// lightweight-delete marker of the target table (not an ordinary physical column with that name); /// it gates the `_row_exists = 0` -> ALTER DELETE shortcut in the UPDATE command. Pass false to fail /// closed (e.g. a non-local ON CLUSTER target, or ALTER DATABASE). + /// `engine` is the engine of the table, empty for `ON CLUSTER`. static AccessRightsElements getRequiredAccessForCommand( - const ASTAlterCommand & command, const String & database, const String & table, bool row_exists_is_lightweight_marker); + const ASTAlterCommand & command, + const String & database, + const String & table, + bool row_exists_is_lightweight_marker, + const String & engine = {}); /// True when `_row_exists` is the hidden virtual lightweight-delete marker of `storage`, i.e. not /// an ordinary physical column with that name (as is possible on engines like `Memory`). Null diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 2e39a90b830b..36295ae51ca4 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -52,7 +53,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -61,6 +64,8 @@ #include #include +#include +#include #include #include #include @@ -204,6 +209,41 @@ namespace ErrorCodes namespace fs = std::filesystem; +namespace +{ + +/// Returns the named collection that the source of a dictionary refers to with the key `name`, if any. +/// The constant expressions of the source must be already evaluated. +std::optional getNamedCollectionOfDictionarySource(const ASTCreateQuery & create) +{ + if (!create.dictionary || !create.dictionary->source || !create.dictionary->source->elements) + return {}; + + for (const auto & child : create.dictionary->source->elements->children) + { + const auto * pair = child->as(); + if (!pair || Poco::toLower(pair->first) != "name") + continue; + + String name; + if (const auto * identifier = pair->second->as()) + name = identifier->name(); + else if (const auto * literal = pair->second->as(); literal && literal->value.getType() == Field::Types::String) + name = literal->value.safeGet(); + else + throw Exception(ErrorCodes::BAD_ARGUMENTS, "The name of a named collection in a dictionary source must be a string"); + + /// The source reads the name from the dictionary configuration, which expands `${...}` with other values of the + /// definition (`${dictionary.comment}`), so the authorized name would not be the one used. + if (name.contains("${")) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "The name of a named collection in a dictionary source cannot contain `${{`: {}", name); + return name; + } + return {}; +} + +} + InterpreterCreateQuery::InterpreterCreateQuery(const ASTPtr & query_ptr_, ContextMutablePtr context_) : WithMutableContext(context_), query_ptr(query_ptr_) { @@ -1121,6 +1161,22 @@ void InterpreterCreateQuery::validateTableStructure(const ASTCreateQuery & creat } } +SharedHeader InterpreterCreateQuery::getMaterializedViewSampleBlock(const ASTCreateQuery & create) const +{ + /// We should treat SELECT as an initial query in order to properly analyze it. + auto context = Context::createCopy(getContext()); + context->setQueryKindInitial(); + + /// For refreshable materialized views, use the MV's database as context. + /// This ensures unqualified references resolve in the MV's database, not session's database. + if (create.refresh_strategy) + context->setCurrentDatabaseUnchecked(create.getDatabase()); + + return InterpreterSelectQueryAnalyzer::getSampleBlock(create.select->clone(), + context, + SelectQueryOptions{}.analyze().createView().checkSubqueryTableAccess()); +} + void InterpreterCreateQuery::validateMaterializedViewColumnsAndEngine(const ASTCreateQuery & create, const TableProperties & properties, const DatabasePtr & database) { /// This is not strict validation, just catches common errors that would make the view not work. @@ -1175,20 +1231,7 @@ void InterpreterCreateQuery::validateMaterializedViewColumnsAndEngine(const ASTC try { if (getContext()->getSettingsRef()[Setting::allow_experimental_analyzer]) - { - /// We should treat SELECT as an initial query in order to properly analyze it. - auto context = Context::createCopy(getContext()); - context->setQueryKindInitial(); - - /// For refreshable materialized views, use the MV's database as context. - /// This ensures unqualified references resolve in the MV's database, not session's database. - if (create.refresh_strategy) - context->setCurrentDatabaseUnchecked(create.getDatabase()); - - input_block = InterpreterSelectQueryAnalyzer::getSampleBlock(create.select->clone(), - context, - SelectQueryOptions{}.analyze().createView().checkSubqueryTableAccess()); - } + input_block = getMaterializedViewSampleBlock(create); else { /// For refreshable materialized views with old analyzer, use MV's database context. @@ -1991,7 +2034,10 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) /// Only here is an engine inherited through `AS` known, and nothing is enqueued or created yet. /// A replay of a stored definition was checked when it was created. if (isFreshTableDefinition(mode, create.attach_short_syntax)) + { checkExportAccess(create); + checkDictionaryEngineAccess(create); + } DatabasePtr database; bool need_add_to_database = !create.isTemporary(); @@ -2007,6 +2053,28 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) getContext()->setSetting("flatten_nested", false); validateMaterializedViewColumnsAndEngine(create, properties, database); } + else if (create.select && create.is_materialized_view && is_restore_from_backup && !is_secondary_query) + { + /// A restore does not validate the view, but checks the rights for the tables that its query reads, as `CREATE` does. + try + { + (void)getMaterializedViewSampleBlock(create); + } + catch (Exception & e) + { + if (e.code() == ErrorCodes::ACCESS_DENIED) + throw; + + /// The query cannot be analyzed, for example a table or a named collection is missing. Then the rights are checked + /// for every table that it names. A table function checks its rights when the view runs. + const auto dependencies = getDependenciesFromCreateQuery( + getContext()->getGlobalContext(), {create.getDatabase(), create.getTable()}, query_ptr, getContext()->getCurrentDatabase()); + for (const auto & table : dependencies.dependencies) + getContext()->checkAccess(AccessType::SELECT, table.database, table.table); + if (dependencies.mv_from_dependency) + getContext()->checkAccess(AccessType::SELECT, *dependencies.mv_from_dependency); + } + } bool is_storage_replicated = false; if (create.storage && isReplicated(*create.storage)) @@ -3555,6 +3623,16 @@ BlockIO InterpreterCreateQuery::execute() create.if_not_exists |= getContext()->getSettingsRef()[Setting::create_if_not_exists]; bool is_create_database = create.database && !create.table; + + /// `getRequiredAccess` must authorize the named collection that is stored and sent to other hosts, so the constant + /// expressions of the source of a dictionary are evaluated once, here: one can return a new value at each evaluation + /// (`randConstant()`). The later evaluation in `getTablePropertiesAndNormalizeCreateQuery` does not change literals. + if (create.is_dictionary && create.dictionary && create.dictionary->source) + { + NormalizeAndEvaluateConstantsVisitor::Data visitor_data{getContext()}; + NormalizeAndEvaluateConstantsVisitor(visitor_data).visit(create.dictionary->source->ptr()); + } + if (!create.cluster.empty() && !maybeRemoveOnCluster(query_ptr, getContext())) { if (create.attach_as_replicated.has_value()) @@ -3571,6 +3649,9 @@ BlockIO InterpreterCreateQuery::execute() && create.storage->engine->name == "Backup" && create.storage->engine->arguments) DatabaseBackup::parseAndAuthorizeLocator(create.storage->engine->arguments->children, getContext()); + if (!is_create_database) + checkDictionaryEngineAccess(create); + /// this branch returns before setEngine, and the worker builds AS src with no user, so /// check the inherited definition here, on a copy of the query if (!create.as_table.empty()) @@ -3610,6 +3691,7 @@ BlockIO InterpreterCreateQuery::execute() /// the worker inherits the move destination of the source too, and runs with no user checkExportAccess(inherited); + checkDictionaryEngineAccess(inherited); /// A worker copies the source's indices with no user, so declare their transforms here. if (inherited.storage && inherited.storage->engine && endsWith(inherited.storage->engine->name, "MergeTree")) @@ -3672,6 +3754,11 @@ AccessRightsElements InterpreterCreateQuery::getRequiredAccess() const else if (create.is_dictionary) { required_access.emplace_back(AccessType::CREATE_DICTIONARY, create.getDatabase(), create.getTable()); + + /// The dictionary is loaded with the global context, which has access to every named collection. + /// So the privilege to use the collection of its source, required by table engines and table functions, is required here. + if (auto collection_name = getNamedCollectionOfDictionarySource(create)) + required_access.emplace_back(AccessType::NAMED_COLLECTION, *collection_name); } else if (create.isView()) { @@ -3745,6 +3832,67 @@ void InterpreterCreateQuery::checkExportAccess(const ASTCreateQuery & create) co getContext()->checkAccess(StorageFactory::instance().getExportAccess(create)); } +void InterpreterCreateQuery::checkDictionaryEngineAccess(ASTCreateQuery & create) const +{ + /// Internal queries (initiated by the server itself) always have access to everything. A replay of `ON CLUSTER` or of a + /// `Replicated` database was checked before it was enqueued, while it still ran as the user, and runs without the user. + if (internal || getContext()->isDDLOrOnClusterInternal()) + return; + + /// An unqualified dictionary name is resolved against the current database of the query that creates the storage + /// and loads the dictionary, so check the dictionary that this query resolves to. + const String & server_default_database = getContext()->getGlobalContext()->getCurrentDatabase(); + String execution_database; + if (!create.cluster.empty()) + { + /// A replay of `ON CLUSTER` runs in the default database of the server. + execution_database = server_default_database; + } + else + { + String database_name = getContext()->resolveDatabase(create.getDatabase()); + auto database = DatabaseCatalog::instance().tryGetDatabase(database_name); + /// A replay in a `Replicated` database runs in that database. + execution_database = database && database->shouldReplicateQuery(getContext(), query_ptr) ? database_name : getContext()->getCurrentDatabase(); + } + + auto check = [&](ASTs & arguments, const String & current_database) + { + /// A wrong number of arguments is reported when the storage is created. + if (arguments.size() != 1) + return; + + /// Keep the name that is checked in the query, so that a replica executing it does not evaluate the argument + /// to another dictionary. + arguments[0] = evaluateConstantExpressionOrIdentifierAsLiteral(arguments[0], getContext()); + auto dictionary_name = checkAndGetLiteralArgument(arguments[0], "dictionary_name"); + const auto & external_loader = getContext()->getExternalDictionariesLoader(); + StorageDictionary::checkDictionaryAccess(external_loader.resolveDictionary(dictionary_name, current_database, getContext()).id, getContext()); + }; + + auto check_engine = [&](ASTStorage & storage) + { + if (storage.engine && storage.engine->name == "Dictionary" && storage.engine->arguments) + check(storage.engine->arguments->children, execution_database); + }; + + if (create.storage) + check_engine(*create.storage); + if (create.targets) + { + for (ASTStorage * inner_engine : create.targets->getInnerEngines()) + check_engine(*inner_engine); + } + + /// `CREATE TABLE ... AS dictionary(...)` creates the storage with the global context, see `doCreateTable`. + if (create.as_table_function) + { + auto & function = create.as_table_function->as(); + if (function.name == "dictionary" && function.arguments) + check(function.arguments->children, server_default_database); + } +} + void InterpreterCreateQuery::extendQueryLogElemImpl(QueryLogElement & elem, const ASTPtr &, ContextPtr) const { if (!as_table_saved.empty()) @@ -3866,6 +4014,17 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr else if (!to_replicated) throw Exception(ErrorCodes::INCORRECT_QUERY, "Can not attach table as not replicated, table is already not replicated"); + /// A short `ATTACH` carries no engine of its own, so `getRequiredAccess` requires no `TABLE ENGINE` grant for it, and + /// `getTablePropertiesAndNormalizeCreateQuery` checks the grant for the converted engine only after the side effects + /// below, which cannot be rolled back. So the converted engine is checked here, before them, as a `CREATE` with that + /// engine would be checked. A converted engine that is not registered is refused first: a grant such as + /// `TABLE ENGINE ON *` would cover it, and the rewritten definition could not be attached. + const String converted_engine_name = DatabaseOrdinary::getConvertedMergeTreeEngineName(engine_name, to_replicated); + if (!StorageFactory::instance().getAllStorages().contains(converted_engine_name)) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, + "Table engine conversion is not supported for {}: there is no table engine {}", engine_name, converted_engine_name); + getContext()->checkAccess(AccessType::TABLE_ENGINE, converted_engine_name); + /// Must precede every side effect below: neither the transaction metadata removal nor the /// metadata rewrite can be rolled back. The other direction takes no Keeper path at all. if (to_replicated) @@ -3900,6 +4059,7 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr /// Set new engine DatabaseOrdinary::setMergeTreeEngine(create, getContext(), to_replicated); + chassert(create.storage->engine->name == converted_engine_name); /// Save new metadata auto db_disk = database->getDisk(); diff --git a/src/Interpreters/InterpreterCreateQuery.h b/src/Interpreters/InterpreterCreateQuery.h index 9baa88d61bbd..d2130bdb37f2 100644 --- a/src/Interpreters/InterpreterCreateQuery.h +++ b/src/Interpreters/InterpreterCreateQuery.h @@ -113,6 +113,8 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext /// Calculate list of columns, constraints, indices, etc... of table. Rewrite query in canonical way. TableProperties getTablePropertiesAndNormalizeCreateQuery(ASTCreateQuery & create, LoadingStrictnessLevel mode); void validateTableStructure(const ASTCreateQuery & create, const TableProperties & properties) const; + /// Analyzes the query of a materialized view as the user. Throws without the rights for a table that it reads. + [[nodiscard]] SharedHeader getMaterializedViewSampleBlock(const ASTCreateQuery & create) const; void validateMaterializedViewColumnsAndEngine(const ASTCreateQuery & create, const TableProperties & properties, const DatabasePtr & database); void setEngine(ASTCreateQuery & create) const; AccessRightsElements getRequiredAccess() const; @@ -121,6 +123,12 @@ class InterpreterCreateQuery : public IInterpreter, WithMutableContext /// `setEngine` has resolved an engine inherited through `AS`, which `getRequiredAccess` cannot see. void checkExportAccess(const ASTCreateQuery & create) const; + /// A `Dictionary` table, including the inner table of a materialized view and a table created `AS dictionary(...)`, + /// needs access to the dictionary it reads, see `StorageDictionary::checkDictionaryAccess`. Checked here, while the + /// query still runs as the user: `Replicated` and `ON CLUSTER` replays run with full access, and so does the deferred + /// creation of a table function with an explicit column list. Replaces the dictionary name argument with the evaluated name. + void checkDictionaryEngineAccess(ASTCreateQuery & create) const; + /// Create IStorage and add it to database. If table already exists and IF NOT EXISTS specified, do nothing and return false. bool doCreateTable(ASTCreateQuery & create, const TableProperties & properties, DDLGuardPtr & ddl_guard, LoadingStrictnessLevel mode); BlockIO doCreateOrReplaceTable(ASTCreateQuery & create, const InterpreterCreateQuery::TableProperties & properties, LoadingStrictnessLevel mode); diff --git a/src/Interpreters/InterpreterHypotheticalIndexQuery.cpp b/src/Interpreters/InterpreterHypotheticalIndexQuery.cpp index 0cbd5e978c65..e84819faa7a2 100644 --- a/src/Interpreters/InterpreterHypotheticalIndexQuery.cpp +++ b/src/Interpreters/InterpreterHypotheticalIndexQuery.cpp @@ -108,12 +108,7 @@ BlockIO InterpreterHypotheticalIndexQuery::execute() if (index_desc.expression) context->checkAccess(AccessType::SELECT, table_id, index_desc.expression->getRequiredColumns()); - /// validate() must run before get(): index creators assume their arguments were already - /// validated and read them unguarded (e.g. set/bloom_filter index.arguments->children[0]), - /// so calling get() on an unvalidated user AST can dereference absent arguments. - MergeTreeIndexFactory::instance().validate(index_desc, /* attach = */ false, *merge_tree->getSettings()); - - /// fail closed, a newly registered index type is rejected until someone checks it + /// fail closed before the validation, which analyzes the arguments: a new index type is rejected until someone checks it static constexpr std::string_view supported_types[] {"bloom_filter", "minmax", "ngrambf_v1", "set", "sparse_grams", "tokenbf_v1"}; if (!std::ranges::contains(supported_types, index_desc.type)) @@ -123,6 +118,11 @@ BlockIO InterpreterHypotheticalIndexQuery::execute() index_desc.type, fmt::join(supported_types, ", ")); + /// validate() must run before get(): index creators assume their arguments were already + /// validated and read them unguarded (e.g. set/bloom_filter index.arguments->children[0]), + /// so calling get() on an unvalidated user AST can dereference absent arguments. + MergeTreeIndexFactory::instance().validate(index_desc, /* attach = */ false, *merge_tree->getSettings()); + /// some argument checks live in the creator, not the validator (tokenizer bounds for /// sparse_grams), so construct once here instead of failing later inside EXPLAIN WHATIF MergeTreeIndexFactory::instance().get(metadata, index_desc, *merge_tree->getSettings()); diff --git a/src/Interpreters/InterpreterSelectQuery.cpp b/src/Interpreters/InterpreterSelectQuery.cpp index df906bbd51b0..140b549ac533 100644 --- a/src/Interpreters/InterpreterSelectQuery.cpp +++ b/src/Interpreters/InterpreterSelectQuery.cpp @@ -881,11 +881,25 @@ InterpreterSelectQuery::InterpreterSelectQuery( && context->getClientInfo().distributed_depth == 0 && context->canUseParallelReplicasCustomKeyForCluster(*context->getClusterForParallelReplicas())) { - /// The key is evaluated on the replicas on behalf of this user. - parallel_replicas_custom_key_ast_to_check - = parseCustomKeyForTable(settings[Setting::parallel_replicas_custom_key], *context); + /// The replicas match `additional_table_filters` against their own current database, so they can miss + /// a filter that matched here and return the rows it excludes. Read without parallel replicas, as the analyzer does. + if (!settings[Setting::additional_table_filters].value.empty()) + { + if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) + throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, + "additional_table_filters is not supported with parallel replicas with a custom key"); - context->setSetting("prefer_localhost_replica", Field(0)); + LOG_DEBUG(log, "Disabling parallel replicas with a custom key to execute a query with additional_table_filters"); + context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); + } + else + { + /// The key is evaluated on the replicas on behalf of this user. + parallel_replicas_custom_key_ast_to_check + = parseCustomKeyForTable(settings[Setting::parallel_replicas_custom_key], *context); + + context->setSetting("prefer_localhost_replica", Field(0)); + } } } diff --git a/src/Interpreters/InterpreterSystemQuery.cpp b/src/Interpreters/InterpreterSystemQuery.cpp index a152a634c05d..52b79626f724 100644 --- a/src/Interpreters/InterpreterSystemQuery.cpp +++ b/src/Interpreters/InterpreterSystemQuery.cpp @@ -2526,6 +2526,7 @@ void InterpreterSystemQuery::instrumentWithXRay(bool add, ASTSystemQuery & query void InterpreterSystemQuery::syncReplicatedDatabase(ASTSystemQuery & query) { const auto database_name = query.getDatabase(); + getContext()->checkAccess(AccessType::SYSTEM_SYNC_DATABASE_REPLICA, database_name); auto guard = DatabaseCatalog::instance().getDDLGuard(database_name, "", nullptr); auto database = DatabaseCatalog::instance().getDatabase(database_name); diff --git a/src/Interpreters/JoinedTables.cpp b/src/Interpreters/JoinedTables.cpp index fda8e3e8f45e..20cb318a5908 100644 --- a/src/Interpreters/JoinedTables.cpp +++ b/src/Interpreters/JoinedTables.cpp @@ -5,13 +5,14 @@ #include #include +#include #include #include #include #include #include #include -#include +#include #include #include @@ -373,26 +374,13 @@ std::shared_ptr JoinedTables::makeTableJoin(const ASTSelectQuery & se } auto storage_dict = std::dynamic_pointer_cast(storage); - if (storage_dict && try_use_direct_join && storage_dict->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) + if (storage_dict && try_use_direct_join) { - FunctionDictHelper dictionary_helper(context); - - auto dictionary_name = storage_dict->getDictionaryName(); - auto dictionary = dictionary_helper.getDictionary(dictionary_name); - if (!dictionary) - { - LOG_TRACE(getLogger("JoinedTables"), "Can't use dictionary join: dictionary '{}' was not found", dictionary_name); - return nullptr; - } - if (dictionary->getSpecialKeyType() == DictionarySpecialKeyType::Range) - { - LOG_TRACE(getLogger("JoinedTables"), "Can't use dictionary join: dictionary '{}' is a range dictionary", dictionary_name); - return nullptr; - } - - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - auto dictionary_kv = std::dynamic_pointer_cast(dictionary); - table_join->setStorageJoin(dictionary_kv); + /// This runs even if the right table is not read, e.g. for `CREATE VIEW`, so the access must be checked here. + auto dictionary = storage_dict->getDictionary(context); + if (dictionary->getSpecialKeyType() != DictionarySpecialKeyType::Range) + /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. + table_join->setStorageJoin(std::dynamic_pointer_cast(dictionary)); } if (auto storage_kv = castStorage(storage, DeferredTable::Load); storage_kv && try_use_direct_join) diff --git a/src/Interpreters/MutationsInterpreter.cpp b/src/Interpreters/MutationsInterpreter.cpp index 3be2fee7b8c8..c8f882735fcf 100644 --- a/src/Interpreters/MutationsInterpreter.cpp +++ b/src/Interpreters/MutationsInterpreter.cpp @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -1804,6 +1805,19 @@ void MutationsInterpreter::prepare(bool dry_run) materialized_projections.insert(projection.name); } + /// A mutation that does not rewrite the whole part keeps the lightweight-deleted rows in it, + /// so a rebuilt projection needs `_row_exists` to leave them out. + const auto & source_part = source.getMergeTreeDataPart(); + const bool projections_see_deleted_mask = settings.return_all_columns + || std::ranges::any_of(stages, [](const Stage & stage) + { return stage.affects_all_columns || stage.column_to_updated.contains(RowExistsColumn::name); }); + if (!materialized_projections.empty() && source_part && source_part->hasLightweightDelete() && !projections_see_deleted_mask) + { + auto & stage = stages.emplace_back(context); + stage.is_readonly = true; + stage.column_to_updated.emplace(RowExistsColumn::name, make_intrusive(RowExistsColumn::name)); + } + /// Every column emitted by a non-readonly stage is written into the new part at its current /// metadata type, so its statistics have to be recomputed rather than carried over from the /// source part. `updated_columns` and `changed_columns` do not cover all emitters: MATERIALIZE @@ -2333,6 +2347,9 @@ static void buildSubqueryPlansForSetsAndAdd(QueryPlan & query_plan, const Prepar if (subqueries.empty()) return; + /// Materialized CTEs referenced by each planned set subquery. + std::vector materialized_ctes_per_subquery; + for (auto & subquery : subqueries) { if (subquery->get()) @@ -2363,6 +2380,10 @@ static void buildSubqueryPlansForSetsAndAdd(QueryPlan & query_plan, const Prepar std::make_shared(nullptr, nullptr, nullptr, FiltersForTableExpressionMap{})); subquery_planner.buildQueryPlanIfNeeded(); + /// The subquery planner has built the plans of the CTEs it references, so the collector + /// admits them here (`hasPlanOrBuilt`). They are planted below, after the sets step. + materialized_ctes_per_subquery.push_back(collectMaterializedCTEs(query_tree, SelectQueryOptions{})); + auto subquery_plan = std::move(subquery_planner).extractQueryPlan(); for (const auto & ctx : subquery_plan.getInterpretersContexts()) query_plan.addInterpreterContext(ctx); @@ -2382,6 +2403,12 @@ static void buildSubqueryPlansForSetsAndAdd(QueryPlan & query_plan, const Prepar network_transfer_limits, prepared_sets_cache); query_plan.addStep(std::move(step)); + + /// `DelayedCreatingSetsStep::makePlansForSets` strips the safety-net `DelayedMaterializingCTEsStep` + /// from a set plan built at run time and relies on the outer plan to gate the CTE readers, which + /// the `Planner` provides for a `SELECT`. This plan is assembled here, so plant that step here. + for (const auto & materialized_ctes : materialized_ctes_per_subquery) + addBuildSubqueriesForMaterializedCTEsIfNeeded(query_plan, SelectQueryOptions{}, materialized_ctes); } std::optional MutationsInterpreter::createFilterDAGForStage(const Stage & stage) diff --git a/src/Interpreters/ProfileEventsExt.cpp b/src/Interpreters/ProfileEventsExt.cpp index 17df2e4a8c9c..062c59e14c20 100644 --- a/src/Interpreters/ProfileEventsExt.cpp +++ b/src/Interpreters/ProfileEventsExt.cpp @@ -19,6 +19,7 @@ namespace DB::ErrorCodes { extern const int LOGICAL_ERROR; + extern const int UNEXPECTED_PACKET_FROM_SERVER; } namespace ProfileEvents @@ -138,6 +139,22 @@ DB::Block getSampleBlock() return Block(std::move(temp_columns)); } +void checkBlockStructure(const DB::Block & block) +{ + using namespace DB; + + static const Block sample_block = getSampleBlock(); + + /// Not `blocksHaveEqualStructure`: a sparse column of the expected type is as unusable for the + /// consumers as a column of another type. + if (!blocksHaveIdenticalStructure(sample_block, block)) + throw Exception( + ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER, + "Unexpected structure of a block with profile events: {}, expected: {}", + block.dumpStructure(), + sample_block.dumpStructure()); +} + DB::Block getProfileEvents( const String & host_name, DB::InternalProfileEventsQueuePtr profile_queue, @@ -193,6 +210,11 @@ DB::Block getProfileEvents( /// after the queue creation decision was already made during connection setup. while (profile_queue && profile_queue->tryPop(curr_block)) { + /// The blocks of the queue are the packets of other servers. They are checked where they are + /// received (see `Connection::receiveProfileEvents`), but the columns are appended below by position + /// and without a check of their types, so whatever has put a block into the queue, it must fit. + checkBlockStructure(curr_block); + auto curr_columns = curr_block.getColumns(); for (size_t j = 0; j < curr_columns.size(); ++j) columns[j]->insertRangeFrom(*curr_columns[j], 0, curr_columns[j]->size()); diff --git a/src/Interpreters/ProfileEventsExt.h b/src/Interpreters/ProfileEventsExt.h index ff6eaee01880..c81469f618c8 100644 --- a/src/Interpreters/ProfileEventsExt.h +++ b/src/Interpreters/ProfileEventsExt.h @@ -37,6 +37,11 @@ void dumpToMapColumn(const Counters::Snapshot & counters, DB::IColumn * column, DB::Block getSampleBlock(); +/// Throws if `block` is not laid out exactly as `getSampleBlock`: the same names, types and kinds of columns +/// in the same order. A `ProfileEvents` packet is produced by another server, and its consumers address the +/// columns by position and cast them to the exact types, so it has to be checked before any of them gets it. +void checkBlockStructure(const DB::Block & block); + DB::Block getProfileEvents( const String & host_name, DB::InternalProfileEventsQueuePtr profile_queue, diff --git a/src/Interpreters/Session.cpp b/src/Interpreters/Session.cpp index 17521ee3d1bc..11f745395f40 100644 --- a/src/Interpreters/Session.cpp +++ b/src/Interpreters/Session.cpp @@ -753,7 +753,11 @@ ContextMutablePtr Session::makeQueryContextImpl(const ClientInfo * client_info_t query_context->setClientVersion(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, DBMS_TCP_PROTOCOL_VERSION); } - if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY) + if (query_context->getClientInfo().query_kind == ClientInfo::QueryKind::INITIAL_QUERY || + /// Some places can send SECONDARY_QUERY with initial_user empty (e.g. dictionaries), and this is OK, + /// it should not block subsequent queries over TCP_INTERSERVER in this session + /// (Connection::sendQuery() forbids forwarding if initial_user != current_user) + (query_context->getClientInfo().initial_user.empty() && !query_context->getClientInfo().current_user.empty())) { query_context->setInitialUserName(query_context->getClientInfo().current_user); query_context->setInitialAddress(*query_context->getClientInfo().current_address); diff --git a/src/Interpreters/TreeOptimizer.cpp b/src/Interpreters/TreeOptimizer.cpp index eeb30eb20f13..c54b77bee8ac 100644 --- a/src/Interpreters/TreeOptimizer.cpp +++ b/src/Interpreters/TreeOptimizer.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include @@ -163,7 +165,19 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NamesAndTypesList & so const auto & dict_name = dict_name_ast->value.safeGet(); const auto & attr_name = attr_name_ast->value.safeGet(); - const auto & dict_ptr = context->getExternalDictionariesLoader().getDictionary(dict_name, context); + const auto & external_loader = context->getExternalDictionariesLoader(); + + /// Do not load the dictionary for a user without access to it, because loading contacts + /// the dictionary source. The query fails later with the proper access error. + auto dictionary = external_loader.resolveDictionary(dict_name, context); + if (!context->getAccess()->isGranted( + AccessType::dictGet, IDictionary::getDatabaseOrNoDatabaseTag(dictionary.id), dictionary.id.getTableName())) + { + ++i; + continue; + } + + const auto & dict_ptr = external_loader.getDictionary(dictionary, context); if (!dict_ptr->isInjective(attr_name)) { ++i; diff --git a/src/Interpreters/loadMetadata.cpp b/src/Interpreters/loadMetadata.cpp index 43f691b47993..e7f3f8937459 100644 --- a/src/Interpreters/loadMetadata.cpp +++ b/src/Interpreters/loadMetadata.cpp @@ -555,7 +555,6 @@ static void maybeConvertOrdinaryDatabaseToAtomic(ContextMutablePtr context, cons executeTrivialBlockIO(res, context); /// Unlock UUID mapping, because it will be locked again on database reload. - /// It's safe to do during metadata loading, because cleanup task is not started yet. DatabaseCatalog::instance().removeUUIDMappingFinally(db_uuid); for (const auto & uuid : tables_uuids) DatabaseCatalog::instance().removeUUIDMappingFinally(uuid); diff --git a/src/Parsers/ASTFunctionWithKeyValueArguments.cpp b/src/Parsers/ASTFunctionWithKeyValueArguments.cpp index 17156bf476ef..6eaaae3cce7d 100644 --- a/src/Parsers/ASTFunctionWithKeyValueArguments.cpp +++ b/src/Parsers/ASTFunctionWithKeyValueArguments.cpp @@ -24,12 +24,14 @@ namespace /// of the `HTTP` source, whose values often carry API tokens. The headers are hidden as a whole, /// names included: the query is logged before the dictionary source validates its structure, /// so a malformed definition must not leak either. + /// The `url` and `endpoint` of the `HTTP` source are hidden whole: the userinfo, the path or the query can carry credentials. bool isSecretKey(const String & key) { return key == "password" || key == "ssl_ca_pem" || key == "ssl_cert_pem" || key == "ssl_key_pem" || key == "sslrootcert_pem" || key == "sslcert_pem" || key == "sslkey_pem" - || key == "headers" || key == "header"; + || key == "headers" || key == "header" + || key == "url" || key == "endpoint"; } } @@ -110,7 +112,16 @@ void ASTPair::formatImpl(WriteBuffer & ostr, const FormatSettings & settings, Fo bool ASTPair::hasSecretParts() const { - return isSecretKey(first) || second->hasSecretParts(); + if (isSecretKey(first)) + return true; + /// The `uri` is a secret part only when it carries a password, see `formatImpl`. + if (first == "uri") + { + String uri = second->formatWithSecretsOneLine(); + if (maskURIPassword(&uri)) + return true; + } + return second->hasSecretParts(); } diff --git a/src/Parsers/ASTSQLSecurity.cpp b/src/Parsers/ASTSQLSecurity.cpp index de06a9ce4591..cee6efc22df9 100644 --- a/src/Parsers/ASTSQLSecurity.cpp +++ b/src/Parsers/ASTSQLSecurity.cpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace DB { @@ -23,7 +24,14 @@ void ASTSQLSecurity::formatImpl(WriteBuffer & ostr, const FormatSettings & setti { ostr << "DEFINER"; ostr << " = "; - if (definer) + if (definer && Poco::toUpper(definer->getBaseName()) == "CURRENT_USER") + { + /// Unquoted, a user named `CURRENT_USER` would be parsed back as the keyword. + FormatSettings quoted_settings = settings; + quoted_settings.identifier_quoting_rule = IdentifierQuotingRule::Always; + definer->format(ostr, quoted_settings, state, frame); + } + else if (definer) definer->format(ostr, settings, state, frame); else ostr << "CURRENT_USER"; diff --git a/src/Parsers/Access/ASTUserNameWithHost.h b/src/Parsers/Access/ASTUserNameWithHost.h index 8c755143ceb4..47d32fb12248 100644 --- a/src/Parsers/Access/ASTUserNameWithHost.h +++ b/src/Parsers/Access/ASTUserNameWithHost.h @@ -22,6 +22,7 @@ class ASTUserNameWithHost : public IAST String getHostPattern() const; String toString() const; + String getBaseName() const; String getID(char) const override { return "UserNameWithHost"; } ASTPtr clone() const override; @@ -35,7 +36,6 @@ class ASTUserNameWithHost : public IAST private: String getStringFromAST(const ASTPtr & ast) const; - String getBaseName() const; ASTPtr username; ASTPtr host_pattern; diff --git a/src/Parsers/FieldFromAST.cpp b/src/Parsers/FieldFromAST.cpp index 4f86b56edbeb..a868ddd42f89 100644 --- a/src/Parsers/FieldFromAST.cpp +++ b/src/Parsers/FieldFromAST.cpp @@ -13,6 +13,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; + extern const int ILLEGAL_TYPE_OF_ARGUMENT; } Field createFieldFromAST(ASTPtr ast) @@ -25,6 +26,17 @@ Field createFieldFromAST(ASTPtr ast) throw Exception(ErrorCodes::LOGICAL_ERROR, "Method {} not implemented for {}", method, getTypeName()); } +bool FieldFromASTImpl::operator == (const CustomTypeImpl & rhs) const +{ + if (std::string_view(getTypeName()) != std::string_view(rhs.getTypeName())) + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Comparing custom types with different type names: {} and {}", + getTypeName(), rhs.getTypeName()); + + /// Compare the unmasked text: masking rewrites every credential to `[HIDDEN]`, so two values + /// differing only in a credential would compare equal. + return toString(/*show_secrets=*/ true) == rhs.toString(/*show_secrets=*/ true); +} + bool FieldFromASTImpl::isSecret() const { return isDiskFunction(ast); diff --git a/src/Parsers/FieldFromAST.h b/src/Parsers/FieldFromAST.h index a69c086a1709..7c5eb6a50603 100644 --- a/src/Parsers/FieldFromAST.h +++ b/src/Parsers/FieldFromAST.h @@ -21,7 +21,7 @@ struct FieldFromASTImpl : public CustomType::CustomTypeImpl bool operator <= (const CustomTypeImpl &) const override { throwNotImplemented("<="); } bool operator > (const CustomTypeImpl &) const override { throwNotImplemented(">"); } bool operator >= (const CustomTypeImpl &) const override { throwNotImplemented(">="); } - bool operator == (const CustomTypeImpl &) const override { throwNotImplemented("=="); } + bool operator == (const CustomTypeImpl & rhs) const override; ASTPtr ast; }; diff --git a/src/Parsers/FunctionSecretArgumentsFinder.cpp b/src/Parsers/FunctionSecretArgumentsFinder.cpp index 90d584a1d004..4132fe984ea9 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.cpp +++ b/src/Parsers/FunctionSecretArgumentsFinder.cpp @@ -332,6 +332,12 @@ void FunctionSecretArgumentsFinder::findOrdinaryFunctionSecretArguments() findHMACSecretArguments(); return; } + if ((name == "sipHash64Keyed") || (name == "sipHash128Keyed") || (name == "sipHash128ReferenceKeyed")) + { + /// sipHash64Keyed((k0, k1), 'message') -> sipHash64Keyed('[HIDDEN]', 'message') + markSecretArgument(0); + return; + } if (name == "bigquery") { /// Accepts positional arguments after named ones and models their slots itself. diff --git a/src/Planner/CollectMaterializedCTE.cpp b/src/Planner/CollectMaterializedCTE.cpp index de159bb3c13d..3eac5175ce8b 100644 --- a/src/Planner/CollectMaterializedCTE.cpp +++ b/src/Planner/CollectMaterializedCTE.cpp @@ -3,10 +3,19 @@ #include #include #include +#include +#include +#include +#include +#include namespace DB { +namespace ErrorCodes +{ + extern const int LOGICAL_ERROR; +} namespace { @@ -77,4 +86,120 @@ OrderedMaterializedCTEs collectMaterializedCTEs(const QueryTreeNodePtr & node, c return ctes_by_level; } +void addBuildSubqueriesForMaterializedCTEsIfNeeded( + QueryPlan & query_plan, + const SelectQueryOptions & select_query_options, + const OrderedMaterializedCTEs & materialized_ctes +) +{ + /// Logical plans are built for serialization to a remote node. `DelayedMaterializingCTEsStep` + /// is stripped on the way out (`Serialization.cpp`), and the only surviving side effect of + /// building it here would be to populate the shared `MaterializedCTE::plan` with a logical + /// (serialize-only) version that the non-logical planner pass would then reuse for local + /// execution and crash on. The materialization is owned by the non-logical pass; remote + /// nodes read from the temp storage by name. + if (select_query_options.build_logical_plan) + return; + + if (materialized_ctes.empty()) + return; + + // The main idea of the algorithm is to unite plans for Materialized CTEs of the same level + // with the main query plan by MaterializingCTEsStep. + // + // This allows to ensure following properties: + // 1) All CTEs are executed before the main query. + // 2) If CTE A depends on CTE B, then A will be executed after B, because A will be on the next level after B. + // 3) CTEs on the same level are independent. + // 3) CTEs of the same level will be executed in the same MaterializingCTEsStep, so they will be executed in parallel. + // 4) Materialized CTEs are executed only once. + // + // Example of query plan structure for query with 2 levels of CTEs: + // + // ┌───────────────────────┐ + // │ │ + // ┌────│ MaterializingCTEsStep │────────────────────────────┐ + // │ │ │ │ │ + // │ └───────────────────────┘ │ │ + // │ │ │ + // │ │ │ + // ┌───────────▼───────────┐ ┌────────▼───────┐ ┌────────▼───────┐ + // │ │ │ │ │ │ + // ┌────────│ MaterializingCTEsStep │─────────┐ │ CTE (level: 0) │ │ CTE (level: 0) │ + // │ │ │ │ │ │ │ │ + // │ └───────────────────────┘ │ └────────────────┘ └────────────────┘ + // │ │ + // │ │ + // ┌──────▼─────┐ ┌────────▼───────┐ + // │ │ │ │ + // │ Query Plan │ │ CTE (level: 1) │ + // │ │ │ │ + // └────────────┘ └────────────────┘ + // + // The CTEs are added as DelayedMaterializingCTEsStep nodes — one per level — so that + // resolveMaterializingCTEs can skip already-materialized CTEs. This is important when + // buildOrderedSetInplace runs a subquery plan that contains CTEs: by the time the main + // plan's resolveMaterializingCTEs fires, is_planned is already true for those CTEs + // so they won't be materialized a second time. + // + // The level structure is preserved: for each level we push one DelayedMaterializingCTEsStep + // on top of the current plan, wrapping it the same way the old eager approach did with + // MaterializingCTEsStep. resolveMaterializingCTEs processes nodes post-order, so the inner + // (lower-level) step is resolved before the outer one, guaranteeing that a CTE at level N + // is always materialized before the CTE at level N-1 that depends on it. + for (const auto & cte_level : materialized_ctes) + { + std::vector ctes; + ctes.reserve(cte_level.size()); + + for (const auto & cte_node : cte_level) + { + auto * cte_table_node = cte_node->as(); + auto materialized_cte = cte_table_node->getMaterializedCTE(); + if (!materialized_cte->hasPlanOrBuilt()) + { + auto cte_subquery = cte_table_node->getMaterializedCTESubquery(); + /// A by-name reference carries no subquery, but a standalone pipeline still needs a + /// gate for it, and the handle alone is enough to build one. The writer stays with + /// whoever holds the subquery. + if (!cte_subquery && select_query_options.force_materialize_cte) + { + ctes.push_back(materialized_cte); + continue; + } + if (!cte_subquery) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "CTE '{}' does not have query tree, but was not planned yet", + materialized_cte->cte_name); + + auto cte_options = select_query_options.subquery(); + /// Gates for a materialized CTE belong to the plan that collected it, where a deeper + /// level yields a higher and therefore dominating gate; this CTE's plan is not that plan. + cte_options.forceMaterializeCTE(false); + Planner cte_planner( + cte_subquery, + cte_options, + std::make_shared(nullptr, nullptr, nullptr, FiltersForTableExpressionMap{})); + cte_planner.buildQueryPlanIfNeeded(); + + auto cte_plan = std::move(cte_planner).extractQueryPlan(); + + auto step = std::make_unique( + cte_plan.getCurrentHeader(), + materialized_cte); + step->setStepDescription("Materializing CTE: " + materialized_cte->cte_name, 100); + cte_plan.addStep(std::move(step)); + materialized_cte->plan = std::make_unique(std::move(cte_plan)); + } + + ctes.push_back(materialized_cte); + } + + auto delayed_step = std::make_unique( + query_plan.getCurrentHeader(), + std::move(ctes)); + query_plan.addStep(std::move(delayed_step)); + } +} + } diff --git a/src/Planner/CollectMaterializedCTE.h b/src/Planner/CollectMaterializedCTE.h index 58896a77180c..1c601f30d2f6 100644 --- a/src/Planner/CollectMaterializedCTE.h +++ b/src/Planner/CollectMaterializedCTE.h @@ -14,8 +14,18 @@ using QueryTreeNodes = std::vector; struct TemporaryTableHolder; using TemporaryTableHolderPtr = std::shared_ptr; +class QueryPlan; + using OrderedMaterializedCTEs = std::vector; OrderedMaterializedCTEs collectMaterializedCTEs(const QueryTreeNodePtr & node, const SelectQueryOptions & select_query_options); +/// Plants one `DelayedMaterializingCTEsStep` per dependency level of `materialized_ctes` on top of +/// `query_plan`, building the plan of every CTE that has none yet. Plan optimization turns the step +/// into the `MaterializingCTEsStep` whose gate orders every reader of a CTE after its writer. +void addBuildSubqueriesForMaterializedCTEsIfNeeded( + QueryPlan & query_plan, + const SelectQueryOptions & select_query_options, + const OrderedMaterializedCTEs & materialized_ctes); + } diff --git a/src/Planner/Planner.cpp b/src/Planner/Planner.cpp index b312f5c22898..8c847f6fe924 100644 --- a/src/Planner/Planner.cpp +++ b/src/Planner/Planner.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include #include @@ -2040,122 +2039,6 @@ void addBuildSubqueriesForSetsStepIfNeeded( } } -void addBuildSubqueriesForMaterializedCTEsIfNeeded( - QueryPlan & query_plan, - const SelectQueryOptions & select_query_options, - const OrderedMaterializedCTEs & materialized_ctes -) -{ - /// Logical plans are built for serialization to a remote node. `DelayedMaterializingCTEsStep` - /// is stripped on the way out (`Serialization.cpp`), and the only surviving side effect of - /// building it here would be to populate the shared `MaterializedCTE::plan` with a logical - /// (serialize-only) version that the non-logical planner pass would then reuse for local - /// execution and crash on. The materialization is owned by the non-logical pass; remote - /// nodes read from the temp storage by name. - if (select_query_options.build_logical_plan) - return; - - if (materialized_ctes.empty()) - return; - - // The main idea of the algorithm is to unite plans for Materialized CTEs of the same level - // with the main query plan by MaterializingCTEsStep. - // - // This allows to ensure following properties: - // 1) All CTEs are executed before the main query. - // 2) If CTE A depends on CTE B, then A will be executed after B, because A will be on the next level after B. - // 3) CTEs on the same level are independent. - // 3) CTEs of the same level will be executed in the same MaterializingCTEsStep, so they will be executed in parallel. - // 4) Materialized CTEs are executed only once. - // - // Example of query plan structure for query with 2 levels of CTEs: - // - // ┌───────────────────────┐ - // │ │ - // ┌────│ MaterializingCTEsStep │────────────────────────────┐ - // │ │ │ │ │ - // │ └───────────────────────┘ │ │ - // │ │ │ - // │ │ │ - // ┌───────────▼───────────┐ ┌────────▼───────┐ ┌────────▼───────┐ - // │ │ │ │ │ │ - // ┌────────│ MaterializingCTEsStep │─────────┐ │ CTE (level: 0) │ │ CTE (level: 0) │ - // │ │ │ │ │ │ │ │ - // │ └───────────────────────┘ │ └────────────────┘ └────────────────┘ - // │ │ - // │ │ - // ┌──────▼─────┐ ┌────────▼───────┐ - // │ │ │ │ - // │ Query Plan │ │ CTE (level: 1) │ - // │ │ │ │ - // └────────────┘ └────────────────┘ - // - // The CTEs are added as DelayedMaterializingCTEsStep nodes — one per level — so that - // resolveMaterializingCTEs can skip already-materialized CTEs. This is important when - // buildOrderedSetInplace runs a subquery plan that contains CTEs: by the time the main - // plan's resolveMaterializingCTEs fires, is_planned is already true for those CTEs - // so they won't be materialized a second time. - // - // The level structure is preserved: for each level we push one DelayedMaterializingCTEsStep - // on top of the current plan, wrapping it the same way the old eager approach did with - // MaterializingCTEsStep. resolveMaterializingCTEs processes nodes post-order, so the inner - // (lower-level) step is resolved before the outer one, guaranteeing that a CTE at level N - // is always materialized before the CTE at level N-1 that depends on it. - for (const auto & cte_level : materialized_ctes) - { - std::vector ctes; - ctes.reserve(cte_level.size()); - - for (const auto & cte_node : cte_level) - { - auto * cte_table_node = cte_node->as(); - auto materialized_cte = cte_table_node->getMaterializedCTE(); - if (!materialized_cte->hasPlanOrBuilt()) - { - auto cte_subquery = cte_table_node->getMaterializedCTESubquery(); - /// A by-name reference carries no subquery, but a standalone pipeline still needs a - /// gate for it, and the handle alone is enough to build one. The writer stays with - /// whoever holds the subquery. - if (!cte_subquery && select_query_options.force_materialize_cte) - { - ctes.push_back(materialized_cte); - continue; - } - if (!cte_subquery) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "CTE '{}' does not have query tree, but was not planned yet", - materialized_cte->cte_name); - - auto cte_options = select_query_options.subquery(); - /// Gates for a materialized CTE belong to the plan that collected it, where a deeper - /// level yields a higher and therefore dominating gate; this CTE's plan is not that plan. - cte_options.forceMaterializeCTE(false); - Planner cte_planner( - cte_subquery, - cte_options, - std::make_shared(nullptr, nullptr, nullptr, FiltersForTableExpressionMap{})); - cte_planner.buildQueryPlanIfNeeded(); - - auto cte_plan = std::move(cte_planner).extractQueryPlan(); - - auto step = std::make_unique( - cte_plan.getCurrentHeader(), - materialized_cte); - step->setStepDescription("Materializing CTE: " + materialized_cte->cte_name, 100); - cte_plan.addStep(std::move(step)); - materialized_cte->plan = std::make_unique(std::move(cte_plan)); - } - - ctes.push_back(materialized_cte); - } - - auto delayed_step = std::make_unique( - query_plan.getCurrentHeader(), - std::move(ctes)); - query_plan.addStep(std::move(delayed_step)); - } -} - /// Support for `additional_result_filter` setting void addAdditionalFilterStepIfNeeded(QueryPlan & query_plan, const QueryNode & query_node, diff --git a/src/Planner/PlannerJoinTree.cpp b/src/Planner/PlannerJoinTree.cpp index c5d95b83f25f..b7c5cbac0a6f 100644 --- a/src/Planner/PlannerJoinTree.cpp +++ b/src/Planner/PlannerJoinTree.cpp @@ -186,6 +186,7 @@ namespace ErrorCodes extern const int TOO_MANY_COLUMNS; extern const int UNSUPPORTED_METHOD; extern const int ACCESS_DENIED; + extern const int SUPPORT_IS_DISABLED; } namespace @@ -2565,8 +2566,27 @@ JoinTreeQueryPlan buildQueryPlanForTableExpression(TableExpressionNodePtr table_ if (query_context->canUseParallelReplicasCustomKey() && to_stage_supports_custom_key && query_context->getClientInfo().distributed_depth == 0) { - if (auto cluster = query_context->getClusterForParallelReplicas(); - query_context->canUseParallelReplicasCustomKeyForCluster(*cluster)) + auto cluster = query_context->getClusterForParallelReplicas(); + + /// The replicas receive this read as query text and match `additional_table_filters` on their own: + /// against their own current database and against the table expression renamed to `__table1`. + /// A filter that matched here can miss there, and the replicas would return the rows it excludes. + /// The custom-key read cannot ship the plan with the filters applied (`serialize_query_plan`), so + /// keep the local read, as the task-based path does. The text is the whole query, so filters set in + /// any of its subqueries count. + bool use_custom_key = query_context->canUseParallelReplicasCustomKeyForCluster(*cluster); + if (use_custom_key && queryTreeSetsAdditionalTableFilters(table_expression_query_info.query_tree.get())) + { + if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) + throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, + "additional_table_filters is not supported with parallel replicas with a custom key"); + + LOG_DEBUG(getLogger("Planner"), + "Disabling parallel replicas with a custom key to execute a query with additional_table_filters"); + use_custom_key = false; + } + + if (use_custom_key) { /// The key is evaluated on the replicas on behalf of this user. auto custom_key_ast = parseCustomKeyForTable(settings[Setting::parallel_replicas_custom_key], *query_context); diff --git a/src/Planner/PlannerJoins.cpp b/src/Planner/PlannerJoins.cpp index 5ac521c6209f..3ac686ce4b8c 100644 --- a/src/Planner/PlannerJoins.cpp +++ b/src/Planner/PlannerJoins.cpp @@ -1020,33 +1020,6 @@ std::optional tryExtractConstantFromJoinNode(const QueryTreeNodePtr & join return tryExtractConstantFromConditionNode(join_node_typed.getJoinExpression()); } -void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join) -{ - StoragePtr storage; - - if (auto * table_node = table_expression->as()) - storage = table_node->getStorage(); - else if (auto * table_function = table_expression->as()) - storage = table_function->getStorage(); - - auto storage_join = castStorage(storage, DeferredTable::Load); - if (storage_join) - { - table_join->setStorageJoin(storage_join); - return; - } - - if (!table_join->isEnabledAlgorithm(JoinAlgorithm::DIRECT) && !table_join->isEnabledAlgorithm(JoinAlgorithm::DEFAULT)) - return; - - if (auto storage_dictionary = std::dynamic_pointer_cast(storage); - storage_dictionary && storage_dictionary->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - table_join->setStorageJoin(std::dynamic_pointer_cast(storage_dictionary->getDictionary())); - else if (auto storage_key_value = castStorage(storage, DeferredTable::Load); storage_key_value) - table_join->setStorageJoin(storage_key_value); -} - static std::shared_ptr tryDirectJoin(const std::shared_ptr & table_join, const PreparedJoinStorage & right_table_expression, SharedHeader & right_table_expression_header) diff --git a/src/Planner/PlannerJoins.h b/src/Planner/PlannerJoins.h index 27da98c3c546..0ce1b12f0f24 100644 --- a/src/Planner/PlannerJoins.h +++ b/src/Planner/PlannerJoins.h @@ -297,6 +297,4 @@ std::set extractJoinTableSidesFromExpression( QueryTreeNodePtr getJoinExpressionFromNode(const JoinNode & join_node); -void trySetStorageInTableJoin(const QueryTreeNodePtr & table_expression, std::shared_ptr & table_join); - } diff --git a/src/Planner/PlannerJoinsLogical.cpp b/src/Planner/PlannerJoinsLogical.cpp index d0582e099162..576d80f44e07 100644 --- a/src/Planner/PlannerJoinsLogical.cpp +++ b/src/Planner/PlannerJoinsLogical.cpp @@ -601,12 +601,16 @@ PreparedJoinStorage tryGetStorageInTableJoin(const QueryTreeNodePtr & table_expr if (result.storage_join) return result; - auto storage_dictionary = std::dynamic_pointer_cast(storage); - if (storage_dictionary && storage_dictionary->getDictionary()->getSpecialKeyType() != DictionarySpecialKeyType::Range) + if (auto storage_dictionary = std::dynamic_pointer_cast(storage)) { - /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. - result.storage_key_value = std::dynamic_pointer_cast(storage_dictionary->getDictionary()); - return result; + /// This runs even if the right table is not read, e.g. for `CREATE VIEW`, so the access must be checked here. + auto dictionary = storage_dictionary->getDictionary(planner_context->getQueryContext()); + if (dictionary->getSpecialKeyType() != DictionarySpecialKeyType::Range) + { + /// NOLINT(storage-cast): a dictionary, which the catalog never hands out behind a proxy. + result.storage_key_value = std::dynamic_pointer_cast(dictionary); + return result; + } } result.storage_key_value = castStorage(storage, DeferredTable::Load); diff --git a/src/Planner/findParallelReplicasQuery.cpp b/src/Planner/findParallelReplicasQuery.cpp index 3949188ee87f..c3be1c435640 100644 --- a/src/Planner/findParallelReplicasQuery.cpp +++ b/src/Planner/findParallelReplicasQuery.cpp @@ -29,6 +29,7 @@ namespace DB { namespace Setting { + extern const SettingsMap additional_table_filters; extern const SettingsBool parallel_replicas_allow_in_with_subquery; extern const SettingsBool parallel_replicas_for_non_replicated_merge_tree; extern const SettingsBool parallel_replicas_allow_materialized_views; @@ -42,6 +43,31 @@ namespace ErrorCodes extern const int UNSUPPORTED_METHOD; } +bool queryTreeSetsAdditionalTableFilters(const IQueryTreeNode * query_tree_node) +{ + std::vector nodes{query_tree_node}; + while (!nodes.empty()) + { + const auto * node = nodes.back(); + nodes.pop_back(); + + ContextPtr node_context; + if (const auto * query_node = node->as()) + node_context = query_node->getContext(); + else if (const auto * union_node = node->as()) + node_context = union_node->getContext(); + if (node_context && !node_context->getSettingsRef()[Setting::additional_table_filters].value.empty()) + return true; + + for (const auto & child : node->getChildren()) + { + if (child) + nodes.push_back(child.get()); + } + } + return false; +} + bool isTableNodeEligibleForParallelReplicas(const TableNode & table_node, const StoragePtr & storage, const ContextPtr & context) { const auto & settings = context->getSettingsRef(); diff --git a/src/Planner/findQueryForParallelReplicas.h b/src/Planner/findQueryForParallelReplicas.h index 21da849fbfd5..3eefd6241dc3 100644 --- a/src/Planner/findQueryForParallelReplicas.h +++ b/src/Planner/findQueryForParallelReplicas.h @@ -36,6 +36,9 @@ bool canUseTableForParallelReplicas(const TableNode & table_node, const ContextP /// Used for views with UNION ALL where each branch reads from a separate MergeTree table. const UnionNode * findTableUnionForParallelReplicas(const QueryTreeNodePtr & query_tree_node, const SelectQueryOptions & select_query_options); +/// Whether the query or any of its subqueries sets `additional_table_filters`. +bool queryTreeSetsAdditionalTableFilters(const IQueryTreeNode * query_tree_node); + struct JoinTreeQueryPlan; class PlannerContext; diff --git a/src/Processors/Executors/PipelineExecutor.cpp b/src/Processors/Executors/PipelineExecutor.cpp index 528122b0b95e..2121884144c0 100644 --- a/src/Processors/Executors/PipelineExecutor.cpp +++ b/src/Processors/Executors/PipelineExecutor.cpp @@ -49,6 +49,13 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; } + +namespace +{ + /// The CPU slot (a lease) that the current thread runs on, or nullptr. + /// A pipeline executor started on this thread runs on it instead of taking a CPU slot of its own. + thread_local ISlotLease * current_cpu_slot = nullptr; +} // Class helping a thread to deal with acquired workload resources struct WorkloadResources { @@ -60,6 +67,10 @@ struct WorkloadResources MemoryReservation * reservation; MemoryTracker * tracker; + // The previously published CPU slot, restored on destruction + ISlotLease * prev_cpu_slot = nullptr; + bool publishes_slot = false; // moved to the new instance by the move constructor + WorkloadResources(IAcquiredSlot * cpu_slot, const QueryStatusPtr & status) : lease(dynamic_cast(cpu_slot)) , reservation(status ? status->getMemoryReservation() : nullptr) @@ -69,10 +80,30 @@ struct WorkloadResources { lease->startConsumption(); last_renew_ns = clock_gettime_ns(); + + // Publish own lease. Without one, a nested executor runs on the lease of the outer executor's thread (if any). + prev_cpu_slot = current_cpu_slot; + current_cpu_slot = lease; + publishes_slot = true; } } - WorkloadResources(WorkloadResources && other) = default; + WorkloadResources(WorkloadResources && other) noexcept + : lease(other.lease) + , last_renew_ns(other.last_renew_ns) + , reservation(other.reservation) + , tracker(other.tracker) + , prev_cpu_slot(other.prev_cpu_slot) + , publishes_slot(other.publishes_slot) + { + other.publishes_slot = false; // the moved-to instance now owns the publication + } + + ~WorkloadResources() + { + if (publishes_slot) + current_cpu_slot = prev_cpu_slot; + } bool isCPULeaseRenewNeeded() { @@ -204,6 +235,10 @@ void PipelineExecutor::execute(size_t num_threads, bool concurrency_control) checkTimeLimit(); num_threads = std::max(num_threads, 1); + /// The only thread is the calling one: it runs on the CPU lease that it already has, as in `executeStep`. + if (num_threads == 1 && current_cpu_slot) + concurrency_control = false; + OpenTelemetry::SpanHolder span("PipelineExecutor::execute()"); span.addAttribute("clickhouse.thread_num", num_threads); @@ -241,7 +276,9 @@ bool PipelineExecutor::executeStep(std::atomic_bool * yield_flag) { if (!is_execution_initialized) { - initializeExecution(1, true); + /// In a processor of an outer executor, the thread already runs on a CPU lease, and so does every step here. + /// A slot of its own would be a second slot for the same thread: it could wait for the slot that it holds. + initializeExecution(1, /*concurrency_control=*/ !current_cpu_slot); // Acquire slot until we are done single_thread_cpu_slot = cpu_slots->acquire(); diff --git a/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp b/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp index 1f05e7aeb77c..a4d0da0d2c57 100644 --- a/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp +++ b/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -1018,6 +1019,12 @@ ColumnPtr RecordBatchDecoder::decodeUnion(const ArrowField & field, size_t rows) VectorWithMemoryTracking child_null_map_holders; /// Maps an Arrow union type id to a local Variant element index, or -1 for the NULL placeholder. UnorderedMapWithMemoryTracking type_id_to_local; + /// No requested type reaches a child, as `fieldToCHType` declares the children below. The requested type + /// of the union does not say which child it describes, and the children restart the dotted path, so a + /// name looked up from it would belong to an unrelated column of the header. + const bool outer_below_union = decoding_below_union; + decoding_below_union = true; + SCOPE_EXIT({ decoding_below_union = outer_below_union; }); for (size_t child_idx = 0; child_idx < type.children.size(); ++child_idx) { const ArrowField & child = type.children[child_idx]; @@ -1801,7 +1808,7 @@ DataTypePtr RecordBatchDecoder::resolveTargetHint(const DataTypePtr & parent_hin /// which resolves a `date32` addressed as a subcolumn (e.g. `t.d`). if (parent_hint) return parent_hint; - if (target_types) + if (target_types && !decoding_below_union) { auto it = target_types->find(path); if (it != target_types->end()) diff --git a/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.h b/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.h index 700be74f6763..3b710c2604f6 100644 --- a/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.h +++ b/src/Processors/Formats/Impl/ArrowIPC/RecordBatchDecoder.h @@ -152,6 +152,8 @@ class RecordBatchDecoder /// Requested column types by normalized (dotted) name, for the recursive `date32` numeric type hint; /// null when the caller did not provide them. Points at the caller's map for the call's duration. const UnorderedMapWithMemoryTracking * target_types = nullptr; + /// Set while decoding the children of a union (see `decodeUnion`): `target_types` is not consulted there. + bool decoding_below_union = false; /// The buffers to decode from: either views into the message body, or into `decompressed_body`. VectorWithMemoryTracking buffer_slices; PODArray decompressed_body; diff --git a/src/Processors/Formats/Impl/AvroConfluentSchemaRegistry.cpp b/src/Processors/Formats/Impl/AvroConfluentSchemaRegistry.cpp index bcbe248d46bf..5ab59ad44eaf 100644 --- a/src/Processors/Formats/Impl/AvroConfluentSchemaRegistry.cpp +++ b/src/Processors/Formats/Impl/AvroConfluentSchemaRegistry.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -16,6 +17,8 @@ #include +#include + #include #include @@ -143,6 +146,8 @@ void ConfluentSchemaRegistry::applyAuth(const Poco::URI & url, Poco::Net::HTTPRe { if (!url.getUserInfo().empty()) { + Context::getGlobalContextInstance()->getHTTPHeaderFilter().checkURIUserInfo(url); + Poco::Net::HTTPCredentials http_credentials; Poco::Net::HTTPBasicCredentials http_basic_credentials; diff --git a/src/Processors/Formats/Impl/NativeFormat.cpp b/src/Processors/Formats/Impl/NativeFormat.cpp index 94b2b195687e..d8024bf28e0c 100644 --- a/src/Processors/Formats/Impl/NativeFormat.cpp +++ b/src/Processors/Formats/Impl/NativeFormat.cpp @@ -17,12 +17,7 @@ class NativeInputFormat final : public IInputFormat public: NativeInputFormat(ReadBuffer & buf, SharedHeader header_, const FormatSettings & settings_) : IInputFormat(header_, &buf) - , reader(std::make_unique( - buf, - *header_, - 0, - settings_, - settings_.defaults_for_omitted_fields ? &block_missing_values : nullptr)) + , reader(makeReader(buf, *header_, settings_, block_missing_values)) , header(header_) , block_missing_values(header->columns()) , settings(settings_) @@ -56,7 +51,7 @@ class NativeInputFormat final : public IInputFormat void setReadBuffer(ReadBuffer & in_) override { - reader = std::make_unique(in_, *header, 0, settings, settings.defaults_for_omitted_fields ? &block_missing_values : nullptr); + reader = makeReader(in_, *header, settings, block_missing_values); IInputFormat::setReadBuffer(in_); } @@ -65,6 +60,19 @@ class NativeInputFormat final : public IInputFormat size_t getApproxBytesReadForChunk() const override { return approx_bytes_read_for_chunk; } private: + /// Revision 0 has no serialization kinds in its layout, so the kind set takes effect only with a non-zero revision. + static std::unique_ptr makeReader( + ReadBuffer & buf, const Block & header_, const FormatSettings & settings_, BlockMissingValues & block_missing_values_) + { + return std::make_unique( + buf, + header_, + 0, + settings_, + settings_.defaults_for_omitted_fields ? &block_missing_values_ : nullptr, + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); + } + std::unique_ptr reader; SharedHeader header; BlockMissingValues block_missing_values; @@ -105,7 +113,7 @@ class NativeSchemaReader final : public ISchemaReader NamesAndTypesList readSchema() override { - auto reader = NativeReader(in, 0, settings); + auto reader = NativeReader(in, 0, settings, ISerialization::KindSet{ISerialization::Kind::DEFAULT}); auto block = reader.read(); return block.getNamesAndTypesList(); } diff --git a/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp b/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp index 82d219cf243a..6c01409db1d9 100644 --- a/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetMetadataInputFormat.cpp @@ -2,6 +2,8 @@ #if USE_PARQUET +#include +#include #include #include #include @@ -21,6 +23,7 @@ #include #include #include +#include #include @@ -30,6 +33,8 @@ namespace DB namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int CANNOT_READ_ALL_DATA; + extern const int TOO_DEEP_RECURSION; } static NamesAndTypesList getHeaderForParquetMetadata() @@ -127,12 +132,89 @@ static void checkHeader(const Block & header) } } +static std::shared_ptr readAt(arrow::io::RandomAccessFile & file, int64_t position, int64_t nbytes) +{ + auto buffer = file.ReadAt(position, nbytes); + if (!buffer.ok()) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: {}", buffer.status().ToString()); + if ((*buffer)->size() != nbytes) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: unexpected end of file"); + return *buffer; +} + +/// Arrow builds the schema tree recursively (`parquet::schema::Unflatten`, `parquet::SchemaDescriptor`), +/// so a deeply nested schema exhausts the stack. Unlike the native Parquet reader, which has `checkStackSize` +/// as a backstop, the recursion in Arrow cannot be guarded, so the depth is always limited by this ceiling, +/// even if `max_parser_depth` is raised or set to 0 (unlimited). In a release build, Arrow exhausts +/// an 8 MiB stack at a depth between 30000 and 100000; frames are several times larger in sanitizer +/// and debug builds, and the ceiling leaves a wide margin for them. +static constexpr size_t MAX_SCHEMA_DEPTH_FOR_ARROW = 1000; + +/// Check the nesting depth of the schema with a non-recursive walk before giving the footer to Arrow, +/// with the same limit as the native Parquet reader (`max_parser_depth`), capped by `MAX_SCHEMA_DEPTH_FOR_ARROW`. +static void checkSchemaDepth(arrow::io::RandomAccessFile & file, const FormatSettings & format_settings) +{ + const size_t max_parser_depth = format_settings.max_parser_depth; + const size_t max_depth = (max_parser_depth == 0) ? MAX_SCHEMA_DEPTH_FOR_ARROW : std::min(max_parser_depth, MAX_SCHEMA_DEPTH_FOR_ARROW); + + auto file_size_or_error = file.GetSize(); + if (!file_size_or_error.ok()) + throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read Parquet metadata: {}", file_size_or_error.status().ToString()); + const int64_t file_size = *file_size_or_error; + + /// Leave invalid and encrypted files (with the "PARE" magic) to Arrow, which reports a proper error. + if (file_size < 12) + return; + auto tail = readAt(file, file_size - 8, 8); + if (memcmp(tail->data() + 4, "PAR1", 4) != 0) + return; + const int64_t metadata_size = unalignedLoadLittleEndian(tail->data()); + if (metadata_size > file_size - 8) + return; + + auto footer = readAt(file, file_size - 8 - metadata_size, metadata_size); + Parquet::parq::FileMetaData metadata; + Parquet::deserializeThriftStruct(metadata, reinterpret_cast(footer->data()), footer->size()); + + /// The schema is a depth-first list of elements where a group element is followed by its `num_children` children. + /// The stack holds the number of children still to come for each group the walk is in. + VectorWithMemoryTracking children_left; + for (const auto & element : metadata.schema) + { + while (!children_left.empty() && children_left.back() == 0) + children_left.pop_back(); + if (!children_left.empty()) + --children_left.back(); + else if (&element != &metadata.schema.front()) + break; /// Elements after the root are invalid, Arrow reports it. + + if (element.__isset.num_children && element.num_children > 0) + { + children_left.push_back(element.num_children); + if (children_left.size() > max_depth) + { + if (max_depth == MAX_SCHEMA_DEPTH_FOR_ARROW) + throw Exception( + ErrorCodes::TOO_DEEP_RECURSION, + "Parquet schema is nested deeper than the limit ({}) of the `ParquetMetadata` format", + max_depth); + throw Exception( + ErrorCodes::TOO_DEEP_RECURSION, + "Parquet schema is nested deeper than the limit ({}). It can be raised with the setting " + "'max_parser_depth', but a very deeply nested schema is rarely intentional", + max_depth); + } + } + } +} + static std::shared_ptr getFileMetadata( ReadBuffer & in, const FormatSettings & format_settings, std::atomic & is_stopped) { auto arrow_file = asArrowFile(in, format_settings, is_stopped, "Parquet", PARQUET_MAGIC_BYTES, /* avoid_buffering */ true); + checkSchemaDepth(*arrow_file, format_settings); return parquet::ReadMetaData(arrow_file); } diff --git a/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp b/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp index dc1ca2139477..42339acd91f4 100644 --- a/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp @@ -146,7 +146,8 @@ void TemplateBlockOutputFormat::finalizeImpl() { auto type = std::make_shared(); ColumnWithTypeAndName col(type->createColumnConst(1, row_count), type, String("tmp")); - switch (static_cast(*format.format_idx_to_column_idx[i])) + const auto part = static_cast(*format.format_idx_to_column_idx[i]); + switch (part) { case ResultsetPart::Totals: if (!statistics.totals || !statistics.totals.hasRows()) @@ -154,15 +155,16 @@ void TemplateBlockOutputFormat::finalizeImpl() writeRow(statistics.totals, 0); break; case ResultsetPart::ExtremesMin: - if (!statistics.extremes) - format.throwInvalidFormat("Cannot print extremes for this request", i); - writeRow(statistics.extremes, 0); - break; case ResultsetPart::ExtremesMax: - if (!statistics.extremes) + { + /// Extremes are two rows: the minimums and the maximums. The chunk is not produced by this format + /// (a client gets it from the server as is), and it can have columns without having both rows, + /// so check the number of rows before reading one of them. + if (statistics.extremes.getNumRows() != 2) format.throwInvalidFormat("Cannot print extremes for this request", i); - writeRow(statistics.extremes, 1); + writeRow(statistics.extremes, part == ResultsetPart::ExtremesMin ? 0 : 1); break; + } case ResultsetPart::Rows: writeValue(row_count, format.escaping_rules[i]); break; diff --git a/src/Processors/QueryPlan/AggregatingStep.cpp b/src/Processors/QueryPlan/AggregatingStep.cpp index 1eb0d6d97b01..98adef5a31f4 100644 --- a/src/Processors/QueryPlan/AggregatingStep.cpp +++ b/src/Processors/QueryPlan/AggregatingStep.cpp @@ -1334,6 +1334,34 @@ QueryPlanStepPtr AggregatingStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in, ctx.max_type_complexity); + const auto & input_header = *ctx.input_headers.front(); + /// The serialized step never merges the states only (it is deserialized with `only_merge = false`), + /// so the arguments of the aggregates must be present in its input. + checkDeserializedAggregateOutputNames(keys, aggregates); + checkDeserializedAggregateArguments(aggregates, input_header); + + /// `AggregatingInOrderTransform` takes the first columns of `group_by_sort_description` as the ones the input + /// is sorted by and looks them up among the keys of its output, and `less` compares the key columns at those positions. + if (sort_description_for_merging.size() > group_by_sort_description.size()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The sort description for merging of a deserialized in-order aggregation has {} columns, " + "more than the {} columns of the `GROUP BY` sort description", + sort_description_for_merging.size(), group_by_sort_description.size()); + for (size_t i = 0; i < sort_description_for_merging.size(); ++i) + if (sort_description_for_merging[i] != group_by_sort_description[i]) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The sort description for merging of a deserialized in-order aggregation is not a prefix of " + "the `GROUP BY` sort description: {} at position {} instead of {}", + sort_description_for_merging[i].column_name, i, group_by_sort_description[i].column_name); + if (!group_by_sort_description.empty()) + { + NameSet key_names(keys.begin(), keys.end()); + for (const auto & column : group_by_sort_description) + if (!key_names.contains(column.column_name)) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The `GROUP BY` sort description of a deserialized in-order aggregation refers to {}, which is not a key", + column.column_name); + } UInt64 stats_key = 0; if (has_stats_key) diff --git a/src/Processors/QueryPlan/CubeStep.cpp b/src/Processors/QueryPlan/CubeStep.cpp index a661d4b2ef50..1e87718db993 100644 --- a/src/Processors/QueryPlan/CubeStep.cpp +++ b/src/Processors/QueryPlan/CubeStep.cpp @@ -194,6 +194,7 @@ QueryPlanStepPtr CubeStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptionsWithoutArguments(aggregates, ctx.in, ctx.max_type_complexity); + checkDeserializedGroupByModifierInput(keys, aggregates, final, *ctx.input_headers.front()); const auto & query_settings = ctx.context->getSettingsRef(); diff --git a/src/Processors/QueryPlan/MergingAggregatedStep.cpp b/src/Processors/QueryPlan/MergingAggregatedStep.cpp index 3f64bfea764a..2a1b458d4bcd 100644 --- a/src/Processors/QueryPlan/MergingAggregatedStep.cpp +++ b/src/Processors/QueryPlan/MergingAggregatedStep.cpp @@ -306,6 +306,73 @@ void MergingAggregatedStep::serialize(Serialization & ctx) const writeIntBinary(params.stats_collecting_params.key, ctx.out); } +/// With grouping sets, `MergingAggregatedTransform` removes `__grouping_set` from the input and, for every set, +/// moves its keys to the front (see `makeReorderingActions`) and drops the other keys. Check the layout it merges. +static void checkMergedAggregatesLayout( + const Names & keys, const GroupingSetsParamsList & grouping_sets_params, const AggregateDescriptions & aggregates, const Block & header) +{ + if (grouping_sets_params.empty()) + { + /// `appendGroupingIfNeeded` would copy a `__grouping_set` column of the input into the output header, + /// but the merge without grouping sets does not produce it. + if (header.has("__grouping_set")) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized `MergingAggregated` step without grouping sets has a `__grouping_set` column"); + checkDeserializedMergedAggregatesLayout(keys, aggregates, header.getColumnsWithTypeAndName()); + return; + } + + /// The transform splits the rows by the values of `__grouping_set` read as `ColumnUInt64`, and the output header + /// takes its type from the input. + size_t num_grouping_set_columns = 0; + for (const auto & column : header) + { + if (column.name != "__grouping_set") + continue; + ++num_grouping_set_columns; + if (column.type->getTypeId() != TypeIndex::UInt64) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The `__grouping_set` column in the input of a deserialized `MergingAggregated` step has type {} instead of UInt64", + column.type->getName()); + } + if (num_grouping_set_columns != 1) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The input of a deserialized `MergingAggregated` step with grouping sets has {} `__grouping_set` columns instead of one", + num_grouping_set_columns); + + /// The per-set layouts below skip the keys of a set after its used keys, but the output header and the + /// reconstruction of the missing keys (`makeCreatingMissingKeysForGroupingSetDAG`) take every key from the + /// original input by name, i.e. from its first occurrence. So every key must occur at most once there. + NameSet seen_keys; + const NameSet all_keys(keys.begin(), keys.end()); + for (const auto & column : header) + if (all_keys.contains(column.name) && !seen_keys.insert(column.name).second) + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} occurs more than once in the input of a deserialized `MergingAggregated` step with grouping sets", + column.name); + + for (const auto & grouping_set : grouping_sets_params) + { + NameSet keys_of_set(grouping_set.used_keys.begin(), grouping_set.used_keys.end()); + keys_of_set.insert(grouping_set.missing_keys.begin(), grouping_set.missing_keys.end()); + + ColumnsWithTypeAndName layout; + for (const auto & key : grouping_set.used_keys) + { + const auto * column = header.findByName(key); + if (!column || key == "__grouping_set") + throw Exception(ErrorCodes::INCORRECT_DATA, + "Key {} of a grouping set is not in the input of a deserialized `MergingAggregated` step", key); + layout.push_back(*column); + } + for (const auto & column : header) + if (column.name != "__grouping_set" && !keys_of_set.contains(column.name)) + layout.push_back(column); + + checkDeserializedMergedAggregatesLayout(grouping_set.used_keys, aggregates, layout); + } +} + QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) { if (ctx.input_headers.size() != 1) @@ -354,10 +421,16 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in, ctx.max_type_complexity); + checkMergedAggregatesLayout(keys, grouping_sets_params, aggregates, *ctx.input_headers.front()); SortDescription group_by_sort_description; deserializeSortDescription(group_by_sort_description, ctx.in); + /// The memory-bound merge is used with a non-empty sort description, and it does not support grouping sets. + if (memory_bound_merging_of_aggregation_results_enabled && !group_by_sort_description.empty() && !grouping_sets_params.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The memory-bound merging of aggregated results with grouping sets in a serialized query plan"); + UInt64 stats_key = 0; if (has_stats_key) readIntBinary(stats_key, ctx.in); @@ -368,6 +441,12 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) ctx.settings[QueryPlanSerializationSetting::max_entries_for_hash_table_stats], ctx.settings[QueryPlanSerializationSetting::max_size_to_preallocate_for_aggregation]); + /// The planners never enable the memory-efficient merge with grouping sets, and it does not support them. + const bool memory_efficient_aggregation = ctx.settings[QueryPlanSerializationSetting::distributed_aggregation_memory_efficient]; + if (memory_efficient_aggregation && !grouping_sets_params.empty()) + throw Exception(ErrorCodes::INCORRECT_DATA, + "The memory-efficient merging of aggregated results with grouping sets in a serialized query plan"); + const auto & settings = ctx.context->getSettingsRef(); Aggregator::Params params( @@ -385,7 +464,7 @@ QueryPlanStepPtr MergingAggregatedStep::deserialize(Deserialization & ctx) std::move(params), std::move(grouping_sets_params), final, - ctx.settings[QueryPlanSerializationSetting::distributed_aggregation_memory_efficient], + memory_efficient_aggregation, settings[Setting::aggregation_memory_efficient_merge_threads], should_produce_results_in_order_of_bucket_number, ctx.settings[QueryPlanSerializationSetting::max_block_size], diff --git a/src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp b/src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp index ac1e27c5cbca..a8be28ef7416 100644 --- a/src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp +++ b/src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp @@ -22,6 +22,7 @@ namespace DB namespace Setting { extern const SettingsBool aggregate_functions_null_for_empty; + extern const SettingsBool apply_deleted_mask; extern const SettingsBool apply_mutations_on_fly; extern const SettingsBool apply_patch_parts; extern const SettingsMaxThreads max_threads; @@ -111,6 +112,10 @@ bool canUseProjectionForReadingStep(ReadFromMergeTree * reading) if (mutations_snapshot->hasDataMutations() || mutations_snapshot->hasPatchParts()) return false; + /// A projection part rebuilt by a lightweight delete does not store the deleted rows. + if (!query_settings[Setting::apply_deleted_mask] && mutations_snapshot->hasLightweightDeletedMask()) + return false; + return true; } diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index 7d558999fcb1..f85a41c012be 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -2881,14 +2881,13 @@ void ReadFromMergeTree::buildIndexes( } { - const auto & partition_key = metadata_snapshot->getPartitionKey(); const auto data_settings = data.getSettings(); - if (auto minmax_columns = MergeTreeData::getMinMaxColumns(partition_key, data_settings); !minmax_columns.empty()) + if (auto minmax_columns = MergeTreeData::getMinMaxColumns(*metadata_snapshot, data_settings); !minmax_columns.empty()) { auto key_condition_factory = [query_context, metadata_snapshot, skip_partition_pruning_, minmax_columns, data_settings](const ActionsDAG *, const ActionsDAG::Node * predicate) { - auto minmax_expression_actions = MergeTreeData::getMinMaxExpr(metadata_snapshot->getPartitionKey(), data_settings, ExpressionActionsSettings(query_context)); + auto minmax_expression_actions = MergeTreeData::getMinMaxExpr(*metadata_snapshot, data_settings, ExpressionActionsSettings(query_context)); ActionsDAGWithInversionPushDown wrapped(predicate, query_context, /* boolean_context */ false); return KeyCondition{ wrapped, query_context, minmax_columns.getNames(), minmax_expression_actions, diff --git a/src/Processors/QueryPlan/RollupStep.cpp b/src/Processors/QueryPlan/RollupStep.cpp index 6537e9458331..bbd21d8c7f27 100644 --- a/src/Processors/QueryPlan/RollupStep.cpp +++ b/src/Processors/QueryPlan/RollupStep.cpp @@ -154,6 +154,7 @@ QueryPlanStepPtr RollupStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptionsWithoutArguments(aggregates, ctx.in, ctx.max_type_complexity); + checkDeserializedGroupByModifierInput(keys, aggregates, final, *ctx.input_headers.front()); const auto & query_settings = ctx.context->getSettingsRef(); diff --git a/src/Processors/QueryPlan/TotalsHavingStep.cpp b/src/Processors/QueryPlan/TotalsHavingStep.cpp index f467f4d313f6..490ae2d6afab 100644 --- a/src/Processors/QueryPlan/TotalsHavingStep.cpp +++ b/src/Processors/QueryPlan/TotalsHavingStep.cpp @@ -209,6 +209,7 @@ QueryPlanStepPtr TotalsHavingStep::deserialize(Deserialization & ctx) AggregateDescriptions aggregates; deserializeAggregateDescriptions(aggregates, ctx.in, ctx.max_type_complexity); + checkDeserializedFinalizedAggregates(aggregates, *ctx.input_headers.front()); std::optional actions_dag; String filter_column_name; diff --git a/src/Processors/Sources/PostgreSQLSource.cpp b/src/Processors/Sources/PostgreSQLSource.cpp index cca7fcab9239..42d5ee2c3c66 100644 --- a/src/Processors/Sources/PostgreSQLSource.cpp +++ b/src/Processors/Sources/PostgreSQLSource.cpp @@ -16,18 +16,52 @@ #include #include #include +#include #include #include +#include + +#include +#include +#include +#include + namespace DB { namespace ErrorCodes { + extern const int CANNOT_OPEN_FILE; + extern const int POSTGRESQL_CONNECTION_FAILURE; extern const int TOO_MANY_COLUMNS; } +void PostgreSQLCancelDeleter::operator()(pg_cancel * cancel) const noexcept +{ + PQfreeCancel(cancel); +} + +namespace +{ + +/// pqxx hands the libpq connection only to its large-object API. +struct LibpqConnection : pqxx::largeobject +{ + using pqxx::largeobject::raw_connection; +}; + +std::unique_ptr makeCancelHandle(const pqxx::dbtransaction & tx) +{ + std::unique_ptr handle(PQgetCancel(LibpqConnection::raw_connection(tx))); + if (!handle) + throw Exception(ErrorCodes::POSTGRESQL_CONNECTION_FAILURE, "Cannot prepare the cancellation of the PostgreSQL query"); + return handle; +} + +} + template PostgreSQLSource::PostgreSQLSource( postgres::ConnectionHolderPtr connection_holder_, @@ -78,16 +112,15 @@ void PostgreSQLSource::init(const Block & sample_block) /// COPY stream and marks the connection broken. A null argument means there is nothing of that kind /// to finalize. Must be called with tx_mutex released, since the calls below block. template -void PostgreSQLSource::finalize(const std::shared_ptr & tx_to_cancel, pqxx::stream_from * stream_to_close) noexcept +void PostgreSQLSource::finalize(pg_cancel * cancel, pqxx::stream_from * stream_to_close) noexcept { try { - if (tx_to_cancel) + if (cancel) { - /// `cancel_query` reads the connection to build its `PGcancel`, so onCancel() and the - /// destructor must not reach it at once. It does not make the connection shareable. - std::lock_guard lock(cancel_mutex); - tx_to_cancel->conn().cancel_query(); + std::array error{}; + if (!PQcancel(cancel, error.data(), static_cast(error.size()))) + LOG_ERROR(getLogger("PostgreSQLSource"), "Cannot cancel the query on the PostgreSQL server: {}", error.data()); } /// Closing it here keeps the exception out of the transaction's pending error, where it @@ -132,8 +165,25 @@ void PostgreSQLSource::onStart() throw; } + auto cancel = makeCancelHandle(*new_tx); + + /// Our own handle on the socket, taken on the owning thread before the read starts. Refuse to + /// start rather than run a read that could not be interrupted. + int fd = ::dup(new_tx->conn().sock()); + if (fd < 0) + throw ErrnoException( + ErrorCodes::CANNOT_OPEN_FILE, "Cannot duplicate the socket of the PostgreSQL connection"); + std::lock_guard lock(tx_mutex); tx = std::move(new_tx); + interrupt_fd = fd; + cancel_handle = std::move(cancel); + } + else + { + auto cancel = makeCancelHandle(*tx); + std::lock_guard lock(tx_mutex); + cancel_handle = std::move(cancel); } /// A cancel during the constructor found `tx` null and could only ask us to stop. Do not open @@ -153,16 +203,25 @@ IProcessor::Status PostgreSQLSource::prepare() { if (!started.load()) { - onStart(); + try + { + onStart(); + } + catch (const pqxx::failure &) + { + /// A start that onCancel() interrupted fails instead of returning. Report the cancellation. + if (!stop_requested.load()) + throw; + } started.store(true); } auto status = ISource::prepare(); - if (status == Status::Finished && !stop_requested.load()) + if (status == Status::Finished && !stop_requested.load() && !teardown_started.exchange(true)) { /// Only a finish that was not cancelled commits here and claims the teardown. After a - /// cancel it is left to the destructor: the cancelling thread may still be in - /// `cancel_query` on this connection, and a `COMMIT` racing it is what libpq forbids. + /// cancel it is left to the destructor: the cancelling thread may be taking the + /// connection down under it. if (stream) stream->close(); @@ -194,7 +253,18 @@ Chunk PostgreSQLSource::generate() while (!isCancelled() && !stop_requested.load()) { - const std::vector * row{stream->read_row()}; + const std::vector * row{nullptr}; + try + { + row = stream->read_row(); + } + catch (const pqxx::failure &) + { + /// An interrupted read fails here instead of returning. Report the cancellation. + if (stop_requested.load()) + break; + throw; + } /// row is nullptr if pqxx::stream_from is finished if (!row) @@ -254,20 +324,38 @@ void PostgreSQLSource::onCancel() noexcept /// Outer try/catch: this function is noexcept, and locking tx_mutex may throw. try { - /// Snapshot under the lock, then use it with the lock released: the pqxx calls below block. - std::shared_ptr tx_snapshot; + /// Snapshot under the lock, then use it with the lock released: the calls below block. + pg_cancel * cancel = nullptr; + int fd = -1; { std::lock_guard lock(tx_mutex); - tx_snapshot = tx; + cancel = cancel_handle.get(); + fd = interrupt_fd; } - /// Interrupt the connection only while onStart() is blocked on it (typically in - /// pqxx::from_query). Once streaming, the pipeline thread owns it, so the flag has to be - /// enough: generate() drops out between rows and the destructor then cancels the COPY. - if (!started.load() && tx_snapshot && tx_snapshot->conn().is_open()) + if (!cancel) + return; + + /// The connection is ours to discard. Ask the server to cancel, then take the transport away, which wakes the + /// read whether or not the server obliged. + if (connection_holder) { - /// `stream` belongs to onStart(), which is still running, so it is not touched here. - finalize(tx_snapshot, nullptr); + /// A finish already under way has nothing left to wake, and its COMMIT must not be broken. + if (teardown_started.exchange(true)) + return; + + finalize(cancel, nullptr); + + /// `shutdown` and not `close` keeps the descriptor valid for the thread still reading it. + ::shutdown(fd, SHUT_RDWR); + connection_holder->setBroken(); + LOG_DEBUG(getLogger("PostgreSQLSource"), "Shut the connection down to interrupt the read"); + } + /// A connection handed in with the transaction stays in use by its owner, so it is not ours to take + /// away. Ask the server instead, which only helps while the COPY is starting. + else if (!started.load()) + { + finalize(cancel, nullptr); } } catch (...) @@ -282,11 +370,18 @@ PostgreSQLSource::~PostgreSQLSource() /// The teardown owner for every path but a clean finish, which prepare() claims. Without /// cancelling the COPY the ROLLBACK issued during transaction abort waits for it. With no /// transaction nothing reached the connection, so it stays healthy and is left in the pool. + /// A connection already cancelled and taken down has nothing left to cancel, and the attempt would block. if (!finalized.exchange(true) && tx) - finalize(stream ? tx : nullptr, stream.get()); + finalize((stream && !teardown_started.load()) ? cancel_handle.get() : nullptr, stream.get()); stream.reset(); tx.reset(); + + if (interrupt_fd >= 0) + { + [[maybe_unused]] int err = ::close(interrupt_fd); + chassert(!err || errno == EINTR); + } } template diff --git a/src/Processors/Sources/PostgreSQLSource.h b/src/Processors/Sources/PostgreSQLSource.h index 1740d64aafdb..c545a72273fa 100644 --- a/src/Processors/Sources/PostgreSQLSource.h +++ b/src/Processors/Sources/PostgreSQLSource.h @@ -10,12 +10,21 @@ #include #include +#include #include +/// libpq's PGcancel. +struct pg_cancel; + namespace DB { +struct PostgreSQLCancelDeleter +{ + void operator()(pg_cancel * cancel) const noexcept; +}; + template class PostgreSQLSource : public ISource { @@ -50,7 +59,7 @@ class PostgreSQLSource : public ISource private: void init(const Block & sample_block); - void finalize(const std::shared_ptr & tx_to_cancel, pqxx::stream_from * stream_to_close) noexcept; + void finalize(pg_cancel * cancel, pqxx::stream_from * stream_to_close) noexcept; const UInt64 max_block_size; bool auto_commit = true; @@ -62,11 +71,16 @@ class PostgreSQLSource : public ISource /// Claimed once by whoever tears the connection down: prepare() on an uncancelled finish, else /// the destructor. onCancel()'s interrupt does not claim it - it cannot close the stream. std::atomic finalized{false}; + /// Claimed by whichever comes first, the clean finish in prepare() or the interrupt in onCancel(). + std::atomic teardown_started{false}; - /// tx and stream are written only by the pipeline thread; this is for onCancel() to read tx. + /// tx, stream, cancel_handle and interrupt_fd are written only by the pipeline thread; this + /// publishes cancel_handle and interrupt_fd to onCancel(). std::mutex tx_mutex; - /// Serializes the cancel_query() in finalize() between onCancel() and the destructor. - std::mutex cancel_mutex; + /// Our own duplicate of the connection's socket. The client library may close its own on a failed read. + int interrupt_fd = -1; + /// Built by the thread that runs the read. Sending it reads only this copy, so onCancel() may. + std::unique_ptr cancel_handle; postgres::ConnectionHolderPtr connection_holder; diff --git a/src/Processors/TTL/TTLColumnAlgorithm.cpp b/src/Processors/TTL/TTLColumnAlgorithm.cpp index cb10166b102b..0228aa971714 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.cpp +++ b/src/Processors/TTL/TTLColumnAlgorithm.cpp @@ -1,4 +1,7 @@ #include +#include +#include +#include namespace DB { @@ -12,12 +15,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_) + bool is_compact_part_, + bool shares_nested_offsets_) : ITTLAlgorithm(ttl_expressions_, description_, old_ttl_info_, current_time_, force_) , column_name(column_name_) , default_expression(default_expression_) , default_column_name(default_column_name_) , is_compact_part(is_compact_part_) + , shares_nested_offsets(shares_nested_offsets_) { if (!isMinTTLExpired()) { @@ -29,6 +34,14 @@ TTLColumnAlgorithm::TTLColumnAlgorithm( new_ttl_info.ttl_finished = true; } +ColumnPtr TTLColumnAlgorithm::createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes) +{ + const auto & column_array = assert_cast(column_with_sizes); + const auto & nested_type = assert_cast(type).getNestedType(); + auto data = nested_type->createColumnConstWithDefaultValue(column_array.getData().size()); + return ColumnArray::create(data->convertToFullColumnIfConst(), column_array.getOffsetsPtr()); +} + void TTLColumnAlgorithm::execute(Block & block) { if (block.empty()) @@ -56,6 +69,8 @@ void TTLColumnAlgorithm::execute(Block & block) result_column->reserve(block.rows()); auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column && shares_nested_offsets) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); if (default_column) { default_column = default_column->convertToFullColumnIfConst(); @@ -71,6 +86,8 @@ void TTLColumnAlgorithm::execute(Block & block) } auto default_column = executeExpressionAndGetColumn(default_expression, block, default_column_name); + if (!default_column && shares_nested_offsets) + default_column = createArraysOfDefaults(*column_with_type.type, *column_with_type.column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); @@ -105,7 +122,7 @@ void TTLColumnAlgorithm::finalize(const MutableDataPartPtr & data_part) const { data_part->ttl_infos.columns_ttl[column_name] = new_ttl_info; data_part->ttl_infos.updatePartMinMaxTTL(new_ttl_info); - if (is_fully_empty) + if (is_fully_empty && !shares_nested_offsets) data_part->expired_columns.insert(column_name); } diff --git a/src/Processors/TTL/TTLColumnAlgorithm.h b/src/Processors/TTL/TTLColumnAlgorithm.h index f34dae952d16..6ef19bb98c70 100644 --- a/src/Processors/TTL/TTLColumnAlgorithm.h +++ b/src/Processors/TTL/TTLColumnAlgorithm.h @@ -6,7 +6,8 @@ namespace DB { /// Deletes (replaces to default) values in column according to column's TTL description. -/// If all values in column are replaced with defaults, this column won't be written to part. +/// If all values in column are replaced with defaults, this column won't be written to part, +/// unless it is a `Nested` subcolumn that shares the array sizes with the other subcolumns. class TTLColumnAlgorithm final : public ITTLAlgorithm { public: @@ -19,12 +20,16 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm const String & column_name_, const ExpressionActionsPtr & default_expression_, const String & default_column_name_, - bool is_compact_part_ + bool is_compact_part_, + bool shares_nested_offsets_ ); void execute(Block & block) override; void finalize(const MutableDataPartPtr & data_part) const override; + /// The default of a `Nested` subcolumn keeps the array sizes, which it shares with the other subcolumns. + static ColumnPtr createArraysOfDefaults(const IDataType & type, const IColumn & column_with_sizes); + private: const String column_name; const ExpressionActionsPtr default_expression; @@ -32,6 +37,7 @@ class TTLColumnAlgorithm final : public ITTLAlgorithm bool is_fully_empty = true; bool is_compact_part; + bool shares_nested_offsets; }; } diff --git a/src/Processors/Transforms/AggregatingInOrderTransform.cpp b/src/Processors/Transforms/AggregatingInOrderTransform.cpp index f4e048fae60e..adc2d9d0b3a1 100644 --- a/src/Processors/Transforms/AggregatingInOrderTransform.cpp +++ b/src/Processors/Transforms/AggregatingInOrderTransform.cpp @@ -457,7 +457,7 @@ void FinalizeAggregatedTransform::transform(Chunk & chunk) { if (params->final) { - finalizeChunk(chunk, aggregates_mask); + finalizeChunk(chunk, aggregates_mask, getOutputPort().getHeader()); } else if (!chunk.getChunkInfos().get()) { diff --git a/src/Processors/Transforms/CubeTransform.cpp b/src/Processors/Transforms/CubeTransform.cpp index a214a2aa1fc4..5a53a2a1bee2 100644 --- a/src/Processors/Transforms/CubeTransform.cpp +++ b/src/Processors/Transforms/CubeTransform.cpp @@ -53,7 +53,7 @@ Chunk CubeTransform::generate() current_chunk = merge(std::move(chunks), !use_nulls, false); } - finalizeChunk(gen_chunk, aggregates_mask); + finalizeChunk(gen_chunk, aggregates_mask, finalized_header); if (!gen_chunk.empty()) gen_chunk.addColumn(0, ColumnUInt64::create(gen_chunk.getNumRows(), grouping_set++)); return gen_chunk; diff --git a/src/Processors/Transforms/RollupTransform.cpp b/src/Processors/Transforms/RollupTransform.cpp index 1a8de8480ba4..d03c42f009af 100644 --- a/src/Processors/Transforms/RollupTransform.cpp +++ b/src/Processors/Transforms/RollupTransform.cpp @@ -10,6 +10,7 @@ GroupByModifierTransform::GroupByModifierTransform(SharedHeader header, Aggregat : IAccumulatingTransform(std::move(header), std::make_shared(generateOutputHeader(params_->getHeader(), params_->params.keys, use_nulls_))) , params(std::move(params_)) , use_nulls(use_nulls_) + , finalized_header(params->getHeader()) { keys.reserve(params->params.keys_size); for (const auto & key : params->params.keys) @@ -99,7 +100,7 @@ Chunk RollupTransform::generate() current_chunk = merge(std::move(chunks), !use_nulls, false); } - finalizeChunk(gen_chunk, aggregates_mask); + finalizeChunk(gen_chunk, aggregates_mask, finalized_header); if (!gen_chunk.empty()) gen_chunk.addColumn(0, ColumnUInt64::create(gen_chunk.getNumRows(), set_counter++)); return gen_chunk; diff --git a/src/Processors/Transforms/RollupTransform.h b/src/Processors/Transforms/RollupTransform.h index b0849099b127..bc85673dedbb 100644 --- a/src/Processors/Transforms/RollupTransform.h +++ b/src/Processors/Transforms/RollupTransform.h @@ -30,6 +30,8 @@ struct GroupByModifierTransform : public IAccumulatingTransform std::unique_ptr output_aggregator; Block intermediate_header; + /// The header of a generated chunk after `finalizeChunk`, without `__grouping_set`. + const Block finalized_header; Chunks consumed_chunks; Chunk current_chunk; diff --git a/src/Processors/Transforms/TTLTransform.cpp b/src/Processors/Transforms/TTLTransform.cpp index b2e3696253fc..119c11476b62 100644 --- a/src/Processors/Transforms/TTLTransform.cpp +++ b/src/Processors/Transforms/TTLTransform.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -11,10 +12,16 @@ #include #include #include +#include namespace DB { +namespace MergeTreeSetting +{ + extern const MergeTreeSettingsBool share_nested_offsets; +} + static TTLExpressions getExpressions(const TTLDescription & ttl_descr, PreparedSets::Subqueries & subqueries_for_sets, const ContextPtr & context) { auto expr = ttl_descr.buildExpression(context); @@ -31,6 +38,17 @@ static TTLExpressions getExpressions(const TTLDescription & ttl_descr, PreparedS return {expr.expression, where_expr.expression}; } +/// Returns a stored `Nested` sibling of `name`, whose array sizes a read uses to fill `name`. +static const ColumnWithTypeAndName * findNestedSiblingWithSizes(const Block & block, const String & name, const auto & expired_columns) +{ + auto table_name = Nested::extractTableName(name); + for (const auto & column : block) + if (column.name != name && !expired_columns.contains(column.name) && isArray(column.type) + && Nested::extractTableName(column.name) == table_name) + return &column; + return nullptr; +} + SharedHeader TTLTransform::addExpiredColumnsToBlock(const SharedHeader & header, const NamesAndTypesList & expired_columns_) { if (expired_columns_.empty()) @@ -108,11 +126,18 @@ TTLTransform::TTLTransform( return Result{actions, default_ast->getColumnName()}; }; + bool share_nested = (*storage_.getSettings())[MergeTreeSetting::share_nested_offsets]; + auto shares_nested_offsets = [&](const NameAndTypePair & column) + { + return share_nested && isArray(column.type) && Nested::extractTableName(column.name) != column.name; + }; + for (const auto & expired_column : expired_columns) { auto [default_expression, default_column_name] = build_default_expr(expired_column.name); - expired_columns_data.emplace( - expired_column.name, ExpiredColumnData{expired_column.type, std::move(default_expression), std::move(default_column_name)}); + ExpiredColumnData data{ + expired_column.type, std::move(default_expression), std::move(default_column_name), shares_nested_offsets(expired_column)}; + expired_columns_data.emplace(expired_column.name, std::move(data)); } if (metadata_snapshot_->hasAnyColumnTTL()) @@ -123,6 +148,7 @@ TTLTransform::TTLTransform( if (!expired_columns_map.contains(name)) { auto [default_expression, default_column_name] = build_default_expr(name); + auto physical_column = storage_columns.tryGetPhysical(name); algorithms.emplace_back(std::make_unique( getExpressions(description, subqueries_for_sets, context), description, @@ -132,7 +158,8 @@ TTLTransform::TTLTransform( name, default_expression, default_column_name, - isCompactPart(data_part))); + isCompactPart(data_part), + physical_column && shares_nested_offsets(*physical_column))); } } } @@ -173,6 +200,9 @@ void TTLTransform::consume(Chunk chunk) { auto default_column = ITTLAlgorithm::executeExpressionAndGetColumn(data.default_expression, block, data.default_column_name); + if (!default_column && data.shares_nested_offsets) + if (const auto * sibling = findNestedSiblingWithSizes(block, column, expired_columns_data)) + default_column = TTLColumnAlgorithm::createArraysOfDefaults(*data.type, *sibling->column); if (default_column) default_column = default_column->convertToFullColumnIfConst(); else diff --git a/src/Processors/Transforms/TTLTransform.h b/src/Processors/Transforms/TTLTransform.h index 02d452fe9dff..bbb6cbcff358 100644 --- a/src/Processors/Transforms/TTLTransform.h +++ b/src/Processors/Transforms/TTLTransform.h @@ -57,6 +57,7 @@ class TTLTransform final : public IAccumulatingTransform DataTypePtr type; ExpressionActionsPtr default_expression; String default_column_name; + bool shares_nested_offsets; }; std::unordered_map expired_columns_data; LoggerPtr log; diff --git a/src/Processors/Transforms/TotalsHavingTransform.cpp b/src/Processors/Transforms/TotalsHavingTransform.cpp index a6750426095e..07f9e0498221 100644 --- a/src/Processors/Transforms/TotalsHavingTransform.cpp +++ b/src/Processors/Transforms/TotalsHavingTransform.cpp @@ -171,7 +171,7 @@ void TotalsHavingTransform::transform(Chunk & chunk) auto finalized = chunk.clone(); if (final) - finalizeChunk(finalized, aggregates_mask); + finalizeChunk(finalized, aggregates_mask, finalized_header); total_keys += finalized.getNumRows(); @@ -292,7 +292,7 @@ void TotalsHavingTransform::prepareTotals() } totals = Chunk(std::move(current_totals), 1); - finalizeChunk(totals, aggregates_mask); + finalizeChunk(totals, aggregates_mask, finalized_header); if (expression) { diff --git a/src/Processors/Transforms/WindowTransform.cpp b/src/Processors/Transforms/WindowTransform.cpp index f7818a4e6e9a..1d8f87e3bf1c 100644 --- a/src/Processors/Transforms/WindowTransform.cpp +++ b/src/Processors/Transforms/WindowTransform.cpp @@ -331,6 +331,7 @@ WindowTransform::WindowTransform(SharedHeader input_header_, aggregate_function->sizeOfData(), aggregate_function->alignOfData()); aggregate_function->create(workspace.aggregate_function_state.data()); + workspace.aggregate_function_state_created = true; workspaces.push_back(std::move(workspace)); } @@ -428,8 +429,8 @@ WindowTransform::~WindowTransform() // Some states may be not created yet if the creation failed. for (auto & ws : workspaces) { - ws.aggregate_function->destroy( - ws.aggregate_function_state.data()); + if (ws.aggregate_function_state_created) + ws.aggregate_function->destroy(ws.aggregate_function_state.data()); } } @@ -1248,8 +1249,13 @@ void WindowTransform::updateAggregationState() if (reset_aggregation) { - a->destroy(buf); + if (ws.aggregate_function_state_created) + { + a->destroy(buf); + ws.aggregate_function_state_created = false; + } a->create(buf); + ws.aggregate_function_state_created = true; } // To achieve better performance, we will have to loop over blocks and @@ -1593,7 +1599,11 @@ void WindowTransform::appendChunk(Chunk & chunk) const auto * a = ws.aggregate_function.get(); auto * buf = ws.aggregate_function_state.data(); - a->destroy(buf); + if (ws.aggregate_function_state_created) + { + a->destroy(buf); + ws.aggregate_function_state_created = false; + } } // Release the arena we use for aggregate function states, so that it @@ -1615,6 +1625,7 @@ void WindowTransform::appendChunk(Chunk & chunk) auto * buf = ws.aggregate_function_state.data(); a->create(buf); + ws.aggregate_function_state_created = true; } } } diff --git a/src/Processors/Transforms/finalizeChunk.cpp b/src/Processors/Transforms/finalizeChunk.cpp index 7fb298c0e826..be64ddd08298 100644 --- a/src/Processors/Transforms/finalizeChunk.cpp +++ b/src/Processors/Transforms/finalizeChunk.cpp @@ -1,11 +1,19 @@ #include +#include #include #include +#include +#include namespace DB { +namespace ErrorCodes +{ + extern const int ILLEGAL_COLUMN; +} + ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions & aggregates) { ColumnsMask mask(header.columns()); @@ -14,7 +22,7 @@ ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions return mask; } -void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask) +void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask, const Block & finalized_header) { auto num_rows = chunk.getNumRows(); auto columns = chunk.detachColumns(); @@ -25,6 +33,20 @@ void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask) continue; auto & column = columns[i]; + + /// A column is finalized with its own function, which may differ from the one of the type in the header + /// if they share the state representation (like `quantile` and `quantiles`): `DataTypeAggregateFunction::equals` + /// considers such types equal, so such a column can pass through a `Union`. Their result types may differ. + const auto & column_aggregate_function = typeid_cast(*column); + const auto & actual_result_type = column_aggregate_function.getAggregateFunction()->getResultType(); + const auto & expected = finalized_header.getByPosition(i); + if (!actual_result_type->equals(*expected.type)) + throw Exception(ErrorCodes::ILLEGAL_COLUMN, + "Cannot finalize the state of aggregate function {} in column {}: it finalizes to {}, but {} is expected. " + "States of different aggregate functions that share a state representation cannot be finalized together", + column_aggregate_function.getAggregateFunction()->getName(), expected.name, + actual_result_type->getName(), expected.type->getName()); + column = ColumnAggregateFunction::convertToValues(IColumn::mutate(std::move(column))); } diff --git a/src/Processors/Transforms/finalizeChunk.h b/src/Processors/Transforms/finalizeChunk.h index 39a1178e270b..f9e7ba796ac7 100644 --- a/src/Processors/Transforms/finalizeChunk.h +++ b/src/Processors/Transforms/finalizeChunk.h @@ -15,6 +15,7 @@ ColumnsMask getAggregatesMask(const Block & header, const AggregateDescriptions /// Convert ColumnAggregateFunction to real values. /// /// @param aggregates_mask columns to convert (see getAggregatesMask()) -void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask); +/// @param finalized_header the expected header after the conversion; throws if a state finalizes to another type +void finalizeChunk(Chunk & chunk, const ColumnsMask & aggregates_mask, const Block & finalized_header); } diff --git a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp index 323b9500a483..f5d4e90b261d 100644 --- a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp +++ b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp @@ -69,7 +69,7 @@ InputFormatPtr getInputFormatFromASTInsertQuery( } std::unique_ptr input_buffer = with_buffers - ? getReadBufferFromASTInsertQuery(ast, settings[Setting::snappy_mode]) + ? getReadBufferFromASTInsertQuery(ast, context) : std::make_unique(); /// Create a source from input buffer using format from query @@ -132,7 +132,7 @@ Pipe getSourceFromASTInsertQuery( return getSourceFromInputFormat(ast, std::move(format), std::move(context), input_function); } -std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, SnappyMode snappy_mode) +std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, const ContextPtr & context) { const auto * insert_query = ast->as(); if (!insert_query) @@ -140,6 +140,10 @@ std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, if (insert_query->infile) { + /// Checked here, before the file is opened: the asynchronous insert queue reads the data without the format check above. + if (context->getApplicationType() == Context::ApplicationType::SERVER) + throw Exception(ErrorCodes::UNKNOWN_TYPE_OF_QUERY, "Query has infile and was send directly to server"); + /// Data can be from infile const auto & in_file_node = insert_query->infile->as(); const auto in_file = in_file_node.value.safeGet(); @@ -156,7 +160,7 @@ std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, /// Buffer for reading from file is created and wrapped with appropriate compression method return wrapReadBufferWithCompressionMethod( std::make_unique(in_file), chooseCompressionMethod(in_file, compression_method), - /*zstd_window_log_max=*/ 0, snappy_mode); + /*zstd_window_log_max=*/ 0, context->getSettingsRef()[Setting::snappy_mode]); } ConcatReadBuffer::Buffers buffers; diff --git a/src/Processors/Transforms/getSourceFromASTInsertQuery.h b/src/Processors/Transforms/getSourceFromASTInsertQuery.h index b5c8ee1ffe16..b9e6e82064e7 100644 --- a/src/Processors/Transforms/getSourceFromASTInsertQuery.h +++ b/src/Processors/Transforms/getSourceFromASTInsertQuery.h @@ -41,7 +41,8 @@ class ReadBuffer; /// Prepares a read buffer, that allows to read inlined data /// from ASTInsertQuert directly, and from tail buffer, if it exists. -/// `snappy_mode` selects the snappy framing used when the data (e.g. `INSERT ... FROM INFILE`) is snappy-compressed. -std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, SnappyMode snappy_mode = SnappyMode::Basic); +/// The `snappy_mode` setting of `context` selects the snappy framing for snappy-compressed data (e.g. `INSERT ... FROM INFILE`). +/// Throws for `INSERT ... FROM INFILE` in the server: the client reads the file, the server must not open the path. +std::unique_ptr getReadBufferFromASTInsertQuery(const ASTPtr & ast, const ContextPtr & context); } diff --git a/src/QueryPipeline/DistributedPlanExecutor.cpp b/src/QueryPipeline/DistributedPlanExecutor.cpp index 7c1a047c75cf..a3d5bee9c7af 100644 --- a/src/QueryPipeline/DistributedPlanExecutor.cpp +++ b/src/QueryPipeline/DistributedPlanExecutor.cpp @@ -916,7 +916,7 @@ std::pair getObjectStorageForTemporaryFiles(const Stri String object_storage_path = getTemporaryFilesPath(unique_temp_file_path, context); if (config.has(config_prefix)) { - ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create("distributed_query_temp_files", config, config_prefix, context, /*skip_access_check=*/false, RemoteHostFilterCheck::None); + ObjectStoragePtr object_storage = ObjectStorageFactory::instance().create("distributed_query_temp_files", config, config_prefix, context, /*run_access_check=*/true, /*run_local_paths_check=*/false, RemoteHostFilterCheck::None); return {object_storage, object_storage_path}; } return {nullptr, object_storage_path}; diff --git a/src/QueryPipeline/RemoteQueryExecutor.cpp b/src/QueryPipeline/RemoteQueryExecutor.cpp index fa389980983e..f862e9641a82 100644 --- a/src/QueryPipeline/RemoteQueryExecutor.cpp +++ b/src/QueryPipeline/RemoteQueryExecutor.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int UNKNOWN_PACKET_FROM_SERVER; + extern const int UNEXPECTED_PACKET_FROM_SERVER; extern const int SYSTEM_ERROR; extern const int UNKNOWN_TABLE; extern const int UNKNOWN_DATABASE; @@ -878,6 +880,16 @@ RemoteQueryExecutor::ReadResult RemoteQueryExecutor::processPacket(Packet packet break; case Protocol::Server::Extremes: + /// Extremes are two rows: the minimums and the maximums. Everything that takes them further + /// (an output format, or a client of this server with its own output format) relies on it, + /// so a block with another number of rows must not get past this point. + if (!packet.block.empty() && packet.block.rows() != 2) + throw Exception( + ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER, + "Received extremes with {} rows instead of 2 from one of the following replicas: {}", + packet.block.rows(), + connections->dumpAddresses()); + extremes = packet.block; if (!extremes.empty()) extremes = adaptBlockStructure(packet.block, *header); @@ -1191,6 +1203,10 @@ void RemoteQueryExecutor::sendExternalTables() auto builder = plan.buildQueryPipeline(QueryPlanOptimizationSettings(my_context), BuildQueryPipelineSettings(my_context)); + /// The receiver accepts only the default serialization, while a table that is not filled + /// through the insert chain (a materialized CTE) keeps `Sparse` columns. + builder->addSimpleTransform([](const SharedHeader & table_header) { return std::make_shared(table_header); }); + builder->resize(1); builder->addTransform(std::make_shared(builder->getSharedHeader(), limits)); diff --git a/src/Server/ArrowFlight/ArrowFlightServer.cpp b/src/Server/ArrowFlight/ArrowFlightServer.cpp index 2548bb088469..a8c3e200cc0b 100644 --- a/src/Server/ArrowFlight/ArrowFlightServer.cpp +++ b/src/Server/ArrowFlight/ArrowFlightServer.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -606,6 +607,7 @@ static arrow::Result, std::vectorpull(block)) return false; + removeSpecialColumnRepresentations(block); if (block_modifier) block_modifier(query_context, block); return true; diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index 5a4d1c228b75..574034365036 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -2739,6 +2739,10 @@ void TCPHandler::processQuery(std::shared_ptr & state) throw exception; /// NOLINT #endif } + /// `TCP_INTERSERVER` passed with `ClientInfo` in a `Query` packet is not trusted: + /// only a connection that uses the cluster secret is interserver. + else if (client_info.interface == ClientInfo::Interface::TCP_INTERSERVER) + client_info.interface = ClientInfo::Interface::TCP; /// `client_info` is what the upstream sent us about itself; the parallel-replicas protocol /// version, however, is negotiated at hello time per-connection — not over the wire as part of @@ -2988,7 +2992,12 @@ bool TCPHandler::skipDataPacket(QueryState & state) else maybe_compressed_in = in; - NativeReader skip_block_in(*maybe_compressed_in, client_tcp_protocol_version, getNativeWireFormatSettings(state.query_context)); + /// Skipped data is held to the same serialization kinds as data that `initBlockInput` reads. + NativeReader skip_block_in( + *maybe_compressed_in, + client_tcp_protocol_version, + getNativeWireFormatSettings(state.query_context), + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); bool has_rows = !skip_block_in.read().empty(); state.at_packet_boundary = true; @@ -3014,11 +3023,15 @@ void TCPHandler::initBlockInput(QueryState & state) else if (state.need_receive_data_for_input) header = state.input_header; + /// Only the default kind: senders materialize, and the consumers `assert_cast` columns to the declared type. + /// No peer is exempt: `query_kind` is declared by the client, and an initiator forwards client data to shards. state.block_in = std::make_unique( *state.maybe_compressed_in, header, client_tcp_protocol_version, - getNativeWireFormatSettings(state.query_context)); + getNativeWireFormatSettings(state.query_context), + /*block_missing_values_=*/ nullptr, + ISerialization::KindSet{ISerialization::Kind::DEFAULT}); } } diff --git a/src/Storages/Kafka/KafkaConfigLoader.cpp b/src/Storages/Kafka/KafkaConfigLoader.cpp index fceea40e63e1..216781441339 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.cpp +++ b/src/Storages/Kafka/KafkaConfigLoader.cpp @@ -17,9 +17,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -50,6 +52,7 @@ namespace KafkaSetting namespace ErrorCodes { + extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; extern const int SUPPORT_IS_DISABLED; } @@ -189,10 +192,155 @@ template struct KafkaInterceptors; namespace { -void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value) +/// librdkafka reads the name as a C string, so it must not contain a null character. +void checkKafkaPropertyName(const String & key) { + if (key.contains('\0')) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Kafka property name {} contains a null character", backQuote(key)); +} + +String toKafkaPropertyName(const String & key) +{ + checkKafkaPropertyName(key); /// "log_level" has valid underscore, the remaining librdkafka setting use dot.separated.format which isn't acceptable for XML. /// See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md + return (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); +} + +/// Only properties reviewed for use without access to server-local resources may be set from SQL. +/// Match the exact name passed to librdkafka, including any `topic.` prefix. +void checkSQLKafkaProperty(const String & name, const String & value) +{ + static constexpr std::string_view allowed_properties[] = { + "acks", + "allow.auto.create.topics", + "api.version.request", + "auto.commit.interval.ms", + "auto.offset.reset", + "batch.num.messages", + "batch.size", + "bootstrap.servers", + "broker.address.family", + "broker.address.ttl", + "check.crcs", + "client.id", + "client.rack", + "compression.codec", + "compression.level", + "compression.type", + "connections.max.idle.ms", + "coordinator.query.interval.ms", + "debug", + "delivery.timeout.ms", + "enable.auto.commit", + "enable.auto.offset.store", + "enable.idempotence", + "enable.partition.eof", + "fetch.error.backoff.ms", + "fetch.max.bytes", + "fetch.message.max.bytes", + "fetch.min.bytes", + "fetch.queue.backoff.ms", + "fetch.wait.max.ms", + "group.id", + "group.instance.id", + "group.protocol", + "group.remote.assignor", + "heartbeat.interval.ms", + "https.ca.pem", + "isolation.level", + "linger.ms", + "log.connection.close", + "log_level", + "max.in.flight", + "max.in.flight.requests.per.connection", + "max.partition.fetch.bytes", + "max.poll.interval.ms", + "message.max.bytes", + "message.send.max.retries", + "message.timeout.ms", + "metadata.broker.list", + "metadata.max.age.ms", + "partition.assignment.strategy", + "partitioner", + "queue.buffering.backpressure.threshold", + "queue.buffering.max.kbytes", + "queue.buffering.max.messages", + "queue.buffering.max.ms", + "queued.max.messages.kbytes", + "queued.min.messages", + "receive.message.max.bytes", + "reconnect.backoff.max.ms", + "reconnect.backoff.ms", + "request.required.acks", + "request.timeout.ms", + "retries", + "retry.backoff.max.ms", + "retry.backoff.ms", + "sasl.mechanism", + "sasl.mechanisms", + "sasl.oauthbearer.assertion.private.key.pem", + "sasl.password", + "sasl.username", + "security.protocol", + "session.timeout.ms", + "socket.connection.setup.timeout.ms", + "socket.keepalive.enable", + "socket.receive.buffer.bytes", + "socket.send.buffer.bytes", + "socket.timeout.ms", + "ssl.ca.pem", + "ssl.certificate.pem", + "ssl.key.password", + "ssl.key.pem", + "statistics.interval.ms", + "topic.acks", + "topic.auto.offset.reset", + "topic.compression.codec", + "topic.compression.level", + "topic.compression.type", + "topic.delivery.timeout.ms", + "topic.message.timeout.ms", + "topic.metadata.refresh.interval.ms", + "topic.partitioner", + "topic.request.required.acks", + "topic.request.timeout.ms", + }; + static_assert(std::ranges::is_sorted(allowed_properties)); + if (std::ranges::binary_search(allowed_properties, std::string_view(name))) + return; + + /// `probe` is not a path: librdkafka searches a fixed list of the standard locations of CA certificates. + if (value == "probe" && (name == "ssl.ca.location" || name == "https.ca.location")) + return; + + static constexpr std::pair pem_alternatives[] = { + {"ssl.key.location", "ssl.key.pem"}, + {"ssl.certificate.location", "ssl.certificate.pem"}, + {"ssl.ca.location", "ssl.ca.pem"}, + {"https.ca.location", "https.ca.pem"}, + {"sasl.oauthbearer.assertion.private.key.file", "sasl.oauthbearer.assertion.private.key.pem"}, + }; + for (const auto & [path_property, pem_property] : pem_alternatives) + if (name == path_property) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file. " + "Pass the contents of the file in the property `{}` instead", + name, + pem_property); + + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Kafka property `{}` can only be specified in a named collection defined in the server configuration file", + name); +} + +void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & key, const String & value, bool from_sql_collection) +{ + const String name = toKafkaPropertyName(key); + if (from_sql_collection) + checkSQLKafkaProperty(name, value); /// ClickHouse-specific keys that live under in server config but are not librdkafka properties. /// Exclude them here so they are not forwarded to cppkafka. @@ -201,8 +349,7 @@ void setKafkaConfigValue(cppkafka::Configuration & kafka_config, const String & if (clickhouse_only_kafka_config_keys.contains(key)) return; - const String setting_name_in_kafka_config = (key == "log_level") ? key : boost::replace_all_copy(key, "_", "."); - kafka_config.set(setting_name_in_kafka_config, value); + kafka_config.set(name, value); } void loadConfigProperty( @@ -214,17 +361,47 @@ void loadConfigProperty( const String property_path = config_prefix + "." + tag; const String property_value = config.getString(property_path); - setKafkaConfigValue(kafka_config, tag, property_value); + setKafkaConfigValue(kafka_config, tag, property_value, /*from_sql_collection=*/false); } -void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const String & collection_name, const String & config_prefix) +bool isNamedTopicSection(std::string_view tag) { - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(-1, config_prefix)) + return tag == KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG || tag.starts_with("kafka_topic["); +} + +/// Return the key within its configuration section. Dots in the property itself are significant. +std::string_view namedCollectionPropertyKey(std::string_view key) +{ + static constexpr std::string_view prefix = "kafka."; + if (!key.starts_with(prefix)) + return {}; /// The collection has no properties below `kafka`. + key.remove_prefix(prefix.size()); + if (key.starts_with("consumer.") || key.starts_with("producer.")) + key.remove_prefix(key.find('.') + 1); + + /// Both `kafka_` and `kafka_topic` (possibly indexed) are topic sections. + if (const auto dot = key.find('.'); dot != std::string_view::npos && key.starts_with("kafka_")) + { + const auto section = key.substr(0, dot); + key.remove_prefix(dot + 1); + if (isNamedTopicSection(section) && key == KafkaConfigLoader::CONFIG_NAME_TAG) + return {}; /// Topic selector, not a librdkafka property. + } + return key; +} + +void loadNamedCollectionConfig(cppkafka::Configuration & kafka_config, const NamedCollection & collection, const String & config_prefix) +{ + for (const auto & key : collection.getKeys(-1, config_prefix)) { - // Cut prefix with '.' before actual config tag. - const auto param_name = key.substr(config_prefix.size() + 1); - setKafkaConfigValue(kafka_config, param_name, collection->get(key)); + const auto property_key = namedCollectionPropertyKey(key); + if (property_key.empty() || key.size() != config_prefix.size() + 1 + property_key.size()) + continue; /// Subsections are loaded separately. + const String param_name(property_key); + const auto value = collection.get(key); + /// The check when the table is created or loaded is not sufficient: the collection is read again here, + /// and `ALTER NAMED COLLECTION` can add a property while the table exists. + setKafkaConfigValue(kafka_config, param_name, value, collection.getSourceId() != NamedCollection::SourceId::CONFIG); } } @@ -236,7 +413,12 @@ void loadLegacyTopicConfig( { if (!collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(collection_name); + /// For a topic called `topic`, the legacy section is also called `kafka_topic`. + /// If it has a `name`, the topic selector must be matched by `loadFromConfig`. + if (config_prefix == "kafka.kafka_topic" && collection->has(config_prefix + ".name")) + return; + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); return; } @@ -249,43 +431,15 @@ void loadLegacyTopicConfig( } } -/// Read server configuration into cppkafa configuration, used by new per-topic configuration -void loadTopicConfig( - cppkafka::Configuration & kafka_config, - const Poco::Util::AbstractConfiguration & config, - const String & collection_name, - const String & config_prefix, - const String & topic) +/// Read a matching per-topic section of the server configuration. +void loadTopicConfig(cppkafka::Configuration & kafka_config, const Poco::Util::AbstractConfiguration & config, const String & config_prefix) { - if (!collection_name.empty()) - { - const auto topic_prefix = fmt::format("{}.{}", config_prefix, KafkaConfigLoader::CONFIG_KAFKA_TOPIC_TAG); - const auto & collection = NamedCollectionFactory::instance().get(collection_name); - for (const auto & key : collection->getKeys(1, config_prefix)) - { - /// Only consider key . Multiple occurrences given as "kafka_topic", "kafka_topic[1]", etc. - if (!key.starts_with(topic_prefix)) - continue; - - const String kafka_topic_path = config_prefix + "." + key; - const String kafka_topic_name_path = kafka_topic_path + "." + KafkaConfigLoader::CONFIG_NAME_TAG; - if (topic == collection->get(kafka_topic_name_path)) - /// Found it! Now read the per-topic configuration into cppkafka. - loadNamedCollectionConfig(kafka_config, collection_name, kafka_topic_path); - } - } - else + Poco::Util::AbstractConfiguration::Keys tags; + config.keys(config_prefix, tags); + for (const auto & tag : tags) { - /// Read all tags one level below - Poco::Util::AbstractConfiguration::Keys tags; - config.keys(config_prefix, tags); - - for (const auto & tag : tags) - { - if (tag == KafkaConfigLoader::CONFIG_NAME_TAG) - continue; // ignore , it is used to match topic configurations + if (tag != KafkaConfigLoader::CONFIG_NAME_TAG) loadConfigProperty(kafka_config, config, config_prefix, tag); - } } } @@ -295,7 +449,16 @@ void loadFromConfig( { if (!params.collection_name.empty()) { - loadNamedCollectionConfig(kafka_config, params.collection_name, config_prefix); + const auto collection = NamedCollectionFactory::instance().get(params.collection_name); + loadNamedCollectionConfig(kafka_config, *collection, config_prefix); + for (const auto & key : collection->getKeys(0, config_prefix)) + { + if (key.size() <= config_prefix.size() || !isNamedTopicSection(std::string_view(key).substr(config_prefix.size() + 1))) + continue; + const String name_key = key + "." + KafkaConfigLoader::CONFIG_NAME_TAG; + if (collection->has(name_key) && std::ranges::contains(params.topics, collection->get(name_key))) + loadNamedCollectionConfig(kafka_config, *collection, key); + } return; } @@ -336,7 +499,7 @@ void loadFromConfig( if (topic_name != topic) continue; - loadTopicConfig(kafka_config, params.config, params.collection_name, kafka_topic_path, topic); + loadTopicConfig(kafka_config, params.config, kafka_topic_path); } continue; } @@ -660,4 +823,18 @@ KafkaConfigLoader::getProducerConfiguration(StorageKafka & storage template cppkafka::Configuration KafkaConfigLoader::getProducerConfiguration(StorageKafka2 & storage, const ProducerConfigParams & params); +void KafkaConfigLoader::checkNamedCollection(const NamedCollection & collection) +{ + if (collection.getSourceId() == NamedCollection::SourceId::CONFIG) + return; + + for (const auto & key : collection.getKeys(-1, CONFIG_KAFKA_TAG)) + { + checkKafkaPropertyName(key); + const auto property_key = namedCollectionPropertyKey(key); + if (!property_key.empty()) + checkSQLKafkaProperty(toKafkaPropertyName(String(property_key)), collection.get(key)); + } +} + } diff --git a/src/Storages/Kafka/KafkaConfigLoader.h b/src/Storages/Kafka/KafkaConfigLoader.h index 9fd04c3750e9..52c332e7483c 100644 --- a/src/Storages/Kafka/KafkaConfigLoader.h +++ b/src/Storages/Kafka/KafkaConfigLoader.h @@ -11,6 +11,7 @@ namespace DB { struct KafkaSettings; +class NamedCollection; class VirtualColumnsDescription; struct KafkaConfigLoader @@ -53,5 +54,10 @@ struct KafkaConfigLoader template static cppkafka::Configuration getProducerConfiguration(TKafkaStorage & storage, const ProducerConfigParams & params); + + /// Throws if a named collection created with SQL sets a librdkafka property that is not explicitly allowed. + /// The same check is done when the configuration of a consumer or a producer is loaded, because the named + /// collection can change while the table exists. + static void checkNamedCollection(const NamedCollection & collection); }; } diff --git a/src/Storages/Kafka/StorageKafkaUtils.cpp b/src/Storages/Kafka/StorageKafkaUtils.cpp index 6e5880d9aca7..f82eb92b0f23 100644 --- a/src/Storages/Kafka/StorageKafkaUtils.cpp +++ b/src/Storages/Kafka/StorageKafkaUtils.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -124,6 +125,10 @@ void registerStorageKafka(StorageFactory & factory) &args.table_id, args.storage_def->settings)) { + /// The named collection is checked every time, also when the definition is read back from metadata + /// (server startup, short `ATTACH`): the collection can change after the table is created. + KafkaConfigLoader::checkNamedCollection(*named_collection); + kafka_settings->loadFromNamedCollection(named_collection); collection_name = assert_cast(args.engine_args[0].get())->name(); } @@ -624,6 +629,8 @@ Similar to GraphiteMergeTree, the Kafka engine supports extended configuration u For a list of possible configuration options, see the [librdkafka configuration reference](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md). Use the underscore (`_`) instead of a dot in the ClickHouse configuration. For example, `check.crcs=true` will be `true`. +A named collection created with `CREATE NAMED COLLECTION` accepts only the `librdkafka` properties on the [allowlist](https://github.com/ClickHouse/ClickHouse/blob/26.8/src/Storages/Kafka/KafkaConfigLoader.cpp), such as `security.protocol`, `sasl.username`, and `fetch.min.bytes`. If a table uses a collection with an unlisted property, such as `ssl.ca.location` or `sasl.kerberos.keytab`, ClickHouse returns `BAD_ARGUMENTS`. To use these properties, define the collection in the server configuration file. This restriction also applies to properties added with `ALTER NAMED COLLECTION` after the table was created. Instead of the path of a TLS file, a named collection created with SQL can contain the contents of the file: `ssl.key.pem`, `ssl.certificate.pem`, and `ssl.ca.pem`. + ### AWS MSK IAM Authentication {#kafka-aws-msk-iam} :::note diff --git a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp index 0d0896b98830..4c3a675ae45c 100644 --- a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp +++ b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp @@ -992,9 +992,9 @@ void DataPartStorageOnDiskBase::clearDirectory( /// Sometimes we add something to checksums.files before actually writing checksums and columns on disk. /// Also sometimes we write checksums.txt and columns.txt in arbitrary order, so this check becomes complex... bool incomplete_temporary_part = is_temp && (!disk->existsFile(fs::path(dir) / "checksums.txt") || !disk->existsFile(fs::path(dir) / "columns.txt")); - if (checksums.empty() || incomplete_temporary_part) + if (checksums.empty() || incomplete_temporary_part || disk->prefersRecursiveRemoval()) { - /// If the part is not completely written, we cannot use fast path by listing files. + /// The fast path by listing files cannot be used for an incomplete part and is not faster on this disk. try { disk->removeSharedRecursive(fs::path(dir) / "", !can_remove_shared_data, names_not_to_remove); diff --git a/src/Storages/MergeTree/IMergeTreeDataPart.cpp b/src/Storages/MergeTree/IMergeTreeDataPart.cpp index 4b7b5be4a128..14d73f5c9f8d 100644 --- a/src/Storages/MergeTree/IMergeTreeDataPart.cpp +++ b/src/Storages/MergeTree/IMergeTreeDataPart.cpp @@ -168,14 +168,13 @@ String getIndexExtensionFromFilesystem(const IDataPartStorage & data_part_storag void IMergeTreeDataPart::MinMaxIndex::load(const IMergeTreeDataPart & part) { const auto metadata_snapshot = part.getMetadataSnapshot(); - const auto & partition_key = metadata_snapshot->getPartitionKey(); const auto data_settings = part.storage.getSettings(); const auto & part_info = part.isProjectionPart() ? part.getParentPart()->info : part.info; const bool fill_virtuals = !part_info.isPatch() && part_info.getBlocksCount() == 1 && part_info.level == 0 && part_info.mutation == 0; FormatSettings format_settings; - for (const auto & [column_name, column_type] : MergeTreeData::getMinMaxColumns(partition_key, data_settings)) + for (const auto & [column_name, column_type] : MergeTreeData::getMinMaxColumns(*metadata_snapshot, data_settings)) { const bool synth_block_number = (fill_virtuals || part.isSystemColumnInvalidated(BlockNumberColumn::name)) && metadata_snapshot->isVirtualColumn(BlockNumberColumn::name) && column_name == BlockNumberColumn::name; const bool synth_block_offset = (fill_virtuals || part.isSystemColumnInvalidated(BlockOffsetColumn::name)) && metadata_snapshot->isVirtualColumn(BlockOffsetColumn::name) && column_name == BlockOffsetColumn::name; @@ -227,7 +226,7 @@ void IMergeTreeDataPart::MinMaxIndex::load(const IMergeTreeDataPart & part) IMergeTreeDataPart::MinMaxIndex::WrittenFiles IMergeTreeDataPart::MinMaxIndex::store( StorageMetadataPtr metadata_snapshot, IDataPartStorage & part_storage, Checksums & out_checksums, const MergeTreeSettingsPtr & storage_settings) const { - return store(MergeTreeData::getMinMaxColumns(metadata_snapshot->getPartitionKey(), storage_settings), part_storage, out_checksums, storage_settings); + return store(MergeTreeData::getMinMaxColumns(*metadata_snapshot, storage_settings), part_storage, out_checksums, storage_settings); } IMergeTreeDataPart::MinMaxIndex::WrittenFiles IMergeTreeDataPart::MinMaxIndex::store( @@ -396,7 +395,7 @@ void IMergeTreeDataPart::MinMaxIndex::repairInheritedBlockColumns(const IMergeTr if (!initialized || source_part.isProjectionPart() || source_info.isPatch()) return; - const auto columns = MergeTreeData::getMinMaxColumns(metadata_snapshot->getPartitionKey(), source_part.storage.getSettings()); + const auto columns = MergeTreeData::getMinMaxColumns(*metadata_snapshot, source_part.storage.getSettings()); /// The inherited index may be narrower than the current set of minmax columns: the block columns are /// appended to the set when `part_minmax_index_columns` is widened, and changing the setting does not @@ -432,13 +431,12 @@ Names IMergeTreeDataPart::MinMaxIndex::getProbablyWrittenFiles(const IMergeTreeD return {}; const auto metadata_snapshot = part.getMetadataSnapshot(); - const auto & partition_key = metadata_snapshot->getPartitionKey(); const auto data_settings = part.storage.getSettings(); const auto & data_part_storage = part.getDataPartStorage(); /// The hyperrectangle may hold more columns than the current setting prescribes (a wider index that /// has not been re-materialized yet), so clamp to what `store` actually writes: its leading prefix. - auto minmax_columns = MergeTreeData::getMinMaxColumns(partition_key, data_settings); + auto minmax_columns = MergeTreeData::getMinMaxColumns(*metadata_snapshot, data_settings); if (minmax_columns.size() > hyperrectangle.size()) minmax_columns.resize(hyperrectangle.size()); @@ -2522,7 +2520,17 @@ void IMergeTreeDataPart::loadColumns(bool require, bool load_metadata_version) SerializationInfoByName infos({}); if (auto in = readFileIfExists(SERIALIZATION_FILE_NAME)) - infos = SerializationInfoByName::readJSON(loaded_columns, *in); + { + try + { + infos = SerializationInfoByName::readJSON(loaded_columns, *in); + } + catch (Exception & e) + { + e.addMessage("While reading {} of part {}", SERIALIZATION_FILE_NAME, name); + throw; + } + } std::optional loaded_metadata_version; if (load_metadata_version) diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index cc1cfddae41a..99cce8edb652 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -5242,7 +5242,10 @@ std::optional KeyCondition::applyMonotonicFunctionsChainToRange( /// on the given range, the Field values are guaranteed to be unchanged. /// We can skip the expensive function application that creates columns and executes the function. /// The monotonicity check already verified that the values fit in the target type. - bool skip_apply = functionIsIntegerCastPreservingFieldRepresentation(func, current_type, result_type); + /// A bound referencing a column in the index block is advanced by the application itself: + /// skipping would leave it on the previous column while `current_type` moves on. + bool skip_apply = key_range.left.isExplicit() && key_range.right.isExplicit() + && functionIsIntegerCastPreservingFieldRepresentation(func, current_type, result_type); if (!skip_apply) { diff --git a/src/Storages/MergeTree/MergeTask.cpp b/src/Storages/MergeTree/MergeTask.cpp index 0522979d205f..dd190bcf219c 100644 --- a/src/Storages/MergeTree/MergeTask.cpp +++ b/src/Storages/MergeTree/MergeTask.cpp @@ -494,8 +494,9 @@ void MergeTask::ExecuteAndFinalizeHorizontalPart::extractMergingAndGatheringColu for (const auto & column : projection->getRequiredColumns()) key_columns.insert(getColumnNameInStorage(column, storage_columns, virtual_columns)); - /// For vertical merge with TTL delete optimization, include columns needed by - /// TTL expressions in the horizontal phase so the TTL filter can be evaluated. + /// The TTL step runs over the merged stream, so every TTL expression it evaluates must read + /// from a merged column - a gathered one is missing from the block and the expression throws. + /// Place the inputs of every TTL the step builds an algorithm for, not just the deleting ones. if (ctx->need_remove_expired_values && canVerticalTTLDelete(*global_ctx)) { auto add_ttl_expression_columns = [&](const TTLDescription & ttl_descr) @@ -511,6 +512,12 @@ void MergeTask::ExecuteAndFinalizeHorizontalPart::extractMergingAndGatheringColu for (const auto & where_ttl : global_ctx->metadata_snapshot->getRowsWhereTTLs()) add_ttl_expression_columns(where_ttl); + + for (const auto & move_ttl : global_ctx->metadata_snapshot->getMoveTTLs()) + add_ttl_expression_columns(move_ttl); + + for (const auto & recompression_ttl : global_ctx->metadata_snapshot->getRecompressionTTLs()) + add_ttl_expression_columns(recompression_ttl); } for (auto it = global_ctx->skip_indexes_by_column.begin(); it != global_ctx->skip_indexes_by_column.end();) @@ -796,7 +803,7 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const } const bool has_block_columns = enabledBlockNumberColumn(global_ctx) && enabledBlockOffsetColumn(global_ctx); - global_ctx->minmax_idx_columns = MergeTreeData::getMinMaxColumns(global_ctx->metadata_snapshot->getPartitionKey(), global_ctx->data_settings, has_block_columns ? MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET : MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); + global_ctx->minmax_idx_columns = MergeTreeData::getMinMaxColumns(*global_ctx->metadata_snapshot, global_ctx->data_settings, has_block_columns ? MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET : MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); extractMergingAndGatheringColumns(exclude_index_names); const auto & expired_columns = global_ctx->new_data_part->expired_columns; @@ -3179,7 +3186,7 @@ void MergeTask::addBuildTextIndexesStep(QueryPlan & plan, const IMergeTreeDataPa std::move(writer_settings), global_ctx->compression_codec, global_ctx->new_data_part->index_granularity_info.mark_type.getFileExtension(), - *global_ctx->data->getSettings()); + global_ctx->data->getSettings()); /// Pass original header as output header to remove temporary columns added by the transform. /// This is important to make this part's plan compatible with other parts' plans that don't materialize indexes. diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index d382d77c1fa4..769f215e2df8 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -436,6 +436,9 @@ namespace FailPoints /// Throws a retryable error (`MEMORY_LIMIT_EXCEEDED`) while loading every outdated part in the /// background. Used to test that the loading is retried later instead of terminating the server. extern const char merge_tree_load_outdated_parts_retryable_error[]; + /// Throws `CANNOT_SCHEDULE_TASK` instead of handing an outdated part to the loading thread pool. + extern const char merge_tree_load_outdated_parts_schedule_error[]; + extern const char mt_pause_before_loading_outdated_part[]; /// Pauses every worker that loads an outdated part in the background until the failpoint is disabled. /// Used to cancel the loading (e.g. with `DETACH TABLE`) while the workers are in flight. extern const char merge_tree_load_outdated_parts_pause[]; @@ -811,7 +814,7 @@ MergeTreeData::MergeTreeData( { try { - checkPartitionKeyAndInitMinMax(metadata_.partition_key); + checkPartitionKeyAndInitMinMax(metadata_); setProperties(metadata_, metadata_, !sanity_checks); if (minmax_idx_date_column_pos == -1) throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, "Could not find Date column"); @@ -826,7 +829,7 @@ MergeTreeData::MergeTreeData( else { is_custom_partitioned = true; - checkPartitionKeyAndInitMinMax(metadata_.partition_key); + checkPartitionKeyAndInitMinMax(metadata_); } setProperties(metadata_, metadata_, !sanity_checks); @@ -1537,19 +1540,26 @@ ExpressionActionsPtr getCombinedIndicesExpression( } ExpressionActionsPtr MergeTreeData::getMinMaxExpr( - const KeyDescription & partition_key, + const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings, const ExpressionActionsSettings & expr_settings) { - return std::make_shared(ActionsDAG(getMinMaxColumns(partition_key, data_settings)), expr_settings); + return std::make_shared(ActionsDAG(getMinMaxColumns(metadata, data_settings)), expr_settings); } -NamesAndTypesList MergeTreeData::getMinMaxColumns(const KeyDescription & partition_key, const MergeTreeSettingsPtr & data_settings, MergeTreePartMinMaxIndexColumns up_to) +NamesAndTypesList MergeTreeData::getMinMaxColumns(const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings, MergeTreePartMinMaxIndexColumns up_to) { NamesAndTypesList columns; + const auto & partition_key = metadata.getPartitionKey(); const MergeTreePartMinMaxIndexColumns setting_level = (*data_settings)[MergeTreeSetting::part_minmax_index_columns]; - const auto level = std::min(setting_level, up_to); + auto level = std::min(setting_level, up_to); + + /// A level applies only if the metadata has all its columns, and each level extends the previous one. + auto has_column = [&](const String & name) { return metadata.getColumns().has(name) || metadata.virtuals.has(name); }; + if (level >= MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET + && !(has_column(BlockNumberColumn::name) && has_column(BlockOffsetColumn::name))) + level = MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY; if (level >= MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY) if (!partition_key.column_names.empty()) @@ -1564,9 +1574,9 @@ NamesAndTypesList MergeTreeData::getMinMaxColumns(const KeyDescription & partiti return columns; } -NamesAndTypesList MergeTreeData::getMinMaxColumns(const KeyDescription & partition_key, const MergeTreeSettingsPtr & data_settings) +NamesAndTypesList MergeTreeData::getMinMaxColumns(const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings) { - return getMinMaxColumns(partition_key, data_settings, MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET); + return getMinMaxColumns(metadata, data_settings, MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET); } ExpressionActionsPtr @@ -1581,15 +1591,16 @@ MergeTreeData::getSortingKeyAndSkipIndicesExpression(const StorageMetadataPtr & return getCombinedIndicesExpression(metadata_snapshot->getSortingKey(), indices, metadata_snapshot->columns, metadata_snapshot->virtuals, getContext()); } -void MergeTreeData::checkPartitionKeyAndInitMinMax(const KeyDescription & new_partition_key) +void MergeTreeData::checkPartitionKeyAndInitMinMax(const StorageInMemoryMetadata & new_metadata) { + const auto & new_partition_key = new_metadata.getPartitionKey(); if (new_partition_key.expression_list_ast->children.empty()) return; checkKeyExpression(*new_partition_key.expression, new_partition_key.sample_block, "Partition", allow_nullable_key); /// Add all columns used in the partition key to the min-max index. - const auto minmax_columns = getMinMaxColumns(new_partition_key, getSettings()); + const auto minmax_columns = getMinMaxColumns(new_metadata, getSettings()); /// Try to find the date column in columns used by the partition key (a common case). /// If there are no - DateTime or DateTime64 would also suffice. @@ -3602,6 +3613,7 @@ try while (true) { ThreadFuzzer::maybeInjectSleep(); + FailPointInjection::pauseFailPoint(FailPoints::mt_pause_before_loading_outdated_part); PartLoadingTree::NodePtr part; { @@ -3629,7 +3641,8 @@ try } /// The captured locals will outlive runner, so capturing by reference is ok - runner.enqueueAndKeepTrack([this, my_part = part, &num_loaded_parts, &failed_parts_mutex, &failed_parts, &retryable_exception, &has_retryable_exception, replicated]() + auto load_part = [this, my_part = part, &num_loaded_parts, &failed_parts_mutex, &failed_parts, + &retryable_exception, &has_retryable_exception, replicated]() { auto blocker_for_runner_thread = CannotAllocateThreadFaultInjector::blockFaultInjections(); @@ -3672,7 +3685,31 @@ try res.part->remove(); else preparePartForRemoval(res.part); - }, Priority{}); + }; + + try + { + fiu_do_on(FailPoints::merge_tree_load_outdated_parts_schedule_error, + { + throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "Injected scheduling error for outdated part {}", part->name); + }); + + runner.enqueueAndKeepTrack(std::move(load_part), Priority{}); + } + catch (const Exception & e) + { + /// E.g. no thread can be started because queries exhausted the global thread pool. + /// The pool has not taken the load, so the part is retried later like a retryable load error. + if (e.code() != ErrorCodes::CANNOT_SCHEDULE_TASK) + throw; + + std::lock_guard lock(failed_parts_mutex); + failed_parts.push_back(part); + if (!retryable_exception) + retryable_exception = std::current_exception(); + has_retryable_exception = true; + break; + } } runner.waitForAllToFinishAndRethrowFirstError(); @@ -4941,6 +4978,12 @@ void MergeTreeData::dropAllData() if (disk->existsDirectory(fs::path(relative_data_path) / MOVING_DIR_NAME)) disk->removeRecursive(fs::path(relative_data_path) / MOVING_DIR_NAME); + if ((*settings_ptr)[MergeTreeSetting::table_disk]) + { + LOG_INFO(log, "dropAllData: the table directory is the root of disk {}, it is kept", disk->getName()); + continue; + } + try { if (!isSharedStorage() && !disk->isDirectoryEmpty(relative_data_path) @@ -8614,6 +8657,8 @@ Pipe MergeTreeData::alterPartition( const PartitionCommands & commands, ContextPtr query_context) { + auto component_guard = Coordination::setCurrentComponent("MergeTreeData::alterPartition"); + /// Reject all ALTER ... PARTITION ... operations on UNIQUE KEY tables. /// Each command interacts with the dense-index sidecar and bitmap state /// in ways that require UK-aware semantics not yet implemented. @@ -10725,7 +10770,7 @@ bool MergeTreeData::isPrimaryOrMinMaxKeyColumnPossiblyWrappedInFunctions( if (column_name == name) return true; - for (const auto & [name, _] : getMinMaxColumns(metadata_snapshot->getPartitionKey(), getSettings())) + for (const auto & [name, _] : getMinMaxColumns(*metadata_snapshot, getSettings())) if (column_name == name) return true; @@ -10763,10 +10808,8 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( { auto func = column.getAggregateFunction(); Arena & arena = column.createOrGetArena(); - size_t size_of_state = func->sizeOfData(); - size_t align_of_state = func->alignOfData(); - auto * place = arena.alignedAlloc(size_of_state, align_of_state); - func->create(place); + column.insertDefault(); + auto * place = column.getData().back(); if (const AggregateFunctionCount * /*agg_count*/ _ = typeid_cast(func.get())) AggregateFunctionCount::set(place, value.safeGet()); else @@ -10775,7 +10818,6 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( const auto * value_column_ptr = value_column.get(); func->add(place, &value_column_ptr, 0, &arena); } - column.insertFrom(place); }; Block virtual_columns_block; @@ -10796,10 +10838,9 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( DataTypes minmax_columns_types; if (filter_dag) { - const auto & partition_key = metadata_snapshot->getPartitionKey(); const auto data_settings = getSettings(); - if (auto minmax_columns = getMinMaxColumns(partition_key, data_settings); !minmax_columns.empty()) + if (auto minmax_columns = getMinMaxColumns(*metadata_snapshot, data_settings); !minmax_columns.empty()) { minmax_columns_types = minmax_columns.getTypes(); @@ -10808,7 +10849,7 @@ Block MergeTreeData::getMinMaxCountProjectionBlock( ActionsDAGWithInversionPushDown wrapped(predicate, query_context, /* boolean_context */ false); return KeyCondition{ wrapped, query_context, minmax_columns.getNames(), - MergeTreeData::getMinMaxExpr(metadata_snapshot->getPartitionKey(), data_settings, ExpressionActionsSettings(query_context)), + MergeTreeData::getMinMaxExpr(*metadata_snapshot, data_settings, ExpressionActionsSettings(query_context)), /*single_point=*/false, /*skip_analysis=*/!query_context->getSettingsRef()[Setting::use_partition_pruning]}; }; @@ -13002,7 +13043,7 @@ std::pair MergeTreeData::createE NamesAndTypesList columns = metadata_snapshot->getColumns().getAllPhysical().filter(block.getNames()); auto minmax_idx = std::make_shared(); - minmax_idx->update(block, getMinMaxColumns(metadata_snapshot->getPartitionKey(), getSettings())); + minmax_idx->update(block, getMinMaxColumns(*metadata_snapshot, getSettings())); DB::IMergeTreeDataPart::TTLInfos move_ttl_infos; VolumePtr volume = getStoragePolicy()->getVolume(0); diff --git a/src/Storages/MergeTree/MergeTreeData.h b/src/Storages/MergeTree/MergeTreeData.h index aa97f33a44eb..f1fe6fcf2399 100644 --- a/src/Storages/MergeTree/MergeTreeData.h +++ b/src/Storages/MergeTree/MergeTreeData.h @@ -1388,12 +1388,12 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr Int64 minmax_idx_time_column_pos = -1; /// In other cases, minmax index often includes a dateTime column. /// Get expression on columns for which part-level min-max index will be calculated. - static ExpressionActionsPtr getMinMaxExpr(const KeyDescription & partition_key, + static ExpressionActionsPtr getMinMaxExpr(const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings, const ExpressionActionsSettings & expr_settings); /// Get the columns covered by the part-level min-max index. - static NamesAndTypesList getMinMaxColumns(const KeyDescription & partition_key, const MergeTreeSettingsPtr & data_settings, MergeTreePartMinMaxIndexColumns up_to); - static NamesAndTypesList getMinMaxColumns(const KeyDescription & partition_key, const MergeTreeSettingsPtr & data_settings); + static NamesAndTypesList getMinMaxColumns(const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings, MergeTreePartMinMaxIndexColumns up_to); + static NamesAndTypesList getMinMaxColumns(const StorageInMemoryMetadata & metadata, const MergeTreeSettingsPtr & data_settings); ExpressionActionsPtr getPrimaryKeyAndSkipIndicesExpression(const StorageMetadataPtr & metadata_snapshot, const MergeTreeIndices & indices) const; @@ -1857,7 +1857,7 @@ class MergeTreeData : public WithMutableContext, public IStorage, public IBackgr void checkMinMaxIndexForJSON(const IndexDescription & index) const; - void checkPartitionKeyAndInitMinMax(const KeyDescription & new_partition_key); + void checkPartitionKeyAndInitMinMax(const StorageInMemoryMetadata & new_metadata); void checkTTLExpressions(const StorageInMemoryMetadata & new_metadata, const StorageInMemoryMetadata & old_metadata) const; diff --git a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index bae6fb67cdc0..22ec979eccb1 100644 --- a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -166,7 +166,7 @@ static std::vector> buildPrimaryKeyToMinMaxSlotMapping( { const auto & primary_key = metadata_snapshot->getPrimaryKey(); const auto minmax_names = MergeTreeData::getMinMaxColumns( - metadata_snapshot->getPartitionKey(), data_settings, MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY).getNames(); + *metadata_snapshot, data_settings, MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY).getNames(); std::vector> mapping(primary_key.column_names.size()); for (size_t i = 0; i < primary_key.column_names.size(); ++i) @@ -726,7 +726,7 @@ RangesInDataParts MergeTreeDataSelectExecutor::filterPartsByPartition( DataTypes minmax_columns_types; if (minmax_idx_condition) - minmax_columns_types = MergeTreeData::getMinMaxColumns(metadata_snapshot->getPartitionKey(), data.getSettings()).getTypes(); + minmax_columns_types = MergeTreeData::getMinMaxColumns(*metadata_snapshot, data.getSettings()).getTypes(); if (metadata_snapshot->hasPartitionKey() && settings[Setting::force_index_by_date] && (!minmax_idx_condition || minmax_idx_condition->generateUnsubstituted().alwaysUnknownOrTrue()) diff --git a/src/Storages/MergeTree/MergeTreeDataWriter.cpp b/src/Storages/MergeTree/MergeTreeDataWriter.cpp index f008dd050d14..c3a401d48e53 100644 --- a/src/Storages/MergeTree/MergeTreeDataWriter.cpp +++ b/src/Storages/MergeTree/MergeTreeDataWriter.cpp @@ -458,7 +458,7 @@ void MergeTreeTemporaryPart::finalize() /// in-memory index so `getMinMaxIndex()` reloads from disk and applies the 0-level correction. const auto metadata_snapshot = part->getMetadataSnapshot(); const auto data_settings = part->storage.getSettings(); - for (const auto & [minmax_column, _] : MergeTreeData::getMinMaxColumns(metadata_snapshot->getPartitionKey(), data_settings)) + for (const auto & [minmax_column, _] : MergeTreeData::getMinMaxColumns(*metadata_snapshot, data_settings)) if (metadata_snapshot->isVirtualColumn(minmax_column)) part->setMinMaxIndex(nullptr); } @@ -730,7 +730,7 @@ MergeTreeTemporaryPartPtr MergeTreeDataWriter::writeTempPartImpl( auto columns = metadata_snapshot->getColumns().getAllPhysical().filter(block.getNames()); /// Do not write _block_number and _block_offset for 0-level parts: block number is not known on this step. - const auto minmax_columns = MergeTreeData::getMinMaxColumns(metadata_snapshot->getPartitionKey(), data_settings, MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); + const auto minmax_columns = MergeTreeData::getMinMaxColumns(*metadata_snapshot, data_settings, MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); auto minmax_idx = std::make_shared(); minmax_idx->update(block, minmax_columns); diff --git a/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp b/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp index 982696184e25..9835d04e5953 100644 --- a/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp +++ b/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp @@ -5,6 +5,10 @@ #include #include +#include +#include +#include + namespace DB { @@ -43,7 +47,7 @@ try /// and it might be not empty inside res_columns (and SubstreamsCache contains the whole columns). std::unordered_map columns_cache_for_subcolumns; - for (size_t pos = 0; pos < num_columns; ++pos) + for (size_t pos : read_order) { if (!res_columns[pos]) { @@ -109,6 +113,18 @@ catch (...) throw; } +void MergeTreeReaderCompactSingleBuffer::fillReadOrder() +{ + read_order.resize(columns_to_read.size()); + std::iota(read_order.begin(), read_order.end(), 0); + + /// Stable, since the columns with the same position share the caches of a granule. + std::ranges::stable_sort(read_order, {}, [&](size_t pos) + { + return column_positions[pos].value_or(std::numeric_limits::max()); + }); +} + void MergeTreeReaderCompactSingleBuffer::init() try { diff --git a/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.h b/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.h index ae10da0deb38..af3c832082ae 100644 --- a/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.h +++ b/src/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.h @@ -16,6 +16,7 @@ class MergeTreeReaderCompactSingleBuffer : public MergeTreeReaderCompact : MergeTreeReaderCompact{std::forward(args)...} { fillColumnPositions(); + fillReadOrder(); } /// Returns the number of rows has been read or zero if there is no columns to read. @@ -27,6 +28,12 @@ class MergeTreeReaderCompactSingleBuffer : public MergeTreeReaderCompact private: MergeTreeReaderStream & getStream(const NameAndTypePair &) override { return *stream; } void init(); + void fillReadOrder(); + + /// Indexes in `columns_to_read` in the order of the columns in the data file. + /// A granule is read in this order, since a backward seek out of the buffer is a new request + /// that reads the data after it again (i.e. mutation reads columns in the order of `NameSet`). + std::vector read_order; bool initialized = false; std::unique_ptr stream; diff --git a/src/Storages/MergeTree/MergeTreeReaderStream.cpp b/src/Storages/MergeTree/MergeTreeReaderStream.cpp index 00710958ba83..8a66bd3cbc8d 100644 --- a/src/Storages/MergeTree/MergeTreeReaderStream.cpp +++ b/src/Storages/MergeTree/MergeTreeReaderStream.cpp @@ -78,6 +78,10 @@ void MergeTreeReaderStream::init() if (!read_settings.local_fs_settings.buffer_size || !read_settings.remote_fs_settings.buffer_size) throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read to empty buffer."); + /// The reader bounds its reads at the right offset of its last mark, see `adjustRightMark`. Knowing it up front + /// lets a pipeline stage that reads before the bound is set, such as the encryption header, already use it. + const size_t right_offset = getRightOffset(getLastMark(all_mark_ranges)); + auto build_read_buffer = [&]() -> std::unique_ptr { ReadPipeline pipeline; @@ -86,6 +90,8 @@ void MergeTreeReaderStream::init() read_settings, estimated_sum_mark_range_bytes, pipeline); + if (right_offset) + pipeline.setInitialReadUntilPosition(right_offset); return pipeline.build(); }; @@ -106,7 +112,7 @@ void MergeTreeReaderStream::init() { auto buffer = std::make_unique( std::string(fs::path(data_part_storage->getFullPath()) / (path_prefix + data_file_extension)), - [this, estimated_sum_mark_range_bytes, read_settings]() + [this, estimated_sum_mark_range_bytes, read_settings, right_offset]() -> std::unique_ptr { auto local_component_guard = Coordination::setCurrentComponent("MergeTreeReaderStream::create_buffer"); @@ -116,6 +122,8 @@ void MergeTreeReaderStream::init() read_settings, estimated_sum_mark_range_bytes, pipeline); + if (right_offset) + pipeline.setInitialReadUntilPosition(right_offset); return pipeline.build(); }, diff --git a/src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp b/src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp index d61b342cbe7a..d36b39934c3e 100644 --- a/src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp +++ b/src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp @@ -950,9 +950,18 @@ void MergeTreeReaderTextIndex::setPrecomputedGranule(const IndexGranulesMap & gr if (it != granules.end() && it->second) { + /// The postings streams are keyed by the tokens of the granule, so a different granule invalidates them. + /// `readRows` opens them only once, so an initialized reader opens them again for the new granule. + const bool granule_changed = it->second != granule; + resetCursors(); postings_blocks.clear(); + if (granule_changed) + large_postings_streams.clear(); setIndexGranule(it->second); + + if (granule_changed && is_initialized) + initializePostingStreams(); } } diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index c7f4576b487a..f202a5da4f5e 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -466,7 +466,9 @@ void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const RPNBuilderTree std::vector storage_columns_guarding_throwing_condition; for (size_t i = 0; i < infos.size(); ++i) { - if (!infos[i].viable || infos[i].expensive || !conditionMayThrow(infos[i].node.getDAGNode())) + /// The AST-based optimization (the old analyzer with `query_plan_optimize_prewhere` disabled) has no DAG nodes. + const auto * dag_node = infos[i].node.getDAGNode(); + if (!infos[i].viable || infos[i].expensive || !dag_node || !conditionMayThrow(dag_node)) continue; for (size_t j = 0; j < i; ++j) { diff --git a/src/Storages/MergeTree/MutateTask.cpp b/src/Storages/MergeTree/MutateTask.cpp index 42653cba1036..3ca11b441854 100644 --- a/src/Storages/MergeTree/MutateTask.cpp +++ b/src/Storages/MergeTree/MutateTask.cpp @@ -2175,8 +2175,8 @@ class PartMergerWriter { public: - explicit PartMergerWriter(MutationContextPtr ctx_) - : ctx(ctx_), projections(ctx->metadata_snapshot->projections) + PartMergerWriter(MutationContextPtr ctx_, MergeTreeDataPartChecksums & subtask_checksums_) + : ctx(ctx_), subtask_checksums(subtask_checksums_), projections(ctx->metadata_snapshot->projections) { } @@ -2236,6 +2236,7 @@ class PartMergerWriter State state{State::NEED_PREPARE}; MutationContextPtr ctx; + MergeTreeDataPartChecksums & subtask_checksums; size_t projection_block_num = 0; std::vector> merge_subtasks; @@ -2417,11 +2418,13 @@ void PartMergerWriter::createBuildTextIndexesTask() ctx->out->getWriterSettings(), ctx->compression_codec, ctx->mrk_extension, - *ctx->data->getSettings()); + ctx->data->getSettings()); } void PartMergerWriter::calculateProjection(size_t projection_idx, const Block & block, UInt64 starting_offset) { + chassert(!ctx->new_data_part->hasLightweightDelete() || block.has(RowExistsColumn::name)); + const auto & projection = *ctx->projections_to_build[projection_idx]; /// When mutations like CLEAR COLUMN do not include all columns in the pipeline output, @@ -2601,7 +2604,7 @@ bool PartMergerWriter::iterateThroughAllMergeSubtasks() if (task->executeStep()) return true; - task->addToChecksums(ctx->new_data_part->checksums); + task->addToChecksums(subtask_checksums); merge_subtasks.pop_back(); if (!projection_name.empty()) @@ -2770,6 +2773,10 @@ class MutateAllPartColumnsTask : public IExecutableTask auto part_compression_codec = ctx->data->getCompressionCodecForPart( ctx->metadata_snapshot, ctx->source_part->getBytesOnDisk(), ctx->source_part->ttl_infos, ctx->time_of_mutation); ctx->compression_codec = std::move(part_compression_codec.codec); + /// Record the chosen codec on the new part before writing: `MergeTextIndexesTask` compresses + /// the text index files with `new_data_part->default_codec`, which is otherwise set only in + /// `MergedBlockOutputStream::finalizePart`, so they would fall back to `LZ4`. + ctx->new_data_part->default_codec = ctx->compression_codec; const bool is_explicit_recompression = part_compression_codec.is_explicit_recompression; NameSet entries_to_hardlink; @@ -2832,7 +2839,10 @@ class MutateAllPartColumnsTask : public IExecutableTask if (need_recalculate) { - skip_indices.push_back(std::move(index_ptr)); + if (dynamic_cast(index_ptr.get())) + ctx->text_indices_to_recalc.insert(std::move(index_ptr)); + else + skip_indices.push_back(std::move(index_ptr)); } else { @@ -2939,7 +2949,10 @@ class MutateAllPartColumnsTask : public IExecutableTask if (ctx->metadata_snapshot->hasPrimaryKey() || ctx->metadata_snapshot->hasSecondaryIndices()) { - auto indices_expression_dag = ctx->data->getPrimaryKeyAndSkipIndicesExpression(ctx->metadata_snapshot, skip_indices)->getActionsDAG().clone(); + MergeTreeIndices indices_to_calculate = skip_indices; + indices_to_calculate.insert(indices_to_calculate.end(), ctx->text_indices_to_recalc.begin(), ctx->text_indices_to_recalc.end()); + + auto indices_expression_dag = ctx->data->getPrimaryKeyAndSkipIndicesExpression(ctx->metadata_snapshot, indices_to_calculate)->getActionsDAG().clone(); auto extracting_subcolumns_dag = createSubcolumnsExtractionActions(builder->getHeader(), indices_expression_dag.getRequiredColumnsNames(), ctx->context); if (!extracting_subcolumns_dag.getNodes().empty()) indices_expression_dag = ActionsDAG::merge(std::move(extracting_subcolumns_dag), std::move(indices_expression_dag)); @@ -3007,7 +3020,7 @@ class MutateAllPartColumnsTask : public IExecutableTask const auto & new_part_columns = ctx->new_data_part->getColumns(); const bool has_block_columns = new_part_columns.contains(BlockNumberColumn::name) && new_part_columns.contains(BlockOffsetColumn::name); ctx->minmax_idx = std::make_shared(); - ctx->minmax_idx_columns = MergeTreeData::getMinMaxColumns(ctx->metadata_snapshot->getPartitionKey(), ctx->data->getSettings(), has_block_columns ? MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET : MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); + ctx->minmax_idx_columns = MergeTreeData::getMinMaxColumns(*ctx->metadata_snapshot, ctx->data->getSettings(), has_block_columns ? MergeTreePartMinMaxIndexColumns::WITH_BLOCK_NUMBER_OFFSET : MergeTreePartMinMaxIndexColumns::PARTITION_KEY_ONLY); ctx->all_gathered_data.statistics = ColumnsStatistics(ctx->metadata_snapshot->getColumns()); MutationHelpers::processStatisticsChanges( @@ -3045,7 +3058,8 @@ class MutateAllPartColumnsTask : public IExecutableTask ctx->mutating_pipeline.disableProfileEventUpdate(); ctx->mutating_executor = std::make_unique(ctx->mutating_pipeline); - part_merger_writer_task = std::make_unique(ctx); + /// `finalizePart` replaces the checksums of the part with `all_gathered_data`. + part_merger_writer_task = std::make_unique(ctx, ctx->all_gathered_data.checksums); } void finalize() @@ -3343,6 +3357,9 @@ class MutateSomePartColumnsTask : public IExecutableTask /// Column-only mutations keep the source part's codec, only the explicitness of a due `RECOMPRESS` is consulted. ctx->compression_codec = ctx->source_part->default_codec; + /// As in `MutateAllPartColumnsTask::prepare`: rebuilt text indexes read the codec from the new part, + /// which is otherwise set only in `finalizeMutatedPart`. + ctx->new_data_part->default_codec = ctx->compression_codec; const bool is_explicit_recompression = isExplicitRecompression( ctx->metadata_snapshot->getRecompressionTTLs(), ctx->source_part->ttl_infos.recompression_ttl, ctx->time_of_mutation); @@ -3426,7 +3443,7 @@ class MutateSomePartColumnsTask : public IExecutableTask ctx->projections_to_build = std::vector{ctx->projections_to_recalc.begin(), ctx->projections_to_recalc.end()}; - part_merger_writer_task = std::make_unique(ctx); + part_merger_writer_task = std::make_unique(ctx, ctx->new_data_part->checksums); } } diff --git a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp index a96864f7acc8..edf45860dbbe 100644 --- a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp +++ b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp @@ -23,6 +23,7 @@ namespace ErrorCodes { extern const int BAD_ARGUMENTS; extern const int LOGICAL_ERROR; + extern const int NO_SUCH_DATA_PART; extern const int TIMEOUT_EXCEEDED; } @@ -475,6 +476,17 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); auto part = storage.getActiveContainingPart(entry.part_name); + /// The pin blocks only merges and DROP PART, so the part can be removed, e.g. by TRUNCATE or DROP PARTITION. + /// A mutation can replace the pinned part with a part covering it, so a covering part with a different + /// name means the part we cloned is gone. Attaching it would attach the wrong checksum and then drop + /// the mutated part from the source, losing rows. + if (!part || part->name != entry.part_name) + throw Exception( + ErrorCodes::NO_SUCH_DATA_PART, + "Part {} is not active on replica {}, it cannot be attached on shard {}", + entry.part_name, + storage.replica_name, + entry.to_shard); /// Allocating block number in other replicas zookeeper path /// TODO Maybe we can do better. diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index 82d904c7670c..c845ef56350c 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include namespace DB @@ -346,8 +347,10 @@ struct ReplicatedMergeTreeCleanupThread::NodeWithStat Int64 ctime = 0; Int64 czxid = 0; Int32 version = 0; + Int32 num_children = 0; - NodeWithStat(String node_, Int64 ctime_, Int64 czxid_, Int32 version_) : node(std::move(node_)), ctime(ctime_), czxid(czxid_), version(version_) {} + NodeWithStat(String node_, Int64 ctime_, Int64 czxid_, Int32 version_, Int32 num_children_) + : node(std::move(node_)), ctime(ctime_), czxid(czxid_), version(version_), num_children(num_children_) {} /// Sort by (ctime, czxid) rather than (ctime, node_name) to ensure consistent ordering /// across different deduplication directories (blocks/, deduplication_hashes/). @@ -383,7 +386,7 @@ size_t ReplicatedMergeTreeCleanupThread::clearOldBlocks( current_time - static_cast(1000 * window_seconds)); /// Virtual node, all nodes that are "greater" than this one will be deleted - NodeWithStat block_threshold{{}, time_threshold, 0, 0}; + NodeWithStat block_threshold{{}, time_threshold, 0, 0, 0}; size_t current_deduplication_window = std::min(timed_blocks.size(), window_size); auto first_outdated_block_fixed_threshold = timed_blocks.begin() + current_deduplication_window; @@ -400,6 +403,44 @@ size_t ReplicatedMergeTreeCleanupThread::clearOldBlocks( first_outdated_block->node, first_outdated_block->ctime, last_outdated_block->node, last_outdated_block->ctime); + /// A node without children is removed with `TryRemove` in a `Multi` batch: it ignores a node that is already + /// removed by another cleaner or has another version, so concurrent cleaners cannot fail the batch. + if (zookeeper.isFeatureEnabled(DB::KeeperFeatureFlag::TRY_REMOVE)) + { + std::vector multi_futures; + Coordination::Requests batch; + for (auto it = first_outdated_block; it != timed_blocks.end(); ++it) + { + cached_block_stats.erase(it->node); + + String path = zookeeper_path + "/" + blocks_dir_name + "/" + it->node; + if (it->num_children > 0) + { + /// `TryRemove` skips nodes with children (leftovers of previous server versions). + /// Another cleaner can remove the node at the same time, so `ZNONODE` is fine. + const auto rc = zookeeper.tryRemoveRecursive(path); + if (rc != Coordination::Error::ZOK && rc != Coordination::Error::ZNONODE) + throw zkutil::KeeperException::fromPath(rc, path); + continue; + } + + batch.push_back(zkutil::makeRemoveRequest(path, it->version, /*try_remove=*/ true)); + if (batch.size() == zkutil::MULTI_BATCH_SIZE) + { + multi_futures.push_back(zookeeper.asyncMulti(batch)); + batch.clear(); + } + } + if (!batch.empty()) + multi_futures.push_back(zookeeper.asyncMulti(batch)); + + for (auto & future : multi_futures) + static_cast(future.get()); /// Throws if the `Multi` failed. + + LOG_TRACE(log_, "Cleared {} old blocks from ZooKeeper", num_nodes_to_delete); + return num_nodes_to_delete; + } + zkutil::AsyncResponses try_remove_futures; for (auto it = first_outdated_block; it != timed_blocks.end(); ++it) { @@ -483,7 +524,7 @@ void ReplicatedMergeTreeCleanupThread::getBlocksSortedByTime( { /// Cached block const auto & entry = it->second; - timed_blocks.emplace_back(block, entry.ctime, entry.czxid, entry.version); + timed_blocks.emplace_back(block, entry.ctime, entry.czxid, entry.version, entry.num_children); } } @@ -497,8 +538,8 @@ void ReplicatedMergeTreeCleanupThread::getBlocksSortedByTime( if (status.error != Coordination::Error::ZNONODE) { auto node_name = fs::path(exists_paths[i]).filename(); - cached_block_stats.emplace(node_name, NodeCacheEntry{status.stat.ctime, status.stat.czxid, status.stat.version}); - timed_blocks.emplace_back(node_name, status.stat.ctime, status.stat.czxid, status.stat.version); + cached_block_stats.emplace(node_name, NodeCacheEntry{status.stat.ctime, status.stat.czxid, status.stat.version, status.stat.numChildren}); + timed_blocks.emplace_back(node_name, status.stat.ctime, status.stat.czxid, status.stat.version, status.stat.numChildren); } } diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h index 2a6d4b82d3d4..29309c6ad107 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.h @@ -26,6 +26,8 @@ class ReplicatedMergeTreeCleanupThread : public IMergeTreeCleanupThread Int64 ctime = 0; Int64 czxid = 0; Int32 version = 0; + /// Block nodes never get children after creation, so the cached value stays valid. + Int32 num_children = 0; }; using NodeCTimeAndVersionCache = std::map; /// Remove old block hashes from ZooKeeper. This is done by the leader replica. Returns the number of removed blocks diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp index 1744b43ed8a3..bf6d6b3ba591 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp @@ -50,6 +50,7 @@ namespace DB { namespace Setting { + extern const SettingsBool async_insert_use_deduplication_cache; extern const SettingsFloat insert_keeper_fault_injection_probability; extern const SettingsUInt64 insert_keeper_fault_injection_seed; extern const SettingsUInt64 insert_keeper_max_retries; @@ -913,7 +914,7 @@ std::vector ReplicatedMergeTreeSink::commitPart( } } - if (is_async_insert) + if (is_async_insert && settings[Setting::async_insert_use_deduplication_cache]) { /// prefilter by cache auto conflicts = detectConflictsInCache(deduplication_hashes); diff --git a/src/Storages/MergeTree/TextIndexUtils.cpp b/src/Storages/MergeTree/TextIndexUtils.cpp index c9af211c950c..b80ab80dcb11 100644 --- a/src/Storages/MergeTree/TextIndexUtils.cpp +++ b/src/Storages/MergeTree/TextIndexUtils.cpp @@ -61,6 +61,7 @@ CompressionCodecPtr makeMarksCompressionCodec(const String & marks_compression_c return CompressionCodecFactory::instance().get(ast, nullptr); } +/// Long stream names are replaced with hashes, as the part writer does. std::pair>> makeOutputStreams( const MergeTreeIndexSubstreams & index_substreams, @@ -68,7 +69,8 @@ makeOutputStreams( const MutableDataPartStoragePtr & data_part_storage, const CompressionCodecPtr & default_codec, const String & marks_file_extension, - const MergeTreeWriterSettings & settings) + const MergeTreeWriterSettings & settings, + const MergeTreeSettings & storage_settings) { auto marks_compression_codec = makeMarksCompressionCodec(settings.marks_compression_codec); MergeTreeIndexOutputStreams streams; @@ -76,7 +78,7 @@ makeOutputStreams( for (const auto & index_substream : index_substreams) { - auto stream_name = index_name + index_substream.suffix; + auto stream_name = replaceFileNameToHashIfNeeded(index_name + index_substream.suffix, storage_settings, data_part_storage.get()); auto stream = std::make_unique( stream_name, @@ -121,7 +123,7 @@ BuildTextIndexTransform::BuildTextIndexTransform( MergeTreeWriterSettings writer_settings_, CompressionCodecPtr default_codec_, String marks_file_extension_, - const MergeTreeSettings & storage_settings) + MergeTreeSettingsPtr storage_settings_) : ISimpleTransform(header, header, false) , index_file_prefix(std::move(index_file_prefix_)) , indexes(std::move(indexes_)) @@ -129,10 +131,11 @@ BuildTextIndexTransform::BuildTextIndexTransform( , writer_settings(std::move(writer_settings_)) , default_codec(std::move(default_codec_)) , marks_file_extension(std::move(marks_file_extension_)) + , storage_settings(std::move(storage_settings_)) , segment_numbers(indexes.size(), 0) , estimated_allocated_bytes(indexes.size(), 0) - , max_processed_tokens(storage_settings[MergeTreeSetting::text_index_max_processed_tokens_before_flush]) - , max_allocated_bytes(storage_settings[MergeTreeSetting::text_index_max_memory_usage_before_flush]) + , max_processed_tokens((*storage_settings)[MergeTreeSetting::text_index_max_processed_tokens_before_flush]) + , max_allocated_bytes((*storage_settings)[MergeTreeSetting::text_index_max_memory_usage_before_flush]) { for (size_t i = 0; i < indexes.size(); ++i) @@ -223,7 +226,8 @@ void BuildTextIndexTransform::writeTemporarySegment(size_t i) temporary_storage, default_codec, marks_file_extension, - writer_settings); + writer_settings, + *storage_settings); writeMarks(streams, writer_settings.can_use_adaptive_granularity); granule->serializeBinaryWithMultipleStreams(streams); @@ -282,13 +286,16 @@ MergeTextIndexesTask::MergeTextIndexesTask( sparse_index_tokens = ColumnString::create(); sparse_index_offsets = ColumnUInt64::create(); + const auto storage_settings = new_data_part->storage.getSettings(); + std::tie(output_streams, output_streams_holders) = makeOutputStreams( index_ptr->getSubstreams(), index_ptr->getFileName(), new_data_part->getDataPartStoragePtr(), new_data_part->default_codec, new_data_part->getMarksFileExtension(), - writer_settings); + writer_settings, + *storage_settings); auto substreams = index_ptr->getSubstreams(); diff --git a/src/Storages/MergeTree/TextIndexUtils.h b/src/Storages/MergeTree/TextIndexUtils.h index dca5d2b6ad76..324954051efd 100644 --- a/src/Storages/MergeTree/TextIndexUtils.h +++ b/src/Storages/MergeTree/TextIndexUtils.h @@ -30,7 +30,7 @@ class BuildTextIndexTransform final : public ISimpleTransform MergeTreeWriterSettings writer_settings_, CompressionCodecPtr default_codec_, String marks_file_extension_, - const MergeTreeSettings & storage_settings); + MergeTreeSettingsPtr storage_settings_); String getName() const override { return "BuildTextIndexTransform"; } @@ -58,6 +58,7 @@ class BuildTextIndexTransform final : public ISimpleTransform MergeTreeWriterSettings writer_settings; CompressionCodecPtr default_codec; String marks_file_extension; + MergeTreeSettingsPtr storage_settings; /// Number of rows in blocks processed by the transform. size_t num_processed_rows = 0; diff --git a/src/Storages/ObjectStorage/Azure/Configuration.h b/src/Storages/ObjectStorage/Azure/Configuration.h index 0c6d57af8e14..630810ea020d 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.h +++ b/src/Storages/ObjectStorage/Azure/Configuration.h @@ -110,6 +110,10 @@ class StorageAzureConfiguration : public StorageObjectStorageConfiguration StorageObjectStorageQuerySettings getQuerySettings(const ContextPtr &) const override; String getContainer() const { return connection_params.getContainer(); } + String getConnectionURLWithoutQuery() const + { + return getSasKey().empty() ? connection_params.getConnectionURLWithoutQuery() : connection_params.endpoint.storage_account_url; + } String getAccountName() const { return connection_params.endpoint.account_name; } String getAccountKey() const { return connection_params.endpoint.account_key; } String getSasKey() const { return connection_params.endpoint.sas_auth; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp index fafc68825667..79a9083c26fe 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp @@ -115,6 +115,7 @@ void StorageObjectStorageConfiguration::initialize( else if (auto named_collection = tryGetNamedCollectionWithOverrides(engine_args, local_context, true, nullptr, table_id)) { configuration_to_initialize.fromNamedCollection(*named_collection, local_context); + configuration_to_initialize.initialized_from_named_collection = true; /// A base-URL setting (e.g. `s3_base`) rewrote a relative URL coming from the named /// collection. Materialize the resolved URL back into the engine args as a `url='...'` diff --git a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h index f903b18e2d47..51c005bb40cf 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h +++ b/src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h @@ -352,6 +352,9 @@ class StorageObjectStorageConfiguration /// startup (see `getClient` and the `s3_load_table_anonymously_if_credentials_restricted` server setting). bool is_loading_from_existing_metadata = false; + /// Set by `initialize` when the arguments come from a named collection. + bool initialized_from_named_collection = false; + /// False when the storage is instantiated from anything other than a user-issued `CREATE` /// (ATTACH, server startup, RESTORE, replicated-DDL replay). `initPartitionStrategy` must not /// apply the `file_like_engine_default_partition_strategy` default to such tables: a pre-26.6 diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index d96efabe196d..1777ec389021 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -69,8 +69,6 @@ #include #include #include -#include -#include #include #include @@ -680,6 +678,12 @@ Chunk StorageObjectStorageSource::generate() FailPointInjection::pauseFailPoint(FailPoints::object_storage_source_pause_before_virtual_columns); + /// `_headers` is added along with the other virtual columns, in the order they are requested in, + /// which is the order of the columns in the header of the source. + std::optional http_response_headers; + if (read_from_format_info.requested_virtual_columns.contains("_headers")) + http_response_headers = tryGetHeadersFromReadBuffer(reader.readBuffer()).value_or(objectAttributesToMap(object_metadata->attributes)); + VirtualColumnUtils::addRequestedFileLikeStorageVirtualsToChunk( chunk, read_from_format_info.requested_virtual_columns, @@ -697,23 +701,11 @@ Chunk StorageObjectStorageSource::generate() .tags = &(object_metadata->tags), .data_lake_snapshot_version = file_iterator->getSnapshotVersion(), .iceberg_metadata_file_path = iceberg_metadata_file_path, + .http_response_headers = http_response_headers ? &*http_response_headers : nullptr, }, read_context, format_settings); - if (read_from_format_info.requested_virtual_columns.contains("_headers")) - { - auto type = std::make_shared( - std::make_shared(std::make_shared()), - std::make_shared(std::make_shared())); - - const Map headers = tryGetHeadersFromReadBuffer(reader.readBuffer()).value_or(objectAttributesToMap(object_metadata->attributes)); - - chunk.addColumn(type->createColumnConst( - chunk.getNumRows(), - headers)->convertToFullColumnIfConst()); - } - if (lazy_row_index_registry) { /// Lazy materialization: append the `__global_row_index` column, which combines the diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp index bb4014269446..33f6fef8cc5f 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp @@ -52,6 +52,7 @@ namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int BAD_ARGUMENTS; + extern const int METADATA_MISMATCH; extern const int REPLICA_ALREADY_EXISTS; extern const int SUPPORT_IS_DISABLED; extern const int TIMEOUT_EXCEEDED; @@ -367,7 +368,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, Coordination::Stat stat; auto metadata_str = zookeeper->get(fs::path(zookeeper_path) / "metadata", &stat); auto metadata_from_zk = ObjectStorageQueueTableMetadata::parse(metadata_str); - auto new_table_metadata{table_metadata}; + auto new_table_metadata{metadata_from_zk}; for (const auto & change : changes) { @@ -393,7 +394,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (change.name == "processing_threads_num") { const auto value = change.value.safeGet(); - if (table_metadata.processing_threads_num == value) + if (new_table_metadata.processing_threads_num == value) { LOG_TRACE(log, "Setting `processing_threads_num` already equals {}. " "Will do nothing", value); @@ -404,7 +405,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "loading_retries") { const auto value = change.value.safeGet(); - if (table_metadata.loading_retries == value) + if (new_table_metadata.loading_retries == value) { LOG_TRACE(log, "Setting `loading_retries` already equals {}. " "Will do nothing", value); @@ -415,7 +416,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "after_processing") { const auto value = ObjectStorageQueueTableMetadata::actionFromString(change.value.safeGet()); - if (table_metadata.after_processing == value) + if (new_table_metadata.after_processing == value) { LOG_TRACE(log, "Setting `after_processing` already equals {}. " "Will do nothing", value); @@ -426,7 +427,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_files_limit") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_limit == value) + if (new_table_metadata.tracked_files_limit == value) { LOG_TRACE(log, "Setting `tracked_files_limit` already equals {}. " "Will do nothing", value); @@ -437,7 +438,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, else if (change.name == "tracked_file_ttl_sec") { const auto value = change.value.safeGet(); - if (table_metadata.tracked_files_ttl_sec == value) + if (new_table_metadata.tracked_files_ttl_sec == value) { LOG_TRACE(log, "Setting `tracked_file_ttl_sec` already equals {}. " "Will do nothing", value); @@ -466,6 +467,7 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (table_metadata.buckets == value) { LOG_TRACE(log, "Setting `buckets` already equals {}. Will do nothing", value); + new_table_metadata.buckets = value; continue; } if (table_metadata.buckets > 1) @@ -494,7 +496,10 @@ void ObjectStorageQueueMetadata::alterSettings(const SettingsChanges & changes, if (is_initial_query) zookeeper->set(table_metadata_path, new_metadata_str, stat.version); - table_metadata.syncChangeableSettings(new_table_metadata); + NameSet changed_names; + for (const auto & change : changes) + changed_names.insert(change.name); + table_metadata.syncChangeableSettings(new_table_metadata, changed_names); } void ObjectStorageQueueMetadata::migrateToBucketsInKeeper(size_t value) @@ -518,10 +523,11 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log) { - ObjectStorageQueueTableMetadata table_metadata(settings, columns, format); + ObjectStorageQueueTableMetadata table_metadata(settings, columns, format, source); std::vector metadata_paths; size_t buckets_num = 0; @@ -558,16 +564,38 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( { auto zk_client = getZooKeeper(log, zookeeper_name); std::optional metadata_from_zk; + Coordination::Stat stat; if (zk_client->exists(table_metadata_path)) { - const auto metadata_str = zk_client->get(table_metadata_path); + const auto metadata_str = zk_client->get(table_metadata_path, &stat); LOG_TRACE(log, "Metadata in keeper: {}", metadata_str); metadata_from_zk.emplace(ObjectStorageQueueTableMetadata::parse(metadata_str)); } if (metadata_from_zk.has_value()) { table_metadata.adjustFromKeeper(metadata_from_zk.value()); + /// A named collection can change without an `ALTER` of the table, so its source is always checked. + if (!strict && !source.from_named_collection && !metadata_from_zk->source_hash.empty() + && table_metadata.source_hash != metadata_from_zk->source_hash) + { + LOG_WARNING(log, "The source of this table differs from the source of the queue"); + table_metadata.source_hash = metadata_from_zk->source_hash; + } table_metadata.checkEquals(metadata_from_zk.value()); + if (metadata_from_zk->source_hash.empty()) + { + if (strict) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper has no source, as an older version wrote it. " + "Attach the main table (following the same `keeper_path`) of this queue on an upgraded server, or use another `keeper_path`"); + + if (!table_metadata.source_hash.empty()) + { + metadata_from_zk->source_hash = table_metadata.source_hash; + code = zk_client->trySet(table_metadata_path, metadata_from_zk->toString(), stat.version); + } + } return; } @@ -580,7 +608,7 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( "either `buckets`>1 or `processing_threads_num`>1 (works as `buckets` if it's not specified) " "will not work properly. Please specify them in the CREATE query. See documentation for more details."; - if (is_attach) + if (!strict) { LOG_WARNING(log, "{}", message); warned = true; @@ -645,6 +673,9 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( *code, exception.getPathForFirstFailedOp(), zookeeper_path.string()); continue; } + /// Keeper was changed after the metadata was read, for example by another server, so start again. + if (*code == Coordination::Error::ZBADVERSION || *code == Coordination::Error::ZNONODE) + continue; if (*code != Coordination::Error::ZOK) zkutil::KeeperMultiException::check(*code, requests, responses); } diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h index 78c4def06b6b..0e311910255a 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.h @@ -101,6 +101,8 @@ class ObjectStorageQueueMetadata /// - adjust, if needed and allowed, passed queue settings according to /// what is in keeper (for example, processing_threads_num is adjustable, /// because its default depends on the CPU cores on the server); + /// - if not `strict` or from a named collection, a table is loaded even if its source differs from keeper; + /// - if keeper has no `source` (metadata written by an older version), save the table's `source` there; static ObjectStorageQueueTableMetadata syncWithKeeper( const String & zookeeper_name, const fs::path & zookeeper_path, @@ -108,7 +110,8 @@ class ObjectStorageQueueMetadata const ColumnsDescription & columns, const std::string & format, const ContextPtr & context, - bool is_attach, + const ObjectStorageQueueTableMetadata::Source & source, + bool strict, LoggerPtr log); /// Alter settings in keeper metadata /// (rewrites what we write in syncWithKeeper()). diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp index e845fa34a6c0..ef8eb6e38554 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.cpp @@ -57,16 +57,24 @@ bool isEmptyValue(const Field & value) return value.getType() == Field::Types::String && value.safeGet().empty(); } +bool changesSourceObjects(const SettingChange & change) +{ + /// `after_processing` other than `keep` modifies the source files. + return (change.name == "after_processing" || change.name == "s3queue_after_processing") + && change.value.safeGet() != "keep"; +} + /// A table moves files only to the destination of its own storage type, see `ObjectStorageQueuePostProcessor::process`. -AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind) +AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, MoveDestinationKind table_kind, bool own_engine) { const bool sets_destination = std::ranges::any_of( changes, [&](const SettingChange & change) { return getMoveDestinationKind(change.name) == table_kind && !isEmptyValue(change.value); }); - if (!sets_destination) + if (!sets_destination && !(own_engine && std::ranges::any_of(changes, changesSourceObjects))) return {}; /// Unfiltered on purpose: a move has no single destination path to match a filter against. + /// For `after_processing`, the URL of the table is not known here either. /// For S3, the move writes keys built from `after_processing_move_prefix` and the source keys, and uses only /// the bucket of the URI, not its key. For Azure, the `azureBlobStorage` function matches source filters against /// the blob path (`StorageAzureConfiguration::getRawURI` returns `blob_path.path`). @@ -78,14 +86,14 @@ AccessRightsElements getMoveDestinationAccess(const SettingsChanges & changes, M } -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::S3); + return getMoveDestinationAccess(changes, MoveDestinationKind::S3, own_engine); } -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes) +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine) { - return getMoveDestinationAccess(changes, MoveDestinationKind::Azure); + return getMoveDestinationAccess(changes, MoveDestinationKind::Azure, own_engine); } void checkObjectStorageQueueS3MoveDestinationHost( diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h index 40601b4b1145..6cb036e19b27 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMoveDestinationAccess.h @@ -21,8 +21,10 @@ class RemoteHostFilter; /// `after_processing_move_connection_string` and `after_processing_move_container` for Azure, with or without the legacy /// `s3queue_` prefix. Changing only the move keys or prefix stays inside a destination an authorized user set. /// An empty value disables the move destination, so it is not a destination and needs no grant. -AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes); -AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes); +/// If `own_engine` (the table has this engine, or its engine is not known, as for `ON CLUSTER`), `after_processing` +/// other than `keep` needs the same unfiltered `WRITE`. +AccessRightsElements getS3QueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); +AccessRightsElements getAzureQueueMoveDestinationAccess(const SettingsChanges & changes, bool own_engine); /// Throws `UNACCEPTABLE_URL` if `remote_url_allow_hosts` does not allow the destination of a move to another S3 bucket. /// The move builds its client directly, so the destination never passes `StorageS3Configuration::check`. diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp index 0e764595e18c..de092e488c89 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace DB @@ -60,7 +61,8 @@ namespace ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_) + const std::string & format_, + const Source & source) : format_name(format_) , columns(columns_.toString(true)) , mode(engine_settings[ObjectStorageQueueSetting::mode].toString()) @@ -77,6 +79,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata( , tracked_files_limit(engine_settings[ObjectStorageQueueSetting::tracked_files_limit]) , tracked_files_ttl_sec(engine_settings[ObjectStorageQueueSetting::tracked_file_ttl_sec]) , buckets(engine_settings[ObjectStorageQueueSetting::buckets]) + , source_hash(source.getHash()) { processing_threads_num_changed = engine_settings[ObjectStorageQueueSetting::processing_threads_num].changed; if (!processing_threads_num_changed && engine_settings[ObjectStorageQueueSetting::processing_threads_num] <= 1) @@ -119,6 +122,7 @@ String ObjectStorageQueueTableMetadata::toString() const json.set("partitioning_mode", partitioning_mode); json.set("partition_regex", partition_regex); json.set("partition_component", partition_component); + json.set("source_hash", source_hash); std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM oss.exceptions(std::ios::failbit); @@ -210,6 +214,7 @@ ObjectStorageQueueTableMetadata::ObjectStorageQueueTableMetadata(const Poco::JSO , tracked_files_limit(getOrDefault(json, "tracked_files_limit", "s3queue_", 0ULL)) , tracked_files_ttl_sec(getOrDefault(json, "tracked_files_ttl_sec", "", getOrDefault(json, "tracked_file_ttl_sec", "s3queue_", 0ULL))) , buckets(getOrDefault(json, "buckets", "", 0ULL)) + , source_hash(getOrDefault(json, "source_hash", "", "")) { validateMode(mode); } @@ -221,6 +226,21 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueTableMetadata::parse(const Str return ObjectStorageQueueTableMetadata(json); } +String ObjectStorageQueueTableMetadata::Source::getHash() const +{ + if (empty()) + return {}; + + /// With the lengths, bucket `ab` with path `c/*` and bucket `a` with path `bc/*` have different hashes. + SipHash hash; + for (const auto & part : {type, endpoint, bucket, path_pattern}) + { + hash.update(part.size()); + hash.update(part); + } + return getHexUIntLowercase(hash.get128()); +} + void ObjectStorageQueueTableMetadata::adjustFromKeeper(const ObjectStorageQueueTableMetadata & from_zk) { if (processing_threads_num != from_zk.processing_threads_num) @@ -262,6 +282,11 @@ void ObjectStorageQueueTableMetadata::checkImmutableFieldsEquals(const ObjectSto from_zk.mode, mode); + if (!from_zk.source_hash.empty() && source_hash != from_zk.source_hash) + throw Exception( + ErrorCodes::METADATA_MISMATCH, + "Existing table metadata in ZooKeeper differs in source (storage type, endpoint, bucket or path)"); + if (bucketing_mode != from_zk.bucketing_mode) throw Exception( ErrorCodes::METADATA_MISMATCH, diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h index f06cfe473a9c..6af691e8b105 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -19,6 +20,20 @@ class ReadBuffer; */ struct ObjectStorageQueueTableMetadata { + /// Where the queue reads files from, without credentials. Tables with the same `keeper_path` must have the same + /// source, because processed files are tracked only by their path. + struct Source + { + String type; + String endpoint; + String bucket; + String path_pattern; + bool from_named_collection = false; + + [[nodiscard]] bool empty() const { return endpoint.empty(); } + [[nodiscard]] String getHash() const; + }; + /// Non-changeable settings. const String format_name; const String columns; @@ -38,11 +53,13 @@ struct ObjectStorageQueueTableMetadata std::atomic buckets; bool processing_threads_num_changed = false; + String source_hash; ObjectStorageQueueTableMetadata( const ObjectStorageQueueSettings & engine_settings, const ColumnsDescription & columns_, - const std::string & format_); + const std::string & format_, + const Source & source); ObjectStorageQueueTableMetadata(const ObjectStorageQueueTableMetadata & other) : format_name(other.format_name) @@ -60,16 +77,22 @@ struct ObjectStorageQueueTableMetadata , tracked_files_limit(other.tracked_files_limit.load()) , tracked_files_ttl_sec(other.tracked_files_ttl_sec.load()) , buckets(other.buckets.load()) + , source_hash(other.source_hash) { } - void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other) + void syncChangeableSettings(const ObjectStorageQueueTableMetadata & other, const NameSet & names) { - after_processing = other.after_processing.load(); - loading_retries = other.loading_retries.load(); - processing_threads_num = other.processing_threads_num.load(); - tracked_files_limit = other.tracked_files_limit.load(); - tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); + if (names.contains("after_processing")) + after_processing = other.after_processing.load(); + if (names.contains("loading_retries")) + loading_retries = other.loading_retries.load(); + if (names.contains("processing_threads_num")) + processing_threads_num = other.processing_threads_num.load(); + if (names.contains("tracked_files_limit")) + tracked_files_limit = other.tracked_files_limit.load(); + if (names.contains("tracked_file_ttl_sec")) + tracked_files_ttl_sec = other.tracked_files_ttl_sec.load(); } explicit ObjectStorageQueueTableMetadata(const Poco::JSON::Object::Ptr & json); diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp index 6692ac9ccc26..b9dfcd331ea2 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp @@ -319,6 +319,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_) : IStreamingStorage(table_id_) , WithContext(context_) @@ -463,6 +465,11 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( &zookeeper_name); LOG_INFO(log, "Using zookeeper path: {}", zk_path.string()); + if (strict_metadata_check && source.empty()) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot identify the source of the queue: the Azure endpoint is not an `http://` or `https://` URL"); + auto table_metadata = ObjectStorageQueueMetadata::syncWithKeeper( zookeeper_name, zk_path, @@ -470,7 +477,8 @@ StorageObjectStorageQueue::StorageObjectStorageQueue( storage_metadata.getColumns(), configuration_->format, context_, - is_attach, + source, + strict_metadata_check, log); ObjectStorageType storage_type = engine_name == "S3Queue" ? ObjectStorageType::S3 : ObjectStorageType::Azure; @@ -1702,6 +1710,14 @@ void StorageObjectStorageQueue::alter( SettingsChanges changed_settings; std::set new_settings_set; + std::set settings_in_query; + for (const auto & command : alter_commands) + { + for (const auto & change : command.settings_changes) + settings_in_query.insert(change.name); + settings_in_query.insert(command.settings_resets.begin(), command.settings_resets.end()); + } + auto metadata = tryGetFilesMetadata(); if (!metadata) throw Exception(ErrorCodes::TABLE_IS_DROPPED, "Table {} is dropped or detached", getStorageID()); @@ -1710,6 +1726,28 @@ void StorageObjectStorageQueue::alter( const size_t dependencies_count = getDependencies(); bool requires_detached_mv = false; + auto read_settings_in_keeper = [this]() + { + String metadata_in_keeper; + ObjectStorageQueueMetadata::getKeeperRetriesControl(log).retryLoop( + [&] { metadata_in_keeper = getZooKeeper()->get(zk_path / "metadata"); }); + const auto table_metadata_in_keeper = ObjectStorageQueueTableMetadata::parse(metadata_in_keeper); + return getSettings(&table_metadata_in_keeper); + }; + /// Shared by all tables with this `keeper_path` on this server, can differ from this table's `old_settings`. + auto local_shared_metadata_settings = getSettings(&metadata->getTableMetadata()); + std::optional settings_in_keeper; + auto differs_from_queue = [&](const SettingChange & setting) + { + if (!ObjectStorageQueueTableMetadata::isStoredInKeeper(setting.name) || !isSettingChangeable(setting.name, mode)) + return false; + if (local_shared_metadata_settings.get(setting.name) != setting.value) + return true; + if (!settings_in_keeper) + settings_in_keeper.emplace(read_settings_in_keeper()); + return settings_in_keeper->get(setting.name) != setting.value; + }; + for (auto & setting : new_settings) { LOG_TEST(log, "New setting {}: {}", setting.name, setting.value); @@ -1725,7 +1763,8 @@ void StorageObjectStorageQueue::alter( old_settings->begin(), old_settings->end(), [&](const SettingChange & change) { return change.name == setting.name; }); - setting_changed = it == old_settings->end() || it->value != setting.value; + setting_changed = it == old_settings->end() || it->value != setting.value + || (settings_in_query.contains(setting.name) && differs_from_queue(setting)); } if (!setting_changed) continue; @@ -1895,7 +1934,7 @@ StorageObjectStorageQueue::createFileIterator(ContextPtr local_context, const Ac shutdown_called); } -ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const +ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings(const ObjectStorageQueueTableMetadata * table_metadata_) const { /// We do not store queue settings /// (because of the inconvenience of keeping them in sync with ObjectStorageQueueTableMetadata), @@ -1903,14 +1942,14 @@ ObjectStorageQueueSettings StorageObjectStorageQueue::getSettings() const ObjectStorageQueueSettings settings; /// If startup() for a table was not called, just use the default queue settings. /// The same holds after shutdown(), which drops the metadata handle while `startup_finished` stays set. - if (!startup_finished) + if (!startup_finished && !table_metadata_) return settings; auto metadata = tryGetFilesMetadata(); if (!metadata) return settings; - const auto & table_metadata = metadata->getTableMetadata(); + const auto & table_metadata = table_metadata_ ? *table_metadata_ : metadata->getTableMetadata(); settings[ObjectStorageQueueSetting::mode] = table_metadata.mode; settings[ObjectStorageQueueSetting::after_processing] = table_metadata.after_processing; if (zookeeper_name == zkutil::DEFAULT_ZOOKEEPER_NAME) diff --git a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h index b82a747e157c..377b615e303d 100644 --- a/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h +++ b/src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h @@ -37,6 +37,8 @@ class StorageObjectStorageQueue : public IStreamingStorage, WithContext std::optional format_settings_, ASTStorage * engine_args, LoadingStrictnessLevel mode, + ObjectStorageQueueTableMetadata::Source source, + bool strict_metadata_check, bool keep_data_in_keeper_); String getName() const override { return engine_name; } @@ -68,7 +70,7 @@ class StorageObjectStorageQueue : public IStreamingStorage, WithContext zkutil::ZooKeeperPtr getZooKeeper() const; - ObjectStorageQueueSettings getSettings() const; + ObjectStorageQueueSettings getSettings(const ObjectStorageQueueTableMetadata * table_metadata = nullptr) const; /// Block until `path` is marked as processed (or failed) in Keeper by this /// queue, then return. diff --git a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp index 6de88a0c3f83..c30c5ed0b4ca 100644 --- a/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp +++ b/src/Storages/ObjectStorageQueue/registerQueueStorage.cpp @@ -6,6 +6,10 @@ #include #include #include +#include +#if CLICKHOUSE_CLOUD +#include +#endif #include #include #include @@ -13,6 +17,7 @@ #include #include #include +#include #if USE_AWS_S3 #include @@ -37,6 +42,7 @@ namespace Setting extern const SettingsString s3queue_default_zookeeper_path; extern const SettingsBool allow_experimental_object_storage_queue_hive_partitioning; extern const SettingsBool s3_allow_server_credentials_in_user_queries; + extern const SettingsS3UriStyle s3_uri_style; } namespace ObjectStorageQueueSetting @@ -44,6 +50,41 @@ namespace ObjectStorageQueueSetting extern const ObjectStorageQueueSettingsBool use_hive_partitioning; } +namespace +{ + +#if USE_AWS_S3 +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageS3Configuration & configuration, const ContextPtr & context) +{ + /// `S3::URI` keeps the user info in the endpoint or the bucket name, so such a URL is parsed again without it. + auto url = configuration.url; + if (!url.uri.getUserInfo().empty()) + { + Poco::URI uri = url.uri; + uri.setUserInfo(""); + url = S3::URI( + uri.toString(), + /*allow_archive_path_syntax*/ false, + /*keep_presigned_query_parameters*/ true, + /*uri_style*/ context->getSettingsRef()[Setting::s3_uri_style]); + } + return {configuration.getTypeName(), url.endpoint, url.bucket, configuration.getRawPath().path}; +} +#endif + +#if USE_AZURE_BLOB_STORAGE +ObjectStorageQueueTableMetadata::Source getQueueSource(const StorageAzureConfiguration & configuration, const ContextPtr &) +{ + String endpoint = configuration.getConnectionURLWithoutQuery(); + const Poco::URI uri(endpoint); + if (uri.getScheme() != "http" && uri.getScheme() != "https") + return {}; + return {configuration.getTypeName(), std::move(endpoint), configuration.getContainer(), configuration.getRawPath().path}; +} +#endif + +} + template StoragePtr createQueueStorage(const StorageFactory::Arguments & args) { @@ -132,12 +173,25 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) } } + auto source = getQueueSource(*configuration, args.getLocalContext()); + source.from_named_collection = configuration->initialized_from_named_collection; + /// The S3 client is built once in the storage constructor and reused by background threads, so the /// constructor needs the effective `s3_allow_server_credentials_in_user_queries` value from the CREATE /// query. The storage itself must keep the persistent global context (`args.getContext()`): it is held /// weakly by `WithContext` and used by background tasks, so a transient settings copy would expire. const bool allow_server_credentials_in_user_queries = args.getLocalContext()->getSettingsRef()[Setting::s3_allow_server_credentials_in_user_queries]; + /// Another replica of a `Replicated` database replays the definition that its initiator has checked. + const auto metadata_txn = args.getLocalContext()->getZooKeeperMetadataTransaction(); + bool is_secondary_ddl_replay = metadata_txn && !metadata_txn->isInitialQuery(); +#if CLICKHOUSE_CLOUD + is_secondary_ddl_replay |= args.getLocalContext()->getClientInfo().is_shared_catalog_internal + && !SharedDatabaseCatalog::isInitialQuery(args.getLocalContext()); +#endif + const bool is_replayed_definition = !isFreshTableDefinition(args.mode, args.query.attach_short_syntax) + || is_secondary_ddl_replay || args.getLocalContext()->isRecoveryFromStoredMetadata(); + const bool strict_metadata_check = (args.is_restore_from_backup && !is_secondary_ddl_replay) || !is_replayed_definition; return std::make_shared( std::move(queue_settings), @@ -151,6 +205,8 @@ StoragePtr createQueueStorage(const StorageFactory::Arguments & args) format_settings, args.storage_def, args.mode, + std::move(source), + strict_metadata_check, /* keep_data_in_keeper */ false); } diff --git a/src/Storages/ProjectionsDescription.cpp b/src/Storages/ProjectionsDescription.cpp index d68efaf8c901..cef5a1ac027e 100644 --- a/src/Storages/ProjectionsDescription.cpp +++ b/src/Storages/ProjectionsDescription.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -239,6 +240,17 @@ class ProjectionDataSink final : public ISink const size_t max_rows_allowed; }; +/// A projection part stores a persistent virtual column only when its query selects it, so only ephemeral ones are always available. +VirtualColumnsDescription createProjectionVirtuals(const KeyDescription * partition_key) +{ + VirtualColumnsDescription virtuals; + for (const auto & virtual_column : MergeTreeData::createVirtuals(partition_key)) + if (virtual_column.isEphemeral()) + virtuals.add(virtual_column); + + return virtuals; +} + } ProjectionDescription ProjectionDescription::getProjectionFromAST( @@ -540,7 +552,7 @@ void ProjectionDescription::fillProjectionDescriptionByQuery( } metadata.setColumns(std::move(metadata_columns)); - metadata.setVirtuals(MergeTreeData::createVirtuals(partition_key)); + metadata.setVirtuals(createProjectionVirtuals(partition_key)); /// Initialize implicit-minmax skip indices from the effective projection-level MergeTree settings /// (defaults from the projection index plus any user-supplied WITH SETTINGS overrides). @@ -653,7 +665,7 @@ ProjectionDescription ProjectionDescription::getMinMaxCountProjection( result.type = ProjectionDescription::Type::Aggregate; StorageInMemoryMetadata metadata; metadata.setColumns(ColumnsDescription(result.sample_block.getNamesAndTypesList())); - metadata.setVirtuals(MergeTreeData::createVirtuals(partition_key)); + metadata.setVirtuals(createProjectionVirtuals(partition_key)); metadata.partition_key = KeyDescription::buildEmptyKey(); metadata.sorting_key = KeyDescription::buildEmptyKey(); metadata.primary_key = KeyDescription::buildEmptyKey(); @@ -707,40 +719,11 @@ Block ProjectionDescription::calculateByQuery( /// It is needed for compatibility with existing projections that use positional arguments to allow successful cluster upgrade. mut_context->setSetting("enable_positional_arguments", positional_arguments_for_projections); - ASTPtr query_ast_copy = nullptr; - /// Only keep required columns Block source_block; for (const auto & column : required_columns) source_block.insert(block.getByName(column)); - /// Respect the _row_exists column. - if (block.has(RowExistsColumn::name)) - { - query_ast_copy = query_ast->clone(); - auto * select_row_exists = query_ast_copy->as(); - if (!select_row_exists) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot get ASTSelectQuery when adding _row_exists = 1. It's a bug"); - - auto row_exists_condition = makeASTOperator("equals", make_intrusive(RowExistsColumn::name), make_intrusive(1)); - - /// If the projection already has a WHERE clause (e.g., from a filtered projection), - /// we must AND the _row_exists condition with the existing WHERE rather than replacing it. - /// Otherwise the projection's own filter would be lost during mutations. - auto existing_where = select_row_exists->where(); - if (existing_where) - { - auto combined_where = makeASTFunction("and", std::move(existing_where), std::move(row_exists_condition)); - select_row_exists->setExpression(ASTSelectQuery::Expression::WHERE, std::move(combined_where)); - } - else - { - select_row_exists->setExpression(ASTSelectQuery::Expression::WHERE, std::move(row_exists_condition)); - } - - source_block.insert(block.getByName(RowExistsColumn::name)); - } - /// Create "_part_offset" column when needed for projection with parent part offsets if (with_parent_part_offset) { @@ -766,8 +749,20 @@ Block ProjectionDescription::calculateByQuery( source_block.insert({std::move(column), std::move(uint64), "_part_offset"}); } + /// Drop lightweight-deleted rows, after `_part_offset` is generated so the survivors keep their parent offsets + if (block.has(RowExistsColumn::name)) + { + FilterDescription row_exists_filter(*block.getByName(RowExistsColumn::name).column); + const size_t existing_rows = row_exists_filter.countBytesInFilter(); + if (existing_rows == 0) + return sample_block.cloneEmpty(); + if (existing_rows != block.rows()) + for (auto & column : source_block) + column.column = row_exists_filter.filter(*column.column, static_cast(existing_rows)); + } + auto builder = InterpreterSelectQuery( - query_ast_copy ? query_ast_copy : query_ast, + query_ast, mut_context, Pipe(std::make_shared(std::make_shared(std::move(source_block)))), SelectQueryOptions{ diff --git a/src/Storages/RabbitMQ/RabbitMQConnection.h b/src/Storages/RabbitMQ/RabbitMQConnection.h index 1dc914ff8b98..8419ef15ad24 100644 --- a/src/Storages/RabbitMQ/RabbitMQConnection.h +++ b/src/Storages/RabbitMQ/RabbitMQConnection.h @@ -40,6 +40,7 @@ class RabbitMQConnection /// RabbitMQHandler is thread safe. Any public methods can be called concurrently. RabbitMQHandler & getHandler() { return event_handler; } + const RabbitMQHandler & getHandler() const { return event_handler; } String connectionInfoForLog() const; diff --git a/src/Storages/RabbitMQ/RabbitMQHandler.cpp b/src/Storages/RabbitMQ/RabbitMQHandler.cpp index bccdfda332fb..3d43c9d311fb 100644 --- a/src/Storages/RabbitMQ/RabbitMQHandler.cpp +++ b/src/Storages/RabbitMQ/RabbitMQHandler.cpp @@ -33,6 +33,13 @@ void RabbitMQHandler::onReady(AMQP::TcpConnection * /* connection */) loop_state.store(Loop::RUN); } +uint16_t RabbitMQHandler::onNegotiate(AMQP::TcpConnection * connection, uint16_t interval) +{ + const auto negotiated_interval = AMQP::LibUvHandler::onNegotiate(connection, interval); + heartbeat_interval.store(negotiated_interval); + return negotiated_interval; +} + void RabbitMQHandler::startLoop() { std::lock_guard lock(startup_mutex); diff --git a/src/Storages/RabbitMQ/RabbitMQHandler.h b/src/Storages/RabbitMQ/RabbitMQHandler.h index 6ad8212f63c5..028015e066db 100644 --- a/src/Storages/RabbitMQ/RabbitMQHandler.h +++ b/src/Storages/RabbitMQ/RabbitMQHandler.h @@ -33,6 +33,7 @@ class RabbitMQHandler : public AMQP::LibUvHandler void onError(AMQP::TcpConnection * connection, const char * message) override; void onReady(AMQP::TcpConnection * connection) override; + uint16_t onNegotiate(AMQP::TcpConnection * connection, uint16_t interval) override; /// Loop for background thread worker. void startLoop(); @@ -55,6 +56,9 @@ class RabbitMQHandler : public AMQP::LibUvHandler bool connectionRunning() const { return connection_running.load(); } bool loopRunning() const { return loop_running.load(); } + /// Heartbeat interval in seconds negotiated with the server, 0 if heartbeats are disabled. + uint16_t getHeartbeatInterval() const { return heartbeat_interval.load(); } + void updateLoopState(UInt8 state) { loop_state.store(state); } UInt8 getLoopState() { return loop_state.load(); } @@ -64,6 +68,7 @@ class RabbitMQHandler : public AMQP::LibUvHandler std::atomic connection_running, loop_running; std::atomic loop_state; + std::atomic heartbeat_interval{0}; std::mutex startup_mutex; }; diff --git a/src/Storages/RabbitMQ/RabbitMQProducer.cpp b/src/Storages/RabbitMQ/RabbitMQProducer.cpp index 3b94e9764b7a..3b9688e9e5db 100644 --- a/src/Storages/RabbitMQ/RabbitMQProducer.cpp +++ b/src/Storages/RabbitMQ/RabbitMQProducer.cpp @@ -1,69 +1,34 @@ #include -#include -#include #include #include -#include -#include -#include -#include -#include namespace DB { -static const auto BATCH = 1000; -static const auto RETURNED_LIMIT = 50000; static const auto FINISH_PRODUCER_NUM_TRIES = 50; namespace ErrorCodes { - extern const int CANNOT_CONNECT_RABBITMQ; extern const int LOGICAL_ERROR; } RabbitMQProducer::RabbitMQProducer( - const RabbitMQConfiguration & configuration_, - const Names & routing_keys_, - const String & exchange_name_, - AMQP::ExchangeType exchange_type_, - size_t channel_id_base_, - bool persistent_, + RabbitMQPublisherPoolPtr publisher_pool_, std::atomic & shutdown_called_, LoggerPtr log_) : AsynchronousMessageProducer(log_) - , connection(configuration_, log_) - , routing_keys(routing_keys_) - , exchange_name(exchange_name_) - , exchange_type(exchange_type_) - , channel_id_base(std::to_string(channel_id_base_)) - , persistent(persistent_) + , publisher_pool(std::move(publisher_pool_)) , shutdown_called(shutdown_called_) - , payloads(BATCH) - , returned(RETURNED_LIMIT) + , payloads(RabbitMQPublisher::BATCH) { } void RabbitMQProducer::initialize() { LOG_TRACE(log, "Initializing producer"); - - if (connection.connect()) - setupChannel(); - else - throw Exception(ErrorCodes::CANNOT_CONNECT_RABBITMQ, "Cannot connect to RabbitMQ {}", connection.connectionInfoForLog()); - - if (exchange_type == AMQP::ExchangeType::headers) - { - for (const auto & header : routing_keys) - { - std::vector matching; - boost::split(matching, header, [](char c){ return c == '='; }); - key_arguments[matching[0]] = matching[1]; - } - } + publisher = publisher_pool->acquire(); } void RabbitMQProducer::stopProducingTask() @@ -73,7 +38,10 @@ void RabbitMQProducer::stopProducingTask() void RabbitMQProducer::finishImpl() { - connection.disconnect(); + if (can_reuse_publisher) + publisher_pool->release(std::move(publisher)); + else + publisher->disconnect(); } void RabbitMQProducer::produce(const String & message, size_t, const Columns &, size_t) @@ -98,218 +66,25 @@ void RabbitMQProducer::cancel() noexcept } } -void RabbitMQProducer::setupChannel() -{ - producer_channel = connection.createChannel(); - LOG_TRACE(log, "Created a producer channel"); - - producer_channel->onError([&](const char * message) - { - LOG_ERROR(log, "Producer's channel {} error: {}", channel_id, message); - - /// Channel is not usable anymore. (https://github.com/CopernicaMarketingSoftware/AMQP-CPP/issues/36#issuecomment-125112236) - producer_channel->close(); - - /* Save records that have not received ack/nack from server before channel closure. They are removed and pushed back again once - * they are republished because after channel recovery they will acquire new delivery tags, so all previous records become invalid - */ - for (const auto & record : delivery_record) - if (!returned.push(record.second)) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); - - LOG_DEBUG(log, "Producer on channel {} hasn't confirmed {} messages, {} waiting to be published", - channel_id, delivery_record.size(), payloads.size()); - - /// Delivery tags are scoped per channel. - delivery_record.clear(); - delivery_tag = 0; - producer_ready = false; - }); - - producer_channel->onReady([&]() - { - channel_id = channel_id_base + "_" + std::to_string(channel_id_counter++); - LOG_DEBUG(log, "Producer's channel {} is ready", channel_id); - - /* if persistent == true, onAck is received when message is persisted to disk or when it is consumed on every queue. If fails, - * onNack() is received. If persistent == false, message is confirmed the moment it is enqueued. First option is two times - * slower than the second, so default is second and the first is turned on in table setting. - * - * "Publisher confirms" are implemented similar to strategy#3 here https://www.rabbitmq.com/tutorials/tutorial-seven-java.html - */ - producer_channel->confirmSelect() - .onAck([&](uint64_t acked_delivery_tag, bool multiple) - { - removeRecord(acked_delivery_tag, multiple, false); - }) - .onNack([&](uint64_t nacked_delivery_tag, bool multiple, bool /* requeue */) - { - removeRecord(nacked_delivery_tag, multiple, true); - }); - producer_ready = true; - }); -} - -void RabbitMQProducer::removeRecord(UInt64 received_delivery_tag, bool multiple, bool republish) -{ - auto record_iter = delivery_record.find(received_delivery_tag); - chassert(record_iter != delivery_record.end()); - - if (multiple) - { - /// If multiple is true, then all delivery tags up to and including current are confirmed (with ack or nack). - ++record_iter; - - if (republish) - for (auto record = delivery_record.begin(); record != record_iter; ++record) - if (!returned.push(record->second)) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); - - /// Delete the records even in case when republished because new delivery tags will be assigned by the server. - delivery_record.erase(delivery_record.begin(), record_iter); - } - else - { - if (republish) - if (!returned.push(record_iter->second)) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); - - delivery_record.erase(record_iter); - } -} - -void RabbitMQProducer::publish(Payloads & messages, bool republishing) -{ - Payload payload; - - /* It is important to make sure that delivery_record.size() is never bigger than returned.size(), i.e. number if unacknowledged - * messages cannot exceed returned.size(), because they all might end up there - */ - while (!messages.empty() && producer_channel->usable() && delivery_record.size() < RETURNED_LIMIT) - { - bool pop_result = messages.pop(payload); - - if (!pop_result) - return; - - AMQP::Envelope envelope(payload.message.data(), payload.message.size()); - - /// if headers exchange is used, routing keys are added here via headers, if not - it is just empty - AMQP::Table message_settings = key_arguments; - - /* There is the case when connection is lost in the period after some messages were published and before ack/nack was sent by the - * server, then it means that publisher will never know whether those messages were delivered or not, and therefore those records - * that received no ack/nack before connection loss will be republished (see onError() callback), so there might be duplicates. To - * let consumer know that received message might be a possible duplicate - a "republished" field is added to message metadata - */ - message_settings["republished"] = std::to_string(republishing); - envelope.setHeaders(message_settings); - - /* Adding here a messageID property to message metadata. Since RabbitMQ does not guarantee exactly-once delivery, then on the - * consumer side "republished" field of message metadata can be checked and, if it set to 1, consumer might also check "messageID" - * property. This way detection of duplicates is guaranteed - */ - envelope.setMessageID(std::to_string(payload.id)); - - /// Delivery mode is 1 or 2. 1 is default. 2 makes a message durable, but makes performance 1.5-2 times worse - if (persistent) - envelope.setDeliveryMode(2); - - if (exchange_type == AMQP::ExchangeType::consistent_hash) - { - producer_channel->publish(exchange_name, std::to_string(delivery_tag), envelope); - } - else if (exchange_type == AMQP::ExchangeType::headers) - { - producer_channel->publish(exchange_name, "", envelope); - } - else - { - producer_channel->publish(exchange_name, routing_keys[0], envelope); - } - - /// This is needed for "publisher confirms", which guarantees at-least-once delivery - ++delivery_tag; - delivery_record.insert(delivery_record.end(), {delivery_tag, payload}); - - /// Need to break at some point to let event loop run, because no publishing actually happens before looping - if (delivery_tag % BATCH == 0) - break; - } - - iterateEventLoop(); -} - void RabbitMQProducer::startProducingTaskLoop() { LOG_TRACE(log, "Starting producer loop"); - while ((!payloads.isFinishedAndEmpty() || !returned.empty() || !delivery_record.empty()) && !shutdown_called.load()) - { - /// If onReady callback is not received, producer->usable() will anyway return true, - /// but must publish only after onReady callback. - if (producer_ready) - { - /* Publish main paylods only when there are no returned messages. This way it is ensured that returned messages are republished - * as fast as possible and no new publishes are made before returned messages are handled - */ - if (!returned.empty() && producer_channel->usable()) - publish(returned, true); - else if (!payloads.empty() && producer_channel->usable()) - publish(payloads, false); - } - - iterateEventLoop(); - - if (!producer_channel->usable()) - { - if (connection.reconnect()) - setupChannel(); - } - } + while ((!payloads.isFinishedAndEmpty() || publisher->hasPendingDeliveries()) && !shutdown_called.load()) + publisher->publishStep(payloads); int res = 0; size_t try_num = 0; - while (++try_num <= FINISH_PRODUCER_NUM_TRIES && (res = iterateEventLoop())) + while (++try_num <= FINISH_PRODUCER_NUM_TRIES && (res = publisher->iterateEventLoop())) { LOG_TEST(log, "Waiting for pending callbacks to finish (count: {}, try: {})", res, try_num); } - /// Shared flag so that a late-dispatched close() callback becomes a no-op if we stop waiting - /// on timeout, mirroring the setup/cleanup paths in StorageRabbitMQ. - auto abandoned = std::make_shared(false); - producer_channel->close() - .onSuccess([this, abandoned]() - { - if (*abandoned) - return; - LOG_TRACE(log, "Successfully closed producer channel"); - connection.getHandler().stopBlockingLoop(); - }) - .onError([this, abandoned](const char * message) - { - if (*abandoned) - return; - LOG_ERROR(log, "Failed to close producer channel: {}", message); - connection.getHandler().stopBlockingLoop(); - }); - - /// If the connection is dead the close() callbacks never fire. Bound the wait so that INSERT - /// producer shutdown (and therefore server shutdown) cannot block indefinitely. - if (!connection.getHandler().startBlockingLoopWithTimeout(BLOCKING_LOOP_TIMEOUT_MS)) - { - /// Make any late-dispatched callback above a no-op before we return. - *abandoned = true; - LOG_WARNING(log, "Timed out waiting for producer channel to close - connection may be dead"); - } + /// All messages are confirmed, so the next insert can continue on the same channel. + if (!shutdown_called.load() && publisher->isReusable()) + can_reuse_publisher = true; else - LOG_DEBUG(log, "Producer on channel completed"); -} - - -int RabbitMQProducer::iterateEventLoop() -{ - return connection.getHandler().iterateLoop(); + publisher->closeChannel(); } } diff --git a/src/Storages/RabbitMQ/RabbitMQProducer.h b/src/Storages/RabbitMQ/RabbitMQProducer.h index c51ebb4e822c..24f75dd08b5c 100644 --- a/src/Storages/RabbitMQ/RabbitMQProducer.h +++ b/src/Storages/RabbitMQ/RabbitMQProducer.h @@ -1,13 +1,10 @@ #pragma once #include -#include +#include #include -#include -#include #include -#include namespace DB { @@ -16,12 +13,7 @@ class RabbitMQProducer : public AsynchronousMessageProducer { public: RabbitMQProducer( - const RabbitMQConfiguration & configuration_, - const Names & routing_keys_, - const String & exchange_name_, - AMQP::ExchangeType exchange_type_, - size_t channel_id_base_, - bool persistent_, + RabbitMQPublisherPoolPtr publisher_pool_, std::atomic & shutdown_called_, LoggerPtr log_); @@ -31,78 +23,33 @@ class RabbitMQProducer : public AsynchronousMessageProducer private: String getProducingTaskName() const override { return "RabbitMQProducingTask"; } - struct Payload - { - String message; - UInt64 id{}; - }; - - using Payloads = ConcurrentBoundedQueue; + using Payload = RabbitMQPublisher::Payload; + using Payloads = RabbitMQPublisher::Payloads; void initialize() override; void stopProducingTask() override; void finishImpl() override; - int iterateEventLoop(); void startProducingTaskLoop() override; - void setupChannel(); - void removeRecord(UInt64 received_delivery_tag, bool multiple, bool republish); - void publish(Payloads & messages, bool republishing); - RabbitMQConnection connection; + RabbitMQPublisherPoolPtr publisher_pool; + + RabbitMQPublisherPtr publisher; - const Names routing_keys; - const String exchange_name; - AMQP::ExchangeType exchange_type; - const String channel_id_base; /// Serial number of current producer buffer - const bool persistent; + bool can_reuse_publisher = false; /* false: when shutdown is called; needed because table might be dropped before all acks are received * true: in all other cases */ std::atomic & shutdown_called; - AMQP::Table key_arguments; - - std::unique_ptr producer_channel; - bool producer_ready = false; - - /// Channel errors lead to channel closure, need to count number of recreated channels to update channel id - UInt64 channel_id_counter = 0; - - /// channel id which contains id of current producer buffer and serial number of recreated channel in this buffer - String channel_id; - /* payloads.queue: * - payloads are pushed to queue in countRow and popped by another thread in writingFunc, each payload gets into queue only once - * returned.queue: - * - payloads are pushed to queue: - * 1) inside channel->onError() callback if channel becomes unusable and the record of pending acknowledgements from server - * is non-empty. - * 2) inside removeRecord() if received nack() - negative acknowledgement from the server that message failed to be written - * to disk or it was unable to reach the queue. - * - payloads are popped from the queue once republished */ - Payloads payloads, returned; - - /* Counter of current delivery on a current channel. Delivery tags are scoped per channel. The server attaches a delivery tag for each - * published message - a serial number of delivery on current channel. Delivery tag is a way of server to notify publisher if it was - * able or unable to process delivery, i.e. it sends back a response with a corresponding delivery tag. - */ - UInt64 delivery_tag = 0; - - /* false: message delivery successfully ended: publisher received confirm from server that all published - * 1) persistent messages were written to disk - * 2) non-persistent messages reached the queue - * true: continue to process deliveries and returned messages - */ -// bool wait_all = true; + Payloads payloads; /// Needed to fill messageID property UInt64 payload_counter = 0; - - /// Record of pending acknowledgements from the server; its size never exceeds size of returned.queue - std::map delivery_record; }; } diff --git a/src/Storages/RabbitMQ/RabbitMQPublisher.cpp b/src/Storages/RabbitMQ/RabbitMQPublisher.cpp new file mode 100644 index 000000000000..de5feb84a799 --- /dev/null +++ b/src/Storages/RabbitMQ/RabbitMQPublisher.cpp @@ -0,0 +1,289 @@ +#include + +#include +#include +#include +#include + + +namespace DB +{ + +static const auto RETURNED_LIMIT = 50000; + +namespace ErrorCodes +{ + extern const int CANNOT_CONNECT_RABBITMQ; + extern const int LOGICAL_ERROR; +} + +RabbitMQPublisher::RabbitMQPublisher( + const RabbitMQConfiguration & configuration_, + const Names & routing_keys_, + const String & exchange_name_, + AMQP::ExchangeType exchange_type_, + size_t channel_id_base_, + bool persistent_, + LoggerPtr log_) + : connection(configuration_, log_) + , routing_keys(routing_keys_) + , exchange_name(exchange_name_) + , exchange_type(exchange_type_) + , channel_id_base(std::to_string(channel_id_base_)) + , persistent(persistent_) + , log(log_) + , returned(RETURNED_LIMIT) +{ + if (exchange_type == AMQP::ExchangeType::headers) + { + for (const auto & header : routing_keys) + { + std::vector matching; + boost::split(matching, header, [](char c){ return c == '='; }); + key_arguments[matching[0]] = matching[1]; + } + } +} + +void RabbitMQPublisher::connect() +{ + if (!connection.connect()) + throw Exception(ErrorCodes::CANNOT_CONNECT_RABBITMQ, "Cannot connect to RabbitMQ {}", connection.connectionInfoForLog()); + + setupChannel(); + + /// The channel `onReady` and `onError` callbacks stop the loop. Wait here rather than in the producing task, + /// so that the channel is ready even if the insert has no rows and the publisher can be reused. + if (!connection.getHandler().startBlockingLoopWithTimeout(BLOCKING_LOOP_TIMEOUT_MS) || !channel_ready) + { + /// Close the connection while the channel callbacks can still safely refer to this object. + disconnect(/* immediately */ true); + throw Exception( + ErrorCodes::CANNOT_CONNECT_RABBITMQ, "Cannot open a producer channel to RabbitMQ {}", connection.connectionInfoForLog()); + } +} + +void RabbitMQPublisher::setupChannel() +{ + channel = connection.createChannel(); + LOG_TRACE(log, "Created a producer channel"); + + channel->onError([&](const char * message) + { + LOG_ERROR(log, "Producer's channel {} error: {}", channel_id, message); + + /// Channel is not usable anymore. (https://github.com/CopernicaMarketingSoftware/AMQP-CPP/issues/36#issuecomment-125112236) + channel->close(); + + /* Save records that have not received ack/nack from server before channel closure. They are removed and pushed back again once + * they are republished because after channel recovery they will acquire new delivery tags, so all previous records become invalid + */ + for (const auto & record : delivery_record) + if (!returned.push(record.second)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); + + LOG_DEBUG(log, "Producer on channel {} hasn't confirmed {} messages", channel_id, delivery_record.size()); + + /// Delivery tags are scoped per channel. + delivery_record.clear(); + delivery_tag = 0; + channel_ready = false; + connection.getHandler().stopBlockingLoop(); + }); + + channel->onReady([&]() + { + channel_id = channel_id_base + "_" + std::to_string(channel_id_counter++); + LOG_DEBUG(log, "Producer's channel {} is ready", channel_id); + + /* if persistent == true, onAck is received when message is persisted to disk or when it is consumed on every queue. If fails, + * onNack() is received. If persistent == false, message is confirmed the moment it is enqueued. First option is two times + * slower than the second, so default is second and the first is turned on in table setting. + * + * "Publisher confirms" are implemented similar to strategy#3 here https://www.rabbitmq.com/tutorials/tutorial-seven-java.html + */ + channel->confirmSelect() + .onAck([&](uint64_t acked_delivery_tag, bool multiple) + { + removeRecord(acked_delivery_tag, multiple, false); + }) + .onNack([&](uint64_t nacked_delivery_tag, bool multiple, bool /* requeue */) + { + removeRecord(nacked_delivery_tag, multiple, true); + }); + channel_ready = true; + connection.getHandler().stopBlockingLoop(); + }); +} + +void RabbitMQPublisher::removeRecord(UInt64 received_delivery_tag, bool multiple, bool republish) +{ + /// The delivery tag comes from the broker, so it may refer to a message that is not (or no longer) in `delivery_record`. + if (multiple) + { + /// If multiple is true, then all delivery tags up to and including current are confirmed (with ack or nack). + auto record_iter = delivery_record.upper_bound(received_delivery_tag); + + if (republish) + for (auto record = delivery_record.begin(); record != record_iter; ++record) + if (!returned.push(record->second)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); + + /// Delete the records even in case when republished because new delivery tags will be assigned by the server. + delivery_record.erase(delivery_record.begin(), record_iter); + } + else + { + auto record_iter = delivery_record.find(received_delivery_tag); + if (record_iter == delivery_record.end()) + { + LOG_WARNING(log, "Received {} for unknown delivery tag {}, ignoring it", republish ? "nack" : "ack", received_delivery_tag); + return; + } + + if (republish) + if (!returned.push(record_iter->second)) + throw Exception(ErrorCodes::LOGICAL_ERROR, "Could not push to returned queue"); + + delivery_record.erase(record_iter); + } +} + +void RabbitMQPublisher::publish(Payloads & messages, bool republishing) +{ + Payload payload; + + /* It is important to make sure that delivery_record.size() is never bigger than returned.size(), i.e. number if unacknowledged + * messages cannot exceed returned.size(), because they all might end up there + */ + while (!messages.empty() && channel->usable() && delivery_record.size() < RETURNED_LIMIT) + { + bool pop_result = messages.pop(payload); + + if (!pop_result) + return; + + AMQP::Envelope envelope(payload.message.data(), payload.message.size()); + + /// if headers exchange is used, routing keys are added here via headers, if not - it is just empty + AMQP::Table message_settings = key_arguments; + + /* There is the case when connection is lost in the period after some messages were published and before ack/nack was sent by the + * server, then it means that publisher will never know whether those messages were delivered or not, and therefore those records + * that received no ack/nack before connection loss will be republished (see onError() callback), so there might be duplicates. To + * let consumer know that received message might be a possible duplicate - a "republished" field is added to message metadata + */ + message_settings["republished"] = std::to_string(republishing); + envelope.setHeaders(message_settings); + + /* Adding here a messageID property to message metadata. Since RabbitMQ does not guarantee exactly-once delivery, then on the + * consumer side "republished" field of message metadata can be checked and, if it set to 1, consumer might also check "messageID" + * property. This way detection of duplicates is guaranteed + */ + envelope.setMessageID(std::to_string(payload.id)); + + /// Delivery mode is 1 or 2. 1 is default. 2 makes a message durable, but makes performance 1.5-2 times worse + if (persistent) + envelope.setDeliveryMode(2); + + if (exchange_type == AMQP::ExchangeType::consistent_hash) + { + channel->publish(exchange_name, std::to_string(delivery_tag), envelope); + } + else if (exchange_type == AMQP::ExchangeType::headers) + { + channel->publish(exchange_name, "", envelope); + } + else + { + channel->publish(exchange_name, routing_keys[0], envelope); + } + + /// This is needed for "publisher confirms", which guarantees at-least-once delivery + ++delivery_tag; + delivery_record.insert(delivery_record.end(), {delivery_tag, payload}); + + /// Need to break at some point to let event loop run, because no publishing actually happens before looping + if (delivery_tag % BATCH == 0) + break; + } + + iterateEventLoop(); +} + +void RabbitMQPublisher::publishStep(Payloads & payloads) +{ + /// If onReady callback is not received, channel->usable() will anyway return true, + /// but must publish only after onReady callback. + if (channel_ready) + { + /* Publish main paylods only when there are no returned messages. This way it is ensured that returned messages are republished + * as fast as possible and no new publishes are made before returned messages are handled + */ + if (!returned.empty() && channel->usable()) + publish(returned, true); + else if (!payloads.empty() && channel->usable()) + publish(payloads, false); + } + + iterateEventLoop(); + + if (!channel->usable()) + { + if (connection.reconnect()) + setupChannel(); + } +} + +bool RabbitMQPublisher::isReusable() +{ + if (connection.isConnected()) + connection.heartbeat(); + iterateEventLoop(); + return connection.isConnected() && channel->usable() && channel_ready && !hasPendingDeliveries(); +} + +void RabbitMQPublisher::closeChannel() +{ + /// Shared flag so that a late-dispatched close() callback becomes a no-op if we stop waiting + /// on timeout, mirroring the setup/cleanup paths in StorageRabbitMQ. + auto abandoned = std::make_shared(false); + channel->close() + .onSuccess([this, abandoned]() + { + if (*abandoned) + return; + LOG_TRACE(log, "Successfully closed producer channel"); + connection.getHandler().stopBlockingLoop(); + }) + .onError([this, abandoned](const char * message) + { + if (*abandoned) + return; + LOG_ERROR(log, "Failed to close producer channel: {}", message); + connection.getHandler().stopBlockingLoop(); + }); + + /// If the connection is dead the close() callbacks never fire. Bound the wait so that INSERT + /// producer shutdown (and therefore server shutdown) cannot block indefinitely. + if (!connection.getHandler().startBlockingLoopWithTimeout(BLOCKING_LOOP_TIMEOUT_MS)) + { + /// Make any late-dispatched callback above a no-op before we return. + *abandoned = true; + LOG_WARNING(log, "Timed out waiting for producer channel to close - connection may be dead"); + } + else + LOG_DEBUG(log, "Producer on channel completed"); +} + +void RabbitMQPublisher::disconnect(bool immediately) +{ + connection.disconnect(immediately); +} + +int RabbitMQPublisher::iterateEventLoop() +{ + return connection.getHandler().iterateLoop(); +} + +} diff --git a/src/Storages/RabbitMQ/RabbitMQPublisher.h b/src/Storages/RabbitMQ/RabbitMQPublisher.h new file mode 100644 index 000000000000..1afc46fc3497 --- /dev/null +++ b/src/Storages/RabbitMQ/RabbitMQPublisher.h @@ -0,0 +1,114 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace DB +{ + +/// A connection with one confirm-mode channel to publish messages to an exchange. +/// The channel callbacks capture the publisher, so it owns all per-channel state (delivery tags and +/// unconfirmed messages). This allows `RabbitMQPublisherPool` to hand the same connection and channel +/// to subsequent `INSERT` queries. A publisher is used by one thread at a time. +class RabbitMQPublisher +{ +public: + struct Payload + { + String message; + UInt64 id{}; + }; + + using Payloads = ConcurrentBoundedQueue; + + /// Number of messages published before the event loop is run. + static constexpr size_t BATCH = 1000; + + RabbitMQPublisher( + const RabbitMQConfiguration & configuration_, + const Names & routing_keys_, + const String & exchange_name_, + AMQP::ExchangeType exchange_type_, + size_t channel_id_base_, + bool persistent_, + LoggerPtr log_); + + /// Connects and waits until the channel is ready. Throws `CANNOT_CONNECT_RABBITMQ`. + void connect(); + + /// Publishes a portion of messages (republished ones first), runs the event loop + /// and restores the connection and the channel if they are lost. + void publishStep(Payloads & payloads); + + /// Whether some messages are not confirmed by the server yet or have to be republished. + bool hasPendingDeliveries() const { return !returned.empty() || !delivery_record.empty(); } + + /// Runs the event loop once to process what the server sent in the meantime (e.g. closed the connection), + /// then checks that the connection and the channel are usable and nothing is pending. + bool isReusable(); + + int iterateEventLoop(); + + /// Closes the channel and waits for the server confirmation with a timeout. + void closeChannel(); + + void disconnect(bool immediately = false); + + /// Heartbeat interval in seconds negotiated with the server, 0 if heartbeats are disabled. + uint16_t getHeartbeatInterval() const { return connection.getHandler().getHeartbeatInterval(); } + +private: + friend class RabbitMQPublisherTest; + + void setupChannel(); + void removeRecord(UInt64 received_delivery_tag, bool multiple, bool republish); + void publish(Payloads & messages, bool republishing); + + RabbitMQConnection connection; + + const Names routing_keys; + const String exchange_name; + AMQP::ExchangeType exchange_type; + const String channel_id_base; /// Serial number of the publisher + const bool persistent; + LoggerPtr log; + + AMQP::Table key_arguments; + + std::unique_ptr channel; + bool channel_ready = false; + + /// Channel errors lead to channel closure, need to count number of recreated channels to update channel id + UInt64 channel_id_counter = 0; + + /// channel id which contains id of the publisher and serial number of recreated channel in this publisher + String channel_id; + + /* returned.queue: + * - payloads are pushed to queue: + * 1) inside channel->onError() callback if channel becomes unusable and the record of pending acknowledgements from server + * is non-empty. + * 2) inside removeRecord() if received nack() - negative acknowledgement from the server that message failed to be written + * to disk or it was unable to reach the queue. + * - payloads are popped from the queue once republished + */ + Payloads returned; + + /* Counter of current delivery on a current channel. Delivery tags are scoped per channel. The server attaches a delivery tag for each + * published message - a serial number of delivery on current channel. Delivery tag is a way of server to notify publisher if it was + * able or unable to process delivery, i.e. it sends back a response with a corresponding delivery tag. + */ + UInt64 delivery_tag = 0; + + /// Record of pending acknowledgements from the server; its size never exceeds size of returned.queue + std::map delivery_record; +}; + +using RabbitMQPublisherPtr = std::unique_ptr; + +} diff --git a/src/Storages/RabbitMQ/RabbitMQPublisherPool.cpp b/src/Storages/RabbitMQ/RabbitMQPublisherPool.cpp new file mode 100644 index 000000000000..029193180206 --- /dev/null +++ b/src/Storages/RabbitMQ/RabbitMQPublisherPool.cpp @@ -0,0 +1,153 @@ +#include + +#include + +#include +#include + + +namespace DB +{ + +RabbitMQPublisherPool::RabbitMQPublisherPool( + const RabbitMQConfiguration & configuration_, + const Names & routing_keys_, + const String & exchange_name_, + AMQP::ExchangeType exchange_type_, + bool persistent_, + size_t max_idle_publishers_, + LoggerPtr log_) + : configuration(configuration_) + , routing_keys(routing_keys_) + , exchange_name(exchange_name_) + , exchange_type(exchange_type_) + , persistent(persistent_) + , max_idle_publishers(max_idle_publishers_) + , log(log_) +{ +} + +RabbitMQPublisherPtr RabbitMQPublisherPool::acquire() +{ + while (auto idle = popIdlePublisher()) + { + if (!isExpired(*idle) && idle->publisher->isReusable()) + { + LOG_TRACE(log, "Reusing an idle producer connection"); + return std::move(idle->publisher); + } + + LOG_DEBUG(log, "Discarding an idle producer connection, which is expired or no longer usable"); + idle->publisher->disconnect(/* immediately */ true); + } + + auto publisher = std::make_unique( + configuration, routing_keys, exchange_name, exchange_type, publisher_id.fetch_add(1), persistent, log); + publisher->connect(); + return publisher; +} + +void RabbitMQPublisherPool::release(RabbitMQPublisherPtr publisher) +{ + { + std::lock_guard lock(mutex); + if (!is_shutdown && idle_publishers.size() < max_idle_publishers) + { + idle_publishers.push_back({std::move(publisher), std::chrono::steady_clock::now()}); + return; + } + } + + publisher->closeChannel(); + publisher->disconnect(); +} + +void RabbitMQPublisherPool::shutdown() +{ + std::vector publishers_to_disconnect; + { + std::lock_guard lock(mutex); + is_shutdown = true; + publishers_to_disconnect.swap(idle_publishers); + } + + /// Idle publishers have no pending deliveries, so closing the connection does not lose messages. + for (auto & idle : publishers_to_disconnect) + idle.publisher->disconnect(); +} + +void RabbitMQPublisherPool::cleanupIdlePublishers() +{ + std::vector publishers_to_check; + { + std::lock_guard lock(mutex); + publishers_to_check.swap(idle_publishers); + } + + std::vector usable_publishers; + size_t num_discarded = 0; + for (auto & idle : publishers_to_check) + { + if (isExpired(idle) || !idle.publisher->isReusable()) + { + idle.publisher->disconnect(/* immediately */ true); + ++num_discarded; + } + else + usable_publishers.push_back(std::move(idle)); + } + + if (num_discarded) + LOG_DEBUG(log, "Discarded {} idle producer connections, which are expired or no longer usable", num_discarded); + + std::vector excess_publishers; + { + std::lock_guard lock(mutex); + if (is_shutdown) + { + excess_publishers.swap(usable_publishers); + } + else + { + /// Publishers released in the meantime are more recent, so the checked ones go to the front. + idle_publishers.insert( + idle_publishers.begin(), std::make_move_iterator(usable_publishers.begin()), std::make_move_iterator(usable_publishers.end())); + + /// The released ones may have filled the pool while it was being checked, then the oldest ones are closed. + if (idle_publishers.size() > max_idle_publishers) + { + const auto num_excess = idle_publishers.size() - max_idle_publishers; + std::move(idle_publishers.begin(), idle_publishers.begin() + num_excess, std::back_inserter(excess_publishers)); + idle_publishers.erase(idle_publishers.begin(), idle_publishers.begin() + num_excess); + } + } + } + + for (auto & excess : excess_publishers) + excess.publisher->disconnect(); +} + +std::optional RabbitMQPublisherPool::popIdlePublisher() +{ + std::lock_guard lock(mutex); + if (idle_publishers.empty()) + return {}; + + auto idle = std::move(idle_publishers.back()); + idle_publishers.pop_back(); + return idle; +} + +bool RabbitMQPublisherPool::isExpired(const IdlePublisher & idle) +{ + const auto heartbeat_interval = idle.publisher->getHeartbeatInterval(); + if (heartbeat_interval == 0) + return false; + + /// The server closes the connection after the full interval without receiving anything. Half of it leaves + /// a margin for the insert itself, and server heartbeats are sent about twice per interval, which keeps + /// intermediate network devices from silently dropping the connection. + return 2 * (std::chrono::steady_clock::now() - idle.released_at) >= std::chrono::seconds(heartbeat_interval); +} + +} diff --git a/src/Storages/RabbitMQ/RabbitMQPublisherPool.h b/src/Storages/RabbitMQ/RabbitMQPublisherPool.h new file mode 100644 index 000000000000..c702ee5c6a91 --- /dev/null +++ b/src/Storages/RabbitMQ/RabbitMQPublisherPool.h @@ -0,0 +1,71 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace DB +{ + +/// Keeps idle publishers (a connection with an open channel) of one table, so that `INSERT` queries +/// do not pay for connecting to RabbitMQ every time. +class RabbitMQPublisherPool +{ +public: + RabbitMQPublisherPool( + const RabbitMQConfiguration & configuration_, + const Names & routing_keys_, + const String & exchange_name_, + AMQP::ExchangeType exchange_type_, + bool persistent_, + size_t max_idle_publishers_, + LoggerPtr log_); + + /// Returns the most recently released publisher that is still usable, otherwise a new connected one. + RabbitMQPublisherPtr acquire(); + + /// Takes back a publisher with a usable channel and no pending deliveries. + /// Closes it instead if the pool is full or shut down. + void release(RabbitMQPublisherPtr publisher); + + void cleanupIdlePublishers(); + + void shutdown(); + +private: + struct IdlePublisher + { + RabbitMQPublisherPtr publisher; + std::chrono::steady_clock::time_point released_at; + }; + + /// Pops the most recently released publisher. + std::optional popIdlePublisher(); + + static bool isExpired(const IdlePublisher & idle); + + const RabbitMQConfiguration configuration; + const Names routing_keys; + const String exchange_name; + const AMQP::ExchangeType exchange_type; + const bool persistent; + const size_t max_idle_publishers; + LoggerPtr log; + + /// Needed to generate unique channel ids. + std::atomic publisher_id = 1; + + /// The network is only touched outside of the mutex. Therefore publishers are taken out of `idle_publishers` + /// before they are checked or disconnected, also in `cleanupIdlePublishers`. + std::mutex mutex; + std::vector idle_publishers; + bool is_shutdown = false; +}; + +using RabbitMQPublisherPoolPtr = std::shared_ptr; + +} diff --git a/src/Storages/RabbitMQ/RabbitMQSettings.cpp b/src/Storages/RabbitMQ/RabbitMQSettings.cpp index edbebc4b407d..9a4b349658d6 100644 --- a/src/Storages/RabbitMQ/RabbitMQSettings.cpp +++ b/src/Storages/RabbitMQ/RabbitMQSettings.cpp @@ -43,6 +43,7 @@ namespace ErrorCodes DECLARE(Bool, reject_unhandled_messages, false, "Allow messages to be rejected in case they cannot be processed. This also automatically implies if there is a x-deadletter-exchange queue setting added", 0) \ DECLARE(Bool, rabbitmq_commit_on_select, false, "Commit messages when select query is made", 0) \ DECLARE(UInt64, rabbitmq_max_rows_per_message, 1, "The maximum number of rows produced in one message for row-based formats.", 0) \ + DECLARE(UInt64, rabbitmq_max_idle_producer_connections, 0, "The maximum number of idle connections, each with an open channel, that are kept to be reused by subsequent INSERT queries. 0 disables the reuse: every INSERT query opens and closes its own connection.", 0) \ DECLARE(StreamingHandleErrorMode, rabbitmq_handle_error_mode, StreamingHandleErrorMode::DEFAULT, "How to handle errors for RabbitMQ engine. Possible values: default (throw an exception after rabbitmq_skip_broken_messages broken messages), stream (save broken messages and errors in virtual columns _raw_message, _error), dead_letter_queue (error related data will be saved in system.dead_letter_queue).", 0) \ #define OBSOLETE_RABBITMQ_SETTINGS(M, ALIAS) \ diff --git a/src/Storages/RabbitMQ/StorageRabbitMQ.cpp b/src/Storages/RabbitMQ/StorageRabbitMQ.cpp index 91af7703dfba..dafcb59a0c0d 100644 --- a/src/Storages/RabbitMQ/StorageRabbitMQ.cpp +++ b/src/Storages/RabbitMQ/StorageRabbitMQ.cpp @@ -67,6 +67,7 @@ namespace RabbitMQSetting extern const RabbitMQSettingsStreamingHandleErrorMode rabbitmq_handle_error_mode; extern const RabbitMQSettingsString rabbitmq_host_port; extern const RabbitMQSettingsUInt64 rabbitmq_max_block_size; + extern const RabbitMQSettingsUInt64 rabbitmq_max_idle_producer_connections; extern const RabbitMQSettingsUInt64 rabbitmq_max_rows_per_message; extern const RabbitMQSettingsUInt64 rabbitmq_num_consumers; extern const RabbitMQSettingsUInt64 rabbitmq_num_queues; @@ -88,6 +89,7 @@ static const uint32_t QUEUE_SIZE = 100000; static const auto MAX_FAILED_READ_ATTEMPTS = 10; static const auto RESCHEDULE_MS = 500; static const auto MAX_THREAD_WORK_DURATION_MS = 60000; +static const auto PUBLISHER_CLEANUP_INTERVAL_MS = 5000; namespace ErrorCodes { @@ -241,6 +243,10 @@ StorageRabbitMQ::StorageRabbitMQ( if (secure_connection) SSL_library_init(); + publisher_pool = std::make_shared( + configuration, routing_keys, exchange_name, exchange_type, persistent, + (*rabbitmq_settings)[RabbitMQSetting::rabbitmq_max_idle_producer_connections].value, log); + if (!columns_.getMaterialized().empty() || !columns_.getAliases().empty() || !columns_.getDefaults().empty() || !columns_.getEphemeral().empty()) { context_->addOrUpdateWarningMessage( @@ -308,6 +314,10 @@ StorageRabbitMQ::StorageRabbitMQ( init_task = getContext()->getMessageBrokerSchedulePool()->createTask(getStorageID(), "RabbitMQConnectionTask", [this]{ connectionFunc(); }); init_task->deactivate(); + + publisher_cleanup_task = getContext()->getMessageBrokerSchedulePool()->createTask( + getStorageID(), "RabbitMQPublisherCleanupTask", [this]{ publisherCleanupFunc(); }); + publisher_cleanup_task->deactivate(); } StorageRabbitMQ::~StorageRabbitMQ() = default; @@ -986,8 +996,7 @@ void StorageRabbitMQ::read( SinkToStoragePtr StorageRabbitMQ::write(const ASTPtr &, const StorageMetadataPtr & metadata_snapshot, ContextPtr local_context, bool /*async_insert*/) { - auto producer = std::make_unique( - configuration, routing_keys, exchange_name, exchange_type, producer_id.fetch_add(1), persistent, shutdown_called, log); + auto producer = std::make_unique(publisher_pool, shutdown_called, log); size_t max_rows = max_rows_per_message; /// Need for backward compatibility. if (format_name == "Avro" && local_context->getSettingsRef()[Setting::output_format_avro_rows_in_file].changed) @@ -1004,6 +1013,10 @@ SinkToStoragePtr StorageRabbitMQ::write(const ASTPtr &, const StorageMetadataPtr void StorageRabbitMQ::startup() { + /// Inserts are possible even if streaming to views is disabled. + if ((*rabbitmq_settings)[RabbitMQSetting::rabbitmq_max_idle_producer_connections] > 0) + publisher_cleanup_task->activateAndSchedule(); + if (getContext()->getMessageQueueDisableInsertion()) { StreamingStorageRegistry::instance().registerTable(getStorageID()); @@ -1023,6 +1036,20 @@ void StorageRabbitMQ::startup() StreamingStorageRegistry::instance().registerTable(getStorageID()); } +void StorageRabbitMQ::publisherCleanupFunc() +{ + try + { + publisher_pool->cleanupIdlePublishers(); + } + catch (...) + { + tryLogCurrentException(log); + } + + publisher_cleanup_task->scheduleAfter(PUBLISHER_CLEANUP_INTERVAL_MS); +} + void StorageRabbitMQ::scheduleStreamingTasksImpl() { streaming_task->schedule(); @@ -1059,6 +1086,10 @@ void StorageRabbitMQ::shutdown(bool) LOG_TRACE(log, "Deactivating looping task"); deactivateTask(looping_task, true, true); + /// Inserts are possible even if streaming to views is disabled, so close their idle connections in any case. + publisher_cleanup_task->deactivate(); + publisher_pool->shutdown(); + if (getContext()->getMessageQueueDisableInsertion()) { StreamingStorageRegistry::instance().unregisterTable(getStorageID(), /* if_exists */ true); @@ -1618,6 +1649,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster] [rabbitmq_password = '',] [rabbitmq_commit_on_select = false,] [rabbitmq_max_rows_per_message = 1,] + [rabbitmq_max_idle_producer_connections = 0,] [rabbitmq_handle_error_mode = 'default'] ``` @@ -1648,6 +1680,7 @@ Optional parameters: - `reject_unhandled_messages` - Reject messages (send RabbitMQ negative acknowledgement) in case of errors. This setting is automatically enabled if there is a `x-dead-letter-exchange` defined in `rabbitmq_queue_settings_list`. - `rabbitmq_commit_on_select` - Commit messages when select query is made. Default: `false`. - `rabbitmq_max_rows_per_message` — The maximum number of rows written in one RabbitMQ message for row-based formats. Default : `1`. +- `rabbitmq_max_idle_producer_connections` - The maximum number of idle connections, each with an open channel, that the table keeps for subsequent `INSERT` queries. Reusing them avoids the cost of connecting to RabbitMQ (and of the TLS handshake) for every `INSERT`, for example when a materialized view writes to the table on each insert into its source. Idle connections are checked every few seconds: a connection that stayed idle for half of the heartbeat timeout negotiated with the server is closed, because the server closes it once the timeout passes, and so is a connection that was lost. `0` disables the reuse: every `INSERT` opens and closes its own connection. Default: `0`. - `rabbitmq_empty_queue_backoff_start_ms` — A start backoff point to reschedule read if the rabbitmq queue is empty. - `rabbitmq_empty_queue_backoff_end_ms` — An end backoff point to reschedule read if the rabbitmq queue is empty. - `rabbitmq_empty_queue_backoff_step_ms` — A backoff step to reschedule read if the rabbitmq queue is empty. diff --git a/src/Storages/RabbitMQ/StorageRabbitMQ.h b/src/Storages/RabbitMQ/StorageRabbitMQ.h index 0fc1d18a399c..12a8dc1d9f77 100644 --- a/src/Storages/RabbitMQ/StorageRabbitMQ.h +++ b/src/Storages/RabbitMQ/StorageRabbitMQ.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -122,6 +123,9 @@ class StorageRabbitMQ final: public IStreamingStorage, WithContext RabbitMQConnectionPtr connection; /// Connection for all consumers RabbitMQConfiguration configuration; + /// Connections with an open channel for insert queries, reused across them. + RabbitMQPublisherPoolPtr publisher_pool; + size_t num_created_consumers = 0; Poco::Semaphore semaphore; std::mutex consumers_mutex; @@ -144,15 +148,14 @@ class StorageRabbitMQ final: public IStreamingStorage, WithContext BackgroundSchedulePoolTaskHolder streaming_task; BackgroundSchedulePoolTaskHolder looping_task; BackgroundSchedulePoolTaskHolder init_task; + /// Closes idle producer connections of `publisher_pool`, which are expired or lost. + BackgroundSchedulePoolTaskHolder publisher_cleanup_task; uint64_t milliseconds_to_wait; /** * ╰( ͡° ͜ʖ ͡° )つ──☆* Evil atomics: */ - /// Counter for producers, needed for channel id. - /// Needed to generate unique producer identifiers. - std::atomic producer_id = 1; /// Allow to remove exchange only once. std::atomic exchange_removed = false; /// For select query we must be aware of the end of streaming @@ -181,6 +184,7 @@ class StorageRabbitMQ final: public IStreamingStorage, WithContext void threadFunc(); void loopingFunc(); void connectionFunc(); + void publisherCleanupFunc(); void startLoop(); void stopLoop(); diff --git a/src/Storages/StorageDictionary.cpp b/src/Storages/StorageDictionary.cpp index 81c711b6f649..2420d9332c49 100644 --- a/src/Storages/StorageDictionary.cpp +++ b/src/Storages/StorageDictionary.cpp @@ -209,27 +209,33 @@ Pipe StorageDictionary::read( const size_t max_block_size, const size_t threads) { - auto registered_dictionary_name = location == Location::SameDatabaseAndNameAsDictionary ? getStorageID().getInternalDictionaryName() : dictionary_name; - auto dictionary = getContext()->getExternalDictionariesLoader().getDictionary(registered_dictionary_name, local_context); + auto dictionary = getDictionary(local_context); + return dictionary->read(column_names, max_block_size, threads); +} +void StorageDictionary::checkDictionaryAccess(const StorageID & dictionary_id, const ContextPtr & local_context) +{ /** * For backward compatibility reasons we require either SELECT or dictGet permission to read directly from the dictionary. * If none of these conditions are met - we ask to grant a dictGet. */ - bool has_dict_get = local_context->getAccess()->isGranted( - AccessType::dictGet, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - bool has_select = local_context->getAccess()->isGranted( - AccessType::SELECT, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - if (!has_dict_get && !has_select) - local_context->checkAccess(AccessType::dictGet, dictionary->getDatabaseOrNoDatabaseTag(), dictionary->getDictionaryID().getTableName()); - - return dictionary->read(column_names, max_block_size, threads); + auto dictionary_database = IDictionary::getDatabaseOrNoDatabaseTag(dictionary_id); + const auto & access = local_context->getAccess(); + if (!access->isGranted(AccessType::dictGet, dictionary_database, dictionary_id.getTableName()) + && !access->isGranted(AccessType::SELECT, dictionary_database, dictionary_id.getTableName())) + local_context->checkAccess(AccessType::dictGet, dictionary_database, dictionary_id.getTableName()); } -std::shared_ptr StorageDictionary::getDictionary() const +std::shared_ptr StorageDictionary::getDictionary(const ContextPtr & query_context) const { auto registered_dictionary_name = location == Location::SameDatabaseAndNameAsDictionary ? getStorageID().getInternalDictionaryName() : dictionary_name; - return getContext()->getExternalDictionariesLoader().getDictionary(registered_dictionary_name, getContext()); + const auto & external_loader = getContext()->getExternalDictionariesLoader(); + + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and load the dictionary that passed the check. + auto dictionary = external_loader.resolveDictionary(registered_dictionary_name, query_context); + checkDictionaryAccess(dictionary.id, query_context); + return external_loader.getDictionary(dictionary, query_context); } void StorageDictionary::shutdown(bool) @@ -415,7 +421,13 @@ void registerStorageDictionary(StorageFactory & factory) if (args.mode <= LoadingStrictnessLevel::CREATE) { - const auto & dictionary = args.getContext()->getExternalDictionariesLoader().getDictionary(dictionary_name, args.getContext()); + /// The user creating the table must be allowed to read the dictionary. Check it before loading the dictionary, + /// because loading contacts the dictionary source. The name is resolved with the query context, + /// like when the table is read. + const auto & external_loader = local_context->getExternalDictionariesLoader(); + auto resolved_dictionary = external_loader.resolveDictionary(dictionary_name, local_context); + StorageDictionary::checkDictionaryAccess(resolved_dictionary.id, local_context); + const auto & dictionary = external_loader.getDictionary(resolved_dictionary, local_context); const DictionaryStructure & dictionary_structure = dictionary->getStructure(); checkNamesAndTypesCompatibleWithDictionary(dictionary_name, args.columns, dictionary_structure); } diff --git a/src/Storages/StorageDictionary.h b/src/Storages/StorageDictionary.h index 2949398d0e0e..597851b95f1d 100644 --- a/src/Storages/StorageDictionary.h +++ b/src/Storages/StorageDictionary.h @@ -82,10 +82,15 @@ friend class TableFunctionDictionary; /// count() can return wrong result, see test_dictionaries_redis/test_long.py::test_redis_dict_long bool parallelizeOutputAfterReading(ContextPtr) const override { return false; } - std::shared_ptr getDictionary() const; + /// Loads the dictionary after checking that the user of `query_context` may read it, see `checkDictionaryAccess`. + [[nodiscard]] std::shared_ptr getDictionary(const ContextPtr & query_context) const; static NamesAndTypesList getNamesAndTypes(const DictionaryStructure & dictionary_structure, bool validate_id_type); + /// Checks the access needed to read the dictionary with the given ID as a table. + /// Must be called before the dictionary is loaded or its definition is read. + static void checkDictionaryAccess(const StorageID & dictionary_id, const ContextPtr & local_context); + bool isDictionary() const override { return true; } bool supportsTruncate() const override { return false; } bool supportsColumnsWithDynamicStructure() const override { return true; } diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index 921a6495154b..8649f24746cf 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -306,7 +306,7 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return; auto it = storages.find(storage.engine->name); if (it != storages.end() && it->second.features.get_export_access_fn) - res.append_range(it->second.features.get_export_access_fn(storage.settings->changes)); + res.append_range(it->second.features.get_export_access_fn(storage.settings->changes, /* own_engine */ true)); }; if (create.storage) @@ -319,13 +319,24 @@ AccessRightsElements StorageFactory::getExportAccess(const ASTCreateQuery & crea return res; } +AccessRightsElements StorageFactory::getExportAccess(const SettingsChanges & changes, const String & engine) const +{ + AccessRightsElements res; + for (const auto & [name, creator] : storages) + { + if (creator.features.get_export_access_fn) + res.append_range(creator.features.get_export_access_fn(changes, name == engine)); + } + return res; +} + AccessRightsElements StorageFactory::getExportAccessOfAnyEngine(const SettingsChanges & changes) const { AccessRightsElements res; for (const auto & [_, creator] : storages) { if (creator.features.get_export_access_fn) - res.append_range(creator.features.get_export_access_fn(changes)); + res.append_range(creator.features.get_export_access_fn(changes, /* own_engine */ true)); } return res; } diff --git a/src/Storages/StorageFactory.h b/src/Storages/StorageFactory.h index bf1784b0a698..6db00cf3c946 100644 --- a/src/Storages/StorageFactory.h +++ b/src/Storages/StorageFactory.h @@ -42,7 +42,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// The grants needed by settings that make a table send its data to another place, e.g. the move destination of a queue. /// Returns nothing if `changes` set no such place. It reads only the changes, so the table need not exist on this host. - using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes); + /// If `own_engine`, also the grants for settings that modify the source files, e.g. `after_processing` of a queue. + using GetExportAccessFn = AccessRightsElements(const SettingsChanges & changes, bool own_engine); struct Arguments { @@ -169,6 +170,8 @@ class StorageFactory : private boost::noncopyable, public IHints<> /// See `GetExportAccessFn`. For the engine of the table and the inner engines of a materialized view or a `TimeSeries` /// table. An unknown engine needs nothing here: creating it fails later. AccessRightsElements getExportAccess(const ASTCreateQuery & create) const; + /// For `changes` of a table with `engine`: the destinations of every engine, as below, and the source files of `engine` only. + AccessRightsElements getExportAccess(const SettingsChanges & changes, const String & engine) const; /// The grants of every engine for which `changes` send the data elsewhere. It does not depend on the engine of the table, /// so `ALTER ... ON CLUSTER` can be authorized on an initiator that does not have the table or has another engine. AccessRightsElements getExportAccessOfAnyEngine(const SettingsChanges & changes) const; diff --git a/src/Storages/StorageInMemoryMetadata.cpp b/src/Storages/StorageInMemoryMetadata.cpp index 3f52ddca92d9..9dcd0338c628 100644 --- a/src/Storages/StorageInMemoryMetadata.cpp +++ b/src/Storages/StorageInMemoryMetadata.cpp @@ -1062,7 +1062,12 @@ void StorageInMemoryMetadata::addImplicitIndicesForVirtualColumns(ContextPtr con if (!index.column_names.empty() && index.column_names.front() == column_name && index.type == "minmax") return; - const auto columns_to_analyze = virtuals.toColumnsDescription(VirtualsKind::All, VirtualsMaterializationPlace::All); + /// A projection has these only when its query selects them. + if (!columns.has(column_name) && !virtuals.has(column_name)) + return; + + const auto columns_to_analyze = columns.has(column_name) ? columns : virtuals.toColumnsDescription(VirtualsKind::All, VirtualsMaterializationPlace::All); + auto index = createImplicitMinMaxIndexDescription(column_name, columns_to_analyze, escape_index_filenames, context); static const MergeTreeSettings default_settings; MergeTreeIndexFactory::instance().validate(index, false, default_settings); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index 5f4a0b9ffb35..7a8a0d84b540 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -150,7 +150,14 @@ StorageMaterializedView::StorageMaterializedView( throw Exception(ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW, "SQL SECURITY INVOKER can't be specified for MATERIALIZED VIEW"); if (storage_metadata.sql_security_type == SQLSecurityType::DEFINER) + { + if (!storage_metadata.definer) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "Cannot resolve DEFINER = CURRENT_USER of {} {} without a current user. " + "If the definer is a user named `CURRENT_USER`, quote it in the stored definition", + getName(), table_id_.getNameForLogs()); DefinerDependencies::instance().addDependency(*storage_metadata.definer, table_id_); + } if (!query.select) throw Exception(ErrorCodes::INCORRECT_QUERY, "SELECT query is not specified for {}", getName()); diff --git a/src/Storages/StorageMergeTreeIndex.cpp b/src/Storages/StorageMergeTreeIndex.cpp index 3c463efbe935..d11288f495a4 100644 --- a/src/Storages/StorageMergeTreeIndex.cpp +++ b/src/Storages/StorageMergeTreeIndex.cpp @@ -309,8 +309,7 @@ StorageMergeTreeIndex::StorageMergeTreeIndex( { Block minmax_block; const auto metadata_snapshot = merge_tree->getInMemoryMetadataPtr(CurrentThread::tryGetQueryContext(), false); - const auto & partition_key = metadata_snapshot->getPartitionKey(); - for (const auto & column : MergeTreeData::getMinMaxColumns(partition_key, merge_tree->getSettings())) + for (const auto & column : MergeTreeData::getMinMaxColumns(*metadata_snapshot, merge_tree->getSettings())) minmax_block.insert({nullptr, std::make_shared(DataTypes{makeNullableSafe(column.type), makeNullableSafe(column.type)}), fmt::format("minmax_{}", column.name)}); minmax_sample_block = std::make_shared(std::move(minmax_block)); } diff --git a/src/Storages/StorageMongoDB.cpp b/src/Storages/StorageMongoDB.cpp index e902d3ca65d6..3662f946d616 100644 --- a/src/Storages/StorageMongoDB.cpp +++ b/src/Storages/StorageMongoDB.cpp @@ -566,7 +566,14 @@ bsoncxx::document::value StorageMongoDB::buildMongoDBQuery(const ContextPtr & co if (!context->getSettingsRef()[Setting::allow_experimental_analyzer]) { if (throw_on_error) - throw Exception(ErrorCodes::NOT_IMPLEMENTED, "MongoDB storage does not support 'enable_analyzer = 0' setting"); + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "MongoDB storage does not support 'enable_analyzer = 0' setting. You can disable this error with 'SET mongodb_throw_on_unsupported_query=0', but this may cause poor performance, and is highly not recommended"); + return make_document(); + } + + if (!query.query_tree) + { + if (throw_on_error) + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "MongoDB storage requires the query tree, which is not available for this query. You can disable this error with 'SET mongodb_throw_on_unsupported_query=0', but this may cause poor performance, and is highly not recommended"); return make_document(); } diff --git a/src/Storages/StorageMySQL.cpp b/src/Storages/StorageMySQL.cpp index 46f9e5c462d1..02c5947cf65d 100644 --- a/src/Storages/StorageMySQL.cpp +++ b/src/Storages/StorageMySQL.cpp @@ -250,7 +250,11 @@ class StorageMySQLSink final : public SinkToStorage sqlbuf << backQuoteMySQL(remote_table_name); sqlbuf << " (" << dumpNamesWithBackQuote(block) << ") VALUES "; - auto writer = FormatFactory::instance().getOutputFormat("Values", sqlbuf, metadata_snapshot->getSampleBlock(), storage.getContext()); + /// Quotes escaped with quotes leave backslashes as is, and MySQL would read `\'` as an escaped quote. + auto format_settings = getFormatSettings(storage.getContext()); + format_settings.values.escape_quote_with_quote = false; + auto writer = FormatFactory::instance().getOutputFormat( + "Values", sqlbuf, metadata_snapshot->getSampleBlock(), storage.getContext(), format_settings); writer->write(block); if (!storage.on_duplicate_clause.empty()) diff --git a/src/Storages/StorageQueryRunner.cpp b/src/Storages/StorageQueryRunner.cpp index a6c2191919f5..474d84c94892 100644 --- a/src/Storages/StorageQueryRunner.cpp +++ b/src/Storages/StorageQueryRunner.cpp @@ -80,6 +80,7 @@ namespace QueryRunnerSetting namespace ErrorCodes { extern const int BAD_ARGUMENTS; + extern const int INCORRECT_QUERY; extern const int NOT_IMPLEMENTED; } @@ -749,7 +750,14 @@ StorageQueryRunner::StorageQueryRunner( storage_metadata.setSQLSecurity(sql_security_->as()); if (storage_metadata.sql_security_type == SQLSecurityType::DEFINER) + { + if (!storage_metadata.definer) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "Cannot resolve DEFINER = CURRENT_USER of {} {} without a current user. " + "If the definer is a user named `CURRENT_USER`, quote it in the stored definition", + getName(), table_id_.getNameForLogs()); DefinerDependencies::instance().addDependency(*storage_metadata.definer, table_id_); + } } else if (cluster_name.empty()) storage_metadata.sql_security_type = SQLSecurityType::INVOKER; diff --git a/src/Storages/StorageURL.cpp b/src/Storages/StorageURL.cpp index b95258dee761..33d25ab2d3d4 100644 --- a/src/Storages/StorageURL.cpp +++ b/src/Storages/StorageURL.cpp @@ -351,11 +351,6 @@ size_t StorageURLSource::DisclosedGlobIterator::size() return pimpl->size(); } -void StorageURLSource::setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri) -{ - setCredentialsFromURL(credentials, request_uri); -} - StorageURLSource::StorageURLSource( const ReadFromFormatInfo & info, std::shared_ptr uri_iterator_, @@ -381,7 +376,7 @@ StorageURLSource::StorageURLSource( , columns_description(info.columns_description) , requested_columns(info.requested_columns) , need_headers_virtual_column(info.requested_virtual_columns.contains("_headers")) - , requested_virtual_columns(info.requested_virtual_columns.eraseNames({"_headers"})) + , requested_virtual_columns(info.requested_virtual_columns) , block_for_format(info.format_header) , uri_iterator(uri_iterator_) , format(format_) @@ -432,7 +427,9 @@ StorageURLSource::StorageURLSource( QueryPipelineBuilder builder; std::optional num_rows_from_cache = std::nullopt; - if (need_only_count && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) + /// The number of rows from the cache is returned without a request for the data, while the `_headers` + /// virtual column is the headers of the response to that request. Do the request when `_headers` is requested. + if (need_only_count && !need_headers_virtual_column && getContext()->getSettingsRef()[Setting::use_cache_for_count_from_files]) num_rows_from_cache = tryGetNumRowsFromCache(curr_uri.toString(), current_file_last_modified); if (num_rows_from_cache) @@ -532,6 +529,15 @@ Chunk StorageURLSource::generate() getContext()); } + chassert(dynamic_cast(read_buf.get())); + if (need_headers_virtual_column && !http_response_headers_initialized) + { + http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); + http_response_headers_initialized = true; + } + + /// `_headers` is added along with the other virtual columns, in the order they are requested in, + /// which is the order of the columns in the header of the source. VirtualColumnUtils::addRequestedFileLikeStorageVirtualsToChunk( chunk, requested_virtual_columns, @@ -542,25 +548,11 @@ Chunk StorageURLSource::generate() .last_modified = current_file_last_modified ? std::optional(Poco::Timestamp::fromEpochTime(*current_file_last_modified)) : std::nullopt, + .http_response_headers = need_headers_virtual_column ? &http_response_headers : nullptr, }, getContext(), format_settings); - chassert(dynamic_cast(read_buf.get())); - if (need_headers_virtual_column) - { - if (!http_response_headers_initialized) - { - http_response_headers = dynamic_cast(read_buf.get())->getResponseHeaders(); - http_response_headers_initialized = true; - } - - auto type = std::make_shared( - std::make_shared(std::make_shared()), - std::make_shared(std::make_shared())); - - chunk.addColumn(type->createColumnConst(chunk.getNumRows(), http_response_headers)->convertToFullColumnIfConst()); - } return chunk; } @@ -606,7 +598,8 @@ std::pair> StorageURLSource: for (const auto & [param, value] : params) request_uri.addQueryParameter(param, value); - setCredentials(credentials, request_uri); + /// Not inside the `try` below: a forbidden option must fail the read, not fall through to the next one. + setCredentialsFromURL(credentials, request_uri, context_->getHTTPHeaderFilter()); const auto & settings = context_->getSettingsRef(); diff --git a/src/Storages/StorageURL.h b/src/Storages/StorageURL.h index b6c5cdd25b7d..8a5cf984bfdd 100644 --- a/src/Storages/StorageURL.h +++ b/src/Storages/StorageURL.h @@ -247,8 +247,6 @@ class StorageURLSource final : public ISource, WithContext void onFinish() override; - static void setCredentials(Poco::Net::HTTPBasicCredentials & credentials, const Poco::URI & request_uri); - static std::pair> getFirstAvailableURIAndReadBuffer( std::vector::const_iterator & option, const std::vector::const_iterator & end, diff --git a/src/Storages/StorageURLCluster.cpp b/src/Storages/StorageURLCluster.cpp index 3d89d3d8f7cf..c6bfd8a2792e 100644 --- a/src/Storages/StorageURLCluster.cpp +++ b/src/Storages/StorageURLCluster.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -36,6 +37,7 @@ namespace ErrorCodes namespace Setting { + extern const SettingsBool enable_url_encoding; extern const SettingsUInt64 glob_expansion_max_elements; extern const SettingsBool use_hive_partitioning; } @@ -146,11 +148,20 @@ RemoteQueryExecutor::Extension StorageURLCluster::getTaskIteratorExtension( auto iterator = std::make_shared( uri, context->getSettingsRef()[Setting::glob_expansion_max_elements], predicate, metadata->virtuals.getSampleBlock(VirtualsKind::All, VirtualsMaterializationPlace::Reader).getNamesAndTypesList(), hive_partition_columns_to_read_from_file_path, context); - auto next_callback = [iter = std::move(iterator)](size_t) mutable -> ClusterFunctionReadTaskResponsePtr + auto next_callback = [iter = std::move(iterator), context](size_t) mutable -> ClusterFunctionReadTaskResponsePtr { auto url = iter->next(); if (url.empty()) return std::make_shared(); + + /// The workers check the credentials under their own configuration, which can differ from this one. + const auto & settings = context->getSettingsRef(); + for (const auto & option : parseRemoteDescription(url, 0, url.size(), '|', settings[Setting::glob_expansion_max_elements])) + { + Poco::Net::HTTPBasicCredentials credentials; + setCredentialsFromURL(credentials, Poco::URI(option, settings[Setting::enable_url_encoding]), context->getHTTPHeaderFilter()); + } + return std::make_shared(std::move(url)); }; auto callback = std::make_shared(std::move(next_callback)); diff --git a/src/Storages/StorageView.cpp b/src/Storages/StorageView.cpp index 1f0fb18f96c1..e00e284cf2b5 100644 --- a/src/Storages/StorageView.cpp +++ b/src/Storages/StorageView.cpp @@ -382,7 +382,14 @@ StorageView::StorageView( storage_metadata.setSQLSecurity(query.sql_security->as()); if (storage_metadata.sql_security_type == SQLSecurityType::DEFINER) + { + if (!storage_metadata.definer) + throw Exception(ErrorCodes::INCORRECT_QUERY, + "Cannot resolve DEFINER = CURRENT_USER of {} {} without a current user. " + "If the definer is a user named `CURRENT_USER`, quote it in the stored definition", + getName(), table_id_.getNameForLogs()); DefinerDependencies::instance().addDependency(*storage_metadata.definer, table_id_); + } if (!query.select) throw Exception(ErrorCodes::INCORRECT_QUERY, "SELECT query is not specified for {}", getName()); diff --git a/src/Storages/System/StorageSystemRemoteDataPaths.cpp b/src/Storages/System/StorageSystemRemoteDataPaths.cpp index 93d79de91559..d2784c94cd09 100644 --- a/src/Storages/System/StorageSystemRemoteDataPaths.cpp +++ b/src/Storages/System/StorageSystemRemoteDataPaths.cpp @@ -36,7 +36,6 @@ namespace ErrorCodes extern const int DIRECTORY_DOESNT_EXIST; } - class SystemRemoteDataPathsSource final : public ISource { public: @@ -50,10 +49,8 @@ class SystemRemoteDataPathsSource final : public ISource , context(std::move(context_)) { for (const auto & disk : disks_) - { - if (disk.second->isRemote()) + if (isDiskObjectStorage(disk.second)) disks.push_back(disk); - } auto component_guard = Coordination::setCurrentComponent("SystemRemoteDataPathsSource::SystemRemoteDataPathsSource"); /// Position at the first disk diff --git a/src/Storages/VirtualColumnUtils.cpp b/src/Storages/VirtualColumnUtils.cpp index 2eca18976ef2..76191007073d 100644 --- a/src/Storages/VirtualColumnUtils.cpp +++ b/src/Storages/VirtualColumnUtils.cpp @@ -539,6 +539,12 @@ void addRequestedFileLikeStorageVirtualsToChunk( else chunk.addColumn(virtual_column.type->createColumnConstWithDefaultValue(chunk.getNumRows())->convertToFullColumnIfConst()); } + else if (virtual_column.name == "_headers" && virtual_values.http_response_headers) + { + /// Added here, in its place among the requested virtual columns, and not by the caller after the other ones: + /// the columns of the chunk must go in the order of the header of the source, which is the requested order. + chunk.addColumn(virtual_column.type->createColumnConst(chunk.getNumRows(), *virtual_values.http_response_headers)->convertToFullColumnIfConst()); + } else if (auto it = hive_map.find(virtual_column.getNameInStorage()); it != hive_map.end()) { chunk.addColumn( diff --git a/src/Storages/VirtualColumnUtils.h b/src/Storages/VirtualColumnUtils.h index 8e986a162878..fc2f38bc95c1 100644 --- a/src/Storages/VirtualColumnUtils.h +++ b/src/Storages/VirtualColumnUtils.h @@ -13,6 +13,7 @@ namespace DB { +struct Map; class Block; class Chunk; class NamesAndTypesList; @@ -157,6 +158,8 @@ struct VirtualsForFileLikeStorage /// Original file path as stored in Iceberg metadata (before resolution to storage path). /// Used by Iceberg position deletes to reference data files in the metadata path format. const String * iceberg_metadata_file_path { nullptr }; + /// The HTTP response headers of the read: the value of the `_headers` virtual column of the storages which read over HTTP. + const Map * http_response_headers { nullptr }; }; void addRequestedFileLikeStorageVirtualsToChunk( diff --git a/src/Storages/tests/gtest_rabbitmq_publisher.cpp b/src/Storages/tests/gtest_rabbitmq_publisher.cpp new file mode 100644 index 000000000000..b52c0d2e32c9 --- /dev/null +++ b/src/Storages/tests/gtest_rabbitmq_publisher.cpp @@ -0,0 +1,117 @@ +#include +#include + +#if USE_AMQPCPP + +#include +#include + +#include + +namespace DB +{ + +/// Drives the publisher confirms handler `RabbitMQPublisher::removeRecord` directly. The delivery tag +/// of an ack or nack comes from the broker, so it is not guaranteed to be in `delivery_record`. +/// The publisher is never connected, so no connection to a broker is made. +class RabbitMQPublisherTest : public ::testing::Test +{ +protected: + RabbitMQPublisherTest() + : publisher(RabbitMQConfiguration{}, Names{"key"}, "exchange", AMQP::ExchangeType::direct, 0, false, getLogger("RabbitMQPublisherTest")) + { + } + + void addRecords(std::initializer_list tags) + { + for (UInt64 tag : tags) + publisher.delivery_record.emplace(tag, RabbitMQPublisher::Payload{"message_" + std::to_string(tag), tag}); + } + + void removeRecord(UInt64 tag, bool multiple, bool republish) { publisher.removeRecord(tag, multiple, republish); } + + std::vector pendingTags() const + { + std::vector result; + for (const auto & [tag, _] : publisher.delivery_record) + result.push_back(tag); + return result; + } + + std::vector returnedIds() + { + std::vector result; + RabbitMQPublisher::Payload payload; + while (publisher.returned.tryPop(payload)) + result.push_back(payload.id); + return result; + } + + RabbitMQPublisher publisher; +}; + +TEST_F(RabbitMQPublisherTest, SingleAckRemovesOnlyItsRecord) +{ + addRecords({1, 2, 3}); + removeRecord(2, /* multiple = */ false, /* republish = */ false); + EXPECT_EQ(pendingTags(), (std::vector{1, 3})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQPublisherTest, UnknownSingleAckOrNackIsIgnored) +{ + addRecords({1, 3}); + removeRecord(2, /* multiple = */ false, /* republish = */ false); + removeRecord(2, /* multiple = */ false, /* republish = */ true); + removeRecord(10, /* multiple = */ false, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{1, 3})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQPublisherTest, RepeatedSingleNackRequeuesOnce) +{ + addRecords({1, 2}); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{2})); + EXPECT_EQ(returnedIds(), (std::vector{1})); +} + +TEST_F(RabbitMQPublisherTest, MultipleAckWithMissingBoundaryTag) +{ + addRecords({1, 2, 4, 5}); + removeRecord(3, /* multiple = */ true, /* republish = */ false); + EXPECT_EQ(pendingTags(), (std::vector{4, 5})); + EXPECT_TRUE(returnedIds().empty()); +} + +TEST_F(RabbitMQPublisherTest, MultipleNackWithMissingBoundaryTagRequeuesOnce) +{ + addRecords({1, 2, 4, 5}); + removeRecord(3, /* multiple = */ true, /* republish = */ true); + removeRecord(3, /* multiple = */ true, /* republish = */ true); + EXPECT_EQ(pendingTags(), (std::vector{4, 5})); + EXPECT_EQ(returnedIds(), (std::vector{1, 2})); +} + +TEST_F(RabbitMQPublisherTest, MultipleNackBeyondAllRecords) +{ + addRecords({1, 2}); + removeRecord(100, /* multiple = */ true, /* republish = */ true); + EXPECT_TRUE(pendingTags().empty()); + EXPECT_EQ(returnedIds(), (std::vector{1, 2})); +} + +TEST_F(RabbitMQPublisherTest, ConfirmsOnEmptyRecord) +{ + removeRecord(1, /* multiple = */ true, /* republish = */ false); + removeRecord(1, /* multiple = */ true, /* republish = */ true); + removeRecord(1, /* multiple = */ false, /* republish = */ false); + removeRecord(1, /* multiple = */ false, /* republish = */ true); + EXPECT_TRUE(pendingTags().empty()); + EXPECT_TRUE(returnedIds().empty()); +} + +} + +#endif diff --git a/src/TableFunctions/ITableFunction.cpp b/src/TableFunctions/ITableFunction.cpp index a1009901d26a..8af708e336aa 100644 --- a/src/TableFunctions/ITableFunction.cpp +++ b/src/TableFunctions/ITableFunction.cpp @@ -4,9 +4,12 @@ #include #include #include +#include #include #include +#include + namespace ProfileEvents { @@ -41,7 +44,7 @@ void ITableFunction::checkSourceAccess(ContextPtr context, bool is_insert_query) if (is_insert_query) type_to_check = AccessType::WRITE; - context->getAccess()->checkAccessWithFilter(type_to_check, toStringSource(*access_object), getFunctionURINormalized()); + checkSourceAccessForURI(context, type_to_check, *access_object, getFunctionURI()); } } @@ -107,13 +110,13 @@ StoragePtr ITableFunction::execute(const ASTPtr & ast_function, ContextPtr conte std::move(cached_columns), needStructureConversion()); } -String ITableFunction::getFunctionURINormalized() const +String ITableFunction::normalizeURIForAccessCheck(const String & uri) { try { - Poco::URI uri(getFunctionURI()); - uri.normalize(); - return uri.toString(); + Poco::URI parsed(uri); + parsed.normalize(); + return parsed.toString(); } catch (const Poco::Exception &) { @@ -121,4 +124,148 @@ String ITableFunction::getFunctionURINormalized() const } } +namespace +{ + +/// Glob alternatives (`{a,..}`, `a|..`) are expanded into separate locations after the check, so they count as segments. +bool hasDotSegment(std::string_view path) +{ + size_t begin = 0; + for (size_t i = 0; i <= path.size(); ++i) + { + if (i == path.size() || std::string_view("/{},|").contains(path[i])) + { + const std::string_view segment = path.substr(begin, i - begin); + if (segment == "." || segment == "..") + return true; + begin = i + 1; + } + } + return false; +} + +/// Glob characters are expanded after the check, so the filter sees them as written. `toString` encodes a `%` of the +/// path as `%25`, so before the query these escapes can only come from a glob character. `url` also sends `,` as written. +String unescapeGlobCharacters(const String & subject, bool unescape_comma) +{ + const size_t query = std::min(subject.find('?'), subject.size()); + String result; + result.reserve(subject.size()); + for (size_t i = 0; i < subject.size(); ++i) + { + if (subject[i] == '%' && i + 2 < query) + { + const std::string_view escape(subject.data() + i + 1, 2); + char c = 0; + if (escape == "2A") + c = '*'; + else if (escape == "3F") + c = '?'; + else if (escape == "7B") + c = '{'; + else if (escape == "7D") + c = '}'; + else if (escape == "7C") + c = '|'; + else if (unescape_comma && escape == "2C") + c = ','; + if (c) + { + result += c; + i += 2; + continue; + } + } + result += subject[i]; + } + return result; +} + +String escapeGlobCharacters(const String & name) +{ + String result; + result.reserve(name.size()); + for (const char c : name) + { + if (c == '*') + result += "%2A"; + else if (c == '?') + result += "%3F"; + else if (c == '{') + result += "%7B"; + else if (c == '}') + result += "%7D"; + else if (c == '|') + result += "%7C"; + else + result += c; + } + return result; +} + +/// Filter subjects for `uri`: glob characters as written and escaped. Both empty: only the whole-source grant passes. +std::pair getSourceAccessSubjects(AccessTypeObjects::Source source, const String & uri) +{ + /// A blob path and a local path are names, used as written, but their dot and empty segments may be resolved on access. + if (source == AccessTypeObjects::Source::AZURE || source == AccessTypeObjects::Source::FILE) + { + if (hasDotSegment(uri) || uri.contains("//")) + return {}; + return {uri, escapeGlobCharacters(uri)}; + } + + /// A fragment is never part of the accessed location. + if (uri.contains('#')) + return {}; + + try + { + const Poco::URI decoded(uri); + const String & path = decoded.getPath(); + if (hasDotSegment(path) || path.contains("//")) + return {}; + /// `url` expands `{}` and splits `|` failover across the whole URI, but the subject escapes them only in the path. + if ((decoded.getScheme() + decoded.getAuthority() + decoded.getRawQuery()).find_first_of("{}|") != String::npos) + return {}; + if (source == AccessTypeObjects::Source::S3) + { + /// `S3::URI` decodes the path once, as the subject does, but folds a query into the key, where `?` is a wildcard. + if (uri.contains('?')) + return {}; + } + else if (source == AccessTypeObjects::Source::URL) + { + /// `url` sends the path as written, so a character the subject escapes, other than glob syntax, is refused. + const String raw_path = Poco::URI(uri, /* enable_url_encoding */ false).getPath(); + if (!std::ranges::all_of( + raw_path, [](char c) { return isAlphaNumericASCII(c) || std::string_view("-._~/&+;=:@*{}|,").contains(c); })) + return {}; + } + else if (Poco::URI(uri, /* enable_url_encoding */ false).getPath().contains('%')) + return {}; + } + catch (const Poco::Exception &) + { + return {}; + } + + String escaped = ITableFunction::normalizeURIForAccessCheck(uri); + String as_written = unescapeGlobCharacters(escaped, /* unescape_comma */ source == AccessTypeObjects::Source::URL); + return {std::move(as_written), std::move(escaped)}; +} + +} + +void ITableFunction::checkSourceAccessForURI( + const ContextPtr & context, const AccessFlags & flags, AccessTypeObjects::Source source, const String & uri) +{ + const auto access = context->getAccess(); + const auto source_name = toStringSource(source); + auto [subject, escaped_subject] = getSourceAccessSubjects(source, uri); + /// Globs expand after the check, so they must match as written and escaped: `.` in `report.csv` matches `*`, not its expansion. + if (subject != escaped_subject && !access->isGrantedWithFilter(flags, source_name, escaped_subject)) + subject.clear(); + access->checkAccessWithFilter(flags, source_name, subject); +} + } diff --git a/src/TableFunctions/ITableFunction.h b/src/TableFunctions/ITableFunction.h index 5cbfb803c94f..75f9db7bd9d6 100644 --- a/src/TableFunctions/ITableFunction.h +++ b/src/TableFunctions/ITableFunction.h @@ -17,6 +17,7 @@ namespace DB { +class AccessFlags; class Context; /** Interface for table functions. @@ -130,6 +131,13 @@ class ITableFunction : public std::enable_shared_from_this /// Check the `TABLE ENGINE` grant, for engines that opt in via `requiresTableEngineGrant`. void checkEngineAccess(ContextPtr context) const; + /// `uri` normalized by Poco; an unparsable URI becomes empty. + static String normalizeURIForAccessCheck(const String & uri); + + /// Checks the source grant for `uri`; a location that no filter would see as accessed needs the whole-source grant. + static void checkSourceAccessForURI( + const ContextPtr & context, const AccessFlags & flags, AccessTypeObjects::Source source, const String & uri); + virtual ~ITableFunction() = default; protected: @@ -156,9 +164,6 @@ class ITableFunction : public std::enable_shared_from_this /// For example for s3Cluster the database storage name is S3Cluster, and we need to check /// privileges as if it was S3. virtual const char * getNonClusteredStorageEngineName() const; - -protected: - String getFunctionURINormalized() const; }; /// Properties of table function that are independent of argument types and parameters. diff --git a/src/TableFunctions/TableFunctionDictionary.cpp b/src/TableFunctions/TableFunctionDictionary.cpp index cbef98953f5b..09eb888c9d6f 100644 --- a/src/TableFunctions/TableFunctionDictionary.cpp +++ b/src/TableFunctions/TableFunctionDictionary.cpp @@ -49,8 +49,13 @@ void TableFunctionDictionary::parseArguments(const ASTPtr & ast_function, Contex ColumnsDescription TableFunctionDictionary::getActualTableStructure(ContextPtr context, bool /*is_insert_query*/) const { const ExternalDictionariesLoader & external_loader = context->getExternalDictionariesLoader(); - std::string resolved_name = external_loader.resolveDictionaryName(dictionary_name, context->getCurrentDatabase()); - auto load_result = external_loader.load(resolved_name); + + /// Check access before loading the dictionary, because loading contacts the dictionary source, + /// and read the dictionary that passed the check. + auto resolved_dictionary = external_loader.resolveDictionary(dictionary_name, context); + StorageDictionary::checkDictionaryAccess(resolved_dictionary.id, context); + + auto load_result = external_loader.load(resolved_dictionary.getKey()); if (load_result) { /// for regexp tree dictionary, the table structure will be different with dictionary structure. it is: @@ -73,7 +78,7 @@ ColumnsDescription TableFunctionDictionary::getActualTableStructure(ContextPtr c } /// otherwise, we get table structure by dictionary structure. - auto dictionary_structure = external_loader.getDictionaryStructure(dictionary_name, context); + auto dictionary_structure = external_loader.getDictionaryStructure(resolved_dictionary); return ColumnsDescription(StorageDictionary::getNamesAndTypes(dictionary_structure, false)); } diff --git a/src/TableFunctions/TableFunctionMergeTreeIndex.cpp b/src/TableFunctions/TableFunctionMergeTreeIndex.cpp index 4d5b07f6ea73..b4fe0bad4325 100644 --- a/src/TableFunctions/TableFunctionMergeTreeIndex.cpp +++ b/src/TableFunctions/TableFunctionMergeTreeIndex.cpp @@ -164,8 +164,7 @@ ColumnsDescription TableFunctionMergeTreeIndex::getActualTableStructure(ContextP if (with_minmax) { - const auto & partition_key = metadata_snapshot->getPartitionKey(); - for (const auto & column : MergeTreeData::getMinMaxColumns(partition_key, merge_tree->getSettings())) + for (const auto & column : MergeTreeData::getMinMaxColumns(*metadata_snapshot, merge_tree->getSettings())) columns.add({fmt::format("minmax_{}", column.name), std::make_shared(DataTypes{makeNullableSafe(column.type), makeNullableSafe(column.type)})}); } diff --git a/tests/casa_del_dolor/properties.py b/tests/casa_del_dolor/properties.py index e5944d960b6a..78e784c95389 100644 --- a/tests/casa_del_dolor/properties.py +++ b/tests/casa_del_dolor/properties.py @@ -169,15 +169,6 @@ def gen(): "database_atomic_delay_before_drop_table_sec": threshold_generator(0.2, 0.2, 0, 60), "database_catalog_drop_error_cooldown_sec": threshold_generator(0.2, 0.2, 0, 30), "database_catalog_drop_table_concurrency": threads_lambda, - "database_catalog_unused_dir_cleanup_period_sec": threshold_generator( - 0.2, 0.2, 60, 86400 - ), - "database_catalog_unused_dir_hide_timeout_sec": threshold_generator( - 0.2, 0.2, 60, 3600 - ), - "database_catalog_unused_dir_rm_timeout_sec": threshold_generator( - 0.2, 0.2, 3600, 2592000 - ), "database_replicated_allow_detach_permanently": true_false_lambda, "database_replicated_drop_broken_tables": true_false_lambda, "dictionaries_lazy_load": true_false_lambda, diff --git a/tests/config/config.d/database_atomic.xml b/tests/config/config.d/database_atomic.xml index a551e710ca37..b3f51d51a79a 100644 --- a/tests/config/config.d/database_atomic.xml +++ b/tests/config/config.d/database_atomic.xml @@ -1,8 +1,3 @@ 60 - - - 0 - 5 - 10 diff --git a/tests/config/config.d/named_collection.xml b/tests/config/config.d/named_collection.xml index dbd2cb0eeab8..e59cb8ac9e3c 100644 --- a/tests/config/config.d/named_collection.xml +++ b/tests/config/config.d/named_collection.xml @@ -106,5 +106,17 @@ operator secret + + + 127.0.0.1:1 + topic + group + JSONEachRow + + /etc/clickhouse-server/server.crt + + diff --git a/tests/integration/helpers/cluster.py b/tests/integration/helpers/cluster.py index 9428017bd620..36562499484f 100644 --- a/tests/integration/helpers/cluster.py +++ b/tests/integration/helpers/cluster.py @@ -2174,6 +2174,7 @@ def add_instance( tmpfs=None, mem_limit=None, cpu_limit=None, + cpuset=None, pids_limit=None, zookeeper_docker_compose_path=None, minio_certs_dir=None, @@ -2319,6 +2320,7 @@ def add_instance( tmpfs=tmpfs or [], mem_limit=mem_limit, cpu_limit=cpu_limit, + cpuset=cpuset, pids_limit=pids_limit, config_root_name=config_root_name, extra_configs=extra_configs, @@ -4403,7 +4405,18 @@ def shutdown( "Kill command failed during shutdown. {}".format(repr(e)) ) logging.debug("Trying to kill forcefully") - run_and_check(self.base_cmd + ["kill"]) + + def logging_compose_kill(**kwargs): + if "exception" in kwargs: + logging.info( + "Got exception in docker compose kill: %s", kwargs["exception"] + ) + + # `kill` fails on a container that exits after it is listed as running; a retry lists + # only the containers that are still running. + retry(log_function=logging_compose_kill, retries=3, delay=3, jitter=2)( + run_and_check, self.base_cmd + ["kill"] + ) # Check server logs for Fatal messages and sanitizer failures. # NOTE: we cannot do this via docker since in case of Fatal message container may already die. @@ -4886,6 +4899,7 @@ def query_all_nodes(self, sql, *args, **kwargs): tmpfs: {tmpfs} {mem_limit} {cpu_limit} + {cpuset} {pids_limit} ulimits: core: -1 @@ -4989,6 +5003,7 @@ def __init__( tmpfs=None, mem_limit=None, cpu_limit=None, + cpuset=None, pids_limit=None, config_root_name="clickhouse", extra_configs=[], @@ -5016,6 +5031,9 @@ def __init__( else: self.cpu_limit = f"cpus: {cpu_limit}" + # CPUs the container may run on, e.g. "0-1" (the `--cpuset-cpus` option of `docker run`). + self.cpuset = f'cpuset: "{cpuset}"' if cpuset is not None else "" + if pids_limit is not None: self.pids_limit = f"pids_limit: {pids_limit}" else: @@ -6650,6 +6668,7 @@ def write_embedded_config(name, dest_dir, fix_log_level=False): tmpfs=str(self.tmpfs), mem_limit=self.mem_limit, cpu_limit=self.cpu_limit, + cpuset=self.cpuset, pids_limit=self.pids_limit, logs_dir=logs_dir, depends_on=str(depends_on), diff --git a/tests/integration/test_ai_functions/mock_ai_server.py b/tests/integration/test_ai_functions/mock_ai_server.py index 859bc38e84ff..78e9c08bb5cf 100644 --- a/tests/integration/test_ai_functions/mock_ai_server.py +++ b/tests/integration/test_ai_functions/mock_ai_server.py @@ -308,6 +308,39 @@ def do_POST(self): LAST_REQUEST["body"] = body LAST_REQUEST["headers"] = {k.lower(): v for k, v in self.headers.items()} + if parsed.path in ("/v1/metrics/openai", "/v1/metrics/anthropic"): + # A known delay provides a lower bound for the request timer. + time.sleep(0.02) + mode = parse_qs(parsed.query).get("mode", ["cached"])[0] + if parsed.path.endswith("anthropic"): + response = make_anthropic_response(extract_user_message(body)) + response["usage"].update( + cache_read_input_tokens=60, cache_creation_input_tokens=30 + ) + if mode == "malformed": + del response["content"] + elif mode == "truncated": + response["stop_reason"] = "max_tokens" + else: + response = make_success_response( + extract_user_message(body), prompt_tokens=100 + ) + response["usage"]["prompt_tokens_details"] = {"cached_tokens": 60} + if mode == "no_details": + del response["usage"]["prompt_tokens_details"] + elif mode == "null_details": + response["usage"]["prompt_tokens_details"] = None + elif mode == "empty_details": + response["usage"]["prompt_tokens_details"] = {} + elif mode == "malformed": + response["choices"] = [] + elif mode == "truncated": + response["choices"][0]["finish_reason"] = "length" + if mode == "no_usage": + del response["usage"] + self._send_json(200, response) + return + if parsed.path == "/v1/chat/slow": self._serve_slowly(lambda: make_success_response(extract_user_message(body))) return diff --git a/tests/integration/test_ai_functions/test.py b/tests/integration/test_ai_functions/test.py index ea4bf564c771..7020b7717261 100644 --- a/tests/integration/test_ai_functions/test.py +++ b/tests/integration/test_ai_functions/test.py @@ -64,21 +64,23 @@ def get_profile_events(query_id, query_type="QueryFinish"): """AI counters from `system.query_log`. A query that threw logs `ExceptionWhileProcessing` rather than `QueryFinish`, so the throwing paths pass that type explicitly.""" instance.query("SYSTEM FLUSH LOGS") - result = instance.query( - f""" + result = instance.query(f""" SELECT ProfileEvents['AIAPICalls'] AS api_calls, ProfileEvents['AIInputTokens'] AS input_tokens, ProfileEvents['AIOutputTokens'] AS output_tokens, ProfileEvents['AIRowsProcessed'] AS rows_processed, ProfileEvents['AIRowsSkipped'] AS rows_skipped, + ProfileEvents['AICacheReadTokens'] AS cache_read_tokens, + ProfileEvents['AICacheWriteTokens'] AS cache_write_tokens, + ProfileEvents['AIRequestMicroseconds'] AS request_us, + ProfileEvents['AIRetryBackoffMicroseconds'] AS retry_backoff_us, peak_threads_usage AS peak_threads FROM system.query_log WHERE query_id = '{query_id}' AND type = '{query_type}' LIMIT 1 FORMAT JSONEachRow - """ - ).strip() + """).strip() assert ( result ), f"no system.query_log row found for query_id={query_id} type={query_type}" @@ -311,6 +313,185 @@ def started_cluster() -> typing.Generator[ClickHouseCluster, None, None]: cluster.shutdown() +# --------------------------------------------------------------------------- +# AI metrics +# --------------------------------------------------------------------------- + + +@pytest.fixture +def metrics_collection(started_cluster): + collections = [] + + def create(provider, mode="cached"): + name = unique_query_id("ai_metrics") + instance.query( + f"CREATE NAMED COLLECTION {name} AS provider = '{provider}', " + f"endpoint = 'http://localhost:{MOCK_PORT}/v1/metrics/{provider}?mode={mode}', " + "model = 'test-model'" + ) + collections.append(name) + return name + + yield create + for name in collections: + instance.query(f"DROP NAMED COLLECTION {name}") + + +@pytest.mark.parametrize("provider,write_tokens", [("openai", 0), ("anthropic", 30)]) +@pytest.mark.parametrize("mode", ["cached", "truncated"]) +@pytest.mark.parametrize("throw_on_error", [0, 1]) +def test_ai_metrics_cache_and_latency( + metrics_collection, provider, write_tokens, mode, throw_on_error +): + collection = metrics_collection(provider, mode) + qid = unique_query_id("cache_metrics") + query = f"SELECT aiGenerate('hello', map('credentials', '{collection}'))" + settings = { + "ai_function_throw_on_error": throw_on_error, + "ai_function_max_retries": 0, + } + throws = mode != "cached" and throw_on_error + if throws: + error = instance.query_and_get_error(query, settings=settings, query_id=qid) + assert ( + "MALFORMED_AI_PROVIDER_RESPONSE" + if mode == "malformed" + else "AI_PROVIDER_RESPONSE_TRUNCATED" + ) in error + else: + instance.query(query, settings=settings, query_id=qid) + events = get_profile_events( + qid, "ExceptionWhileProcessing" if throws else "QueryFinish" + ) + assert int(events["api_calls"]) == 1 + # Both providers report 100 total input tokens, using different usage fields. + assert int(events["input_tokens"]) == 100 + assert int(events["output_tokens"]) == 5 + assert int(events["cache_read_tokens"]) == 60 + assert int(events["cache_write_tokens"]) == write_tokens + assert int(events["rows_processed"]) == (1 if mode == "cached" else 0) + assert int(events["request_us"]) >= 20000 + assert int(events["retry_backoff_us"]) == 0 + + +@pytest.mark.parametrize( + "mode", ["no_usage", "no_details", "null_details", "empty_details"] +) +def test_ai_metrics_optional_cache_usage(metrics_collection, mode): + collection = metrics_collection("openai", mode) + qid = unique_query_id("optional_cache_metrics") + instance.query( + f"SELECT aiGenerate('hello', map('credentials', '{collection}'))", query_id=qid + ) + events = get_profile_events(qid) + assert int(events["input_tokens"]) == (0 if mode == "no_usage" else 100) + assert int(events["cache_read_tokens"]) == 0 + assert int(events["cache_write_tokens"]) == 0 + + +def test_ai_metrics_anthropic_cache_counts_towards_quota(metrics_collection): + collection = metrics_collection("anthropic") + qid = unique_query_id("cached_quota_metrics") + instance.query( + f"SELECT aiGenerate(toString(number), map('credentials', '{collection}')) FROM numbers(3)", + settings={ + "max_threads": 1, + # One request at a time, so the token quota is seen before the next request. + "ai_function_max_concurrent_requests_per_thread": 1, + "ai_function_max_input_tokens_per_query": 100, + "ai_function_throw_on_quota_exceeded": 0, + }, + query_id=qid, + ) + events = get_profile_events(qid) + assert int(events["api_calls"]) == 1 + assert int(events["input_tokens"]) == 100 + assert int(events["cache_read_tokens"]) == 60 + assert int(events["cache_write_tokens"]) == 30 + assert int(events["rows_processed"]) == 1 + assert int(events["rows_skipped"]) == 2 + + +@pytest.mark.parametrize( + "expression,calls,processed", + [ + ("aiGenerate(x, map('credentials', 'ai_mock'))", 4, 4), + ("aiEmbed(x, 'test-model', map('credentials', 'ai_embed'))", 2, 3), + ("aiSimilarity(x, x, 'test-model', map('credentials', 'ai_embed'))", 3, 3), + ], +) +def test_ai_metrics_rows_and_batches(started_cluster, expression, calls, processed): + qid = unique_query_id("rows_metrics") + instance.query( + f"SELECT {expression} FROM (SELECT arrayJoin(['a', '', NULL, 'b', 'c']) AS x)", + settings={"max_threads": 1, "ai_function_embedding_max_batch_size": 2}, + query_id=qid, + ) + events = get_profile_events(qid) + assert int(events["rows_processed"]) == processed + assert int(events["rows_skipped"]) == 0 + assert int(events["api_calls"]) == calls + assert int(events["request_us"]) > 0 + assert int(events["retry_backoff_us"]) == 0 + + +@pytest.mark.parametrize( + "expression", + [ + "aiGenerate(toString(number), map('credentials', 'ai_mock'))", + "aiEmbed(toString(number), 'test-model', map('credentials', 'ai_embed'))", + "aiSimilarity(toString(number), toString(number), 'test-model', map('credentials', 'ai_embed'))", + ], +) +@pytest.mark.parametrize("rows", [0, 9]) +def test_ai_metrics_multiple_blocks(started_cluster, expression, rows): + qid = unique_query_id("blocks_metrics") + instance.query( + f"SELECT {expression} FROM numbers({rows})", + settings={"max_threads": 1, "max_block_size": 2}, + query_id=qid, + ) + events = get_profile_events(qid) + assert int(events["rows_processed"]) == rows + if rows == 0: + assert int(events["api_calls"]) == 0 + assert int(events["request_us"]) == 0 + + +@pytest.mark.parametrize( + "expression", + [ + "aiGenerate('hello', map('credentials', 'ai_error'))", + "aiEmbed('hello', 'test-model', map('credentials', 'ai_embed_error'))", + "aiSimilarity('hello', 'world', 'test-model', map('credentials', 'ai_embed_error'))", + ], +) +@pytest.mark.parametrize("throw_on_error", [0, 1]) +def test_ai_metrics_retry_latency(started_cluster, expression, throw_on_error): + qid = unique_query_id("retry_metrics") + settings = { + "ai_function_max_retries": 2, + "ai_function_retry_initial_delay_ms": 10, + "ai_function_throw_on_error": throw_on_error, + } + if throw_on_error: + error = instance.query_and_get_error( + f"SELECT {expression}", settings=settings, query_id=qid + ) + assert "RECEIVED_ERROR_FROM_REMOTE_IO_SERVER" in error + else: + instance.query(f"SELECT {expression}", settings=settings, query_id=qid) + events = get_profile_events( + qid, "ExceptionWhileProcessing" if throw_on_error else "QueryFinish" + ) + assert int(events["api_calls"]) == 3 + assert int(events["input_tokens"]) == 0 + assert int(events["cache_read_tokens"]) == 0 + assert int(events["request_us"]) > 0 + # Two backoffs: 10 ms and 20 ms. + assert int(events["retry_backoff_us"]) >= 30000 + + # --------------------------------------------------------------------------- # aiGenerate # --------------------------------------------------------------------------- diff --git a/tests/integration/test_allowed_url_from_config/test.py b/tests/integration/test_allowed_url_from_config/test.py index 23186d5fa0d0..214f29475e89 100644 --- a/tests/integration/test_allowed_url_from_config/test.py +++ b/tests/integration/test_allowed_url_from_config/test.py @@ -60,6 +60,37 @@ def test_config_with_hosts(start_cluster): node1.query("DROP TABLE table_test_1_2") +@pytest.mark.parametrize( + "query, secret", + [ + ( + "SELECT * FROM url('http://leakuser:pw_userinfo_canary@host:123/', CSV, 'x UInt8')", + "pw_userinfo_canary", + ), + ( + "SELECT * FROM url('http://host:123/v1/chat?access_token=pw_access_token_canary', CSV, 'x UInt8')", + "pw_access_token_canary", + ), + ( + "SELECT * FROM url('http://host:123/pw_path_canary/f.csv', CSV, 'x UInt8')", + "pw_path_canary", + ), + ], + ids=["userinfo", "access_token", "secret_in_path"], +) +def test_rejected_url_credentials_masked(start_cluster, query, secret): + error = node1.query_and_get_error(query) + # The client echoes the submitted query after the exception, so only the exception line is checked. + rejections = [ + line + for line in error.splitlines() + if "is not allowed in configuration file" in line + ] + assert len(rejections) == 1, error + assert 'URL "host:123"' in rejections[0], error + assert secret not in rejections[0], error + + @pytest.mark.parametrize( "query", [ @@ -90,17 +121,17 @@ def test_azure_host_filter_before_client_creation(start_cluster, query): ( "storage_account_url = 'https://onelake.blob.fabric.microsoft.com', " "account_name = 'account', account_key = 'YQ=='", - "https://onelake.dfs.fabric.microsoft.com", + "onelake.dfs.fabric.microsoft.com:443", ), ( "connection_string = 'BlobEndpoint=https://onelake.blob.fabric.microsoft.com/;" "DfsEndpoint=http://127.0.0.1:1;SharedAccessSignature=sv=2022&sig=c2FzY2FuYXJ5'", - "http://127.0.0.1:1", + "127.0.0.1:1", ), ( "endpoint = 'BlobEndpoint=http://host:80/account/container', " "connection_string = 'BlobEndpoint=http://127.0.0.1:1'", - "http://127.0.0.1:1", + "127.0.0.1:1", ), ], ) @@ -116,7 +147,9 @@ def test_azure_disk_client_host(start_cluster, endpoint, rejected_url): f"SETTINGS disk = disk(type = azure_blob_storage, {endpoint}, container_name = 'container')", settings={"azure_sdk_max_retries": 0}, ) + # Only host:port is printed: the rest of the URL can carry secrets (SAS token). assert f'URL "{rejected_url}" is not allowed' in error + assert "c2FzY2FuYXJ5" not in error.split("(query:")[0] assert node2.query(container_requests) == before diff --git a/tests/integration/test_arrowflight_interface/test.py b/tests/integration/test_arrowflight_interface/test.py index 03a2dd8558ba..643f3c4bc1cc 100644 --- a/tests/integration/test_arrowflight_interface/test.py +++ b/tests/integration/test_arrowflight_interface/test.py @@ -10,6 +10,8 @@ from helpers.cluster import ClickHouseCluster, get_docker_compose_path from helpers.test_tools import TSV +from .flight_sql_client import FlightSQLClient + SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) DOCKER_COMPOSE_PATH = get_docker_compose_path() @@ -614,6 +616,76 @@ def test_doget_cmd_select_arrow_format(): assert actual.column("name").equals(expected_names) +def test_doget_sparse_columns(): + node.query( + "CREATE TABLE mytable (id UInt64, x UInt64, n Nullable(Int64), s Nullable(String), t Tuple(a UInt64, b String)) " + "ENGINE = MergeTree ORDER BY id " + "SETTINGS ratio_of_defaults_for_sparse_serialization = 0.5, nullable_serialization_version = 'allow_sparse'" + ) + node.query( + "INSERT INTO mytable SELECT number, if(number % 10 = 0, number, 0), if(number % 10 = 0, number, NULL), " + "if(number % 10 = 0, toString(number), NULL), (if(number % 10 = 0, number, 0), if(number % 10 = 0, toString(number), '')) " + "FROM numbers(100)" + ) + assert node.query( + "SELECT column, serialization_kind, subcolumns.serializations FROM system.parts_columns " + "WHERE database = currentDatabase() AND table = 'mytable' AND active ORDER BY column" + ) == TSV( + [ + ["id", "Default", "[]"], + ["n", "Sparse", "[]"], + ["s", "Sparse", "['Sparse']"], + ["t", "Default", "['Sparse','Sparse','Sparse']"], + ["x", "Sparse", "[]"], + ] + ) + + # No ORDER BY: sorting would materialize the sparse columns before they reach the Arrow Flight server. + query = "SELECT id, x, n, s, s.null, s.size, t FROM mytable" + client, options = get_client() + raw = client.do_get(flight.Ticket(query.encode()), options).read_all() + flight_info = client.get_flight_info( + flight.FlightDescriptor.for_command(query), options + ) + via_info = pa.concat_tables( + [client.do_get(e.ticket, options).read_all() for e in flight_info.endpoints] + ) + + with open(os.path.join(SCRIPT_DIR, "certs/ca-cert.pem"), "rb") as file: + tls_root_certs = file.read() + sql_client = FlightSQLClient( + host=node.ip_address, + port=8888, + tls_root_certs=tls_root_certs, + override_hostname=SSL_HOST, + username="user1", + password="qwe123", + ) + poll = sql_client.poll_flight_info(flight.FlightDescriptor.for_command(query)) + while poll.flight_descriptor is not None: + poll = sql_client.poll_flight_info(poll.flight_descriptor) + via_poll = pa.concat_tables( + [sql_client.do_get(e.ticket).read_all() for e in poll.info.endpoints] + ) + + rows = range(100) + expected = { + "id": list(rows), + "x": [i if i % 10 == 0 else 0 for i in rows], + "n": [i if i % 10 == 0 else None for i in rows], + "s": [str(i) if i % 10 == 0 else None for i in rows], + "s.null": [0 if i % 10 == 0 else 1 for i in rows], + "s.size": [len(str(i)) if i % 10 == 0 else None for i in rows], + "t": [ + {"a": i if i % 10 == 0 else 0, "b": str(i) if i % 10 == 0 else ""} + for i in rows + ], + } + assert raw.sort_by("id").to_pydict() == expected + assert via_info.sort_by("id").to_pydict() == expected + assert via_poll.sort_by("id").to_pydict() == expected + + # Invalid queries are handled too. def test_doget_invalid_query(): client, options = get_client() diff --git a/tests/integration/test_async_metrics_in_cgroup/test.py b/tests/integration/test_async_metrics_in_cgroup/test.py index 9ee53758c788..70a7c2c5cb59 100644 --- a/tests/integration/test_async_metrics_in_cgroup/test.py +++ b/tests/integration/test_async_metrics_in_cgroup/test.py @@ -5,6 +5,23 @@ cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance("node1", stay_alive=True, main_configs=["configs/config.xml"]) node2 = cluster.add_instance("node2", stay_alive=True, main_configs=["configs/config.xml"], cpu_limit=6) +# No CPU quota, the limit is only in the cpuset: as for a Kubernetes pod with exclusive CPUs +# under the `static` CPU manager policy, where `cpu.max` is `max`. +node3 = cluster.add_instance( + "node3", + stay_alive=True, + main_configs=["configs/config.xml"], + cpu_limit=False, + cpuset="0-1", +) +# A quota larger than the cpuset: the cpuset is the limit. +node4 = cluster.add_instance( + "node4", + stay_alive=True, + main_configs=["configs/config.xml"], + cpu_limit=4, + cpuset="0-1", +) @pytest.fixture(scope="module") @@ -89,3 +106,26 @@ def test_system_wide_metrics(start_cluster): ]: node2_value = get_async_metric(node2, metric) assert float(node2_value) > 0 + + +def test_cpuset_without_quota(start_cluster): + max_cpu = node3.query_with_retry( + "SELECT value FROM system.asynchronous_metrics WHERE metric = 'CGroupMaxCPU'", + check_callback=lambda result: result.strip() == "2", + ) + assert max_cpu.strip() == "2" + + # Normalized metrics are computed from the second update on. + normalized = node3.query_with_retry( + "SELECT count() FROM system.asynchronous_metrics WHERE metric = 'CGroupUserTimeNormalized'", + check_callback=lambda result: result.strip() == "1", + ) + assert normalized.strip() == "1" + + +def test_quota_larger_than_cpuset(start_cluster): + max_cpu = node4.query_with_retry( + "SELECT value FROM system.asynchronous_metrics WHERE metric = 'CGroupMaxCPU'", + check_callback=lambda result: result.strip() == "2", + ) + assert max_cpu.strip() == "2" diff --git a/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml b/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml index 22fe3a73a9cc..7d771893ee43 100644 --- a/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml +++ b/tests/integration/test_attach_backup_from_s3_plain/configs/disk_s3.xml @@ -16,6 +16,7 @@ + /local_plain/ backup_disk_s3_plain backup_disk_local_plain diff --git a/tests/integration/test_backup_restore_new/test.py b/tests/integration/test_backup_restore_new/test.py index 5948216ac36d..e51579ba0896 100644 --- a/tests/integration/test_backup_restore_new/test.py +++ b/tests/integration/test_backup_restore_new/test.py @@ -1342,6 +1342,65 @@ def test_required_privileges(): instance.query(f"RESTORE ALL FROM {backup_name}", user="u1") +def test_restore_materialized_view_checks_source_rights(): + create_and_fill_table(n=5) + instance.query("CREATE TABLE test.secret (x UInt32, y String) ENGINE = MergeTree ORDER BY y") + instance.query("CREATE TABLE test.sink (x UInt32, y String) ENGINE = MergeTree ORDER BY y") + instance.query("CREATE MATERIALIZED VIEW test.mv TO test.sink AS SELECT x, y FROM test.table") + + instance.query("CREATE USER u1") + instance.query("GRANT READ ON DISK, WRITE ON DISK TO u1") + instance.query("GRANT SELECT, INSERT, BACKUP ON test.table TO u1") + instance.query("GRANT SELECT, INSERT, CREATE VIEW, BACKUP ON test.mv TO u1") + instance.query("GRANT SELECT, INSERT ON test.sink TO u1") + + # The backup names `test.secret` as the table that the view reads. + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE test.mv, TABLE test.table AS test.secret TO {backup_name}", user="u1") + definition = open(os.path.join(get_path_to_backup(backup_name), "metadata/test/mv.sql")).read() + assert "FROM test.secret" in definition, definition + instance.query("DROP TABLE test.mv") + + # As for `CREATE MATERIALIZED VIEW`, the rights for that table are needed. + expected_error = "necessary to have the grant SELECT ON test.secret" + assert expected_error in instance.query_and_get_error(f"RESTORE TABLE test.mv FROM {backup_name}", user="u1") + assert instance.query("EXISTS test.mv") == "0\n" + + # A table that the query of the view names but that does not exist does not hide another table. + instance.query("CREATE TABLE test.other (x UInt32) ENGINE = MergeTree ORDER BY x") + instance.query( + "CREATE MATERIALIZED VIEW test.mv2 TO test.sink AS " + "SELECT t.x AS x, t.y AS y FROM test.table AS t INNER JOIN test.other AS o ON t.x = o.x" + ) + instance.query("GRANT SELECT, BACKUP ON test.other TO u1") + instance.query("GRANT SELECT, INSERT, CREATE VIEW, BACKUP ON test.mv2 TO u1") + instance.query("GRANT SELECT ON test.missing TO u1") + backup_name2 = new_backup_name() + instance.query( + f"BACKUP TABLE test.mv2, TABLE test.table AS test.missing, TABLE test.other AS test.secret TO {backup_name2}", + user="u1", + ) + instance.query("DROP TABLE test.mv2") + assert expected_error in instance.query_and_get_error(f"RESTORE TABLE test.mv2 FROM {backup_name2}", user="u1") + assert instance.query("EXISTS test.mv2") == "0\n" + + # A view with a table function that cannot be resolved at the time of the restore is restored as well. + instance.query( + "CREATE MATERIALIZED VIEW test.mv3 TO test.sink AS " + "SELECT x, y FROM test.table WHERE x IN (SELECT x FROM remote('127.0.0.1', test.other))" + ) + backup_name3 = new_backup_name() + instance.query(f"BACKUP TABLE test.mv3 TO {backup_name3}") + instance.query("DROP TABLE test.mv3") + instance.query("DROP TABLE test.other") + instance.query(f"RESTORE TABLE test.mv3 FROM {backup_name3}") + assert instance.query("EXISTS test.mv3") == "1\n" + + instance.query("GRANT SELECT ON test.secret TO u1") + instance.query(f"RESTORE TABLE test.mv FROM {backup_name}", user="u1") + assert instance.query("EXISTS test.mv") == "1\n" + + def test_system_table(): backup_name = new_backup_name() instance.query(f"BACKUP TABLE system.numbers TO {backup_name}") @@ -1628,6 +1687,78 @@ def test_restore_access_partial_revokes_preserve_grant_and_table_requirements(): assert instance.query("SELECT * FROM test.table") == "1\n" +def create_constrained_actor(grants): + # Created after the backup, so that the backup holds only the entities to restore. + instance.query("CREATE USER u2 SETTINGS allow_introspection_functions = 0 CONST") + instance.query("GRANT READ ON DISK TO u2") + instance.query(f"GRANT {grants} ON *.* TO u2") + + +@pytest.mark.parametrize( + "kind,system_table,target", + [ + ("USER", "users", "u1"), + ("ROLE", "roles", "r1"), + ("SETTINGS PROFILE", "settings_profiles", "prof1"), + ], +) +def test_restore_access_checks_settings_constraints(kind, system_table, target): + instance.query(f"CREATE {kind} {target} SETTINGS allow_introspection_functions = 1") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.{system_table} TO {backup_name}") + instance.query(f"DROP {kind} {target}") + + create_constrained_actor(f"CREATE {kind}") + assert "SETTING_CONSTRAINT_VIOLATION" in instance.query_and_get_error( + f"CREATE {kind} {target} SETTINGS allow_introspection_functions = 1", user="u2" + ) + restore = f"RESTORE TABLE system.{system_table} FROM {backup_name}" + assert "SETTING_CONSTRAINT_VIOLATION" in instance.query_and_get_error( + restore, user="u2" + ) + count = f"SELECT count() FROM system.{system_table} WHERE name = '{target}'" + assert instance.query(count) == "0\n" + + instance.query(restore) + assert "allow_introspection_functions = true" in instance.query( + f"SHOW CREATE {kind} {target}" + ) + + +def test_restore_access_checks_settings_of_existing_entities(): + instance.query("CREATE USER u1 SETTINGS allow_introspection_functions = 1") + backup_name = new_backup_name() + instance.query(f"BACKUP TABLE system.users TO {backup_name}") + instance.query("ALTER USER u1 SETTINGS NONE") + show_u1 = "SHOW CREATE USER u1" + assert instance.query(show_u1) == "CREATE USER u1 IDENTIFIED WITH no_password\n" + + create_constrained_actor("CREATE USER") + # `u1` exists here, but it may not exist on another host of `RESTORE ON CLUSTER`. + assert "SETTING_CONSTRAINT_VIOLATION" in instance.query_and_get_error( + f"RESTORE TABLE system.users FROM {backup_name}", user="u2" + ) + assert instance.query(show_u1) == "CREATE USER u1 IDENTIFIED WITH no_password\n" + + # Replacing a user along with the profile it keeps the constrained setting through is allowed. + instance.query("DROP USER u1, u2") + instance.query( + "CREATE SETTINGS PROFILE prof1 SETTINGS allow_introspection_functions = 0 CONST" + ) + instance.query("CREATE USER u1 SETTINGS PROFILE prof1") + backup_name = new_backup_name() + backup_tables = "TABLE system.users, TABLE system.settings_profiles" + instance.query(f"BACKUP {backup_tables} TO {backup_name}") + create_constrained_actor( + "CREATE USER, DROP USER, CREATE SETTINGS PROFILE, DROP SETTINGS PROFILE" + ) + instance.query( + f"RESTORE {backup_tables} FROM {backup_name} SETTINGS create_access='replace'", + user="u2", + ) + assert "SETTINGS PROFILE `prof1`" in instance.query(show_u1) + + def test_system_users_async(): instance.query("CREATE USER u1 IDENTIFIED BY 'qwe123' SETTINGS custom_c = 3") diff --git a/tests/integration/test_backup_restore_on_cluster/test.py b/tests/integration/test_backup_restore_on_cluster/test.py index 633b5f6e252d..6a02cebdfda4 100644 --- a/tests/integration/test_backup_restore_on_cluster/test.py +++ b/tests/integration/test_backup_restore_on_cluster/test.py @@ -826,6 +826,23 @@ def test_system_users(): assert node1.query("SHOW GRANTS FOR u1") == "GRANT SELECT ON default.tbl TO u1\n" +def test_system_users_settings_constraints(): + node1.query("CREATE USER u1 SETTINGS allow_introspection_functions = 1") + backup_name = new_backup_name() + node1.query(f"BACKUP TABLE system.users ON CLUSTER 'cluster' TO {backup_name}") + node1.query("DROP USER u1") + + # The hosts restore without the user, so the initiator checks the constraints for them. + node1.query("CREATE USER u2 SETTINGS allow_introspection_functions = 0 CONST") + node1.query("GRANT CLUSTER, CREATE USER ON *.* TO u2") + node1.query("GRANT READ ON DISK TO u2") + assert "SETTING_CONSTRAINT_VIOLATION" in node1.query_and_get_error( + f"RESTORE TABLE system.users ON CLUSTER 'cluster' FROM {backup_name}", user="u2" + ) + for node in [node1, node2]: + assert node.query("SELECT count() FROM system.users WHERE name = 'u1'") == "0\n" + + def test_system_functions(): node1.query("CREATE FUNCTION linear_equation AS (x, k, b) -> k*x + b;") node1.query("CREATE FUNCTION parity_str AS (n) -> if(n % 2, 'odd', 'even');") diff --git a/tests/integration/test_backward_compatibility/test.py b/tests/integration/test_backward_compatibility/test.py index 1f50921bcc57..7af077c824fc 100644 --- a/tests/integration/test_backward_compatibility/test.py +++ b/tests/integration/test_backward_compatibility/test.py @@ -42,3 +42,21 @@ def test_backward_compatability1(start_cluster): node1.query("SYSTEM SYNC REPLICA t", timeout=10) assert node1.query("SELECT count() FROM t") == "1\n" + + +def test_new_client_and_initiator_with_negative_seconds_in_old_server_profile(start_cluster): + node1.query("DROP USER IF EXISTS u_negative_seconds") + node1.query("CREATE USER u_negative_seconds IDENTIFIED WITH no_password SETTINGS max_execution_time = -1") + node1.query("GRANT SELECT ON system.one TO u_negative_seconds") + try: + # `node1.query*` runs the tested client against the old server; the client warns about the value it skips. + out, err = node1.query_and_get_answer_with_error("SELECT 1", user="u_negative_seconds") + assert out == "1\n" + # Servers older than revision DBMS_MIN_REVISION_WITH_SERVER_SETTINGS (e.g. the 23.3 Altinity stable used + # as CLICKHOUSE_CI_MIN_TESTED_VERSION here) send no settings in their Hello, so there is nothing to skip. + old_major = int(node1.query("SELECT version()").strip().split(".")[0]) + if old_major >= 25: + assert "Cannot parse the value of setting `max_execution_time`, skipping it" in err + assert node2.query("SELECT count() FROM remote('node1', system.one, 'u_negative_seconds', '')") == "1\n" + finally: + node1.query("DROP USER IF EXISTS u_negative_seconds") diff --git a/tests/integration/test_dictionaries_ddl/test.py b/tests/integration/test_dictionaries_ddl/test.py index dd8031348d74..dda7625701e2 100644 --- a/tests/integration/test_dictionaries_ddl/test.py +++ b/tests/integration/test_dictionaries_ddl/test.py @@ -440,7 +440,7 @@ def test_dictionary_with_where(started_cluster): DB 'dictionary_with_where' TABLE 'special_table' REPLICA(PRIORITY 1 HOST 'mysql80' PORT 3306) - WHERE 'value1 = \\'qweqwe\\' OR value1 = \\'\\\\u3232\\'' + WHERE 'value1 = \\'qweqwe\\' OR value1 = \\'it\\'\\'s ㈲\\'' )) LAYOUT(FLAT()) LIFETIME(MIN 1 MAX 3) @@ -521,6 +521,7 @@ def test_clickhouse_remote(started_cluster): # https://github.com/ClickHouse/ClickHouse/issues/38450 # suggests placing 'secure' in named_collections def test_secure(started_cluster): + # `CREATE DICTIONARY` with a named collection requires `NAMED COLLECTION` on it, which only `admin` has node1.query("DROP TABLE IF EXISTS test.foo_dict") node1.query("CREATE TABLE test.foo_dict(`id` UInt64, `value` String) ENGINE = Log") node1.query("INSERT INTO test.foo_dict values (1, 'value1')") @@ -564,7 +565,8 @@ def test_secure(started_cluster): TABLE 'foo_dict' DB 'test' )) LIFETIME(MIN 1 MAX 10) - """ + """, + user="admin", ) value = node1.query( "SELECT dictGet('test.clickhouse_secure', 'value', toUInt64(1))" @@ -586,7 +588,8 @@ def test_secure(started_cluster): TABLE 'foo_dict' DB 'test' )) LIFETIME(MIN 1 MAX 10) - """ + """, + user="admin", ) with pytest.raises(QueryRuntimeException) as excinfo: node1.query("SELECT dictGet('test.clickhouse_secure', 'value', toUInt64(1))") @@ -611,7 +614,8 @@ def test_secure(started_cluster): TABLE 'foo_dict' DB 'test' )) LIFETIME(MIN 1 MAX 10) - """ + """, + user="admin", ) with pytest.raises(QueryRuntimeException) as excinfo: node1.query("SELECT dictGet('test.clickhouse_secure', 'value', toUInt64(1))") @@ -637,7 +641,8 @@ def test_secure(started_cluster): )) LIFETIME(MIN 1 MAX 10) """ - # Overriding a stored key requires `SHOW NAMED COLLECTIONS SECRETS`, which `default` does not have + # A named collection requires `NAMED COLLECTION` on it, and overriding a stored key `SHOW NAMED COLLECTIONS SECRETS`: + # `default` has neither, `admin` has both assert "ACCESS_DENIED" in node1.query_and_get_error(create_with_override) node1.query(create_with_override, user="admin") value = node1.query( @@ -660,7 +665,8 @@ def test_named_collection(started_cluster): LAYOUT(FLAT()) SOURCE(CLICKHOUSE(NAME click1)) LIFETIME(MIN 1 MAX 10) - """ + """, + user="admin", ) node1.query( diff --git a/tests/integration/test_disk_over_web_server/configs/http_forbid_headers.xml b/tests/integration/test_disk_over_web_server/configs/http_forbid_headers.xml new file mode 100644 index 000000000000..346e5bb79319 --- /dev/null +++ b/tests/integration/test_disk_over_web_server/configs/http_forbid_headers.xml @@ -0,0 +1,5 @@ + + +
X-Forbidden-Placeholder
+
+
diff --git a/tests/integration/test_disk_over_web_server/test.py b/tests/integration/test_disk_over_web_server/test.py index 6dd8d986d1ea..abc0708a2c88 100644 --- a/tests/integration/test_disk_over_web_server/test.py +++ b/tests/integration/test_disk_over_web_server/test.py @@ -42,7 +42,11 @@ def cluster(): ) cluster.add_instance( "node5", - main_configs=["configs/storage_conf.xml", "configs/no_async_load.xml"], + main_configs=[ + "configs/storage_conf.xml", + "configs/no_async_load.xml", + "configs/http_forbid_headers.xml", + ], with_nginx=True, use_old_analyzer=True, ) @@ -414,3 +418,37 @@ def test_config_reload(cluster): node1.query("SYSTEM RELOAD CONFIG") node1.query(f"DROP TABLE {table_name} SYNC") + + +FORBID_CONFIG = "/etc/clickhouse-server/config.d/http_forbid_headers.xml" +FORBID_PLACEHOLDER = "
X-Forbidden-Placeholder
" + + +def test_userinfo_with_forbidden_authorization(cluster): + # The userinfo of the endpoint is sent as Basic credentials in the `Authorization` header with every data read. + node = cluster.instances["node5"] + table_name = "userinfo_forbidden_authorization" + node.query( + f""" + DROP TABLE IF EXISTS {table_name}; + CREATE TABLE {table_name} UUID '{uuids[0]}' + (id Int32) ENGINE = MergeTree() ORDER BY id + SETTINGS disk = disk(type=web, endpoint='http://user:pass@nginx:80/test1/'); + """ + ) + # The filter makes the query read the column instead of answering it from the part statistics. + query = f"SELECT sum(id) FROM {table_name} WHERE id % 2 = 0" + try: + expected = node.query(query) + assert int(expected) > 0 + node.replace_in_config(FORBID_CONFIG, FORBID_PLACEHOLDER, FORBID_PLACEHOLDER + "
Authorization
") + node.query("SYSTEM RELOAD CONFIG") + try: + error = node.query_and_get_error(query) + assert 'HTTP header "Authorization" is forbidden' in error, error + finally: + node.replace_in_config(FORBID_CONFIG, "
Authorization
", "") + node.query("SYSTEM RELOAD CONFIG") + assert node.query(query) == expected + finally: + node.query(f"DROP TABLE IF EXISTS {table_name} SYNC") diff --git a/tests/integration/test_distributed_inter_server_secret/test.py b/tests/integration/test_distributed_inter_server_secret/test.py index 06eb003f208a..a97d683b9781 100644 --- a/tests/integration/test_distributed_inter_server_secret/test.py +++ b/tests/integration/test_distributed_inter_server_secret/test.py @@ -466,20 +466,33 @@ def test_per_user_protocol_settings_secure_cluster(user, password): def test_secure_cluster_distributed_over_distributed_different_users_remote(): - # This works because we will have initial_user='default' + # With the local-replica optimization the read runs in new_user's session while remote() + # stamps initial_user='default', so forwarding it over the cluster secret is rejected. + error = n1.query_and_get_error( + "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", + user="new_user", + settings={"prefer_localhost_replica": 1}, + ) + assert "Refusing to forward a query over the cluster secret" in error + + # With the optimization off, remote() opens a real connection that authenticates 'default', + # so initial_user==current_user=='default' and the query runs as 'default'. n1.query( - "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", user="new_user" + "SELECT * FROM remote('n1', currentDatabase(), dist_secure)", + user="new_user", + settings={"prefer_localhost_replica": 0}, + ) + + # new_user exists only on n1, so the secret forward to n2 fails there -- deeper than our + # guard, with no stable error text, so only assert the query is rejected. + assert n2.query_and_get_error( + "SELECT * FROM remote('n1', currentDatabase(), dist_secure, 'new_user')" + ) + + # Also rejected: dist-over-dist on the secure cluster (new_user is still missing on n2). + assert n1.query_and_get_error( + "SELECT * FROM dist_over_dist_secure", user="new_user" ) - # While this is broken because now initial_user='new_user', and n2 does not has it - with pytest.raises(QueryRuntimeException): - n2.query( - "SELECT * FROM remote('n1', currentDatabase(), dist_secure, 'new_user')" - ) - # And this is still a problem, let's assume that this is OK, since we are - # expecting that in case of dist-over-dist the clusters are the same (users - # and stuff). - with pytest.raises(QueryRuntimeException): - n1.query("SELECT * FROM dist_over_dist_secure", user="new_user") def test_secure_cluster_distributed_over_distributed_different_users_cluster(): diff --git a/tests/integration/test_grant_and_revoke/test_with_table_engine_grant.py b/tests/integration/test_grant_and_revoke/test_with_table_engine_grant.py index 93beb149252a..eced43a84a68 100644 --- a/tests/integration/test_grant_and_revoke/test_with_table_engine_grant.py +++ b/tests/integration/test_grant_and_revoke/test_with_table_engine_grant.py @@ -702,7 +702,8 @@ def test_grant_current_grants_with_partial_revoke(): assert instance.query("SHOW GRANTS FOR C") == TSV( [ "GRANT SELECT ON *.* TO C", - "GRANT CREATE TABLE ON test.`table` TO C", + "REVOKE SELECT ON test.* FROM C", + "GRANT SELECT, CREATE TABLE ON test.`table` TO C", ] ) diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml index 10c47386bf00..d2b62ac2bc5f 100644 --- a/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/config.d/clusters.xml @@ -11,5 +11,28 @@ + + + + interserver_secret_for_test + + + 127.0.0.1 + 9000 + + + + + + + + + 127.0.0.1 + 9000 + + + diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml new file mode 100644 index 000000000000..3feeedf7c9e1 --- /dev/null +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/configs/users.d/profiles.xml @@ -0,0 +1,10 @@ + + + + + 0 + + + diff --git a/tests/integration/test_interserver_marker_requires_cluster_secret/test.py b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py index 4fdf35b9bdf1..3be66dff44ab 100644 --- a/tests/integration/test_interserver_marker_requires_cluster_secret/test.py +++ b/tests/integration/test_interserver_marker_requires_cluster_secret/test.py @@ -16,6 +16,7 @@ """ import socket + import pytest from helpers.cluster import ClickHouseCluster @@ -27,6 +28,9 @@ "configs/config.d/clusters.xml", "configs/config.d/session_log.xml", ], + user_configs=[ + "configs/users.d/profiles.xml", + ], ) USER_INTERSERVER_MARKER = " INTERSERVER SECRET " @@ -146,3 +150,172 @@ def test_cluster_without_secret_rejected(started_cluster): ) > 0 ), "Expected a LoginFailure row in system.session_log for the rejected interserver marker" + + +def send_forged_secondary_query(user, password, query, forged_initial_user): + """Send one query over a plain (non-interserver) connection, forging query_kind=SECONDARY_QUERY + and a client-chosen initial_user. Return the raw bytes the server sends back.""" + # A revision accepted by the server but below DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS + # (54470): new enough for the quota-key addendum field, old enough to avoid chunked framing and + # its negotiation, so the Hello, addendum, Query and Data packets are plain back-to-back bytes. + client_revision = 54462 + + # A regular (non-interserver) Hello: authenticates as a normal user with a password. + hello = b"".join( + [ + encode_varuint(0), # Client::Hello + encode_string(b"test"), # client_name + encode_varuint(24), # version_major + encode_varuint(1), # version_minor + encode_varuint(client_revision), + encode_string(b""), # default database + encode_string(user), + encode_string(password), + ] + ) + addendum = encode_string(b"") # quota key + + # A Query packet that claims to be a SECONDARY_QUERY on behalf of another initial_user. + client_info = b"".join( + [ + b"\x02", # query_kind = SECONDARY_QUERY + encode_string(forged_initial_user), # forged initial_user + encode_string(b""), # initial_query_id + encode_string(b"127.0.0.1:9000"), # initial_address + (0).to_bytes(8, "little"), # initial_query_start_time_microseconds + b"\x01", # interface = TCP + encode_string(b""), # os_user + encode_string(b""), # client_hostname + encode_string(b"test"), # client_name + encode_varuint(24), # version_major + encode_varuint(1), # version_minor + encode_varuint(client_revision), # client_tcp_protocol_version + encode_string(b""), # quota_key + encode_varuint(0), # distributed_depth + encode_varuint(0), # version_patch + b"\x00", # no OpenTelemetry trace context + encode_varuint(0), # collaborate_with_initiator + encode_varuint(0), # obsolete_count_participating_replicas + encode_varuint(0), # number_of_current_replica + ] + ) + query_packet = b"".join( + [ + encode_varuint(1), # Client::Query + encode_string(b""), # query_id + client_info, + encode_string(b""), # end of settings + encode_string(b"\x00" * 32), # interserver hash (ignored without the secret handshake) + encode_varuint(2), # stage = Complete + encode_varuint(0), # compression disabled + encode_string(query), + encode_string(b""), # end of parameters + ] + ) + + # An empty Data block signals end of input, so the server runs the query to completion. + data_block = b"".join( + [ + encode_varuint(2), # Client::Data + encode_string(b""), # temporary table name + encode_varuint(1), # BlockInfo field: is_overflows + b"\x00", # is_overflows = false + encode_varuint(2), # BlockInfo field: bucket_num + (-1).to_bytes(4, "little", signed=True), # bucket_num = -1 + encode_varuint(0), # end of BlockInfo + encode_varuint(0), # columns + encode_varuint(0), # rows + ] + ) + + packet = hello + addendum + query_packet + data_block + response = b"" + with socket.create_connection((node.ip_address, 9000), timeout=20) as connection: + connection.settimeout(5) + connection.sendall(packet) + # The server keeps the connection open after the result, so read until it goes idle. + try: + while True: + chunk = connection.recv(65536) + if not chunk: + break + response += chunk + except (socket.timeout, ConnectionResetError, BrokenPipeError): + pass + return response + + +def test_forged_secondary_query_cannot_impersonate_on_secret_cluster(started_cluster): + """A user forges a SECONDARY_QUERY and reads a Distributed table over a secret cluster. The attacker + never gets the admin-only data: a query impersonating 'admin' is not forwarded, and an empty + initial_user means the authenticated user (the shard would otherwise authenticate it as no user, + i.e. with full access).""" + try: + # A table only `admin` may read, exposed through a Distributed table over the secret cluster. + node.query( + "CREATE TABLE default.secret_data (secret String) ENGINE = MergeTree ORDER BY secret" + ) + node.query("INSERT INTO default.secret_data VALUES ('TOP_SECRET_ADMIN_ONLY')") + node.query( + "CREATE TABLE default.secret_dist AS default.secret_data " + "ENGINE = Distributed(secret_cluster, default, secret_data)" + ) + node.query("CREATE USER admin IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.secret_data TO admin") + # The attacker may read only the Distributed table, never the secret table directly. + node.query("CREATE USER attacker IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.secret_dist TO attacker") + + for forged_initial_user, expected_error in [ + # Another user's name is refused at the interserver-secret boundary. + (b"admin", b"Refusing to forward a query over the cluster secret"), + # An empty name means the authenticated user, which has no access on the shard. + (b"", b"attacker: Not enough privileges"), + ]: + response = send_forged_secondary_query( + user=b"attacker", + password=b"", + query="SELECT secret FROM default.secret_dist", + forged_initial_user=forged_initial_user, + ) + + # The attacker must not obtain the admin-only data. + assert b"TOP_SECRET_ADMIN_ONLY" not in response + assert expected_error in response + finally: + node.query("DROP TABLE IF EXISTS default.secret_dist SYNC") + node.query("DROP TABLE IF EXISTS default.secret_data SYNC") + node.query("DROP USER IF EXISTS attacker, admin") + + +def test_mixed_secret_and_insecure_cluster_rejected(started_cluster): + """A non-secret Distributed table whose shard re-forwards over a secret one leaves the shard with + initial_user != current_user, so the fix rejects it instead of laundering an unverified + initiator (the non-secret hop cannot vouch for it).""" + try: + node.query( + "CREATE TABLE default.mixed_data (secret String) ENGINE = MergeTree ORDER BY secret" + ) + node.query("INSERT INTO default.mixed_data VALUES ('TOP_SECRET_ADMIN_ONLY')") + # A non-secret Distributed table (outer) whose shard reads a secret Distributed table (inner). + node.query( + "CREATE TABLE default.mixed_inner_dist AS default.mixed_data " + "ENGINE = Distributed(secret_cluster, default, mixed_data)" + ) + node.query( + "CREATE TABLE default.mixed_outer_dist AS default.mixed_data " + "ENGINE = Distributed(insecure_cluster, default, mixed_inner_dist)" + ) + # A non-default user, so the shard sees initial_user (mixed_user) != current_user (default). + node.query("CREATE USER mixed_user IDENTIFIED WITH no_password HOST ANY") + node.query("GRANT SELECT ON default.* TO mixed_user") + + error = node.query_and_get_error( + "SELECT secret FROM default.mixed_outer_dist", user="mixed_user" + ) + assert "Refusing to forward a query over the cluster secret" in error + finally: + node.query("DROP TABLE IF EXISTS default.mixed_outer_dist SYNC") + node.query("DROP TABLE IF EXISTS default.mixed_inner_dist SYNC") + node.query("DROP TABLE IF EXISTS default.mixed_data SYNC") + node.query("DROP USER IF EXISTS mixed_user") diff --git a/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml new file mode 100644 index 000000000000..f2632aa4fb13 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/http_handler_with_user.xml @@ -0,0 +1,16 @@ + + + + + /handler_with_user + GET,POST + + predefined_query_handler + SELECT currentUser() + http_handler_user + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml new file mode 100644 index 000000000000..23888f3dcef6 --- /dev/null +++ b/tests/integration/test_ldap_external_user_directory/configs/memory_user_directory.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/tests/integration/test_ldap_external_user_directory/test.py b/tests/integration/test_ldap_external_user_directory/test.py index 9ffdaf00f25b..9f153e673c10 100644 --- a/tests/integration/test_ldap_external_user_directory/test.py +++ b/tests/integration/test_ldap_external_user_directory/test.py @@ -1,4 +1,5 @@ import logging +import uuid import pytest @@ -12,7 +13,12 @@ instance1 = cluster.add_instance( "instance1", - main_configs=["configs/ldap_with_role_mapping.xml", "configs/remote_servers.xml"], + main_configs=[ + "configs/ldap_with_role_mapping.xml", + "configs/memory_user_directory.xml", + "configs/http_handler_with_user.xml", + "configs/remote_servers.xml", + ], user_configs=["configs/users.xml"], macros={"shard": 1, "replica": "instance1"}, stay_alive=True, @@ -229,3 +235,154 @@ def test_remote_query_user_does_not_exist_locally(ldap_cluster): instance2.query("DROP USER IF EXISTS non_local", user="common_user", password="qwerty") instance2.query("DROP TABLE IF EXISTS test_table SYNC", user="common_user", password="qwerty") + + +def add_ldap_user(ldap_cluster, user_cn, password): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """echo "dn: cn={user_cn},ou=users,dc=example,dc=org +objectClass: inetOrgPerson +cn: {user_cn} +sn: {user_cn} +userPassword: {password}" | \ +ldapadd -H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + password=password, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def delete_ldap_user(ldap_cluster, user_cn): + code, (stdout, stderr) = ldap_cluster.ldap_container.exec_run( + [ + "sh", + "-c", + """ldapdelete 'cn={user_cn},ou=users,dc=example,dc=org' \ +-H ldap://{host}:{port} -D "{admin_bind_dn}" -x -w {admin_password} + """.format( + host=ldap_cluster.ldap_host, + port=ldap_cluster.ldap_port, + admin_bind_dn=LDAP_ADMIN_BIND_DN, + admin_password=LDAP_ADMIN_PASSWORD, + user_cn=user_cn, + ), + ], + demux=True, + ) + logging.debug( + f"test_ldap_external_user_directory code:{code} stdout:{stdout}, stderr:{stderr}" + ) + assert code == 0 + + +def user_storages(name): + return instance1.query( + f"SELECT storage FROM system.users WHERE name = '{name}' ORDER BY storage", + user="common_user", + password="qwerty", + ).split() + + +def test_same_name_user_in_other_directory(ldap_cluster): + """ + A user authenticated by LDAP must not share its name with a user from another user directory. + The `memory` directory follows the LDAP one, so a login by LDAP credentials would reach LDAP first + if the user were not looked up in all directories before. + """ + # A unique name, so that the LDAP user is not yet known to the server even if the test is retried. + name = f"same_name_{uuid.uuid4().hex[:8]}" + add_ldap_user(ldap_cluster, name, "ldap_password") + + try: + instance1.query( + f"CREATE USER {name} IDENTIFIED WITH plaintext_password BY 'local_password' IN memory", + user="common_user", + password="qwerty", + ) + + # The LDAP user is not known yet, so there is no conflict. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + assert user_storages(name) == ["memory"] + + # The LDAP directory would recognize the user, but the name is already used in the `memory` directory, + # so only that directory authenticates the user, and LDAP does not introduce a second user with this name. + assert f"{name}: Authentication failed" in instance1.query_and_get_error( + "SELECT currentUser()", user=name, password="ldap_password" + ) + assert user_storages(name) == ["memory"] + + # The local user can still log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="local_password" + ) == TSV([[name]]) + + instance1.query( + f"DROP USER {name} FROM memory", + user="common_user", + password="qwerty", + ) + + # Now the LDAP user can log in. + assert instance1.query( + "SELECT currentUser()", user=name, password="ldap_password" + ) == TSV([[name]]) + assert user_storages(name) == ["ldap"] + + # A new user with the same name cannot be created in another directory, whether it is specified or not. + for query in [ + f"CREATE USER {name}", + f"CREATE USER {name} IN memory", + f"CREATE USER OR REPLACE {name} IN memory", + ]: + assert "ACCESS_ENTITY_ALREADY_EXISTS" in instance1.query_and_get_error( + query, user="common_user", password="qwerty" + ) + finally: + for storage in ["memory", "local_directory"]: + instance1.query( + f"DROP USER IF EXISTS {name} FROM {storage}", + user="common_user", + password="qwerty", + ) + delete_ldap_user(ldap_cluster, name) + + +def test_same_name_user_in_other_directory_always_allow_credentials(ldap_cluster): + """ + An HTTP handler with a configured user authenticates it with `AlwaysAllowCredentials`, which the LDAP directory + accepts without contacting the LDAP server. If the user exists in another directory, LDAP must not introduce + a second user with the same name. + """ + name = "http_handler_user" + try: + instance1.query( + f"CREATE USER {name} IN memory", + user="common_user", + password="qwerty", + ) + for _ in range(2): + response = instance1.http_request("handler_with_user") + assert response.status_code == 200, response.text + assert response.text.strip() == name + assert user_storages(name) == ["memory"] + finally: + instance1.query( + f"DROP USER IF EXISTS {name} FROM memory", + user="common_user", + password="qwerty", + ) diff --git a/tests/integration/test_mask_sensitive_info/test.py b/tests/integration/test_mask_sensitive_info/test.py index 031e83f12ea1..5f7785333e6a 100644 --- a/tests/integration/test_mask_sensitive_info/test.py +++ b/tests/integration/test_mask_sensitive_info/test.py @@ -885,7 +885,7 @@ def test_create_dictionary(): f"LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())" ) - for toggle, secret in enumerate(["[HIDDEN]", password]): + for toggle, (secret, url) in enumerate([("[HIDDEN]", "[HIDDEN]"), (password, "http://localhost:8123/dict.tsv")]): assert ( node.query(f"SHOW CREATE TABLE dict1 {show_secrets}={toggle}") == f"CREATE DICTIONARY default.dict1\\n(\\n `n` int DEFAULT 0,\\n `m` int DEFAULT 1\\n)\\nPRIMARY KEY n\\nSOURCE(CLICKHOUSE(HOST \\'localhost\\' PORT 9000 USER \\'user1\\' TABLE \\'test\\' PASSWORD \\'{secret}\\' DB \\'default\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" @@ -893,12 +893,12 @@ def test_create_dictionary(): assert ( node.query(f"SHOW CREATE TABLE dict2 {show_secrets}={toggle}") - == f"CREATE DICTIONARY default.dict2\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" + == f"CREATE DICTIONARY default.dict2\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\'))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" ) assert ( node.query(f"SHOW CREATE TABLE dict3 {show_secrets}={toggle}") - == f"CREATE DICTIONARY default.dict3\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\')))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" + == f"CREATE DICTIONARY default.dict3\\n(\\n `n` int DEFAULT 0\\n)\\nPRIMARY KEY n\\nSOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\')))\\nLIFETIME(MIN 0 MAX 10)\\nLAYOUT(FLAT())\n" ) assert ( @@ -907,8 +907,8 @@ def test_create_dictionary(): ) == ( f"CREATE DICTIONARY default.dict1 (`n` int DEFAULT 0, `m` int DEFAULT 1) PRIMARY KEY n SOURCE(CLICKHOUSE(HOST \\'localhost\\' PORT 9000 USER \\'user1\\' TABLE \\'test\\' PASSWORD \\'{secret}\\' DB \\'default\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" - f"CREATE DICTIONARY default.dict2 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" - f"CREATE DICTIONARY default.dict3 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'http://localhost:8123/dict.tsv\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\'))) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" + f"CREATE DICTIONARY default.dict2 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' USER \\'huser\\' PASSWORD \\'{secret}\\')) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" + f"CREATE DICTIONARY default.dict3 (`n` int DEFAULT 0) PRIMARY KEY n SOURCE(HTTP(URL \\'{url}\\' FORMAT \\'TabSeparated\\' CREDENTIALS (USER \\'huser\\' PASSWORD \\'{secret}\\'))) LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())\n" ) ) @@ -919,11 +919,11 @@ def test_create_dictionary(): "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", "CREATE DICTIONARY dict2 (`n` int DEFAULT 0) PRIMARY KEY n " - "SOURCE(HTTP(URL 'http://localhost:8123/dict.tsv' FORMAT 'TabSeparated' USER 'huser' PASSWORD '[HIDDEN]')) " + "SOURCE(HTTP(URL '[HIDDEN]' FORMAT 'TabSeparated' USER 'huser' PASSWORD '[HIDDEN]')) " "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", "CREATE DICTIONARY dict3 (`n` int DEFAULT 0) PRIMARY KEY n " - "SOURCE(HTTP(URL 'http://localhost:8123/dict.tsv' FORMAT 'TabSeparated' CREDENTIALS (USER 'huser' PASSWORD '[HIDDEN]'))) " + "SOURCE(HTTP(URL '[HIDDEN]' FORMAT 'TabSeparated' CREDENTIALS (USER 'huser' PASSWORD '[HIDDEN]'))) " "LIFETIME(MIN 0 MAX 10) LAYOUT(FLAT())", ], must_not_contain=[password], diff --git a/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml b/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml index 210be774bda9..4c0dcd49270b 100644 --- a/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml +++ b/tests/integration/test_merge_tree_s3/configs/config.d/storage_conf.xml @@ -174,8 +174,4 @@ 131072 11 - - 0 - 60 - 1 diff --git a/tests/integration/test_partition/test.py b/tests/integration/test_partition/test.py index 5eb6eee9055f..c8e03826b798 100644 --- a/tests/integration/test_partition/test.py +++ b/tests/integration/test_partition/test.py @@ -91,11 +91,12 @@ def partition_complex_assert_checksums(after_detach=False): checksums = ( "082814b5aa5109160d5c0c5aff10d4df\tshadow/1/data/test/partition_complex/19700102_2_2_0/k.bin\n" "082814b5aa5109160d5c0c5aff10d4df\tshadow/1/data/test/partition_complex/19700201_1_1_0/v1.bin\n" + "098dd565871f350b60a234b8d50ded04\tshadow/1/data/test/partition_complex/19700201_1_1_0/checksums.txt\n" "13cae8e658e0ca4f75c56b1fc424e150\tshadow/1/data/test/partition_complex/19700102_2_2_0/minmax_p.idx\n" "25daad3d9e60b45043a70c4ab7d3b1c6\tshadow/1/data/test/partition_complex/19700102_2_2_0/partition.dat\n" "3726312af62aec86b64a7708d5751787\tshadow/1/data/test/partition_complex/19700201_1_1_0/partition.dat\n" - "37855b06a39b79a67ea4e86e4a3299aa\tshadow/1/data/test/partition_complex/19700102_2_2_0/checksums.txt\n" "38e62ff37e1e5064e9a3f605dfe09d13\tshadow/1/data/test/partition_complex/19700102_2_2_0/v1.bin\n" + "3bcd3a70bec37bb8378ad42e1a5cb2e1\tshadow/1/data/test/partition_complex/19700102_2_2_0/checksums.txt\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/k.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/p.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/v1.mrk\n" @@ -103,7 +104,6 @@ def partition_complex_assert_checksums(after_detach=False): "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700201_1_1_0/p.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700201_1_1_0/v1.mrk\n" "55a54008ad1ba589aa210d2629c1df41\tshadow/1/data/test/partition_complex/19700201_1_1_0/primary.idx\n" - "5f087cb3e7071bf9407e095821e2af8f\tshadow/1/data/test/partition_complex/19700201_1_1_0/checksums.txt\n" "77d5af402ada101574f4da114f242e02\tshadow/1/data/test/partition_complex/19700102_2_2_0/columns.txt\n" "77d5af402ada101574f4da114f242e02\tshadow/1/data/test/partition_complex/19700201_1_1_0/columns.txt\n" "7e1a7e6aeff3a879f5787bbddd6553eb\tshadow/1/data/test/partition_complex/19700102_2_2_0/columns_substreams.txt\n" @@ -122,11 +122,12 @@ def partition_complex_assert_checksums(after_detach=False): checksums = ( "082814b5aa5109160d5c0c5aff10d4df\tshadow/1/data/test/partition_complex/19700102_2_2_0/k.bin\n" "082814b5aa5109160d5c0c5aff10d4df\tshadow/1/data/test/partition_complex/19700201_1_1_0/v1.bin\n" + "098dd565871f350b60a234b8d50ded04\tshadow/1/data/test/partition_complex/19700201_1_1_0/checksums.txt\n" "13cae8e658e0ca4f75c56b1fc424e150\tshadow/1/data/test/partition_complex/19700102_2_2_0/minmax_p.idx\n" "25daad3d9e60b45043a70c4ab7d3b1c6\tshadow/1/data/test/partition_complex/19700102_2_2_0/partition.dat\n" "3726312af62aec86b64a7708d5751787\tshadow/1/data/test/partition_complex/19700201_1_1_0/partition.dat\n" - "37855b06a39b79a67ea4e86e4a3299aa\tshadow/1/data/test/partition_complex/19700102_2_2_0/checksums.txt\n" "38e62ff37e1e5064e9a3f605dfe09d13\tshadow/1/data/test/partition_complex/19700102_2_2_0/v1.bin\n" + "3bcd3a70bec37bb8378ad42e1a5cb2e1\tshadow/1/data/test/partition_complex/19700102_2_2_0/checksums.txt\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/k.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/p.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700102_2_2_0/v1.mrk\n" @@ -134,7 +135,6 @@ def partition_complex_assert_checksums(after_detach=False): "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700201_1_1_0/p.mrk\n" "4ae71336e44bf9bf79d2752e234818a5\tshadow/1/data/test/partition_complex/19700201_1_1_0/v1.mrk\n" "55a54008ad1ba589aa210d2629c1df41\tshadow/1/data/test/partition_complex/19700201_1_1_0/primary.idx\n" - "5f087cb3e7071bf9407e095821e2af8f\tshadow/1/data/test/partition_complex/19700201_1_1_0/checksums.txt\n" "77d5af402ada101574f4da114f242e02\tshadow/1/data/test/partition_complex/19700102_2_2_0/columns.txt\n" "77d5af402ada101574f4da114f242e02\tshadow/1/data/test/partition_complex/19700201_1_1_0/columns.txt\n" "7e1a7e6aeff3a879f5787bbddd6553eb\tshadow/1/data/test/partition_complex/19700102_2_2_0/columns_substreams.txt\n" diff --git a/tests/integration/test_postgresql_kill_query/test.py b/tests/integration/test_postgresql_kill_query/test.py index 000fc5e8f7d2..78bc325ac0ca 100644 --- a/tests/integration/test_postgresql_kill_query/test.py +++ b/tests/integration/test_postgresql_kill_query/test.py @@ -1,5 +1,7 @@ import pytest import socket +import struct +from contextlib import contextmanager import uuid import threading import time @@ -196,7 +198,7 @@ class StatementStallingProxy: constructor, before `onStart` has published `tx`. Stalling the `COPY` pins it one step later, inside `pqxx::stream_from`'s constructor, with `tx` published and still no statement running on the connection. Those are the two startup windows in which a cancel - finds nothing to interrupt. + request to the server finds no statement to interrupt. `skip` exists because the source's transaction is not the only one on the wire. Reading through `postgresql()` without an explicit column list first fetches the table structure, @@ -314,6 +316,118 @@ def stop(self): t.join(timeout=5) +class ResponseStallingProxy(StatementStallingProxy): + """Forwards the `CopyOutResponse` and withholds every row after it, keeping both sockets open. + The source is then blocked in `read_row()` with nothing buffered to drain. + """ + + def __init__(self): + super().__init__(marker=StatementStallingProxy.COPY) + self._copy_sent = threading.Event() + + def _pump(self, source, destination, is_client_to_server): + carry = b"" + buf = bytearray() + stalled_once = False + while not self._stop: + try: + data = source.recv(4096) + except socket.timeout: + continue + except OSError: + break + if not data: + break + + try: + if is_client_to_server: + if not self._copy_sent.is_set() and self._marker in carry + data: + self._copy_sent.set() + carry = (carry + data)[-(len(self._marker) - 1) :] + destination.sendall(data) + continue + + if stalled_once or not self._copy_sent.is_set(): + destination.sendall(data) + continue + + # The response starts at a message boundary. Forward its first message only. + buf += data + if len(buf) < 5 or len(buf) < 1 + int.from_bytes(buf[1:5], "big"): + continue + first = 1 + int.from_bytes(buf[1:5], "big") + destination.sendall(bytes(buf[:first])) + stalled_once = True + self._stalled.set() + self._release.wait(timeout=60) + destination.sendall(bytes(buf[first:])) + except OSError: + break + + for s in (source, destination): + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + +class CancelResettingProxy(StatementStallingProxy): + """Forwards the wire protocol. When a cancel request arrives, it first resets the client's other + connections with a TCP RST and only then forwards the cancel, so the reading thread sees its + connection fail instead of the server's reply.""" + + CANCEL_REQUEST = struct.pack("!ii", 16, 80877102) + + def __init__(self): + super().__init__() + self._reset = threading.Event() + self._reset_done = threading.Event() + + def connection_was_reset(self): + return self._reset_done.is_set() + + def _pump(self, source, destination, is_client_to_server): + head = b"" + decided = not is_client_to_server + is_cancel = False + while not self._stop: + try: + data = source.recv(4096) + except socket.timeout: + if decided and is_client_to_server and not is_cancel and self._reset.is_set(): + source.setsockopt( + socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0) + ) + source.close() + self._reset_done.set() + break + continue + except OSError: + break + if not data: + break + if not decided: + head += data + if len(head) < len(self.CANCEL_REQUEST): + continue + decided = True + data, head = head, b"" + if data.startswith(self.CANCEL_REQUEST): + is_cancel = True + self._reset.set() + self._reset_done.wait(timeout=30) + try: + destination.sendall(data) + except OSError: + break + + for s in (source, destination): + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def test_kill_query_while_transaction_is_starting(started_cluster, setup_infinite_query): """A cancel arriving while the transaction is still being constructed must not be lost. @@ -411,12 +525,9 @@ def test_kill_query_while_copy_is_starting(started_cluster, setup_streaming_view """A cancel arriving after the transaction is published but before the COPY starts must not be lost either. - This is one step later than `test_kill_query_while_transaction_is_starting`. Here `tx` is - already published, so `onCancel` does call `cancel_query()` -- but no statement is running - on that connection yet, so PostgreSQL has nothing to interrupt and the cancel is dropped. - `onStart` opens the COPY straight afterwards, so the destructor has to be the one that - cancels it. If a cancel could take the teardown away from it, nothing would, and the - rollback would sit waiting for the COPY. + This is one step later than `test_kill_query_while_transaction_is_starting`: `tx` is + published but no statement runs yet, so a cancel request to the server would be dropped. + The failed `COPY` start must still surface as a cancellation, not a transport error. Stalling the COPY request rather than the `BEGIN` is what places the cancel in this window; `test_kill_query_while_transaction_is_starting` cannot reach it, because there @@ -468,22 +579,13 @@ def execute_query(): sleep_time=0.5, ) + # Delivered while the COPY is still withheld, so the connection has no statement in + # progress. The query ends at once, so there is no cancelled state to observe. node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC") - # Deliver the cancel while the COPY is still withheld, so that `onCancel` runs - # against a connection with no statement in progress. - assert_eq_with_retry( - node1, - f"SELECT is_cancelled FROM system.processes WHERE query_id='{query_id}'", - "1", - retry_count=60, - sleep_time=0.5, - ) finally: proxy.release() - # Once the COPY reaches the server the read has to be abandoned. Without the fix the - # dropped cancel leaves the source streaming the view to its end, so this join times - # out. + # Without the fix the dropped cancel leaves the source streaming to the end of the view. query_thread.join(timeout=60) assert ( not query_thread.is_alive() @@ -505,6 +607,131 @@ def execute_query(): assert not query_thread.is_alive(), "query thread outlived the test" +@contextmanager +def stalled_postgres_table(started_cluster, table): + """An engine table read through a `ResponseStallingProxy`. Released and dropped on exit.""" + proxy = ResponseStallingProxy() + port = proxy.start((started_cluster.postgres_ip, started_cluster.postgres_port)) + proxy_host = socket.gethostbyname(socket.gethostname()) + node1.query(f"DROP TABLE IF EXISTS {table}") + node1.query( + f"""CREATE TABLE {table} (counter Nullable(Int32)) +ENGINE = PostgreSQL( + '{proxy_host}:{port}', + 'postgres_database', + 'streaming_counter', + 'postgres', + 'ClickHouse_PostgreSQL_P@ssw0rd')""" + ) + try: + yield proxy + finally: + proxy.stop() + node1.query(f"DROP TABLE IF EXISTS {table}") + + +def wait_until_blocked_in_read(proxy, query_id): + proxy.wait_until_stalled() + # Nothing is buffered after `CopyOutResponse`, so from here the source blocks in the read. + node1.wait_for_log_line(f"{query_id}.*Generate a chunk from stream") + + +def test_kill_query_while_the_read_is_stalled(started_cluster, setup_streaming_view): + """A cancel arriving while the COPY is streaming must not wait for the server. + The proxy stays stalled across the kill, so only the transport itself can end the read. + """ + query_id = str(uuid.uuid4()) + query_errors = [] + + with stalled_postgres_table(started_cluster, "read_stalled_counter") as proxy: + + def execute_query(): + _, error = node1.query_and_get_answer_with_error( + "SELECT * FROM read_stalled_counter", query_id=query_id, timeout=120 + ) + query_errors.append(error) + + query_thread = threading.Thread(target=execute_query) + query_thread.start() + try: + wait_until_blocked_in_read(proxy, query_id) + node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC") + + # Still stalled: without the fix the read waits for as long as the peer stays silent. + query_thread.join(timeout=30) + assert ( + not query_thread.is_alive() + ), "cancelled query kept waiting on a silent connection" + assert query_errors and "QUERY_WAS_CANCELLED" in query_errors[0], query_errors + finally: + node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC", ignore_error=True) + query_thread.join(timeout=60) + assert not query_thread.is_alive(), "query thread outlived the test" + + +def test_max_execution_time_while_the_read_is_stalled(started_cluster, setup_streaming_view): + """The deadline is enforced by a background thread and has to end a read the query itself + cannot leave. + """ + query_id = str(uuid.uuid4()) + query_errors = [] + + with stalled_postgres_table(started_cluster, "read_stalled_counter") as proxy: + + def execute_query(): + _, error = node1.query_and_get_answer_with_error( + "SELECT * FROM read_stalled_counter SETTINGS max_execution_time = 5", + query_id=query_id, + timeout=120, + ) + query_errors.append(error) + + query_thread = threading.Thread(target=execute_query) + query_thread.start() + try: + proxy.wait_until_stalled() + + # Still stalled: without the fix the deadline fires, but nothing wakes the read. + query_thread.join(timeout=30) + assert ( + not query_thread.is_alive() + ), "timed-out query kept waiting on a silent connection" + assert query_errors and "TIMEOUT_EXCEEDED" in query_errors[0], query_errors + finally: + node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC", ignore_error=True) + query_thread.join(timeout=60) + assert not query_thread.is_alive(), "query thread outlived the test" + + +def test_drop_refreshable_view_while_the_read_is_stalled(started_cluster, setup_streaming_view): + """Dropping a refreshable view waits for its refresh to stop, so the cancel it sends has to + end a stalled read as well. + """ + with stalled_postgres_table(started_cluster, "read_stalled_counter") as proxy: + node1.query("DROP TABLE IF EXISTS stalled_refresh") + node1.query( + """CREATE MATERIALIZED VIEW stalled_refresh REFRESH EVERY 1 HOUR +ENGINE = MergeTree ORDER BY tuple() EMPTY AS SELECT * FROM read_stalled_counter""" + ) + try: + node1.query("SYSTEM REFRESH VIEW stalled_refresh") + + # The refresh is the only query reading the table. + refresh_query = ( + "SELECT query_id FROM system.processes " + "WHERE query LIKE '%read_stalled_counter%' AND query NOT LIKE '%system.processes%'" + ) + assert_eq_with_retry( + node1, f"SELECT count() FROM ({refresh_query})", "1", retry_count=60, sleep_time=0.5 + ) + wait_until_blocked_in_read(proxy, node1.query(refresh_query).strip()) + + # Still stalled: without the fix the drop waits for the refresh, which waits for the peer. + node1.query("DROP TABLE stalled_refresh", timeout=30) + finally: + node1.query("DROP TABLE IF EXISTS stalled_refresh") + + def test_kill_query_when_postgresql_cancel_connection_fails( started_cluster, setup_sleepy_view ): @@ -546,14 +773,21 @@ def execute_query(): ) wait_for_port_forward_connection(port_forward) - # Keep the active `postgresql` data connection open, but refuse the separate - # `pqxx::connection::cancel_query` connection opened by `KILL QUERY`. + # Keep the data connection open but refuse new ones: the cancel request fails, and the + # kill has to get by without it. port_forward.stop() wait_for_proxy_listener_closed(proxy_host, port) node1.query(f"KILL QUERY WHERE query_id='{query_id}'") node1.wait_for_log_line("PQcancel\\(\\) -- connect\\(\\) failed", timeout=30) + assert_eq_with_retry( + node1, + f"SELECT count() FROM system.processes WHERE query_id='{query_id}'", + "0", + retry_count=60, + sleep_time=0.5, + ) assert node1.query("SELECT 1").strip() == "1" finally: port_forward.stop(force=True) @@ -561,7 +795,57 @@ def execute_query(): query_thread.join(timeout=30) assert not query_thread.is_alive() assert not query_exceptions - assert query_errors + assert query_errors and "QUERY_WAS_CANCELLED" in query_errors[0], query_errors + + +def test_kill_query_when_the_connection_resets_during_the_cancel( + started_cluster, setup_infinite_query +): + """The connection fails while the cancel request is in flight, so the reading thread drops the + connection itself while the cancelling thread is still cancelling.""" + proxy = CancelResettingProxy() + port = proxy.start((started_cluster.postgres_ip, started_cluster.postgres_port)) + proxy_host = socket.gethostbyname(socket.gethostname()) + query_id = str(uuid.uuid4()) + query_errors = [] + + # A declared structure keeps the read the only connection. `infinite_counter` never answers + # the COPY, so the reading thread stays inside `stream_from`'s constructor. + node1.query("DROP TABLE IF EXISTS reset_counter") + node1.query( + f"""CREATE TABLE reset_counter (counter Nullable(Int32)) +ENGINE = PostgreSQL( + '{proxy_host}:{port}', + 'postgres_database', + 'infinite_counter', + 'postgres', + 'ClickHouse_PostgreSQL_P@ssw0rd')""" + ) + + def execute_query(): + _, error = node1.query_and_get_answer_with_error( + "SELECT * FROM reset_counter", query_id=query_id, timeout=120 + ) + query_errors.append(error) + + query_thread = threading.Thread(target=execute_query) + query_thread.start() + + try: + node1.wait_for_log_line(f"{query_id}.*Stream data from database") + node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC") + + query_thread.join(timeout=60) + assert not query_thread.is_alive(), "cancelled query kept running" + assert query_errors and "QUERY_WAS_CANCELLED" in query_errors[0], query_errors + assert proxy.connection_was_reset(), "the cancel arrived without the data connection being reset" + assert node1.query("SELECT 1").strip() == "1" + finally: + node1.query(f"KILL QUERY WHERE query_id='{query_id}' ASYNC", ignore_error=True) + proxy.stop() + query_thread.join(timeout=60) + node1.query("DROP TABLE IF EXISTS reset_counter") + assert not query_thread.is_alive(), "query thread outlived the test" def test_kill_infinite_query(setup_infinite_query): diff --git a/tests/integration/test_readonly_restricts_set_role/test.py b/tests/integration/test_readonly_restricts_set_role/test.py index c36af86fa720..a640267ad01f 100644 --- a/tests/integration/test_readonly_restricts_set_role/test.py +++ b/tests/integration/test_readonly_restricts_set_role/test.py @@ -25,6 +25,11 @@ def started_cluster(): "CREATE USER probe IDENTIFIED WITH plaintext_password BY 'x';" "GRANT ro_role, other_role TO probe;" "ALTER USER probe DEFAULT ROLE ro_role;" + # A separate user for `SET DEFAULT ROLE`, so that the cases changing its default roles + # do not affect the ones above, which expect `probe` to start with `ro_role`. + "CREATE USER default_role_probe IDENTIFIED WITH plaintext_password BY 'x';" + "GRANT ro_role, other_role TO default_role_probe;" + "ALTER USER default_role_probe DEFAULT ROLE ro_role;" ) yield cluster @@ -114,3 +119,44 @@ def post(sql, **extra): answer, error = post("SELECT currentRoles()") assert error is None assert answer.strip() == "['ro_role']" + + +def default_roles(node): + return node.query( + "SELECT default_roles_list FROM system.users WHERE name = 'default_role_probe'" + ).strip() + + +@pytest.mark.parametrize( + "readonly, statement", + [ + # `TO CURRENT_USER` requires no grant, so it is not refused by the access check. + (1, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL TO CURRENT_USER"), + (1, "SET DEFAULT ROLE ALL EXCEPT ro_role TO CURRENT_USER"), + (1, "SET DEFAULT ROLE NONE TO CURRENT_USER"), + (2, "SET DEFAULT ROLE other_role TO CURRENT_USER"), + ], +) +def test_set_default_role_refused_when_enabled(readonly, statement): + _, error = node_on.query_and_get_answer_with_error( + statement, user="default_role_probe", password="x", settings={"readonly": readonly} + ) + assert "READONLY" in error + assert default_roles(node_on) == "['ro_role']" + # The next session starts with the same role. + answer = node_on.query( + "SELECT currentRoles()", user="default_role_probe", password="x" + ) + assert answer.strip() == "['ro_role']" + + +def test_set_default_role_allowed_at_default_settings(): + _, error = node_off.query_and_get_answer_with_error( + "SET DEFAULT ROLE other_role TO CURRENT_USER", + user="default_role_probe", + password="x", + settings={"readonly": 1}, + ) + assert error == "" + assert default_roles(node_off) == "['other_role']" diff --git a/tests/integration/test_replicated_database/test.py b/tests/integration/test_replicated_database/test.py index e3d4e5230101..199905efa9ec 100644 --- a/tests/integration/test_replicated_database/test.py +++ b/tests/integration/test_replicated_database/test.py @@ -1839,6 +1839,7 @@ def test_sync_database_replica_strict(started_cluster): # DEFAULT: needs the frozen snapshot fully processed -> times out. default_error = dummy_node.http_query_and_get_error( "system sync database replica strict_sync", + method="POST", params=sync_params, timeout=60, ) @@ -1851,6 +1852,7 @@ def test_sync_database_replica_strict(started_cluster): # the guard). dummy_node.http_query( "system sync database replica strict_sync strict", + method="POST", params=sync_params, timeout=60, ) diff --git a/tests/integration/test_scheduler_io/test.py b/tests/integration/test_scheduler_io/test.py index 579b655179d6..690ec30da45b 100644 --- a/tests/integration/test_scheduler_io/test.py +++ b/tests/integration/test_scheduler_io/test.py @@ -11,6 +11,7 @@ from helpers.client import QueryRuntimeException from helpers.cluster import ClickHouseCluster from helpers.network import PartitionManager +from helpers.test_tools import assert_eq_with_retry cluster = ClickHouseCluster(__file__) @@ -1258,3 +1259,49 @@ def test_config_based_workloads_and_resources(): # Make sure it's possible to clean the config without "Logical error: 'Removing workload 'all' with children" node.query("DROP WORKLOAD development") + + +def test_workload_entity_keeper_storage_session_renewal(): + # A query that renews the expired Keeper session of `node` must not overwrite what `node2` wrote meanwhile + definitions = "select value from system.zookeeper where path = '/clickhouse/workload' and name = 'definitions.sql'" + + def expire_keeper_session_of_node(sync_workload): + # The watching thread of `node` refreshes on this change and then sleeps for up to 10 seconds + node2.query(f"create workload {sync_workload} in all") + assert_eq_with_retry( + node, + f"select count() from system.workloads where name = '{sync_workload}'", + "1", + retry_count=100, + sleep_time=0.1, + ) + # The watch dies with the session, so `node` does not see the next change of `node2` + node.query("system reconnect zookeeper") + + node.query("create workload all; create workload development in all") + try: + assert_eq_with_retry( + node2, + "select count() from system.workloads where name = 'development'", + "1", + retry_count=100, + sleep_time=0.1, + ) + + expire_keeper_session_of_node("admin") + node2.query("create workload production in development") + assert "cannot be dropped" in node.query_and_get_error( + "drop workload development" + ) + assert "production" in node2.query(definitions) + + expire_keeper_session_of_node("prod_merges") + node2.query("create workload dev_merges in all") + node.query("create workload prod_mutations in all") + result = node2.query(definitions) + assert "dev_merges" in result and "prod_mutations" in result + finally: + node.query( + "drop workload if exists prod_mutations; drop workload if exists dev_merges; drop workload if exists prod_merges; " + "drop workload if exists production; drop workload if exists admin; drop workload if exists development; drop workload if exists all" + ) diff --git a/tests/integration/test_store_cleanup/__init__.py b/tests/integration/test_serialization_kind_stack_validation/__init__.py similarity index 100% rename from tests/integration/test_store_cleanup/__init__.py rename to tests/integration/test_serialization_kind_stack_validation/__init__.py diff --git a/tests/integration/test_serialization_kind_stack_validation/configs/backups_disk.xml b/tests/integration/test_serialization_kind_stack_validation/configs/backups_disk.xml new file mode 100644 index 000000000000..f7d666c65426 --- /dev/null +++ b/tests/integration/test_serialization_kind_stack_validation/configs/backups_disk.xml @@ -0,0 +1,14 @@ + + + + + local + /backups/ + + + + + backups + /backups/ + + diff --git a/tests/integration/test_serialization_kind_stack_validation/test.py b/tests/integration/test_serialization_kind_stack_validation/test.py new file mode 100644 index 000000000000..4d6b303b6ced --- /dev/null +++ b/tests/integration/test_serialization_kind_stack_validation/test.py @@ -0,0 +1,284 @@ +# A part can have only the serialization kinds Default and Sparse in `serialization.json`. +# A part or a backup with another kind stack must not load, and the server must stay alive. +# +# The test edits files of parts and backups on disk, so it is an integration test. +# Each edit keeps the length of `serialization.json`: then `checksums.txt` of the part and the +# `.backup` metadata stay valid, because the server checks only the sizes of these files. +# Thus the test does not depend on the names of the column files. + +import base64 +import json + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) +node = cluster.add_instance( + "node", main_configs=["configs/backups_disk.xml"], stay_alive=True +) + +SPARSE_OVER_SPARSE_ERROR = "Serialization kind Sparse is out of order in a kind stack: While checking serialization info of column 's'" +DETACHED_MAP_ERROR = "Unexpected serialization kind Detached in the received data: While checking serialization info of column 'm'" + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def exec_root(cmd): + return node.exec_in_container(["bash", "-c", cmd], privileged=True, user="root") + + +def set_s_kind(kind): + def edit(columns): + for entry in columns: + if entry["name"] == "s": + entry["kind"] = kind + return columns + + return edit + + +def set_m_kind(kind): + # The entry of `k` goes away to keep the file length. A column without an entry is Default. + def edit(columns): + columns = [entry for entry in columns if entry["name"] != "k"] + columns.append({"kind": kind, "name": "m", "num_defaults": 0, "num_rows": 100}) + return columns + + return edit + + +BAD_EDITS = [ + pytest.param( + "sparse_over_sparse", + set_s_kind("SparseOverSparse"), + SPARSE_OVER_SPARSE_ERROR, + id="sparse_over_sparse", + ), + pytest.param( + "detached_map", set_m_kind("Detached"), DETACHED_MAP_ERROR, id="detached_map" + ), +] + +# The same edits with a valid kind. They must load, so the bad edits fail only because of the kind stack. +VALID_EDITS = [ + pytest.param("sparse", set_s_kind("Sparse"), id="sparse"), + pytest.param("default_map", set_m_kind("Default"), id="default_map"), +] + + +def edit_serialization_json(path, edit): + old = base64.b64decode(exec_root(f"base64 -w0 {path}")).decode() + info = json.loads(old) + # `exact_num_defaults` is only a hint. Without it, there is space for longer kind names. + for entry in info["columns"]: + entry.pop("exact_num_defaults", None) + info["columns"] = edit(info["columns"]) + new = json.dumps(info, separators=(",", ":")) + assert len(new) <= len(old), (old, new) + new = new[:-1] + " " * (len(old) - len(new)) + "}" + + # Write a new file and do not change the old one: a file of a backup can be a hard link to a file of a table. + encoded = base64.b64encode(new.encode()).decode() + exec_root( + f"echo {encoded} | base64 -d > {path}.tmp && chown --reference={path} {path}.tmp " + f"&& chmod --reference={path} {path}.tmp && mv {path}.tmp {path}" + ) + assert base64.b64decode(exec_root(f"base64 -w0 {path}")).decode() == new + + +def create_table(table, num_parts): + # Each INSERT makes one Wide part in full storage, so `serialization.json` is a file. + # Most values of `s` are 0, so `s` is Sparse. + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query(f""" + CREATE TABLE {table} (k UInt64, s UInt64, m Map(String, UInt64)) + ENGINE = MergeTree ORDER BY k + SETTINGS storage_policy = 'default', min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, + ratio_of_defaults_for_sparse_serialization = 0.5 + """) + node.query(f"SYSTEM STOP MERGES {table}") + for i in range(num_parts): + node.query( + f"INSERT INTO {table} SELECT number + {i * 100}, if(number % 10 = 0, number, 0), map('a', number + {i * 1000}) FROM numbers(100)" + ) + + database, name = split_name(table) + assert ( + node.query( + f"SELECT DISTINCT column, serialization_kind FROM system.parts_columns " + f"WHERE database = '{database}' AND table = '{name}' AND active AND column IN ('m', 's') ORDER BY column" + ) + == "m\tDefault\ns\tSparse\n" + ) + return node.query( + f"SELECT name FROM system.parts WHERE database = '{database}' AND table = '{name}' AND active ORDER BY name" + ).split() + + +def split_name(table): + return table.split(".") if "." in table else ("default", table) + + +def totals(*parts): + # The expected `count(), sum(s), sum(m.key_a), sum(m['a'])` for the parts with these numbers. + count = 100 * len(parts) + sum_m = sum(4950 + 100000 * i for i in parts) + return f"{count}\t{450 * len(parts)}\t{sum_m}\t{sum_m}\n" + + +def select_totals(table): + return node.query(f"SELECT count(), sum(s), sum(m.key_a), sum(m['a']) FROM {table}") + + +def check_server_is_alive(): + assert node.query("SELECT 1") == "1\n" + for text in ("Logical error", "LOGICAL_ERROR", "Received signal"): + assert not node.contains_in_log(text), f"'{text}' is in the server log" + + +@pytest.mark.parametrize("name, edit, error", BAD_EDITS) +def test_attach_part_with_bad_kind_stack(started_cluster, name, edit, error): + table = f"t_attach_{name}" + bad_part, _ = create_table(table, 2) + node.query(f"ALTER TABLE {table} DETACH PART '{bad_part}'") + path = node.query( + f"SELECT path FROM system.detached_parts WHERE database = 'default' AND table = '{table}' AND name = '{bad_part}'" + ).strip() + edit_serialization_json(f"{path}/serialization.json", edit) + + message = node.query_and_get_error(f"ALTER TABLE {table} ATTACH PART '{bad_part}'") + assert "INCORRECT_DATA" in message and error in message, message + + # The part stays in `detached`, and the reads see only the other part. + assert ( + node.query( + f"SELECT name FROM system.detached_parts WHERE database = 'default' AND table = '{table}'" + ).strip() + == bad_part + ) + assert select_totals(table) == totals(1) + node.query(f"DROP TABLE {table} SYNC") + check_server_is_alive() + + +@pytest.mark.parametrize("name, edit", VALID_EDITS) +def test_attach_part_with_valid_edit(started_cluster, name, edit): + table = f"t_attach_valid_{name}" + part, _ = create_table(table, 2) + node.query(f"ALTER TABLE {table} DETACH PART '{part}'") + path = node.query( + f"SELECT path FROM system.detached_parts WHERE database = 'default' AND table = '{table}' AND name = '{part}'" + ).strip() + edit_serialization_json(f"{path}/serialization.json", edit) + + node.query(f"ALTER TABLE {table} ATTACH PART '{part}'") + assert select_totals(table) == totals(0, 1) + node.query(f"DROP TABLE {table} SYNC") + check_server_is_alive() + + +def test_bad_parts_on_startup(started_cluster): + table = "t_startup" + sparse_part, map_part, good_part = create_table(table, 3) + paths = dict( + line.split("\t") + for line in node.query( + f"SELECT name, path FROM system.parts WHERE database = 'default' AND table = '{table}' AND active" + ).splitlines() + ) + + node.stop_clickhouse() + edit_serialization_json( + f"{paths[sparse_part]}/serialization.json", set_s_kind("SparseOverSparse") + ) + edit_serialization_json( + f"{paths[map_part]}/serialization.json", set_m_kind("Detached") + ) + node.start_clickhouse() + + # The table loads without the bad parts, and they go to `detached` as broken. + assert node.query( + f"SELECT name, reason FROM system.detached_parts WHERE database = 'default' AND table = '{table}' ORDER BY name" + ) == "".join( + f"broken-on-start_{part}\tbroken-on-start\n" + for part in sorted([sparse_part, map_part]) + ) + assert ( + node.query( + f"SELECT name FROM system.parts WHERE database = 'default' AND table = '{table}' AND active" + ).strip() + == good_part + ) + assert select_totals(table) == totals(2) + node.query(f"DROP TABLE {table} SYNC") + check_server_is_alive() + + +def make_edited_backup(backup, edit): + node.query("DROP DATABASE IF EXISTS db_kind_src SYNC") + node.query("CREATE DATABASE db_kind_src") + create_table("db_kind_src.tab", 1) + exec_root(f"rm -rf /backups/{backup}") + node.query(f"BACKUP DATABASE db_kind_src TO Disk('backups', '{backup}')") + node.query("DROP DATABASE db_kind_src SYNC") + + paths = exec_root(f"find /backups/{backup} -name serialization.json").split() + assert len(paths) == 1, paths + # The `.backup` metadata keeps the old checksum: the server uses it only to find the file, and does not check the data. + edit_serialization_json(paths[0], edit) + + +@pytest.mark.parametrize("name, edit, error", BAD_EDITS) +def test_backup_with_bad_kind_stack(started_cluster, name, edit, error): + backup = f"kind_{name}" + make_edited_backup(backup, edit) + + node.query("DROP DATABASE IF EXISTS db_kind_restored SYNC") + message = node.query_and_get_error( + f"RESTORE DATABASE db_kind_src AS db_kind_restored FROM Disk('backups', '{backup}')" + ) + # In this release, RESTORE reports the error of the part as it is. + assert "INCORRECT_DATA" in message and error in message, message + node.query("DROP DATABASE IF EXISTS db_kind_restored SYNC") + + # A `Backup` database reads the parts from the backup. The bad part does not load. + node.query("DROP DATABASE IF EXISTS db_kind_backup SYNC") + node.query( + f"CREATE DATABASE db_kind_backup ENGINE = Backup('db_kind_src', Disk('backups', '{backup}'))" + ) + assert select_totals("db_kind_backup.tab") == "0\t0\t0\t0\n" + broken = node.grep_in_log("is broken and needs manual correction") + assert any( + "db_kind_backup.tab" in line and error in line for line in broken.splitlines() + ), broken + node.query("DROP DATABASE db_kind_backup SYNC") + check_server_is_alive() + + +@pytest.mark.parametrize("name, edit", VALID_EDITS) +def test_backup_with_valid_edit(started_cluster, name, edit): + backup = f"kind_valid_{name}" + make_edited_backup(backup, edit) + + node.query("DROP DATABASE IF EXISTS db_kind_restored SYNC") + node.query( + f"RESTORE DATABASE db_kind_src AS db_kind_restored FROM Disk('backups', '{backup}')" + ) + assert select_totals("db_kind_restored.tab") == totals(0) + node.query("DROP DATABASE db_kind_restored SYNC") + + node.query("DROP DATABASE IF EXISTS db_kind_backup SYNC") + node.query( + f"CREATE DATABASE db_kind_backup ENGINE = Backup('db_kind_src', Disk('backups', '{backup}'))" + ) + assert select_totals("db_kind_backup.tab") == totals(0) + node.query("DROP DATABASE db_kind_backup SYNC") + check_server_is_alive() diff --git a/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml new file mode 100644 index 000000000000..7f6c26058269 --- /dev/null +++ b/tests/integration/test_storage_kerberized_kafka/configs/named_collections.xml @@ -0,0 +1,25 @@ + + + + + kerberized_kafka1:19092 + kafka_json_as_string_named_collection + 1 + kafka_json_as_string_named_collection + JSONAsString + 1000 + + SASL_PLAINTEXT + GSSAPI + kafka + /tmp/keytab/clickhouse.keytab + anotherkafkauser/instance@TEST.CLICKHOUSE.TECH + security + false + + + + diff --git a/tests/integration/test_storage_kerberized_kafka/test.py b/tests/integration/test_storage_kerberized_kafka/test.py index 1056a36e617d..c8fcd6e3d2e6 100644 --- a/tests/integration/test_storage_kerberized_kafka/test.py +++ b/tests/integration/test_storage_kerberized_kafka/test.py @@ -15,7 +15,7 @@ cluster = ClickHouseCluster(__file__) instance = cluster.add_instance( "instance", - main_configs=["configs/kafka.xml"], + main_configs=["configs/kafka.xml", "configs/named_collections.xml"], user_configs=["configs/users.xml"], with_kerberized_kafka=True, clickhouse_path_dir="clickhouse_path", @@ -235,7 +235,9 @@ def test_kafka_json_as_string_no_kdc(kafka_cluster): assert instance.contains_in_log("KerberosInit failure:") -def test_kafka_config_from_sql_named_collection(kafka_cluster): +def test_kafka_config_from_named_collection(kafka_cluster): + # The named collection `kafka_config` is in `configs/named_collections.xml`: a named collection created with SQL + # cannot set `kafka.sasl_kerberos_keytab`, because it is a path on the server. kafka_produce( kafka_cluster, "kafka_json_as_string_named_collection", @@ -247,26 +249,6 @@ def test_kafka_config_from_sql_named_collection(kafka_cluster): ], ) - instance.query( - """ - DROP NAMED COLLECTION IF EXISTS kafka_config; - CREATE NAMED COLLECTION kafka_config AS - kafka.security_protocol = 'SASL_PLAINTEXT', - kafka.sasl_mechanism = 'GSSAPI', - kafka.sasl_kerberos_service_name = 'kafka', - kafka.sasl_kerberos_keytab = '/tmp/keytab/clickhouse.keytab', - kafka.sasl_kerberos_principal = 'anotherkafkauser/instance@TEST.CLICKHOUSE.TECH', - kafka.debug = 'security', - kafka.api_version_request = 'false', - - kafka_broker_list = 'kerberized_kafka1:19092', - kafka_topic_list = 'kafka_json_as_string_named_collection', - kafka_commit_on_select = 1, - kafka_group_name = 'kafka_json_as_string_named_collection', - kafka_format = 'JSONAsString', - kafka_flush_interval_ms=1000; - """ - ) instance.query( """ CREATE TABLE test.kafka (field String) diff --git a/tests/integration/test_storage_mysql/test.py b/tests/integration/test_storage_mysql/test.py index 4599dc4459fb..aa25c21faa72 100644 --- a/tests/integration/test_storage_mysql/test.py +++ b/tests/integration/test_storage_mysql/test.py @@ -1,4 +1,5 @@ import os +import shlex import threading import time from contextlib import contextmanager @@ -1900,6 +1901,91 @@ def test_query_passing_type_mismatch(started_cluster): conn.close() +def test_no_backslash_escapes_sql_mode(started_cluster): + # Generated queries escape string literals with backslashes. With `NO_BACKSLASH_ESCAPES` a quote + # escaped as `\'` would end the literal, and the rest of the value would run as SQL. + conn = get_mysql_conn(started_cluster, cluster.mysql8_ip) + with conn.cursor() as cursor: + cursor.execute("SELECT @@GLOBAL.sql_mode") + global_sql_mode = cursor.fetchone()[0] + cursor.execute("DROP TABLE IF EXISTS clickhouse.nbse_data") + cursor.execute("DROP TABLE IF EXISTS clickhouse.nbse_secret") + cursor.execute("CREATE TABLE clickhouse.nbse_data (k VARCHAR(255) PRIMARY KEY, v VARCHAR(255))") + cursor.execute("CREATE TABLE clickhouse.nbse_secret (s VARCHAR(255))") + cursor.execute("INSERT INTO clickhouse.nbse_data VALUES (0x615C62, 'backslash')") + cursor.execute("INSERT INTO clickhouse.nbse_secret VALUES ('TOP_SECRET')") + cursor.execute("SET GLOBAL sql_mode = CONCAT(@@GLOBAL.sql_mode, ',NO_BACKSLASH_ESCAPES')") + conn.commit() + + source = f"'mysql80:3306', 'clickhouse', 'nbse_data', 'root', '{mysql_pass}'" + leak = "updatexml(1, concat(0x7e, (SELECT s FROM nbse_secret LIMIT 1)), 1)" + try: + node1.query("DROP TABLE IF EXISTS nbse_data") + node1.query("DROP DICTIONARY IF EXISTS nbse_dict") + node1.query(f"CREATE TABLE nbse_data (k String, v String) ENGINE = MySQL({source})") + node1.query( + f"CREATE DICTIONARY nbse_dict (k String, v String DEFAULT 'none') PRIMARY KEY k " + f"SOURCE(MYSQL(HOST 'mysql80' PORT 3306 USER 'root' PASSWORD '{mysql_pass}' DB 'clickhouse' TABLE 'nbse_data')) " + f"LAYOUT(COMPLEX_KEY_DIRECT())" + ) + + assert node1.query(f"SELECT v FROM nbse_data WHERE k = 'x\\' OR {leak} #'") == "" + assert node1.query(f"SELECT v FROM mysql({source}) WHERE k = 'x\\' OR {leak} #'") == "" + assert node1.query(f"SELECT dictGet('nbse_dict', 'v', tuple('x\\' OR {leak}) #'))") == "none\n" + assert node1.query("SELECT v FROM nbse_data WHERE k = 'a\\\\b'") == "backslash\n" + assert node1.query("SELECT dictGet('nbse_dict', 'v', tuple('a\\\\b'))") == "backslash\n" + + node1.query("INSERT INTO nbse_data VALUES ('y\\', (SELECT s FROM nbse_secret)) #', 'a\\\\b\\nc')") + expected = "y', (SELECT s FROM nbse_secret)) #".encode().hex().upper() + "\t" + b"a\\b\nc".hex().upper() + assert node1.query("SELECT hex(k), hex(v) FROM nbse_data WHERE v != 'backslash'") == expected + "\n" + finally: + with conn.cursor() as cursor: + cursor.execute(f"SET GLOBAL sql_mode = '{global_sql_mode}'") + cursor.execute("DROP TABLE IF EXISTS clickhouse.nbse_data") + cursor.execute("DROP TABLE IF EXISTS clickhouse.nbse_secret") + conn.commit() + conn.close() + node1.query("DROP DICTIONARY IF EXISTS nbse_dict") + node1.query("DROP TABLE IF EXISTS nbse_data") + + + +def test_insert_ignores_values_quoting_settings(started_cluster): + # With `output_format_values_escape_quote_with_quote` the `Values` format writes backslashes as is, + # so a value starting with `\'` would end the literal in the `INSERT` sent to MySQL. + conn = get_mysql_conn(started_cluster, cluster.mysql8_ip) + with conn.cursor() as cursor: + cursor.execute("DROP TABLE IF EXISTS clickhouse.quote_sink") + cursor.execute("DROP TABLE IF EXISTS clickhouse.quote_secret") + cursor.execute("CREATE TABLE clickhouse.quote_sink (v VARCHAR(255))") + cursor.execute("CREATE TABLE clickhouse.quote_secret (s VARCHAR(255))") + cursor.execute("INSERT INTO clickhouse.quote_secret VALUES ('TOP_SECRET')") + conn.commit() + + value = "\\' ), ((SELECT s FROM quote_secret)) #" + query = ( + f"INSERT INTO FUNCTION mysql('mysql80:3306', 'clickhouse', 'quote_sink', 'root', '{mysql_pass}') " + r"VALUES ('\\\' ), ((SELECT s FROM quote_secret)) #')" + ) + try: + node1.exec_in_container( + [ + "bash", + "-c", + f"clickhouse local --output_format_values_escape_quote_with_quote=1 --query {shlex.quote(query)}", + ] + ) + with conn.cursor() as cursor: + cursor.execute("SELECT v FROM clickhouse.quote_sink") + assert cursor.fetchall() == ((value,),) + finally: + with conn.cursor() as cursor: + cursor.execute("DROP TABLE IF EXISTS clickhouse.quote_sink") + cursor.execute("DROP TABLE IF EXISTS clickhouse.quote_secret") + conn.commit() + conn.close() + + if __name__ == "__main__": with contextmanager(started_cluster)() as cluster: for name, instance in list(cluster.instances.items()): diff --git a/tests/integration/test_storage_rabbitmq/test.py b/tests/integration/test_storage_rabbitmq/test.py index 6b4f639cc6b4..e46a961590a6 100644 --- a/tests/integration/test_storage_rabbitmq/test.py +++ b/tests/integration/test_storage_rabbitmq/test.py @@ -881,6 +881,93 @@ def onReceived(channel, method, properties, body): rabbitmq_check_result(result, True) +def test_rabbitmq_insert_reuses_producer_connection(rabbitmq_cluster, db, unique): + # With rabbitmq_max_idle_producer_connections an insert publishes over the connection and channel of a previous + # insert instead of connecting to RabbitMQ again. A dedicated vhost isolates the connections of this table. + def rabbitmqctl(*args): + return rabbitmq_cluster.exec_in_container( + rabbitmq_cluster.rabbitmq_docker_id, + ["env", f"RABBITMQ_ERLANG_COOKIE={rabbitmq_cluster.rabbitmq_cookie}", "rabbitmqctl", *args], + ) + + def list_in_vhost(command, *columns): + # The vhost is the first column and the name, which contains spaces, the last one. + rows = [line.split(None, len(columns)) for line in rabbitmqctl("-q", command, "vhost", *columns).splitlines()] + return [tuple(row[1:]) for row in rows if row and row[0] == unique] + + def connections(): + return {name for (name,) in list_in_vhost("list_connections", "name")} + + def confirm_channels(): + # A channel name consists of the connection name and the channel number. + return {name for confirm, name in list_in_vhost("list_channels", "confirm", "name") if confirm == "true"} + + def queued_messages(): + out = rabbitmqctl("-q", "list_queues", "-p", unique, "name", "messages") + rows = [line.split() for line in out.splitlines() if line.strip()] + return sum(int(messages) for name, messages in rows if name == queue_name) + + def wait_for(condition, description): + deadline = time.monotonic() + DEFAULT_TIMEOUT_SEC + while not condition(): + assert time.monotonic() < deadline, description + time.sleep(0.1) + + def insert(key): + instance.query(f"INSERT INTO {db}.rabbitmq VALUES ({key})") + + queue_name = f"{unique}_out" + rabbitmqctl("add_vhost", unique) + try: + rabbitmqctl("set_permissions", "-p", unique, "root", ".*", ".*", ".*") + instance.query( + f""" + CREATE TABLE {db}.rabbitmq (key UInt64) + ENGINE = RabbitMQ + SETTINGS rabbitmq_host_port = 'rabbitmq1:5672', + rabbitmq_vhost = '{unique}', + rabbitmq_exchange_name = '{unique}', + rabbitmq_exchange_type = 'direct', + rabbitmq_routing_key_list = 'insert', + rabbitmq_format = 'JSONEachRow', + rabbitmq_max_idle_producer_connections = 2 + """ + ) + + credentials = pika.PlainCredentials("root", "clickhouse") + connection = pika.BlockingConnection( + pika.ConnectionParameters(rabbitmq_cluster.rabbitmq_ip, rabbitmq_cluster.rabbitmq_port, unique, credentials) + ) + channel = connection.channel() + channel.queue_declare(queue=queue_name) + channel.queue_bind(exchange=unique, queue=queue_name, routing_key="insert") + connection.close() + + # The table keeps its own connection for consumers. + connections_before = connections() + + insert(0) + producer_connections = connections() - connections_before + assert len(producer_connections) == 1, f"expected one idle producer connection, got {producer_connections}" + producer_channels = confirm_channels() + assert len(producer_channels) == 1, f"expected one idle producer channel, got {producer_channels}" + + for key in range(1, 6): + insert(key) + assert connections() - connections_before == producer_connections + assert confirm_channels() == producer_channels + + # The broker closes the idle connection, the next insert must not fail on it. + rabbitmqctl("close_all_connections", "-p", unique, "test") + insert(6) + wait_for(lambda: queued_messages() == 7, "not all messages are in the queue") + + instance.query(f"DROP TABLE {db}.rabbitmq SYNC") + wait_for(lambda: not connections(), "connections are left after the table is dropped") + finally: + rabbitmqctl("delete_vhost", unique) + + def test_rabbitmq_insert_headers_exchange(rabbitmq_cluster, db, unique): instance.query( f""" @@ -963,6 +1050,7 @@ def test_rabbitmq_many_inserts(rabbitmq_cluster, db, unique): rabbitmq_routing_key_list = 'insert2', rabbitmq_flush_interval_ms=1000, rabbitmq_max_block_size=100, + rabbitmq_max_idle_producer_connections = 4, rabbitmq_format = 'TSV', rabbitmq_row_delimiter = '\\n'; CREATE TABLE {db}.rabbitmq_consume (key UInt64, value UInt64) diff --git a/tests/integration/test_storage_s3_queue/test_0.py b/tests/integration/test_storage_s3_queue/test_0.py index 4496aa8b720e..54db82aa863e 100644 --- a/tests/integration/test_storage_s3_queue/test_0.py +++ b/tests/integration/test_storage_s3_queue/test_0.py @@ -86,6 +86,16 @@ def started_cluster(): stay_alive=True, ) + cluster.add_instance( + "instance_old", + with_zookeeper=True, + image="clickhouse/clickhouse-server", + # A release that is no longer supported, so it never gets the source hash in a backport. + tag="26.7", + with_installed_binary=True, + stay_alive=True, + ) + logging.info("Starting cluster...") cluster.start() logging.info("Cluster started") @@ -1156,6 +1166,43 @@ def test_multiple_tables_meta_mismatch(started_cluster): ) +def test_source_hash_after_upgrade(started_cluster): + """A queue that an older version created gets the hash of its source in Keeper after the upgrade.""" + node = started_cluster.instances["instance_old"] + keeper_path = f"/clickhouse/test_upgrade_{generate_random_string()}" + + def create_queue(name, bucket): + return f""" + CREATE TABLE {name} (x String) + ENGINE = S3Queue('http://localhost:11111/{bucket}/upgrade/*', NOSIGN, 'CSV') + SETTINGS mode = 'unordered', keeper_path = '{keeper_path}' + """ + + def get_source_hash(): + return node.query( + f"SELECT JSONExtractString(value, 'source_hash') FROM system.zookeeper " + f"WHERE path = '{keeper_path}' AND name = 'metadata'" + ).strip() + + try: + node.query(create_queue("queue", "test")) + assert get_source_hash() == "" + + node.restart_with_latest_version() + # Tables are loaded in the background, and a query to a table waits until it is loaded. + node.query("DESCRIBE TABLE queue") + assert get_source_hash() != "" + + # Now the source is checked: a queue of another bucket cannot use this `keeper_path`. + error = node.query_and_get_error(create_queue("other", "other")) + assert "differs in source" in error + node.query(create_queue("same", "test")) + finally: + node.query("DROP TABLE IF EXISTS queue SYNC") + node.query("DROP TABLE IF EXISTS same SYNC") + node.restart_with_original_version() + + def test_virtual_columns(started_cluster): start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") node = started_cluster.instances["instance"] diff --git a/tests/integration/test_storage_url/configs/conf.xml b/tests/integration/test_storage_url/configs/conf.xml index 15928bdc44e4..ade42899894a 100644 --- a/tests/integration/test_storage_url/configs/conf.xml +++ b/tests/integration/test_storage_url/configs/conf.xml @@ -37,6 +37,14 @@ + + + + node2 + 9000 + + + diff --git a/tests/integration/test_storage_url/index_pages_server.py b/tests/integration/test_storage_url/index_pages_server.py index bc95198974d2..c43ccf79e11c 100644 --- a/tests/integration/test_storage_url/index_pages_server.py +++ b/tests/integration/test_storage_url/index_pages_server.py @@ -56,6 +56,7 @@ def make_zip_file(entries): "/data/auth_failover/part1.tsv": "23\n", "/data/apache_sort/subdir/part1.tsv": "7\n", "/data/apache_sort/subdir/part2.tsv": "11\n", + "/data/dictionary/data.tsv": "1\tone\n", } SHARD_0_ARCHIVE = make_zip_file([("value.tsv", "101\n")]) @@ -69,10 +70,12 @@ class RequestHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): pass - @classmethod - def _record_request(cls, method, path): + def _record_request(self, method, path): key = f"{method} {path}" - cls.request_counts[key] = cls.request_counts.get(key, 0) + 1 + self.request_counts[key] = self.request_counts.get(key, 0) + 1 + # The requests that carry the header, for the tests of `http_forbid_headers`. + if "Authorization" in self.headers: + self.request_counts["Authorization"] = self.request_counts.get("Authorization", 0) + 1 def _handle_control(self): if self.path == "/__stats__": @@ -366,7 +369,10 @@ def do_GET(self): if path == "/data/cross_origin_redirect/": host = self.headers.get("Host", "resolver:8087").split(":", 1)[0] self.send_response(302) - self.send_header("Location", f"http://{host}:8088/data/cross_origin_target/") + self.send_header( + "Location", + f"http://redirect_user:redirect_pass@{host}:8088/data/cross_origin_target/", + ) self.end_headers() return if path == "/data/redirect_target/": diff --git a/tests/integration/test_storage_url/test.py b/tests/integration/test_storage_url/test.py index f0bbc2824b71..8fe648510427 100644 --- a/tests/integration/test_storage_url/test.py +++ b/tests/integration/test_storage_url/test.py @@ -5,7 +5,7 @@ import json from helpers.cluster import ClickHouseCluster -from helpers.test_tools import TSV +from helpers.test_tools import TSV, assert_eq_with_retry from helpers.mock_servers import start_mock_servers cluster = ClickHouseCluster(__file__) @@ -17,6 +17,8 @@ with_nginx=True, with_minio=True, ) +# The worker of `test_cluster_node2`; `forbidden_authorization` changes only node1's configuration. +node2 = cluster.add_instance("node2", main_configs=["configs/conf.xml"]) @pytest.fixture(scope="module", autouse=True) def setup_node(): @@ -62,6 +64,11 @@ def with_url_wildcard_setting(query): return f"{query} SETTINGS {URL_WILDCARD_EXPERIMENTAL_SETTING}" +def server_part_of_error(error): + # The client appends "(query: ...)" with the query text as sent, credentials included. + return error.split("(query: ")[0] + + def test_partition_by(): result = node1.query( "select * from url('http://nginx:80/test_1', 'TSV', 'column1 UInt32, column2 UInt32, column3 UInt32')" @@ -284,9 +291,12 @@ def test_url_wildcard_missing_listing(): def test_url_wildcard_oversize_index_page(): error = node1.query_and_get_error( - with_url_wildcard_setting("SELECT count() FROM url('http://resolver:8087/data/oversize/**/part*.tsv', 'TSV', 'x UInt64')") + with_url_wildcard_setting("SELECT count() FROM url('http://user:pass@resolver:8087/data/oversize/**/part*.tsv', 'TSV', 'x UInt64')") ) assert "exceeds max_http_index_page_size" in error + server_error = server_part_of_error(error) + assert "user:pass@" not in server_error + assert "'http://[HIDDEN]@resolver:8087/data/oversize/'" in server_error def test_url_wildcard_query_fragment_matching(): @@ -725,6 +735,11 @@ def test_url_wildcard_rejects_cross_origin_index_redirect(): ) ) assert "redirected to a different origin" in error + server_error = server_part_of_error(error) + assert "user:pass@" not in server_error + assert "redirect_pass" not in server_error + assert "'http://[HIDDEN]@resolver:8087/data/cross_origin_redirect/'" in server_error + assert "'http://[HIDDEN]@resolver:8088/data/cross_origin_target/'" in server_error redirect_target_stats = get_index_page_server_stats(8088) assert "GET /data/cross_origin_target/" not in redirect_target_stats @@ -850,3 +865,265 @@ def test_file_formats(file_format): expected_result += f"{i}\t{i + 1}\t{i + 2}\n" assert result == expected_result + + +CONF_PATH = "/etc/clickhouse-server/config.d/conf.xml" +FORBIDDEN_HEADER = "
X-Forbidden-Url-Wildcard
" + + +class forbidden_authorization: + """Forbids the `Authorization` header in `http_forbid_headers` for the duration of the block.""" + + def __enter__(self): + node1.replace_in_config( + CONF_PATH, FORBIDDEN_HEADER, FORBIDDEN_HEADER + "
Authorization
" + ) + node1.query("SYSTEM RELOAD CONFIG") + + def __exit__(self, *args): + node1.replace_in_config(CONF_PATH, "
Authorization
", "") + node1.query("SYSTEM RELOAD CONFIG") + + +def authorization_requests(port=8087): + return get_index_page_server_stats(port).get("Authorization", 0) + + +def assert_authorization_forbidden(error, secret="user:pass"): + assert 'HTTP header "Authorization" is forbidden' in error, error + assert secret not in server_part_of_error(error), error + + +@pytest.mark.parametrize( + "query", + [ + pytest.param( + "SELECT sum(x) FROM url('http://user:pass@resolver:8087/data/2025/part1.tsv', 'TSV', 'x UInt64')", + id="userinfo", + ), + # The first option is unreachable, so the read moves on to the second one. + pytest.param( + "SELECT sum(x) FROM url(" + "'http://127.0.0.1:1/data/2025/part1.tsv|http://user:pass@resolver:8087/data/2025/part1.tsv', " + "'TSV', 'x UInt64') SETTINGS http_max_tries = 1", + id="failover", + ), + # The second option is usable, so the read must not move on to it. + pytest.param( + "SELECT sum(x) FROM url(" + "'http://user:pass@resolver:8087/data/2025/part1.tsv|http://resolver:8087/data/2025/part1.tsv', " + "'TSV', 'x UInt64') SETTINGS http_max_tries = 1", + id="failover_first", + ), + pytest.param( + "SELECT sum(x) FROM urlCluster('test_cluster_two_shards', " + "'http://user:pass@resolver:8087/data/2025/part1.tsv', 'TSV', 'x UInt64')", + id="url_cluster", + ), + pytest.param( + with_url_wildcard_setting( + "SELECT sum(x) FROM url('http://user:pass@resolver:8087/data/2025/part*.tsv', 'TSV', 'x UInt64')" + ), + id="wildcard", + ), + # Requests with the `Authorization` header get 403 there, so the read moves on to the second option. + pytest.param( + with_url_wildcard_setting( + "SELECT sum(x) FROM url('http://{user:pass@resolver:8087|resolver:8087}/data/auth_failover/part*.tsv', " + "'TSV', 'x UInt64')" + ), + id="wildcard_failover_first", + ), + ], +) +def test_url_userinfo_with_forbidden_authorization(query): + # The userinfo is sent as Basic credentials in the `Authorization` header. + reset_index_page_server_stats() + node1.query(query) + assert authorization_requests() > 0 + + reset_index_page_server_stats() + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + assert authorization_requests() == 0 + + +def test_url_cluster_userinfo_refused_by_initiator(): + # node1 refuses the URL before node2, which does not forbid the header, gets it. The userinfo is in the second + # failover option, so the URL as a whole has none. + query = ( + "SELECT sum(x) FROM urlCluster('test_cluster_node2', " + "'http://127.0.0.1:1/data/2025/part1.tsv|http://user:pass@resolver:8087/data/2025/part1.tsv', " + "'TSV', 'x UInt64') SETTINGS http_max_tries = 1" + ) + reset_index_page_server_stats() + assert node1.query(query) == "3\n" + assert authorization_requests() > 0 + + reset_index_page_server_stats() + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + assert authorization_requests() == 0 + + +def test_url_userinfo_without_username_with_forbidden_authorization(): + # Credentials without a username are not sent, so they are not refused. + reset_index_page_server_stats() + with forbidden_authorization(): + assert ( + node1.query("SELECT sum(x) FROM url('http://:pass@resolver:8087/data/2025/part1.tsv', 'TSV', 'x UInt64')") + == "3\n" + ) + assert authorization_requests() == 0 + + +def test_stored_url_wildcard_table_with_forbidden_authorization(): + # A stored table loads after the header is forbidden, but its reads do not send the userinfo. + table_name = "url_wildcard_userinfo" + node1.query(f"DROP TABLE IF EXISTS {table_name}") + node1.query( + f"CREATE TABLE {table_name} (x UInt64) " + "ENGINE = URL('http://user:pass@resolver:8087/data/2025/part*.tsv', 'TSV')", + settings={"allow_experimental_url_wildcard_from_index_pages": 1}, + ) + try: + reset_index_page_server_stats() + assert node1.query(f"SELECT sum(x) FROM {table_name}") == "12\n" + assert authorization_requests() > 0 + + with forbidden_authorization(): + node1.query(f"DETACH TABLE {table_name}") + node1.query(f"ATTACH TABLE {table_name}") + reset_index_page_server_stats() + assert_authorization_forbidden(node1.query_and_get_error(f"SELECT sum(x) FROM {table_name}")) + assert authorization_requests() == 0 + finally: + node1.query(f"DROP TABLE IF EXISTS {table_name}") + + +def test_web_index_disk_userinfo_with_forbidden_authorization(): + # Creating a table on a `web_index` disk probes `format_version.txt` with a HEAD request, before any listing. + table_name = "web_index_userinfo" + query = ( + f"CREATE TABLE {table_name} (x UInt64) ENGINE = MergeTree ORDER BY x " + "SETTINGS disk = disk(type = web, endpoint = 'http://user:pass@resolver:8087/data/web_index_userinfo/', " + "metadata_type = web_index)" + ) + try: + reset_index_page_server_stats() + node1.query(query) + assert authorization_requests() > 0 + node1.query(f"DROP TABLE {table_name} SYNC") + + reset_index_page_server_stats() + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + assert authorization_requests() == 0 + finally: + node1.query(f"DROP TABLE IF EXISTS {table_name} SYNC") + + +def test_url_redirect_userinfo_is_not_sent_with_forbidden_authorization(): + # The redirect has a userinfo in its `Location`, which does not become the credentials of the request. + reset_index_page_server_stats(8088) + with forbidden_authorization(): + node1.query( + "SELECT * FROM url('http://resolver:8087/data/cross_origin_redirect/', 'LineAsString') " + "SETTINGS max_http_get_redirects = 1" + ) + stats = get_index_page_server_stats(8088) + assert stats["GET /data/cross_origin_target/"] > 0 + assert "Authorization" not in stats + + +def test_http_dictionary_credentials_with_forbidden_authorization(): + def create_dictionary(name): + node1.query( + f"CREATE DICTIONARY {name} (id UInt64, name String) PRIMARY KEY id " + "SOURCE(HTTP(url 'http://resolver:8087/data/dictionary/data.tsv' format 'TabSeparated' " + "credentials(user 'user' password 'dict_secret_pw'))) " + "LIFETIME(0) LAYOUT(FLAT())" + ) + + allowed, forbidden = "http_credentials_allowed", "http_credentials_forbidden" + try: + create_dictionary(allowed) + reset_index_page_server_stats() + assert node1.query(f"SELECT dictGet('{allowed}', 'name', toUInt64(1))") == "one\n" + assert authorization_requests() > 0 + + with forbidden_authorization(): + create_dictionary(forbidden) + reset_index_page_server_stats() + assert_authorization_forbidden( + node1.query_and_get_error(f"SELECT dictGet('{forbidden}', 'name', toUInt64(1))"), + secret="dict_secret_pw", + ) + assert authorization_requests() == 0 + finally: + node1.query(f"DROP DICTIONARY IF EXISTS {allowed}") + node1.query(f"DROP DICTIONARY IF EXISTS {forbidden}") + + +def test_loaded_http_dictionary_credentials_with_forbidden_authorization(): + # A loaded dictionary keeps its source across its updates, so the credentials are checked per request. + name = "http_credentials_loaded" + node1.query( + f"CREATE DICTIONARY {name} (id UInt64, name String) PRIMARY KEY id " + "SOURCE(HTTP(url 'http://resolver:8087/data/dictionary/data.tsv' format 'TabSeparated' " + "credentials(user 'user' password 'dict_secret_pw'))) " + "LIFETIME(MIN 1 MAX 1) LAYOUT(FLAT())" + ) + try: + reset_index_page_server_stats() + assert node1.query(f"SELECT dictGet('{name}', 'name', toUInt64(1))") == "one\n" + assert authorization_requests() > 0 + + with forbidden_authorization(): + assert_eq_with_retry( + node1, + f"SELECT last_exception LIKE '%Authorization%is forbidden%' FROM system.dictionaries WHERE name = '{name}'", + "1", + retry_count=60, + sleep_time=0.5, + ) + finally: + node1.query(f"DROP DICTIONARY IF EXISTS {name}") + + +@pytest.mark.parametrize( + "registry_url", + [ + pytest.param("http://user:pass@resolver:8087/", id="userinfo"), + # Without an authority the URL has no userinfo, but the schema is requested from + # `http://user:pass@resolver:8087/schemas/ids/1`, which its path resolves to. + pytest.param("http:http://user:pass@resolver:8087/", id="without_authority"), + ], +) +def test_avro_schema_registry_userinfo_with_forbidden_authorization(registry_url): + # The data is the magic byte and the schema id 1, so the schema is requested. The server has no + # schema registry, so the request fails anyway: only the header it was sent with matters. + query = ( + "SELECT * FROM format(AvroConfluent, 'a UInt8', '\\x00\\x00\\x00\\x00\\x01') " + f"SETTINGS format_avro_schema_registry_url = '{registry_url}'" + ) + reset_index_page_server_stats() + node1.query_and_get_error(query) + assert authorization_requests() > 0 + + reset_index_page_server_stats() + with forbidden_authorization(): + assert_authorization_forbidden(node1.query_and_get_error(query)) + assert authorization_requests() == 0 + + +def test_avro_schema_registry_output_userinfo_with_forbidden_authorization(): + # Writing `AvroConfluent` registers the schema, with the userinfo of the registry URL as Basic credentials. + # Over HTTP the server writes the output, `clickhouse client` would write it itself. + query = ( + "SELECT toInt64(1) AS a FORMAT AvroConfluent " + "SETTINGS format_avro_schema_registry_url = 'http://user:pass@resolver:8087/', " + "output_format_avro_confluent_subject = 'subject'" + ) + with forbidden_authorization(): + assert_authorization_forbidden(node1.http_query_and_get_error(query)) diff --git a/tests/integration/test_store_cleanup/configs/store_cleanup.xml b/tests/integration/test_store_cleanup/configs/store_cleanup.xml deleted file mode 100644 index 5fbe87cce006..000000000000 --- a/tests/integration/test_store_cleanup/configs/store_cleanup.xml +++ /dev/null @@ -1,11 +0,0 @@ - - 0 - 60 - 1 - - - - testkeeper - - \ No newline at end of file diff --git a/tests/integration/test_store_cleanup/test.py b/tests/integration/test_store_cleanup/test.py deleted file mode 100644 index 6ed52880752f..000000000000 --- a/tests/integration/test_store_cleanup/test.py +++ /dev/null @@ -1,221 +0,0 @@ -import pytest - -from helpers.cluster import ClickHouseCluster - -cluster = ClickHouseCluster(__file__) - -node1 = cluster.add_instance( - "node1", - stay_alive=True, - main_configs=["configs/store_cleanup.xml"], - with_remote_database_disk=False, # The test checks data on the local disk -) - -path_to_data = "/var/lib/clickhouse/" - - -@pytest.fixture(scope="module") -def started_cluster(): - try: - cluster.start() - yield cluster - - finally: - cluster.shutdown() - - -def test_store_cleanup(started_cluster): - sync_drop = {"database_atomic_wait_for_drop_and_detach_synchronously": True} - - node1.query("DROP DATABASE IF EXISTS db", settings=sync_drop) - node1.query("DROP DATABASE IF EXISTS db2", settings=sync_drop) - node1.query("DROP DATABASE IF EXISTS db3", settings=sync_drop) - - node1.query("CREATE DATABASE db UUID '10000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db.log UUID '10000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query( - "CREATE TABLE db.mt UUID '10000000-1000-4000-8000-000000000003' ENGINE=MergeTree ORDER BY tuple() AS SELECT 1" - ) - node1.query( - "CREATE TABLE db.mem UUID '10000000-1000-4000-8000-000000000004' ENGINE=Memory AS SELECT 1" - ) - - node1.query("CREATE DATABASE db2 UUID '20000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db2.log UUID '20000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query("DETACH DATABASE db2", settings=sync_drop) - - node1.query("CREATE DATABASE db3 UUID '30000000-1000-4000-8000-000000000001'") - node1.query( - "CREATE TABLE db3.log UUID '30000000-1000-4000-8000-000000000002' ENGINE=Log AS SELECT 1" - ) - node1.query( - "CREATE TABLE db3.log2 UUID '30000000-1000-4000-8000-000000000003' ENGINE=Log AS SELECT 1" - ) - node1.query("DETACH TABLE db3.log") - node1.query("DETACH TABLE db3.log2 PERMANENTLY") - - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - node1.stop_clickhouse(kill=True) - # All dirs related to `db` will be removed - node1.exec_in_container(["rm", f"{path_to_data}/metadata/db.sql"]) - - node1.exec_in_container(["mkdir", f"{path_to_data}/store/kek"]) - node1.exec_in_container(["touch", f"{path_to_data}/store/12"]) - try: - node1.exec_in_container(["mkdir", f"{path_to_data}/store/456"]) - except Exception as e: - print("Failed to create 456/:", str(e)) - node1.exec_in_container(["mkdir", f"{path_to_data}/store/456/testgarbage"]) - node1.exec_in_container( - ["mkdir", f"{path_to_data}/store/456/30000000-1000-4000-8000-000000000003"] - ) - node1.exec_in_container( - ["touch", f"{path_to_data}/store/456/45600000-1000-4000-8000-000000000003"] - ) - node1.exec_in_container( - ["mkdir", f"{path_to_data}/store/456/45600000-1000-4000-8000-000000000004"] - ) - - node1.start_clickhouse() - node1.query("DETACH DATABASE db2", settings=sync_drop) - node1.query("DETACH TABLE db3.log") - - node1.wait_for_log_line( - "Removing access rights for unused directory", - timeout=60, - look_behind_lines=1000000, - ) - node1.wait_for_log_line( - "directories from store", timeout=60, look_behind_lines=1000000 - ) - - store = node1.exec_in_container(["ls", f"{path_to_data}/store"]) - assert "100" in store - assert "200" in store - assert "300" in store - assert "456" in store - assert "kek" in store - assert "12" in store - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) - - # Metadata is removed, so store/100 contains garbage - store100 = node1.exec_in_container(["ls", f"{path_to_data}/store/100"]) - assert "10000000-1000-4000-8000-000000000001" in store100 - assert "10000000-1000-4000-8000-000000000002" in store100 - assert "10000000-1000-4000-8000-000000000003" in store100 - assert "d---------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) - - # Database is detached, nothing to clean up - store200 = node1.exec_in_container(["ls", f"{path_to_data}/store/200"]) - assert "20000000-1000-4000-8000-000000000001" in store200 - assert "20000000-1000-4000-8000-000000000002" in store200 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - - # Tables are detached, nothing to clean up - store300 = node1.exec_in_container(["ls", f"{path_to_data}/store/300"]) - assert "30000000-1000-4000-8000-000000000001" in store300 - assert "30000000-1000-4000-8000-000000000002" in store300 - assert "30000000-1000-4000-8000-000000000003" in store300 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - # Manually created garbage - store456 = node1.exec_in_container(["ls", f"{path_to_data}/store/456"]) - assert "30000000-1000-4000-8000-000000000003" in store456 - assert "45600000-1000-4000-8000-000000000003" in store456 - assert "45600000-1000-4000-8000-000000000004" in store456 - assert "testgarbage" in store456 - assert "----------" in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) - - node1.wait_for_log_line( - "Removing unused directory", timeout=90, look_behind_lines=1000000 - ) - node1.wait_for_log_line( - "directories from store", timeout=90, look_behind_lines=1000000 - ) - node1.wait_for_log_line( - "Nothing to clean up from store/", timeout=90, look_behind_lines=1000000 - ) - - store = node1.exec_in_container(["ls", f"{path_to_data}/store"]) - assert "100" in store - assert "200" in store - assert "300" in store - assert "456" in store - assert "kek" not in store # changed - assert "\n12\n" not in store # changed - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store"] - ) # changed - - # Metadata is removed, so store/100 contains garbage - store100 = node1.exec_in_container(["ls", f"{path_to_data}/store/100"]) # changed - assert "10000000-1000-4000-8000-000000000001" not in store100 # changed - assert "10000000-1000-4000-8000-000000000002" not in store100 # changed - assert "10000000-1000-4000-8000-000000000003" not in store100 # changed - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/100"] - ) # changed - - # Database is detached, nothing to clean up - store200 = node1.exec_in_container(["ls", f"{path_to_data}/store/200"]) - assert "20000000-1000-4000-8000-000000000001" in store200 - assert "20000000-1000-4000-8000-000000000002" in store200 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/200"] - ) - - # Tables are detached, nothing to clean up - store300 = node1.exec_in_container(["ls", f"{path_to_data}/store/300"]) - assert "30000000-1000-4000-8000-000000000001" in store300 - assert "30000000-1000-4000-8000-000000000002" in store300 - assert "30000000-1000-4000-8000-000000000003" in store300 - assert "d---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/300"] - ) - - # Manually created garbage - store456 = node1.exec_in_container(["ls", f"{path_to_data}/store/456"]) - assert "30000000-1000-4000-8000-000000000003" not in store456 # changed - assert "45600000-1000-4000-8000-000000000003" not in store456 # changed - assert "45600000-1000-4000-8000-000000000004" not in store456 # changed - assert "testgarbage" not in store456 # changed - assert "---------" not in node1.exec_in_container( - ["ls", "-l", f"{path_to_data}/store/456"] - ) # changed - - node1.query("ATTACH TABLE db3.log2") - node1.query("ATTACH DATABASE db2") - node1.query("ATTACH TABLE db3.log") - - assert "1\n" == node1.query("SELECT * FROM db3.log") - assert "1\n" == node1.query("SELECT * FROM db3.log2") - assert "1\n" == node1.query("SELECT * FROM db2.log") diff --git a/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py new file mode 100644 index 000000000000..8642b61ce073 --- /dev/null +++ b/tests/integration/test_table_function_mongodb/malformed_cursor_batch_server.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +""" +A fake MongoDB server that answers `find` and `getMore` with hand-encoded cursor replies. + +The collection name of the `find` command selects the reply, see `SCENARIOS`. +The cursor ID of the `getMore` command selects the next batch. + +The server listens on a free port that the kernel selects, and writes the port number to the port file. + +Usage: malformed_cursor_batch_server.py +""" + +import os +import socketserver +import struct +import sys + + +# Encode BSON directly so the server can send malformed embedded documents. +def document(*elements): + body = b"".join(elements) + return struct.pack(" (first batch, cursor ID, next batch). +# A nonzero cursor ID keeps the cursor open. Each open cursor has a different ID. +# If the next batch is `None`, the server does not expect `getMore`. +SCENARIOS = { + "valid": ([VALID, VALID], 0, None), + "empty": ([], 0, None), + # Neither a short length nor a missing NUL terminator must abort the process. + "short": ([SHORT], 0, None), + "nonnul": ([NONNUL], 0, None), + # A bad document after a valid one, while the cursor is still open. + "after_valid": ([VALID, SHORT], 1, None), + # A bad document in a `getMore` reply. + "next_batch": ([VALID], 2, [NONNUL]), +} +NEXT_BATCHES = { + cursor_id: (collection, next_batch) + for collection, (_, cursor_id, next_batch) in SCENARIOS.items() + if cursor_id != 0 +} + + +def cursor_reply(collection, documents, batch, cursor_id): + return document( + element( + 0x03, + "cursor", + document( + element(0x12, "id", struct.pack(" /var/log/clickhouse-server/malformed_cursor_batch_server.log 2>&1", + ], + detach=True, + ) + # The server binds to port 0 in the container of `node`, and writes the port to the port file when it listens. + port = wait_condition( + lambda: node.exec_in_container( + ["bash", "-c", f"cat {port_file} 2>/dev/null"], nothrow=True + ).strip(), + lambda reply: reply.isdigit(), + max_attempts=40, + delay=0.5, + ) + return f"127.0.0.1:{port}" + + +def test_malformed_cursor_batch(started_cluster, malformed_cursor_batch_server): + # A MongoDB server that returned a malformed document in a cursor batch used to abort the ClickHouse server + # (`BSON_ASSERT` in `_mongoc_cursor_response_read` of the C driver). Now the query fails with an exception + # (upstream CDRIVER-6559 since 2.5.10). + # The fake MongoDB server answers `find` and `getMore` with hand-encoded replies. + # The collection name selects the reply. + node = started_cluster.instances["node"] + + def select(collection): + return ( + f"SELECT * FROM mongodb('{malformed_cursor_batch_server}', 'db', '{collection}', '', '', 'v String', " + "'serverSelectionTimeoutMS=30000&socketTimeoutMS=30000')" + ) + + # The fake server is good enough for the driver when all documents are valid. + assert node.query(select("valid")) == "hello\nhello\n" + assert node.query(select("empty")) == "" + + for collection in [ + # Neither a short length nor a missing NUL terminator must abort the process. + "short", + "nonnul", + # Reject a bad document after reading a valid one, even when the cursor is still open. + "after_valid", + # The same validation must apply to a `getMore` reply. + "next_batch", + ]: + error = node.query_and_get_error(select(collection)) + assert "Invalid server reply: element of cursor batch is" in error, (collection, error) + assert node.query("SELECT 1") == "1\n", collection diff --git a/tests/performance/nested_tuple_small_blocks.xml b/tests/performance/nested_tuple_small_blocks.xml new file mode 100644 index 000000000000..0ab55087663e --- /dev/null +++ b/tests/performance/nested_tuple_small_blocks.xml @@ -0,0 +1,12 @@ + + + +CREATE TABLE IF NOT EXISTS nested_tuple_rowbinary (c0 Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b UInt8)))))))))))))))), c1 Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b UInt8))))))))))))))))) ENGINE = File(RowBinary) + +INSERT INTO nested_tuple_rowbinary SELECT * FROM generateRandom('c0 Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b UInt8)))))))))))))))), c1 Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b Tuple(a UInt8, b UInt8))))))))))))))))', 1, 10, 2) LIMIT 15000 + +SELECT * FROM nested_tuple_rowbinary FORMAT Null SETTINGS max_block_size = 1, input_format_parallel_parsing = 0, max_threads = 1 + +DROP TABLE IF EXISTS nested_tuple_rowbinary + + diff --git a/tests/queries/0_stateless/01271_show_privileges.reference b/tests/queries/0_stateless/01271_show_privileges.reference index c5a77060b902..f2d51825def9 100644 --- a/tests/queries/0_stateless/01271_show_privileges.reference +++ b/tests/queries/0_stateless/01271_show_privileges.reference @@ -52,7 +52,7 @@ ALTER UNLOCK SNAPSHOT ['UNLOCK SNAPSHOT'] TABLE ALTER TABLE ALTER EXECUTE ['ALTER TABLE EXECUTE'] TABLE ALTER TABLE ALTER DATABASE SETTINGS ['ALTER DATABASE SETTING','ALTER MODIFY DATABASE SETTING','MODIFY DATABASE SETTING'] DATABASE ALTER DATABASE ALTER NAMED COLLECTION [] NAMED_COLLECTION NAMED COLLECTION ADMIN -ALTER HANDLER [] GLOBAL ALTER +ALTER HANDLER [] GLOBAL HANDLER ADMIN ALTER TABLE [] \N ALTER ALTER DATABASE [] \N ALTER ALTER VIEW MODIFY QUERY ['ALTER TABLE MODIFY QUERY'] VIEW ALTER VIEW @@ -71,7 +71,7 @@ CREATE FUNCTION [] GLOBAL CREATE CREATE WORKLOAD [] GLOBAL CREATE CREATE RESOURCE [] GLOBAL CREATE CREATE NAMED COLLECTION [] NAMED_COLLECTION NAMED COLLECTION ADMIN -CREATE HANDLER [] GLOBAL CREATE +CREATE HANDLER [] GLOBAL HANDLER ADMIN CREATE [] \N ALL DROP DATABASE [] DATABASE DROP DROP TABLE [] TABLE DROP @@ -81,7 +81,7 @@ DROP FUNCTION [] GLOBAL DROP DROP WORKLOAD [] GLOBAL DROP DROP RESOURCE [] GLOBAL DROP DROP NAMED COLLECTION [] NAMED_COLLECTION NAMED COLLECTION ADMIN -DROP HANDLER [] GLOBAL DROP +DROP HANDLER [] GLOBAL HANDLER ADMIN DROP [] \N ALL UNDROP TABLE [] TABLE ALL TRUNCATE ['TRUNCATE TABLE'] TABLE ALL @@ -123,7 +123,8 @@ SHOW NAMED COLLECTIONS ['SHOW NAMED COLLECTIONS'] NAMED_COLLECTION NAMED COLLECT SHOW NAMED COLLECTIONS SECRETS ['SHOW NAMED COLLECTIONS SECRETS'] NAMED_COLLECTION NAMED COLLECTION ADMIN NAMED COLLECTION ['NAMED COLLECTION USAGE','USE NAMED COLLECTION'] NAMED_COLLECTION NAMED COLLECTION ADMIN NAMED COLLECTION ADMIN ['NAMED COLLECTION CONTROL'] NAMED_COLLECTION ALL -SHOW HANDLERS ['SHOW HANDLER'] GLOBAL ALL +SHOW HANDLERS ['SHOW HANDLER'] GLOBAL HANDLER ADMIN +HANDLER ADMIN [] \N ALL SET DEFINER [] DEFINER ALL TABLE ENGINE ['TABLE ENGINE'] TABLE_ENGINE ALL SYSTEM SHUTDOWN ['SYSTEM KILL','SHUTDOWN'] GLOBAL SYSTEM diff --git a/tests/queries/0_stateless/01601_detach_permanently.sql b/tests/queries/0_stateless/01601_detach_permanently.sql index bb3cc6ec6813..4f56e525387f 100644 --- a/tests/queries/0_stateless/01601_detach_permanently.sql +++ b/tests/queries/0_stateless/01601_detach_permanently.sql @@ -33,8 +33,7 @@ SELECT 'can still show the create statement'; SHOW CREATE TABLE test1601_detach_permanently_atomic.test_name_reuse FORMAT Vertical; SELECT 'can not attach with bad uuid'; --- STD_EXCEPTION occurred when running flaky test, the table directory's access right was removed. Refer `DatabaseCatalog::maybeRemoveDirectory`. -ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse UUID '00000000-0000-0000-0000-000000001601' (`number` UInt64 ) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192 ; -- { serverError TABLE_ALREADY_EXISTS, STD_EXCEPTION } +ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse UUID '00000000-0000-0000-0000-000000001601' (`number` UInt64 ) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8192 ; -- { serverError TABLE_ALREADY_EXISTS } SELECT 'can attach with short syntax'; ATTACH TABLE test1601_detach_permanently_atomic.test_name_reuse; diff --git a/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.reference b/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.reference index 312809828dbd..b87c12285cc0 100644 --- a/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.reference +++ b/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.reference @@ -236,87 +236,40 @@ StripeLog: empty: 1 element: [[3,5,7]] ['a1','a2'] [4.1,4.2] -data.bin size=208 -00000000 e9 71 8f e5 06 82 a8 be 5b 58 f2 9b a5 f9 7a 5c |.q......[X....z\| -00000010 82 0c 00 00 00 02 00 00 00 20 03 01 53 d7 6d 37 |......... ..S.m7| -00000020 bf 7a fb 8b c6 f5 96 b2 63 a2 ef 26 82 31 00 00 |.z......c..&.1..| -00000030 00 32 00 00 00 92 01 78 13 41 72 72 61 79 28 06 |.2.....x.Array(.| -00000040 00 92 49 6e 74 33 32 29 29 01 00 01 00 12 03 07 |..Int32)).......| -00000050 00 01 08 00 80 05 00 00 00 07 00 00 00 0d 77 ad |..............w.| -00000060 98 63 11 30 fa 9a cb b6 7a eb ee 9a 14 82 28 00 |.c.0....z.....(.| -00000070 00 00 20 00 00 00 f2 05 03 79 2e 7a 0d 41 72 72 |.. ......y.z.Arr| -00000080 61 79 28 53 74 72 69 6e 67 29 02 00 01 00 60 02 |ay(String)....`.| -00000090 61 31 02 61 32 43 59 b0 e8 66 5f 82 43 20 c5 2b |a1.a2CY..f_.C .+| -000000a0 47 74 75 7e 59 82 2b 00 00 00 23 00 00 00 f2 06 |Gtu~Y.+...#.....| -000000b0 03 79 2e 77 0e 41 72 72 61 79 28 46 6c 6f 61 74 |.y.w.Array(Float| -000000c0 33 32 29 02 00 01 00 80 33 33 83 40 66 66 86 40 |32).....33.@ff.@| -000000d0 -index.mrk size=96 -00000000 fb d3 41 e4 f9 03 e2 5c 61 58 96 37 a7 ab 3a 70 |..A....\aX.7..:p| -00000010 82 50 00 00 00 6d 00 00 00 b2 03 01 01 78 13 41 |.P...m.......x.A| -00000020 72 72 61 79 28 06 00 9a 49 6e 74 33 32 29 29 1c |rray(...Int32)).| -00000030 00 01 00 52 03 79 2e 7a 0d 22 00 8a 53 74 72 69 |...R.y.z."..Stri| -00000040 6e 67 29 5d 21 00 62 00 03 79 2e 77 0e 22 00 40 |ng)]!.b..y.w.".@| -00000050 46 6c 6f 61 46 00 16 95 23 00 50 00 00 00 00 00 |FloaF...#.P.....| -00000060 -sizes.json size=72 -00000000 7b 22 63 6c 69 63 6b 68 6f 75 73 65 22 3a 7b 22 |{"clickhouse":{"| -00000010 64 61 74 61 25 32 45 62 69 6e 22 3a 7b 22 73 69 |data%2Ebin":{"si| -00000020 7a 65 22 3a 22 32 30 38 22 7d 2c 22 69 6e 64 65 |ze":"208"},"inde| -00000030 78 25 32 45 6d 72 6b 22 3a 7b 22 73 69 7a 65 22 |x%2Emrk":{"size"| -00000040 3a 22 39 36 22 7d 7d 7d |:"96"}}}| -00000048 +data.bin decompressed: +00000000 03 01 01 78 13 41 72 72 61 79 28 41 72 72 61 79 |...x.Array(Array| +00000010 28 49 6e 74 33 32 29 29 01 00 00 00 00 00 00 00 |(Int32))........| +00000020 03 00 00 00 00 00 00 00 03 00 00 00 05 00 00 00 |................| +00000030 07 00 00 00 03 79 2e 7a 0d 41 72 72 61 79 28 53 |.....y.z.Array(S| +00000040 74 72 69 6e 67 29 02 00 00 00 00 00 00 00 02 61 |tring).........a| +00000050 31 02 61 32 03 79 2e 77 0e 41 72 72 61 79 28 46 |1.a2.y.w.Array(F| +00000060 6c 6f 61 74 33 32 29 02 00 00 00 00 00 00 00 33 |loat32)........3| +00000070 33 83 40 66 66 86 40 |3.@ff.@| +00000077 +index.mrk decompressed size=109 +sizes.json: {"clickhouse":{"data%2Ebin":{"size":"OK"},"index%2Emrk":{"size":"OK"}}} 3 elements: [] [] [] [[3,5,7]] ['a1','a2'] [4.1,4.2] [[10]] ['a3'] [4.3] -data.bin size=416 -00000000 e9 71 8f e5 06 82 a8 be 5b 58 f2 9b a5 f9 7a 5c |.q......[X....z\| -00000010 82 0c 00 00 00 02 00 00 00 20 03 01 53 d7 6d 37 |......... ..S.m7| -00000020 bf 7a fb 8b c6 f5 96 b2 63 a2 ef 26 82 31 00 00 |.z......c..&.1..| -00000030 00 32 00 00 00 92 01 78 13 41 72 72 61 79 28 06 |.2.....x.Array(.| -00000040 00 92 49 6e 74 33 32 29 29 01 00 01 00 12 03 07 |..Int32)).......| -00000050 00 01 08 00 80 05 00 00 00 07 00 00 00 0d 77 ad |..............w.| -00000060 98 63 11 30 fa 9a cb b6 7a eb ee 9a 14 82 28 00 |.c.0....z.....(.| -00000070 00 00 20 00 00 00 f2 05 03 79 2e 7a 0d 41 72 72 |.. ......y.z.Arr| -00000080 61 79 28 53 74 72 69 6e 67 29 02 00 01 00 60 02 |ay(String)....`.| -00000090 61 31 02 61 32 43 59 b0 e8 66 5f 82 43 20 c5 2b |a1.a2CY..f_.C .+| -000000a0 47 74 75 7e 59 82 2b 00 00 00 23 00 00 00 f2 06 |Gtu~Y.+...#.....| -000000b0 03 79 2e 77 0e 41 72 72 61 79 28 46 6c 6f 61 74 |.y.w.Array(Float| -000000c0 33 32 29 02 00 01 00 80 33 33 83 40 66 66 86 40 |32).....33.@ff.@| -000000d0 f8 ed 62 84 7b b1 cf 59 6e 10 a8 10 0a 0c 73 37 |..b.{..Yn.....s7| -000000e0 82 0c 00 00 00 02 00 00 00 20 03 02 d5 4e 18 97 |......... ...N..| -000000f0 1b d0 d8 03 85 c7 b5 d1 20 a3 16 09 82 2a 00 00 |........ ....*..| -00000100 00 32 00 00 00 92 01 78 13 41 72 72 61 79 28 06 |.2.....x.Array(.| -00000110 00 83 49 6e 74 33 32 29 29 00 01 00 1a 01 08 00 |..Int32)).......| -00000120 50 00 0a 00 00 00 51 5b fd 47 31 2e ec ac ba 00 |P.....Q[.G1.....| -00000130 d3 89 f3 55 b1 4c 82 2c 00 00 00 25 00 00 00 f3 |...U.L.,...%....| -00000140 04 03 79 2e 7a 0d 41 72 72 61 79 28 53 74 72 69 |..y.z.Array(Stri| -00000150 6e 67 29 00 01 00 b0 01 00 00 00 00 00 00 00 02 |ng).............| -00000160 61 33 d9 ff b3 4c 97 40 40 37 88 bc 6b 6b cf 84 |a3...L.@@7..kk..| -00000170 57 f0 82 2e 00 00 00 27 00 00 00 f3 05 03 79 2e |W......'......y.| -00000180 77 0e 41 72 72 61 79 28 46 6c 6f 61 74 33 32 29 |w.Array(Float32)| -00000190 00 01 00 c0 01 00 00 00 00 00 00 00 9a 99 89 40 |...............@| -000001a0 -index.mrk size=189 -00000000 fb d3 41 e4 f9 03 e2 5c 61 58 96 37 a7 ab 3a 70 |..A....\aX.7..:p| -00000010 82 50 00 00 00 6d 00 00 00 b2 03 01 01 78 13 41 |.P...m.......x.A| -00000020 72 72 61 79 28 06 00 9a 49 6e 74 33 32 29 29 1c |rray(...Int32)).| -00000030 00 01 00 52 03 79 2e 7a 0d 22 00 8a 53 74 72 69 |...R.y.z."..Stri| -00000040 6e 67 29 5d 21 00 62 00 03 79 2e 77 0e 22 00 40 |ng)]!.b..y.w.".@| -00000050 46 6c 6f 61 46 00 16 95 23 00 50 00 00 00 00 00 |FloaF...#.P.....| -00000060 ec d4 1e 6d fc b7 7d d4 3d 8d 6d 74 a9 ba 10 35 |...m..}.=.mt...5| -00000070 82 4d 00 00 00 6d 00 00 00 b2 03 02 01 78 13 41 |.M...m.......x.A| -00000080 72 72 61 79 28 06 00 9a 49 6e 74 33 32 29 29 ec |rray(...Int32)).| -00000090 00 01 00 52 03 79 2e 7a 0d 22 00 9d 53 74 72 69 |...R.y.z."..Stri| -000000a0 6e 67 29 26 01 22 00 22 77 0e 22 00 40 46 6c 6f |ng)&."."w.".@Flo| -000000b0 61 46 00 16 62 23 00 50 00 00 00 00 00 |aF..b#.P.....| -000000bd -sizes.json size=73 -00000000 7b 22 63 6c 69 63 6b 68 6f 75 73 65 22 3a 7b 22 |{"clickhouse":{"| -00000010 64 61 74 61 25 32 45 62 69 6e 22 3a 7b 22 73 69 |data%2Ebin":{"si| -00000020 7a 65 22 3a 22 34 31 36 22 7d 2c 22 69 6e 64 65 |ze":"416"},"inde| -00000030 78 25 32 45 6d 72 6b 22 3a 7b 22 73 69 7a 65 22 |x%2Emrk":{"size"| -00000040 3a 22 31 38 39 22 7d 7d 7d |:"189"}}}| -00000049 +data.bin decompressed: +00000000 03 01 01 78 13 41 72 72 61 79 28 41 72 72 61 79 |...x.Array(Array| +00000010 28 49 6e 74 33 32 29 29 01 00 00 00 00 00 00 00 |(Int32))........| +00000020 03 00 00 00 00 00 00 00 03 00 00 00 05 00 00 00 |................| +00000030 07 00 00 00 03 79 2e 7a 0d 41 72 72 61 79 28 53 |.....y.z.Array(S| +00000040 74 72 69 6e 67 29 02 00 00 00 00 00 00 00 02 61 |tring).........a| +00000050 31 02 61 32 03 79 2e 77 0e 41 72 72 61 79 28 46 |1.a2.y.w.Array(F| +00000060 6c 6f 61 74 33 32 29 02 00 00 00 00 00 00 00 33 |loat32)........3| +00000070 33 83 40 66 66 86 40 03 02 01 78 13 41 72 72 61 |3.@ff.@...x.Arra| +00000080 79 28 41 72 72 61 79 28 49 6e 74 33 32 29 29 00 |y(Array(Int32)).| +00000090 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 01 |................| +000000a0 00 00 00 00 00 00 00 0a 00 00 00 03 79 2e 7a 0d |............y.z.| +000000b0 41 72 72 61 79 28 53 74 72 69 6e 67 29 00 00 00 |Array(String)...| +000000c0 00 00 00 00 00 01 00 00 00 00 00 00 00 02 61 33 |..............a3| +000000d0 03 79 2e 77 0e 41 72 72 61 79 28 46 6c 6f 61 74 |.y.w.Array(Float| +000000e0 33 32 29 00 00 00 00 00 00 00 00 01 00 00 00 00 |32).............| +000000f0 00 00 00 9a 99 89 40 |......@| +000000f7 +index.mrk decompressed size=218 +sizes.json: {"clickhouse":{"data%2Ebin":{"size":"OK"},"index%2Emrk":{"size":"OK"}}} diff --git a/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.sh b/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.sh index 55c01e632947..1eafc95ff6bb 100755 --- a/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.sh +++ b/tests/queries/0_stateless/02047_log_family_complex_structs_data_file_dumps.sh @@ -5,13 +5,56 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh . "$CURDIR"/../shell_config.sh +# Dumps the files of the table. +# +# `Log` and `TinyLog` store each column with its own codec. The columns are pinned to `LZ4`, which keeps the +# dumps independent of the server default codec, and these files are dumped as they are. +# +# `StripeLog` instead writes one shared `data.bin` (and its `index.mrk`) with the server default codec regardless +# of the column codec (currently `ZSTD(3)`). The bytes and the sizes of its compressed blocks depend on the +# version of the compression library, so `data.bin` is dumped decompressed, and only the decompressed size is +# printed for `index.mrk`, which holds the offsets of the compressed blocks. A size in `sizes.json` is replaced +# with `OK` only if it is the size of the file. What the index says about the data is checked by `reattach_table`. +dump_files() +{ + for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do + file_path=$data_dir$name + if [ "$engine" != "StripeLog" ]; then + file_size=$(stat -c%s "$file_path") + echo "$name size=$file_size" + hexdump -C "$file_path" + elif [ "$name" == "data.bin" ]; then + echo "$name decompressed:" + ${CLICKHOUSE_COMPRESSOR} --decompress < "$file_path" | hexdump -C + elif [ "$name" == "index.mrk" ]; then + echo "$name decompressed size=$(${CLICKHOUSE_COMPRESSOR} --decompress < "$file_path" | wc -c)" + else + data_size=$(stat -c%s "${data_dir}data.bin") + index_size=$(stat -c%s "${data_dir}index.mrk") + echo "$name: $(sed \ + -e "s/\"data%2Ebin\":{\"size\":\"$data_size\"}/\"data%2Ebin\":{\"size\":\"OK\"}/" \ + -e "s/\"index%2Emrk\":{\"size\":\"$index_size\"}/\"index%2Emrk\":{\"size\":\"OK\"}/" \ + "$file_path")" + fi + done +} + +# Makes the next query read the table from its files: while the table is attached, the index of `StripeLog` +# and the marks of `Log` are served from memory, so a wrong index or wrong sizes on disk would stay unnoticed. +reattach_table() +{ + $CLICKHOUSE_CLIENT --query="DETACH TABLE tbl" + $CLICKHOUSE_CLIENT --query="ATTACH TABLE tbl" +} + declare -a engines=("Log" "TinyLog" "StripeLog") for engine in "${engines[@]}" do echo "$engine:" $CLICKHOUSE_CLIENT --query="DROP TABLE IF EXISTS tbl" - $CLICKHOUSE_CLIENT --query="CREATE TABLE tbl(x Array(Array(Int32)), y Nested(z String, w Float32)) ENGINE=$engine" + # Pin the column codec to `LZ4`, see `dump_files`. + $CLICKHOUSE_CLIENT --query="CREATE TABLE tbl(x Array(Array(Int32)) CODEC(LZ4), y Nested(z String, w Float32) CODEC(LZ4)) ENGINE=$engine" data_dir=$($CLICKHOUSE_CLIENT --query="SELECT data_paths[1] FROM system.tables WHERE name='tbl' AND database=currentDatabase()") echo "empty:" @@ -19,23 +62,15 @@ do echo "1 element:" $CLICKHOUSE_CLIENT --query="INSERT INTO tbl VALUES ([[3,5,7]], ['a1', 'a2'], [4.1, 4.2])" + reattach_table $CLICKHOUSE_CLIENT --query="SELECT * FROM tbl ORDER BY x" - for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do - file_path=$data_dir$name - file_size=$(stat -c%s "$file_path") - echo "$name size=$file_size" - hexdump -C $file_path - done + dump_files echo "3 elements:" $CLICKHOUSE_CLIENT --query="INSERT INTO tbl VALUES ([], [], []), ([[10]], ['a3'], [4.3])" + reattach_table $CLICKHOUSE_CLIENT --query="SELECT * FROM tbl ORDER BY x" - for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do - file_path=$data_dir$name - file_size=$(stat -c%s "$file_path") - echo "$name size=$file_size" - hexdump -C $file_path - done + dump_files echo done diff --git a/tests/queries/0_stateless/02047_log_family_data_file_dumps.reference b/tests/queries/0_stateless/02047_log_family_data_file_dumps.reference index bdb91497eb0d..774656cef4f3 100644 --- a/tests/queries/0_stateless/02047_log_family_data_file_dumps.reference +++ b/tests/queries/0_stateless/02047_log_family_data_file_dumps.reference @@ -98,63 +98,22 @@ StripeLog: empty: 1 element: 1 a -data.bin size=104 -00000000 0c d3 31 cc 9f f3 94 97 56 a2 ee 76 f7 4c 35 0f |..1.....V..v.L5.| -00000010 82 0c 00 00 00 02 00 00 00 20 02 01 d3 b5 6c 48 |......... ....lH| -00000020 05 89 3b 01 ad 3a 99 3a 40 10 f0 fa 82 17 00 00 |..;..:.:@.......| -00000030 00 0d 00 00 00 d0 01 78 06 55 49 6e 74 33 32 01 |.......x.UInt32.| -00000040 00 00 00 07 12 7f b8 90 bb cb c1 5b 93 d1 61 7e |...........[..a~| -00000050 27 86 3e 82 15 00 00 00 0b 00 00 00 b0 01 79 06 |'.>...........y.| -00000060 53 74 72 69 6e 67 01 61 |String.a| -00000068 -index.mrk size=60 -00000000 e0 18 ce 21 0a cc 9f ac d8 51 d4 27 00 4d 7e 75 |...!.....Q.'.M~u| -00000010 82 2c 00 00 00 34 00 00 00 da 02 01 01 78 06 55 |.,...4.......x.U| -00000020 49 6e 74 33 32 1c 00 01 00 a6 01 79 06 53 74 72 |Int32......y.Str| -00000030 69 6e 67 43 18 00 50 00 00 00 00 00 |ingC..P.....| -0000003c -sizes.json size=72 -00000000 7b 22 63 6c 69 63 6b 68 6f 75 73 65 22 3a 7b 22 |{"clickhouse":{"| -00000010 64 61 74 61 25 32 45 62 69 6e 22 3a 7b 22 73 69 |data%2Ebin":{"si| -00000020 7a 65 22 3a 22 31 30 34 22 7d 2c 22 69 6e 64 65 |ze":"104"},"inde| -00000030 78 25 32 45 6d 72 6b 22 3a 7b 22 73 69 7a 65 22 |x%2Emrk":{"size"| -00000040 3a 22 36 30 22 7d 7d 7d |:"60"}}}| -00000048 +data.bin decompressed: +00000000 02 01 01 78 06 55 49 6e 74 33 32 01 00 00 00 01 |...x.UInt32.....| +00000010 79 06 53 74 72 69 6e 67 01 61 |y.String.a| +0000001a +index.mrk decompressed size=52 +sizes.json: {"clickhouse":{"data%2Ebin":{"size":"OK"},"index%2Emrk":{"size":"OK"}}} 3 elements: 1 a 22 bc 333 def -data.bin size=219 -00000000 0c d3 31 cc 9f f3 94 97 56 a2 ee 76 f7 4c 35 0f |..1.....V..v.L5.| -00000010 82 0c 00 00 00 02 00 00 00 20 02 01 d3 b5 6c 48 |......... ....lH| -00000020 05 89 3b 01 ad 3a 99 3a 40 10 f0 fa 82 17 00 00 |..;..:.:@.......| -00000030 00 0d 00 00 00 d0 01 78 06 55 49 6e 74 33 32 01 |.......x.UInt32.| -00000040 00 00 00 07 12 7f b8 90 bb cb c1 5b 93 d1 61 7e |...........[..a~| -00000050 27 86 3e 82 15 00 00 00 0b 00 00 00 b0 01 79 06 |'.>...........y.| -00000060 53 74 72 69 6e 67 01 61 55 84 52 9f 32 10 4d 9e |String.aU.R.2.M.| -00000070 eb 58 e8 2a 3a 8c e8 df 82 0c 00 00 00 02 00 00 |.X.*:...........| -00000080 00 20 02 02 5f c2 08 eb 23 e5 a3 7a e2 22 e7 fc |. .._...#..z."..| -00000090 23 57 79 fd 82 1c 00 00 00 11 00 00 00 f0 02 01 |#Wy.............| -000000a0 78 06 55 49 6e 74 33 32 16 00 00 00 4d 01 00 00 |x.UInt32....M...| -000000b0 87 a2 af 21 6c 93 79 77 88 8c 5f ae e9 41 df 5a |...!l.yw.._..A.Z| -000000c0 82 1b 00 00 00 10 00 00 00 f0 01 01 79 06 53 74 |............y.St| -000000d0 72 69 6e 67 02 62 63 03 64 65 66 |ring.bc.def| -000000db -index.mrk size=120 -00000000 e0 18 ce 21 0a cc 9f ac d8 51 d4 27 00 4d 7e 75 |...!.....Q.'.M~u| -00000010 82 2c 00 00 00 34 00 00 00 da 02 01 01 78 06 55 |.,...4.......x.U| -00000020 49 6e 74 33 32 1c 00 01 00 a6 01 79 06 53 74 72 |Int32......y.Str| -00000030 69 6e 67 43 18 00 50 00 00 00 00 00 82 27 58 46 |ingC..P......'XF| -00000040 ad 45 bc 2f 66 02 78 84 e1 42 dd 03 82 2c 00 00 |.E./f.x..B...,..| -00000050 00 34 00 00 00 da 02 02 01 78 06 55 49 6e 74 33 |.4.......x.UInt3| -00000060 32 84 00 01 00 a6 01 79 06 53 74 72 69 6e 67 b0 |2......y.String.| -00000070 18 00 50 00 00 00 00 00 |..P.....| -00000078 -sizes.json size=73 -00000000 7b 22 63 6c 69 63 6b 68 6f 75 73 65 22 3a 7b 22 |{"clickhouse":{"| -00000010 64 61 74 61 25 32 45 62 69 6e 22 3a 7b 22 73 69 |data%2Ebin":{"si| -00000020 7a 65 22 3a 22 32 31 39 22 7d 2c 22 69 6e 64 65 |ze":"219"},"inde| -00000030 78 25 32 45 6d 72 6b 22 3a 7b 22 73 69 7a 65 22 |x%2Emrk":{"size"| -00000040 3a 22 31 32 30 22 7d 7d 7d |:"120"}}}| -00000049 +data.bin decompressed: +00000000 02 01 01 78 06 55 49 6e 74 33 32 01 00 00 00 01 |...x.UInt32.....| +00000010 79 06 53 74 72 69 6e 67 01 61 02 02 01 78 06 55 |y.String.a...x.U| +00000020 49 6e 74 33 32 16 00 00 00 4d 01 00 00 01 79 06 |Int32....M....y.| +00000030 53 74 72 69 6e 67 02 62 63 03 64 65 66 |String.bc.def| +0000003d +index.mrk decompressed size=104 +sizes.json: {"clickhouse":{"data%2Ebin":{"size":"OK"},"index%2Emrk":{"size":"OK"}}} diff --git a/tests/queries/0_stateless/02047_log_family_data_file_dumps.sh b/tests/queries/0_stateless/02047_log_family_data_file_dumps.sh index 1edfd200fab2..e89b53b8989b 100755 --- a/tests/queries/0_stateless/02047_log_family_data_file_dumps.sh +++ b/tests/queries/0_stateless/02047_log_family_data_file_dumps.sh @@ -5,13 +5,56 @@ CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh . "$CURDIR"/../shell_config.sh +# Dumps the files of the table. +# +# `Log` and `TinyLog` store each column with its own codec. The columns are pinned to `LZ4`, which keeps the +# dumps independent of the server default codec, and these files are dumped as they are. +# +# `StripeLog` instead writes one shared `data.bin` (and its `index.mrk`) with the server default codec regardless +# of the column codec (currently `ZSTD(3)`). The bytes and the sizes of its compressed blocks depend on the +# version of the compression library, so `data.bin` is dumped decompressed, and only the decompressed size is +# printed for `index.mrk`, which holds the offsets of the compressed blocks. A size in `sizes.json` is replaced +# with `OK` only if it is the size of the file. What the index says about the data is checked by `reattach_table`. +dump_files() +{ + for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do + file_path=$data_dir$name + if [ "$engine" != "StripeLog" ]; then + file_size=$(stat -c%s "$file_path") + echo "$name size=$file_size" + hexdump -C "$file_path" + elif [ "$name" == "data.bin" ]; then + echo "$name decompressed:" + ${CLICKHOUSE_COMPRESSOR} --decompress < "$file_path" | hexdump -C + elif [ "$name" == "index.mrk" ]; then + echo "$name decompressed size=$(${CLICKHOUSE_COMPRESSOR} --decompress < "$file_path" | wc -c)" + else + data_size=$(stat -c%s "${data_dir}data.bin") + index_size=$(stat -c%s "${data_dir}index.mrk") + echo "$name: $(sed \ + -e "s/\"data%2Ebin\":{\"size\":\"$data_size\"}/\"data%2Ebin\":{\"size\":\"OK\"}/" \ + -e "s/\"index%2Emrk\":{\"size\":\"$index_size\"}/\"index%2Emrk\":{\"size\":\"OK\"}/" \ + "$file_path")" + fi + done +} + +# Makes the next query read the table from its files: while the table is attached, the index of `StripeLog` +# and the marks of `Log` are served from memory, so a wrong index or wrong sizes on disk would stay unnoticed. +reattach_table() +{ + $CLICKHOUSE_CLIENT --query="DETACH TABLE tbl" + $CLICKHOUSE_CLIENT --query="ATTACH TABLE tbl" +} + declare -a engines=("Log" "TinyLog" "StripeLog") for engine in "${engines[@]}" do echo "$engine:" $CLICKHOUSE_CLIENT --query="DROP TABLE IF EXISTS tbl" - $CLICKHOUSE_CLIENT --query="CREATE TABLE tbl(x UInt32, y String) ENGINE=$engine" + # Pin the column codec to `LZ4`, see `dump_files`. + $CLICKHOUSE_CLIENT --query="CREATE TABLE tbl(x UInt32 CODEC(LZ4), y String CODEC(LZ4)) ENGINE=$engine" data_dir=$($CLICKHOUSE_CLIENT --query="SELECT data_paths[1] FROM system.tables WHERE name='tbl' AND database=currentDatabase()") echo "empty:" @@ -19,23 +62,15 @@ do echo "1 element:" $CLICKHOUSE_CLIENT --query="INSERT INTO tbl VALUES (1, 'a')" + reattach_table $CLICKHOUSE_CLIENT --query="SELECT * FROM tbl ORDER BY x" - for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do - file_path=$data_dir$name - file_size=$(stat -c%s "$file_path") - echo "$name size=$file_size" - hexdump -C $file_path - done + dump_files echo "3 elements:" $CLICKHOUSE_CLIENT --query="INSERT INTO tbl VALUES (22, 'bc'), (333, 'def')" + reattach_table $CLICKHOUSE_CLIENT --query="SELECT * FROM tbl ORDER BY x" - for name in $(find "$data_dir"* -print0 | xargs -0 -n 1 basename | sort); do - file_path=$data_dir$name - file_size=$(stat -c%s "$file_path") - echo "$name size=$file_size" - hexdump -C $file_path - done + dump_files echo done diff --git a/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.reference b/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.reference index b7dc21a39790..4a860b953eea 100644 --- a/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.reference +++ b/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.reference @@ -21,8 +21,8 @@ SELECT file_segment_range_begin, file_segment_range_end, size, state FORMAT Vertical SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -0 0 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +0 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SELECT file_segment_range_begin, file_segment_range_end, size, state FROM @@ -48,16 +48,16 @@ size: 746 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 -SELECT count(), sum(size) size FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SYSTEM CLEAR FILESYSTEM CACHE INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100, 200) SELECT file_segment_range_begin, file_segment_range_end, size, state @@ -84,24 +84,24 @@ size: 1660 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SETTINGS enable_filesystem_cache_on_write_operations=0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(300, 10000) -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -27 84396 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +27 SYSTEM START MERGES test_02241 OPTIMIZE TABLE test_02241 FINAL -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -36 167711 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +36 ALTER TABLE test_02241 UPDATE value = 'kek' WHERE key = 100 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -46 251128 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +46 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) SYSTEM FLUSH LOGS query_log INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) 0 @@ -132,8 +132,8 @@ SELECT file_segment_range_begin, file_segment_range_end, size, state FORMAT Vertical SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -0 0 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +0 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SELECT file_segment_range_begin, file_segment_range_end, size, state FROM @@ -159,16 +159,16 @@ size: 746 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 -SELECT count(), sum(size) size FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SYSTEM CLEAR FILESYSTEM CACHE INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100, 200) SELECT file_segment_range_begin, file_segment_range_end, size, state @@ -195,24 +195,24 @@ size: 1660 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SETTINGS enable_filesystem_cache_on_write_operations=0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(300, 10000) -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -27 84396 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +27 SYSTEM START MERGES test_02241 OPTIMIZE TABLE test_02241 FINAL -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -36 167711 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +36 ALTER TABLE test_02241 UPDATE value = 'kek' WHERE key = 100 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -46 251128 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +46 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) SYSTEM FLUSH LOGS query_log INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) 0 @@ -243,8 +243,8 @@ SELECT file_segment_range_begin, file_segment_range_end, size, state FORMAT Vertical SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -0 0 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +0 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SELECT file_segment_range_begin, file_segment_range_end, size, state FROM @@ -270,16 +270,16 @@ size: 746 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 SELECT * FROM test_02241 FORMAT Null SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '__tmp_internal' 2 -SELECT count(), sum(size) size FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 1217 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 SYSTEM CLEAR FILESYSTEM CACHE INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100, 200) SELECT file_segment_range_begin, file_segment_range_end, size, state @@ -306,24 +306,24 @@ size: 1660 state: DOWNLOADED SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '__tmp_internal' 9 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SETTINGS enable_filesystem_cache_on_write_operations=0 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -9 2131 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +9 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(300, 10000) -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -27 84396 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +27 SYSTEM START MERGES test_02241 OPTIMIZE TABLE test_02241 FINAL -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -36 167711 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +36 ALTER TABLE test_02241 UPDATE value = 'kek' WHERE key = 100 -SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' -46 251128 +SELECT count() FROM system.filesystem_cache WHERE cache_name = '__tmp_internal' +46 INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) SYSTEM FLUSH LOGS query_log INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000) 0 diff --git a/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.sh b/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.sh index 3383d1da907d..35415ed08fdc 100755 --- a/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.sh +++ b/tests/queries/0_stateless/02241_filesystem_cache_on_write_operations.sh @@ -40,7 +40,7 @@ for disk in 's3_disk' 'local_disk' 'azure'; do FORMAT Vertical" $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '$cache_name'" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100)" @@ -62,7 +62,7 @@ for disk in 's3_disk' 'local_disk' 'azure'; do FORMAT Vertical" $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '$cache_name'" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --query "SELECT * FROM test_02241 FORMAT Null" $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '$cache_name'" @@ -70,7 +70,7 @@ for disk in 's3_disk' 'local_disk' 'azure'; do $CLICKHOUSE_CLIENT --echo --query "SELECT * FROM test_02241 FORMAT Null" $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_hits > 0 AND cache_name = '$cache_name'" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) size FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" echo "SYSTEM CLEAR FILESYSTEM CACHE" drop_filesystem_cache $cache_name @@ -95,24 +95,24 @@ for disk in 's3_disk' 'local_disk' 'azure'; do FORMAT Vertical;" $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM (SELECT arrayJoin(cache_paths) AS cache_path, local_path, remote_path FROM system.remote_data_paths ) AS data_paths INNER JOIN system.filesystem_cache AS caches ON data_paths.cache_path = caches.cache_path WHERE caches.cache_name = '$cache_name'" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100) SETTINGS enable_filesystem_cache_on_write_operations=0" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(100)" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(300, 10000)" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --query "SYSTEM START MERGES test_02241" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "OPTIMIZE TABLE test_02241 FINAL" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --mutations_sync=2 --query "ALTER TABLE test_02241 UPDATE value = 'kek' WHERE key = 100" - $CLICKHOUSE_CLIENT --echo --query "SELECT count(), sum(size) FROM system.filesystem_cache WHERE cache_name = '$cache_name'" + $CLICKHOUSE_CLIENT --echo --query "SELECT count() FROM system.filesystem_cache WHERE cache_name = '$cache_name'" $CLICKHOUSE_CLIENT --echo --enable_filesystem_cache_on_write_operations=1 --query "INSERT INTO test_02241 SELECT number, toString(number) FROM numbers(5000000)" $CLICKHOUSE_CLIENT --echo --query "SYSTEM FLUSH LOGS query_log" diff --git a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference index a51336301866..78027ce0f9e2 100644 --- a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference +++ b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.reference @@ -1,18 +1,16 @@ Using storage policy: s3_cache -(0,519) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_CACHE +0 519 READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_CACHE +0 end_of_data READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_CACHE +0 end_of_data READ_FROM_CACHE Using storage policy: local_cache -(0,519) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_CACHE +0 519 READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_CACHE Using storage policy: azure_cache -(0,519) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_FS_AND_DOWNLOADED_TO_CACHE -(0,808110) READ_FROM_CACHE -(0,808110) READ_FROM_CACHE +0 519 READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_CACHE +0 end_of_data READ_FROM_FS_AND_DOWNLOADED_TO_CACHE +0 end_of_data READ_FROM_CACHE +0 end_of_data READ_FROM_CACHE diff --git a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh index 6b34813159f6..f2fdaafe94b0 100755 --- a/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh +++ b/tests/queries/0_stateless/02242_system_filesystem_cache_log_table.sh @@ -1,5 +1,9 @@ #!/usr/bin/env bash -# Tags: long, no-fasttest, no-parallel, no-object-storage, no-random-settings +# Tags: long, no-fasttest, no-parallel, no-object-storage, no-random-settings, no-flaky-check +# Tag no-flaky-check: the test reads through the shared `s3_cache`, `local_cache` and `azure_cache` caches +# and expects exact cache hit/miss sequences. Repeated runs start while background merges of `test.hits_s3` +# are still writing through `s3_cache` with `cache_on_write_operations`, which fills the whole cache with +# non-releasable segments, so reads bypass the cache or re-download. # set -x @@ -20,10 +24,11 @@ for STORAGE_POLICY in 's3_cache' 'local_cache' 'azure_cache'; do $CLICKHOUSE_CLIENT --enable_filesystem_cache_on_write_operations=0 --enable_filesystem_cache_log=1 --query "SELECT 2242, '$STORAGE_POLICY', * FROM test_2242 FORMAT Null" $CLICKHOUSE_CLIENT --query "SYSTEM FLUSH LOGS filesystem_cache_log, query_log" - $CLICKHOUSE_CLIENT --query "SELECT file_segment_range, read_type FROM system.filesystem_cache_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND query_id = (SELECT query_id from system.query_log where query LIKE '%SELECT 2242%$STORAGE_POLICY%' AND current_database = currentDatabase() AND type = 'QueryFinish' ORDER BY event_time desc LIMIT 1) ORDER BY file_segment_range, read_type" + # The end of the segment of the compressed data is not printed, because it depends on the version of the compression library. + $CLICKHOUSE_CLIENT --query "SELECT file_segment_range.1, if(file_segment_range.2 < 100000, toString(file_segment_range.2), 'end_of_data'), read_type FROM system.filesystem_cache_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND query_id = (SELECT query_id from system.query_log where query LIKE '%SELECT 2242%$STORAGE_POLICY%' AND current_database = currentDatabase() AND type = 'QueryFinish' ORDER BY event_time desc LIMIT 1) ORDER BY file_segment_range, read_type" $CLICKHOUSE_CLIENT --enable_filesystem_cache_on_write_operations=0 --enable_filesystem_cache_log=1 --query "SELECT 2243, '$STORAGE_POLICY', * FROM test_2242 FORMAT Null" $CLICKHOUSE_CLIENT --query "SYSTEM FLUSH LOGS filesystem_cache_log, query_log" - $CLICKHOUSE_CLIENT --query "SELECT file_segment_range, read_type FROM system.filesystem_cache_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND query_id = (SELECT query_id from system.query_log where query LIKE '%SELECT 2243%$STORAGE_POLICY%' AND current_database = currentDatabase() AND type = 'QueryFinish' ORDER BY event_time desc LIMIT 1) ORDER BY file_segment_range, read_type" + $CLICKHOUSE_CLIENT --query "SELECT file_segment_range.1, if(file_segment_range.2 < 100000, toString(file_segment_range.2), 'end_of_data'), read_type FROM system.filesystem_cache_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND query_id = (SELECT query_id from system.query_log where query LIKE '%SELECT 2243%$STORAGE_POLICY%' AND current_database = currentDatabase() AND type = 'QueryFinish' ORDER BY event_time desc LIMIT 1) ORDER BY file_segment_range, read_type" done diff --git a/tests/queries/0_stateless/02381_compress_marks_and_primary_key.reference b/tests/queries/0_stateless/02381_compress_marks_and_primary_key.reference index 53bddb77b845..d46e65884b68 100644 --- a/tests/queries/0_stateless/02381_compress_marks_and_primary_key.reference +++ b/tests/queries/0_stateless/02381_compress_marks_and_primary_key.reference @@ -1,13 +1,11 @@ 1000 10000 1000 10000 -test_02381 2000000 16112790 11904 16100886 -test_02381_compress 2000000 16099626 1658 16097968 +2000000 2000000 1 1 10000 100000 10000 100000 10000 100000 10000 100000 -test_02381 4000000 28098334 2946 28095388 -test_02381_compress 4000000 28125412 23616 28101796 +4000000 4000000 1 1 1 Hello 2 World 1 Hello diff --git a/tests/queries/0_stateless/02381_compress_marks_and_primary_key.sql b/tests/queries/0_stateless/02381_compress_marks_and_primary_key.sql index 7581e4a6d336..37de418bdde7 100644 --- a/tests/queries/0_stateless/02381_compress_marks_and_primary_key.sql +++ b/tests/queries/0_stateless/02381_compress_marks_and_primary_key.sql @@ -16,8 +16,15 @@ select * from test_02381_compress where a = 1000 limit 1; optimize table test_02381_compress final; select * from test_02381_compress where a = 1000 limit 1; --- Compare the size of marks on disk -select table, sum(rows), sum(bytes_on_disk) sum_bytes, sum(marks_bytes) sum_marks_bytes, (sum_bytes - sum_marks_bytes) exclude_marks from system.parts_columns where active and database = currentDatabase() and table like 'test_02381%' group by table order by table; +-- Compare the sizes on disk. The tables hold the same data, so the compressed marks are several times smaller, +-- and the rest of the part is smaller as well, because the primary key is compressed. +-- The exact sizes are not checked, because they depend on the versions of the compression libraries. +select + sumIf(rows, table = 'test_02381') as rows_plain, + sumIf(rows, table = 'test_02381_compress') as rows_compressed, + 3 * sumIf(marks_bytes, table = 'test_02381_compress') < sumIf(marks_bytes, table = 'test_02381') as marks_are_smaller, + sumIf(bytes_on_disk - marks_bytes, table = 'test_02381_compress') < sumIf(bytes_on_disk - marks_bytes, table = 'test_02381') as primary_key_is_smaller +from system.parts_columns where active and database = currentDatabase() and table like 'test_02381%'; -- Switch to compressed and uncompressed -- Test wide part @@ -35,7 +42,13 @@ select * from test_02381 where a = 10000 limit 1; optimize table test_02381 final; select * from test_02381 where a = 10000 limit 1; -select table, sum(rows), sum(bytes_on_disk) sum_bytes, sum(marks_bytes) sum_marks_bytes, (sum_bytes - sum_marks_bytes) exclude_marks from system.parts_columns where active and database = currentDatabase() and table like 'test_02381%' group by table order by table; +-- The tables have swapped the settings: now `test_02381` is the one with the compressed marks and primary key. +select + sumIf(rows, table = 'test_02381') as rows_compressed, + sumIf(rows, table = 'test_02381_compress') as rows_plain, + 3 * sumIf(marks_bytes, table = 'test_02381') < sumIf(marks_bytes, table = 'test_02381_compress') as marks_are_smaller, + sumIf(bytes_on_disk - marks_bytes, table = 'test_02381') < sumIf(bytes_on_disk - marks_bytes, table = 'test_02381_compress') as primary_key_is_smaller +from system.parts_columns where active and database = currentDatabase() and table like 'test_02381%'; drop table if exists test_02381; drop table if exists test_02381_compress; diff --git a/tests/queries/0_stateless/02477_invalid_reads.sql b/tests/queries/0_stateless/02477_invalid_reads.sql index f2f10296426a..bee4120396e4 100644 --- a/tests/queries/0_stateless/02477_invalid_reads.sql +++ b/tests/queries/0_stateless/02477_invalid_reads.sql @@ -65,6 +65,11 @@ SELECT finalizeAggregation(CAST(unhex('0F000000000000803F'), SELECT finalizeAggregation(CAST(unhex('01080000000000000000'), 'AggregateFunction(groupUniqArray, Tuple(String))')); -- { serverError INCORRECT_DATA } +-- LowCardinality(String) interns through ColumnUnique. Its arena record has a trailing byte, so an +-- encoded size of zero must be rejected instead of becoming SIZE_MAX at the hash input. +SELECT finalizeAggregation(CAST(unhex('0109000000000000000000'), + 'AggregateFunction(groupUniqArray, Tuple(Variant(LowCardinality(String))))')); -- { serverError INCORRECT_DATA } + -- uniq stores skip_degree as the first byte and thins hashes by 2 ^ skip_degree. Thinning cannot -- raise the degree beyond one past its budget, so a larger one is rejected. The last accepted -- degree still admits a count that saturates the hash space, which size() reports as its maximum. diff --git a/tests/queries/0_stateless/02714_local_object_storage.sh b/tests/queries/0_stateless/02714_local_object_storage.sh index fb44697ddeee..3f0698ebb8f6 100755 --- a/tests/queries/0_stateless/02714_local_object_storage.sh +++ b/tests/queries/0_stateless/02714_local_object_storage.sh @@ -12,13 +12,6 @@ settings=( --local_filesystem_read_method='pread' ) -server_path=$(${CLICKHOUSE_CLIENT} -q "SELECT path FROM system.disks WHERE name = 'default'") - -if [ "${server_path:0:1}" != "/" ]; then - echo "path should be absolute (path: $path)" >&2 - exit 1 -fi - $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " DROP TABLE IF EXISTS test; @@ -26,7 +19,7 @@ $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " ENGINE = MergeTree() ORDER BY tuple() SETTINGS disk = disk( type = 'local_blob_storage', - path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/'); + path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/'); INSERT INTO test SELECT 1, 'test'; SELECT * FROM test; @@ -39,7 +32,7 @@ $CLICKHOUSE_CLIENT "${settings[@]}" -nm -q " type = 'cache', max_size = '10Mi', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/', - disk = disk(type='local_blob_storage', path='${server_path}/disks/${CLICKHOUSE_TEST_UNIQUE_NAME}/')); + disk = disk(type='local_blob_storage', path='${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/')); INSERT INTO test SELECT 1, 'test'; SELECT * FROM test; diff --git a/tests/queries/0_stateless/02770_async_buffer_ignore.reference b/tests/queries/0_stateless/02770_async_buffer_ignore.reference index 9a9d6d6febfa..ad05a699da0d 100644 --- a/tests/queries/0_stateless/02770_async_buffer_ignore.reference +++ b/tests/queries/0_stateless/02770_async_buffer_ignore.reference @@ -1 +1 @@ -4 66446 66446 +1 1 1 1 diff --git a/tests/queries/0_stateless/02770_async_buffer_ignore.sh b/tests/queries/0_stateless/02770_async_buffer_ignore.sh index 429fdb4dd790..ce200f6c1ad2 100755 --- a/tests/queries/0_stateless/02770_async_buffer_ignore.sh +++ b/tests/queries/0_stateless/02770_async_buffer_ignore.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# Tags: no-fasttest, no-random-settings, no-distributed-cache +# Tags: no-fasttest, no-random-settings, no-distributed-cache, no-parallel-replicas +# Tag no-parallel-replicas: asserts on `ProfileEvents` of the initial query, but with parallel replicas the read may run on a remote replica CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -18,15 +19,22 @@ INSERT INTO test_s3 SELECT number, number FROM numbers(1000000); " query="SELECT sum(b) FROM test_s3 WHERE a >= 100000 AND a <= 102000" query_id=$(${CLICKHOUSE_CLIENT} -nm --query " -SET read_through_distributed_cache=0; +SET remote_filesystem_read_method='threadpool'; select queryID() from ($query) limit 1 " 2>&1) ${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" +# This query seeks each column once, from offset 0, so a correct lazy ignore never +# triggers: `AsynchronousReaderIgnoredBytes` is the oracle for the prefix over-read. +# `RemoteFSSeeks` guards against it passing vacuously on the synchronous path, +# where there is no `AsynchronousBoundedReadBuffer` to exercise. +# `ReadCompressedBytes` bounds granule selection only; it counts blocks handed to +# the decompressor and so cannot see a discarded prefix. ${CLICKHOUSE_CLIENT} -m --query " SELECT - ProfileEvents['S3ReadRequestsCount'], - ProfileEvents['ReadBufferFromS3Bytes'], - ProfileEvents['ReadCompressedBytes'] + ProfileEvents['RemoteFSSeeks'] > 0, + ProfileEvents['AsynchronousReaderIgnoredBytes'] = 0, + ProfileEvents['S3ReadRequestsCount'] < 100, + ProfileEvents['ReadCompressedBytes'] < 1000000 FROM system.query_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND type = 'QueryFinish' AND current_database = currentDatabase() diff --git a/tests/queries/0_stateless/02888_obsolete_settings.reference b/tests/queries/0_stateless/02888_obsolete_settings.reference index e6e3555b7746..eb5dde0a28bc 100644 --- a/tests/queries/0_stateless/02888_obsolete_settings.reference +++ b/tests/queries/0_stateless/02888_obsolete_settings.reference @@ -1,6 +1,9 @@ -- Obsolete server settings allow_experimental_webterminal allow_impersonate_user +database_catalog_unused_dir_cleanup_period_sec +database_catalog_unused_dir_hide_timeout_sec +database_catalog_unused_dir_rm_timeout_sec dictionaries_lib_path storage_metadata_write_full_object_key -- Obsolete general settings diff --git a/tests/queries/0_stateless/02947_merge_tree_index_table_2.reference b/tests/queries/0_stateless/02947_merge_tree_index_table_2.reference index bd02e316977c..3c3b7094849d 100644 --- a/tests/queries/0_stateless/02947_merge_tree_index_table_2.reference +++ b/tests/queries/0_stateless/02947_merge_tree_index_table_2.reference @@ -20,8 +20,8 @@ │ all_1_1_0 │ 3 │ 1 │ 4 │ 9 │ 19 │ (0,72) │ (0,72) │ (NULL,NULL) │ (0,27) │ (0,0) │ (0,72) │ (0,8) │ (0,66) │ (0,72) │ (0,108) │ (0,216) │ (0,72) │ (0,72) │ (NULL,NULL) │ (0,72) │ │ all_1_1_0 │ 4 │ 0 │ 4 │ 9 │ 19 │ (0,80) │ (0,80) │ (NULL,NULL) │ (0,36) │ (0,0) │ (0,80) │ (0,25) │ (0,84) │ (0,80) │ (0,120) │ (0,240) │ (0,80) │ (0,80) │ (NULL,NULL) │ (0,80) │ │ all_2_2_0 │ 0 │ 3 │ 0 │ 0 │ 96 │ (0,0) │ (42,0) │ (84,0) │ (NULL,NULL) │ (126,0) │ (NULL,NULL) │ (NULL,NULL) │ (165,0) │ (NULL,NULL) │ (232,0) │ (286,0) │ (NULL,NULL) │ (NULL,NULL) │ (342,0) │ (391,0) │ -│ all_2_2_0 │ 1 │ 2 │ 3 │ 3 │ 96 │ (433,0) │ (472,0) │ (511,0) │ (NULL,NULL) │ (550,0) │ (NULL,NULL) │ (NULL,NULL) │ (589,0) │ (NULL,NULL) │ (659,0) │ (717,0) │ (NULL,NULL) │ (NULL,NULL) │ (773,0) │ (817,0) │ -│ all_2_2_0 │ 2 │ 0 │ 4 │ 4 │ 96 │ (856,0) │ (856,0) │ (856,0) │ (NULL,NULL) │ (856,0) │ (NULL,NULL) │ (NULL,NULL) │ (856,0) │ (NULL,NULL) │ (856,0) │ (856,0) │ (NULL,NULL) │ (NULL,NULL) │ (856,0) │ (856,0) │ +│ all_2_2_0 │ 1 │ 2 │ 3 │ 3 │ 96 │ (433,0) │ (472,0) │ (511,0) │ (NULL,NULL) │ (550,0) │ (NULL,NULL) │ (NULL,NULL) │ (589,0) │ (NULL,NULL) │ (659,0) │ (712,0) │ (NULL,NULL) │ (NULL,NULL) │ (768,0) │ (812,0) │ +│ all_2_2_0 │ 2 │ 0 │ 4 │ 4 │ 96 │ (851,0) │ (851,0) │ (851,0) │ (NULL,NULL) │ (851,0) │ (NULL,NULL) │ (NULL,NULL) │ (851,0) │ (NULL,NULL) │ (851,0) │ (851,0) │ (NULL,NULL) │ (NULL,NULL) │ (851,0) │ (851,0) │ │ all_3_3_0 │ 0 │ 3 │ 0 │ 0 │ 96 │ (0,0) │ (0,0) │ (0,0) │ (NULL,NULL) │ (0,0) │ (0,0) │ (0,8) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (NULL,NULL) │ (0,0) │ │ all_3_3_0 │ 1 │ 3 │ 1 │ 6 │ 96 │ (0,24) │ (0,24) │ (0,24) │ (NULL,NULL) │ (0,24) │ (0,24) │ (0,8) │ (0,22) │ (0,24) │ (0,36) │ (0,72) │ (0,24) │ (0,24) │ (NULL,NULL) │ (0,24) │ │ all_3_3_0 │ 2 │ 3 │ 3 │ 3 │ 96 │ (0,48) │ (0,48) │ (0,48) │ (NULL,NULL) │ (0,48) │ (0,48) │ (0,8) │ (0,44) │ (0,48) │ (0,72) │ (0,144) │ (0,48) │ (0,48) │ (NULL,NULL) │ (0,48) │ diff --git a/tests/queries/0_stateless/02947_merge_tree_index_table_4.reference b/tests/queries/0_stateless/02947_merge_tree_index_table_4.reference index e5f33902d202..68a2783e8de8 100644 --- a/tests/queries/0_stateless/02947_merge_tree_index_table_4.reference +++ b/tests/queries/0_stateless/02947_merge_tree_index_table_4.reference @@ -20,8 +20,8 @@ │ all_1_1_0 │ 3 │ 1 │ 4 │ 9 │ 19 │ (0,72) │ (0,72) │ (NULL,NULL) │ (0,27) │ (0,0) │ (0,72) │ (0,8) │ (0,66) │ (0,72) │ (0,108) │ (0,216) │ (0,72) │ (0,72) │ (NULL,NULL) │ (0,72) │ │ all_1_1_0 │ 4 │ 0 │ 4 │ 9 │ 19 │ (0,80) │ (0,80) │ (NULL,NULL) │ (0,36) │ (0,0) │ (0,80) │ (0,25) │ (0,84) │ (0,80) │ (0,120) │ (0,240) │ (0,80) │ (0,80) │ (NULL,NULL) │ (0,80) │ │ all_2_2_0 │ 0 │ 3 │ 0 │ 0 │ 96 │ (0,0) │ (42,0) │ (84,0) │ (NULL,NULL) │ (126,0) │ (165,8) │ (165,32) │ (165,32) │ (232,0) │ (232,24) │ (286,24) │ (342,0) │ (342,24) │ (NULL,NULL) │ (391,0) │ -│ all_2_2_0 │ 1 │ 2 │ 3 │ 3 │ 96 │ (433,0) │ (472,0) │ (511,0) │ (NULL,NULL) │ (550,0) │ (589,8) │ (589,24) │ (589,24) │ (659,0) │ (659,16) │ (717,16) │ (773,0) │ (773,16) │ (NULL,NULL) │ (817,0) │ -│ all_2_2_0 │ 2 │ 0 │ 4 │ 4 │ 96 │ (856,0) │ (856,0) │ (856,0) │ (NULL,NULL) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (856,0) │ (NULL,NULL) │ (856,0) │ +│ all_2_2_0 │ 1 │ 2 │ 3 │ 3 │ 96 │ (433,0) │ (472,0) │ (511,0) │ (NULL,NULL) │ (550,0) │ (589,8) │ (589,24) │ (589,24) │ (659,0) │ (659,16) │ (712,16) │ (768,0) │ (768,16) │ (NULL,NULL) │ (812,0) │ +│ all_2_2_0 │ 2 │ 0 │ 4 │ 4 │ 96 │ (851,0) │ (851,0) │ (851,0) │ (NULL,NULL) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (851,0) │ (NULL,NULL) │ (851,0) │ │ all_3_3_0 │ 0 │ 3 │ 0 │ 0 │ 96 │ (0,0) │ (0,0) │ (0,0) │ (NULL,NULL) │ (0,0) │ (0,0) │ (0,8) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (0,0) │ (NULL,NULL) │ (0,0) │ │ all_3_3_0 │ 1 │ 3 │ 1 │ 6 │ 96 │ (0,24) │ (0,24) │ (0,24) │ (NULL,NULL) │ (0,24) │ (0,24) │ (0,8) │ (0,22) │ (0,24) │ (0,36) │ (0,72) │ (0,24) │ (0,24) │ (NULL,NULL) │ (0,24) │ │ all_3_3_0 │ 2 │ 3 │ 3 │ 3 │ 96 │ (0,48) │ (0,48) │ (0,48) │ (NULL,NULL) │ (0,48) │ (0,48) │ (0,8) │ (0,44) │ (0,48) │ (0,72) │ (0,144) │ (0,48) │ (0,48) │ (NULL,NULL) │ (0,48) │ diff --git a/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql b/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh old mode 100644 new mode 100755 similarity index 88% rename from tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql rename to tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh index 6b285d423e79..bdcbf491dcf2 --- a/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sql +++ b/tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh @@ -1,12 +1,19 @@ --- Tags: no-fasttest +#!/usr/bin/env bash +# Tags: no-fasttest + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +$CLICKHOUSE_CLIENT -q " drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test1/'); +settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test1/'); drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test2/'); -- { serverError BAD_ARGUMENTS } +settings disk=disk(name='02963_custom_disk', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test2/'); -- { serverError BAD_ARGUMENTS } drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() @@ -26,7 +33,7 @@ settings disk='s3_disk_02963'; drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() -settings disk=disk(name='s3_disk_02963', type = object_storage, object_storage_type = local_blob_storage, path='./02963_test2/'); -- { serverError BAD_ARGUMENTS } +settings disk=disk(name='s3_disk_02963', type = object_storage, object_storage_type = local_blob_storage, path='${CLICKHOUSE_DISKS_FILES}/02963_test2/'); -- { serverError BAD_ARGUMENTS } drop table if exists test; create table test (a Int32) engine = MergeTree() order by tuple() @@ -96,3 +103,4 @@ settings disk=disk(name='test7', endpoint = 'http://localhost:11111/test/common/', access_key_id = clickhouse, secret_access_key = clickhouse); -- { serverError UNKNOWN_ELEMENT_IN_CONFIG } +" diff --git a/tests/queries/0_stateless/03254_project_lwd_respects_row_exists.sql b/tests/queries/0_stateless/03254_project_lwd_respects_row_exists.sql index 9dbe18338b28..aec0d7279973 100644 --- a/tests/queries/0_stateless/03254_project_lwd_respects_row_exists.sql +++ b/tests/queries/0_stateless/03254_project_lwd_respects_row_exists.sql @@ -23,8 +23,7 @@ GROUP BY age SETTINGS optimize_use_projections = 1, force_optimize_projection = 1, parallel_replicas_local_plan = 1, parallel_replicas_support_projection = 1, optimize_aggregation_in_order = 0; -- tuple subcolumn in projection ORDER BY (PR #99043) --- _row_exists must be added to source_block separately from projection columns, --- and addSubcolumnsFromSortingKeyAndSkipIndicesExpression must materialize tup.a. +-- addSubcolumnsFromSortingKeyAndSkipIndicesExpression must materialize tup.a. DROP TABLE IF EXISTS users_tuple; CREATE TABLE users_tuple ( diff --git a/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh b/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh index e835186ddfb4..9ef3b3895ede 100755 --- a/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh +++ b/tests/queries/0_stateless/03362_merge_tree_with_background_refresh.sh @@ -18,7 +18,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/03362/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/03362/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query " @@ -30,7 +30,7 @@ SETTINGS table_disk = true, refresh_parts_interval = 1, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/03362/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/03362/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query "INSERT INTO writer VALUES ('Hello')"; diff --git a/tests/queries/0_stateless/03641_clickhouse_prefer_symbols_from_contrib_over_rust_crates.sh b/tests/queries/0_stateless/03641_clickhouse_prefer_symbols_from_contrib_over_rust_crates.sh index de5462ed7041..0cdeae9d1c10 100755 --- a/tests/queries/0_stateless/03641_clickhouse_prefer_symbols_from_contrib_over_rust_crates.sh +++ b/tests/queries/0_stateless/03641_clickhouse_prefer_symbols_from_contrib_over_rust_crates.sh @@ -19,8 +19,9 @@ if [ $($CLICKHOUSE_LOCAL -q "SELECT value = 'Darwin' FROM system.build_options W exit 0 fi +# ThinLTO repeats the DWARF entry of a function in every module that imports it, so compare the set of units. $CLICKHOUSE_LOCAL -q " -SELECT replaceRegexpOne(unit_name, '.*(contrib)', '\1') +SELECT DISTINCT replaceRegexpOne(unit_name, '.*(contrib)', '\1') FROM file('$(which $CLICKHOUSE_BINARY)', DWARF) WHERE name IN ('ZSTD_compressStream2', 'LZ4_compress_fast_extState') AND not(has(attr_name, 'declaration')) ORDER BY ALL diff --git a/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh b/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh index f18d0b9e3eff..9402ab467686 100755 --- a/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh +++ b/tests/queries/0_stateless/03776_local_object_storage_blob_storage_log.sh @@ -14,7 +14,7 @@ $CLICKHOUSE_CLIENT -q " CREATE TABLE test_local_blob_log (a Int32, b String) ENGINE = MergeTree() ORDER BY a - SETTINGS disk = disk(type = 'local_blob_storage', path = '03776_test_local_blob_log/'); + SETTINGS disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/03776_test_local_blob_log/'); INSERT INTO test_local_blob_log VALUES (1, 'test1'), (2, 'test2'), (3, 'test3'); diff --git a/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.reference b/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.reference index 050519e0a488..c344c935d0a3 100644 --- a/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.reference +++ b/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.reference @@ -5,7 +5,8 @@ -9223372036854756720 -9223372036854775808 2023-03-16 03:22:33.123 2023-03-16 19:22:33.123 1969-10-26 01:59:59.999 -1969-10-26 09:59:59.999 +1969-10-26 10:59:59.999 +1969-10-26 05:59:59.999 1945-09-16 02:59:59.999 1945-09-15 22:59:59.999 01:59:59.999 diff --git a/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.sql b/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.sql index 334dbb97a192..e4a029a90512 100644 --- a/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.sql +++ b/tests/queries/0_stateless/03891_utc_timestamp_datetime64_overflow.sql @@ -24,10 +24,12 @@ SELECT to_utc_timestamp(toDateTime64('2023-03-16 11:22:33.123', 3), 'Asia/Shangh -- one. America/New_York changes -04:00 -> -05:00 at 1969-10-26 06:00:00 UTC, so 05:59:59.999 UTC -- is still -04:00 and from_utc_timestamp must return 01:59:59.999, not 00:59:59.999 (negative offset). SELECT from_utc_timestamp(toDateTime64('1969-10-26 05:59:59.999', 3), 'America/New_York'); --- to_utc_timestamp must floor too: the underlying floor second 05:59:59 is -04:00, so the result --- is 09:59:59.999, not 10:59:59.999 (the -05:00 ceil second). This input straddles the boundary; --- the earlier 01:59:59.999 case did not and would pass even without flooring this direction. +-- to_utc_timestamp reads its argument as a New York local time: 05:59:59.999 on 1969-10-26 is after the change +-- to -05:00, so it is 10:59:59.999 UTC. SELECT to_utc_timestamp(toDateTime64('1969-10-26 05:59:59.999', 3), 'America/New_York'); +-- It must floor too: local 01:59:59 is still -04:00 and 02:00:00 is -05:00, so 01:59:59.999 is 05:59:59.999 UTC, +-- not 06:59:59.999. +SELECT to_utc_timestamp(toDateTime64('1969-10-26 01:59:59.999', 3), 'America/New_York'); -- Positive offset direction: Europe/Paris changes +02:00 -> +01:00 at 1945-09-16 01:00:00 UTC, -- so the floor second 00:59:59 UTC is still +02:00 and from_utc_timestamp must return 02:59:59.999. SELECT from_utc_timestamp(toDateTime64('1945-09-16 00:59:59.999', 3), 'Europe/Paris'); diff --git a/tests/queries/0_stateless/04089_merge_tree_refresh_after_merge.sh b/tests/queries/0_stateless/04089_merge_tree_refresh_after_merge.sh index 1d891275f11f..516910d6f32c 100755 --- a/tests/queries/0_stateless/04089_merge_tree_refresh_after_merge.sh +++ b/tests/queries/0_stateless/04089_merge_tree_refresh_after_merge.sh @@ -18,7 +18,7 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS writer SYNC" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS reader SYNC" -disk_path="disks/04089/${CLICKHOUSE_DATABASE}/" +disk_path="${CLICKHOUSE_DISKS_FILES}/04089/${CLICKHOUSE_DATABASE}/" ${CLICKHOUSE_CLIENT} --query " CREATE TABLE writer (s String) ORDER BY () diff --git a/tests/queries/0_stateless/04094_projection_with_where.sql b/tests/queries/0_stateless/04094_projection_with_where.sql index 97846284bb64..0560f23f9466 100644 --- a/tests/queries/0_stateless/04094_projection_with_where.sql +++ b/tests/queries/0_stateless/04094_projection_with_where.sql @@ -143,8 +143,8 @@ SETTINGS force_optimize_projection = 1; -- { serverError PROJECTION_NOT_USED } DROP TABLE t_proj_alias; -- A mutation must preserve the projection's WHERE while also applying the mutation. --- During mutation, the projection part is rematerialized with its WHERE combined with the --- `_row_exists` condition, so after `ALTER TABLE ... DELETE WHERE` the filtered projection must +-- During mutation, the projection part is rematerialized from the surviving rows with its WHERE +-- still applied, so after `ALTER TABLE ... DELETE WHERE` the filtered projection must -- contain only rows satisfying both the projection predicate and the (negated) delete condition. SELECT 'Mutation with filtered projection'; @@ -175,7 +175,7 @@ INSERT INTO t_proj_mut VALUES ALTER TABLE t_proj_mut MATERIALIZE PROJECTION proj_pageview_mut SETTINGS mutations_sync = 2; -- Delete one `pageview` row with a heavyweight mutation, which rematerializes the projection part --- (the projection's WHERE is combined with `_row_exists` during materialization). +-- (the projection's WHERE is applied to the surviving rows during materialization). ALTER TABLE t_proj_mut DELETE WHERE message = 'a' SETTINGS mutations_sync = 2; -- `force_optimize_projection = 1` proves the rebuilt projection (not the base table) is read, diff --git a/tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sql b/tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sh old mode 100644 new mode 100755 similarity index 59% rename from tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sql rename to tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sh index 5d9339acb866..6c64bd319d9b --- a/tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sql +++ b/tests/queries/0_stateless/04103_plain_rewritable_get_last_modified_bug.sh @@ -1,6 +1,14 @@ +#!/usr/bin/env bash +# Tags: no-object-storage, no-replicated-database, no-shared-merge-tree + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +$CLICKHOUSE_CLIENT -q " CREATE TABLE test_plain_rewr_ts_04103 (a Int32, b String) ENGINE = MergeTree() ORDER BY a -SETTINGS disk = disk(type = 'object_storage', object_storage_type = 'local', path = 'disks/plain_rewritable_04103/', metadata_type = 'plain_rewritable'); +SETTINGS disk = disk(type = 'object_storage', object_storage_type = 'local', path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/', metadata_type = 'plain_rewritable'); INSERT INTO test_plain_rewr_ts_04103 VALUES (1, 'hello'), (2, 'world'); @@ -10,3 +18,4 @@ SELECT FROM system.parts_columns WHERE database = currentDatabase() AND table = 'test_plain_rewr_ts_04103' AND active AND column = 'a' ORDER BY name; +" diff --git a/tests/queries/0_stateless/04105_blob_storage_log_read_local.sh b/tests/queries/0_stateless/04105_blob_storage_log_read_local.sh index b654e0e7f79a..6238f33636e3 100755 --- a/tests/queries/0_stateless/04105_blob_storage_log_read_local.sh +++ b/tests/queries/0_stateless/04105_blob_storage_log_read_local.sh @@ -12,7 +12,7 @@ $CLICKHOUSE_CLIENT -q " CREATE TABLE test_local_blob_log_read (a Int32, b String) ENGINE = MergeTree() ORDER BY a - SETTINGS disk = disk(type = 'local_blob_storage', path = '04105_test_local_blob_log_read/'); + SETTINGS disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/04105_test_local_blob_log_read/'); INSERT INTO test_local_blob_log_read VALUES (1, 'test1'), (2, 'test2'), (3, 'test3'); diff --git a/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.reference b/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.reference index 54b58171d8a1..10c796835490 100644 --- a/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.reference +++ b/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.reference @@ -64,7 +64,7 @@ With idx_l (set, hypothetical): --- CREATE rejects reserved auto_minmax_index_ name --- reserved index name --- CREATE rejects unknown index type --- -INCORRECT_QUERY +NOT_IMPLEMENTED --- type_full distinguishes parametrized index types --- i1 bloom_filter bloom_filter(0.01) i2 bloom_filter bloom_filter(0.001) diff --git a/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.sh b/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.sh index 9e2fb1cb4225..a8c65c375c61 100755 --- a/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.sh +++ b/tests/queries/0_stateless/04223_hypothetical_index_lifecycle.sh @@ -224,7 +224,7 @@ $CLICKHOUSE_CLIENT -n -q " DROP TABLE IF EXISTS t_hypo_bad; CREATE TABLE t_hypo_bad (a UInt64, b UInt64) ENGINE = MergeTree ORDER BY a; CREATE HYPOTHETICAL INDEX bad ON t_hypo_bad (b) TYPE no_such_type GRANULARITY 1; -" 2>&1 | grep -m1 -oE 'INCORRECT_QUERY|UNKNOWN_FUNCTION|BAD_ARGUMENTS' +" 2>&1 | grep -m1 -oE 'INCORRECT_QUERY|UNKNOWN_FUNCTION|BAD_ARGUMENTS|NOT_IMPLEMENTED' echo "--- type_full distinguishes parametrized index types ---" $CLICKHOUSE_CLIENT -n -q " diff --git a/tests/queries/0_stateless/04241_get_server_setting_live_values.reference b/tests/queries/0_stateless/04241_get_server_setting_live_values.reference index 627e1097cda3..6a4bd63af406 100644 --- a/tests/queries/0_stateless/04241_get_server_setting_live_values.reference +++ b/tests/queries/0_stateless/04241_get_server_setting_live_values.reference @@ -3,3 +3,4 @@ 1 1 1 +0 diff --git a/tests/queries/0_stateless/04241_get_server_setting_live_values.sql b/tests/queries/0_stateless/04241_get_server_setting_live_values.sql index 674c3c4b4523..cdfcd27a552d 100644 --- a/tests/queries/0_stateless/04241_get_server_setting_live_values.sql +++ b/tests/queries/0_stateless/04241_get_server_setting_live_values.sql @@ -27,3 +27,10 @@ SELECT toString(getServerSetting('mark_cache_policy')) SELECT toString(getServerSetting('keeper_hosts')) = (SELECT value FROM system.server_settings WHERE name = 'keeper_hosts') AS keeper_hosts_matches; + +-- The client evaluates an INSERT ... VALUES expression itself and has none of the server caches, so it stores 0. +DROP TABLE IF EXISTS t_04241_client_values; +CREATE TABLE t_04241_client_values (v UInt64) ENGINE = Memory; +INSERT INTO t_04241_client_values SETTINGS async_insert = 0, send_table_structure_on_insert_with_inline_data = 1 VALUES (getServerSetting('mark_cache_size')); +SELECT v FROM t_04241_client_values; +DROP TABLE t_04241_client_values; diff --git a/tests/queries/0_stateless/04305_adaptive_codec_default_merge.reference b/tests/queries/0_stateless/04305_adaptive_codec_default_merge.reference index 05ddc37191f5..935e03eef9c2 100644 --- a/tests/queries/0_stateless/04305_adaptive_codec_default_merge.reference +++ b/tests/queries/0_stateless/04305_adaptive_codec_default_merge.reference @@ -1,39 +1,39 @@ Adaptive ON all_1_2_1 a a 162666 800000 {'T64':13} -all_1_2_1 b b 400518 800000 {'LZ4':13} -all_1_2_1 c c 464728 488890 {'LZ4':7} +all_1_2_1 b b 400539 800000 {'LZ4':13} +all_1_2_1 c c 464688 488890 {'LZ4':7} all_1_2_1 c c.size 3676 800000 {'LZ4':13} -all_1_2_1 d d 400642 1600000 {'LZ4':13} +all_1_2_1 d d 400623 1600000 {'LZ4':13} all_1_2_1 e e 162666 800000 {'T64':13} all_1_2_1 e e.null 463 100000 {'LZ4':2} all_1_2_1 f f 174702 400000 {'T64':7} all_1_2_1 f f.size0 3645 800000 {'LZ4':13} Adaptive OFF -all_1_2_1 a a 400518 800000 {'LZ4':13} -all_1_2_1 b b 400518 800000 {'LZ4':13} -all_1_2_1 c c 464728 488890 {'LZ4':7} +all_1_2_1 a a 400539 800000 {'LZ4':13} +all_1_2_1 b b 400539 800000 {'LZ4':13} +all_1_2_1 c c 464688 488890 {'LZ4':7} all_1_2_1 c c.size 3676 800000 {'LZ4':13} -all_1_2_1 d d 400642 1600000 {'LZ4':13} -all_1_2_1 e e 400518 800000 {'LZ4':13} +all_1_2_1 d d 400623 1600000 {'LZ4':13} +all_1_2_1 e e 400539 800000 {'LZ4':13} all_1_2_1 e e.null 463 100000 {'LZ4':2} all_1_2_1 f f 401725 400000 {'LZ4':7} all_1_2_1 f f.size0 3645 800000 {'LZ4':13} Adaptive INSERT -all_1_1_0 a a 400518 800000 {'LZ4':13} -all_1_1_0 b b 400518 800000 {'LZ4':13} -all_1_1_0 c c 464728 488890 {'LZ4':7} +all_1_1_0 a a 400539 800000 {'LZ4':13} +all_1_1_0 b b 400539 800000 {'LZ4':13} +all_1_1_0 c c 464688 488890 {'LZ4':7} all_1_1_0 c c.size 3676 800000 {'LZ4':13} -all_1_1_0 d d 400642 1600000 {'LZ4':13} -all_1_1_0 e e 400518 800000 {'LZ4':13} +all_1_1_0 d d 400623 1600000 {'LZ4':13} +all_1_1_0 e e 400539 800000 {'LZ4':13} all_1_1_0 e e.null 463 100000 {'LZ4':2} all_1_1_0 f f 401725 400000 {'LZ4':7} all_1_1_0 f f.size0 3645 800000 {'LZ4':13} Adaptive MUTATION -all_1_1_0_2 a a 400518 800000 {'LZ4':13} -all_1_1_0_2 b b 400518 800000 {'LZ4':13} -all_1_1_0_2 c c 464728 488890 {'LZ4':7} +all_1_1_0_2 a a 400539 800000 {'LZ4':13} +all_1_1_0_2 b b 400539 800000 {'LZ4':13} +all_1_1_0_2 c c 464688 488890 {'LZ4':7} all_1_1_0_2 c c.size 3676 800000 {'LZ4':13} -all_1_1_0_2 d d 400642 1600000 {'LZ4':13} +all_1_1_0_2 d d 400623 1600000 {'LZ4':13} all_1_1_0_2 e e 185194 800000 {'T64':13} all_1_1_0_2 e e.null 463 100000 {'LZ4':2} all_1_1_0_2 f f 401725 400000 {'LZ4':7} diff --git a/tests/queries/0_stateless/04318_system_restart_disk_plain_rewritable.sh b/tests/queries/0_stateless/04318_system_restart_disk_plain_rewritable.sh index 1e834947cf92..854b19478441 100755 --- a/tests/queries/0_stateless/04318_system_restart_disk_plain_rewritable.sh +++ b/tests/queries/0_stateless/04318_system_restart_disk_plain_rewritable.sh @@ -23,7 +23,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04318/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04318/${CLICKHOUSE_DATABASE}/') " # Same backing path, but readonly and WITHOUT refresh_parts_interval, so the only way for @@ -37,7 +37,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04318/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04318/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query "INSERT INTO writer VALUES ('Hello')" diff --git a/tests/queries/0_stateless/04371_load_compact_part_non_adaptive_reader.sh b/tests/queries/0_stateless/04371_load_compact_part_non_adaptive_reader.sh index 32c41396c5c0..0c49518a0786 100755 --- a/tests/queries/0_stateless/04371_load_compact_part_non_adaptive_reader.sh +++ b/tests/queries/0_stateless/04371_load_compact_part_non_adaptive_reader.sh @@ -26,7 +26,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04371/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04371/${CLICKHOUSE_DATABASE}/') " # Same backing path, readonly, and non-adaptive granularity (index_granularity_bytes = 0) so that @@ -41,7 +41,7 @@ SETTINGS table_disk = true, index_granularity_bytes = 0, min_bytes_for_wide_part type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04371/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04371/${CLICKHOUSE_DATABASE}/') " # Same shared path and settings, but this reader picks parts up via the background @@ -58,7 +58,7 @@ SETTINGS table_disk = true, refresh_parts_interval = 1, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04371/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04371/${CLICKHOUSE_DATABASE}/') " # A single small insert produces a Compact part. diff --git a/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh b/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh index a9ba7bd33bcb..64c015304592 100755 --- a/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh +++ b/tests/queries/0_stateless/04421_merge_tree_refresh_parts_reschedule_after_error.sh @@ -22,7 +22,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04421/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04421/${CLICKHOUSE_DATABASE}/') " ${CLICKHOUSE_CLIENT} --query " @@ -34,7 +34,7 @@ SETTINGS table_disk = true, refresh_parts_interval = 1, type = object_storage, object_storage_type = local, metadata_type = plain_rewritable, - path = 'disks/04421/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04421/${CLICKHOUSE_DATABASE}/') " # Sanity check: the background refresh picks up the first part. diff --git a/tests/queries/0_stateless/04492_lightweight_delete_filtered_projection.sql b/tests/queries/0_stateless/04492_lightweight_delete_filtered_projection.sql index b518d5115ef8..794b82ca71d8 100644 --- a/tests/queries/0_stateless/04492_lightweight_delete_filtered_projection.sql +++ b/tests/queries/0_stateless/04492_lightweight_delete_filtered_projection.sql @@ -25,8 +25,8 @@ WHERE database = currentDatabase() AND table = 't_lwd_proj' AND name = 'proj_pv' DELETE FROM t_lwd_proj WHERE message = 'a' SETTINGS lightweight_deletes_sync = 2; --- After a lightweight delete the projection is rebuilt; the projection WHERE must be --- AND-combined with _row_exists, so only surviving pageview rows remain (c, d = 2 rows). +-- After a lightweight delete the projection is rebuilt from the surviving rows and its WHERE +-- still applies, so only surviving pageview rows remain (c, d = 2 rows). SELECT 'after', sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_proj' AND name = 'proj_pv' AND active; diff --git a/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.reference b/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.reference index aa1d5915c356..dc118c86261c 100644 --- a/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.reference +++ b/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.reference @@ -7,7 +7,7 @@ BAD_ARGUMENTS --- sparse_grams with no arguments --- BAD_ARGUMENTS --- vector_similarity with no arguments --- -INCORRECT_QUERY +NOT_IMPLEMENTED --- server is still alive --- 1 --- well-formed set is still accepted --- diff --git a/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.sh b/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.sh index 026dd989e7cb..e0d27466eccb 100755 --- a/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.sh +++ b/tests/queries/0_stateless/04499_hypothetical_index_missing_arguments.sh @@ -30,7 +30,7 @@ echo "--- sparse_grams with no arguments ---" $CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_noargs (b) TYPE sparse_grams GRANULARITY 1;" 2>&1 | grep -m1 -oE 'INCORRECT_QUERY|BAD_ARGUMENTS' echo "--- vector_similarity with no arguments ---" -$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_noargs (v) TYPE vector_similarity GRANULARITY 1;" 2>&1 | grep -m1 -oE 'INCORRECT_QUERY|BAD_ARGUMENTS' +$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_noargs (v) TYPE vector_similarity GRANULARITY 1;" 2>&1 | grep -m1 -oE 'INCORRECT_QUERY|BAD_ARGUMENTS|NOT_IMPLEMENTED' echo "--- server is still alive ---" $CLICKHOUSE_CLIENT -q "SELECT 1" diff --git a/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh b/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh index 6d8a269bc8a0..8cf55a313ecb 100755 --- a/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh +++ b/tests/queries/0_stateless/04545_read_only_disk_refresh_parts.sh @@ -16,7 +16,7 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS writer SYNC" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS reader SYNC" -disk_path="disks/04545/${CLICKHOUSE_DATABASE}/" +disk_path="${CLICKHOUSE_DISKS_FILES}/04545/${CLICKHOUSE_DATABASE}/" # Writer: a read-write plain_rewritable object-storage disk. ${CLICKHOUSE_CLIENT} --query " @@ -67,7 +67,7 @@ SETTINGS table_disk = true, type = object_storage, object_storage_type = local, metadata_type = local, - path = 'disks/04545_local/${CLICKHOUSE_DATABASE}/') + path = '${CLICKHOUSE_DISKS_FILES}/04545_local/${CLICKHOUSE_DATABASE}/') " 2>&1 | grep -qF "requires metadata stored on the object storage" && echo "local metadata read-only disk rejected for table_disk" ${CLICKHOUSE_CLIENT} --query "DROP TABLE IF EXISTS reader_local SYNC" diff --git a/tests/queries/0_stateless/04546_remote_fs_prefetch_huge_read_buffer_size.sh b/tests/queries/0_stateless/04546_remote_fs_prefetch_huge_read_buffer_size.sh index d2fa5fbe0512..351d75987a93 100755 --- a/tests/queries/0_stateless/04546_remote_fs_prefetch_huge_read_buffer_size.sh +++ b/tests/queries/0_stateless/04546_remote_fs_prefetch_huge_read_buffer_size.sh @@ -14,7 +14,7 @@ CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) ${CLICKHOUSE_CLIENT} -m --query " drop table if exists ${CLICKHOUSE_DATABASE}.test; create table ${CLICKHOUSE_DATABASE}.test (a UInt64, b String) ENGINE = MergeTree() ORDER BY tuple() -settings disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/'); +settings disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/'); insert into ${CLICKHOUSE_DATABASE}.test select number, toString(number) from numbers(100000); " diff --git a/tests/queries/0_stateless/04610_filesystem_cache_huge_prefetch_buffer_size.sh b/tests/queries/0_stateless/04610_filesystem_cache_huge_prefetch_buffer_size.sh index 36b0048896f6..2397f27a8846 100755 --- a/tests/queries/0_stateless/04610_filesystem_cache_huge_prefetch_buffer_size.sh +++ b/tests/queries/0_stateless/04610_filesystem_cache_huge_prefetch_buffer_size.sh @@ -21,7 +21,7 @@ settings disk = disk( name = '${CLICKHOUSE_TEST_UNIQUE_NAME}', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/', max_size = '1Gi', - disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}_blob/')); + disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}_blob/')); insert into ${CLICKHOUSE_DATABASE}.test select number, toString(number) from numbers(100000); " diff --git a/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python b/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python index 048ef838a2e0..2048c1728342 100644 --- a/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python +++ b/tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python @@ -5,7 +5,7 @@ # # A crafted `REPLICATED`-serialized column can trigger the same out-of-bounds read # (nested_column[index]) via two independent paths that SerializationReplicated must -# reject with INCORRECT_DATA (code 117), while the server stays alive: +# reject with INCORRECT_DATA (code 117): # # 1. out-of-bounds index: per-row indexes point past the nested ("elements") column. # Before the fix, only the index row count was validated, not the index values. @@ -16,15 +16,26 @@ # ColumnReplicated, not the nested column size), so without an explicit post-read # size check the nested column would silently end up smaller than num_elements. # -# The client speaks the raw native protocol pinned to revision 54482 +# Only a server may choose the `REPLICATED` kind, so the crafted columns arrive the way a real +# one does: in a result block, sent to clickhouse-client by a fake server. A block that a client +# sends to the server accepts only the default kind, so there such a column is rejected by its +# kind, before SerializationReplicated reads it, and the server must stay alive (the last scenario). +# +# Both sides speak the raw native protocol pinned to revision 54482 # (DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION, the minimum that enables REPLICATED), # so the set of exchanged, revision-gated fields is fixed and does not drift. import os import socket import struct +import sys import uuid +CURDIR = os.path.dirname(os.path.realpath(__file__)) +sys.path.insert(0, os.path.join(CURDIR, "helpers")) + +from fake_native_server import runClientAgainstFakeServer + CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") @@ -251,13 +262,17 @@ def readHeader(s): readKindStack(s) -def sendCraftedReplicatedBlock(s): +CLIENT_DATA = 2 +SERVER_DATA = 1 + + +def craftedReplicatedBlock(packet_type): limit = 4 num_elements = 1 oob_index = 0xFFFFFFFF ba = bytearray() - writeVarUInt(2, ba) # Data + writeVarUInt(packet_type, ba) # Data writeStringBinary("", ba) # table name serializeBlockInfo(ba) writeVarUInt(1, ba) # columns @@ -278,7 +293,7 @@ def sendCraftedReplicatedBlock(s): for _ in range(num_elements): ba.extend(struct.pack(" 90 rows survive in both base and projection. +SELECT 'compact base rows', count() FROM t_lwd_norm_proj_compact; +SELECT 'compact projection rows', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_lwd_norm_proj_compact' AND name = 'p' AND active; + +-- A read forced through the projection must not return deleted rows, and must match the same +-- read without the projection. +SELECT 'compact deleted leaked via projection', countIf(id % 11 = 0) +FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; + +SELECT 'compact projection read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; +SELECT 'compact base read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 0; + +-- A second lightweight DELETE: the rebuild must keep the rows removed by the first one, which +-- `_row_exists` now carries too. +DELETE FROM t_lwd_norm_proj_compact WHERE id % 13 = 0; + +SELECT 'compact second delete base rows', count() FROM t_lwd_norm_proj_compact SETTINGS optimize_use_projections = 0; +SELECT 'compact second delete projection rows', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_lwd_norm_proj_compact' AND name = 'p' AND active; + +SELECT 'compact second delete deleted leaked via projection', countIf(id % 11 = 0 OR id % 13 = 0) +FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; + +SELECT 'compact second delete projection read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; +SELECT 'compact second delete base read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_compact WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 0; + +DROP TABLE t_lwd_norm_proj_compact; + +-- Wide part (MutateSomePartColumns path). Pin min_bytes_for_full_part_storage = 0 so the runner +-- cannot randomize this small part into Packed storage, which would reroute to MutateAllPartColumns. +DROP TABLE IF EXISTS t_lwd_norm_proj_wide; +CREATE TABLE t_lwd_norm_proj_wide (id UInt64, g UInt8, v Int64, + PROJECTION p (SELECT id, g, v ORDER BY (g, id))) +ENGINE = MergeTree ORDER BY id +SETTINGS lightweight_mutation_projection_mode = 'rebuild', index_granularity = 4, + min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0; + +INSERT INTO t_lwd_norm_proj_wide SELECT number, number % 7, number * 10 FROM numbers(100); +DELETE FROM t_lwd_norm_proj_wide WHERE id % 11 = 0; + +SELECT 'wide storage', part_type, part_storage_type FROM system.parts +WHERE database = currentDatabase() AND table = 't_lwd_norm_proj_wide' AND active; + +SELECT 'wide base rows', count() FROM t_lwd_norm_proj_wide; +SELECT 'wide projection rows', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_lwd_norm_proj_wide' AND name = 'p' AND active; + +SELECT 'wide deleted leaked via projection', countIf(id % 11 = 0) +FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; + +SELECT 'wide projection read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; +SELECT 'wide base read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 0; + +-- apply_deleted_mask = 0 reads the deleted rows, which the rebuilt projection does not store, so the +-- projection is not used. +SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20 +SETTINGS apply_deleted_mask = 0, optimize_use_projections = 1, force_optimize_projection = 1; -- { serverError PROJECTION_NOT_USED } + +SELECT 'wide apply_deleted_mask = 0', count(), countIf(id % 11 = 0) +FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 SETTINGS apply_deleted_mask = 0; + +-- A second lightweight DELETE: the rebuild must keep the rows removed by the first one, which +-- `_row_exists` now carries too. +DELETE FROM t_lwd_norm_proj_wide WHERE id % 13 = 0; + +SELECT 'wide second delete base rows', count() FROM t_lwd_norm_proj_wide SETTINGS optimize_use_projections = 0; +SELECT 'wide second delete projection rows', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_lwd_norm_proj_wide' AND name = 'p' AND active; + +SELECT 'wide second delete deleted leaked via projection', countIf(id % 11 = 0 OR id % 13 = 0) +FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; + +SELECT 'wide second delete projection read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection = 1; +SELECT 'wide second delete base read', groupArray(id) FROM (SELECT id FROM t_lwd_norm_proj_wide WHERE g BETWEEN 2 AND 5 ORDER BY g, id LIMIT 20) +SETTINGS optimize_use_projections = 0; + +DROP TABLE t_lwd_norm_proj_wide; + +DROP TABLE IF EXISTS t_lwd_agg_proj; +CREATE TABLE t_lwd_agg_proj (id UInt64, g UInt8, PROJECTION p (SELECT g, count() GROUP BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS lightweight_mutation_projection_mode = 'rebuild', index_granularity = 4; + +INSERT INTO t_lwd_agg_proj SELECT number, number % 3 FROM numbers(12); +DELETE FROM t_lwd_agg_proj WHERE id % 2 = 0; + +SELECT g, count() FROM t_lwd_agg_proj GROUP BY g ORDER BY g +SETTINGS apply_deleted_mask = 0, optimize_use_projections = 1, force_optimize_projection = 1; -- { serverError PROJECTION_NOT_USED } + +SELECT 'aggregate apply_deleted_mask = 0', g, count() FROM t_lwd_agg_proj GROUP BY g ORDER BY g SETTINGS apply_deleted_mask = 0; +SELECT 'aggregate projection', g, count() FROM t_lwd_agg_proj GROUP BY g ORDER BY g SETTINGS optimize_use_projections = 1, force_optimize_projection = 1; + +DROP TABLE t_lwd_agg_proj; + +-- Projection index: stores the parent `_part_offset` ordered by the indexed column. +DROP TABLE IF EXISTS t_lwd_proj_index; +CREATE TABLE t_lwd_proj_index (a UInt32, b UInt32, PROJECTION p INDEX b TYPE basic) +ENGINE = MergeTree ORDER BY a +SETTINGS lightweight_mutation_projection_mode = 'rebuild', index_granularity = 4, min_bytes_for_full_part_storage = 0; + +INSERT INTO t_lwd_proj_index SELECT number, number % 13 FROM numbers(100); +DELETE FROM t_lwd_proj_index WHERE a % 11 = 0; + +-- `a` equals the base `_part_offset` here, so a deleted row's offset is a multiple of 11. +SELECT 'index projection rows', count(), countIf(_parent_part_offset % 11 = 0) +FROM mergeTreeProjection(currentDatabase(), t_lwd_proj_index, p); +SELECT 'index parent-offset matches', sum(l.b = r.b), count() +FROM t_lwd_proj_index l JOIN mergeTreeProjection(currentDatabase(), t_lwd_proj_index, p) r ON l._part_offset = r._parent_part_offset +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +DROP TABLE t_lwd_proj_index; + +-- Projection that references no column: the source block must still carry the surviving row count. +DROP TABLE IF EXISTS t_lwd_count_proj; +CREATE TABLE t_lwd_count_proj (x UInt64, PROJECTION p (SELECT count() GROUP BY 0)) +ENGINE = MergeTree ORDER BY x +SETTINGS lightweight_mutation_projection_mode = 'rebuild', index_granularity = 4; + +INSERT INTO t_lwd_count_proj SELECT number FROM numbers(10); +DELETE FROM t_lwd_count_proj WHERE x < 3; + +SELECT 'count projection', count() FROM t_lwd_count_proj +SETTINGS optimize_use_projections = 1, force_optimize_projection = 1, optimize_trivial_count_query = 0; + +DROP TABLE t_lwd_count_proj; diff --git a/tests/queries/0_stateless/04630_text_index_serialization_version_compatibility.sh b/tests/queries/0_stateless/04630_text_index_serialization_version_compatibility.sh index a684eb4b669d..880d64073967 100755 --- a/tests/queries/0_stateless/04630_text_index_serialization_version_compatibility.sh +++ b/tests/queries/0_stateless/04630_text_index_serialization_version_compatibility.sh @@ -43,7 +43,9 @@ SELECT count() FROM tab WHERE hasPhrase(str, 'qux quux'); echo '-- the part merged under the pin contains the positions substream' part_path=$($CLICKHOUSE_LOCAL --path "$data_path" -q "SELECT path FROM system.parts WHERE database = currentDatabase() AND table = 'tab' AND active") -if [ -f "${part_path}skp_idx_text_idx.pos.idx" ]; then +# The file name is hashed on case-insensitive file systems. +hashed_name=$($CLICKHOUSE_LOCAL -q "SELECT lower(hex(reverse(sipHash128('skp_idx_text_idx.pos'))))") +if [ -f "${part_path}skp_idx_text_idx.pos.idx" ] || [ -f "${part_path}${hashed_name}.idx" ]; then echo 'positions file exists' else echo "no positions file in $part_path:" diff --git a/tests/queries/0_stateless/04661_vector_search_quantize_pq_codebook_mark_range.sh b/tests/queries/0_stateless/04661_vector_search_quantize_pq_codebook_mark_range.sh index 2640c31613e2..f7f1da26c0cf 100755 --- a/tests/queries/0_stateless/04661_vector_search_quantize_pq_codebook_mark_range.sh +++ b/tests/queries/0_stateless/04661_vector_search_quantize_pq_codebook_mark_range.sh @@ -28,7 +28,7 @@ ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1024, index_granularity_bytes = '10Mi', min_bytes_for_wide_part = 0, min_compress_block_size = 65536, max_compress_block_size = 1048576, min_columns_to_activate_adaptive_write_buffer = 1, adaptive_write_buffer_initial_size = 16384, - disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_TEST_UNIQUE_NAME}/'); + disk = disk(type = 'local_blob_storage', path = '${CLICKHOUSE_DISKS_FILES}/${CLICKHOUSE_TEST_UNIQUE_NAME}/'); -- ~10 granules in a single wide part. INSERT INTO quantize_pq_codebook_mark_range diff --git a/tests/queries/0_stateless/04757_hypothetical_index_supported_types.reference b/tests/queries/0_stateless/04757_hypothetical_index_supported_types.reference index 7c4f7c2fb249..a763108d5445 100644 --- a/tests/queries/0_stateless/04757_hypothetical_index_supported_types.reference +++ b/tests/queries/0_stateless/04757_hypothetical_index_supported_types.reference @@ -9,9 +9,9 @@ sparse_grams(3, 100, 512, 2, 0): applicable empirical Supported types: bloom_filter, minmax, ngrambf_v1, set, sparse_grams, tokenbf_v1 NOT_IMPLEMENTED NOT_IMPLEMENTED ---- validate still runs before the allowlist check --- -ILLEGAL_INDEX -INCORRECT_QUERY +--- the allowlist check runs before validate --- +NOT_IMPLEMENTED +NOT_IMPLEMENTED --- arguments the creator rejects fail at CREATE, not later --- BAD_ARGUMENTS --- a schema change that invalidates the index degrades to not_applicable --- diff --git a/tests/queries/0_stateless/04757_hypothetical_index_supported_types.sh b/tests/queries/0_stateless/04757_hypothetical_index_supported_types.sh index 059a11f01cc3..957b721e92fb 100755 --- a/tests/queries/0_stateless/04757_hypothetical_index_supported_types.sh +++ b/tests/queries/0_stateless/04757_hypothetical_index_supported_types.sh @@ -36,11 +36,11 @@ echo "$error" | grep -oE 'Supported types: [a-z0-9_, ]+' | head -1 echo "$error" | grep -oE 'NOT_IMPLEMENTED' | head -1 $CLICKHOUSE_CLIENT -q "SET allow_experimental_full_text_index = 1; CREATE HYPOTHETICAL INDEX hi ON t_hypo_types (s) TYPE text(tokenizer = 'array') GRANULARITY 1;" 2>&1 | grep -oE 'NOT_IMPLEMENTED' | head -1 -echo "--- validate still runs before the allowlist check ---" -# 'hypothesis' is registered but its validator rejects it outright, so that error must win -$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_types (a > 0) TYPE hypothesis GRANULARITY 1;" 2>&1 | grep -oE 'ILLEGAL_INDEX' | head -1 -# an unregistered type is rejected by the factory lookup, not by the allowlist -$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_types (s) TYPE no_such_index GRANULARITY 1;" 2>&1 | grep -oE 'INCORRECT_QUERY' | head -1 +echo "--- the allowlist check runs before validate ---" +# the validator of 'hypothesis' rejects it, but the allowlist rejects it first +$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_types (a > 0) TYPE hypothesis GRANULARITY 1;" 2>&1 | grep -oE 'ILLEGAL_INDEX|NOT_IMPLEMENTED' | head -1 +# the allowlist also rejects an unregistered type, before the factory lookup +$CLICKHOUSE_CLIENT -q "CREATE HYPOTHETICAL INDEX hi ON t_hypo_types (s) TYPE no_such_index GRANULARITY 1;" 2>&1 | grep -oE 'INCORRECT_QUERY|NOT_IMPLEMENTED' | head -1 echo "--- arguments the creator rejects fail at CREATE, not later ---" # sparse_grams tokenizer bounds are enforced by the creator; validate only checks arity diff --git a/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.reference b/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.reference new file mode 100644 index 000000000000..1abc6d4b269e --- /dev/null +++ b/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.reference @@ -0,0 +1,13 @@ +open range (9,-294876) (9,-294876) +closed range (9,-294876) (9,-294876) +two functions after cast (15,-119) (15,-119) +single point (1,-50) (1,-50) +functions in the other order (15,-119) (15,-119) +unsigned key (11,165) (11,165) +wrapped in (3,-20) (3,-20) +granules read 1 +no cast (15,-119) (15,-119) +chain granules read, lightweight analysis 1 +wrapped in granules read, lightweight analysis 1 +chain granules read, full analysis 1 +wrapped in granules read, full analysis 1 diff --git a/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.sql b/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.sql new file mode 100644 index 000000000000..489112154e69 --- /dev/null +++ b/tests/queries/0_stateless/04948_key_condition_widening_cast_block_ref.sql @@ -0,0 +1,96 @@ +-- A condition that wraps the primary key in a widening integer cast and then applies another +-- monotonic function on top of it must return exactly the rows a table without a sort key returns. +-- Every check prints (count, sum) for the sorted table next to (count, sum) for an identical table +-- with no sort key, so the two tuples on a line must be equal. + +DROP TABLE IF EXISTS t_wpk_edge; +DROP TABLE IF EXISTS t_wpk_edge_unsorted; +DROP TABLE IF EXISTS t_wpk_chain; +DROP TABLE IF EXISTS t_wpk_chain_unsorted; +DROP TABLE IF EXISTS t_wpk_unsigned; +DROP TABLE IF EXISTS t_wpk_unsigned_unsorted; + +CREATE TABLE t_wpk_edge (x Int16) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 8; +CREATE TABLE t_wpk_edge_unsorted (x Int16) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8; +INSERT INTO t_wpk_edge SELECT toInt64(number) - 32768 FROM numbers(16); +INSERT INTO t_wpk_edge_unsorted SELECT toInt64(number) - 32768 FROM numbers(16); + +CREATE TABLE t_wpk_chain (x Int16) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 8; +CREATE TABLE t_wpk_chain_unsorted (x Int16) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8; +INSERT INTO t_wpk_chain SELECT toInt64(number) - 50 FROM numbers(64); +INSERT INTO t_wpk_chain_unsorted SELECT toInt64(number) - 50 FROM numbers(64); + +CREATE TABLE t_wpk_unsigned (x UInt16) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 8; +CREATE TABLE t_wpk_unsigned_unsorted (x UInt16) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 8; +INSERT INTO t_wpk_unsigned SELECT number FROM numbers(64); +INSERT INTO t_wpk_unsigned_unsorted SELECT number FROM numbers(64); + +-- The cast reaches the smallest value of the key type, where the extra width changes the result. +SELECT 'open range', + (SELECT (count(), sum(x)) FROM t_wpk_edge WHERE negate(toInt64(x)) >= 32760), + (SELECT (count(), sum(x)) FROM t_wpk_edge_unsorted WHERE negate(toInt64(x)) >= 32760); + +SELECT 'closed range', + (SELECT (count(), sum(x)) FROM t_wpk_edge WHERE negate(toInt64(x)) BETWEEN 32760 AND 32768), + (SELECT (count(), sum(x)) FROM t_wpk_edge_unsorted WHERE negate(toInt64(x)) BETWEEN 32760 AND 32768); + +-- Two more functions after the cast. +SELECT 'two functions after cast', + (SELECT (count(), sum(x)) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) BETWEEN 10 AND 20), + (SELECT (count(), sum(x)) FROM t_wpk_chain_unsorted WHERE abs(negate(toInt64(x))) BETWEEN 10 AND 20); + +SELECT 'single point', + (SELECT (count(), sum(x)) FROM t_wpk_chain WHERE abs(negate(toInt32(x))) = 50), + (SELECT (count(), sum(x)) FROM t_wpk_chain_unsorted WHERE abs(negate(toInt32(x))) = 50); + +SELECT 'functions in the other order', + (SELECT (count(), sum(x)) FROM t_wpk_chain WHERE negate(abs(toInt64(x))) BETWEEN -20 AND -10), + (SELECT (count(), sum(x)) FROM t_wpk_chain_unsorted WHERE negate(abs(toInt64(x))) BETWEEN -20 AND -10); + +SELECT 'unsigned key', + (SELECT (count(), sum(x)) FROM t_wpk_unsigned WHERE abs(negate(toUInt64(x))) BETWEEN 10 AND 20), + (SELECT (count(), sum(x)) FROM t_wpk_unsigned_unsorted WHERE abs(negate(toUInt64(x))) BETWEEN 10 AND 20); + +-- A set membership test reaches the key bounds through the key's set index, so a chain wrapped in +-- `IN` is analysed over the same bounds as one wrapped in a range comparison. +SELECT 'wrapped in', + (SELECT (count(), sum(x)) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) IN (10, 20)), + (SELECT (count(), sum(x)) FROM t_wpk_chain_unsorted WHERE abs(negate(toInt64(x))) IN (10, 20)); + +-- A cast alone still narrows the read down to the granules that can hold matching rows. +SELECT 'granules read', count() > 0 +FROM (EXPLAIN indexes = 1 SELECT sum(x) FROM t_wpk_chain WHERE toInt64(x) BETWEEN -50 AND -40) +WHERE explain ILIKE '%Granules: 2/8%'; + +-- The same chain with no cast, as a control: a failure here points outside the cast path. +SELECT 'no cast', + (SELECT (count(), sum(x)) FROM t_wpk_chain WHERE abs(negate(x)) BETWEEN 10 AND 20), + (SELECT (count(), sum(x)) FROM t_wpk_chain_unsorted WHERE abs(negate(x)) BETWEEN 10 AND 20); + +-- A widening cast followed by another monotonic function must still prune. Result comparisons +-- alone cannot show this: a chain that declines analysis reads every granule and returns the +-- same correct rows. +SET use_lightweight_primary_key_index_analysis = 1; +SELECT 'chain granules read, lightweight analysis', count() > 0 +FROM (EXPLAIN indexes = 1 SELECT sum(x) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) BETWEEN 10 AND 20) +WHERE explain ILIKE '%Granules: 5/8%'; + +SELECT 'wrapped in granules read, lightweight analysis', count() > 0 +FROM (EXPLAIN indexes = 1 SELECT sum(x) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) IN (10, 20)) +WHERE explain ILIKE '%Granules: 5/8%'; + +SET use_lightweight_primary_key_index_analysis = 0; +SELECT 'chain granules read, full analysis', count() > 0 +FROM (EXPLAIN indexes = 1 SELECT sum(x) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) BETWEEN 10 AND 20) +WHERE explain ILIKE '%Granules: 5/8%'; + +SELECT 'wrapped in granules read, full analysis', count() > 0 +FROM (EXPLAIN indexes = 1 SELECT sum(x) FROM t_wpk_chain WHERE abs(negate(toInt64(x))) IN (10, 20)) +WHERE explain ILIKE '%Granules: 5/8%'; + +DROP TABLE t_wpk_edge; +DROP TABLE t_wpk_edge_unsorted; +DROP TABLE t_wpk_chain; +DROP TABLE t_wpk_chain_unsorted; +DROP TABLE t_wpk_unsigned; +DROP TABLE t_wpk_unsigned_unsorted; diff --git a/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python new file mode 100644 index 000000000000..db56872e4742 --- /dev/null +++ b/tests/queries/0_stateless/05061_query_log_interface_enum_unknown.python @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# `ClientInfo::read` stores the reported `interface` and `http_method` bytes without checking that +# they name an enumerator, so `system.query_log` and `system.processes` must be able to render any +# byte a client sends. This script speaks the raw native protocol to report values outside both +# enums. +# +# The queries are sent as `SECONDARY_QUERY`. That is the query kind whose reported interface is +# allowed to differ from the receiving session's: a query forwarded to a shard carries the +# initiator's interface, so an HTTP initiator forwarding over a native TCP connection reports +# `HTTP` on a TCP session, and `validateClientInfo` exempts it. An `INITIAL_QUERY` reporting +# anything but the session's own interface is refused with `CLIENT_INFO_DOES_NOT_MATCH` wherever +# `validate_tcp_client_information` is on, which includes the stateless-test server. +# +# The revision is pinned to 54484, the newest one whose `ClientInfo` layout is fully written below +# (`client_agent` is added at 54485), so the set of exchanged fields is fixed and does not drift. + +import os +import socket +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "interface enum poc" + +REVISION = 54484 + +INTERFACE_TCP = 1 +INTERFACE_HTTP = 2 +# Each `*_LOW` byte is the smallest value its own enum does not name, so a projection keyed on a +# threshold instead of on membership either passes it through, and rendering then throws, or has +# already remapped a named value that `03258_refreshable_mv_misc` and `04306_create_handler_http` +# pin. 200 narrows to -56, keeping the negative `Int8` class armed. Adding an enumerator to either +# enum moves that field's `*_LOW` byte: it is the next value that enum would allocate. +INTERFACE_UNMAPPED_LOW = 12 +HTTP_METHOD_UNMAPPED_LOW = 7 +UNMAPPED_HIGH_BIT = 200 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) + writeStringBinary("default", ba) # user + writeStringBinary("", ba) # password + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version (>= 54471) + readStringBinary(s) # timezone (>= 54058) + readStringBinary(s) # display name (>= 54372) + readVarUInt(s) # version patch (>= 54401) + readStringBinary(s) # proto_send chunked (>= 54470) + readStringBinary(s) # proto_recv chunked (>= 54470) + for _ in range(readVarUInt(s)): # password complexity rules (>= 54461) + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce, UInt64 (>= 54462) + while True: # server settings in STRINGS_WITH_FLAGS format (>= 54474) + if readStringBinary(s) == "": + break + readVarUInt(s) # flags + readStringBinary(s) # value + readVarUInt(s) # query plan serialization version (>= 54477) + readVarUInt(s) # cluster function protocol version (>= 54479) + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key (>= 54458) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # parallel replicas protocol version (>= 54471) + s.sendall(ba) + + +def serializeClientInfo(ba, query_id, interface, http_method): + ba.append(2) # SECONDARY_QUERY + writeStringBinary("default", ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds (>= 54449) + ba.append(interface) + if interface == INTERFACE_TCP: + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + elif interface == INTERFACE_HTTP: + ba.append(http_method) + writeStringBinary(CLIENT_NAME, ba) # http_user_agent + writeStringBinary("", ba) # forwarded_for (>= 54443) + writeStringBinary("", ba) # http_referer (>= 54447) + writeStringBinary("", ba) # quota key (>= 54060) + writeVarUInt(0, ba) # distributed_depth (>= 54448) + if interface == INTERFACE_TCP: + writeVarUInt(1, ba) # client version patch (>= 54401) + ba.append(0) # opentelemetry: no trace id (>= 54442) + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator (>= 54453) + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number (>= 54475) + writeVarUInt(0, ba) # script line number (>= 54475) + ba.append(0) # jwt: none (>= 54476) + + +def sendQuery(s, query, interface, http_method, query_id, settings): + ba = bytearray() + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id, interface, http_method) + for key, value in settings.items(): + writeStringBinary(key, ba) + writeVarUInt(1, ba) # is_important + writeStringBinary(str(value), ba) + writeStringBinary("", ba) # end of per-query settings + writeStringBinary("", ba) # interserver externally granted roles (>= 54472) + writeStringBinary("", ba) # interserver secret (>= 54441) + writeVarUInt(2, ba) # stage = Complete + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator (>= 54459) + s.sendall(ba) + + +def sendEmptyBlock(s): + ba = bytearray() + writeVarUInt(2, ba) # Data + writeStringBinary("", ba) + writeVarUInt(1, ba) # block info field 1 + ba.append(0) # is_overflows = false + writeVarUInt(2, ba) # block info field 2 + ba.extend((-1).to_bytes(4, "little", signed=True)) # bucket_num = -1 + writeVarUInt(0, ba) # end of block info + writeVarUInt(0, ba) # columns + writeVarUInt(0, ba) # rows + s.sendall(ba) + + +def expectQueryAccepted(s): + # Any first packet other than an `Exception` proves the server accepted the reported client info: + # a `SELECT` answers with its result header once the query has started, and a completed + # `INSERT ... SELECT` run with `interactive_delay = 0` answers only after its commit. The rest of + # the stream is not read. + packet_type = readVarUInt(s) + if packet_type == 2: # Exception + readUInt(s, 4) # code + readStringBinary(s) # name + raise RuntimeError("Unexpected exception: {}".format(readStringBinary(s))) + + +def runQuery(label, query, interface, http_method, query_id=None, settings=None): + query_id = query_id or uuid.uuid4().hex + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.settimeout(30) + s.connect((CLICKHOUSE_HOST, CLICKHOUSE_PORT)) + sendHello(s) + receiveHello(s) + sendAddendum(s) + sendQuery(s, query, interface, http_method, query_id, settings or {}) + sendEmptyBlock(s) + expectQueryAccepted(s) + print("{}: query accepted".format(label)) + + +def observeSelfInProcesses(label, interface, http_method): + # `system.processes` is filled from the live process list, so a running query sees its own row + # and can persist what the server renders for it. That is the only way to assert on + # `system.processes`: it holds nothing once the query has ended. + query_id = uuid.uuid4().hex + # With `interactive_delay = 0` the server runs a completed pipeline without a periodic progress + # callback, so the first packet it sends is the one after the INSERT has committed. A client that + # disconnects while such a pipeline is still running has its query cancelled, losing the row. + runQuery( + label, + "INSERT INTO processes_snapshot " + "SELECT toString(interface), toString(http_method) " + "FROM system.processes WHERE query_id = '{}'".format(query_id), + interface, + http_method, + query_id, + settings={"interactive_delay": 0}, + ) + + +def main(): + runQuery( + "reported interface out of domain", + "SELECT 1 SETTINGS log_comment = 'interface_enum_unknown'", + INTERFACE_UNMAPPED_LOW, + 0, + ) + runQuery( + "reported http_method out of domain", + "SELECT 2 SETTINGS log_comment = 'http_method_enum_unknown'", + INTERFACE_HTTP, + UNMAPPED_HIGH_BIT, + ) + # Two queries, because one cannot report an out-of-domain value for both columns at once: + # `http_method` is only read off the wire when the reported interface is `HTTP`. + # The `system.processes` probes carry the other byte of each pair, so both projections are + # reported both classes across their two call sites. + observeSelfInProcesses("processes: reported interface out of domain", UNMAPPED_HIGH_BIT, 0) + observeSelfInProcesses( + "processes: reported http_method out of domain", INTERFACE_HTTP, HTTP_METHOD_UNMAPPED_LOW + ) + + +if __name__ == "__main__": + main() diff --git a/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference b/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference index ca36e0892c1a..235f48b8dcc7 100644 --- a/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference +++ b/tests/queries/0_stateless/05141_http_dictionary_hide_header_values.reference @@ -1,4 +1,4 @@ -CREATE DICTIONARY default.d_05141\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'http://localhost:11111/x.tsv\' FORMAT \'TabSeparated\' CREDENTIALS (USER \'user\' PASSWORD \'[HIDDEN]\') HEADERS (\'[HIDDEN]\')))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) +CREATE DICTIONARY default.d_05141\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'TabSeparated\' CREDENTIALS (USER \'user\' PASSWORD \'[HIDDEN]\') HEADERS (\'[HIDDEN]\')))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) 0 0 1 d_05141_flat HEADERS \'[HIDDEN]\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) d_05141_foo HEADERS (\'[HIDDEN]\'))) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) diff --git a/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference new file mode 100644 index 000000000000..2c3e1cbad3a7 --- /dev/null +++ b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.reference @@ -0,0 +1,5 @@ +1 1 +1 +1 +identical value accepted under readonly +1 diff --git a/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh new file mode 100755 index 000000000000..42cf354af3b6 --- /dev/null +++ b/tests/queries/0_stateless/05153_reassign_ast_valued_custom_setting.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A custom setting (enabled by `custom_settings_prefixes`) can hold an AST rather than a literal, e.g. +# `custom_x = disk(type = 's3', ...)`. Assigning such a setting a second time compares the new value +# with the one the session already holds, and both sides being AST-valued is the only way to reach +# that comparison. `custom_x` lives for the lifetime of an HTTP session, so every statement below runs +# in one session. + +SESSION="05153_$CLICKHOUSE_DATABASE" + +# A successful SET writes nothing, so no request below is redirected: an exception body would land in +# the output and no longer match the reference. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153first', secret_access_key = 'c05153secret')" + +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153second', secret_access_key = 'c05153secret')" + +# The second value wins. `name` is one of the arguments the credential masker leaves visible. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT + position(value, 'c05153second') > 0, + position(value, 'c05153first') = 0 + FROM system.settings WHERE name = 'custom_x'" + +# Re-assigning the identical value is accepted too. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153second', secret_access_key = 'c05153secret')" +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT position(value, 'c05153second') > 0 FROM system.settings WHERE name = 'custom_x'" + +# A nested SETTINGS clause is clamped against the session value rather than refused, which reaches the +# same comparison through a different caller. The inner scope sees the nested value. +${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&session_id=$SESSION" \ + --data-binary "SELECT * FROM ( + SELECT position(value, 'c05153nested') > 0 + FROM system.settings WHERE name = 'custom_x' + SETTINGS custom_x = disk(type = 's3', name = 'c05153nested') + )" + +# Under `readonly = 1` a setting change is refused, but an assignment the constraint check judges +# unchanged returns before that check (`SettingsConstraints.cpp:362`), so the comparison's verdict is +# observable: an exact repeat stays silent, while a value differing only in its credential is refused. +# `readonly = 1` also refuses the settings the test runner appends to the URL, so this session's URL +# carries nothing but the session id. +RO_SESSION="05153_ro_$CLICKHOUSE_DATABASE" +RO_URL="${CLICKHOUSE_URL%%\?*}?session_id=$RO_SESSION" + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153secret')" +${CLICKHOUSE_CURL} -sS "$RO_URL" --data-binary "SET readonly = 1" + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153secret')" +echo 'identical value accepted under readonly' + +${CLICKHOUSE_CURL} -sS "$RO_URL" \ + --data-binary "SET custom_x = disk(type = 's3', name = 'c05153ro', secret_access_key = 'c05153other')" 2>&1 \ + | grep -c "Cannot modify 'custom_x' setting in readonly mode" diff --git a/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.reference b/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.reference new file mode 100644 index 000000000000..0595ebd73dfe --- /dev/null +++ b/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.reference @@ -0,0 +1,29 @@ +0 +3 +0 100 +1 100 +2 100 +3 3 +4 4 +0 200 +1 200 +2 200 +3 3 +4 4 +0 250 +1 200 +2 250 +3 3 +4 4 +0 250 +1 260 +2 250 +3 3 +4 4 +0 300 +1 300 +2 300 +3 3 +4 4 +3 3 +4 4 diff --git a/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.sql b/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.sql new file mode 100644 index 000000000000..3ece6f512d78 --- /dev/null +++ b/tests/queries/0_stateless/05182_lightweight_update_materialized_cte_in_subquery.sql @@ -0,0 +1,50 @@ +-- Lightweight UPDATE / DELETE whose IN subquery defines a materialized CTE. +-- The mutation plan must gate the CTE readers like the Planner does for a SELECT, +-- also when the set is built at run time (empty table, non-key column, index analysis for IN disabled). + +SET enable_analyzer = 1; +SET enable_materialized_cte = 1; +SET enable_lightweight_update = 1; +SET lightweight_delete_mode = 'lightweight_update_force'; + +DROP TABLE IF EXISTS t_lwu_materialized_cte; + +CREATE TABLE t_lwu_materialized_cte (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1; + +-- Empty table: nothing to read, the set is built at run time. +UPDATE t_lwu_materialized_cte SET v = 1 WHERE id IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT count() FROM t_lwu_materialized_cte; + +INSERT INTO t_lwu_materialized_cte SELECT number, number FROM numbers(5); + +-- SELECT analogue: the Planner plants the gate itself. +SELECT count() FROM t_lwu_materialized_cte WHERE v IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); + +-- Non-key column: no primary-key analysis, the set is built at run time. +UPDATE t_lwu_materialized_cte SET v = 100 WHERE v IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +-- Key column with index analysis for IN disabled: the set is built at run time. +SET use_index_for_in_with_subqueries = 0; +UPDATE t_lwu_materialized_cte SET v = 200 WHERE id IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +-- Two IN subqueries, each defining its own materialized CTE named c: one gate per set subquery. +UPDATE t_lwu_materialized_cte SET v = 250 WHERE v IN (WITH c AS MATERIALIZED (SELECT number + 200 AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b) AND id IN (WITH c AS MATERIALIZED (SELECT number * 2 AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +-- A materialized CTE depending on another one inside the set subquery: two dependency levels. +UPDATE t_lwu_materialized_cte SET v = 260 WHERE v IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)), d AS MATERIALIZED (SELECT x + 200 AS y FROM c) SELECT a.y FROM d AS a, d AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +-- Key column with index analysis: the set is built in place during primary-key analysis. +SET use_index_for_in_with_subqueries = 1; +UPDATE t_lwu_materialized_cte SET v = 300 WHERE id IN (WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +-- Lightweight DELETE goes through the same mutation plan. +DELETE FROM t_lwu_materialized_cte WHERE v IN (WITH c AS MATERIALIZED (SELECT number + 300 AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b); +SELECT * FROM t_lwu_materialized_cte ORDER BY id; + +DROP TABLE t_lwu_materialized_cte; diff --git a/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference new file mode 100644 index 000000000000..f61a1ae7dddc --- /dev/null +++ b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.reference @@ -0,0 +1,11 @@ +data path outside, disk registered 0 +data path outside, directory not created +metadata path outside, disk registered 0 +s3 metadata path outside, disk registered 0 +escaping name, disk registered 0 +nested data path outside, disk registered 0 +encrypted path outside wrapped disk, disk registered 0 +encrypted over local disk outside base directory, disk registered 0 +data path inside 2 +s3 with default metadata path 2 +cache over config disk 2 diff --git a/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh new file mode 100755 index 000000000000..dd311cc0bfc3 --- /dev/null +++ b/tests/queries/0_stateless/05212_custom_disk_local_paths_confined.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-distributed-cache +# no-fasttest: the S3 cases need the minio instance. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +name="${CLICKHOUSE_TEST_UNIQUE_NAME}" +server_path=$(${CLICKHOUSE_CLIENT} -q "SELECT path FROM system.disks WHERE name = 'default'") +inside="${CLICKHOUSE_DISKS_FILES}/${name}" +outside="${server_path}${name}_outside" +s3_args="endpoint = 'http://localhost:11111/test/${name}/', access_key_id = 'clickhouse', secret_access_key = 'clickhouse'" + +${CLICKHOUSE_CLIENT} -q " +CREATE TABLE t_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_outside', type = 'local_blob_storage', path = '${outside}/'); -- { serverError BAD_ARGUMENTS } +SELECT 'data path outside, disk registered', count() FROM system.disks WHERE name = '${name}_outside'; +" +test -d "${outside}" && echo "data path outside, directory created" || echo "data path outside, directory not created" + +${CLICKHOUSE_CLIENT} -q " +CREATE TABLE t_meta_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_meta_outside', type = 'local_blob_storage', path = '${inside}_meta/', metadata_path = '${outside}_meta/'); -- { serverError BAD_ARGUMENTS } +SELECT 'metadata path outside, disk registered', count() FROM system.disks WHERE name = '${name}_meta_outside'; + +CREATE TABLE t_s3_meta_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_s3_meta_outside', type = 's3', ${s3_args}, metadata_path = '${outside}_s3/'); -- { serverError BAD_ARGUMENTS } +SELECT 's3 metadata path outside, disk registered', count() FROM system.disks WHERE name = '${name}_s3_meta_outside'; + +CREATE TABLE t_escaping_name (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '../${name}_escape', type = 's3', ${s3_args}); -- { serverError BAD_ARGUMENTS } +SELECT 'escaping name, disk registered', count() FROM system.disks WHERE name = '../${name}_escape'; + +CREATE TABLE t_cache_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = cache, name = '${name}_cache_outside', path = '${name}_cache_outside', max_size = '10Mi', + disk = disk(name = '${name}_nested_outside', type = 'local_blob_storage', path = '${outside}_nested/')); -- { serverError BAD_ARGUMENTS } +SELECT 'nested data path outside, disk registered', count() FROM system.disks WHERE name = '${name}_nested_outside'; + +CREATE TABLE t_encrypted_outside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = encrypted, name = '${name}_encrypted_outside', disk = 'local_disk', path = '../../${name}_escape/', key = '1234567812345678'); -- { serverError BAD_ARGUMENTS } +SELECT 'encrypted path outside wrapped disk, disk registered', count() FROM system.disks WHERE name = '${name}_encrypted_outside'; + +CREATE TABLE t_encrypted_default (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = encrypted, name = '${name}_encrypted_default', disk = 'default', path = '${name}_encrypted/', key = '1234567812345678'); -- { serverError BAD_ARGUMENTS } +SELECT 'encrypted over local disk outside base directory, disk registered', count() FROM system.disks WHERE name = '${name}_encrypted_default'; + +CREATE TABLE t_inside (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_inside', type = 'local_blob_storage', path = '${inside}/'); +INSERT INTO t_inside VALUES (1), (2); +SELECT 'data path inside', count() FROM t_inside; + +CREATE TABLE t_s3 (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(name = '${name}_s3', type = 's3', ${s3_args}); +INSERT INTO t_s3 VALUES (1), (2); +SELECT 's3 with default metadata path', count() FROM t_s3; + +CREATE TABLE t_cache (a Int32) ENGINE = MergeTree ORDER BY a +SETTINGS disk = disk(type = cache, name = '${name}_cache', path = '${name}_cache', max_size = '10Mi', disk = 'local_disk'); +INSERT INTO t_cache VALUES (1), (2); +SELECT 'cache over config disk', count() FROM t_cache; +" diff --git a/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference new file mode 100644 index 000000000000..2672ec645c5f --- /dev/null +++ b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.reference @@ -0,0 +1,6 @@ +count 100 +expired_left 0 +ids 1 199 100 +cols 150 150 150 +parts 1 +algo Vertical diff --git a/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql new file mode 100644 index 000000000000..a504e087125a --- /dev/null +++ b/tests/queries/0_stateless/05212_ttl_delete_vertical_merge_other_ttl_families.sql @@ -0,0 +1,75 @@ +-- Tags: no-object-storage +-- An object-storage policy has no disk `default`, so the move TTL below could not be created there. + +-- A vertical TTL merge evaluates every TTL family's expression against the merged block, so the +-- inputs of the move and recompression TTLs must be merged too, not gathered. Without that the +-- merge throws `NOT_FOUND_COLUMN_IN_BLOCK` and the parts never merge. +-- +-- The rows TTL reads `d`, the recompression TTL reads `e` and the move TTL reads `f`: three +-- different columns, so none of them rides into the merged stream on another TTL's back. + +SET optimize_throw_if_noop = 0; + +DROP TABLE IF EXISTS t_ttl_vert_families; + +CREATE TABLE t_ttl_vert_families +( + id UInt64, + d DateTime, + e DateTime, + f DateTime, + c1 UInt64, + c2 UInt64, + c3 UInt64 +) +ENGINE = MergeTree +ORDER BY id +TTL d + INTERVAL 1 DAY DELETE, + e + INTERVAL 1 MONTH RECOMPRESS CODEC(ZSTD(1)), + f + INTERVAL 2 MONTH TO DISK 'default' +SETTINGS + min_bytes_for_wide_part = 0, + min_bytes_for_full_part_storage = 0, + enable_block_number_column = 0, + enable_block_offset_column = 0, + vertical_merge_algorithm_min_rows_to_activate = 1, + vertical_merge_algorithm_min_columns_to_activate = 1, + vertical_merge_optimize_ttl_delete = 1, + max_bytes_to_merge_at_max_space_in_pool = 1, + merge_with_ttl_timeout = 100000, + ratio_of_defaults_for_sparse_serialization = 1.0; + +-- Two parts, so the merge reads from the merging algorithm rather than short-circuiting a single +-- part. Even rows are expired by the rows TTL. `max_bytes_to_merge_at_max_space_in_pool = 1` keeps +-- the background pool off regular merges and the TTL blocker off TTL merges until both parts exist, +-- so the `OPTIMIZE` is the first merge logged. +SYSTEM STOP TTL MERGES t_ttl_vert_families; + +INSERT INTO t_ttl_vert_families +SELECT number, if(number % 2, now() + INTERVAL 1 YEAR, '2000-01-01 00:00:00'), now(), now(), 1, 1, 1 +FROM numbers(100); + +INSERT INTO t_ttl_vert_families +SELECT number + 100, if(number % 2, now() + INTERVAL 1 YEAR, '2000-01-01 00:00:00'), now(), now(), 2, 2, 2 +FROM numbers(100); + +SYSTEM START TTL MERGES t_ttl_vert_families; + +OPTIMIZE TABLE t_ttl_vert_families FINAL; + +SELECT 'count', count() FROM t_ttl_vert_families; +SELECT 'expired_left', count() FROM t_ttl_vert_families WHERE d + INTERVAL 1 DAY <= now(); +SELECT 'ids', min(id), max(id), countIf(id % 2 = 1) FROM t_ttl_vert_families; +SELECT 'cols', sum(c1), sum(c2), sum(c3) FROM t_ttl_vert_families; +SELECT 'parts', count() FROM system.parts + WHERE database = currentDatabase() AND table = 't_ttl_vert_families' AND active; + +SYSTEM FLUSH LOGS part_log; +-- Exclude `TTLDropMerge`: a part whose rows are all expired is dropped by a short-circuit that +-- always uses the `Horizontal` algorithm. +SELECT 'algo', merge_algorithm FROM system.part_log + WHERE database = currentDatabase() AND table = 't_ttl_vert_families' AND event_type = 'MergeParts' + AND merge_reason != 'TTLDropMerge' + ORDER BY event_time_microseconds LIMIT 1; + +DROP TABLE t_ttl_vert_families; diff --git a/tests/queries/0_stateless/05218_projection_index_filter_polarity.reference b/tests/queries/0_stateless/05218_projection_index_filter_polarity.reference new file mode 100644 index 000000000000..4d03ba1d43a4 --- /dev/null +++ b/tests/queries/0_stateless/05218_projection_index_filter_polarity.reference @@ -0,0 +1,22 @@ +2000 +2000 +2000 +2000 +2000 +2000 +2000 +2000 +2000 +1 +1983 +2000 +1 +1 +1 +1 +1 +2 +2 +1 +1 +1 1 1 1 1 1 1 1 1 diff --git a/tests/queries/0_stateless/05218_projection_index_filter_polarity.sql b/tests/queries/0_stateless/05218_projection_index_filter_polarity.sql new file mode 100644 index 000000000000..7dd28c1cb009 --- /dev/null +++ b/tests/queries/0_stateless/05218_projection_index_filter_polarity.sql @@ -0,0 +1,95 @@ +-- Tags: no-parallel-replicas +-- no-parallel-replicas: the `read_rows` assertion below reads the initiator's own plan. + +-- Restricting a filter to a projection's columns replaces a conjunct it cannot compute with true. +-- Weakening a conjunct is sound only where the `AND` is read with positive polarity: under `NOT`, as a +-- comparison operand or as a branch condition it makes the restricted filter stronger instead, and the +-- projection index then prunes granules holding rows that do match. + +SET enable_analyzer = 1; +SET optimize_use_projections = 1, optimize_use_projection_filtering = 1; +SET use_indexes_refiner_in_read_pools = 0; -- decides whether pruned ranges are dropped or skipped while reading, which moves read_rows +SET use_query_condition_cache = 0; -- a cached granule set would leak between the read_rows arms below + +DROP TABLE IF EXISTS t_projection_polarity; + +CREATE TABLE t_projection_polarity (id UInt64, a UInt64, x UInt64, b UInt64) ENGINE = MergeTree ORDER BY id +SETTINGS index_granularity = 8192, index_granularity_bytes = 0, min_bytes_for_wide_part = 0; + +-- `b` is outside the projection, which is what makes a conjunct over it non-computable there. +ALTER TABLE t_projection_polarity ADD PROJECTION p (SELECT a, x, _part_offset ORDER BY a); + +-- A single part, above `min_table_rows_to_use_projection_index`, so the projection is used as an index. +INSERT INTO t_projection_polarity SELECT number, number % 1000, intDiv(number, 1000), 7 FROM numbers(2000000) +SETTINGS max_insert_block_size = 2000000, min_insert_block_size_rows = 2000000; + +-- Every row with a = 1 has b = 7, so each predicate below is true for all 2000 of them. +SELECT count() FROM t_projection_polarity WHERE a = 1 AND NOT (a = 1 AND b = 2); +SELECT count() FROM t_projection_polarity WHERE a = 1 AND (a = 1 AND b = 2) = 0; +SELECT count() FROM t_projection_polarity WHERE a = 1 AND multiIf(a = 1 AND b = 2, 0, 1); +-- `b` is read as a condition by one conjunct and as a value by another, through the same input node. +SELECT count() FROM t_projection_polarity WHERE a = 1 AND b AND b = 7; +-- A `NOT` under an `OR` is still not weakened. +SELECT count() FROM t_projection_polarity WHERE a = 1 AND (x = 5 OR NOT (a = 1 AND b = 2)); +-- A conjunct whose type has no true value stays in place; a float conjunct is replaced with a float true. +SELECT count() FROM t_projection_polarity WHERE (a = 1 AND if(b = 1, NULL, NULL)) OR a = 2; +SELECT count() FROM t_projection_polarity WHERE a = 1 AND toFloat64(b); +-- `throwIf` runs only where `b = 1`, so `b = 1` must not be weakened under the `OR`. +SELECT count() FROM t_projection_polarity WHERE (a <= 2 AND b = 1 AND throwIf(a = 0) = 0) OR a = 2; +-- Under `force_enable` the `gcd` also runs only where `b = 1`, so `b = 1` must not be weakened under the `OR`. +SELECT count() FROM t_projection_polarity WHERE (a <= 2 AND b = 1 AND gcd(a, 0) = 0) OR a = 2 +SETTINGS short_circuit_function_evaluation = 'force_enable'; +-- `rand()` must not be drawn a second time over the projection: about half of the a = 1 rows are kept. +SELECT count() BETWEEN 2800 AND 3200 FROM t_projection_polarity WHERE (a = 1 AND b = 7 AND rand() % 2 = 0) OR a = 2; +-- The projection evaluates the filter on rows the main read skips (`id < 16384`), and `gcd` throws on `x = 5` there. +SELECT count() FROM t_projection_polarity WHERE id >= 16384 AND ((a = 1 AND b = 7 AND gcd(1, x - 5) = 1) OR (a = 2 AND b = 8)); + +-- A conjunct of an `AND` read with positive polarity must still be weakened, or the index stops pruning. +SELECT count() FROM t_projection_polarity WHERE a = 1 AND b = 7; +SELECT count() FROM t_projection_polarity WHERE a = 1 AND x = 5 AND b = 7 +SETTINGS log_comment = '05218_pruning_alive'; +SELECT count() FROM t_projection_polarity WHERE a = 1 AND x = 5 AND b = 7 +SETTINGS log_comment = '05218_pruning_off', optimize_use_projection_filtering = 0; +-- Unmerged filter steps reach the projection as `and(and(x = 5, b = 7), a = 1)`, so only a descent into the +-- nested `AND` weakens `b = 7`; dropping that whole conjunct instead is still correct but stops pruning. +SELECT count() FROM (SELECT * FROM t_projection_polarity WHERE x = 5 AND b = 7) WHERE a = 1 +SETTINGS log_comment = '05218_pruning_alive_nested', query_plan_merge_filters = 0; +-- `OR` is monotone too, so an `AND` under it must still be weakened. +SELECT count() FROM t_projection_polarity WHERE (a = 1 AND x = 5 AND b = 7) OR (a = 2 AND x = 6 AND b = 8) +SETTINGS log_comment = '05218_pruning_alive_or'; +SELECT count() FROM t_projection_polarity WHERE a = 1 AND ((x = 5 AND b = 7) OR (x = 6 AND b = 8)) +SETTINGS log_comment = '05218_pruning_alive_or_nested'; +SELECT count() FROM t_projection_polarity WHERE a IN (1, 2) AND ((x = 5 AND b = 7) OR (x = 6 AND b = 8)) +SETTINGS log_comment = '05218_pruning_alive_or_in'; +-- A function in a conjunct that is replaced is never evaluated, so it does not stop the walk, also over projection columns. +SELECT count() FROM t_projection_polarity WHERE (a = 1 AND x = 5 AND toFloat64(b)) OR (a = 2 AND x = 6 AND toFloat64(a) + b > 0) +SETTINGS log_comment = '05218_pruning_alive_or_dropped'; +-- A conjunct outside the weakened `OR` is evaluated without the walk too, so it does not stop the walk, also in another `OR`. +SELECT count() FROM t_projection_polarity WHERE toString(a) != '' AND ((a = 1 AND x = 5 AND b = 7) OR (a = 2 AND x = 6 AND b = 8)) +SETTINGS log_comment = '05218_pruning_alive_or_outside'; +SELECT count() FROM t_projection_polarity +WHERE (toString(a) != '' OR toString(x) = '6') AND ((a = 1 AND x = 5 AND b = 7) OR (a = 2 AND x = 6 AND b = 8)) +SETTINGS log_comment = '05218_pruning_alive_or_outside_or'; + +SYSTEM FLUSH LOGS query_log; + +-- The table pins a granule at 8192 rows and one carries the single matching row, so a live projection index +-- reads at most two; with the row-level filter off the whole table is read. The pair fails from both sides: +-- if the relaxation stops firing the first flips, if the fixture stops pruning the second does. +SELECT + maxIf(read_rows, log_comment = '05218_pruning_alive') <= 2 * 8192 AS pruned, + minIf(read_rows, log_comment = '05218_pruning_off') >= 2000000 AS not_pruned, + maxIf(read_rows, log_comment = '05218_pruning_alive_nested') <= 2 * 8192 AS pruned_nested, + maxIf(read_rows, log_comment = '05218_pruning_alive_or') <= 2 * 8192 AS pruned_or, + maxIf(read_rows, log_comment = '05218_pruning_alive_or_nested') <= 2 * 8192 AS pruned_or_nested, + maxIf(read_rows, log_comment = '05218_pruning_alive_or_in') <= 2 * 8192 AS pruned_or_in, + maxIf(read_rows, log_comment = '05218_pruning_alive_or_dropped') <= 2 * 8192 AS pruned_or_dropped, + maxIf(read_rows, log_comment = '05218_pruning_alive_or_outside') <= 2 * 8192 AS pruned_or_outside, + maxIf(read_rows, log_comment = '05218_pruning_alive_or_outside_or') <= 2 * 8192 AS pruned_or_outside_or +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' + AND log_comment IN ('05218_pruning_alive', '05218_pruning_off', '05218_pruning_alive_nested', + '05218_pruning_alive_or', '05218_pruning_alive_or_nested', '05218_pruning_alive_or_in', + '05218_pruning_alive_or_dropped', '05218_pruning_alive_or_outside', '05218_pruning_alive_or_outside_or'); + +DROP TABLE t_projection_polarity; diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference new file mode 100644 index 000000000000..61054c4b3976 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.reference @@ -0,0 +1,19 @@ +--- SHOW GRANTS +GRANT SELECT ON *.* TO grantor WITH GRANT OPTION +REVOKE SELECT ON d.t1 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM grantor +REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM grantor +REVOKE SELECT ON db1.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON db2.* FROM grantor +REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM grantor +--- system.grants +d t1 SELECT 0 1 +d t2 SELECT 1 1 +d zt2 SELECT 1 1 +db1 \N SELECT 0 1 +db2 \N SELECT 1 1 +zdb2 \N SELECT 1 1 +\N \N SELECT 1 0 +--- nothing is granted for a database whose grant option was revoked +--- positive control: a database that was never revoked is still passed on with grant option +GRANT SELECT ON db3.* TO victim2 WITH GRANT OPTION diff --git a/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh new file mode 100755 index 000000000000..27e3c75cf831 --- /dev/null +++ b/tests/queries/0_stateless/05255_revoke_grant_option_shared_prefix.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Tests that "REVOKE GRANT OPTION FOR" is listed by SHOW GRANTS and by system.grants, and that the +# user can no longer pass the grant option on, also when another revoked database or table name +# shares a prefix with it. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +grantor="user05255_1_${CLICKHOUSE_DATABASE}_$RANDOM" +victim1="user05255_2_${CLICKHOUSE_DATABASE}_$RANDOM" +victim2="user05255_3_${CLICKHOUSE_DATABASE}_$RANDOM" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS $grantor, $victim1, $victim2" +${CLICKHOUSE_CLIENT} --query "CREATE USER $grantor, $victim1, $victim2" + +${CLICKHOUSE_CLIENT} --query "GRANT SELECT ON *.* TO $grantor WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON db1.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON db2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON zdb2.* FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE SELECT ON d.t1 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.t2 FROM $grantor" +${CLICKHOUSE_CLIENT} --query "REVOKE GRANT OPTION FOR SELECT ON d.zt2 FROM $grantor" + +echo "--- SHOW GRANTS" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $grantor" | sed "s/$grantor/grantor/g" + +echo "--- system.grants" +${CLICKHOUSE_CLIENT} --query " + SELECT database, table, access_type, grant_option, is_partial_revoke + FROM system.grants WHERE user_name = '$grantor' ORDER BY database, table, access_type" + +echo "--- nothing is granted for a database whose grant option was revoked" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db2.*) TO $victim1 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim1" | sed "s/$victim1/victim1/g" + +echo "--- positive control: a database that was never revoked is still passed on with grant option" +${CLICKHOUSE_CLIENT} --user "$grantor" --query "GRANT CURRENT GRANTS(SELECT ON db3.*) TO $victim2 WITH GRANT OPTION" +${CLICKHOUSE_CLIENT} --query "SHOW GRANTS FOR $victim2" | sed "s/$victim2/victim2/g" + +${CLICKHOUSE_CLIENT} --query "DROP USER $grantor, $victim1, $victim2" diff --git a/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference new file mode 100644 index 000000000000..f68e8fc52e9b --- /dev/null +++ b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.reference @@ -0,0 +1,134 @@ +NOT_LOADED +--- no grants +SELECT * FROM dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +SELECT dictGet('db.d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT dictHas('db.d', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('db.d', 'value', number) SETTINGS enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +SELECT * FROM dictionary('d') +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('d') +ACCESS_DENIED +NOT_LOADED +SELECT dictGet('d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT dictHas('d', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +--- SELECT on a Dictionary table is not enough without a grant on the dictionary +SELECT * FROM w +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct' +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'hash' +ACCESS_DENIED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +ACCESS_DENIED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +ACCESS_DENIED +NOT_LOADED +EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +ACCESS_DENIED +NOT_LOADED +--- creating a Dictionary table needs access to the dictionary +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(d) +ACCESS_DENIED +NOT_LOADED +--- no grants, naiveBayesClassifier +NOT_LOADED +SELECT naiveBayesClassifier('nb', 'good') +ACCESS_DENIED +NOT_LOADED +SELECT naiveBayesClassifierWithProb('nb', 'good') +ACCESS_DENIED +NOT_LOADED +SELECT naiveBayesClassifierWithAllProbs('nb', 'good') +ACCESS_DENIED +NOT_LOADED +--- SELECT is enough for the dictionary table function, but not for dictGet +SELECT dictGet('d', 'value', toUInt64(1)) +ACCESS_DENIED +NOT_LOADED +DESCRIBE TABLE dictionary('d') +id UInt64 +value String +SELECT * FROM dictionary('d') +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = 1 +0 +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = 0 +0 +1 a +LOADED +--- dictGet +NOT_LOADED +SELECT dictGet('d', 'value', toUInt64(1)) +a +LOADED +NOT_LOADED +SELECT dictHas('db.d', toUInt64(1)) +1 +LOADED +NOT_LOADED +SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0 +1 +LOADED +NOT_LOADED +SELECT * FROM dictionary('d') +1 a +LOADED +NOT_LOADED +SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct' +0 +1 a +LOADED +NOT_LOADED +CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct' + +LOADED +NOT_LOADED +CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(db.d) + +LOADED +CREATE TABLE w_unqualified_by_user (id UInt64, value String) ENGINE = Dictionary(d) + +LOADED +1 a +LOADED +--- dictGet, naiveBayesClassifier +SELECT naiveBayesClassifier('nb', 'good') +0 +LOADED diff --git a/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh new file mode 100755 index 000000000000..414d987173c3 --- /dev/null +++ b/tests/queries/0_stateless/05291_dictionary_access_check_before_load.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Access rights must be checked before a dictionary is loaded, +# so a query without the required grants does not trigger the load. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +${CLICKHOUSE_CLIENT} -m --query " + DROP USER IF EXISTS ${username}; + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + INSERT INTO src VALUES (1, 'a'); + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE TABLE nb_src (class_id UInt32, ngram String, count UInt64) ENGINE = Memory; + INSERT INTO nb_src VALUES (0, 'good', 10), (1, 'bad', 10); + CREATE DICTIONARY nb (ngram String, class_id UInt32 DEFAULT 0, count UInt64 DEFAULT 0) + PRIMARY KEY ngram + SOURCE(CLICKHOUSE(TABLE 'nb_src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 1 mode 'token')) + LIFETIME(0); + CREATE TABLE w (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d); + SYSTEM UNLOAD DICTIONARY d; + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; +" + +# The queries go over HTTP: starting a client for each of them makes the test too slow. +function query() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" --data-binary "$1" +} + +function status() +{ + query "SELECT status FROM system.dictionaries WHERE database = currentDatabase() AND name = '${1:-d}'" +} + +function unload() +{ + query "SYSTEM UNLOAD DICTIONARY d" + status +} + +function as_user() +{ + echo "$1" | sed "s/${CLICKHOUSE_DATABASE}/db/g" + local output + output=$(${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&user=${username}" --data-binary "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" + fi +} + +status + +echo "--- no grants" +# Both a qualified name and an unqualified one resolved against the current database. +for dict in "${CLICKHOUSE_DATABASE}.d" "d" +do + as_user "SELECT * FROM dictionary('${dict}')" + status + as_user "DESCRIBE TABLE dictionary('${dict}')" + status + as_user "SELECT dictGet('${dict}', 'value', toUInt64(1))" + status + as_user "SELECT dictHas('${dict}', toUInt64(1))" + status + as_user "SELECT count() FROM numbers(1) GROUP BY dictGet('${dict}', 'value', number) SETTINGS enable_analyzer = 0" + status +done + +echo "--- SELECT on a Dictionary table is not enough without a grant on the dictionary" +query "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.w TO ${username}" +as_user "SELECT * FROM w" +status +# A join may use the dictionary directly as a key-value storage, check it is covered as well. +for settings in "join_algorithm = 'direct'" "join_algorithm = 'hash'" "join_algorithm = 'direct', enable_analyzer = 0" +do + as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS ${settings}" + status +done +# Queries that are only analyzed do not read the right table, but the join planning must not load the dictionary either. +query "GRANT CREATE VIEW ON ${CLICKHOUSE_DATABASE}.* TO ${username}" +for analyzer in 1 0 +do + as_user "EXPLAIN SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status + as_user "CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status +done + +echo "--- creating a Dictionary table needs access to the dictionary" +${CLICKHOUSE_CLIENT} -m --query " + GRANT CREATE TABLE ON ${CLICKHOUSE_DATABASE}.* TO ${username}; + GRANT TABLE ENGINE ON Dictionary TO ${username}; +" +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" +status +# An unqualified name is resolved against the current database, like when the table is read. +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(d)" +status + +echo "--- no grants, naiveBayesClassifier" +status nb +as_user "SELECT naiveBayesClassifier('nb', 'good')" +status nb +as_user "SELECT naiveBayesClassifierWithProb('nb', 'good')" +status nb +as_user "SELECT naiveBayesClassifierWithAllProbs('nb', 'good')" +status nb + +echo "--- SELECT is enough for the dictionary table function, but not for dictGet" +query "GRANT SELECT ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "SELECT dictGet('d', 'value', toUInt64(1))" +status +as_user "DESCRIBE TABLE dictionary('d')" +as_user "SELECT * FROM dictionary('d')" +status +# The same rule applies to a direct join against a Dictionary table, with both analyzers. +for analyzer in 1 0 +do + unload + as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct', enable_analyzer = ${analyzer}" + status +done + +echo "--- dictGet" +${CLICKHOUSE_CLIENT} -m --query " + REVOKE SELECT ON ${CLICKHOUSE_DATABASE}.d FROM ${username}; + GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}; +" +unload +as_user "SELECT dictGet('d', 'value', toUInt64(1))" +status +unload +as_user "SELECT dictHas('${CLICKHOUSE_DATABASE}.d', toUInt64(1))" +status +unload +as_user "SELECT count() FROM numbers(1) GROUP BY dictGet('d', 'value', number) SETTINGS enable_analyzer = 0" +status +unload +as_user "SELECT * FROM dictionary('d')" +status +unload +as_user "SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id ORDER BY n.number SETTINGS join_algorithm = 'direct'" +status +unload +as_user "CREATE VIEW v_by_user AS SELECT n.number, w.value FROM numbers(2) AS n LEFT JOIN w ON n.number = w.id SETTINGS join_algorithm = 'direct'" +status +# With access, creating a Dictionary table loads the dictionary to validate the columns. +unload +as_user "CREATE TABLE w_by_user (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" +status +as_user "CREATE TABLE w_unqualified_by_user (id UInt64, value String) ENGINE = Dictionary(d)" +status +# Reading the table resolves the same dictionary. +query "SELECT * FROM w_unqualified_by_user" +status + +echo "--- dictGet, naiveBayesClassifier" +query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.nb TO ${username}" +as_user "SELECT naiveBayesClassifier('nb', 'good')" +status nb + +query "DROP USER ${username}" diff --git a/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference new file mode 100644 index 000000000000..1addf3c1d31b --- /dev/null +++ b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.reference @@ -0,0 +1,57 @@ +--- no grants +SELECT dictGet('d', 'no_such_attribute', toUInt64(1)) +ACCESS_DENIED +DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1))) +ACCESS_DENIED +SELECT dictGet('d', 'value', number) FROM numbers(0) +ACCESS_DENIED +SELECT dictGetOrDefault('d', 'value', toUInt64(1), 'x') +ACCESS_DENIED +SELECT dictGetOrNull('d', 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys('d', 'value', 'a') +ACCESS_DENIED +SELECT dictGetKeys('d', 'no_such_attribute', 'a') +ACCESS_DENIED +SELECT naiveBayesClassifier('d', 'good') +ACCESS_DENIED +--- dictGet +DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1))) +dictGet(\'d\', \'value\', toUInt64(1)) String +SELECT dictGet('d', 'no_such_attribute', toUInt64(1)) +No such attribute +SELECT dictGetKeys('d', 'no_such_attribute', 'a') +has no attribute +SELECT naiveBayesClassifier('d', 'good') +NAIVE_BAYES layout +--- missing dictionary, no grants +SELECT dictGet('no_such_dictionary', 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys('no_such_dictionary', 'value', 'a') +ACCESS_DENIED +SELECT naiveBayesClassifier('no_such_dictionary', 'good') +ACCESS_DENIED +SELECT * FROM dictionary('no_such_dictionary') +ACCESS_DENIED +--- identifier, no grants +SELECT dictGet(d, 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictGet(no_such_dictionary, 'value', toUInt64(1)) +ACCESS_DENIED +SELECT dictHas(no_such_dictionary, toUInt64(1)) +ACCESS_DENIED +SELECT dictGetKeys(no_such_dictionary, 'value', 'a') +ACCESS_DENIED +SELECT naiveBayesClassifier(no_such_dictionary, 'good') +ACCESS_DENIED +--- missing dictionary, dictGet +SELECT dictGet('no_such_dictionary', 'value', toUInt64(1)) +not found +SELECT dictGetKeys('no_such_dictionary', 'value', 'a') +not found +SELECT naiveBayesClassifier('no_such_dictionary', 'good') +not found +SELECT * FROM dictionary('no_such_dictionary') +not found +SELECT dictGet(no_such_dictionary, 'value', toUInt64(1)) +not found diff --git a/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh new file mode 100755 index 000000000000..e563358676e2 --- /dev/null +++ b/tests/queries/0_stateless/05292_dictionary_metadata_access_check.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Without the `dictGet` grant, the dictionary definition (attributes, layout) must not be revealed, +# even when a query only needs the result type and does not execute the function. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +${CLICKHOUSE_CLIENT} -m --query " + DROP USER IF EXISTS ${username}; + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; +" + +function as_user() +{ + echo "$1" + local output + output=$(${CLICKHOUSE_CLIENT} --user "${username}" --query "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" + fi +} + +echo "--- no grants" +as_user "SELECT dictGet('d', 'no_such_attribute', toUInt64(1))" +as_user "DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1)))" +as_user "SELECT dictGet('d', 'value', number) FROM numbers(0)" +as_user "SELECT dictGetOrDefault('d', 'value', toUInt64(1), 'x')" +as_user "SELECT dictGetOrNull('d', 'value', toUInt64(1))" +as_user "SELECT dictGetKeys('d', 'value', 'a')" +as_user "SELECT dictGetKeys('d', 'no_such_attribute', 'a')" +as_user "SELECT naiveBayesClassifier('d', 'good')" + +echo "--- dictGet" +${CLICKHOUSE_CLIENT} --query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "DESCRIBE (SELECT dictGet('d', 'value', toUInt64(1)))" +as_user "SELECT dictGet('d', 'no_such_attribute', toUInt64(1))" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|No such attribute|unexpected ACCESS_DENIED" | head -2 +as_user "SELECT dictGetKeys('d', 'no_such_attribute', 'a')" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|has no attribute|unexpected ACCESS_DENIED" | head -2 +as_user "SELECT naiveBayesClassifier('d', 'good')" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|NAIVE_BAYES layout|unexpected ACCESS_DENIED" | head -2 + +# A missing dictionary must look the same as an existing one without access. +${CLICKHOUSE_CLIENT} --query "REVOKE dictGet ON ${CLICKHOUSE_DATABASE}.d FROM ${username}" +echo "--- missing dictionary, no grants" +as_user "SELECT dictGet('no_such_dictionary', 'value', toUInt64(1))" +as_user "SELECT dictGetKeys('no_such_dictionary', 'value', 'a')" +as_user "SELECT naiveBayesClassifier('no_such_dictionary', 'good')" +as_user "SELECT * FROM dictionary('no_such_dictionary')" + +# The dictionary name can also be an identifier, which the analyzer resolves separately. +echo "--- identifier, no grants" +as_user "SELECT dictGet(d, 'value', toUInt64(1))" +as_user "SELECT dictGet(no_such_dictionary, 'value', toUInt64(1))" +as_user "SELECT dictHas(no_such_dictionary, toUInt64(1))" +as_user "SELECT dictGetKeys(no_such_dictionary, 'value', 'a')" +as_user "SELECT naiveBayesClassifier(no_such_dictionary, 'good')" + +echo "--- missing dictionary, dictGet" +${CLICKHOUSE_CLIENT} --query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.* TO ${username}" +for query in \ + "SELECT dictGet('no_such_dictionary', 'value', toUInt64(1))" \ + "SELECT dictGetKeys('no_such_dictionary', 'value', 'a')" \ + "SELECT naiveBayesClassifier('no_such_dictionary', 'good')" \ + "SELECT * FROM dictionary('no_such_dictionary')" \ + "SELECT dictGet(no_such_dictionary, 'value', toUInt64(1))" +do + as_user "${query}" | sed 's/^ACCESS_DENIED$/unexpected ACCESS_DENIED/' | grep -o -E "^SELECT.*|not found|unexpected ACCESS_DENIED" | head -2 +done + +${CLICKHOUSE_CLIENT} --query "DROP USER ${username}" diff --git a/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.reference b/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.reference new file mode 100644 index 000000000000..e0f463ee94b5 --- /dev/null +++ b/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.reference @@ -0,0 +1,32 @@ +(1,NULL) +(1,NULL) +(2,NULL) +(2,NULL) +(1,NULL) +(2,NULL) +(NULL,NULL) +(1,NULL) +(2,NULL) +(NULL,NULL) +(1,NULL) +(2,NULL) +((1,NULL),2) +((1,NULL),3) +((2,NULL),3) +(1,NULL) +(1,NULL) +(2,NULL) +(1,NULL) +(1,NULL) +(2,NULL) +(1,NULL) +(1,NULL) +(2,NULL) +[(2,NULL),(1,NULL)] +(0,NULL) +(2,NULL) +(3,NULL) +(2,NULL) +(1,NULL) +(2,NULL) +(NULL,NULL) (NULL,NULL) diff --git a/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.sql b/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.sql new file mode 100644 index 000000000000..c4c83ba2026b --- /dev/null +++ b/tests/queries/0_stateless/05315_if_tuple_null_element_in_both_branches.sql @@ -0,0 +1,14 @@ +-- if() over tuples where an element is NULL in both branches. + +SELECT if(number = 0, (1, NULL), (number, NULL)) FROM numbers(3); +SELECT if(number % 2, (1, NULL), (2, NULL)) FROM numbers(3); +SELECT if(number = 0, (NULL, NULL), (number, number * NULL)) FROM numbers(3); +SELECT CAST(if(number = 0, (NULL, NULL), (number, number * NULL)), 'Tuple(Nullable(UInt64), Nullable(UInt64))') FROM numbers(3); +SELECT if(number = 0, ((1, NULL), 2), ((number, NULL), 3)) FROM numbers(3); +SELECT if(number = 0, toNullable((1, NULL)), (number, NULL)) FROM numbers(3); +SELECT if(toNullable(number = 0), (1, NULL), (number, NULL)) FROM numbers(3); +SELECT CASE WHEN number = 0 THEN (1, NULL) ELSE (number, NULL) END FROM numbers(3); +SELECT arrayMap(x -> if(x, (1, NULL), (2, NULL)), [0, 1]); +SELECT if(number = 0, tuple(number, materialize(NULL)), tuple(number + 1, materialize(NULL))) FROM numbers(3); +SELECT if(number % 2, (1, NULL::Nullable(UInt8)), (2, NULL::Nullable(UInt8))) FROM numbers(3); +SELECT anyRespectNullsTupleDistinct(CAST(if(number = 0, (NULL, NULL), (number, number * NULL)), 'Tuple(Nullable(UInt64), Nullable(UInt64))')) AS r, r FROM numbers(3); diff --git a/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.reference b/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.reference new file mode 100644 index 000000000000..915f83d8a763 --- /dev/null +++ b/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.reference @@ -0,0 +1,4 @@ +0 1 +0 +0 1 +0 diff --git a/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.sql b/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.sql new file mode 100644 index 000000000000..f95877489a9c --- /dev/null +++ b/tests/queries/0_stateless/05315_plain_rewritable_part_removal_without_copies.sql @@ -0,0 +1,45 @@ +-- Tags: no-fasttest, no-replicated-database +-- Tag no-fasttest: requires S3 +-- Tag no-replicated-database: plain rewritable should not be shared between replicas + +-- Removing parts from a `plain_rewritable` disk must not copy their files. + +DROP TABLE IF EXISTS t_prr_plain; +DROP TABLE IF EXISTS t_prr_encrypted; + +CREATE TABLE t_prr_plain (a UInt64, s String) ENGINE = MergeTree ORDER BY a +SETTINGS disk = 's3_plain_rewritable', old_parts_lifetime = 0, merge_tree_clear_old_parts_interval_seconds = 100000; +SYSTEM STOP MERGES t_prr_plain; +SYSTEM STOP CLEANUP t_prr_plain; +INSERT INTO t_prr_plain SELECT number, toString(number) FROM numbers(100); +INSERT INTO t_prr_plain SELECT number, toString(number) FROM numbers(100, 100); +INSERT INTO t_prr_plain SELECT number, toString(number) FROM numbers(200, 100); +TRUNCATE TABLE t_prr_plain; + +CREATE TABLE t_prr_encrypted (a UInt64, s String) ENGINE = MergeTree ORDER BY a +SETTINGS disk = 'encrypted_s3_plain_rewritable_cache', old_parts_lifetime = 0, merge_tree_clear_old_parts_interval_seconds = 100000; +SYSTEM STOP MERGES t_prr_encrypted; +SYSTEM STOP CLEANUP t_prr_encrypted; +INSERT INTO t_prr_encrypted SELECT number, toString(number) FROM numbers(100); +INSERT INTO t_prr_encrypted SELECT number, toString(number) FROM numbers(100, 100); +INSERT INTO t_prr_encrypted SELECT number, toString(number) FROM numbers(200, 100); +TRUNCATE TABLE t_prr_encrypted; + +SYSTEM FLUSH LOGS query_log; + +SELECT ProfileEvents['DiskS3CopyObject'] + ProfileEvents['DiskS3UploadPartCopy'] AS copies, + ProfileEvents['DiskS3DeleteObjects'] > 0 AS removed_in_query +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND event_date >= yesterday() + AND query LIKE 'TRUNCATE TABLE t_prr_plain%'; +SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_prr_plain' AND rows > 0; + +SELECT ProfileEvents['DiskS3CopyObject'] + ProfileEvents['DiskS3UploadPartCopy'] AS copies, + ProfileEvents['DiskS3DeleteObjects'] > 0 AS removed_in_query +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND event_date >= yesterday() + AND query LIKE 'TRUNCATE TABLE t_prr_encrypted%'; +SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_prr_encrypted' AND rows > 0; + +DROP TABLE t_prr_plain; +DROP TABLE t_prr_encrypted; diff --git a/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference new file mode 100644 index 000000000000..47a0f3741797 --- /dev/null +++ b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.reference @@ -0,0 +1,2 @@ +1 +0 0 1 diff --git a/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh new file mode 100755 index 000000000000..41f4a0fc8560 --- /dev/null +++ b/tests/queries/0_stateless/05317_http_dictionary_source_hides_url_password.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The source of an `HTTP` dictionary is shown in `system.dictionaries` without the userinfo of its url. +user="user_${CLICKHOUSE_DATABASE}" +$CLICKHOUSE_CLIENT -q "DROP USER IF EXISTS ${user}" +$CLICKHOUSE_CLIENT -q "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'plain_dictionary_password'" + +url="http://${user}:plain_dictionary_password@${CLICKHOUSE_HOST}:${CLICKHOUSE_PORT_HTTP}/?query=SELECT+number,toString(number)+FROM+numbers(2)+FORMAT+TabSeparated" +$CLICKHOUSE_CLIENT -q "CREATE DICTIONARY dict_http (key UInt64, value String) PRIMARY KEY key SOURCE(HTTP(URL '${url}' FORMAT 'TabSeparated')) LIFETIME(0) LAYOUT(FLAT())" +$CLICKHOUSE_CLIENT -q "SELECT dictGet('dict_http', 'value', 1)" +$CLICKHOUSE_CLIENT -q "SELECT countSubstrings(source, 'plain_dictionary_password'), countSubstrings(source, '${user}'), countSubstrings(source, '[HIDDEN]') FROM system.dictionaries WHERE database = currentDatabase() AND name = 'dict_http'" + +$CLICKHOUSE_CLIENT -q "DROP DICTIONARY dict_http" +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.reference b/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.reference new file mode 100644 index 000000000000..efb2cddc9585 --- /dev/null +++ b/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.reference @@ -0,0 +1,15 @@ +update normal Wide 7 +update normal projection [7,8,9,3,4,5,6] +update normal base [7,8,9,3,4,5,6] +update aggregate projection [(100,1),(101,1),(102,1),(103,1),(104,1),(105,1),(106,1)] +update aggregate base [(100,1),(101,1),(102,1),(103,1),(104,1),(105,1),(106,1)] +update offset projection [9,7,6,4,3,1,0] [1,3,4,6,7,9,10] +update offset base [9,7,6,4,3,1,0] [1,3,4,6,7,9,10] +update compact Compact 7 +update compact projection [7,8,9,3,4,5,6] +materialize 7 +materialize projection [7,8,9,3,4,5,6] +clear 7 +clear projection [(3,0),(4,0),(5,0),(6,0),(7,0),(8,0),(9,0)] +unrelated 7 +unrelated base 7 49 diff --git a/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.sql b/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.sql new file mode 100644 index 000000000000..b4bee66bb82f --- /dev/null +++ b/tests/queries/0_stateless/05339_projection_rebuild_by_mutation_after_lightweight_delete.sql @@ -0,0 +1,106 @@ +-- A mutation that rewrites only some columns of a Wide part keeps the lightweight-deleted rows in it, +-- and a projection it rebuilds must still leave them out. + +SET mutations_sync = 2, lightweight_deletes_sync = 2; + +DROP TABLE IF EXISTS t_upd_normal; +DROP TABLE IF EXISTS t_upd_aggregate; +DROP TABLE IF EXISTS t_upd_offset; +DROP TABLE IF EXISTS t_upd_compact; +DROP TABLE IF EXISTS t_materialize; +DROP TABLE IF EXISTS t_clear; +DROP TABLE IF EXISTS t_unrelated; + +-- UPDATE of a column a normal projection stores +CREATE TABLE t_upd_normal (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT id, g ORDER BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_upd_normal SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_upd_normal WHERE id < 3; +ALTER TABLE t_upd_normal UPDATE g = g + 100 WHERE 1; + +SELECT 'update normal', part_type, sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_upd_normal' AND name = 'p' AND active GROUP BY part_type; +SELECT 'update normal projection', groupArray(id) FROM (SELECT id FROM t_upd_normal WHERE g >= 100 ORDER BY g, id) SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection_name = 'p'; +SELECT 'update normal base', groupArray(id) FROM (SELECT id FROM t_upd_normal WHERE g >= 100 ORDER BY g, id) SETTINGS optimize_use_projections = 0; + +-- the same through an aggregate projection +CREATE TABLE t_upd_aggregate (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT g, count() GROUP BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_upd_aggregate SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_upd_aggregate WHERE id < 3; +ALTER TABLE t_upd_aggregate UPDATE g = g + 100 WHERE 1; + +SELECT 'update aggregate projection', groupArray((g, c)) FROM (SELECT g, count() AS c FROM t_upd_aggregate GROUP BY g ORDER BY g) SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection_name = 'p'; +SELECT 'update aggregate base', groupArray((g, c)) FROM (SELECT g, count() AS c FROM t_upd_aggregate GROUP BY g ORDER BY g) SETTINGS optimize_use_projections = 0; + +-- a projection with `_part_offset` keeps the parent offset of each surviving row +CREATE TABLE t_upd_offset (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT g, _part_offset ORDER BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_upd_offset SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_upd_offset WHERE id IN (2, 5, 8); +ALTER TABLE t_upd_offset UPDATE g = 10 - id WHERE 1; + +SELECT 'update offset projection', groupArray(_parent_part_offset), groupArray(g) +FROM (SELECT _parent_part_offset, g FROM mergeTreeProjection(currentDatabase(), t_upd_offset, p) ORDER BY g); +SELECT 'update offset base', groupArray(_part_offset), groupArray(g) +FROM (SELECT _part_offset, g FROM t_upd_offset ORDER BY g) SETTINGS optimize_use_projections = 0; + +-- a Compact part is rewritten as a whole +CREATE TABLE t_upd_compact (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT id, g ORDER BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = '1G', min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_upd_compact SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_upd_compact WHERE id < 3; +ALTER TABLE t_upd_compact UPDATE g = g + 100 WHERE 1; + +SELECT 'update compact', part_type, sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_upd_compact' AND name = 'p' AND active GROUP BY part_type; +SELECT 'update compact projection', groupArray(id) FROM (SELECT id FROM t_upd_compact WHERE g >= 100 ORDER BY g, id) SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection_name = 'p'; + +-- MATERIALIZE PROJECTION of a projection added after the delete +CREATE TABLE t_materialize (id UInt64, g UInt64, w UInt64) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_materialize SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_materialize WHERE id < 3; +ALTER TABLE t_materialize ADD PROJECTION p (SELECT id, g ORDER BY g); +ALTER TABLE t_materialize MATERIALIZE PROJECTION p; + +SELECT 'materialize', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_materialize' AND name = 'p' AND active; +SELECT 'materialize projection', groupArray(id) FROM (SELECT id FROM t_materialize WHERE g < 100 ORDER BY g, id) SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection_name = 'p'; + +-- CLEAR COLUMN of a column the projection stores +CREATE TABLE t_clear (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT id, g ORDER BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_clear SELECT number, number % 7 + 1, number FROM numbers(10); +DELETE FROM t_clear WHERE id < 3; +ALTER TABLE t_clear CLEAR COLUMN g; + +SELECT 'clear', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_clear' AND name = 'p' AND active; +SELECT 'clear projection', groupArray((id, g)) FROM (SELECT id, g FROM t_clear WHERE g < 100 ORDER BY g, id) SETTINGS optimize_use_projections = 1, optimize_read_in_order = 1, force_optimize_projection_name = 'p'; + +-- an UPDATE of a column the projection does not use keeps the projection as it is +CREATE TABLE t_unrelated (id UInt64, g UInt64, w UInt64, PROJECTION p (SELECT id, g ORDER BY g)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, lightweight_mutation_projection_mode = 'rebuild'; +INSERT INTO t_unrelated SELECT number, number % 7, number FROM numbers(10); +DELETE FROM t_unrelated WHERE id < 3; +ALTER TABLE t_unrelated UPDATE w = w + 1 WHERE 1; + +SELECT 'unrelated', sum(rows) FROM system.projection_parts +WHERE database = currentDatabase() AND table = 't_unrelated' AND name = 'p' AND active; +SELECT 'unrelated base', count(), sum(w) FROM t_unrelated SETTINGS optimize_use_projections = 0; + +DROP TABLE t_upd_normal; +DROP TABLE t_upd_aggregate; +DROP TABLE t_upd_offset; +DROP TABLE t_upd_compact; +DROP TABLE t_materialize; +DROP TABLE t_clear; +DROP TABLE t_unrelated; diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference new file mode 100644 index 000000000000..a2e64b66af38 --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.reference @@ -0,0 +1,27 @@ +2 +3 +1 +1 +1 0 +tq_a delete +tq_b delete +tq_a keep +tq_b keep +tq_a delete +tq_b delete +tq_a keep +tq_b keep +keep +tq_a 1 +tq_b 1 +1 +1 +tq_s1 keep +tq_s2 keep +keep +tag +keep keep +keep keep +5 +2 +1 diff --git a/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql new file mode 100644 index 000000000000..8dc72c6f92b4 --- /dev/null +++ b/tests/queries/0_stateless/05366_s3queue_metadata_mismatch_immutable_fields.sql @@ -0,0 +1,240 @@ +-- Tags: no-fasttest, zookeeper +-- no-fasttest: the `S3Queue` and `AzureQueue` engines are not built in the fast test. +-- zookeeper: the immutable part of the queue metadata lives under `keeper_path` in keeper. + +-- A queue table stores the settings listed in `ObjectStorageQueueTableMetadata::isStoredInKeeper` +-- under its `keeper_path` (docs/reference/engines/table-engines/integrations/s3queue.mdx, section +-- `keeper_path`). A second table pointed at the same path must agree with what is already stored +-- there, so each of the immutable fields below is rejected with `METADATA_MISMATCH` on its own. +-- The object storage is never contacted: the metadata check happens while the engine is built. + +DROP TABLE IF EXISTS tq_base; +DROP TABLE IF EXISTS tq_bucket_base; + +CREATE TABLE tq_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +-- `after_processing`: stored as 'keep', local 'delete'. +CREATE TABLE tq1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + after_processing = 'delete'; -- { serverError METADATA_MISMATCH } + +-- `bucketing_mode`: stored as 'path', local 'partition'. A 'partition' bucketing mode hashes the +-- partition key instead of the path, so `bucketing_mode = 'partition'` is rejected outright unless a +-- partitioning mode is set too. To vary `bucketing_mode` alone, a second keeper path already stores +-- `partitioning_mode = 'regex'`, which needs no experimental setting. +CREATE TABLE tq_bucket_base (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +CREATE TABLE tq2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_bucket', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', partition_component = 'part', + bucketing_mode = 'partition'; -- { serverError METADATA_MISMATCH } + +-- `partitioning_mode`: stored as 'none', local 'regex'. The stored `partition_regex` and +-- `partition_component` differ too, but the partitioning mode is compared first. +CREATE TABLE tq3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partitioning_mode = 'regex', partition_regex = '(?P.+)/', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `partition_regex`: stored empty, local set. +CREATE TABLE tq4 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_regex = '(?P.+)'; -- { serverError METADATA_MISMATCH } + +-- `partition_component`: stored empty, local set. +CREATE TABLE tq5 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + partition_component = 'part'; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_limit`: stored as the default 1000, local 7. +CREATE TABLE tq6 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_files_limit = 7; -- { serverError METADATA_MISMATCH } + +-- `tracked_files_ttl_sec`: stored as the default 0, local 60. +CREATE TABLE tq7 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + tracked_file_ttl_sec = 60; -- { serverError METADATA_MISMATCH } + +-- `last_processed_path`: stored empty, local set. +CREATE TABLE tq8 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', + last_processed_path = 'a.csv'; -- { serverError METADATA_MISMATCH } + +-- `source`: stored path `05366_queue/*`, local path `05366_other/*`. +CREATE TABLE tq9 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_other/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- `source`: bucket `test0` with path `5366_queue/*` is another source than bucket `test` with path `05366_queue/*`. +CREATE TABLE tq10 (x String) ENGINE = S3Queue('http://localhost:11111/test0/5366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366'; -- { serverError METADATA_MISMATCH } + +-- Every mismatching table was rejected, so only the two base tables exist. +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +-- The check is selective: a table that agrees on all of the immutable fields joins the same path. +CREATE TABLE tq_same (x String) +ENGINE = S3Queue('http://localhost:11111/test/05366_queue/*', NOSIGN, 'CSV') +SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366', processing_threads_num = 1, + polling_min_timeout_ms = 1, polling_max_timeout_ms = 1, polling_backoff_ms = 0; + +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name LIKE 'tq%'; + +DROP TABLE tq_same; +DROP TABLE tq_bucket_base; +DROP TABLE tq_base; + +-- An `AzureQueue` and an `S3Queue` with the same endpoint, bucket and path read different storages. +CREATE TABLE tq_type_azure (x String) ENGINE = AzureQueue('http://localhost:11111', 'test', '05366_type/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; +CREATE TABLE tq_type_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_type/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_type'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_type_azure; + +-- The user info of a URL is not a part of the source. +CREATE TABLE tq_u (x String) ENGINE = S3Queue('http://user:secret@localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +CREATE TABLE tq_u2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_u/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info'; +DROP TABLE tq_u2; DROP TABLE tq_u; +-- The URL without user info is parsed with the same `s3_uri_style`: here `.s3.` in the host does not make it virtual-hosted. +SET s3_uri_style = 'path'; +CREATE TABLE tq_u3 (x String) ENGINE = S3Queue('http://user:secret@queue.s3.localhost:11111/test/05366_u3/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info_path'; +CREATE TABLE tq_u4 (x String) ENGINE = S3Queue('http://queue.s3.localhost:11111/test/05366_u3/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_user_info_path'; +SET s3_uri_style = DEFAULT; +DROP TABLE tq_u4; DROP TABLE tq_u3; +-- Paths that differ only in a part like `&sig=` are different sources. +CREATE TABLE tq_sig (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=a/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; +CREATE TABLE tq_sig_z (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_root&sig=z/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sig'; -- { serverError METADATA_MISMATCH } +DROP TABLE tq_sig; + +-- Azure forms that have a source: a scheme in upper case, and an `abfss` URL with a separate SAS. +CREATE TABLE tq_az_upper (x String) ENGINE = AzureQueue('HTTP://localhost:11111', 'test', '05366_upper/*', 'devstoreaccount1', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_upper'; +CREATE TABLE tq_az_sas (x String) ENGINE = AzureQueue('abfss://cont@acc.dfs.core.windows.net/05366_sas/*.csv', 'sv=1&sig=2') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_sas'; +SELECT JSONExtractString(value, 'source_hash') != '' FROM system.zookeeper WHERE path IN ('/clickhouse/' || currentDatabase() || '/05366_upper', '/clickhouse/' || currentDatabase() || '/05366_sas') AND name = 'metadata' ORDER BY path; +DROP TABLE tq_az_upper; +DROP TABLE tq_az_sas; + +-- `send_logs_level` keeps the warnings of the attached tables, and the errors of the refused queries, out of the test output. +SET send_logs_level = 'fatal'; + +CREATE TABLE tq_a (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; +CREATE TABLE tq_b (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_shared/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1, after_processing = 'keep'; +-- Keeper has only a hash of the source. +SELECT JSONExtractString(value, 'source_hash') != '', value LIKE '%05366_shared%' FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +-- Tables with the same `keeper_path` share `after_processing`: after the `ALTER` of `tq_a` both tables have `delete`, +-- while `tq_b` still has `keep` in its definition. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +-- Set `keep` in keeper, as the initiator of a `Replicated` database does before this server runs the query: only the copy of +-- this server still has `delete`, and the `ALTER` to `keep` below must still change it. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- `tq_b` already has `keep` in its definition, but an `ALTER` or a `RESET` to `keep` must still change the queue. +-- The same holds for `tq_a`, whose definition already has `delete`. +ALTER TABLE tq_b MODIFY SETTING after_processing = 'keep'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_a MODIFY SETTING after_processing = 'delete'; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +ALTER TABLE tq_b RESET SETTING after_processing; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'after_processing' ORDER BY table; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +-- Leave `keep` in the definition of `tq_a` too, so that both tables can be attached again below. +ALTER TABLE tq_a MODIFY SETTING after_processing = 'keep'; +-- The same holds for any setting stored in keeper that an `ALTER` can change, e.g. `processing_threads_num`. +ALTER TABLE tq_a MODIFY SETTING processing_threads_num = 2; +ALTER TABLE tq_b MODIFY SETTING processing_threads_num = 1; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table IN ('tq_a', 'tq_b') AND name = 'processing_threads_num' ORDER BY table; + +-- A setting that the mode does not allow to change can still be repeated with the value of the definition, +-- also when the queue uses the value of another table (`tq_o1` uses 4 threads of `tq_o`). +CREATE TABLE tq_o (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 4; +CREATE TABLE tq_o1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_o/*', NOSIGN, 'CSV') SETTINGS mode = 'ordered', keeper_path = '/clickhouse/{database}/05366_o', processing_threads_num = 1; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 4; +ALTER TABLE tq_o1 MODIFY SETTING processing_threads_num = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%processing_threads_num = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_o1'; +ALTER TABLE tq_o MODIFY SETTING processing_threads_num = 5; -- { serverError SUPPORT_IS_DISABLED } +DROP TABLE tq_o; +DROP TABLE tq_o1; + +-- `parallel_inserts` is not stored in keeper, so repeating its value next to another setting changes only the other one. +CREATE TABLE tq_p (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_p/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_p', parallel_inserts = 1; +ALTER TABLE tq_p MODIFY SETTING parallel_inserts = 1, polling_max_timeout_ms = 2000; +SELECT create_table_query LIKE '%parallel_inserts = 1%polling_max_timeout_ms = 2000%' FROM system.tables WHERE database = currentDatabase() AND name = 'tq_p'; +DROP TABLE tq_p; + +-- `after_processing` is still checked when a table is attached, as on master. A table that fails to attach cannot be +-- detached again in a `Replicated` database, so this uses an `Atomic` one. +CREATE DATABASE {CLICKHOUSE_DATABASE_1:Identifier} ENGINE = Atomic; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale', after_processing = 'keep'; +-- After the `ALTER` of `tq_s1`, `tq_s2` still has `keep` in its definition and keeper has `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'keep'; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +SELECT table, value FROM system.s3_queue_settings WHERE database = currentDatabase() || '_1' AND table IN ('tq_s1', 'tq_s2') AND name = 'after_processing' ORDER BY table; + +-- Set `after_processing` to `keep` directly in keeper, as another server would, while the copy of this server has `delete`. +-- Then a reattached table and a new table fail instead of taking the outdated `delete`. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'delete'; +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2 MODIFY SETTING after_processing = 'delete'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"delete"', '"after_processing":"keep"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DETACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; +ATTACH TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s2; -- { serverError METADATA_MISMATCH } +CREATE TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s3 (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_stale/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_stale'; -- { serverError METADATA_MISMATCH } +-- An `ALTER` of another setting needs no `WRITE` grant, so it must not write the outdated `delete` of this server back to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +-- An `ALTER` of `after_processing` itself is written to keeper. +ALTER TABLE {CLICKHOUSE_DATABASE_1:Identifier}.tq_s1 MODIFY SETTING after_processing = 'tag', after_processing_tag_key = 'k', after_processing_tag_value = 'v'; +SELECT JSONExtractString(value, 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '_1/05366_stale' AND name = 'metadata'; +DROP DATABASE {CLICKHOUSE_DATABASE_1:Identifier} SYNC; + +-- Set `delete` directly in keeper, as another server would, while the definition and the copy of this server have +-- `keep`. An explicit `keep` must still reach keeper, by a `MODIFY` and by a `RESET`. +CREATE TABLE tq_k (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_k/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_k', after_processing = 'keep'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING after_processing = 'keep'; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"after_processing":"keep"', '"after_processing":"delete"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k RESET SETTING after_processing; +SELECT JSONExtractString(value, 'after_processing'), (SELECT value FROM system.s3_queue_settings WHERE database = currentDatabase() AND table = 'tq_k' AND name = 'after_processing') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +-- An `ALTER` changes only the settings it names: `loading_retries` set by another server stays in keeper. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceOne(value, '"loading_retries":10', '"loading_retries":5') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +ALTER TABLE tq_k MODIFY SETTING polling_max_timeout_ms = 2000; +SELECT JSONExtractUInt(value, 'loading_retries') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_k' AND name = 'metadata'; +DROP TABLE tq_k; + +-- Change the source in keeper: the tables must still attach, with a warning. +DETACH TABLE tq_a; DETACH TABLE tq_b; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT count() FROM system.tables WHERE database = currentDatabase() AND name IN ('tq_a', 'tq_b'); + +-- A named collection can change without an `ALTER` of the table, so a table that uses one must still match the source +-- in keeper when it attaches. Changing the source in keeper has the same effect as changing the collection. +CREATE TABLE tq_nc (x String) ENGINE = S3Queue(s3_conn, filename = '05366_nc/*', format = 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_nc'; +DETACH TABLE tq_nc; +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpOne(value, '"source_hash":"[^"]*"', '"source_hash":"00"') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; -- { serverError METADATA_MISMATCH } +-- Without a source in keeper, as in metadata of an older version, the table attaches and writes its source there. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_nc' AND name = 'metadata'; +ATTACH TABLE tq_nc; +DROP TABLE tq_nc; + +-- Remove `source` from keeper, as in metadata of an older version: the first attached table writes it back. +-- A new table must not join such metadata, because it could belong to another source. +INSERT INTO system.zookeeper (name, path, value) SELECT name, path, replaceRegexpAll(value, ',"source_hash":"[^"]*"', '') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; +DETACH TABLE tq_a; DETACH TABLE tq_b; +CREATE TABLE tq_c (x String) ENGINE = S3Queue('http://localhost:11111/test/05366_c/*', NOSIGN, 'CSV') SETTINGS mode = 'unordered', keeper_path = '/clickhouse/{database}/05366_shared', processing_threads_num = 1; -- { serverError METADATA_MISMATCH } +ATTACH TABLE tq_b; ATTACH TABLE tq_a; +SELECT JSONExtractString(value, 'source_hash') NOT IN ('', '00') FROM system.zookeeper WHERE path = '/clickhouse/' || currentDatabase() || '/05366_shared' AND name = 'metadata'; + +DROP TABLE tq_b; +DROP TABLE tq_a; diff --git a/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.reference b/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.reference new file mode 100644 index 000000000000..62b0e28558db --- /dev/null +++ b/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.reference @@ -0,0 +1,96 @@ +bare key, rollup true +bare key, rollup \N +if, rollup true +if, rollup \N +if, cube true +if, cube \N +if false branch, rollup true +if false branch, rollup \N +multiIf, rollup true +multiIf, rollup \N +multiIf kept, rollup true +multiIf kept, rollup \N +nested if, rollup true +nested if, rollup \N +multiIf condition, rollup true +multiIf condition, rollup \N +correlated, collapsed column repeated true +correlated, collapsed column repeated \N +if, rollup, grouping() true 0 +if, rollup, grouping() \N 1 +two if keys, cube true false +two if keys, cube true \N +two if keys, cube \N false +two if keys, cube \N \N +reported query true 1 +reported query \N 1 +if, rollup, UInt8 1 +if, rollup, UInt8 \N +if, rollup, UInt64 1 +if, rollup, UInt64 \N +if, rollup, String x +if, rollup, String \N +if, rollup, Nullable true +if, rollup, Nullable \N +if and bare key, rollup true +if and bare key, rollup \N +if and bare key, rollup \N +if, totals true + +if, totals \N +if, rollup, setting off false +if, rollup, setting off true +collapsed column repeated x 1 +collapsed column repeated \N 1 +collapsed column repeated, written sub-key x 1 +collapsed column repeated, written sub-key \N 1 +collapsed column repeated, written sub-key \N 1 +nested, collapsed column repeated x 1 +nested, collapsed column repeated \N 1 +nested, collapsed column repeated \N 1 +other branch not a key x 1 +other branch not a key \N 1 +nested, other branch not a key x 1 +nested, other branch not a key \N 1 +collapses to another key, rollup 3 1 +collapses to another key, rollup x 1 1 +collapses to another key, rollup x x 0 1 +collapses to another key, cube 1 +collapses to another key, cube x 1 +collapses to another key, cube x 1 +collapses to another key, cube x x 1 +collapses to another key, grouping sets x 1 +collapses to another key, grouping sets x 1 +collapses to another key, rollup, nulls x x 1 +collapses to another key, rollup, nulls x \N 1 +collapses to another key, rollup, nulls \N \N 1 +collapses to another key, rollup, nulls, multiIf x x 1 +collapses to another key, rollup, nulls, multiIf x \N 1 +collapses to another key, rollup, nulls, multiIf \N \N 1 +if chain, rollup, nulls, multiIf p pz 1 +if chain, rollup, nulls, multiIf q qz 1 +if chain, rollup, nulls, multiIf r rz 1 +if chain, rollup, nulls, multiIf \N \N 3 +if chain of other keys, rollup, nulls, multiIf x w x 1 +if chain of other keys, rollup, nulls, multiIf x w \N 1 +if chain of other keys, rollup, nulls, multiIf x \N \N 1 +if chain of other keys, rollup, nulls, multiIf \N \N \N 1 +collapses to another key, other sources, cube 1 +collapses to another key, other sources, cube x 1 +collapses to another key, other sources, cube x 1 +collapses to another key, other sources, cube x x 1 +collapses to columns of other sources, rollup 0 1 +collapses to columns of other sources, rollup 1 1 +collapses to columns of other sources, rollup 1 1 +subquery of a query with a key that collapses to another key 1 1 +subquery of a query with a key that collapses to another key 1 1 +subquery of a query with a key that collapses to another key \N 1 +subquery of a query with a key that collapses to another key \N 1 +subquery of a query with a key that collapses to another key \N 2 +keys collapse together, grouping sets 1 +keys collapse together, grouping sets, setting off 0 1 +keys collapse together, grouping sets, setting off 1 1 +dictionary condition, rollup true +dictionary condition, rollup \N +nested dictionary condition, rollup true +nested dictionary condition, rollup \N diff --git a/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.sql b/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.sql new file mode 100644 index 000000000000..cf744914c6bd --- /dev/null +++ b/tests/queries/0_stateless/05385_group_by_use_nulls_constant_condition_group_by_key.sql @@ -0,0 +1,224 @@ +-- A GROUP BY key `if`/`multiIf` with a constant condition always evaluates to one of its branches. When that +-- branch is a column, the key read back by other clauses and a correlated subquery reading the column must return +-- what they return when the column itself is the key, including the NULLs of ROLLUP/CUBE/GROUPING SETS under +-- `group_by_use_nulls`. + +-- clickhouse-test randomizes these; they are pinned at their defaults to keep the query shapes below. +SET optimize_multiif_to_if = 1, optimize_if_chain_to_multiif = 0, optimize_group_by_function_keys = 1, + optimize_injective_functions_in_group_by = 1, optimize_functions_to_subcolumns = 1, + optimize_if_transform_strings_to_enum = 0; +SET enable_analyzer = 1, allow_experimental_correlated_subqueries = 1; + +DROP DICTIONARY IF EXISTS d05385; +CREATE DICTIONARY d05385 (id UInt64, v String) PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()) LIFETIME(0); + +-- A correlated subquery cannot appear in ORDER BY, so the collapsing key is ordered by instead, or +-- the aggregation is wrapped. Both are needed: ROLLUP emits its grouping sets in no fixed order. + +-- The reference the collapsing forms below must agree with: the same query with the bare key. +SELECT 'bare key, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY c0 WITH ROLLUP ORDER BY c0 NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false) WITH ROLLUP +ORDER BY if(1, c0, false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, cube', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false) WITH CUBE +ORDER BY if(1, c0, false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- The false branch is taken here. +SELECT 'if false branch, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(0, false, c0) WITH ROLLUP +ORDER BY if(0, false, c0) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'multiIf, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY multiIf(1, c0, false) WITH ROLLUP +ORDER BY multiIf(1, c0, false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- The same with the rewrite of `multiIf` to `if` disabled. +SELECT 'multiIf kept, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY multiIf(1, c0, false) WITH ROLLUP +ORDER BY multiIf(1, c0, false) NULLS LAST +SETTINGS group_by_use_nulls = 1, optimize_multiif_to_if = 0; + +SELECT 'nested if, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, if(1, c0, false), false) WITH ROLLUP +ORDER BY if(1, if(1, c0, false), false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- The condition is itself a `multiIf` with a constant condition. +SELECT 'multiIf condition, rollup', (SELECT c0) FROM (SELECT 1::Bool, 1::UInt8) t0(c0, c1) +GROUP BY if(multiIf(1, 1, c1), c0, false) WITH ROLLUP +ORDER BY if(multiIf(1, 1, c1), c0, false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'correlated, collapsed column repeated', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, not(c0)) WITH ROLLUP +ORDER BY if(1, c0, not(c0)) NULLS LAST SETTINGS group_by_use_nulls = 1, enable_identifier_resolve_cache = 1; + +SELECT 'if, rollup, grouping()', (SELECT c0), grouping(if(1, c0, false)) AS g +FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false) WITH ROLLUP ORDER BY g SETTINGS group_by_use_nulls = 1; + +SELECT 'two if keys, cube', a, b FROM +( + SELECT (SELECT c0) AS a, (SELECT c1) AS b + FROM (SELECT 1::Bool AS c0, 0::Bool AS c1) t0 + GROUP BY if(1, c0, false), if(1, c1, true) WITH CUBE +) +ORDER BY a NULLS LAST, b NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- The query from the report, with the condition and the always-false branch kept as they were. +SELECT 'reported query', x, c FROM +( + SELECT (SELECT c0) AS x, count() AS c FROM (SELECT CAST('1', 'Bool')) AS t0(c0) + GROUP BY GROUPING SETS ((if(82, c0, (1 IN tuple(2, 2147483648, 5, toUInt128(4), 3)))), ()) +) +ORDER BY x NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- Types other than `Bool` returned these values before the fix as well and must keep returning them. +SELECT 'if, rollup, UInt8', (SELECT c0) FROM (SELECT 1::UInt8) t0(c0) +GROUP BY if(1, c0, 0) WITH ROLLUP +ORDER BY if(1, c0, 0) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, rollup, UInt64', (SELECT c0) FROM (SELECT 1::UInt64) t0(c0) +GROUP BY if(1, c0, 0) WITH ROLLUP +ORDER BY if(1, c0, 0) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, rollup, String', (SELECT c0) FROM (SELECT 'x'::String) t0(c0) +GROUP BY if(1, c0, 'y') WITH ROLLUP +ORDER BY if(1, c0, 'y') NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, rollup, Nullable', (SELECT c0) FROM (SELECT 1::Nullable(Bool)) t0(c0) +GROUP BY if(1, c0, false::Nullable(Bool)) WITH ROLLUP +ORDER BY if(1, c0, false::Nullable(Bool)) NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if and bare key, rollup', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false), c0 WITH ROLLUP +ORDER BY c0 NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'if, totals', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false) WITH TOTALS +ORDER BY if(1, c0, false) NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- Without the setting the key keeps its own type. +SELECT 'if, rollup, setting off', (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, c0, false) WITH ROLLUP +ORDER BY if(1, c0, false) NULLS LAST SETTINGS group_by_use_nulls = 0; + +-- Keys in which the collapsed column occurs more than once, with enable_identifier_resolve_cache on (the default). +SELECT 'collapsed column repeated', if(1, c0, lower(c0)) AS k, count() FROM (SELECT 'x'::String) t0(c0) +GROUP BY k WITH ROLLUP ORDER BY k NULLS LAST SETTINGS group_by_use_nulls = 1, enable_identifier_resolve_cache = 1; + +SELECT 'collapsed column repeated, written sub-key', if(1, c0, lower(c0)) AS k, count() FROM (SELECT 'x'::String) t0(c0) +GROUP BY lower(c0), k WITH ROLLUP ORDER BY k NULLS LAST SETTINGS group_by_use_nulls = 1, enable_identifier_resolve_cache = 1; + +SELECT 'nested, collapsed column repeated', if(0, c0, if(0, lower(c0), c0)) AS k, count() FROM (SELECT 'x'::String) t0(c0) +GROUP BY lower(c0), k WITH ROLLUP ORDER BY k NULLS LAST SETTINGS group_by_use_nulls = 1, enable_identifier_resolve_cache = 1; + +-- The branch that is not taken reads a column that is not a key. +SELECT 'other branch not a key', multiIf(0, b, a) AS k, count() FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 +GROUP BY k WITH ROLLUP ORDER BY k NULLS LAST SETTINGS group_by_use_nulls = 1; + +SELECT 'nested, other branch not a key', if(0, b, if(0, b, a)) AS k, count() FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 +GROUP BY k WITH ROLLUP ORDER BY k NULLS LAST SETTINGS group_by_use_nulls = 1; + +-- A key that collapses to another key keeps its own grouping sets. +SELECT 'collapses to another key, rollup', a, if(0, b, if(0, b, a)) AS k, grouping(a, k), count() +FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 GROUP BY ROLLUP(a, k) ORDER BY a, k; + +SELECT 'collapses to another key, cube', a, if(0, b, if(0, b, a)) AS k, count() +FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 GROUP BY CUBE(a, k) ORDER BY a, k; + +SELECT 'collapses to another key, grouping sets', a, if(0, b, if(0, b, a)) AS k, count() +FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 GROUP BY GROUPING SETS ((a), (k)) ORDER BY a, k; + +SELECT 'collapses to another key, rollup, nulls', a, if(0, b, if(0, b, a)) AS k, count() +FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 GROUP BY ROLLUP(a, k) ORDER BY a NULLS LAST, k NULLS LAST +SETTINGS group_by_use_nulls = 1; + +-- The same with `if` chains rewritten to `multiIf`. +SELECT 'collapses to another key, rollup, nulls, multiIf', a, if(0, b, if(0, b, a)) AS k, count() +FROM (SELECT 'x'::String AS a, 'y'::String AS b) t0 GROUP BY ROLLUP(a, k) ORDER BY a NULLS LAST, k NULLS LAST +SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; + +-- Also when the conditions are not constant, and when they read other keys. +SELECT 'if chain, rollup, nulls, multiIf', if(number > 1, 'p', if(number > 0, 'q', 'r')) AS k, concat(k, 'z'), count() +FROM numbers(3) GROUP BY k WITH ROLLUP ORDER BY k NULLS LAST +SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; + +SELECT 'if chain of other keys, rollup, nulls, multiIf', a, b, if(a = 'x', a, if(b = 'y', b, a)) AS k, count() +FROM (SELECT 'x' AS a, 'w' AS b) t0 GROUP BY ROLLUP(a, b, k) ORDER BY ALL +SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; + +-- Columns of different sources are different keys, in the branch that is taken and in the ones that are not. +SELECT 'collapses to another key, other sources, cube', if(0, s2.b, if(0, s2.b, s1.a)) AS k1, if(0, s3.b, if(0, s3.b, s1.a)) AS k2, count() +FROM (SELECT 'x' AS a) AS s1, (SELECT 'y' AS b) AS s2, (SELECT 'y' AS b) AS s3 GROUP BY CUBE(k1, k2) ORDER BY k1, k2; + +SELECT 'collapses to columns of other sources, rollup', a, c FROM +( + SELECT (SELECT s1.a) AS a, count() AS c FROM (SELECT 1::UInt8 AS a) AS s1, (SELECT 1::UInt8 AS a) AS s2 + GROUP BY ROLLUP(if(1, s1.a, 0), if(1, s2.a, 0)) +) +ORDER BY a, c; + +-- The same in a subquery of such a query. +SELECT 'subquery of a query with a key that collapses to another key', a, count() FROM +( + SELECT (SELECT c0) AS a FROM (SELECT 1::UInt8) t0(c0) + GROUP BY if(1, c0, 0) WITH ROLLUP +) +GROUP BY ROLLUP(a, if(0, a, if(0, a, a))) ORDER BY ALL SETTINGS group_by_use_nulls = 1; + +-- Keys that collapse to the same column and are in the same grouping sets. +SELECT 'keys collapse together, grouping sets', (SELECT c0) FROM (SELECT 1::UInt8) t0(c0) +GROUP BY GROUPING SETS ((if(1, c0, 0), if(1, c0, 2))) SETTINGS group_by_use_nulls = 1; + +SELECT 'keys collapse together, grouping sets, setting off', a, c FROM +( + SELECT (SELECT c0) AS a, count() AS c FROM (SELECT 1::UInt8) t0(c0) + GROUP BY GROUPING SETS ((if(1, c0, 0), if(1, c0, 2)), ()) +) +ORDER BY a SETTINGS group_by_use_nulls = 0; + +-- The condition becomes constant only when the dictionary lookup, which matches no key, is optimized away. +SELECT 'dictionary condition, rollup', (SELECT c0) FROM (SELECT 1::Bool AS c0, 1::UInt64 AS id) t0 +GROUP BY if(dictGet('d05385', 'v', id) = 'x', false, c0) WITH ROLLUP +ORDER BY if(dictGet('d05385', 'v', id) = 'x', false, c0) NULLS LAST +SETTINGS group_by_use_nulls = 1, optimize_inverse_dictionary_lookup = 1; + +SELECT 'nested dictionary condition, rollup', (SELECT c0) FROM (SELECT 1::Bool AS c0, 1::UInt64 AS id) t0 +GROUP BY if(1, if(dictGet('d05385', 'v', id) = 'x', false, c0), false) WITH ROLLUP +ORDER BY if(1, if(dictGet('d05385', 'v', id) = 'x', false, c0), false) NULLS LAST +SETTINGS group_by_use_nulls = 1, optimize_inverse_dictionary_lookup = 1; + +-- A key that does not collapse to the correlated column keeps rejecting the query. +SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(1, toUInt8(c0), 0) WITH ROLLUP +SETTINGS group_by_use_nulls = 1; -- { serverError NOT_IMPLEMENTED } + +SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY toBool(c0) WITH ROLLUP +SETTINGS group_by_use_nulls = 1; -- { serverError NOT_IMPLEMENTED } + +SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY c0 AND true WITH ROLLUP +SETTINGS group_by_use_nulls = 1; -- { serverError NOT_IMPLEMENTED } + +SELECT (SELECT c0) FROM (SELECT 1::Bool) t0(c0) +GROUP BY tuple(c0).1 WITH ROLLUP +SETTINGS group_by_use_nulls = 1; -- { serverError NOT_IMPLEMENTED } + +SELECT (SELECT c0) FROM (SELECT 1::LowCardinality(Bool)) t0(c0) +GROUP BY if(1, c0, false::LowCardinality(Bool)) WITH ROLLUP +SETTINGS group_by_use_nulls = 1, allow_suspicious_low_cardinality_types = 1; -- { serverError NOT_IMPLEMENTED } + +SELECT (SELECT c0) FROM (SELECT 1::Bool AS c0, 1::UInt64 AS id) t0 +GROUP BY if(1, if(dictGet('d05385', 'v', id) = 'x', false, c0), false) WITH ROLLUP +SETTINGS group_by_use_nulls = 1, optimize_inverse_dictionary_lookup = 0; -- { serverError NOT_IMPLEMENTED } + +-- An uncorrelated reference to the column is still rejected: the column is not one of the keys as written. +SELECT c0 FROM (SELECT 1::Bool) t0(c0) +GROUP BY if(82, c0, false) WITH ROLLUP +SETTINGS group_by_use_nulls = 1; -- { serverError NOT_AN_AGGREGATE } + +DROP DICTIONARY d05385; diff --git a/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.reference b/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.reference new file mode 100644 index 000000000000..6276a3f8eb1e --- /dev/null +++ b/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.reference @@ -0,0 +1,34 @@ +v0 +v1 +v2 +v3 +v4 +v5 +v6 +v0 +v1 +v2 +v3 +v4 +v5 +v6 +0 +1 +2 +0 +2 +0 +1 +2 + 9 +0 3 +1 3 +2 3 +0 +1 +2 +0 0x +1 1x +2 2x +0 0 +0 diff --git a/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.sql b/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.sql new file mode 100644 index 000000000000..5d6de99f70fe --- /dev/null +++ b/tests/queries/0_stateless/05386_analyzer_identifier_cache_constant_if_chain.sql @@ -0,0 +1,45 @@ +-- A GROUP BY alias of a nested `if`/`multiIf` with constant conditions that is referenced again (ORDER BY, HAVING, +-- LIMIT BY, GROUPING SETS) must return the same rows with `enable_identifier_resolve_cache` on and off. +-- https://github.com/ClickHouse/ClickHouse/issues/122404 + +SET enable_analyzer = 1; + +DROP TABLE IF EXISTS u2; +DROP TABLE IF EXISTS u3; +DROP TABLE IF EXISTS t; + +CREATE TABLE u2 (p String, a1 LowCardinality(String), a2 String, a8 String) ENGINE = MergeTree ORDER BY p; +CREATE TABLE u3 (p String, g1 LowCardinality(String), g2 String) ENGINE = MergeTree ORDER BY p; +INSERT INTO u2 SELECT toString(number % 20), 'v' || toString(number % 7), 'a', 'f' FROM numbers(100); +INSERT INTO u3 SELECT toString(number), 'm', 'n' FROM numbers(20); + +-- The query from the issue. +SELECT multiIf(('x2' IN ('x1')), q2.g1, multiIf(('x2' IN ('x2')), q1.a1, multiIf(('x2' IN ('x3')), q1.a2, multiIf(('x2' IN ('x4')), q1.a8, multiIf(('x2' IN ('x5')), q2.g2, q1.a1))))) AS r1 +FROM u2 AS q1 INNER JOIN u3 AS q2 ON q1.p = q2.p GROUP BY r1 ORDER BY r1 ASC +SETTINGS enable_identifier_resolve_cache = 1; + +SELECT multiIf(('x2' IN ('x1')), q2.g1, multiIf(('x2' IN ('x2')), q1.a1, multiIf(('x2' IN ('x3')), q1.a2, multiIf(('x2' IN ('x4')), q1.a8, multiIf(('x2' IN ('x5')), q2.g2, q1.a1))))) AS r1 +FROM u2 AS q1 INNER JOIN u3 AS q2 ON q1.p = q2.p GROUP BY r1 ORDER BY r1 ASC +SETTINGS enable_identifier_resolve_cache = 0; + +CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY s; +INSERT INTO t SELECT toString(number % 3) FROM numbers(9); + +SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r SETTINGS enable_identifier_resolve_cache = 1; +SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r HAVING r != '1' ORDER BY r SETTINGS enable_identifier_resolve_cache = 1; +SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r LIMIT 1 BY r SETTINGS enable_identifier_resolve_cache = 1; +SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r, count() FROM t GROUP BY GROUPING SETS ((r), ()) ORDER BY r SETTINGS enable_identifier_resolve_cache = 1; +SELECT r FROM t GROUP BY if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r HAVING r != '' ORDER BY r SETTINGS enable_identifier_resolve_cache = 1; +SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r, r || 'x' AS q FROM t GROUP BY r ORDER BY r SETTINGS enable_identifier_resolve_cache = 1; + +-- The query tree is the same with and without the cache. +SELECT + (SELECT countIf(explain ILIKE '%function_name: if,%' OR explain ILIKE '%function_name: multiIf,%') FROM (EXPLAIN QUERY TREE SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r SETTINGS enable_identifier_resolve_cache = 1)), + (SELECT countIf(explain ILIKE '%function_name: if,%' OR explain ILIKE '%function_name: multiIf,%') FROM (EXPLAIN QUERY TREE SELECT if(0, s, if(0, s, if(0, s, if(0, s, s)))) AS r FROM t GROUP BY r ORDER BY r SETTINGS enable_identifier_resolve_cache = 0)); + +-- A chain of constant conditions is folded completely. +SELECT countIf(explain ILIKE '%function_name: if,%' OR explain ILIKE '%function_name: multiIf,%') FROM (EXPLAIN QUERY TREE SELECT if(0, number, if(0, number, if(0, number, if(0, number, number)))) FROM numbers(1)); + +DROP TABLE t; +DROP TABLE u3; +DROP TABLE u2; diff --git a/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference new file mode 100644 index 000000000000..74d9aa4e2d8f --- /dev/null +++ b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.reference @@ -0,0 +1,70 @@ +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +\N \N 2 +3 +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +\N \N 2 +1 [] 1 +1 [3] 1 +2 [] 1 +2 [2] 1 +\N [] 2 +0 q 1 +0 \N 1 +1 q 1 +1 \N 1 +2 p 1 +2 \N 1 +3 q 1 +3 \N 1 +\N \N 4 +0 q +1 q +2 p +3 q +1 +3 +5 +0 +2 +4 +1 u +3 w +5 w +0 y +2 y +4 y +1 +(0) 4 +(1) 3 +(2) 3 +\N 10 +0 (0) +1 (1) +0 \N +1 \N +\N \N +(0) 4 +(1) 3 +(2) 3 +(0) 4 +(0) 10 +(1) 3 +(2) 3 +(0) 4 +(1) 3 +(2) 3 +\N 10 +(0,0) 2 +(0,1) 2 +(0,2) 2 +(1,0) 2 +(1,1) 2 +(1,2) 2 +\N 12 +0 diff --git a/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql new file mode 100644 index 000000000000..ebfb03157381 --- /dev/null +++ b/tests/queries/0_stateless/05397_group_by_key_in_if_chain_and_order_by_tuple.sql @@ -0,0 +1,31 @@ +-- An if chain or an ORDER BY tuple that contains a GROUP BY key reads the key from the aggregation result. + +SET optimize_if_transform_strings_to_enum = 0; + +-- A constant-condition `if` key nested in an `if` chain (#125803). +SELECT n, if(n = 5, toString(n), if(1, if(n > 1, 'p', 'q'), 'z')) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(1, if(n > 1, 'p', 'q'), 'z')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT count() FROM (SELECT n, if(n = 5, toString(n), if(1, if(n > 1, 'p', 'q'), 'z')) AS e FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(1, if(n > 1, 'p', 'q'), 'z')) HAVING e IS NULL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1); + +-- A plain `if` key nested in an `if` chain. +SELECT n, if(n = 5, toString(n), if(n > 1, 'p', 'q')) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(n > 1, 'p', 'q')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, [toUInt8(n)], if(n > 1, [2], [3])) AS e, count() FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n, if(n > 1, [2], [3])) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, toString(n), if(m > 1, 'p', 'q')) AS e, count() FROM (SELECT number AS n, number % 3 AS m FROM numbers(4)) GROUP BY ROLLUP(n, if(m > 1, 'p', 'q')) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1; +SELECT n, if(n = 5, toString(n), if(m > 1, 'p', 'q')) AS e FROM (SELECT number AS n, number % 3 AS m FROM numbers(4)) GROUP BY n, if(m > 1, 'p', 'q') ORDER BY n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1; + +-- A key whose `then` branch is itself a chain. +SELECT n FROM (SELECT number AS n, number % 2 = 1 AS a, number % 3 = 1 AS p, number % 5 = 1 AS q FROM numbers(6)) GROUP BY n, if(a, if(p, 'u', if(q, 'v', 'w')), 'y') ORDER BY if(n = 5, 'x', if(a, if(p, 'u', if(q, 'v', 'w')), 'y')), n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1; +SELECT n, if(a, if(p, 'u', if(q, 'v', 'w')), 'y') AS k FROM (SELECT number AS n, number % 2 = 1 AS a, number % 3 = 1 AS p, number % 5 = 1 AS q FROM numbers(6)) GROUP BY n, k ORDER BY if(n = 5, 'x', k), n SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 1, enable_identifier_resolve_cache = 1; + +-- A chain without a key is still rewritten. +SELECT count() FROM (EXPLAIN QUERY TREE SELECT n, if(n = 1, 'a', if(n = 2, 'b', 'c')) FROM (SELECT arrayJoin([1, 2]) AS n) GROUP BY ROLLUP(n) SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 1) WHERE explain ILIKE '%function_name: multiIf%'; + +-- A tuple key in ORDER BY (#125804). +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY ROLLUP(k) ORDER BY k SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT a, if(1, tuple(a), tuple(0)) AS k FROM (SELECT number % 2 AS a FROM numbers(4)) GROUP BY ROLLUP(a, k) ORDER BY k, a SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY k ORDER BY k SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY ROLLUP(k) ORDER BY k SETTINGS group_by_use_nulls = 0, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a), tuple(0)) AS k, count() FROM (SELECT number % 3 AS a FROM numbers(10)) GROUP BY CUBE(k) ORDER BY ALL SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; +SELECT if(1, tuple(a, b), tuple(0, 0)) AS k, count() FROM (SELECT number % 2 AS a, number % 3 AS b FROM numbers(12)) GROUP BY GROUPING SETS ((k), ()) ORDER BY k SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0; + +-- A tuple of keys that is not itself a key is still split. +SELECT count() FROM (EXPLAIN QUERY TREE SELECT a, b FROM (SELECT number % 2 AS a, number % 3 AS b FROM numbers(12)) GROUP BY ROLLUP(a, b) ORDER BY tuple(a, b) SETTINGS group_by_use_nulls = 1, optimize_if_chain_to_multiif = 0) WHERE explain ILIKE '%function_name: tuple%'; diff --git a/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.reference b/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.reference new file mode 100644 index 000000000000..d38f7b7992ac --- /dev/null +++ b/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.reference @@ -0,0 +1,14 @@ +offset compact storage Compact Full 1200000 +offset compact first delete rows 1188118 1188118 0 +offset compact first delete parent-offset matches 1188118 1188118 +offset compact second delete rows 1176582 1176582 0 +offset compact second delete parent-offset matches 1176582 1176582 +offset compact merged rows 1 1177582 1177582 0 +offset compact merged parent-offset matches 1177582 1177582 +offset wide storage Wide Full 1200000 +offset wide first delete rows 1188118 1188118 0 +offset wide first delete parent-offset matches 1188118 1188118 +offset wide second delete rows 1176582 1176582 0 +offset wide second delete parent-offset matches 1176582 1176582 +offset wide merged rows 1 1177582 1177582 0 +offset wide merged parent-offset matches 1177582 1177582 diff --git a/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.sql b/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.sql new file mode 100644 index 000000000000..b3a26bf77f95 --- /dev/null +++ b/tests/queries/0_stateless/05401_lwd_rebuild_projection_part_offset_multi_block.sql @@ -0,0 +1,108 @@ +-- Tags: long +-- 1.2M-row parts, too heavy for the 180 s flaky-check limit under sanitizers. + +SET mutations_sync = 2, lightweight_deletes_sync = 2; + +-- Projection storing the parent `_part_offset` (with_parent_part_offset path), on Compact +-- (MutateAllPartColumns) and Wide (MutateSomePartColumns) parts. The deletion mask must filter the +-- generated offset column too, so surviving rows keep their original parent offsets. Mutations and +-- merges squash source blocks to `min_insert_block_size_rows` (1048449) rows before calculating a +-- projection, so 1.2M rows are needed for a batch to start at a non-zero offset. The base side of each +-- check reads with optimize_use_projections = 0, otherwise its `_part_offset` comes from the same projection. +DROP TABLE IF EXISTS t_lwd_offset_compact; +CREATE TABLE t_lwd_offset_compact (a UInt32, b UInt32, + PROJECTION p (SELECT a, b, _part_offset ORDER BY b)) +ENGINE = MergeTree ORDER BY a +SETTINGS lightweight_mutation_projection_mode = 'rebuild', min_bytes_for_wide_part = '1G', + min_bytes_for_full_part_storage = 0, index_granularity = 8192, index_granularity_bytes = '10Mi', + merge_max_block_size = 8192; + +INSERT INTO t_lwd_offset_compact SELECT number, number % 13 FROM numbers(1200000) +SETTINGS max_block_size = 1200000, max_insert_block_size = 1200000, min_insert_block_size_rows = 0, min_insert_block_size_bytes = 0; + +SELECT 'offset compact storage', part_type, part_storage_type, rows FROM system.parts +WHERE database = currentDatabase() AND table = 't_lwd_offset_compact' AND active; + +DELETE FROM t_lwd_offset_compact WHERE a % 101 = 0; + +SELECT 'offset compact first delete rows', + (SELECT count() FROM t_lwd_offset_compact SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_compact' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) WHERE a % 101 = 0); +SELECT 'offset compact first delete parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_compact l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +DELETE FROM t_lwd_offset_compact WHERE a % 103 = 1; + +SELECT 'offset compact second delete rows', + (SELECT count() FROM t_lwd_offset_compact SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_compact' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) WHERE a % 101 = 0 OR a % 103 = 1); +SELECT 'offset compact second delete parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_compact l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +-- A merge rebuilds the projection from the surviving rows (MergeTask::calculateProjections). +INSERT INTO t_lwd_offset_compact SELECT number + 1200000, number % 13 FROM numbers(1000); +OPTIMIZE TABLE t_lwd_offset_compact FINAL; + +SELECT 'offset compact merged rows', + (SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_lwd_offset_compact' AND active), + (SELECT count() FROM t_lwd_offset_compact SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_compact' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) WHERE a < 1200000 AND (a % 101 = 0 OR a % 103 = 1)); +SELECT 'offset compact merged parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_compact l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_compact, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +DROP TABLE t_lwd_offset_compact; + +DROP TABLE IF EXISTS t_lwd_offset_wide; +CREATE TABLE t_lwd_offset_wide (a UInt32, b UInt32, + PROJECTION p (SELECT a, b, _part_offset ORDER BY b)) +ENGINE = MergeTree ORDER BY a +SETTINGS lightweight_mutation_projection_mode = 'rebuild', min_bytes_for_wide_part = 0, + min_bytes_for_full_part_storage = 0, index_granularity = 8192, index_granularity_bytes = '10Mi', + merge_max_block_size = 8192; + +INSERT INTO t_lwd_offset_wide SELECT number, number % 13 FROM numbers(1200000) +SETTINGS max_block_size = 1200000, max_insert_block_size = 1200000, min_insert_block_size_rows = 0, min_insert_block_size_bytes = 0; + +SELECT 'offset wide storage', part_type, part_storage_type, rows FROM system.parts +WHERE database = currentDatabase() AND table = 't_lwd_offset_wide' AND active; + +DELETE FROM t_lwd_offset_wide WHERE a % 101 = 0; + +SELECT 'offset wide first delete rows', + (SELECT count() FROM t_lwd_offset_wide SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_wide' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) WHERE a % 101 = 0); +SELECT 'offset wide first delete parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_wide l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +DELETE FROM t_lwd_offset_wide WHERE a % 103 = 1; + +SELECT 'offset wide second delete rows', + (SELECT count() FROM t_lwd_offset_wide SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_wide' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) WHERE a % 101 = 0 OR a % 103 = 1); +SELECT 'offset wide second delete parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_wide l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +-- A merge rebuilds the projection from the surviving rows (MergeTask::calculateProjections). +INSERT INTO t_lwd_offset_wide SELECT number + 1200000, number % 13 FROM numbers(1000); +OPTIMIZE TABLE t_lwd_offset_wide FINAL; + +SELECT 'offset wide merged rows', + (SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_lwd_offset_wide' AND active), + (SELECT count() FROM t_lwd_offset_wide SETTINGS optimize_use_projections = 0), + (SELECT sum(rows) FROM system.projection_parts WHERE database = currentDatabase() AND table = 't_lwd_offset_wide' AND name = 'p' AND active), + (SELECT count() FROM mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) WHERE a < 1200000 AND (a % 101 = 0 OR a % 103 = 1)); +SELECT 'offset wide merged parent-offset matches', sum(l._part_offset = r._parent_part_offset), count() +FROM t_lwd_offset_wide l JOIN mergeTreeProjection(currentDatabase(), t_lwd_offset_wide, p) r USING (a) +SETTINGS enable_analyzer = 1, optimize_use_projections = 0; + +DROP TABLE t_lwd_offset_wide; diff --git a/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.reference b/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.reference new file mode 100644 index 000000000000..77cae706c539 --- /dev/null +++ b/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.reference @@ -0,0 +1,2 @@ +1 1 601 +299 599 diff --git a/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.sql b/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.sql new file mode 100644 index 000000000000..cac2e0ba85c7 --- /dev/null +++ b/tests/queries/0_stateless/05423_deeply_nested_array_subcolumns.sql @@ -0,0 +1,17 @@ +-- Tags: no-fasttest +-- no-fasttest: `MsgPack` is not available in the fast test build + +-- Enumerating the subcolumns of a deeply nested `Array` type used to take time cubic in the nesting depth +-- (seconds of CPU for a depth of 2000 in a release build), because `SerializationArray::supportsPooling` +-- walked the whole nested chain and was called for every level of every subcolumn. +-- The input is a chain of single-element MsgPack arrays (`0x91`), which schema inference turns into a deeply nested type. + +SET input_format_msgpack_number_of_columns = 1, max_parser_depth = 100000, schema_inference_make_columns_nullable = 1; + +DESC format(MsgPack, repeat('\x91', 300) || '\x00') FORMAT Null; + +SELECT toTypeName(c1) = repeat('Array(', 300) || 'Nullable(Int64)' || repeat(')', 300), c1.size0, length(toString(c1)) +FROM format(MsgPack, repeat('\x91', 300) || '\x00'); + +SELECT countSubstrings(toTypeName(c1.size299), 'Array('), length(toString(c1.size299)) +FROM format(MsgPack, repeat('\x91', 300) || '\x00'); diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference index e5046dab0a10..e1c3ed4e18d6 100644 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.reference @@ -7,6 +7,8 @@ settings that are not a destination: allowed -- ALTER with WRITE on S3 limited by a URL filter -- ALTER with WRITE on S3 destination with WRITE on S3: allowed +after_processing = 'delete' with WRITE on S3: allowed +after_processing = 'delete' in a Replicated database with WRITE on S3: allowed empty destination without WRITE on S3: allowed -- ALTER with WRITE on S3, restricted by a row policy empty destination with a row policy: allowed @@ -26,6 +28,7 @@ table without a destination: created 0 -- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3 CREATE AS with WRITE on S3: created +after_processing = 'delete' with WRITE on S3: created materialized view with WRITE on S3: created RESTORE with WRITE on S3: restored RESTORE ON CLUSTER with WRITE on S3: restored diff --git a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh index 5474fde6a4fd..e570f2e26d06 100755 --- a/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh +++ b/tests/queries/0_stateless/05441_s3queue_move_destination_access.sh @@ -12,6 +12,7 @@ # `after_processing_move_connection_string` or `after_processing_move_container` needs `WRITE` on the `S3` (`AZURE`) # source without a URL filter, because the move writes keys built from the prefix and the source keys, not from the URI. # `ALTER` needs `SELECT` on the table too. Settings that do not choose a destination need no extra grant. +# `after_processing` = `delete`, `move` or `tag` modifies the source files, so it also needs `WRITE` on the source. CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) # shellcheck source=../shell_config.sh @@ -25,6 +26,7 @@ src="http://localhost:11111/test/${db}_move_src/" dst="http://localhost:11111/test/${db}_move_dst/" backup="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}')" backup_tmp="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_tmp')" +backup_src="Disk('backups', '05441_${CLICKHOUSE_TEST_UNIQUE_NAME}_src')" keys="after_processing_move_access_key_id = 'clickhouse', after_processing_move_secret_access_key = 'clickhouse'" attach_uuid=$($CLICKHOUSE_CLIENT -q "SELECT generateUUIDv4()") azure_connection_string="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://localhost:10000/devstoreaccount1;" @@ -33,6 +35,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; @@ -41,6 +46,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " @@ -101,6 +107,18 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " -- { serverError ACCESS_DENIED } " +# `delete`, `move` and `tag` modify the source files, so they need `WRITE` on `S3` too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = '${action}' + -- { serverError ACCESS_DENIED } + " +done +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING s3queue_after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" + echo "-- ALTER ON CLUSTER is rejected by the initiator" $CLICKHOUSE_CLIENT -q "GRANT CLUSTER ON *.* TO ${user_alter}" @@ -108,6 +126,10 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError ACCESS_DENIED } " +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" echo "-- ALTER ON CLUSTER of a table that does not exist on the initiator" @@ -142,6 +164,28 @@ $CLICKHOUSE_CLIENT --user "${user_alter}" -q " ALTER TABLE ${db}.t MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} " && echo "destination with WRITE on S3: allowed" +# `AzureQueue` also has `after_processing`, but an `S3Queue` table needs no grant on `AZURE`. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "ALTER TABLE ${db}.t MODIFY SETTING after_processing = 'keep'" +# With `ON CLUSTER` the table on another host may be an `AzureQueue`, so both grants are needed. +$CLICKHOUSE_CLIENT --user "${user_alter}" -q " + ALTER TABLE ${db}.t ON CLUSTER test_shard_localhost MODIFY SETTING after_processing = 'delete' + -- { serverError ACCESS_DENIED } +" +# In a `Replicated` database the initiator checks the same grants. +$CLICKHOUSE_CLIENT --distributed_ddl_output_mode none -q " + CREATE DATABASE ${db}_replicated ENGINE = Replicated('/test/05441_${db}', 's1', 'r1'); + CREATE TABLE ${db}_replicated.t (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_replicated'; + GRANT ALTER SETTINGS, SELECT ON ${db}_replicated.t TO ${user_alter}; +" +$CLICKHOUSE_CLIENT --user "${user_alter}" --distributed_ddl_output_mode none -q " + ALTER TABLE ${db}_replicated.t MODIFY SETTING after_processing = 'delete' +" && echo "after_processing = 'delete' in a Replicated database with WRITE on S3: allowed" +$CLICKHOUSE_CLIENT -q "DROP DATABASE ${db}_replicated SYNC" + # Resetting the destination disables the move, so it needs no grant for a destination. $CLICKHOUSE_CLIENT -q "REVOKE WRITE ON S3 FROM ${user_alter}" $CLICKHOUSE_CLIENT --user "${user_alter}" -q " @@ -180,6 +224,10 @@ $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing_move_uri = '${dst}', ${keys} -- { serverError NOT_IMPLEMENTED } " +$CLICKHOUSE_CLIENT -q " + ALTER TABLE ${db}.t_alias MODIFY SETTING after_processing = 'delete' + -- { serverError NOT_IMPLEMENTED } +" $CLICKHOUSE_CLIENT -q " ALTER TABLE ${db}.t_alias MODIFY SETTING polling_max_timeout_ms = 20000 " && echo "settings that are not a destination through an alias: allowed" @@ -205,6 +253,15 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -q " after_processing_move_connection_string = '${azure_connection_string}', after_processing_move_container = 'dst' -- { serverError ACCESS_DENIED } " +# `CREATE` with `delete`, `move` or `tag` needs `WRITE` on the source too. +for action in delete move tag; do + $CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_create (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_create', after_processing = '${action}', + after_processing_move_prefix = 'p', after_processing_tag_key = 'k', after_processing_tag_value = 'v' + -- { serverError ACCESS_DENIED } + " +done # The same CREATE without a destination, or with an empty one, needs no grant for it. $CLICKHOUSE_CLIENT --user "${user_create}" -q " @@ -317,6 +374,20 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -m -q " SELECT count() FROM system.tables WHERE is_temporary AND name = 't_tmp_backup'; " +# `RESTORE` is checked like `CREATE`: a queue with a different source cannot use an existing `keeper_path`. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE ${db}.t_src (x UInt8) ENGINE = S3Queue('${dst}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; + BACKUP TABLE ${db}.t_src TO ${backup_src} FORMAT Null; + DROP TABLE ${db}.t_src SYNC; + CREATE TABLE ${db}.t_src_other (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_src'; +" +$CLICKHOUSE_CLIENT -q " + RESTORE TABLE ${db}.t_src FROM ${backup_src} SETTINGS structure_only = 1 FORMAT Null + -- { serverError METADATA_MISMATCH } +" + echo "-- CREATE AS and CREATE MATERIALIZED VIEW with WRITE on S3" # The same queries succeed with the grant, so `WRITE` on `S3` was the only missing one. @@ -325,6 +396,10 @@ $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE TABLE ${db}.t_as AS ${db}.t SETTINGS keeper_path = '${keeper_path}_as', after_processing = 'move', after_processing_move_uri = '${dst}', ${keys} " && echo "CREATE AS with WRITE on S3: created" +$CLICKHOUSE_CLIENT --user "${user_create}" -q " + CREATE TABLE ${db}.t_delete (x UInt8) ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') + SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_delete', after_processing = 'delete' +" && echo "after_processing = 'delete' with WRITE on S3: created" $CLICKHOUSE_CLIENT --user "${user_create}" -q " CREATE MATERIALIZED VIEW ${db}.mv ENGINE = S3Queue('${src}', 'clickhouse', 'clickhouse', 'CSV') SETTINGS mode = 'unordered', keeper_path = '${keeper_path}_mv', after_processing = 'move', @@ -361,6 +436,9 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_alias SYNC; DROP TABLE IF EXISTS ${db}.t SYNC; DROP TABLE IF EXISTS ${db}.t_create SYNC; + DROP TABLE IF EXISTS ${db}.t_delete SYNC; + DROP TABLE IF EXISTS ${db}.t_src SYNC; + DROP TABLE IF EXISTS ${db}.t_src_other SYNC; DROP TABLE IF EXISTS ${db}.t_as SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster SYNC; DROP TABLE IF EXISTS ${db}.t_as_cluster_new SYNC; @@ -369,6 +447,7 @@ $CLICKHOUSE_CLIENT -q " DROP TABLE IF EXISTS ${db}.t_backup SYNC; DROP TABLE IF EXISTS ${db}.t_backup_cluster SYNC; DROP TABLE IF EXISTS ${db}.mv SYNC; + DROP DATABASE IF EXISTS ${db}_replicated SYNC; DROP ROW POLICY IF EXISTS p_${db} ON ${db}.t; DROP USER IF EXISTS ${user_alter}, ${user_create}; " diff --git a/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.reference b/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.reference new file mode 100644 index 000000000000..61e4e7b88ebf --- /dev/null +++ b/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.reference @@ -0,0 +1,37 @@ +MultiPolygon +1 MULTIPOLYGON() 0 0 0 0 0 MULTIPOLYGON() MULTIPOLYGON() +2 MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0))) 1 4 1 1 1 MULTIPOLYGON(((0 1,1 1,1 0,0 0,0 1))) MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0))) +3 MULTIPOLYGON() 0 0 0 0 0 MULTIPOLYGON() MULTIPOLYGON() +4 MULTIPOLYGON() 0 0 0 0 0 MULTIPOLYGON() MULTIPOLYGON() +5 MULTIPOLYGON(((0 0,0 2,2 2,2 0,0 0))) 4 8 1 1 1 MULTIPOLYGON(((0 1,1 1,1 0,0 0,0 1))) MULTIPOLYGON(((0 0,0 2,2 2,2 0,0 0))) +6 MULTIPOLYGON(((0 0,0 3,3 3,3 0,0 0)),((5 5,5 6,6 6,6 5,5 5))) 10 16 1 1 1 MULTIPOLYGON(((0 1,1 1,1 0,0 0,0 1))) MULTIPOLYGON(((0 0,0 3,3 3,3 0,0 0)),((5 5,5 6,6 6,6 5,5 5))) + + +MultiPolygon with empty polygons +1 MULTIPOLYGON(()) 0 +2 MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0))) 1 +3 MULTIPOLYGON((),((0 0,0 2,2 2,2 0,0 0))) 4 +4 MULTIPOLYGON() 0 +5 MULTIPOLYGON(((0 0,0 3,3 3,3 0,0 0))) 9 +Nested +[0,0,9,9,9,9] [0,0,9,9,9,9] +MultiLineString +1 MULTILINESTRING() MULTILINESTRING() +2 MULTILINESTRING((0 0,0 1)) MULTILINESTRING((0 0,0 1)) +3 MULTILINESTRING() MULTILINESTRING() +4 MULTILINESTRING() MULTILINESTRING() +5 MULTILINESTRING((0 0,0 2)) MULTILINESTRING((0 0,0 2)) +6 MULTILINESTRING((0 0,0 3),(1 1,2 2)) MULTILINESTRING((0 0,0 3),(1 1,2 2)) +Polygon +1 POLYGON() 0 0 POLYGON() +2 POLYGON((0 0,0 1,1 1,1 0,0 0)) 1 4 POLYGON((0 0,0 1,1 1,1 0,0 0)) +3 POLYGON() 0 0 POLYGON() +4 POLYGON() 0 0 POLYGON() +5 POLYGON((0 0,0 2,2 2,2 0,0 0)) 4 8 POLYGON((0 0,0 2,2 2,2 0,0 0)) +Geometry +1 MULTIPOLYGON() +2 MULTIPOLYGON(((0 0,0 1,1 1,1 0,0 0))) +3 POLYGON((0 0,0 4,4 4,4 0,0 0)) +4 MULTIPOLYGON() +5 MULTIPOLYGON(((0 0,0 2,2 2,2 0,0 0))) +6 MULTIPOLYGON(((0 0,0 3,3 3,3 0,0 0))) diff --git a/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.sql b/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.sql new file mode 100644 index 000000000000..fdf7a8e86bc0 --- /dev/null +++ b/tests/queries/0_stateless/05480_geometry_rows_after_empty_value.sql @@ -0,0 +1,70 @@ +-- Tags: no-fasttest +-- no-fasttest: h3PolygonToCells needs the h3 library + +-- Empty geometries at the start, in the middle and twice in a row must not change the result of the other rows of the block. + +SELECT 'MultiPolygon'; +SELECT n, wkt(mp), polygonAreaCartesian(mp), polygonPerimeterCartesian(mp), polygonAreaSpherical(mp) > 0, length(h3PolygonToCells(mp, 5)) > 0, + polygonsWithinCartesian(mp, [[[(-1., -1.), (-1., 10.), (10., 10.), (10., -1.), (-1., -1.)]]]), + wkt(polygonsIntersectionCartesian(mp, [[[(0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)]]])), + wkt(CAST(mp, 'Geometry')) +FROM values('n UInt8, mp MultiPolygon', + (1, []), + (2, [[[(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]]]), + (3, []), + (4, []), + (5, [[[(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]]]), + (6, [[[(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)]], [[(5, 5), (5, 6), (6, 6), (6, 5), (5, 5)]]])) +ORDER BY n; + +SELECT svg(mp) FROM values('n UInt8, mp MultiPolygon', (1, []), (2, [[[(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]]])) ORDER BY n; + +SELECT 'MultiPolygon with empty polygons'; +SELECT n, wkt(mp), polygonAreaCartesian(mp) +FROM values('n UInt8, mp MultiPolygon', + (1, [[]]), + (2, [[[(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]]]), + (3, [[], [[(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]]]), + (4, []), + (5, [[[(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)]]])) +ORDER BY n; + +SELECT 'Nested'; +SELECT groupArray(polygonAreaCartesian(mp)), groupArray(polygonAreaCartesian(polygonsIntersectionCartesian(mp, mp))) +FROM (SELECT arrayJoin([[], [], [[[(0., 0.), (0., 3.), (3., 3.), (3., 0.), (0., 0.)]]], [[[(0., 0.), (0., 3.), (3., 3.), (3., 0.), (0., 0.)]]], [[[(0., 0.), (0., 3.), (3., 3.), (3., 0.), (0., 0.)]]], [[[(0., 0.), (0., 3.), (3., 3.), (3., 0.), (0., 0.)]]]])::MultiPolygon AS mp); + +SELECT 'MultiLineString'; +SELECT n, wkt(ml), wkt(CAST(ml, 'Geometry')) +FROM values('n UInt8, ml MultiLineString', + (1, []), + (2, [[(0, 0), (0, 1)]]), + (3, []), + (4, []), + (5, [[(0, 0), (0, 2)]]), + (6, [[(0, 0), (0, 3)], [(1, 1), (2, 2)]])) +ORDER BY n; + +SELECT 'Polygon'; +SELECT n, wkt(p), polygonAreaCartesian(p), polygonPerimeterCartesian(p), wkt(CAST(p, 'Geometry')) +FROM values('n UInt8, p Polygon', + (1, []), + (2, [[(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]]), + (3, []), + (4, []), + (5, [[(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]])) +ORDER BY n; + +SELECT 'Geometry'; +SELECT n, wkt(g) +FROM +( + SELECT n, if(n = 3, CAST(p, 'Geometry'), CAST(mp, 'Geometry')) AS g + FROM values('n UInt8, p Polygon, mp MultiPolygon', + (1, [], []), + (2, [], [[[(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]]]), + (3, [[(0, 0), (0, 4), (4, 4), (4, 0), (0, 0)]], []), + (4, [], []), + (5, [], [[[(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]]]), + (6, [], [[[(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)]]])) +) +ORDER BY n; diff --git a/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference new file mode 100644 index 000000000000..39f55ad38c86 --- /dev/null +++ b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.reference @@ -0,0 +1,5 @@ +0 +5 +5 +5 +5 diff --git a/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh new file mode 100755 index 000000000000..c7e3dae2f5e5 --- /dev/null +++ b/tests/queries/0_stateless/05480_replicated_deduplication_window_cleanup_batches.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database, no-fasttest, no-shared-merge-tree +# no-replicated-database: the explicit ZooKeeper path is used as is +# no-shared-merge-tree: relies on the ZooKeeper layout of ReplicatedMergeTree + +# The cleanup thread removes the expired deduplication entries in batches. Check that +# - more expired entries than fit in one batch are all removed, +# - an expired entry with children (a leftover of previous server versions) is removed too, +# - the entries inside the window are kept, so the inserts that are still in the window are deduplicated. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +CLICKHOUSE_TEST_ZOOKEEPER_PREFIX="${CLICKHOUSE_TEST_ZOOKEEPER_PREFIX}/${CLICKHOUSE_DATABASE}" +ZK_PATH="/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_dedup_cleanup_batches" + +$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS t_dedup_cleanup_batches SYNC" +$CLICKHOUSE_CLIENT --query " + CREATE TABLE t_dedup_cleanup_batches (n UInt64) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/t_dedup_cleanup_batches', '{replica}') + ORDER BY n + SETTINGS replicated_deduplication_window = 5, cleanup_delay_period = 1, cleanup_delay_period_random_add = 0, cleanup_thread_preferred_points_per_iteration = 0" + +# Collect the expired entries first, so that the cleanup thread usually removes them in one pass. +# `SYSTEM STOP CLEANUP` does not wait for an iteration that already runs, so the results do not depend on it. +$CLICKHOUSE_CLIENT --query "SYSTEM STOP CLEANUP t_dedup_cleanup_batches" + +# The cleanup only uses the creation order of the entries, so the expired entries can be created directly: +# 250 entries are more than two batches of 100 removals. They are older than the inserts below, so they are expired. +$CLICKHOUSE_CLIENT --async_insert=0 --query " + INSERT INTO system.zookeeper (path, name, value) + SELECT '$ZK_PATH/deduplication_hashes', 'expired_' || toString(number), '' FROM numbers(250)" + +# A leftover entry with a child. +$CLICKHOUSE_CLIENT --async_insert=0 --query "INSERT INTO system.zookeeper (path, name, value) VALUES ('$ZK_PATH/deduplication_hashes', 'leftover', '')" +$CLICKHOUSE_CLIENT --async_insert=0 --query "INSERT INTO system.zookeeper (path, name, value) VALUES ('$ZK_PATH/deduplication_hashes/leftover', 'child', '')" + +# One entry per block: 5 blocks fill the window. +INSERT_SETTINGS=(--insert_keeper_fault_injection_probability=0 --max_insert_threads=1 --max_block_size=1 --min_insert_block_size_rows=1 --min_insert_block_size_bytes=0) +$CLICKHOUSE_CLIENT "${INSERT_SETTINGS[@]}" --insert_deduplication_token=recent --query "INSERT INTO t_dedup_cleanup_batches SELECT number FROM numbers(5)" + +COUNT_EXPIRED="SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes' AND (name LIKE 'expired\_%' OR name = 'leftover')" +$CLICKHOUSE_CLIENT --query "SYSTEM START CLEANUP t_dedup_cleanup_batches" + +for _ in {1..300} +do + [ "$($CLICKHOUSE_CLIENT --query "$COUNT_EXPIRED")" -eq 0 ] && break + sleep 0.2 +done + +$CLICKHOUSE_CLIENT --query "$COUNT_EXPIRED" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes'" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM t_dedup_cleanup_batches" + +# All 5 blocks are still in the window, so they are deduplicated. The insert adds no entries, so the cleanup +# thread that still runs cannot change the result. +$CLICKHOUSE_CLIENT "${INSERT_SETTINGS[@]}" --insert_deduplication_token=recent --query "INSERT INTO t_dedup_cleanup_batches SELECT number FROM numbers(5)" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM t_dedup_cleanup_batches" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.zookeeper WHERE path = '$ZK_PATH/deduplication_hashes'" + +$CLICKHOUSE_CLIENT --query "DROP TABLE t_dedup_cleanup_batches SYNC" diff --git a/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.reference b/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.reference new file mode 100644 index 000000000000..2b8b9c42c8da --- /dev/null +++ b/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.reference @@ -0,0 +1,96 @@ +2026-10-24 23:00:00 +2026-10-24 23:00:00.5 +2026-11-01 07:30:00 +2026-03-08 08:00:00 +2026-03-08 04:00:00 +2026-10-25 02:00:00 +Europe/Berlin +2026-03-29 00:00:00 2026-03-28 23:00:00 2026-03-29 00:00:00 1 +2026-03-29 00:30:00 2026-03-28 23:30:00 2026-03-29 00:30:00 1 +2026-03-29 01:00:00 2026-03-29 00:00:00 2026-03-29 01:00:00 1 +2026-03-29 01:30:00 2026-03-29 00:30:00 2026-03-29 01:30:00 1 +2026-03-29 02:00:00 2026-03-29 00:00:00 2026-03-29 01:00:00 1 +2026-03-29 02:30:00 2026-03-29 00:30:00 2026-03-29 01:30:00 1 +2026-03-29 03:00:00 2026-03-29 01:00:00 2026-03-29 03:00:00 1 +2026-03-29 03:30:00 2026-03-29 01:30:00 2026-03-29 03:30:00 1 +2026-03-29 04:00:00 2026-03-29 02:00:00 2026-03-29 04:00:00 1 +2026-03-29 04:30:00 2026-03-29 02:30:00 2026-03-29 04:30:00 1 +2026-10-25 00:00:00 2026-10-24 22:00:00 2026-10-25 00:00:00 1 +2026-10-25 00:30:00 2026-10-24 22:30:00 2026-10-25 00:30:00 1 +2026-10-25 01:00:00 2026-10-24 23:00:00 2026-10-25 01:00:00 1 +2026-10-25 01:30:00 2026-10-24 23:30:00 2026-10-25 01:30:00 1 +2026-10-25 02:00:00 2026-10-25 00:00:00 2026-10-25 02:00:00 1 +2026-10-25 02:30:00 2026-10-25 00:30:00 2026-10-25 02:30:00 1 +2026-10-25 03:00:00 2026-10-25 02:00:00 2026-10-25 03:00:00 1 +2026-10-25 03:30:00 2026-10-25 02:30:00 2026-10-25 03:30:00 1 +2026-10-25 04:00:00 2026-10-25 03:00:00 2026-10-25 04:00:00 1 +2026-10-25 04:30:00 2026-10-25 03:30:00 2026-10-25 04:30:00 1 +America/New_York +2026-03-08 00:00:00 2026-03-08 05:00:00 2026-03-08 00:00:00 1 +2026-03-08 00:30:00 2026-03-08 05:30:00 2026-03-08 00:30:00 1 +2026-03-08 01:00:00 2026-03-08 06:00:00 2026-03-08 01:00:00 1 +2026-03-08 01:30:00 2026-03-08 06:30:00 2026-03-08 01:30:00 1 +2026-03-08 02:00:00 2026-03-08 06:00:00 2026-03-08 01:00:00 1 +2026-03-08 02:30:00 2026-03-08 06:30:00 2026-03-08 01:30:00 1 +2026-03-08 03:00:00 2026-03-08 07:00:00 2026-03-08 03:00:00 1 +2026-03-08 03:30:00 2026-03-08 07:30:00 2026-03-08 03:30:00 1 +2026-03-08 04:00:00 2026-03-08 08:00:00 2026-03-08 04:00:00 1 +2026-03-08 04:30:00 2026-03-08 08:30:00 2026-03-08 04:30:00 1 +2026-03-08 05:00:00 2026-03-08 09:00:00 2026-03-08 05:00:00 1 +2026-03-08 05:30:00 2026-03-08 09:30:00 2026-03-08 05:30:00 1 +2026-03-08 06:00:00 2026-03-08 10:00:00 2026-03-08 06:00:00 1 +2026-03-08 06:30:00 2026-03-08 10:30:00 2026-03-08 06:30:00 1 +2026-03-08 07:00:00 2026-03-08 11:00:00 2026-03-08 07:00:00 1 +2026-03-08 07:30:00 2026-03-08 11:30:00 2026-03-08 07:30:00 1 +2026-11-01 00:00:00 2026-11-01 04:00:00 2026-11-01 00:00:00 1 +2026-11-01 00:30:00 2026-11-01 04:30:00 2026-11-01 00:30:00 1 +2026-11-01 01:00:00 2026-11-01 05:00:00 2026-11-01 01:00:00 1 +2026-11-01 01:30:00 2026-11-01 05:30:00 2026-11-01 01:30:00 1 +2026-11-01 02:00:00 2026-11-01 07:00:00 2026-11-01 02:00:00 1 +2026-11-01 02:30:00 2026-11-01 07:30:00 2026-11-01 02:30:00 1 +2026-11-01 03:00:00 2026-11-01 08:00:00 2026-11-01 03:00:00 1 +2026-11-01 03:30:00 2026-11-01 08:30:00 2026-11-01 03:30:00 1 +2026-11-01 04:00:00 2026-11-01 09:00:00 2026-11-01 04:00:00 1 +2026-11-01 04:30:00 2026-11-01 09:30:00 2026-11-01 04:30:00 1 +2026-11-01 05:00:00 2026-11-01 10:00:00 2026-11-01 05:00:00 1 +2026-11-01 05:30:00 2026-11-01 10:30:00 2026-11-01 05:30:00 1 +2026-11-01 06:00:00 2026-11-01 11:00:00 2026-11-01 06:00:00 1 +2026-11-01 06:30:00 2026-11-01 11:30:00 2026-11-01 06:30:00 1 +2026-11-01 07:00:00 2026-11-01 12:00:00 2026-11-01 07:00:00 1 +2026-11-01 07:30:00 2026-11-01 12:30:00 2026-11-01 07:30:00 1 +DateTime64, America/New_York +1969-10-25 23:59:59.750 1969-10-26 03:59:59.750 1 +1969-10-26 00:29:59.750 1969-10-26 04:29:59.750 1 +1969-10-26 00:59:59.750 1969-10-26 04:59:59.750 1 +1969-10-26 01:29:59.750 1969-10-26 05:29:59.750 1 +1969-10-26 01:59:59.750 1969-10-26 05:59:59.750 1 +1969-10-26 02:29:59.750 1969-10-26 07:29:59.750 1 +1969-10-26 02:59:59.750 1969-10-26 07:59:59.750 1 +1969-10-26 03:29:59.750 1969-10-26 08:29:59.750 1 +1969-10-26 03:59:59.750 1969-10-26 08:59:59.750 1 +1969-10-26 04:29:59.750 1969-10-26 09:29:59.750 1 +1969-10-26 04:59:59.750 1969-10-26 09:59:59.750 1 +1969-10-26 05:29:59.750 1969-10-26 10:29:59.750 1 +1969-10-26 05:59:59.750 1969-10-26 10:59:59.750 1 +1969-10-26 06:29:59.750 1969-10-26 11:29:59.750 1 +1969-10-26 06:59:59.750 1969-10-26 11:59:59.750 1 +1969-10-26 07:29:59.750 1969-10-26 12:29:59.750 1 +2026-03-07 23:59:59.750 2026-03-08 04:59:59.750 1 +2026-03-08 00:29:59.750 2026-03-08 05:29:59.750 1 +2026-03-08 00:59:59.750 2026-03-08 05:59:59.750 1 +2026-03-08 01:29:59.750 2026-03-08 06:29:59.750 1 +2026-03-08 01:59:59.750 2026-03-08 06:59:59.750 1 +2026-03-08 02:29:59.750 2026-03-08 06:29:59.750 1 +2026-03-08 02:59:59.750 2026-03-08 06:59:59.750 1 +2026-03-08 03:29:59.750 2026-03-08 07:29:59.750 1 +2026-03-08 03:59:59.750 2026-03-08 07:59:59.750 1 +2026-03-08 04:29:59.750 2026-03-08 08:29:59.750 1 +2026-03-08 04:59:59.750 2026-03-08 08:59:59.750 1 +2026-03-08 05:29:59.750 2026-03-08 09:29:59.750 1 +2026-03-08 05:59:59.750 2026-03-08 09:59:59.750 1 +2026-03-08 06:29:59.750 2026-03-08 10:29:59.750 1 +2026-03-08 06:59:59.750 2026-03-08 10:59:59.750 1 +2026-03-08 07:29:59.750 2026-03-08 11:29:59.750 1 +0 0 0 0 0 0 +0 0 +0 diff --git a/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.sql b/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.sql new file mode 100644 index 000000000000..8eb1858c4775 --- /dev/null +++ b/tests/queries/0_stateless/05483_to_utc_timestamp_daylight_saving_time.sql @@ -0,0 +1,55 @@ +-- `toUTCTimestamp` converts a local time to UTC as `toDateTime(s, time_zone)` does, also next to a daylight saving time change. +-- In `Europe/Berlin` 02:00-02:59 happens twice on 2026-10-25 and does not exist on 2026-03-29. +-- https://github.com/ClickHouse/ClickHouse/issues/128266 + +SET session_timezone = 'UTC'; + +SELECT toUTCTimestamp(toDateTime('2026-10-25 01:00:00'), 'Europe/Berlin'); +SELECT toUTCTimestamp(toDateTime64('2026-10-25 01:00:00.5', 1), 'Europe/Berlin'); +SELECT toUTCTimestamp(toDateTime('2026-11-01 02:30:00'), 'America/New_York'); +SELECT toUTCTimestamp(toDateTime('2026-03-08 04:00:00'), 'America/New_York'); +SELECT fromUTCTimestamp(toUTCTimestamp(toDateTime('2026-03-08 04:00:00'), 'America/New_York'), 'America/New_York'); +-- The value is read as a UTC wall clock in any session time zone. +SELECT to_utc_timestamp(toDateTime('2026-10-25 04:00:00'), 'Europe/Berlin') SETTINGS session_timezone = 'Europe/Moscow'; + +SELECT 'Europe/Berlin'; +SELECT s, toUTCTimestamp(toDateTime(s), 'Europe/Berlin') AS t, fromUTCTimestamp(t, 'Europe/Berlin'), + toUnixTimestamp(t) = toUnixTimestamp(toDateTime(s, 'Europe/Berlin')) +FROM (SELECT formatDateTime(toDateTime(d) + n * 1800, '%Y-%m-%d %H:%i:%s') AS s + FROM (SELECT arrayJoin(['2026-03-29', '2026-10-25']) AS d, arrayJoin(range(10)) AS n)) +ORDER BY s; + +-- West of UTC the hours after the change were wrong. +SELECT 'America/New_York'; +SELECT s, toUTCTimestamp(toDateTime(s), 'America/New_York') AS t, fromUTCTimestamp(t, 'America/New_York'), + toUnixTimestamp(t) = toUnixTimestamp(toDateTime(s, 'America/New_York')) +FROM (SELECT formatDateTime(toDateTime(d) + n * 1800, '%Y-%m-%d %H:%i:%s') AS s + FROM (SELECT arrayJoin(['2026-03-08', '2026-11-01']) AS d, arrayJoin(range(16)) AS n)) +ORDER BY s; + +-- DateTime64, also before 1970, with the fraction just below each half hour. +SELECT 'DateTime64, America/New_York'; +SELECT s, toUTCTimestamp(toDateTime64(s, 3), 'America/New_York') AS t, + toUnixTimestamp64Milli(t) = toUnixTimestamp64Milli(toDateTime64(s, 3, 'America/New_York')) +FROM (SELECT concat(formatDateTime(toDateTime64(d, 0) + toIntervalSecond(n * 1800 - 1), '%Y-%m-%d %H:%i:%s'), '.750') AS s + FROM (SELECT arrayJoin(['1969-10-26', '2026-03-08']) AS d, arrayJoin(range(16)) AS n)) +ORDER BY s; + +-- Every 15 minutes of 2026: the number of local times converted differently from `toDateTime(s, time_zone)`. +SELECT + countIf(toUnixTimestamp(toUTCTimestamp(w, 'Europe/Berlin')) != toUnixTimestamp(toDateTime(s, 'Europe/Berlin'))), + countIf(toUnixTimestamp(toUTCTimestamp(w, 'America/New_York')) != toUnixTimestamp(toDateTime(s, 'America/New_York'))), + countIf(toUnixTimestamp(toUTCTimestamp(w, 'Australia/Sydney')) != toUnixTimestamp(toDateTime(s, 'Australia/Sydney'))), + countIf(toUnixTimestamp(toUTCTimestamp(w, 'Australia/Lord_Howe')) != toUnixTimestamp(toDateTime(s, 'Australia/Lord_Howe'))), + countIf(toUnixTimestamp(toUTCTimestamp(w, 'America/Santiago')) != toUnixTimestamp(toDateTime(s, 'America/Santiago'))), + countIf(toUnixTimestamp(toUTCTimestamp(w, 'Africa/Casablanca')) != toUnixTimestamp(toDateTime(s, 'Africa/Casablanca'))) +FROM (SELECT toDateTime('2026-01-01 00:00:00') + number * 900 AS w, formatDateTime(w, '%Y-%m-%d %H:%i:%s') AS s FROM numbers(35040)); + +-- Outside the years 1900-2299 the conversion takes another code path and still matches `toDateTime64(s, 3, time_zone)`. +SELECT + countIf(toUnixTimestamp64Milli(toUTCTimestamp(toDateTime64(s, 3), 'Europe/Berlin')) != toUnixTimestamp64Milli(toDateTime64(s, 3, 'Europe/Berlin'))), + countIf(toUnixTimestamp64Milli(toUTCTimestamp(toDateTime64(s, 3), 'America/New_York')) != toUnixTimestamp64Milli(toDateTime64(s, 3, 'America/New_York'))) +FROM (SELECT concat(formatDateTime(toDateTime64('2300-01-01 00:00:00', 0) + toIntervalSecond(number * 900), '%Y-%m-%d %H:%i:%s'), '.750') AS s FROM numbers(35040)); +SELECT + countIf(toUnixTimestamp64Milli(toUTCTimestamp(toDateTime64(s, 3), 'America/New_York')) != toUnixTimestamp64Milli(toDateTime64(s, 3, 'America/New_York'))) +FROM (SELECT concat(formatDateTime(toDateTime64('1883-01-01 00:00:00', 0) + toIntervalSecond(number * 900), '%Y-%m-%d %H:%i:%s'), '.750') AS s FROM numbers(35040)); diff --git a/tests/queries/0_stateless/05493_handler_admin_privilege.reference b/tests/queries/0_stateless/05493_handler_admin_privilege.reference new file mode 100644 index 000000000000..7a98064c8034 --- /dev/null +++ b/tests/queries/0_stateless/05493_handler_admin_privilege.reference @@ -0,0 +1,11 @@ +--- CREATE, ALTER and DROP do not include the handler privileges --- +1 +0 +ACCESS_DENIED +ACCESS_DENIED +ACCESS_DENIED +--- HANDLER ADMIN includes all handler privileges --- +create ok +alter ok +drop ok +1 diff --git a/tests/queries/0_stateless/05493_handler_admin_privilege.sh b/tests/queries/0_stateless/05493_handler_admin_privilege.sh new file mode 100755 index 000000000000..1262b2e60b1f --- /dev/null +++ b/tests/queries/0_stateless/05493_handler_admin_privilege.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +USER_NAME="u_${CLICKHOUSE_DATABASE}" +ADMIN_HANDLER="ha_${CLICKHOUSE_DATABASE}" +USER_HANDLER="hu_${CLICKHOUSE_DATABASE}" +URL_PREFIX="/handler_admin_${CLICKHOUSE_DATABASE}" + +cleanup() { + ${CLICKHOUSE_CLIENT} -q "DROP HANDLER IF EXISTS \`${ADMIN_HANDLER}\`; DROP HANDLER IF EXISTS \`${USER_HANDLER}\`; DROP USER IF EXISTS \`${USER_NAME}\`" +} +trap cleanup EXIT +cleanup + +${CLICKHOUSE_CLIENT} -q " + CREATE USER \`${USER_NAME}\` NOT IDENTIFIED; + GRANT CREATE, ALTER, DROP ON *.* TO \`${USER_NAME}\`; + CREATE HANDLER \`${ADMIN_HANDLER}\` URL '${URL_PREFIX}/admin' AS SELECT 1" + +echo "--- CREATE, ALTER and DROP do not include the handler privileges ---" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "CHECK GRANT CREATE TABLE ON *.*" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "CHECK GRANT CREATE HANDLER ON *.*" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "CREATE HANDLER \`${USER_HANDLER}\` URL '${URL_PREFIX}/user' AS SELECT 1" 2>&1 | grep -o -m1 'ACCESS_DENIED' +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "ALTER HANDLER \`${ADMIN_HANDLER}\` AS SELECT 2" 2>&1 | grep -o -m1 'ACCESS_DENIED' +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "DROP HANDLER \`${ADMIN_HANDLER}\`" 2>&1 | grep -o -m1 'ACCESS_DENIED' + +${CLICKHOUSE_CLIENT} -q "REVOKE CREATE, ALTER, DROP ON *.* FROM \`${USER_NAME}\`; GRANT HANDLER ADMIN ON *.* TO \`${USER_NAME}\`" + +echo "--- HANDLER ADMIN includes all handler privileges ---" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "CREATE HANDLER \`${USER_HANDLER}\` URL '${URL_PREFIX}/user' AS SELECT 1" && echo "create ok" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "ALTER HANDLER \`${USER_HANDLER}\` AS SELECT 2" && echo "alter ok" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "DROP HANDLER \`${USER_HANDLER}\`" && echo "drop ok" +${CLICKHOUSE_CLIENT} --user "${USER_NAME}" -q "CHECK GRANT SHOW HANDLERS ON *.*" diff --git a/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference new file mode 100644 index 000000000000..d679bc77aff6 --- /dev/null +++ b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.reference @@ -0,0 +1,16 @@ +-- without TABLE ENGINE grants, both directions are refused +TABLE ENGINE ON ReplicatedMergeTree +TABLE ENGINE ON ReplicatedReplacingMergeTree +TABLE ENGINE ON MergeTree +-- the refused queries keep the stored definitions +mt MergeTree +rmt ReplicatedMergeTree +rpl ReplacingMergeTree +-- TABLE ENGINE ON ReplicatedMergeTree allows only the conversion to ReplicatedMergeTree +TABLE ENGINE ON ReplicatedReplacingMergeTree +TABLE ENGINE ON MergeTree +mt ReplicatedMergeTree +1 +-- TABLE ENGINE ON MergeTree allows the conversion back +mt MergeTree +1 diff --git a/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh new file mode 100755 index 000000000000..9e9189bc4cb2 --- /dev/null +++ b/tests/queries/0_stateless/05494_attach_as_replicated_requires_table_engine_grant.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-replicated-database, no-ordinary-database, no-shared-merge-tree +# no-replicated-database, no-ordinary-database: `ATTACH TABLE ... AS [NOT] REPLICATED` is supported only for `Atomic` databases. +# no-shared-merge-tree: the tables must keep the engines they are created with. + +# `ATTACH TABLE ... AS [NOT] REPLICATED` requires the `TABLE ENGINE` grant on the engine the table is converted to, +# and a refused conversion leaves the stored definition of the detached table as it was. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A table converted to `ReplicatedMergeTree` has no metadata in ZooKeeper and logs a warning when it is attached. +CLIENT="${CLICKHOUSE_CLIENT} --server_logs_file=/dev/null" +user="user_05494_${CLICKHOUSE_DATABASE}" + +cleanup() +{ + ${CLIENT} --query "DROP USER IF EXISTS ${user}" +} + +trap cleanup EXIT +cleanup + +${CLIENT} <&1 | grep -o -m1 "TABLE ENGINE ON [A-Za-z]*" +} + +echo "-- without TABLE ENGINE grants, both directions are refused" +attach_as_user_denied "ATTACH TABLE mt AS REPLICATED" +attach_as_user_denied "ATTACH TABLE rpl AS REPLICATED" +attach_as_user_denied "ATTACH TABLE rmt AS NOT REPLICATED" + +echo "-- the refused queries keep the stored definitions" +${CLIENT} <&1) + grep -o -m1 -E "ACCESS_DENIED|POSTGRESQL_CONNECTION_FAILURE|Connection refused" <<< "${output}" | head -1 +} + +as_user "SELECT dictHas('${remote_db}.t', toUInt64(1))" +as_user "SELECT dictGet('${remote_db}.t', 'value', toUInt64(1))" +as_user "SELECT dictGet(${remote_db}.t, 'value', toUInt64(1))" +as_user "SELECT naiveBayesClassifier('${remote_db}.t', 'good')" +as_user "SELECT * FROM dictionary('${remote_db}.t')" + +${CLICKHOUSE_CLIENT} -m --query " + DROP DATABASE ${remote_db}; + DROP USER ${username}; +" diff --git a/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference new file mode 100644 index 000000000000..5573d0203026 --- /dev/null +++ b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.reference @@ -0,0 +1,34 @@ +--- ON CLUSTER +CREATE TABLE cluster_db.w_1 ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_2 ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_default ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(db.d) +ACCESS_DENIED +NOT_LOADED +--- inner table of a materialized view +CREATE MATERIALIZED VIEW mv ENGINE = Dictionary(db.d) AS SELECT id, value FROM db.src +ACCESS_DENIED +NOT_LOADED +--- table function +CREATE TABLE w_function (id UInt64, value String) AS dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +0 +CREATE TABLE cluster_db.w_function ON CLUSTER test_shard_localhost (id UInt64, value String) AS dictionary('db.d') +ACCESS_DENIED +NOT_LOADED +0 +--- unqualified name, resolved by ON CLUSTER in the default database of the server +CREATE TABLE cluster_db.w_unqualified ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary('d_unqualified') +ACCESS_DENIED +NOT_LOADED +--- dictionary name given by an expression +CREATE TABLE w_expression (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d')) +ACCESS_DENIED +NOT_LOADED +CREATE TABLE cluster_db.w_expression ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d')) + +1 diff --git a/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh new file mode 100755 index 000000000000..70048b9db131 --- /dev/null +++ b/tests/queries/0_stateless/05498_dictionary_engine_access_check_distributed_ddl.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Creating a `Dictionary` table needs `dictGet` or `SELECT` on the dictionary. `ON CLUSTER` and `Replicated` databases +# execute `CREATE` again with full access, so the access must be checked before, and the dictionary must not be loaded. + +username="user_${CLICKHOUSE_TEST_UNIQUE_NAME}" +cluster_db="${CLICKHOUSE_DATABASE}_on_cluster" +# A dictionary with this name exists both in the test database and in `default`. +unqualified="d_${CLICKHOUSE_TEST_UNIQUE_NAME}" + +function cleanup() +{ + ${CLICKHOUSE_CLIENT} -m --query " + DROP DATABASE IF EXISTS ${cluster_db}; + DROP DICTIONARY IF EXISTS default.${unqualified}; + DROP USER IF EXISTS ${username}; + " +} +cleanup +trap cleanup EXIT + +${CLICKHOUSE_CLIENT} -m --query " + CREATE TABLE src (id UInt64, value String) ENGINE = Memory; + INSERT INTO src VALUES (1, 'a'); + CREATE DICTIONARY d (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DICTIONARY ${unqualified} (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DICTIONARY default.${unqualified} (id UInt64, value String) + PRIMARY KEY id + SOURCE(CLICKHOUSE(TABLE 'src' DB '${CLICKHOUSE_DATABASE}')) + LAYOUT(FLAT()) + LIFETIME(0); + CREATE DATABASE ${cluster_db}; + CREATE USER ${username} NOT IDENTIFIED; + GRANT CREATE TEMPORARY TABLE ON *.* TO ${username}; + GRANT dictGet ON ${CLICKHOUSE_DATABASE}.${unqualified} TO ${username}; + GRANT CREATE TABLE, CREATE VIEW ON ${CLICKHOUSE_DATABASE}.* TO ${username}; + GRANT CREATE TABLE ON ${cluster_db}.* TO ${username}; + GRANT SELECT ON ${CLICKHOUSE_DATABASE}.src TO ${username}; + GRANT CLUSTER ON *.* TO ${username}; + GRANT TABLE ENGINE ON Dictionary TO ${username}; +" + +function query() +{ + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" --data-binary "$1" +} + +function status() +{ + query "SELECT status FROM system.dictionaries WHERE database = currentDatabase() AND name = 'd'" +} + +function unload() +{ + query "SYSTEM UNLOAD DICTIONARY d" +} + +# Runs a query as the user, with the given extra URL parameters. +function as_user() +{ + echo "$1" | sed -e "s/${username}/user/g" -e "s/${cluster_db}/cluster_db/g" -e "s/${unqualified}/d_unqualified/g" -e "s/${CLICKHOUSE_DATABASE}/db/g" + local output + output=$(${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&user=${username}&distributed_ddl_output_mode=none${2:-}" --data-binary "$1" 2>&1) + if grep -q ACCESS_DENIED <<< "${output}" + then + echo ACCESS_DENIED + else + echo "${output}" | sed -e "s/${cluster_db}/cluster_db/g" -e "s/${CLICKHOUSE_DATABASE}/db/g" + fi +} + +echo "--- ON CLUSTER" +for version in 1 2 "" +do + unload + as_user "CREATE TABLE ${cluster_db}.w_${version:-default} ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d)" "${version:+&distributed_ddl_entry_format_version=${version}}" + status +done + +echo "--- inner table of a materialized view" +unload +as_user "CREATE MATERIALIZED VIEW mv ENGINE = Dictionary(${CLICKHOUSE_DATABASE}.d) AS SELECT id, value FROM ${CLICKHOUSE_DATABASE}.src" +status + +echo "--- table function" +unload +as_user "CREATE TABLE w_function (id UInt64, value String) AS dictionary('${CLICKHOUSE_DATABASE}.d')" +status +query "EXISTS TABLE w_function" +unload +as_user "CREATE TABLE ${cluster_db}.w_function ON CLUSTER test_shard_localhost (id UInt64, value String) AS dictionary('${CLICKHOUSE_DATABASE}.d')" "&distributed_ddl_entry_format_version=2" +status +query "EXISTS TABLE ${cluster_db}.w_function" + +echo "--- unqualified name, resolved by ON CLUSTER in the default database of the server" +query "SYSTEM UNLOAD DICTIONARY default.${unqualified}" +as_user "CREATE TABLE ${cluster_db}.w_unqualified ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary('${unqualified}')" +query "SELECT status FROM system.dictionaries WHERE database = 'default' AND name = '${unqualified}'" + +echo "--- dictionary name given by an expression" +unload +as_user "CREATE TABLE w_expression (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d'))" +status +query "GRANT dictGet ON ${CLICKHOUSE_DATABASE}.d TO ${username}" +as_user "CREATE TABLE ${cluster_db}.w_expression ON CLUSTER test_shard_localhost (id UInt64, value String) ENGINE = Dictionary(concat(currentDatabase(), '.d'))" +# The query sent to the replicas carries the checked name, so a replica does not evaluate the expression again. +query " + SELECT query LIKE '%ENGINE = Dictionary(\\'${CLICKHOUSE_DATABASE}.d\\')%' + FROM system.distributed_ddl_queue + WHERE cluster = 'test_shard_localhost' AND query LIKE '%${cluster_db}.w_expression%' + LIMIT 1" diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference new file mode 100644 index 000000000000..32cc47d3073e --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.reference @@ -0,0 +1,8 @@ +wide 1 [NULL,NULL] ['x','y'] +rows 1 ['',''] ['x','y'] +rows 2 ['c'] ['z'] +compact 1 ['',''] ['x','y'] +enum 1 ['ok','ok'] ['x','y'] +enum 2 ['other'] ['z'] +single ['',''] ['',''] 2 2 +added ['a','b'] ['x','y'] ['',''] diff --git a/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql new file mode 100644 index 000000000000..990fb36db1db --- /dev/null +++ b/tests/queries/0_stateless/05508_column_ttl_nested_subcolumn_keeps_siblings.sql @@ -0,0 +1,82 @@ +-- A column TTL on one `Nested` subcolumn resets it to arrays of defaults of the same size, +-- because its array sizes are shared with the other subcolumns, which keep their values. + +DROP TABLE IF EXISTS t_nested_ttl_wide; +DROP TABLE IF EXISTS t_nested_ttl_rows; +DROP TABLE IF EXISTS t_nested_ttl_compact; +DROP TABLE IF EXISTS t_nested_ttl_enum; +DROP TABLE IF EXISTS t_nested_ttl_single; +DROP TABLE IF EXISTS t_nested_ttl_added; + +-- A Wide part with every row expired, the type change also rewrites the subcolumn. +CREATE TABLE t_nested_ttl_wide (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_wide VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_wide MODIFY COLUMN `n.a` Array(Nullable(String)) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_wide MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'wide', id, `n.a`, `n.b` FROM t_nested_ttl_wide; + +-- Only some rows of the part are expired. +CREATE TABLE t_nested_ttl_rows (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_rows VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['c'], ['z']); +ALTER TABLE t_nested_ttl_rows MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_rows FINAL; +SELECT 'rows', id, `n.a`, `n.b` FROM t_nested_ttl_rows ORDER BY id; + +-- A Compact part stores the sizes of each subcolumn separately, but it gets the same default. +CREATE TABLE t_nested_ttl_compact (id UInt64, ts DateTime, n Nested(a String, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000; + +INSERT INTO t_nested_ttl_compact VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_compact MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY; +ALTER TABLE t_nested_ttl_compact MATERIALIZE TTL SETTINGS mutations_sync = 2; +SELECT 'compact', id, `n.a`, `n.b` FROM t_nested_ttl_compact; + +-- The default of an `Enum` element is its first value, not zero. +CREATE TABLE t_nested_ttl_enum (id UInt64, ts DateTime, n Nested(a Enum8('ok' = 1, 'other' = 2), b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_enum VALUES (1, '2020-01-01 00:00:00', ['other', 'other'], ['x', 'y']), (2, '2100-01-01 00:00:00', ['other'], ['z']); +ALTER TABLE t_nested_ttl_enum MODIFY COLUMN `n.a` Array(Enum8('ok' = 1, 'other' = 2)) TTL ts + INTERVAL 1 DAY SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_enum FINAL; +SELECT 'enum', id, `n.a`, `n.b` FROM t_nested_ttl_enum ORDER BY id; + +-- The sizes are kept when every subcolumn expires. +CREATE TABLE t_nested_ttl_single (id UInt64, ts DateTime, n Nested(a String, b String), m UInt64 MATERIALIZED length(`n.a`)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_nested_ttl_single VALUES (1, '2020-01-01 00:00:00', ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_single + MODIFY COLUMN `n.a` Array(String) TTL ts + INTERVAL 1 DAY, + MODIFY COLUMN `n.b` Array(String) TTL ts + INTERVAL 1 DAY +SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_single FINAL; +SELECT 'single', `n.a`, `n.b`, m, length(`n.a`) FROM t_nested_ttl_single; + +-- A subcolumn that no part stores gets the sizes of the other subcolumns, as in a read. +-- A vertical merge does not use the TTL transform for these columns, so it is disabled here. +CREATE TABLE t_nested_ttl_added (id UInt64, n Nested(a String, c String)) +ENGINE = MergeTree ORDER BY id +SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, enable_vertical_merge_algorithm = 0; + +INSERT INTO t_nested_ttl_added VALUES (1, ['a', 'b'], ['x', 'y']); +ALTER TABLE t_nested_ttl_added ADD COLUMN `n.d` Array(String); +ALTER TABLE t_nested_ttl_added ADD COLUMN ts DateTime DEFAULT '2020-01-01 00:00:00'; +ALTER TABLE t_nested_ttl_added MODIFY TTL ts + INTERVAL 1 DAY WHERE id = 100 SETTINGS materialize_ttl_after_modify = 0; +OPTIMIZE TABLE t_nested_ttl_added FINAL; +SELECT 'added', `n.a`, `n.c`, `n.d` FROM t_nested_ttl_added; + +DROP TABLE t_nested_ttl_wide; +DROP TABLE t_nested_ttl_rows; +DROP TABLE t_nested_ttl_compact; +DROP TABLE t_nested_ttl_enum; +DROP TABLE t_nested_ttl_single; +DROP TABLE t_nested_ttl_added; diff --git a/tests/queries/0_stateless/05564_source_grant_dot_segments.reference b/tests/queries/0_stateless/05564_source_grant_dot_segments.reference new file mode 100644 index 000000000000..136ea62c8bd2 --- /dev/null +++ b/tests/queries/0_stateless/05564_source_grant_dot_segments.reference @@ -0,0 +1,38 @@ +s3 dot segment: denied READ ON S3 +s3 escaped dot segment: denied READ ON S3 +s3 backup dot segment: denied WRITE ON S3 +s3 restore dot segment: denied READ ON S3 +0 +s3 dot segment inside the filter: denied READ ON S3 +s3 empty segment: denied READ ON S3 +s3 query wildcard: denied READ ON S3 +s3 escape without a query: not denied +azure dot segment: denied WRITE ON AZURE +azure escape: denied WRITE ON AZURE +azure scheme-like name: denied WRITE ON AZURE +file escape: denied READ ON FILE +url dot segment: denied READ ON URL +url escape: denied READ ON URL +azure archive escaped dot segments: denied WRITE ON AZURE +url glob alternative: denied READ ON URL +s3 escaped wildcard inside the filter: not denied +s3 glob against an escaped filter: denied READ ON S3 +url glob against an escaped filter: denied READ ON URL +s3 fragment: denied READ ON S3 +url fragment: denied READ ON URL +s3 glob: not denied +url glob alternatives: not denied +file: not denied +azure archive: not denied +s3 exact filter: not denied +s3 glob against an exact filter: denied READ ON S3 +s3 escaped wildcard against an exact filter: denied READ ON S3 +url failover against an exact filter: denied READ ON URL +azure glob against an exact filter: denied READ ON AZURE +url failover in the query: denied READ ON URL +url glob in the query: denied READ ON URL +file empty segment: denied READ ON FILE +azure empty segment: denied WRITE ON AZURE +url raw character against an escaped filter: denied READ ON URL +url raw comma against an escaped filter: denied READ ON URL +s3 dot segment with the whole-source grant: not denied diff --git a/tests/queries/0_stateless/05564_source_grant_dot_segments.sh b/tests/queries/0_stateless/05564_source_grant_dot_segments.sh new file mode 100755 index 000000000000..940b1d315153 --- /dev/null +++ b/tests/queries/0_stateless/05564_source_grant_dot_segments.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-replicated-database +# Tag no-fasttest: requires S3 and Azure +# Tag no-replicated-database: without enable_read_write_grants, replicated access storage drops grant filters + +# A source grant filter must only authorize the location the storage accesses: a location the +# normalization used for the check would change (dot segments, empty segments, escapes, a fragment) +# or that is expanded outside its path needs the grant on the whole source, and a glob character +# must match the filter both as written and escaped. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db=${CLICKHOUSE_DATABASE} +user="u_05564_${CLICKHOUSE_DATABASE}" +ufp=${USER_FILES_PATH%/} +s3="http://localhost:11111" +container="cont-05564-$(echo "${CLICKHOUSE_DATABASE}" | tr _ -)" +azure_key="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" + +function cleanup() +{ + ${CLICKHOUSE_CLIENT} -q "DROP USER IF EXISTS $user" +} +trap cleanup EXIT + +${CLICKHOUSE_CLIENT} -q "DROP USER IF EXISTS $user" +${CLICKHOUSE_CLIENT} --multiquery -q " +CREATE TABLE $db.t (x UInt64) ENGINE = MergeTree ORDER BY x; +INSERT INTO $db.t VALUES (1); +CREATE USER $user; +GRANT CREATE TEMPORARY TABLE ON *.* TO $user; +GRANT BACKUP, SELECT ON $db.t TO $user; +GRANT CREATE TABLE, INSERT ON $db.* TO $user; +GRANT READ ON S3('$s3/test/.*') TO $user; +GRANT WRITE ON S3('$s3/test/$db/allowed/.*') TO $user; +GRANT WRITE ON AZURE('$db/backups/.*') TO $user; +GRANT WRITE ON AZURE('$db:.*') TO $user; +GRANT READ ON FILE('$ufp/$db/allowed/.*') TO $user; +GRANT READ ON URL('$s3/test/.*') TO $user; +GRANT READ ON S3('$s3/esc/a%2A.tsv') TO $user; +GRANT READ ON URL('$s3/esc/%7Ba%2Cb%7D.tsv') TO $user; +GRANT READ ON URL('$s3/esc/a%21b.tsv') TO $user; +GRANT READ ON URL('$s3/esc/a%2Cb.tsv') TO $user; +GRANT WRITE ON AZURE('$db/arc/ok.tar') TO $user; +GRANT READ ON S3('$s3/exact/report.csv') TO $user; +GRANT READ ON URL('$s3/exact/report.csv') TO $user; +GRANT READ ON AZURE('$db/exact/report.csv') TO $user; +" + +# Prints whether the query was refused for the named grant; any other outcome is "not denied". +function check() +{ + local grant=$1 query=$2 + if ${CLICKHOUSE_CLIENT} --user "$user" -q "$query" 2>&1 | grep -q -F "necessary to have the grant $grant"; then + echo "denied $grant" + else + echo "not denied" + fi +} + +function azure() +{ + echo "AzureBlobStorage('http://localhost:10000/devstoreaccount1', '$container', '$1', 'devstoreaccount1', '$azure_key')" +} + +function azure_table() +{ + echo "azureBlobStorage('http://localhost:10000/devstoreaccount1', '$container', '$1', 'devstoreaccount1', '$azure_key', 'CSV')" +} + +s3_backup_settings="SETTINGS backup_restore_s3_retry_attempts = 0" + +echo "s3 dot segment: $(check 'READ ON S3' "SELECT * FROM s3('$s3/other/../test/a.tsv', 'TSV')")" +echo "s3 escaped dot segment: $(check 'READ ON S3' "SELECT * FROM s3('$s3/other/%2e%2e/test/a.tsv', 'TSV')")" +echo "s3 backup dot segment: $(check 'WRITE ON S3' "BACKUP TABLE $db.t TO S3('$s3/test/$db/denied/../allowed/dotdot.tar', 'clickhouse', 'clickhouse') $s3_backup_settings")" +echo "s3 restore dot segment: $(check 'READ ON S3' "RESTORE TABLE $db.t AS $db.r FROM S3('$s3/other/../test/$db/nothing', 'clickhouse', 'clickhouse') $s3_backup_settings")" +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM system.tables WHERE database = '$db' AND name = 'r'" +echo "s3 dot segment inside the filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test/sub/../a.tsv', 'TSV')")" +echo "s3 empty segment: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test//a.tsv', 'TSV')")" +echo "s3 query wildcard: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test/a.ts?', 'TSV')")" +echo "s3 escape without a query: $(check 'READ ON S3' "SELECT * FROM s3('$s3/%74est/a.tsv', 'TSV')")" +echo "azure dot segment: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "$db/other/../backups/x")")" +echo "azure escape: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "$db%2Fbackups/y")")" +echo "azure scheme-like name: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "${db^^}:x")")" +echo "file escape: $(check 'READ ON FILE' "SELECT * FROM icebergLocal('$ufp/$db%2Fallowed/t')")" +echo "url dot segment: $(check 'READ ON URL' "SELECT * FROM url('$s3/other/../test/a.tsv', 'TSV')")" +echo "url escape: $(check 'READ ON URL' "SELECT * FROM url('$s3/%74est/a.tsv', 'TSV')")" +echo "azure archive escaped dot segments: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "$db/backups/a%2F..%2F..%2Fz.tar")")" +echo "url glob alternative: $(check 'READ ON URL' "SELECT * FROM url('$s3/test/{a,..}/a.tsv', 'TSV')")" +echo "s3 escaped wildcard inside the filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test/a.ts%3F', 'TSV')")" +echo "s3 glob against an escaped filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/esc/a*.tsv', 'TSV')")" +echo "url glob against an escaped filter: $(check 'READ ON URL' "SELECT * FROM url('$s3/esc/{a,b}.tsv', 'TSV')")" +echo "s3 fragment: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test/a.tsv#x', 'TSV')")" +echo "url fragment: $(check 'READ ON URL' "SELECT * FROM url('$s3/test/a.tsv#x', 'TSV')")" +echo "s3 glob: $(check 'READ ON S3' "SELECT * FROM s3('$s3/test/$db/*.tsv', 'TSV')")" +echo "url glob alternatives: $(check 'READ ON URL' "SELECT * FROM url('$s3/test/$db/{a,b}.tsv', 'TSV')")" +echo "file: $(check 'READ ON FILE' "SELECT * FROM icebergLocal('$ufp/$db/allowed/t')")" +echo "azure archive: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "$db/arc/ok.tar")")" +echo "s3 exact filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/exact/report.csv', 'CSV')")" +echo "s3 glob against an exact filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/exact/report*csv', 'CSV')")" +echo "s3 escaped wildcard against an exact filter: $(check 'READ ON S3' "SELECT * FROM s3('$s3/exact/report%3Fcsv', 'CSV')")" +echo "url failover against an exact filter: $(check 'READ ON URL' "SELECT * FROM url('$s3/exact/report|csv', 'CSV')")" +echo "azure glob against an exact filter: $(check 'READ ON AZURE' "SELECT * FROM $(azure_table "$db/exact/report*csv")")" +echo "url failover in the query: $(check 'READ ON URL' "SELECT * FROM url('$s3/test/a.tsv?x|$s3/other/a.tsv', 'TSV')")" +echo "url glob in the query: $(check 'READ ON URL' "SELECT * FROM url('$s3/test/a.tsv?{x,y}', 'TSV')")" +echo "file empty segment: $(check 'READ ON FILE' "SELECT * FROM icebergLocal('$ufp/$db/allowed//t')")" +echo "azure empty segment: $(check 'WRITE ON AZURE' "BACKUP TABLE $db.t TO $(azure "$db/backups//z")")" +echo "url raw character against an escaped filter: $(check 'READ ON URL' "SELECT * FROM url('$s3/esc/a!b.tsv', 'TSV')")" +echo "url raw comma against an escaped filter: $(check 'READ ON URL' "SELECT * FROM url('$s3/esc/a,b.tsv', 'TSV')")" + +${CLICKHOUSE_CLIENT} -q "GRANT READ ON S3 TO $user" +echo "s3 dot segment with the whole-source grant: $(check 'READ ON S3' "SELECT * FROM s3('$s3/other/../test/a.tsv', 'TSV')")" diff --git a/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.reference b/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.reference new file mode 100644 index 000000000000..9542fa128a00 --- /dev/null +++ b/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.reference @@ -0,0 +1,22 @@ +probe_sparse.k is Sparse 1 +Const key +0 7 +1 7 +0 0 +1 0 +0 8 +1 8 +0 6 +1 6 +LowCardinality const key +0 7 +1 7 +Replicated key after ARRAY JOIN +a 0 7 +a 1 7 +c 0 0 +c 1 0 +a 0 7 +a 1 7 +Sparse key +100 501 1 diff --git a/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.sql b/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.sql new file mode 100644 index 000000000000..a07fc7bb2a50 --- /dev/null +++ b/tests/queries/0_stateless/05569_direct_join_complex_key_dictionary_non_plain_key.sql @@ -0,0 +1,65 @@ +-- Tags: no-parallel-replicas +-- DirectKeyValueJoin cannot be chosen with parallel replicas. + +DROP DICTIONARY IF EXISTS dict_direct; +DROP DICTIONARY IF EXISTS dict_cache; +DROP DICTIONARY IF EXISTS dict_direct_u64; +DROP TABLE IF EXISTS dict_source; +DROP TABLE IF EXISTS dict_source_u64; +DROP TABLE IF EXISTS probe_arr; +DROP TABLE IF EXISTS probe_sparse; + +CREATE TABLE dict_source (k String, v UInt8) ENGINE = MergeTree ORDER BY k; +INSERT INTO dict_source VALUES ('a', 7), ('b', 8); + +CREATE TABLE dict_source_u64 (k UInt64, v UInt8) ENGINE = MergeTree ORDER BY k; +INSERT INTO dict_source_u64 VALUES (0, 5), (3, 6); + +CREATE DICTIONARY dict_direct (k String, v UInt8) PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'dict_source' DB currentDatabase())) LAYOUT(COMPLEX_KEY_DIRECT()); + +-- LIFETIME 0: every lookup is a cache miss that loads keys from the source. +CREATE DICTIONARY dict_cache (k String, v UInt8) PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'dict_source' DB currentDatabase())) LIFETIME(MIN 0 MAX 0) LAYOUT(COMPLEX_KEY_CACHE(SIZE_IN_CELLS 16)); + +CREATE DICTIONARY dict_direct_u64 (k UInt64, v UInt8) PRIMARY KEY k +SOURCE(CLICKHOUSE(TABLE 'dict_source_u64' DB currentDatabase())) LAYOUT(COMPLEX_KEY_DIRECT()); + +CREATE TABLE probe_arr (k String) ENGINE = MergeTree ORDER BY tuple(); +INSERT INTO probe_arr VALUES ('a'), ('c'); + +CREATE TABLE probe_sparse (n UInt64, k UInt64) ENGINE = MergeTree ORDER BY n +SETTINGS ratio_of_defaults_for_sparse_serialization = 0.5; +INSERT INTO probe_sparse SELECT number, if(number = 3, 3, 0) FROM numbers(100); + +-- The sparse arm is only meaningful if `k` is stored as Sparse. +SELECT 'probe_sparse.k is Sparse', countIf(serialization_kind = 'Sparse') > 0 FROM system.parts_columns +WHERE database = currentDatabase() AND table = 'probe_sparse' AND column = 'k' AND active; + +SET join_algorithm = 'direct'; -- the path under test +SET join_use_nulls = 0; -- a miss prints 0 +SET enable_lazy_columns_replication = 1; -- keys after ARRAY JOIN are ColumnReplicated + +SELECT 'Const key'; +SELECT l.n, d.v FROM (SELECT number AS n, 'a' AS k FROM numbers(2)) AS l INNER JOIN dict_direct AS d ON l.k = d.k ORDER BY l.n; +SELECT l.n, d.v FROM (SELECT number AS n, 'c' AS k FROM numbers(2)) AS l LEFT JOIN dict_direct AS d ON l.k = d.k ORDER BY l.n; +SELECT l.n, d.v FROM (SELECT number AS n, 'b' AS k FROM numbers(2)) AS l INNER JOIN dict_cache AS d ON l.k = d.k ORDER BY l.n; +SELECT l.n, d.v FROM (SELECT number AS n, toUInt64(3) AS k FROM numbers(2)) AS l INNER JOIN dict_direct_u64 AS d ON l.k = d.k ORDER BY l.n; + +SELECT 'LowCardinality const key'; +SELECT l.n, d.v FROM (SELECT number AS n, toLowCardinality('a') AS k FROM numbers(2)) AS l INNER JOIN dict_direct AS d ON l.k = d.k ORDER BY l.n; + +SELECT 'Replicated key after ARRAY JOIN'; +SELECT l.k, l.x, d.v FROM (SELECT k, x FROM probe_arr ARRAY JOIN range(2) AS x) AS l LEFT JOIN dict_direct AS d ON l.k = d.k ORDER BY l.k, l.x; +SELECT l.k, l.x, d.v FROM (SELECT k, x FROM probe_arr ARRAY JOIN range(2) AS x) AS l INNER JOIN dict_cache AS d ON l.k = d.k ORDER BY l.k, l.x; + +SELECT 'Sparse key'; +SELECT count(), sum(d.v), countIf(d.v = 6) FROM probe_sparse AS l INNER JOIN dict_direct_u64 AS d ON l.k = d.k; + +DROP DICTIONARY dict_direct; +DROP DICTIONARY dict_cache; +DROP DICTIONARY dict_direct_u64; +DROP TABLE dict_source; +DROP TABLE dict_source_u64; +DROP TABLE probe_arr; +DROP TABLE probe_sparse; diff --git a/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python b/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python new file mode 100644 index 000000000000..79174b3929da --- /dev/null +++ b/tests/queries/0_stateless/05617_async_insert_native_serialization_kind_gate.python @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Regression test for post-auth type confusion in asynchronous inserts over the native TCP protocol. +# +# The sender chooses each column's serialization kind. For `INSERT ... FORMAT Native`, choosing +# `Sparse` or `Replicated` puts a `ColumnSparse` / `ColumnReplicated` in the block but keeps the +# column's declared type. With `async_insert = 1`, the block was queued unchanged. The flush used +# `insertRangeFrom` to copy it into a full column. Its `assert_cast` reinterpreted the column. +# `assert_cast` is a plain `static_cast` in release builds. +# +# Senders of these blocks need only the default kind. The server must accept only that kind at +# every nesting depth in all peer blocks: `INSERT` data, external tables and scalars. These +# scenarios send well-formed blocks, so only the kind can cause rejection. All expect +# `INCORRECT_DATA` (code 117) and a server that stays alive. An ordinary block is still inserted. +# +# The client uses the raw native protocol pinned to revision 54482 +# (`DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION`). This keeps the exchanged revision-gated +# fields fixed. + +import os +import socket +import struct +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "async insert serialization kind" + +REVISION = 54482 + +# KindStackBinarySerializationType +KIND_STACK_DEFAULT = 0 +KIND_STACK_SPARSE = 1 +KIND_STACK_REPLICATED = 4 +KIND_STACK_COMBINATION = 5 + +# Protocol::Client +CLIENT_DATA = 2 +CLIENT_SCALAR = 7 + +# Protocol::Server +SERVER_EXCEPTION = 2 +SERVER_PROGRESS = 3 +SERVER_END_OF_STREAM = 5 +SERVER_PROFILE_EVENTS = 14 + +END_OF_GRANULE_FLAG = 1 << 62 + +ROWS = 4 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") if isinstance(s, str) else s + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt(s, size=1): + res = readStrict(s, size) + val = 0 + for i in range(len(res)): + val += res[i] << (i * 8) + return val + + +def readUInt8(s): + return readUInt(s) + + +def readUInt32(s): + return readUInt(s, 4) + + +def readVarUInt(s): + x = 0 + for i in range(9): + byte = readStrict(s)[0] + x |= (byte & 0x7F) << (7 * i) + if not byte & 0x80: + return x + return x + + +def readStringBinary(s): + size = readVarUInt(s) + return readStrict(s, size).decode("utf-8") + + +def sendHello(s): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeStringBinary(CLICKHOUSE_DATABASE, ba) # database + writeStringBinary("default", ba) # user + writeStringBinary("", ba) # password + s.sendall(ba) + + +def receiveHello(s): + assert readVarUInt(s) == 0 # Hello + readStringBinary(s) # server name + readVarUInt(s) # major + readVarUInt(s) # minor + readVarUInt(s) # revision + readVarUInt(s) # parallel replicas protocol version (>= 54471) + readStringBinary(s) # timezone (>= 54058) + readStringBinary(s) # display name (>= 54372) + readVarUInt(s) # version patch (>= 54401) + readStringBinary(s) # proto_send chunked (>= 54470) + readStringBinary(s) # proto_recv chunked (>= 54470) + for _ in range(readVarUInt(s)): # password complexity rules (>= 54461) + readStringBinary(s) + readStringBinary(s) + readStrict(s, 8) # nonce, UInt64 (>= 54462) + # Server settings in STRINGS_WITH_FLAGS format: (name, flags, value)* terminated + # by an empty name (>= 54474). + while True: + if readStringBinary(s) == "": # setting name + break + readVarUInt(s) # flags + readStringBinary(s) # value + readVarUInt(s) # query plan serialization version (>= 54477) + readVarUInt(s) # cluster function protocol version (>= 54479) + + +def sendAddendum(s): + ba = bytearray() + writeStringBinary("", ba) # quota key (>= 54458) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # parallel replicas protocol version (>= 54471) + s.sendall(ba) + + +def serializeClientInfo(ba, query_id): + ba.append(1) # INITIAL_QUERY + writeStringBinary("default", ba) # initial_user + writeStringBinary(query_id, ba) # initial_query_id + writeStringBinary("127.0.0.1:9000", ba) # initial_address + ba.extend([0] * 8) # initial_query_start_time_microseconds (>= 54449) + ba.append(1) # interface = TCP + writeStringBinary("os_user", ba) + writeStringBinary("client_hostname", ba) + writeStringBinary(CLIENT_NAME, ba) + writeVarUInt(24, ba) # client major + writeVarUInt(9, ba) # client minor + writeVarUInt(REVISION, ba) # client tcp protocol version + writeStringBinary("", ba) # quota key (>= 54060) + writeVarUInt(0, ba) # distributed_depth (>= 54448) + writeVarUInt(1, ba) # client version patch (>= 54401) + ba.append(0) # opentelemetry: no trace id (>= 54442) + writeVarUInt(0, ba) # parallel replicas: collaborate_with_initiator (>= 54453) + writeVarUInt(0, ba) # parallel replicas: obsolete count + writeVarUInt(0, ba) # parallel replicas: number_of_current_replica + writeVarUInt(0, ba) # script query number (>= 54475) + writeVarUInt(0, ba) # script line number (>= 54475) + ba.append(0) # jwt: none (>= 54476) + + +def sendQuery(s, query): + ba = bytearray() + query_id = uuid.uuid4().hex + writeVarUInt(1, ba) # Query + writeStringBinary(query_id, ba) + serializeClientInfo(ba, query_id) + # Skip the slow text stack trace symbolization; readException discards the trace anyway. + # It must be a protocol setting: an inline SETTINGS clause does not reach the reply path. + writeStringBinary("calculate_text_stack_trace", ba) + writeVarUInt(1, ba) # is_important + writeStringBinary("0", ba) + writeStringBinary("", ba) # end of per-query settings + writeStringBinary("", ba) # interserver externally granted roles (>= 54472) + writeStringBinary("", ba) # interserver secret (>= 54441) + writeVarUInt(2, ba) # stage = Complete + ba.append(0) # no compression + writeStringBinary(query, ba) + writeStringBinary("", ba) # query parameters terminator (>= 54459) + s.sendall(ba) + + +def serializeBlockInfo(ba): + writeVarUInt(1, ba) # field 1 + ba.append(0) # is_overflows = false + writeVarUInt(2, ba) # field 2 + ba.extend(struct.pack("= 54480) + for _ in range(readVarUInt(s)): + readUInt32(s) + else: + raise RuntimeError("Unknown BlockInfo field {}".format(field_num)) + + +def emptyBlock(): + ba = bytearray() + writeVarUInt(2, ba) # Data + writeStringBinary("", ba) + serializeBlockInfo(ba) + writeVarUInt(0, ba) # columns + writeVarUInt(0, ba) # rows + return bytes(ba) + + +def readException(s): + code = readUInt32(s) + readStringBinary(s) # name + text = readStringBinary(s) + readStringBinary(s) # trace + readUInt8(s) # has_nested + return code, text + + +def readKindStack(s): + kind = readUInt8(s) + if kind == KIND_STACK_COMBINATION: # number of kinds and the kinds themselves + readStrict(s, readVarUInt(s)) + + +def readHeader(s): + packet_type = receiveReply(s) + if packet_type == SERVER_EXCEPTION: + code, text = readException(s) + raise RuntimeError("Unexpected exception {}: {}".format(code, text)) + assert packet_type == 1, "Expected Data (header) packet, got {}".format(packet_type) + readStringBinary(s) # external table name + readBlockInfo(s) + columns = readVarUInt(s) + rows = readVarUInt(s) + assert rows == 0, "Expected an empty header block, got {} rows".format(rows) + # Consume the per-column descriptor so the stream stays aligned. + for _ in range(columns): + readStringBinary(s) # column name + readStringBinary(s) # column type + if readUInt8(s): # has custom serialization (>= 54454) + readKindStack(s) + + +def skipProfileEvents(s): + fixed_sizes = {"DateTime": 4, "UInt64": 8, "Int64": 8} + readStringBinary(s) # external table name + readBlockInfo(s) + columns = readVarUInt(s) + rows = readVarUInt(s) + for _ in range(columns): + readStringBinary(s) # column name + column_type = readStringBinary(s) + assert readUInt8(s) == 0 # has custom serialization (>= 54454) + if column_type == "String": + for _ in range(rows): + readStringBinary(s) + elif column_type.startswith("Enum8("): + readStrict(s, rows) + else: + readStrict(s, rows * fixed_sizes[column_type]) + + +def receiveReply(s): + """Skips the reports of a running `INSERT` and returns the type of the packet that ends it.""" + while True: + packet_type = readVarUInt(s) + if packet_type == SERVER_PROFILE_EVENTS: + skipProfileEvents(s) + elif packet_type == SERVER_PROGRESS: + # read_rows, read_bytes, total_rows_to_read, total_bytes_to_read (>= 54463), + # written_rows, written_bytes (>= 54420), elapsed_ns (>= 54460) + for _ in range(7): + readVarUInt(s) + else: + return packet_type + + +def dataBlockPrefix(column_type, table_name="", packet_type=CLIENT_DATA): + """The beginning of a Data or Scalar packet with one column `x`, up to its serialization kinds.""" + ba = bytearray() + writeVarUInt(packet_type, ba) + writeStringBinary(table_name, ba) # empty for the data of an INSERT + serializeBlockInfo(ba) + writeVarUInt(1, ba) # columns + writeVarUInt(ROWS, ba) + writeStringBinary("x", ba) # column name + writeStringBinary(column_type, ba) + return ba + + +def sparseOffsets(): + """SparseOffsets substream: rows 0 and 1 are non-default, the trailing defaults close the granule.""" + ba = bytearray() + writeVarUInt(0, ba) + writeVarUInt(0, ba) + writeVarUInt((ROWS - 2) | END_OF_GRANULE_FLAG, ba) + return ba + + +def sparseBlock(table_name=""): + ba = dataBlockPrefix("UInt64", table_name) + ba.append(1) # has_custom serialization + ba.append(KIND_STACK_SPARSE) + ba.extend(sparseOffsets()) + ba.extend(struct.pack("<2Q", 42, 43)) # SparseElements substream + return bytes(ba) + + +def replicatedBlock(table_name="", packet_type=CLIENT_DATA): + num_elements = 2 + ba = dataBlockPrefix("UInt64", table_name, packet_type) + ba.append(1) # has_custom serialization + ba.append(KIND_STACK_REPLICATED) + # ReplicatedIndexes substream: row count, index type size, in-range indexes. + writeVarUInt(ROWS, ba) + ba.append(8) # sizeof(UInt64) + for i in range(ROWS): + ba.extend(struct.pack(" 12 AND id < 28 AND _block_number > 1 SETTINGS optimize_use_projections = 0; +SELECT 'range projection', count(), min(id), max(id) FROM proj_src WHERE id > 12 AND id < 28 AND _block_number > 1 SETTINGS optimize_use_projections = 1; + +-- The same rows read directly: results with and without the projection must agree. +SELECT 'no projection', id, _block_number, _block_offset FROM proj_src WHERE id IN (5, 15) ORDER BY id SETTINGS optimize_use_projections = 0; +SELECT 'projection', id, _block_number, _block_offset FROM proj_src WHERE id IN (5, 15) ORDER BY id SETTINGS optimize_use_projections = 1; +SELECT 'filter no projection', count() FROM proj_src WHERE id = 15 AND _block_number = 2 SETTINGS optimize_use_projections = 0; +SELECT 'filter projection', count() FROM proj_src WHERE id = 15 AND _block_number = 2 SETTINGS optimize_use_projections = 1; + +DROP TABLE proj_src; + +-- A projection that is not read can still prune parent parts through its indexes; those must not see synthesized values either. +DROP TABLE IF EXISTS proj_filter; + +CREATE TABLE proj_filter (id UInt64, v String, PROJECTION p (SELECT * WHERE id = 15 ORDER BY id)) +ENGINE = MergeTree ORDER BY tuple() +SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + part_minmax_index_columns = 'with_block_number_offset', + index_granularity = 4; + +INSERT INTO proj_filter SELECT number, toString(number) FROM numbers(20); + +SELECT 'offset filter no projection', count() FROM proj_filter WHERE id = 15 AND _block_offset = 15 SETTINGS optimize_use_projections = 0; +SELECT 'offset filter projection', count() FROM proj_filter WHERE id = 15 AND _block_offset = 15 SETTINGS optimize_use_projections = 1; +SELECT 'offset filter projection filtering', count() FROM proj_filter WHERE id = 15 AND _block_offset = 15 SETTINGS optimize_use_projections = 1, optimize_use_projection_filtering = 1; + +DROP TABLE proj_filter; + +-- A projection that stores the columns explicitly stays usable and returns the stored values. +DROP TABLE IF EXISTS proj_stored; + +CREATE TABLE proj_stored (id UInt64, v String, PROJECTION p (SELECT *, _block_number, _block_offset ORDER BY id)) +ENGINE = MergeTree ORDER BY tuple() +SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + allow_commit_order_projection = 1, + index_granularity = 4; + +INSERT INTO proj_stored SELECT number, toString(number) FROM numbers(10); +INSERT INTO proj_stored SELECT number + 10, toString(number) FROM numbers(10); +OPTIMIZE TABLE proj_stored FINAL; + +SELECT 'stored projection', id, _block_number, _block_offset FROM proj_stored WHERE id IN (5, 15) ORDER BY id SETTINGS force_optimize_projection_name = 'p'; + +DROP TABLE proj_stored; + +-- An implicit minmax index on `_block_number` is built only for a projection that stores the column. +DROP TABLE IF EXISTS proj_minmax_plain; +DROP TABLE IF EXISTS proj_minmax_commit_order; + +CREATE TABLE proj_minmax_plain (id UInt64, v String) +ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1, index_granularity = 4; +ALTER TABLE proj_minmax_plain ADD PROJECTION p (SELECT * ORDER BY id) WITH SETTINGS (add_minmax_index_for_block_number_column = 1); + +CREATE TABLE proj_minmax_commit_order (id UInt64, v String) +ENGINE = MergeTree ORDER BY tuple() +SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1, allow_commit_order_projection = 1, index_granularity = 4; +ALTER TABLE proj_minmax_commit_order ADD PROJECTION p INDEX * TYPE commit_order WITH SETTINGS (add_minmax_index_for_block_number_column = 1); + +INSERT INTO proj_minmax_plain SELECT number, toString(number) FROM numbers(10); +INSERT INTO proj_minmax_plain SELECT number + 10, toString(number) FROM numbers(10); +OPTIMIZE TABLE proj_minmax_plain FINAL; + +INSERT INTO proj_minmax_commit_order SELECT number, toString(number) FROM numbers(10); +INSERT INTO proj_minmax_commit_order SELECT number + 10, toString(number) FROM numbers(10); +OPTIMIZE TABLE proj_minmax_commit_order FINAL; + +SELECT 'minmax plain', count() FROM proj_minmax_plain WHERE id = 15 AND _block_number = 2; +SELECT 'minmax commit_order', count() FROM proj_minmax_commit_order WHERE id = 15 AND _block_number = 2; + +DROP TABLE proj_minmax_plain; +DROP TABLE proj_minmax_commit_order; + +-- A projection that stores only `_block_number`: it provides that column, but neither `_block_offset` nor part min-max index slots for block columns. +DROP TABLE IF EXISTS proj_partial; + +CREATE TABLE proj_partial (id UInt64, v String, PROJECTION p (SELECT *, _block_number ORDER BY id)) +ENGINE = MergeTree ORDER BY tuple() +SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + allow_commit_order_projection = 1, + part_minmax_index_columns = 'with_block_number_offset', + index_granularity = 4; + +INSERT INTO proj_partial SELECT number, toString(number) FROM numbers(10); +INSERT INTO proj_partial SELECT number + 10, toString(number) FROM numbers(10); +OPTIMIZE TABLE proj_partial FINAL; + +SELECT 'partial number read', id, _block_number FROM proj_partial WHERE id = 15 SETTINGS force_optimize_projection_name = 'p'; +SELECT 'partial number filter', count() FROM proj_partial WHERE id = 15 AND _block_number = 2; +SELECT 'partial offset filter', count() FROM proj_partial WHERE id = 15 AND _block_offset = 5; + +DROP TABLE proj_partial; + +-- A range filter on the block columns over a source whose projection stores them: the projection may be used and nothing is lost. +DROP TABLE IF EXISTS proj_stored_src; + +CREATE TABLE proj_stored_src (id UInt64, ts DateTime, v String, PROJECTION by_id (SELECT *, _block_number, _block_offset ORDER BY id)) +ENGINE = MergeTree ORDER BY ts +SETTINGS + enable_block_number_column = 1, + enable_block_offset_column = 1, + allow_commit_order_projection = 1, + part_minmax_index_columns = 'with_block_number_offset', + index_granularity = 4; + +INSERT INTO proj_stored_src SELECT number, toDateTime('2026-01-01 00:00:00') - number, toString(number) FROM numbers(10); +INSERT INTO proj_stored_src SELECT number + 10, toDateTime('2026-01-01 00:00:00') - number, toString(number) FROM numbers(10); +INSERT INTO proj_stored_src SELECT number + 20, toDateTime('2026-01-01 00:00:00') - number, toString(number) FROM numbers(10); +OPTIMIZE TABLE proj_stored_src FINAL; + +SELECT 'stored range no projection', count(), min(id), max(id) FROM proj_stored_src WHERE id > 12 AND id < 28 AND _block_number > 1 SETTINGS optimize_use_projections = 0; +SELECT 'stored range projection', count(), min(id), max(id) FROM proj_stored_src WHERE id > 12 AND id < 28 AND _block_number > 1 SETTINGS optimize_use_projections = 1; + +DROP TABLE proj_stored_src; diff --git a/tests/queries/0_stateless/05617_mongodb_format_schema_query_null_query_tree.reference b/tests/queries/0_stateless/05617_mongodb_format_schema_query_null_query_tree.reference new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/queries/0_stateless/05617_mongodb_format_schema_query_null_query_tree.sql b/tests/queries/0_stateless/05617_mongodb_format_schema_query_null_query_tree.sql new file mode 100644 index 000000000000..7e0c281027ee --- /dev/null +++ b/tests/queries/0_stateless/05617_mongodb_format_schema_query_null_query_tree.sql @@ -0,0 +1,6 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the MongoDB storage and the Protobuf format are not built in the Fast test build. + +-- The input side is used because clickhouse-client applies the output format itself, where the schema query is refused. +-- GROUP BY makes the MongoDB storage throw before any connection attempt to the dummy host. +SELECT * FROM format(Protobuf, 'x Int32', '') SETTINGS format_schema_source = 'query', format_schema_message_name = 'M', format_schema = 'SELECT toString((SELECT count() FROM mongodb(''mongodb://some-cluster:27017/db'', ''collection'', ''x Int32'') GROUP BY x))'; -- { serverError NOT_IMPLEMENTED } diff --git a/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference new file mode 100644 index 000000000000..bc8f970e4471 --- /dev/null +++ b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.reference @@ -0,0 +1,3 @@ +odbc_table_function: OK masked +query_log: OK masked +odbc_engine_insert: OK masked diff --git a/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh new file mode 100755 index 000000000000..23ccef17ba5b --- /dev/null +++ b/tests/queries/0_stateless/05617_xdbc_connection_string_masked.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Tags: no-asan, no-msan, no-fasttest, no-cpu-aarch64 +# Tag no-msan: can't pass because odbc libraries are not instrumented +# Tag no-cpu-aarch64: clickhouse-odbc is not setup for arm + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A bridge request carries the ODBC connection string in the `connection_string` parameter of its URI. +# Wherever that URI is shown, the value must be shown as [HIDDEN], as it is in the query text. + +SECRET="xdbcpw${CLICKHOUSE_TEST_UNIQUE_NAME}" +SHAPE="connection_string=[HIDDEN]" + +# Reads text from stdin: the secret must be absent and the masked parameter present, so a text that never +# carried the URI fails instead of passing. +assert_shape() { + local label="$1" secret="$2" shape="$3" text + text=$(cat) + if echo "$text" | grep -qF "$secret"; then + echo "$label: FAIL cleartext" + elif echo "$text" | grep -qF "$shape"; then + echo "$label: OK masked" + else + echo "$label: FAIL uri absent" + fi +} + +# The bridge is started on first use. +for _ in $(seq 1 10); do + ${CLICKHOUSE_CLIENT} --query "SELECT * FROM odbc('DSN=no_such_dsn', 'db', 't')" 2>&1 | grep -qF 'Received error from remote server' && break + sleep 0.1 +done + +# The bridge cannot connect to the DSN and answers with an error, which quotes the request URI. Grep that +# line: the client also echoes the submitted query, which legitimately contains what the user typed. +${CLICKHOUSE_CLIENT} --query_id "${CLICKHOUSE_TEST_UNIQUE_NAME}_tf" --query "SELECT * FROM odbc('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_table_function" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "SYSTEM FLUSH LOGS query_log" +${CLICKHOUSE_CLIENT} --query " + SELECT exception + FROM system.query_log + WHERE event_date >= yesterday() + AND current_database = currentDatabase() + AND query_id = '${CLICKHOUSE_TEST_UNIQUE_NAME}_tf' + AND type != 'QueryStart'" | assert_shape "query_log" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_odbc (a Int32) ENGINE = ODBC('DSN=no_such_dsn;PWD=${SECRET}', 'db', 't')" +${CLICKHOUSE_CLIENT} --query "INSERT INTO t_odbc VALUES (1)" 2>&1 \ + | grep -F 'Received error from remote server' | assert_shape "odbc_engine_insert" "$SECRET" "$SHAPE" + +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_odbc" diff --git a/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.reference b/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.reference new file mode 100644 index 000000000000..1d7c2d9d3d3d --- /dev/null +++ b/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.reference @@ -0,0 +1,4 @@ +3 +3 +0 +3 diff --git a/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.sql b/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.sql new file mode 100644 index 000000000000..2368ca59a2ba --- /dev/null +++ b/tests/queries/0_stateless/05618_load_outdated_parts_schedule_error.sql @@ -0,0 +1,41 @@ +-- Tags: no-shared-merge-tree, no-parallel, no-fasttest +-- no-shared-merge-tree: SharedMergeTree doesn't load inactive parts to memory after restart +-- no-parallel: SYSTEM ENABLE FAILPOINT is process-wide + +DROP TABLE IF EXISTS t_load_outdated_parts_schedule; + +-- Outdated parts must survive DETACH/ATTACH to be loaded in the background after ATTACH. +CREATE TABLE t_load_outdated_parts_schedule (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS old_parts_lifetime = 600; + +INSERT INTO t_load_outdated_parts_schedule VALUES (1); +INSERT INTO t_load_outdated_parts_schedule VALUES (2); +INSERT INTO t_load_outdated_parts_schedule VALUES (3); +OPTIMIZE TABLE t_load_outdated_parts_schedule FINAL; + +SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_load_outdated_parts_schedule' AND NOT active; + +DETACH TABLE t_load_outdated_parts_schedule; + +-- No outdated part can be handed to the loading thread pool, as when queries exhaust the global thread pool. +SYSTEM ENABLE FAILPOINT merge_tree_load_outdated_parts_schedule_error; +SYSTEM ENABLE FAILPOINT mt_pause_before_loading_outdated_part; +ATTACH TABLE t_load_outdated_parts_schedule; + +-- The first loading attempt is about to hand out a part. Re-arm the pause for the next attempt, then let this one fail. +SYSTEM WAIT FAILPOINT mt_pause_before_loading_outdated_part PAUSE; +SYSTEM ENABLE FAILPOINT mt_pause_before_loading_outdated_part; +SYSTEM NOTIFY FAILPOINT mt_pause_before_loading_outdated_part; + +-- The next attempt starts only if the failed one did not terminate the server and scheduled a retry. +SYSTEM WAIT FAILPOINT mt_pause_before_loading_outdated_part PAUSE; + +SELECT count() FROM t_load_outdated_parts_schedule; +SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_load_outdated_parts_schedule' AND NOT active; + +SYSTEM DISABLE FAILPOINT merge_tree_load_outdated_parts_schedule_error; +SYSTEM DISABLE FAILPOINT mt_pause_before_loading_outdated_part; +SYSTEM WAIT LOADING PARTS t_load_outdated_parts_schedule; + +SELECT count() FROM system.parts WHERE database = currentDatabase() AND table = 't_load_outdated_parts_schedule' AND NOT active; + +DROP TABLE t_load_outdated_parts_schedule; diff --git a/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference new file mode 100644 index 000000000000..1d5e015fb91f --- /dev/null +++ b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.reference @@ -0,0 +1,2 @@ +Sparse +1000 9500 33 diff --git a/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql new file mode 100644 index 000000000000..69a2302fc7a9 --- /dev/null +++ b/tests/queries/0_stateless/05618_materialized_cte_sparse_columns_to_shards.sql @@ -0,0 +1,25 @@ +-- A materialized CTE keeps the `Sparse` columns it has read, and the table behind it is sent to the shards +-- as an external table. A shard accepts only the default serialization in the blocks it receives. + +SET enable_materialized_cte = 1; +SET enable_analyzer = 1; + +DROP TABLE IF EXISTS t_sparse; + +CREATE TABLE t_sparse (id UInt64, x UInt64, t Tuple(a UInt64, b String)) +ENGINE = MergeTree ORDER BY id +SETTINGS ratio_of_defaults_for_sparse_serialization = 0.1; + +INSERT INTO t_sparse SELECT number, if(number % 50 = 0, number, 0), (if(number % 30 = 0, number, 0), '') FROM numbers(1000); + +SELECT serialization_kind FROM system.parts_columns +WHERE database = currentDatabase() AND table = 't_sparse' AND active AND column = 'x'; + +-- The CTE is referenced twice, otherwise it is inlined. `127.0.0.2` is not a local address: the shard is reached over the network. +WITH m AS MATERIALIZED (SELECT id, x, t FROM t_sparse) +SELECT count(), sum(m.x), countIf(m.t != (0, '')) +FROM remote('127.0.0.2', numbers(1000)) AS r +INNER JOIN m ON r.number = m.id +WHERE m.x IN (SELECT x FROM m); + +DROP TABLE t_sparse; diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference new file mode 100644 index 000000000000..d7624b276d3a --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.reference @@ -0,0 +1,6 @@ +1 t_05620 x = 1 local_directory +1 t_05620 x = 2 local_directory +1 t_05620 x = 2 memory +1 t_05620 x = 3 local_directory +denied +denied diff --git a/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh new file mode 100755 index 000000000000..4ed4ded7baf2 --- /dev/null +++ b/tests/queries/0_stateless/05620_row_policy_on_cluster_current_database.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# Tag no-replicated-database: its replicated access storage replaces the local_directory and memory storages + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="u_05620_${CLICKHOUSE_DATABASE}" +user2="u2_05620_${CLICKHOUSE_DATABASE}" +policy="p_05620_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05620 (x Int32) ENGINE = MergeTree ORDER BY x" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}, ${user2} IDENTIFIED WITH no_password" +${CLICKHOUSE_CLIENT} --query "GRANT CLUSTER ON *.* TO ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY ON ${CLICKHOUSE_DATABASE}.* TO ${user}" + +# A bare table name refers to the current database, as it does without ON CLUSTER. +on_cluster() { ${CLICKHOUSE_CLIENT} --user "${user}" --distributed_ddl_output_mode none --query "$1"; } +show() { ${CLICKHOUSE_CLIENT} --query "SELECT database = currentDatabase(), table, select_filter, storage FROM system.row_policies WHERE short_name = '${policy}'"; } + +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost IN local_directory USING x = 1 TO ALL" +show +on_cluster "ALTER ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost USING x = 2" +show +on_cluster "MOVE ROW POLICY ${policy} ON t_05620 TO memory ON CLUSTER test_shard_localhost" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# On a cluster with , the privileges are also checked on the current database. +on_cluster "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING x = 3 TO ALL" +show +on_cluster "DROP ROW POLICY ${policy} ON t_05620 ON CLUSTER test_shard_localhost" +show + +# The privileges are checked before the query is queued: on the current database, and globally for ON *. +denied() +{ + if ${CLICKHOUSE_CLIENT} --user "$1" --query "$2" 2>&1 | grep -qF "necessary to have the grant $3"; then echo denied; else echo "not denied"; fi +} +denied "${user2}" "CREATE ROW POLICY ${policy} ON t_05620 ON CLUSTER test_cluster_two_shards_different_databases USING 1 TO ALL" "CREATE ROW POLICY ON ${CLICKHOUSE_DATABASE}.t_05620" +denied "${user}" "CREATE ROW POLICY ${policy} ON * ON CLUSTER test_shard_localhost USING 1 TO ALL" "CREATE ROW POLICY ON *.*" +show + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${user2}" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05620" diff --git a/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference new file mode 100644 index 000000000000..94cd23857655 --- /dev/null +++ b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.reference @@ -0,0 +1,5 @@ +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +UNKNOWN_TYPE_OF_QUERY +0 diff --git a/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh new file mode 100755 index 000000000000..3acc1e842236 --- /dev/null +++ b/tests/queries/0_stateless/05632_async_insert_infile_rejected_before_open.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# `INSERT ... FROM INFILE` is read by the client. The server must refuse it before it opens the path, +# also for an asynchronous insert: the result must not depend on whether the file exists. + +readable="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.txt" +missing="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_missing.txt" +echo "line" > "${readable}" + +${CLICKHOUSE_CLIENT} -q "CREATE TABLE t_async_infile (line String) ENGINE = Memory" + +for wait in 0 1; do + for path in "${readable}" "${missing}"; do + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}&async_insert=1&wait_for_async_insert=${wait}" \ + --data-binary "INSERT INTO t_async_infile FROM INFILE '${path}' FORMAT LineAsString" \ + | grep -o -m1 'UNKNOWN_TYPE_OF_QUERY\|FILE_DOESNT_EXIST\|CANNOT_OPEN_FILE' || echo "accepted" + done +done + +${CLICKHOUSE_CLIENT} -q "SELECT count() FROM t_async_infile" +${CLICKHOUSE_CLIENT} -q "DROP TABLE t_async_infile" +rm -f "${readable}" diff --git a/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.reference b/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.reference new file mode 100644 index 000000000000..f59cb48c5f50 --- /dev/null +++ b/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.reference @@ -0,0 +1 @@ +1 0 diff --git a/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.sql.j2 b/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.sql.j2 new file mode 100644 index 000000000000..18fc1239b577 --- /dev/null +++ b/tests/queries/0_stateless/05632_compact_mutation_reads_in_file_order.sql.j2 @@ -0,0 +1,23 @@ +-- Tags: no-fasttest +-- no-fasttest: needs S3 + +-- Mutation reads columns in the order of `NameSet`, but a Compact part should be read in the order of the file, +-- since each backward seek out of the buffer is a new S3 request that reads the same data again. + +DROP TABLE IF EXISTS t_compact_mutation_order; + +CREATE TABLE t_compact_mutation_order (key UInt64{% for i in range(50) %}, c{{ i }} UInt64{% endfor %}) +ENGINE = MergeTree ORDER BY key +SETTINGS storage_policy = 's3_no_cache', min_bytes_for_wide_part = '10G', min_rows_for_wide_part = 1000000000, index_granularity = 8192, index_granularity_bytes = '10Mi'; + +INSERT INTO t_compact_mutation_order SELECT number{% for i in range(50) %}, rand64({{ i }}){% endfor %} FROM numbers(20000); + +ALTER TABLE t_compact_mutation_order DELETE WHERE key % 100 = 0 SETTINGS mutations_sync = 2; + +SYSTEM FLUSH LOGS part_log; + +SELECT count() > 0, countIf(part_type != 'Compact' OR ProfileEvents['ReadBufferFromS3Bytes'] >= 2 * size_in_bytes) +FROM system.part_log +WHERE event_date >= yesterday() AND database = currentDatabase() AND table = 't_compact_mutation_order' AND event_type = 'MutatePart'; + +DROP TABLE t_compact_mutation_order; diff --git a/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference new file mode 100644 index 000000000000..9337af0e7b78 --- /dev/null +++ b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.reference @@ -0,0 +1,8 @@ +-- huge positive exponent does not fit +\N \N \N +-- exponent sum out of range +\N +-- huge negative exponent rounds to zero +0 0 0 +-- ordinary exponents +1500 1.5 1000000000000000 \N diff --git a/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql new file mode 100644 index 000000000000..079a8681ece0 --- /dev/null +++ b/tests/queries/0_stateless/05632_decimal_text_extreme_exponent.sql @@ -0,0 +1,17 @@ +-- A decimal text exponent close to the `Int32` limits must not wrap around: +-- `1e2147483647` used to pass the "too big" check and read as 0. + +SELECT '-- huge positive exponent does not fit'; +SELECT toDecimal64OrNull('1e2147483647', 2), toDecimal32OrNull('1e2147483647', 0), toDecimal256OrNull('-1e2147483647', 10); +SELECT toDecimal64('1e2147483647', 2); -- { serverError ARGUMENT_OUT_OF_BOUND } +SELECT * FROM format(CSV, 'd Decimal(10, 2)', '1e2147483647'); -- { serverError ARGUMENT_OUT_OF_BOUND } + +SELECT '-- exponent sum out of range'; +SELECT toDecimal64OrNull('0.1e-2147483648', 2); +SELECT toDecimal64('0.1e-2147483648', 2); -- { serverError CANNOT_PARSE_NUMBER } + +SELECT '-- huge negative exponent rounds to zero'; +SELECT toDecimal64OrNull('1e-2147483648', 2), toDecimal64OrNull('1e-2147483647', 2), toDecimal128('-5e-2147483648', 3); + +SELECT '-- ordinary exponents'; +SELECT toDecimal64('1.5e3', 2), toDecimal64('15e-1', 2), toDecimal64('1e15', 2), toDecimal64OrNull('1e16', 2); diff --git a/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.reference b/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.reference new file mode 100644 index 000000000000..f060a3bdfeef --- /dev/null +++ b/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.reference @@ -0,0 +1,2 @@ +BAD_ARGUMENTS +BAD_ARGUMENTS diff --git a/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.sh b/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.sh new file mode 100755 index 000000000000..40fc25285f6d --- /dev/null +++ b/tests/queries/0_stateless/05638_ai_functions_insecure_endpoint_error_hides_endpoint.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Errors about the endpoint of an AI named collection do not contain the endpoint. + +INSECURE="ai_insecure_${CLICKHOUSE_DATABASE}" +MALFORMED="ai_malformed_${CLICKHOUSE_DATABASE}" + +$CLICKHOUSE_CLIENT -q " + DROP NAMED COLLECTION IF EXISTS ${INSECURE}; + DROP NAMED COLLECTION IF EXISTS ${MALFORMED}; + CREATE NAMED COLLECTION ${INSECURE} AS + provider = 'openai', endpoint = 'http://ai.example.com/v1/chat?access_token=ENDPOINT_TOKEN_SECRET', api_key = 'fake-key'; + CREATE NAMED COLLECTION ${MALFORMED} AS + provider = 'openai', endpoint = 'https://ai.example.com/ENDPOINT_TOKEN_SECRET%', api_key = 'fake-key'; +" + +for collection in "${INSECURE}" "${MALFORMED}" +do + error=$($CLICKHOUSE_CLIENT -q "SELECT aiGenerate('ping', map('credentials', '${collection}'))" 2>&1) + echo "$error" | grep -q "BAD_ARGUMENTS" && echo "BAD_ARGUMENTS" + echo "$error" | grep -q "ENDPOINT_TOKEN_SECRET" && echo "endpoint leaked" +done + +$CLICKHOUSE_CLIENT -q " + DROP NAMED COLLECTION ${INSECURE}; + DROP NAMED COLLECTION ${MALFORMED}; +" diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference new file mode 100644 index 000000000000..6f1822583bd6 --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.reference @@ -0,0 +1,13 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +memory +1 +1 +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +1 +1 +0 diff --git a/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh new file mode 100755 index 000000000000..c2526dc6f58e --- /dev/null +++ b/tests/queries/0_stateless/05770_same_name_user_in_other_storage.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A user name must not be used in more than one user directory. +# `memory` is the last user directory, so `CREATE USER` without `IN` would pick an earlier one. + +user="user_05770_${CLICKHOUSE_DATABASE}" +source_user="user_05770_source_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP USER IF EXISTS ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IDENTIFIED WITH plaintext_password BY 'p1' IN memory" + +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER ${user} IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER IF NOT EXISTS ${user}" + +# A replacement is refused if another directory holds the name, but allowed within the same directory. +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2'" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN local_directory" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT storage FROM system.users WHERE name = '${user}'" +${CLICKHOUSE_CLIENT} --user "${user}" --password p1 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --query "CREATE USER OR REPLACE ${user} IDENTIFIED WITH plaintext_password BY 'p2' IN memory" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" + +# A rename to a name held by another directory is refused, and both users remain usable. +${CLICKHOUSE_CLIENT} --query "CREATE USER ${source_user} IDENTIFIED WITH plaintext_password BY 'p3' IN local_directory" +${CLICKHOUSE_CLIENT} --query "ALTER USER ${source_user} RENAME TO ${user}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${user}', storage FROM system.users WHERE name IN ('${user}', '${source_user}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --user "${user}" --password p2 --query "SELECT currentUser() = '${user}'" +${CLICKHOUSE_CLIENT} --user "${source_user}" --password p3 --query "SELECT currentUser() = '${source_user}'" + +${CLICKHOUSE_CLIENT} --query "DROP USER ${user}, ${source_user}" +${CLICKHOUSE_CLIENT} --query "SELECT count() FROM system.users WHERE name IN ('${user}', '${source_user}')" diff --git a/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference new file mode 100644 index 000000000000..52bebd7dba71 --- /dev/null +++ b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.reference @@ -0,0 +1,4 @@ +1 +TOO_DEEP_RECURSION +TOO_DEEP_RECURSION +TOO_DEEP_RECURSION diff --git a/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh new file mode 100755 index 000000000000..660f3c111362 --- /dev/null +++ b/tests/queries/0_stateless/05773_parquet_metadata_schema_depth.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: the `ParquetMetadata` format needs Arrow, which is not built in the fast test. + +# The `ParquetMetadata` format limits the nesting depth of the Parquet schema with `max_parser_depth`, +# and always with a hard ceiling, because Arrow builds the schema tree recursively. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Writes a Parquet file without row groups, with a column nested in the given number of groups. +# It is written directly, because ClickHouse does not parse such deep types. +function write_deep_parquet() +{ + python3 -I -c ' +import struct, sys + +def varint(n): + out = b"" + while True: + b = n & 0x7f + n >>= 7 + if not n: + return out + bytes([b]) + out += bytes([b | 0x80]) + +def zigzag(n): + return varint((n << 1) ^ (n >> 63)) + +def field(delta, thrift_type): + return bytes([(delta << 4) | thrift_type]) + +I32, I64, BINARY, LIST, STRUCT = 5, 6, 8, 9, 12 + +def schema_element(name, physical_type=None, repetition=None, num_children=None): + # Field ids: 1 type, 3 repetition_type, 4 name, 5 num_children. + out = b"" + last = 0 + if physical_type is not None: + out += field(1 - last, I32) + zigzag(physical_type) + last = 1 + if repetition is not None: + out += field(3 - last, I32) + zigzag(repetition) + last = 3 + out += field(4 - last, BINARY) + varint(len(name)) + name + last = 4 + if num_children is not None: + out += field(5 - last, I32) + zigzag(num_children) + return out + b"\x00" + +def struct_list(items): + header = bytes([(len(items) << 4) | STRUCT]) if len(items) < 15 else bytes([0xf0 | STRUCT]) + varint(len(items)) + return header + b"".join(items) + +depth = int(sys.argv[1]) +schema = [schema_element(b"schema", num_children=1)] +schema += [schema_element(b"c", repetition=1, num_children=1) for _ in range(depth)] +schema += [schema_element(b"c", physical_type=1, repetition=1)] +# FileMetaData: 1 version, 2 schema, 3 num_rows, 4 row_groups. +metadata = field(1, I32) + zigzag(1) + field(1, LIST) + struct_list(schema) + field(1, I64) + zigzag(0) + field(1, LIST) + struct_list([]) + b"\x00" +sys.stdout.buffer.write(b"PAR1" + metadata + struct.pack(" "$2" +} + +file="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}.parquet" + +write_deep_parquet 100 "$file" +$CLICKHOUSE_LOCAL -q "SELECT num_columns FROM file('$file', ParquetMetadata)" +$CLICKHOUSE_LOCAL --max_parser_depth 50 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' + +# Raising `max_parser_depth` or setting it to 0 (unlimited) does not remove the hard ceiling. +write_deep_parquet 100000 "$file" +$CLICKHOUSE_LOCAL --max_parser_depth 0 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' +$CLICKHOUSE_LOCAL --max_parser_depth 1000000 -q "SELECT num_columns FROM file('$file', ParquetMetadata)" 2>&1 | grep -o -m1 'TOO_DEEP_RECURSION' + +rm -f "$file" diff --git a/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference new file mode 100644 index 000000000000..3749278cffff --- /dev/null +++ b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.reference @@ -0,0 +1 @@ +['{"a":1,"b":2}'] ['{"a":1,"b":2}'] diff --git a/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql new file mode 100644 index 000000000000..974d00da071d --- /dev/null +++ b/tests/queries/0_stateless/05780_json_aggregate_state_duplicate_paths.sql @@ -0,0 +1,39 @@ +-- A serialized value of a `JSON` column in an aggregate state (here of `groupArray`) has every path of a row once, +-- in sorted order. A repeated path must be rejected instead of producing a column with subcolumns of different sizes. + +-- The state of `groupArray` with one row: the number of paths, then the size of the path, the path, +-- the size of the value and the value (Dynamic binary: type `Int64` and the number) for every path. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '0100000000000000' || hex('b') || '0900000000000000' || '0A0200000000000000' AS path_b, + '013C' || '0200000000000000' AS header +SELECT + finalizeAggregation(CAST(unhex(header || path_a || path_b), 'AggregateFunction(groupArray, JSON)')), + finalizeAggregation(CAST(unhex(header || path_a || path_b), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); + +-- The same path twice: into a dynamic path and into shared data. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_a || path_a), 'AggregateFunction(groupArray, JSON)')); -- { serverError INCORRECT_DATA } + +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_a || path_a), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } + +-- Paths out of order in shared data. +WITH + '0100000000000000' || hex('a') || '0900000000000000' || '0A0100000000000000' AS path_a, + '0100000000000000' || hex('b') || '0900000000000000' || '0A0200000000000000' AS path_b, + '013C' || '0200000000000000' AS header +SELECT finalizeAggregation(CAST(unhex(header || path_b || path_a), 'AggregateFunction(groupArray, JSON(max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } + +-- A typed path repeated as a dynamic path or in shared data. Typed paths come first in the serialized value. +SELECT finalizeAggregation(CAST( + unhex('012a0300000000000000010000000000000001000000000000006109000000000000000a0100000000000000'), + 'AggregateFunction(groupArray, JSON(a Int64))')); -- { serverError INCORRECT_DATA } + +SELECT finalizeAggregation(CAST( + unhex('012a0300000000000000010000000000000001000000000000006109000000000000000a0100000000000000'), + 'AggregateFunction(groupArray, JSON(a Int64, max_dynamic_paths = 0))')); -- { serverError INCORRECT_DATA } diff --git a/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference b/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference new file mode 100644 index 000000000000..b82532f53e1e --- /dev/null +++ b/tests/queries/0_stateless/05791_aggregating_step_argument_types.reference @@ -0,0 +1,35 @@ +argument type differs from the input INCORRECT_DATA +argument is not in the input INCORRECT_DATA +well-formed accepted +grouping set column is a String INCORRECT_DATA +grouping set column is duplicated INCORRECT_DATA +memory-efficient grouping sets merge INCORRECT_DATA +grouping set key is repeated after the states INCORRECT_DATA +memory-bound grouping sets merge INCORRECT_DATA +well-formed grouping sets merge accepted +grouping set column without grouping sets INCORRECT_DATA +well-formed merge without grouping sets accepted +finalized column is not a state INCORRECT_DATA +finalized state is not in the input INCORRECT_DATA +finalized state is of another function INCORRECT_DATA +well-formed totals accepted +aggregate is duplicated INCORRECT_DATA +Rollup input has another column INCORRECT_DATA +Rollup state is finalized to another type INCORRECT_DATA +Rollup without final INCORRECT_DATA +well-formed Rollup accepted +Cube input has another column INCORRECT_DATA +Cube state is finalized to another type INCORRECT_DATA +Cube without final INCORRECT_DATA +well-formed Cube accepted +in-order sort description for merging is longer INCORRECT_DATA +in-order sort description for merging is not a prefix INCORRECT_DATA +in-order sort description refers to an aggregate INCORRECT_DATA +well-formed in-order accepted +TotalsHaving of a union with quantile states ILLEGAL_COLUMN +Rollup of a union with quantile states ILLEGAL_COLUMN +Cube of a union with quantile states ILLEGAL_COLUMN +TotalsHaving of a union with quantiles states accepted +Rollup of a union with quantiles states accepted +Cube of a union with quantiles states accepted +3 diff --git a/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh b/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh new file mode 100755 index 000000000000..da072d4ac4ff --- /dev/null +++ b/tests/queries/0_stateless/05791_aggregating_step_argument_types.sh @@ -0,0 +1,262 @@ +#!/usr/bin/env bash +# The aggregate functions of a deserialized `Aggregating` step are resolved from the argument types written +# in the plan, but they are executed on the input columns of the same names. A plan with other types made a +# function interpret a column of another type. `AggregatingStep::deserialize` (and the merging steps for the +# states) now check the types against the input header. The steps merging the states read the keys and then the +# states by position, so their input must have them in the order of the plan, without duplicates. +# The well-formed plans are accepted, so the refusals are specific. +# The raw protocol client is the one of 05575_filling_step_plan_deserialization.sh. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +python3 - <<'PYEOF' +import os +import socket +import struct +E = os.environ.get +HOST, PORT = E("CLICKHOUSE_HOST", "127.0.0.1"), int(E("CLICKHOUSE_PORT_TCP", "9000")) +USER, PASSWORD = E("CLICKHOUSE_USER", "default"), E("CLICKHOUSE_PASSWORD", "") +DATABASE = E("CLICKHOUSE_DATABASE", "default") +CLIENT = "aggregating step argument types" +REVISION = 54482 # pinned, so the revision-gated fields of the handshake are fixed +VERSION = 10 # DBMS_QUERY_PLAN_SERIALIZATION_VERSION of 26.8, pinned so the byte layout is fixed too +U64, STR = b"\x04", b"\x15" # BinaryTypeIndex +NUL = b"\x00" # a zero flags byte + + +def vu(x): + out = bytearray() + while True: + out.append((x & 0x7F) | (0x80 if x > 0x7F else 0)) + x >>= 7 + if not x: + return bytes(out) + +def sb(s): + return vu(len(s)) + s.encode() + +def rv(f): + x = shift = 0 + while True: + c = f.read(1)[0] + x |= (c & 0x7F) << shift + shift += 7 + if not c & 0x80: + return x + +def skip_hello(f): + assert rv(f) == 0 + for kind in "SVVVVSSVSS": # name, 4 versions, timezone, display name, patch, 2 chunked modes + rv(f) if kind == "V" else f.read(rv(f)) + for _ in range(rv(f) * 2): # password complexity rules, two strings each + f.read(rv(f)) + f.read(8) # nonce + while f.read(rv(f)): # server settings, an empty name terminates + rv(f) + f.read(rv(f)) + rv(f), rv(f) # query plan serialization and cluster function versions + +def header(columns): + return vu(len(columns)) + b"".join(sb(n) + t for n, t in columns) + +def node(step, payload, out_columns, children=(), version=VERSION, settings=()): + # The children are read before their parent: the number of children, the children, then the step. + out = vu(len(children)) + b"".join(children) + out += sb(step) + (vu(0) if version >= 19 else b"") # step name, per-step version + out += sb("") + header(out_columns) # description, header + out += vu(len(settings)) # the number of settings, then name, flags, value (a `Bool` is a `VarUInt`) + for name, value in settings: + out += sb(name) + vu(0) + vu(value) + return out + payload + +def read_nothing(columns): + return node("ReadNothing", b"", columns) + +def forge(label, payload, children=(), version=VERSION, out_columns=(), step="Aggregating", settings=()): + # One `ReadNothing` child per header of `children`. + forge_tree(label, node(step, payload, out_columns, [read_nothing(columns) for columns in children], version, settings), version) + +def forge_tree(label, root, version=VERSION): + plan = vu(version) + vu(0) + NUL + root # version, max_threads, concurrency + qid = os.urandom(16).hex() + info = (b"\x01" + sb(USER) + sb(qid) + sb("127.0.0.1:9000") + bytes(8) + b"\x01" + + sb("os_user") + sb("host") + sb(CLIENT) + vu(24) + vu(9) + vu(REVISION) + sb("") + + vu(0) + vu(1) + bytes(7)) # depth, patch, no tracing/replicas/script/jwt + with socket.socket() as s: + s.settimeout(60) + s.connect((HOST, PORT)) + f = s.makefile("rb") + s.sendall(vu(0) + sb(CLIENT) + vu(24) + vu(9) + vu(REVISION) + + sb(DATABASE) + sb(USER) + sb(PASSWORD)) + skip_hello(f) + s.sendall(sb("") + sb("notchunked") + sb("notchunked") + vu(0) # addendum + + vu(1) + sb(qid) + info + sb("") + sb("") + sb("") + + vu(7) + NUL + sb("SELECT 1") + sb("") # 7 == QueryProcessingStage::QueryPlan + + vu(13) + plan + # an empty `Data` block ends the external tables: no table name, the block info, no columns and rows + + vu(2) + sb("") + vu(1) + NUL + vu(2) + struct.pack("= 4: + code = int.from_bytes(data[position - 4:position], "little") + break + s.settimeout(1 if data.endswith(b"\x05") else 60) + names = {117: "INCORRECT_DATA", 48: "NOT_IMPLEMENTED", 44: "ILLEGAL_COLUMN"} + print(label, "accepted" if code is None else names.get(code, code)) + +FINAL = 1 +AF = b"\x25" # BinaryTypeIndex::AggregateFunction + +def state(function, argument_type): # AggregateFunction(function, argument_type), version 0 + return AF + vu(0) + sb(function) + vu(0) + vu(1) + argument_type + +def aggregating(flags, argument_type=None, keys=(), aggregates=None): + # Flags, keys, then the aggregates: name, arguments with their types, function, parameters. + # The final `vu(0)` is the number of sets of the plan. By default one aggregate `a` = any(x). + if aggregates is None: + aggregates = [("a", "x", argument_type, "any")] + out = bytes([flags]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + vu(len(aggregates)) + for name, argument, a_type, function, *parameters in aggregates: + out += sb(name) + vu(1) + sb(argument) + a_type + sb(function) + vu(len(parameters)) + b"".join(parameters) + return out + vu(0) + +X = [("x", U64)] +A = [("a", U64)] +forge("argument type differs from the input", aggregating(FINAL, STR), [X], VERSION, A) +forge("argument is not in the input", aggregating(FINAL, U64), [[("y", U64)]], VERSION, A) +forge("well-formed", aggregating(FINAL, U64), [X], VERSION, A) + +ANY_SUM = [("a", "x", U64, "any"), ("b", "x", U64, "sum")] +STATES = [("a", state("any", U64)), ("b", state("sum", U64))] +AB = [("a", U64), ("b", U64)] + +# With grouping sets, the merge splits the rows by `__grouping_set`, read as `UInt64`, and keeps its type in the output. +GROUPING_SETS = 4 +def merging_grouping_sets(keys, sets, aggregates): # flags, keys, the used keys of every set, aggregates + out = bytes([FINAL | GROUPING_SETS]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + vu(len(sets)) + for used_keys in sets: + out += vu(len(used_keys)) + b"".join(sb(k) for k in used_keys) + return out + aggregating(FINAL, aggregates=aggregates)[2:-1] + vu(0) + vu(0) # sort description, sets of the plan + +GS = merging_grouping_sets(["k"], [["k"], []], ANY_SUM[:1]) +K_STATE = [("k", U64), STATES[0]] +K_A = [("k", U64), ("a", U64)] +forge("grouping set column is a String", GS, [[("__grouping_set", STR)] + K_STATE], VERSION, + [("__grouping_set", STR)] + K_A, "MergingAggregated") +forge("grouping set column is duplicated", GS, [[("__grouping_set", U64)] * 2 + K_STATE], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated") +# The memory-efficient merge (on by default in the settings of the step) does not support grouping sets. +forge("memory-efficient grouping sets merge", GS, [[("__grouping_set", U64)] + K_STATE], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated") +# The output header and the reconstruction of the missing keys take every key from the input by name. +forge("grouping set key is repeated after the states", GS, [[("__grouping_set", U64)] + K_STATE + [("k", U64)]], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated", [("distributed_aggregation_memory_efficient", 0)]) +# The memory-bound merge (with a non-empty sort description) does not support grouping sets either. +MEMORY_BOUND = 32 +GS_SORTED = bytes([GS[0] | MEMORY_BOUND]) + GS[1:-2] + vu(1) + sb("k") + b"\x03" + vu(0) +forge("memory-bound grouping sets merge", GS_SORTED, [[("__grouping_set", U64)] + K_STATE], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated", [("distributed_aggregation_memory_efficient", 0)]) +forge("well-formed grouping sets merge", GS, [[("__grouping_set", U64)] + K_STATE], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated", [("distributed_aggregation_memory_efficient", 0)]) + +# Without grouping sets, the merge does not produce `__grouping_set`, so the input must not have it. +MERGING = bytes([FINAL]) + vu(1) + sb("k") + aggregating(FINAL, aggregates=ANY_SUM[:1])[2:-1] + vu(0) + vu(0) +forge("grouping set column without grouping sets", MERGING, [K_STATE + [("__grouping_set", U64)]], VERSION, + [("__grouping_set", U64)] + K_A, "MergingAggregated") +forge("well-formed merge without grouping sets", MERGING, [K_STATE], VERSION, K_A, "MergingAggregated") + +# `TotalsHaving` finalizes the states it finds in the input by the names of its aggregates. +def totals_having(aggregates): # flags (final), then the aggregates as for `Aggregating`, without the keys + return bytes([FINAL]) + aggregating(FINAL, aggregates=aggregates)[2:] + +forge("finalized column is not a state", totals_having(ANY_SUM[:1]), [A], VERSION, A, "TotalsHaving") +forge("finalized state is not in the input", totals_having(ANY_SUM[:1]), [[("b", state("any", U64))]], VERSION, [("b", U64)], "TotalsHaving") +forge("finalized state is of another function", totals_having(ANY_SUM[:1]), [[("a", state("sum", U64))]], VERSION, A, "TotalsHaving") +forge("well-formed totals", totals_having(ANY_SUM), [STATES], VERSION, AB, "TotalsHaving") + +# The output of an ordinary aggregation has a column for every key and aggregate, finalized by name. +forge("aggregate is duplicated", aggregating(FINAL, aggregates=[("a", "x", U64, "groupArray")] * 2), [X], VERSION, A * 2) + +# `Rollup` and `Cube` always finalize, address the whole input with a mask for the keys and the states, +# and finalize a single chunk with the functions of its columns. +F64 = b"\x03" # Field::Types::Float64 +def group_by_modifier(flags, aggregates, keys=("k",)): # aggregates: name, function, argument type, parameters + out = bytes([flags]) + vu(len(keys)) + b"".join(sb(k) for k in keys) + vu(len(aggregates)) + for name, function, a_type, parameters in aggregates: + out += sb(name) + sb(function) + vu(1) + a_type + vu(len(parameters)) + b"".join(parameters) + return out + vu(0) # the number of sets of the plan + +SUM = group_by_modifier(FINAL, [("a", "sum", U64, [])]) +K_SUM = [("k", U64), ("a", state("sum", U64))] +OUT = [("__grouping_set", U64), ("k", U64), ("a", U64)] +QUANTILES = group_by_modifier(FINAL, [("a", "quantiles", U64, [F64 + struct.pack("&1 | grep -o -m1 "ACCESS_DENIED" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${CLICKHOUSE_DATABASE}" 2>&1 | grep -o -m1 "ACCESS_DENIED" + +echo "-- with the grant" +${CLICKHOUSE_CLIENT} --query "GRANT SYSTEM SYNC DATABASE REPLICA ON ${db}.* TO ${user}" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${db}" +${CLICKHOUSE_CLIENT} --user "${user}" --query "SYSTEM SYNC DATABASE REPLICA ${CLICKHOUSE_DATABASE}" 2>&1 | grep -o -m1 "ACCESS_DENIED" diff --git a/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.reference b/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.reference new file mode 100644 index 000000000000..bc4d025d4f1a --- /dev/null +++ b/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.reference @@ -0,0 +1,3 @@ +200000 19999900000 1088890 +1 0 +1 0 diff --git a/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.sql b/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.sql new file mode 100644 index 000000000000..d02c6e5e6784 --- /dev/null +++ b/tests/queries/0_stateless/05813_encrypted_disk_prefetch_not_cancelled.sql @@ -0,0 +1,34 @@ +-- Tags: no-fasttest, no-distributed-cache +-- no-fasttest: needs MinIO. +-- no-distributed-cache: reads through the distributed cache do not use remote prefetches. + +-- Merges and queries on an encrypted remote disk must not cancel their prefetches. `ReadBufferFromEncryptedFile::prefetch` +-- used to start the inner prefetch before applying the pending seek and read range, so the first read discarded it. + +DROP TABLE IF EXISTS t_encrypted_prefetch; + +CREATE TABLE t_encrypted_prefetch (k UInt64, s String) ENGINE = MergeTree ORDER BY k +SETTINGS storage_policy = 's3_no_cache_encrypted', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0; + +INSERT INTO t_encrypted_prefetch SELECT number, toString(number) FROM numbers(100000); +INSERT INTO t_encrypted_prefetch SELECT number, toString(number) FROM numbers(100000, 100000); +OPTIMIZE TABLE t_encrypted_prefetch FINAL; + +-- Pin the randomized settings that could disable remote prefetches. With parallel replicas the reads can +-- happen in the queries on the replicas, which this query's `ProfileEvents` would not show. +SELECT count(), sum(k), sum(length(s)) FROM t_encrypted_prefetch +SETTINGS remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1, use_uncompressed_cache = 0, + use_page_cache_for_object_storage = 0, use_page_cache_for_disks_without_file_cache = 0, enable_parallel_replicas = 0, + log_comment = '05813_select'; + +SYSTEM FLUSH LOGS part_log, query_log; + +SELECT sum(ProfileEvents['RemoteFSPrefetches']) > 0, sum(ProfileEvents['RemoteFSCancelledPrefetches']) +FROM system.part_log +WHERE database = currentDatabase() AND table = 't_encrypted_prefetch' AND event_type = 'MergeParts'; + +SELECT ProfileEvents['RemoteFSPrefetches'] > 0, ProfileEvents['RemoteFSCancelledPrefetches'] +FROM system.query_log +WHERE current_database = currentDatabase() AND log_comment = '05813_select' AND type = 'QueryFinish'; + +DROP TABLE t_encrypted_prefetch; diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference new file mode 100644 index 000000000000..d669fdca1cc6 --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.reference @@ -0,0 +1,10 @@ +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +0 local_directory +1 memory +ACCESS_ENTITY_ALREADY_EXISTS +ACCESS_ENTITY_ALREADY_EXISTS +policy_05813_source local_directory +policy_05813_target memory +policy_05813_renamed local_directory +policy_05813_target memory diff --git a/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh new file mode 100755 index 000000000000..08195f41a32c --- /dev/null +++ b/tests/queries/0_stateless/05813_same_name_quota_row_policy_in_other_storage.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Tags: no-replicated-database +# no-replicated-database: that configuration replaces the user directories, so there is no `memory` storage. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A rename of a quota or a row policy with `IN` must not take a name used in another user directory. + +source_quota="quota_05813_source_${CLICKHOUSE_DATABASE}" +target_quota="quota_05813_target_${CLICKHOUSE_DATABASE}" + +${CLICKHOUSE_CLIENT} --query "DROP QUOTA IF EXISTS ${source_quota}, ${target_quota}" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${source_quota} IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE QUOTA ${target_quota} IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER QUOTA IF EXISTS ${source_quota} IN local_directory RENAME TO ${target_quota}" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT name = '${target_quota}', storage FROM system.quotas WHERE name IN ('${source_quota}', '${target_quota}') ORDER BY storage" +${CLICKHOUSE_CLIENT} --query "DROP QUOTA ${source_quota}, ${target_quota}" + +${CLICKHOUSE_CLIENT} --query "CREATE TABLE t_05813 (x UInt8) ENGINE = Memory" +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY IF EXISTS policy_05813_source, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory" +${CLICKHOUSE_CLIENT} --query "CREATE ROW POLICY policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813 IN memory" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY IF EXISTS policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_target" 2>&1 | grep -o -m1 "ACCESS_ENTITY_ALREADY_EXISTS" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +# A rename within the requested directory to a free name still works. +${CLICKHOUSE_CLIENT} --query "ALTER ROW POLICY policy_05813_source ON ${CLICKHOUSE_DATABASE}.t_05813 IN local_directory RENAME TO policy_05813_renamed" +${CLICKHOUSE_CLIENT} --query "SELECT short_name, storage FROM system.row_policies WHERE database = '${CLICKHOUSE_DATABASE}' AND table = 't_05813' ORDER BY storage" + +${CLICKHOUSE_CLIENT} --query "DROP ROW POLICY policy_05813_renamed, policy_05813_target ON ${CLICKHOUSE_DATABASE}.t_05813" +${CLICKHOUSE_CLIENT} --query "DROP TABLE t_05813" diff --git a/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference new file mode 100644 index 000000000000..e722b1cbb8b7 --- /dev/null +++ b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.reference @@ -0,0 +1,6 @@ +CREATE DICTIONARY default.d_url\n(\n `id` UInt64,\n `v` String\n)\nPRIMARY KEY id\nSOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\'))\nLIFETIME(MIN 0 MAX 0)\nLAYOUT(FLAT()) +d_endpoint SOURCE(HTTP(ENDPOINT \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_plain SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_token SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +d_url SOURCE(HTTP(URL \'[HIDDEN]\' FORMAT \'CSV\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +4 0 diff --git a/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql new file mode 100644 index 000000000000..ee9ca781bfa6 --- /dev/null +++ b/tests/queries/0_stateless/05814_http_dictionary_url_secrets_hidden.sql @@ -0,0 +1,40 @@ +-- The `url` and `endpoint` of an `HTTP` dictionary source are hidden whole in `SHOW CREATE DICTIONARY`, +-- `system.tables` and `system.query_log`. + +SET format_display_secrets_in_show_and_select = 0; + +DROP DICTIONARY IF EXISTS d_url; +DROP DICTIONARY IF EXISTS d_endpoint; +DROP DICTIONARY IF EXISTS d_plain; +DROP DICTIONARY IF EXISTS d_token; + +CREATE DICTIONARY d_url (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'http://admin:SEKRIT_PW@localhost:11111/data.csv?access_token=SEKRIT_TOKEN&x=1' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_endpoint (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(ENDPOINT 'http://admin:SEKRIT_PW@localhost:11111/data.csv?sig=SEKRIT_SIG' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_plain (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'http://localhost:11111/data.csv?x=1' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +CREATE DICTIONARY d_token (id UInt64, v String) PRIMARY KEY id +SOURCE(HTTP(URL 'https://SEKRIT_TOKEN@localhost:11111/data.csv' FORMAT 'CSV')) +LIFETIME(0) LAYOUT(FLAT()); + +SHOW CREATE DICTIONARY d_url; + +SELECT name, extract(create_table_query, 'SOURCE.*\\)\\)') +FROM system.tables WHERE database = currentDatabase() AND name IN ('d_url', 'd_endpoint', 'd_plain', 'd_token') ORDER BY name; + +SYSTEM FLUSH LOGS query_log; +SELECT count(), countIf(query LIKE concat('%', 'SEKRIT', '%')) +FROM system.query_log +WHERE current_database = currentDatabase() AND query_kind = 'Create' AND type = 'QueryFinish' AND event_date >= yesterday(); + +DROP DICTIONARY d_url; +DROP DICTIONARY d_endpoint; +DROP DICTIONARY d_plain; +DROP DICTIONARY d_token; diff --git a/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference new file mode 100644 index 000000000000..cd6458e7af8e --- /dev/null +++ b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.reference @@ -0,0 +1,2 @@ +SOURCE(MONGODB(URI \'mongodb://admin:[HIDDEN]@localhost:27017/db\' COLLECTION \'c\')) LIFETIME(MIN 0 MAX 0) LAYOUT(FLAT()) +1 0 diff --git a/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql new file mode 100644 index 000000000000..293df73d37ee --- /dev/null +++ b/tests/queries/0_stateless/05815_mongodb_dictionary_uri_password_hidden.sql @@ -0,0 +1,22 @@ +-- Tags: no-fasttest +-- no-fasttest: the MongoDB dictionary source needs USE_MONGODB + +-- The password in the `uri` of a `MongoDB` dictionary source is hidden in `system.tables` and `system.query_log`. + +SET format_display_secrets_in_show_and_select = 0; + +DROP DICTIONARY IF EXISTS d_mongo; + +CREATE DICTIONARY d_mongo (id UInt64, v String) PRIMARY KEY id +SOURCE(MONGODB(URI 'mongodb://admin:SEKRIT_PW@localhost:27017/db' COLLECTION 'c')) +LIFETIME(0) LAYOUT(FLAT()); + +SELECT extract(create_table_query, 'SOURCE.*\\)\\)') +FROM system.tables WHERE database = currentDatabase() AND name = 'd_mongo'; + +SYSTEM FLUSH LOGS query_log; +SELECT count(), countIf(query LIKE concat('%', 'SEKRIT', '%')) +FROM system.query_log +WHERE current_database = currentDatabase() AND query_kind = 'Create' AND type = 'QueryFinish' AND event_date >= yesterday(); + +DROP DICTIONARY d_mongo; diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference new file mode 100644 index 000000000000..af49df254bf0 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.reference @@ -0,0 +1,55 @@ +--- File properties are rejected in a collection created by SQL +kafka.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_certificate_location: Kafka property `ssl.certificate.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.certificate.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.ssl_crl_location: Kafka property `ssl.crl.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_keystore_location: Kafka property `ssl.keystore.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_location: Kafka property `ssl.engine.location` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_engine_id: Kafka property `ssl.engine.id` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.ssl_providers: Kafka property `ssl.providers` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.https_ca_location: Kafka property `https.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `https.ca.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_kerberos_keytab: Kafka property `sasl.kerberos.keytab` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_kerberos_kinit_cmd: Kafka property `sasl.kerberos.kinit.cmd` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_file: Kafka property `sasl.oauthbearer.assertion.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_private_key_file: Kafka property `sasl.oauthbearer.assertion.private.key.file` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `sasl.oauthbearer.assertion.private.key.pem` instead. (BAD_ARGUMENTS) +kafka.sasl_oauthbearer_assertion_jwt_template_file: Kafka property `sasl.oauthbearer.assertion.jwt.template.file` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.plugin_library_paths: Kafka property `plugin.library.paths` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Unlisted properties are server-local by default +kafka.future_option: Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.future.fetch_min_bytes: Kafka property `future.fetch.min.bytes` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +--- Other spellings and sections +kafka.ssl.key.location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.topic.offset.store.path: Kafka property `topic.offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location: Kafka property `ssl.key.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.key.pem` instead. (BAD_ARGUMENTS) +kafka.producer.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +kafka.kafka_topic.offset_store_path: Kafka property `offset.store.path` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +kafka.kafka_topic.ssl_ca_location: Kafka property `ssl.ca.location` can only be specified in a named collection defined in the server configuration file. Pass the contents of the file in the property `ssl.ca.pem` instead. (BAD_ARGUMENTS) +--- A null character in the name of a property +kafka.ssl_key_location\0suffix: Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +kafka.consumer.ssl_key_location\0: Kafka property name `kafka.consumer.ssl_key_location\0` contains a null character. (BAD_ARGUMENTS) +kafka.client_rack\0suffix: Kafka property name `kafka.client_rack\0suffix` contains a null character. (BAD_ARGUMENTS) +--- The contents of the file are accepted, and also the value that is not a path +kafka.ssl_ca_location: OK +kafka.ssl_key_pem: OK +kafka.consumer.fetch.min.bytes: OK +--- A collection from the server configuration file is accepted +OK +--- Consumers are created for the accepted properties +Consumer set property fetch.min.bytes:456 +kafka_config_table: OK 0 +kafka_pem_table: OK 0 +kafka_probe_table: OK 0 +--- A property that is added after the table is created +kafka.ssl_key_pem: OK +kafka.future_option: +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +Kafka property `future.option` can only be specified in a named collection defined in the server configuration file. (BAD_ARGUMENTS) +OK +kafka.ssl_key_pem: OK +kafka.ssl_key_location\0suffix: +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +Kafka property name `kafka.ssl_key_location\0suffix` contains a null character. (BAD_ARGUMENTS) +OK diff --git a/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh new file mode 100755 index 000000000000..b1adaaa9e2d6 --- /dev/null +++ b/tests/queries/0_stateless/05816_kafka_server_local_file_properties.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +# Tags: no-fasttest, no-replicated-database +# no-fasttest: the Kafka engine is not built in fasttest +# no-replicated-database: named collections created by SQL are not replicated + +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The `kafka.*` keys of a named collection are forwarded to librdkafka. Some librdkafka properties refer to +# the filesystem of the server: librdkafka reads, creates, loads or runs the file with the privileges of the server. +# `CREATE NAMED COLLECTION` does not require the privileges to access the files of the server, thus these +# properties are accepted only from a named collection that is defined in the server configuration file. +# No broker is needed: `CREATE TABLE` does not connect, and the configuration of a consumer or a producer +# is checked before the connection. + +collection="${CLICKHOUSE_TEST_UNIQUE_NAME}" +required_keys="kafka_broker_list = '127.0.0.1:1', kafka_topic_list = 'topic', kafka_group_name = 'group', kafka_format = 'JSONEachRow'" +table_settings="SETTINGS kafka_poll_timeout_ms = 100, kafka_flush_interval_ms = 100" +all_collections=() +all_tables=(kafka_table kafka_probe_table kafka_pem_table kafka_config_table kafka_scoped_table kafka_altered_table kafka_altered_null_table) + +function cleanup() +{ + local queries="" + for name in "${all_tables[@]}" + do + queries+=" DROP TABLE IF EXISTS ${name};" + done + for name in "${all_collections[@]}" + do + queries+=" DROP NAMED COLLECTION IF EXISTS ${name};" + done + $CLICKHOUSE_CLIENT -q "$queries" +} +trap cleanup EXIT + +# Prints `OK` and the result of the queries, or the message of the error about the Kafka property. +function run() +{ + local output + local message + if output=$($CLICKHOUSE_CLIENT -q "$1" 2>&1) + then + echo "OK${output:+ $output}" + else + message=$(grep -o 'Kafka property .*(BAD_ARGUMENTS)' <<< "$output" | sed 's/: While executing [A-Za-z]*\././' | head -1) + echo "${message:-$output}" + fi +} + +# Creates a named collection with one extended property and then a table that uses it. +function create_table() +{ + local key="$1" + local value="$2" + local table="${3:-kafka_table}" + local name="${collection}_${#all_collections[@]}" + all_collections+=("$name") + + echo "${key}: $(run " + CREATE NAMED COLLECTION ${name} AS ${required_keys}, \`${key}\` = '${value}'; + CREATE TABLE ${table} (x UInt64) ENGINE = Kafka(${name}) ${table_settings};")" +} + +# Creates a table with an accepted named collection, and then adds a property to the collection. +function alter_collection_of_existing_table() +{ + local key="$1" + local table="$2" + + create_table 'kafka.ssl_key_pem' 'contents of the file' "$table" + $CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET \`${key}\` = '/etc/passwd'" + echo "${key}:" + run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1" + run "INSERT INTO ${table} VALUES (1)" + # A table that is read back from its metadata is checked in the same way as a new table. + $CLICKHOUSE_CLIENT -q "DETACH TABLE ${table}" + run "ATTACH TABLE ${table}" + # The table is attached again when the collection does not have the property. + # `ALTER NAMED COLLECTION ... DELETE` is not used: the formatted query cannot be parsed back if the key has a dot. + # The collection is created again instead: the detached table does not prevent `DROP NAMED COLLECTION`. + $CLICKHOUSE_CLIENT -q " + DROP NAMED COLLECTION ${all_collections[-1]}; + CREATE NAMED COLLECTION ${all_collections[-1]} AS ${required_keys};" + run "ATTACH TABLE ${table}" +} + +echo '--- File properties are rejected in a collection created by SQL' +for key in \ + ssl_key_location ssl_certificate_location ssl_ca_location ssl_crl_location ssl_keystore_location \ + ssl_engine_location ssl_engine_id ssl_providers https_ca_location \ + sasl_kerberos_keytab sasl_kerberos_kinit_cmd \ + sasl_oauthbearer_assertion_file sasl_oauthbearer_assertion_private_key_file sasl_oauthbearer_assertion_jwt_template_file \ + plugin_library_paths offset_store_path +do + create_table "kafka.${key}" '/etc/passwd' +done + +echo '--- Unlisted properties are server-local by default' +create_table 'kafka.future_option' '1' +create_table 'kafka.consumer.future.fetch_min_bytes' '1' + +echo '--- Other spellings and sections' +create_table 'kafka.ssl.key.location' '/etc/passwd' +create_table 'kafka.topic.offset.store.path' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location' '/etc/passwd' +create_table 'kafka.producer.ssl_ca_location' '/etc/passwd' +create_table 'kafka.kafka_topic.offset_store_path' '/etc/passwd' +create_table 'kafka.kafka_topic.ssl_ca_location' '' + +echo '--- A null character in the name of a property' +# librdkafka gets the name as a C string, thus it uses only the part before the null character: +# without the check, the first key sets `ssl.key.location`. +create_table 'kafka.ssl_key_location\0suffix' '/etc/passwd' +create_table 'kafka.consumer.ssl_key_location\0' '/etc/passwd' +create_table 'kafka.client_rack\0suffix' 'rack' + +echo '--- The contents of the file are accepted, and also the value that is not a path' +create_table 'kafka.ssl_ca_location' 'probe' kafka_probe_table +create_table 'kafka.ssl_key_pem' 'contents of the file' kafka_pem_table +create_table 'kafka.consumer.fetch.min.bytes' '123' kafka_scoped_table +$CLICKHOUSE_CLIENT -q "ALTER NAMED COLLECTION ${all_collections[-1]} SET + \`kafka.consumer.kafka_topic.name\` = 'topic', \`kafka.consumer.kafka_topic.fetch_min_bytes\` = '456'" + +echo '--- A collection from the server configuration file is accepted' +run "CREATE TABLE kafka_config_table (x UInt64) ENGINE = Kafka(kafka_config_file_paths) ${table_settings}" + +echo '--- Consumers are created for the accepted properties' +# Each consumer waits for the assignment of partitions for 15 seconds, thus the tables are read at the same time. +{ + for table in kafka_probe_table kafka_pem_table kafka_config_table + do + echo "${table}: $(run "SELECT count() FROM ${table} SETTINGS stream_like_engine_allow_direct_select = 1")" & + done + $CLICKHOUSE_CLIENT --send_logs_level=trace -q 'SELECT count() FROM kafka_scoped_table SETTINGS stream_like_engine_allow_direct_select = 1' 2>&1 \ + | grep -o 'Consumer set property fetch.min.bytes:456' | sort -u & + wait +} | sort + +echo '--- A property that is added after the table is created' +alter_collection_of_existing_table 'kafka.future_option' kafka_altered_table +alter_collection_of_existing_table 'kafka.ssl_key_location\0suffix' kafka_altered_null_table diff --git a/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference new file mode 100644 index 000000000000..394d6bf8f288 --- /dev/null +++ b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.reference @@ -0,0 +1,3 @@ +(1,'a') (5,'b') 3 +1 +0 diff --git a/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh new file mode 100755 index 000000000000..be515083ee16 --- /dev/null +++ b/tests/queries/0_stateless/05828_minmax_count_projection_state_leak.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# `_minmax_count_projection` builds one `min`/`max` state per part. For a `Tuple` key that state owns +# heap memory, so a state that is never destroyed is a leak. A leak reports only at process exit, so +# the queries run in a short-lived `clickhouse-local` and the leak reports in its own sanitizer log +# are counted. The count is 0 on a build without a leak sanitizer, so one reference matches every +# build type. The last `log_path` wins over the runner's, and the pipeline keeps the shell from +# printing a job status line to stderr when the sanitizer aborts. +log="${CLICKHOUSE_TMP}/05828_${CLICKHOUSE_TEST_UNIQUE_NAME}" +rm -f "$log"* + +o="log_path=$log" +ASAN_OPTIONS="${ASAN_OPTIONS:+$ASAN_OPTIONS:}$o" MSAN_OPTIONS="${MSAN_OPTIONS:+$MSAN_OPTIONS:}$o" \ +TSAN_OPTIONS="${TSAN_OPTIONS:+$TSAN_OPTIONS:}$o" UBSAN_OPTIONS="${UBSAN_OPTIONS:+$UBSAN_OPTIONS:}$o" \ + $CLICKHOUSE_LOCAL --query " + CREATE TABLE tab (k Tuple(UInt64, String)) ENGINE = MergeTree ORDER BY k; + SYSTEM STOP MERGES tab; + INSERT INTO tab VALUES ((1, 'a')), ((5, 'b')); + INSERT INTO tab VALUES ((3, 'c')); + + SELECT min(k), max(k), count() FROM tab SETTINGS optimize_use_projections = 1, optimize_use_implicit_projections = 1; + + -- The query above must be answered by the projection, otherwise a zero leak count proves nothing. + SELECT count() > 0 FROM (EXPLAIN SELECT min(k), max(k), count() FROM tab SETTINGS optimize_use_projections = 1, optimize_use_implicit_projections = 1) + WHERE explain ILIKE '%_minmax_count_projection%'; + " | cat + +cat "$log"* 2>/dev/null | grep -c 'detected memory leaks' || true +rm -f "$log"* diff --git a/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.reference b/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.reference new file mode 100644 index 000000000000..b39af7ee8289 --- /dev/null +++ b/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.reference @@ -0,0 +1,20 @@ +-- union String and unrelated column IPv6 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30012729 2001:db8::1 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30022729 2001:db8::2 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30032729 2001:db8::3 +-- union inside a list +5B282720015C72B85C305C305C305C305C305C305C305C305C305C305C300127295D 2001:db8::1 +5B282720015C72B85C305C305C305C305C305C305C305C305C305C305C300227295D 2001:db8::2 +5B282720015C72B85C305C305C305C305C305C305C305C305C305C305C300327295D 2001:db8::3 +-- union Variant and unrelated column IPv6 +Tuple(s String) 282720015C72B85C305C305C305C305C305C305C305C305C305C305C30012729 2001:db8::1 +Tuple(s String) 282720015C72B85C305C305C305C305C305C305C305C305C305C305C30022729 2001:db8::2 +Tuple(s String) 282720015C72B85C305C305C305C305C305C305C305C305C305C305C30032729 2001:db8::3 +-- nullable struct in a union and unrelated column Tuple +((0)) (0) +((0)) (1) +((2)) (2) +-- nullable struct in a union and unrelated column Nullable +((0)) (0) +((0)) (1) +((2)) (2) diff --git a/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.sh b/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.sh new file mode 100755 index 000000000000..57bba70001a0 --- /dev/null +++ b/tests/queries/0_stateless/05829_arrow_ipc_union_unrelated_hint.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: Arrow formats are not available in the fast test build + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The children of an Arrow union restart the dotted path, so the struct child `s` of a union child has the path +# `s`, which is also the name of an unrelated column of the header. The requested type of that column must not +# change how the union child decodes: the union declares its children from the Arrow schema. Before the fix the +# child was decoded under the type of `s` (`IPv6`, or a `Tuple` or `Nullable` type that keeps the null map of a +# struct) while still declared as the schema says, and the cast of the union read its column as another type. + +DATA="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +$CLICKHOUSE_LOCAL -q " + SELECT CAST(CAST(tuple(unhex('20010db800000000000000000000000' || toString(number + 1))) AS Tuple(s String)) AS Variant(Tuple(s String), UInt64)) AS u, + [u] AS a, + unhex('20010db800000000000000000000000' || toString(number + 1)) AS s + FROM numbers(3) + INTO OUTFILE '${DATA}.union' TRUNCATE FORMAT ArrowStream" + +# The struct child of the union is a nullable struct. +$CLICKHOUSE_LOCAL -q " + SELECT CAST(CAST(tuple(if(number = 1, NULL, CAST(tuple(number) AS Nullable(Tuple(x UInt64))))) AS Tuple(s Nullable(Tuple(x UInt64)))) AS Variant(Tuple(s Nullable(Tuple(x UInt64))), String)) AS u, + CAST(tuple(number) AS Tuple(x UInt64)) AS s + FROM numbers(3) + INTO OUTFILE '${DATA}.nullable' TRUNCATE FORMAT ArrowStream SETTINGS allow_experimental_nullable_tuple_type = 1" + +echo "-- union String and unrelated column IPv6" +$CLICKHOUSE_LOCAL -q "SELECT hex(u), s FROM file('${DATA}.union', ArrowStream, 'u String, s IPv6')" +echo "-- union inside a list" +$CLICKHOUSE_LOCAL -q "SELECT hex(a), s FROM file('${DATA}.union', ArrowStream, 'a String, s IPv6')" +echo "-- union Variant and unrelated column IPv6" +$CLICKHOUSE_LOCAL -q "SELECT variantType(u), hex(CAST(u AS String)), s FROM file('${DATA}.union', ArrowStream, 'u Variant(Tuple(s String), UInt64), s IPv6')" +echo "-- nullable struct in a union and unrelated column Tuple" +$CLICKHOUSE_LOCAL -q "SELECT u, s FROM file('${DATA}.nullable', ArrowStream, 'u String, s Tuple(x UInt64)') SETTINGS enable_nullable_tuple_type = 0" +echo "-- nullable struct in a union and unrelated column Nullable" +$CLICKHOUSE_LOCAL -q "SELECT u, s FROM file('${DATA}.nullable', ArrowStream, 'u String, s Nullable(String)') SETTINGS enable_nullable_tuple_type = 0" + +rm -f "${DATA}.union" "${DATA}.nullable" diff --git a/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.reference b/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.reference new file mode 100644 index 000000000000..b0efa2952713 --- /dev/null +++ b/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.reference @@ -0,0 +1,10 @@ +tab_compact Compact Full +tab_packed Wide Packed +tab_compact 1 +tab_packed 1 +1 +1 +1 +1 +1 +1 diff --git a/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.sql b/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.sql new file mode 100644 index 000000000000..b1aa6f6527bf --- /dev/null +++ b/tests/queries/0_stateless/05829_text_index_materialize_packed_part_flush.sql @@ -0,0 +1,66 @@ +-- `MATERIALIZE INDEX` on a packed or compact part must build text indexes in flushed segments. + +DROP TABLE IF EXISTS tab_packed; +DROP TABLE IF EXISTS tab_compact; + +-- The mutation reads a granule per block, and the flush limit is checked after each block. +CREATE TABLE tab_packed ( + id UInt64, + s String, + s2 String, + INDEX idx_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_xxxxxxxxxxx s2 TYPE text(tokenizer = 'array') +) +ENGINE = MergeTree +ORDER BY id +SETTINGS min_level_for_full_part_storage = 2, min_bytes_for_wide_part = 0, text_index_max_memory_usage_before_flush = 65536, index_granularity = 1024, replace_long_file_name_to_hash = 1; + +CREATE TABLE tab_compact ( + id UInt64, + s String, + s2 String, + INDEX idx_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_xxxxxxxxxxx s2 TYPE text(tokenizer = 'array') +) +ENGINE = MergeTree +ORDER BY id +SETTINGS min_bytes_for_full_part_storage = 0, min_bytes_for_wide_part = '1G', text_index_max_memory_usage_before_flush = 65536, index_granularity = 1024, replace_long_file_name_to_hash = 1; + +INSERT INTO tab_packed SELECT number, concat('token', toString(number)), concat('other', toString(number)) FROM numbers(20000); +INSERT INTO tab_compact SELECT number, concat('token', toString(number)), concat('other', toString(number)) FROM numbers(20000); + +SELECT table, part_type, part_storage_type FROM system.parts +WHERE database = currentDatabase() AND table IN ('tab_packed', 'tab_compact') AND active +ORDER BY table; + +ALTER TABLE tab_packed ADD INDEX idx s TYPE text(tokenizer = 'array'); +ALTER TABLE tab_compact ADD INDEX idx s TYPE text(tokenizer = 'array'); + +ALTER TABLE tab_packed MATERIALIZE INDEX idx SETTINGS mutations_sync = 2; +ALTER TABLE tab_compact MATERIALIZE INDEX idx SETTINGS mutations_sync = 2; + +SYSTEM FLUSH LOGS part_log; + +-- Without a flush triggered by the memory limit, each of the two text indexes writes a single segment. +SELECT table, ProfileEvents['TextIndexTemporarySegmentsWritten'] > 2 +FROM system.part_log +WHERE event_date >= yesterday() + AND database = currentDatabase() + AND table IN ('tab_packed', 'tab_compact') + AND event_type = 'MutatePart' + AND error = 0 +ORDER BY table; + +DETACH TABLE tab_packed; +ATTACH TABLE tab_packed; +DETACH TABLE tab_compact; +ATTACH TABLE tab_compact; + +CHECK TABLE tab_packed SETTINGS check_query_single_value_result = 1; +CHECK TABLE tab_compact SETTINGS check_query_single_value_result = 1; + +SELECT count() FROM tab_packed WHERE s = 'token12345' SETTINGS force_data_skipping_indices = 'idx'; +SELECT count() FROM tab_packed WHERE s2 = 'other12345' SETTINGS force_data_skipping_indices = 'idx_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_xxxxxxxxxxx'; +SELECT count() FROM tab_compact WHERE s = 'token12345' SETTINGS force_data_skipping_indices = 'idx'; +SELECT count() FROM tab_compact WHERE s2 = 'other12345' SETTINGS force_data_skipping_indices = 'idx_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_very_long_name_xxxxxxxxxxx'; + +DROP TABLE tab_packed; +DROP TABLE tab_compact; diff --git a/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference new file mode 100644 index 000000000000..a7242c5404cf --- /dev/null +++ b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.reference @@ -0,0 +1,3 @@ +window: OK +argMax: OK +1 diff --git a/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh new file mode 100755 index 000000000000..3c442930addc --- /dev/null +++ b/tests/queries/0_stateless/05830_aggregate_state_create_throws_after_destroy.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +# An aggregate state was destroyed twice when its `create` threw right after the previous state was destroyed: +# in `recreate` of window aggregate states, and in `-ArgMin` / `-ArgMax` when the nested state is reset. +# `-Resample` makes most of the allocations happen in `create`, and only the last bucket keeps data that is freed +# twice. `-OrDefault` makes the results of the empty buckets cheap. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +SETTINGS="SETTINGS allow_introspection_functions = 1, memory_tracker_fault_probability = 0.0001, max_untracked_memory = 1" + +function check() +{ + local name=$1 query=$2 expected=$3 + local unexpected=0 + for _ in {1..10}; do + out=$($CLICKHOUSE_CLIENT --send_logs_level=fatal -q "$query $SETTINGS" 2>&1) + if [ "$out" != "$expected" ] && ! grep -q "MEMORY_LIMIT_EXCEEDED" <<< "$out"; then + echo "$name: unexpected output: $out" + unexpected=1 + fi + done + [ $unexpected -eq 0 ] && echo "$name: OK" +} + +check window "SELECT count() FROM (SELECT flameGraphOrDefaultResample(0, 100, 1)(['a'], 99) OVER (PARTITION BY number) AS r FROM numbers(5000))" 5000 +check argMax "SELECT length(flameGraphResampleArgMax(0, 100, 1)(['a'], 99, number)) FROM numbers(3000)" 100 + +# The server is alive. +$CLICKHOUSE_CLIENT -q "SELECT 1" diff --git a/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.reference b/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.reference new file mode 100644 index 000000000000..4e71302c86ae --- /dev/null +++ b/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.reference @@ -0,0 +1,8 @@ +-- Arrow: union String and unrelated column IPv6 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30012729 2001:db8::1 +37 2001:db8::2 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30022729 2001:db8::1 +-- ArrowStream: union String and unrelated column IPv6 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30012729 2001:db8::1 +37 2001:db8::2 +282720015C72B85C305C305C305C305C305C305C305C305C305C305C30022729 2001:db8::1 diff --git a/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.sh b/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.sh new file mode 100755 index 000000000000..d117aed6a9ee --- /dev/null +++ b/tests/queries/0_stateless/05830_arrow_ipc_union_dictionary_unrelated_hint.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: needs the pyarrow Python module, as the ClickHouse writer does not dictionary-encode inside a union. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The dictionary of a field below an Arrow union is decoded before any record batch, for the position of the +# field. The children of a union restart the dotted path, so the struct child `s` of a union child has the path +# `s`, which is also the name of an unrelated column of the header. Its requested type must not reach the +# dictionary: before the fix the dictionary values were decoded as `IPv6` while the union declared them as +# `String`, and the cast of the union read the `IPv6` column as a `String` one. + +DATA="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}" + +python3 - "${DATA}" <<'PY' +import sys +import pyarrow as pa +import pyarrow.ipc as ipc + +prefix = sys.argv[1] +raw = [bytes.fromhex("20010db8000000000000000000000001"), bytes.fromhex("20010db8000000000000000000000002")] +child = pa.StructArray.from_arrays( + [pa.DictionaryArray.from_arrays(pa.array([0, 1], type=pa.int32()), pa.array(raw, type=pa.binary()))], names=["s"]) +# Rows 0 and 2 select the struct child, row 1 the integer one. +u = pa.UnionArray.from_dense( + pa.array([0, 1, 0], type=pa.int8()), pa.array([0, 0, 1], type=pa.int32()), [child, pa.array([7], type=pa.uint64())]) +batch = pa.record_batch([u, pa.array(raw + raw[:1], type=pa.binary())], names=["u", "s"]) +for name, new_writer in (("arrow", ipc.new_file), ("arrows", ipc.new_stream)): + with new_writer(f"{prefix}.{name}", batch.schema) as writer: + writer.write_batch(batch) +PY + +for FORMAT in Arrow ArrowStream; do + FILE="${DATA}.arrow" + [ "${FORMAT}" = "ArrowStream" ] && FILE="${DATA}.arrows" + echo "-- ${FORMAT}: union String and unrelated column IPv6" + $CLICKHOUSE_LOCAL -q "SELECT hex(u), s FROM file('${FILE}', ${FORMAT}, 'u String, s IPv6')" +done + +rm -f "${DATA}.arrow" "${DATA}.arrows" diff --git a/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.reference b/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.reference new file mode 100644 index 000000000000..2d21e8567612 --- /dev/null +++ b/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.reference @@ -0,0 +1,2 @@ +3266 +3266 diff --git a/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.sql b/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.sql new file mode 100644 index 000000000000..4333446ed081 --- /dev/null +++ b/tests/queries/0_stateless/05831_prewhere_guard_old_analyzer_ast.sql @@ -0,0 +1,15 @@ +-- The AST-based move to PREWHERE (the old analyzer with `query_plan_optimize_prewhere` disabled) +-- has no DAG nodes, so the check for a throwing condition must not dereference them. + +SET enable_analyzer = 0, optimize_move_to_prewhere = 1, query_plan_optimize_prewhere = 0; + +DROP TABLE IF EXISTS t_prewhere_ast; +CREATE TABLE t_prewhere_ast (id UInt64, s String, v UInt64) ENGINE = MergeTree ORDER BY id; +INSERT INTO t_prewhere_ast SELECT number, if(number % 3 = 0, '', toString(number)), number % 100 FROM numbers(10000); + +SELECT count() FROM t_prewhere_ast WHERE s != '' AND v > 50; + +SET query_plan_enable_optimizations = 0, query_plan_optimize_prewhere = 1; +SELECT count() FROM t_prewhere_ast WHERE s != '' AND v > 50; + +DROP TABLE t_prewhere_ast; diff --git a/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.reference b/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.reference new file mode 100644 index 000000000000..65debdc6160d --- /dev/null +++ b/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.reference @@ -0,0 +1,7 @@ +DESTINATION_ATTACH +1 +2 +DESTINATION_ATTACH 1 1 +2 +CANCELLED 1 +0 diff --git a/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.sh b/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.sh new file mode 100755 index 000000000000..ddb227025254 --- /dev/null +++ b/tests/queries/0_stateless/05842_part_move_to_shard_source_part_mutated.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-shared-merge-tree, no-replicated-database, no-fasttest +# Tag zookeeper: ReplicatedMergeTree and the part move entries live in Keeper. +# Tag no-shared-merge-tree: SharedMergeTree does not move parts between shards. +# Tag no-replicated-database: the test detaches and attaches replicated tables itself. +# Tag no-fasttest: the move advances on a three second background poll, so a run takes 7-14 s. + +# A source part replaced by an ALTER DELETE mutation must not be attached on the destination: +# the cloned part is stale, and dropping the mutated source part would lose rows. +# The move should fail with NO_SUCH_DATA_PART and still be cancellable. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# One request per iteration paces the loop and an elapsed-time budget bounds it. The caller prints +# the final value, so a timeout shows up as a reference diff. +function wait_for() +{ + local query=$1 expected=$2 + local deadline=$((SECONDS + 60)) + while (( SECONDS < deadline )); do + case "$($CLICKHOUSE_CURL -sS "$CLICKHOUSE_URL" -d "$query")" in + "$expected"*) return ;; + esac + done +} + +MOVE_STATE="SELECT state FROM system.part_moves_between_shards WHERE database = currentDatabase() AND table = 'src'" + +$CLICKHOUSE_CLIENT -q " +CREATE TABLE src (id UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/src', 'r1') ORDER BY id + SETTINGS part_moves_between_shards_enable = 1, part_moves_between_shards_delay_seconds = 0, assign_part_uuids = 1; +CREATE TABLE dst (id UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/dst', 'r1') ORDER BY id + SETTINGS part_moves_between_shards_enable = 1, part_moves_between_shards_delay_seconds = 0, assign_part_uuids = 1; +INSERT INTO src VALUES (1), (2); +" +PART=$($CLICKHOUSE_CLIENT -q "SELECT name FROM system.parts WHERE database = currentDatabase() AND table = 'src' AND active") + +# The destination cannot fetch, so the move waits for the destination to clone the part. +$CLICKHOUSE_CLIENT -q " +SYSTEM STOP FETCHES dst; +ALTER TABLE src MOVE PART '$PART' TO SHARD '/clickhouse/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/dst'; +" +wait_for "SELECT count() > 0 FROM system.replication_queue + WHERE database = currentDatabase() AND table = 'dst' AND type = 'CLONE_PART_FROM_SHARD'" 1 + +# Disabling moves lets the waiting step finish but starts no other one, so the move stops right +# before it attaches the cloned part on the destination. +$CLICKHOUSE_CLIENT -q " +ALTER TABLE src MODIFY SETTING part_moves_between_shards_enable = 0; +SYSTEM START FETCHES dst; +" +wait_for "$MOVE_STATE" DESTINATION_ATTACH +$CLICKHOUSE_CLIENT -q "$MOVE_STATE" + +# Mutate the source after the destination has already cloned its old contents. +# Keep row 2 in the replacement part so this does not merely exercise the missing-part case. +$CLICKHOUSE_CLIENT --mutations_sync=2 -q "ALTER TABLE src DELETE WHERE id = 1" +$CLICKHOUSE_CLIENT -q "SELECT name != '$PART' FROM system.parts WHERE database = currentDatabase() AND table = 'src' AND active" +$CLICKHOUSE_CLIENT -q "SELECT id FROM src ORDER BY id" + +# A disabled table does not resume its moves by itself, so restart it after enabling them again. +$CLICKHOUSE_CLIENT -q " +ALTER TABLE src MODIFY SETTING part_moves_between_shards_enable = 1; +DETACH TABLE src; +ATTACH TABLE src; +" +wait_for "SELECT num_tries > 0 FROM system.part_moves_between_shards WHERE database = currentDatabase() AND table = 'src'" 1 +$CLICKHOUSE_CLIENT -q "SELECT state, num_tries > 0, last_exception LIKE '%NO_SUCH_DATA_PART%' + FROM system.part_moves_between_shards WHERE database = currentDatabase() AND table = 'src'" +$CLICKHOUSE_CLIENT -q "SELECT id FROM src ORDER BY id" + +$CLICKHOUSE_CLIENT -q "KILL PART_MOVE_TO_SHARD WHERE database = currentDatabase() AND table = 'src'" > /dev/null +wait_for "$MOVE_STATE" CANCELLED +$CLICKHOUSE_CLIENT -q " +SELECT state, rollback FROM system.part_moves_between_shards WHERE database = currentDatabase() AND table = 'src'; +SELECT count() FROM dst; +DROP TABLE src SYNC; +DROP TABLE dst SYNC; +" diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.reference b/tests/queries/0_stateless/05843_capnproto_group_fields.reference new file mode 100644 index 000000000000..920aaa9d364b --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.reference @@ -0,0 +1,44 @@ +two groups in a struct without pointers +6 1 2 3 +20971526 4 5 6 +117440518 7 8 9 +16045690984833335023 1229782938533634594 3689348815028241476 18446744073709551615 +the same as tuples +(6) 1 2 (3) +(20971526) 4 5 (6) +groups in a struct with pointers +a (6,'b',(7)) c +dd (20971526,'ee',(4294967295)) ff +named unions +6 1 a +\N 2 \N +20971526 3 \N +\N 4 b +groups in a nested struct and in a list +303132335758595A343536376162636438392D2D65666768 (1,(7)) [((6,'a')),((20971526,'b'))] +0600400100000000 (2,(20971526)) [] +null-first named unions after other fields +42 a 7 b +43 c \N \N +44 d 20971526 \N +45 e \N f +the same data read as plain fields +42 a 1 7 1 b +43 c 0 0 0 +44 d 1 20971526 0 +45 e 0 0 1 f +a tuple under a flattened name in a group +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +a tuple under a flattened name in a struct +(6,7) 1 +(20971526,117440518) 2 +6 7 1 +20971526 117440518 2 +schema inference +g Tuple(\n x UInt64) +m1 UInt64 +m2 UInt64 +h Tuple(\n y UInt64) diff --git a/tests/queries/0_stateless/05843_capnproto_group_fields.sql b/tests/queries/0_stateless/05843_capnproto_group_fields.sql new file mode 100644 index 000000000000..da33b61bbd3e --- /dev/null +++ b/tests/queries/0_stateless/05843_capnproto_group_fields.sql @@ -0,0 +1,63 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- A group (or a named union) is stored inline in its parent struct, not behind a pointer. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +-- The `file` table function is used so that both the writer and the reader use the schema below. +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xd508eaf2a79b4a10; struct Inner { a @0 :UInt64; g :group { x @1 :UInt64; } } struct Elem { g :group { x @0 :UInt64; s @1 :Text; } } struct TwoGroups { g :group { x @0 :UInt64; } m1 @1 :UInt64; m2 @2 :UInt64; h :group { y @3 :UInt64; } } struct WithPointers { s1 @0 :Text; g :group { x @1 :UInt64; s @2 :Text; n :group { y @3 :UInt32; } } s2 @4 :Text; } struct NamedUnion { n :union { value @0 :UInt64; null @1 :Void; } m @2 :UInt64; t :union { null @3 :Void; value @4 :Text; } } struct Nested { blob @0 :Data; inner @1 :Inner; elems @2 :List(Elem); } struct NullFirst { prefix @0 :UInt64; s @1 :Text; n :union { null @2 :Void; value @3 :UInt64; } t :union { null @4 :Void; value @5 :Text; } } struct NullFirstPlain { prefix @0 :UInt64; s @1 :Text; nTag @2 :UInt16; nValue @3 :UInt64; tTag @4 :UInt16; tValue @5 :Text; } struct FlatGroups { g :group { h :group { x @0 :UInt64; y @1 :UInt64; } z @2 :UInt64; } } struct Pair { x @0 :UInt64; y @1 :UInt64; } struct Mid { h @0 :Pair; z @1 :UInt64; } struct FlatStructs { g @0 :Mid; }'; + +SELECT 'two groups in a struct without pointers'; +SET format_schema_message_name = 'TwoGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') VALUES (6, 1, 2, 3), (20971526, 4, 5, 6), (117440518, 7, 8, 9), (16045690984833335023, 1229782938533634594, 3689348815028241476, 18446744073709551615); +SELECT * FROM file(currentDatabase() || '_05843_1.capnp', CapnProto, '`g.x` UInt64, m1 UInt64, m2 UInt64, `h.y` UInt64') ORDER BY m1; + +SELECT 'the same as tuples'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') VALUES ((6), 1, 2, (3)), ((20971526), 4, 5, (6)); +SELECT * FROM file(currentDatabase() || '_05843_2.capnp', CapnProto, 'g Tuple(x UInt64), m1 UInt64, m2 UInt64, h Tuple(y UInt64)') ORDER BY m1; + +SELECT 'groups in a struct with pointers'; +SET format_schema_message_name = 'WithPointers'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') VALUES ('a', (6, 'b', (7)), 'c'), ('dd', (20971526, 'ee', (4294967295)), 'ff'); +SELECT * FROM file(currentDatabase() || '_05843_3.capnp', CapnProto, 's1 String, g Tuple(x UInt64, s String, n Tuple(y UInt32)), s2 String') ORDER BY s1; + +SELECT 'named unions'; +SET format_schema_message_name = 'NamedUnion'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') VALUES (6, 1, 'a'), (NULL, 2, NULL), (20971526, 3, NULL), (NULL, 4, 'b'); +SELECT * FROM file(currentDatabase() || '_05843_4.capnp', CapnProto, 'n Nullable(UInt64), m UInt64, t Nullable(String)') ORDER BY m; + +SELECT 'groups in a nested struct and in a list'; +SET format_schema_message_name = 'Nested'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') VALUES ('0123WXYZ4567abcd89--efgh', (1, (7)), [((6, 'a')), ((20971526, 'b'))]), (unhex('0600400100000000'), (2, (20971526)), []); +SELECT hex(blob), inner, elems FROM file(currentDatabase() || '_05843_5.capnp', CapnProto, 'blob String, inner Tuple(a UInt64, g Tuple(x UInt64)), elems Array(Tuple(g Tuple(x UInt64, s String)))') ORDER BY inner.a; + +-- The value of a union is not in the slot 0 here, unlike its `Void` member. +SELECT 'null-first named unions after other fields'; +SET format_schema_message_name = 'NullFirst'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') VALUES (42, 'a', 7, 'b'), (43, 'c', NULL, NULL), (44, 'd', 20971526, NULL), (45, 'e', NULL, 'f'); +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, n Nullable(UInt64), t Nullable(String)') ORDER BY prefix; + +-- `NullFirstPlain` has the same layout as `NullFirst`, with the discriminants of the unions as ordinary fields. +SELECT 'the same data read as plain fields'; +SET format_schema_message_name = 'NullFirstPlain'; +SELECT * FROM file(currentDatabase() || '_05843_6.capnp', CapnProto, 'prefix UInt64, s String, nTag UInt16, nValue UInt64, tTag UInt16, tValue String') ORDER BY prefix; + +SELECT 'a tuple under a flattened name in a group'; +SET format_schema_message_name = 'FlatGroups'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_7.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'a tuple under a flattened name in a struct'; +SET format_schema_message_name = 'FlatStructs'; +INSERT INTO FUNCTION file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') VALUES ((6, 7), 1), ((20971526, 117440518), 2); +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h` Tuple(x UInt64, y UInt64), `g.z` UInt64') ORDER BY `g.z`; +SELECT * FROM file(currentDatabase() || '_05843_8.capnp', CapnProto, '`g.h.x` UInt64, `g.h.y` UInt64, `g.z` UInt64') ORDER BY `g.z`; + +SELECT 'schema inference'; +SET format_schema_message_name = 'TwoGroups'; +DESC format(CapnProto, ''); diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference new file mode 100644 index 000000000000..b5535d7646e5 --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.reference @@ -0,0 +1,8 @@ +a list in a group +([],[]) +([1],[2]) +([3,4],[5,6]) +a list in a struct +([],[]) +([1],[2]) +([3,4],[5,6]) diff --git a/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql new file mode 100644 index 000000000000..36c42eb0304c --- /dev/null +++ b/tests/queries/0_stateless/05844_capnproto_flattened_list_sizes.sql @@ -0,0 +1,27 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: the Cap'n Proto format is not built in the Fast test build. + +-- Columns with flattened names (like `l.x` and `l.y`) are written to the same list, so the sizes of their arrays must match. +-- For top-level columns it is also checked on `INSERT` before the format, so the flattened names are put inside a `Tuple` +-- to reach the check in the format itself, like `SELECT ... FORMAT CapnProto` does. + +SET output_format_parallel_formatting = 0; +SET input_format_parallel_parsing = 0; +SET engine_file_truncate_on_insert = 1; + +SET format_schema_source = 'string'; +SET format_schema = '@0xeed9ecfa9f9df117; struct E { x @0 :UInt64; y @1 :UInt64; } struct T { l @0 :List(E); } struct InGroup { t :group { l @0 :List(E); } } struct InStruct { t @0 :T; }'; + +SELECT 'a list in a group'; +SET format_schema_message_name = 'InGroup'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_1.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); + +SELECT 'a list in a struct'; +SET format_schema_message_name = 'InStruct'; +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') SELECT ([1, 2], [2]); -- { serverError SIZES_OF_ARRAYS_DONT_MATCH } +INSERT INTO FUNCTION file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') VALUES (([], [])), (([1], [2])), (([3, 4], [5, 6])); +SELECT * FROM file(currentDatabase() || '_05844_2.capnp', CapnProto, 't Tuple(`l.x` Array(UInt64), `l.y` Array(UInt64))') ORDER BY length(t.1); diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference new file mode 100644 index 000000000000..08552bc1f284 --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.reference @@ -0,0 +1,10 @@ +x Nullable(Int64) +y Nullable(UInt64) +x Nullable(Int64) +y Nullable(UInt64) +a Array(Nullable(Float64)) +b Array(Nullable(UInt64)) +x Nullable(String) +x Nullable(String) +x Nullable(String) +Array(Nullable(Int64)) Array(Dynamic) Array(Dynamic) diff --git a/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql new file mode 100644 index 000000000000..422740e3deaa --- /dev/null +++ b/tests/queries/0_stateless/05848_json_schema_inference_freed_type_mark.sql @@ -0,0 +1,15 @@ +-- A type freed during inference must not pass its negative or parsed-from-string mark to another value. + +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"x":-1}\n{"x":-2}\n{"y":1}\n{"y":18446744073709551615}'); +DESC format(JSONEachRow, '{"a":[-1, 1.5], "b":[1, 18446744073709551615]}'); +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"2"}\n{"y":1}\n{"y":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } + +-- The marks still work. +DESC format(JSONEachRow, '{"x":0}\n{"x":-1}\n{"y":-1}\n{"y":18446744073709551615}'); -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":["-1"]}\n{"x":["18446744073709551615"]}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":"-1"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +DESC format(JSONEachRow, '{"x":1}\n{"x":1.5}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; -- { serverError CANNOT_EXTRACT_TABLE_STRUCTURE } +DESC format(JSONEachRow, '{"x":"1"}\n{"x":"18446744073709551615"}\n{"x":"abc"}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1, input_format_json_read_numbers_as_strings = 0; +SELECT dynamicType(j.a), dynamicType(j.b), dynamicType(j.c) FROM format(JSONEachRow, 'j JSON', '{"j":{"a":[-1, 1], "b":["-1", "18446744073709551615"], "c":[-1, 18446744073709551615]}}') SETTINGS input_format_json_try_infer_numbers_from_strings = 1; diff --git a/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.reference b/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.reference new file mode 100644 index 000000000000..ea01c6913bec --- /dev/null +++ b/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.reference @@ -0,0 +1,41 @@ +--- A non-SELECT invalidate query is not sent +a +rejected: 1 +0 +--- A non-SELECT update query is not sent +a +rejected: 1 +a +--- Lookups with any key are sent +quote backslash +--- The queries held by a named collection are checked +1 +--- A named collection requires the privilege NAMED COLLECTION +Without the grant: denied, not created +1 +0 +Without the grant, ON CLUSTER: denied, not created +1 +0 +Without the grant, the name is an expression: denied, not created +1 +0 +Without the grant, CREATE OR REPLACE: denied, not created +1 +0 +--- The name of the collection cannot refer to other values of the definition +1 +0 +1 +0 +With the grant: created +0 +1 +With the grant, ON CLUSTER: created +0 +1 +--- The errors do not show a query held by a named collection +backslash: rejected 1, shown 0 +last_exception: rejected 1, shown 0 +syntax: rejected 1, shown 0 +last_exception: rejected 1, shown 0 diff --git a/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.sh b/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.sh new file mode 100755 index 000000000000..1c49aba561ec --- /dev/null +++ b/tests/queries/0_stateless/05871_dictionary_external_source_queries_select_only.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# Tags: zookeeper, no-fasttest +# no-fasttest: the MySQL integration is not available in the fast test build. + +# The queries of a MySQL, PostgreSQL or ODBC dictionary source are sent to the database with the credentials of the source, +# which can come from a named collection that the author of the dictionary has no grant for: the dictionary is loaded +# with the global context. So a dictionary created by `CREATE DICTIONARY` sends only `SELECT`, and `CREATE DICTIONARY` +# requires `NAMED COLLECTION` on the collection of its source. The checks of the load query are in +# `05872_dictionary_external_source_queries_syntax`. + +# The MySQL source connects to this server, and a failed self-connect attempt is reported at Warning. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=error + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +user="${CLICKHOUSE_TEST_UNIQUE_NAME}_user" +backend_user="${CLICKHOUSE_TEST_UNIQUE_NAME}_backend" +nc="${CLICKHOUSE_TEST_UNIQUE_NAME}_nc" +# A query `ON CLUSTER` another cluster than the one of a `Replicated` database is replicated by the database with the clause, +# and its execution then fails with `ON CLUSTER is not allowed for Replicated database`. The test database is `Replicated` +# in the `DBReplicated` runs, so the dictionaries created `ON CLUSTER` are in a separate `Atomic` database. +atomic_db="${CLICKHOUSE_DATABASE}_atomic" + +function cleanup() +{ + $CLICKHOUSE_CLIENT --multiquery --query " + DROP DICTIONARY IF EXISTS dict_invalidate; + DROP DICTIONARY IF EXISTS dict_update; + DROP DICTIONARY IF EXISTS dict_nc; + DROP DICTIONARY IF EXISTS dict_keys; + DROP DICTIONARY IF EXISTS dict_hidden; + DROP USER IF EXISTS $user; + DROP USER IF EXISTS $backend_user; + DROP NAMED COLLECTION IF EXISTS $nc; + DROP NAMED COLLECTION IF EXISTS ${nc}_query; + DROP NAMED COLLECTION IF EXISTS ${nc}_backslash; + DROP NAMED COLLECTION IF EXISTS ${nc}_syntax; + DROP DATABASE IF EXISTS ${atomic_db} SYNC;" +} +trap cleanup EXIT +cleanup + +echo '--- A non-SELECT invalidate query is not sent' +# The source connects to this server over the MySQL protocol as a user that can create tables, so the canary table +# would be created if the invalidate query were sent. The invalidate query runs when the lifetime expires: the failed +# check is logged by the loader, and the dictionary is updated anyway. +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE USER $backend_user IDENTIFIED WITH plaintext_password BY 'p'; + GRANT SELECT, CREATE TABLE ON ${CLICKHOUSE_DATABASE}.* TO $backend_user; + CREATE TABLE src (id UInt64, value String) ENGINE = MergeTree ORDER BY id; + INSERT INTO src VALUES (1, 'a'); + CREATE DICTIONARY dict_invalidate (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT ${CLICKHOUSE_PORT_MYSQL} USER '$backend_user' PASSWORD 'p' DB '${CLICKHOUSE_DATABASE}' TABLE 'src' + INVALIDATE_QUERY 'CREATE TABLE ${CLICKHOUSE_DATABASE}.canary (x UInt8) ENGINE = Memory')) + LAYOUT(FLAT()) LIFETIME(MIN 1 MAX 1); + SELECT dictGet(dict_invalidate, 'value', toUInt64(1));" + +# The loader checks the dictionaries every few seconds. +rejected=0 +while [ "$rejected" != "1" ] && [ $SECONDS -lt 120 ]; do + rejected=$($CLICKHOUSE_CLIENT --multiquery --query " + SYSTEM FLUSH LOGS text_log; + SELECT count() > 0 FROM system.text_log + WHERE event_date >= yesterday() + AND event_time >= now() - INTERVAL 10 MINUTE + AND message LIKE '%Could not check if dictionary%${CLICKHOUSE_DATABASE}.dict_invalidate%Only SELECT query can be used as a dictionary invalidate query%'") + [ "$rejected" = "1" ] || sleep 0.5 +done +echo "rejected: $rejected" +$CLICKHOUSE_CLIENT --query "SELECT count() FROM system.tables WHERE database = currentDatabase() AND name = 'canary'" + +echo '--- A non-SELECT update query is not sent' +# The update query is composed from `update_field` as written, and only an update after the first load sends it: the first load +# sends the load query. MySQL executes the content of a `/*! ... */` comment, so the update query would run the statement in it. +# The update is rejected, and the dictionary keeps the previous version. +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE TABLE src_update (id UInt64, value String, updated DateTime) ENGINE = MergeTree ORDER BY id; + INSERT INTO src_update VALUES (1, 'a', now()); + CREATE DICTIONARY dict_update (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT ${CLICKHOUSE_PORT_MYSQL} USER '$backend_user' PASSWORD 'p' DB '${CLICKHOUSE_DATABASE}' TABLE 'src_update' + UPDATE_FIELD 'updated /*! ; CREATE TABLE ${CLICKHOUSE_DATABASE}.canary_update (x UInt8) ENGINE = Memory */')) + LAYOUT(FLAT()) LIFETIME(MIN 1 MAX 1); + SELECT dictGet(dict_update, 'value', toUInt64(1));" + +rejected=0 +deadline=$((SECONDS + 120)) +while [ "$rejected" != "1" ] && [ $SECONDS -lt $deadline ]; do + rejected=$($CLICKHOUSE_CLIENT --query " + SELECT count() > 0 FROM system.dictionaries + WHERE database = currentDatabase() AND name = 'dict_update' + AND last_exception LIKE '%Update query for MySQL dictionary%cannot contain comments%'") + [ "$rejected" = "1" ] || sleep 0.5 +done +echo "rejected: $rejected" +$CLICKHOUSE_CLIENT --query "SELECT dictGet(dict_update, 'value', toUInt64(1))" + +echo '--- Lookups with any key are sent' +# The lookups of a `direct` layout add the keys to the checked load query, escaped in the style of MySQL: a quote or a backslash +# in a key is not a part of the query for the database. +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE TABLE src_keys (k String, v String) ENGINE = MergeTree ORDER BY k; + INSERT INTO src_keys VALUES ('O''Brien', 'quote'), ('a\\\\b', 'backslash'); + CREATE DICTIONARY dict_keys (k String, v String) PRIMARY KEY k + SOURCE(MYSQL(HOST '127.0.0.1' PORT ${CLICKHOUSE_PORT_MYSQL} USER '$backend_user' PASSWORD 'p' DB '${CLICKHOUSE_DATABASE}' TABLE 'src_keys')) + LAYOUT(COMPLEX_KEY_DIRECT()); + SELECT dictGet(dict_keys, 'v', tuple('O''Brien')), dictGet(dict_keys, 'v', tuple('a\\\\b')); + DROP DICTIONARY dict_keys;" + +echo '--- The queries held by a named collection are checked' +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE NAMED COLLECTION ${nc}_query AS host = '127.0.0.1', port = 1, user = 'u', password = 'p', db = 'd', query = 'DROP TABLE t'; + CREATE DICTIONARY dict_nc (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(NAME ${nc}_query)) LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1);" +$CLICKHOUSE_CLIENT --query "SYSTEM RELOAD DICTIONARY dict_nc" 2>&1 | grep -q "Only SELECT query can be used as a dictionary source" && echo 1 || echo 0 +$CLICKHOUSE_CLIENT --query "DROP DICTIONARY dict_nc" + +echo '--- A named collection requires the privilege NAMED COLLECTION' +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE NAMED COLLECTION $nc AS host = '127.0.0.1', port = 1, user = 'u', password = 'p', db = 'd'; + CREATE USER $user; + CREATE DATABASE ${atomic_db} ENGINE = Atomic; + GRANT CREATE DICTIONARY, DROP DICTIONARY ON ${CLICKHOUSE_DATABASE}.* TO $user; + GRANT CREATE DICTIONARY, DROP DICTIONARY ON ${atomic_db}.* TO $user; + GRANT CLUSTER ON *.* TO $user;" + +# Prints whether the `CREATE` was denied for the named collection, and whether the dictionary exists. +function create_as_user() +{ + local on_cluster="$1" + local name="$2" + local statement="${3:-CREATE DICTIONARY}" + local db="$CLICKHOUSE_DATABASE" + [ -n "$on_cluster" ] && db="$atomic_db" + $CLICKHOUSE_CLIENT --user "$user" --distributed_ddl_output_mode=none --query " + ${statement} ${db}.dict_nc ${on_cluster} (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(NAME ${name} TABLE 't')) LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1)" 2>&1 \ + | grep -qE "necessary to have the grant NAMED COLLECTION ON \`?${nc}\`?\." && echo 1 || echo 0 + $CLICKHOUSE_CLIENT --multiquery --query " + SELECT count() FROM system.tables WHERE database = '${db}' AND name = 'dict_nc'; + DROP DICTIONARY IF EXISTS ${db}.dict_nc;" +} + +echo 'Without the grant: denied, not created' +create_as_user "" "$nc" +echo 'Without the grant, ON CLUSTER: denied, not created' +create_as_user "ON CLUSTER test_shard_localhost" "$nc" +echo 'Without the grant, the name is an expression: denied, not created' +create_as_user "" "concat('$nc', '')" +echo 'Without the grant, CREATE OR REPLACE: denied, not created' +create_as_user "" "$nc" "CREATE OR REPLACE DICTIONARY" +$CLICKHOUSE_CLIENT --query "GRANT NAMED COLLECTION ON $nc TO $user" +echo '--- The name of the collection cannot refer to other values of the definition' +# The source reads the name from the dictionary configuration, which expands `${...}`: `${dictionary.comment}` would be +# the collection named by the comment, while the grant is checked on the literal name. +$CLICKHOUSE_CLIENT --query "GRANT NAMED COLLECTION ON \`\${dictionary.comment}\` TO $user" +for on_cluster in "" "ON CLUSTER test_shard_localhost"; do + db="$CLICKHOUSE_DATABASE" + [ -n "$on_cluster" ] && db="$atomic_db" + # shellcheck disable=SC2016 # The pattern is the literal `${`. + $CLICKHOUSE_CLIENT --user "$user" --distributed_ddl_output_mode=none --query " + CREATE DICTIONARY ${db}.dict_nc ${on_cluster} (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(NAME '\${dictionary.comment}')) LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1) + COMMENT '$nc'" 2>&1 \ + | grep -qF 'cannot contain `${`' && echo 1 || echo 0 + $CLICKHOUSE_CLIENT --multiquery --query " + SELECT count() FROM system.tables WHERE database = '${db}' AND name = 'dict_nc'; + DROP DICTIONARY IF EXISTS ${db}.dict_nc;" +done +echo 'With the grant: created' +create_as_user "" "$nc" +echo 'With the grant, ON CLUSTER: created' +create_as_user "ON CLUSTER test_shard_localhost" "$nc" + +echo '--- The errors do not show a query held by a named collection' +# The values of a named collection are hidden from a user without `SHOW NAMED COLLECTIONS SECRETS`, who can still use it, +# and the error of the check of its query reaches the caller of `dictGet`. +$CLICKHOUSE_CLIENT --multiquery --query " + CREATE NAMED COLLECTION ${nc}_backslash AS host = '127.0.0.1', port = 1, user = 'u', password = 'p', db = 'd', + query = 'SELECT id, value FROM t WHERE k = ''hidden_value\\\\\\\\x'''; + CREATE NAMED COLLECTION ${nc}_syntax AS host = '127.0.0.1', port = 1, user = 'u', password = 'p', db = 'd', + query = 'SELECT id, value FROM t WHERE k = 1 FOR UPDATE hidden_value'; + GRANT NAMED COLLECTION ON ${nc}_backslash TO $user; + GRANT NAMED COLLECTION ON ${nc}_syntax TO $user; + GRANT dictGet ON ${CLICKHOUSE_DATABASE}.* TO $user;" +for case in "backslash INCORRECT_QUERY" "syntax SYNTAX_ERROR"; do + read -r name error <<< "$case" + $CLICKHOUSE_CLIENT --user "$user" --query " + CREATE DICTIONARY ${CLICKHOUSE_DATABASE}.dict_hidden (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(NAME ${nc}_${name})) LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1)" + output=$($CLICKHOUSE_CLIENT --user "$user" --query "SELECT dictGet(${CLICKHOUSE_DATABASE}.dict_hidden, 'value', toUInt64(1))" 2>&1) + echo "$name: rejected $(grep -qF "($error)" <<< "$output" && echo 1 || echo 0), shown $(grep -qF 'hidden_value' <<< "$output" && echo 1 || echo 0)" + # The error is kept in `system.dictionaries`, which a user can read without the privileges of the collection. + $CLICKHOUSE_CLIENT --query " + SELECT 'last_exception: rejected ' || toString(last_exception != '') || ', shown ' || toString(position(last_exception, 'hidden_value') > 0) + FROM system.dictionaries WHERE database = currentDatabase() AND name = 'dict_hidden'" + $CLICKHOUSE_CLIENT --query "DROP DICTIONARY ${CLICKHOUSE_DATABASE}.dict_hidden" +done diff --git a/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.reference b/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.reference new file mode 100644 index 000000000000..c65c16f58530 --- /dev/null +++ b/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.reference @@ -0,0 +1,3 @@ +250005 +250005 +1 1 diff --git a/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.sql b/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.sql new file mode 100644 index 000000000000..6db7e94950ec --- /dev/null +++ b/tests/queries/0_stateless/05871_encrypted_disk_s3_requests_like_plain.sql @@ -0,0 +1,50 @@ +-- Tags: no-fasttest, no-distributed-cache +-- no-fasttest: needs MinIO. +-- no-distributed-cache: reads through the distributed cache do not make these S3 requests. + +-- Reading from an encrypted disk must make as many S3 requests as reading the same data from the disk under it. +-- The encryption header used to be read with an unbounded request, which was reopened when the reader set its range. +-- Parts in packed storage are excluded with `min_bytes_for_full_part_storage = 0`: a file inside the packed archive +-- does not start at the archive's header, so its header is read with a request of its own. +-- Nothing may load the marks or the primary key before the queries, so that both queries load them themselves: +-- otherwise the shared caches decide whether a query reads them. +-- The merges are not compared: in this version the `ProfileEvents` of a merge in `system.part_log` count only the +-- merge thread itself, not the threads that prefetch for it, so they do not count the same requests for both disks. + +DROP TABLE IF EXISTS t_plain; +DROP TABLE IF EXISTS t_encrypted; + +CREATE TABLE t_plain (k UInt64, s String) ENGINE = MergeTree ORDER BY k +SETTINGS storage_policy = 's3_no_cache', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, min_bytes_for_full_part_storage = 0, + prewarm_mark_cache = 0, prewarm_primary_key_cache = 0, use_primary_key_cache = 0, index_granularity = 1024; + +CREATE TABLE t_encrypted (k UInt64, s String) ENGINE = MergeTree ORDER BY k +SETTINGS storage_policy = 's3_no_cache_encrypted', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, min_bytes_for_full_part_storage = 0, + prewarm_mark_cache = 0, prewarm_primary_key_cache = 0, use_primary_key_cache = 0, index_granularity = 1024; + +-- One part per table, so that no background merge runs before `OPTIMIZE` and each table has exactly one merge. +INSERT INTO t_plain SELECT number, toString(number) FROM numbers(200000) SETTINGS max_insert_threads = 1; +INSERT INTO t_encrypted SELECT number, toString(number) FROM numbers(200000) SETTINGS max_insert_threads = 1; +OPTIMIZE TABLE t_plain FINAL; +OPTIMIZE TABLE t_encrypted FINAL; + +-- A mark range, with the randomized settings that change how the data is read pinned. +SELECT sum(length(s)) FROM t_plain WHERE k BETWEEN 10000 AND 60000 +SETTINGS max_threads = 1, remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1, use_uncompressed_cache = 0, + use_page_cache_for_object_storage = 0, use_page_cache_for_disks_without_file_cache = 0, + enable_parallel_replicas = 0, log_comment = '05871_plain'; +SELECT sum(length(s)) FROM t_encrypted WHERE k BETWEEN 10000 AND 60000 +SETTINGS max_threads = 1, remote_filesystem_read_method = 'threadpool', remote_filesystem_read_prefetch = 1, use_uncompressed_cache = 0, + use_page_cache_for_object_storage = 0, use_page_cache_for_disks_without_file_cache = 0, + enable_parallel_replicas = 0, log_comment = '05871_encrypted'; + +SYSTEM FLUSH LOGS query_log; + +SELECT + sumIf(ProfileEvents['S3GetObject'], log_comment = '05871_plain') > 0, + sumIf(ProfileEvents['S3GetObject'], log_comment = '05871_encrypted') = sumIf(ProfileEvents['S3GetObject'], log_comment = '05871_plain') +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND log_comment IN ('05871_plain', '05871_encrypted'); + +DROP TABLE t_plain; +DROP TABLE t_encrypted; diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference new file mode 100644 index 000000000000..f7167d89dfe9 --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.reference @@ -0,0 +1,20 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128Keyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', number, \'visible_input\')\nFROM numbers(1) +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); +SELECT sipHash64Keyed(\'[HIDDEN]\', \'visible_input\')\nFROM numbers(1) +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +SELECT sipHash64(tuple(CAST(\'1311768467463790320\', \'UInt64\'), CAST(\'18364758544493064720\', \'UInt64\')), \'visible_input\')\nFROM system.one +1 +SELECT sipHash128Keyed(\'[HIDDEN]\', \'logged_input_2\') FORMAT `Null` +SELECT sipHash128ReferenceKeyed(\'[HIDDEN]\', \'logged_input_3\') FORMAT `Null` +SELECT sipHash64Keyed(\'[HIDDEN]\', \'logged_input_1\') FORMAT `Null` +0 diff --git a/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql new file mode 100644 index 000000000000..ae1de74058d0 --- /dev/null +++ b/tests/queries/0_stateless/05871_keyed_siphash_key_masking.sql @@ -0,0 +1,32 @@ +-- The key (the first argument) of the keyed SipHash functions must not be visible in formatted or logged queries. + +-- { echoOn } +EXPLAIN SYNTAX SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); +EXPLAIN SYNTAX SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), number, 'visible_input') FROM numbers(1); + +-- A key which is not a literal is hidden as well. +EXPLAIN SYNTAX SELECT sipHash64Keyed((toUInt64(1311768467463790320), number + 18364758544493064720), 'visible_input') FROM numbers(1); + +-- The functions without a key are not affected. +EXPLAIN SYNTAX SELECT sipHash64((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input'); +-- { echoOff } + +-- Masking does not change the result. +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'visible_input') = sipHash64Keyed((materialize(1311768467463790320::UInt64), 18364758544493064720::UInt64), 'visible_input'); + +SELECT sipHash64Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_1') FORMAT Null; +SELECT sipHash128Keyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_2') FORMAT Null; +SELECT sipHash128ReferenceKeyed((1311768467463790320::UInt64, 18364758544493064720::UInt64), 'logged_input_3') FORMAT Null; + +SYSTEM FLUSH LOGS query_log; + +SELECT query +FROM system.query_log +WHERE current_database = currentDatabase() AND type = 'QueryFinish' AND query LIKE '%logged\_input\__%' AND query NOT LIKE '%system.query_log%' +ORDER BY query; + +SELECT count() +FROM system.query_log +WHERE current_database = currentDatabase() AND query NOT LIKE '%system.query_log%' + AND (query LIKE '%1311768467463790320%' OR query LIKE '%18364758544493064720%') AND query NOT LIKE '%sipHash64(%'; diff --git a/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.reference b/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.reference new file mode 100644 index 000000000000..662fc2b90bff --- /dev/null +++ b/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.reference @@ -0,0 +1,4 @@ +--- Statements other than SELECT are rejected +--- What the database reads differently from ClickHouse is rejected +--- The load query of a lookup is checked +--- SELECT is sent diff --git a/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.sql b/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.sql new file mode 100644 index 000000000000..32d1f13325ac --- /dev/null +++ b/tests/queries/0_stateless/05872_dictionary_external_source_queries_syntax.sql @@ -0,0 +1,81 @@ +-- Tags: no-fasttest +-- no-fasttest: the MySQL and PostgreSQL integrations are not available in the fast test build. + +-- A MySQL, PostgreSQL or ODBC dictionary created by `CREATE DICTIONARY` sends only `SELECT` to the database: the query +-- is checked when it is sent, before any connection. An ODBC source needs the bridge to be created, so it is not tested here. The sources point at `127.0.0.1` port 1, where nothing listens, +-- so a checked query ends in a connection failure. The invalidate query is tested in `05871_dictionary_external_source_queries_select_only`. + +SELECT '--- Statements other than SELECT are rejected'; +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'DROP TABLE t')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(POSTGRESQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'DELETE FROM t WHERE id = 1')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +-- `where` is a part of the composed query, so a second statement in it is rejected too. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' TABLE 't' WHERE '1; DROP TABLE t')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError SYNTAX_ERROR } +DROP DICTIONARY d; + +SELECT '--- What the database reads differently from ClickHouse is rejected'; +-- MySQL executes the text of `/*! ... */`. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, value FROM t /*! INTO OUTFILE ''/tmp/x'' */')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +-- MySQL writes the file of `INTO OUTFILE` on its host. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, value FROM t INTO OUTFILE ''/tmp/x''')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +-- PostgreSQL reads a backslash in a string literally, so `'\\'` is two backslashes for it and one for ClickHouse. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(POSTGRESQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, ''\\\\'' AS value FROM t')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +-- `FORMAT` and `SETTINGS` are a part of a `SELECT` only for ClickHouse. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, value FROM t FORMAT TSV')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, value FROM t SETTINGS max_threads = 1')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; + +SELECT '--- The load query of a lookup is checked'; +-- A `direct` layout never loads all, its lookups add a condition on the keys to the load query. +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'DELETE FROM t WHERE {condition}')) + LAYOUT(DIRECT()); +SELECT dictGet(d, 'value', toUInt64(1)); -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; +-- In a string literal, the quotes of the condition on the keys would end the literal, and a key would be read as SQL. +CREATE DICTIONARY d (id String, value String) PRIMARY KEY id + SOURCE(POSTGRESQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT ''{condition}'' AS id, '''' AS value')) + LAYOUT(COMPLEX_KEY_DIRECT()); +SELECT dictGet(d, 'value', tuple('x')); -- { serverError INCORRECT_QUERY } +DROP DICTIONARY d; + +SELECT '--- SELECT is sent'; +CREATE DICTIONARY d (id UInt64, value String) PRIMARY KEY id + SOURCE(MYSQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' QUERY 'SELECT id, value FROM t WHERE {condition}' INVALIDATE_QUERY 'SELECT max(updated) FROM t')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError ALL_CONNECTION_TRIES_FAILED } +DROP DICTIONARY d; +CREATE DICTIONARY d (id UInt64, value String DEFAULT '' EXPRESSION 'concat(value, ''x'')') PRIMARY KEY id + SOURCE(POSTGRESQL(HOST '127.0.0.1' PORT 1 USER 'u' PASSWORD 'p' DB 'd' TABLE 't' WHERE 'id > 0' UPDATE_FIELD 'updated')) + LAYOUT(FLAT()) LIFETIME(0) SETTINGS(dictionary_lazy_load = 1); +SYSTEM RELOAD DICTIONARY d; -- { serverError POSTGRESQL_CONNECTION_FAILURE } +DROP DICTIONARY d; diff --git a/tests/queries/0_stateless/05873_text_index_reader_granule_change.reference b/tests/queries/0_stateless/05873_text_index_reader_granule_change.reference new file mode 100644 index 000000000000..a8760340523a --- /dev/null +++ b/tests/queries/0_stateless/05873_text_index_reader_granule_change.reference @@ -0,0 +1,2 @@ +7000 +7000 diff --git a/tests/queries/0_stateless/05873_text_index_reader_granule_change.sql b/tests/queries/0_stateless/05873_text_index_reader_granule_change.sql new file mode 100644 index 000000000000..6acdb236ded4 --- /dev/null +++ b/tests/queries/0_stateless/05873_text_index_reader_granule_change.sql @@ -0,0 +1,29 @@ +-- A text index reader that a read task hands a rebuilt granule of its part must not keep postings streams of the old granule. +-- The split of the read into layers counts the marks of a layer border twice, so the cached index read result of the big +-- part is released before its last read task, which rebuilds it. Detected by sanitizer builds (heap-use-after-free). + +DROP TABLE IF EXISTS tab; + +CREATE TABLE tab (id UInt64, text String, INDEX idx(text) TYPE text(tokenizer = 'splitByNonAlpha', posting_list_codec = 'bitpacking') GRANULARITY 1) +ENGINE = MergeTree ORDER BY id +SETTINGS index_granularity = 64, index_granularity_bytes = '10Mi', text_index_posting_list_block_size = 16; + +INSERT INTO tab SELECT number, concat('abc def row ', toString(number)) FROM numbers(6400); +OPTIMIZE TABLE tab FINAL; +SYSTEM STOP MERGES tab; +INSERT INTO tab SELECT 3000 + number, concat('abc def row ', toString(number)) FROM numbers(300); +INSERT INTO tab SELECT 3100 + number, concat('abc def row ', toString(number)) FROM numbers(300); + +SET max_threads = 4, max_threads_min_free_memory_per_thread = 0, max_streams_to_max_threads_ratio = 1; +SET merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 1; +SET use_query_condition_cache = 0, optimize_move_to_prewhere = 0, query_plan_optimize_prewhere = 0; +SET use_skip_indexes = 1, use_skip_indexes_on_data_read = 1, query_plan_direct_read_from_text_index = 1; +SET max_rows_to_read = 0; -- A throwing row limit applies the skip indexes before the read instead of on data read. +SET query_plan_optimize_count_from_text_index = 0; +SET merge_tree_min_rows_for_concurrent_read = 64, merge_tree_min_bytes_for_concurrent_read = 0, merge_tree_min_read_task_size = 1; +SET merge_tree_min_bytes_per_read_stream = 0, allow_prefetched_read_pool_for_local_filesystem = 0, read_backoff_min_latency_ms = 0; + +SELECT count() FROM tab WHERE hasAllTokens(text, ['abc', 'def']) SETTINGS text_index_posting_list_apply_mode = 'materialize'; +SELECT count() FROM tab WHERE hasAllTokens(text, ['abc', 'def']) SETTINGS text_index_posting_list_apply_mode = 'lazy'; + +DROP TABLE tab; diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference new file mode 100644 index 000000000000..616bb8316151 --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.reference @@ -0,0 +1,3 @@ +1 [1,2,3] [1,2,3] +2 [4] [4] +1 5 diff --git a/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql new file mode 100644 index 000000000000..ee1916b245ab --- /dev/null +++ b/tests/queries/0_stateless/05874_column_ttl_on_alias_column_merge.sql @@ -0,0 +1,17 @@ +-- A column TTL on a column that is not stored (ALIAS, EPHEMERAL) must not break TTL merges. + +DROP TABLE IF EXISTS t_alias_ttl; +CREATE TABLE t_alias_ttl (id UInt64, dt Date, arr Array(UInt64), al Array(UInt64) ALIAS arr TTL dt + INTERVAL 1 MONTH) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_alias_ttl VALUES (1, '2000-01-01', [1, 2, 3]), (2, '2100-01-01', [4]); +OPTIMIZE TABLE t_alias_ttl FINAL; +SELECT id, arr, al FROM t_alias_ttl ORDER BY id; +DROP TABLE t_alias_ttl; + +DROP TABLE IF EXISTS t_ephemeral_ttl; +CREATE TABLE t_ephemeral_ttl (id UInt64, dt Date, e UInt64 EPHEMERAL 0 TTL dt + INTERVAL 1 MONTH, v UInt64 DEFAULT e) +ENGINE = MergeTree ORDER BY id; +INSERT INTO t_ephemeral_ttl (id, dt, e) VALUES (1, '2000-01-01', 5); +OPTIMIZE TABLE t_ephemeral_ttl FINAL; +SELECT id, v FROM t_ephemeral_ttl; +DROP TABLE t_ephemeral_ttl; diff --git a/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.reference b/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.reference new file mode 100644 index 000000000000..a16134b3250d --- /dev/null +++ b/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.reference @@ -0,0 +1,3 @@ +0 +3 +0 0 diff --git a/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.sh b/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.sh new file mode 100755 index 000000000000..682995cb755a --- /dev/null +++ b/tests/queries/0_stateless/05876_async_insert_dedup_cache_disabled.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Tags: zookeeper + +# With `async_insert_use_deduplication_cache = 0` an async insert must not be dropped as a duplicate +# when the deduplication cache of a replica still holds a hash that was removed from Keeper +# by TRUNCATE on another replica. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +SETTINGS="--async_insert 1 --wait_for_async_insert 1 --deduplicate_insert enable" +VALUES="('a', 1), ('b', 2), ('c', 3)" + +$CLICKHOUSE_CLIENT -q "DROP TABLE IF EXISTS t1 SYNC" +$CLICKHOUSE_CLIENT -q "DROP TABLE IF EXISTS t2 SYNC" +$CLICKHOUSE_CLIENT -q "CREATE TABLE t1 (k String, v Int32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/05876/t', 'r1') ORDER BY tuple()" +$CLICKHOUSE_CLIENT -q "CREATE TABLE t2 (k String, v Int32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/05876/t', 'r2') ORDER BY tuple()" + +function flush_events() +{ + $CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS query_log, asynchronous_insert_log" + $CLICKHOUSE_CLIENT -q " + SELECT ProfileEvents['AsyncInsertCacheHits'], ProfileEvents['DuplicatedAsyncInserts'] + FROM system.query_log + -- AND current_database = currentDatabase() -- Just to silence style check: the flush is scoped via flush_query_id below. + WHERE type = 'QueryFinish' AND query_id IN ( + SELECT flush_query_id FROM system.asynchronous_insert_log + WHERE database = currentDatabase() AND query_id = '$1' + )" +} + +$CLICKHOUSE_CLIENT $SETTINGS -q "INSERT INTO t1 VALUES $VALUES" + +# Repeat the duplicate insert into t2 until its cache holds the hash. +warm=0 +for i in {1..50}; do + query_id="${CLICKHOUSE_DATABASE}_warm_${i}" + $CLICKHOUSE_CLIENT $SETTINGS --query_id "$query_id" -q "INSERT INTO t2 VALUES $VALUES" + hits=$(flush_events "$query_id" | cut -f1) + if [ -n "$hits" ] && [ "$hits" != "0" ]; then + warm=1 + break + fi +done +[ "$warm" == "1" ] || echo "The deduplication cache of t2 was not warmed up" + +# The cache hit above scheduled a cache refresh; let it finish before TRUNCATE, +# otherwise it may load the snapshot without the hash and the test would not check anything. +for _ in {1..600}; do + pending=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.background_schedule_pool + WHERE database = currentDatabase() AND table = 't2' + AND log_name LIKE '%(AsyncBlockIDsCache)' + AND (scheduled OR delayed OR executing)") + [ "$pending" == "0" ] && break + sleep 0.1 +done + +$CLICKHOUSE_CLIENT -q "TRUNCATE TABLE t1" +$CLICKHOUSE_CLIENT -q "SYSTEM SYNC REPLICA t2" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM t2" + +query_id="${CLICKHOUSE_DATABASE}_after_truncate" +$CLICKHOUSE_CLIENT $SETTINGS --async_insert_use_deduplication_cache 0 --query_id "$query_id" -q "INSERT INTO t2 VALUES $VALUES" +$CLICKHOUSE_CLIENT -q "SELECT count() FROM t2" +flush_events "$query_id" + +$CLICKHOUSE_CLIENT -q "DROP TABLE t1 SYNC" +$CLICKHOUSE_CLIENT -q "DROP TABLE t2 SYNC" diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference new file mode 100644 index 000000000000..78981922613b --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.reference @@ -0,0 +1 @@ +a diff --git a/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql new file mode 100644 index 000000000000..7546f3b71464 --- /dev/null +++ b/tests/queries/0_stateless/05876_dictionary_remote_source_over_distributed_with_secret.sql @@ -0,0 +1,25 @@ +-- Tags: no-fasttest +-- no-fasttest: the cluster secret requires SSL + +-- A remote (non-local) ClickHouse dictionary source sends its query without `initial_user`, +-- and the remote server has to forward it over a cluster with a secret. + +DROP DICTIONARY IF EXISTS dict; +DROP TABLE IF EXISTS dist; +DROP TABLE IF EXISTS data; + +CREATE TABLE data (key UInt64, value String) ENGINE = MergeTree ORDER BY key; +INSERT INTO data VALUES (1, 'a'); +CREATE TABLE dist AS data ENGINE = Distributed(test_cluster_interserver_secret, currentDatabase(), data); + +CREATE DICTIONARY dict (key UInt64, value String) +PRIMARY KEY key +SOURCE(CLICKHOUSE(HOST '127.0.0.2' PORT tcpPort() DB currentDatabase() TABLE 'dist')) +LAYOUT(HASHED()) +LIFETIME(0); + +SELECT dictGet('dict', 'value', 1::UInt64); + +DROP DICTIONARY dict; +DROP TABLE dist; +DROP TABLE data; diff --git a/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.reference b/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.reference new file mode 100644 index 000000000000..cfb962511420 --- /dev/null +++ b/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.reference @@ -0,0 +1,7 @@ +a transform that reads a table the user cannot read +(NOT_IMPLEMENTED) +0 +a transform with a wrong number of arguments +(NOT_IMPLEMENTED) +a tokenizer that does not exist +(NOT_IMPLEMENTED) diff --git a/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.sh b/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.sh new file mode 100755 index 000000000000..3ca0fa8d0b87 --- /dev/null +++ b/tests/queries/0_stateless/05876_hypothetical_index_unsupported_type_first.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# an unsupported hypothetical index type is rejected before its arguments are analyzed + +user="u_${CLICKHOUSE_DATABASE}" +$CLICKHOUSE_CLIENT -n -q " + CREATE TABLE events (id UInt32, val String) ENGINE = MergeTree ORDER BY id; + CREATE TABLE secrets (secret String) ENGINE = MergeTree ORDER BY tuple(); + INSERT INTO secrets VALUES ('hidden-value'); + DROP USER IF EXISTS ${user}; + CREATE USER ${user} NOT IDENTIFIED; + GRANT SELECT(id, val), SHOW COLUMNS ON ${CLICKHOUSE_DATABASE}.events TO ${user}; +" + +create_index() +{ + $CLICKHOUSE_CLIENT --user "${user}" -q "CREATE HYPOTHETICAL INDEX i ON ${CLICKHOUSE_DATABASE}.events (val) TYPE $1" 2>&1 +} + +echo "a transform that reads a table the user cannot read" +out=$(create_index "text(tokenizer = array, preprocessor = concat(val, toString((SELECT CAST(secret AS Enum8('na' = 1)) FROM ${CLICKHOUSE_DATABASE}.secrets LIMIT 1))))") +echo "$out" | grep -o '([A-Z_]*)' | tail -1 +echo "$out" | grep -c 'hidden-value' + +echo "a transform with a wrong number of arguments" +create_index "text(tokenizer = array, preprocessor = lower(val, val))" | grep -o '([A-Z_]*)' | tail -1 + +echo "a tokenizer that does not exist" +create_index "text(tokenizer = no_such_tokenizer)" | grep -o '([A-Z_]*)' | tail -1 + +$CLICKHOUSE_CLIENT -q "DROP USER ${user}" diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.reference b/tests/queries/0_stateless/05877_forged_interserver_interface.reference new file mode 100644 index 000000000000..3e43aed0dcab --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.reference @@ -0,0 +1,2 @@ +forged interface: query accepted +1 diff --git a/tests/queries/0_stateless/05877_forged_interserver_interface.sh b/tests/queries/0_stateless/05877_forged_interserver_interface.sh new file mode 100755 index 000000000000..824717dc22bb --- /dev/null +++ b/tests/queries/0_stateless/05877_forged_interserver_interface.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +python3 - < "$base/db/inner.csv" +echo 'secret' > "$base/other/secret.csv" + +fs_db="${CLICKHOUSE_DATABASE}_fs" +${CLICKHOUSE_CLIENT} -q "CREATE DATABASE $fs_db ENGINE = Filesystem('$base/db')" + +function query() +{ + ${CLICKHOUSE_CLIENT} -q "$1" 2>&1 | grep -o -m1 -e 'PATH_ACCESS_DENIED' -e '^[a-z01]*$' +} + +echo "-- inside" +query "SELECT * FROM $fs_db.\`inner.csv\`" +query "SELECT * FROM $fs_db.\`sub/../inner.csv\`" +query "SELECT * FROM $fs_db.\`{inner,missing}.csv\`" +query "EXISTS TABLE $fs_db.\`inner.csv\`" + +echo "-- outside" +query "SELECT * FROM $fs_db.\`../other/secret.csv\`" +query "SELECT * FROM $fs_db.\`$base/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`../other/*.csv\`" +query "SELECT * FROM $fs_db.\`{..,sub}/other/secret.csv\`" +query "SELECT * FROM $fs_db.\`{../other/secret,inner}.csv\`" +query "EXISTS TABLE $fs_db.\`../other/secret.csv\`" +query "EXISTS TABLE $fs_db.\`../other/missing.csv\`" + +${CLICKHOUSE_CLIENT} -q "DROP DATABASE $fs_db" +rm -rf "$base" diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference new file mode 100644 index 000000000000..2f72dd2c0684 --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.reference @@ -0,0 +1,18 @@ +-- _headers before another virtual column +hello / 1 +-- _headers between other virtual columns +/ hello 1 +-- _headers after the other virtual columns +/ hello 1 +-- _headers in SELECT, another virtual column in WHERE +hello 1 +-- the query of the AST fuzzer, with the condition negated to get a row +1 1 +-- _headers before all the other virtual columns +hello 1 1 / 1 +-- the number of rows is in the cache +1 +-- only virtual columns, _headers before another virtual column +hello / +-- only virtual columns, _headers after another virtual column +/ hello diff --git a/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql new file mode 100644 index 000000000000..2b656def13df --- /dev/null +++ b/tests/queries/0_stateless/05878_url_headers_virtual_column_order.sql @@ -0,0 +1,50 @@ +-- The `url` table function added the `_headers` virtual column to its chunks after all the other +-- virtual columns, while the header of the source lists the virtual columns in the order they are +-- requested in. With `_headers` requested before another virtual column, the query read one column +-- in place of the other: an exception about the type of a column at best, a server crash otherwise. + +-- The HTTP interface adds the header of the `http_response_headers` setting, `{'X-Test':'hello'}`, to its response. + +SELECT '-- _headers before another virtual column'; +SELECT _headers['X-Test'], _path, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers between other virtual columns'; +SELECT _path, _headers['X-Test'], _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers after the other virtual columns'; +SELECT _path, _file, _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- _headers in SELECT, another virtual column in WHERE'; +SELECT _headers['X-Test'], s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE _path = '/'; + +SELECT '-- the query of the AST fuzzer, with the condition negated to get a row'; +SELECT empty(_headers['X-Long']), s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String') +WHERE NOT isNotDistinctFrom(_size, true); + +-- The HTTP interface does not tell the size and the modification time of its response. +SELECT '-- _headers before all the other virtual columns'; +SELECT _headers['X-Test'], _size IS NULL OR _size > 0, _time IS NULL OR _time > '2000-01-01 00:00:00', _path, _file, s +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +-- A read of only virtual columns takes the number of rows from the cache without a request for the +-- data, and `_headers` was empty then, while it is the headers of the response to that request. +-- The cache is used for a URL without the `Last-Modified` header only with the setting below. +SET schema_inference_cache_require_modification_time_for_url = 0; + +SELECT '-- the number of rows is in the cache'; +SELECT count() +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers before another virtual column'; +SELECT _headers['X-Test'], _path +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers after another virtual column'; +SELECT _path, _headers['X-Test'] +FROM url('http://127.0.0.1:8123/?query=SELECT+1&http_response_headers=%7B%27X-Test%27%3A%27hello%27%7D', LineAsString, 's String'); diff --git a/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.reference b/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.reference new file mode 100644 index 000000000000..218e8c2ec963 --- /dev/null +++ b/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.reference @@ -0,0 +1,23 @@ +-- _headers before another virtual column +hello 12 part1.tsv hello +hello 12 part1.tsv world +-- _headers between other virtual columns +part1.tsv hello 12 hello +part1.tsv hello 12 world +-- _headers after the other virtual columns +part1.tsv 12 hello hello +part1.tsv 12 hello world +-- _headers in SELECT, another virtual column in WHERE +hello hello +hello world +-- the query of the AST fuzzer, with the condition negated to get rows +1 hello +1 world +-- the number of rows is in the cache +2 +-- only virtual columns, _headers before other virtual columns +hello 12 part1.tsv +hello 12 part1.tsv +-- only virtual columns, _headers after other virtual columns +part1.tsv 12 hello +part1.tsv 12 hello diff --git a/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.sh b/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.sh new file mode 100755 index 000000000000..c51e4b0abb27 --- /dev/null +++ b/tests/queries/0_stateless/05879_url_wildcard_headers_virtual_column_order.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: needs a local HTTP server serving index pages. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# A `url` with a listable glob in the path is read by the object storage over HTTP index pages. Its +# source added the `_headers` virtual column to its chunks after all the other virtual columns, +# while the header of the source lists the virtual columns in the order they are requested in. With +# `_headers` requested before another virtual column, the query read one column in place of the +# other: an exception about the type of a column at best, a server crash otherwise. + +HTTP_PORT=$(python3 -c " +import socket +s = socket.socket() +s.bind(('127.0.0.1', 0)) +print(s.getsockname()[1]) +s.close() +") + +# An index page listing one part, and a response header to look for in `_headers`. +python3 -c " +from http.server import HTTPServer, BaseHTTPRequestHandler + +PARTS = {'/data/part1.tsv': b'hello\nworld\n'} +INDEX = b'part1.tsv\n' + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def body(self): + path = self.path.split('?')[0] + if path == '/data/': + return INDEX, 'text/html' + return PARTS.get(path), 'text/plain' + + def respond(self, with_body): + data, content_type = self.body() + if data is None: + self.send_response(404) + self.end_headers() + if with_body: + self.wfile.write(b'Not Found') + return + # The part can be read with a range request, depending on the settings. + rng = self.headers.get('Range') + status = 200 + if rng: + begin, end = rng.split('=')[1].split('-') + begin = int(begin) + end = min(int(end), len(data) - 1) if end else len(data) - 1 + content_range = 'bytes %d-%d/%d' % (begin, end, len(data)) + data = data[begin:end + 1] + status = 206 + self.send_response(status) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(len(data))) + self.send_header('Accept-Ranges', 'bytes') + if status == 206: + self.send_header('Content-Range', content_range) + self.send_header('Last-Modified', 'Thu, 01 Jan 2026 00:00:00 GMT') + self.send_header('X-Test', 'hello') + self.end_headers() + if with_body: + try: + self.wfile.write(data) + except (BrokenPipeError, ConnectionResetError): + pass + + def do_HEAD(self): + self.respond(False) + + def do_GET(self): + self.respond(True) + +HTTPServer(('127.0.0.1', $HTTP_PORT), Handler).serve_forever() +" & +HTTP_PID=$! +trap "kill $HTTP_PID 2>/dev/null; wait $HTTP_PID 2>/dev/null" EXIT + +for _ in $(seq 1 50); do + curl -s "http://127.0.0.1:$HTTP_PORT/data/" -o /dev/null 2>/dev/null && break + sleep 0.1 +done + +GLOB_URL="http://127.0.0.1:${HTTP_PORT}/data/*.tsv" + +$CLICKHOUSE_CLIENT -q " +SET allow_experimental_url_wildcard_from_index_pages = 1; +SET http_max_tries = 1; + +SELECT '-- _headers before another virtual column'; +SELECT _headers['X-Test'], _size, _file, s +FROM url('${GLOB_URL}', LineAsString, 's String') ORDER BY s; + +SELECT '-- _headers between other virtual columns'; +SELECT _file, _headers['X-Test'], _size, s +FROM url('${GLOB_URL}', LineAsString, 's String') ORDER BY s; + +SELECT '-- _headers after the other virtual columns'; +SELECT _file, _size, _headers['X-Test'], s +FROM url('${GLOB_URL}', LineAsString, 's String') ORDER BY s; + +SELECT '-- _headers in SELECT, another virtual column in WHERE'; +SELECT _headers['X-Test'], s +FROM url('${GLOB_URL}', LineAsString, 's String') WHERE _size = 12 ORDER BY s; + +SELECT '-- the query of the AST fuzzer, with the condition negated to get rows'; +SELECT empty(_headers['X-Long']), s +FROM url('${GLOB_URL}', LineAsString, 's String') WHERE NOT isNotDistinctFrom(_size, true) ORDER BY s; + +-- A read of only virtual columns can take the number of rows from the cache, without a request for +-- the data, but not if \`_headers\` is requested: it is the headers of the response to that request. +SELECT '-- the number of rows is in the cache'; +SELECT count() +FROM url('${GLOB_URL}', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers before other virtual columns'; +SELECT _headers['X-Test'], _size, _file +FROM url('${GLOB_URL}', LineAsString, 's String'); + +SELECT '-- only virtual columns, _headers after other virtual columns'; +SELECT _file, _size, _headers['X-Test'] +FROM url('${GLOB_URL}', LineAsString, 's String'); +" diff --git a/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.reference b/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.reference new file mode 100644 index 000000000000..e0a0b3d677db --- /dev/null +++ b/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.reference @@ -0,0 +1,62 @@ +short name, sampling +0 +1 +2 +3 +4 +5 +6 +7 +8 +short name, range +0 +1 +2 +3 +4 +5 +6 +7 +8 +alias +0 +1 +2 +3 +4 +5 +6 +7 +8 +subquery +0 +1 +2 +3 +4 +5 +6 +7 +8 +old analyzer, MergeTree +0 +1 +2 +3 +4 +5 +6 +7 +8 +45 180 +old analyzer, ReplicatedMergeTree +0 +1 +2 +3 +4 +5 +6 +7 +8 +45 180 diff --git a/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.sql b/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.sql new file mode 100644 index 000000000000..87cdd89faf6d --- /dev/null +++ b/tests/queries/0_stateless/05961_custom_key_parallel_replicas_additional_table_filters.sql @@ -0,0 +1,63 @@ +-- Tags: zookeeper +-- Tag zookeeper: uses ReplicatedMergeTree. + +-- A read with parallel replicas with a custom key is sent to the replicas as query text. A replica must not return +-- the rows excluded by `additional_table_filters` when it would match the filter differently: by the short table +-- name against its own current database, or by an alias the shipped query renames. + +DROP TABLE IF EXISTS t; +CREATE TABLE t (k UInt32, v UInt32) ENGINE = MergeTree ORDER BY k; +INSERT INTO t SELECT number, number % 12 FROM numbers(60); + +SET max_parallel_replicas = 3, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost', + parallel_replicas_for_non_replicated_merge_tree = 1, enable_parallel_replicas = 1; + +SELECT 'short name, sampling'; +SELECT DISTINCT v FROM t ORDER BY v +SETTINGS additional_table_filters = {'t': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT 'short name, range'; +SELECT DISTINCT v FROM t ORDER BY v +SETTINGS additional_table_filters = {'t': 'v < 9'}, parallel_replicas_mode = 'custom_key_range', parallel_replicas_custom_key = 'k'; + +SELECT 'alias'; +SELECT DISTINCT v FROM t AS a ORDER BY v +SETTINGS additional_table_filters = {'a': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT 'subquery'; +SELECT DISTINCT v FROM (SELECT v FROM t) ORDER BY v +SETTINGS additional_table_filters = {'t': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +-- Parallel replicas are required, but the custom-key read cannot keep the filters. +SELECT DISTINCT v FROM t ORDER BY v +SETTINGS additional_table_filters = {'t': 'v < 9'}, enable_parallel_replicas = 2, + parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; -- { serverError SUPPORT_IS_DISABLED } + +SELECT 'old analyzer, MergeTree'; +SELECT DISTINCT v FROM t ORDER BY v +SETTINGS enable_analyzer = 0, additional_table_filters = {'t': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT count(), sum(v) FROM t +SETTINGS enable_analyzer = 0, additional_table_filters = {'t': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT DISTINCT v FROM t ORDER BY v +SETTINGS enable_analyzer = 0, additional_table_filters = {'t': 'v < 9'}, enable_parallel_replicas = 2, + parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; -- { serverError SUPPORT_IS_DISABLED } + +DROP TABLE IF EXISTS tr; +CREATE TABLE tr (k UInt32, v UInt32) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{database}/05961_tr', 'r1') ORDER BY k; +INSERT INTO tr SELECT number, number % 12 FROM numbers(60); + +SELECT 'old analyzer, ReplicatedMergeTree'; +SELECT DISTINCT v FROM tr ORDER BY v +SETTINGS enable_analyzer = 0, additional_table_filters = {'tr': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT count(), sum(v) FROM tr +SETTINGS enable_analyzer = 0, additional_table_filters = {'tr': 'v < 9'}, parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; + +SELECT DISTINCT v FROM tr ORDER BY v +SETTINGS enable_analyzer = 0, additional_table_filters = {'tr': 'v < 9'}, enable_parallel_replicas = 2, + parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'v'; -- { serverError SUPPORT_IS_DISABLED } + +DROP TABLE tr; +DROP TABLE t; diff --git a/tests/queries/0_stateless/05961_lz4_empty_output.reference b/tests/queries/0_stateless/05961_lz4_empty_output.reference new file mode 100644 index 000000000000..b73d93459ced --- /dev/null +++ b/tests/queries/0_stateless/05961_lz4_empty_output.reference @@ -0,0 +1,5 @@ +11 +0 +0 +1 +2 diff --git a/tests/queries/0_stateless/05961_lz4_empty_output.sh b/tests/queries/0_stateless/05961_lz4_empty_output.sh new file mode 100755 index 000000000000..48979d0440ee --- /dev/null +++ b/tests/queries/0_stateless/05961_lz4_empty_output.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Zero rows written to a `.lz4` file must produce a valid empty LZ4 frame: +# since lz4 v1.11.0, `LZ4F_compressEnd` fails if the frame header was not written. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +FILE_NAME="${CLICKHOUSE_DATABASE}_05961.tsv.lz4" +FILE_PATH="${USER_FILES_PATH}/${FILE_NAME}" +rm -f "${FILE_PATH}" + +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION file('${FILE_NAME}', 'TSV', 'x UInt64') SELECT number FROM numbers(0)" +# The frame header (7 bytes with the preferences that ClickHouse uses) and the end mark (4 bytes). +wc -c < "${FILE_PATH}" | tr -d ' ' +${CLICKHOUSE_CLIENT} --query "SELECT count() FROM file('${FILE_NAME}', 'TSV', 'x UInt64')" + +${CLICKHOUSE_CLIENT} --query "INSERT INTO FUNCTION file('${FILE_NAME}', 'TSV', 'x UInt64') SELECT number FROM numbers(3) SETTINGS engine_file_truncate_on_insert = 1" +${CLICKHOUSE_CLIENT} --query "SELECT x FROM file('${FILE_NAME}', 'TSV', 'x UInt64') ORDER BY x" + +rm -f "${FILE_PATH}" diff --git a/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.reference b/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.reference new file mode 100644 index 000000000000..049be43d54e8 --- /dev/null +++ b/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.reference @@ -0,0 +1,14 @@ +A lease that can be parked +materialized CTE +10000000 9999999 +materialized CTE built for the primary key analysis +99990 +dictGet on a direct dictionary +10 +A lease that cannot be parked +materialized CTE +10000000 9999999 +materialized CTE built for the primary key analysis +99990 +dictGet on a direct dictionary +10 diff --git a/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.sh b/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.sh new file mode 100755 index 000000000000..6909eee03943 --- /dev/null +++ b/tests/queries/0_stateless/05978_nested_executor_on_outer_cpu_lease.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Tags: no-parallel +# no-parallel: the server allows only one MASTER THREAD / WORKER THREAD resource at a time + +# A processor can run a nested pipeline on a thread of the outer executor, which already runs on a CPU lease: +# the writer of a materialized CTE, or `dictGet` on a `direct` dictionary. The nested executor must not take a CPU slot +# of its own: in a workload with one slot it would wait for the slot that this thread holds. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +WORKLOAD="${CLICKHOUSE_DATABASE}_one_slot" +# Not per database: `CREATE OR REPLACE` then also replaces the resource of a killed run +RESOURCE="test_05978_cpu" + +cleanup() +{ + $CLICKHOUSE_CLIENT -q "KILL QUERY WHERE query_id LIKE '${CLICKHOUSE_DATABASE}_nested_%' FORMAT Null" 2>/dev/null + $CLICKHOUSE_CLIENT -q "DROP DICTIONARY IF EXISTS d" 2>/dev/null + $CLICKHOUSE_CLIENT -q "DROP WORKLOAD IF EXISTS ${WORKLOAD}" 2>/dev/null + $CLICKHOUSE_CLIENT -q "DROP RESOURCE IF EXISTS ${RESOURCE}" 2>/dev/null + $CLICKHOUSE_CLIENT -q "DROP RESOURCE IF EXISTS ${RESOURCE}_worker" 2>/dev/null +} +trap cleanup EXIT + +# The aggregation in the view makes one lookup of the dictionary take several CPU quanta. +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k; + INSERT INTO t SELECT number FROM numbers(100000); + CREATE VIEW v AS SELECT number % 10 AS k, sum(cityHash64(number)) AS v FROM numbers(10000000) GROUP BY k; + CREATE DICTIONARY d (k UInt64, v UInt64) PRIMARY KEY k + SOURCE(CLICKHOUSE(TABLE 'v' DB '${CLICKHOUSE_DATABASE}')) LAYOUT(DIRECT()); + + DROP RESOURCE IF EXISTS ${RESOURCE}_worker; + CREATE OR REPLACE RESOURCE ${RESOURCE} (MASTER THREAD, WORKER THREAD); + CREATE WORKLOAD ${WORKLOAD} SETTINGS max_concurrent_threads = 1; +" + +run() +{ + timeout 60 $CLICKHOUSE_CLIENT --query_id "${CLICKHOUSE_DATABASE}_nested_$1" -q "$2 + SETTINGS workload = '${WORKLOAD}', use_concurrency_control = 1, max_threads = $3, enable_materialized_cte = 1" \ + || echo "The query has failed or has not finished" +} + +queries() +{ + echo "materialized CTE" + # A CTE referenced once is inlined, so it is referenced twice to be materialized. + run "cte_$1" " + WITH c AS MATERIALIZED (SELECT number FROM numbers(10000000)) + SELECT count(), any(b.m) FROM c AS a, (SELECT max(number) AS m FROM c) AS b" 8 + + echo "materialized CTE built for the primary key analysis" + # The sets for the primary key are built at planning time, by a pipeline that materializes the CTE. + run "cte_planning_$1" " + WITH c AS MATERIALIZED (SELECT number AS k, repeat(toString(number), 20) AS w FROM numbers(2000000)) + SELECT count() FROM t WHERE k IN (SELECT k FROM c WHERE length(w) > 0) AND k NOT IN (SELECT k FROM c WHERE k < 10)" 8 + + echo "dictGet on a direct dictionary" + run "dict_$1" "SELECT countIf(dictGet('d', 'v', number) != 0) FROM numbers(10)" 1 +} + +echo "A lease that can be parked" +queries parkable + +# Separate resources for the master thread and for the worker threads make the leases not parkable. +$CLICKHOUSE_CLIENT -m -q " + DROP WORKLOAD ${WORKLOAD}; + DROP RESOURCE ${RESOURCE}; + CREATE RESOURCE ${RESOURCE} (MASTER THREAD); + CREATE RESOURCE ${RESOURCE}_worker (WORKER THREAD); + CREATE WORKLOAD ${WORKLOAD} SETTINGS max_concurrent_threads = 1; +" + +echo "A lease that cannot be parked" +queries not_parkable diff --git a/tests/queries/0_stateless/05978_view_definer_named_current_user.reference b/tests/queries/0_stateless/05978_view_definer_named_current_user.reference new file mode 100644 index 000000000000..187c10dc81ed --- /dev/null +++ b/tests/queries/0_stateless/05978_view_definer_named_current_user.reference @@ -0,0 +1,14 @@ +CREATE VIEW v\nDEFINER = `CURRENT_USER` SQL SECURITY DEFINER\nAS SELECT 1 +CREATE VIEW v\nDEFINER = `current_user`@\'h05978\' SQL SECURITY DEFINER\nAS SELECT 1 +ALTER TABLE v\n (MODIFY DEFINER = `Current_User` SQL SECURITY DEFINER) +CREATE VIEW v\nDEFINER = CURRENT_USER SQL SECURITY DEFINER\nAS SELECT 1 +mv current_user@h05978 +v1 CURRENT_USER +v2 CURRENT_USER +v3 CURRENT_USER +1 +2 +3 +v: Cannot resolve DEFINER = CURRENT_USER +mv: Cannot resolve DEFINER = CURRENT_USER +r: Cannot resolve DEFINER = CURRENT_USER diff --git a/tests/queries/0_stateless/05978_view_definer_named_current_user.sh b/tests/queries/0_stateless/05978_view_definer_named_current_user.sh new file mode 100755 index 000000000000..1f9117f2623c --- /dev/null +++ b/tests/queries/0_stateless/05978_view_definer_named_current_user.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Tags: no-parallel +# no-parallel: the users have fixed names + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +db=${CLICKHOUSE_DATABASE} + +${CLICKHOUSE_CLIENT} <&1 | grep -o -m 1 -F 'Cannot resolve DEFINER = CURRENT_USER')" +} + +check_stored_definer v "CREATE VIEW db.v SQL SECURITY INVOKER AS SELECT 1 AS x" "SELECT * FROM db.v" +check_stored_definer mv "CREATE TABLE db.source (x Int64) ENGINE = Memory; CREATE MATERIALIZED VIEW db.mv ENGINE = Memory SQL SECURITY NONE AS SELECT x FROM db.source" "SELECT * FROM db.mv" +check_stored_definer r "CREATE TABLE db.r (query String) ENGINE = QueryRunner SQL SECURITY INVOKER" "INSERT INTO db.r VALUES ('SELECT 1')" + +rm -rf "${WORKING_DIR}" diff --git a/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.reference b/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.reference new file mode 100644 index 000000000000..284c3518cc6f --- /dev/null +++ b/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.reference @@ -0,0 +1,5 @@ +--- with a CA --- +OK: the connection was refused +--- without TLS credentials --- +--- handshake responses --- +handshake response from user user_without_ca diff --git a/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.sh b/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.sh new file mode 100755 index 000000000000..10c6b7b352d3 --- /dev/null +++ b/tests/queries/0_stateless/05979_mysql_tls_required_with_ca.sh @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# Tag no-fasttest: the fast test is built with `ENABLE_LIBRARIES=0`, so it has no MySQL client. + +# With a CA configured, a MySQL server that does not offer TLS (or a greeting with the TLS capability +# removed on the way) must not get the handshake response with the user and the password. +# A fake MySQL server greets without `CLIENT_SSL` and records the user of every handshake response. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +STUB="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_mysql_stub.py" +LOG="${CLICKHOUSE_TMP}/${CLICKHOUSE_TEST_UNIQUE_NAME}_mysql_stub.log" + +cat > "$STUB" <<'PYEOF' +import socket +import struct +import sys + +PORT = int(sys.argv[1]) +LOG = sys.argv[2] + +# `CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB | CLIENT_PROTOCOL_41 +# | CLIENT_TRANSACTIONS | CLIENT_SECURE_CONNECTION | CLIENT_PLUGIN_AUTH`, without `CLIENT_SSL`. +CAPABILITIES = 0x1 | 0x4 | 0x8 | 0x200 | 0x2000 | 0x8000 | 0x80000 + + +def recv_exact(sock, size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + return None + data += chunk + return data + + +def handshake_packet(): + payload = b"\x0a" + b"8.0.0-fake\x00" + struct.pack("> 16) + bytes([21]) + b"\x00" * 10 + payload += bytes(range(9, 21)) + b"\x00" + b"mysql_native_password\x00" + return struct.pack("/dev/null; wait ${STUB_PID} 2>/dev/null; rm -f "${STUB}" "${LOG}"' EXIT + +for _ in $(seq 1 100); do + if python3 -c " +import socket, sys +sys.exit(0 if socket.socket().connect_ex(('127.0.0.1', ${PORT})) == 0 else 1) +" 2>/dev/null; then + break + fi + sleep 0.1 +done + +# The content of the CA is not read: the connection fails before TLS would start. +echo "--- with a CA ---" +ERROR=$(${CLICKHOUSE_CLIENT} -q "SELECT * FROM mysql('127.0.0.1:${PORT}', 'db', 't', 'user_with_ca', 'password', ssl_ca_pem = 'not a certificate')" 2>&1) +if grep -qF "SSL is required, but the server does not support it" <<< "$ERROR" +then + echo "OK: the connection was refused" +else + echo "FAIL: got: $ERROR" +fi + +# Without TLS credentials TLS is optional, so the handshake response is sent: this shows the server works. +echo "--- without TLS credentials ---" +${CLICKHOUSE_CLIENT} -q "SELECT * FROM mysql('127.0.0.1:${PORT}', 'db', 't', 'user_without_ca', 'password')" > /dev/null 2>&1 + +echo "--- handshake responses ---" +sort -u "$LOG" 2>/dev/null diff --git a/tests/queries/0_stateless/05995_native_insert_tuple_of_another_size.python b/tests/queries/0_stateless/05995_native_insert_tuple_of_another_size.python new file mode 100644 index 000000000000..9e7f9ee928fe --- /dev/null +++ b/tests/queries/0_stateless/05995_native_insert_tuple_of_another_size.python @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# With `input_format_native_allow_types_conversion = 0`, a column of a `Native` block whose type +# differs from the type of the table's column is not converted. The server only relabels it with the +# type of the table, and only for a difference in `LowCardinality`, which it packs or unpacks to +# accept the data of old clients. +# +# A tuple with another number of elements must be rejected. One with fewer elements used to pass, +# because only the elements it has were compared with the elements of the table's tuple. The block +# went on with a column of one element under a type of two, and reading the missing element is an +# out-of-bounds access, in the insert pipeline as well as in the flush of an asynchronous insert. +# +# `clickhouse-client` converts the data to the structure of the table before sending it, so the test +# speaks the raw native protocol. The revision is pinned to an old one, 54449: the set of exchanged +# revision-gated fields is then fixed and small. + +import os +import socket +import struct +import uuid + +CLICKHOUSE_HOST = os.environ.get("CLICKHOUSE_HOST", "127.0.0.1") +CLICKHOUSE_PORT = int(os.environ.get("CLICKHOUSE_PORT_TCP", "9000")) +CLICKHOUSE_DATABASE = os.environ.get("CLICKHOUSE_DATABASE", "default") +CLIENT_NAME = "tuple of another size" + +CLIENT_REVISION = 54449 + +TYPE_MISMATCH = 53 + +# Protocol::Client +CLIENT_HELLO = 0 +CLIENT_QUERY = 1 +CLIENT_DATA = 2 + +# Protocol::Server +SERVER_HELLO = 0 +SERVER_DATA = 1 +SERVER_EXCEPTION = 2 +SERVER_PROGRESS = 3 +SERVER_END_OF_STREAM = 5 +SERVER_TABLE_COLUMNS = 11 + + +def writeVarUInt(x, ba): + for _ in range(0, 9): + byte = x & 0x7F + if x > 0x7F: + byte |= 0x80 + ba.append(byte) + x >>= 7 + if x == 0: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") + writeVarUInt(len(b), ba) + ba.extend(b) + + +def readStrict(s, size=1): + res = bytearray() + while size: + cur = s.recv(size) + if not cur: + raise EOFError("Connection closed by server") + size -= len(cur) + res.extend(cur) + return res + + +def readUInt8(s): + return readStrict(s)[0] + + +def readUInt32(s): + return struct.unpack(" FakePeer: LogMessageOfFakePeer +log_extra_column: exit code 0, Log block have different structure +log_sparse_column: exit code 0, Log block have different structure +The server is alive diff --git a/tests/queries/0_stateless/05995_remote_profile_events_and_log_block_structure.sh b/tests/queries/0_stateless/05995_remote_profile_events_and_log_block_structure.sh new file mode 100755 index 000000000000..fd0aa9a3be81 --- /dev/null +++ b/tests/queries/0_stateless/05995_remote_profile_events_and_log_block_structure.sh @@ -0,0 +1,263 @@ +#!/usr/bin/env bash + +# The warnings of the server are a part of what is checked. +CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=warning + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# The blocks of the `ProfileEvents` and `Log` packets are laid out by the server that sends them, while +# the receiving server appends their columns by position to the columns of its own packets, without a +# check of their types, and forwards the result to the client. So a block of any other structure than +# the expected one must not get that far: such `ProfileEvents` are refused, and such `Log` is dropped. +# +# The remote server here is a script that speaks just enough of the native protocol: it answers the +# handshake and then, whatever it is asked for, sends one packet and the end of the stream. The name +# of the user selects the packet. + +PEER_SCRIPT="${CLICKHOUSE_TMP}/05995_peer_${CLICKHOUSE_DATABASE}.py" +PEER_PORT_FILE="${CLICKHOUSE_TMP}/05995_peer_${CLICKHOUSE_DATABASE}.port" + +rm -f "$PEER_PORT_FILE" + +cat > "$PEER_SCRIPT" <<'EOF' +import os +import socket +import struct +import sys +import threading + +port_file = sys.argv[1] + +# The packets of the server. +HELLO = 0 +END_OF_STREAM = 5 +LOG = 10 +PROFILE_EVENTS = 14 + +# `ProfileEvents` of the present form are sent since this revision of the protocol. +REVISION = 54451 +# Since this revision the sender tells the kind of serialization of every column. +REVISION_WITH_CUSTOM_SERIALIZATION = 54454 + +DEFAULT = 0 +SPARSE = 1 + + +def varuint(value): + result = bytearray() + while value >= 0x80: + result.append((value & 0x7F) | 0x80) + value >>= 7 + result.append(value) + return bytes(result) + + +def string(value): + return varuint(len(value)) + value + + +def column(name, type_name, data, kind=DEFAULT): + return (name, type_name, data, kind) + + +# One default value in the sparse serialization: no values, only the number of the defaults +# at the end of a granule. +END_OF_GRANULE_FLAG = 1 << 62 +SPARSE_THREAD_ID = column(b"thread_id", b"UInt64", varuint(END_OF_GRANULE_FLAG | 1), SPARSE) +THREAD_ID = column(b"thread_id", b"UInt64", struct.pack(" the revision of the protocol, the packet and the columns of its block. +SCENARIOS = { + "expected": (REVISION, PROFILE_EVENTS, [HOST_NAME, CURRENT_TIME, THREAD_ID, TYPE, NAME, VALUE]), + "extra_column": (REVISION, PROFILE_EVENTS, [HOST_NAME, CURRENT_TIME, THREAD_ID, TYPE, NAME, VALUE, EXTRA]), + "missing_column": (REVISION, PROFILE_EVENTS, [HOST_NAME, CURRENT_TIME, THREAD_ID, TYPE, NAME]), + "no_columns": (REVISION, PROFILE_EVENTS, []), + "another_order": (REVISION, PROFILE_EVENTS, [HOST_NAME, CURRENT_TIME, THREAD_ID, TYPE, VALUE, NAME]), + "another_name": ( + REVISION, + PROFILE_EVENTS, + [HOST_NAME, CURRENT_TIME, THREAD_ID, TYPE, NAME, column(b"amount", b"Int64", struct.pack("= REVISION_WITH_CUSTOM_SERIALIZATION: + packet += b"\x00" if kind == DEFAULT else b"\x01" + bytes([kind]) + packet += data + return packet + + +def read_exactly(reader, size): + data = reader.read(size) + if len(data) != size: + raise EOFError + return data + + +def read_varuint(reader): + result = 0 + shift = 0 + while True: + byte = read_exactly(reader, 1)[0] + result |= (byte & 0x7F) << shift + if not byte & 0x80: + return result + shift += 7 + + +def read_string(reader): + return read_exactly(reader, read_varuint(reader)) + + +def serve(connection): + try: + reader = connection.makefile("rb") + + # The hello of the client: the type of the packet, the name and the version of the client, + # the default database, the user and the password. + read_varuint(reader) + read_string(reader) + for _ in range(3): + read_varuint(reader) + read_string(reader) + revision, packet_type, columns = SCENARIOS[read_string(reader).decode()] + read_string(reader) + + connection.sendall(hello(revision)) + + # The answer does not depend on the query, so it is sent as soon as the query begins to arrive. + read_exactly(reader, 1) + connection.sendall(packet_with_block(packet_type, revision, columns) + varuint(END_OF_STREAM)) + + # The other side closes the connection, so that it reads the whole answer before that. + while reader.read(65536): + pass + except (OSError, EOFError, KeyError): + pass + finally: + connection.close() + + +listener = socket.socket() +listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +listener.bind(("127.0.0.1", 0)) +listener.listen(16) + +with open(port_file + ".tmp", "w") as f: + f.write(str(listener.getsockname()[1])) +os.rename(port_file + ".tmp", port_file) + +while True: + connection, _ = listener.accept() + threading.Thread(target=serve, args=(connection,), daemon=True).start() +EOF + +python3 "$PEER_SCRIPT" "$PEER_PORT_FILE" & +PEER_PID=$! +# shellcheck disable=SC2064 +trap "kill $PEER_PID 2>/dev/null; rm -f '$PEER_SCRIPT' '$PEER_PORT_FILE'" EXIT + +for _ in {1..300}; do + [ -s "$PEER_PORT_FILE" ] && break + sleep 0.1 +done + +PEER_PORT=$(cat "$PEER_PORT_FILE") + +SCENARIOS="expected extra_column missing_column no_columns another_order another_name another_type sparse_column previous_revision" +SCENARIOS+=" log_expected log_extra_column log_sparse_column" + +# The structure of the tables is specified, so that the server does not ask the peer for it, and +# the remote table is a table function, so that the server does not ask for its status either. +for scenario in $SCENARIOS; do + echo "CREATE TABLE peer_${scenario} (x UInt8) + AS remote('127.0.0.1:${PEER_PORT}', view(SELECT 1 AS x), '${scenario}');" +done | $CLICKHOUSE_CLIENT + +for scenario in $SCENARIOS; do + # The peer sends no data, so the result is empty. The client prints the profile events and the logs + # that it receives, which are the ones of the server and, if the server has accepted them, of the peer. + output=$($CLICKHOUSE_CLIENT --print-profile-events --query "SELECT * FROM peer_${scenario}" 2>&1) + exit_code=$? + + outcome=$(echo "$output" | grep -o -E \ + -e "ProfileEventOfFakePeer: [0-9]+ \((increment|gauge)\)" \ + -e "Unexpected structure of a block with profile events" \ + -e "<[A-Za-z]+> FakePeer: LogMessageOfFakePeer" \ + -e "Log block have different structure" \ + | sort -u) + + echo "${scenario}: exit code ${exit_code}, ${outcome:-nothing of the peer}" +done + +$CLICKHOUSE_CLIENT --query "SELECT 'The server is alive'" diff --git a/tests/queries/0_stateless/05995_stem_too_long_word.reference b/tests/queries/0_stateless/05995_stem_too_long_word.reference new file mode 100644 index 000000000000..0b739693b5f5 --- /dev/null +++ b/tests/queries/0_stateless/05995_stem_too_long_word.reference @@ -0,0 +1,5 @@ +-- A long word below the limit. +1048576 +-- One byte longer than the limit. +-- In an array. +-- In an array of Nullable. diff --git a/tests/queries/0_stateless/05995_stem_too_long_word.sql b/tests/queries/0_stateless/05995_stem_too_long_word.sql new file mode 100644 index 000000000000..892892300297 --- /dev/null +++ b/tests/queries/0_stateless/05995_stem_too_long_word.sql @@ -0,0 +1,21 @@ +-- Tags: no-fasttest +-- Tag no-fasttest: depends on libstemmer_c + +-- Snowball keeps the length of a word and the offsets inside it as `int`, +-- so `stem` accepts words of at most 64 MiB and throws an exception for longer ones. + +SELECT '-- A long word below the limit.'; +SELECT length(stem(repeat(repeat('a', 1024), 1024), 'en')); + +-- The queries below use the stemmer for Hindi, because it only looks at the end of a word, +-- and they select the length instead of the result. So if the length of a word is not checked, +-- they fail quickly instead of stemming and printing words of 64 MiB, which is very slow under sanitizers. + +SELECT '-- One byte longer than the limit.'; +SELECT length(stem(concat(repeat(repeat('a', 1024), 65536), 'a'), 'hindi')); -- { serverError TOO_LARGE_STRING_SIZE } + +SELECT '-- In an array.'; +SELECT length(stem(['word', concat(repeat(repeat('a', 1024), 65536), 'a')], 'hindi')); -- { serverError TOO_LARGE_STRING_SIZE } + +SELECT '-- In an array of Nullable.'; +SELECT length(stem([NULL, concat(repeat(repeat('a', 1024), 65536), 'a')], 'hindi')); -- { serverError TOO_LARGE_STRING_SIZE } diff --git a/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.reference b/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.reference new file mode 100644 index 000000000000..09f261c82fe3 --- /dev/null +++ b/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.reference @@ -0,0 +1,11 @@ +The server formats the result of the peer: +Template, rows in extremes: 2, result: b,a,c; min=a; max=c +Template, rows in extremes: 0, result: UNEXPECTED_PACKET_FROM_SERVER +Template, rows in extremes: 1, result: UNEXPECTED_PACKET_FROM_SERVER +Template, rows in extremes: 3, result: UNEXPECTED_PACKET_FROM_SERVER +JSONCompact, rows in extremes: 1, result: UNEXPECTED_PACKET_FROM_SERVER +The client formats the result of the peer: +Template, rows in extremes: 2, result: b,a,c; min=a; max=c +Template, rows in extremes: 0, result: INVALID_TEMPLATE_FORMAT +Template, rows in extremes: 1, result: INVALID_TEMPLATE_FORMAT +Template, rows in extremes: 3, result: INVALID_TEMPLATE_FORMAT diff --git a/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.sh b/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.sh new file mode 100755 index 000000000000..0e8ee808bac9 --- /dev/null +++ b/tests/queries/0_stateless/05995_template_extremes_row_count_from_remote.sh @@ -0,0 +1,293 @@ +#!/usr/bin/env bash + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +# Extremes are two rows: the minimums and the maximums. The block of extremes that a server gets from +# another server, or a client from its server, is not produced locally, so the number of its rows has +# to be checked before the rows are used: the `Template` format prints `${min}` and `${max}` from the +# rows 0 and 1 of this block. +# +# The peer below speaks the native protocol and answers a `SELECT` with a block of extremes of as many +# rows as the name of the table says. It is queried in two ways: +# - through the `remote` table function, where the server formats the result (the HTTP interface); +# - directly by `clickhouse-client`, where the client formats the result. + +# The names are unique per run, so that concurrent runs of this test do not interfere. +PEER_SCRIPT="${CLICKHOUSE_TMP}/05995_peer_${CLICKHOUSE_DATABASE}.py" +PEER_PORT_FILE="${CLICKHOUSE_TMP}/05995_peer_${CLICKHOUSE_DATABASE}.port" + +rm -f "$PEER_PORT_FILE" + +cat > "$PEER_SCRIPT" <<'EOF' +import functools +import os +import re +import shlex +import socket +import struct +import subprocess +import sys +import threading + +port_file = sys.argv[1] +compressor = shlex.split(os.environ["CLICKHOUSE_COMPRESSOR"]) + +# The oldest revision that the settings of a query can be sent to. The older the revision, +# the fewer fields there are in the packets. +REVISION = 54429 + +# The packets of the client +CLIENT_HELLO, CLIENT_QUERY, CLIENT_DATA, CLIENT_CANCEL, CLIENT_PING, CLIENT_TABLES_STATUS_REQUEST, CLIENT_SCALAR = 0, 1, 2, 3, 4, 5, 7 +# and of the server. +SERVER_HELLO, SERVER_DATA, SERVER_PONG, SERVER_END_OF_STREAM, SERVER_EXTREMES, SERVER_TABLES_STATUS_RESPONSE = 0, 1, 4, 5, 8, 9 + + +def varuint(value): + out = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + out.append(byte | 0x80 if value else byte) + if not value: + return bytes(out) + + +def string(value): + return varuint(len(value)) + value + + +def block(columns): + """A block of `String` columns: `[(name, [values])]`.""" + # `BlockInfo`: `is_overflows` and `bucket_num` with the default values. + out = b"\x01\x00\x02" + struct.pack("/dev/null; rm -f '$PEER_SCRIPT' '$PEER_PORT_FILE'" EXIT + +for _ in {1..300}; do + [ -s "$PEER_PORT_FILE" ] && break + sleep 0.1 +done + +PEER_PORT=$(cat "$PEER_PORT_FILE") + +# Prints the result, or the name of the error, or the beginning of the output if it is neither of them. +function result_or_error() +{ + local output + output=$(cat) + grep -o -m1 -E '^[a-z,]+; min=[a-z]; max=[a-z]$|UNEXPECTED_PACKET_FROM_SERVER|INVALID_TEMPLATE_FORMAT|LOGICAL_ERROR' <<< "$output" \ + || echo "unexpected output: ${output:0:500}" +} + +# The server passes the extremes of a remote server on only when that server runs the whole query, and the peer +# can do nothing else: it takes a query as text and answers with the final result. Two settings that some of +# the checks turn on change what the server asks for, so they are pinned: +# - with parallel replicas, the server asks for an intermediate stage of the query and finishes it by itself; +# - with `serialize_query_plan`, the server builds the plan for the remote server by itself, from a table +# of its own with this name, and the table exists only on the peer. +function query_server() +{ + local rows=$1 + local format=$2 + ${CLICKHOUSE_CURL} -sS "${CLICKHOUSE_URL}" -d " + SELECT x FROM remote('127.0.0.1:${PEER_PORT}', 'peer', 'extremes_of_${rows}_rows') + FORMAT ${format} + SETTINGS extremes = 1, enable_parallel_replicas = 0, serialize_query_plan = 0, + format_template_row_format = '\${x:Raw}', format_template_rows_between_delimiter = ',', + format_template_resultset_format = '\${data}; min=\${min}; max=\${max}'" 2>&1 +} + +function query_client() +{ + local rows=$1 + # shellcheck disable=SC2016,SC2086 + ${CLICKHOUSE_CLIENT_BINARY} --host 127.0.0.1 --port "${PEER_PORT}" --extremes 1 --format Template \ + --format_template_row_format '${x:Raw}' --format_template_rows_between_delimiter ',' \ + --format_template_resultset_format '${data}; min=${min}; max=${max}' \ + --query "SELECT x FROM extremes_of_${rows}_rows" 2>&1 +} + +echo 'The server formats the result of the peer:' +for rows in 2 0 1 3; do + echo -n "Template, rows in extremes: ${rows}, result: " + query_server "$rows" Template | result_or_error +done + +# The other formats do not get such a block either. +echo -n "JSONCompact, rows in extremes: 1, result: " +query_server 1 JSONCompact | result_or_error + +echo 'The client formats the result of the peer:' +for rows in 2 0 1 3; do + echo -n "Template, rows in extremes: ${rows}, result: " + query_client "$rows" | result_or_error +done diff --git a/tests/queries/0_stateless/helpers/fake_native_server.py b/tests/queries/0_stateless/helpers/fake_native_server.py new file mode 100644 index 000000000000..63f86ac67a43 --- /dev/null +++ b/tests/queries/0_stateless/helpers/fake_native_server.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""A fake ClickHouse server that answers the query of clickhouse-client with a crafted reply. + +It is used by the tests of what a reader of the native protocol does with a malformed result block: +a real server never sends one. The server announces `REVISION`, so the reply must use its layout. +""" + +import os +import shlex +import socket +import struct +import subprocess +import threading + +# DBMS_MIN_REVISION_WITH_REPLICATED_SERIALIZATION +REVISION = 54482 +QUERY = "SELECT 'the reply of a fake server'" + + +def writeVarUInt(x, ba): + while True: + byte = x & 0x7F + x >>= 7 + ba.append(byte | (0x80 if x else 0)) + if not x: + return + + +def writeStringBinary(s, ba): + b = bytes(s, "utf-8") + writeVarUInt(len(b), ba) + ba.extend(b) + + +def serverHello(): + ba = bytearray() + writeVarUInt(0, ba) # Hello + writeStringBinary("fake server", ba) + writeVarUInt(24, ba) # major + writeVarUInt(9, ba) # minor + writeVarUInt(REVISION, ba) + writeVarUInt(1, ba) # parallel replicas protocol version (>= 54471) + writeStringBinary("UTC", ba) # timezone (>= 54058) + writeStringBinary("fake", ba) # display name (>= 54372) + writeVarUInt(0, ba) # version patch (>= 54401) + writeStringBinary("notchunked", ba) # proto_send chunked (>= 54470) + writeStringBinary("notchunked", ba) # proto_recv chunked (>= 54470) + writeVarUInt(0, ba) # password complexity rules (>= 54461) + ba.extend(struct.pack("= 54462) + writeStringBinary("", ba) # end of the server settings (>= 54474) + writeVarUInt(0, ba) # query plan serialization version (>= 54477) + writeVarUInt(0, ba) # cluster function protocol version (>= 54479) + return bytes(ba) + + +def serveOneQuery(listener, reply): + """Answers the query of one client with `reply`, without parsing what the client sends.""" + connection, _ = listener.accept() + with connection: + connection.settimeout(60) + received = connection.recv(65536) # the Hello of the client + connection.sendall(serverHello()) + # The addendum and the Query packet follow. Once the text of the query is here, the + # client is about to wait for the result. + while QUERY.encode() not in received: + chunk = connection.recv(65536) + if not chunk: + return + received += chunk + connection.sendall(reply) + # The reply may be cut short: signal EOF so that the client gets a short read instead of + # waiting for the missing bytes, then wait until it closes the connection. + connection.shutdown(socket.SHUT_WR) + try: + while connection.recv(65536): + pass + except OSError: + pass + + +def runClientAgainstFakeServer(reply): + """The output of clickhouse-client whose server answers the query with `reply`.""" + client = shlex.split(os.environ["CLICKHOUSE_CLIENT_BINARY"]) + listener = socket.create_server(("127.0.0.1", 0)) + listener.settimeout(60) + thread = threading.Thread(target=serveOneQuery, args=(listener, reply), daemon=True) + thread.start() + try: + port = listener.getsockname()[1] + result = subprocess.run( + client + + ["--host", "127.0.0.1", "--port", str(port), "--compression", "0"] + + ["--query", QUERY], + capture_output=True, + timeout=120, + ) + return (result.stdout + result.stderr).decode("utf-8", "replace") + finally: + thread.join(timeout=60) + listener.close() diff --git a/utils/self-extracting-executable/compressor.cpp b/utils/self-extracting-executable/compressor.cpp index 33701efaf253..01ed732f1939 100644 --- a/utils/self-extracting-executable/compressor.cpp +++ b/utils/self-extracting-executable/compressor.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -7,9 +8,11 @@ #include #include #include +#include #include #include #include +#include #if defined(OS_DARWIN) && defined(__GNUC__) # include @@ -64,25 +67,26 @@ static ssize_t read_data(int fd, void *buf, size_t count) return count; } -/// Main compression part -static int doCompress(char * input, char * output, off_t & in_offset, off_t & out_offset, - off_t input_size, off_t output_size, ZSTD_CCtx * cctx) +/// Compress one block into its own zstd frame +static size_t doCompress(const char * input, off_t input_size, char * output, size_t output_size, int level) { - size_t compressed_size = ZSTD_compress2(cctx, output + out_offset, output_size, input + in_offset, input_size); - if (ZSTD_isError(compressed_size)) - { - std::cerr << "Error (ZSTD): " << compressed_size << " " << ZSTD_getErrorName(compressed_size) << std::endl; - return 1; - } - in_offset += input_size; - out_offset += compressed_size; - return 0; + ZSTD_CCtx * cctx = ZSTD_createCCtx(); + if (cctx == nullptr) + return static_cast(-ZSTD_error_memory_allocation); + + size_t result = ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level); + if (!ZSTD_isError(result)) + result = ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1); + if (!ZSTD_isError(result)) + result = ZSTD_compress2(cctx, output, output_size, input, input_size); + + ZSTD_freeCCtx(cctx); + return result; } /// compress data from opened file into output file static int compress(int in_fd, int out_fd, int level, off_t & pointer, const struct stat & info_in, uint64_t & compressed_size) { - off_t in_offset = 0; compressed_size = 0; /// mmap files @@ -93,42 +97,26 @@ static int compress(int in_fd, int out_fd, int level, off_t & pointer, const str return 1; } - /// Create context - ZSTD_CCtx * cctx = ZSTD_createCCtx(); - if (cctx == nullptr) - { - std::cerr << "Error (ZSTD): failed to create compression context" << std::endl; - return 1; - } - - size_t check_result = 0; - - /// Set level and enable checksums - check_result = ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level); - if (ZSTD_isError(check_result)) - { - std::cerr << "Error (ZSTD): " << check_result << " " << ZSTD_getErrorName(check_result) << std::endl; - ZSTD_freeCCtx(cctx); - return 1; - } - check_result = ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1); - if (ZSTD_isError(check_result)) - { - std::cerr << "Error (ZSTD): " << check_result << " " << ZSTD_getErrorName(check_result) << std::endl; - ZSTD_freeCCtx(cctx); - return 1; - } - /// limits for size of block to prevent high memory usage or bad compression off_t max_block_size = 1ull<<27; off_t min_block_size = 1ull<<23; - off_t size = 0; - off_t current_block_size = 0; - /// Create buffer for compression + /// Split input into blocks: take blocks of maximum size, + /// optimize last block (it can be bigger, if it is not too huge) + std::vector> blocks; + for (off_t in_offset = 0; in_offset < info_in.st_size;) + { + off_t size = info_in.st_size - in_offset < max_block_size + min_block_size ? info_in.st_size - in_offset : max_block_size; + blocks.emplace_back(in_offset, size); + in_offset += size; + } + + /// Blocks are independent frames, so a batch of them is compressed in parallel and written in order. /// Block can't become much bigger after compression. + size_t num_threads = std::max(1, std::min(std::thread::hardware_concurrency(), blocks.size())); + size_t output_size = 2 * max_block_size; char * output = static_cast( - mmap(nullptr, 2 * max_block_size, + mmap(nullptr, num_threads * output_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0) @@ -136,67 +124,74 @@ static int compress(int in_fd, int out_fd, int level, off_t & pointer, const str if (output == MAP_FAILED) { perror("mmap"); - ZSTD_freeCCtx(cctx); + munmap(input, info_in.st_size); return 1; } if (-1 == lseek(out_fd, 0, SEEK_END)) { perror("lseek"); - ZSTD_freeCCtx(cctx); + munmap(input, info_in.st_size); + munmap(output, num_threads * output_size); return 1; } uint64_t total_size = 0; + int ret = 0; + std::vector results(num_threads); /// Compress data - while (in_offset < info_in.st_size) + for (size_t batch_begin = 0; batch_begin < blocks.size() && ret == 0; batch_begin += num_threads) { - /// take blocks of maximum size - /// optimize last block (it can be bigger, if it is not too huge) - if (info_in.st_size - in_offset < max_block_size || info_in.st_size - in_offset < max_block_size + min_block_size) - size = info_in.st_size - in_offset; - else - size = max_block_size; - - /// Compress data or exit if error happens - if (0 != doCompress(input, output, in_offset, current_block_size, size, ZSTD_compressBound(size), cctx)) + size_t batch_size = std::min(num_threads, blocks.size() - batch_begin); + std::vector threads; + for (size_t i = 0; i < batch_size; ++i) { - if (0 != munmap(input, info_in.st_size)) - perror("munmap"); - if (0 != munmap(output, 2 * max_block_size)) - perror("munmap"); - ZSTD_freeCCtx(cctx); - return 1; + const auto & [offset, size] = blocks[batch_begin + i]; + threads.emplace_back([&, i, offset, size] + { results[i] = doCompress(input + offset, size, output + i * output_size, output_size, level); }); } + for (auto & thread : threads) + thread.join(); /// Save data into file and refresh pointer - if (current_block_size != write_data(out_fd, output, current_block_size)) + for (size_t i = 0; i < batch_size; ++i) { - perror("write"); - ZSTD_freeCCtx(cctx); - return 1; + size_t current_block_size = results[i]; + if (ZSTD_isError(current_block_size)) + { + std::cerr << "Error (ZSTD): " << current_block_size << " " << ZSTD_getErrorName(current_block_size) << std::endl; + ret = 1; + break; + } + if (static_cast(current_block_size) != write_data(out_fd, output + i * output_size, current_block_size)) + { + perror("write"); + ret = 1; + break; + } + off_t size = blocks[batch_begin + i].second; + pointer += current_block_size; + printf("...block compression rate: %.2f%%\n", static_cast(current_block_size) / static_cast(size) * 100); // NOLINT(modernize-use-std-print) + total_size += size; + compressed_size += current_block_size; } - pointer += current_block_size; - printf("...block compression rate: %.2f%%\n", static_cast(current_block_size) / static_cast(size) * 100); // NOLINT(modernize-use-std-print) - total_size += size; - compressed_size += current_block_size; - current_block_size = 0; } - std::cout << - "Compressed size: " << compressed_size << - ", compression rate: " << std::fixed << std::setprecision(2) << - static_cast(compressed_size) / static_cast(total_size) * 100 << "%" - << std::endl; if (0 != munmap(input, info_in.st_size) || - 0 != munmap(output, 2 * max_block_size)) + 0 != munmap(output, num_threads * output_size)) { perror("munmap"); - ZSTD_freeCCtx(cctx); return 1; } + if (ret != 0) + return ret; + + std::cout << + "Compressed size: " << compressed_size << + ", compression rate: " << std::fixed << std::setprecision(2) << + static_cast(compressed_size) / static_cast(total_size) * 100 << "%" + << std::endl; - ZSTD_freeCCtx(cctx); return 0; }