Skip to content

Sort, filter and page a result in the Web UI - #115540

Merged
alexey-milovidov merged 21 commits into
masterfrom
play-result-sorting
Aug 24, 2026
Merged

alexey-milovidov merged 21 commits into
masterfrom
play-result-sorting

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Related: #105249

The Web UI can now sort a result by its columns, filter it by their values, and page through it, without editing the query.

None of it happens in the browser. Each change re-runs the query with the corresponding query-construction setting added by #105249 — order, filter, limit + page — which the server materializes by wrapping the query as a derived table. What is on screen is therefore the sorted, filtered, paged result of the whole query, not a rearrangement of the rows the page happened to hold. And because the settings are applied to the parsed query rather than to its text, they compose with whatever the query already is: a UNION, a trailing FORMAT clause, or the query's own ORDER BY and LIMIT all keep working, and the text in the editor is never rewritten.

Sorting

Two arrows in every column header. The arrow of the active direction deactivates it, the other replaces it, a plain click makes the column the only sort key, and Shift appends it after the keys already in effect (or only flips the direction of a key it already is, keeping its position). With more than one key, each active arrow shows its position in the ORDER BY as a superscript.

Filtering

A funnel in every header opens an input for a predicate on that column, with an apply button glued to it. The input opens inside the header cell, on the very line the filter is shown on once it is set, so a filter is edited where it is read; the header grows a line for it and shrinks back afterwards. What is typed is the part that follows the column name, so anything the server accepts there works — > 10, BETWEEN 1 AND 5, IN (1, 2, 3), % 2 = 0. A column being filtered shows its predicate under its name for as long as it is set, with a cross to remove it, so it is never invisible that the rows on screen are a subset of the result.

Selecting a cell also offers the comparisons that fit its value: =, !=, >, <, >=, <= for a number or a date/time; =, !=, contains for a string; =, != for an Enum; true / false for a Bool; IS NULL / IS NOT NULL for a NULL. contains becomes a LIKE pattern with the value's own % and _ escaped, so it matches literally. There is one filter per column wherever it came from, and the header always displays the one in effect.

Pagination

A result cut off at the display limit gets a pager, which lists the ten pages before the current one, the current one and the next one, plus an ellipsis that takes any page number, and ends with an editable Per page. The count of pages is not shown because knowing it would mean counting the rows; the next page is offered only while the current one is full, since a short page is the end of the result. The page size is capped at what the result can display at once — a larger page would return rows the table then truncates away and the next page would start beyond them, silently skipping the rows that never fit.

Where it applies, and what it is bound to

Only to the statements those settings shape, i.e. SELECT / UNION (resolved by the same CTE-aware statement-kind walk that already decides the Run all parallelization, so a write hidden behind a leading WITH is not mistaken for one). Not to SHOW / DESCRIBE / EXISTS / EXPLAIN, where the settings are silently ignored and a control would promise an order the rows do not have; and not to a multi-query run, whose statements are separate queries with separate columns.

A shape belongs to the statement it was made on and is dropped by a run of anything else, so a stale sort can never put an ORDER BY on a column the new statement lacks. The two launch paths spell the same statement differently (with and without its trailing ;), which the binding normalizes — otherwise a shape would be dropped by its own re-run.

It belongs to the run context as well — the selected database, the connection and the query parameter values — since the same text names different columns after any of those change; a result snapshot records the context that produced its rows, and a restore re-binds the shape to it, so the first re-run after a context change drops the shape instead of shaping a different result. Only a shape restored from a URL, which records no context, adopts the context of the run that re-applies it — for a run=1 link, the auto-run itself.

A result can carry the same column name twice (SELECT 1 AS x, 2 AS x, a join of tables sharing column names), and the name-keyed settings could not tell such columns apart, so they get no sort or filter controls at all — fail closed — while the uniquely named columns of the same result keep theirs.

Persistence

Kept per tab, and mirrored into the URL (sort_columns, filters, page, page_size), the history entry and the tab's result snapshot, alongside the existing color modes and pinned columns. Since the shape decides the rows and not only their presentation, an auto-run (run=1) link reproduces the result itself; Download re-runs with the same settings so the exported file matches the table.

Header icons

The pushpin and rainbow emoji became inline SVG on the same grid and stroke weight as the new funnel — they rendered visibly larger than the line art beside them, and being colour glyphs they could take no text colour. All four icons now follow one rule: muted while the feature they control is not in effect on the column, and in a colour reserved for controls in effect (magenta in the light theme, yellow in the dark one) once it is, which is also when they stay shown without hovering. Each lays the header's colour behind itself at 90% alpha so a column name running underneath does not muddle it.

Testing

  • tests/integration/test_play_result_shaping runs the real shape helpers extracted from the served /play page in a Node harness, covering the sort-arrow semantics, the ORDER BY / WHERE construction and its quoting and LIKE escaping, the translation of a page into limit + page, the validation of a shape read back from a URL, the statement and context binding (including the re-binding of a restored snapshot to its producing context), and the duplicate-name classification.
  • gtest_play_query_is_read_only now also covers the statement-kind gate: the walk is refactored into a shared statementKeyword, and queryIsShapeable is verified to be strictly narrower than the read-only classification.
  • The behaviour itself was driven in a real browser (Chromium via Puppeteer) against a local server, in both themes, for each of the cases above.

Documentation: docs/concepts/features/interfaces/web-ui-result-shaping.mdx.

Written with Claude Code.

Changelog category (leave one):

  • New Feature

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

The built-in Web SQL UI (/play) can now sort a result by its columns, filter it by their values, and page through it, without editing the query. Sorting arrows and a filter input appear in every column header, a selected cell offers the comparisons that fit its value, and a pager with an adjustable page size appears under a result that does not fit on one screen. It is all performed by the server, using the order, filter, limit and page query-construction settings, so the whole result is shaped rather than the rows that happen to be displayed; the chosen sort, filters and page travel in the page URL, so a shared link reproduces the result.


Workflow [PR]
Sync PR [sync-upstream/pr/115540]

Version info

  • Merged into: 26.8.1.1971 (included in 26.8 and later)

alexey-milovidov and others added 14 commits August 20, 2026 00:56
Add per-column sorting to the built-in Web SQL UI. Two arrows in every column
header choose the sort; the query is then re-run with it as the `order`
query-construction setting (added by #105249), so the server returns the whole
result sorted instead of the page reordering the rows it happens to hold.

The arrow semantics: the arrow of the active direction deactivates it, the other
direction replaces it, a plain click makes the column the only sort key, and
Shift appends the column after the keys already in effect (or only flips the
direction of a key it already is, keeping its position). Every active arrow shows
its position in the `ORDER BY` as a superscript when there is more than one key.
The arrows follow the pin and colorize toggles: hidden until the header is
hovered or an arrow is focused on a hovering pointer, always visible on a coarse
pointer, and always visible while active.

The sort is sent as a fully back-quoted `ORDER BY` expression list, so a result
column whose name is an expression (`count()`) or carries a space is a usable
sort key. It is offered only where the setting actually shapes the result - a
`SELECT` / `UNION`, resolved by the same statement-kind walk that decides the
`Run all` classification - so a `SHOW` / `DESCRIBE` / `EXPLAIN` result never
carries a sort indicator the rows do not have. A multi-statement run and the
vertical single-row layout offer no sorting either.

Like the color modes and the pinned columns, the sort is per tab and travels with
the tab's result snapshot, the URL and the history entry; unlike them it shapes
the rows, so an auto-run `run=1` link reproduces the sorted result, and Download
re-runs with the same `order`. A sort stays bound to the statement it was made
on and is dropped by a run of anything else, so a stale sort cannot put an
`ORDER BY` on a column the new statement lacks.

Co-Authored-By: Claude Opus 5 <[email protected]>
Adds the two remaining halves of shaping a result from the result view, on top
of the sorting added in the previous commit, and reworks the three into one
per-tab "result shape" that is sent as the `order` / `filter` / `limit` + `page`
query-construction settings of the run.

Filtering. A funnel in every column header opens an input for a predicate on
that column, with an apply button glued to it and a placeholder suggesting the
shape a predicate takes for the column's type (`> 10` for a number,
`LIKE '%test%'` for a string). What is typed is the part that follows the column
name, so any expression the server accepts there works. A filter in effect is
shown under the column name for as long as it is set, with a cross to remove it,
so it is never invisible that the rows on screen are a subset of the result.

Selecting a cell also puts a funnel next to its copy icon and offers the
comparisons that fit its value: `=`, `!=`, `>`, `<`, `>=`, `<=` for a number,
`=`, `!=`, `startsWith`, `endsWith`, `contains` for a string of at most 100
characters, `IS NULL` / `IS NOT NULL` for a NULL. The prefix/suffix/substring
options become `LIKE` patterns with the value's own `%` and `_` escaped, so they
match it literally. There is one filter per column wherever it came from, so a
filter set from a cell replaces the one the header input had put there and the
header displays whichever is in effect.

Pagination. A result cut off at the display limit gets a pager under the table,
which lists the ten pages before the current one, the current one and the next
one, plus an ellipsis that turns into an input for any page number (the count of
pages is not shown because knowing it would mean counting the rows). Selecting a
page sends the display limit as `limit` and the page as `page`. Changing the sort
or a filter goes back to the first page: both change which rows the result has,
or in what order, so the page no longer denotes the same slice.

Sorting. A sorted column now shows both of its arrows without hovering, not only
the active one, since reversing the direction is the likeliest next action.

Two things the shape controls need that were not there before: a NULL cell is now
recognized on the page's own default format (a `JSONCompactStrings…` format
writes a NULL as its plain-text glyph inside an ordinary JSON string, so the
`data-is-null` marker never fired there), and a shaped result keeps its
horizontal layout - the vertical layout of an empty or single-row result drops the
header row, which would leave a filter that matched nothing unremovable.

Co-Authored-By: Claude Opus 5 <[email protected]>
… the end

Follow-up fixes to the result-shape controls:

 - the header icons are drawn with a halo of the header background (a stacked
   `drop-shadow`, which unlike `text-shadow` also applies to the colour-emoji
   icons and to the inline SVG), and the funnel's hollow middle is filled, so
   they stay legible where a narrow column's name runs under them;
 - the gaps between the funnel, the colorize icon and the sort arrows are
   evened out and tightened, so they read as one cluster;
 - the filter input closes when the focus leaves it, so a stray click does not
   leave an input standing open over the result. The controls that act ON that
   input - the funnel, the apply button, the filter text and its cross - no
   longer take the focus on a press, or the input would close a moment before
   the click could reach them (which for the funnel would reopen what the user
   meant to close);
 - the pager offers a next page only while the current one is full. A page that
   came back short is the end of the result, so the page after it would only
   ever be empty.

Co-Authored-By: Claude Opus 5 <[email protected]>
The header icons contradicted each other: the pushpin was dimmed to 55%
translucent when the column was not pinned and only became opaque once it was,
while the rainbow was fully opaque when the column carried no color mode and
*dimmed* on hover - so the same visual move meant "off" on one icon and "on" on
the other. Neither said anything at all once its feature was in effect, except
by being slightly more opaque.

Give all four icons - pushpin, rainbow, sort arrows, funnel - one rule: muted
while the feature it controls is not in effect on that column, at full strength
once it is (and while the pointer or the keyboard focus is on the icon itself,
as a preview of turning it on). An icon whose feature is in effect also stays
shown without hovering, so a pinned, colorized, sorted or filtered column says
so by itself.

Muting is now a loss of color and contrast rather than of opacity: the glyph
icons take `--misc-text-color` and the accent color, the emoji icons - which
cannot take a text color at all - are drained with `grayscale` and nudged
towards the header background. A half-transparent icon over a column name or
over the color coding of the cells read as damaged rather than as inactive, and
how faded it looked depended on whatever happened to be behind it. Opacity is
left doing only what it must: hiding an icon outright, which keeps these
buttons in the tab order while invisible where `display: none` would not.

Also: a `Date` / `Date32` / `DateTime` / `DateTime64` cell now offers the same
comparisons a numeric one does (`=`, `!=`, `>`, `<`, `>=`, `<=`), against the
text the server rendered it as - which ClickHouse parses back as the column's
own type, so the page needs no date formatting of its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ons in place

The four header icons were laid out pin | name | funnel colorize sort, which
grouped nothing: the two that only change how the result is DISPLAYED sat at
opposite ends, and the two that RE-RUN the query were split by the colorize
icon. Move the colorize icon next to the pin on the left and the funnel next to
the sort arrows on the right, so each pair is one cluster.

Also drop the rules that chose where to put the selected cell's copy button, its
filter funnel and the comparison menu - above the cell normally, off to the side
for the first body row - and put them in one unconditional place.

That place is just below the cell rather than above it, which is where the
default branch used to put them. Above the cell they land inside the sticky
header's band for the first body row, where the header paints over them: they
become invisible and unclickable, which is what the removed side-placement was
working around. No z-index fixes that, because they sit inside the selected
cell's stacking context, and that whole band has to stay below the headers - the
order is selected cell < pinned cell < header < pinned header, so that a pinned
column stays visible over a selected cell scrolling past it and every body cell
scrolls under the headers. Lifting the buttons over a header would mean lifting
the selected cell over pinned columns.

Keeping them outside the cell rather than within it is also deliberate: at the
cell's own top right corner they would cover the value they act on, which in a
right-aligned numeric column is exactly where they would sit.

Co-Authored-By: Claude Opus 5 <[email protected]>
…olumn name

Three fixes to the result-view controls.

The copy and filter chips on the selected cell were not the same size: the copy
icon was inline, so its chip carried the leading of a line box on top and stood
27px tall against the filter chip's 24px, and a 5px gap sat between them. Both
now use the same rule with a block-level icon, and the filter chip's offset is
the same expression as the chip's own width, so they are identical and touching
at any font size. The comparison menu under them closes its gap the same way.

The chips hung below the CELL, which for a selected multi-line value put them
inside its expanded content: selecting a cell expands it into an absolutely
positioned overlay - up to 50vh - while the cell keeps the row height, so
`top: 100%` of the cell lands part way up the overlay. CSS cannot see that
height, the overlay being a sibling of the chips rather than their container, so
`_positionCellControls` measures it on selection and hands over the one number
the stylesheet cannot compute; the viewport `resize` hook re-measures it, since a
value long enough to be clamped at 50vh changes height with the viewport.

The header icons were centred in the header cell, which is the same thing as
being level with the column name only while every header is one line tall. A
column carrying a filter shows it under its name and makes the whole header row
taller, and the icons then slid down into that second line. They are now
positioned against the first line instead, and the header cells align their
content to the top rather than to the middle, so the names of the columns
WITHOUT a filter stay on that first line too, in one row with the icons.

Co-Authored-By: Claude Opus 5 <[email protected]>
The filter chip sat one chip width in from the cell's right edge, to leave the
edge itself to the copy chip. A cell has no copy chip when there is nothing
worth copying - an empty value, a zero, a NULL - and the filter chip then hung
there with a chip-sized hole beside it.

Both chips are now flush with the edge, the filter chip giving way only when a
copy chip is actually there. The copy chip is rendered with the cell and the
filter chip is added when the cell is selected, so the latter always follows the
former in the DOM and a sibling selector tells the two cases apart without any
bookkeeping.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two changes to the filter controls in a column header.

The filter input no longer hangs under the header as a panel over the first
rows: it opens inside the header cell, on the same line the filter itself is
shown on once it is set, and the header grows to make room for it as soon as the
funnel is clicked (and shrinks back when the input goes away). A filter is now
edited exactly where it is going to be read, and nothing of the result is
covered while editing. It is laid out in flow rather than absolutely positioned,
so the cell reserves the room; it takes the width of the column, down to a floor
that keeps it usable in a narrow one, where it overflows onto the neighbouring
header. While the input stands in for the filter, that filter's own line - text
and the cross that removes it - is hidden; applying an empty input removes the
filter just as the cross does.

The color a control in effect is drawn in - the arrow of the active sort
direction, the funnel of a filtered column, and the filter shown underneath - is
now its own theme value rather than the link color: magenta in the light theme,
yellow in the dark one. These are not links, and a hue nothing else in the
result uses makes the shaped columns pick themselves out of a wide header at a
glance.

Co-Authored-By: Claude Opus 5 <[email protected]>
…r's way

The pushpin and the rainbow were emoji among line-art icons: they rendered
visibly larger than the funnel and the sort arrows beside them (18px against
13px), and being colour glyphs they could take no text colour, so marking them
muted or active needed a filter of their own instead of the colour every other
control uses. Both are now inline SVG on the same 24x24 grid and in the same
stroke weight as the funnel, and all three are sized in one rule, in em of the
header's own font - which also meant giving the icon buttons `font: inherit`,
since a button otherwise keeps the browser's form-control font size and every
`em` would have meant something different. The muted/active distinction is then
a single colour switch across all four icons, and the emoji-only filter
machinery goes away with them.

Three placement fixes that came out of the taller headers a filter produces:

 - the resizer is now only as tall as the name line, not the whole cell. A
   header grown for a filter otherwise laid this grab strip over the filter
   input, which overflows the cell to the right in a narrow column: hovering the
   input lit the resizer up, and the input's apply button sat underneath it.
 - a filtered column moves its funnel down to the bottom left corner, onto the
   line the filter is shown on. On the name's line the sort arrows sit
   immediately to its right, so it cannot be beside the filter it belongs to
   there, and that left the filter's line starting with a gap where its icon
   should be. While the input is open it takes that line, so the funnel goes
   back up beside the other icons.
 - the pager is inset from the left edge by the same padding it has above and
   below, instead of starting flush against it.

Co-Authored-By: Claude Opus 5 <[email protected]>
… filters

The apply button beside the filter input looked pressable when the box was
empty, and pressing it did nothing. It is now inactive - muted and inert, like
an inactive icon - whenever applying would change nothing, and Enter refuses
there too, so the key cannot do what the button will not.

"Nothing to apply" is an empty box on a column that carries no filter. An empty
box on a column that IS filtered keeps the button active: emptying the box and
applying is how a filter is removed from the input, the cross beside the filter
doing the same once the input is closed. Disabling that case as well would take
the removal away from the input entirely.

An `Enum` cell now offers a filter menu too, comparing against the name the
server rendered - but only `=` and `!=`. A prefix or substring match over a
closed set of names is not a filter anyone means, even though `LIKE` would
accept it.

Also: the pushpin and the colorize icon sat almost 10px apart, twice the gap of
the pair on the other side of the header. The second is now placed off the first
- its offset, plus the width of an icon, plus the gap the right-hand cluster
keeps - so the two read as one group.

Co-Authored-By: Claude Opus 5 <[email protected]>
The pager showed which page is being read but not how large a page is, and the
size was fixed at whatever the result could display at once. It now ends with
`Per page: <n>`, edited the way the page jump already is: click the value, type
another, and it is taken when the field loses focus.

The size is capped at what the result can display at once. A larger page would
return rows the table then truncates away and the next page would start beyond
them, so paging on would silently skip the rows that never fit; a bigger number
is taken as that maximum, which is then what the value shows, so the number on
screen is always the size in effect rather than the one that was asked for.

Changing it starts again at the first page: pages of a new size hold different
rows, so the page the user was on no longer denotes the slice they were looking
at - the same reason changing the sort or a filter starts over.

Co-Authored-By: Claude Opus 5 <[email protected]>
…filters

The header icons were thin grey strokes a few pixels across, with a halo of
stacked drop-shadows behind them - faint on their own, and only just enough to
keep them out of a column name running underneath. They are now drawn at full
contrast (the text colour, the accent colour once their feature is on, and the
accent on hover as a preview of that), and instead of a halo each lays the
header's own colour behind itself, extended a couple of pixels past the glyph by
a box-shadow spread rather than by padding, which would have moved them. Not
quite opaque, so it dims the letters it covers rather than punching a hole in
the name, and being the header colour it is invisible on a plain header. The
light theme's accent goes to full-brightness magenta with them.

A table that cannot scroll horizontally has no pin toggle - pinning is
meaningless there - so the colorize icon now takes the left edge itself instead
of leaving a hole where the pin would have been.

Three changes to what a cell offers:

 - a `Bool` cell offers `true` and `false`, the two values themselves rather
   than a comparison against the one in this cell: the choice is which of the
   two to keep, which is as often the other one as it is this one;
 - `startsWith` and `endsWith` are gone, leaving `contains`. An empty string
   loses that too - every string contains it - and keeps only `=` and `!=`;
 - the menu hangs from the cell's right edge and grows leftwards, so for a cell
   near the left of the page its first options ran off the side. It is now
   nudged back to the table's left edge, or the window's if the table is
   scrolled out past it. Measured, not decided from the column index: what
   matters is where the cell has ended up on screen.

Co-Authored-By: Claude Opus 5 <[email protected]>
Every header icon is meant to lay the header's colour behind itself so a column
name running underneath does not muddle it, but the funnel had none: the rule
that grants it comes before each icon's own, and the funnel's own rule - unlike
the pin's and the arrows', which are declared earlier - cleared the background
again afterwards. All three buttons stop resetting their background now and
leave it to the one rule that sets it.

Co-Authored-By: Claude Opus 5 <[email protected]>
A result the query-construction settings cannot shape dropped its sort arrows
but kept its funnel, which left two things wrong at once: the funnel was a
control that did nothing - `setColumnFilter` refuses on such a result, exactly
as the sort does - and it sat with the empty space of the missing arrows beside
it. Most visibly on a multi-query ("Run all") run, where a shape naming one
result's columns cannot be sent for the others, so no table of it is shapeable.

The funnel, the filter it displays and its input now go with the arrows. The
colorize toggle and the pin stay: those only change how a result is displayed,
so they work on any table.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c64b6e]

Summary: ✅


AI Review

Summary

This PR adds server-side result shaping to the Web UI: per-column sorting, filtering, pagination, URL/history persistence, and the surrounding restore logic. The overall design is strong, but the current restore path still reuses persisted shape state without revalidating it against the actual header that is now on screen, which leaves two correctness gaps.

Findings
  • ⚠️ [programs/server/play.html:2506] Restored pagination only validates that page and size are finite positive integers. It does not re-check the invariant that size must not exceed the current _pageSize(). A shared/edited URL or an old snapshot can therefore rerun page 2 with a limit larger than the table can display, truncate half the returned rows locally, and make the next page skip those rows entirely.
  • ⚠️ [programs/server/play.html:4536] Duplicate-name handling currently hides the sort/filter controls but does not scrub an already-restored sort or filter on that name. A shared URL or stored snapshot can still rerun with order / filter on SELECT 1 AS x, 2 AS x, leaving an invisible shape on a duplicate-named result or failing only after the rerun.
Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 87.00% +0.20%
Functions 91.90% 91.90% +0.00%
Branches 79.10% 79.30% +0.20%

Changed lines: Changed C/C++ lines covered: 39/39 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 20, 2026
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2c64b6eba with master f16824e50 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.68 MiB 702.76 MiB -2.92 MiB (-0.41%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

4 object files changed (+109.76 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Server/WebUIRequestHandler.cpp.o 8.14 MiB 8.25 MiB +109.77 KiB (+1.32%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

…nite page

Addresses the review of the result-shaping controls.

`sanitizePagination` accepted a non-finite `page` / `page_size`: `Infinity`, or an
overflowing literal such as `1e309`, survives `Number` and passes every lower bound, so a
hand-edited or shared link could make `renderPagination` iterate from `Infinity` to
`Infinity` (never terminating) and send `limit=Infinity` with the next run. Both values are
now required to be finite integers, and `_goToPage` rejects a non-finite page typed into the
pager's jump input for the same reason.

The shape was bound to the producing statement's text alone, but the columns of a result also
depend on the selected database, the connection and the query-parameter bindings:
`SELECT * FROM events` after switching databases, or `SELECT * FROM {tbl:Identifier}` after
editing the parameter, would keep the old sort, filter and page and apply them to a different
table. The binding now also carries `shapeContextKey` - the database, server, user and
parameter snapshot the run was launched with - and `resolveShapeForRun` drops the shape when
that changes, exactly as it does for a different statement. A shape restored from a URL, a
history entry or a stored snapshot has no recorded context and adopts the one of the run that
re-applies it.

`commitResultShape` stamped the chosen shape into the URL and the history entry before
launching the re-run that decides whether it still applies. A `Stop` or a reload in between
therefore left `sort_columns` / `filters` / `page` behind, to be rebound to whatever query
that entry carries on the next load. The stamping moved into the launch (`postSingle` right
after `resolveShapeForRun`, `postMulti` after dropping the shape a multi-statement run cannot
carry), so what reaches the URL and the history is the shape that actually ran;
`persistResultShape` takes the tab to persist and leaves the URL alone for a background one.

Tests: `test_play_result_shaping` covers the non-finite `page` / `page_size` payloads and
the context binding (a different database, server, user or parameter value drops the shape, the
parameter order does not matter, an unbound restored shape adopts the running context);
`test_play_reconcile_startup` gains `shape-not-stamped-before-run`, which asserts that a
shape change leaves no `sort_columns` in the URL or the history entry until the run stamps it.
Its stubbed `query-result` element also gains the methods this feature added, which the
startup reconciliation calls when a URL carries a shape.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 90c0dec (merged master too).

Addressed all three findings of the AI review and resolved the threads:

  • sanitizePagination (and the pager's page-jump input) now require finite integers, so page=Infinity / 1e309 can no longer make renderPagination loop forever or send limit=Infinity.
  • The result shape is now bound to the run CONTEXT as well as to the statement text — shapeContextKey(database, url, user, params) — so a database switch, a connection change or an edited query parameter drops it instead of shaping a different table.
  • The shape reaches the URL / the history entry only through the run that applies it (persistResultShape moved into postSingle/postMulti), so a Stop or a reload between the click and the run leaves nothing stale behind.

Also fixed this PR's own CI red: test_play_reconcile_startup failed in every integration shard with TypeError: el.refreshSortIndicators is not a function — the harness's stubbed query-result element lacked the methods this feature added, which the startup reconciliation calls when the URL carries a shape. Both JavaScript harnesses pass locally against the checkout.

The remaining reds are unrelated: the AST fuzzer Logical error: 'Equal values are not contiguous within the range assumed to be sorted' is tracked by #115831 and #115455 (a Web UI page cannot reach it), and Docker server image errored without a test result.

Comment thread programs/server/play.html Resolved
@mintlify

mintlify Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 22, 2026, 2:52 AM

Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 2 commits August 23, 2026 22:08
Address AI review: a shape restored from a stored result snapshot (a
reload, a tab reopened from IndexedDB, Back/Forward) was left with an
unbound context (`shapeContext = null`), so the first rerun adopted
whatever context it ran in - a database switch, a connection change or
an edited query parameter between the restore and the rerun kept the
old `ORDER BY` / `filter` and sent it into a different result
(`SELECT * FROM {tbl:Identifier}` sorted on a column of `hits` sent
that `ORDER BY` into `visits` after the parameter was edited).

The snapshot records the database, connection and parameters its rows
were produced with, so the restore now re-binds the shape to that
context (`snapshotShapeContext`), both in `materializeResult` and in
the tabs reopened from IndexedDB by `reconcileStartup`, and the first
rerun after a context change drops the shape exactly as it would have
before the reload. The unbound null context remains only for a shape
restored from a URL, which records no producing context; for a `run=1`
link the adopting run is the auto-run that follows the load, before
anything can be edited.

`shape_harness.js` extracts the new helper and pins the re-binding,
including the motivating parameter-edit trace, and the URL-restore
scenario is re-captioned to say what it now is: the one restore that
stays unbound.

#115540

Co-Authored-By: Claude Fable 5 <[email protected]>
Address AI review: the result shape keys both sorting and filtering by
the output column name, and a result can legitimately carry one name
twice - `SELECT 1 AS x, 2 AS x`, a join of tables sharing column
names, a `SELECT *` expansion. Both visible headers then collapsed
onto one shape slot: a click on either could only emit
`order=\`x\`` / `filter=(\`x\` ...)`, acting on an ambiguous
key or on the wrong column, and the per-type header maps overwrote one
namesake's type with the other's, so a cell menu could offer the wrong
comparisons.

Fail closed instead: `appendHeader` computes the names the header
carries more than once (`duplicateColumnNames`) and appends no sort
arrows and no filter controls on those columns, while the uniquely
named columns of the same result keep theirs. The shape entry points
(`_toggleSort`, `setColumnFilter`, the cell filter button) and the
indicator painters guard on the same set, so a shape smuggled in by a
hand-edited URL cannot resurrect the controls, and a duplicate-named
header never advertises a sort or filter state (`aria-sort`, the
in-effect coloring) it offers no control over. Pinning and color coding
stay: they are display state, where the name collapse can at worst
paint the namesakes alike, while a shape would act on the data of the
wrong column.

`shape_harness.js` pins the classification, and the fail-close
behavior is documented as a limitation.

#115540

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 2c64b6e (merged master too).

Addressed both findings of the AI review and resolved the threads:

  • A shape restored from a stored result snapshot is now re-bound to the snapshot's producing context — snapshotShapeContext builds the shapeContextKey from the recorded database / url / user / params — in materializeResult and in the tabs reopened from IndexedDB, so the first rerun after a database, connection or parameter change drops the shape instead of shaping a different result. The unbound-adopting null context remains only for a shape restored from a URL, which records no context of its own; for a run=1 link the adopting run is the auto-run itself. The {tbl:Identifier} trace from the review is pinned in shape_harness.js.
  • Duplicate output column names fail closed: appendHeader computes the names the header carries more than once (duplicateColumnNames) and offers no sort or filter controls on those columns — with matching guards in the shape entry points and the indicator painters — while the uniquely named columns keep theirs. Pinned in the harness and documented as a limitation.

All four Node harnesses (shape, reconcile, chart, image preview) pass locally against the checkout.

The one red, Stress test (arm_debug) — Logical error: The size of reverse_flags (A) does not match the size of KeyDescription B (STID: 3072-3c97) — is unrelated: it hit 32 runs across 26 PRs on 2026-08-23 and was caused by Lightweight Updates v2 (#103182), which #116005 has since reverted from master; this branch now carries the revert. (The dedicated fix, #115900, was closed for the same reason; the resubmission is #116007.)

Comment thread programs/server/play.html
/// an overflowing literal like `1e309`, and `Number` turns both into `Infinity`, which no comparison
/// against a lower bound rejects. An infinite page would make `renderPagination` loop forever, and an
/// infinite size would be sent as `limit=Infinity`.
function sanitizePagination(value) {

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.

The interactive Per page path clamps through _setPageSize, but restored pagination never re-checks that invariant. A shared or hand-edited URL can keep page_size=1000 even when the current header only supports, say, 500 rows per page; page 2 then reruns with limit=1000, the table renders only 500 rows, and page 3 starts at row 2001, silently skipping the truncated half-page. I think a restored size needs to be revalidated against the current _pageSize() (or dropped) before shapeUrlParams() reuses it, not only checked for finiteness and positivity.

Comment thread programs/server/play.html
/// `duplicateColumnNames`). Pinning and color coding stay: they are display state,
/// where the name collapse can at worst paint the namesakes alike, while a shape
/// would act on the data of the wrong column.
if (!this._duplicate_columns.has(elem.name))

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 only hides the duplicate-named column's controls. It does not scrub an already restored sort_columns / filters entry for that name, so a shared URL or stored snapshot can still rerun SELECT 1 AS x, 2 AS x with order=\x`orfilter=(`x` ...)`. That leaves an invisible shape on a result whose header offers no way to clear it, or fails only after the rerun. I think the duplicate-name classification needs to delete any existing sort/filter entries for those names once the header is known, not just suppress the buttons.

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Aug 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 24, 2026
Merged via the queue into master with commit b4f5ce4 Aug 24, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the play-result-sorting branch August 24, 2026 05:01
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
andybradshaw pushed a commit to andybradshaw/ClickHouse that referenced this pull request Aug 25, 2026
A result of at most one row on its first page has nothing to sort and
nothing to filter: any order of a single row is the same order, and a
filter on it can only keep it or drop it, so the column-header arrows
and funnels (and the cell funnel) could do nothing but re-run the query
for the same rows - and an empty result has not even a row to drop. They
are now withheld there, exactly as the colorize toggles already are:
with no more than one row there is nothing to compare either.

Two single-row results keep their controls, because there the controls
are the only way back: one the user has already shaped, whose sort must
stay reversible and whose filter must stay clearable (a filter matching
a single row is exactly how a long result becomes a short one), and one
cut off at the display limit, which is the first page of a longer result
(the page size is capped by the cell budget, so a very wide result can be
cut to a single row).

Follow-up to ClickHouse#115540

This branch was successfully deployed

1 active deployment
staging - docs — 2c64b6eb Deployed Aug 23, 2026 by mintlify[bot]
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.

2 participants