Skip to content

feat: ClickHouse and Elasticsearch query adapters and fallback clients (layout step 8) - #883

Draft
zzylol wants to merge 1 commit into
refactor/layout-ingest-adaptersfrom
refactor/layout-query-adapters
Draft

zzylol wants to merge 1 commit into
refactor/layout-ingest-adaptersfrom
refactor/layout-query-adapters

Conversation

@zzylol

@zzylol zzylol commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: ASAPQuery answers ClickHouse (/clickhouse/query) and Elasticsearch (POST /_sql, POST /_search) clients and forwards what it cannot answer to that protocol's server. The backend serves only the Prometheus API. Step 8 of docs/design/repo-layout.md (docs(design): repository layout and engine boundaries #874) brings both query adapters and their fallback clients over.
  • Change:
    • crates/adapters/query/clickhouse-http (clickhouse_http): reads the query (the query parameter of the URL or a form, else the plain SQL body), writes TabSeparated, and ClickHouseHttpFallback posts the query to /?database=<db>.
    • crates/adapters/query/elastic-http (elastic_http): reads _sql and _search bodies, writes _search hits and Elasticsearch error bodies, and ElasticHttpFallback posts to /_sql or /<index>/_search.
    • Both fallbacks implement common::FallbackClient. Both crates depend on common only.
    • data-plane: --clickhouse-url/--clickhouse-database and --elastic-url/--elastic-index serve the routes. Each request becomes a common::QueryRequest, goes through the new QueryDispatcher::dispatch, and what the plan does not answer goes to the route's FallbackClient. This is the first production caller of the trait.
    • Ported read-only from ASAPQuery's main. refactor(query-engine): extract asap-adapters crate ASAPQuery#936 and #937 are still open; names follow #936 (ClickHouseHttpFallback, ElasticHttpFallback) and #937's QueryRequest (already in common).
  • Effect:
    • Without the new flags nothing changes: every existing endpoint is byte-identical to feat: VictoriaMetrics Remote Write and OTLP ingest adapters (layout step 7) #882's head, and the three new paths are 404 (proxied in forward mode), as before.
    • With them, every ClickHouse and Elasticsearch query is forwarded to its server. None is answered from the plan yet, because no plan can hold one (see Deferred).

Review guide

Dependency graph

clickhouse_http ──► common, async-trait, form_urlencoded, reqwest, thiserror
elastic_http ─────► common, async-trait, reqwest, serde_json, thiserror
data_plane ──► + clickhouse_http, elastic_http

No new lockfile package besides the two crates.

Behavior: before → after

Request Before After
Every existing route, /metrics, forward-mode proxying byte-identical (see Parity)
/clickhouse/query, /_sql, /_search without the new flags 404; forward mode: proxied the same
GET/POST /clickhouse/query with --clickhouse-url 404 / proxied query from the URL, a form or the plain body; posted to ClickHouse with the client's Authorization; ClickHouse's status, Content-Type and body returned (x-asap-execution: forwarded). 400 with no query, 502 when ClickHouse cannot be reached
POST /_sql, POST /_search with --elastic-url 404 / proxied posted to /_sql ({"query", "fetch_size": 1000}, trailing ; dropped) or /<index>/_search (body as sent); response returned as is. A body that does not parse: 400 parsing_exception; GET: 400 illegal_argument_exception; 502 when unreachable
A ClickHouse query whose text equals a planned PromQL query forwarded; it is not the plan's query

--no-forward with either flag is refused (clap, and the builder).

Interfaces

crates/data-plane/src/dispatcher.rs

 impl QueryDispatcher {
     pub async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome<Answer>;
     pub async fn range(&self, query: &str, times_ms: impl Iterator<Item = i64>) -> QueryOutcome<Vec<(i64, Answer)>>;
+    /// Through ExecutorQueryEngine::execute. Only a PromQL request can be the plan's;
+    /// any other language is Unmatched.
+    pub async fn dispatch(&self, request: &QueryRequest) -> QueryOutcome<QueryResult>;
 }

crates/data-plane/src/lib.rs

 impl DataPlane {
+    /// Serves /clickhouse/query; refused with --no-forward.
+    pub fn with_clickhouse_fallback(self, fallback: impl FallbackClient + 'static) -> anyhow::Result<Self>;
+    /// Serves POST /_sql and POST /_search; refused with --no-forward.
+    pub fn with_elastic_fallback(self, fallback: impl FallbackClient + 'static) -> anyhow::Result<Self>;
 }

crates/adapters/query/clickhouse-http (new)

+pub struct MissingQuery;                                   // 400 "missing parameter \"query\""
+pub const TAB_SEPARATED_CONTENT_TYPE: &str;
+pub fn parse_query(url_query: Option<&str>, body: &[u8], now_ms: i64) -> Result<QueryRequest, MissingQuery>;
+pub struct UnsupportedResult(&'static str);                // a range or a scalar
+pub fn tab_separated(result: &QueryResult) -> Result<Vec<u8>, UnsupportedResult>;
+pub struct fallback::ClickHouseHttpFallback;
+impl ClickHouseHttpFallback { pub fn new(base_url: &str, database: &str, timeout: Duration) -> Self; }
+impl FallbackClient for ClickHouseHttpFallback;           // ClickHouse SQL instant queries only

crates/adapters/query/elastic-http (new)

+pub struct BadRequestBody(String);
+impl BadRequestBody { pub fn error_body(&self) -> Value; } // 400 parsing_exception
+pub fn get_refused_body() -> Value;                         // 400 illegal_argument_exception
+pub fn parse_sql(body: &[u8], now_ms: i64) -> Result<QueryRequest, BadRequestBody>;     // SQL(ElasticSQL)
+pub fn parse_search(body: &[u8], now_ms: i64) -> Result<QueryRequest, BadRequestBody>;  // ElasticDSL, body kept as sent
+pub struct UnsupportedResult(&'static str);
+pub fn search_response(result: &QueryResult) -> Result<Value, UnsupportedResult>;    // instant vector → hits
+pub struct fallback::ElasticHttpFallback;
+impl ElasticHttpFallback { pub fn new(base_url: &str, index: &str, timeout: Duration) -> Self; }
+impl FallbackClient for ElasticHttpFallback;               // ElasticSQL and Query DSL instant queries only

crates/data-plane/src/main.rs

+--clickhouse-url URL   --clickhouse-database NAME (default "default")
+--elastic-url URL      --elastic-index NAME (default "": every index)

Tests

  • clickhouse_http (6): parsing from the URL, a form and a plain body, and refusals (from ASAPQuery's test_parse_get_request, test_parse_post_request_form, test_missing_query_parameter); TabSeparated of an instant vector (ASAPQuery's test_format_success_response fixture: host1\t91, host2\t77.5), of a table with escapes and nan/-inf, and of series with different labels; ranges and scalars refused. Fallback against a mock ClickHouse: the query posted to /?database=… with Authorization, the response and a ClickHouse exception (404) returned unchanged; ranges, other languages and an unreachable server refused (ASAPQuery's test_execute_query_*, test_range_query_not_implemented).
  • elastic_http (6): _sql keeps only query (ASAPQuery's test_parse_sql_query*); _search keeps the body byte for byte and refuses non-objects (test_parse_json_post_request, test_parse_query_with_timestamp, test_invalid_json); error bodies (test_format_error_response); hits (test_format_success_response). Fallback against a mock Elasticsearch: /_sql body with fetch_size, /<index>/_search and /_search, Authorization; ranges, other languages and an unreachable server refused.
  • data_plane dispatcher (+1): through ExecutorQueryEngine::execute, a planned PromQL request is answered with the values the Prometheus path gives, is not ready where that path is not, and the same text in ClickHouse SQL is unmatched.
  • data_plane tests/query_protocols.rs (+5, end to end through the router with a mock upstream):
    • ClickHouse queries from the URL, a form and a plain body are forwarded with Authorization; a ClickHouse exception comes back as sent; no query is 400 and not forwarded.
    • With the views stored, the planned PromQL query is answered from them on /api/v1/query, while the same text on /clickhouse/query is forwarded to ClickHouse.
    • _sql and _search are forwarded; bad bodies and GET are 400 without forwarding.
    • The routes are 404 without their server, --no-forward refuses either server, an unreachable server is 502.
    • Forward mode: /_search still goes to Elasticsearch, other paths are still proxied to the raw store.

Gate on the restacked head (1c2d5d1): cargo fmt --all -- --check and cargo clippy --workspace --all-targets --locked -- -D warnings clean, cargo test --workspace --locked: 236 passed, 0 failed, 3 ignored (56 suites; planner_executor_parity::push_precompute_stores_the_window_paths_view_rows failed once under load and passed alone) (#882: 218 passed, 0 failed, 3 ignored (51 suites); +18 new).

Parity

The uncommitted dump test from #880–#882, with /clickhouse/query, /_sql, /_search and /clickhouse/ping added (not configured). Fixture: the plan of sum by (job) (sum_over_time(data[10s])), 3 series written through 60 s; planned instant and range queries, cached steps, not-ready and unplanned queries, malformed and empty Remote Write bodies, /api/v1/status/asap, with and without --no-forward, headers except date, and the /metrics names and label sets. The dump is byte-identical to #882's head (32,469 bytes both; stable over 4 runs).

Benchmarks

Release builds, same host, cores 0–15, #882's head and this branch alternating. No code on these paths changed; the differences are within run-to-run spread.

#882 head this PR
view_read_bench 10000 40 15, cold mmap (ms per window, 8 runs) median 3.08 [2.88–3.63] median 3.08 [2.88–3.58]
… warm mmap 2.38 [2.34–2.38] 2.38 [2.37–2.38]
… cold pread 2.88 [2.74–3.03] 2.83 [2.78–2.97]
… warm pread 2.43 [2.39–2.44] 2.42 [2.42–2.43]
offset_bench 1000 5, through the router and dispatcher (ms, 3 queries × 3 runs) median 10.6 [10.4–15.9] median 10.7 [8.7–16.0]
tier_bench 2000 70, RESULT_CACHE=0, through the router (ms, rounds 2–5 × 3 runs): quantile_over_time(0.99, lat[1h]) 49.6 [30.5–58.7] 50.3 [43.8–57.7]
… max_over_time(lat[30m]) 20.5 [14.1–23.0] 21.0 [17.8–23.2]
… topk(10, sum by (job) (rate(reqs[1h]))) 9.9 [6.3–12.1] 11.0 [6.1–12.1]
… sum by (job) (increase(reqs[1h])) 11.0 [6.2–12.0] 11.3 [9.6–12.1]

range_bench 1000 views 15 fails the same way on both trees (a 422 for quantile_over_time(0.99, lat[1h]): a view window not tiling the range), so it is not compared here.

Deviations from ASAPQuery

  • Responses pass through. The server's status, Content-Type and body are returned as sent. ASAPQuery turned a ClickHouse exception into an empty 400, sent Elasticsearch errors with HTTP 200, and answered network errors with 500; here they are the server's own status, or 502.
  • Elasticsearch error bodies are sent with HTTP 400 (as Elasticsearch sends them), without ASAPQuery's Parse error: / Protocol error: prefixes.
  • Authorization is forwarded on GET and POST, to both servers. ASAPQuery forwarded it on POST only and never to ClickHouse. X-ClickHouse-User/X-ClickHouse-Key and user/password URL parameters are not forwarded.
  • The ClickHouse database is URL-encoded; the timeout is --forward-timeout-seconds (default 120 s) instead of a fixed 30 s.
  • _search takes only a JSON object and forwards it byte for byte (ASAPQuery accepted any JSON value and re-serialized it). Content-Type is not checked.
  • TabSeparated escapes \, tab, newline, carriage return and NUL; floats use Rust's shortest round-trip digits (no exponent form). Vector columns are every label name, sorted.
  • Not ported: the runtime-info routes (/clickhouse/ping, /_cluster/health; docs(query-engine): design engine boundaries for ASAPPlanner plans ASAPQuery#935's T4) and the always-failing range routes (/clickhouse/query_range, /_search_range).

Why the fallback clients repeat code

ClickHouseHttpFallback, ElasticHttpFallback and PrometheusHttpFallback each convert headers, turn the response into a FallbackResponse (with the application/octet-stream default) and build a reqwest client, and UnsupportedResult is defined in both new adapters. This is deliberate: adapters may depend only on common, on nothing, or on the adapter whose wire format they extend, never on each other, and common holds no HTTP crate. Sharing the code would need an adapter-to-adapter dependency or HTTP types in common; please do not "fix" it that way.

Deferred

  • Answering SQL and Query DSL from views. The control plane plans PromQL workloads only; ASAPPlanner lowers SQL to Table scans (and refuses Elasticsearch SQL; it has no Query DSL frontend), while storage holds time series only. A planned ClickHouse query needs table sources end to end (ingest, a raw table store, a SQL catalog for the control plane). Until then dispatch returns Unmatched for any language but PromQL, and the encoders and the plan branch of answer_or_forward are reached only in unit tests. They are kept so the routes answer a planned query without change once one exists.
  • Response headers other than Content-Type (X-Elastic-Product, X-ClickHouse-*) are not passed through; FallbackResponse carries only the content type. Some Elasticsearch clients check X-Elastic-Product.
  • Upstream responses are buffered whole (as the Prometheus fallback does).
  • _sql cursors, params, ?format=, and ClickHouse settings parameters (default_format, …) are not forwarded.
  • Doc. docs(design): repository layout and engine boundaries #874's doc is updated on its branch: the seam the two routes use, the language guard, and a row for SQL and Query DSL in "Where the backend differs from #935".

@zzylol zzylol added area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior feature: PromQL PromQL compatibility and execution semantics labels Nov 26, 2026
@zzylol zzylol added enhancement New feature or request and removed feature: PromQL PromQL compatibility and execution semantics labels Nov 27, 2026
…s (layout step 8)

Ports ASAPQuery's ClickHouse (/clickhouse/query) and Elasticsearch
(POST /_sql, POST /_search) query adapters into
crates/adapters/query/{clickhouse-http,elastic-http}, each with a
fallback client implementing common::FallbackClient. The data plane
serves the routes when --clickhouse-url / --elastic-url is given: each
request becomes a common::QueryRequest, goes through the new
QueryDispatcher::dispatch, and what the plan does not answer is sent to
the route's fallback. Only PromQL can be planned today, so every such
query is forwarded. Existing endpoints are unchanged.
@zzylol
zzylol force-pushed the refactor/layout-ingest-adapters branch from 93d4d49 to 11a1c3a Compare November 28, 2026 00:56
@zzylol
zzylol force-pushed the refactor/layout-query-adapters branch from 2a2b6bb to 1c2d5d1 Compare November 28, 2026 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant