diff --git a/Cargo.lock b/Cargo.lock index 843aae1e..86a32166 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -723,6 +723,15 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -820,6 +829,17 @@ dependencies = [ "vob 4.0.1", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -905,6 +925,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -937,6 +963,12 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "const-random" version = "0.1.18" @@ -963,6 +995,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -1044,6 +1085,15 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "csv" version = "1.4.0" @@ -1065,6 +1115,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -1706,6 +1765,18 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -1781,6 +1852,12 @@ version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40404c3f5f511ec4da6fe866ddf6a717c309fdbb69fbbad7b0f3edab8f2e835f" +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + [[package]] name = "fallible-streaming-iterator" version = "0.1.9" @@ -1974,7 +2051,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "wasm-bindgen", ] @@ -1999,6 +2076,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", "wasip2", "wasip3", ] @@ -2113,6 +2191,15 @@ dependencies = [ "cmake", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + [[package]] name = "home" version = "0.5.12" @@ -2138,6 +2225,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2326,9 +2422,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.102" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -2426,6 +2522,15 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2574,6 +2679,16 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.2" @@ -2643,7 +2758,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", - "wasi", + "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.61.2", ] @@ -2728,6 +2843,24 @@ dependencies = [ "libc", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + [[package]] name = "object" version = "0.37.3" @@ -2851,6 +2984,16 @@ dependencies = [ "phf_shared 0.12.1", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared 0.13.1", + "serde", +] + [[package]] name = "phf_generator" version = "0.11.3" @@ -2892,6 +3035,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -3419,6 +3571,49 @@ dependencies = [ "version_check", ] +[[package]] +name = "postgres" +version = "0.19.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ad20e0aa0b24f5a394eab4f78c781d248982b22b25cecc7e3aa46a681605bd" +dependencies = [ + "bytes", + "fallible-iterator", + "futures-util", + "log", + "tokio", + "tokio-postgres", +] + +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64 0.22.1", + "byteorder", + "bytes", + "fallible-iterator", + "hmac", + "md-5", + "memchr", + "rand 0.10.4", + "sha2", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator", + "postgres-protocol", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -3550,6 +3745,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.2", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -3588,6 +3794,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rand_distr" version = "0.4.3" @@ -3907,6 +4119,17 @@ dependencies = [ "unsafe-libyaml-norway", ] +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -4087,6 +4310,17 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -4175,6 +4409,7 @@ dependencies = [ "asap_sketchlib 0.4.0 (git+https://github.com/ProjectASAP/asap_sketchlib?rev=a05b35ce14e4079eaa6acb29dd8c416bd1a2a3d1)", "clap", "futures", + "postgres", "prost", "serde", "serde_json", @@ -4372,6 +4607,32 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "tokio-postgres" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf 0.13.1", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand 0.10.4", + "socket2", + "tokio", + "tokio-util", + "whoami", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -4437,6 +4698,18 @@ dependencies = [ "rand 0.9.4", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -4452,6 +4725,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + [[package]] name = "unicode-reverse" version = "1.0.9" @@ -4607,6 +4886,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4625,14 +4913,22 @@ dependencies = [ "wit-bindgen 0.51.0", ] +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + [[package]] name = "wasm-bindgen" -version = "0.2.125" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -4640,19 +4936,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.75" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "503b14d284f2c8dac03b819967e155ea753f573586193b2b2c95990cb5d69280" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.125" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4660,22 +4957,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.125" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.125" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -4714,6 +5011,16 @@ dependencies = [ "semver", ] +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -4724,6 +5031,19 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs index c1e82d7b..87f16211 100644 --- a/aqpbm-cli/src/benchmark_external_cmd.rs +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -63,7 +63,7 @@ pub struct RunArgs { #[arg(long)] pub run_directory: PathBuf, /// The engine: `fake` (the harness's own fake engine), `clickhouse`, - /// `victoriametrics` or `asapquery-backend`. + /// `victoriametrics`, `asapquery-backend` or `postgresql` (TimescaleDB). #[arg(long)] pub engine: String, /// Only these variants (repeatable); every variant under plans/ by default. diff --git a/docs/system-bench.md b/docs/system-bench.md index 6956a78f..072b2397 100644 --- a/docs/system-bench.md +++ b/docs/system-bench.md @@ -16,7 +16,7 @@ Not every system supports every measurement: |---|---|---|---| | `duckdb` | | yes | | | `clickhouse` | yes | yes | | -| `postgresql` (with TimescaleDB) | | yes | | +| `postgresql` (with TimescaleDB) | yes | yes | | | `druid` | | yes | | | `pilotdb` (over DuckDB) | | yes | | | `victoriametrics` | yes | | | @@ -39,6 +39,7 @@ What to run comes from a run directory: the workloads, and the plans if a system `scripts/plan-suite.sh` prepares a run directory from a suite. `scripts/one-shot-workload.sh` and `scripts/one-shot-clickbench.sh` prepare one and run every system for one-shot queries. `scripts/write-throughput-asapquery-precompute-engine.sh` measures the write throughput of an ASAPQuery precompute engine. +`scripts/timescaledb-variants.sh` adds the TimescaleDB variants to a run directory: `postgresql` runs each query's PromQL text over a hypertable, over continuous aggregates, or with the Toolkit's quantile sketches, as its adapter's module docs say. ## Output diff --git a/scripts/timescaledb-variants.sh b/scripts/timescaledb-variants.sh new file mode 100755 index 00000000..9739ac17 --- /dev/null +++ b/scripts/timescaledb-variants.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Add the TimescaleDB variants to a benchmark-external run directory, for +# `approxbench benchmark-external run --engine postgresql --variant `. +# +# scripts/timescaledb-variants.sh +# +# Each variant runs every workload query's PromQL text (no plan file, "plans": false) and +# runs only when named with --variant ("run_by_default": false), so the other engines' +# runs over the same directory skip it. What each variant computes is in the module docs +# of system-bench/src/engines_external/timescaledb_server.rs: +# timescaledb.hypertable exact, at query time over the raw hypertable +# timescaledb.continuous-aggregate exact, one continuous aggregate per query +# timescaledb.uddsketch quantiles by uddsketch at query time +# timescaledb.tdigest quantiles by tdigest at query time +# timescaledb.continuous-aggregate.uddsketch quantiles by uddsketch per bucket +# timescaledb.continuous-aggregate.tdigest quantiles by tdigest per bucket +# +# Example: scripts/timescaledb-variants.sh /data/run-1 +set -euo pipefail + +run=${1:?run directory} +[ -d "$run/workloads" ] || { echo "$run has no workloads/" >&2; exit 1; } +for line in \ + "timescaledb.hypertable false" \ + "timescaledb.continuous-aggregate false" \ + "timescaledb.uddsketch true" \ + "timescaledb.tdigest true" \ + "timescaledb.continuous-aggregate.uddsketch true" \ + "timescaledb.continuous-aggregate.tdigest true"; do + read -r variant substitutions <<<"$line" + [ -e "$run/plans/$variant" ] && { echo "$run/plans/$variant exists" >&2; exit 1; } + mkdir -p "$run/plans/$variant" + printf '{"substitutions_allowed": %s, "plans": false, "run_by_default": false}\n' "$substitutions" \ + > "$run/plans/$variant/variant.json" +done diff --git a/system-bench/Cargo.toml b/system-bench/Cargo.toml index a0ece251..9ba77dd3 100644 --- a/system-bench/Cargo.toml +++ b/system-bench/Cargo.toml @@ -52,6 +52,7 @@ thiserror.workspace = true prost = "0.13" snap = "1.1" ureq = { version = "2", default-features = false } +postgres = "0.19" [dev-dependencies] aqpbm-datagen.workspace = true diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 6bf0b9b2..d79dc294 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -27,6 +27,7 @@ pub mod plan_file; pub mod postgresql_command_line; mod restart_command; pub mod server_cgroup; +pub mod timescaledb_server; pub mod victoriametrics; pub mod victoriametrics_server; diff --git a/system-bench/src/engines_external/timescaledb_server.rs b/system-bench/src/engines_external/timescaledb_server.rs new file mode 100644 index 00000000..e586be8d --- /dev/null +++ b/system-bench/src/engines_external/timescaledb_server.rs @@ -0,0 +1,1170 @@ +//! A PostgreSQL server with TimescaleDB and the TimescaleDB Toolkit as an +//! engine under test for periodic queries (`--engine postgresql`), started +//! by `scripts/extbench-up-timescaledb.sh`. +//! +//! Each arm is a query-text arm (a variant with `"plans": false`): the +//! adapter reads each workload query's PromQL text and writes its SQL itself. +//! The variant name says how the queries run: +//! +//! | variant | `quantile_over_time` | other functions | +//! |---|---|---| +//! | `timescaledb.hypertable` | `percentile_cont` over the raw rows | plain SQL over the raw rows | +//! | `timescaledb.continuous-aggregate` | `array_agg` per bucket, `percentile_cont` over the window's values | `sum`/`count`/`min`/`max` per bucket; `counter_agg` per bucket for `rate`/`increase` | +//! | `timescaledb.uddsketch` | `approx_percentile` of `uddsketch(200, 0.001, value)` over the raw rows | as `timescaledb.hypertable` | +//! | `timescaledb.tdigest` | `approx_percentile` of `tdigest(100, value)` over the raw rows | as `timescaledb.hypertable` | +//! | `timescaledb.continuous-aggregate.uddsketch` | `uddsketch(200, 0.001, value)` per bucket, `rollup` over the window | as `timescaledb.continuous-aggregate` | +//! | `timescaledb.continuous-aggregate.tdigest` | `tdigest(100, value)` per bucket, `rollup` over the window | as `timescaledb.continuous-aggregate` | +//! +//! The first two are exact; the sketch variants report each sketch as a +//! substitution. No variant uses `hyperloglog`: it counts distinct values, +//! and no PromQL function of the periodic suites does. +//! +//! Queries: `[sum|avg|min|max|count [by (l, ...)]] (f(metric[d]))`, with +//! `f` one of `sum_over_time`, `count_over_time`, `avg_over_time`, +//! `min_over_time`, `max_over_time`, `rate`, `increase`, or +//! `quantile_over_time(φ, metric[d])` with `φ` in [0, 1]. Any other text +//! (label matchers, `offset`, `without`, other functions) is refused at +//! install. Semantics are PromQL's: the window is `(T − d, T]`; the quantile +//! interpolates linearly at rank `φ · (n − 1)` (`percentile_cont`); `rate` +//! and `increase` follow Prometheus `extrapolatedRate` (v3.15.1, as the +//! ClickHouse translator's query-time rate) over at least 2 samples; an +//! aggregation over no series answers nothing. Answers are keyed by the +//! series' labels without `__name__`, or by the `by` labels with empty values +//! left out. +//! +//! Storage: each install has its own schema `bench__`, with one +//! hypertable per metric the queries read (`ts timestamptz`, `value float8`, +//! `series text`: the full label map as compact JSON, and one text column +//! per `by` label). A chunk is one binary `COPY` per metric. Example: +//! `sum by (job) (rate(requests_total[1m]))` reads `"requests_total"` with +//! columns `ts, value, series, job`. +//! +//! Continuous aggregates: one per query, over buckets of `b = gcd(d, +//! evaluation interval)`, bucketed by `time_bucket(b, ts, "offset" => 1 µs)` +//! so a bucket is `(k·b, (k+1)·b]` at the microsecond resolution of +//! `timestamptz`, left-open like the window. Real-time aggregation is off +//! (`timescaledb.materialized_only = true`) and no refresh policy runs: +//! every ingest step ends with `refresh_continuous_aggregate` over the +//! step's buckets, so an evaluation reads complete materialized buckets +//! only, answers exactly, and the refresh is ingest CPU. The raw hypertable +//! stays: TimescaleDB refreshes a continuous aggregate from it. +//! +//! CPU and memory: the server's container cgroup, read on this host or over +//! SSH. PostgreSQL keeps no per-query CPU counter, so [`StepReport`] carries +//! only each query's wall time as the client saw it. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::engine::{ + Answers, ArmSpec, CpuAccounting, EngineDescription, EngineError, EngineUnderTest, Footprint, + InstalledArm, PlanSummary, QueryLanguage, SampleChunk, SeriesLabels, StepReport, WorkloadSpec, +}; +use aqpbm_core::harness::protocol::Protocol; +use postgres::binary_copy::BinaryCopyInWriter; +use postgres::types::{ToSql, Type}; +use postgres::{Client, NoTls}; + +use super::server_cgroup::ServerCgroupOptions; + +/// The column of a series' identity: its label map as compact JSON. +const SERIES: &str = "series"; +/// Column names of the source tables that a label may not take. +const SAMPLE_COLUMNS: [&str; 3] = ["ts", "value", SERIES]; +/// `uddsketch(size, max_error, value)`: the toolkit's `percentile_agg` +/// defaults. +const UDDSKETCH: &str = "uddsketch(200, 0.001, value)"; +/// `tdigest(buckets, value)`. +const TDIGEST: &str = "tdigest(100, value)"; + +/// Where the queries' state lives. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Placement { + /// Every query reads the raw hypertable. + QueryTime, + /// Every query reads its own continuous aggregate. + ContinuousAggregate, +} + +/// How `quantile_over_time` is computed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QuantileMethod { + Exact, + UddSketch, + TDigest, +} + +/// How an arm runs its queries, from its variant name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mode { + pub placement: Placement, + pub quantile: QuantileMethod, +} + +/// Every variant name the adapter runs, with its mode. +pub const VARIANTS: [(&str, Mode); 6] = [ + ( + "timescaledb.hypertable", + Mode { + placement: Placement::QueryTime, + quantile: QuantileMethod::Exact, + }, + ), + ( + "timescaledb.continuous-aggregate", + Mode { + placement: Placement::ContinuousAggregate, + quantile: QuantileMethod::Exact, + }, + ), + ( + "timescaledb.uddsketch", + Mode { + placement: Placement::QueryTime, + quantile: QuantileMethod::UddSketch, + }, + ), + ( + "timescaledb.tdigest", + Mode { + placement: Placement::QueryTime, + quantile: QuantileMethod::TDigest, + }, + ), + ( + "timescaledb.continuous-aggregate.uddsketch", + Mode { + placement: Placement::ContinuousAggregate, + quantile: QuantileMethod::UddSketch, + }, + ), + ( + "timescaledb.continuous-aggregate.tdigest", + Mode { + placement: Placement::ContinuousAggregate, + quantile: QuantileMethod::TDigest, + }, + ), +]; + +impl Mode { + pub fn of_variant(name: &str) -> Result { + VARIANTS + .iter() + .find(|(variant, _)| *variant == name) + .map(|(_, mode)| *mode) + .ok_or_else(|| { + let names: Vec<&str> = VARIANTS.iter().map(|(variant, _)| *variant).collect(); + EngineError(format!( + "variant {name}: engine postgresql runs only the variants {}", + names.join(", ") + )) + }) + } +} + +/// A PromQL range function. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RangeFunction { + SumOverTime, + CountOverTime, + AvgOverTime, + MinOverTime, + MaxOverTime, + QuantileOverTime(f64), + Rate, + Increase, +} + +/// A PromQL aggregation operator. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Aggregation { + Sum, + Avg, + Min, + Max, + Count, +} + +/// A query of the subset in the module docs, e.g. `sum by (job) +/// (rate(requests_total[1m]))`. +#[derive(Debug, Clone, PartialEq)] +pub struct RangeQuery { + /// The outer aggregation and its `by` labels, if any. + pub aggregation: Option<(Aggregation, Vec)>, + pub function: RangeFunction, + pub metric: String, + pub range_ms: u64, +} + +/// Parses `text` as a query of the subset in the module docs. +pub fn parse_query(text: &str) -> Result { + let mut parser = Parser { text, at: 0 }; + let query = parser.query()?; + parser.skip_space(); + if parser.at != text.len() { + return Err(format!("unexpected '{}'", &text[parser.at..])); + } + Ok(query) +} + +struct Parser<'a> { + text: &'a str, + at: usize, +} + +impl Parser<'_> { + fn skip_space(&mut self) { + while self.text[self.at..].starts_with(char::is_whitespace) { + self.at += self.text[self.at..] + .chars() + .next() + .map_or(1, char::len_utf8); + } + } + + fn expect(&mut self, symbol: char) -> Result<(), String> { + self.skip_space(); + if self.text[self.at..].starts_with(symbol) { + self.at += 1; + Ok(()) + } else { + Err(format!( + "expected '{symbol}' at '{}'", + &self.text[self.at..] + )) + } + } + + fn name(&mut self) -> Result { + self.skip_space(); + let rest = &self.text[self.at..]; + let length = rest + .char_indices() + .find(|&(i, c)| { + !(c.is_ascii_alphabetic() || c == '_' || c == ':' || (i > 0 && c.is_ascii_digit())) + }) + .map_or(rest.len(), |(i, _)| i); + if length == 0 { + return Err(format!("expected a name at '{rest}'")); + } + self.at += length; + Ok(rest[..length].to_string()) + } + + fn number(&mut self) -> Result { + self.skip_space(); + let rest = &self.text[self.at..]; + let length = rest + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .unwrap_or(rest.len()); + let number = rest[..length] + .parse() + .map_err(|_| format!("expected a number at '{rest}'"))?; + self.at += length; + Ok(number) + } + + /// A duration such as `1m`, `90s` or `1h30m`, in ms. + fn duration(&mut self) -> Result { + self.skip_space(); + let start = self.at; + let mut total_ms = 0u64; + loop { + let rest = &self.text[self.at..]; + let digits = rest + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(rest.len()); + if digits == 0 { + break; + } + let count: u64 = rest[..digits] + .parse() + .map_err(|_| format!("duration '{rest}'"))?; + let unit_text = &rest[digits..]; + let (unit_ms, unit_length) = [ + ("ms", 1), + ("s", 1_000), + ("m", 60_000), + ("h", 3_600_000), + ("d", 86_400_000), + ] + .into_iter() + .find(|(unit, _)| unit_text.starts_with(unit)) + .map(|(unit, ms)| (ms, unit.len())) + .ok_or_else(|| format!("duration without a unit at '{rest}'"))?; + total_ms += count * unit_ms; + self.at += digits + unit_length; + } + if self.at == start || total_ms == 0 { + return Err(format!("expected a duration at '{}'", &self.text[start..])); + } + Ok(total_ms) + } + + fn query(&mut self) -> Result { + let name = self.name()?; + let aggregation = match name.as_str() { + "sum" => Some(Aggregation::Sum), + "avg" => Some(Aggregation::Avg), + "min" => Some(Aggregation::Min), + "max" => Some(Aggregation::Max), + "count" => Some(Aggregation::Count), + _ => None, + }; + let Some(aggregation) = aggregation else { + return self.range_function(&name); + }; + self.skip_space(); + let mut by = Vec::new(); + if !self.text[self.at..].starts_with('(') { + let keyword = self.name()?; + if keyword != "by" { + return Err(format!("{name} {keyword}: only 'by' is supported")); + } + self.expect('(')?; + loop { + by.push(self.name()?); + self.skip_space(); + if self.text[self.at..].starts_with(',') { + self.at += 1; + } else { + break; + } + } + self.expect(')')?; + } + self.expect('(')?; + let function = self.name()?; + let mut inner = self.range_function(&function)?; + self.expect(')')?; + inner.aggregation = Some((aggregation, by)); + Ok(inner) + } + + fn range_function(&mut self, name: &str) -> Result { + self.expect('(')?; + let function = match name { + "sum_over_time" => RangeFunction::SumOverTime, + "count_over_time" => RangeFunction::CountOverTime, + "avg_over_time" => RangeFunction::AvgOverTime, + "min_over_time" => RangeFunction::MinOverTime, + "max_over_time" => RangeFunction::MaxOverTime, + "rate" => RangeFunction::Rate, + "increase" => RangeFunction::Increase, + "quantile_over_time" => { + let q = self.number()?; + if !(0.0..=1.0).contains(&q) { + return Err(format!("quantile {q} is outside [0, 1]")); + } + self.expect(',')?; + RangeFunction::QuantileOverTime(q) + } + other => return Err(format!("function {other} is not supported")), + }; + let metric = self.name()?; + self.expect('[')?; + let range_ms = self.duration()?; + self.expect(']')?; + self.expect(')')?; + Ok(RangeQuery { + aggregation: None, + function, + metric, + range_ms, + }) + } +} + +/// `"name"`, quoted for SQL. +fn quoted(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn literal(text: &str) -> String { + format!("'{}'", text.replace('\'', "''")) +} + +/// `t` ms as a `timestamptz` expression, e.g. `to_timestamp(1700000100.500)`; +/// `to_timestamp` rounds to the microsecond, so a whole ms is exact. +fn timestamp(t_ms: i64) -> String { + format!( + "to_timestamp({}.{:03})", + t_ms.div_euclid(1000), + t_ms.rem_euclid(1000) + ) +} + +pub fn greatest_common_divisor(a: u64, b: u64) -> u64 { + let (mut x, mut y) = (a, b); + while y != 0 { + (x, y) = (y, x % y); + } + x +} + +/// One query as an arm runs it. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryPlan { + pub id: String, + pub query: RangeQuery, + /// The source table, schema-qualified. + pub source: String, + /// The continuous aggregate (schema-qualified) and its bucket width. + pub continuous_aggregate: Option<(String, u64)>, + pub quantile: QuantileMethod, + pub asked_from_ms: Option, +} + +impl QueryPlan { + /// The per-series key columns: the series identity, then the `by` labels. + fn keys(&self) -> String { + std::iter::once(SERIES.to_string()) + .chain(self.by().iter().map(|label| quoted(label))) + .collect::>() + .join(", ") + } + + fn by(&self) -> &[String] { + match &self.query.aggregation { + Some((_, by)) => by, + None => &[], + } + } + + /// The quantile expression over raw `value`s, e.g. + /// `percentile_cont(0.99) WITHIN GROUP (ORDER BY value)`. + fn quantile_over_values(&self, q: f64) -> String { + match self.quantile { + QuantileMethod::Exact => format!("percentile_cont({q}) WITHIN GROUP (ORDER BY value)"), + QuantileMethod::UddSketch => format!("approx_percentile({q}, {UDDSKETCH})"), + QuantileMethod::TDigest => format!("approx_percentile({q}, {TDIGEST})"), + } + } + + /// The continuous aggregate's definition. + pub fn continuous_aggregate_sql(&self) -> Option { + let (name, bucket_ms) = self.continuous_aggregate.as_ref()?; + let columns = match self.query.function { + RangeFunction::SumOverTime => "sum(value) AS sum_value".to_string(), + RangeFunction::CountOverTime => "count(*) AS sample_count".to_string(), + RangeFunction::AvgOverTime => { + "sum(value) AS sum_value, count(*) AS sample_count".to_string() + } + RangeFunction::MinOverTime => "min(value) AS min_value".to_string(), + RangeFunction::MaxOverTime => "max(value) AS max_value".to_string(), + RangeFunction::QuantileOverTime(_) => match self.quantile { + QuantileMethod::Exact => "array_agg(value) AS sample_values".to_string(), + QuantileMethod::UddSketch => format!("{UDDSKETCH} AS sketch"), + QuantileMethod::TDigest => format!("{TDIGEST} AS sketch"), + }, + RangeFunction::Rate | RangeFunction::Increase => { + "counter_agg(ts, value) AS counter".to_string() + } + }; + let keys = self.keys(); + Some(format!( + "CREATE MATERIALIZED VIEW {name} WITH (timescaledb.continuous, \ + timescaledb.materialized_only = true) AS \ + SELECT time_bucket(INTERVAL '{bucket_ms} milliseconds', ts, \"offset\" => INTERVAL '1 microsecond') AS bucket, \ + {keys}, {columns} FROM {source} GROUP BY bucket, {keys} WITH NO DATA", + source = self.source + )) + } + + /// The SQL of the query at `t_ms`: rows of key columns, then `value`. + pub fn sql(&self, t_ms: i64) -> String { + let keys = self.keys(); + let start = timestamp(t_ms - self.query.range_ms as i64); + let end = timestamp(t_ms); + let per_series = match &self.continuous_aggregate { + None => { + let from = format!("{} WHERE ts > {start} AND ts <= {end}", self.source); + match self.query.function { + RangeFunction::Rate | RangeFunction::Increase => { + let counters = format!( + "SELECT {keys}, count(*) AS n, min(t_ms) AS first_ms, max(t_ms) AS last_ms, \ + min(v_first) AS v_first, \ + max(v_last) - min(v_first) + coalesce(sum(prev) FILTER (WHERE value < prev), 0) \ + AS increase \ + FROM (SELECT {keys}, (extract(epoch FROM ts) * 1000)::bigint AS t_ms, value, \ + lag(value) OVER w AS prev, first_value(value) OVER w AS v_first, \ + last_value(value) OVER (w ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS v_last \ + FROM {from} WINDOW w AS (PARTITION BY {SERIES} ORDER BY ts)) AS samples \ + GROUP BY {keys} HAVING count(*) >= 2" + ); + self.extrapolated(&counters, t_ms) + } + function => { + let expression = match function { + RangeFunction::SumOverTime => "sum(value)".to_string(), + RangeFunction::CountOverTime => "count(*)::float8".to_string(), + RangeFunction::AvgOverTime => "avg(value)".to_string(), + RangeFunction::MinOverTime => "min(value)".to_string(), + RangeFunction::MaxOverTime => "max(value)".to_string(), + RangeFunction::QuantileOverTime(q) => self.quantile_over_values(q), + RangeFunction::Rate | RangeFunction::Increase => unreachable!(), + }; + format!("SELECT {keys}, {expression} AS value FROM {from} GROUP BY {keys}") + } + } + } + Some((name, _)) => { + let from = format!("{name} WHERE bucket > {start} AND bucket <= {end}"); + match self.query.function { + RangeFunction::Rate | RangeFunction::Increase => { + let counters = format!( + "SELECT {keys}, num_elements(c) AS n, \ + (extract(epoch FROM first_time(c)) * 1000)::bigint AS first_ms, \ + (extract(epoch FROM last_time(c)) * 1000)::bigint AS last_ms, \ + first_val(c) AS v_first, delta(c) AS increase \ + FROM (SELECT {keys}, rollup(counter) AS c FROM {from} GROUP BY {keys}) AS rolled \ + WHERE num_elements(c) >= 2" + ); + self.extrapolated(&counters, t_ms) + } + RangeFunction::QuantileOverTime(q) + if self.quantile == QuantileMethod::Exact => + { + format!( + "SELECT {keys}, percentile_cont({q}) WITHIN GROUP (ORDER BY v) AS value \ + FROM {name} CROSS JOIN LATERAL unnest(sample_values) AS v \ + WHERE bucket > {start} AND bucket <= {end} GROUP BY {keys}" + ) + } + function => { + let expression = match function { + RangeFunction::SumOverTime => "sum(sum_value)".to_string(), + RangeFunction::CountOverTime => "sum(sample_count)::float8".to_string(), + RangeFunction::AvgOverTime => { + "sum(sum_value) / sum(sample_count)".to_string() + } + RangeFunction::MinOverTime => "min(min_value)".to_string(), + RangeFunction::MaxOverTime => "max(max_value)".to_string(), + RangeFunction::QuantileOverTime(q) => { + format!("approx_percentile({q}, rollup(sketch))") + } + RangeFunction::Rate | RangeFunction::Increase => unreachable!(), + }; + format!("SELECT {keys}, {expression} AS value FROM {from} GROUP BY {keys}") + } + } + } + }; + match &self.query.aggregation { + None => format!("SELECT {SERIES}, value FROM ({per_series}) AS per_series"), + Some((aggregation, by)) => { + let function = match aggregation { + Aggregation::Sum => "sum(value)", + Aggregation::Avg => "avg(value)", + Aggregation::Min => "min(value)", + Aggregation::Max => "max(value)", + Aggregation::Count => "count(*)::float8", + }; + let columns: Vec = by.iter().map(|label| quoted(label)).collect(); + let (selected, grouped) = if columns.is_empty() { + (String::new(), "()".to_string()) + } else { + (format!("{}, ", columns.join(", ")), columns.join(", ")) + }; + format!( + "SELECT {selected}{function} AS value FROM ({per_series}) AS per_series \ + GROUP BY {grouped} HAVING count(*) > 0" + ) + } + } + } + + /// Prometheus `extrapolatedRate` (`promql/functions.go`, v3.15.1) over + /// `counters`, which gives per series `n`, `first_ms`, `last_ms`, + /// `v_first` and the reset-corrected `increase` of the window's samples + /// (at least 2): the 1.1 × average-gap threshold first, then the + /// zero-point clamp; divided by the range in seconds for a rate. + fn extrapolated(&self, counters: &str, t_ms: i64) -> String { + let keys = self.keys(); + let range_ms = self.query.range_ms as i64; + let per_second = if self.query.function == RangeFunction::Rate { + format!(" / {}", range_ms as f64 / 1000.0) + } else { + String::new() + }; + let start_ms = t_ms - range_ms; + format!( + "SELECT {keys}, increase * (sampled + least(d_start, d_zero) + d_end) / sampled{per_second} AS value \ + FROM (SELECT *, CASE WHEN increase > 0 AND v_first >= 0 THEN sampled * v_first / increase \ + ELSE d_start END AS d_zero \ + FROM (SELECT *, CASE WHEN to_start >= 1.1 * avg_gap THEN avg_gap / 2 ELSE to_start END AS d_start, \ + CASE WHEN to_end >= 1.1 * avg_gap THEN avg_gap / 2 ELSE to_end END AS d_end \ + FROM (SELECT {keys}, increase::float8 AS increase, v_first::float8 AS v_first, \ + (last_ms - first_ms) / 1000.0::float8 AS sampled, \ + (last_ms - first_ms) / 1000.0::float8 / (n - 1) AS avg_gap, \ + (first_ms - ({start_ms})) / 1000.0::float8 AS to_start, \ + ({t_ms} - last_ms) / 1000.0::float8 AS to_end \ + FROM ({counters}) AS counters) AS gaps) AS starts) AS extrapolation" + ) + } + + /// What the query's answer rows are keyed by. + fn answer_key(&self) -> AnswerKey { + match &self.query.aggregation { + None => AnswerKey::Series, + Some((_, by)) => AnswerKey::Labels(by.clone()), + } + } + + /// The sketch this query answers with instead of the exact quantile. + fn substitution(&self) -> Option { + let RangeFunction::QuantileOverTime(_) = self.query.function else { + return None; + }; + let sketch = match self.quantile { + QuantileMethod::Exact => return None, + QuantileMethod::UddSketch => UDDSKETCH, + QuantileMethod::TDigest => TDIGEST, + }; + Some(format!( + "approx_percentile of {sketch} for quantile_over_time at query {}: approximate", + self.id + )) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum AnswerKey { + /// The first column is the series identity. + Series, + /// The first columns are these labels. + Labels(Vec), +} + +/// Per metric, the label columns of its source table, e.g. `latency` → `[job]`. +pub type LabelColumns = BTreeMap>; + +/// The queries of `workload` as an arm in `mode` runs them in `schema`, and +/// the label columns of each metric's source table. Refuses a query outside +/// the subset in the module docs. +pub fn plan_queries( + workload: &WorkloadSpec, + mode: Mode, + schema: &str, +) -> Result<(Vec, LabelColumns), EngineError> { + let mut plans = Vec::new(); + let mut label_columns = LabelColumns::new(); + for (index, query) in workload.queries.iter().enumerate() { + let text = query + .text_in(QueryLanguage::PromQl) + .ok_or_else(|| EngineError(format!("query {} has no PromQL text", query.id)))?; + let parsed = parse_query(text) + .map_err(|error| EngineError(format!("query {} ('{text}'): {error}", query.id)))?; + if parsed.range_ms != query.window_ms { + return Err(EngineError(format!( + "query {} reads [{} ms] but its window is {} ms", + query.id, parsed.range_ms, query.window_ms + ))); + } + let columns = label_columns.entry(parsed.metric.clone()).or_default(); + if let Some((_, by)) = &parsed.aggregation { + for label in by { + if SAMPLE_COLUMNS.contains(&label.as_str()) || label == "__name__" { + return Err(EngineError(format!( + "query {}: grouping by {label} is not supported", + query.id + ))); + } + if !columns.contains(label) { + columns.push(label.clone()); + } + } + } + let continuous_aggregate = (mode.placement == Placement::ContinuousAggregate).then(|| { + ( + format!("{schema}.{}", quoted(&format!("q{index}_{}", query.id))), + greatest_common_divisor(parsed.range_ms, query.evaluation_interval_ms), + ) + }); + plans.push(QueryPlan { + id: query.id.clone(), + source: format!("{schema}.{}", quoted(&parsed.metric)), + query: parsed, + continuous_aggregate, + quantile: mode.quantile, + asked_from_ms: workload.asked_from_ms(query), + }); + } + Ok((plans, label_columns)) +} + +/// How to reach the server. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TimescaleDbServer { + /// A libpq connection string, e.g. `host=10.0.0.1 port=5432 dbname=bench`. + pub connection: String, + /// Applied with `SET` on every connection, e.g. + /// `max_parallel_workers_per_gather=0`. + pub settings: Vec<(String, String)>, + pub cgroup: Option, +} + +impl TimescaleDbServer { + fn connect(&self) -> Result { + let mut client = Client::connect(&self.connection, NoTls).map_err(|error| { + EngineError(format!("PostgreSQL at '{}': {error}", self.connection)) + })?; + for (name, value) in &self.settings { + client + .batch_execute(&format!("SET {} = {}", quoted(name), literal(value))) + .map_err(|error| EngineError(format!("SET {name}: {error}")))?; + } + Ok(client) + } +} + +/// A TimescaleDB server; see the module docs. +pub struct TimescaleDbEngine { + server: TimescaleDbServer, + description: EngineDescription, + schema_prefix: String, +} + +/// Installs made by this process: numbers each install's schema. +static INSTALL_COUNT: AtomicU64 = AtomicU64::new(0); + +fn sql_error(what: &str) -> impl Fn(postgres::Error) -> EngineError + '_ { + move |error| { + let detail = error + .as_db_error() + .map(|db| db.message().to_string()) + .unwrap_or_else(|| error.to_string()); + EngineError(format!("{what}: {detail}")) + } +} + +impl TimescaleDbEngine { + /// Connects, checks both extensions and reads the server version. Schemas + /// of an earlier run (`bench_*`) are refused: dropping them would be + /// charged to this run. + pub fn new(server: TimescaleDbServer) -> Result { + let mut client = server.connect()?; + let extensions: Vec = client + .query( + "SELECT extname FROM pg_extension WHERE extname IN ('timescaledb', 'timescaledb_toolkit')", + &[], + ) + .map_err(sql_error("reading extensions"))? + .iter() + .map(|row| row.get(0)) + .collect(); + for needed in ["timescaledb", "timescaledb_toolkit"] { + if !extensions.iter().any(|name| name == needed) { + return Err(EngineError(format!( + "the database has no extension {needed}: CREATE EXTENSION {needed}" + ))); + } + } + let leftovers: Vec = client + .query( + "SELECT nspname::text FROM pg_namespace WHERE nspname LIKE 'bench\\_%' ORDER BY 1", + &[], + ) + .map_err(sql_error("reading schemas"))? + .iter() + .map(|row| row.get(0)) + .collect(); + if !leftovers.is_empty() { + return Err(EngineError(format!( + "the database holds schemas of an earlier run: {}; start the server from an empty data dir", + leftovers.join(", ") + ))); + } + let version: String = client + .query_one( + "SELECT current_setting('server_version') || ' with ' || \ + (SELECT string_agg(extname || ' ' || extversion, ', ' ORDER BY extname) \ + FROM pg_extension WHERE extname <> 'plpgsql')", + &[], + ) + .map_err(sql_error("reading the version"))? + .get(0); + let settings: Vec = server + .settings + .iter() + .map(|(name, value)| format!("{name}={value}")) + .collect(); + Ok(TimescaleDbEngine { + description: EngineDescription { + id: "postgresql".into(), + version: format!("PostgreSQL {version}"), + version_dirty: false, + build_profile: if settings.is_empty() { + "server settings".into() + } else { + settings.join(" ") + }, + }, + schema_prefix: format!("bench_{}", std::process::id()), + server, + }) + } +} + +impl EngineUnderTest for TimescaleDbEngine { + fn description(&self) -> EngineDescription { + self.description.clone() + } + + fn cpu_accounting(&self) -> CpuAccounting { + match &self.server.cgroup { + Some(source) => CpuAccounting::Cgroup(source.clone()), + None => CpuAccounting::NotMeasured, + } + } + + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + if arm.engine_options.get("plan_file").is_some() { + return Err(EngineError( + "engine postgresql runs each query's PromQL text and installs no plan file: give \ + it a variant with plans: false (scripts/timescaledb-variants.sh)" + .into(), + )); + } + let mode = Mode::of_variant(&arm.name)?; + let schema = format!( + "{}_{}", + self.schema_prefix, + INSTALL_COUNT.fetch_add(1, Ordering::Relaxed) + ); + let (queries, label_columns) = plan_queries(workload, mode, &schema)?; + let mut client = self.server.connect()?; + let mut statements = vec![format!("CREATE SCHEMA {schema}")]; + let sources: Vec = label_columns + .into_iter() + .map(|(metric, labels)| SourceTable { + table: format!("{schema}.{}", quoted(&metric)), + metric, + labels, + }) + .collect(); + for source in &sources { + let labels: String = source + .labels + .iter() + .map(|label| format!(", {} text NOT NULL", quoted(label))) + .collect(); + statements.push(format!( + "CREATE TABLE {} (ts timestamptz NOT NULL, value float8 NOT NULL, {SERIES} text NOT NULL{labels})", + source.table + )); + statements.push(format!( + "SELECT create_hypertable({}, by_range('ts', INTERVAL '1 day'))", + literal(&source.table) + )); + } + statements.extend( + queries + .iter() + .filter_map(QueryPlan::continuous_aggregate_sql), + ); + let summary = PlanSummary { + text: statements + .iter() + .map(|statement| format!("{statement};\n")) + .chain( + queries + .iter() + .map(|query| format!("-- {}\n{};\n", query.id, query.sql(0))), + ) + .collect(), + node_kinds: Vec::new(), + stored_outputs: queries + .iter() + .filter_map(|query| query.continuous_aggregate.as_ref()) + .map(|(name, _)| name.clone()) + .collect(), + substitutions: queries.iter().filter_map(QueryPlan::substitution).collect(), + sharing_lost: Vec::new(), + }; + client + .batch_execute(&statements[0]) + .map_err(sql_error("creating the schema"))?; + // From here on, dropping the arm drops the schema. + let mut installed = TimescaleDbArm { + client: RefCell::new(client), + schema, + sources, + queries, + // Every sample is after the data start, a multiple of each + // bucket width; refreshing from -infinity instead would commit + // once per batch of empty buckets since the epoch. + refreshed_until_ms: workload.data_start_ms(), + summary, + }; + for statement in &statements[1..] { + installed + .client + .get_mut() + .batch_execute(statement) + .map_err(sql_error(statement))?; + } + Ok(Box::new(installed)) + } +} + +/// A metric's hypertable and its label columns. +struct SourceTable { + metric: String, + table: String, + labels: Vec, +} + +/// One installed arm: its schema and the queries it answers. +struct TimescaleDbArm { + /// In a cell: [`InstalledArm::footprint`] reads sizes through `&self`. + client: RefCell, + schema: String, + sources: Vec, + queries: Vec, + /// The end of the last refreshed ingest step (at first, the data start). + refreshed_until_ms: Option, + summary: PlanSummary, +} + +impl Drop for TimescaleDbArm { + fn drop(&mut self) { + // Best effort: a server that is gone keeps nothing anyway. + let _ = self + .client + .get_mut() + .batch_execute(&format!("DROP SCHEMA IF EXISTS {} CASCADE", self.schema)); + } +} + +/// One source-table row: `ts`, `value`, `series`, then the label columns. +type Row = (SystemTime, f64, String, Vec); + +fn system_time(ts_ms: i64) -> SystemTime { + if ts_ms >= 0 { + UNIX_EPOCH + Duration::from_millis(ts_ms as u64) + } else { + UNIX_EPOCH - Duration::from_millis(ts_ms.unsigned_abs()) + } +} + +impl TimescaleDbArm { + /// `hypertable_size` of a hypertable or a continuous aggregate. + fn size(&self, relation: &str) -> Result { + let bytes: Option = self + .client + .borrow_mut() + .query_one("SELECT hypertable_size($1::text::regclass)", &[&relation]) + .map_err(sql_error(relation))? + .get(0); + Ok(bytes.unwrap_or(0).max(0) as u64) + } +} + +impl InstalledArm for TimescaleDbArm { + fn plan_summary(&self) -> PlanSummary { + self.summary.clone() + } + + fn ingest(&mut self, chunk: &SampleChunk) -> Result { + // One pass over the chunk: each sample's row goes to its metric's + // table; a metric no query reads is skipped. + let mut rows: Vec> = (0..self.sources.len()).map(|_| Vec::new()).collect(); + for sample in &chunk.samples { + let Some(at) = sample.labels.get("__name__").and_then(|metric| { + self.sources + .iter() + .position(|source| &source.metric == metric) + }) else { + continue; + }; + let labels = self.sources[at] + .labels + .iter() + .map(|label| sample.labels.get(label).cloned().unwrap_or_default()) + .collect(); + rows[at].push(( + system_time(sample.ts_ms), + sample.value, + serde_json::to_string(sample.labels.as_ref()).expect("a string map serializes"), + labels, + )); + } + for (source, rows) in self.sources.iter().zip(&rows) { + if rows.is_empty() { + continue; + } + let columns: String = source + .labels + .iter() + .map(|label| format!(", {}", quoted(label))) + .collect(); + let mut types = vec![Type::TIMESTAMPTZ, Type::FLOAT8, Type::TEXT]; + types.extend(source.labels.iter().map(|_| Type::TEXT)); + let sink = self + .client + .get_mut() + .copy_in(&format!( + "COPY {} (ts, value, {SERIES}{columns}) FROM STDIN (FORMAT binary)", + source.table + )) + .map_err(sql_error("COPY"))?; + let mut writer = BinaryCopyInWriter::new(sink, &types); + for (ts, value, series, labels) in rows { + let mut row: Vec<&(dyn ToSql + Sync)> = vec![ts, value, series]; + row.extend(labels.iter().map(|label| label as &(dyn ToSql + Sync))); + writer.write(&row).map_err(sql_error("COPY"))?; + } + writer.finish().map_err(sql_error("COPY"))?; + } + let start = match self.refreshed_until_ms { + Some(ms) => format!("{} + INTERVAL '1 microsecond'", timestamp(ms)), + None => "NULL".into(), + }; + let end = format!("{} + INTERVAL '1 microsecond'", timestamp(chunk.end_ms)); + for (name, _) in self + .queries + .iter() + .filter_map(|query| query.continuous_aggregate.as_ref()) + { + // One statement per call: a refresh may not run in a transaction block. + self.client + .get_mut() + .batch_execute(&format!( + "CALL refresh_continuous_aggregate({}, {start}, {end})", + literal(name) + )) + .map_err(sql_error("refreshing a continuous aggregate"))?; + } + self.refreshed_until_ms = Some(chunk.end_ms); + Ok(StepReport::default()) + } + + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError> { + let mut answers = BTreeMap::new(); + let mut report = StepReport::default(); + for query in &self.queries { + if query.asked_from_ms.is_some_and(|from_ms| at_ms < from_ms) { + continue; + } + if let Some((_, bucket_ms)) = &query.continuous_aggregate { + if at_ms.rem_euclid(*bucket_ms as i64) != 0 { + return Err(EngineError(format!( + "query {} reads buckets of {bucket_ms} ms, so it answers only at their ends, not at {at_ms} ms", + query.id + ))); + } + } + let started = Instant::now(); + let rows = self + .client + .get_mut() + .query(&query.sql(at_ms), &[]) + .map_err(sql_error(&format!("query {}", query.id)))?; + report + .query_wall_ns + .insert(query.id.clone(), started.elapsed().as_nanos() as u64); + let mut series = BTreeMap::new(); + let key = query.answer_key(); + for row in rows { + let value: Option = row.get(row.len() - 1); + let value = value + .ok_or_else(|| EngineError(format!("query {}: a NULL value", query.id)))?; + let labels: SeriesLabels = match &key { + AnswerKey::Series => { + let identity: String = row.get(0); + let mut labels: SeriesLabels = + serde_json::from_str(&identity).map_err(|error| { + EngineError(format!("series identity '{identity}': {error}")) + })?; + labels.remove("__name__"); + labels + } + AnswerKey::Labels(by) => by + .iter() + .enumerate() + .map(|(i, label)| (label.clone(), row.get::<_, String>(i))) + .filter(|(_, value)| !value.is_empty()) + .collect(), + }; + if series.insert(labels.clone(), value).is_some() { + return Err(EngineError(format!( + "query {}: two rows for the series {labels:?}", + query.id + ))); + } + } + answers.insert(query.id.clone(), series); + } + Ok((Answers(answers), report)) + } + + fn footprint(&self) -> Result { + let mut footprint = Footprint::default(); + for source in &self.sources { + footprint.raw_retained_bytes += self.size(&source.table)?; + } + for view in &self.summary.stored_outputs { + footprint.view_bytes += self.size(view)?; + } + Ok(footprint) + } +} + +#[derive(clap::Args, Debug, Clone)] +pub struct TimescaleDbOptions { + #[arg( + long, + help = "A PostgreSQL connection string for psql, for example \"host=127.0.0.1 port=5432 dbname=bench\"; engine postgresql connects any system that speaks the PostgreSQL protocol this way, which is how TimescaleDB is connected" + )] + pub postgresql_connection: Option, + #[arg( + long = "postgresql-setting", + value_parser = super::parse_setting, + help = "A setting applied with SET before every query, as name=value, for example max_parallel_workers_per_gather=0 (repeatable)" + )] + pub postgresql_settings: Vec<(String, String)>, + #[command(flatten)] + pub cgroup: ServerCgroupOptions, +} + +pub fn periodic_queries( + matches: &clap::ArgMatches, + _: &Protocol, +) -> anyhow::Result> { + let options = ::from_arg_matches(matches)?; + let Some(connection) = options.postgresql_connection else { + anyhow::bail!("engine postgresql needs --postgresql-connection"); + }; + Ok(Box::new(TimescaleDbEngine::new(TimescaleDbServer { + connection, + settings: options.postgresql_settings, + cgroup: options.cgroup.source(), + })?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timestamps_are_exact_milliseconds() { + assert_eq!(timestamp(1_700_000_100_500), "to_timestamp(1700000100.500)"); + assert_eq!(timestamp(-1_500), "to_timestamp(-2.500)"); + assert_eq!(timestamp(0), "to_timestamp(0.000)"); + } + + #[test] + fn identifiers_and_literals_are_escaped() { + assert_eq!(quoted("a\"b"), "\"a\"\"b\""); + assert_eq!(literal("it's"), "'it''s'"); + } +} diff --git a/system-bench/src/registry.rs b/system-bench/src/registry.rs index a83822b4..f56574e5 100644 --- a/system-bench/src/registry.rs +++ b/system-bench/src/registry.rs @@ -17,6 +17,7 @@ use crate::engines_external::druid_sql::{self, DruidOptions}; use crate::engines_external::duckdb_command_line::{self, DuckDbOptions}; use crate::engines_external::pilotdb::{self, PilotDbOptions}; use crate::engines_external::postgresql_command_line::{self, PostgreSqlOptions}; +use crate::engines_external::timescaledb_server::{self, TimescaleDbOptions}; use crate::engines_external::victoriametrics_server::{self, VictoriaMetricsOptions}; pub struct System { @@ -114,7 +115,10 @@ pub const SYSTEMS: &[System] = &[ }, System { name: "postgresql", - periodic_queries: None, + periodic_queries: Some(PeriodicQueries { + options: TimescaleDbOptions::augment_args, + build: timescaledb_server::periodic_queries, + }), write_throughput: None, one_shot_queries: Some(OneShotQueries { dialect: postgresql_command_line::DIALECT, diff --git a/system-bench/tests/timescaledb_conformance.rs b/system-bench/tests/timescaledb_conformance.rs new file mode 100644 index 00000000..6b2f9ab5 --- /dev/null +++ b/system-bench/tests/timescaledb_conformance.rs @@ -0,0 +1,483 @@ +//! Conformance of the TimescaleDB adapter against a real server +//! (`#[ignore]`: set `AQPBM_POSTGRESQL_CONNECTION` to a libpq connection +//! string of a server started with `scripts/extbench-up-timescaledb.sh`). +//! Each case installs a workload on every variant, ingests hand-made chunks +//! and compares the answers with hand-computed ones: exact variants to 1e-9 +//! relative, sketch variants within the stated bound. Run with +//! `--test-threads 1`: the cases share the server. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use aqpbm_core::harness::data::Sample; +use aqpbm_core::harness::engine::{ + Answers, ArmSpec, EngineUnderTest, InstalledArm, QueryLanguage, QueryText, SampleChunk, + SeriesLabels, WorkloadQuery, WorkloadSpec, +}; +use system_bench::engines_external::timescaledb_server::{ + QuantileMethod, TimescaleDbEngine, TimescaleDbServer, VARIANTS, +}; + +fn engine() -> TimescaleDbEngine { + TimescaleDbEngine::new(TimescaleDbServer { + connection: std::env::var("AQPBM_POSTGRESQL_CONNECTION") + .expect("AQPBM_POSTGRESQL_CONNECTION"), + settings: vec![("max_parallel_workers_per_gather".into(), "0".into())], + cgroup: None, + }) + .expect("the server answers") +} + +fn arm(variant: &str) -> ArmSpec { + ArmSpec { + name: variant.into(), + raw_data_retained: true, + engine_options: serde_json::json!({}), + } +} + +/// Queries `q0`, `q1`, … of `texts`, each over `window_ms`, every 10 s. +fn workload(texts: &[&str], window_ms: u64) -> WorkloadSpec { + WorkloadSpec::periodic( + "conformance".into(), + texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + dialect: None, + }], + window_ms, + evaluation_interval_ms: 10_000, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![], + ) +} + +fn series(pairs: &[(&str, &str)]) -> Arc { + Arc::new( + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ) +} + +/// `samples` cut into time-ordered 10 s chunks `(end − 10 s, end]`. +fn chunks(mut samples: Vec) -> Vec { + samples.sort_by_key(|s| s.ts_ms); + let mut out: Vec = Vec::new(); + for sample in samples { + let end_ms = (sample.ts_ms + 9_999).div_euclid(10_000) * 10_000; + match out.last_mut() { + Some(chunk) if chunk.end_ms == end_ms => chunk.samples.push(sample), + _ => out.push(SampleChunk { + end_ms, + samples: vec![sample], + }), + } + } + out +} + +/// Answers of query `q` as (labels joined by `,`, value). +fn rows(answers: &Answers, index: usize) -> BTreeMap { + answers + .0 + .get(&format!("q{index}")) + .into_iter() + .flatten() + .map(|(labels, value)| { + assert!(!labels.contains_key("__name__"), "{labels:?}"); + let key: Vec = labels.iter().map(|(n, v)| format!("{n}={v}")).collect(); + (key.join(","), *value) + }) + .collect() +} + +fn assert_rows( + context: &str, + got: &BTreeMap, + expected: &[(&str, f64)], + tolerance: f64, +) { + assert_eq!(got.len(), expected.len(), "{context}: {got:?}"); + for (key, want) in expected { + let value = got + .get(*key) + .unwrap_or_else(|| panic!("{context}: no {key} in {got:?}")); + assert!( + (value - want).abs() <= tolerance * want.abs().max(1.0), + "{context}: {key}: {value} vs {want}" + ); + } +} + +/// Every variant: install `texts`, ingest `samples`, evaluate at `at_ms`. +fn answers_of_every_variant( + engine: &TimescaleDbEngine, + texts: &[&str], + window_ms: u64, + samples: &[Sample], + at_ms: i64, +) -> Vec<(&'static str, QuantileMethod, Answers, Box)> { + let chunks = chunks(samples.to_vec()); + VARIANTS + .iter() + .map(|(variant, mode)| { + let mut installed = engine + .install(&workload(texts, window_ms), &arm(variant)) + .unwrap_or_else(|e| panic!("{variant}: {e}")); + for chunk in chunks.iter().filter(|chunk| chunk.end_ms <= at_ms) { + installed + .ingest(chunk) + .unwrap_or_else(|e| panic!("{variant}: {e}")); + } + let (answers, _) = installed + .evaluate(at_ms) + .unwrap_or_else(|e| panic!("{variant}: {e}")); + (*variant, mode.quantile, answers, installed) + }) + .collect() +} + +/// A sketch's bound around the order statistics next to PromQL's rank: +/// the toolkit's `approx_percentile` returns a value near one order +/// statistic, not PromQL's linear interpolation between two, so with 60 +/// samples its 0.99 quantile is near the 59th or 60th value, not 59.41. +/// uddsketch(200, 0.001) is within 0.1 % relative of a value while it has +/// not collapsed (here, values 1..120); tdigest(100) within 2 %. +fn assert_quantile( + context: &str, + method: QuantileMethod, + got: &BTreeMap, + expected: &[(&str, f64, (f64, f64))], +) { + if method == QuantileMethod::Exact { + let exact: Vec<(&str, f64)> = expected.iter().map(|(k, v, _)| (*k, *v)).collect(); + return assert_rows(context, got, &exact, 1e-9); + } + let tolerance = if method == QuantileMethod::UddSketch { + 0.002 + } else { + 0.02 + }; + assert_eq!(got.len(), expected.len(), "{context}: {got:?}"); + for (key, _, (low, high)) in expected { + let value = got[*key]; + assert!( + value >= low * (1.0 - tolerance) && value <= high * (1.0 + tolerance), + "{context}: {key}: {value} outside [{low}, {high}] ± {tolerance}" + ); + } +} + +/// `sum/count/min/max/avg_over_time` grouped by job at 1 m over job a (1.0 +/// and 0.5 each second) and b (2.0): at 120 s sum a 90, b 120; count a 120, +/// b 60; min a 0.5, b 2; max a 1, b 2; avg a 0.75, b 2. +#[test] +#[ignore = "needs a TimescaleDB server"] +fn grouped_sums_counts_minimums_maximums_and_averages() { + let engine = engine(); + let samples: Vec = (1..=120) + .flat_map(|s: i64| { + [("a", "1", 1.0), ("a", "2", 0.5), ("b", "1", 2.0)] + .into_iter() + .map(move |(job, id, value)| Sample { + labels: series(&[("__name__", "latency"), ("job", job), ("id", id)]), + ts_ms: s * 1000, + value, + }) + }) + .collect(); + let texts = [ + "sum by (job) (sum_over_time(latency[1m]))", + "sum by (job) (count_over_time(latency[1m]))", + "min by (job) (min_over_time(latency[1m]))", + "max by (job) (max_over_time(latency[1m]))", + "avg by (job) (avg_over_time(latency[1m]))", + ]; + for (variant, _, answers, installed) in + answers_of_every_variant(&engine, &texts, 60_000, &samples, 120_000) + { + for (index, expected) in [ + [("job=a", 90.0), ("job=b", 120.0)], + [("job=a", 120.0), ("job=b", 60.0)], + [("job=a", 0.5), ("job=b", 2.0)], + [("job=a", 1.0), ("job=b", 2.0)], + [("job=a", 0.75), ("job=b", 2.0)], + ] + .iter() + .enumerate() + { + assert_rows(variant, &rows(&answers, index), expected, 1e-9); + } + let footprint = installed.footprint().unwrap(); + let continuous = variant.starts_with("timescaledb.continuous-aggregate"); + assert!( + footprint.raw_retained_bytes > 0 && (footprint.view_bytes > 0) == continuous, + "{variant}: {footprint:?}" + ); + assert!( + installed.plan_summary().substitutions.is_empty(), + "{variant}" + ); + } +} + +/// `quantile_over_time(0.99)` of 1..60 per series over (60 s, 120 s]: 1 + +/// 0.99 · 59 = 59.41 and twice that; `avg by (job)` of the 0.9 quantiles +/// (54.1 and 108.2): 81.15. A sketch variant answers near the order +/// statistics next to those ranks, and reports its substitution. +#[test] +#[ignore = "needs a TimescaleDB server"] +fn quantiles_and_their_averages() { + let engine = engine(); + let samples: Vec = (61..=120) + .flat_map(|s: i64| { + [("1", 1.0), ("2", 2.0)] + .into_iter() + .map(move |(id, base)| Sample { + labels: series(&[("__name__", "latency"), ("job", "a"), ("id", id)]), + ts_ms: s * 1000, + value: base * (s - 60) as f64, + }) + }) + .collect(); + let texts = [ + "quantile_over_time(0.99, latency[1m])", + "avg by (job) (quantile_over_time(0.9, latency[1m]))", + ]; + for (variant, method, answers, installed) in + answers_of_every_variant(&engine, &texts, 60_000, &samples, 120_000) + { + assert_quantile( + variant, + method, + &rows(&answers, 0), + &[ + ("id=1,job=a", 59.41, (59.0, 60.0)), + ("id=2,job=a", 2.0 * 59.41, (118.0, 120.0)), + ], + ); + assert_quantile( + variant, + method, + &rows(&answers, 1), + &[("job=a", 81.15, (81.0, 82.5))], + ); + println!("{variant}: {:?} {:?}", rows(&answers, 0), rows(&answers, 1)); + assert_eq!( + installed.plan_summary().substitutions.len(), + if method == QuantileMethod::Exact { + 0 + } else { + 2 + }, + "{variant}" + ); + } +} + +/// The counter data of the ClickHouse conformance case (x, y, z, w), each +/// series in its own job, over 600 s. +fn counter_samples() -> Vec { + let mut samples = Vec::new(); + for s in 1..=600i64 { + let x = if s <= 450 { s } else { s - 450 } as f64; + let y = if s <= 360 { 3 * s } else { s - 360 } as f64; + let z = if s < 400 { + s as f64 + } else if s < 500 { + (s - 5) as f64 + } else { + (s - 500) as f64 / 2.0 + }; + for (job, value) in [("x", x), ("y", y), ("z", z)] { + samples.push(Sample { + labels: series(&[("__name__", "requests_total"), ("job", job)]), + ts_ms: s * 1000, + value, + }); + } + if s % 10 == 5 { + samples.push(Sample { + labels: series(&[("__name__", "requests_total"), ("job", "w")]), + ts_ms: s * 1000, + value: s as f64, + }); + } + } + samples +} + +/// Prometheus' rate over (300 s, 600 s] (the ClickHouse query-time case): +/// x 1, y 417/299, z 642/299, w 1, per series and summed by job; increase +/// is the rate times 300. +#[test] +#[ignore = "needs a TimescaleDB server"] +fn rate_and_increase_are_promql() { + let engine = engine(); + let texts = [ + "rate(requests_total[5m])", + "sum by (job) (rate(requests_total[5m]))", + "increase(requests_total[5m])", + ]; + let rates = [ + ("job=x", 1.0), + ("job=y", 417.0 / 299.0), + ("job=z", 642.0 / 299.0), + ("job=w", 1.0), + ]; + let increases: Vec<(&str, f64)> = rates.iter().map(|(k, v)| (*k, v * 300.0)).collect(); + for (variant, _, answers, _) in + answers_of_every_variant(&engine, &texts, 300_000, &counter_samples(), 600_000) + { + assert_rows(variant, &rows(&answers, 0), &rates, 1e-9); + assert_rows(variant, &rows(&answers, 1), &rates, 1e-9); + assert_rows(variant, &rows(&answers, 2), &increases, 1e-9); + } +} + +/// The window is (T − 1 m, T]: at 120 s, samples at 60 s and 120 s, 30 s +/// apart, give one sample in the window plus one on its start; only the one +/// at 120 s counts. At 130 s the sample at 120 s is still counted. +#[test] +#[ignore = "needs a TimescaleDB server"] +fn the_window_is_left_open() { + let engine = engine(); + let samples: Vec = [60, 90, 120] + .into_iter() + .map(|s: i64| Sample { + labels: series(&[("__name__", "latency"), ("job", "a")]), + ts_ms: s * 1000, + value: s as f64, + }) + .collect(); + let chunks = chunks(samples); + for (variant, _) in VARIANTS { + let mut installed = engine + .install( + &workload( + &["count_over_time(latency[1m])", "sum_over_time(latency[1m])"], + 60_000, + ), + &arm(variant), + ) + .unwrap(); + let mut ingested = 0; + for at_ms in [120_000, 130_000, 150_000] { + while ingested < chunks.len() && chunks[ingested].end_ms <= at_ms { + installed.ingest(&chunks[ingested]).unwrap(); + ingested += 1; + } + if at_ms == 130_000 { + installed + .ingest(&SampleChunk { + end_ms: 130_000, + samples: vec![], + }) + .unwrap(); + } + if at_ms == 150_000 { + for end_ms in [140_000, 150_000] { + installed + .ingest(&SampleChunk { + end_ms, + samples: vec![], + }) + .unwrap(); + } + } + let (answers, _) = installed.evaluate(at_ms).unwrap(); + let (count, sum) = match at_ms { + 120_000 => (2.0, 210.0), + 130_000 => (2.0, 210.0), + _ => (1.0, 120.0), + }; + assert_rows( + &format!("{variant} at {at_ms}"), + &rows(&answers, 0), + &[("job=a", count)], + 1e-9, + ); + assert_rows( + &format!("{variant} at {at_ms}"), + &rows(&answers, 1), + &[("job=a", sum)], + 1e-9, + ); + } + } +} + +/// Two installs of one workload hold their own data and answer alike; a +/// dropped arm leaves no schema, and a server holding one is refused. +#[test] +#[ignore = "needs a TimescaleDB server"] +fn installs_are_isolated_and_dropped() { + let engine = engine(); + let samples: Vec = (1..=60) + .map(|s: i64| Sample { + labels: series(&[("__name__", "latency"), ("job", "a")]), + ts_ms: s * 1000, + value: s as f64, + }) + .collect(); + let chunks = chunks(samples); + let texts = ["sum_over_time(latency[1m])"]; + let mut first = engine + .install( + &workload(&texts, 60_000), + &arm("timescaledb.continuous-aggregate"), + ) + .unwrap(); + let mut second = engine + .install( + &workload(&texts, 60_000), + &arm("timescaledb.continuous-aggregate"), + ) + .unwrap(); + for chunk in &chunks { + first.ingest(chunk).unwrap(); + second.ingest(chunk).unwrap(); + } + let a = first.evaluate(60_000).unwrap().0; + let b = second.evaluate(60_000).unwrap().0; + assert_eq!(a, b); + assert_rows("isolated", &rows(&a, 0), &[("job=a", 1830.0)], 1e-9); + // A third engine while both are installed sees their schemas. + assert!(TimescaleDbEngine::new(TimescaleDbServer { + connection: std::env::var("AQPBM_POSTGRESQL_CONNECTION").unwrap(), + settings: vec![], + cgroup: None, + }) + .is_err()); + drop(first); + drop(second); + let _ = self::engine(); + assert!(engine + .install( + &workload(&texts, 60_000), + &arm("clickhouse.equivalent-only") + ) + .is_err()); + assert!(engine + .install( + &workload(&texts, 60_000), + &ArmSpec { + name: "timescaledb.hypertable".into(), + raw_data_retained: true, + engine_options: serde_json::json!({"plan_file": "x.plan.json"}), + } + ) + .is_err()); +} diff --git a/system-bench/tests/timescaledb_server.rs b/system-bench/tests/timescaledb_server.rs new file mode 100644 index 00000000..741acb04 --- /dev/null +++ b/system-bench/tests/timescaledb_server.rs @@ -0,0 +1,169 @@ +//! The TimescaleDB adapter without a server: which query texts and variants +//! it runs, and the SQL it writes. The answers on a real server are in +//! `timescaledb_conformance.rs`. + +use std::path::PathBuf; + +use aqpbm_core::harness::engine::{QueryLanguage, QueryText, WorkloadQuery, WorkloadSpec}; +use system_bench::engines_external::timescaledb_server::{ + parse_query, plan_queries, Aggregation, Mode, Placement, QuantileMethod, RangeFunction, + RangeQuery, VARIANTS, +}; +use system_bench::registry::{self, PeriodicQueries}; + +fn workload(texts: &[(&str, u64, u64)]) -> WorkloadSpec { + WorkloadSpec::periodic( + "w".into(), + texts + .iter() + .enumerate() + .map(|(i, (text, window_ms, interval_ms))| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + dialect: None, + }], + window_ms: *window_ms, + evaluation_interval_ms: *interval_ms, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![], + ) +} + +#[test] +fn every_showcase_query_parses() { + let suites = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../suites"); + let mut parsed = 0; + for suite in ["showcase-1m", "showcase-1h"] { + for entry in std::fs::read_dir(suites.join(suite)).unwrap() { + let path = entry.unwrap().path(); + if !path.to_string_lossy().ends_with(".workload.json") { + continue; + } + let spec: WorkloadSpec = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + for mode in VARIANTS.iter().map(|(_, mode)| *mode) { + let (queries, _) = plan_queries(&spec, mode, "s") + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + parsed += queries.len(); + } + } + } + assert_eq!(parsed, 2 * 12 * 6); +} + +#[test] +fn the_subset_parses_to_its_parts() { + assert_eq!( + parse_query("sum by (job) (rate(requests_total[1m]))").unwrap(), + RangeQuery { + aggregation: Some((Aggregation::Sum, vec!["job".into()])), + function: RangeFunction::Rate, + metric: "requests_total".into(), + range_ms: 60_000, + } + ); + assert_eq!( + parse_query(" quantile_over_time( 0.99 , latency [1h30m] ) ").unwrap(), + RangeQuery { + aggregation: None, + function: RangeFunction::QuantileOverTime(0.99), + metric: "latency".into(), + range_ms: 5_400_000, + } + ); + assert_eq!( + parse_query("count(max_over_time(latency[10s]))") + .unwrap() + .aggregation, + Some((Aggregation::Count, vec![])) + ); +} + +#[test] +fn texts_outside_the_subset_are_refused() { + for text in [ + "sum without (job) (rate(requests_total[1m]))", + "rate(requests_total{job=\"a\"}[1m])", + "rate(requests_total[1m] offset 1m)", + "stddev_over_time(latency[1m])", + "quantile_over_time(1.5, latency[1m])", + "latency", + "sum by (job) (latency)", + "rate(requests_total[1m]) * 2", + "sum(sum by (job) (rate(requests_total[1m])))", + ] { + assert!(parse_query(text).is_err(), "{text}"); + } +} + +#[test] +fn a_range_other_than_the_window_is_refused() { + let error = plan_queries( + &workload(&[("max_over_time(latency[1m])", 120_000, 10_000)]), + Mode::of_variant("timescaledb.hypertable").unwrap(), + "s", + ) + .unwrap_err(); + assert!(error.0.contains("window"), "{error}"); +} + +#[test] +fn variant_names_pick_the_mode() { + assert_eq!( + Mode::of_variant("timescaledb.continuous-aggregate.tdigest").unwrap(), + Mode { + placement: Placement::ContinuousAggregate, + quantile: QuantileMethod::TDigest, + } + ); + assert!(Mode::of_variant("clickhouse.equivalent-only").is_err()); +} + +#[test] +fn continuous_aggregates_bucket_by_the_gcd_and_stay_left_open() { + let (queries, labels) = plan_queries( + &workload(&[ + ("sum by (job) (sum_over_time(latency[1m]))", 60_000, 10_000), + ("quantile_over_time(0.9, latency[90s])", 90_000, 60_000), + ]), + Mode::of_variant("timescaledb.continuous-aggregate").unwrap(), + "s", + ) + .unwrap(); + assert_eq!(labels["latency"], vec!["job".to_string()]); + assert_eq!(queries[0].continuous_aggregate.as_ref().unwrap().1, 10_000); + assert_eq!(queries[1].continuous_aggregate.as_ref().unwrap().1, 30_000); + let definition = queries[0].continuous_aggregate_sql().unwrap(); + assert!( + definition.contains("\"offset\" => INTERVAL '1 microsecond'") + && definition.contains("materialized_only = true"), + "{definition}" + ); + let sql = queries[0].sql(120_000); + assert!( + sql.contains("bucket > to_timestamp(60.000) AND bucket <= to_timestamp(120.000)"), + "{sql}" + ); + let raw = plan_queries( + &workload(&[("max_over_time(latency[1m])", 60_000, 10_000)]), + Mode::of_variant("timescaledb.hypertable").unwrap(), + "s", + ) + .unwrap() + .0; + assert!(raw[0] + .sql(120_000) + .contains("ts > to_timestamp(60.000) AND ts <= to_timestamp(120.000)")); +} + +#[test] +fn postgresql_runs_periodic_queries() { + assert!(registry::names::().contains(&"postgresql")); +}