Repository navigation
Conversation
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
… read below plan version 3 Co-Authored-By: Claude Fable 5 <[email protected]>
… serialization manifest Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…ion idempotent Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…sort/aggregate descriptions, header) Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…ity) Co-Authored-By: Claude Fable 5 <[email protected]>
…(internal-only) Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…eserialization Co-Authored-By: Claude Fable 5 <[email protected]>
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]>
…-to-read version Co-Authored-By: Claude Fable 5 <[email protected]>
…he same thing) 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]>
|
Workflow [PR], commit [cbd39b0] Summary: ✅
AI ReviewSummaryThis 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
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit cbd39b0.
Changed lines: Changed C/C++ lines covered: 2675/3211 (83.31%) · Uncovered code |
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ization Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…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.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…an append Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
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]>
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]>
| /// 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); |
There was a problem hiding this comment.
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?
…::move` Co-Authored-By: Claude Opus 4.8 <[email protected]>
| /// 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"); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
|
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. |
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 withserialize_query_plan = 1,EXPLAINof 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 knownformat_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
mastercan 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_sizeserver 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_versionholds every writer on a server at an older version while a fleet is mixed, and thequery_plan_serialization_versionquery 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_planandserialize_query_planare experimental and not in production, so the format is replaced now while the change is free.Changelog category (leave one):
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_planandserialize_query_planfeatures), 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 themax_serialized_query_plan_sizeandmax_query_plan_serialization_versionserver settings and thequery_plan_serialization_versionquery setting.Workflow [PR]
Sync PR [sync-upstream/pr/111824]