Skip to content

Fix UBSan null deref in StorageTimeSeries constructor - #104905

Merged
alexey-milovidov merged 12 commits into
masterfrom
fix-storage-time-series-null-deref
May 20, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
fix-storage-time-series-null-deref

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 14, 2026 •

Copy link
Copy Markdown
Member

When a TimeSeries table is constructed with an external (non-inner) metrics table, the constructor calls tryGetTable to check the target table's columns for LowCardinality. During ATTACH (server startup), the target table may not yet be loaded, so tryGetTable returns nullptr. The code then unconditionally dereferences it to call getInMemoryMetadataPtr, triggering a UBSan "member call on null pointer" error and aborting the server (with abort_on_logical_error.yaml enabled in stress tests).

Symptom in CI:

src/Storages/StorageTimeSeries.cpp:171:36: runtime error: member call on null pointer of type 'DB::IStorage'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /ClickHouse/src/Storages/StorageTimeSeries.cpp:171:36

Reproduction surface: https://s3.amazonaws.com/clickhouse-test-reports/PRs/97254/44e317738d517ea52e1fbf4bb87a75c512c8f60a/stress_test_amd_asan_ubsan/clickhouse-server.log.zst (surfaced as "Cannot start clickhouse-server" in the Stress test (amd_asan_ubsan) report for #97254 - the failure itself is unrelated to that PR).

Root cause: commit 16e69df ("make getInMemoryMetadataPtr aware of context") rewrote table->getInMemoryMetadataPtr() to table->getInMemoryMetadataPtr(getContext(), false) but kept the implicit assumption that tryGetTable always returns non-null.

Fix: only perform the LowCardinality validation when tryGetTable returns a non-null pointer. If the target table can't be resolved right now (typically because we are attaching tables at startup), the check is skipped - the next time the table is created the validator will catch any unsupported columns.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Fix UBSan null pointer dereference in StorageTimeSeries constructor when the external metrics target table is not yet loaded.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No documentation needed - internal fix to silence a UBSan error that aborted the server during stress tests on ASan+UBSan builds.

Version info

  • Merged into: 26.5.1.869

When a `TimeSeries` table is constructed with an external (non-inner)
metrics table, the constructor calls `tryGetTable` to check the target
table's columns for `LowCardinality`. During `ATTACH` (server startup),
the target table may not yet be loaded, so `tryGetTable` returns
`nullptr`. The code then unconditionally dereferences it to call
`getInMemoryMetadataPtr`, triggering a UBSan "member call on null
pointer" error.

The bug surfaces in stress tests that build with UBSan and abort on
logical error: e.g.
https://s3.amazonaws.com/clickhouse-test-reports/PRs/97254/44e317738d517ea52e1fbf4bb87a75c512c8f60a/stress_test_amd_asan_ubsan/clickhouse-server.log.zst

```
src/Storages/StorageTimeSeries.cpp:171:36: runtime error: member call on null pointer of type 'DB::IStorage'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /ClickHouse/src/Storages/StorageTimeSeries.cpp:171:36
```

Caused by commit 16e69df ("make `getInMemoryMetadataPtr` aware of
context"), which rewrote
`table->getInMemoryMetadataPtr()` to
`table->getInMemoryMetadataPtr(getContext(), false)` without adding the
missing null check.

Fix: only perform the `LowCardinality` validation when `tryGetTable`
returns a non-null pointer. If the target table can't be resolved
right now (typically because we are attaching tables at startup), the
check is skipped — the next time the table is created the validator
will catch any unsupported columns.

Surfaced in CI for #97254
but unrelated to that PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59dbf62]

Summary: ✅


AI Review

Summary

This PR fixes a null dereference in StorageTimeSeries during ATTACH when an external METRICS target table is not loaded, scopes the external metrics validation to CREATE (to avoid attach-order-dependent behavior), and adds a focused regression test (04238_attach_timeseries_external_metrics). I reviewed the current diff and code plus all prior discussion threads; previously raised concerns are addressed, and I found no remaining correctness, safety, or coverage gaps in the changed surface.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 14, 2026
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
The `LowCardinality` check on the external `METRICS` target now runs only
when `mode < LoadingStrictnessLevel::ATTACH`, matching the gating used by
`validator.validateColumns` immediately above. This removes the
attach-order-dependent behaviour the bot reviewer flagged: at server
startup the target table may or may not be loaded yet, and we should not
re-validate something that was already validated at CREATE time.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
At CREATE time `initTarget` has already resolved the external metrics
target via `DatabaseCatalog::getTable`, which throws if the table is
missing. Using `tryGetTable` here for the `LowCardinality` validation
created a fail-open path: if lookup unexpectedly returned `nullptr`,
the validation was silently skipped and an unsupported schema could be
accepted. Switch back to `getTable` to keep the validation contract
deterministic and consistent with the project's fail-close policy.

The original UBSan null-deref scenario only happens during `ATTACH`,
which is already gated by `mode < LoadingStrictnessLevel::ATTACH`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CI failures on this PR are unrelated to the StorageTimeSeries change:

@groeneai, please investigate the amd_msan WasmEdge system log flush timeouts and file/track an umbrella flaky issue if one is missing. If a fix is already in progress, please link it here.

Comment thread src/Storages/StorageTimeSeries.cpp Resolved

@Ergus Ergus 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. However I think that this should be considered a "Bug Fix" not a "CI Fix or Improvement"

@Ergus Ergus self-assigned this May 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Follow-up: the latest CI run also surfaced two failures not in my previous comment, both confirmed unrelated to StorageTimeSeries:

alexey-milovidov and others added 3 commits May 15, 2026 00:09
The previous commits gate the `StorageTimeSeries` constructor's external
metrics validation behind `mode < LoadingStrictnessLevel::ATTACH`, mirroring
the existing `validateColumns` gating. Without the fix, attaching a
`TimeSeries` table whose external metrics target was not yet loaded would
dereference a null pointer returned by `tryGetTable` and crash.

The new test reproduces the ordering by detaching both tables and then
re-attaching the `TimeSeries` table before its external metrics target.

Verified locally: with the previous (buggy) binary the `ATTACH` call hits a
`SIGSEGV` in `StorageTimeSeries::StorageTimeSeries`; with the fix the test
passes.

Addresses review feedback on #104905.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ated`

The experimental `TimeSeries` table engine does not round-trip through
`DatabaseReplicated`: `DETACH`/`ATTACH` of the metrics target hangs the
test cleanup, which then hung the entire CI run (719s timeout for this
test, then 114 cascading HTTP timeouts).

Add `Tags: no-replicated-database`, mirroring the other `TimeSeries`
tests (`04131_prometheus_query_parser`, `04202_prometheus_query_datetime64_nanosecond_modern_timestamp`).

CI report: #104905

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed two updates:

  1. Skip 04238_attach_timeseries_external_metrics under DatabaseReplicated (the experimental TimeSeries engine doesn't round-trip through it; the test was hanging the cleanup query, causing 114 cascading HTTP timeouts in the Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) run). This mirrors 04131_prometheus_query_parser and 04202_prometheus_query_datetime64_nanosecond_modern_timestamp.
  2. Merged master.

Remaining red checks look unrelated to this PR:

  • AST fuzzer (amd_debug, targeted) / (...old_compatibility) — same fuzz pattern as the open issue #104459 (same STID prefix 4870, AggregateFunctionArray combinator).
  • Stress test (amd_asan_ubsan) — Hung check failed, possible deadlock found; the hung threads are doing query analysis for naiveBayesClassifier / arrayZipUnaligned, completely unrelated to StorageTimeSeries. This check also failed on master at 2026-05-13.

@groeneai, could you investigate the AST fuzzer failure (open issue #104459) and the Stress test (amd_asan_ubsan) hung check at #104905 in a separate PR if a fix isn't already in progress? Both look pre-existing and unrelated to this PR.

Comment thread src/Storages/StorageTimeSeries.cpp Resolved
`LowCardnality` -> `LowCardinality` so diagnostics stay searchable
and consistent with the type name.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master to pick up any flaky-test fixes since the last run.

One newly observed unrelated failure on the previous CI run:

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) -> test_storage_kafka/test_batch_fast.py::test_kafka_engine_put_errors_to_stream_with_random_malformed_json (AssertionError: assert 54 == 64). This test has failed on 5 distinct unrelated PRs in the last 30 days and 0 times on master — a flaky integration test, not specific to this PR.

@groeneai, please track test_kafka_engine_put_errors_to_stream_with_random_malformed_json as a flaky test (no open issue exists) and provide a fix in a separate PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed via CIDB — tracking test_kafka_engine_put_errors_to_stream_with_random_malformed_json as flaky. Same assert 54 == 64 symptom (10 missing error rows) on PR #96886, PR #104902 and this PR (#104905) in the last 14 days, all in Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6). Across both parametrized variants ([generate_old_create_table_query] + [generate_new_create_table_query]) the test hit 23 failures across 5 distinct unrelated PRs in 30 days and 0 times on master/release.

The failing test (tests/integration/test_storage_kafka/test_batch_fast.py:2829) waits for Committed offset 128 and then asserts _data and _errors row counts immediately:

instance.wait_for_log_line(f"{kafka_table}.*Committed offset 128")
assert TSV(instance.query(f"SELECT count() FROM test.{kafka_table}_data")) == TSV("640")
assert TSV(instance.query(f"SELECT count() FROM test.{kafka_table}_errors")) == TSV("64")

The Kafka offset commit and the materialized view's INSERT flush into the destination MergeTree are not strictly ordered — Committed offset 128 can land in the log before the last _errors block has finished flushing. The author of the helper even acknowledged this elsewhere in the same file (tests/integration/helpers/kafka/common.py:463):

Since everything is async and shaky when receiving messages from Kafka, we may want to try and check results multiple times in a loop.

This is the same family I'm already tracking as a chronic flake — test_storage_kafka/test_batch_fast.py::test_kafka_engine_put_errors_to_stream* (4 parametrized variants, 47 hits, 10+ PRs in 30d, suspected librdkafka/MV-flush race). The _with_random_malformed_json shape is now part of the same task.

Fix plan (separate PR): replace the bare assert with instance.query_with_retry(..., check_callback=lambda x: int(x) == 64) (and the same for _data), matching the pattern already used elsewhere in test_batch_fast.py (e.g. line 1053). This addresses the MV-flush race without weakening the assertion or changing the test's intent. Will reproduce locally with --count 50 on the amd_asan_ubsan, db disk, old analyzer config before submitting.

No open flaky test issue exists for this family — I'll file one alongside the fix PR.

cc @alexey-milovidov

pull Bot pushed a commit to infdahai/ClickHouse that referenced this pull request May 17, 2026
…formed_json

Both tests in test_storage_kafka/test_batch_fast.py wait for the
Kafka 'Committed offset 128' log line and then assert the destination
row counts immediately:

    instance.wait_for_log_line(f'{kafka_table}.*Committed offset 128')
    assert TSV(instance.query(f'SELECT count() FROM test.{kafka_table}_data'))
        == TSV('...')
    assert TSV(instance.query(f'SELECT count() FROM test.{kafka_table}_errors'))
        == TSV('64')

The offset commit and the materialized-view INSERT into the destination
MergeTree are not strictly ordered: the consumer side can log
'Committed offset 128' before the last MV block has finished flushing,
so the immediate SELECT undercounts (typically by exactly the last
block, i.e. assert 54 == 64).

Across both parametrized variants of each test the family has hit 23+
failures across 5 distinct unrelated PRs in the last 30 days (e.g.
ClickHouse#96886, ClickHouse#104902, ClickHouse#104905), with 0 master failures. Surfaced again by
@alexey-milovidov on
ClickHouse#104905 (comment).

The helper file in the same suite already acknowledges this anti-pattern
(tests/integration/helpers/kafka/common.py:463):
"Since everything is async and shaky when receiving messages from
Kafka, we may want to try and check results multiple times in a loop."

Most other tests in test_batch_fast.py already use query_with_retry
with a check_callback for exactly this reason (see e.g. line 1053,
1516). These two tests were the outliers.

Replace the bare assert with query_with_retry + check_callback. The
asserted values are unchanged, so no test intent is weakened: if the
count never reaches the expected value, query_with_retry returns the
last observed result and the surrounding assert ... == EXPECTED fails
loudly.

@alexey-milovidov alexey-milovidov left a comment

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.

Ok.

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

Did not notice this and come up with the same fix more or less

@clickhouse-gh

clickhouse-gh Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 88.89% (8/9) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 20, 2026
Merged via the queue into master with commit b007210 May 20, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-storage-time-series-null-deref branch May 20, 2026 05:40
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 20, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…-series-null-deref

Fix UBSan null deref in StorageTimeSeries constructor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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