#10691·timescaledb

[Bug]: Wrong query results after merge_chunks on compressed chunks whose orderby ranges overlap

Author: cevianCreated Sep 28, 2026Updated Sep 28, 2026
Labelsbugneeds-triagev2.31.0

What type of bug is this?

Incorrect result

What subsystems and features are affected?

Compression, Query planner, Partitioning

What happened?

After merging two compressed chunks whose orderby-column value ranges overlap, queries that rely on the compressed batches being ordered return wrong results. In the reproduction count(DISTINCT c1) over 300 distinct values returns 601 after the merge and 300 before it. The same query returns 300 after the merge with enable_presorted_aggregate = off or timescaledb.enable_optimizations = off. Recompressing the merged chunk afterwards does not change the wrong answer.

The merged chunk's status in _timescaledb_catalog.chunk is 9 (compressed, partial); it does not get the unordered flag (2) that an out-of-order direct-compress insert sets.

TimescaleDB version affected

2.31.0-dev, built from main at 8ffe9536a

PostgreSQL version used

17.2

What operating system did you use?

macOS 14 (Darwin 23.3.0) arm64

What installation method did you use?

Source

What platform did you run on?

On prem/Self-hosted

Relevant log output and stack trace

How can we reproduce the bug?

bash
CREATE TABLE t (ts timestamptz NOT NULL, c1 int8 NOT NULL, c2 int8 NOT NULL);
SELECT create_hypertable('t', 'ts', chunk_time_interval => interval '7 days');
ALTER TABLE t SET (timescaledb.compress, timescaledb.compress_segmentby = '',
                   timescaledb.compress_orderby = 'c1 DESC NULLS FIRST, ts ASC, c2 DESC');
INSERT INTO t SELECT '2024-01-01'::timestamptz + i * interval '1 minute', (i * 7919) % 300, i
              FROM generate_series(1, 2500) i;
INSERT INTO t SELECT '2024-01-10'::timestamptz + i * interval '1 minute', (i * 104729) % 300, i
              FROM generate_series(1, 2500) i;
SET timescaledb.compression_batch_size_limit = 1000;
SELECT compress_chunk(c) FROM show_chunks('t') c;
SELECT count(DISTINCT c1) FROM t;                       -- 300
DO $$ DECLARE cs regclass[];
BEGIN  -- merge the two oldest chunks by range, whatever their names
  SELECT array_agg(format('%I.%I', chunk_schema, chunk_name)::regclass) INTO cs
  FROM (SELECT * FROM timescaledb_information.chunks WHERE hypertable_name = 't' ORDER BY range_start LIMIT 2) c;
  CALL merge_chunks(cs);
END $$;
SELECT count(DISTINCT c1) FROM t;                       -- 601
SET enable_presorted_aggregate = off;
SELECT count(DISTINCT c1) FROM t;                       -- 300