Skip to content

Read an ISO 8601 duration's number as one decimal - #117810

Merged
Algunenano merged 6 commits into
ClickHouse:masterfrom
navneet83:fix-iso8601-duration-fraction-rounding
Sep 10, 2026
Merged

Algunenano merged 6 commits into
ClickHouse:masterfrom
navneet83:fix-iso8601-duration-fraction-rounding

Conversation

@navneet83

@navneet83 navneet83 commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Closes: #117808
Related: #116993

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Documentation entry for user-facing changes

The fractional part was accumulated as value += digit * scale, with scale starting at 0.1 and multiplied by 0.1 at each step. Neither 0.1 nor any of its powers is representable in binary, so every term was rounded before it was added and the errors compounded:

SELECT parseISO8601Duration('PT0.7S');        -- 0.7000000000000001
SELECT parseISO8601Duration('PT0.7S') = 0.7;  -- 0

700 of the 1000 fractions PT0.<n>S differed from the double that the same decimal parses to. The integer loop had the same shape (value = value * 10 + digit) and lost exactness above 2^53.

The numeric substring now goes to tryReadFloatTextPrecise, which is documented as always returning the closest machine representable number to the input. Validation is unchanged - the substring still holds only digits and at most one decimal point, so there is no exponent for the reader to consume, and the existing rejections (P1.5, P1.D, PT1,5S, the overflow cases) keep working.

Why the tests missed it. Every fraction they used - PT1.5S, PT0.5H, P1DT12H30M5.5S - happens to be exactly representable, so the accumulated error was zero. The new cases check a decimal that is not representable and sweep all 1000 of PT0.<n>S against toFloat64 of the same decimal, which is a property rather than a handful of examples.

Introduced by #116993, so nothing released is affected.


Workflow [PR]
Sync PR [sync-upstream/pr/117810]

The fractional part was accumulated as `value += digit * scale` with `scale`
starting at 0.1 and multiplied by 0.1 each step. Neither 0.1 nor its powers is
representable in binary, so every term was rounded before it was added and the
errors compounded: `parseISO8601Duration('PT0.7S')` returned 0.7000000000000001,
`parseISO8601Duration('PT0.7S') = 0.7` was false, and 700 of the 1000 fractions
`PT0.<n>S` differed from the double the same decimal parses to. The integer loop
built the value the same way and lost exactness above 2^53.

Hand the numeric substring to `tryReadFloatTextPrecise` instead, which returns the
closest representable double to the input. Validation is unchanged: the substring
is still only digits and at most one point, so there is no exponent to read.

The tests only used fractions that happen to be representable - 0.5, 1.5, 5.5 -
which is why this was not caught. They now check a decimal that is not, and sweep
all 1000 of `PT0.<n>S` against `toFloat64` of the same decimal.
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dadf40d]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Server unresponsive: memory limit exceeded FAIL cidb IGNORED

AI Review

Summary

This PR replaces digit-by-digit accumulation in parseISO8601Duration with tryReadFloatTextPrecise, so fractional and large-integer components now round the same way as other Float64 parsing paths. I did not find any remaining correctness, compatibility, or evidence gaps in the current diff; the earlier underflow/overflow concern does not apply because tryReadFloatTextPrecise treats result_out_of_range as a successful parse and still leaves 0 or inf for the caller to distinguish.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit dadf40d.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 14/16 (87.50%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dadf40df6 with master b666e5df6 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

I traced the new number path end to end and the fix is correct for the claimed shape: the scanner still enforces digits-plus-at-most-one-dot before the substring is built (leading . and empty fractions are still rejected, a comma still falls out as an unexpected designator), so tryReadFloatTextPrecise only ever sees \d+(\.\d+)? and no exponent/sign/inf/nan surface opens up. ReadBufferFromMemory guarantees the precise fast path, which is correctly-rounded from_chars over exactly the substring — PT0.7S is exact and the past-2^53 case matches toFloat64 parity as the test asserts.

One behavior change looks unintended, though. The vendored fast-float sets result_out_of_range not only on overflow to infinity but also when a nonzero mantissa underflows to exactly 0, and tryReadFloatTextPrecise turns any nonzero error code into false, which this PR maps to the "could not read the number" rejection at parseISO8601Duration.cpp:191. So SELECT parseISO8601Duration(concat('PT0.', repeat('0', 324), '1S')) — a syntactically valid duration — now throws BAD_ARGUMENTS, where the pre-PR accumulation loop returned 0. The cliff is inconsistent: PT0. + 323 zeros + 5S still parses (it rounds to a subnormal, error code 0), one more zero throws — the rejection tracks "rounded to exactly zero", not "too small". It also contradicts the function's own documentation at the head, which scopes rejection to values that do not fit into Float64 (0 fits). The clean fix is to treat result_out_of_range with a finite result as success — that value is the closest representable number — and reject only the infinity case.

Related, minor: per-component overflow (PT + 309 nines + S) now also comes back as result_out_of_range, so it reports "could not read the number at position 2" instead of the dedicated component-too-large message, wrongly implying malformed input; the !std::isfinite(value) check right below is now unreachable for a single component because from_chars never returns success with infinity for digit-only text. The same finite-vs-infinite split on the error code restores the intended message.

Since the function is new in this development cycle, both are bug-in-PR observations, not released regressions.

@Algunenano Algunenano self-assigned this Sep 3, 2026

@Algunenano Algunenano left a comment

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.

LGTM, but since this wasn't part of any release it should not be tagged as BugFix, and instead we should simply use Not For Changelog

The comment claimed the integer part stays exact past 2^53, which no `Float64` can
do - `toFloat64('9007199254740993')` is already 9007199254740992. The assertion is
parity with `toFloat64` on the same decimal text, which is the contract the fix
gives; say that instead.
@navneet83

Copy link
Copy Markdown
Member Author

Thanks for tracing it that carefully - the first part matches what I intended, so it is good to have it confirmed independently.

On the two behaviour notes though, I think they rest on tryReadFloatTextPrecise mapping every nonzero error code to false, and I do not believe it does. Both parseFloatFromRange call sites in readFloatTextPreciseImpl let result_out_of_range through, with a comment for exactly this case (readFloatText.cpp:366-368):

/// result_out_of_range means overflow/underflow: fast_float has already set x to +-inf or +-0,
/// matching strtod semantics. Only a genuine parse failure is an error.
if (unlikely(res.ec != std::errc() && res.ec != std::errc::result_out_of_range))

and the same condition on the slow path at :452. So as I read it:

  • PT0. + 324 zeros + 1S underflows, x is set to 0, the reader returns true, and the function returns 0 - the same as the accumulation loop did. No BAD_ARGUMENTS.
  • PT + 309 nines + S overflows, x is set to inf, the reader still returns true, so the !std::isfinite(value) check below is reached and the dedicated "numeric value of a component is too large to represent" message is what fires. That check is not unreachable.

Which would mean the fix you suggest - treat result_out_of_range with a finite result as success and reject only infinity - is already what the reader does, so doing it again in the caller would be dead code.

I would rather be wrong about this than leave a hole, so if you traced a different path to false for those two inputs, could you point me at it? There is a tryReadBigIntegerToFloat branch for long digit strings that I have only read rather than followed, and the 309-nines case would go through it, so that is the most likely place for me to be missing something.

@navneet83

Copy link
Copy Markdown
Member Author

@yariks5s could you take a look at this one when you get a chance? It is a defect in #116993 that you merged, not a new feature - the fractional part was accumulated as digit * 0.1^k, so parseISO8601Duration('PT0.7S') = 0.7 came back false and 700 of the 1000 PT0.<n>S fractions were off. It now goes through tryReadFloatTextPrecise.

Merged master in 16e2d00, so the Docs examples failure is gone. Only CH Inc sync is left and that is an unused namespace fs alias in TransactionManager.cpp on the private side, nothing to do with this.

@navneet83 navneet83 added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 3, 2026
@navneet83

Copy link
Copy Markdown
Member Author

Thanks - you are right, and the PR body already said as much ("Introduced by #116993, so nothing released is affected") while the category said Bug Fix, which was inconsistent of me. Changed to Not for changelog and swapped the label to pr-not-for-changelog.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b2d94d0d-d4d1-455a-aef6-aca8c549cf8b
  • MIRAI run: fdbe10bb-d76c-46a9-b12e-a3caf23d837a
  • PR check IDs:
    • clickbench_1563019_1788817221
    • clickbench_1563025_1788817221
    • clickbench_1563031_1788817221
    • tpch_adapted_1_official_1563042_1788817221
    • tpch_adapted_1_official_1563054_1788817221
    • tpch_adapted_1_official_1563091_1788817221

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
@navneet83

Copy link
Copy Markdown
Member Author

For whoever picks this up: Algunenano's approval is on 91d74ec8d. The only commits since are 1262e3a05, which rewords a comment about the past-2^53 case, and a master merge — nothing behavioural changed after the review.

Green on the current head, branch is clean.

@qoega
qoega added this pull request to the merge queue Sep 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 6, 2026
@navneet83

Copy link
Copy Markdown
Member Author

@qoega thanks for queueing this. It was ejected by the pre-merge hook rather than by anything in the change:

ERROR: Sync PR #72299 in ClickHouse/clickhouse-private has conflicts and cannot be merged
Fail [python3 ./ci/jobs/scripts/workflow_hooks/check_sync_pr_mergeable.py]

Every real job (Fast test, builds, style) was dropped rather than run. The branch was 2062 commits behind master, and while it still merged into public master with no conflicts, the sync mirror had gone stale.

I have merged current master in — 2ceedee — so the mirror should refresh. Happy to re-queue whenever suits you.

I have done the same for #117977 and #118005, which were from the same week and would have hit this on their way in.

@Algunenano

Algunenano commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

@navneet83 Please tone down the AI messages. You should own and handle your PRs and messages

@Algunenano
Algunenano added this pull request to the merge queue Sep 10, 2026
Merged via the queue into ClickHouse:master with commit 5bc0675 Sep 10, 2026
173 of 175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-not-for-changelog This PR should not be mentioned in the changelog 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.

parseISO8601Duration accumulates fractions by repeated *=0.1, not correctly rounded

4 participants