Skip to content

Fix server abort on a corrupt ORC stripe footer - #114924

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:orc-protobuf-stream-contract
Aug 17, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:orc-protobuf-stream-contract

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Closes: #114674
Related: ClickHouse/orc#25

Reading a corrupt ORC blob aborts a debug or sanitizer server instead of raising
INCORRECT_DATA:

generated_message_tctable_lite.cc:228] Check failed: VerifyHasBitConsistency(msg, table) is OK
(INTERNAL: Has bits mismatch for Type=orc.proto.StripeFooter Field=1

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted),
report),
and reproduced on pristine master with default settings by
SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('4f524311...524317')), so any
user-supplied ORC bytes reach it.

Root cause. ORC's DecompressionStream throws where protobuf's
ZeroCopyInputStream::Next contract requires a false return, so the exception originates
inside protobuf's parse loop. TcParser keeps has-bits in a register-cached local and writes
them back only on its own exit paths, so the unwind skips that write-back and leaves
StripeFooter with the repeated field streams appended to and its has-bit clear. Since
the v35.1 protobuf bump the generated destructor checks that invariant, so destroying it
aborts. DebugHardenCheckHasBitConsistency() gates it on !NDEBUG or a sanitizer, so
release builds are unaffected, hence a CI fix.

Change. A submodule bump only. ORC's parse boundary now wraps the caller's stream in an
adapter that captures anything escaping Next/BackUp/Skip/ByteCount, returns the
contract's failure value, and rethrows the original exception once the parser has returned
consistent. One header covers all nine parseProtobufFromStream call sites, including
embedder streams such as ClickHouse's ORCInputStream.

Validation. The blob aborts (RC 134) before the change and afterwards reports
Code: 117 ... Read past EOF in DecompressionStream::readBuffer ... (INCORRECT_DATA),
byte-identical to master release today, so no user-visible message or code changes. New test
04856_orc_corrupt_stripe_footer passes 50/50 randomized and fails on the unfixed binary
with the has-bits tokens. A 183-case corruption sweep and the full orc suite show no
behaviour change.

ProtobufZeroCopyInputStreamFromReadBuffer (Prometheus remote-write) has the same shape,
but is unreported and I could not reproduce a failure there, so it is untouched.

Reading a corrupt ORC blob aborted debug and sanitizer builds instead of raising
INCORRECT_DATA:

  Check failed: VerifyHasBitConsistency(msg, table) is OK
  (INTERNAL: Has bits mismatch for Type=orc.proto.StripeFooter Field=1

ORC's DecompressionStream throws where protobuf's ZeroCopyInputStream contract
requires a false return, so the exception unwinds through the parser and skips
its has-bits write-back. The message is left with a repeated field appended to
and its has-bit clear, and since the protobuf v35.1 bump the generated
destructor checks that invariant, so destroying the message aborts. Release
builds already reported the error correctly because the assertion is compiled
out there.

The submodule bump makes ORC's protobuf parse boundary honour the stream
contract: exceptions are captured, the parser is allowed to finish and leave the
message consistent, and the original error is rethrown afterwards. The reported
message and error code are unchanged.

Reachable from any user-supplied ORC bytes: format(), file(), s3(), url(), and
ORC-backed Iceberg or DeltaLake.
ORC's DecompressionStream throws where protobuf's ZeroCopyInputStream::Next
contract requires returning false, so the exception unwinds through TcParser and
skips its has-bits write-back. StripeFooter is left with the repeated field
"streams" appended to and its has-bit clear, and since the protobuf v35.1 bump the
generated destructor verifies that invariant, so tearing the message down aborts a
debug or sanitizer server instead of raising INCORRECT_DATA.

ClickHouse/orc#25 wraps the caller's stream at ORC's parse boundary so exceptions
are captured, the contract's failure value is returned, and the original exception
is rethrown once the parser has returned consistent.

Found by the AST fuzzer (STID 3257-29d9). Related: ClickHouse#114674
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, all findings resolved)

Two independent review rounds plus an adversarial second-model gate. Adjudicated: 7 agreed
and fixed, 0 disagreed, 3 dropped on measurement.

❌ Gitlink was on a PR-scoped ref only (blocker, raised in both rounds) - the pin was
c73cb90e, advertised solely as refs/pull/25/head, which is not a branch and disappears
if the PR ref is pruned. Fixed: repointed at the merge commit
6a2fe65eb16ce4c760964dca619260226c1b418e. Verified by measurement, not assumption - a
throwaway clone advertises it as refs/heads/ClickHouse/2.3.1, and a fresh empty repo
fetching that exact SHA succeeds and yields tree ea5c0f75, i.e. the tree the first round
reviewed, with the wrapper present. 8ca5eeed...6a2fe65e is ahead_by=2, behind_by=0
touching one file, so the bump carries nothing but this fix.

⚠️ Relationship links were shorthand - Related: #114674 neither used the full URLs the
PR template asks for nor auto-closed the issue this change actually fixes. Now
Closes: the issue and Related: the ORC PR, as full URLs on separate lines. Issue 114674
was checked to be a single-STID CI matcher issue with the identical
CheckHasBitConsistency -> StripeFooter::SharedDtor -> getStripeFooter stack, so closing
it is correct rather than merely plausible.

⚠️ "Release builds compile the assertion out" was imprecise - ABSL_CHECK_OK at
generated_message_tctable_lite.cc:228 is unconditional; the gating is at the call site via
if constexpr (DebugHardenCheckHasBitConsistency()), which port.h:357 defines as
!NDEBUG || ADDRESS/MEMORY/THREAD_SANITIZER. So the abort is live in debug and all three
sanitizer builds, and absent only from a plain release build. The body now names the gate so
this is checkable, and it independently confirms the CI Fix or Improvement category.

💡 Carriers enumerated independently before reading the implementer's evidence, and the
lists agree. All nine parseProtobufFromStream call sites route through the patched helper;
the three remaining direct-parse sites (Reader.cc:1560, Reader.cc:1645,
tools/src/FileMetadata.cc:83) are non-carriers because they parse a buffer, not a throwing
stream. The wrapper covers all five ZeroCopyInputStream virtuals: four are overridden, and
ReadCord is deliberately inherited because its base implementation
(zero_copy_stream.cc:30) reaches the stream only through Next()/BackUp(). The
CodedInputStream is scoped so its destructor's BackUp runs before the stored exception is
rethrown.

💡 Test liveness confirmed, not assumed. The grep alternation also matches
Has bits mismatch and Check failure stack trace, so an abort produces extra reference
lines and the test reddens on revert; a mutation arm measured this directly. The control arm
guards ordinary reads. The odd-looking escape inside the hex blob was hand-decoded rather
than tidied: it is the only non-hex byte, decodes deterministically, and both normalized
variants stop reproducing, so those bytes are load-bearing.

💡 Dropped after measurement (looked like problems, were not): the pin being "diverged"
from ORC's main - master's current pin is equally diverged and .gitmodules records no
branch key, so CI fetches the recorded SHA; test number 04856 - free on master, in all open
PRs, and across 950 build trees; and mergeability - merge-tree against current master is
conflict-free and both orc::ParseError -> INCORRECT_DATA handlers still exist verbatim,
so the pinned error message is still what master produces.

Coverage limit, stated rather than glossed over: the automated gate's change map is a
superproject diff, so the 88 lines of ExceptionIsolatingInputStream render as a single
Subproject commit line and were not in its reviewed diff. That C++ was reviewed by reading
contrib/orc at source, and it is in any case already merged upstream as
ClickHouse/orc#25.

Session id: cron:clickhouse-review-slot-8:20260815-022500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT c0 FROM format(ORC, 'c0 DateTime64(3)', unhex('4f524311...524317'))" on a debug build aborts with RC 134 every run, no non-default settings. Also reproduces on an independent debug build of the same base commit.
b Root cause explained? Yes. ORC's DecompressionStream throws (Compression.cc:491, and :589 from BackUp) where ZeroCopyInputStream::Next is contractually required to return false (zero_copy_stream.h:117-129). The exception unwinds through TcParser, skipping SyncHasbits (generated_message_tctable_impl.h:903-921), so StripeFooter keeps streams (field 1) non-empty with its has-bit clear, which VerifyHasBitConsistency rejects (..._lite.cc:134-140). Since the v35.1 bump that check runs from the generated destructor, so the abort fires during unwinding.
c Fix matches root cause? Yes. The contract violation is corrected at the boundary where ORC hands protobuf a stream, not guarded at the crash site. A check after the parse would be dead code: parseProtobufFromStream never returns on this input, and Reader.cc:640 appears in the stack only because that is where the message's destructor runs while unwinding. message->Clear() would also not repair the state, since generated Clear() is itself has-bit gated.
d Test intent preserved / new tests added? New test 04856_orc_corrupt_stripe_footer.sh. No existing test weakened or removed. Parallel-safe (no no-parallel tag), $CLICKHOUSE_TMP/$CLICKHOUSE_DATABASE-scoped, inline unhex() so no binary fixture is added. It asserts the full message text, not just the error code.
e Both directions demonstrated? Yes, same worktree and command, only the binary differs. Pre-fix: RC 134, Has bits mismatch + Check failure stack trace, no Read past EOF. Post-fix: RC 117, Read past EOF in DecompressionStream::readBuffer + INCORRECT_DATA, neither has-bits token. The token sets are disjoint. The new test also fails on the pre-fix binary with exactly that diff.
f Fix is general across code paths? Yes. One wrapper covers all nine parseProtobufFromStream call sites (Reader.cc:542,548,629,825,923,1624,1725,1782, StripeStream.cc:160) and all four stream virtuals, so BackUp/Skip/ByteCount throw sites are covered too, as are embedder-supplied streams such as ClickHouse's ORCInputStream::read. ReadCord is deliberately not overridden: its inherited implementation reaches the wrapped stream only via Next/BackUp, both already guarded.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 183-case corruption sweep (length-preserving XOR runs of 1/8/64 bytes at 61 offsets) over a zstd-compressed 5-column ORC file with Nullable and Array columns, read through a real projection: pre-fix and post-fix agree on all 183, zero aborts. Two earlier sweeps were discarded as vacuous (postscript-only failures; count() answered from metadata), so the final probe is validated rather than assumed.
h Backward compatible? (maintainer-approved exception only) Yes. No settings, no serialization format change, no SettingsChangesHistory.cpp entry, no experimental gate. Post-fix debug output is byte-identical to the current official master release output on the same input, so the error code and message users see are unchanged.
i Invariants and contracts preserved? Yes, the protobuf stream contract is restored rather than bypassed. The inner scope around codedStream is load-bearing: ~CodedInputStream calls BackUp (coded_stream.cc:80-93) and ORC's BackUp throws, so rethrowing before that destructor could swallow a corrupt-input error into a silent wrong result. First exception wins, so the original cause is preserved; ByteCount() has no contract failure value, so it returns the last known count and records the exception.

Session id: cron:clickhouse-impl-slot-4:20260811-133900

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6cb9bb2]

Summary: ✅


AI Review

Summary

This PR bumps contrib/orc to restore protobuf's ZeroCopyInputStream contract for ORC decompression streams and adds a focused stateless regression test for the corrupt StripeFooter case. I did not find a remaining correctness or coverage gap in the current diff: the pinned ORC commit centralizes the fix in parseProtobufFromStream, every runtime file-content protobuf parse in that ORC tree already goes through that helper, and the new test distinguishes the old debug/sanitizer abort from the intended INCORRECT_DATA path.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-ci submodule changed At least one submodule changed in this PR. labels Aug 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix, could you review this? It is a contrib/orc bump plus a regression test: ORC handed protobuf a stream that throws where ZeroCopyInputStream::Next must return false, so the exception unwound through TcParser and skipped its has-bits write-back, leaving StripeFooter inconsistent enough that its own destructor aborts debug and sanitizer builds.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6cb9bb237 with master b04769724 (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
Binary Master PR Δ
programs/clickhouse-stripped 693.40 MiB 690.39 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

9 translation units recompiled, 20 s compile time in total, 6 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/arrow-cmake/__/orc/c++/src/Reader.cc: 6.6 s

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6cb9bb2

CI is fully finished on this head with real coverage: praktika reports top-level OK,
177 leaves, 0 dropped jobs, 153 OK and 24 skipped (every skip carries an explicit
reason: not labeled pr-performance, not a bug-fix PR, reused from cache, not affected
by the changed files). GitHub agrees: 157 success, 20 skipped, 0 failure.

No failed tests, so there is nothing to own.

Check / test Reason Owner / fixing PR
(none) no test failed on this head n/a

One note for the record: CIDB holds a Config Workflow / Pre Hooks FAIL row for this
same SHA at 03:08:44 UTC. That is a superseded first attempt - the 03:23 re-run of
Config Workflow is green end to end (repo unshallow, Pre Hooks, Check CI DB,
Filter not affected jobs, Init Report all OK) and the live check conclusion is
success. It is not an outstanding failure.

Session id: cron:our-pr-ci-monitor:20260815-093000

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 09de2af Aug 17, 2026
356 of 358 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
alexey-milovidov added a commit that referenced this pull request Aug 24, 2026
Edited following .claude/skills/edit-changelog/SKILL.md, by hand on a
workstation: the editing step of the NightlyChangelog job has been failing
its own verification since 2026-08-12, so three raw blocks had accumulated
(47 + 84 + 628 entries).

Of the 759 raw entries, 482 are integrated into the in-progress 26.8 section
and 277 are dropped:

- Section 3: the 300 `NOT FOR CHANGELOG / INSIGNIFICANT` entries are dropped,
  except 41 that describe a user-visible change and are promoted into a real
  category, among them a server abort on a corrupt `ORC` stripe footer
  (#114924), `EXPLAIN ANALYZE` for streaming queries (#112445), `SELECT` from
  `TimeSeries` (#115622), streaming watermarks (#106169), and the
  `clickhouse-local` CORS overrides (#115129).
- Section 2: every revert in the range cancels out inside it, so neither side
  appears. Two are re-applications: #114912 re-applies the
  `accurateCastOrDefault` fix, so #109946 keeps its entry with both links and
  the intervening revert #114911 is gone; #114409 re-applies the PromQL
  streaming plan, recorded on the #113656 entry.
- Section 4: `Build/Testing/Packaging Improvement` keeps the seven entries a
  user, packager or from-source builder notices (musl `getaddrinfo` and
  `sched_getcpu`, signed macOS artifacts, Debian packages for release builds
  only, zstd-compressed Docker layers, `unit_tests_dbms` without the full
  library set, vendored Rust built with optimizations locally) and drops the
  CI plumbing.
- Sections 5 and 6: bare pull request URLs converted to links, settings put
  in backticks, four entries rewritten from developer notes into user-visible
  descriptions, and three moved into `Performance Improvement`.

No entry of a strict-retention category was deleted: the job's own
`verify_edit` passes on this edit.

Not done here, because the release manager does it at release time: the full
significance sort, the aggressive merging of sibling pull requests, and the
`FIXME` release date and presentation links.
@groeneai

Copy link
Copy Markdown
Collaborator Author

This fix is not on the 26.7 and 26.3 release branches. Both still pin contrib/orc at 8ca5eee, the commit this PR bumps from; 26.8 and newer have 6a2fe65.

26.7 has just hit the same abort (orc::getStripeFooter -> ~StripeFooter -> TcParser::CheckHasBitConsistency, STID 3257-29d9) in Stress test (arm_msan): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.7&sha=12c66714e81c89e012ea7ac3d813242a04009610&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_msan%29

26.3 has the same contrib/orc and contrib/google-protobuf pins as 26.7. As on master, the abort fires in debug and sanitizer builds, where protobuf compiles in the has-bit check.

The cherry-pick should apply cleanly: the submodule bump starts from the branches' current pin, ClickHouse/orc#25 changes only c++/src/wrap/coded-stream-wrapper.h, and the test files are new. v26.3-must-backport on this PR would cover both branches.

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Received signal 6 (STID: 3257-29d9)

3 participants