Repository navigation
Conversation
…mpty `countResample(begin, end, step)` with `end < begin` is a legal function: the constructor takes the `end < begin` branch and sets `total = 0` without throwing. Then `sizeOfData()` is `mulOverflow(0, size_of_data)` = 0 and `serialize` loops `total` times, so such a state writes no bytes at all and a hundred rows of it occupy zero bytes in a part. `SerializationAggregateFunction::deserializeBinaryBulk` stops on `istr.eof()`, which for that column is already true before the first iteration, so it appends zero rows and reports success. The desync surfaces far away: `SerializationVariant` finds a sub-column of size 0 where the discriminators promise 100 and throws `Size of variant ... is expected to be not less than 100 according to discriminators, but it is 0`, `MergeTreeReaderCompact` rejects the short read with `CANNOT_READ_ALL_DATA`, and `Log` returns nothing. A background merge performs the same read, so a table that received such a value is unreadable and unmergeable for good. The leaf cannot honour `limit` unconditionally. `limit` is documented as an upper bound, "Read no more than limit values", and `TinyLog` relies on that: it has no marks file, keeps `row_limit` at the maximum of `size_t`, passes `min(block_size, ...)` and terminates on a short read, so reconstructing `limit` states there would invent rows that are not on disk. An exact count is not automatically a trustworthy one either: `NativeReader` knows the count exactly, but it comes from a block header bounded only by `DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS`, and `clickhouse-client` sets no memory limit by default, so reconstructing from it would let a small input allocate without bound. Two things must therefore both hold. `number_of_rows_is_exact` says the caller's row count is exact and comes from data the server itself wrote: the two MergeTree readers set it, `LogSource` sets it only when a marks file exists, and `NativeReader` deliberately does not. `serializedStateIsEmpty()` is a declared property of the function rather than something measured by running it, true for `Resample` over an empty range and forwarded by the combinators whose `serialize` is exactly the nested call. Measuring it instead would be unbounded in both directions: `nothingResample(0, 1048576, 1)` also has `sizeOfData() == 0` yet writes a megabyte per state, and a read-side probe would need a `catch` around an error that nothing downstream can re-raise. Two combinators reach an empty state by a route that is not a bare forward. `-Tuple` lays the nested states out back to back with no framing of its own, so a tuple of empty ranges is empty; `countResampleTuple` needs each *argument* to be a `Tuple` and hands element i of each to nested function i, which is why an earlier probe of it read as unconstructible. The `Null` combinator consults `getOwnNullAdapter` before its own variadic default, and `AggregateFunctionIf` returns the `<false, false>` adapter whenever the result cannot be inside `Nullable`, as an `Array` cannot; there `prefix_size` is 0 and `getFlag` is the literal `true`, so `serialize` writes exactly the nested bytes. The `!serialize_flag` guard keeps the instantiations that do write a flag byte out of this, which is the whole difference between a state of no size and a state of no bytes. `AggregateFunctionNothing` is the counterexample that shapes the guard. Its `sizeOfData()` is 0 while `serialize` writes one byte, so keying on the size alone would lose its `eof` stop and turn the existing case in 05055 that declares a billion rows of it into an eight gigabyte allocation. `Log` also decided whether it held any rows from the size of its first data file, which such a column leaves at zero bytes while `__marks.mrk` records its rows, so a table whose first or only column is one read as empty however the states were deserialized. The marks are what answer that for `Log`; `TinyLog` has none and can only look at the size, so it keeps the old test. A `Native` file holding such a column still fails with `CANNOT_READ_ALL_DATA`, for the reason above. The TCP wire is unaffected, because the protocol bytes that follow a block keep the stream from ending. This is not a regression of a9bbf03, which only moved the `eof` stop into a block loop: `createAndDeserializeBatch` has carried it since 96bb781, and the inline loop before that had it too. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 passes; 5 blockers and majors in
Severity: ❌ blocker / Not in this change, and disclosed rather than promised: Session id: cron:clickhouse-review-slot-10:20260912-220600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260912-212000 |
|
Workflow [PR], commit [ea951d4] Summary: ❌
AI ReviewSummaryThis PR fixes deserialization of zero-byte aggregate-function states by letting trusted Findings❌ Blockers
Tests
Final VerdictChanges requested: fix the remaining LLVM Coverage ReportMeasured on commit ea951d4.
Changed lines: Changed C/C++ lines covered: 59/66 (89.39%) · Uncovered code |
| /// A column can legitimately occupy no bytes (an aggregate state that serializes to nothing), so | ||
| /// for `Log` the marks are what say whether there are rows; `TinyLog` has none and can only look | ||
| /// at the size of the data. | ||
| const bool no_rows = !num_data_files |
There was a problem hiding this comment.
StorageLog::createReadingPipe now correctly uses marks instead of the first data file's size, but StorageLog::backupData still returns early on !file_checker.getFileSize(data_files[INDEX_WITH_REAL_ROW_COUNT].path) at src/Storages/StorageLog.cpp:1252. For a non-empty ENGINE = Log table whose first or only column is one of these zero-byte aggregate states, SELECT starts working again after this patch but BACKUP still writes no table data and restore loses every row. Can we switch backupData to the same marks-based emptiness check as here, using the file-size proxy only for TinyLog?
There was a problem hiding this comment.
Confirmed, and reproduced independently on plain master without this patch, so it does not depend on the read fix: with the zero-byte column as the only data file, BACKUP writes the metadata and no data/ directory at all, BACKUP_CREATED and RESTORED both report success, CHECK TABLE passes, and the restored table holds 0 of the 100 rows.
The marks-based check is the right shape for that half, and so is keeping the size proxy for TinyLog, which has no row count on disk and must not invent rows. It is not the whole fix, though. When the zero-byte column is not the first data file, the proxy already passes today, yet the 0-byte .bin is still missing after a restore and any query touching that column fails with Code: 107 ... FILE_DOESNT_EXIST. The second site is BackupImpl::copyFileToDisk, where an entry of size zero is materialised only under WriteMode::Rewrite (src/Backups/BackupImpl.cpp:1399-1402), while Append falls through creating nothing, and Append is the mode both StorageLog and StorageStripeLog restore with (StorageStripeLog.cpp:734). TinyLog reproduces that half too, which is why I would fix it at the shared backup layer rather than inside Log. Changing backupData alone would turn a silent loss into a table that no longer reads.
I am deliberately keeping both out of this pull request: the changelog entry here covers the read path, and the backup half needs BACKUP/RESTORE test coverage plus a guard against recreating a file that already exists, since FS::createFile opens with O_EXCL. I have it in progress separately and will post that pull request link in this thread when it opens.
There was a problem hiding this comment.
Opened as #119722, both sites in one commit as described above, with BACKUP/RESTORE test coverage and the existsFile() guard.
One deviation from the shape suggested here, worth naming because I committed to the other one: the predicate does not use the marks alone for Log. It checks the recorded size of every data file first and only then the engine's row signal. A marks-only check regresses two states that are reachable today. TinyLog(s, k) with the zero-byte column declared first is classified empty on the strength of data_files[0], so a later column's real bytes are dropped from the backup; and for a Log table whose __marks.mrk has gone missing while sizes.json still records data bytes, master fails the backup loudly at createHardLink, whereas a marks-only predicate would report BACKUP_CREATED with no data. Recorded bytes first keeps that failure loud and adds no new error code. The size proxy is still what TinyLog falls back to, so the one case that stays lossy is a TinyLog table in which no column occupies any bytes, since no row count exists on disk there to recover.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes164 object files changed (+244.34 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3053 translation units recompiled, 15916 s compile time in total, 3053 of them have a recent master baseline. |
|
The They are not caused by this pull request. That assertion is master's, at |
CI finish ledger - ea951d4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260913-040029 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix reading a column of aggregate function states whose serialized form is empty, such as
countResampleover an empty range. The column read back as zero rows, which made aDynamicorVariantcolumn holding it fail with a logical error on every read and on every merge, leaving the table unreadable and unmergeable, and made aLogtable holding only such a column read as empty.Description
countResample(begin, end, step)withend < beginis a legal function whose state occupies no bytes and whoseserializewrites none, so a hundred rows occupy zero bytes in a part. Reading them back,SerializationAggregateFunction::deserializeBinaryBulkstops onistr.eof(), appends zero rows and reports success. ADynamiccolumn then aborts withA merge reads the parts the same way, so such a table stays unreadable and unmergeable. A bare column fails with
CANNOT_READ_ALL_DATAin a compact part, andLogdecides whether it holds rows from the size of its first data file, which such a column leaves empty.limitis an upper bound by contract, so the leaf cannot just honour it:TinyLogpasses a block size it has no row count for, and would invent rows not on disk. So a caller whose count is exact and server-written says so (number_of_rows_is_exact, set by the two MergeTree readers and byLog), a function declares whether its serialized form is empty (serializedStateIsEmpty(), true forResampleover an empty range and forwarded by every combinator adding no bytes of its own,-Tupleand the flagless nullable adapter included), and only then are the states reconstructed from the count.Nativekeeps today'sCANNOT_READ_ALL_DATA: its count comes from an untrusted header and clients have no memory limit by default.The
eofstop is long-standing, so this is not a regression of #117370. Found by the AST fuzzer on an unrelated pull request (job, report); reproduced on plainmasterwithout the thread sanitizer, ruling it out.05055_aggregate_state_bulk_deserialization_overflowgains the carrier, a merge, a compact part, three combinator empty ranges,LogagainstTinyLog, and non-empty zero-size controls; existing expectations unchanged.Workflow [PR]
Sync PR [sync-upstream/pr/119700]