Skip to content

Validate the Log family column name length at DDL time - #113072

Closed
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112714-log-column-name-length
Closed

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112714-log-column-name-length

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Log and TinyLog accepted a column whose derived on-disk file name did not fit one path component, so CREATE TABLE succeeded and every INSERT then failed with Code: 1001, STD_EXCEPTION and no message. Such a column is now refused at CREATE TABLE with ARGUMENT_OUT_OF_BOUND naming the file and the limit, and an existing table with such a column keeps loading and reports the same typed message on write.

Description

Every Log/TinyLog stream is stored as <derived name>.bin in one path component, and nothing bounded that name. CREATE accepted it and the refusal surfaced only at the first INSERT, as a std::filesystem::filesystem_error rather than a DB::Exception, so its text was lost and only Code: 1001 reached the client.

The limit is now checked against the derived name at three sites, one per writer that can reach the filesystem:

  • the constructor, for a fresh definition: a CREATE, or an ATTACH that did not come from stored metadata, the predicate registerStorageMergeTree uses for the same question. The unwritable table is never created, and a full-definition ATTACH is covered too;
  • StorageLog::write, so a table created before this check reports the file and the limit instead of the bare Code: 1001;
  • StorageLog::restoreDataImpl, which appends the backup's files with copyFileToDisk and passes through neither of the above. It is reachable with a backup taken where the derived name fits and restored where it does not. Refusing restored tables at creation would instead reject the empty pre-fix tables that restore cleanly today, whose backups hold metadata only because their first INSERT failed before any data file existed.

The bound is probed with pathconf(_PC_NAME_MAX) at the disk root, like computeMaxTableNameLength does, and measured after derivation because escapeForFileName and substreams both expand the name. StripeLog is unaffected, all its columns share one data.bin.

Verified in both directions: every rejection case succeeds wrongly on master, a pre-fix table still loads and drops with its INSERT now typed, and an at-limit table with data still backs up and restores cleanly. 04686_log_column_name_length pins the DDL cases. Unit tests in gtest_storage_log.cpp pin the two runtime guards: deleting either one fails them with the untyped Code: 107.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113072&sha=1bf035b384b0e9d81a95e12a393bc60eb1b4d3d8&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29

Log and TinyLog store every column stream in its own <derived name>.bin, and
StorageLog::addDataFiles built that path with no length policy, so CREATE TABLE
accepted a column the filesystem could never hold. The table was then permanently
unwritable: the LogSink ctor calls saveFileSizes -> FileChecker::update ->
fileReallyExists -> std::filesystem::status, which fails ENAMETOOLONG. That arrives
as a std::filesystem::filesystem_error rather than a DB::Exception, so its text was
dropped and the client saw a bare Code: 1001 (STD_EXCEPTION) naming neither the
column nor any limit. Reads and DROP kept working.

The check measures the derived, escaped stream name inside the enumerateStreams
callback rather than the column name, because both escaping and substreams expand it:
84 '%' characters escape to 252 bytes, and a Nested(a UInt64) column overflows at 246
characters via <name>%2Ea.size0 while a plain column fits up to 251. A column-name
check misses both. The budget is pathconf(_PC_NAME_MAX) probed at the disk root, since
pathconf on a path that does not exist yet answers -1/ENOENT and the disk root is
created at registration. The measured boundary (251 accepted, 252 refused) matches
budget - strlen(".bin"), and .bin is the only suffix the family derives.

An existing table whose stored metadata already carries an over-long name still loads,
because the check is gated on a freshness flag: attach_short_syntax marks every
definition read back from stored metadata, exempting a restart, a short ATTACH and a
Replicated DDL replay. A RESTORE is deliberately not exempt, since it shares
SECONDARY_CREATE with that replay and only is_restore_from_backup separates them, and
a restored table that can never accept a row is not a successful restore. Writing to
such a legacy table now reports the offending file and the limit instead of the
filesystem error, which is the one runtime site that needed the translation.

That translation is conditional on the refused basename being over the budget:
ENAMETOOLONG also covers a PATH_MAX overflow, and StorageLog::rename rebuilds paths
from an unconstrained table path, so a short column name under a deep table path keeps
its existing error instead of being misattributed to a column.

The DDL rejection was chosen over hashing the on-disk name because Log has nowhere to
record a mapping: sizes.json keys are the basenames themselves, backupData writes them
into the backup, and the family has no settings schema to carry a max_file_name_length
analogue. Since no ALTER can introduce a column name after creation, a CREATE-time
check is complete for this engine.

Closes: ClickHouse#112714
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, adjudicated)

An independent model reviewed this diff cold, and I reviewed it separately before seeing its
output. Verdicts below; I state my reasoning so a reviewer can check the disagreement rather than
take my word for it.

⚠️ Does the NAME_MAX probe wrongly reject valid object-storage-backed Log tables? -- DISAGREE

The claim: IDisk::getPath need not be a local path, Log accepts any configured disk, so probing
pathconf(_PC_NAME_MAX) (and falling back to NAME_MAX when it returns -1) could refuse a name
that an object-storage backend would happily store.

The scenario needs a writable Log table on a disk whose getPath is not a local directory, and
that combination is unreachable:

  • every Log data file is opened WriteMode::Append (StorageLog.cpp:474, and the marks file at
    :918);
  • DiskObjectStorageTransaction::writeFileImpl throws NOT_IMPLEMENTED for Append unless
    metadata_storage->supportWritingWithAppend() (DiskObjectStorageTransaction.cpp:272-273);
  • that predicate is false by default (IMetadataStorage.h:328). Only MetadataStorageFromDisk
    returns true (MetadataStorageFromDisk.cpp:136-139); the cache variant just delegates
    (MetadataStorageFromCacheObjectStorage.cpp:187-190). plain, plain_rewritable, keeper,
    web and web_index all inherit false;
  • in both append-capable cases getPath resolves to a local directory:
    DiskObjectStorage::getPath returns metadata_storage->getPath()
    (DiskObjectStorage.h:54), which for MetadataStorageFromDisk is a DiskLocal created over
    metadata_path right after fs::create_directories (MetadataStorageFactory.cpp:133-141).

So a disk on which the probe would be meaningless is a disk on which the table cannot be written at
all, and no valid table is rejected. Measured independently while implementing: INSERT into a
Log table on a metadata_type=plain disk fails Code: 48, NOT_IMPLEMENTED whatever the column is
named.

On the fallback direction: if pathconf fails, NAME_MAX gives a limit of 251, which is the
conservative side, and it is the same policy computeMaxTableNameLength already ships for table
names.

💡 Nits I found in my own review

  • The Nested arms' comment in the stateless test names the derived stream %2Ea.size0. The
    boundary it teaches (245 fits, 246 does not) is correct and measured, but the actual overflowing
    stream is the shared offsets one, <name>.size0 (251 bytes at 245), because
    share_nested_offsets makes it use the extracted table name -- see y.size0.bin in
    02047_log_family_complex_structs_data_file_dumps.reference. I corrected the description above;
    the test comment still teaches the right number.
  • The new header includes <Disks/IDisk.h> for DiskPtr where the tree usually forward-declares
    the alias. Fan-out is one translation unit, so I left it.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization needed: clickhouse local -q "CREATE TABLE t (\<252 x c>` UInt8) ENGINE = Log; INSERT INTO t VALUES (1);"givesCode: 1001 (STD_EXCEPTION). Identical for TinyLog`.
b Root cause explained? StorageLog::addDataFiles builds <table_path><derived stream name>.bin with no length policy, so CREATE accepts a name the filesystem cannot hold. At INSERT the LogSink ctor calls saveFileSizes -> FileChecker::update -> fileReallyExists -> std::filesystem::status, which fails ENAMETOOLONG. That is a std::filesystem::filesystem_error, not a DB::Exception, so the text is lost and only Code: 1001 reaches the client.
c Fix matches root cause? Yes. The name is refused where it is derived, so the unwritable table is never created. The runtime arm only re-types the backend's own refusal and adds no length policy of its own. No widened bound, no data reduction, no guard masking an upstream bug.
d Test intent preserved / new tests added? No existing test weakened. All 26 log-engine tagged tests plus 03305_log_unsupported_types, 01800_log_nested and 00554_nested_and_table_engines still pass. Added 04686_log_column_name_length and tests/integration/test_log_column_name_length (9 tests).
e Both directions demonstrated? Yes, on Build-ID-verified binaries (pristine 03d156b5 vs fixed 06700e74). Stateless: all 5 rejection arms report "the query succeeded but the server error '69' was expected" pre-fix, 50/50 pass post-fix. Integration: 5 failed / 4 passed pre-fix, 9/9 post-fix.
f Fix is general across code paths? Log and TinyLog share the class and are both tested. StripeLog is not a carrier (one shared data.bin) and is pinned as unaffected. I swept every other getFileNameForStream caller in the tree: all use the name as an in-memory key, not a filesystem path, so StorageLog was the only unbounded one. Fixed at the derivation site, not at the site that fails.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and this drove the design: the check measures the derived ESCAPED stream name, so it covers plain names (251/252 boundary), escaping expansion (84 % chars -> 252 bytes), and substream-derived names (Nested overflows at 246 through its shared offsets stream <name>.size0, which a column-name-only check would miss). Boundaries measured for each shape rather than predicted. ALIAS columns are correctly exempt (no file derived); Variant still reports ILLEGAL_COLUMN. The limit is probed with pathconf(_PC_NAME_MAX) and saturates at 0, so no unsigned wrap can report a huge limit.
h Backward compatible? (maintainer-approved exception only) Two deliberate narrowings, both stated in the PR body: a CREATE that used to succeed now fails, and a RESTORE of such a table now fails. Both only remove tables that can never accept a row. Existing tables keep loading (freshness gate, integration-tested), so nothing becomes unreachable. No setting default changes, hence no SettingsChangesHistory.cpp entry, and no serialization or on-disk format change.
i Invariants and contracts preserved? The check runs inside the existing enumerateStreams iteration and throws before any file is registered, so the data_files ordering the marks file depends on is untouched, as is checkSupportedDataTypes running first. saveFileSizes only wraps the existing loop and rethrows unchanged on every non-matching path. The runtime translation is conditional on the refused BASENAME being over the budget, so a PATH_MAX overflow from a deep table path keeps its original error instead of being misattributed to a column: verified with a 4039-byte data path and a short column name.

Session id: cron:clickhouse-impl-slot-43:20260803-040500 (implementation) / cron:clickhouse-review-slot-48:20260803-083300 (review)

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @alesapin, could you review this? Log/TinyLog accepted a column whose derived, escaped stream name did not fit one path component, so CREATE succeeded and every INSERT then failed with an untyped Code: 1001; the check now runs inside enumerateStreams (so substream-derived names are covered too) and is gated on a freshness flag that exempts metadata replay but deliberately not RESTORE.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9ea8522]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Compile before-binary (ninja unit_tests_dbms, without the fix) ERROR

AI Review

Summary

This PR fixes the local Log/TinyLog DDL path and adds typed runtime guards for legacy writes and backup restores, but one distributed create path still bypasses the new validation. As written, follower hosts in replicated / ON CLUSTER creates can still accept an unwritable table definition and rediscover the problem only on first INSERT.

Findings

⚠️ Majors

  • [src/Storages/StorageLog.cpp:1448] The new DDL-time guard is keyed only off CREATE and full-definition ATTACH, but the bound comes from pathconf(disk->getPath(), _PC_NAME_MAX), so it is a property of the local target disk and must be revalidated on every host that creates the table locally. SECONDARY_CREATE still goes through the constructor's new-table path (mode < LoadingStrictnessLevel::ATTACH), yet this predicate treats it as already-validated metadata and skips the check. In CREATE ... ON CLUSTER and Replicated database replays, a follower with a smaller component limit will therefore accept the DDL and only fail on the first INSERT, recreating the original unwritable-table bug on that node. Suggested fix: treat SECONDARY_CREATE as fresh when !args.is_restore_from_backup, or otherwise revalidate per-host before constructing the storage.
Final Verdict

Changes required: the per-host stream-name check still misses fresh SECONDARY_CREATE executions.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.80% -0.10%

Changed lines: Changed C/C++ lines covered: 92/128 (71.88%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
#include <Storages/LogStreamFileNameLength.h>

#include <Common/ErrnoException.h>
#include <Common/Exception.h>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai again, do you need such a long PR to fix the issue?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No, and you were right to ask twice. It is now +85/-0 over 4 files (047e54e1), down from +466/-3 over 10. Three things went:

  • LogStreamFileNameLength.{h,cpp} existed to re-type the filesystem's ENAMETOOLONG by inspecting an in-flight exception, and to keep that basename-conditional so a PATH_MAX overflow was not blamed on the column. Checking the derived names in StorageLog::write before the sink runs gives the same message with no exception plumbing at all, so the file, its two catch (...) classifiers and the PATH_MAX ambiguity are gone.
  • The is_fresh_definition bool threaded through the constructor, the header and registerStorageLog collapses to mode <= LoadingStrictnessLevel::CREATE, already a constructor parameter, which is how checkTableNameLength gates itself at InterpreterCreateQuery.cpp:2162.
  • The integration test existed only to plant metadata on disk to build a legacy table. An A/B against the pre-fix binary proves the same property directly, so the whole directory went and the stateless test is 30 lines.

One trade this creates, so you can reverse it if you disagree: RESTORE of such a table, and a full-definition ATTACH (only reachable on the deprecated Ordinary engine, Atomic refuses the syntax), now report the limit at the first write instead of refusing the DDL. Measured, both give the typed ARGUMENT_OUT_OF_BOUND, and neither is a regression since master gives Code: 1001 for both. Refusing them at DDL time is what needed the freshness flag plus the integration test to separate RESTORE from a Replicated replay, i.e. most of what I just deleted. Say the word and it comes back.

On #113044: it is a different size, +1269/-87, and I will look at it there rather than argue it here.

Two mechanical lint failures, no change to the fix logic.

The `catch (...)` blocks in `recoverFailedPath` and `isFilenameTooLongError`
classify an exception that the caller still owns and rethrows, so nothing is
swallowed there. `check_catch_all` cannot see that, and the convention it asks
for is a comment containing `Ok`, matching the existing form at
`src/Client/LocalConnection.cpp:445`.

`various_checks.sh` requires an `__init__.py` in every
`tests/integration/test_*` directory; the new integration test was missing
its (empty) one.

Also corrects a comment in the stateless test. It named a derived stream
`%2Ea.size0` that does not exist: with `flatten_nested = 1` the column is
`<base>.a`, and `share_nested_offsets` makes the `ArraySizes` substream use
the extracted table name, so the two derived streams are `<base>%2Ea` and the
shared `<base>.size0`. In-tree artifact
`02047_log_family_complex_structs_data_file_dumps.reference` shows exactly
this shape (`y%2Ez.bin`, `y%2Ew.bin`, shared `y.size0.bin`). The measured
245/246 boundary is unaffected: `.size0` is the longer suffix and 245 + 6 is
251, the limit.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageLog.cpp Resolved
@PedroTadim asked twice today whether these PRs need to be this long. This one
did not: it is now +84/-0 over 4 files, down from +470/-3 over 10.

Three things went away.

The separate translation unit `LogStreamFileNameLength.{h,cpp}` existed to
re-type the filesystem's own `ENAMETOOLONG` into `ARGUMENT_OUT_OF_BOUND` by
inspecting an in-flight exception, and to keep that inspection basename
conditional so a PATH_MAX overflow from a deep table path was not blamed on the
column. Checking the derived names in `StorageLog::write` before the sink runs
gets the same message without ever touching an exception, so the exception
plumbing, its two `catch (...)` classifiers and the PATH_MAX ambiguity are all
gone. The check is one loop over `data_files`, whose names `addDataFiles`
already derived.

The `is_fresh_definition` flag threaded through the constructor, the header and
`registerStorageLog` reduces to `mode <= LoadingStrictnessLevel::CREATE`, which
is already a constructor parameter. That is exactly how the in-tree precedent
for this check gates itself: `InterpreterCreateQuery.cpp:2162` skips
`checkTableNameLength` for secondary creates for the same backward
compatibility reason. The previous three-term flag also checked `RESTORE`, but
a restore of an over-long definition is now refused at the first `INSERT`
rather than at `RESTORE`, which is the same place every other legacy table
reports it.

The integration test went with it. It existed only to build a legacy table by
planting metadata on disk, which @alexey-milovidov's rule keeps out of
functional tests. That fixture was proving the same thing an A/B against the
pre-fix binary proves directly: a table created by the old binary still loads,
still SELECTs, still DROPs, and its INSERT now reports the file and the limit
instead of `Code: 1001`. The remaining stateless test is 30 lines and keeps the
cases that are not obvious from the code: the boundary for both engines, an 84
character name that overflows because escaping expands it, a `Nested` column
that overflows 6 characters early because a substream appends to the name, and
StripeLog staying unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageLog.cpp Resolved
DROP TABLE IF EXISTS t_at_limit;
DROP TABLE IF EXISTS t_nested_at_limit;

CREATE TABLE t_at_limit (`ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc` UInt8) ENGINE = Log;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai add test examples with RENAME table. Are long column names safe for these engines?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added the RENAME TABLE case, and no, a rename cannot make these names unsafe.

A rename never touches a column name, and the limit is per path component, so the derived
<name>.bin component is unchanged however long the table or database name becomes. I
measured it both ways: the at-limit 251-byte column stays writable after a rename within a
database, after a rename into a database with a 200-byte name, and under Ordinary, where
the data path really is name-derived and grew from 96 to 191 bytes. The test now pins the
same-database case.

No ALTER can introduce a long name after creation either: StorageLog does not override
checkAlterIsPossible, so IStorage refuses every non-comment alter, and RENAME COLUMN
comes back Code: 48.

Your question did find something, though. ATTACH TABLE t [FROM '<path>'] (<definition>) ENGINE = Log supplies a fresh definition but arrives under LoadingStrictnessLevel::ATTACH,
so the mode <= CREATE gate skipped the check and that DDL accepted a name a plain CREATE
refuses. Fixed in 1bf035b by using the predicate registerStorageMergeTree already
uses for this exact question: fresh means CREATE, or an ATTACH that did not come from
stored metadata (attach_short_syntax). Existing tables are unaffected, verified against a
table built by a pre-fix binary: it still loads, reads and drops, and its INSERT reports
the file and the limit.

+31/-5 over 5 files now, one commit on top of the reduction.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

One correction to my last answer, since I found a case where the answer is not simply yes.

A RESTORE can still bring in a name that does not fit. The DDL check and the write-time check
both run before any file is opened, but restoreDataImpl appends the backup's files directly and
goes through neither, so a backup taken where the derived name fits and restored where it does not
still surfaces the raw Code: 1001 rather than the typed message. I reproduced it by restoring a
backup whose data file already carries an over-long name: master and this PR behave identically,
so the guard genuinely does not cover that path. I am adding the same check before the append.

Worth saying what is not affected, because it narrows the fix: a table that predates the check
can never hold data, since its first INSERT always failed before any file was created. Its
backup therefore contains only metadata, restoreDataFromBackup returns early, and restoring it
works today and keeps working; the first INSERT afterwards reports the limit. So the fix belongs
at the append site, not as a refusal of restored tables, which would break those empty ones.

Separately, the test I added is not parallel-safe and the flaky check caught it: the
full-definition ATTACH case pins a literal table UUID, and a UUID is server-global, so
concurrent copies race and one gets TABLE_ALREADY_EXISTS instead of the expected error. The
explicit UUID is mandatory for that syntax, so I am moving the case to a shell test that generates
one per run rather than serialising the test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both landed in f261948, and one correction to what I said above: the test did not need a
shell after all.

I said I would move the full-definition ATTACH case to an .sh test to generate a unique UUID
per run. That is unnecessary, because the FROM '<path>' form of the same full-definition
ATTACH requires no UUID clause at all and reaches the identical predicate, so the case stays
pure SQL with no new file and no tag. Measured with 24 simultaneous attaches, one database each:
the old form returns TABLE_ALREADY_EXISTS 8 times out of 24, the new form returns the expected
ARGUMENT_OUT_OF_BOUND 24 out of 24. The runner alone does not expose the collision at
--test-runs 34 -j 8, which is why the flaky check only caught it 10 times in 34.

The restoreDataImpl guard is the typed check before the append, as described. An at-limit table
with data still backs up and restores, and the empty pre-fix tables still restore, which is why
the check is not at creation.

+7/-2 over 2 files on top of the previous commit.

@PedroTadim PedroTadim self-assigned this Aug 3, 2026
`ATTACH TABLE t [FROM '<path>'] (<definition>) ENGINE = Log` supplies a fresh
definition but reaches the storage under `LoadingStrictnessLevel::ATTACH`, so
gating the check on `mode <= CREATE` skipped it and the DDL still accepted a
column whose derived file name cannot exist. The write-time check kept the
error typed, so this was never a return to the reported `Code: 1001`, but the
name was accepted where a plain `CREATE` refuses it.

The gate is now the predicate `registerStorageMergeTree` already uses for the
same question: fresh means `CREATE`, or `ATTACH` that did not come from stored
metadata. Definitions replayed from metadata carry `attach_short_syntax` (set
in `createTableFromAST`), so a restart, a short `ATTACH TABLE t`, an
`ATTACH DATABASE` and a `Replicated` DDL replay stay exempt and a table whose
stored name is already over the limit still loads, still reads and still drops.

The test also covers `RENAME TABLE`, which @PedroTadim asked about. A rename
cannot cross the bound: it never touches a column name, and the limit is per
path component, so the derived `<name>.bin` component is unchanged however
long the table or database name becomes. No `ALTER` can introduce a name
either, since `StorageLog` does not override `checkAlterIsPossible` and
`IStorage` refuses every non-comment alter, including `RENAME COLUMN`.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageLog.cpp Resolved
…st parallel-safe

Two fixes from the CI of the previous commit.

The `Stateless tests (amd_tsan, flaky check)` job failed 10 of 34 runs of
`04686_log_column_name_length` with `Expected server error code: 69 but got: 57`.
The full-definition `ATTACH` case pinned a literal table UUID, and a table UUID is
server-global under `Atomic`, so the flaky check's concurrent repetitions of the
test collided and one got `TABLE_ALREADY_EXISTS` before the length check could
run. The explicit UUID is mandatory for that syntax, but the `FROM '<path>'` form
of the same full-definition `ATTACH` needs none and reaches the identical
predicate, so the case now uses it and stays pure SQL, with no tag and no new
file. Measured with 24 simultaneous attaches, one database each: the old form
returns `TABLE_ALREADY_EXISTS` 8 times out of 24, the new form returns the
expected `ARGUMENT_OUT_OF_BOUND` 24 times out of 24.

`StorageLog::restoreDataImpl` appends the backup's data files with
`copyFileToDisk` and goes through neither the DDL check nor `StorageLog::write`,
so a backup carrying a derived stream name that does not fit the destination was
refused by the filesystem as an untyped `filesystem_error` whose own message is
lost, surfacing as a bare `Code: 1001`. It now runs the same typed check before
the append. This happens for a backup taken where the derived name fits and
restored where it does not; a table that predates the check cannot reach it,
because its first `INSERT` always failed before any data file was created, so its
backup holds only metadata and `restoreDataFromBackup` returns early. Refusing
restored tables at creation instead would have rejected exactly those empty
tables, which restore cleanly today.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageLog.cpp Resolved
The stateless test only reaches the fresh-definition DDL checks: every over-long
name is refused at DDL, so `StorageLog::write` is never reached, and every
at-limit name fits, so the guard there is a no-op. The two runtime guards added
by this PR were therefore verified only by hand, against a pre-fix binary, and a
refactor could drop either `checkStreamFileNameLengths` call with nothing going
red.

Both are reachable from a unit test without fabricating any on-disk state, which
is what made the earlier integration test unnecessary. `StorageLog`'s
constructor already takes `is_fresh_definition`, so passing it false with an
over-long column builds exactly the state a table created before the check
loads in, with no metadata planted on disk. The write path then needs nothing
more than a `write` call. For the restore path only the derived file name
matters, because the guard runs before any backup entry is read, so a minimal
`IBackup` that answers `hasFiles` and `fileExists` reaches it and fails the test
if `copyFileToDisk` is ever called.

A third case pins the compatibility direction: the same over-long definition
must keep loading, since the DDL check stays exempt for stored metadata.

Removing both guards fails exactly the two guard tests with code 107, the
untyped filesystem error this PR replaces, and leaves the loading test green.
Asserting only the error code and the phrase let an implementation drop the
offending file name and the two lengths while still passing. Degrading the
message to keep just its class now fails both guard tests, and the message is
the whole point of the change: the untyped filesystem error it replaces is
refused for losing exactly that information.

The bound itself is whatever the disk reports, so the test requires a digit
after the phrase rather than a fixed 251.
Requiring only a digit after the phrase let an implementation report an
arbitrary bound while passing. The test now derives the value the storage must
report from the test disk and asserts it, so reporting 1 instead of the real
limit fails.
/// that runs under `ATTACH`; definitions read back from stored metadata carry
/// `attach_short_syntax` (see `createTableFromAST`). Same predicate as
/// `registerStorageMergeTree`.
const bool is_fresh_definition = args.mode <= LoadingStrictnessLevel::CREATE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SECONDARY_CREATE is still being treated as "already validated metadata", but this check depends on pathconf(disk->getPath(), _PC_NAME_MAX), i.e. the local target disk rather than just the AST. In a Replicated database or CREATE ... ON CLUSTER, only the initiator reaches this branch as CREATE; the other hosts replay the same definition under SECONDARY_CREATE, skip the constructor check here, and can still create an unwritable Log/TinyLog table if their local disk has a smaller component limit. The failure then moves back to the first INSERT on those nodes.

I think this predicate needs a SECONDARY_CREATE && !args.is_restore_from_backup arm so replicated / ON CLUSTER creates are revalidated per host, while the restore compatibility tradeoff stays intact.

Poco::Exception::message returns const std::string &, so copy-initializing a
const String from it is a needless copy. clang-tidy's
performance-unnecessary-copy-initialization is warnings-as-errors in the
arm_tidy build, which failed the whole build on that one diagnostic.

Also trim the registerStorageLog comment to the local invariant: the
attach_short_syntax rationale and the cross-file citations belong here in the
commit message, not at the call site.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4cdb20a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Invalid number of rows in Chunk ... column Array(Nullable(UInt64)) at position 2: expected 8192, got 8065 (STID 3366-3cc4) trunk logical error on the MergeTree read path: two Array columns sharing an offsets stream come back short by an incomplete granule while their siblings are full a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Bugfix validation (unit tests) harness aborts as inconclusive because the base branch moved submodules after the branch split (.gitmodules, contrib/arrow, google-protobuf, grpc, orc, simdjson, xsimd); the job carries allow_failure and is outside the merge gate a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks build-profile telemetry INSERT fails against the internal LogCluster endpoint; the check itself is success and non-gating #113009 (mine, open)

Not PR-caused. This diff validates Log-family column name length at DDL time and touches only
StorageLog, its gtest and one stateless test; the aborting stack is
Chunk::checkNumRowsIsConsistent under MergeTreeSelectProcessor::readCurrentTask, which it does
not reach.

On the first row: the sibling assert column->size() == num_rows on the same tail frame is covered
by #113225 (mine, open), but that fix is on the prewhere MergeTreeRangeReader path and its
coverage of this array shape is not yet measured, so linking it here would be a guess. The fix task
above owns confirming or refuting that coverage; if #113225 does cover it, its link replaces this
line.

Session id: cron:our-pr-ci-monitor:20260804-160000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger correction - 4cdb20a

Row 1 of my ledger above said the coverage of #113225 for this array shape "is not yet measured, so
linking it here would be a guess", and that the fix task owns confirming or refuting it. I measured
it: #113225 does cover it, so its link replaces that line.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Invalid number of rows in Chunk ... column Array(Nullable(UInt64)) at position 2: expected 8192, got 8065 (STID 3366-3cc4) trunk logical error reading a re-added Nested member subcolumn beside present siblings that share its offsets stream #113225 (mine, open)

Three arms, all pre-built binaries, Build IDs asserted, fixture = the CI shape minimised
(share_nested_offsets = 1, Wide, index_granularity = 8192 with index_granularity_bytes = 0,
65636 rows, mark layout asserted from system.parts, arr.nested dropped and re-added after the
INSERT, then arr.nested.b read beside arr.n Array(Nullable(UInt64)) and
arr.lc Array(LowCardinality(String))):

arm contents result at max_block_size = 68809
current master (e8010e9c609ef326, build id 92d965683ebfbb14) has the merged prefetch fix, not #113225 abort rc=134
pristine base (91687a7d610e6ee, build id 86a06a744ba91a07) neither abort rc=134
#113225 head (99c95544ab696c4, build id 89eef43ca99f2a46) 3a + 3b clean, 65636 0 0 0, also at 8192 and 1000

The master arm is a valid control: NestedUtils.cpp, inplaceBlockConversions.cpp,
MergeTreeReaderWide.cpp and SerializationArray.cpp are byte-identical by md5 to origin/master
there. So the repair comes from #113225 and from nothing already merged.

The reason this fingerprint looked distinct from the column->size() == num_rows sightings of the
same defect is the build type, not the code path. That check is a chassert
(MergeTreeRangeReader.cpp:511-513), which is compiled out unless DEBUG_OR_SANITIZER_BUILD
(base/base/defines.h:68,84). Stress test (arm_release) is a release build, so the inconsistent
block survives the range reader and reaches Chunk::checkNumRowsIsConsistent (Chunk.cpp:60-69),
an unconditional throw reached from the Chunk constructor in
MergeTreeSelectProcessor::readCurrentTask. Same short read, second guard.

The abort message is self-consistent with that: the dropped and re-added member arr.nested.b is
full at 8192 while both present siblings are short at 8065, which is the direction of this defect
(the missing member reads correctly, the present siblings are the victims).

The victim query is from 04756_nested_sibling_shared_offsets_prefetch, byte-identical between this
build's sha and master. That test inserts 100 rows, so the 8192-row blocks the defect needs came
from the AST fuzzer, which issued INSERT ... FROM numbers(65536) against the same table and was
still in flight when the server aborted.

Session id: cron:clickhouse-plan-slot-36:20260804-204400

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Resolution of the Finish Workflow / Post Hooks (new_tests_check.py) row on my CI finish ledger

I promised a fixing-PR link for this row. There will not be one: I investigated the hook
and concluded no fix to it is warranted. Recording that here rather than leaving the
promise open.

new_tests_check.py reds Post Hooks when no per-arch Bugfix validation job reported a
strict success. Measured over the last 30 days, that happens for two reasons, and neither
is a defect in the hook:

  1. The per-arch jobs were dropped or skipped by an upstream failure. In a 12 hour
    sample every one of the 10 rows with this text resolved to a real upstream red on the
    same head (a Fast test failure, a Build (arm_tidy) failure) that dropped the whole
    downstream matrix, or to a genuine "bug does not reproduce on this arch" verdict. The
    hook is relaying that faithfully; suppressing it would remove signal. Fix or re-run the
    upstream job and this row clears on its own.
  2. The validation job aborted with no completed test row. I first read this as the
    gate passing on zero evidence. It is not: in 12 of 12 sampled runs the job uploaded a
    core dump whose thread matches that PR's own bug (core.MergeMutate for a mutation
    bug, core.QueryPullPipeEx for a SELECT bug, and so on). On a debug or sanitizer
    master-HEAD binary a reproduced logical error aborts the server, which is exactly a
    zero-row abort, and reconcile_bugfix_crash_repro documents that abort as the bug
    reproducing. So the verdict is correct.

Two smaller diagnostics gaps I am not fixing here, since both change what
clickhouse-test reports rather than fixing a bug: the wedged server's logs are not
collected, so the fatal-message check greps an empty directory and the report shows
Failed: 0, Passed: 0, Skipped: 0 with no hint that a core was captured; and distinct
StopTesting causes are not given distinct exit codes the way the global time limit and
max-failures stops are.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0a512fc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Test script failed infra: job-level exit code 1 while every durability gate in the same job is green (Test script exit code, Server successfully started, No lost s3 keys, No SharedMergeTree lost forever all OK across the server runs); no crash or sanitizer signature captured a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Integration tests (amd_msan, 3/8) / test_tcp_handler_connection_limits/test.py::test_query_count_limit flaky, pre-existing: 38 rows across 31 distinct pull requests in 30 days, 6 of them on master a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT rejected with LogCluster query failed with code 500 #113409 (external, open)

All 174 check-runs completed and Finish Workflow succeeded. The Bugfix validation (unit tests)
row on this commit is not a test failure: the harness reports itself inconclusive because the
merge-base and the checkout differ in submodule state, so it cannot build a before-binary. That is a
harness limitation, tracked separately, and it is neither a reproduction nor a refutation of the
regression case.

Session id: cron:our-pr-ci-monitor:20260805-230000

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_tcp_handler_connection_limits/test.py::test_query_count_limit row on my CI finish ledger: #113530 (merged 2026-08-06T00:24:35Z).

It replaces the oracle that counted every Done processing connection. line with one that counts only connections closed because a limit was reached (Closing connection due to limits: queries=), so the startup readiness probe and a reconnecting client no longer pollute the count.

The failure on this PR was on a build that predates that merge. Probing the test file per build (marker get_limit_closed_count, with a control string present in both the pre- and post-fix versions scored on every probe): of 28 recent msan runs, the 14 whose build contains the fix are 14 OK / 0 FAIL, and every failure sits on a build without it. On msan flavours the rate went from 63 FAIL / 197 OK before the merge to 0 FAIL / 219 OK after it.

No action needed here beyond a rerun or a rebase onto current master.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9ea8522c5 with master d53179b03 (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 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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

10 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9ea8522

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 175/175 check-runs completed, 0 incomplete, Config Workflow
and Finish Workflow both success, one failing job.

Check / test Reason Owner / fixing PR
Bugfix validation (unit tests) harness gap: the before-binary cannot COMPILE the overlaid gtest, so the job reports inconclusive rather than a verdict on the regression case a fix task owns this and is being worked at full effort - the fixing-PR link will follow on this PR

Not caused by this PR, and it is not a test failure. The job's own report says so:
Bugfix validation inconclusive: the before-binary failed to COMPILE the overlaid test, which cannot be attributed to the touched regression case. The overlaid gtest_storage_log.cpp references the
DDL-time validation this PR introduces, so it cannot compile against the merge-base tree by
construction. The other three arms agree the coverage is sound:
Bugfix validation (functional tests, amd64) and (aarch64) both success, and the integration
arms are skipped with no integration changes.

Note this is a different arm from the two inconclusive rows previously ledgered on this PR: the
4cdb20a6bc60 head hit the submodule-drift variant (merge-base pins moved), while this head hits the
compile variant. Same job, two distinct harness gaps, and neither blocks merge - the job is
allow_failure, and ERROR never gates in new_tests_check.py.

Session id: cron:our-pr-ci-monitor:20260809-040000

@PedroTadim

Copy link
Copy Markdown
Member

I think the fix is easier than this. Thanks for trying.

@PedroTadim PedroTadim closed this Aug 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Taking the close as final, and correcting a question I asked 20 minutes ago on #113044.

There I asked whether a bare length check on the derived .bin name in the StorageLog constructor is the shape you want. That question was wrong in one detail, and the measurement changes the constant, so I would rather get it right before writing anything.

StorageLog::addDataFiles does not derive one name per column. It enumerates one file per serialization substream via ISerialization::getFileNameForStream, which runs the column name through escapeForFileName and then appends a per-substream suffix. So the accepted column-name length is not a single number, it depends on the type and on the characters in the name. Measured on master 604017b70, Log, each row the last accepted length and the first rejected one:

column type derived suffix longest name accepted first name whose INSERT fails
Int .bin 251 252
Nullable(Int) .null.bin 246 247
Array(Int) .size0.bin 245 246
Int, name of - characters .bin 83 84

Every one of those failures produces a derived basename of exactly 256 characters, one past NAME_MAX. The last row is the reason a name-length constant cannot work: escapeForFileName expands each non-word byte to three characters, so 84 source characters become a 252-character escaped name.

That makes the check one condition rather than a constant: in addDataFiles, where data_file.path is already being built, reject when the derived basename data_file_name + ".bin" exceeds pathconf(_PC_NAME_MAX). It is the same measurement computeMaxTableNameLength already does for table names, and it is at the one point every substream of every column passes through, so Array, Nullable, Tuple, Map and escaped names are all covered by the single condition with no per-type arithmetic.

Two things I would want your call on, because they are the difference between one condition and the machinery you just rejected:

ATTACH. The constructor runs for CREATE and for every attach and restore path, distinguished only by LoadingStrictnessLevel. An unconditional throw there rejects a table that already exists on disk: today a 252-character Log column is accepted at CREATE, the table loads on restart and can be dropped, only INSERT fails. Gating on mode == LoadingStrictnessLevel::CREATE keeps that table loadable and is one extra term, but it is exactly the kind of term that grew the closed PR. If you would rather have the unconditional check and accept that such tables stop attaching, say so and it is simpler.

TinyLog and StripeLog share this constructor, so the same check covers them. StripeLog writes one file for all columns and may not need it.

No test fabricates anything for this: CREATE TABLE plus INSERT in a plain SQL test reproduces it, and I will not add a gtest.

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants