Skip to content

Implement CREATE HANDLER / DROP HANDLER / ALTER HANDLER queries - #100203

Closed
Daedalus-Icarus wants to merge 13 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-100000
Closed

Daedalus-Icarus wants to merge 13 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-100000

Conversation

@Daedalus-Icarus

Copy link
Copy Markdown
Contributor

Implement CREATE HANDLER / DROP HANDLER / ALTER HANDLER queries

Add SQL-based management of custom HTTP handlers, allowing users to create, alter, and drop HTTP endpoints dynamically without editing XML configuration files.

Closes #100000

Syntax:

CREATE [IF NOT EXISTS] HANDLER name URL [PREFIX|REGEXP] '/path' [METHODS (GET, POST)] AS 'SELECT ...'
ALTER HANDLER [IF EXISTS] name [URL [PREFIX|REGEXP] '/path'] [METHODS (GET, POST)] [AS 'SELECT ...']
DROP [IF EXISTS] HANDLER name

SQL-defined handlers are persisted to disk (under handlers_metadata/) and restored on server startup. They are matched after config-defined handlers but before the default dynamic query handler, using PredefinedQueryHandler for execution. Handlers are matched lexicographically by name for deterministic ordering.

New access types: CREATE_HANDLER, ALTER_HANDLER, DROP_HANDLER.

Changelog category (leave one):

  • New Feature

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

Add CREATE HANDLER, ALTER HANDLER, and DROP HANDLER queries for SQL-based management of custom HTTP handlers, removing the need to edit XML configuration for defining HTTP endpoints.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)
  • Motivation: Currently, custom HTTP handlers in ClickHouse can only be defined via XML configuration (<http_handlers> section), requiring a config reload or server restart. This feature allows managing HTTP handlers dynamically via SQL, similar to how CREATE NAMED COLLECTION works.

  • Parameters:

    • name — Handler identifier (used for matching priority and management).
    • URL [PREFIX|REGEXP] '/path' — URL matching rule. Default is exact match. PREFIX matches path prefixes, REGEXP uses RE2 regular expressions.
    • METHODS (GET, POST, ...) — Allowed HTTP methods. Defaults to GET.
    • AS 'query' — The SQL query to execute when the handler is matched.
  • Access control: Requires CREATE_HANDLER, ALTER_HANDLER, or DROP_HANDLER grants respectively.

  • Example use:

    -- Create a handler that returns server uptime
    CREATE HANDLER my_uptime URL '/api/uptime' METHODS (GET) AS 'SELECT uptime()';
    
    -- Test it: curl http://localhost:8123/api/uptime
    
    -- Modify the handler
    ALTER HANDLER my_uptime AS 'SELECT uptime(), version()';
    
    -- Remove the handler
    DROP HANDLER my_uptime;

@Daedalus-Icarus

Daedalus-Icarus commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov @Avogar
I've done and tested locally. Could you please review this?

@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f1dba2]

Summary: ✅


AI Review

Summary

This PR introduces SQL-managed HTTP handlers via CREATE HANDLER / ALTER HANDLER / DROP HANDLER, including parser/interpreter wiring, runtime matching, persistence, access control, and tests. The implementation looks substantially complete and addresses many core risks (atomic file writes, rollback on persist failures, ambiguity checks, gate setting, and coverage for key runtime paths). I found one remaining major documentation gap: docs currently omit ON CLUSTER usage even though it is implemented.

Findings

⚠️ Majors

  • [docs/en/sql-reference/statements/create/handler.md:22] Syntax/docs do not mention ON CLUSTER support for handler DDL, but parser and interpreter paths support it (Parser*HandlerQuery + removeOnClusterClauseIfNeeded/executeDDLQueryOnCluster). This creates user-facing discoverability mismatch for distributed deployments.
    • Suggested fix: Document ON CLUSTER form for CREATE HANDLER, ALTER HANDLER, and DROP HANDLER in syntax blocks or an explicit section.
ClickHouse Rules
Item Status Notes
Deletion logging ✅
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ⚠️ Docs gap for ON CLUSTER reduces operational discoverability for cluster rollout.
Compilation time ✅
No large/binary files ✅
User-Lens

Users running multi-node setups can miss ON CLUSTER support entirely from current docs and may assume handlers are single-node-only, despite implemented distributed execution.

Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add ON CLUSTER documentation for CREATE HANDLER, ALTER HANDLER, and DROP HANDLER to align docs with implemented behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Ok. Let's test (and add automated tests whenever possible) every single statement from the spec. Just to make sure...

const auto updated_query = removeOnClusterClauseIfNeeded(query_ptr, getContext());
const auto & query = updated_query->as<const ASTCreateHandlerQuery &>();

current_context->checkAccess(AccessType::CREATE_HANDLER);

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 introduces a new SQL surface (CREATE HANDLER/ALTER HANDLER/DROP HANDLER) but there is no experimental feature gate check in the interpreters.

Per ClickHouse rollout rules, new behavior should be guarded (for example with allow_experimental_*) until it is proven safe in production. Without a gate, existing deployments cannot disable the feature after upgrade.

Please add an experimental setting check before executing these statements (and document the default).


std::string file_path = metadata_path + "/" + escapeForFileName(handler_name) + ".sql";
if (fs::exists(file_path))
fs::remove(file_path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

DROP HANDLER deletes persisted metadata files, but this deletion path does not emit a log entry.

ClickHouse requires logging deletion events (data/metadata/Keeper entries) for auditability and incident debugging. Please add at least an INFO/DEBUG log before or after fs::remove (including handler name and file path).

Comment thread src/Server/HTTPHandlerFactory.cpp Outdated
@@ -259,6 +260,9 @@ static inline auto createHandlersFactoryFromConfig(
"{}.{}, must be 'rule' or 'defaults'", prefix, key);
}

/// Add SQL-defined custom handlers after config-defined handlers
main_handler_factory->addHandler(createCustomHandlerRequestHandlerFactory(server));

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.

createHandlersFactoryFromConfig always adds createCustomHandlerRequestHandlerFactory here, but the defaults branch already calls addDefaultHandlersFactory, which now also adds the same custom factory.

When http_handlers.defaults is enabled, this registers SQL handlers twice. It is easy to miss in tests but adds duplicate matching work on every HTTP request and can alter expected precedence when combined with custom rules.

Please keep a single insertion point (either only in addDefaultHandlersFactory or only here, with a guard).


if (def.url_type == "regexp")
{
re2::RE2 regex(def.url);

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.

matchesURL recompiles RE2 patterns on every request (re2::RE2 regex(def.url)), and then createRequestHandler compiles the same pattern again for PredefinedQueryHandler.

Because this code runs on the HTTP request path, repeated regex compilation can become a visible CPU overhead under load (especially with multiple regexp handlers). It also duplicates work for every successful regexp match.

Please compile regexp patterns once when handlers are created/altered/loaded, store the compiled object in the handler definition, and reuse it here.

query->format(buf, format_settings);

std::string file_path = metadata_path + "/" + escapeForFileName(handler_name) + ".sql";
WriteBufferFromFile out(file_path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

saveToDisk writes directly to the final metadata file path. If the process is interrupted during write (exception, power loss, restart), the .sql file can be left partially written.

On startup, loadFromDisk catches parse failures and continues, so a partially written file can silently drop a handler definition after restart.

Please switch to an atomic write pattern (write to temp file in the same directory, finalize/sync, then rename to target).

def.methods.push_back("GET");

if (def.url_type == "regexp")
def.compiled_regex = std::make_shared<re2::RE2>(def.url);

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.

CREATE HANDLER/ALTER HANDLER currently accept invalid URL REGEXP patterns.

At this line, a re2::RE2 object is constructed but its validity is never checked (ok()), so malformed regexps are persisted successfully and only fail later at request match time (silently never matching). The same pattern appears in alter and loadFromDisk.

Please validate regexp compilation at definition time and throw CANNOT_COMPILE_REGEXP (or equivalent) when !compiled_regex->ok(), including the RE2 error text. That makes invalid definitions fail fast and avoids persisting broken handlers.


std::unique_ptr<HTTPRequestHandler> createRequestHandler(const HTTPServerRequest & request) override
{
auto handlers = CustomHandlersFactory::instance().getAll();

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 code runs on every HTTP request, but it copies all SQL handler definitions (getAll) and sorts them every time. With many handlers this adds avoidable allocations and O(N log N) work to the hot path.

Please consider maintaining an immutable pre-sorted snapshot (updated on create/alter/drop) and reading that snapshot here, so request handling only does a linear scan without per-request copying/sorting.

@@ -398,6 +405,9 @@ void addDefaultHandlersFactory(
{
addCommonDefaultHandlersFactory(factory, server, config);

/// Add SQL-defined custom handlers before the default dynamic query handler
factory.addHandler(createCustomHandlerRequestHandlerFactory(server));

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.

allow_experimental_sql_handlers currently gates only DDL interpreters, but SQL handlers are still loaded and activated unconditionally in the HTTP handler chain.

That means the experimental feature remains active for request execution even when the setting is 0 (default), which weakens the rollout gate semantics.

Could you gate registration/loading of SQL handlers with the same setting (or a dedicated server-level setting), so disabling the experimental feature fully disables both management and runtime matching/execution?

@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov
Could you please review this PR?

if (def.url_type == "regexp")
def.compiled_regex = std::make_shared<re2::RE2>(def.url);

handlers[query.handler_name] = std::move(def);

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.

create mutates in-memory state before persistence (saveToDisk). If disk write/rename fails, the query throws but the handler remains active in memory until restart.

That breaks atomicity: users get an exception yet behavior changed, and state after restart differs from runtime state.

Please persist first (or rollback the in-memory insertion on exception) so CREATE HANDLER is all-or-nothing.

if (it == handlers.end())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Handler `{}` does not exist", handler_name);

handlers.erase(it);

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.

remove erases the handler from memory before deleting metadata on disk. If removeFromDisk throws (I/O/permissions), DROP HANDLER fails but the handler is already gone from memory; after restart it can reappear from the leftover metadata file.

Please make this atomic: delete metadata first and erase from memory only after successful persistence, or rollback memory state on failure.

SETTINGS="--allow_experimental_sql_handlers=1"

# Basic CREATE HANDLER
$CLICKHOUSE_CLIENT $SETTINGS -q "CREATE HANDLER test_h1_${SUFFIX} URL '/api/test1_${SUFFIX}' AS 'SELECT 1'"

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 test only verifies that CREATE HANDLER/ALTER HANDLER/DROP HANDLER statements parse and execute, but never checks runtime behavior through HTTP requests. The feature’s core contract is request matching and query execution, so we should add end-to-end assertions (for exact/prefix/regexp URL matching and method filtering) by issuing HTTP calls and validating responses.

Without that, regressions in CustomHandlerRequestHandlerFactory can pass CI while DDL-only checks remain green.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1, it does not test the feature.


## Part 2: End-to-end HTTP handler tests (exact URL match)

$CLICKHOUSE_CLIENT $SETTINGS -q "CREATE HANDLER test_exact_${SUFFIX} URL '/e2e_exact_${SUFFIX}' METHODS (GET) AS 'SELECT 42 AS answer'"

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 test now covers DDL and request matching, but it still misses the persistence contract of SQL handlers (handlers_metadata restore on startup).

Please add a restart round-trip check: create handler → restart server → verify endpoint works; drop handler → restart server → verify endpoint is absent. This is the main behavior guarded by saveToDisk/loadFromDisk.

query->query = query_ast->as<ASTLiteral &>().value.safeGet<String>();
}

node = query;

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.

ALTER HANDLER currently accepts a statement with no modifications (for example, ALTER HANDLER h), because all clauses are optional and there is no post-parse validation that at least one of URL / METHODS / AS was provided.

This silently succeeds as a no-op, which can hide user mistakes and make automation think an intended change was applied.

Please reject empty alters with a clear BAD_ARGUMENTS exception when none of the optional fields is set.

def.query = *query.query;

if (!metadata_path.empty())
saveToDisk(query.handler_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.

ALTER HANDLER mutates in-memory state before persistence. If saveToDisk throws here (I/O, permissions, rename failure), the query returns an exception but the modified handler stays active in memory until restart.

That breaks atomicity and can cause restart-time behavior rollback (disk still has old definition). Please make alter all-or-nothing: either persist first and then swap state, or keep a copy and roll back in-memory fields if persistence fails.

node2.restart_clickhouse()

# Verify persistence on node1 after restart
text, code = http_get(node1, "/keeper_test_1")

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 keeper tests still validate only node_with_keeper after restart, so they can pass even if cross-node Keeper propagation is broken.

In test_keeper_create_and_restart, we create the handler on node_with_keeper, restart both nodes, then assert only on node_with_keeper (/keeper_test_1). Please also assert that node_with_keeper_2 serves the same handler (and similarly for alter/drop paths), otherwise the advertised Keeper-backed multi-node behavior is not actually covered.

@alexey-milovidov

Copy link
Copy Markdown
Member

@Desel72, please fix tests and conflicts.

Comment thread programs/server/Server.cpp Outdated
@@ -2100,6 +2101,12 @@ try
#endif

NamedCollectionFactory::instance().loadIfNot();

{
auto handlers_metadata_path = fs::path(global_context->getPath()) / "handlers_metadata/";

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.

handlers_metadata is hardcoded here, so the new <custom_handlers_storage><type>zookeeper</type>...</custom_handlers_storage> configuration from the integration setup is never read by production code.

That means CREATE/ALTER/DROP HANDLER still persist only to local disk, and the Keeper-backed multi-node behavior exercised in tests/integration/test_sql_handlers is not actually implemented by this PR.

Please wire CustomHandlersFactory initialization to custom_handlers_storage config (at least selecting local vs zookeeper backend) and keep local-disk mode as the default fallback.

@@ -0,0 +1,107 @@
#!/usr/bin/env bash

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 PR removes the existing regression test 04040_clear_column_with_projection_index (for #99388) without adding equivalent coverage.

Per ClickHouse review rules, existing tests should not be removed unless replacement coverage is provided. Dropping this test weakens protection for CLEAR COLUMN + projection rebuild behavior and can reintroduce regressions unrelated to this feature.

Please restore this test (or move it with identical assertions so it still runs).

Add SQL-based management of custom HTTP handlers, allowing users to
create, alter, and drop HTTP endpoints without editing config files.

Syntax:
  CREATE [IF NOT EXISTS] HANDLER name URL [PREFIX|REGEXP] '/path'
    [METHODS (GET, POST)] AS 'SELECT ...'
  ALTER HANDLER [IF EXISTS] name [URL ...] [METHODS ...] [AS ...]
  DROP [IF EXISTS] HANDLER name

Handlers are persisted to disk and loaded on server startup. SQL-defined
handlers are matched after config-defined handlers but before the default
dynamic query handler, using PredefinedQueryHandler for execution.

New access types: CREATE_HANDLER, ALTER_HANDLER, DROP_HANDLER.
Gated by allow_experimental_sql_handlers setting (default: false).

ALTER HANDLER is atomic: persistence happens before in-memory swap,
with rollback on I/O failure. Metadata files use atomic write-then-rename.

Includes stateless tests (DDL, end-to-end HTTP exact/prefix/regexp URL
matching, method filtering, ALTER semantics, DROP removal, experimental
setting gate) and integration tests (local-disk and keeper-based storage
with restart round-trips and cross-node propagation).

#100000

try
{
persist(query.handler_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.

create/alter/remove keep mutex locked while persisting (saveToDisk does sync + rename; saveToZooKeeper does network I/O). In parallel, each HTTP request path (CustomHandlerRequestHandlerFactory::createRequestHandler) calls getAll, which takes the same mutex.

This can serialize request matching behind slow I/O from a single DDL statement. Please consider shrinking the critical section: update in-memory state under lock, release lock, then persist with a rollback/swap strategy on failure.

Comment thread src/CMakeLists.txt
@@ -335,6 +335,7 @@ if (ENABLE_CLICKHOUSE_DISTRIBUTED_CACHE)
endif()

add_object_library(clickhouse_server Server)
add_object_library(clickhouse_server_custom_handlers Server/CustomHandlers)

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 PR is focused on SQL handler DDL/runtime, but this added object library introduces unrelated build-scope changes in src/CMakeLists.txt.

Please keep this PR scoped to handler functionality and move unrelated build-system changes (and any sanitizer-coverage adjustments) into a separate PR with dedicated motivation/validation. Mixing concerns makes review and regression attribution much harder.

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please add end user documentation.

{
if (!metadata_path.empty())
removeFromDisk(handler_name);
if (!zk_path.empty())

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.

unpersist references zk_path and removeFromZooKeeper, but neither is declared in CustomHandlersFactory.

This is a build blocker: the PR cannot compile as-is because these identifiers are undefined in this translation unit/class.

Please either remove the ZooKeeper branch for now (since fallback-to-local is used), or add the missing member/function declarations and implementation.

@Avogar

Avogar commented Mar 26, 2026

Copy link
Copy Markdown
Member

I took a look at the changes (with the help from claude), and unfortunately we cannot merge it in the current state.

Blockers

1. No-op ALTER HANDLER silently accepted

ALTER HANDLER h_name with no clauses parses and succeeds, doing nothing. There's no validation that at least one of URL / METHODS / AS is present. This makes user mistakes invisible.

Fix: after parsing optional clauses, reject if none were provided.

2. Query is not validated at creation time

The spec says: "The query is parsed for syntactic correctness during handler creation/alter, but not analyzed."

Right now the query is stored as an opaque string literal. CREATE HANDLER h URL '/x' AS 'this is not SQL at all' succeeds, and the error only surfaces when an HTTP request hits the handler. The query should be parsed (but not analyzed) at DDL time.

3. Per-request copy + sort of all handlers

In CustomHandlerRequestHandlerFactory.cpp, every HTTP request copies the entire handler map and sorts it. This is O(N log N) work on the hot path for every HTTP request, including normal queries that go through the default handler.

Fix: maintain a pre-sorted snapshot inside CustomHandlersFactory, updated only on DDL changes. Read it lock-free or under a short shared lock in the request path.

4. Runtime matching not gated by experimental setting

allow_experimental_sql_handlers only gates the DDL interpreters. Handlers loaded from disk at startup are always registered and matched on every HTTP request, even when the setting is false. If someone creates handlers and then disables the setting, the handlers remain active and matchable.

5. PredefinedQueryHandler created with empty HTTPHandlerConnectionConfig

In CustomHandlerRequestHandlerFactory.cpp, the handler is created with HTTPHandlerConnectionConfig{}. This means connection-level settings like max_query_size use defaults rather than the server's actual configuration. Config-defined handlers get their connection config from the server config — SQL-defined ones should too.

Spec gaps

6. No HTTP method validation

The spec says: "We also support POST, PUT, DELETE, but not arbitrary names." The parser accepts any identifier — METHODS (FOOBAR) would be accepted silently. Validate against the allowed set {GET, POST, PUT, DELETE}.

7. Fragment identifier # not stripped from URL

The spec says: "The URL is matched without ? query string and # fragment identifier." getRequestPath only strips ?, not #.

8. No ambiguity checking for exact URLs and prefixes

The spec says: "For exact URLs and prefixes, we should check for ambiguity at creation/alter time and throw an exception if there is ambiguity." Two handlers with the same exact URL can coexist silently.

9. Missing features from the spec

These are probably fine to defer to follow-up PRs, but worth noting:

  • PROTOCOL clause
  • TYPE query clause
  • currentHandler() and currentRequestURL() functions
  • query_log fields for handler name and HTTP request URL

Code quality

10. Magic strings for url_type

The strings "exact", "prefix", "regexp" are used as string comparisons across multiple files (ASTs, factory, request handler). An enum would prevent typos and enable compiler checking.

11. Dead code

  • global_context is stored in CustomHandlersFactory::loadFromConfig but never used.
  • shutdown() has an empty body and is never called.

Docs

12. Grant syntax in docs uses underscores

The docs show GRANT CREATE_HANDLER, but the access types are registered as CREATE HANDLER (with a space). The example should be:

GRANT CREATE HANDLER, ALTER HANDLER, DROP HANDLER ON *.* TO my_user;

Tests

13. Missing test coverage

  • No test for ALTER HANDLER with no clauses (the no-op bug).
  • No test for invalid method names.
  • No test for duplicate exact URL ambiguity.
  • No test for ON CLUSTER behavior (parsers and interpreters support it, but there are no tests).
  • Integration test assertions are weak — patterns like assert code != 200 or "42" not in _ accept multiple failure modes without verifying the specific expected behavior.

…or SQL handlers

- Reject no-op `ALTER HANDLER` with no URL/METHODS/AS clause
- Validate query syntax at DDL time using `ParserQuery` (parse, not analyze)
- Validate HTTP methods against allowed set {GET, POST, PUT, DELETE}
- Check for URL ambiguity at CREATE/ALTER time (exact and prefix overlaps)
- Replace per-request copy+sort with pre-sorted snapshot (`shared_mutex`)
- Gate runtime handler matching by `allow_experimental_sql_handlers` setting
- Strip `#` fragment identifier from URL in `getRequestPath`
- Replace magic url_type strings with `HandlerURLType` enum
- Remove dead code (`global_context` member, empty `shutdown`)
- Fix grant syntax in docs (underscores to spaces)
- Strengthen test assertions and add coverage for new validations

if (def.url_type == HandlerURLType::Exact && existing.url_type == HandlerURLType::Exact)
urls_conflict = (def.url == existing.url);
else if (def.url_type == HandlerURLType::Prefix && existing.url_type == HandlerURLType::Prefix)

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.

checkAmbiguity handles Exact/Prefix overlap, but for Prefix/Prefix it only treats equal strings as conflicting. With prefix matching semantics (startsWith), handlers like /api and /api/v1 with overlapping methods are still ambiguous, and one silently shadows the other by name order.

Please treat nested prefixes as conflicts too (e.g. def.url.starts_with(existing.url) || existing.url.starts_with(def.url)), consistent with the Exact/Prefix branch.

const auto updated_query = removeOnClusterClauseIfNeeded(query_ptr, getContext());
const auto & query = updated_query->as<const ASTCreateHandlerQuery &>();

current_context->checkAccess(AccessType::CREATE_HANDLER);

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.

⚠️ CREATE_HANDLER/ALTER_HANDLER/DROP_HANDLER checks were added here, but this PR still lacks coverage that these grants are actually enforced (GRANT, REVOKE, and denied execution paths).

Please add a stateless test that creates a user without these grants, verifies each statement fails with access denied, then grants each privilege and verifies success.


current_context->checkAccess(AccessType::CREATE_HANDLER);

if (!query.cluster.empty())

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.

⚠️ These statements now support ON CLUSTER, but I don’t see tests covering distributed execution semantics.

Please add integration coverage for CREATE HANDLER/ALTER HANDLER/DROP HANDLER with ON CLUSTER on a multi-node cluster, including success paths and IF EXISTS/IF NOT EXISTS behavior.

…equest path

The setting is session-level and not available in the HTTP request handler
context (which has no session). Gate DDL only, consistent with how other
experimental features work: once created, handlers serve requests; use
`DROP HANDLER` to deactivate.
/// Validate that each method in the list is one of the allowed HTTP methods.
static void validateMethods(const std::vector<std::string> & methods)
{
static const std::unordered_set<std::string> allowed_methods = {"GET", "POST", "PUT", "DELETE"};

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.

METHODS values are validated case-sensitively here ("GET", "POST", ...), but request matching later is case-insensitive via Poco::icompare.

As a result, CREATE HANDLER ... METHODS (get) is rejected with BAD_ARGUMENTS even though the runtime path treats method names case-insensitively. This is a user-visible inconsistency.

Please normalize methods before validation (for example, convert to uppercase once in parser/factory), then keep runtime matching as-is. Also add coverage for lowercase/mixed-case methods in both CREATE HANDLER and ALTER HANDLER.

@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov If you have some free time, could you please review this PR?

@Avogar Avogar self-assigned this Mar 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

/// Fall back to local storage so the server starts normally.
LOG_WARNING(log, "ZooKeeper-based storage for SQL handlers is not yet implemented, falling back to local storage");

metadata_path = fs::path(context->getPath()) / "handlers_metadata/";

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.

When custom_handlers_storage.type is zookeeper/keeper, the fallback-to-local branch hardcodes metadata_path to <path>/handlers_metadata/ and ignores custom_handlers_storage.path. That means a user-provided path is silently discarded, and handlers are persisted/restored from an unexpected directory.

Please reuse the same path resolution as the local branch (respect custom_handlers_storage.path when present) even in fallback mode.

@alexey-milovidov

Copy link
Copy Markdown
Member

The flaky test failures in this PR (01605_drop_settings_profile_while_assigned, 01418_custom_settings, 02015_async_inserts_4) are caused by non-unique access entity names and will be resolved by #102131.

@alexey-milovidov

Copy link
Copy Markdown
Member

The flaky check failure is fixed in #102148, let's update the branch.

@@ -0,0 +1,122 @@
---

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 new docs page frontmatter is missing sidebar_position. For new files under docs/, we require full frontmatter fields (description, sidebar_label, sidebar_position, slug, title, doc_type) so navigation ordering is explicit and stable.

Please add sidebar_position to this file.

bool matchesMethod(const CustomHandlerDefinition & def, const std::string & method)
{
if (def.methods.empty())
return method == Poco::Net::HTTPRequest::HTTP_GET;

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.

METHODS handling currently treats GET as GET only, so HEAD requests do not match handlers created with default methods (or explicit METHODS (GET)).

In ClickHouse HTTP handlers, GET endpoints generally also accept HEAD (e.g. via allowGetAndHeadRequest). With the current logic, clients relying on HEAD for health checks or metadata probes will get unexpected misses for SQL handlers.

Please either:

  1. treat HEAD as equivalent to GET in matchesMethod, or
  2. support HEAD in parser/validation/docs and include it in defaults.

fm4v added a commit that referenced this pull request Apr 14, 2026
Split flaky check and targeted check into separate roles:

Flaky check — runs only new/modified tests from the PR with thread
fuzzer enabled. Tests run in parallel with themselves (shared queue)
to ensure new tests are parallel-safe under randomized thread ordering.

Targeted check — runs previously failed and coverage-relevant tests
with per-worker partitioning (--no-self-parallel) so the same test
never runs concurrently on multiple workers, avoiding conflicts on
shared resources (hardcoded users, roles, settings profiles, etc.).
Both use --test-runs 50.

Changes:
- Add --no-self-parallel flag to clickhouse-test: partitions tests
  by name hash so all copies go to the same worker
- Flaky check: only changed tests, thread fuzzer, shared queue
- Targeted check: relevant tests, no thread fuzzer, per-worker queues,
  50 runs, single clickhouse-test invocation
- Restore original thread fuzzer parameters (reverts reductions from
  06c945a and 9790435)
- Add amd_binary to flaky check, use AMD_LARGE for targeted debug
- Targeted check uses --flaky-check --no-self-parallel

PRs affected by tests running in parallel with themselves:
#102015 #101093 #99653 #101503 #101108 #101884 #100746
#101447 #100941 #101099 #100203 #96130

#102038
fm4v added a commit that referenced this pull request Apr 14, 2026
Split flaky check and targeted check into separate roles:

Flaky check — runs only new/modified tests from the PR with thread
fuzzer enabled. Tests can run in parallel with themselves (shared
queue) to ensure new tests are parallel-safe.

Targeted check — runs previously failed and coverage-relevant tests
with per-worker partitioning (--no-self-parallel) so the same test
never runs concurrently on multiple workers, avoiding conflicts on
shared resources (hardcoded users, roles, settings profiles, etc.).
Both use --test-runs 50.

Changes:
- Add --no-self-parallel flag to clickhouse-test: partitions tests
  by name hash so all copies go to the same worker
- Flaky check: only changed tests, thread fuzzer, shared queue
- Targeted check: relevant tests, no thread fuzzer, per-worker
  partitioning, 50 runs, single clickhouse-test invocation
- Restore original thread fuzzer parameters
- Change targeted check to arm_asan_ubsan on ARM_LARGE

PRs affected by tests running in parallel with themselves:
#102015 #101093 #99653 #101503 #101108 #101884 #100746
#101447 #100941 #101099 #100203 #96130
**Syntax**

```sql
CREATE [IF NOT EXISTS] HANDLER name URL [PREFIX|REGEXP] '/path' [METHODS (GET, POST, ...)] AS 'query'

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.

CREATE HANDLER/ALTER HANDLER/DROP HANDLER support ON CLUSTER in parser/interpreter code, but this syntax block omits it. Please document the ON CLUSTER variants (or a dedicated note) for all three statements so users can discover distributed usage from docs.

@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 79.00% (508/643) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Split flaky check and targeted check into separate roles:

Flaky check — runs only new/modified tests from the PR with thread
fuzzer enabled. Tests run in parallel with themselves (shared queue)
to ensure new tests are parallel-safe under randomized thread ordering.

Targeted check — runs previously failed and coverage-relevant tests
with per-worker partitioning (--no-self-parallel) so the same test
never runs concurrently on multiple workers, avoiding conflicts on
shared resources (hardcoded users, roles, settings profiles, etc.).
Both use --test-runs 50.

Changes:
- Add --no-self-parallel flag to clickhouse-test: partitions tests
  by name hash so all copies go to the same worker
- Flaky check: only changed tests, thread fuzzer, shared queue
- Targeted check: relevant tests, no thread fuzzer, per-worker queues,
  50 runs, single clickhouse-test invocation
- Restore original thread fuzzer parameters (reverts reductions from
  06c945a and 9790435)
- Add amd_binary to flaky check, use AMD_LARGE for targeted debug
- Targeted check uses --flaky-check --no-self-parallel

PRs affected by tests running in parallel with themselves:
ClickHouse#102015 ClickHouse#101093 ClickHouse#99653 ClickHouse#101503 ClickHouse#101108 ClickHouse#101884 ClickHouse#100746
ClickHouse#101447 ClickHouse#100941 ClickHouse#101099 ClickHouse#100203 ClickHouse#96130

ClickHouse#102038
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement CREATE HANDLER query

4 participants