Skip to content

Support SYSTEM START/STOP LISTEN in clickhouse-local - #101143

Merged
alexey-milovidov merged 86 commits into
masterfrom
local-server-system-listen
Jun 22, 2026
Merged

alexey-milovidov merged 86 commits into
masterfrom
local-server-system-listen

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

Allow clickhouse-local to be transformed into a server by executing
SYSTEM START LISTEN TCP or SYSTEM START LISTEN HTTP.

This makes LocalServer implement the IServer interface and register
start/stop server callbacks on the global context. Default ports
(tcp_port=9000, http_port=8123) are preconfigured so the commands
work without explicit port configuration.

Example usage:

-- In clickhouse-local interactive mode:
SYSTEM START LISTEN TCP;   -- Now accepting native protocol connections on port 9000
SYSTEM START LISTEN HTTP;  -- Now accepting HTTP connections on port 8123
SYSTEM STOP LISTEN TCP;    -- Stop accepting TCP connections

Changelog category (leave one):

  • New Feature

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

clickhouse-local now supports SYSTEM START LISTEN and SYSTEM STOP LISTEN queries, allowing it to be transformed into a server accepting TCP and HTTP connections.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

clickhouse-local can now start listening for TCP (native protocol) and HTTP connections via SYSTEM START LISTEN TCP and SYSTEM START LISTEN HTTP. Default ports are tcp_port=9000 and http_port=8123. Custom ports can be specified via --tcp_port and --http_port command-line options.


Note

Cursor Bugbot is generating a summary for commit b7ccd7d. Configure here.

Version info

  • Merged into: 26.6.1.1132

Allow `clickhouse-local` to be transformed into a server by executing
`SYSTEM START LISTEN TCP` or `SYSTEM START LISTEN HTTP`. This makes
`clickhouse-local` implement the `IServer` interface and register
start/stop server callbacks on the global context.

Default ports (`tcp_port=9000`, `http_port=8123`) are preconfigured
so the commands work without explicit port configuration.

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

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aaffd6b]

Summary: ✅


AI Review

Summary

This PR adds SYSTEM START/STOP LISTEN support to clickhouse-local for TCP and HTTP, refactors shared listener helpers, publishes listener ports safely for runtime getServerPort, documents the security/session behavior, and adds focused stateless coverage for listener lifecycle, port validation, grouped types, and rollback. After reading the current diff and prior review threads, I did not find remaining blockers or major issues; the previously open bot comments on the port-range tests are fixed in the current code and were resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 30, 2026
Comment thread programs/local/LocalServer.cpp Resolved
Comment thread programs/local/LocalServer.cpp Resolved
alexey-milovidov and others added 2 commits March 30, 2026 02:09
… improve test

- Extract `stopServers` and `socketBindListen` into shared utilities
  in `src/Server/` so both `Server.cpp` and `LocalServer.cpp` reuse
  the same implementation instead of duplicating it.
- Fix style check: `asynchronous_heavy_metrics_update_period_s` type
  should be `ServerSettingsUInt32`, not `ServerSettingsUInt64`.
- Add post-condition check in `LocalServer::startServers` that at least
  one listener was actually created, throwing on total bind failure
  instead of silently returning success.
- Update test `03564_clickhouse_local_system_queries` to reflect that
  `SYSTEM START/STOP LISTEN` is now supported in `clickhouse-local`.
- Improve test `04068_local_system_start_stop_listen` to verify the
  HTTP listener is actually reachable via the `url` table function,
  use random ports to avoid conflicts, and add `no-fasttest` tag.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
alexey-milovidov and others added 2 commits March 30, 2026 03:45
- Fix mismatched-tags warning: forward-declare `ServerSettings` as
  `struct` (not `class`) in `socketBindListen.h`
- Set `is_cancelled = true` before stopping listeners in
  `LocalServer::cleanup` so that active `TCPHandler` connections exit
  promptly instead of waiting for socket timeout
- Add documentation for SYSTEM START/STOP LISTEN in clickhouse-local
- Rename test to 04070 to avoid collision with master

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
Fix the `03564_clickhouse_local_system_queries` test failing in CI
because default ports (8123, 9000) are already in use by the running
ClickHouse server. Use port 0 (OS-assigned) for `SYSTEM START LISTEN`
tests.

Add a connectivity check that verifies the started TCP listener is
actually reachable by connecting from `clickhouse-client`.

Improve `LocalServer::cleanup` shutdown sequence to mirror Server.cpp:
- Wait for active connections to drain via `waitServersToFinish`
- Join the server thread pool before destroying context
- Clear server list only after pool is joined

This prevents use-after-free when handlers are still running while
context is being torn down.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits April 6, 2026 17:54
- Extract common `createServer` logic from `Server::createServer` into a
  shared free function in `src/Server/createServer.h/.cpp`, reused by both
  `Server.cpp` and `LocalServer.cpp`. This eliminates the duplicated
  `create_server` lambda.

- Add `--listen_host`, `--tcp_port`, `--http_port` command-line options
  to `clickhouse-local` so tests can configure ports without relying on
  config files.

- Fix test 03564: replace fragile `lsof`-based port discovery with
  direct `clickhouse-client` connection retry loop, use a specific port
  instead of port 0, fix `sleepEachRow` exceeding the per-block sleep
  limit, and `exit 1` on connection failure.

- Remove unnecessary `no-fasttest` tag from test 04070.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
alexey-milovidov and others added 2 commits April 12, 2026 13:07
…`, add negative test

- Register the actual bound port via `portNumber()` instead of the configured
  value from `config.getInt(port_name)`. This fixes `--tcp_port 0` / `--http_port 0`
  where the OS assigns an ephemeral port but `registerServerPort` recorded 0.
  Applied to both `LocalServer` and `Server`.

- Remove the now-unused `ErrorCodes::NETWORK_ERROR` declaration from Server.cpp
  (moved to `createServer.cpp` in a previous commit).

- Add a negative test case to 03564: `SYSTEM START LISTEN TCP` with an
  unreachable `listen_host` (192.0.2.1) must throw `NETWORK_ERROR`, not
  silently succeed.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
- Treat repeated `SYSTEM START LISTEN TCP`/`HTTP` as a no-op when a
  matching listener is already active, mirroring `clickhouse-server`
  behavior. Previously the unconditional `servers.size() == servers_before`
  check threw `NETWORK_ERROR` even though the listener was running.

- Make `03564_clickhouse_local_system_queries` more reliable by binding
  to OS-assigned port 0 and reading the actual port via `getServerPort`
  from `clickhouse-local` stdout, instead of guessing a random port that
  could collide with parallel CI tests. Capture stderr to a temp file
  so future failures are debuggable.
…local

Covers the invariant enforced by the previous commit: repeating
`SYSTEM START LISTEN TCP`/`HTTP` in the same `clickhouse-local` session
returns without throwing when a matching listener is already active,
matching `clickhouse-server` behavior.
The test previously chose `--tcp_port`/`--http_port` via shell `RANDOM`,
which can collide with parallel CI jobs and produce flaky `NETWORK_ERROR`
failures unrelated to the feature.

Switch to `--tcp_port 0 --http_port 0` (OS-assigned ephemeral ports) and
construct the `url()` endpoint from the actual bound port via
`getServerPort('http_port')`. This mirrors the approach already adopted
for `03564_clickhouse_local_system_queries.sh`.
Comment thread programs/local/LocalServer.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, provide a fix for Unit tests (asan_ubsan, function_prop_fuzzer) FAIL
FunctionsStress.stress

@groeneai

Copy link
Copy Markdown
Collaborator

This FunctionsStress.stress failure (gtest_functions_stress.cpp:2423, "1 threads got stuck") is the chronic stuck-thread shape of #104877, not caused by this PR (clickhouse-local listeners only). It fires on master and across unrelated PRs: 107 hits / 96 distinct PRs + 12 master hits in the last 30 days.

The fix is already in flight, and it is yours: #107389 ("Fix arrayResize with a Decimal size"). Besides the arrayResize.cpp Decimal fix, it makes the harness integer_at_most constraint two-sided (res = if(res > limit, 0, res) -> abs(res) > limit), so a large-magnitude negative size can no longer slip past the clamp. That is the input class that drove the stuck thread: the fuzzer feeds e.g. arrayResize(a, <huge negative size>), the iteration runs well past max_execution_time=15s (historical reports show 21-35s), and the watchdog reports the worker as stuck. #107389's own function_prop_fuzzer checks pass on asan_ubsan, msan, and tsan.

No separate PR from me. Once #107389 merges this shape should stop; I am tracking the residual under #104877 and will flag if anything survives.

(session cron:clickhouse-worker-slot-0:20260614-023600)

…n clickhouse-local

A follow-up to validating the command-line `--tcp_port` / `--http_port`
options: a `tcp_port` / `http_port` value coming from a loaded config file
(rather than the command line) still reached the listener path unchecked.
`createServer` casts the configured port to `UInt16`, so an out-of-range
config value such as `<tcp_port>70000</tcp_port>` or `<http_port>-1</http_port>`
would silently wrap (to `4464` / `65535`) and `SYSTEM START LISTEN` would bring
the listener up on an unexpected port instead of failing.

Validate the effective `tcp_port` / `http_port` value in `LocalServer::startServers`
for every protocol being started, rejecting values outside `0..65535` with
`BAD_ARGUMENTS` (`0` is allowed and means an OS-assigned port). The check is
done in the local-specific `startServers` rather than in the shared
`createServer`, so it does not change `clickhouse-server` behavior, and it runs
lazily only when the user actually requests a listener, so a stray out-of-range
port in a shared config does not break plain `clickhouse-local` invocations that
never listen.

Added `05017_local_system_listen_config_port_range` covering the rejected
out-of-range config values and an accepted config `tcp_port=0`.

Addresses: #101143 (comment)

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

Copy link
Copy Markdown
Member Author

Pushed 4612e6d598b addressing the bot follow-up on config-file port validation (see the resolved thread on src/Server/createServer.cpp): the effective tcp_port / http_port is now range-checked in LocalServer::startServers so an out-of-range value from a loaded config file (not just --tcp_port / --http_port) is rejected before SYSTEM START LISTEN binds a wrapped port. Verified locally — full *_local_system_listen_* suite + 03564 pass on the rebuilt binary, and the new 05017_local_system_listen_config_port_range covers the rejected config values and an accepted config <tcp_port>0</tcp_port>.

CI triage on the remaining reds (all unrelated to this PR):

  • Unit tests (asan_ubsan, function_prop_fuzzer) — chronic flaky FunctionsStress.stress watchdog ("1 threads got stuck" on a slow randomly-fuzzed arrayResize). Fails on master and ~379 unrelated PRs over the last 60 days; tracked by FunctionsStress.stress #104877 and FunctionsStress #107242. Re-runs with this push.
  • CH Inc sync — "tests failed" (the upstream→private merge itself is clean, no manual intervention); the failures are private-only test configs (distributed cache, meta in keeper, distributed plan, FIPS, db disk) whose logs are not publicly inspectable.

Comment thread programs/local/LocalServer.cpp Resolved
alexey-milovidov and others added 4 commits June 14, 2026 16:42
The `test_numbers_check` style check (`check_gaps_in_tests_numbers` in
`ci/jobs/check_style.py`) failed with `Gap (4338, 5017) > 100`: the
config-file port-range test was numbered `05017`, far above this PR's
other tests, leaving a 679-wide hole in the stateless test numbering.

Rename `05017_local_system_listen_config_port_range.{sh,reference}` to
`04339_local_system_listen_config_port_range.{sh,reference}` — the next
free number after this PR's `04338` test, which the check confirms is the
true second-highest number in the tree. Also update the internal temp
config filename from `05017_config_port_range.xml` to
`04339_config_port_range.xml` to match. Test logic is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101143&sha=4612e6d598bf7826507d47e158e70ca5819c0c5a&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to the test renumbering: the renamed test still referenced
`05017_config_port_range.xml` as its temporary config-file path. Rename
it to `04339_config_port_range.xml` so the internal name matches the test
number. This is a cosmetic consistency fix; the temp file is created and
removed within the test, so behaviour is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…house-local

`LocalServer::startServers` started each listener's accept thread as soon
as its socket was bound (`createServer(..., start_server=true, ...)`).
With multiple `listen_host` values, an earlier listener could therefore
accept a connection and begin executing a query while a later bind in the
same call was still pending. If that later bind then failed, the
rollback stopped accepting new connections but, by the documented
lifetime rule, deliberately left the already-busy adapter in `servers` —
so a rejected `SYSTEM START LISTEN` could leave an external session
running. Under the default unauthenticated local users setup that is a
real concern.

Split the start into two phases. Phase 1 binds every requested
`listen_host` x protocol socket with `start_server=false`: the socket is
bound and listening at the kernel level, but no accept thread runs and no
connection is ever handed to a handler. Only after the per-protocol
verification confirms the whole requested set is bound does phase 2 start
the accept threads. The "Listening for ..." log line, previously emitted
by `createServer`, moves to phase 2.

This closes the accept window: on a bind or verification failure none of
the appended adapters has started accepting, so the rollback simply
closes their bound sockets (any connection queued in the kernel backlog
is reset, never served). The existing stop-then-erase rollback shape is
kept as the correct general rule for the rare case where `start` itself
throws in phase 2 after some accept threads are already live.

`TCPServer` (and `HTTPServer`, which derives from it) reports
`isOpen() == true` from construction, so a bound-but-unstarted adapter is
correctly counted by the per-protocol verification and its socket is
properly closed by `stop()` during rollback.

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

Copy link
Copy Markdown
Member Author

@groeneai, fix 04007_pipeline_stuck_ping_pong_deadlock

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov fixed in a separate PR: #107565.

Not caused by this PR. 04007_pipeline_stuck_ping_pong_deadlock is flaky under MergeTree-settings randomization (also hit #106734). The deadlock detection comes only from the pinned query SETTINGS, not storage layout. Two unrelated randomized combos break it: index_granularity = 1 makes the 1M-row inserts ~20x slower and times out the amd_msan/WasmEdge runner (the failure you saw here), and part_minmax_index_columns = 'with_block_number_offset' without the block-number/offset columns is rejected at CREATE TABLE. #107565 adds no-random-merge-tree-settings; passes 50/50 under randomization.

alexey-milovidov and others added 2 commits June 17, 2026 15:03
The merge with master brought in the multistage distributed queries
feature, whose `ExchangeServer` startup code in `Server.cpp` throws
`Exception(ErrorCodes::NETWORK_ERROR, ...)`. This branch had removed the
`extern const int NETWORK_ERROR;` declaration from `Server.cpp` because
its only previous use (in `Server::createServer`) was extracted into
`src/Server/createServer.cpp`. Restore the declaration so the new use
compiles.

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

Copy link
Copy Markdown
Member Author

Merged master (the branch was 919 commits behind and red on an unrelated amd_msan timeout). The merge surfaced a latent build break: master's multistage-distributed-queries feature added an ExchangeServer startup path in Server.cpp that throws Exception(ErrorCodes::NETWORK_ERROR, ...), but this branch had removed the extern const int NETWORK_ERROR; declaration from Server.cpp (its only previous use, in Server::createServer, was extracted into src/Server/createServer.cpp). Restored the declaration in a follow-up commit so the merged tree compiles. The remaining unresolved thread is the non-blocking test-port nit, already discussed above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai fix this error: test_storage_azure_blob_storage/test.py::test_azure_glob_scheherazade

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov The test_azure_glob_scheherazade failure is not caused by this PR. Your changes touch only clickhouse-local SYSTEM LISTEN handling; the test times out in its own cleanup, which drops 1001 AzureBlobStorage tables serially after the glob assertion. Under sanitizer builds with concurrent xdist workers that serial cleanup crosses the 900s pytest-timeout.

Fixed in a separate PR: #107799. It parallelizes the cleanup using the same chunked-thread pattern the test already uses to create the tables (creation runs ~31 concurrent threads doing heavier CREATE + INSERT without timing out). Test intent unchanged: still 1001 tables, still asserts glob selection beyond the 1000-blob boundary. Local benchmark: serial cleanup 61s vs parallel 6.6s.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged latest master (branch was 732 commits behind and CI was red) and pushed 475ba79ba3a..a8ee8e17eea.

The merge is clean: the only master-side change to a file this PR touches is Context.cpp/Context.h, where master added setAuthenticatedUserName in a region disjoint from this PR's registerServerPort/getServerPort mutex changes — auto-merged without conflict. The net diff of the merge commit against master is byte-identical to this PR's own 31-file diff (+1165 / -100); none of the delicate listener files (Server.cpp, LocalServer.cpp, ServerType.h, the new src/Server/*) were touched by master in the interval.

All 21 failures on the previous head were unrelated to this change and transient — refreshed by re-running CI on the merge:

  • Stateless tests (arm_asan_ubsan, targeted) — job-level ERROR, not a test failure: the test-targeter could not query the CI DB (Quota for user 'play' ... QUOTA_EXCEEDED). The new 04xxx tests themselves pass (flaky check: 400 passed / 0 failed across all four sanitizers).
  • BuzzHouse (amd_tsan) — job-level ERROR in the fuzzer runner script (FileNotFoundError: status.tsv); the other three BuzzHouse jobs passed.
  • Integration tests (…, 6/6) — test_storage_azure_blob_storage/test.py::test_azure_glob_scheherazade, a known Azure Timeout flake.
  • Performance Comparison (arm_release, 1/6) — query noise (coalesce, datetime64_conversion, decimal_aggregates, index_bulk_filtering, right_full_parallel_join, top_k_through_join, visit_param_extract_raw), flagged on both ::old and ::new; this PR touches no query-execution code.

The AI-review verdict on PR #101143 requested changes: the two negative
port-range tests for `clickhouse-local` could pass even when the validation
they cover regresses, because their `check_rejected` helpers only printed
`FAIL` and returned a zero exit status (and `04339` additionally evaluated the
listener command inside a command substitution, discarding its exit status).

Make both helpers fail hard:
- `04338_local_system_listen_port_range_validation.sh`: `check_rejected` now
  returns nonzero on unexpected acceptance or a wrong diagnostic; results are
  accumulated and the script ends with `exit $rc`.
- `04339_local_system_listen_config_port_range.sh`: `check_rejected` now runs
  the listener command itself (instead of receiving the output of a separate
  `run_listen` command substitution), so the exit status is no longer
  discarded, and it returns nonzero on unexpected acceptance or a wrong error.

The emitted stdout is unchanged, so the `.reference` files still match on a
correct build; a build that silently accepts an out-of-range `tcp_port` /
`http_port` now fails the test both via the reference diff and a nonzero exit.

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

clickhouse-gh Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 274/293 (93.52%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

alexey-milovidov pushed a commit that referenced this pull request Jun 20, 2026
This is a pipeline-deadlock regression test (issue #57728): it checks that a
full_sorting_merge join with the PingPongProcessor / FilterBySetOnTheFly
optimization no longer hangs. The deadlock detection is driven entirely by the
pinned query-level SETTINGS (join_algorithm = 'full_sorting_merge',
query_plan_join_swap_table = 0, max_threads = 2) and is independent of the
table's on-disk layout.

CI randomizes MergeTree settings per run, and two unrelated randomized
combinations break this test without exercising any new pipeline behavior:

  1. index_granularity = 1 with min_bytes_for_wide_part = 0 produces ~1M marks
     for the 1M-row tables, making each INSERT ~20x slower. On the slow
     amd_msan / WasmEdge runner this pushes the total runtime past the 180s
     timeout (seen on PR #101143). The query still returns the correct result;
     it is pure slowness, not a deadlock.
  2. part_minmax_index_columns = 'with_block_number_offset' without
     enable_block_number_column / enable_block_offset_column is rejected at
     CREATE TABLE with BAD_ARGUMENTS (seen on PR #106734, amd_tsan and
     arm_binary).

Pinning a single setting cannot cover both classes, and the test does not
depend on MergeTree storage randomization for any of its coverage. Add the
no-random-merge-tree-settings tag, which disables only MergeTree-settings
randomization while leaving session-level setting randomization (where the
pipeline / join behavior lives) intact. The same tag is used by sibling tests
(00564, 00926, 02981) for the same reason.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov
alexey-milovidov merged commit d31a039 into master Jun 22, 2026
165 of 166 checks passed
@alexey-milovidov
alexey-milovidov deleted the local-server-system-listen branch June 22, 2026 18:30
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants