diff --git a/Cargo.lock b/Cargo.lock index 336d69d12547a..ee2b397c074f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli", +] + [[package]] name = "adler2" version = "2.0.1" @@ -31,6 +40,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "alloc-no-stdlib" version = "3.0.0" @@ -138,7 +156,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7eb93bbb63b9c227414f6eb3a0adfddca591a8ce1e9b60661bb08969b87e340b" dependencies = [ - "object", + "object 0.37.3", ] [[package]] @@ -159,8 +177,7 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "arrow" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5ae4998cf4c111d52898382fbe81f37213b1a420677f480c55925eddfd46217" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-arith", "arrow-array", @@ -182,8 +199,7 @@ dependencies = [ [[package]] name = "arrow-arith" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5a50de298a7c0069ad475c66db65e731df547e85a9e1e7b6e7e0bf8f0c53725" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -196,8 +212,7 @@ dependencies = [ [[package]] name = "arrow-array" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a75080e8066219ed2d1e3b8fd2eb0b1a4b35d03b6fa87fb1035e93bd8dac95" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "ahash", "arrow-buffer", @@ -216,8 +231,7 @@ dependencies = [ [[package]] name = "arrow-avro" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee843c3d6581309f43323ddb6a6e4a3a5e03b7318874128e3ab6eb6fda631ea3" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -240,8 +254,7 @@ dependencies = [ [[package]] name = "arrow-buffer" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c6bf2edf52662586214410c6030204215453eb86b8715037e8951326e173b19" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "bytes", "half", @@ -252,8 +265,7 @@ dependencies = [ [[package]] name = "arrow-cast" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcad6713dda348c245cd6ef36a578b4362c143c3a9dd829aa19e89f407c3e48b" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -274,8 +286,7 @@ dependencies = [ [[package]] name = "arrow-cmp" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e23e1092a61d7addfe57a69bf5cde7628b7b6685adea11731c19acdfd86695" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -285,8 +296,7 @@ dependencies = [ [[package]] name = "arrow-csv" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9168dc86bba5375cb5a884f684d320148c6b556db18c0dace9f1d60ac543a1" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-cast", @@ -300,8 +310,7 @@ dependencies = [ [[package]] name = "arrow-data" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a7becabdb9bf3fa058b55845c52e0f792bedc88fd0e28d6580c9730a902b60" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-buffer", "arrow-schema", @@ -313,8 +322,7 @@ dependencies = [ [[package]] name = "arrow-flight" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b91c84f077937c5f6dc351995091365e652afae67987253e25d013e3d08b758" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-arith", "arrow-array", @@ -339,8 +347,7 @@ dependencies = [ [[package]] name = "arrow-ipc" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fe9198046b67abf4e3e3ef70de2d705099975bdc2a7d9f0661675a978a083" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -355,8 +362,7 @@ dependencies = [ [[package]] name = "arrow-json" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19629d9e810280f0878738e2a361757b8ac53eae14336bb449e6879a68f71b9a" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -380,8 +386,7 @@ dependencies = [ [[package]] name = "arrow-ord" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3935eb956aeb858ab67685e167e230facd7bf4b294cf003a72d85a80edac1d2" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -394,8 +399,7 @@ dependencies = [ [[package]] name = "arrow-row" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79af8292302d7c3a1b64469a91afd33b34e7567365030098fdf4faa8130d43c3" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -407,10 +411,9 @@ dependencies = [ [[package]] name = "arrow-schema" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ - "bitflags", + "bitflags 2.11.1", "serde", "serde_core", "serde_json", @@ -419,8 +422,7 @@ dependencies = [ [[package]] name = "arrow-select" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d6a571e56e54b485b9f2d1dac4c3c34edcaffaa2668a23a7204108b66ef163d" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "ahash", "arrow-array", @@ -434,8 +436,7 @@ dependencies = [ [[package]] name = "arrow-string" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9eb6c979ef0582fd29189b66fa252e717ee32b41fd03158e801ac61005aefb9" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "arrow-array", "arrow-buffer", @@ -974,6 +975,21 @@ dependencies = [ "tower-service", ] +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object 0.40.0", + "rustc-demangle", + "windows-link", +] + [[package]] name = "base64" version = "0.21.7" @@ -1015,6 +1031,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.11.1" @@ -1069,7 +1091,7 @@ checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4" dependencies = [ "async-stream", "base64 0.22.1", - "bitflags", + "bitflags 2.11.1", "bollard-buildkit-proto", "bollard-stubs", "bytes", @@ -1187,6 +1209,12 @@ version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.0" @@ -1494,6 +1522,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpp_demangle" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" +dependencies = [ + "cfg-if", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1822,6 +1859,7 @@ dependencies = [ "mimalloc", "object_store", "parquet", + "pprof", "rand 0.9.4", "regex", "serde", @@ -2825,6 +2863,15 @@ dependencies = [ "insta", ] +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "uuid", +] + [[package]] name = "deranged" version = "0.5.8" @@ -2890,7 +2937,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags", + "bitflags 2.11.1", "objc2", ] @@ -3007,6 +3054,26 @@ dependencies = [ "log", ] +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -3113,6 +3180,18 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "findshlibs" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64" +dependencies = [ + "cc", + "lazy_static", + "libc", + "winapi", +] + [[package]] name = "fixedbitset" version = "0.5.7" @@ -3125,7 +3204,7 @@ version = "25.12.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" dependencies = [ - "bitflags", + "bitflags 2.11.1", "rustc_version", ] @@ -3360,6 +3439,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + [[package]] name = "glob" version = "0.3.4" @@ -3459,6 +3544,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -3822,6 +3913,24 @@ dependencies = [ "web-time", ] +[[package]] +name = "inferno" +version = "0.11.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88" +dependencies = [ + "ahash", + "indexmap 2.14.2", + "is-terminal", + "itoa", + "log", + "num-format", + "once_cell", + "quick-xml 0.26.0", + "rgb", + "str_stack", +] + [[package]] name = "insta" version = "1.49.0" @@ -3866,6 +3975,17 @@ dependencies = [ "serde", ] +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -4144,7 +4264,7 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" dependencies = [ - "bitflags", + "bitflags 2.11.1", "libc", "plain", "redox_syscall 0.7.4", @@ -4279,6 +4399,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + [[package]] name = "mimalloc" version = "0.1.52" @@ -4340,13 +4469,24 @@ dependencies = [ "smallvec", ] +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + [[package]] name = "nix" version = "0.31.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" dependencies = [ - "bitflags", + "bitflags 2.11.1", "cfg-if", "cfg_aliases", "libc", @@ -4358,7 +4498,7 @@ version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ - "bitflags", + "bitflags 2.11.1", "cfg-if", "cfg_aliases", "libc", @@ -4440,6 +4580,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" +[[package]] +name = "num-format" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" +dependencies = [ + "arrayvec", + "itoa", +] + [[package]] name = "num-integer" version = "0.1.46" @@ -4496,7 +4646,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags", + "bitflags 2.11.1", "dispatch2", "objc2", ] @@ -4513,7 +4663,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags", + "bitflags 2.11.1", "objc2", ] @@ -4556,6 +4706,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.14.2" @@ -4581,7 +4740,7 @@ dependencies = [ "nix 0.31.4", "parking_lot 0.12.5", "percent-encoding", - "quick-xml", + "quick-xml 0.41.0", "rand 0.10.1", "reqwest", "rustls-pki-types", @@ -4709,8 +4868,7 @@ dependencies = [ [[package]] name = "parquet" version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957" +source = "git+https://github.com/andygrove/arrow-rs?branch=polars-gap#56bf00ab5f5ddd3361ab21817504c21ff69ef7aa" dependencies = [ "ahash", "arrow-array", @@ -5019,6 +5177,28 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "pprof" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187" +dependencies = [ + "aligned-vec", + "backtrace", + "cfg-if", + "findshlibs", + "inferno", + "libc", + "log", + "nix 0.26.4", + "once_cell", + "smallvec", + "spin", + "symbolic-demangle", + "tempfile", + "thiserror", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -5146,6 +5326,15 @@ dependencies = [ "cc", ] +[[package]] +name = "quick-xml" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd" +dependencies = [ + "memchr", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -5385,7 +5574,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] [[package]] @@ -5394,7 +5583,7 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f450ad9c3b1da563fb6948a8e0fb0fb9269711c9c73d9ea1de5058c79c8d643a" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] [[package]] @@ -5403,7 +5592,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] [[package]] @@ -5527,6 +5716,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + [[package]] name = "ring" version = "0.17.14" @@ -5581,6 +5779,12 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustc-hash" version = "2.1.2" @@ -5602,7 +5806,7 @@ version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys", @@ -5698,7 +5902,7 @@ version = "19.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56e1d6bd81c2d5feafd2419138df9183c45a10a492c4e873b8b0acb8eb2b549e" dependencies = [ - "bitflags", + "bitflags 2.11.1", "clipboard-win", "home", "libc", @@ -5802,7 +6006,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.11.1", "core-foundation", "core-foundation-sys", "libc", @@ -6118,6 +6322,9 @@ name = "spin" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +dependencies = [ + "lock_api 0.4.14", +] [[package]] name = "sqllogictest" @@ -6219,6 +6426,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "str_stack" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f446288b699d66d0fd2e30d1cfe7869194312524b3b9252594868ed26ef056a" + [[package]] name = "stringprep" version = "0.1.5" @@ -6329,6 +6542,29 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "symbolic-common" +version = "12.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "332615d90111d8eeaf86a84dc9bbe9f65d0d8c5cf11b4caccedc37754eb0dcfd" +dependencies = [ + "debugid", + "memmap2", + "stable_deref_trait", + "uuid", +] + +[[package]] +name = "symbolic-demangle" +version = "12.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "912017718eb4d21930546245af9a3475c9dccf15675a5c215664e76621afc471" +dependencies = [ + "cpp_demangle", + "rustc-demangle", + "symbolic-common", +] + [[package]] name = "syn" version = "2.0.119" @@ -6800,7 +7036,7 @@ version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ - "bitflags", + "bitflags 2.11.1", "bytes", "futures-util", "http", @@ -7317,7 +7553,7 @@ version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ - "bitflags", + "bitflags 2.11.1", "hashbrown 0.15.5", "indexmap 2.14.2", "semver", @@ -7661,7 +7897,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", - "bitflags", + "bitflags 2.11.1", "indexmap 2.14.2", "log", "serde", diff --git a/Cargo.toml b/Cargo.toml index 2d7acb9a0b2a5..5a857f8c1531c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -398,3 +398,23 @@ incremental = false [profile.ci-bench] inherits = "ci" opt-level = 1 + +[patch.crates-io] +arrow = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-arith = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-array = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-avro = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-buffer = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-cast = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-cmp = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-csv = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-data = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-flight = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-ipc = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-json = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-ord = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-row = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-schema = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-select = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +arrow-string = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } +parquet = { git = "https://github.com/andygrove/arrow-rs", branch = "polars-gap" } diff --git a/benchmarks/Cargo.toml b/benchmarks/Cargo.toml index 2ddcc48a322f5..5246721c85c09 100644 --- a/benchmarks/Cargo.toml +++ b/benchmarks/Cargo.toml @@ -36,6 +36,7 @@ datafusion = { workspace = true, default-features = true } datafusion-common = { workspace = true, default-features = true } datafusion-common-runtime = { workspace = true } env_logger = { workspace = true } +pprof = { version = "0.15", features = ["flamegraph"] } futures = { workspace = true } libmimalloc-sys = { version = "0.1", optional = true } log = { workspace = true } diff --git a/benchmarks/polars-gap/REPORT.md b/benchmarks/polars-gap/REPORT.md new file mode 100644 index 0000000000000..e434f10dbc730 --- /dev/null +++ b/benchmarks/polars-gap/REPORT.md @@ -0,0 +1,251 @@ +# DataFusion vs Polars on TPC-H SF100: gap analysis + +Context: [apache/datafusion#26169](https://github.com/apache/datafusion/issues/26169). +Branch: `andygrove/datafusion:polars-gap` (13 commits on apache/main `05b6de3e4`), +plus `andygrove/arrow-rs:polars-gap` (one kept commit on arrow-rs 60.2.0). + +## Headline + +TPC-H SF100, Parquet, best of 3 iterations, wall-clock milliseconds. Hardware: +AMD Ryzen 9 7950X (16 cores, 32 threads), 125 GB RAM. Both DataFusion builds +use the `release` (LTO) profile. + +| query | DF main | DF `polars-gap` | Polars 2.2 (streaming) | branch vs main | branch vs Polars | +| --------- | ----------: | --------------: | ---------------------: | -------------: | ---------------: | +| q1 | 6,085 | 2,512 | 4,754 | 2.4× | 0.53× | +| q2 | 1,668 | 589 | 163 | 2.8× | 3.6× | +| q3 | 4,698 | 3,050 | 2,656 | 1.5× | 1.15× | +| q4 | 1,307 | 1,244 | 1,198 | 1.1× | 1.04× | +| q5 | 7,989 | 3,164 | 2,871 | 2.5× | 1.10× | +| q6 | 1,494 | 1,051 | 1,408 | 1.4× | 0.75× | +| q7 | 13,390 | 3,297 | 3,560 | 4.1× | 0.93× | +| q8 | 8,711 | 4,340 | 3,185 | 2.0× | 1.36× | +| q9 | 15,276 | 10,339 | 6,404 | 1.5× | 1.61× | +| q10 | 6,579 | 4,581 | 4,112 | 1.4× | 1.11× | +| q11 | 1,753 | 725 | 194 | 2.4× | 3.7× | +| q12 | 1,462 | 1,112 | 493 | 1.3× | 2.3× | +| q13 | 4,174 | 3,815 | 3,762 | 1.1× | 1.01× | +| q14 | 2,815 | 1,750 | 2,104 | 1.6× | 0.83× | +| q15 | 5,863 | 2,047 | 2,028 | 2.9× | 1.01× | +| q16 | 943 | 836 | 372 | 1.1× | 2.2× | +| q17 | 14,394 | 2,496 | 2,738 | 5.8× | 0.91× | +| q18 | 11,001 | 4,952 | 5,342 | 2.2× | 0.93× | +| q19 | 3,558 | 1,778 | 2,266 | 2.0× | 0.78× | +| q20 | 5,159 | 2,410 | 1,818 | 2.1× | 1.33× | +| q21 | 15,130 | 7,039 | 6,387 | 2.1× | 1.10× | +| q22 | 680 | 690 | 656 | 1.0× | 1.05× | +| **total** | **134,131** | **63,815** | **58,471** | **2.10×** | **1.09×** | + +On this suite the branch is 2.1× faster than DataFusion main, and its total is +within 9% of Polars. It beats Polars on 7 queries. The remaining gap is +concentrated in q9, q8, q2, q11, q12 and q16; see +[Remaining gaps](#remaining-gaps). + +## How the gap closed + +Cumulative totals. Every step was measured on the full suite before it was +kept; these runs use the `release-nonlto` profile, which is within 1% of LTO +here. + +| step | total (ms) | main beneficiaries | +| -------------------------------------------------------------------- | ------------------------------: | ----------------------------------------------- | +| apache/main | 133,543 | | +| `target_partitions` = 16 (physical cores) instead of 32 | 117,723 | q1 6.2→3.2 s, q6, q14, q15 | +| `pushdown_filters=true`, conjuncts merged into one `RowFilter` | 87,561 | q7 13.2→3.3 s, q5 7.1→3.2 s, q20, q21, q11, q18 | +| arrow-rs: bounded decode of sparse masks | 82,402 | q15 6.7→4.2 s, q6 2.5→2.0 s, q9 14.0→11.9 s | +| adaptive dynamic-filter hash lookups | (within noise; q9 −3%, q18 −4%) | | +| statistics: scan filter selectivity, string equality, composite keys | 72,427 | q17 10.8→2.5 s, q13, q18 | +| cache-sized partial aggregation | 70,075 | q18 6.9→4.8 s | +| compute repeated subplans once (q15 view) | 67,790 | q15 4.2→2.1 s | +| push static filters only when they skip decoding columns | 65,889 | q6 2.0→1.0 s, q12, q19 | +| build side by rows; LIKE selectivity by pattern length | 64,743 | q9 11.5→10.2 s | +| move aggregate-valued join keys into the join filter | 64,385 | q2 1.1→0.57 s | + +## What was changed and kept + +Each item has an environment variable that switches back to the previous +behavior, so a single binary can A/B it. The last commit makes all of these the +defaults. + +1. **One `RowFilter` predicate instead of one per conjunct** + (`datasource-parquet/src/row_filter.rs`, `DF_ROWFILTER_MODE=split|group|single`, default `single`). + + - With one `ArrowPredicate` per conjunct, arrow-rs decodes the columns of each predicate in a separate pass, and the selection of each pass narrows the next. + - Merging the conjuncts into a single predicate decodes each filter column once. + - Worth about 2% on top of plain pushdown, and more on queries with several conjuncts on the same columns. + +2. **Turn `pushdown_filters` on, but push static filters only where it pays** + (`datasource-parquet/src/source.rs`, `DF_PUSHDOWN_MODE=all|auto|dynamic`, default `auto`). + + - A static filter becomes a row filter only when the scan projects more columns outside the filter than inside it. + - That is when late materialization skips real decode work. + - Otherwise the filter stays in a `FilterExec`, and the parquet predicate is still used for pruning. + - Dynamic join filters are always pushed down. + - The decision is stored on the `ParquetSource` and sticks once it is true, so a filter that was reported as `PushedDown::Yes` is always evaluated in the scan. + - Static pushdown hurts q6, q12 and q19 (every filter column is also decoded for the output) and helps q1, q3, q14 and q15. `auto` gets the better of the two on each of these queries. + +3. **arrow-rs: decode at most `batch_size` rows per mask chunk** + (`andygrove/arrow-rs@f27661c`). + + - `read_mask_batch` used to keep decoding until it had `batch_size` _selected_ rows. + - Under a sparse mask (1–2% selected) that decodes hundreds of thousands of rows into one giant array before filtering, and these allocations dominated q15 and q6 with pushdown on. + - Now it decodes and filters `batch_size` pieces and concatenates the filtered pieces. + - A follow-up that skipped the split for dense masks was measured, found slower (q9 +12%), and reverted. + +4. **Adaptive hash-table lookups in dynamic filters** + (`physical-plan/src/joins/hash_join/partitioned_hash_eval.rs`, `DF_LOOKUP_MIN_ROWS`, `DF_LOOKUP_MAX_KEPT`). + + - A `HashTableLookupExpr` counts the rows it sees and keeps. + - After 1M rows, if it kept more than 90% of them, it switches itself to `true` (Impala does the same). + - In q9, three of the four dynamic filters on `lineitem` keep everything but cost 14% of CPU in `contain_hashes`. + +5. **Better statistics for join ordering and build-side selection** + + - `FileScanConfig::statistics()` applies the selectivity of exactly-pushed static filters (`DF_SCAN_FILTER_STATS`). + - Before, a scan with a pushed-down filter reported its unfiltered row count. + - So when `FilterExec` disappeared under pushdown, filtered `part` looked like 20M rows instead of 20K. + - Selectivity for string equality without an NDV defaults to 10% instead of the generic 20% (`DF_STR_EQ_SEL`). + - Multi-key joins estimate distinct key tuples as the product of per-key NDVs, capped at row count (`DF_JOIN_COMPOSITE_NDV`). + - This means joining on a composite primary key such as `partsupp(ps_partkey, ps_suppkey)` no longer multiplies rows. + - The q9 `lineitem ⋈ partsupp` estimate dropped from 480M to 80M. + - The LIKE selectivity of a pattern with wildcards shrinks by 0.8 for each literal character (`DF_LIKE_CHAR_SEL`). + - `join_selection` compares estimated **rows** rather than bytes when choosing the build side (`DF_JOIN_SWAP=bytes` restores the old behavior). + - Hash table build cost is per row. + - Choosing by bytes kept 150M-row `orders` as the q9 build side because the probe side had wider rows. + - Effect on q17: the build side is now the 600K-row join instead of the 20M-group aggregate over 600M rows. The dynamic filter then reaches below the aggregate, and q17 drops from 10.8 s to 2.5 s (Polars: 2.7 s). + +6. **Cache-sized partial aggregation** + (`physical-plan/src/aggregates/hash_stream.rs`, `DF_PARTIAL_FLUSH_GROUPS`, default 4096). + + - The partial hash table emits its states and starts over once it holds 4096 groups. + - If it reduced its input by less than 2× since the last flush, the limit doubles instead, up to 1M groups, and then the table is unbounded. + - Clustered keys, such as q18's `l_orderkey` in `lineitem` file order, get an L1/L2-resident table. + - Unclustered keys grow it back or trip the existing skip-partial probe. + - q18 drops from 6.9 s to 4.8 s, and q13 improves 4%. + +7. **Compute a repeated subplan once** + (`optimizer/src/materialize_common_subplans.rs`, `DF_AUTO_CTE`). + + - The last logical rule finds identical subtrees, including inside subquery expressions, that aggregate or join, and that occur more than once. + - It wraps the plan in the existing `MaterializedCte` node, so the subtree is computed once and read through `MaterializedCteScan`. + - q15's `revenue0` view drops from 4.2 s to 2.0 s. + +8. **Move join keys on aggregate results into the join filter** + (`optimizer/src/defer_aggregate_join_keys.rs`, `DF_DEFER_AGG_KEYS`). + + - q2's decorrelated subquery joins on `(p_partkey = ps_partkey, ps_supplycost = min(ps_supplycost))`. + - Because one key is an aggregate output, the dynamic filter cannot pass the aggregate, so the full `partsupp ⋈ supplier ⋈ nation ⋈ region` aggregate (11.8M groups) was computed. + - With that key moved into the join filter, the filter on `ps_partkey` reaches the `partsupp` scan. This works like magic-set decorrelation, without a new operator. + - q2 drops from 1.1 s to 0.57 s. + +9. **`target_partitions` defaults to physical cores** (`common/src/utils`, `DF_PHYSICAL_PARTITIONS=0` to disable). + - On Linux with SMT active it divides `available_parallelism` by the number of threads per core. + - With 32 partitions on 16 cores, sibling hyperthreads thrash each other's L1/L2 caches in aggregation and joins. + - q1's user CPU time doubles while its wall time also gets worse. + +Also on the branch: + +- `dfbench tpch` writes per-query flamegraphs with `DF_PPROF=` and shows plan statistics with `DF_SHOW_STATS`. +- `[patch.crates-io]` points the workspace at the arrow-rs branch. + +Correctness: + +- `datasource-parquet` unit tests pass in every mode. The exception is one test that asserts a static filter is pushed, which `auto` deliberately does not do. +- The full sqllogictest suite with every change on shows only EXPLAIN diffs, plus one row-order change in a query without `ORDER BY`. +- arrow-rs parquet lib tests pass. + +## Tried and rejected + +| idea | result | +| ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| Global `batch_size` 2048 (helps cache residency of q1) | q1 −68% at 32 partitions, but joins and large scans got much slower; ~1.7× worse total. 4096: total 116.7 s vs 117.7 s. Not kept. | +| Decimal128 arithmetic fast path skipping overflow checks | Fired correctly, no speedup: the kernel is memory-bound (16-byte values), not instruction-bound. Reverted. | +| `DF_ROWFILTER_MODE=group` (one predicate per distinct column set) | Same as `split`. | +| Only dynamic filters pushed down (`dynamic`) | Ties `all` in total; `auto` beats both. | +| Disabling join reordering for q17 | No change: the issue was estimates, not reordering. | +| arrow-rs: no split for dense masks | q9 +12%, q1 unchanged. Reverted. | + +## Gap analysis + +### 1. Plan shape + +| gap | queries | Polars | DataFusion main | status on branch | +| --------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Correlated scalar subquery evaluated over the whole table | q2, q17, q20 | Polars: magic-set style, aggregates only the keys that can match (via `CACHE` of the outer side) | Aggregates all of `partsupp` (q2) / `lineitem` (q17) | Fixed: dynamic filters now pass the aggregate (items 5 and 8). | +| Common subexpressions computed twice | q15, q11 | Polars `CACHE` | View computed twice | q15 fixed (item 7). q11's two copies differ after projection pruning: the outer one keeps `ps_partkey`. Matching modulo projection would fix it (0.5 s). | +| Wrong build side from bad estimates | q9, q17, q8 | Polars: picks the smaller side using runtime sizes | Bytes-based choice and missing NDV/selectivity | Partly fixed (item 5). q9 is now the right shape: 32.6M-row build, `orders` and `partsupp` probed with dynamic filters that prune 120M and 76M rows. | +| Runtime filter overhead | q9, q18, q8 | Not compared | Exact hash-table lookups per row, never disabled | Fixed (item 4). A Bloom filter would make the surviving ones cheaper still. | + +### 2. Optimizer statistics + +- These parquet files (written by parquet-rs) carry no `distinct_count`. All NDV is therefore unknown or inferred, and every equality, LIKE and join estimate falls back to defaults: + - 20% for any predicate; + - `|L|·|R| / max(NDV)` for joins. +- Primary keys only give NDVs for single-column keys (`add_key_distinct_counts`). +- Filter selectivity was dropped once a filter was pushed into the scan. +- Highest-value next step: sample-based NDV estimates, or HyperLogLog NDVs written by DataFusion's own parquet writer. + +### 3. Execution + +| bottleneck | evidence | status | +| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| SMT oversubscription | q1 at 32 partitions: 2× user CPU, 6.2 s vs 3.2 s at 16 | Fixed (item 9). | +| Parquet decode is most of the CPU in scan-heavy queries | q15/q6 profiles: snappy 20%, dictionary decode 11%, `coerce_i64` (INT64 → Decimal128 widening) 5–25% | Open. Polars keeps `DECIMAL(15,2)` in 8 bytes; DataFusion widens to 16 bytes at decode, so every later kernel moves twice the memory. | +| Late materialization decodes filter columns twice | q6 with static pushdown: `coerce_i64` 4× the non-pushdown profile | Avoided by `auto` (item 2). The root cause is in arrow-rs (predicate cache, mask decode) and needs more work. | +| Sparse-mask decode | `read_mask_batch` decoded unbounded runs | Fixed in arrow-rs (item 3). | +| Hash join probe and build | q9: ~700 ns per probed row; build of 32.6M rows 6 s CPU; `take` of wide payloads | Open. The biggest remaining gap; see q9 below. | +| Partial aggregation table larger than cache | q18: 40 s CPU in group-id lookup for 150M groups | Fixed (item 6). | +| Final aggregation hash table | q15: `GroupValuesPrimitive` 25% of CPU for 1M groups | Open: radix-partitioned or prefetching group tables. | + +## Remaining gaps + +Ranked by absolute gap to Polars (branch, LTO): + +- **q9** (+3.9 s). + - The plan is now right, but the operators are slow. + - The `lineitem` scan spends 78 s of CPU (6 columns, with the part dynamic filter pruning 567M rows row by row). + - Each of the two big joins spends about 25 s of CPU at 32M rows. + - Candidates: + - Bloom-filter dynamic filters instead of exact hash lookups; + - prefetching hash probes; + - a narrower probe payload, carrying row ids and taking late. +- **q8** (+1.2 s). Seven-way join. Not analyzed in depth; the profile is dominated by the same join-operator costs as q9. +- **q21** (+0.7 s). Three `lineitem` scans with EXISTS/NOT EXISTS. Not analyzed in depth. +- **q12** (+0.6 s), **q16** (+0.5 s), **q20** (+0.6 s), **q11** (+0.5 s), **q2** (+0.4 s). + - Small absolute gaps; per-query fixed costs (planning, footer and page-index reads) are a larger share here and were not profiled separately. + - q11 is the common-subplan case that differs only by projection. +- **q3** (+0.4 s), **q10** (+0.5 s). Join and aggregation over `orders`/`lineitem`; mostly the join operator again. + +## Recommendations (upstream-able, roughly by value/effort) + +1. Default `target_partitions` to physical cores. + - One-line default change. + - About 12% on this machine, and the biggest single win for a CPU-only change. +2. Turn `pushdown_filters` on, with the merged `RowFilter` and the `auto` static-filter rule. + - About 30% here. + - Needs the arrow-rs sparse-mask fix upstream: without it, pushdown slowed q6, q12, q15 and q22 here. +3. Statistics: + - keep filter selectivity on scans with pushed filters; + - composite-key NDV; + - build side by rows. + - Small changes; they fix q17 (5.8×) and q9. +4. `DeferAggregateJoinKeys` and `MaterializeCommonSubplans` as optimizer rules. + - Small and self-contained. + - Their plan changes show up in EXPLAIN tests only. +5. Cache-sized partial aggregation. Self-contained in `PartialHashAggregateStream`. +6. Adaptive disabling of dynamic filter lookups. +7. Longer-term: + - 8-byte decimals end to end; + - Bloom runtime filters; + - sample-based cardinality estimates; + - faster hash join probe (prefetch, late materialization of build payload). + +## Reproducing + +- `benchmarks/polars-gap/scripts/` has the scripts used: + - `sync.sh` builds the current worktree on the benchmark host; + - `run_df.sh` and `matrix.sh` run `dfbench tpch` under a lock, best of 3; + - `summarize.py` prints the comparison tables; + - `top.py`, `diffprof.py` and `planx.py` read profiles and EXPLAIN ANALYZE output. +- Polars numbers come from `polars-2.0-benchmark`'s `bench.py` (Polars 2.2.0, streaming engine). +- All runs read the same SF100 Parquet files: 8 files per table, written by parquet-rs 60.0.0, snappy, no NDV statistics. diff --git a/benchmarks/polars-gap/scripts/diffprof.py b/benchmarks/polars-gap/scripts/diffprof.py new file mode 100644 index 0000000000000..fc63179195aaf --- /dev/null +++ b/benchmarks/polars-gap/scripts/diffprof.py @@ -0,0 +1,13 @@ +import collections,sys,re +def load(p): + s=collections.Counter(); t=0 + for line in open(p): + st,_,c=line.rstrip().rpartition(" "); c=int(c); t+=c + f=st.split(";")[-1] + f=re.sub(r"\{closure#\d+\}","{c}",f) + s[f[:140]]+=c + return s,t +a,ta=load(sys.argv[1]); b,tb=load(sys.argv[2]) +print(f"total samples A={ta} B={tb}") +keys=sorted(set(a)|set(b), key=lambda k: -(a[k]+b[k]))[:int(sys.argv[3]) if len(sys.argv)>3 else 30] +for k in keys: print(f"{a[k]:7d} {b[k]:7d} {k}") diff --git a/benchmarks/polars-gap/scripts/matrix.sh b/benchmarks/polars-gap/scripts/matrix.sh new file mode 100755 index 0000000000000..1589258ebc3a5 --- /dev/null +++ b/benchmarks/polars-gap/scripts/matrix.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# usage: matrix.sh BIN "tag|env|args" ... runs sequentially; writes ~/pg/matrix.done when finished +B=$1; shift +rm -f ~/pg/matrix.done +for spec in "$@"; do + IFS='|' read -r tag envs args <<< "$spec" + env $envs ~/pg/run_df.sh $B $tag all $args > ~/pg/results/$tag.log 2>&1 +done +touch ~/pg/matrix.done diff --git a/benchmarks/polars-gap/scripts/planx.py b/benchmarks/polars-gap/scripts/planx.py new file mode 100644 index 0000000000000..b36a44f8b2bb6 --- /dev/null +++ b/benchmarks/polars-gap/scripts/planx.py @@ -0,0 +1,18 @@ +import re,sys +# condense a dfbench --debug metrics plan +txt=open(sys.argv[1]).read() +sec=txt.split("=== Physical plan with metrics ===")[1].split("\n\n")[0] +for line in sec.splitlines(): + m=re.match(r"^(\s*)(\w+Exec)(.*)$",line) + if not m: continue + ind,name,rest=m.groups() + def g(k): + mm=re.search(k+r"=([^,\]]+)",rest); return mm.group(1) if mm else None + head=re.sub(r"file_groups=\{[^}]*\}","",rest) + head=re.sub(r", metrics=\[.*","",head) + head=re.sub(r"pruning_predicate=.*?required_guarantees=\[[^\]]*\]","",head) + extra=[] + for k in ["output_rows","elapsed_compute","build_time","join_time","build_input_rows","input_rows","selectivity","pushdown_rows_pruned","pushdown_rows_matched","row_groups_pruned_statistics","skipped_aggregation_rows","time_calculating_group_ids","probe_hit_rate","avg_fanout"]: + v=g(k) + if v: extra.append(f"{k}={v}") + print(f"{ind}{name}{head[:int(sys.argv[2]) if len(sys.argv)>2 else 200]}\n{ind} [{' '.join(extra)}]") diff --git a/benchmarks/polars-gap/scripts/run_df.sh b/benchmarks/polars-gap/scripts/run_df.sh new file mode 100755 index 0000000000000..fb37227a53dc7 --- /dev/null +++ b/benchmarks/polars-gap/scripts/run_df.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# usage: run_df.sh BIN TAG [QUERY] [extra dfbench args...] -> ~/pg/results/TAG.json +BIN=$1; TAG=$2; Q=$3; shift 3 +mkdir -p ~/pg/results +cd ~/git/apache/datafusion-polars-gap; QA=""; [ -n "$Q" ] && [ "$Q" != all ] && QA="--query $Q" +flock ~/pg/bench.lock $BIN tpch --iterations ${ITERS:-3} --path /mnt/bigdata/tpcgen4/tpch/sf${SF:-100} --format parquet --scale-factor ${SF:-100} $QA -o ~/pg/results/$TAG.json "$@" 2>&1 | grep -E "Query .* (avg|iteration)|failed|rror" diff --git a/benchmarks/polars-gap/scripts/summarize.py b/benchmarks/polars-gap/scripts/summarize.py new file mode 100644 index 0000000000000..d431f8f531e58 --- /dev/null +++ b/benchmarks/polars-gap/scripts/summarize.py @@ -0,0 +1,35 @@ +import json,sys,glob,os +# usage: summarize.py tag1 tag2 ... (DF json in ~/pg/results, polars jsonl tags start with polars:) +def load_df(tag): + d=json.load(open(os.path.expanduser(f"~/pg/results/{tag}.json"))) + out={} + for q in d["queries"]: + n=int(q["query"].split()[-1]); its=[i["elapsed"] for i in q["iterations"]] + if its: out[n]=min(its) + return out +def load_polars(tag): + out={} + for f in glob.glob(os.path.expanduser(f"~/git/polars-2.0-benchmark/results/{tag}/*.json")): + r=json.load(open(f)) + if r.get("status")!="ok": continue + n=int(r["query"].lstrip("q")); out[n]=min(out.get(n,1e18),r["wall_time_s"]*1000) + return out +def load_qe2(pat): + out={} + for f in glob.glob(os.path.expanduser(pat)): + for line in open(f): + p=line.split() + if len(p)>3 and p[0].startswith("q") and p[1]=="ok": + n=int(p[0][1:]); out[n]=min(out.get(n,1e18),float(p[2])) + return out +cols=[] +for a in sys.argv[1:]: + name,_,src=a.partition("=") + cols.append((name, load_polars(src[2:]) if src.startswith("p:") else load_qe2(src[2:]) if src.startswith("q:") else load_df(src or name))) +print("query "+" ".join(f"{n:>12}" for n,_ in cols)) +tot=[0]*len(cols) +for q in range(1,23): + vals=[c.get(q) for _,c in cols] + print(f"q{q:<4} "+" ".join(f"{v:12.0f}" if v else f"{'-':>12}" for v in vals)) + for i,v in enumerate(vals): tot[i]+= v or 0 +print("total "+" ".join(f"{v:12.0f}" for v in tot)) diff --git a/benchmarks/polars-gap/scripts/sync.sh b/benchmarks/polars-gap/scripts/sync.sh new file mode 100755 index 0000000000000..f8cf6cab4b79b --- /dev/null +++ b/benchmarks/polars-gap/scripts/sync.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# usage: sync.sh NAME +# Applies this worktree's diff against BASE to a checkout on HOST, builds +# dfbench (release-nonlto) there and copies it to ~/pg/bin/NAME. +set -e +HOST=${HOST:?set HOST to the benchmark machine} +BASE=${BASE:-05b6de3e4} +REMOTE_REPO=${REMOTE_REPO:-'~/git/apache/datafusion-polars-gap'} +cd "$(git rev-parse --show-toplevel)" +DIFF=$(mktemp) +git add -N . >/dev/null 2>&1 || true +git diff "$BASE" > "$DIFF" +scp -q "$DIFF" "$HOST":pg/pg.diff +rm -f "$DIFF" +ssh "$HOST" "cd $REMOTE_REPO && git reset -q --hard $BASE && git clean -fdq datafusion benchmarks && (test ! -s ~/pg/pg.diff || git apply ~/pg/pg.diff) && export PATH=\$HOME/.cargo/bin:\$PATH && cargo build --profile release-nonlto --bin dfbench -p datafusion-benchmarks 2>&1 | grep -E '^(error|warning)' -A5; cp target/release-nonlto/dfbench ~/pg/bin/$1 && echo built $1" diff --git a/benchmarks/polars-gap/scripts/top.py b/benchmarks/polars-gap/scripts/top.py new file mode 100644 index 0000000000000..b0ec626637651 --- /dev/null +++ b/benchmarks/polars-gap/scripts/top.py @@ -0,0 +1,13 @@ +import collections,sys +# usage: top.py folded [N] [filter-substring-for-inclusive] +self_=collections.Counter(); incl=collections.Counter(); tot=0 +for line in open(sys.argv[1]): + st,_,c=line.rstrip().rpartition(" "); c=int(c); tot+=c + fr=st.split(";"); self_[fr[-1]]+=c + for f in set(fr): incl[f]+=c +N=int(sys.argv[2]) if len(sys.argv)>2 else 25 +print("--- self"); [print(f"{100*c/tot:5.1f}% {f[:170]}") for f,c in self_.most_common(N)] +if len(sys.argv)>3: + print("--- inclusive matching", sys.argv[3]) + for f,c in incl.most_common(4000): + if sys.argv[3] in f: print(f"{100*c/tot:5.1f}% {f[:170]}") diff --git a/benchmarks/src/tpch/run.rs b/benchmarks/src/tpch/run.rs index ccea71ad0d4b8..404c3c43a9e5d 100644 --- a/benchmarks/src/tpch/run.rs +++ b/benchmarks/src/tpch/run.rs @@ -102,7 +102,33 @@ impl RunOpt { for query_id in query_range { benchmark_run.start_new_case(&format!("Query {query_id}")); + let guard = std::env::var("DF_PPROF").ok().map(|dir| { + let g = pprof::ProfilerGuardBuilder::default() + .frequency(499) + .blocklist(&["libc", "libgcc", "pthread", "vdso"]) + .build() + .unwrap(); + (dir, g) + }); let query_run = self.benchmark_query(query_id, scale_factor, &ctx).await; + if let Some((dir, g)) = guard + && let Ok(report) = g.report().build() + { + let f = std::fs::File::create(format!("{dir}/q{query_id}.svg")).unwrap(); + report.flamegraph(f).unwrap(); + use std::io::Write; + let mut folded = + std::fs::File::create(format!("{dir}/q{query_id}.folded")).unwrap(); + for (frames, count) in report.data.iter() { + let names: Vec = frames + .frames + .iter() + .rev() + .map(|f| f.first().map(|s| s.name()).unwrap_or_default()) + .collect(); + writeln!(folded, "{} {count}", names.join(";")).unwrap(); + } + } match query_run { Ok(query_results) => { for iter in query_results { @@ -219,7 +245,9 @@ impl RunOpt { if debug { println!( "=== Physical plan ===\n{}\n", - displayable(physical_plan.as_ref()).indent(true) + displayable(physical_plan.as_ref()) + .set_show_statistics(std::env::var("DF_SHOW_STATS").is_ok()) + .indent(true) ); } let result = collect(physical_plan.clone(), state.task_ctx()).await?; diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index cdcecfe6196b4..921b0d0123aec 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -15,7 +15,7 @@ use crate::parquet_config::{ DFTimeUnit, RowGroupRangeAssignment, }; use crate::parsers::{CompressionTypeVariant, CsvQuoteStyle}; -use crate::utils::get_available_parallelism; +use crate::utils::{get_available_parallelism, get_physical_parallelism}; use crate::{DataFusionError, Result}; #[cfg(feature = "parquet_encryption")] use hex; @@ -889,7 +889,7 @@ config_namespace! { /// concurrency. /// /// Defaults to the number of CPU cores on the system - pub target_partitions: usize, transform = ExecutionOptions::normalized_parallelism, default = get_available_parallelism() + pub target_partitions: usize, transform = ExecutionOptions::normalized_parallelism, default = get_physical_parallelism() /// The default time zone /// @@ -1309,7 +1309,7 @@ config_namespace! { /// (reading) If true, filter expressions are be applied during the parquet decoding operation to /// reduce the number of rows decoded. This optimization is sometimes called "late materialization". - pub pushdown_filters: bool, default = false + pub pushdown_filters: bool, default = true /// (reading) If true, filter expressions evaluated during the parquet decoding operation /// will be reordered heuristically to minimize the cost of evaluation. If false, diff --git a/datafusion/common/src/utils/mod.rs b/datafusion/common/src/utils/mod.rs index c07e116c6b64c..55efddbc0e167 100644 --- a/datafusion/common/src/utils/mod.rs +++ b/datafusion/common/src/utils/mod.rs @@ -1391,6 +1391,44 @@ pub fn get_available_parallelism() -> usize { *PARALLELISM } +/// Returns [`get_available_parallelism`] divided by the number of hardware +/// threads per physical core, when that is known (Linux with SMT active). +/// +/// Running more partitions than physical cores makes the sibling hardware +/// threads share one core's caches, which slows down cache-sensitive +/// operators such as hash aggregation and hash joins. +pub fn get_physical_parallelism() -> usize { + static PARALLELISM: LazyLock = LazyLock::new(|| { + let logical = get_available_parallelism(); + if std::env::var("DF_PHYSICAL_PARTITIONS").is_ok_and(|v| v == "0") { + return logical; + } + (logical / threads_per_core().unwrap_or(1)).max(1) + }); + *PARALLELISM +} + +fn threads_per_core() -> Option { + let smt = std::fs::read_to_string("/sys/devices/system/cpu/smt/active").ok()?; + if smt.trim() != "1" { + return None; + } + let siblings = std::fs::read_to_string( + "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list", + ) + .ok()?; + let mut count = 0; + for part in siblings.trim().split(',') { + count += match part.split_once('-') { + Some((start, end)) => { + end.parse::().ok()? - start.parse::().ok()? + 1 + } + None => 1, + }; + } + (count > 0).then_some(count) +} + /// Converts a collection of function arguments into a fixed-size array of length N /// producing a reasonable error message in case of unexpected number of arguments. /// diff --git a/datafusion/datasource-parquet/src/opener/mod.rs b/datafusion/datasource-parquet/src/opener/mod.rs index 1866b6ba81992..e24f526789aae 100644 --- a/datafusion/datasource-parquet/src/opener/mod.rs +++ b/datafusion/datasource-parquet/src/opener/mod.rs @@ -256,6 +256,8 @@ pub(super) struct ParquetMorselizer { /// Should the filters be evaluated during the parquet scan using /// [`DatafusionArrowPredicate`](crate::row_filter::DatafusionArrowPredicate)? pub pushdown_filters: bool, + /// Should conjuncts without a dynamic filter become row filters? + pub push_static_filters: bool, /// Should the filters be reordered to optimize the scan? pub reorder_filters: bool, /// Should we force the reader to use RowSelections for filtering @@ -457,6 +459,7 @@ struct PreparedParquetOpen { virtual_state: Option>, reorder_predicates: bool, pushdown_filters: bool, + push_static_filters: bool, force_filter_selections: bool, enable_page_index: bool, enable_bloom_filter: bool, @@ -569,6 +572,7 @@ impl DecoderReadPlans { prepared.reorder_predicates, prepared.file_metrics.clone(), prepared.max_predicate_cache_size, + prepared.push_static_filters, ) }); Ok(Self { @@ -985,6 +989,7 @@ impl ParquetMorselizer { virtual_state: self.virtual_state.as_ref().map(Arc::clone), reorder_predicates: self.reorder_filters, pushdown_filters: self.pushdown_filters, + push_static_filters: self.push_static_filters, force_filter_selections: self.force_filter_selections, enable_page_index: self.enable_page_index, enable_bloom_filter: self.enable_bloom_filter, @@ -2693,6 +2698,7 @@ mod test { }), schema_provider: None, pushdown_filters: self.pushdown_filters, + push_static_filters: true, reorder_filters: self.reorder_filters, force_filter_selections: self.force_filter_selections, enable_page_index: self.enable_page_index, diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index 3d70cef744328..3b7d130e7ac3b 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -371,11 +371,13 @@ impl RowFilterContext { reorder_predicates: bool, file_metrics: ParquetFileMetrics, max_predicate_cache_size: Option, + push_static_filters: bool, ) -> Option { match prebuild_row_filter_candidates( predicate, physical_file_schema, file_metadata.as_ref(), + push_static_filters, ) { Ok(Some(prebuilt)) => Some(Self { prebuilt: PrebuiltRowFilterCandidateList::new(prebuilt), diff --git a/datafusion/datasource-parquet/src/row_filter.rs b/datafusion/datasource-parquet/src/row_filter.rs index f07e01a365bab..ade9f0997796c 100644 --- a/datafusion/datasource-parquet/src/row_filter.rs +++ b/datafusion/datasource-parquet/src/row_filter.rs @@ -420,7 +420,8 @@ pub fn build_row_filter( // that splits conjuncts, orders candidates, and wires metrics — callers // that build once per file go through the same code as the per-row-group // rebuild path in `RowFilterContext`. - let Some(prebuilt) = prebuild_row_filter_candidates(expr, file_schema, metadata)? + let Some(prebuilt) = + prebuild_row_filter_candidates(expr, file_schema, metadata, true)? else { return Ok(None); }; @@ -476,12 +477,14 @@ pub(crate) fn prebuild_row_filter_candidates( expr: &Arc, file_schema: &SchemaRef, metadata: &ParquetMetaData, + push_static_filters: bool, ) -> Result>> { // Split into conjuncts: // `a = 1 AND b = 2 AND c = 3` -> [`a = 1`, `b = 2`, `c = 3`] let predicates = split_conjunction(expr); let candidates: Vec = predicates .into_iter() + .filter(|expr| push_static_filters || is_dynamic(expr)) .map(|expr| { FilterCandidateBuilder::new(Arc::clone(expr), Arc::clone(file_schema)) .build(metadata) @@ -495,6 +498,8 @@ pub(crate) fn prebuild_row_filter_candidates( return Ok(None); } + let candidates = merge_candidates(candidates, file_schema, metadata)?; + let prebuilt: Vec = candidates .into_iter() .map(|candidate| { @@ -513,6 +518,57 @@ pub(crate) fn prebuild_row_filter_candidates( Ok(Some(prebuilt)) } +pub(crate) fn is_dynamic(expr: &Arc) -> bool { + datafusion_physical_expr::expressions::DynamicFilterTracking::classify(expr) + .contains_dynamic_filter() +} + +fn row_filter_mode() -> &'static str { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + MODE.get_or_init(|| { + std::env::var("DF_ROWFILTER_MODE").unwrap_or_else(|_| "single".to_string()) + }) +} + +/// Merges conjunct candidates so that fewer predicates (and fewer decode +/// passes) are needed: `group` merges conjuncts reading the same columns, +/// `single` merges all of them into one predicate. +fn merge_candidates( + candidates: Vec, + file_schema: &SchemaRef, + metadata: &ParquetMetaData, +) -> Result> { + let mode = row_filter_mode(); + if candidates.len() < 2 || mode == "split" { + return Ok(candidates); + } + let mut groups: Vec<(ProjectionMask, Vec>)> = vec![]; + for c in candidates { + let key = if mode == "single" { + None + } else { + Some(c.read_plan.projection_mask.clone()) + }; + match groups + .iter_mut() + .find(|(m, _)| key.as_ref().is_none_or(|k| k == m)) + { + Some((_, exprs)) => exprs.push(c.expr), + None => groups.push((c.read_plan.projection_mask.clone(), vec![c.expr])), + } + } + let mut out = Vec::with_capacity(groups.len()); + for (_, exprs) in groups { + let expr = datafusion_physical_expr::conjunction(exprs); + if let Some(c) = + FilterCandidateBuilder::new(expr, Arc::clone(file_schema)).build(metadata)? + { + out.push(c); + } + } + Ok(out) +} + /// Wrap a list of prebuilt candidates into a fresh [`RowFilter`], assigning /// per-predicate metric counters and (optionally) reordering by /// `required_bytes`. This is the cheap per-row-group rebuild path — no tree diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 6f4af5561cb9f..17455c919b342 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -3,6 +3,7 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements //! ParquetSource implementation for reading parquet files +use std::collections::HashSet; use std::fmt::Debug; use std::fmt::Formatter; use std::sync::Arc; @@ -36,7 +37,7 @@ use datafusion_datasource::file_scan_config::FileScanConfig; use datafusion_functions::core::file_row_index::FileRowIndexFunc; use datafusion_physical_expr::expressions::{Column, DynamicFilterTracking}; use datafusion_physical_expr::projection::ProjectionExprs; -use datafusion_physical_expr::utils::split_conjunction; +use datafusion_physical_expr::utils::{collect_columns, split_conjunction}; use datafusion_physical_expr::{EquivalenceProperties, conjunction}; use datafusion_physical_expr_adapter::DefaultPhysicalExprAdapterFactory; use datafusion_physical_expr_adapter::rewrite::{ @@ -302,6 +303,11 @@ pub struct ParquetSource { pub(crate) metadata_size_hint: Option, /// Projection to apply to the output. pub(crate) projection: ProjectionExprs, + /// Whether conjuncts without a dynamic filter become row filters. + /// `None` until [`FileSource::try_pushdown_filters`] decides, which means + /// they do. Once true it stays true: the filters it pushed are no longer + /// evaluated above the scan. + pub(crate) push_static_filters: Option, #[cfg(feature = "parquet_encryption")] pub(crate) encryption_factory: Option>, /// If true, the opener flips row-group iteration order. Unless @@ -337,6 +343,7 @@ impl ParquetSource { let indices: Vec = (0..full_schema.fields().len()).collect(); Self { projection: ProjectionExprs::from_indices(&indices, full_schema), + push_static_filters: None, table_schema, table_parquet_options: TableParquetOptions::default(), metrics: ExecutionPlanMetricsSet::new(), @@ -444,6 +451,10 @@ impl ParquetSource { self.table_parquet_options.global.pushdown_filters } + pub(crate) fn push_static_filters(&self) -> bool { + self.push_static_filters.unwrap_or(true) + } + /// If true, the `RowFilter` made by `pushdown_filters` may try to /// minimize the cost of filter evaluation by reordering the /// predicate [`Expr`]s. If false, the predicates are applied in @@ -634,6 +645,7 @@ impl FileSource for ParquetSource { parquet_file_reader_factory, schema_provider: self.schema_provider.clone(), pushdown_filters: self.pushdown_filters(), + push_static_filters: self.push_static_filters(), reorder_filters: self.reorder_filters(), force_filter_selections: self.force_filter_selections(), enable_page_index: self.enable_page_index(), @@ -698,6 +710,9 @@ impl FileSource for ParquetSource { let exact = split_conjunction(predicate) .into_iter() .filter(|expr| can_expr_be_pushed_down_with_schemas(expr, pushable_schema)) + .filter(|expr| { + self.push_static_filters() || crate::row_filter::is_dynamic(expr) + }) .cloned() .collect::>(); (!exact.is_empty()).then(|| conjunction(exact)) @@ -910,6 +925,14 @@ impl FileSource for ParquetSource { } None => conjunction(allowed_filters), }; + if filters.iter().any(|f| { + matches!(f.discriminant, PushedDown::Yes) + && !crate::row_filter::is_dynamic(&f.predicate) + }) && source.push_static_filters != Some(true) + { + source.push_static_filters = + Some(should_push_static_filters(&predicate, &source.projection)); + } source.predicate = Some(predicate); source = source.with_pushdown_filters(pushdown_filters); let source = Arc::new(source); @@ -922,7 +945,18 @@ impl FileSource for ParquetSource { .with_updated_node(source)); } Ok(FilterPushdownPropagation::with_parent_pushdown_result( - filters.iter().map(|f| f.discriminant).collect(), + filters + .iter() + .map(|f| { + if !source.push_static_filters() + && !crate::row_filter::is_dynamic(&f.predicate) + { + PushedDown::No + } else { + f.discriminant + } + }) + .collect(), ) .with_updated_node(source)) } @@ -1158,6 +1192,7 @@ impl FileSource for ParquetSource { batch_size: _, metadata_size_hint, // Carried by `base` as projection expressions. + push_static_filters: _, projection: _, // Not serialized or restored by the default decoder. #[cfg(feature = "parquet_encryption")] @@ -1380,6 +1415,37 @@ fn table_schema_with_row_index_col(table_schema: &TableSchema) -> (TableSchema, ) } +/// Whether the conjuncts of `predicate` without a dynamic filter should +/// become row filters of a scan that outputs `projection`. +/// +/// A row filter decodes its columns first and then only the selected rows of +/// the other columns, which pays off when there are more of those. Otherwise +/// decoding all columns and filtering afterwards is cheaper. +fn should_push_static_filters( + predicate: &Arc, + projection: &ProjectionExprs, +) -> bool { + match std::env::var("DF_PUSHDOWN_MODE").as_deref() { + Ok("dynamic") => return false, + Ok("all") => return true, + _ => {} + } + let filter_columns: HashSet = split_conjunction(predicate) + .into_iter() + .filter(|expr| !crate::row_filter::is_dynamic(expr)) + .flat_map(collect_columns) + .map(|column| column.name().to_string()) + .collect(); + let other_columns = projection + .iter() + .flat_map(|proj| collect_columns(&proj.expr)) + .map(|column| column.name().to_string()) + .filter(|name| !filter_columns.contains(name)) + .collect::>() + .len(); + other_columns > filter_columns.len() +} + #[cfg(test)] mod tests { use super::*; diff --git a/datafusion/datasource/src/file_scan_config/mod.rs b/datafusion/datasource/src/file_scan_config/mod.rs index 45d16817135d0..4ea89142207d7 100644 --- a/datafusion/datasource/src/file_scan_config/mod.rs +++ b/datafusion/datasource/src/file_scan_config/mod.rs @@ -1344,12 +1344,44 @@ impl FileScanConfig { let filter_may_change_row_count = self.file_source.filter().is_some() && self.statistics.num_rows != Precision::Exact(0); if filter_may_change_row_count { - self.statistics.clone().to_inexact() + let stats = self.statistics.clone().to_inexact(); + self.apply_exact_filter_selectivity(&stats).unwrap_or(stats) } else { self.statistics.clone() } } + /// Estimates the rows left by the conjuncts the source applies to every + /// row (so no `FilterExec` above it estimates them), as a `FilterExec` + /// would. Dynamic filters are unknown at planning time and are skipped. + fn apply_exact_filter_selectivity(&self, stats: &Statistics) -> Option { + if std::env::var("DF_SCAN_FILTER_STATS").is_ok_and(|v| v == "0") { + return None; + } + let filter = self.file_source.exact_filter()?; + let static_conjuncts: Vec<_> = split_conjunction(&filter) + .into_iter() + .filter(|expr| { + !datafusion_physical_expr::expressions::DynamicFilterTracking::classify( + expr, + ) + .contains_dynamic_filter() + }) + .cloned() + .collect(); + if static_conjuncts.is_empty() { + return None; + } + let predicate = datafusion_physical_expr::conjunction(static_conjuncts); + datafusion_physical_plan::filter::FilterExec::statistics_helper( + self.file_source.table_schema().table_schema(), + stats.clone(), + &predicate, + 20, + ) + .ok() + } + pub fn projected_schema(&self) -> Result> { let schema = self.file_source.table_schema().table_schema(); match self.file_source.projection() { diff --git a/datafusion/optimizer/src/defer_aggregate_join_keys.rs b/datafusion/optimizer/src/defer_aggregate_join_keys.rs new file mode 100644 index 0000000000000..542cba9a1d291 --- /dev/null +++ b/datafusion/optimizer/src/defer_aggregate_join_keys.rs @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! [`DeferAggregateJoinKeys`] moves join keys on aggregate results into the +//! join filter. + +use datafusion_common::tree_node::Transformed; +use datafusion_common::{Column, NullEquality, Result}; +use datafusion_expr::logical_plan::{Join, LogicalPlan}; +use datafusion_expr::utils::conjunction; +use datafusion_expr::{Expr, JoinType}; + +use crate::optimizer::ApplyOrder; +use crate::{OptimizerConfig, OptimizerRule}; + +/// Moves the equality of a join key that is an aggregate result, such as +/// `ps_supplycost = min(ps_supplycost)` from a decorrelated scalar subquery, +/// from the equijoin keys into the join filter, as long as another key remains. +/// +/// The join then filters its other input by the remaining keys only. These are +/// grouping keys of the aggregate, so that filter can reach below the +/// aggregate, which then only aggregates the groups that can match. +#[derive(Default, Debug)] +pub struct DeferAggregateJoinKeys; + +impl DeferAggregateJoinKeys { + #[expect(missing_docs)] + pub fn new() -> Self { + Self {} + } +} + +/// Whether `column` of `plan` is computed from aggregate results of an +/// [`LogicalPlan::Aggregate`] (and not a grouping key passed through). +fn is_aggregate_result(plan: &LogicalPlan, column: &Column) -> bool { + let Ok(index) = plan.schema().index_of_column(column) else { + return false; + }; + is_aggregate_result_at(plan, index) +} + +fn is_aggregate_result_at(plan: &LogicalPlan, index: usize) -> bool { + match plan { + LogicalPlan::Aggregate(aggregate) => aggregate + .group_expr_len() + .is_ok_and(|group_len| index >= group_len), + LogicalPlan::Projection(projection) => { + let Some(expr) = projection.expr.get(index) else { + return false; + }; + let columns = expr.column_refs(); + !columns.is_empty() + && columns + .into_iter() + .all(|column| is_aggregate_result(&projection.input, column)) + } + LogicalPlan::SubqueryAlias(alias) => is_aggregate_result_at(&alias.input, index), + LogicalPlan::Filter(filter) => is_aggregate_result_at(&filter.input, index), + LogicalPlan::Sort(sort) => is_aggregate_result_at(&sort.input, index), + LogicalPlan::Limit(limit) => is_aggregate_result_at(&limit.input, index), + _ => false, + } +} + +fn is_aggregate_key(expr: &Expr, plan: &LogicalPlan) -> bool { + match expr { + Expr::Column(column) => is_aggregate_result(plan, column), + Expr::Cast(cast) => is_aggregate_key(&cast.expr, plan), + _ => false, + } +} + +impl OptimizerRule for DeferAggregateJoinKeys { + fn name(&self) -> &str { + "defer_aggregate_join_keys" + } + + fn apply_order(&self) -> Option { + Some(ApplyOrder::BottomUp) + } + + fn rewrite( + &self, + plan: LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result> { + if std::env::var("DF_DEFER_AGG_KEYS").is_ok_and(|v| v == "0") { + return Ok(Transformed::no(plan)); + } + let LogicalPlan::Join(join) = plan else { + return Ok(Transformed::no(plan)); + }; + if join.on.len() < 2 + || join.null_equality != NullEquality::NullEqualsNothing + || join.null_aware + || !matches!( + join.join_type, + JoinType::Inner + | JoinType::LeftSemi + | JoinType::RightSemi + | JoinType::LeftAnti + | JoinType::RightAnti + ) + { + return Ok(Transformed::no(LogicalPlan::Join(join))); + } + + let (deferred, kept): (Vec<_>, Vec<_>) = + join.on.iter().cloned().partition(|(left, right)| { + is_aggregate_key(left, &join.left) || is_aggregate_key(right, &join.right) + }); + if deferred.is_empty() + || kept.is_empty() + || kept.iter().any(|(left, right)| { + is_aggregate_key(left, &join.left) || is_aggregate_key(right, &join.right) + }) + { + return Ok(Transformed::no(LogicalPlan::Join(join))); + } + + let filter = conjunction( + join.filter + .iter() + .cloned() + .chain(deferred.into_iter().map(|(left, right)| left.eq(right))), + ); + Ok(Transformed::yes(LogicalPlan::Join(Join { + on: kept, + filter, + ..join + }))) + } +} diff --git a/datafusion/optimizer/src/lib.rs b/datafusion/optimizer/src/lib.rs index 754e37000b895..e3b35a039b0aa 100644 --- a/datafusion/optimizer/src/lib.rs +++ b/datafusion/optimizer/src/lib.rs @@ -30,6 +30,7 @@ pub mod common_subexpr_eliminate; pub mod decorrelate; pub mod decorrelate_lateral_join; pub mod decorrelate_predicate_subquery; +pub mod defer_aggregate_join_keys; pub mod eliminate_aggregate_distinct; pub mod eliminate_cross_join; pub mod eliminate_duplicated_expr; @@ -47,6 +48,7 @@ pub mod eliminate_outer_join; pub mod extract_equijoin_predicate; pub mod extract_leaf_expressions; pub mod filter_null_join_keys; +pub mod materialize_common_subplans; pub mod optimize_projections; pub mod optimize_unions; pub mod optimizer; diff --git a/datafusion/optimizer/src/materialize_common_subplans.rs b/datafusion/optimizer/src/materialize_common_subplans.rs new file mode 100644 index 0000000000000..543d656fda4fc --- /dev/null +++ b/datafusion/optimizer/src/materialize_common_subplans.rs @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! [`MaterializeCommonSubplans`] computes a subplan that a query repeats once. + +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; + +use datafusion_common::Result; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; +use datafusion_expr::logical_plan::{ + LogicalPlan, MaterializedCte, MaterializedCteId, MaterializedCtePlan, + MaterializedCteScan, +}; + +use crate::optimizer::ApplyOrder; +use crate::{OptimizerConfig, OptimizerRule}; + +/// Computes a subplan that occurs more than once in a query, for example a +/// view referenced twice, only once and reads its buffered result everywhere +/// it occurs. +/// +/// Only subplans that aggregate or join are shared: rereading a scan is +/// cheaper than buffering it. +#[derive(Default, Debug)] +pub struct MaterializeCommonSubplans; + +impl MaterializeCommonSubplans { + #[expect(missing_docs)] + pub fn new() -> Self { + Self {} + } +} + +fn enabled() -> bool { + std::env::var("DF_AUTO_CTE").map_or(true, |v| v != "0") +} + +fn plan_hash(plan: &LogicalPlan) -> u64 { + let mut hasher = DefaultHasher::new(); + plan.hash(&mut hasher); + hasher.finish() +} + +fn is_expensive(plan: &LogicalPlan) -> bool { + plan.exists(|node| { + Ok(matches!( + node, + LogicalPlan::Aggregate(_) | LogicalPlan::Join(_) + )) + }) + .unwrap_or(false) +} + +fn has_materialized_cte(plan: &LogicalPlan) -> bool { + let mut found = false; + let _ = plan.apply_with_subqueries(|node| { + found = matches!(node, LogicalPlan::MaterializedCte(_)); + Ok(if found { + TreeNodeRecursion::Stop + } else { + TreeNodeRecursion::Continue + }) + }); + found +} + +impl OptimizerRule for MaterializeCommonSubplans { + fn name(&self) -> &str { + "materialize_common_subplans" + } + + fn apply_order(&self) -> Option { + None + } + + fn rewrite( + &self, + plan: LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result> { + if !enabled() || has_materialized_cte(&plan) { + return Ok(Transformed::no(plan)); + } + + let mut counts: HashMap = HashMap::new(); + plan.apply_with_subqueries(|node| { + *counts.entry(plan_hash(node)).or_default() += 1; + Ok(TreeNodeRecursion::Continue) + })?; + + // The largest repeated subplans, outermost first. + let mut shared: Vec = vec![]; + plan.apply_with_subqueries(|node| { + if !matches!(node, LogicalPlan::Subquery(_)) + && counts.get(&plan_hash(node)).copied().unwrap_or(0) >= 2 + && is_expensive(node) + && node.all_out_ref_exprs().is_empty() + { + if !shared.contains(node) { + shared.push(node.clone()); + } + return Ok(TreeNodeRecursion::Jump); + } + Ok(TreeNodeRecursion::Continue) + })?; + drop(counts); + if shared.is_empty() { + return Ok(Transformed::no(plan)); + } + + let ctes: Vec<(MaterializedCteId, String, LogicalPlan)> = shared + .into_iter() + .enumerate() + .map(|(i, body)| (MaterializedCteId::next(), format!("__common_{i}"), body)) + .collect(); + + let mut continuation = plan + .transform_down_with_subqueries(|node| { + if matches!(node, LogicalPlan::Subquery(_)) { + return Ok(Transformed::no(node)); + } + match ctes.iter().find(|(_, _, body)| *body == node) { + Some((id, name, body)) => Ok(Transformed::new( + LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan( + MaterializedCteScan::new( + *id, + name.clone(), + Arc::clone(body.schema()), + ), + )), + true, + TreeNodeRecursion::Jump, + )), + None => Ok(Transformed::no(node)), + } + })? + .data; + + for (id, name, body) in ctes.into_iter().rev() { + continuation = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte( + MaterializedCte::try_new( + id, + name, + Arc::new(body), + Arc::new(continuation), + )?, + )); + } + Ok(Transformed::yes(continuation)) + } +} diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rs index fdf5e5bbb1bf8..af00ad2fda3ea 100644 --- a/datafusion/optimizer/src/optimizer.rs +++ b/datafusion/optimizer/src/optimizer.rs @@ -31,6 +31,7 @@ use datafusion_expr::{ use crate::common_subexpr_eliminate::CommonSubexprEliminate; use crate::decorrelate_lateral_join::DecorrelateLateralJoin; use crate::decorrelate_predicate_subquery::DecorrelatePredicateSubquery; +use crate::defer_aggregate_join_keys::DeferAggregateJoinKeys; use crate::eliminate_aggregate_distinct::EliminateAggregateDistinct; use crate::eliminate_cross_join::EliminateCrossJoin; use crate::eliminate_duplicated_expr::EliminateDuplicatedExpr; @@ -42,6 +43,7 @@ use crate::eliminate_outer_join::EliminateOuterJoin; use crate::extract_equijoin_predicate::ExtractEquijoinPredicate; use crate::extract_leaf_expressions::{ExtractLeafExpressions, PushDownLeafProjections}; use crate::filter_null_join_keys::FilterNullJoinKeys; +use crate::materialize_common_subplans::MaterializeCommonSubplans; use crate::optimize_projections::OptimizeProjections; use crate::optimize_unions::OptimizeUnions; use crate::plan_signature::LogicalPlanSignature; @@ -339,6 +341,8 @@ impl Optimizer { Arc::new(PushDownLeafProjections::new()), Arc::new(OptimizeProjections::new()), Arc::new(ReplaceFilterTop1::new()), + Arc::new(DeferAggregateJoinKeys::new()), + Arc::new(MaterializeCommonSubplans::new()), ]; Self::with_rules(rules) diff --git a/datafusion/physical-optimizer/src/join_selection.rs b/datafusion/physical-optimizer/src/join_selection.rs index 8740cddc45f7a..4b4b4cce6f235 100644 --- a/datafusion/physical-optimizer/src/join_selection.rs +++ b/datafusion/physical-optimizer/src/join_selection.rs @@ -80,6 +80,15 @@ pub(crate) fn should_swap_join_order( let left_stats = get_stats(left, context)?; let right_stats = get_stats(right, context)?; + if std::env::var("DF_JOIN_SWAP").map_or(true, |v| v != "bytes") + && let (Some(l), Some(r)) = ( + left_stats.num_rows.get_value(), + right_stats.num_rows.get_value(), + ) + { + return Ok(l > r); + } + // First compare total_byte_size, then fall back to num_rows if byte // sizes are unavailable. match ( diff --git a/datafusion/physical-plan/src/aggregates/hash_stream.rs b/datafusion/physical-plan/src/aggregates/hash_stream.rs index e3ee8fb28a547..afb7322fbeb1b 100644 --- a/datafusion/physical-plan/src/aggregates/hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/hash_stream.rs @@ -153,6 +153,13 @@ pub(crate) struct PartialHashAggregateStream { /// be empty. See struct comments for details. group_values_soft_limit: Option, + /// Groups the table may hold before its states are emitted and it starts + /// over; see [`Self::handle_input_batch`]. + flush_limit: usize, + + /// Input rows aggregated since the table last started over. + rows_since_flush: usize, + /// The hash table owns the lower-level state for emitting output batches. hash_table: Option>, } @@ -266,6 +273,8 @@ impl PartialHashAggregateStream { early_emit_count, skip_aggregation_probe, group_values_soft_limit: agg.limit_options().map(|config| config.limit()), + flush_limit: partial_flush_groups(), + rows_since_flush: 0, hash_table: Some(hash_table), }) } @@ -404,8 +413,32 @@ impl PartialHashAggregateStream { return Ok(HandleInputResult::SwitchToSkipAggregation); } + // -------------------------------------------------------------- + // Step 4: Keep the partial table cache sized. Once it holds more + // groups than fit in cache, every insert misses; emitting its + // states and starting over costs nothing when keys are clustered, + // and when they are not the skip probe above turns the partial + // aggregate off. + // -------------------------------------------------------------- + self.rows_since_flush += input_rows; + let groups = hash_table.building_group_count(); + if self.group_values_soft_limit.is_none() && groups >= self.flush_limit { + // A table that has not halved its input since it started over + // gains from holding more groups, so let it grow instead + // (up to `MAX_PARTIAL_FLUSH_GROUPS`, after which it never starts over). + if self.rows_since_flush < 2 * groups { + self.flush_limit = self.flush_limit.saturating_mul(2); + if self.flush_limit > MAX_PARTIAL_FLUSH_GROUPS { + self.flush_limit = usize::MAX; + } + } else { + self.rows_since_flush = 0; + return Ok(HandleInputResult::OOM); + } + } + // ------------------------------------------------- - // Step 4: Larger-than-memory execution (early emit) + // Step 5: Larger-than-memory execution (early emit) // ------------------------------------------------- let resize_result = self.reservation.try_resize(hash_table.memory_size()); match resize_result { @@ -882,6 +915,18 @@ impl FinalHashAggregateStream { } } +fn partial_flush_groups() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("DF_PARTIAL_FLUSH_GROUPS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(4096) + }) +} + +const MAX_PARTIAL_FLUSH_GROUPS: usize = 1 << 20; + #[cfg(test)] mod tests { use std::sync::Arc; diff --git a/datafusion/physical-plan/src/filter.rs b/datafusion/physical-plan/src/filter.rs index a847e20c6ac82..a08d35de118e6 100644 --- a/datafusion/physical-plan/src/filter.rs +++ b/datafusion/physical-plan/src/filter.rs @@ -355,7 +355,8 @@ impl FilterExec { /// /// A contradictory predicate (e.g. `a = 1 AND a = 2`) yields zero rows and /// empty-column statistics. - pub(crate) fn statistics_helper( + #[doc(hidden)] + pub fn statistics_helper( schema: &SchemaRef, input_stats: Statistics, predicate: &Arc, @@ -1446,6 +1447,16 @@ fn collect_null_rejecting_columns(predicate: &Arc) -> HashSet< } /// Returns the column index and selectivity for a string comparison with a literal. +fn string_equality_default_selectivity() -> f64 { + static SEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *SEL.get_or_init(|| { + std::env::var("DF_STR_EQ_SEL") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0.1) + }) +} + fn string_selectivity( predicate: &Arc, schema: &Schema, @@ -1490,11 +1501,19 @@ fn string_selectivity( return Some((index, 0.0)); }; let column_stats = input_stats.column_statistics.get(index)?; + // Without an NDV, a string equality is assumed to keep fewer rows than an + // arbitrary predicate: string columns compared to a literal are usually + // low-cardinality codes (a brand, a status, a container). + let unknown_ndv_selectivity = if like.is_none() { + string_equality_default_selectivity().min(default_selectivity) + } else { + default_selectivity + }; let equality_selectivity = column_stats .distinct_count .get_value() .filter(|&&ndv| ndv > 0) - .map_or(default_selectivity, |&ndv| 1.0 / ndv as f64); + .map_or(unknown_ndv_selectivity, |&ndv| 1.0 / ndv as f64); let positive_selectivity = match like { Some(like) => like_selectivity( value, @@ -1541,6 +1560,18 @@ fn scale_to_non_null_rows( /// fallback, halved for each anchored end. Thus prefix/suffix patterns are /// estimated to match fewer rows than an unanchored contains pattern. These are /// heuristics, not bounds on the number of matches. +/// Each literal character of a pattern with wildcards makes a match rarer: +/// `%green%` keeps fewer rows than `%g%`. +fn like_char_selectivity() -> f64 { + static SEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *SEL.get_or_init(|| { + std::env::var("DF_LIKE_CHAR_SEL") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0.8) + }) +} + fn like_selectivity( pattern: &str, case_insensitive: bool, @@ -1553,13 +1584,17 @@ fn like_selectivity( let mut starts_with_percent = false; let mut ends_with_percent = false; let mut first = true; + let mut literal_chars = 0i32; while let Some(ch) = chars.next() { let percent = ch == '%'; if ch == '\\' { // Arrow treats a trailing backslash as a literal backslash too. chars.next(); + literal_chars += 1; } else if matches!(ch, '%' | '_') { has_wildcard = true; + } else { + literal_chars += 1; } all_percent &= percent; if first { @@ -1581,7 +1616,10 @@ fn like_selectivity( } else { let start_factor = if starts_with_percent { 1.0 } else { 0.5 }; let end_factor = if ends_with_percent { 1.0 } else { 0.5 }; - default_selectivity * start_factor * end_factor + default_selectivity + * start_factor + * end_factor + * like_char_selectivity().powi(literal_chars).max(0.01) } } diff --git a/datafusion/physical-plan/src/joins/hash_join/partitioned_hash_eval.rs b/datafusion/physical-plan/src/joins/hash_join/partitioned_hash_eval.rs index eabc1bc86f633..3b9c17fcce28e 100644 --- a/datafusion/physical-plan/src/joins/hash_join/partitioned_hash_eval.rs +++ b/datafusion/physical-plan/src/joins/hash_join/partitioned_hash_eval.rs @@ -274,6 +274,54 @@ pub struct HashTableLookupExpr { description: String, /// Shared pruning-only view of the build side's key range pruning_bitmap: Option>, + /// Observed pass rate, shared by every copy of this expression + selectivity: Arc, +} + +/// Tracks how many probe rows a [`HashTableLookupExpr`] keeps. A lookup that +/// keeps nearly every row costs a hash and a probe per row without filtering +/// anything, so after enough rows it stops looking up and keeps every row +/// (as Impala disables ineffective runtime filters). The expression only ever +/// appears in dynamic filters, which may keep extra rows. +#[derive(Debug, Default)] +struct LookupSelectivity { + rows: std::sync::atomic::AtomicU64, + kept: std::sync::atomic::AtomicU64, + disabled: std::sync::atomic::AtomicBool, +} + +impl LookupSelectivity { + fn settings() -> (u64, f64) { + static S: std::sync::OnceLock<(u64, f64)> = std::sync::OnceLock::new(); + *S.get_or_init(|| { + let min_rows = std::env::var("DF_LOOKUP_MIN_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1_000_000); + let max_kept = std::env::var("DF_LOOKUP_MAX_KEPT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0.9); + (min_rows, max_kept) + }) + } + + fn is_disabled(&self) -> bool { + self.disabled.load(std::sync::atomic::Ordering::Relaxed) + } + + fn record(&self, rows: usize, kept: usize) { + use std::sync::atomic::Ordering::Relaxed; + let (min_rows, max_kept) = Self::settings(); + if min_rows == u64::MAX { + return; + } + let total = self.rows.fetch_add(rows as u64, Relaxed) + rows as u64; + let total_kept = self.kept.fetch_add(kept as u64, Relaxed) + kept as u64; + if total >= min_rows && total_kept as f64 > max_kept * total as f64 { + self.disabled.store(true, Relaxed); + } + } } /// The build side a [`HashTableLookupExpr`] checks probe keys against. @@ -412,6 +460,7 @@ impl HashTableLookupExpr { lookup, description, pruning_bitmap, + selectivity: Arc::default(), }) } @@ -420,6 +469,34 @@ impl HashTableLookupExpr { self.pruning_bitmap.as_ref() } + fn evaluate_lookup(&self, batch: &RecordBatch) -> Result { + let join_keys = evaluate_columns(&self.on_columns, batch)?; + + match &self.lookup { + Lookup::Single(map) => { + let map: &Map = map; + match map { + Map::HashMap(map) => with_hashes( + &join_keys, + self.random_state.random_state(), + |hashes| { + let array = map.contain_hashes(hashes); + Ok(ColumnarValue::Array(Arc::new(array))) + }, + ), + Map::ArrayMap(map) => { + let array = map.contain_keys(&join_keys)?; + Ok(ColumnarValue::Array(Arc::new(array))) + } + } + } + Lookup::Routed { router, maps } => { + let array = self.evaluate_routed(&join_keys, router, maps)?; + Ok(ColumnarValue::Array(Arc::new(array))) + } + } + } + /// Membership of each row of `keys` in the map of its routed partition. fn evaluate_routed( &self, @@ -605,6 +682,7 @@ impl PhysicalExpr for HashTableLookupExpr { lookup: self.lookup.clone(), description: self.description.clone(), pruning_bitmap: self.pruning_bitmap.clone(), + selectivity: Arc::clone(&self.selectivity), })) } @@ -617,32 +695,20 @@ impl PhysicalExpr for HashTableLookupExpr { } fn evaluate(&self, batch: &RecordBatch) -> Result { - // Evaluate columns - let join_keys = evaluate_columns(&self.on_columns, batch)?; - - match &self.lookup { - Lookup::Single(map) => { - let map: &Map = map; - match map { - Map::HashMap(map) => with_hashes( - &join_keys, - self.random_state.random_state(), - |hashes| { - let array = map.contain_hashes(hashes); - Ok(ColumnarValue::Array(Arc::new(array))) - }, - ), - Map::ArrayMap(map) => { - let array = map.contain_keys(&join_keys)?; - Ok(ColumnarValue::Array(Arc::new(array))) - } - } - } - Lookup::Routed { router, maps } => { - let array = self.evaluate_routed(&join_keys, router, maps)?; - Ok(ColumnarValue::Array(Arc::new(array))) - } + if self.selectivity.is_disabled() { + return Ok(ColumnarValue::Scalar( + datafusion_common::ScalarValue::Boolean(Some(true)), + )); + } + let result = self.evaluate_lookup(batch)?; + if let ColumnarValue::Array(array) = &result { + let kept = array + .as_any() + .downcast_ref::() + .map_or_else(|| array.len(), |a| a.true_count()); + self.selectivity.record(array.len(), kept); } + Ok(result) } #[cfg(feature = "proto")] fn try_to_proto( @@ -663,6 +729,7 @@ impl PhysicalExpr for HashTableLookupExpr { lookup: _, description: _, pruning_bitmap: _, + selectivity: _, } = self; // HashTableLookupExpr holds a runtime Arc (the build-side hash diff --git a/datafusion/physical-plan/src/joins/utils.rs b/datafusion/physical-plan/src/joins/utils.rs index 2e0cfc68941f8..8b9f0c86a2083 100644 --- a/datafusion/physical-plan/src/joins/utils.rs +++ b/datafusion/physical-plan/src/joins/utils.rs @@ -1082,6 +1082,10 @@ fn estimate_inner_join_cardinality( return Some(Precision::Inexact(0)); } + if let Some(estimate) = estimate_composite_key_cardinality(left_stats, right_stats) { + return Some(estimate); + } + // Follow Spark Catalyst's conservative NDV join estimate: for multi-key // joins, use the most selective key instead of multiplying all key denominators. let mut join_selectivity = Precision::Absent; @@ -1131,6 +1135,35 @@ fn estimate_inner_join_cardinality( } } +/// For a join on several keys, estimates each side's number of distinct key +/// tuples as the product of its keys' distinct counts, capped by its row count +/// (so a side whose keys form a unique key, such as a composite primary key, +/// gets one tuple per row), and divides the Cartesian product by the larger. +fn estimate_composite_key_cardinality( + left_stats: &Statistics, + right_stats: &Statistics, +) -> Option> { + if std::env::var("DF_JOIN_COMPOSITE_NDV").is_ok_and(|v| v == "0") + || left_stats.column_statistics.len() < 2 + { + return None; + } + let tuples = |stats: &Statistics| -> Option { + let rows = *stats.num_rows.get_value()? as u128; + let mut product: u128 = 1; + for column in &stats.column_statistics { + let ndv = *max_distinct_count(&stats.num_rows, column).get_value()? as u128; + product = product.saturating_mul(ndv.max(1)); + } + Some(product.min(rows).max(1)) + }; + let left_rows = *left_stats.num_rows.get_value()? as u128; + let right_rows = *right_stats.num_rows.get_value()? as u128; + let denominator = tuples(left_stats)?.max(tuples(right_stats)?); + let estimate = (left_rows * right_rows / denominator).min(usize::MAX as u128); + Some(Precision::Inexact(estimate as usize)) +} + /// Estimates if inputs are non-overlapping, using input statistics. /// If inputs are disjoint, returns zero estimation, otherwise returns None fn estimate_disjoint_inputs(