Skip to content

Add parseISO8601Duration - #116993

Merged
yariks5s merged 9 commits into
ClickHouse:masterfrom
navneet83:parse-iso8601-duration
Sep 2, 2026
Merged

yariks5s merged 9 commits into
ClickHouse:masterfrom
navneet83:parse-iso8601-duration

Conversation

@navneet83

@navneet83 navneet83 commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Adds parseISO8601Duration, which parses an ISO 8601 duration string and returns the number of seconds as Float64.

There's currently no way to do this in ClickHouse, so people end up assembling it from extract calls and a chain of regular expressions, which quietly breaks on fractional seconds and week designators. The issue has a good example of one.

SELECT parseISO8601Duration('PT1H30M');        -- 5400
SELECT parseISO8601Duration('P1DT12H30M5.5S'); -- 131405.5
SELECT parseISO8601Duration('P2W');            -- 1209600

Years and months are rejected. Neither has a fixed length in seconds, so converting them needs either a reference date or an arbitrary average — and the averages already in the tree disagree with each other: parseTimeDelta uses 365 days and 30.5 days, IntervalKind::toAvgSeconds uses 365.2425 days. Adding a third would make that worse. java.time.Duration parses only PnDTnHnMn.nS for the same reason, and Temporal.Duration.total refuses calendar units without a relativeTo reference. P1Y and P1M throw BAD_ARGUMENTS naming the designator and saying what to use instead. There's more detail in the issue comment.

Design decisions

A few things ISO 8601 leaves open, or that the issue didn't pin down:

  • A fraction is accepted on any component, not only the smallest. Strict ISO allows it only on the lowest-order component present, which felt like a gratuitous rejection.
  • W can be combined with D. ISO 8601:2004 treats the week designator as exclusive, but java.time.Period allows combining and nothing breaks.
  • Comma is not accepted as a decimal separator, even though ISO permits PT1,5S. ClickHouse rejects comma decimals elsewhere and I kept that consistent.
  • Negative durations are rejected — they come from RFC 3339 / XSD, not core ISO 8601.
  • Designators must appear in canonical order and at most once, so PT1M1H and PT1S1S throw.

Happy to change any of these if you'd rather they went the other way.

Closes: #116905

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

New function parseISO8601Duration for parsing ISO 8601 duration strings such as PT1H30M into a number of seconds.


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

Parses an ISO 8601 duration string into a number of seconds, so that users do not
have to assemble it from `extract` calls and a chain of regular expressions.

The year designator and the month designator before `T` are rejected. Neither has a
fixed length in seconds, so converting them needs either a reference date or an
arbitrary average, and the averages already present in the codebase disagree with one
another: `parseTimeDelta` uses 365 days and 30.5 days, while
`IntervalKind::toAvgSeconds` uses 365.2425 days. Rejecting the two ambiguous
designators keeps the function exact and follows `java.time.Duration`, which parses
only `PnDTnHnMn.nS`, and `Temporal.Duration.total`, which refuses calendar units
without a reference point.

Closes: ClickHouse#116905
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [535253c]

Summary: ✅


AI Review

Summary

This PR adds parseISO8601Duration, documents its deliberate ISO 8601 deviations, and covers the main failure surfaces with focused stateless tests, including overflow, LowCardinality, Nullable, Dynamic, and Variant inputs. I re-checked the prior discussion against the current head and did not find any remaining correctness, contract, or evidence gaps in the changed surface.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 535253c.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

Changed lines: Changed C/C++ lines covered: 177/180 (98.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 29, 2026
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
Components were accumulated straight into a `Float64`, so a long enough run of digits
overflowed to infinity and was returned as a value rather than reported as an error.

Two checks are needed, not one: a component can be finite on its own and still overflow once
it is scaled to seconds, so the total is checked separately. `P` followed by 304 nines and `D`
is finite as a component and infinite as a number of seconds.

Found by the automatic review on the pull request.
@navneet83

Copy link
Copy Markdown
Member Author

Fixed in d7d7be7.

Two checks were needed rather than one. A component can be finite on its own and still overflow once it is scaled to seconds — P followed by 304 nines parses to a finite 1e304, and only becomes infinite after multiplying by 86400. So there is now an isfinite check on each parsed component and a second one on the accumulated total, with a stateless case for each.

Small note on the repro in the review: P + 309 nines + S was already rejected before this change, but for an unrelated reason — S outside the time section throws "unexpected designator 'S' before 'T'", since the seconds designator requires T. The overflow is reachable as PT + nines + S, which is what the test uses.

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 535253cfe with master 744240e35 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6d34bffad; 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.

Object file sizes

3 object files changed (+230.68 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/parseISO8601Duration.cpp.o new 230.68 KiB +230.68 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@navneet83 navneet83 added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 29, 2026
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
The function deliberately departs from ISO 8601 in four ways, and only the rejection of `Y` and
date-position `M` was written down. Accepting a fraction on any component rather than only the
lowest-order one, allowing `W` alongside the other designators, and rejecting both comma decimals
and signed durations are all user-visible, so they belong in the reference page the
`FunctionDocumentation` generates.

The stateless test also never exercised the comma or the sign, which are the two easiest to lose
during a parser cleanup.

Requested in the automatic review on the pull request.
@navneet83

Copy link
Copy Markdown
Member Author

Both addressed in b9aeb7a.

Docs — the description now covers all four deliberate deviations rather than just the Y/date-position M rejection: a fraction is accepted on any component rather than only the lowest-order one as ISO 8601 requires, W may be combined with the other designators unlike ISO 8601:2004, and neither a comma decimal separator (PT1,5S) nor a leading sign (-PT1S, from RFC 3339 and XML Schema) is accepted. The Float64 overflow rejection is noted too.

Tests — added BAD_ARGUMENTS cases for PT1,5S, P1,5D, -PT1S and +PT1S. The fraction-on-a-non-S-component branch was already covered by PT0.5H returning 1800.

Worth noting the two rejections arrive by different routes, which is why both spellings are tested: a sign fails the leading P check, while a comma is consumed as a unit designator and fails as an unexpected one. A parser cleanup could plausibly break either independently.

@navneet83

Copy link
Copy Markdown
Member Author

@yariks5s can we please merge this too?

@yariks5s yariks5s self-assigned this Aug 30, 2026
@navneet83
navneet83 requested a lite review from Copilot August 31, 2026 01:59

Copilot AI left a comment

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds a new ClickHouse scalar function parseISO8601Duration that converts ISO 8601 duration strings into seconds (Float64), with explicit rejection of year/month designators.

Changes:

  • Implements parseISO8601Duration with validation and detailed error reporting.
  • Adds stateless query tests for valid/invalid inputs, overflow handling, and argument validation.
  • Documents function behavior and design constraints in the function registration docs.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.

File Description
src/Functions/parseISO8601Duration.cpp Adds the new function implementation and user-facing documentation.
tests/queries/0_stateless/05048_parse_iso8601_duration.sql Adds functional and negative tests covering parsing rules and errors.
tests/queries/0_stateless/05048_parse_iso8601_duration.reference Adds expected outputs for the successful test cases.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Functions/parseISO8601Duration.cpp Resolved
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
Comment thread src/Functions/parseISO8601Duration.cpp Resolved
The bullet list said seconds may carry a fractional part, while a later paragraph said any component
may. Only the second is true, so state it once, next to the list it qualifies.

Requested in the Copilot review on the pull request.
@navneet83

Copy link
Copy Markdown
Member Author

Thanks — one of the three is a real inconsistency and is fixed in 14a6988. The other two I do not think apply here.

Fractional part in the docs — fixed. The bullet list attached the fraction to S while a later paragraph said any component may carry one. Only the second is true, so it is now stated once, immediately after the list.

std::string_view from getDataAt — there is no implicit conversion involved. IColumn::getDataAt returns std::string_view directly (src/Columns/IColumn.h:218: [[nodiscard]] virtual std::string_view getDataAt(size_t n) const = 0;), so this is copy-construction from a string_view, not a conversion from a StringRef-like type. It is also the same form the sibling function uses (src/Functions/parseTimeDelta.cpp:158).

Explicit includes for Exception and fmt::format — the general point about transitive includes is fair, but this file follows the convention of its neighbours rather than departing from it: parseTimeDelta.cpp throws Exception without including Common/Exception.h, and bech32.cpp uses fmt::format with no fmt include. Adding them here would make this file inconsistent with the rest of src/Functions. Happy to add them if a maintainer would prefer it, but I would rather not diverge on my own initiative.

@yariks5s yariks5s 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.

Also, in the issue it was requested to have OrNull and OrZero variants. Do you plan to make them or we don't need them anymore?

Comment thread src/Functions/parseISO8601Duration.cpp Resolved

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.

SELECT parseISO8601Duration(x)
  FROM (SELECT CAST(arrayJoin(['PT1S', 'PT2S']) AS LowCardinality(String)) AS x);

I think this will throw BAD_ARGUMENTS, because unused empty dictionary is parsed

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

useDefaultImplementationForLowCardinalityColumns is not overridden here, so it defaults to true (IFunction.h:100) and the function is applied to the dictionary, which carries the unused empty default that my parser rejects.

I could not confirm that without a build, so I have added your query as a test case in 6e6f243 instead. If it throws, Fast test will now say so and the fix is to override that implementation and handle the column directly. Leaving this open until CI reports.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Update: you were right, and CI reproduced it exactly on 6e6f243:

Code: 36. DB::Exception: Invalid argument of function parseISO8601Duration:
the duration is empty, str: "": while executing function parseISO8601Duration
on arguments __table1.x LowCardinality(String)
LowCardinality(size = 0, UInt8(size = 0), Unique(size = 1, String(size = 1)))

The dictionary always carries the default empty string whether or not any row references it, so the function was asked to parse "".

Fixed in 0ded5d8 by overriding canBeExecutedOnDefaultArguments, which is the same opt-out throwIf and digits use for this reason - the default LowCardinality implementation stays in place. Fast test passes on 0ded5d89.

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.

SELECT parseISO8601Duration(x)
  FROM (SELECT arrayJoin(CAST([NULL, 'PT1S'] AS Array(Nullable(String)))) AS x);

I think this example will throw as well.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

useDefaultImplementationForNulls defaults to true (IFunction.h:82), so the function runs over whatever sits under the null map. Added as a test case in the same commit, with sum so the expected value does not depend on arrayJoin ordering.
Worth noting parseTimeDelta and parseDateTime have the same shape with neither implementation overridden, so if this is a real bug it is not confined to this PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Update: right as well, though the test aborted on the LowCardinality query before reaching this one, so rather than spend another CI round finding out I traced the mechanism.

defaultImplementationForNulls runs the function over createBlockWithNestedColumns, i.e. over the values sitting under the null map, and only filters those rows out when null_ratio >= short_circuit_function_evaluation_for_nulls_threshold. That threshold defaults to 1.0, so the skip only happens when every row is null - the single non-null row in your example is enough to reach the empty string under the null and throw.

Fixed in the same commit by taking useDefaultImplementationForNulls off and handling the null map directly, so only values the caller actually supplied are parsed. The test now also covers parseISO8601Duration(NULL), a Nullable(String) null, and the Nullable(Float64) return type.

…guments

`introduced_in` said 26.10; the tree is at 26.9.1.1-testing, so a function merged now ships in 26.9.

Both `LowCardinality` and `Nullable` reach the function through the default implementations, which
apply it to the dictionary and to the values under the null map. Neither position holds a valid
duration, so if the function throws on them the two new cases fail and say so, rather than the
behaviour being argued about.

Raised in review on the pull request.
@navneet83

Copy link
Copy Markdown
Member Author

Thanks — all three addressed in 6e6f243.

introduced_in — you're right, taken. I had read 26.9 as already released; VERSION_DESCRIBE is v26.9.1.1-testing, so a function merged now ships in 26.9.

LowCardinality and Nullable — I could not verify either way without a build, and I would rather not guess at it, so I have added both of your queries as test cases instead. If you are right and they throw, CI will now say so and I will fix it; if they pass, the behaviour is pinned.

For what it's worth your reasoning looks sound to me: useDefaultImplementationForLowCardinalityColumns and useDefaultImplementationForNulls both default to true (IFunction.h:100 and :82), so the function is applied to the dictionary — including its unused default entry — and to whatever sits under the null map. The parser rejects an empty string, so both would throw. If the tests confirm it, the fix is to override those two and handle the columns directly. Note parseTimeDelta and parseDateTime have the same shape, so it may be worth a separate look at those.

I used ORDER BY and sum in the two cases rather than relying on arrayJoin ordering or on where NULL sorts, so the expected output is deterministic.

OrNull / OrZero — I did not include them, but they are worth having and I am happy to. Two things worth deciding first: #113560 asks for the same wrappers on parseTimeDelta, so the error-handling scaffolding could be written once and shared rather than twice; and if the Nullable case above turns out to throw, OrNull becomes the natural answer for dirty input and it would be better to design them together with that fix. Would you prefer them in this PR, or a follow-up once this one settles?

…ongside the data

Both default implementations hand the function values that no row asked about. The
`LowCardinality` one applies it to the whole dictionary, which always contains the
default empty string whether or not any row references it. The `Nullable` one applies
it to the nested column under the null map, whose contents are that column's defaults.
An empty string is not a duration, so in both cases the function threw and failed the
whole query.

Opt out of executing on default arguments, which is what keeps the dictionary's unused
default out of the call, and handle the null map directly so that only rows the caller
actually supplied are parsed.

`short_circuit_function_evaluation_for_nulls_threshold` defaults to 1.0, so the
`Nullable` path is only skipped when every row is null; a single non-null row was
enough to reach the values under the null map.

Co-Authored-By: Claude Opus 5 <[email protected]>
`sum` ignores nulls, so the mixed `Nullable(String)` case passed whether the null
row came back as null or as zero, and it would have kept passing if the null map
were dropped. Return the rows themselves, ordered with `NULLS LAST` so the
expected output does not depend on `arrayJoin` ordering.

Co-Authored-By: Claude Opus 5 <[email protected]>
@navneet83

Copy link
Copy Markdown
Member Author

@yariks5s both of your cases were real - thank you for catching them. Neither was covered and both would have shipped.

The LowCardinality one reproduced exactly as you described: the dictionary carries the default empty string whether or not a row references it, and the function threw on "". The Nullable one throws for a related reason - defaultImplementationForNulls executes over the values under the null map, and only skips them when every row is null, since short_circuit_function_evaluation_for_nulls_threshold defaults to 1.0.

Both fixed in 0ded5d8: canBeExecutedOnDefaultArguments opts out of the dictionary default, and the null map is now handled directly rather than through the default implementation. Fast test passes on 0ded5d89, having failed on the commit before it with precisely the error you predicted. bfcd94e then strengthened the null test after a review comment pointed out that sum cannot tell NULL from 0.

introduced_in is {26, 9} as you suggested - I had misread 26.9 as already released.

On OrNull and OrZero: I would prefer a follow-up, if that works for you. #113560 asks for the same pair on parseTimeDelta, so the wrappers seem worth writing once for both rather than twice. Happy to fold them in here instead if you would rather close the issue in one go.

One thing worth flagging beyond this PR: parseTimeDelta and parseDateTime have the same shape - neither overrides canBeExecutedOnDefaultArguments nor useDefaultImplementationForNulls - so if I have read this right, they reject a LowCardinality(String) column for the same reason this one did. I have not verified that and it is out of scope here, but it may deserve a separate issue.

Comment thread src/Functions/parseISO8601Duration.cpp Resolved
`useDefaultImplementationForDynamic` and `useDefaultImplementationForVariant` both
default to `useDefaultImplementationForNulls`, so taking that off to handle the null
map directly disabled them as a side effect. That left
`getReturnTypeForDefaultImplementationForDynamic` unreachable and sent a `Dynamic`
argument into `getReturnTypeImpl`, where `validateFunctionArguments` sees `Dynamic`
rather than `String` and rejects it.

Both adaptors dispatch on the concrete type held in the column and handle null rows
themselves, so enable them explicitly, as `UTMToGeo` does for the same reason. The
new cases compare against the plain `String` result so they do not depend on how the
adaptors spell the return type.

Co-Authored-By: Claude Opus 5 <[email protected]>
@yariks5s

yariks5s commented Sep 1, 2026

Copy link
Copy Markdown
Member

@navneet83 please update your branch with master, docs check in CI has been fixed today

@navneet83

Copy link
Copy Markdown
Member Author

Done, merged master in 535253c.

That was the failure I was seeing too - toYYYYMM(now(), 'US/Eastern') documented as 202608 and returning 202609 since the month rolled over. 26de122 fixes it.

@yariks5s
yariks5s enabled auto-merge September 2, 2026 17:27
@yariks5s
yariks5s added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit 2b87762 Sep 2, 2026
344 of 345 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@navneet83 @yariks5s — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@navneet83
navneet83 deleted the parse-iso8601-duration branch September 23, 2026 03:19
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-feature Pull request with new product feature 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.

parse ISO 8601 duration strings (e.g. PT1M, P3Y6M4DT12H30M5S) to Float64 seconds

6 participants