Skip to content

Send the update_field bound of the ClickHouse dictionary source as a Unix timestamp for non-text columns - #127765

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-dictionary-update-field-bound-time-zone
Nov 2, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-dictionary-update-field-bound-time-zone

Conversation

@groeneai

@groeneai groeneai commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #98708
Related: #125510

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

Fixed incremental updates (update_field) of dictionaries with a ClickHouse source. The lower bound was sent as the server's local time, so it was shifted when the column's time zone differed from the server's (for example, with a DateTime('UTC') column on a server east of UTC, new rows were never loaded), and in the hour repeated at the end of DST every update re-read the last hour of rows. The bound is now sent as a Unix timestamp for non-text columns.

Description

02530_dictionaries_update_field_hashed and _complex_key_hashed hit the 600 s deadline waiting for SecondUpdated in jobs started on 2026-10-25 00:05-01:40 UTC, for example this job of #98708.

On 26.8.28.14, a dictionary with SOURCE(CLICKHOUSE(... UPDATE_FIELD 't')) over a DateTime('UTC') column on a server with TZ=Europe/Amsterdam never loads rows inserted after the first load.

getUpdateFieldAndDate formatted previous update time - update_lag as wall-clock text in the server's time zone, and the receiving server parses update_field >= '<text>' in the column's time zone. In the repeated hour the text is ambiguous and resolves to the first occurrence, so CI servers (Europe/Amsterdam) re-read Second together with SecondUpdated on every update, and hashed layouts keep the first fetched row of a key (flat keeps the last one and passed).

The bound is now if(toTypeName(update_field) LIKE '%String%' OR toTypeName(update_field) LIKE '%Dynamic%', '<local text>', '<Unix timestamp>'), so a column that can hold text is still compared as text. Other types get the timestamp, clamped at 0 and padded to 10 digits (a shorter number is rejected or read as YYYYMMDD), which DateTime/DateTime64 parse as the same instant in any time zone and date_time_input_format. The if folds to a constant, so the primary key is still used, with both analyzers (checked on 26.3, 26.8, 26.10). Date fails as before. Other sources keep the text.

The new test puts the bound with update_lag in the repeated hour, failing on master with the server in Europe/Amsterdam, UTC and Asia/Tokyo, and at an 8-digit timestamp, failing without the padding. String, Dynamic and SimpleAggregateFunction(anyLast, Dynamic) arms fail when text is compared with the timestamp. It passes 20 times with random settings.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1127-master (included in 26.11 and later)

…Unix timestamp

ClickHouseDictionarySource::getUpdateFieldAndDate formatted the lower bound of
an incremental update (previous update time - update_lag) as wall-clock text in
the server's default time zone, and the receiving server parses
`update_field >= '<text>'` in the column's time zone. So:

- when the column's zone differs from the server's (DateTime('UTC') on a
  non-UTC server, a remote server in another zone), the bound is shifted by the
  difference all the time; east of the column's zone it lies in the future and
  rows inserted after the first load are never loaded (measured on 26.8.28.14
  and 26.9.19.9 with TZ=Europe/Amsterdam);
- in the hour repeated at the end of DST the text is ambiguous and resolves to
  the first occurrence, so during the second pass every update re-reads the
  last hour. CI servers run in Europe/Amsterdam; on 2026-10-25 01:00-02:00 UTC
  02530_dictionaries_update_field_{hashed,complex_key_hashed} re-read 'Second'
  together with 'SecondUpdated' on every update, and a hashed layout keeps the
  first fetched row of a key, so the tests timed out ('flat' keeps the last
  row and passed).

A decimal Unix timestamp is read by the DateTime/DateTime64 text parsers as
the same instant in every zone and every date_time_input_format. Integer
update fields now work too; Date/Date32 still fail; a String update_field now
matches every row on each update. Sources that send the text to an external
system (MySQL, PostgreSQL, ODBC, HTTP, executable) are unchanged: there the
external system defines how the text is read.

The new test sets update_lag so that the bound falls in the repeated
Europe/Amsterdam hour on a DateTime('Europe/Amsterdam') column; it fails on
master with the server in Europe/Amsterdam, UTC and Asia/Tokyo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ A String update_field now matches every row ('1792891800' sorts before '2...'), so each update reads the whole table, and with several source rows per key a hashed layout keeps the first one (ClickHouseDictionarySource.cpp:112) DISAGREE The mechanism is real and is stated in the description. With unique keys the result stays correct (a full read). Keeping the first of several rows per key is what hashed already does on every full load (HashedDictionary.h:1105-1112). The documented contract is the previous update time in seconds, and no String type is documented. Every exact-instant alternative breaks a type: toDateTime(<ts>) turns a String field into NO_COMMON_TYPE.
2 ⚠️ The test covers only a DateTime('Europe/Amsterdam') field, not integer or DateTime64 fields DISAGREE The bound is one type-independent text; a 10-digit string is whole seconds for DateTime64 too (ReadHelpers.h:1288-1291, covered by 01732_more_consistent_datetime64_parsing). Measured end to end through a hashed dictionary: DateTime64(3), DateTime64(6, 'UTC'), DateTime64(9, 'Asia/Kolkata'), UInt32 and Int64 load exactly the expected rows with the fix.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261025-041300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test sets update_lag so that the bound falls at 2026-10-25 01:30 UTC (second pass of the repeated Amsterdam hour). It fails 10/10 on master with random settings.
b Root cause explained? getUpdateFieldAndDate sent the bound as wall-clock text in the server's zone. The receiver parses it in the column's zone, so the bound shifts by the zone difference, and in the repeated DST hour it resolves to the first occurrence (1 h early). hashed keeps the first of the duplicate fetched rows, so SecondUpdated never showed up.
c Fix matches root cause? Yes. The bound is now a Unix timestamp, which names one instant in every zone. No test was widened or retagged.
d Test intent preserved / new tests added? New regression test 05448_dictionary_clickhouse_source_update_field_time_zone, covering the table form and the custom {condition} query. The 02530_* files are untouched and pass 15/15.
e Both directions demonstrated? Master FAIL and fix OK with the server in Europe/Amsterdam (+row below the bound), UTC (+row below the bound) and Asia/Tokyo (-row above the bound). The server log shows t >= '2026-10-25 02:30:00' before the fix and t >= '1792891800' after it. 50/50 OK with random settings.
f Fix is general across code paths? getUpdateFieldAndDate is the only producer of the bound for the ClickHouse source (local and remote, table and query forms). The MySQL/PostgreSQL/ODBC/HTTP/executable sources stay unchanged, because the external system defines how the text is read.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested end to end through a hashed dictionary. DateTime, DateTime64(3), DateTime('UTC'), DateTime64(6,'UTC'), DateTime64(9,'Asia/Kolkata') and Nullable(DateTime) are exact. UInt32/Int64 used to fail and now work. Date/Date32 fail as before. String now re-reads all rows.
h Backward compatible? (maintainer-approved exception only) No setting or format change. ClickHouse has read a Unix timestamp as DateTime text for a long time, so remote servers of older versions accept it. The only behaviour change is for a String update_field, which is disclosed in the description.
i Invariants and contracts preserved? update_time bookkeeping, the first full load, the copy constructor and the update_lag arithmetic are unchanged. Only the text of the bound literal changes.

Session id: cron:clickhouse-impl-slot-6:20261025-030700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @vitlibar, could you review this and add the can be tested label so CI runs? The ClickHouse dictionary source sent the update_field lower bound as server-local wall-clock text, which the receiving server parses in the column's time zone, so the bound was shifted for a column in another zone and ambiguous in the repeated DST hour; it is now sent as a Unix timestamp.

@clickhouse-gh

clickhouse-gh Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c73d1c]

Summary: ✅


AI Review

Summary

This PR fixes time-zone-dependent incremental dictionary updates by sending a padded Unix timestamp for non-text ClickHouse source columns while preserving text comparisons for columns that can hold text. Reviewed head 7c73d1ce573d164f8e10759cc797ea8e81f3d405: no remaining actionable findings. The earlier text-valued Dynamic regression, including SimpleAggregateFunction wrappers, is addressed and covered by the new regression test. Preserving existing comparisons for text-capable Dynamic and Variant columns is an accepted compatibility tradeoff.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). labels Oct 25, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 47739a3

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

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while the master this head was tested on still says its default became true in 26.10 (same 1 / 0 row on every PR since 2026-10-24 04:17Z). The fix merged at 11:26Z, after this run started, and is absent from the tested merge commit #127687 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #127687 (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261025-133007

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The fix looks right for every time-typed column. I checked on master that '1792891800' compares as the same instant for DateTime('Europe/Amsterdam'), DateTime64(3, 'UTC'), DateTime64(9, 'Asia/Kolkata'), UInt32 and Nullable(DateTime('UTC')), with date_time_input_format set to basic, best_effort and best_effort_us.

A String update_field needs a line in the changelog entry

With a String or LowCardinality(String) column holding 'YYYY-MM-DD hh:mm:ss' text, the old bound compared correctly as text. '1792891800' sorts below every such value, so every update now reads the whole table. When the source has several rows for one key, for example an append-only change log, the rows within an update block don't overwrite each other: the first one fetched for a key wins, and it replaces the newer value already in the dictionary. So the dictionary can go back to an older value on every update. Before, incremental updates fetched only the newer rows, and those replaced the old values.

A String update_field isn't documented, so I don't think this should block the PR. But it is a silent change for anyone who uses one. Could you add something like this to the changelog entry?

An update_field stored as text (String) now matches every row on each update; store it as DateTime to keep incremental updates.

Minor: hr_time = update_time - update_lag is negative when update_lag is larger than the current time. '-5' doesn't parse as DateTime, so the update query fails, where the old text formatting clamped it. Under best_effort, a bound of 8 digits or fewer (before 1973) can also be read as YYYYMMDD. Both need an update_lag of decades, so a std::max<time_t>(hr_time, 0) or a comment is enough.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai are you also sure this is portable to other OS, c++ compilers and is it safe for timezones and locales?

A bound below 0 (update_lag larger than the current time) was sent as
`'-100'`, which no DateTime type accepts, so every update failed. A bound
with fewer than 9 digits (before 1973) is rejected, or read as `YYYYMMDD`
by the DateTime parser: `'20000101'` matched 2000-01-01 and skipped rows
from 1970. A 10-digit number is read as a Unix timestamp by every DateTime
type and every `date_time_input_format`, and integer columns ignore the
leading zeros. The test gains an 8-digit bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7c73d1ce5 with master ffdc946f5 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ac6858960; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. Both points are in e36e37a.

  • Changelog entry: I added your sentence about a String update_field.
  • Negative or short bound: std::max alone is not enough, because '0' is rejected too. With the types and date_time_input_format values from your check, every bound shorter than 9 digits, including '0' and '-5', fails with CANNOT_PARSE_DATETIME for DateTime/DateTime64 or is misread ('20000101' as 2000-01-01). A zero-padded 10-digit bound ('0000000000', '0012345678') compares as the right instant in all of them, and UInt32/Int64 ignore the leading zeros. So the bound is now fmt::format("{:010}", std::max<time_t>(hr_time, 0)), the same form AuthenticationData.cpp uses for VALID UNTIL. On a hashed dictionary with the previous commit, a negative bound made every update fail and '20000101' dropped a row from 1970; with this one both load all rows. The test gains the 8-digit case, which fails without the padding.

Portability, time zones, locales:

  • fmt is the bundled contrib/fmtlib, and integer formatting without the L specifier does not read the locale, so the output is plain ASCII digits with no grouping on every OS. Only Clang is supported (cmake/tools.cmake), so there is no other compiler to consider.
  • The time_t arithmetic is unchanged. After the clamp the value is between 0 and the current time, so it is exactly 10 digits until 2286.
  • A 10-digit number is read as a Unix timestamp without any time zone lookup (parseDateTimeBestEffort.cpp:362-368), which matches your matrix.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai On second thought, the String case needs a fix rather than a changelog line. When the source has several rows per key, a hashed dictionary now goes back to an older value on every update, which is a regression in correctness, not just in performance.

A constant that picks its form from the column type keeps the old text comparison for text columns and the Unix timestamp for everything else:

update_field >= if(toTypeName(update_field) LIKE '%String%', '<old local text>', '<10-digit timestamp>')

On master with the server in Europe/Amsterdam and the bound in the repeated DST hour, it gives the correct rows for DateTime('Europe/Amsterdam'), DateTime64(3, 'UTC'), Nullable(DateTime('UTC')), UInt32, Int64, String, LowCardinality(String) and Nullable(String). The if folds to a constant, so the primary key is still used (EXPLAIN indexes = 1 reads 23 of 45 granules for both a DateTime64 and a String key), including with enable_analyzer = 0 for older remote servers. Could you send that (the old DateLUT::instance().timeToString(hr_time) next to the padded timestamp), drop the String sentence from the changelog entry, and add a String column to the test?

…tamp

A `String` update_field holding 'YYYY-MM-DD hh:mm:ss' text sorted every
row above the 10-digit timestamp bound, so each incremental update re-read
the whole source. With several source rows per key, a `hashed` dictionary
keeps the first fetched row of a key, so it could go back to an older value
on every update.

The ClickHouse source now sends
`update_field >= if(toTypeName(update_field) LIKE '%String%', '<local text>', '<timestamp>')`.
The `if` folds to a constant on the receiving server, so the primary key is
still used, and the form works with both analyzers (measured on 26.3, 26.8
and 26.10). The other sources keep sending the quoted local text.

The test gains a `String` update_field; it fails without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Send the update_field bound of the ClickHouse dictionary source as a Unix timestamp Send the update_field bound of the ClickHouse dictionary source as a Unix timestamp for non-text columns Nov 2, 2026
@groeneai

groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

Done in f737654.

  • Bound: the ClickHouse source now sends update_field >= if(toTypeName(update_field) LIKE '%String%', '<DateLUT::instance().timeToString(hr_time)>', '<padded timestamp>'), in both the generated query and the {condition} of a custom query. To pass an expression instead of a quoted literal, ExternalQueryBuilder gained composeUpdateQueryWithBound, and composeUpdateQuery now wraps it with the quotes, so the MySQL, PostgreSQL and ODBC queries are byte-identical.
  • Checked: on 26.3, 26.8 and 26.10 with enable_analyzer 0 and 1, your type list plus FixedString(19) returns the right rows with the bound in the repeated hour, and the primary key is used for both a DateTime64 and a String key.
  • Changelog: the String sentence is removed; the entry and the title now say the timestamp is for non-text columns.
  • Test: 05448 gains a String update_field for both the table and the {condition} query. It holds UTC text two days from the bound, so the server and session time zones do not matter. It fails on the previous head (the row below the bound is re-read in all four String iterations) and passes 20 times with random settings; the 02530 family passes as well.

groeneai and others added 2 commits November 2, 2026 11:14
`toTypeName` of a `Dynamic` column is `Dynamic`, so it got the 10-digit
timestamp bound, while the comparison dispatches on the contained values:
a `Dynamic` holding 'YYYY-MM-DD hh:mm:ss' text compared every row above the
bound as text, so each update re-read the whole source, the same rollback
the `String` case had. A `Dynamic` column is now compared with the local
text, as before this PR. A per-row choice is not possible with a constant
bound: a `Dynamic` holding `DateTime` rejects a non-constant `String`
right-hand side (`NO_COMMON_TYPE`). A `Variant` with a `String` variant
already matched `%String%`.

Measured in Europe/Amsterdam with the bound in the repeated DST hour on
26.3, 26.8 and 26.10, both analyzers: the exact rows for every ordinary
type and for `Dynamic` text, and the same granules read for a `DateTime64`
and a `String` primary key.

The test gains a `Dynamic` update_field (the source table moves from
`TinyLog`, which rejects `Dynamic`, to `Memory`); it fails without this
change. The 8-digit bound is checked for the timestamp form only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`toTypeName` of `SimpleAggregateFunction(anyLast, Dynamic)` does not
start with `Dynamic`, so a column of that type holding
'YYYY-MM-DD hh:mm:ss' text got the 10-digit timestamp bound and every
update re-read the whole source, the rollback the `Dynamic` case had.
The guard now matches `Dynamic` anywhere in the type name.

Census in Europe/Amsterdam with the bound in the repeated DST hour, 33
column types (`String`/`FixedString`/`Dynamic` under `Nullable`,
`LowCardinality`, `Variant`, `SimpleAggregateFunction`, JSON paths, and
the time and numeric types, including `SimpleAggregateFunction` over
them), on 26.3, 26.8 and this build: only the three
`SimpleAggregateFunction(..., Dynamic)` shapes differed from the
released text bound before this change, and every type now selects the
exact rows. A `DateTime64` and a `String` primary key still read 41/64
and 40/64 granules with both analyzers.

The test gains a `SimpleAggregateFunction(anyLast, Dynamic)`
update_field; it fails without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit 45925e5 Nov 2, 2026
179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
@Algunenano

Copy link
Copy Markdown
Member

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged. The time goes into ten sequential waits for an incremental dictionary update: the external loader checks for outdated dictionaries every 5 s (ExternalLoader.cpp, check_period_sec), and SYSTEM RELOAD DICTIONARY does a full load, so it cannot replace the wait. I'll make the ten cases share one update cycle, or tag the test no-fasttest if that is still too slow, and post the PR here.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in #129298: the ten cases now share one round of dictionary updates, so the test takes about 5 s instead of about 49 s (debug build, median of 20 runs, max 5.3 s) with the same output, and it stays in the fast test.

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 comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). 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.

5 participants