Repository navigation
Infer leading-zero decimals as numbers in TSV schema inference - #112226
Conversation
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.
Internal second-model review (4 review rounds, 9 gate runs, 21 findings adjudicated) - click to expandBefore opening this PR I ran it through an independent review pipeline: a separate reviewer reads the Totals. 5 approach-gate rounds ($17.38, 3 findings, all agreed, all three redesigned the approach) Adjudicated as real, and fixed
Adjudicated as not real, with the evidence
Noted, not blocking
Everything above was resolved before this PR was opened; nothing is deferred into review. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260728-043001 |
|
cc @al13n321 @tavplubix, could you review this? It narrows the TSV-family leading-zero guard in |
|
Workflow [PR], commit [f363cac] Summary: ✅
AI ReviewSummaryThis PR narrows the TSV-family leading-zero fallback so genuine decimals such as Final Verdict✅ No material findings. |
| @@ -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'); | |||
There was a problem hiding this comment.
-.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.
CI finish ledger - 636893fCI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code |
CI finish ledger — f363cacEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
This replaces the ledger for Session id: cron:our-pr-ci-monitor:20260728-183000 |
`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]>
Infer leading-zero decimals as numbers in TSV schema inference
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes schema inference for the
TSVfamily of formats inferringStringfor a decimal value written with a leading zero, such as0.0or0.5, whereCSVcorrectly infersFloat64. A first row of such values was additionally consumed as a header byTSVheader auto-detection and disappeared from the result. Also fixesTSKVinferring a numeric type for a value written using an escape sequence, such asx=1\x2E5, which then failed to parse. Values whose leading zero is padding of an integer, such as007, keep inferringStringbecause theTSVvalue parser cannot read them back. Closes #112105.Description
tryInferDataTypeByEscapingRulereturnedStringfor any TSV field starting with0and 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.The sign sensitivity the reporter observed shares that single cause:
-0.0,+0.5and.5all worked because the check readsfield[0], which is not0in those cases.The limitation being protected against is in the integer read path only
The check's own comment names the reason:
SerializationNumber<T>::deserializeTextcallsreadIntTextUnsafefor integralT, and that reader consumes the leading0as the complete value, leaving the rest of the field unparsed. Measured with an explicit structure, so that inference is out of the picture:Float64Int640.00.50.0000.000.508.500.00000000.1Code: 2700007032420100090100000Code: 270142-7So the check is correct for integer-shaped fields and unnecessary for genuine decimals.
The change
Move the existing
tryInferDataTypeForSingleFieldcall above the check and keepStringonly 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, becausetryInferNumberdocuments 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
0are unaffected. Fields that do start with0now run inference before the check where they previously returned early, which is oneReadBufferFromStringparse of a short field. This path is not schema inference only,SerializationDynamiccalls 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 = 0now falls out for free: with integer inference disabled, inference yieldsFloat64,readIntTextUnsafeis 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 tolerantreadIntTextbranch handles leading zeros) keeps its exact position and polarity.TSKVneeds a second, narrower guard, and it also fixes a pre-existing failureTSKVshares this escaping rule, so a leading-zero decimal now infersFloat64there too, which is the intended part of the change. But its schema reader reads the value withreadEscapedString, which decodes escape sequences, while its value path parses the original bytes. So the wire bytesx=0\x2E5, which decode to0.5, would newly inferFloat64and then fail the read withCode: 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 ofparseComplexEscapeSequencechanges that count (\xAAconsumes 4 and emits 1,\Nconsumes 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\x2E5andx=1\x30currently inferFloat64andInt64and then failCode: 27, and now read back correctly as1.5and10. Narrowing the guard to leading-zero fields only would have left those erroring for no principled reason.What this deliberately does not change
007keep inferringStringat default settings. Inferring a number for them would turn a wrong type into a hardCode: 27on 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 reads3242. That is a separate concern and not touched here.-007, still infersInt64and then failsCode: 27. The check reads the first byte of the field whilereadIntTextUnsafeskips 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,+007and-00, so it is neither introduced nor repaired here. Making the check sign-aware would demote those values toString, 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.0e5and0.5e10keep inferringStringin the TSV family underinput_format_try_infer_exponent_floats = 1, so a divergence from CSV remains for them. Schema inference uses the permissivetryReadFloatTextExt, while deserialization usesreadFloatTextPrecise(precise_float_parsingdefaults to true), and the permissive reader accepts values the precise one rejects:0.5e+would inferFloat64and then failCode: 72. That matters because this code path is not inference only,SerializationDynamicimmediately 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 for1.5e+,1e+and1.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.TSKVvalues whose escape sequence sits inside a nested value, or inside a date, keep failing. The nested case (c=[0\x2E5]) infersArray(Nullable(Float64))and the date case (x=2020-01-0\x31) infersNullable(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 anArraynor aDateis 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
Stringis treated as a header when a later row infers a number. Because0.0inferredStringwhile10.5inferredFloat64, the first data row was consumed as a column name and silently dropped: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 stayString, 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 ofinput_format_try_infer_integers, theTSVRawandTabSeparatedsiblings, several leading zeros with a fractional part, theDynamicruntime path, andTSKV(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 escapedDateand 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 withCode: 72rather than only on a type assertion; replacing the type test with an unconditional true fails only theinput_format_try_infer_integers = 0group; removing theTSKVguard fails group 15 withCode: 27, again on a read rather than on a type assertion; and dropping only theisNumberconjunct of theTSKVguard fails exactly the two rows asserting that an escapedDateand an escaped number inside an array keep their own inferred type. One mutation, dropping theNullableandLowCardinalitystrip, is undetected by design: for a field starting with0inference 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_statelesswas swept for a committed reference that depends on the old behaviour and none was found; the 39 candidates that mentionTSKVor sit in the TSV inference neighbourhood were all run and moved zero references, including02514_tsv_zero_started_number,02982_dont_infer_exponent_floats, and the two theTSKVguard could most plausibly have disturbed,02240_tskv_schema_inference_bugand02247_names_order_in_json_and_tskv. Three of the 39 fail identically on a pristine master binary for reasons unrelated to this change: a missingtest_shard_localhostcluster, an absentsystem.query_log, and an Avro schema registry.Version info
26.8.1.299(included in26.8and later)