Skip to content

Fix segfault and silent data corruption when appending a non-appendable format to a file - #112839

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/avro-finalize-null-stream
Aug 1, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/avro-finalize-null-stream

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111164

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes a segfault and silent data corruption when an INSERT into the File engine or the file table function appends to a non-empty file in a format that does not support appending, such as Avro. Writing through a file descriptor or a partitioned path bypassed the existing check, so the format prefix was suppressed and a second header was written after the existing bytes, leaving the file unreadable. Such an INSERT is now rejected with CANNOT_APPEND_TO_FILE, as it already is for a plain path.

Description

ClickHouse declares that some output formats cannot be appended to and enforces that in StorageFile::write, but the check is inside if (!paths.empty()). Writes through a file descriptor never populate paths, and partitioned writes return a sink earlier, so neither reaches it and both let StorageFileSink::initialize suppress the format prefix for a target that already has bytes.

With rows, that appends a second Avro header after the existing data: exit code 0, no diagnostic, and the file no longer reads back. With zero rows nothing binds the Avro encoder to a stream, and close() flushes the encoder before sync() binds it, so the server dereferences a null pointer and dies with SIGSEGV, which is the failure reported on #111164.

The fix moves the format's own append check into StorageFileSink::initialize, next to where the per-sink size is computed and one statement before the prefix is suppressed. That is the only place the authoritative size is known, so it also closes the window between the query-start stat and the per-sink fstat. All four routes now agree, and the error is the code the plain-path route already raises.

Behavior change: on these two routes an INSERT into a non-empty file now fails for Arrow, ArrowStream, JSON, Npy, ORC and Parquet where it previously returned success. Measuring all thirteen non-appendable formats there shows none ever appended: five read back only the original row, discarding the appended one, Parquet fails a column read, and the rest already errored. The documented promise never held here, so this is a bug fix rather than a backward incompatible change. Both escape-hatch settings are unaffected, and the File engine documentation is qualified in the same commit.

The reported CI query was path-based and fuzzer-mutated, while the deterministic reproducer is descriptor-based; both reach the same state.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111164&sha=1ddf512de11b00b3261684cb133ea3ab93ed2763&name_0=PR&name_1=Stress+test+%28arm_asan_ubsan%29

Version info

  • Merged into: 26.8.1.597 (included in 26.8 and later)
  • Backported to: 26.7.2.56, 26.6.2.142, 26.5.6.105, 26.3.17.100, 25.8.29.43

groeneai and others added 2 commits July 31, 2026 21:25
…geFileSink

A format that registers markFormatHasNoAppendSupport cannot be appended to, and
StorageFile::write enforces that. The check lives inside if (!paths.empty()), so
two routes into StorageFileSink never reach it: a write through a file descriptor
never populates paths, and a partitioned write returns its sink before the check.
Both then let StorageFileSink::initialize suppress the format prefix for a target
that already has bytes.

With rows that appends a second Avro header after the existing data, so the query
succeeds with no diagnostic and the resulting file no longer reads back. With zero
rows nothing calls DataFileWriterBase::syncIfNeeded, which is the only thing that
binds the encoder to a stream; DataFileWriterBase::sync then flushes the encoder as
its first statement and binds the stream one line later, so StreamWriter::out_ is
still the default nullptr and the server dies with SIGSEGV. The second one is the
failure reported on ClickHouse#111164.

Ask the format's own append-support checker in StorageFileSink::initialize, where
the authoritative per-sink size is computed and one statement before the prefix is
suppressed. That covers both symptoms and both uncovered routes, and it also closes
the window between the query-start stat in StorageFile::write and the per-sink
fstat. Adding syncIfNeeded to AvroRowOutputFormat::finalizeImpl was tried first and
rejected on measurement: it stops the fault but still writes an unreadable file, so
it trades a loud failure for silent corruption.

On these two routes an INSERT into a non-empty file now fails for Arrow,
ArrowStream, JSON, Npy, ORC and Parquet where it previously returned success.
Measuring all thirteen always-non-appendable formats there shows none of them ever
appended: five read back only the original row and silently discard the appended
one, Parquet fails a column read, and the rest already errored. The File engine
documentation is qualified accordingly in the same commit.
…ed checker

Review round 1 on the StorageFileSink no-append guard.

The documentation sentence added with the guard advised the
`engine_file_truncate_on_insert` and `engine_file_allow_create_multiple_files`
settings unconditionally, but neither setting applies on the file-descriptor
route: `StorageFileSink::initialize` builds a `WriteBufferFromFileDescriptor`
without consulting `flags`, and the multiple-files branch rewrites `paths`,
which is empty there. The guard's own error message already omits that advice
for this reason, so the two artifacts contradicted each other about the
behaviour this change introduces. The sentence is now scoped to a plain file
path and states why the descriptor route is different.

The settings-dependent-checker test cell only drove the checker's appendable
branch, where a guard keyed on a hardcoded format list and no guard at all both
succeed, so the cell could not distinguish them; removing the guard left it
green. It now also asserts the non-appendable configuration is rejected, which
fails under both bypasses and proves the per-statement setting reaches the
checker through `getFormatSettings`.

The test number moved from 04660 to 04668: 04660 was free on master when the
test was written but is now claimed by other unpublished work and by an open
pull request.

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

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent review rounds ran against this change before it was opened: an
independent cold reading of the resulting code, and a separate second-model pass. Round 1
found one blocker and one major and sent the change back; round 2 found no blocker and no
major. Totals across both rounds: 4 findings agreed and fixed, 1 dropped, 2 recorded as
non-blocking, 0 overridden.

Fixed before opening

❌ The documentation sentence gave route-invalid remediation advice (blocker, round 1).
The sentence added with the guard advised engine_file_truncate_on_insert and
engine_file_allow_create_multiple_files unconditionally, but neither applies on the
file-descriptor route: StorageFileSink::initialize builds a WriteBufferFromFileDescriptor
without consulting flags, and the multiple-files branch rewrites paths, which is empty
there. The guard's own error message already omits that advice for exactly this reason, so
the two artifacts contradicted each other about the behavior this change introduces. The
sentence is now scoped to a plain file path and states why the descriptor route differs.
Route table verified from source: plain path both settings live; partitioned truncate live
but multiple-files bypassed (the sink returns thirty lines before that branch); descriptor
both inert.

❌ The settings-dependent-checker test cell could not distinguish the fix from two
bypasses
(major, round 1). It drove only the appendable branch of the CustomSeparated
checker, where a guard keyed on a hardcoded format list and no guard at all both succeed;
removing the guard left the cell green. It now also asserts the non-appendable configuration
is rejected, which fails under both bypasses and proves the per-statement setting reaches the
checker through getFormatSettings. Confirmed on a real pre-guard binary rather than only by
mutation: five assertion arms move (both reported symptoms, the partitioned route, Parquet,
and the new non-appendable CustomSeparated arm) while five stay identical, and those five
are deliberate must-not-regress controls asserting values rather than mere success.

⚠️ Comment style in the guard (round 1) and a link that did not render (round 1).
StorageFile::write() became `StorageFile::write` per the repository convention that
function names are written without parentheses and inside inline code. The Related: line had
been left inside the leading HTML comment, so it did not render; it is now a visible line.

Verified and recorded, not blocking

⚠️ Literal names in the new test's comments are not all wrapped in inline code
(round 2). Avro, TableFunctionFile and getApplicationType should be backticked, and the
last is written with parentheses. The finding is correct and the underlying convention is
binding; the comments' factual content was checked and is accurate, so only the formatting is
affected. It is disclosed rather than fixed because the round that found it had no substantive
finding to accompany it, and it originated in the review scope of the previous round rather
than in the implementation. Happy to reformat those three comment lines on request.

💡 The new test's number shares its five-digit prefix with other in-flight work. Measured
before deciding it was harmless: the style check accumulates test numbers into a set and only
rejects gaps of 100 or more, so it reports no gaps here; prefix reuse is the norm on master,
where 2167 of 3676 five-digit prefixes carry more than one distinct test name and one carries
115; there are no duplicate filenames; and the test runner does not key on the prefix.

Dropped

The documentation sentence names six formats with "such as" rather than all thirteen
non-appendable ones, which is illustrative and correct. A line-length observation about the
same sentence has no convention behind it.

What was checked beyond the findings

The invariant carrier set was enumerated independently and is closed: doNotWritePrefix has
exactly one call site in the tree, the guard sits directly above it, and StorageFileSink has
three construction sites all funnelling through initialize. No object-storage sink suppresses
a format prefix. Three risks the new throw could have carried were each checked and are clean:
format_name == "Distributed" is rejected before both sink paths so the append check can never
see an unregistered format; WriteBuffer's destructor suppresses its assertion while an
exception is in flight, and the descriptor is owned by the caller, so nothing leaks on the
throw path; and the guard only fires when the target already has bytes, so no stray file is
created. All three existing tests asserting CANNOT_APPEND_TO_FILE exercise the plain-path
route, which already raised that error, and assert the error code rather than the message, so
none of them moves.

Session id: cron:clickhouse-review-slot-10:20260731-233800

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. printf 'PREBYTES' > t.avro then clickhouse local -q "INSERT INTO FUNCTION file(3, 'Avro', 'c0 UInt8') SELECT 1 WHERE 0" 3>>t.avro gives rc=139, Address: NULL pointer, Received signal 11, with frames avro::StreamWriter::flush / BinaryEncoder::flush / DataFileWriterBase::{sync,close,flush} / IOutputFormat::finalizeUnlocked / StorageFileSink::finalizeBuffers matching the CI stack. Dropping WHERE 0 gives the other symptom: rc=0, 155-byte file, readback Code 636 "Magic does not match". Not a low-probability flake.
b Root cause explained? YES. The format's no-append contract is enforced in StorageFile::write inside if (!paths.empty()), so the file-descriptor route (never populates paths) and the partitioned route (returns a sink earlier) both let StorageFileSink::initialize suppress the format prefix for a target that already has bytes. With rows that writes a second Avro header after the existing data; with zero rows nothing calls DataFileWriterBase::syncIfNeeded, and sync() flushes the encoder before it binds the stream, so StreamWriter::out_ is still the default nullptr.
c Fix matches root cause? YES. The check is placed in StorageFileSink::initialize where the authoritative per-sink size is computed, one statement before the prefix is suppressed, so it covers both symptoms and both uncovered routes and closes the query-start-stat vs per-sink-fstat window. The narrower alternative (adding syncIfNeeded() to AvroRowOutputFormat::finalizeImpl) was built and measured: it stops the segfault but still produces an unreadable file, i.e. it converts a loud failure into silent corruption. Rejected.
d Test intent preserved / new tests added? YES. No existing test weakened or removed. New 04668_file_sink_no_append_format.sh ships 9 cells / 10 assertion arms: both reported symptoms, the partitioned route, Parquet, an empty-target control, an append-capable format, both escape-hatch settings, and a settings-dependent CustomSeparated configuration in both directions. Mutation-verified non-vacuous (see e).
e Both directions demonstrated? YES. Baseline built from the same worktree with only the guard reverted (source md5 back to the pristine value), SELECT lower(buildId()) asserted equal to readelf -n per arm. Before: rc=139 null deref / rc=0 unreadable 155-byte file / partitioned 147 -> 294 bytes unreadable. After: CANNOT_APPEND_TO_FILE with the target byte-for-byte untouched, and the first partition intact and readable. Mutation check: removing the guard and rebuilding (Build ID moved) reddens exactly cells 1, 2, 5, 6 and the non-appendable CustomSeparated arm of cell 9, and leaves 3, 4, 7, 8 and the appendable arm of cell 9 green; restoring it relinks bit-identically.
f Fix is general across code paths? YES. Invariant: a StorageFileSink never suppresses the format prefix for a format that declared it does not support appends. doNotWritePrefix() has exactly one call site in the tree and the guard sits directly above it, so all four routes into the sink now agree and no other storage can reach the suppressed-prefix state. StorageObjectStorageSink and friends never suppress a prefix. Of the 9 output formats overriding both writePrefix and finalizeImpl, Avro is the only one holding a lazily-stream-bound third-party encoder; driving all 13 non-appendable formats through the crashing shape confirms only Avro faults.
g Fix generalizes across inputs (params/datatypes/wrappers)? YES. The guard asks the format's own append-support checker rather than matching a format name, so it covers all 13 always-non-appendable formats and consults the 2 settings-dependent ones correctly in both directions. Pinned in the test: Avro with zero rows and with rows, Parquet, the partitioned route, JSONEachRow (still appends), an appendable CustomSeparated configuration (still appends), and the empty-target boundary (still written and readable).
h Backward compatible? No setting, serialization format or protocol change, so no SettingsChangesHistory.cpp entry. The deliberate behavior change is that Arrow, ArrowStream, JSON, Npy, ORC and Parquet now report an error on these two routes instead of returning success; measurement shows none of the 13 ever appended successfully there (five silently discarded the appended row, Parquet failed a column read, the rest already errored), so the documented promise was never load-bearing. Both documented escape hatches are measured unaffected, and the File engine documentation is qualified in the same commit.
i Invariants and contracts preserved? YES. The throw happens in initialize() from the constructor, before write_buf and writer are assigned, so no half-constructed sink can exist; ~StorageFileSink only cancels a cancelled sink and finalizeBuffers returns early on !writer. The local WriteBufferFromFile is a unique_ptr and unwinds; on the descriptor route the fd is owned by the caller and is not closed. Measured: the target file is untouched in every rejecting arm, and the partitioned route leaves the already-written first partition intact and readable.

Regression sweep: 180 selected tests exercising File-engine writes, both arms built from the same worktree with only the guard reverted, identical selection and settings. Both arms ran the same 181 test instances (ran_only_in_base and ran_only_in_fix both empty): 0 regressions, 1 improvement (this PR's own new test), 33 failures shared by both arms and environmental for a bare local server. Randomized 50/50 on the new test: 50 OK / 0 FAIL, no tag needed beyond no-fasttest.

Session id: cron:clickhouse-review-slot-10:20260731-233800

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @vitlibar, could you review this? The format's no-append contract is enforced in StorageFile::write inside if (!paths.empty()), so a write through a file descriptor and a partitioned write both skip it and let StorageFileSink::initialize suppress the format prefix on a file that already has bytes, which segfaults with zero rows and writes a second Avro header with rows; this moves the check into the sink where the per-sink size is known.

@PedroTadim PedroTadim self-assigned this Aug 1, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 11:02
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ad0aa7]

Summary: ✅


AI Review

Summary

This PR moves the non-appendable-format guard from StorageFile::write into StorageFileSink::initialize, which closes the file-descriptor and partitioned-write gaps that previously allowed either a second format header to be appended or the Avro zero-row null dereference. I reviewed the current diff, the surrounding StorageFile sink construction and append-check paths, the prior PR discussion, and the current all-green CI reports, and I did not find any remaining blocker or major issue in the head revision.

Final Verdict

✅ No new findings. The fix, regression coverage, and changelog metadata are consistent with the user-visible behavior change.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 1, 2026
@PedroTadim PedroTadim added pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Aug 1, 2026
Merged via the queue into ClickHouse:master with commit d8a2732 Aug 1, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 1, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 1, 2026
…n appending a non-appendable format to a file
clickhouse-gh Bot added a commit that referenced this pull request Aug 1, 2026
Backport #112839 to 26.7: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Backport #112839 to 26.6: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Cherry pick #112839 to 26.5: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Cherry pick #112839 to 26.3: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Cherry pick #112839 to 25.8: Fix segfault and silent data corruption when appending a non-appendable format to a file
robot-clickhouse added a commit that referenced this pull request Aug 2, 2026
…n appending a non-appendable format to a file
robot-clickhouse added a commit that referenced this pull request Aug 2, 2026
…n appending a non-appendable format to a file
robot-clickhouse added a commit that referenced this pull request Aug 2, 2026
…n appending a non-appendable format to a file
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 2, 2026
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Backport #112839 to 26.3: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Backport #112839 to 25.8: Fix segfault and silent data corruption when appending a non-appendable format to a file
PedroTadim added a commit that referenced this pull request Aug 2, 2026
Backport #112839 to 26.5: Fix segfault and silent data corruption when appending a non-appendable format to a file
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
…uption when appending a non-appendable format to a file
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
PROTO: File/file() append in a non-appendable format (fd or partitioned path) -> crash plus corruption.
Effect in the production build a394e92: its upstream test(s) 04668_file_sink_no_append_format fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04668_file_sink_no_append_format.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants