Skip to content

TimescaleDB periodic queries: hypertable, continuous-aggregate and Toolkit sketch variants - #292

Draft
zzylol wants to merge 2 commits into
mainfrom
feat/timescaledb-periodic
Draft

zzylol wants to merge 2 commits into
mainfrom
feat/timescaledb-periodic

Conversation

@zzylol

@zzylol zzylol commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

What this changes

approxbench benchmark-external run --engine postgresql now runs periodic suites (such as showcase-1m and showcase-1h) on PostgreSQL with TimescaleDB and the TimescaleDB Toolkit. Until now, postgresql ran only one-shot queries.

Each arm runs each workload query's PromQL text. The adapter turns that text into SQL itself, so it needs no plan file (variants with "plans": false). The variant name picks how the queries run:

variant quantile_over_time other range functions answers
timescaledb.hypertable percentile_cont over the raw rows plain SQL over the raw rows exact
timescaledb.continuous-aggregate array_agg per bucket, then percentile_cont over the window's values sum/count/min/max per bucket; counter_agg per bucket for rate/increase exact
timescaledb.uddsketch approx_percentile(φ, uddsketch(200, 0.001, value)) at query time as hypertable approximate (recorded as a substitution)
timescaledb.tdigest approx_percentile(φ, tdigest(100, value)) at query time as hypertable approximate
timescaledb.continuous-aggregate.uddsketch uddsketch per bucket, rollup over the window as continuous-aggregate approximate
timescaledb.continuous-aggregate.tdigest tdigest per bucket, rollup over the window as continuous-aggregate approximate

scripts/timescaledb-variants.sh <run-dir> adds the six variants with run_by_default: false, so runs of the other engines over the same directory skip them.

Semantics and where TimescaleDB differs

  • Window: (T − d, T], the same as PromQL. A continuous aggregate uses time_bucket(b, ts, "offset" => 1 µs), so each bucket is (k·b, (k+1)·b] at the microsecond resolution of timestamptz. The bucket width is b = gcd(range, evaluation interval).
  • Quantile: percentile_cont is PromQL's linear interpolation at rank φ·(n−1), so the result is exact. The Toolkit's approx_percentile does not interpolate: it returns a value near one order statistic. Part of a sketch variant's error is therefore this difference in definition, not sketch error. For example, with 60 samples, p99 comes out near the 60th value instead of 59.41.
  • rate / increase: Prometheus extrapolatedRate (v3.15.1), computed the same way as ClickHouse's query-time translator: reset-corrected increase, the 1.1 × average-gap threshold, the zero-point clamp, and at least 2 samples. The continuous-aggregate variants take n, first/last time, first value and the reset-corrected delta from rollup(counter_agg), so they match exactly too.
  • Continuous aggregates: real-time aggregation is off (timescaledb.materialized_only = true) and no refresh policy runs. At the end of every ingest step, the adapter calls refresh_continuous_aggregate over that step's buckets. Every evaluation therefore reads complete, materialized buckets, and the refresh counts as ingest CPU. The raw hypertable stays, because TimescaleDB refreshes from it, so raw_retained_bytes > 0 in every variant.
  • hyperloglog: not used. No PromQL function in the periodic suites counts distinct values.
  • Query subset: [sum|avg|min|max|count [by (...)]] (f(metric[d])) with f = *_over_time (sum/count/avg/min/max), rate, increase, or quantile_over_time. Anything else (label matchers, offset, without, nested expressions) is refused at install.

Storage: each install gets its own schema, bench_<pid>_<n>, with one hypertable per metric (ts timestamptz, value float8, series = the label map as JSON, and one text column per by label). Each chunk is written with one binary COPY per metric over a persistent connection. --postgresql-setting values are applied with SET on that connection; for example, max_parallel_workers_per_gather=0 gives a single-worker row, matching ClickHouse's max_threads=1. CPU and memory come from the container cgroup. The new dependency is the postgres crate (sync client).

Interfaces

 // system-bench/src/registry.rs
     System {
         name: "postgresql",
-        periodic_queries: None,
+        periodic_queries: Some(PeriodicQueries {
+            options: TimescaleDbOptions::augment_args,
+            build: timescaledb_server::periodic_queries,
+        }),
+// system-bench/src/engines_external/timescaledb_server.rs (new)
+pub struct TimescaleDbEngine;            // EngineUnderTest
+pub struct TimescaleDbServer { pub connection: String, pub settings: Vec<(String, String)>, pub cgroup: Option<CgroupSource> }
+pub const VARIANTS: [(&str, Mode); 6];
+pub fn parse_query(text: &str) -> Result<RangeQuery, String>;
+pub fn plan_queries(workload: &WorkloadSpec, mode: Mode, schema: &str) -> Result<(Vec<QueryPlan>, LabelColumns), EngineError>;

Tests

  • system-bench/tests/timescaledb_server.rs (no server): all 24 query texts in showcase-1m and showcase-1h parse in all six modes; texts outside the subset and a range that differs from the window are refused; variant → mode; the cagg bucket is the gcd and stays left-open; postgresql is listed for periodic queries.
  • system-bench/tests/timescaledb_conformance.rs (#[ignore], AQPBM_POSTGRESQL_CONNECTION), on a real server (the pinned image, 8 cores). Each case runs on all six variants, and all 5 pass:
    • grouped sum/count/min/max/avg_over_time: hand-computed, to 1e-9;
    • quantile 0.99 of 1..60 = 59.41, and avg by (job) of the 0.9 quantiles = 81.15: exact variants to 1e-9; sketch variants within 0.2 % (uddsketch) or 2 % (tdigest) of the neighbouring order statistics;
    • rate[5m] and increase on the ClickHouse conformance counter data (x 1, y 417/299, z 642/299, w 1), per series and summed by job: all variants to 1e-9;
    • left-open window at T−d and T;
    • two installs are isolated and answer alike; a dropped arm leaves no schema; leftover schemas, unknown variant names and plan-file arms are refused.
  • End-to-end: showcase-1m with all six variants, --warmup 0 --runs 1, all 48 cells ran (21.5 min on a throttled host). Report with truth postgresql/timescaledb.hypertable: timescaledb.continuous-aggregate max relative error ≤ 1.2e-15 on every workload. Sketch variants on quantile workloads: max 9.1 % (tdigest) and 10.9 % (uddsketch), median 0.6–0.7 %. Non-quantile queries in the sketch variants stay exact.

Run locally: cargo nextest run -p system-bench timescaledb; against a server: AQPBM_POSTGRESQL_CONNECTION="host=… port=… dbname=bench" cargo test -p system-bench --test timescaledb_conformance -- --ignored --test-threads 1.

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi

zzylol and others added 2 commits December 3, 2026 07:39
…olkit sketch variants

Engine postgresql now runs periodic suites on a PostgreSQL server with
TimescaleDB and the TimescaleDB Toolkit. Each arm runs each query's PromQL
text (a subset: [agg by (...)] (f(metric[d]))) as SQL it writes itself;
the variant name picks exact query-time SQL over the hypertable, one
continuous aggregate per query (real-time aggregation off, refreshed at each
ingest step), or uddsketch/tdigest quantiles at query time or per bucket.
scripts/timescaledb-variants.sh adds the six variants to a run directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rom -infinity

The first refresh with a NULL start committed once per batch of empty buckets
since the epoch (seconds of WAL syncs per arm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zzylol zzylol added the enhancement New feature or request label Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant