Skip to content

Infer leading-zero decimals as numbers in TSV schema inference - #112226

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:tsv-infer-leading-zero-decimals
Jul 28, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:tsv-infer-leading-zero-decimals

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Infer leading-zero decimals as numbers in TSV schema inference

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 schema inference for the TSV family of formats inferring String for a decimal value written with a leading zero, such as 0.0 or 0.5, where CSV correctly infers Float64. A first row of such values was additionally consumed as a header by TSV header auto-detection and disappeared from the result. Also fixes TSKV inferring a numeric type for a value written using an escape sequence, such as x=1\x2E5, which then failed to parse. Values whose leading zero is padding of an integer, such as 007, keep inferring String because the TSV value parser cannot read them back. Closes #112105.

Description

tryInferDataTypeByEscapingRule returned String for any TSV field starting with 0 and longer than one character, before number inference was attempted at all. The check is a proxy for a real limitation of the value parser, and the proxy was too wide: it also caught genuine decimals whose leading zero is not padding.

$ printf 'a\n0.0\n' | clickhouse local --input-format=TSVWithNames -q "DESCRIBE TABLE table"
a	Nullable(String)
$ printf 'a\n0.0\n' | clickhouse local --input-format=CSVWithNames -q "DESCRIBE TABLE table"
a	Nullable(Float64)

The sign sensitivity the reporter observed shares that single cause: -0.0, +0.5 and .5 all worked because the check reads field[0], which is not 0 in those cases.

The limitation being protected against is in the integer read path only

The check's own comment names the reason: SerializationNumber<T>::deserializeText calls readIntTextUnsafe for integral T, and that reader consumes the leading 0 as the complete value, leaving the rest of the field unparsed. Measured with an explicit structure, so that inference is out of the picture:

field read as Float64 read as Int64
0.0 0.5 0.000 0. 000.5 08.5 00.0 0000000.1 parses (0, 0.5, 0, 0, 0.5, 8.5, 0, 0.1) Code: 27
00 007 03242 0100 09 01 00000 parses (0, 7, 3242, 100, 9, 1, 0) Code: 27
control 0 1 42 -7 parses parses

So the check is correct for integer-shaped fields and unnecessary for genuine decimals.

The change

Move the existing tryInferDataTypeForSingleField call above the check and keep String only when the inferred type is one the TSV value parser cannot read back. The integer case is decided by asking the inferred type instead of re-deriving the field's shape from its punctuation, because tryInferNumber documents its own float-versus-integer decomposition as a current assumption, so a punctuation proxy would silently rot as inference evolves. The exponent case stays a field test, since the divergence it guards sits between two float readers and is not visible in the inferred type.

On cost: this is a reordering of a call the function already makes, so no path gains a call. Fields not starting with 0 are unaffected. Fields that do start with 0 now run inference before the check where they previously returned early, which is one ReadBufferFromString parse of a short field. This path is not schema inference only, SerializationDynamic calls this function once per value, so that is worth stating rather than describing the change as free everywhere.

One consequence is that the behaviour for input_format_try_infer_integers = 0 now falls out for free: with integer inference disabled, inference yields Float64, readIntTextUnsafe is never involved, and zero-padded integers are readable, so the check no longer applies to them.

allow_number_leading_zeros (used by hive partitioning, where the tolerant readIntText branch handles leading zeros) keeps its exact position and polarity.

TSKV needs a second, narrower guard, and it also fixes a pre-existing failure

TSKV shares this escaping rule, so a leading-zero decimal now infers Float64 there too, which is the intended part of the change. But its schema reader reads the value with readEscapedString, which decodes escape sequences, while its value path parses the original bytes. So the wire bytes x=0\x2E5, which decode to 0.5, would newly infer Float64 and then fail the read with Code: 27, because the float reader stops at the backslash. On master that subset was accidentally shielded by the old check, so leaving it alone would have turned working data into a hard error.

The second hunk closes it in TSKVSchemaReader::readRowAndGetNamesAndDataTypes: compare the bytes the read consumed against the length of the value it produced, and if they differ, an escape was decoded, so refuse a numeric inferred type. Every decoding branch of parseComplexEscapeSequence changes that count (\xAA consumes 4 and emits 1, \N consumes 2 and emits 0, the kept-as-is and control branches consume 2 and emit 1); the one branch that does not retains the backslash in the value, and a value containing a backslash can never infer a number. So the condition is exactly the unsafe set, with no false positives and no false negatives.

Because the discriminator is "an escape was decoded and the inferred type is a number" rather than "the field starts with a zero", it also repairs cases that fail on master today: x=1\x2E5 and x=1\x30 currently infer Float64 and Int64 and then fail Code: 27, and now read back correctly as 1.5 and 10. Narrowing the guard to leading-zero fields only would have left those erroring for no principled reason.

What this deliberately does not change

  • Zero-padded integers such as 007 keep inferring String at default settings. Inferring a number for them would turn a wrong type into a hard Code: 27 on data that reads today. The parser side of this is the sibling of issue Issue with import tsv files containing zero-padded numbers #5999, which is closed as completed yet still reproduces: printf '03242\n' | clickhouse local --input-format=TSV --structure="a Int32" fails while CSV reads 3242. That is a separate concern and not touched here.
  • A zero-padded integer carrying a sign, such as -007, still infers Int64 and then fails Code: 27. The check reads the first byte of the field while readIntTextUnsafe skips a leading minus before applying the same leading-zero short-circuit, and it rejects a leading plus outright, so signed spellings never reach the check. Measured identical on master and on this branch for -007, +007 and -00, so it is neither introduced nor repaired here. Making the check sign-aware would demote those values to String, which is a behaviour change for a class this PR does not otherwise touch, so it belongs with the parser half above rather than in this change.
  • Exponent forms such as 0e5 and 0.5e10 keep inferring String in the TSV family under input_format_try_infer_exponent_floats = 1, so a divergence from CSV remains for them. Schema inference uses the permissive tryReadFloatTextExt, while deserialization uses readFloatTextPrecise (precise_float_parsing defaults to true), and the permissive reader accepts values the precise one rejects: 0.5e+ would infer Float64 and then fail Code: 72. That matters because this code path is not inference only, SerializationDynamic immediately deserializes the value into the inferred variant, so an unsafe inference is a hard error at insert time rather than a mis-typed column. The same divergence already exists for 1.5e+, 1e+ and 1.5e- on both TSV and CSV. Aligning the two float readers is the right fix for that half and is a much wider change, so it is left out of this one.
  • TSKV values whose escape sequence sits inside a nested value, or inside a date, keep failing. The nested case (c=[0\x2E5]) infers Array(Nullable(Float64)) and the date case (x=2020-01-0\x31) infers Nullable(Date), and both then fail the read on master and with this change alike, because the guard described above tests the top-level inferred type and neither an Array nor a Date is a number. Unchanged behaviour, so not a regression, but a real boundary rather than a fully closed class.

Silent row loss, which is the strongest symptom

With TSV header auto-detection on by default, a first row whose fields all infer String is treated as a header when a later row infers a number. Because 0.0 inferred String while 10.5 inferred Float64, the first data row was consumed as a column name and silently dropped:

$ printf '0.0\n10.5\n2.3\n' | clickhouse local --input-format=TSV -q "SELECT count() FROM table"
2                     -- three rows in, two rows out; the column is even named "0.0"
$ printf '0.0\n10.5\n2.3\n' | clickhouse local --input-format=CSV -q "SELECT count() FROM table"
3
$ printf '1.5\n10.5\n2.3\n' | clickhouse local --input-format=TSV -q "SELECT count() FROM table"
3                     -- control: same shape without a leading zero

This is fixed for decimals. It is not fixed for zero-padded integers, where the value legitimately stays String; that half belongs to the #5999 family above.

Verification

New stateless test 04648_tsv_schema_inference_leading_zero_decimals, 15 groups: the newly working decimals, a CSV control for each so the agreement is asserted rather than assumed, the values that deliberately stay String, non-numbers, the values that already worked, date-shaped controls, a round trip that reads every admitted value back, the row-loss regression, type merge across rows, the exponent exclusion in both the type and the read direction, both values of input_format_try_infer_integers, the TSVRaw and TabSeparated siblings, several leading zeros with a fractional part, the Dynamic runtime path, and TSKV (plain values, the null representation, and the escaped forms in both the type and the read direction, including a non-numeric escaped control and an escaped Date and escaped nested value, so neither conjunct of the guard can be dropped without a failure). The test carries no skip tags and runs in the fast test.

The test fails on master HEAD and passes with the change. Eight mutations were run, one per behaviour, each rebuilt and diffed against the committed reference: reverting the change reproduces master's output byte for byte; removing the check entirely fails the String-preserving groups; dropping either disjunct fails exactly the group it protects, with the exponent one failing in the read direction with Code: 72 rather than only on a type assertion; replacing the type test with an unconditional true fails only the input_format_try_infer_integers = 0 group; removing the TSKV guard fails group 15 with Code: 27, again on a read rather than on a type assertion; and dropping only the isNumber conjunct of the TSKV guard fails exactly the two rows asserting that an escaped Date and an escaped number inside an array keep their own inferred type. One mutation, dropping the Nullable and LowCardinality strip, is undetected by design: for a field starting with 0 inference can only return a bare numeric type, so the strip guards a state that is unreachable here and is kept as future-proofing rather than covered by an assertion. Restoring the source afterwards rebuilds bit-identically.

Every file under tests/queries/0_stateless was swept for a committed reference that depends on the old behaviour and none was found; the 39 candidates that mention TSKV or sit in the TSV inference neighbourhood were all run and moved zero references, including 02514_tsv_zero_started_number, 02982_dont_infer_exponent_floats, and the two the TSKV guard could most plausibly have disturbed, 02240_tskv_schema_inference_bug and 02247_names_order_in_json_and_tskv. Three of the 39 fail identically on a pristine master binary for reasons unrelated to this change: a missing test_shard_localhost cluster, an absent system.query_log, and an Avro schema registry.

Version info

  • Merged into: 26.8.1.299 (included in 26.8 and later)

groeneai and others added 4 commits July 27, 2026 19:24
Schema inference for the TSV family returned String for any field starting
with 0 and longer than one character, before number inference was attempted.
Genuine decimals such as 0.0 and 0.5 were caught along with zero-padded
integers such as 007, while CSV inferred Float64 for the decimals. The sign
sensitivity users observed, where -0.0 and +0.5 worked but 0.0 did not,
shares that single cause: the check reads field[0].

The limitation the check protects against is in the integer read path only.
SerializationNumber<T>::deserializeText calls readIntTextUnsafe for integral
T, and that reader consumes the leading 0 as the complete value, leaving the
rest of the field unparsed. The float read path has no such limitation, which
is measurable with an explicit structure: 0.0, 0.5, 0.000, 0., 000.5, 08.5,
00.0 and 0000000.1 all read correctly as Float64, while 00, 007, 03242, 0100,
09, 01 and 00000 all fail with CANNOT_PARSE_INPUT_ASSERTION_FAILED as Int64.
So the check was correct for integer-shaped fields and unnecessary for
genuine decimals.

Move the existing tryInferDataTypeForSingleField call above the check and
keep String only when the inferred type is one the value parser cannot read
back. This is a reordering of a call the function already makes, so it costs
nothing on any path, and it asks the inferred type instead of re-deriving the
answer from the field's punctuation. tryInferNumber documents its own
float-versus-integer decomposition as a current assumption, so a punctuation
proxy would silently rot as inference evolves. As a consequence the behaviour
under input_format_try_infer_integers = 0 now follows for free: inference
yields Float64 there, readIntTextUnsafe is never involved, and the padded
integers are readable.

Zero-padded integers keep inferring String at default settings, because
inferring a number for them would turn a wrong type into a hard parse error
on data that reads today. Exponent forms keep inferring String as well:
inference uses the permissive tryReadFloatTextExt while deserialization uses
readFloatTextPrecise, so 0.5e+ would infer Float64 and then fail to parse,
and this code path is not inference only, SerializationDynamic immediately
deserializes the value into the inferred variant. Aligning the two float
readers is a much wider change and is left out of this one.

The user-visible symptom is worse than a wrong type. With TSV header
auto-detection on by default, a first row whose fields all infer String is
treated as a header when a later row infers a number, so the first data row
was silently dropped: three rows of 0.0, 10.5, 2.3 read back as two.

Closes ClickHouse#112105.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review round 1 covers three points, all in the test. The production hunk in
EscapingRuleUtils.cpp is unchanged.

Group 10 asserted the type of exponent forms but never executed the malformed
form the exponent condition exists for, so removing that condition failed only
type assertions and never a read. The group now also covers 0.5e+, 0e+ and
0.5e-, reads all three back through the inferred schema, and drives two of them
through the Dynamic runtime path. A read of the CSV form is asserted to fail
with CANNOT_PARSE_NUMBER, which makes the pre-existing divergence between the
two formats visible rather than implied. The plain reads are what carry the
failure: with the condition removed, the Dynamic path returns 0.5 as a Float64
rather than erroring, so a Dynamic assertion alone is still a type assertion.

The no-fasttest tag claimed that format() and the Dynamic type are unavailable
in the fast test build. Both halves are false. 03033_dynamic_text_serialization
has no tags and selects from format(TSV, 'd Dynamic', ...), the table function
and the data type are registered unconditionally, and the only USE_ guards in
registerFormats.cpp are for Hive. The tag is removed and the test is confirmed
selected and green under --fast-tests-only.

A TSKV group is added, since TSKV uses the same escaping rule and a leading-zero
decimal now infers Float64 there too. TSKV decodes escape sequences before
inferring but parses the original bytes when reading, so a decimal written as an
escape sequence infers a type its own value path cannot read. That asymmetry is
pre-existing and independent of leading zeros, is unreachable from anything
ClickHouse writes, and is left to its own change. The group pins the plain
values plus the null representation and escape controls.

Co-Authored-By: Claude Opus 5 <[email protected]>
The TSKV schema reader infers from the DECODED bytes (readEscapedString) while
the value path reads the ORIGINAL bytes (deserializeTextEscaped ->
readFloatTextPrecise / readIntText). Before the leading-zero narrowing in this
PR, the shape check in tryInferDataTypeByEscapingRule accidentally shielded the
subset whose decoded value starts with '0': those fields became String and read
back correctly. Narrowing the check to the inferred type exposes them, so wire
bytes such as `x=0\x2E5` would infer Float64 and then throw Code 27 on a value
that reads fine today.

Guard it where the split lives. The escaped read reports whether it decoded
anything by comparing consumed bytes against the value length: readEscapedString
stops at a delimiter without consuming it, so with no escape the two are equal,
and every decoding branch of parseComplexEscapeSequence changes the count except
the branch that keeps the backslash in the value, which can never infer a number.
When a decode happened and the inferred type strips to a number, keep String.

This also repairs the same failure without a leading zero, which had no owner
before: `x=1\x2E5` and `x=1\x30` inferred Float64 and Int64 and threw Code 27 on
master, and now read 1.5 and 10. A number inside an Array and a Date value are
not numbers at the top level, so they behave exactly as they do on master; both
are covered by a separate follow-up.

Group 15 of the new test pins all three directions: the escaped decimal must
infer String AND read back its decoded value, the non-zero forms must read
correctly, and a non-numeric decoded escape plus the backslash-retaining escape
branch must be unaffected.
The TSKV schema reader decodes escape sequences before inferring while the
value path parses the original bytes, so a field whose escapes were decoded
must not infer a number. The guard added for that keeps String only when an
escape was decoded AND the inferred type strips to a number, which is what
leaves an escaped Date and an escaped number inside an array with their own
inferred types, unchanged from before this PR.

Only the first half of that condition was pinned by a test: every escaped row
in the TSKV group produced the same result with and without the isNumber
conjunct, so dropping it would have passed the whole test while silently
turning escaped dates and nested values into String, contradicting the
boundary the PR description states.

Add two DESC rows for it: an escaped Date, which reaches
tryInferDateOrDateTimeFromString and returns before the numeric check, and an
escaped number inside an array, whose top-level type is not a number either.
Both are DESC only, because both reads fail here exactly as they fail on
master, and annotating them with a serverError would encode that existing
breakage as expected behaviour. The read direction of this guard is already
covered by the scalar rows above them.

A mutant that removes only the isNumber conjunct now fails exactly these two
lines and nothing else; it was undetected before.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 review rounds, 9 gate runs, 21 findings adjudicated) - click to expand

Before opening this PR I ran it through an independent review pipeline: a separate reviewer reads the
resulting code cold, a second model gates the approach and then the diff, and every finding is
adjudicated with evidence rather than with prose. This comment records the outcome so a maintainer can
see what was already challenged, and what I deliberately did not change.

Totals. 5 approach-gate rounds ($17.38, 3 findings, all agreed, all three redesigned the approach)
and 4 diff-gate rounds ($55.71). At the diff stage 21 findings were adjudicated: 17 AGREE, 3 DISAGREE,
1 with nothing to decide. Gate findings per diff round: 3, 1, 1, 0. The final round is clean.

Adjudicated as real, and fixed

# Finding Where it landed
❌ TSKV would newly infer a number for a value written as an escape sequence. TSKVSchemaReader reads the value with readEscapedString, which decodes escapes, while the value path parses the original bytes, so x=0\x2E5 would infer Float64 and fail the read with Code: 27. Raised twice, blocker on the second raise. Second hunk in TSKVRowInputFormat.cpp. It also repairs x=1\x2E5 and x=1\x30, which fail on master today.
❌ The TSKV guard's isNumber conjunct was not pinned by any test. Every escaped row produced the same output with and without it, so a later simplification would have silently turned escaped dates and nested values into String while the whole test still passed. Two DESC rows in group 15 plus mutant M8, which now fails exactly those two lines.
❌ The malformed-exponent exclusion was asserted only on DESC output. The reason the exponent forms must stay String is a read failure, so the test had to prove it in the read direction. Group 10 now reads 0.5e+, 0e+, 0.5e- and the Dynamic variants, and asserts the CSV counterpart fails with CANNOT_PARSE_NUMBER.
❌ The unconditional integer block was over-broad. With input_format_try_infer_integers = 0 inference yields Float64, readIntTextUnsafe is never reached, and zero-padded integers are readable, so blocking them was wrong. The guard asks the inferred type (isInteger) instead of the field's punctuation, so the setting dependency falls out; group 11 pins both values.
❌ A no-fasttest tag with no load-bearing reason. Tag deleted; the test was then proven selected and green in the fast test.
⚠️ Several description and carrier-table statements that measurement did not support (a claim about what a test row asserts versus what was only verified locally, a file count attributed to the wrong tree, a bullet that went stale when the fix widened). Corrected in the description before this PR was opened.

Adjudicated as not real, with the evidence

# Finding Why I disagreed
💡 The changelog should be Critical Bug Fix because a row disappears. Silent row loss is severe, but the category is reserved for crashes, LOGICAL_ERROR, data loss and RBAC, and is applied on a maintainer's request rather than proactively. Bug Fix (user-visible misbehavior in an official stable release) is the honest category for a schema-inference wrong type; the row loss is described in full in the body instead.
💡 Untracked per-run artifacts sit next to the test in the working tree. They are .gitignored harness output (*.stderr), git ls-files shows only the .sql and .reference, and the tree is otherwise clean, so they cannot reach the PR. Harness artifacts are never deleted to satisfy a finding.

Noted, not blocking

  • The Nullable/LowCardinality strip in the guard is unreachable today, which is why mutant M6
    (strip removed) is undetected: this arm's inference returns bare types and nullability is applied
    later. It is kept deliberately as the strip idiom requested in Fix JSON_EXISTS/JSON_VALUE/JSON_QUERY LOGICAL_ERROR on Dynamic input with LowCardinality path elements #109944, rather than deleted or
    wrapped in an assertion for a state that cannot occur here. Disclosed in the description too.
  • The TSKV guard detects a decoded escape from the consumed-byte delta of readEscapedString. That
    delta is exact per escape branch, but PeekableReadBuffer::nextImpl carries an in-tree FIXME that
    its byte count is inexact after a rollback or refill, and the TSKV schema reader does run over such
    a buffer during format auto-detection and for a file descriptor. A refill landing inside one value
    would make the flag a false positive, whose effect is conservative: String instead of a number,
    never a new error path, and identical to master's behaviour for the whole leading-zero set. The exact
    alternative, inferring from the non-decoding readTSVField, was implemented and measured, and moves
    two committed references because \N then arrives as two literal characters and stops matching the
    null representation. That needs decoding-aware null detection or an aligned TSKV merge, both wider
    than this PR.
  • The two TSKV boundary cases the guard does not reach, an escape inside a Date and inside a nested
    value, keep failing exactly as they do on master. They are asserted DESC-only, because annotating
    the reads with a serverError would encode existing breakage as expected behaviour.

Everything above was resolved before this PR was opened; nothing is deferred into review.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. printf 'a\n0.0\n' | clickhouse local --input-format=TSVWithNames -q "DESCRIBE TABLE table" returns Nullable(String) while the same input in CSVWithNames returns Nullable(Float64), and printf '0.0\n10.5\n2.3\n' | clickhouse local --input-format=TSV -q "SELECT count() FROM table" returns 2 for three input rows. No server, no settings, no randomization involved.
b Root cause explained? Yes. tryInferDataTypeByEscapingRule's Raw/Escaped arm returned String for any field matching field[0] == '0' && field.size() != 1 before calling tryInferDataTypeForSingleField. That check exists because SerializationNumber<T>::deserializeText uses readIntTextUnsafe for integral T, which consumes the leading 0 as the whole value and leaves the rest unparsed. But it tested the field's shape rather than the type that would be inferred, so it also caught genuine decimals that the float read path reads perfectly. The sign sensitivity (-0.0, +0.5, .5 all worked) is the same cause, since field[0] is not 0 in those cases.
c Fix matches root cause? Yes. The existing inference call is moved above the check and the check now keeps String only when the inferred type is one the value parser cannot read back (an integer, or an exponent form). No bound was widened, no no-random-* tag added, no dataset reduced, no defensive check placed at a symptom site, and the parser is untouched. Measured with an explicit structure: 0.0 0.5 0.000 0. 000.5 08.5 00.0 0000000.1 all read fine as Float64 while 00 007 03242 0100 09 01 00000 all fail Code: 27 as Int64.
d Test intent preserved / new tests added? Yes. New stateless test 04648_tsv_schema_inference_leading_zero_decimals with 15 groups, including the values that deliberately stay String (so a later change that removes the check fails loudly), the exponent exclusion in both the type and the read direction, and the TSKV sibling in both the type and the read direction. It also pins that the TSKV guard fires only when an escape was decoded and the inferred type is a number, by asserting that an escaped Date still infers Nullable(Date) and an escaped number inside an array still infers Array(Nullable(Float64)), so the guard cannot later be widened to "any decoded escape" without a red test. It carries no skip tags and runs in the fast test. No existing test was weakened; a sweep of all 26282 committed files under tests/queries/0_stateless on the base tree found no committed reference that depends on the old behaviour, and a 39-test sweep over every file mentioning TSKV plus the TSV inference neighbourhood moved zero references, with 02514_tsv_zero_started_number, 02982_dont_infer_exponent_floats, 02240_tskv_schema_inference_bug and 02247_names_order_in_json_and_tskv all passing unchanged.
e Both directions demonstrated? Yes. The new test fails on master HEAD (96-line diff against the pristine master binary's output, Build ID 9ebd11fe9bc8d547, which aborts inside the TSKV group) and passes with the change (Build ID 4f726b24459b2a43), 50 out of 50 randomized runs and 50 out of 50 non-randomized runs, with the test server's buildId() asserted equal to the binary's Build ID in every run. Eight mutations were run, one per behaviour, each failing exactly the predicted groups: reverting the inference reordering reproduces master's TSV behaviour, removing the check fails the String-preserving groups, dropping either disjunct fails only the group it protects, and replacing the type test with an unconditional true fails only the input_format_try_infer_integers = 0 group. Two mutants must fail in the READ direction and both do: dropping the exponent disjunct fails with Code: 72 CANNOT_PARSE_NUMBER, and removing the TSKV decoded-escape override fails with Code: 27 Found garbage after field in TSKV format, neither merely on a type assertion. An eighth mutant drops only the isNumber conjunct of the TSKV guard and fails exactly the two rows that assert the escaped Date and the escaped nested value, and nothing else. Restoring the source afterwards rebuilds bit-identically to the same Build ID.
f Fix is general across code paths? Yes. The change sits in the single Raw/Escaped arm shared by TSV, TabSeparated, TSVRaw, TabSeparatedRaw, TSKV, CustomSeparated, Template and Regexp when configured with either of those escaping rules, and it fixes the inference source rather than guarding a consumer. The test asserts TSVRaw, TabSeparated and TSKV directly; CustomSeparated, Template and Regexp were verified by reading both of their paths rather than by a test row, since each of them infers through the non-decoding readTSVField and reads through deserializeFieldByEscapingRule, so the bytes are the same on both sides and the split below cannot occur there. (RawBLOB does not use this arm: RawBLOBSchemaReader is an IExternalSchemaReader returning a fixed raw_blob String schema, verified.) The CSV, Quoted and JSON arms have no such check and are untouched. Both arms that are not inference only, the SerializationDynamic runtime path and Form, are asserted or measured. All five schema readers using this arm were checked for a decode-before-infer versus read-original-bytes split, and TSKV is the only one with it: it infers from decoded bytes but reads the original bytes, so it gets its own guard in the same change, keeping String when an escape was actually decoded and the inferred type strips to a number. That guard covers scalar values regardless of a leading zero. Its two remaining boundaries are unchanged from master, disclosed rather than left silent, and asserted rather than merely described: a number inside an Array and a Date, neither of which is a number at the top level, so both keep their inferred type and still fail their read exactly as they do today.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The type test strips Nullable and LowCardinality before asking. The test covers zero, one and many leading zeros, with and without a fractional part, 0. with no digits after the dot, 25 digits of precision, the UInt64 boundary 018446744073709551615, 0x/0b/0o radix prefixes, malformed shapes such as 0.1.2 and 0.5f, date and time shapes, signed and unsigned forms, both values of input_format_try_infer_integers, and input_format_try_infer_exponent_floats = 1. Two sweeps were run against the pristine binary: a 2x2 settings matrix over 34 values (136 cells) and a 45-value adversarial dot-shape sweep under both values of precise_float_parsing. Zero unsafe cells in both.
h Backward compatible? (maintainer-approved exception only) A field that used to infer String now infers Float64, which is what the issue asks for, and CSV has always behaved this way so there is an in-repo precedent for the target behaviour. No setting is added and no default changes, so no SettingsChangesHistory.cpp entry, no format versioning and no experimental gate are required. The allow_number_leading_zeros opt-out used by hive partitioning is unchanged in position and polarity.
i Invariants and contracts preserved? Yes. The arm's contract, that it may only infer a numeric type for a field the TSV value parser can read back, is now enforced instead of approximated. The !type fallthrough to String is preserved, so every non-number path is unchanged. field is guaranteed non-empty at that point because an empty field returns nullptr earlier in the same arm, so the field[0] access remains safe, and the size() != 1 term preserves the behaviour for the single-character "0". The TSKV guard rests on a property of the reader that was derived rather than assumed: readEscapedStringIntoImpl stops at a delimiter without consuming it, so with no escape the consumed byte count equals the value length exactly, and every decoding branch of parseComplexEscapeSequence changes that count except the one branch that keeps the backslash in the value, which therefore can never infer a number. Each branch was also measured. No locking, concurrency or durability surface is involved.

Session id: cron:clickhouse-impl-slot-6:20260728-043001

@groeneai

groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @tavplubix, could you review this? It narrows the TSV-family leading-zero guard in tryInferDataTypeByEscapingRule so it fires on the inferred type (an integer, or an exponent form) instead of on the field's first character, which makes 0.5 infer Float64 as it already does in CSV, and adds a second guard in the TSKV schema reader for its decode-before-infer versus read-original-bytes asymmetry.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f363cac]

Summary: ✅


AI Review

Summary

This PR narrows the TSV-family leading-zero fallback so genuine decimals such as 0.0 and 0.5 infer numeric types instead of String, and it adds a TSKV-specific guard for decoded escapes so schema inference does not pick numeric types that the raw-value reader cannot deserialize. I reviewed the current diff and prior discussion against the current code and did not find any remaining correctness, compatibility, or test-evidence issues that clear the review bar for a new finding.

Final Verdict

✅ No material findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@PedroTadim PedroTadim self-assigned this Jul 28, 2026
@@ -0,0 +1,197 @@
-- 1. Leading-zero decimals must now infer Float64 in the TSV family, as they always did in CSV.
SELECT 'group 1: TSV infers Float64';
DESC format(TSV, '0.0');

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 what about numbers such as -.5 ?

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.

-.5 was never affected, and the reason is that the check I rewrote only ever looked at the first byte of the field (field[0] == '0'), so a sign or a bare fractional dot put the value out of its reach. I measured it on this head and on a pristine master binary: -.5, +.5, -.0, .5, -0.5, -0.0, +0.5, -00.5 and +00.5 all infer Nullable(Float64) and read back as the number, identically on both, in TSV, CSV, TSKV and the Dynamic path, with no row lost.

You were right to ask about the test though: it pinned .5, -0.5, -0.0 and +0.5 but not the bare-dot signed forms, and no reads for any of them. f363cac adds all of them plus their reads and a CSV control. It is a real boundary, not decoration: a plausible rewrite of this check that skipped a leading sign and keyed on isNumber instead of on the inferred integer type demotes the five sign-then-zero values to String while leaving the four bare-dot ones alone, and I confirmed by mutation that the new rows catch exactly that and the bare-dot rows hold.

One thing the question did turn up, which I have added to the PR description rather than fixed here: a zero-padded integer carrying a sign is worse off than the unsigned one. -007 infers Int64 and then fails Code: 27, while 007 merely infers String and reads. readIntTextUnsafe consumes a leading - before applying the same leading-zero short-circuit and rejects + outright, so signed spellings never reach the check at all. Measured identical on master and on this branch, so it is neither introduced nor repaired here, and making the check sign-aware would demote those values to String, which is a behaviour change for a class this PR does not otherwise touch. It belongs with the readIntTextUnsafe half of #5999 that the description already defers, and I have it recorded with the measurement.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 636893f

CI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
Finish Workflow success at 11:57:46Z. Zero failing checks (156 success, 18 skipped), so there is
nothing to assign an owner to.

Check / test Reason Owner / fixing PR
(none) - no failures on this head

Session id: cron:our-pr-ci-monitor:20260728-120000

Reviewer question on the test: what about numbers such as -.5.

The check this PR rewrites only ever looked at the first byte of the field, so
any sign or bare fractional dot moved the leading zero out of its reach and
those spellings already inferred a float before the fix. Measured on this head
and on a pristine master binary, DESC and the value read agree for -.5, +.5,
-.0, .5, -0.5, -0.0, +0.5, -00.5 and +00.5 in TSV, CSV, TSKV and the Dynamic
path, and no row is lost. So the fix does not change them.

The test asserted .5, -0.5, -0.0 and +0.5 but not the bare-dot signed forms,
and it asserted no reads for any of them. Group 5 now pins all of the
spellings plus their reads and a CSV control, so a later rewrite of the check
that skipped a leading sign instead of keying on the inferred type would be
caught: such a rewrite demotes the five sign-then-zero values to String while
leaving the four bare-dot ones alone, which is exactly the boundary these rows
now hold.

Test only, no source change.
@PedroTadim
PedroTadim enabled auto-merge July 28, 2026 13:42
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.50% 78.40% -0.10%

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

Full report · Diff report

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 28, 2026
Merged via the queue into ClickHouse:master with commit f75f7ed Jul 28, 2026
178 checks passed
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f363cac

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.

Check / test Reason Owner / fixing PR
(none) 174 check-runs, 0 failures nothing to own

This replaces the ledger for 636893f4bacc3c; the commit added after it pins the signed and
bare-dot spellings in the leading-zero test. Config Workflow and Finish Workflow both
completed successfully; no check queued or in progress.

Session id: cron:our-pr-ci-monitor:20260728-183000

@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 16, 2026
`TSKVSchemaReader::readRowAndGetNamesAndDataTypes` read each field with
`readEscapedString`, which decodes escape sequences, while
`TSKVRowInputFormat::readRow` parses the original bytes. Inference therefore
answered a question about bytes that are never parsed, so `DESCRIBE` succeeded and
`SELECT` on the same input failed: `c=[0\x2E5]` inferred `Array(Nullable(Float64))`
from the decoded `[0.5]` and then stopped at the backslash with
`CANNOT_READ_ARRAY_FROM_TEXT`, and `x=2020-01-0\x31` inferred `Date` and failed
with `CANNOT_PARSE_INPUT_ASSERTION_FAILED`.

The schema reader now uses `readTSVField`, which does not decode. TSKV was the
only escaped-rule reader that decoded before inferring. ClickHouse#112226's numeric guard
tested only the top-level inferred type, so an escape inside a `Date` or inside a
container still inferred an unreadable type; it is dead now and removed, together
with the three includes it needed.

Reading raw has one consequence for null fields. A field equal to the null
representation stops decoding to the empty string, so it would infer
`Nullable(Nothing)`, join the cross-row merge, and let this format's `String`
default discard a container type another row inferred. A field therefore
contributes no type, exactly as the decoded empty string used to, only where the
value path reads it as a null rather than as data: `\N`, and only while `\N` is
the null representation. `SerializationNullable` wants the configured
representation followed by a delimiter, and
`deserializeNullAsDefaultOrNestedTextEscaped` substitutes a default only while
`input_format_null_as_default` is on, so nothing else may step aside. Naming a
container for a row the reader will not accept as a null would rebuild the very
DESCRIBE/SELECT asymmetry this commit removes, and with
`input_format_null_as_default=0` no container type is readable for a column with
null rows at all; inference must not consult that setting either, since it is not
part of the schema-cache key. Restricting it this way is also what keeps
`02240_tskv_schema_inference_bug`'s `Array(Nullable(Int64))`.

Inference thus changes for escaped fields, and for `x=\N` once the null
representation is something else. `x=\N` under a different representation and
`x=\N\N` improve on master, which names a container for them and then cannot read
the null row.

Co-Authored-By: Claude Opus 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-bugfix Pull request with bugfix, not backported by default 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.

TSV schema inference infers unsigned leading-zero decimals (0.0, 0.5) as String

3 participants