Skip to content

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

Closed
alexey-milovidov wants to merge 71 commits into
masterfrom
web-ui-history-on-run
Closed

alexey-milovidov wants to merge 71 commits into
masterfrom
web-ui-history-on-run

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

In the Web UI (play.html), the query editor's input handler updated the browser-history entry and the URL, re-set the window title, rebuilt the tab bar, and scheduled a workspace save on every keystroke. For a long query that is needless work on each character.

Now the input handler only keeps the active tab's query in sync in memory (tab.query). Browser history, the URL and the persisted workspace are recorded when a query is successfully run (saveHistory) or on a structural tab change — switch, add, close, rename — each of which captures the editor and writes history / schedules a save itself.

This branch was reconciled onto master's per-tab, concurrent-run rework of the same layer (the persistent-tabs series). That architecture already provides most of the supporting machinery — structural-boundary folding in switchToTab/addTab, the preserve_local_query stale-reload branch in reconcileStartup, a debounced persist that folds the live draft via captureActiveTab, the lastSavedQuery marker, and saveHistory's launch-vs-live divergence guard that drops run=1 when the editor moves on. So the "history on run, not on keypress" policy is applied as three focused changes on top of it:

  • the query_area input handler syncs only tab.query in memory (no refreshCurrentHistoryEntry / scheduleSave per keystroke);
  • window.onpopstate keeps a newer unrun draft (preserve_draft: tab.query !== event.state.query && tab.query !== tab.lastSavedQuery) instead of overwriting it with the entry's older query, so activateTab restores the draft while the entry's own result snapshot still renders. The predicate deliberately uses lastSavedQuery (dirty since the tab's last history write), not tabReflectsRun, so a clean Run selected — whose result snapshots only the selected statement while the editor keeps the full text — is not mistaken for a draft;
  • closeTab folds the active tab's latest edit into its own history entry (captureActiveTab + refreshCurrentHistoryEntry) before removing it, so a later Back that recreates the closed tab (resolveTabForState) restores the draft, not the stale last-run text.

Behavior guarantees: an unrun draft is never auto-executed — the editor-only history writers never stamp run=1 for an unrun edit (tabReflectsRun fails once the editor diverges from the produced result). The run=1 marker itself is a per-tab policy (tab.runnableUrl, persisted with the workspace but honored on restore only when the load itself carries the run=1 directive): it is (re)stamped by a genuine run under a ?run=1 load and adopted from a Back/Forward entry whose URL already carries it, never derived from a mutable session-global — so a stale reload's suppression is scoped to the preserved draft's own entries (an explicit rerun recovers run=1, and switching into another clean run-backed tab keeps its marker), while a run=1 URL meant for one tab can never make another tab's URLs auto-runnable, and the directive never outlives its own session: a plain /play navigation clears the restored markers, so it neither rewrites a restored tab's URL back to ?run=1 nor lets a later reload auto-execute a query that this navigation never asked to run. When a run's completion — or a structural leave (switchToTab/addTab/duplicateTab/closeTab, whose captureActiveTab snapshots the live inputs) — lands after the user already edited the query but before the async placeholder rebuild, the writer prunes the parameters by a conservative textual placeholder scan of the captured text (queryMentionsParam), so the URL never pairs the newer draft with a removed placeholder's binding, even transiently. An unrun edit is generally not restored across a reload if no run or structural change followed it; the last successfully run query is shown, which matches "remember what you ran". Where a debounced persist did flush a draft to IndexedDB, a reload restores it as editor text but never re-runs it (reconcileStartup's stale-reload branch refuses the URL's run=1); a clean run, by contrast, is both restored and re-run.

Pinned by the stateless regression test 04549_play_ui_history_draft_regression, which extracts the real tab/history functions (saveHistory, writeHistoryEntry, window.onpopstate, closeTab, switchToTab, reconcileStartup, postAll/postMulti, …) from the served /play page and drives them under node with stub DOM / history / a minimal in-memory IndexedDB, with cases for the run=1 policy scoping, for the adoption of a legacy pre-tabId history entry on Back (so the structural folds recognize it and a close+Back keeps the draft), and for an edit typed while a multi-statement run is genuinely in flight inside the real postAll -> postMulti completion plumbing (only the lexer and the network round-trip are stubbed) (stale reload → explicit rerun → reload; stale reload → tab switch), by 04616_play_ui_history_param_placeholder_sync, which drives the REAL parameter pipeline (embedded WASM lexer, updateQueryParams rebuild, launch-time binding) including the entry written before a racing rebuild lands, and by the integration test test_play_reconcile_startup (whose harness executes the real page script and drives the actual editor input handler / structural fold). Since no CI image had a JavaScript engine, node is installed into the stateless-test image as part of this change.

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)

🤖 Generated with Claude Code

The query editor's `input` handler ran `refreshCurrentHistoryEntry` on every
keystroke, which rewrote the browser-history entry and URL, re-set
`document.title` to the whole query, and rebuilt the tab bar - per character.
It also scheduled a workspace save on every edit. For a long query this is
needless work on each keystroke.

Only keep the active tab's query in sync in memory on input. Browser history,
the URL and the persisted workspace are now recorded when a query is
successfully run (`saveHistory`) or on a structural tab change - switch, add,
close, rename - which capture the editor and write history / schedule a save
themselves. As a result an unrun edit is not restored across a reload if no
run or tab change followed it; the last successfully run query is shown, which
matches "remember what you ran".

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [234ff3a]

Summary: ✅


AI Review

Summary

This PR moves the Web UI history / URL updates off the editor's per-keystroke path and adds substantial regression coverage around play.html history, persistence, and parameter syncing. One blocker remains: same-session Back/Forward draft preservation now keeps only the draft text / params, while restoring the older entry's execution target, so rerunning a preserved draft can hit the wrong database or connection.

Findings

❌ Blockers

  • [programs/server/play.html:9718] preserve_draft keeps tab.query / tab.params, but window.onpopstate has already rewound the older entry's execution context before reactivating the editor. I reproduced this with the real extracted harness by creating two run-backed entries on the same tab with different database= values, typing an unrun draft on the newer one, and pressing Back: the draft text survives, but selected_database becomes the older entry's db1, so pressing Run executes the preserved draft in db1. The same handler restores url / user on cross-connection navigation, so the mixed state is broader than the database case. Preserve the draft's target context together with its text, or disable draft preservation when the Back target differs in connection / database; add a regression that varies database= (and ideally url= / user=) between the two entries.
Final Verdict

Request changes.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
…e tab

The previous commit stopped refreshing the active tab's browser-history entry
on every keystroke, recording it only on a run or a structural tab change. The
PR describes closing a tab as one of those structural changes that "capture the
editor", but `closeTab` did not actually fold the closing tab's latest editor
edit into its own history entry the way `switchToTab` and `addTab` do for the
tab they leave.

As a result, after editing the active tab and closing it, pressing browser Back
recreated the tab from `history.state` (`resolveTabForState`) using the stale
last-run/URL snapshot rather than the newer unrun edit, losing the draft.

Now `closeTab` calls `captureActiveTab` + `refreshCurrentHistoryEntry` for the
tab being closed before splicing it out, mirroring `switchToTab`/`addTab`, so a
later Back that recreates the tab restores its latest edit and parameters.

Found by AI Review on #109360

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
@alexey-milovidov
alexey-milovidov requested a review from pamarcos July 6, 2026 04:57
@pamarcos

pamarcos commented Jul 6, 2026

Copy link
Copy Markdown
Member

Feedback from GPT-5.5:
The “do not update history on every keypress” contract still leaks unrun edits. A pending debounced persist snapshots the live editor when the timer fires, so an edit made during the debounce window can survive reload, and parameter edits still call syncHistory and can restamp an unrun query into URL/history state. Please persist only the snapshot that was current when the save was armed, and avoid parameter edits persisting unrun query text unless that behavior is intended and documented.

@pamarcos pamarcos self-assigned this Jul 6, 2026
alexey-milovidov and others added 2 commits July 11, 2026 23:43
The AI review (Request changes) and @pamarcos's GPT-5.5 feedback flagged that,
after this PR stopped per-keystroke history/persist updates, two paths can still
fold a later unrun draft into a saved/URL entry: a debounced `persist` that fires
after fresh typing, and a trusted parameter edit that calls `syncHistory`.

Both are real but intentional and harmless, and the suggested "fixes" are worse:
- Freezing the debounced save to an arm-time snapshot would drop structural tab
  changes coalesced within the 400 ms window (`scheduleSave` is a no-op while a
  timer is pending), i.e. a genuine loss of persisted tabs.
- Making a parameter edit sync only params (not the query) would either stamp
  params onto a mismatched query or leave the URL params stale relative to the
  tab, contradicting the invariant that a reload's URL params are never stale.

In both paths a restored draft is only shown, never auto-executed: the workspace
store carries no `run` flag and the editor-only history writers never set `run=1`
for an unrun edit (`tabReflectsRun` is false once the editor diverges). Document
this intended, harmless behavior at both sites and refine the input-handler
comment so the "unrun edit is not restored" contract names these two exceptions.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
…und-trip

The AI review found that after removing the per-keystroke history refresh,
`window.onpopstate` could clobber a newer in-memory draft: run `SELECT 1`,
type `SELECT 2`, press browser Back to an older entry, then Forward. The
forward entry still carries `SELECT 1`, so restoring `event.state.query`
overwrote the live `SELECT 2` draft (an in-session data loss).

`onpopstate` already captures the outgoing tab's editor into `tab.query` via
`captureActiveTab`, so the latest draft survives in memory; the fix is to not
overwrite it when returning to a stale entry. Keep the draft when it diverges
from the entry AND does not merely reflect the entry's own produced result
(`tabReflectsRun` false); the entry's result snapshot is still rendered,
reproducing the pre-navigation edited-but-unrun state. A freshly recreated tab
has `tab.query === event.state.query`, and normal Back/Forward between two runs
of the same tab reports `tabReflectsRun` true, so both keep restoring the
entry's query exactly as before. Reload behavior is unchanged (the URL still
holds the entry's last-synced query).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 2 commits July 13, 2026 15:39
The review twice found draft-loss regressions in the play.html history
contract (closeTab not folding the latest draft into the closed tab's
entry, and onpopstate clobbering a newer unrun draft on a Back/Forward
round-trip), and both were caught only by manual reasoning. Pin the
contract with a stateless test: it extracts the real tab/history
functions from the served /play page and drives them under node with
stub DOM/history objects, asserting that a closed tab's entry carries
the latest draft (without run=1), that Back recreates the tab with the
draft, that a same-session Back-then-Forward round-trip preserves a
newer unrun draft, and that a clean editor keeps restoring entries
verbatim.

node was not available in any CI image, so install it into the
stateless-test image (the stress image inherits it); the test is tagged
no-fasttest because the fast test (including arm_darwin, which runs
natively) has no node.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/server/play.html Resolved
When `window.onpopstate` preserves a newer unrun draft over the history
entry's older query, it still overwrote `tab.params` from the entry and
passed the entry's params into `restoreFromHistory`, so a same-session
Back/Forward round-trip kept the draft query text while silently
restoring (and then persisting, via the scheduled save) the older
parameter bindings under it — an incoherent query/params pair. Keep the
captured `tab.params` together with the draft query and pass them
through the restore state; with no draft, entry params keep restoring
verbatim as before.

Extend `04538_play_ui_history_draft_regression` to pin this: the
harness now models live parameter inputs (`getParamValues` snapshots
them, the `restoreFromHistory` stub propagates `state.params` into the
inputs and the active tab, and a `setParam` helper mimics the trusted
`param-` input handler including its `syncHistory` stamp), and adds a
preserved-draft round-trip with non-empty params plus a clean-editor
control. Verified the new asserts fail on the previous code for both
the full and the restore-state-only regression.

Addresses the AI review Blocker and Major on the PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 3 commits July 14, 2026 08:22
…auto-run)

Address review (clickhouse-gh) on `programs/server/play.html`.

The `window.onpopstate` comment claimed that after preserving an unrun draft
across a same-session Back/Forward, "a subsequent reload still restores the
entry's query, per the contract". That is not what happens: the handler sets
`lastSavedQuery` to the entry query while `tab.query` holds the draft, and the
trailing `scheduleSave` persists the pair `{ query: <draft>,
lastSavedQuery: <entry query> }`. `reconcileStartup` treats exactly that shape
as a stale reload of an edited-but-unresynced tab and restores the DRAFT as
editor text, not the entry query.

This is the same harmless outcome the `scheduleSave` comment already documents
for any debounced save that flushes a divergent draft: the draft is only shown,
never auto-executed (the workspace store carries no `run` flag, editor-only
history writers never stamp `run=1` for an unrun edit, and `reconcileStartup`
drops the URL's `run=1` on the stale-reload branch). The guaranteed reload
invariant is "an unrun draft is never auto-run", not "reload always restores
the last run's query".

Correct the `onpopstate` comment, generalize the editor `input` handler comment
(the earlier "two narrow paths" wording undercounted: the `onpopstate`
`scheduleSave` and `persistColorModes` are additional paths that fold a draft
in), and add a note to `persistColorModes` that its debounced `persist`
snapshots the live editor. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review (clickhouse-gh): the earlier `04538_play_ui_history_draft_regression`
harness stubbed `setTimeout` so the debounced `persist` never ran, so it could not
observe what a reload does with a persisted unrun draft.

Extend the harness with a minimal in-memory IndexedDB and extract the real
`persist`, `loadFromDb`, `persistColorModes` and `reconcileStartup`, plus a `reload`
helper that flushes the workspace and re-runs startup reconciliation against the URL,
exactly as a real reload does. New cases pin the two paths the review flagged:

  - after a preserved-draft Back/Forward round-trip, a reload restores the draft as
    editor text but does NOT auto-run it (the stale-reload branch drops the URL `run=1`);
  - a color-mode toggle over an unrun draft (`persistColorModes`) persists the live
    editor, so a reload likewise restores the draft as editor text, never auto-run.

A control asserts the contrast: reloading a clean run both restores and re-runs the
query, since the URL stays authoritative. Verified by mutation — breaking the
stale-reload detection fails the "draft restored" assertions, and dropping the
`!preserve_local_query` auto-run guard fails the "not auto-run" assertions.

The history stub now syncs `location.href` on navigation (as a browser does), so
`persistColorModes`'s `new URL(window.location)` and the `onpopstate` restamp read the
current entry back.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
@pamarcos

Copy link
Copy Markdown
Member

Feedback from GPT-5.6 Sol Pro

The new draft-preservation predicate conflates an unrun edit with a clean partial execution. After Run selected, the full editor in tab.query intentionally differs from the selected statement in tab.result.query, so !tabReflectsRun(tab) makes preserve_draft true even when the user has not edited anything after the run.

Concrete sequence: run SELECT 0; change the editor to SELECT 1; SELECT 2; run only SELECT 2; then press Back. The URL and displayed historical result move to SELECT 0, but the editor remains SELECT 1; SELECT 2. Back/Forward therefore leaves the editor, URL, and result describing different states.

This is also captured in the unresolved inline thread. The regression harness currently always models query === resultQuery, so please add a case with a clean Run selected, followed by Back/Forward, plus a control case where a genuine post-run edit is preserved.

…editor

The `onpopstate` handler decided whether to preserve a live in-memory draft
over a history entry's older query using `!tabReflectsRun(tab)`. But
`tabReflectsRun` is also false for a clean `Run selected`: `saveHistory` keeps
the full editor in `tab.query` while the result snapshots only the selected
statement in `tab.result.query`, so the editor never reproduces the result even
without any post-run edit. As a result, browser Back/Forward after a `Run
selected` mistook the run-backed editor for a newer unrun draft and stopped
restoring older query text.

Use a precise "dirty since the tab's last history write" check instead,
`tab.query !== tab.lastSavedQuery`: an unrun edit updates `tab.query` in memory
but leaves `lastSavedQuery` at the last run / structural-change value, so the
two diverge exactly when there is a genuine unrun draft. A draft already stamped
into a history entry by a parameter edit (via `syncHistory`) is then navigable
coherently: Back restores the prior entry and Forward returns to the stamped
draft, so the draft is never lost.

Extend `04538_play_ui_history_draft_regression` with a clean `Run selected`
Back/Forward case (which fails on the old predicate), a draft-typed-after-`Run
selected` case, and a dirty-draft parameter-preservation case.

Addresses the AI review finding on #109360

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@pamarcos The GPT-5.6 finding crossed paths with the fix: commit f4d7ea3 (pushed two minutes after the comment) replaces !tabReflectsRun(tab) with a precise "dirty since the tab's last history write" predicate: tab.query !== tab.lastSavedQuery. lastSavedQuery is stamped by writeHistoryEntry on every entry write, so it diverges from tab.query exactly when there is a genuine unrun edit — a clean Run selected no longer counts as a draft, and Back/Forward restore the entries as expected.

The regression harness 04538_play_ui_history_draft_regression.sh now covers both requested cases: a clean Run selected followed by Back/Forward ("run-selected back/forward"), and a control where a genuine post-run edit typed after Run selected is preserved ("run-selected+draft back"). The corresponding inline thread is resolved, and the AI re-review of the new head flipped to Approve.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109360&sha=f4d7ea385828706b6c33bcd9e056cce835612765&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

01039_mergetree_exec_time expected TIMEOUT_EXCEEDED (159) but got QUERY_WAS_CANCELLED (394, "Query ... is killed in pending state") under TSan parallel load. The harness rerun diagnosis passed 27/27 with the same randomized settings, and this is the only occurrence of this test failing across all of CI in the last 14 days, so it is unrelated to this PR (which only touches programs/server/play.html and a stateless shell test). I found no open issue tracking it.

@pamarcos

Copy link
Copy Markdown
Member

Feedback from GPT-5.6 Sol Pro

The clean Run selected versus dirty-draft issue from the previous round is fixed and now has focused assertions. Two in-flight edit paths still violate the new history contract:

  1. postAll snapshots the launch-time editor, but postMulti passes the live query_area.value to saveHistory when the old run finishes. Typing does not cancel the request. On a page opened with run=1, start SELECT sleep(2); SELECT 1, replace the editor during execution with an unrun mutation, wait for completion, and reload: saveHistory records the new draft as the completed run and retains run=1, so reload executes it. Use the run-start snapshot, and never mark a divergent live draft as fromRun.

  2. A delayed single-query completion saves the run-start query and saveHistory overwrites tab.query even if the visible editor changed meanwhile. A subsequent parameter edit updates only tab.params before syncHistory, pairing the old query with inputs belonging to the visible draft and potentially losing that draft on reload.

Please preserve the live editor independently of an in-flight result and add deterministic tests that edit query text and parameters while single- and multi-query runs are outstanding.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI reds on 5c3c663b520 were both unrelated to this HTML-only change, and both are now handled:

The remaining AI Review Major (rename writing history outside the capture funnel) is fixed in 179b14ee24f, with a mutation-verified regression in 04616_play_ui_history_param_placeholder_sync.

Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 2 commits July 30, 2026 17:26
…funnel

A trusted edit of a live parameter input wrote history from a raw
`getParamValues()`. After a query edit that removed a placeholder, the
live inputs (and `currentQueryParams`) still describe the pre-edit text
until the asynchronous `updateQueryParams` rebuild lands, so editing
another value in that window serialized the removed placeholder's
binding into the entry and the URL (`/play?param_x=1&param_y=3#SELECT
{y:Int32}`); a reload or a copied link then resurrected it.

The listener now goes through `captureActiveTab` before `syncHistory`,
like every other history writer: the capture merges the tab-owned
snapshot behind the live inputs and prunes the result against
`tab.query` (`queryMentionsParam`), so the stale binding never reaches
the entry while the edited binding survives.

Pinned in `04616_play_ui_history_param_placeholder_sync`: with the
removing edit's tokenization gated, a trusted edit of the surviving
parameter must not carry the removed one (fails pre-fix at 'the capture
prunes the removed binding'), and the landing rebuild keeps the edited
binding.

Co-Authored-By: Claude Fable 5 <[email protected]>
The only red on 91d1694 was 01666_merge_tree_max_query_limit
(amd_llvm_coverage), whose fix #112385 merged into master after the
previous merge; this pulls it in. Master did not touch play.html.
Comment thread programs/server/play.html Resolved
`queryMentionsParam` was a raw regex over the query text, so
placeholder-shaped text inside a string literal or a comment
(`SELECT '{x:Int32}'`, `-- {x:Int32}`) counted as a live placeholder:
after an edit that moved the placeholder into quotes, a structural
capture or `saveHistory`'s diverged-draft prune kept the stale
`param_*` binding, and the entry/URL carried it with nothing left to
repair them once the activation superseded the rebuild. The raw scan
also under-reported a comment between the placeholder tokens
(`{/*c*/x/*c*/: Int32}`), wrongly dropping a live binding.

The scan now blanks out string literals, quoted identifiers, heredocs
and comments first (`maskQuotedAndComments`, mirroring the lexical
rules of `src/Parsers/Lexer.cpp` behind `tokenize`), and stays
conservative in the keep direction: it can only over-report relative
to the token-level extraction, never miss a real placeholder.

Test: 04616 gains a lexical table cross-checked against the real
embedded WASM lexer (the scan must never report a placeholder gone
where the token-level extraction finds it), a capture-funnel case (a
gated rebuild, the placeholder edited into a string literal, a tab
switch must prune the binding while an unquoted one survives), and a
`saveHistory` completion-race case with a commented-out placeholder.
Mutation-verified: reverting to the raw regex fails the new asserts.
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 2 commits August 1, 2026 16:20
The inline title editor's `commit` unconditionally reached the
`captureActiveTab` + `syncHistory` + `scheduleSave` funnel, so canceling a
rename with `Escape` (or committing an unchanged/empty title) copied an
unrun editor draft into `history.state`, the URL hash and `lastSavedQuery`
— a reload then restored text the contract says is only recorded on a run
or a real structural change. Gate the funnel on an actual title change;
an actual rename remains a history writer.

Regressions in 04616: canceled (`Escape`) rename, same-title rename and
all-whitespace rename over an unrun draft leave the entry, `run=1` and the
title untouched, while a real rename over the same draft still writes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/server/play.html Resolved
`window.onpopstate` only ever promoted `tab.runnableUrl` to `true` and never
cleared it, so the bit was sticky for the whole page tab. Browser-history
entries outlive a page, so one tab can hold an older entry written under a
plain load and a newer one written after a fresh navigation to a shared
`?run=1` link. After visiting the newer entry, going Back to the older plain
one left `tab.runnableUrl === true`; the next structural write (`addTab`,
`switchToTab`, a rename, ...) then saw a clean run-backed tab and
`writeHistoryEntry` re-stamped that older entry as `?run=1`. Reloading or
sharing it would auto-execute a query that was never opened with `run=1`.

`writeHistoryEntry` now records the policy in the entry state (`runnableUrl`),
and `window.onpopstate` restores the policy of the entry it navigates to. The
POLICY is stored rather than the entry's own `run=1` marker: an editor-only
entry written during a `run=1` session legitimately carries no marker
(`tabReflectsRun` is false) yet must keep the policy so the next clean run of
that session can stamp the marker again. A legacy entry without the stored
policy keeps the previous promote-only behavior, the only evidence available.

`04549_play_ui_history_draft_regression` gains a case that mixes an older
plain-load entry with a newer `?run=1` entry for the same tab across a fresh
navigation, navigates Back/Forward between them and performs a structural
write. It fails before this change with
`Back to the older plain entry clears the policy: expected false, got true`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single CI red on 58ce6931137 — AST fuzzer (amd_debug, targeted, old_compatibility), Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-3775) — is unrelated to this PR, which only touches programs/server/play.html and its two node-driven regression tests.

It is a known plan-based parallel replicas issue with an open fix:

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109360&sha=58ce693113723a3ab6090bccb79097d5e7a03c2e&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

The AI-review blocker (sticky runnableUrl across history entries) is fixed in 88d7775c2dd, and master is merged in.

Comment thread programs/server/play.html Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 234ff3a - the build was skipped, reused from cache, or predates profile upload.

…ly exception as `persistColorModes`

A column-pin toggle takes the same `scheduleSave` -> `persist` ->
`captureActiveTab` chain as a color-mode toggle, so it can also flush a
dirty editor draft to IndexedDB and have `reconcileStartup` restore it
on reload (as editor text only, never auto-run). Name the pin toggle in
the `onQueryInput` contract comment and pin the behavior with a focused
case in `04549_play_ui_history_draft_regression`, mirroring the
color-toggle case.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ll` -> `postMulti` completion path

The delayed-completion cases of `04549_play_ui_history_draft_regression` drove
successful runs by calling `saveHistory` with an already-captured launch
snapshot, so they proved only the `saveHistory` half of the contract: a revert
of `postAll`/`postMulti` to re-read the live `query_area.value` after their
lexer preflight awaits would have passed while a multi-statement run could
again stamp an in-flight unrun draft as `run=1` and auto-execute it on reload.

Extract the real `postAll` (as `realPostAll`, so `reconcileStartup`'s startup
auto-run keeps hitting the observable stub), `postMulti`, `beginFlight`,
`endFlight`, `resolveRunParams`, `pickRunParams` and `extractRunParamNames`
into the harness, stubbing only the WASM lexer and the `postImpl` network
round-trip. The new "run all in flight" case parks the launch on a gated
`tokenize` stub — the run's FIRST preflight await — types the draft while it
is parked, then releases it, so any re-read of the live editor after an await
(at snapshot time or at completion) is caught; the clean-control case pins
that the divergence guard does not fire spuriously and the real path still
stamps `run=1`. `WebAssembly` and `extractQueryParams` are exposed in the
sandbox because `extractRunParamNames` checks the former and looks up the
latter (the callee) before awaiting `tokenize` — without them the preflight
short-circuits to its no-lexer fallback without parking on the gate.

Mutation-verified: reverting `postMulti`'s `saveHistory` call to
`query_area.value`, or `postAll`'s `postMulti` call to pass the live editor
text, fails at "run all in flight: the result snapshot holds the launched
editor text".
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status on 7a627554cda: the only red is AST fuzzer (amd_debug) — Logical error: ColumnBLOB should be converted to a regular column before usage on a merge() + LIMIT ... WITH TIES query (STID 3059-311c). This is unrelated to this HTML-only PR: it is the known marshalled-blocks issue tracked in #113165 and #111945, with the fix in #111997 (approved, not yet merged), so merging master would not clear it yet.

Pushed a5f3937e88b addressing the remaining review item: the in-flight edit hazard is now pinned through the real postAll -> postMulti completion path in 04549_play_ui_history_draft_regression.

…opstate`

A legacy title-only entry (`{tabName, query}`, written before `tabId`
existed) resolved by `resolveTabForState` stayed foreign to the tab it was
bound to: every later "is this entry the active tab's?" check keys on
`tabId`, so `refreshCurrentHistoryEntry` bailed on it and the structural
folds (`closeTab`, `switchToTab`, `addTab`, a rename) never folded the
latest unrun draft into the entry. Landing on such an entry via Back,
editing, then closing the tab and pressing Back again recreated the tab
with the stale entry query instead of the draft.

`window.onpopstate` now restamps legacy entries too: the identity-restamp
block fires when the state has no `tabId` at all, adopting the entry as
the resolved tab's (`tabId` + current title, and the URL's `tab=` key).

A regression case in 04549 lands on a legacy entry via Back, types a
draft, closes the tab and verifies the fold landed the draft in the
adopted entry and Back restores it. It fails on the previous code at
`legacy entry: the entry is adopted with the tab id`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two CI failures on a5f3937e88b are unrelated to this HTML-only PR:

Neither fix has merged into master yet, so updating the branch would not clear these.

Comment thread programs/server/play.html
/// first clause short-circuits; and after a clean Back/Forward this handler sets both `tab.query`
/// and `lastSavedQuery` to the entry query (below), so a subsequent navigation with no edit stays
/// non-dirty and keeps restoring the entry's query exactly as before.
const preserve_draft = tab.query !== event.state.query && tab.query !== tab.lastSavedQuery;

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.

preserve_draft only keeps tab.query / tab.params. window.onpopstate still rewinds the navigated entry's execution target before the editor is reactivated, so the preserved draft no longer represents the state the user actually typed.

Concrete trace I reproduced with the real extracted harness:

  1. run SELECT 1 in db1;
  2. run SELECT 2 in the same tab, so there are now two run-backed history entries;
  3. switch selected_database to db2, which rewrites only the newer entry;
  4. type an unrun draft;
  5. press Back.

The editor still shows the draft, but selected_database has already been restored from the older entry (db1), and pressing Run executes the preserved draft in db1. The same handler also restores the older url / user on a cross-connection Back, so this mixed-state problem is not limited to databases.

Please either preserve the draft's execution context together with the text, or disable preserve_draft when the target entry differs in connection / database. A focused regression with differing database= (and ideally url= / user=) between the two entries would catch this.

Comment thread programs/server/play.html
/// `tabReflectsRun` uses against `result.params`).
const params_unchanged = JSON.stringify(tab.params || {}) === JSON.stringify(stateData.params || {});
///
/// A bookkeeping artifact must not read as such an edit, though: `tab.params` can still carry

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.

I do not understand why we need so much complexity. Most likely, this PR was wasted by rounds of pointless reviews.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing this in favour of a much smaller change.

The performance complaint here is real — per keystroke, writeHistoryEntry structured-clones the whole result snapshot through history.replaceState, base64-encodes the query into the URL hash, retitles the document and rebuilds the tab bar — but the way this branch fixes it is too expensive in complexity.

Of the +534 lines in play.html, 360 are comments and 169 are code; the nominal change is about 8 of them. The rest is compensation. Per-keystroke refreshCurrentHistoryEntry was wasteful, but it made history.state an eventually-consistent mirror of the editor, at most one keystroke stale, and the rest of the file leaned on that: any transient inconsistency was repaired by the next character. Deleting the writer removes the repair mechanism too, so every remaining write site becomes the last chance to be correct and has to synchronously reconstruct what used to arrive asynchronously a moment later. That is where maskQuotedAndComments comes from — an 80-line hand-written re-implementation of src/Parsers/Lexer.cpp's quoting, heredoc and nested-comment rules, in JavaScript, which will silently drift from the real lexer.

The replacement keeps the in-memory and persisted state synced on every keystroke — including the query parameters — and moves only the browser-history and URL write off the keystroke path. Because tab.params then stays coherent with tab.query, no synchronous approximation of the lexer is needed anywhere.

Two changes here are fixes for pre-existing bugs on master, unrelated to the keystroke policy; they are being split into their own pull requests.

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 wasted Discussion went in a wrong direction

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants