Skip to content

Support negative LIMIT BY - #103222

Merged
nihalzp merged 25 commits into
ClickHouse:masterfrom
nihalzp:negative-limit-by
May 11, 2026
Merged

nihalzp merged 25 commits into
ClickHouse:masterfrom
nihalzp:negative-limit-by

Conversation

@nihalzp

@nihalzp nihalzp commented Apr 21, 2026 •

Copy link
Copy Markdown
Member

Given,

CREATE TABLE limit_by(id Int, val Int) ENGINE = Memory;
INSERT INTO limit_by VALUES (1, 10), (1, 11), (1, 12), (1, 13), 
1, 14), (2, 20), (2, 21), (2, 22), (2,23);

We can now do:

SELECT * FROM limit_by ORDER BY id, val LIMIT -1 OFFSET -1 BY id;
┌─id─┬─val─┐
│  1 │  13 │
│  2 │  22 │
└────┴─────┘

The implementation is highly optimized; in many cases, this transform is much faster than LIMIT BY with positive values.

Negative LIMIT BY:

SELECT number % 1000 AS k
FROM numbers_mt(10000000)
ORDER BY k
LIMIT -1 BY k
FORMAT NULL

Elapsed: 0.078 sec.

LIMIT BY:

SELECT number % 1000 AS k
FROM numbers_mt(10000000)
ORDER BY k
LIMIT 1 BY k
FORMAT NULL

Elapsed: 0.233 sec.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Support negative values in the LIMIT BY clause to select rows from the end of each group instead of the beginning. For example, LIMIT -2 BY id returns the last two rows per id. Negative offsets (LIMIT -1 OFFSET -1 BY id) and mixed signs (LIMIT -2 OFFSET 1 BY id) are supported as well.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.506

@clickhouse-gh

clickhouse-gh Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6ca4c09]

Summary: ✅


AI Review

Summary

This PR adds support for negative LIMIT BY semantics (including negative offsets) via new planner lowering and NegativeLimitBy query-plan/transform steps. The current implementation still has a correctness issue in distributed first-stage planning: negative-offset forms are rewritten/pre-applied in a way that is not semantics-preserving.

Findings
  • ❌ Blockers
    • [src/Planner/Planner.cpp:1074-1082] do_not_skip_offset currently rewrites any non-zero limit_by_offset by folding it into limit_by_length and forcing is_offset_negative = false. This breaks negative-offset semantics (e.g. LIMIT -2 OFFSET -3 BY id becomes equivalent to LIMIT -5 BY id instead of “drop last 3, then keep last 2”).
    • [src/Planner/Planner.cpp:1292] preliminary distributed planning still calls addLimitByStep(..., do_not_skip_offset=true) for negative-offset LIMIT BY forms, so shard-local pre-application can drop globally valid rows before initiator merge.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ❌ LIMIT BY semantics are not preserved for negative-offset forms on shard-stage planning/rewrite.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ❌ Query result semantics change incorrectly for valid negative LIMIT BY queries.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ❌ Not safe to roll out with unresolved distributed correctness issue.
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Restrict do_not_skip_offset rewrite in addLimitByStep to positive offsets only (!is_offset_negative).
  2. Disable preliminary shard-stage LIMIT BY application for negative-offset forms (or make it provably semantics-preserving).

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 21, 2026
Comment thread src/Planner/Planner.cpp
{
if (limit_by_limit > std::numeric_limits<UInt64>::max() - limit_by_offset)
return;
if (limit_by_offset > 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do_not_skip_offset currently folds any non-zero LIMIT BY offset into limit_by_length (limit_by_length += limit_by_offset) and then forces is_offset_negative = false. This is only semantics-preserving for positive offsets.

For negative offset, this changes query meaning on distributed first stage. Concrete example:

  • input clause: LIMIT -2 OFFSET -3 BY id
  • after this rewrite: LIMIT -5 OFFSET 0 BY id

These are not equivalent: original means “drop last 3 per group, then keep last 2 of the remainder”, while rewritten means “keep last 5”.

Please gate this rewrite to the positive-offset case only (or skip first-stage LIMIT BY rewrite when offset is negative).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is also semantic preserving.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-checked the current code and this is still not resolved.

In addLimitByStep, the do_not_skip_offset rewrite still runs for any non-zero limit_by_offset and unconditionally forces is_offset_negative = false:

if (do_not_skip_offset)
{
    if (limit_by_offset > 0)
    {
        ...
        limit_by_length += limit_by_offset;
        limit_by_offset = 0;
        is_offset_negative = false;
    }
}

For LIMIT -2 OFFSET -3 BY id this still rewrites to NegativeLimitByStep(limit=5, offset=0), which is not equivalent (it keeps 5 tail rows instead of dropping 3 then keeping 2).

Please gate this rewrite to !is_offset_negative (positive offset only), and keep negative-offset forms on the negative-offset execution path.

}
}

AggregatedDataVariants::Type AggregatedDataVariants::chooseMethod(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok - this PR contains a few small, unrelated changes from Aggregator refactoring. This is alright.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The refactoring allows negative LIMIT BY to use the same hash tables as the aggregator; allowing LIMIT BY to benefit from years of optimizations in AggregatedDataVariants. Same change is also present in the LIMIT BY optimization PR #103349.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great!

@alexey-milovidov alexey-milovidov self-assigned this May 10, 2026
Comment thread src/Planner/Planner.cpp
/// https://github.com/ClickHouse/ClickHouse/blob/67c1e89d90ef576e62f8b1c68269742a3c6f9b1e/src/Interpreters/InterpreterSelectQuery.cpp#L1697-L1705
/// Let's be optimistic and only don't skip offset (it will be skipped on the initiator).
addLimitByStep(query_plan, limit_by_analysis_result, query_node, true /*do_not_skip_offset*/);
addLimitByStep(query_plan, limit_by_analysis_result, query_analysis_result, true /*do_not_skip_offset*/);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addLimitByStep(..., do_not_skip_offset = true) is now used for negative LIMIT BY forms on the shard stage too, but negative offsets are not safe to pre-apply per shard.

For LIMIT N OFFSET -M BY key, this lowers to NegativeLimitByStep(MAX, M) + LimitByStep(N, 0). Running that on each shard drops each shard-local tail, not the global tail, so rows can be lost before the initiator sees them.

Concrete example for one group ordered by v:

  • shard A: [1, 100]
  • shard B: [2, 3]
  • query: LIMIT 10 OFFSET -1 BY g
  • correct global result: [1, 2, 3] (drop only 100)
  • with shard-preliminary step: A -> [1], B -> [2], initiator can no longer recover 3.

Please disable preliminary LIMIT BY for cases with negative offset (or otherwise keep it semantically lossless for distributed first stage).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When do_not_skip_offset = true, offset is set to 0 and limit becomes limit + offset. This means offset is never applied on shard. We also have tests that exercise the exact path.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This concern is still live in current code.

addPreliminarySortOrDistinctOrLimitStepsIfNeeded still always calls:

addLimitByStep(..., true /*do_not_skip_offset*/);

for first-stage distributed planning, including negative-offset forms. Combined with the current do_not_skip_offset rewrite in addLimitByStep, this pre-applies LIMIT BY semantics per shard for negative-offset cases, which is not globally lossless.

Please disable shard-stage LIMIT BY pre-application for negative-offset forms (or otherwise ensure semantic equivalence before initiator merge).

@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 95.95% (521/543) | lost baseline coverage: 8 line(s) · Uncovered code

Full report · Diff report

@nihalzp

nihalzp commented May 10, 2026

Copy link
Copy Markdown
Member Author

@groeneai Investigate why the performance test CI failed.

@groeneai

Copy link
Copy Markdown
Collaborator

@nihalzp — investigated. It's an infrastructure flake on the Install Reference ClickHouse step, not a performance regression in this PR. The re-run is clean.

Root cause

Attempt 1, shard Performance Comparison (arm_release, master_head, 1/6) (job 75240226061) ran for only 39s and failed during the Install Reference ClickHouse step:

Run command: [wget -nv ... https://clickhouse-builds.s3.us-east-1.amazonaws.com/REFs/master/d640b7762fd44f3d26d41f5e6d2f9cef4d421d51/build_arm_release/clickhouse]
2026-05-10 17:55:45 ERROR 500: Internal Server Error.
ERROR: command failed after 1/1 attempt(s), exit code: 8
Fail [Install Reference ClickHouse]

S3 (clickhouse-builds.s3.us-east-1.amazonaws.com) returned HTTP 500 when fetching the reference master binary for the comparison. The praktika wrapper retries 1/1 (i.e. no retry), so a single transient 500 fails the whole shard. The PR's binary was never even started.

This is independent of your changes — the same failure mode hit PR #104523 (HashTable deserialization, completely unrelated to LIMIT BY) on shard arm_release 5/6 ~3.5h later at 19:24 UTC, also on the wget of REFs/master/<sha>/build_arm_release/clickhouse. CIDB shows 3 instances of this exact job-level Failures: 1/2 signature in the last 14 days, all on different PRs and different shards — consistent with a transient S3-side issue.

Re-run is clean

Attempt 2's shard 1/6 (job 75251403038) completed normally — 47 minutes, 354 queries, full report at:

performance_comparison_arm_release_master_head_1_6/report.html

PR-level summary across all 5 completed arm shards:

[WARN] arm_release 1/6  -- 2 faster, 1 slower (and_function #0, +60.3% vs threshold +59.7%), 4 unstable / 354 queries
[  OK] arm_release 3/6  -- 1 faster, 7 unstable / 352 queries
[WARN] arm_release 4/6  -- 4 faster, 3 slower (destroy_aggregate_states / general_purpose_hashes / insert_select_squashing_dynamic, all ≤+0.5pp over their thresholds), 15 unstable / 399 queries
[  OK] arm_release 5/6  -- 3 unstable / 349 queries
[  OK] arm_release 6/6  -- 3 faster, 8 unstable / 367 queries
Total: 1821 queries | 10 faster | 4 slower | 37 unstable

The 4 "slower" entries are all 0.3–0.6 percentage points above their own noise thresholds and live in tests (and_function, destroy_aggregate_states, general_purpose_hashes, insert_select_squashing_dynamic) that don't touch the LIMIT BY plan path this PR modifies — i.e. threshold-edge noise rather than a real effect. The same report flags set_index #1 as -1.336x (-25.1%) faster with p=0.235, a larger swing than any "slower" entry. Net: no actionable perf signal from this PR.

Suggested action

Nothing to do on your end for the perf failure — the re-run cleared the shard. If you want a defense-in-depth fix on the CI side, raising the retry count for the Install Reference ClickHouse step in the praktika wrapper would eliminate this class of failure (a separate change unrelated to this PR).

Unrelated note while you're here

The same attempt-1 job log contains the AI Code Review verdict (Block) flagging a different issue at src/Planner/Planner.cpp:1292: with the new distributed preliminary path applying addLimitByStep(..., do_not_skip_offset = true), the bot argues that LIMIT N OFFSET -M BY ... queries can lose rows when groups are split across shards (shard-local-tail trimming rather than global-tail trimming). That's a separate concern from the perf flake — wanted to surface it since it's in the same job log and the bot suggests adding a distributed regression test. Worth a quick look even if you disagree with the diagnosis.


— @groeneai, session cron:clickhouse-ci-task-worker:20260510-201500

@nihalzp
nihalzp added this pull request to the merge queue May 11, 2026
Merged via the queue into ClickHouse:master with commit 896e7f7 May 11, 2026
325 of 326 checks passed
@nihalzp
nihalzp deleted the negative-limit-by branch May 11, 2026 05:53
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants