Skip to content

Query plan serialization: framed outline format with step manifests - #111824

Draft
davenger wants to merge 78 commits into
masterfrom
query_plan_framed_serialization
Draft

davenger wants to merge 78 commits into
masterfrom
query_plan_framed_serialization

Conversation

@davenger

@davenger davenger commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Query plan serialization gets a framed format (plan version 16) that lets servers of different versions exchange plans safely, together with a compile-time step-manifest framework that declares each step's wire content once.

Motivation. The older format is versioned and reads field by field with per-version branches (if (version < X) ...), so it does exchange plans across versions — but every serialization change costs a global plan-version bump, which a stable release cannot claim, so a correctness fix cannot be backported to it; and without framing a reader cannot skip a step or field it does not know, so a new step desynchronizes the stream rather than being refused. make_distributed_plan, parallel replicas with serialize_query_plan = 1, EXPLAIN of a serialized plan, and backported fixes all put an old and a new server on the two ends. The framed format decides compatibility per name and lets a reader walk past and refuse content it does not know, so a serialized plan does exactly one of two things on the receiver — run correctly, or be refused with a clear message — never misread into wrong results.

The format. A framed plan is a two-field head [plan_version][format_kind], an outline, and the payloads. The outline carries the plan-level fields, the node and set counts, and per node its input edges, step name, output header and changed settings; each step payload and each set then follows as its own sized frame. The body is self-delimiting for a known format_kind, so a reader walks it to its exact end with no total length, builds each step as its payload arrives (children-first), and can validate the whole plan or render its shape from the outline before decoding a payload.

Compatibility rides on names, not the version. A receiver runs a plan when it knows every step name, setting name, type/function tag and set kind the plan uses, and refuses cleanly otherwise; the plan version is only a coarse gate. Each step name owns exactly one immutable payload layout — a new step, a new field, or a backported fix is a new serialization name — so master can change a step between releases with no version bump and a fix can be backported to an old release without one. A field is omitted for an old name only when its absence cannot change results; otherwise the plan is refused at that version (lossless-or-fail). Settings travel in a separate channel keyed by name, written only when they differ from a frozen wire default.

Step manifests. Each step declares a plain wire struct and a compile-time manifest naming each field; from that one declaration the framework generates the writer, the reader, the settings channel, the cache-key hash and the registry entry, and the step writes only toWire/fromWire. A checked-in baseline test prints every manifest, so a wire-format change cannot slip in unnoticed. Every step is on a manifest.

Safety and recovery. Element counts and declared sizes are checked against the frame before anything is allocated, and the max_serialized_query_plan_size server setting caps the whole plan — it is a server setting so the sender cannot raise it; the stateless-worker envelope caps the plan length before allocating. The writer serializes and validates the whole plan into a buffer before it writes the packet, so a late failure cannot leave a partial packet on the wire. A refused plan whose body the reader can walk is drained off the connection first, so it costs the query and not the connection.

Version selection during an upgrade. The version a writer emits by default is its own constant that can lag the newest one, so a fleet reads a new version everywhere before anyone writes it; max_query_plan_serialization_version holds every writer on a server at an older version while a fleet is mixed, and the query_plan_serialization_version query setting lets one query try a newer version.

The older, pre-framed writers and readers are kept for peers below the framed baseline on the negotiated TCP path. make_distributed_plan and serialize_query_plan are experimental and not in production, so the format is replaced now while the change is free.

Changelog category (leave one):

  • Experimental Feature

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

Reworked query plan serialization (used by the experimental make_distributed_plan and serialize_query_plan features), with a focus on: maintainable code structure — each step declares once what it puts on the wire; rolling upgrades — servers of different versions can exchange plans, and a plan a server cannot read is refused with a clear error instead of failing unpredictably; and robustness against oversized or malformed input. Adds the max_serialized_query_plan_size and max_query_plan_serialization_version server settings and the query_plan_serialization_version query setting.

  • Documentation entry for user-facing changes

Workflow [PR]
Sync PR [sync-upstream/pr/111824]

davenger and others added 22 commits July 22, 2026 21:26
… read below plan version 3

Co-Authored-By: Claude Fable 5 <[email protected]>
… serialization manifest

Co-Authored-By: Claude Fable 5 <[email protected]>
…sort/aggregate descriptions, header)

Co-Authored-By: Claude Fable 5 <[email protected]>
…age names; align frame error codes

Co-Authored-By: Claude Fable 5 <[email protected]>
… envelope truncation as `CANNOT_PARSE_QUERY_PLAN`

Co-Authored-By: Claude Fable 5 <[email protected]>
The head carries `min_reader_plan_version` computed by the writer from every
carrier a reader decodes (step registry info, write-site requirements via
`requireReaderVersion`, header and tuple-set types, settings, set kinds,
nested subquery plans recursively). A reader accepts any v4+ stream whose
requirement it meets, even from a newer writer; validation cross-checks the
declared per-node values against this binary's registry info.

Co-Authored-By: Claude Fable 5 <[email protected]>
`make_distributed_plan` is experimental, so mixed-version smoothness is not
required on this path yet: a worker too old for the plan rejects it by the
version in the head with a clear error, never misreads it.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cbd39b0]

Summary: ✅


AI Review

Summary

This PR replaces query-plan serialization with a framed outline/manifest format and adds per-query/server version-selection knobs for mixed fleets. The current head fixes several of the earlier frame-boundary bugs, but it still breaks two of the advertised contracts: mixed-version writers are order-dependent, and some malformed framed payloads can still either force oversized allocations or desynchronize the connection before the drain logic runs.

Findings

❌ Blockers

  • [src/Client/Connection.cpp:1227; src/Processors/QueryPlan/Serialization.cpp:539-596] sendQueryPlan still chooses the cached serialization through each connection's server_query_plan_serialization_version, but QueryPlan only stores one version. In a mixed 15/16 shard the first replica to send fixes the cache, and the next framed replica can then throw even though it could read the already-cached older bytes. The result depends on replica iteration order, which violates the PR's "serialize once and exchange safely across versions" contract.
    Suggested fix: choose one writer version for the whole fan-out before any send, or cache serializations per version instead of rejecting on the second framed peer.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1780-1788] query_plan_serialization_version is removed from task_description.settings_changes, so a stateless-worker fragment that fans out again loses the initiator's requested writer version. The first hop may write an older compatible plan, but the second hop falls back to the worker default or ceiling and can still break a mixed fleet or make local and remote execution diverge.
    Suggested fix: carry the resolved writer version in a versioned task field that newer workers preserve on downstream plan writes.

  • [src/Processors/QueryPlan/QueryPlanOutline.cpp:216-246; src/Processors/QueryPlan/Serialization.cpp:404-417] The v16 "refuse the plan without losing the connection" contract still fails during outline parsing. readQueryPlanOutline and readOutlineFrameCounts throw on oversized or malformed outline frames before the drain guard in deserializeFramedBody is armed, and they do not consume the unread outline bytes on the exceptional path. The next packet is then parsed from the middle of the rejected plan.
    Suggested fix: move the drain scope up to cover outline parsing too, and make the skip_data path consume the oversized outline frame before throwing.

  • [src/Interpreters/ActionsDAG.cpp:4350-4376, 4491-4497, 4667-4848; src/Interpreters/AggregateDescription.cpp:220-244, 281-295; src/Core/SortDescription.cpp:329-343; src/Processors/QueryPlan/WindowStep.cpp:284-317] The new framed allocation guards are still incomplete inside helper codecs. Nested counts such as lambda captures and captured columns still resize vectors from untrusted varints without a frame-derived cap, and the bare readStringBinary calls in these framed readers still accept the global 1 GiB default even when only a few payload bytes remain. A tiny QueryPlan payload can therefore still trigger huge allocations before EOF.
    Suggested fix: thread bytesRemainingInFrame or max_elements through all nested helper readers, cap every string read by the current frame, and add the missing count check for deserializeAggregateDescriptionsWithoutArguments.

  • [src/Processors/QueryPlan/SetsSerialization.cpp:454-460] The legacy v1-v3 tuple-set guard still uses max_serialized_query_plan_size bytes as a row cap. For fixed-width columns NativeReader::readData allocates rows * sizeof(T) before reading payload bytes, so a tiny legacy set can still ask for tens of GiB while staying under the current 2_GiB row ceiling.
    Suggested fix: bound legacy tuple-set rows by the remaining bytes and per-column minimum element width, or read them through a bounded wrapper that rejects impossible row counts before resizing the column.

⚠️ Majors

  • [src/Processors/QueryPlan/QueryPlan.h:147-151, 295-324; src/Client/Connection.cpp:1217-1230; src/QueryPipeline/RemoteQueryExecutor.h:267] One-shot sends still leave a full serialized copy of shipped sets attached to the QueryPlan for the rest of the query. The chunked cache removed the earlier extra envelope copy, but ensureSerialized still publishes cached chunks that are never dropped, and RemoteQueryExecutor keeps the plan alive after the send. Large literal or subquery IN sets are therefore duplicated in memory until the executor is destroyed.
    Suggested fix: stream directly when no reuse is needed, or release the cached chunks once the last send for a plan completes.
Tests
  • ⚠️ There is no focused regression that sends one shared QueryPlan to a mixed 15/16 replica set in both orders. The current PlanIsSerializedOnceAndOffVersionPeersAreRefused coverage only checks current versus pre_framed, so it would not catch the live 15 first / 16 second failure.

  • ⚠️ There is no stateless-worker multi-hop test that sets query_plan_serialization_version on the initiator and asserts the same version is used when a worker fans out again.

  • ⚠️ The new allocation-guard tests cover oversized element counts, but there is no matching malformed-payload test for small framed inputs that advertise huge string lengths or lambda-capture and captured-column counts.

Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the mixed-version writer selection, preserve the chosen writer version across stateless-worker hops, and close the remaining outline/helper-codec allocation and drain gaps so malformed framed plans cannot still desynchronize the connection or force oversized allocations.

LLVM Coverage Report

Measured on commit cbd39b0.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.30% -0.50%
Branches 81.30% 81.20% -0.10%

Changed lines: Changed C/C++ lines covered: 2675/3211 (83.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 24, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
davenger and others added 22 commits September 4, 2026 14:26
…erialization

# Conflicts:
#	src/Core/ProtocolDefines.h
…erialization

A step declares a wire struct and a `constexpr` manifest; the framework writes and reads the
payload, fills the settings channel, derives the reader requirement and the registry entry,
and pins every declaration in a baseline test. `LimitStep`, `OffsetStep` and `DistinctStep`
use it for streams at the framed version; older streams keep their hand-written layout.
… custom ones

Twenty-one more steps declare a wire struct and a manifest: the limit families, `Expression`,
`Filter`, `ObjectFilter`, `LimitBy`, `Union`, `Extremes`, `ReadNothing`, `TotalsHaving`,
`ArrayJoin`, `BuildRuntimeFilter` and the six exchange steps. The eight custom steps register a
manifest without fields. The registry entry says whether a step's content is a wire struct, for a
converter to another plan format.
…cess

A registry now stands for a build: the steps and formats it knows and the plan version it
speaks. Tests make one the current registry for a thread, so an older and a newer build can
exchange plans in one process. The manifest descriptions live in the registry too. A writer held
below the version a value needs refuses with a regular error instead of a logical one, because
the generated writer raises that requirement on purpose.
A size or count inside the plan can no longer read past the declared body into the
bytes that follow it on the connection; an over-read hits the buffer end and the body
is drained to its end on every exit.
Codec reads now check their element count against the remaining frame bytes before
allocating; `ActionsDAG::deserialize` takes a `max_elements` bound that query plan
callers set from the payload and the trusted cluster read-task caller leaves off.
Every setting a step declares is written whatever its value, so a reader takes it off
the wire instead of reconstructing a default that can differ between versions.
A manifest carries the number of input streams the step reads, derived from its base
class and declared with `.inputs` or `.variableInputs` for a step that is neither a
source nor a transforming step. The outline validation rejects a node whose child count
does not match, so a crafted plan can no longer make a factory read an input header that
is not there.
…s present

A step payload is copied in as it arrives rather than reserving its declared size up
front, so a short stream costs an allocation of what it sent, not what it claimed. The
window function parameter count is checked against the remaining payload before the
resize, like the other codec counts.
…e limit

Each step payload is a `LimitReadBuffer` over the body instead of a materialized copy, so
nothing is duplicated. A codec sizes a count against the bytes left before the limit, which
`LimitReadBuffer::bytesUntilLimit` reports exactly whatever the socket has buffered, rather
than `available()` which is only the current chunk on a streaming source.
A setting a receiver does not know stays off the wire while it sits at its default, so adding a
setting does not break an older receiver on the common path. This relies on the registered defaults
being frozen wire defaults, which `registerManifest` already checks against each wire struct's
initializer; a changed behavior gets a new setting name rather than a changed default.
…lag bits

A set a step's expressions reference must have its data in the outline; a binding left unfilled is
now refused at parse time instead of failing later at execution. A serialized sort description with a
flag bit this reader does not define is refused rather than silently ignored.
…ing plan versions

An older reader reads the formats up to the one it knows and skips the rest, which is only correct
when a later format's version is above every earlier one. `registerManifest` now checks it.
…ed` payload

The merge step does not collect hash table statistics, so the stats key and its three settings were
written and then ignored on read. The framed format carries them no longer.
- Encode each node's inputs as explicit child indices instead of a child count, so the
  format can describe a step shared by several parents, not only a tree.
- Send step descriptions only when the writer asks for them; a normal plan omits the debug text.
- Read the outline straight from the stream through a size-bounded buffer instead of copying it.
- Drain an oversize declared body before rejecting it, so the next packet is not parsed from
  the middle of the refused plan.
It had no consumer and cost a byte per node. A future per-node outline field is added when it is
needed and gated by the plan version, so an older reader rejects it cleanly rather than skipping it.
- Rename `QueryPlanEnvelope` to `QueryPlanOutline`.
- The head is `[plan_version][format_kind]`; remove `min_reader_version` end to end. The plan version
  is a coarse gate, and the step names, settings and set kinds decide, failing closed on anything the
  reader does not know.
- Each step name owns one payload layout: refuse any `step_format_version` other than 1 and require
  each payload frame to be consumed exactly.
- Serialize and validate the whole plan before writing the packet, so a late failure cannot leave a
  partial packet, and cap the worker plan length before allocating.
- Bound the per-count allocation guard to a `LimitReadBuffer` frame, so a streamed plan is not
  refused when a count crosses a buffer boundary.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ifest

Master took plan serialization versions 12-15 (ReadInOrder, the `only_merge` flag, `IntersectOrExcept`,
`LimitRange`), so the framed format moves from 12 to 16: `DBMS_QUERY_PLAN_SERIALIZATION_VERSION`,
`DBMS_DEFAULT_QUERY_PLAN_SERIALIZATION_VERSION` and `DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_OUTLINE`
are 16.

Conflicts resolved:
- `Connection.cpp`: keep the `query_plan_serialization_version` handshake and take master's
  `chooseNetworkCompressionCodec`.
- `ProtocolDefines.h`: keep master's 12-15 definitions, add 16 for the framed format, keep
  `DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PARALLEL_REPLICAS = 3` (the flag-bit gate; the plan is
  written per peer version, not one shared blob).
- `Fractional`/`Negative` `Limit`/`Offset` steps: keep both the manifest hooks and master's
  runtime-dataflow-statistics support.
- `IntersectOrExcept` and `LimitRange` now serialize through a `StepManifest` in the framed format,
  with their pre-framed hand-written serialization kept as the legacy path for older peers.
- Carry `only_merge` in the framed `Aggregating` payload: master added the flag only to the legacy
  stream, so the framed manifest dropped it, which lost it on the wire and in the cache key.
- Regenerate the checked-in manifest baseline for the new fields (every format now reads
  `introduced_in 16`, the framed plan version).
- Fix the `only_merge` legacy-gate test to write the flag at the version that introduced it and replay
  it one version older, instead of relying on the framed stream matching the old flags-byte layout.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@davenger davenger changed the title Query plan serialization v4: framed outline format with rolling upgrade support Query plan serialization: framed outline format with step manifests Sep 9, 2026
davenger and others added 2 commits September 9, 2026 19:55
The `catch_all` style check flags an empty `catch (...)` unless a comment says the swallow is intended.
These four catches step over a frame or drain the rest of a refused plan; the real error is re-thrown or
reported separately, so mark each with an `Ok` comment.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The cache key (hash-table statistics, and the parallel-replicas node match) is a logical hash. The
older serializer honored `for_cache_key` and skipped fields that do not affect the statistics it
identifies; the framed manifest dropped that and hashed every field, so a step that differed only in
such a field no longer matched, which stopped automatic parallel replicas from collecting statistics.

- `writeManifestPayload` now honors `for_cache_key`: it skips physical fields and any logical field a
  manifest marks `notInCacheKey`. The bytes are only ever hash input, so skipping is safe; the real
  transport still writes every field.
- Mark `final` on `AggregatingStep` `notInCacheKey` (a partial and a final aggregation build the same
  number of groups) and drop the manual `if (for_cache_key)` zeroing it replaces.
- Drop `prevent_input_removal` from the `Expression` and `Filter` wire structs: it only guides
  `removeUnusedColumns` during optimization and a plan reaching a reader is already optimized, so a
  remote does not need it and the older format never sent it. Its presence leaked a physical
  difference in a child step into the node hash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Client/Connection.cpp
/// The plan is serialized once at this server's version and every peer is sent those bytes. A
/// framed replica reads them by their own version check; a replica too old for the framed format
/// is refused here rather than served a separate older serialization.
query_plan.ensureSerialized(server_query_plan_serialization_version, query_plan_serialization_version);

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.

Feeding each connection's server_query_plan_serialization_version into a cache that only stores one serialization version still breaks the mixed-version contract outside the explicit prewarm path.

MultiplexedConnections::sendQueryPlan reuses one QueryPlan across all replicas. If a mixed 15/16 shard sends to a 15 replica first, ensureSerialized caches v15 here; the next 16 replica then reaches QueryPlan::writeSerializedTo with version = 16 and throws on serialized_plans.version != version, even though that peer can read the already-cached v15 bytes. If the 16 replica sends first, the 15 replica is refused instead. So whether serialize_query_plan works now depends on replica iteration order, not on negotiated compatibility.

Can we choose one fleet-wide version before the send loop (for example min(writer_version, min_peer_version) with the hedged-replica conservatism applied there), or keep separate cached serializations per version?

/// so an outline larger than the body has to be rejected before anything is read or allocated.
/// Otherwise a plan declaring a small body could still make the reader take bytes that belong
/// to the protocol after it.
UInt64 outline_size = readCappedVarUInt(in, std::min(MAX_OUTLINE_BYTES, max_frame_bytes), "outline bytes");

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 still loses the v16 "refuse the plan, keep the connection" guarantee for outline failures. readCappedVarUInt can throw here before any node/set counts are known, and deserializeFramedBody does not enter its try/skipSizedFrames drain until after readQueryPlanOutline returns. The same thing happens if readOutlineBody rejects after consuming only part of the outline frame: readQueryPlanOutline rethrows without stepping over the unread bytes.

So an oversized or malformed outline still desynchronizes the connection; the next packet is parsed from the middle of the rejected plan. Can we move the drain scope up to cover outline parsing too, and make the skip_data path consume the oversized outline frame before throwing?

LambdaCapture capture;
deserializeCapture(capture, in, max_type_complexity);
auto capture_dag = ActionsDAG::deserialize(in, registry, context, max_type_complexity);
auto capture_dag = ActionsDAG::deserialize(in, registry, context, max_type_complexity, max_elements);

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.

Passing max_elements into the nested ActionsDAG still leaves the other capture-side allocations unchecked. In the framed path we still resize captured_names, captured_types, lambda_arguments, and captured_columns from untrusted varints without a frame-derived cap, and the bare readStringBinary calls in these helper codecs (ActionsDAG, AggregateDescription, SortDescription, WindowStep) still accept the global 1 GiB limit even when only a few payload bytes remain.

That breaks the PR's new "check counts and declared sizes against the frame before allocation" guarantee: a tiny QueryPlan payload can still drive multi-GB allocations before EOF. Please thread bytesRemainingInFrame or max_elements through those nested helpers too, and add the missing num_args bound in deserializeAggregateDescriptionsWithoutArguments.

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @davenger, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants