Skip to content

Web UI: do not update browser history on every keypress - #113596

Merged
alexey-milovidov merged 7 commits into
masterfrom
web-ui-no-history-on-keypress
Aug 10, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
web-ui-no-history-on-keypress

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The query editor's input handler rewrote the browser-history entry and the URL on every character. For a long query that means structured-cloning the whole result snapshot through replaceState, base64-encoding the query into the URL hash, retitling the document and rebuilding the tab bar per keystroke; browsers also rate-limit replaceState.

Now the handler keeps only the in-memory and persisted state in sync — the active tab's query and, through the parameter rebuild, its query parameters — and schedules the (already debounced) workspace save. Browser history and the URL are written when a query is successfully run (saveHistory) or on a structural tab change: switch, add, close, rename.

Three places compensate for the entry no longer tracking every keystroke:

  • closeTab and closeOtherTabs fold the active tab's latest edit into its own entry before the tab goes away, exactly as switchToTab/addTab already do on leave, so a later Back that recreates the closed tab restores the draft rather than the stale last-run text;
  • window.onpopstate keeps a newer unrun draft instead of overwriting it with the navigated entry's older query. tab.query !== tab.lastSavedQuery is exactly "the editor holds text no entry has recorded", since writeHistoryEntry sets lastSavedQuery to whatever it wrote;
  • a run that completes after the editor moved on records the launch snapshot rather than the live draft, so the entry is a coherent query/params pair by construction. Writing the newer draft instead would pair it with the parameter map of the older text — the draft's own parameter rebuild (updateQueryParams) is asynchronous and need not have landed — so the URL would advertise a binding for a placeholder the draft no longer has.

syncParamsAfterRebuild folds the rebuilt param_* inputs into the active tab, so the parameters follow the editor per keystroke without any history write; a new input is seeded from the tab's snapshot when no live input survived a restore, so folding cannot erase a saved binding.

An unrun edit is not restored across a reload unless a run or a structural change followed it, or the debounced save flushed it — in which case reconcileStartup's stale-reload branch restores it as editor text and never re-runs it. An unrun draft is never auto-executed.

Pinned by scenarios added to the existing test_play_reconcile_startup harness, which executes the real page script under node against a live server: a keystroke leaves the entry and URL untouched while still reaching the tab and IndexedDB; the persisted draft is restored, unrun, on reload; parameters follow the editor and leave no stale param_x in a later structural write; a run completing after an edit writes a coherent entry; Back/Forward keeps the draft; closing a tab folds it.

This replaces #109360, which took the same policy but reconstructed synchronously, at each remaining write site, what the per-keystroke write used to repair asynchronously — including an 80-line hand-written re-implementation of src/Parsers/Lexer.cpp's quoting, heredoc and comment rules in JavaScript. Keeping the parameters in sync per keystroke and recording the launch snapshot on a divergent run removes the need for any of it: programs/server/play.html here is +43/-20 code lines against +169/-27 there, with no new persisted state, no second lexer and no new CI image dependency.

Related: #109360
Related: #113595

Changelog category (leave one):

  • Improvement

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

In the Web UI, the browser history and the URL are no longer updated on every keypress; they are recorded when a query is successfully run or on a tab change.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

The query editor's `input` handler rewrote the browser-history entry and the
URL on every character. For a long query that means structured-cloning the
whole result snapshot through `replaceState`, base64-encoding the query into
the URL hash, retitling the document and rebuilding the tab bar per keystroke;
browsers also rate-limit `replaceState`.

Now the handler keeps only the in-memory and persisted state in sync — the
active tab's query and, through the parameter rebuild, its query parameters —
and schedules the (already debounced) workspace save. Browser history and the
URL are written when a query is successfully run (`saveHistory`) or on a
structural tab change: switch, add, close, rename.

Three places compensate for the entry no longer tracking every keystroke:

- `closeTab` and `closeOtherTabs` fold the active tab's latest edit into its
  own entry before the tab goes away, exactly as `switchToTab`/`addTab`
  already do on leave, so a later Back that recreates the closed tab restores
  the draft rather than the stale last-run text;
- `window.onpopstate` keeps a newer unrun draft instead of overwriting it with
  the navigated entry's older query. `tab.query !== tab.lastSavedQuery` is
  exactly "the editor holds text no entry has recorded", since
  `writeHistoryEntry` sets `lastSavedQuery` to whatever it wrote;
- a run that completes after the editor moved on records the LAUNCH snapshot
  rather than the live draft. The entry is then a coherent query/params pair
  by construction. Writing the newer draft instead would pair it with the
  parameter map of the older text — the draft's own parameter rebuild
  (`updateQueryParams`) is asynchronous and need not have landed — so the URL
  would advertise a binding for a placeholder the draft no longer has.

`syncParamsAfterRebuild` folds the rebuilt `param_*` inputs into the active
tab, so the parameters follow the editor per keystroke without any history
write; a new input is seeded from the tab's snapshot when no live input
survived a restore, so folding cannot erase a saved binding.

An unrun edit is not restored across a reload unless a run or a structural
change followed it, or the debounced save flushed it — in which case
`reconcileStartup`'s stale-reload branch restores it as editor text and never
re-runs it. An unrun draft is never auto-executed.

Pinned by scenarios in the existing `test_play_reconcile_startup` harness,
which executes the real page script under `node`: a keystroke leaves the entry
and URL untouched while still reaching the tab and `IndexedDB`; the persisted
draft is restored, unrun, on reload; parameters follow the editor and leave no
stale `param_x` in a later structural write; a run completing after an edit
writes a coherent entry; Back/Forward keeps the draft; closing a tab folds it.

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

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4d41944]

Summary: ✅


AI Review

Summary

This PR stops rewriting the /play history entry and URL on every query keystroke, and instead syncs browser history only on runs or structural tab changes while trying to keep draft queries and parameter snapshots coherent across reloads and Back/Forward. The overall direction is good, but one new regression still drops trusted param_* edits after a query-side rebuild failure, and the current textual-prune fallback can still leak removed parameter values into shareable URLs when the old placeholder text survives only inside comments or strings.

Findings

⚠️ Majors

  • [programs/server/play.html:12230] Routing trusted param_* edits through captureActiveTab drops the user's new value when extractQueryParamNamesSync cannot re-derive the query anymore (for example after editing into a query that is too large for the lexer). updateQueryParams leaves the old input on screen in that failure mode, but this handler now persists the old tab.params snapshot instead of the live DOM value, so a reload or quick close loses the edit. Suggested fix: when this path handles a trusted parameter edit, preserve the live value for the names that are still on screen, or clear those stale inputs immediately once the query-side rebuild fails so the old snapshot cannot be re-persisted.

  • [dismissed by author -- https://github.com/Web UI: do not update browser history on every keypress #113596#discussion_r3739673963] [programs/server/play.html:11930] pruneParamsToText treats any textual {name: opener as proof that a binding still belongs to the query. If the real placeholder was removed but the old opener survives only inside a comment or string, the fallback still republishes that deleted value into browser history / copied URLs. That is not just an unused param_*: it can leak sensitive parameter contents after the query stopped referencing them.

Tests
  • ⚠️ Add a focused harness scenario where updateQueryParams fails after a visible param_* input already exists (for example by growing the query past the lexer limit), then edit that surviving input and assert that the new value survives syncHistory() / persisted reload instead of falling back to the old snapshot.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 6, 2026
Comment thread programs/server/play.html Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4d4194438 with master e493bf79b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2b2987cc1; 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 690.67 MiB 687.67 MiB -3.01 MiB (-0.44%)

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 (+18.71 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Server/WebUIRequestHandler.cpp.o 7.90 MiB 7.92 MiB +18.70 KiB (+0.23%)

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

Addresses the AI review finding: the parameter inputs are rebuilt
asynchronously after a query edit (most visibly while the first
`WebAssembly.instantiate` of the lexer is still in flight), so a
history-writing action in that window (`addTab`, `closeTab`, a database
change) snapshotted the PREVIOUS text's `param_*` inputs under the new
draft — e.g. recording `param_x=42` under `#SELECT 1` after editing
`SELECT {x:Int32}`, which Back/Forward, copied URLs and the next
persisted write then restored.

`captureActiveTab` now tracks which text the inputs describe
(`params_synced_text`, committed by `updateQueryParams`) and, on a
mismatch, re-derives the placeholder set synchronously from the captured
text (`tokenizeSync`, split out of `tokenize`), binding only surviving
names — live input values first, the tab's own saved snapshot as the
fallback seed, mirroring what the pending rebuild would eventually
commit. When even that is impossible (lexer not yet instantiated or the
text too large to tokenize), the tab's last committed snapshot is kept
instead of adopting values known to describe different text. The lexer
instantiation is kicked off eagerly at startup to shrink that window,
and the trusted parameter-edit path snapshots through `captureActiveTab`
for the same coherence.

The reconcile harness gains a scenario driving the race deliberately
(the close runs in the same synchronous turn as the edit): a removed
placeholder's binding must not appear in the folded entry, and a
surviving placeholder must keep its value.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three CI failures on cf9f9aa are unrelated to this HTML-only change (all are server-side logical errors from stress/fuzzer runs):

None of the fixes are on master yet, so re-merging master would not clear them.

alexey-milovidov and others added 2 commits August 7, 2026 10:41
…cribe

The previous fix (f449c10) made `captureActiveTab` re-derive the
placeholder set synchronously, but when even that is impossible — the first
`WebAssembly.instantiate` of the lexer still in flight, a text too large to
tokenize, or a tab restore that has not committed yet — the capture kept the
previous text's snapshot and a structural write (`closeTab`, `addTab`, a
database change) still published it: `{"query":"SELECT 1","params":{"x":"42"}}`
for a draft that no longer has `{x:Int32}`.

Track per tab which query text the snapshot was last coherently committed for
(`paramsSyncedQuery`, stamped by every commit site: the capture, a restore, a
popstate, `syncParamsAfterRebuild`, the startup URL reconciliation), and let
`writeHistoryEntry` publish the snapshot only while it matches the recorded
text — otherwise the entry records an empty parameter map, coherent by
construction, while `tab.params` stays in memory as the seed the pending
rebuild prunes and re-commits.

The new `capture-races-lexer-load` harness scenario pins it: it delays
`WebAssembly.instantiate` past startup settlement (the reviewer's reproducer)
and folds a `closeTab` inside that window; on the previous code it fails with
exactly the stale entry above.

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

alexey-milovidov commented Aug 8, 2026 •

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113596&sha=3ff35b9f829b63cacf83160804ed63be3c1c99d6&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this HTML-only PR: Logical error: Bad cast from type A to B — a failed assert_cast<const ColumnNullable &> in SerializationNullable::enumerateStreams, reached from collectOffsetsColumns in inplaceBlockConversions.cpp while reading offsets of a missing Array(Nullable(...)) column. CIDB shows the same signature (STID: 3520-4525) failing 21 times on 2026-08-07 across master (pull_request_number = 0) and 18 other PRs, so it is a master-side regression. I found no open issue or PR matching this exact site (issue #113891 is a different serialization cast, in SerializationString::serializeBinaryBulk).

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

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

A fix is in progress; I will link the PR here when it opens. Full root-cause write-up is on
#113595 (#113595 (comment)) to avoid repeating it on all three threads.

Short version: unrelated to this PR, and the regression is mine. PR #113225
(3f32ec585343475, merged 2026-08-05 07:15:20Z) let a subcolumn entry win a Nested group
member's element type in getSubcolumnsOfNested; a subcolumn entry's type_in_storage is the
type in metadata, so a part still holding Array(String) gets walked as
Array(Nullable(String)) and enumerateStreams asserts on it.

Your reading that #113891 is a different site is correct, and I verified it independently: that
one is the write path (SerializationString::serializeBinaryBulk under
MergeTreeDataPartWriterOnDisk::initColumnsSubstreamsIfNeeded from MutateTask::execute), with
zero occurrences of collectOffsetsColumns, fillMissingColumns or enumerateStreams in its
trace. Your "no open issue or PR matching this exact site" was also correct.

… time

When a history-writing action lands while the tab's parameter snapshot is
not provably coherent with the recorded text (`paramsSyncedQuery` mismatch
and the synchronous re-derivation impossible — e.g. the first
`WebAssembly.instantiate` of the lexer still in flight), `writeHistoryEntry`
used to publish an empty parameter map. That fixed the removed-placeholder
case but regressed the surviving-placeholder one: editing
`SELECT {x:Int32}` to `SELECT {x:Int32} + 1` and closing the tab inside the
lexer-load window published `{}", so Back or a copied URL recreated the
draft without `x` although the placeholder survived and its value was
still valid.

Deciding which of the OLD text's bindings survive in the new one needs no
tokenizer: a real placeholder always contains the opener `{name:` literally.
`pruneParamsToText` keeps exactly the bindings whose opener appears in the
recorded text (whitespace-tolerant, identifier names only) and drops the
rest. The over-approximation — an opener inside a string literal or comment
keeps a binding the rebuild would prune — costs one unused `param_*` in a
URL, pruned again on restore, unlike dropping a live value.

The harness `capture-races-lexer-load` scenario now runs both edits: the
removed placeholder still publishes no binding, and the surviving one keeps
`x=42" (fails on the previous head with `params: {}").
Comment thread programs/server/play.html Resolved
When the lexer never becomes available (no `WebAssembly`, a failed load, or
a permanently too-large query), an edit advances `tab.query` and the
debounced `persist` records the new text with the OLD parameter snapshot in
`IndexedDB`. On reload, `restoreEditor`'s no-rebuild branch stamped that
never-rebuilt pair as coherent for the new text (`paramsSyncedQuery =
state.query`), so the startup history write republished the stale binding:
`history.state.params = {x: '42'}` and `?param_x=42` under a `SELECT 1`
that no longer has `{x:Int32}`.

Persist the snapshot's provenance (`paramsSyncedQuery`) with the tab record
and pass it through `activateTab` into `restoreEditor`, which now stamps
the text the committed values PROVABLY describe: the restored query when the
inputs were rebuilt for it (or when the state's own pair was coherent), and
the pair's original provenance otherwise. An incoherent pair then stays
incoherent across the reload, so `writeHistoryEntry` publishes it pruned
textually, exactly like the same-session lexer-load window: a removed
placeholder's binding is dropped, a surviving one keeps its value. For a
legacy record without the field the provenance defaults to null (fail-closed);
that costs nothing for a coherent pair, whose textual prune is a no-op. This
also covers the same-session variant: switching away from and back to a tab
edited during a no-lexer window no longer re-stamps its pair as coherent.

Adds the `disableWasm` harness knob (removes `WebAssembly` outright, so the
lexer never loads) and the `persisted-draft-stale-params` scenario: edit a
saved parameterized tab with the lexer unavailable, wait for the debounced
persist, reload, and assert the entry/URL carry no removed-placeholder binding
while a surviving placeholder keeps its value. The removed-placeholder variant
fails on the previous commit with exactly `?param_x=42#SELECT 1`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single CI failure on c40d67f — Stress test (arm_release), S3_ERROR: The specified key does not exist while loading part all_1_1_0 of t_merge_over_stale_packed (reported via no_such_key_errors.txt) — is unrelated to this HTML-only PR. The table comes from the stateless test 04630_merge_over_stale_packed_tmp_dir, which corrupts shared S3 keys when it runs on an S3 disk in stress runs; the fix is already open: #113978 (pin the test to the local disk).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both CI failures on 2c3f9fc are unrelated to this HTML-only change:

Neither fix has merged to master yet, so remerging the base would not clear these reds. The AI review reports no blocking issues on the current head.

Comment thread programs/server/play.html
/// `syncHistory` below publishes it.
const tab = getActiveTab();
if (tab) { tab.params = getParamValues(); syncHistory(); }
if (tab) { captureActiveTab(); syncHistory(); }

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.

Routing trusted param_* edits through captureActiveTab regresses the "query too large to tokenize" path. If a tab already shows param_x, the user edits the query into a text that makes updateQueryParams fail, and then edits that still-visible param_x, captureActiveTab returns at extractQueryParamNamesSync(tab.query) === null without adopting the live DOM value. syncHistory() and the scheduled persist() then keep the old tab.params.x, so a reload or quick close loses the user's new value even though the input they just edited stayed on screen. We still need either to preserve trusted DOM values for surviving on-screen names when re-derivation fails here, or to clear those stale inputs once the query-side rebuild fails so this handler cannot persist the old snapshot.

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 would be too much.

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 9d76cce Aug 10, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the web-ui-no-history-on-keypress branch August 10, 2026 13:47
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

3 participants