Skip to content

Check the schema of every block a client sends for an external table - #119849

Merged
alexey-milovidov merged 4 commits into
masterfrom
sec-external-table-block-schema
Sep 14, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
sec-external-table-block-schema

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

The schema of a query-local external table is bound once, by the first Native block the client sends for it. TCPHandler::processData did not compare the blocks that follow against that schema, and nothing else does either: the columns of such a block are written to the table as a Chunk, which carries no types at all, and MemorySink::consume labels them with the table header again. A client that declared one type in the first block and another in the second therefore got its data read back as the type named by the header - for AggregateFunction columns, the state of one function read as the state of another.

Every block after the one that bound the schema is now validated against it and rejected with INCORRECT_DATA.

The HTTP multipart path had the same gap in a milder form: ExternalTablesHandler::handlePart looks up _structure / _types by the part name each time and HTMLForm::readMultipart adds plain form fields as it reads them, so a later part with the same name could declare another schema. There the mismatch surfaced as a client-triggerable LOGICAL_ERROR at pipeline connect. Every such part is now checked against the bound schema too and rejected with INCORRECT_DATA. The Native protocol specification documents the invariant.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed the server not validating the schema of the second and subsequent data blocks that a client sends for an external table over the native protocol. Such a block could make the data be interpreted as a type other than the one it was sent as.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.9.1.1488 (included in 26.9 and later)
  • Backported to: 26.8.5.11, 26.7.9.11, 26.6.7.17, 26.3.33.81

The schema of a query-local external table is bound once, by the first Native
block the client sends for it. `TCPHandler::processData` did not compare the
blocks that follow against that schema, and nothing else does either: the columns
of such a block are written to the table as a `Chunk`, which carries no types at
all, and `MemorySink::consume` labels them with the table header again. A client
that declared one type in the first block and another in the second therefore got
its data read back as the type named by the header - a type confusion on data the
client controls, which for `AggregateFunction` columns means the state of one
function being interpreted as the state of another.

Every block after the one that bound the schema is now validated against it and
rejected with `INCORRECT_DATA`.

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

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3fcf2e0]

Summary: ✅


AI Review

Summary

This PR fixes the missing schema validation for repeated external-table uploads on the native TCP and HTTP multipart paths, adds focused regressions for both, and updates the Native protocol spec to document the per-table schema invariant. The two earlier inline concerns on this PR are addressed in the current head, and I did not find a remaining blocker or major issue in the patched code.

Final Verdict

✅ No blocking or major findings on the current PR head.

LLVM Coverage Report

Measured on commit 3fcf2e0.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.40% -0.10%

Changed lines: Changed C/C++ lines covered: 22/22 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 13, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3fcf2e014 with master 7df5d31fe (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

8 translation units recompiled, 26 s compile time in total, 8 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits September 14, 2026 01:58
…block-schema

# Conflicts:
#	src/Server/TCPHandler.cpp
…xternal table

`ExternalTablesHandler::handlePart` looks up the `_structure` / `_types` fields by the part name each time,
and `HTMLForm::readMultipart` adds plain form fields to the parameter set as it reads them, so a later part
with the same name could declare a different schema than the one the first part bound. The data of such a
part reached the already-bound `StorageMemory` table, where the mismatch surfaced only as a `LOGICAL_ERROR`
from the pipeline connect (`Block structure mismatch in function connect between ParallelParsingBlockInputFormat
and MemorySink stream`), i.e. a client-triggerable logical error instead of a data error.

Compare the declared schema of every part after the first with the bound one and reject a mismatch with
`INCORRECT_DATA`, as the Native protocol path now does.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ets in the Native protocol spec

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@mintlify

mintlify Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 14, 2026, 2:40 AM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://github.com/ClickHouse/clickhouse-private/actions/runs/34819722237/job/103902645387 (CH Inc sync PR https://github.com/ClickHouse/clickhouse-private/pull/74720, Stress test (amd_tsan, SharedCatalog, meta in keeper): S3_ERROR "The specified key does not exist" while a fuzzed SELECT reads data.bin of part all_1_1_0 via MergeTreeSelect(pool: PrefetchedReadPool)) and provide a fix in a separate PR. If the fix is already in progress, link it here. This PR only touches the external-table schema check in ExternalTable.cpp / TCPHandler.cpp, so the failure is not caused by it; it looks like the No such key family tracked in #111188, but on the foreground read path.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the foreground MergeTreeSelect(pool: PrefetchedReadPool) read of all_1_1_0/data.bin that failed with S3_ERROR "The specified key does not exist" in that stress run, starting with whether it shares a mechanism with the background-merge read tracked in #111188 or is a distinct foreground one.

I will follow up in this thread with a separate fix PR, or with a link to the existing PR if one turns out to cover this signature.

@groeneai

Copy link
Copy Markdown
Collaborator

Three measurements, and the first one changes the framing.

The pool name is a formatting artifact, not a mechanism. While executing MergeTreeSelect(pool: ..., algorithm: ...) is appended by the executor to any exception escaping IProcessor::work() (src/Processors/Executors/Runtime/ExecutionThreadContext.cpp:78-84; only the cancellation and limit codes are exempt), and the string comes from MergeTreeSelectProcessor::getName() (MergeTreeSelectProcessor.cpp:194-196) plus MergeTreePrefetchedReadPool::getName() (MergeTreePrefetchedReadPool.h:39). Which pool is chosen depends on settings the test runner randomizes (ReadFromMergeTree.cpp:745-778). It records which processor was running, not that prefetching is implicated. Empirically: in one public job the same missing key, belonging to part all_1_1_0, was reported by a SELECT through PrefetchedReadPool, by another SELECT through ReadPoolInOrder, and by MergePlainMergeTreeTask under OPTIMIZE FINAL (report); in a master job the same day, by a fuzzed SELECT through PrefetchedReadPool, four CHECK TABLE runs and the statistics refresh task (report). Foreground versus background is which reader reached an already-deleted object first.

The public carrier of this signature is gone. Over 120 days, 20 CIDB rows carry that addendum. 19 are t_merge_over_stale_packed on cached_s3_encrypted, all between 2026-08-07 and 2026-08-09, and they stop when you converted 04630_merge_over_stale_packed_tmp_dir to an integration test in 808c8255ae4d3. The 20th is 03100_lwu_drop_update_race reading a patch part on cached_s3, 2026-05-19, which is what #111188 was filed for. In the 36 days since, the family has 23 public rows: 20 are the s3_plain_rewritable __root/mutation_N.txt entry (#119154) and 3 are the filesystem-cache background download. None is a foreground read of a part's .bin. Your run is a carrier with no public analogue.

The read side cannot be the defect in this tree. A live SELECT owns the part through MergeTreeSelectProcessor::pool to parts_ranges to MergeTreeReadTaskInfo::data_part_info to an owning DataPartPtr, so grabOldParts skips it (MergeTreeData.cpp:4148). A prefetch cannot outlive that: readers is declared before prefetch_runner, so the runner is destroyed first and calls waitForAllToFinish(), and ~ThreadTask waits on readers_future (MergeTreePrefetchedReadPool.h:78-92).

That leaves the deletion side, which is where your configuration leaves the tree. MetadataStorageType::Keeper is in the enum (DiskType.h:28-38), but MetadataStorageFromKeeper is registered only under #if CLICKHOUSE_CLOUD and CMakeLists.txt:26 sets that to 0; MetadataStorages/Keeper/ and src/Storages/SharedMergeTree/ do not exist here. Blob retention on that path is the _blob_manager/refcount Keeper subtree, of which only the metric declaration is public (CurrentMetrics.cpp:458). One concrete thing to check there: MergeTreeReadTask.h:98-103 says stateless-worker parts use BorrowedMergeTreeDataPartInfoForReader, a non-owning variant absent from this tree, and non-owning part info is exactly what would break the ownership chain above.

I cannot read the run. The private repo, that run, that job and PR 74720 all return 404 for my token, and the public CH Inc sync status carries no report URL. What decides it is that key's lifecycle in the job's clickhouse-server.*.log: the Writing blob for path line naming the original owner, the deleteFileFromS3: Objects with paths [...] were removed from S3 line, and the thread that issued it. Paste those, or attach no_such_key_errors.txt, and I will attribute it and open the fix.

On whether a fix is already in progress, nothing open covers this signature. #119154 covers the s3_plain_rewritable mutation entry, #113454 a part-destruction read of packed index marks, #114180 a transient not-found at part load. #114046 was the fix I opened for #111188 at your request on #110321; it applies to local metadata only, so it cannot be this one, and it is closed as not needed with my clarifying question unanswered, so tell me if you want it revived.

One offer rather than an unsolicited PR: the harness records the matched line in no_such_key_errors.txt but not the blob's lifecycle, which is why every occurrence in this family costs a manual log read and why this one is opaque to me. I can make that check also emit the Writing blob and deleteFileFromS3 lines for each matched key, so future occurrences arrive attributed, including on runs I cannot read.

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d28c419e-d0ca-4331-9dd0-0b979be65fc3
  • MIRAI run: 3c5c0510-fb98-4600-a409-5749af056143
  • PR check IDs:
    • clickbench_145909_1789390647
    • clickbench_145915_1789390647
    • clickbench_145921_1789390647
    • tpch_adapted_1_official_145932_1789390647
    • tpch_adapted_1_official_145944_1789390647
    • tpch_adapted_1_official_145980_1789390647

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks for the analysis. What I can add from the private side:

Same head, different result. The private sync PR head is unchanged (86d4ba57). The job you were asked about (run 34819722237, Stress test (amd_tsan, SharedCatalog, meta in keeper)) failed once; the re-run of the whole workflow on the identical commit (run 34834414657) passed that job. The second run has two other red jobs that were green in the first run on the same commit (Integration tests (amd_asan_ubsan, db disk, 4/8): two test_shared_merge_tree_backup_from_snapshot lock-progress assertions; Stress test (amd_msan, meta in keeper): hung check on a server-side ASTFuzzer INSERT ... SELECT into a JSON table, writer thread still inside SerializationObject → SerializationDynamic → SerializationVariant under MSan after 1146 s, is_cancelled = 1). None of the three is deterministic, and none touches the external-table code.

What the harness recorded for the key. The only line the job kept is the no_such_key_errors.txt match, verbatim:

[ 22611 ] {0420b56d-b5ac-4336-977b-6c7b1b2d59c5} <Trace> ASTFuzzer: Fuzzed query failed: Code: 499. DB::Exception: The specified key does not exist. This error happened for S3 disk: while reading key: test/hbh/jgrvazoaycbynltbyvlekbwkxfdvg, from bucket: test: While reading or decompressing data.bin (position: 2172110, typename: DB::ReadBufferFromFileView, compressed data header: 399f28b325cfc71395532142efacefec820e00000004000000): (while reading column a): (attempt to read data part all_1_1_0 (state Active) failed with error. It can mean that some retryable error happened, or data is corrupted. Please retry the query: While reading part all_1_1_0: While executing MergeTreeSelect(pool: PrefetchedReadPool, algorithm: Thread). (S3_ERROR)

I cannot give you the Writing blob for path / deleteFileFromS3 lines for test/hbh/jgrvazoaycbynltbyvlekbwkxfdvg: the server logs live only in the private report bucket (anonymous access is 401), and the report directory is keyed by PR + sha, so the same-commit re-run overwrote the failed job's artifacts with the passing ones. The lifecycle of that key is gone.

Harness improvement: yes, please. Emitting the Writing blob and deleteFileFromS3 lines for each matched key next to the no_such_key_errors.txt match is exactly what would have made this attributable. Open it as a separate PR.

#114046: agreed that it cannot be this signature (local metadata only); no need to revive it for this one.

No action on this PR: the public CI is 159 green / 0 red, and the private reds are flakes on an unchanged commit. I will re-run the failed private jobs once that workflow finishes.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am opening a separate PR that emits, next to each Code: 499 ... The specified key does not exist match, the Writing blob for path and deleteFileFromS3 lines for that same key, so the artifact carries the object's lifecycle instead of only the failing read. I will cover both sites that run that grep today: tests/docker_scripts/stress_tests.lib (the one that writes the no_such_key_errors.txt you quoted) and the Lost s3 keys check in ci/jobs/scripts/clickhouse_proc.py, which prints its matches without keeping a file. I will link the PR in this thread.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of the CH Inc sync check on this pass (private sync PR https://github.com/ClickHouse/clickhouse-private/pull/74720, head 86d4ba57 unchanged, run 34834414657 still in progress): it reports tests failed (4 new, 1 known). All of them are outside this PR's code (the external-table schema check in ExternalTable.cpp / TCPHandler.cpp):

@groeneai, thanks for taking the harness improvement, nothing else is needed from you for this PR. I will re-run the failed private jobs once the workflow completes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The separate fix for 05153_clear_column_stale_materialized_warning is #119989.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 14, 2026
Merged via the queue into master with commit 0271f28 Sep 14, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the sec-external-table-block-schema branch September 14, 2026 19:14
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 14, 2026
…terialized_warning` by time

The test checked for the stale `MATERIALIZED` warning with a `SELECT` over `system.text_log`
filtered only by `logger_name`. In a long parallel run the table grows past the 20M-row
`max_rows_to_read` limit of the test profile, and the query fails with `TOO_MANY_ROWS`
(seen in the `CH Inc sync` run of ClickHouse#119849:
`Stateless tests (amd_release, distributed cache, meta in keeper, s3 storage, parallel)`).
Add the `event_date` / `event_time` bound that the other `text_log` tests use, so the scan
goes through the primary key.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
ei-grad added a commit to ei-grad/ClickHouse that referenced this pull request Sep 14, 2026
Integrate upstream through 360a086 while preserving the existing
profiler changes. Resolve the protocol documentation overlap by retaining
the external-table schema validation guarantee and the rule that
`ProfileTraces` delivery waits for the upload terminator.

The five overlapping C++ files preserve the previous profiler diff.
The external-table schema guard remains before storage writes, and early
upload exceptions still discard queued traces before the terminal response.

Related: ClickHouse#118415
Related: ClickHouse#119849

Co-Authored-By: Codex CLI <[email protected]>
robot-ch-test-poll3 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #119849 to 26.6: Check the schema of every block a client sends for an external table
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #119849 to 26.3: Check the schema of every block a client sends for an external table
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #119849 to 26.8: Check the schema of every block a client sends for an external table
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 14, 2026
Cherry pick #119849 to 26.7: Check the schema of every block a client sends for an external table
robot-clickhouse added a commit that referenced this pull request Sep 14, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

#120101

Both sites covered. Each matched key now gets its Writing blob for path and deleteFileFromS3 lines under its own header in timestamp order, from one grep -F pass over the same logs; a key with nothing to show says so rather than going blank. Grouping requires a delimited occurrence of the key, which matters on the path-keyed families (s3_plain, s3_plain_rewritable) where the key is the local path, so a part directory does not collect the lines of the objects below it.

One thing found on the way: the Lost s3 keys check was losing most of its own output. tee /dev/stderr | grep -q . exits at its first line, so tee takes SIGPIPE and the tail never reaches the report: on a 133,848-byte match set only 28,200 bytes arrived. That site now writes the matches to a file and cats it, with the emptiness test as the verdict.

clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #119849 to 26.8: Check the schema of every block a client sends for an external table
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #119849 to 26.7: Check the schema of every block a client sends for an external table
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #119849 to 26.6: Check the schema of every block a client sends for an external table
alexey-milovidov added a commit that referenced this pull request Sep 15, 2026
Backport #119849 to 26.3: Check the schema of every block a client sends for an external table
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 19, 2026
A `Code: 499 ... The specified key does not exist` red records only the failing
read: `no_such_key_errors.txt` holds the matched error line and nothing else, so
the artifact names the victim and never the culprit. It does not say when the
object was written, whether it was deleted, by which thread, or whether the
delete was a batch removal. By the time the question is asked the server logs
are usually gone, and the investigation dead-ends on lines that were in the log
at the time.

Those lines are in the same logs, keyed by the same string.
`ReadBufferFromS3::key` is `splitBucketAndKey(remote_path).second`, which for a
non-qualified path returns `remote_path` verbatim, and that is also the key that
`Writing blob for path` and `deleteFileFromS3` print. They were simply never
selected.

`ci/jobs/scripts/s3_key_lifecycle.py` extracts each matched key with
`while reading key: (...)`, makes one `grep -F` pass over the enumerated logs
for all keys at once, and prints each key's lines under its own header in
timestamp order (grep reports one file at a time, so file order is not time
order and an upload would otherwise print after the delete that followed it).
Lines are kept by logger name rather than by message wording, so rewording a log
message cannot silently empty the report. A key with nothing to show says so:
an empty report and "no lifecycle exists" must not look alike. Every distinct
key always gets a header and only the per-key line expansion is capped, so no
key can vanish from the largest incident, which is the one worth attributing.

Both harness sites that run the grep call it. Note that `no_such_key_command`
in `clickhouse_proc.py` is fed to TWO `Result` rows, `Lost s3 keys` and
`S3_ERROR No such key thrown (in clickhouse-server.log or
clickhouse-server.err.log)`, so the single edit moves both.

The verdicts are unchanged. The appender's status is discarded and the group's
status comes from the trailing `echo`, so a failed collection cannot turn a real
failure into `No lost s3 keys`; it leaves a marker in the artifact instead. Both
row texts are left alone deliberately, because those strings are the CIDB
`test_name`s and renaming them would break every query keyed on the signature.

Replacing `tee /dev/stderr | grep -q .` with `cat >&2` plus an explicit
emptiness test also repairs a pre-existing truncation of those two rows' `info`:
`grep -q` exits on its first line, so `tee` takes SIGPIPE and the copy to stderr
is cut off once the content grows. Measured on a 133,848-byte report, the old
shape delivered 28,200 bytes and the new one delivers all of it. The appended
section sits at the end, which is exactly the part that was being lost.

Commissioned in
ClickHouse#119849 (comment)

This branch was successfully deployed

1 active deployment
staging - docs — 3fcf2e01 Deployed Sep 14, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

5 participants