Skip to content

Implement CREATE HANDLER: SQL-defined HTTP handlers - #106231

Merged
alexey-milovidov merged 139 commits into
masterfrom
create-handler-100000
Aug 14, 2026
Merged

alexey-milovidov merged 139 commits into
masterfrom
create-handler-100000

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Implements #100000: create and manage custom HTTP handlers from SQL, without editing the server configuration file.

New SQL statements:

  • CREATE HANDLER [IF NOT EXISTS] name [PROTOCOL p] URL [PREFIX|REGEXP] '/x' [METHODS (GET, POST)] [TYPE query] AS <query>
  • ALTER HANDLER name ... — partial update of any subset of clauses
  • DROP [IF EXISTS] HANDLER name

Handlers are matched after configuration-defined handlers, in the lexicographical order of their names. The URL is matched without the ? query string and # fragment; exact/prefix URLs are checked for ambiguity at create/alter time. The query is parsed (not analyzed) at creation, can be parameterized (URL params, form variables, headers, and named regexp capture groups), and an INSERT handler reads its data from the HTTP body.

Handlers are persisted in a local or Keeper storage, mirroring named collections, configured via the query_rules_storage config section, and kept in sync across replicas.

Access control adds CREATE HANDLER, ALTER HANDLER and DROP HANDLER grants. Introspection adds the currentHandler and currentRequestURL functions, the http_handler_name and http_request_url columns in system.query_log, and the system.handlers table.

Changelog category (leave one):

  • New Feature

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

Added CREATE HANDLER, ALTER HANDLER and DROP HANDLER statements to define custom HTTP handlers from SQL, persisted in a local or Keeper storage. Added the currentHandler and currentRequestURL functions, the system.handlers table, and the http_handler_name / http_request_url columns in system.query_log.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Add the ability to create and manage custom HTTP handlers from SQL,
without editing the server configuration file, as requested in #100000.

New SQL statements:
- `CREATE [IF NOT EXISTS] HANDLER name [PROTOCOL p] URL [PREFIX|REGEXP] '/x'
  [METHODS (GET, POST)] [TYPE query] AS <query>`
- `ALTER HANDLER name ...` (partial update of any subset of clauses)
- `DROP [IF EXISTS] HANDLER name`

Handlers are matched after configuration-defined handlers, in the
lexicographical order of their names. The URL is matched without the
`?` query string and `#` fragment. Exact/prefix URLs are checked for
ambiguity at create/alter time. The query is parsed but not analyzed at
creation, can be parameterized (URL params, form variables, headers, and
named regexp capture groups), and an `INSERT` handler reads its data from
the HTTP body.

Handlers are persisted in a local or Keeper storage, mirroring named
collections, configured via the `query_rules_storage` config section, and
kept in sync across replicas.

Access control: `CREATE HANDLER`, `ALTER HANDLER` and `DROP HANDLER` grants.

Introspection:
- new `currentHandler` and `currentRequestURL` functions
- new `http_handler_name` and `http_request_url` columns in `system.query_log`
- new `system.handlers` table

The query-parameter substitution visitor preserves the placeholders in a
handler's query (its parameterizable interface), like parameterized views.

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

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18857c1]

Summary: ✅


AI Review

Summary

This PR adds SQL-defined HTTP handlers (CREATE / ALTER / DROP HANDLER), their replicated/local metadata storage, HTTP routing/execution, and introspection surfaces such as currentHandler, currentRequestURL, system.handlers, and query-log fields. The feature is close, but I do not think it is ready to merge yet: one previously reported runtime contract is still not actually fixed, and the remaining absence of an experimental gate is still a material ClickHouse rollout-risk issue.

Findings

⚠️ Majors

  • [src/Server/HTTPHandler.cpp:270-271,347] The deep-handler invocation fix is still caller-overridable. HTTPHandler::processQuery sets max_parser_depth / max_parser_backtracks to 0 for SQL-defined handlers, but then the normal request-parameter settings path reapplies any caller-supplied max_parser_depth / max_parser_backtracks before executeQuery reparses the stored handler SQL. That means a handler created from a deep query is still not reliably invokable once the request carries those settings, despite the resolved thread and the docs/test comments now claiming invocation uses unlimited parser limits. The fix needs to happen after request settings are applied, or those two settings need to be ignored on the stored-handler reparse path.

  • [src/Interpreters/InterpreterCreateHandlerQuery.cpp:21] [dismissed by author -- https://github.com/Implement CREATE HANDLER: SQL-defined HTTP handlers #106231#discussion_r3441526129] This feature still ships without an experimental gate. CREATE HANDLER introduces persistent, optionally Keeper-replicated HTTP routing plus stored SQL execution on externally reachable endpoints; that is exactly the kind of new server behavior the ClickHouse experimental-gate rule is meant to quarantine until it hardens. I still consider the missing allow_experimental_* setting a real rollout risk, not just a preference.

Tests

⚠️ Add a focused regression that invokes a deep SQL-defined handler with request-supplied max_parser_depth / max_parser_backtracks (for example ...?max_parser_depth=10) and proves the stored handler query still executes. The current 04844_handler_deep_query_invocation only covers lowered session defaults, not the still-reachable request-setting override.

Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 81.20% 86.70% +5.50%
Functions 91.40% 92.00% +0.60%
Branches 73.10% 79.00% +5.90%

Changed lines: Changed C/C++ lines covered: 1066/1426 (74.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 1, 2026
Expand the stateless tests to cover every statement of the spec:
- parser/registry (04303): mandatory URL, syntactic validation at create time,
  parentheses around the query, arbitrary queries (SHOW), FORMAT belonging to
  the query, all four HTTP methods, overlapping regexp handlers (no ambiguity),
  ALTER into ambiguity, and the existing exact/prefix/regexp/type/ambiguity cases.
- HTTP (04304): currentHandler branching, custom HTTP response headers via the
  query SETTINGS, HTTP headers used as usual (X-ClickHouse-Database), lexicographic
  matching order, authentication via request credentials, invoking needs no grant,
  query grants checked during invocation, SQL SECURITY DEFINER view access, and
  separate CREATE/ALTER/DROP HANDLER grants.

Add an integration test (test_create_handler) for behaviors that need special
server setups: local-storage persistence across restart, configuration-defined
handler priority over SQL-defined handlers, composable PROTOCOL scoping, ON CLUSTER,
and Keeper-storage replication across nodes.

Fix: the Keeper-backed handler storage was missing the
`Coordination::setCurrentComponent` guards that every ZooKeeper operation requires,
which made Keeper-stored handlers fail at startup with a LOGICAL_ERROR. Found by
the new integration test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Resolved
CI style fixes:
- Remove the unused `LOGICAL_ERROR` error code from SQLDefinedHandlerFromAST.cpp.
- 04304: target `SYSTEM FLUSH LOGS query_log`, add a `current_database = currentDatabase()`
  condition and a retry loop around the query_log check.

Review feedback:
- Do not persist sensitive request parameters: `system.query_log.http_request_url` now stores
  the request path only (query string and fragment stripped). `currentRequestURL()` still
  returns the full URL at runtime.
- Keeper storage: ALTER only changes a child's data, which a children-list watch does not
  observe, so other replicas could serve stale definitions. Bump a version on the root node on
  every create/drop/alter and watch the root node's data, so all changes propagate.
- Keeper storage: ALTER now uses `set` instead of create-or-update, so a delayed ALTER cannot
  resurrect a handler that was concurrently dropped; `ZNONODE` maps to HANDLER_DOESNT_EXIST.
- Keep the idempotent contract under replicated storage: `CREATE HANDLER IF NOT EXISTS` swallows
  a concurrent `HANDLER_ALREADY_EXISTS`, and `DROP HANDLER [IF EXISTS]` uses `removeIfExists`.
- Docs: narrow the documented parameter sources to what is implemented (URL query parameters and
  named URL REGEXP captures; standard ClickHouse HTTP headers), add the missing system-table
  frontmatter, and document the path-only query_log column.

Tests:
- Integration: verify ALTER HANDLER propagates across Keeper-backed replicas.
- 04304: assert the query_log URL is the path only (query string not persisted).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits June 3, 2026 04:42
After merging master, the test numbers 04303 and 04304 collided with
newly added tests. Renumber to 04305 (`04305_create_handler_basic`) and
04306 (`04306_create_handler_http`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In `SQLDefinedHandlersFactory::updateFromSQL`, the old handler was erased
from `loaded_handlers` before persisting, and restored only when
`checkAmbiguity` threw. If `store` threw instead (for example Keeper
returns an error or loses the connection, or the local metadata write
fails), `loaded_handlers` was left missing the entry while it still
exists in storage, corrupting the local registry for subsequent
`ALTER HANDLER` / `DROP HANDLER` calls.

Move `store` inside the recovery scope so the old handler is restored on
any failure of the check or the write.

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

Copy link
Copy Markdown
Member Author

Picked this up via /continue-pr.

Merged master (branch was 313 behind + red CI → merge rule). Zero conflicts; this picks up the noexcept-public fix (#106096) and the rest of the chronic-flake fixes, so the remaining CI reds are unrelated:

  • Server died (multiple shards) — chronic flake across master, not this PR.
  • AST fuzzer Logical error: Column identifier A is already registered (STID 4697-4326) — backtrace is MutationsInterpreter / updateLightweight / InterpreterUpdateQuery, unrelated to handlers; chronic on master.

Renumbered tests to avoid collisions introduced by master: 04303_create_handler_basic → 04305, 04304_create_handler_http → 04306.

Fixed bot review thread (SQLDefinedHandlersFactory.cpp:220) — ALTER HANDLER could leave loaded_handlers corrupted (missing an entry that still exists in storage) if the persistent store threw. Moved store inside the recovery scope so the old handler is restored on any failure. Resolved that thread.

Verified on a fresh debug build (built clean from the merged branch): 04305_create_handler_basic matches its reference, and 04306_create_handler_http matches once CLICKHOUSE_CLIENT carries --database (confirmed system.query_log records http_handler_name and the query-string-stripped http_request_url).

Deferred to you — three remaining bot threads are design decisions on this new feature, not mechanical fixes:

  1. SQLDefinedHandlersFactory.cpp (ambiguity check) — exact/prefix ambiguity is only validated against the local snapshot before the Keeper write, so two replicas can concurrently create overlapping handlers. Making it globally serialized (Keeper lock / versioned txn) is a distributed-design call.
  2. StorageSystemHandlers.cpp:68 — system.handlers exposes every query/create_query with no handler-specific access check or secret hiding. Giving it a system.named_collections-style contract (a SHOW HANDLER-type privilege + secret-aware formatting) is a meaningful access-control design addition.
  3. SQLDefinedHandlersMetadataStorage.cpp:269 — the child-znode mutation and the bumpVersion notification are not atomic; folding them into a single Keeper multi-op (or deriving reloads from a value committed in the same mutation) is a Keeper-storage design call.

Left these for your call rather than guessing at the intended semantics.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

The Keeper child mutation (`create`/`set`/`remove`) and the root-version bump
that notifies replicas were issued as two separate requests. A connection loss
between them could commit the handler change while leaving the watched root
version unchanged, so other replicas would keep serving a stale set of handlers
until an unrelated change bumped the version.

Issue both in a single `multi` transaction via `bumpVersionRequest`, so the
watched root version always advances together with the change (or not at all).
This also makes the `IF EXISTS` drop a clean atomic no-op: if the node is
absent, the whole transaction is rejected and nothing changes.

Addresses review feedback on SQLDefinedHandlersMetadataStorage.
With Keeper-backed handler storage, handlers are synchronized across replicas
automatically, so an `ON CLUSTER` clause is redundant: fanning out a non-`IF
NOT EXISTS` `CREATE HANDLER` makes the second host fail with
`HANDLER_ALREADY_EXISTS`, diverging from the unreplicated behavior.

Add the `ignore_on_cluster_for_replicated_handler_queries` setting (mirroring
`ignore_on_cluster_for_replicated_named_collections_queries`) and a
`SQLDefinedHandlersFactory::isReplicated` query, and teach
`removeOnClusterClauseIfNeeded` to strip `ON CLUSTER` from `CREATE`, `ALTER`
and `DROP HANDLER` when the setting is enabled and the storage is replicated.

Also fix the `DROP HANDLER` syntax in the docs: the parser consumes `IF EXISTS`
after `HANDLER` (`DROP HANDLER [IF EXISTS] name`), matching `DROP NAMED
COLLECTION`, so the previously documented `DROP [IF EXISTS] HANDLER name` failed
to parse. Document the new setting and add an integration test.

Addresses review feedback on InterpreterCreateHandlerQuery and the docs.
Handlers are a global, server-wide namespace, and 04305 uses fixed handler
names. The flaky check runs several copies of the same test concurrently
(`--test-runs N --jobs M`), so a `DROP HANDLER IF EXISTS` in one copy removes a
handler another copy is about to drop, surfacing as

    Code: 1009. Cannot drop handler `h04305_b`, because it doesn't exist. (HANDLER_DOESNT_EXIST)

and, once `--max-failures` aborts the run, a hung in-flight HTTP request in the
sibling 04306 test reported as "Server died". Tag the test `no-parallel`, the
same way named collection tests (also a global namespace) are tagged.

CI report: #106231
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Continued work on this PR: merged latest master, addressed three review threads, and fixed the flaky-check failure.

Fixed the "Server died" flaky-check failure. The flaky check runs each new test ~50× with --jobs 8, i.e. several concurrent copies of the same test. Handlers are a global, server-wide namespace, and 04305_create_handler_basic uses fixed handler names, so a DROP HANDLER IF EXISTS h04305_b in one copy removes a handler another copy was about to DROP, producing Cannot drop handler 'h04305_b', because it doesn't exist (HANDLER_DOESNT_EXIST); once --max-failures aborted the run, the sibling 04306 HTTP test's in-flight request hung and was reported as "Server died". Tagged 04305 no-parallel, the same way named-collection tests (also a global namespace) are tagged. 04306 already uses ${CLICKHOUSE_DATABASE}-scoped names and stays parallel.

Review threads addressed (resolved):

  • Keeper metadata mutation + version bump are now a single multi transaction (bumpVersionRequest) — no more divergence between a committed change and an unbumped root version on connection loss.
  • CREATE/ALTER/DROP HANDLER ... ON CLUSTER now honors a new ignore_on_cluster_for_replicated_handler_queries setting (mirroring named collections), so Keeper-backed handlers aren't double-created across the cluster. New test_ignore_on_cluster_for_replicated_storage integration test.
  • Fixed the DROP HANDLER [IF EXISTS] name syntax in the docs.

Left open as design decisions (replied inline, not resolved):

  • system.handlers exposes query/create_query without a SHOW HANDLERS-style grant or secret masking — should mirror system.named_collections (needs a new access type + secret-aware formatting).
  • Cross-replica checkAmbiguity race — two replicas can concurrently create overlapping handlers; closing it needs global serialization on the replicated path.

Unrelated CI failure: test_refreshable_mat_view_replicated::test_circular_dependencies_survive_restart is a known flaky tracked in #106651.

CI report: #106231

…y` parameter

There is a single, non-rewindable HTTP request body. Binding `_request_body`
drains it in `PredefinedQueryHandler::customizeContext` before
`HTTPHandler::processQuery` builds the query's input pipeline, so a handler
whose query also takes the body as its own input data (a plain `INSERT`, or
an `INSERT ... SELECT` reading from `input`) would find the stream at EOF
and silently insert nothing. Reject such a handler at `CREATE`/`ALTER` time
with `BAD_ARGUMENTS` instead of creating one that discards every upload.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status 2026-08-13:

  • AI Blocker fixed (18857c19d683): a handler can no longer be created (or altered) with a query that both takes the HTTP request body as its own input data (a plain INSERT, or INSERT ... SELECT reading from input) and uses the _request_body parameter — binding _request_body drains the single body stream before the query's input pipeline is built, so the upload was silently lost. Such handlers are now rejected with BAD_ARGUMENTS. New test 04871_handler_request_body_parameter_conflict (verified to fail without the fix); docs updated. Thread resolved.
  • Merged master (1de993454b53, conflict-free): pulls in the Revert the PromQL topk/limitk streaming plan and its shared-subquery materialization #114326 revert, which fixes the fleet-wide stress hung-check storm — both Stress test (amd_msan) / (arm_msan) hung checks on aad98388 show its exact signature (DROP TABLE prometheus stuck in waitTableFinallyDropped under StorageTimeSeries::dropInnerTableIfAny), unrelated to this PR.
  • Stress test (arm_debug) Logical error: Coordination mode mismatch for stream A: got B, expected C (STID 6117-726a): 16 failures across 16 distinct PRs in 21 days, tracked by Logical error: Coordination mode mismatch for stream A: got B, expected C (STID: 6117-68e9) #106039 — unrelated.
  • Integration tests (arm_binary, distributed plan, 1/4) test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write: 86 failures across 74 PRs (incl. master) in 21 days — known NATS JetStream reconnect flake; fix in progress in Recover a NATS JetStream subscription closed by the broker #112828 — unrelated.

All 27 handler stateless tests pass locally on the new head (two excluded as scratch-env-only: 03354 needs /var/lib/clickhouse/user_files, 03642 needs system.text_log). The remaining ⚠️ Major (experimental-setting gate) stays as previously dismissed by the author.

Comment thread src/Functions/currentRequestURL.cpp Resolved

@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.

The implementation is pretty straightforward and pedantic. Very good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 14, 2026
Merged via the queue into master with commit 9bd8657 Aug 14, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the create-handler-100000 branch August 14, 2026 04:29
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
Blargian added a commit to Blargian/ClickHouse that referenced this pull request Aug 26, 2026
Treat additions and modifications under `docs/en` as unpublished documentation, while allowing cleanup deletions.

Related: ClickHouse#106231
Blargian added a commit to Blargian/ClickHouse that referenced this pull request Aug 26, 2026
Register `CREATE HANDLER` in `StatementFactory`, keep the full reference body in the parser registration, and mark the Mintlify page as generated through `system.documentation`.

Related: ClickHouse#115609

Related: ClickHouse#106231
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

The fix for the Stress test (amd_tsan, meta in keeper) logical error you asked me to investigate here is #117793.

On 2026-07-31 I said I would rather not open one, because the private artifact was unreachable and the message phrase had zero CIDB hits, so I could not see the failure. That changed: it surfaced publicly in Upgrade check (amd_release) on an unrelated PR, and the window turned out to be reachable on the public tree, so the fix is measured rather than speculative. A non-transactional DROP PARTITION makes its empty covering part durable before addNewPartAndRemoveCovered stores the covered parts removal TID; an abrupt stop between those two writes leaves an Outdated part with a committed creation CSN and no removal TID, preparePartForRemoval rejects that pair, and startup then terminates on every later start.

The keeper-backend rollback inconsistency I flagged in that same comment is a different shape and is not what #117793 addresses.

This branch was successfully deployed

1 active deployment
staging - docs — 18857c19 Deployed Aug 13, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants