Skip to content

Resubmit: Preserve parameter types in timeseries aggregate functions - #103428

Merged
vitlibar merged 8 commits into
ClickHouse:masterfrom
vitlibar:resubmit-preserve-parameter-types-in-timeseries-agg-functions
May 11, 2026
Merged

vitlibar merged 8 commits into
ClickHouse:masterfrom
vitlibar:resubmit-preserve-parameter-types-in-timeseries-agg-functions

Conversation

@vitlibar

@vitlibar vitlibar commented Apr 23, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Resubmit #101083: Preserve parameter types in timeseries aggregate functions
(it was reverted in #102358)

We need to restore the initial invariant: For any aggregation function IAggregateFunction::getParameters() should return exactly the parameters used to create the aggregation function. Aggregation functions are not allowed to change or normalize these parameters.

Otherwise it would become a different DataTypeAggregateFunction (see DataTypeAggregateFunction::strictEquals),
and could fail to reattach a table because decodeDataType() would reconstruct a type different from the one
recorded in the column metadata; or fail on parallel replicas under serialize_query_plan=1 because the replica's
decodeDataType() would reconstruct a type different from the one the coordinator sent in the plan. And we actually saw a bunch of such issues already (#101407, #102345, #103079)

It's difficult to fix all these issues and it's better to just restore the invariant. By the way, for non-timeseries aggregate functions parameter types are always preserved, and for example quantile(toFloat32(0.5)) isn't silently converted to quantile(0.5) or vice versa.

Version info

  • Merged into: 26.5.1.518

@vitlibar
vitlibar force-pushed the resubmit-preserve-parameter-types-in-timeseries-agg-functions branch from fe9cf62 to 737f05d Compare April 23, 2026 08:39
@vitlibar
vitlibar requested a review from Copilot April 23, 2026 08:40
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a57841f]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb

AI Review

Summary

This PR restores parameter-type preservation for timeseries aggregate functions and adds coverage around the resulting type-mismatch behavior. The main remaining issue is that the new invariant check in AggregateFunctionFactory is still globally weakened, so it can miss future regressions in unrelated aggregate functions.

Findings

⚠️ Majors

  • [src/AggregateFunctions/AggregateFunctionFactory.cpp:232] The chassert currently allows function->getParameters().empty() for all aggregate functions. That means any function that accidentally drops non-empty parameters to [] will pass the check, which defeats the intended invariant guard in debug builds.
    Suggested fix: restrict the exception to the known legacy cases (kolmogorovSmirnovTest, mannWhitneyUTest) and keep strict equality for all other functions.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Invariant enforcement in AggregateFunctionFactory is still over-relaxed.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Narrow the function->getParameters().empty() exemption in AggregateFunctionFactory to the known legacy aggregate functions instead of allowing it for all functions.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Apr 23, 2026
/// recorded in the column metadata; or fail on parallel replicas under serialize_query_plan=1 because the replica's
/// decodeDataType() would reconstruct a type different from the one the coordinator sent in the plan.)
chassert(function && function->getParameters() == parameters,
"function->getParameters() must equal the parameters passed to the factory");

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.

I added a comment and assertion here to document the invariant.

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

Restores the invariant that IAggregateFunction::getParameters() must return exactly the parameters used to create the aggregate function (no normalization), primarily to keep DataTypeAggregateFunction stable across serialization/deserialization (e.g., parallel replicas + serialize_query_plan=1) and stored table metadata.

Changes:

  • Pass through original parameter Array into time series aggregate function implementations (instead of normalizing stored parameters to Decimal64).
  • Add chassert-based invariants in AggregateFunctionFactory to detect any aggregate function/combinator that mutates parameters.
  • Add/update stateless tests and tweak existing tests to avoid flakiness from randomized parallel replicas.

Reviewed changes

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

Show a summary per file
File Description
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h Stores the original parameters_ in the base IAggregateFunction state for timeseries aggregates.
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesHelpers.cpp Threads the original parameters through constructors for all relevant timeseries functions.
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h Updates ctor to accept the original parameters_ (but introduces a ctor ambiguity risk).
src/AggregateFunctions/AggregateFunctionFactory.cpp Adds assertions to enforce parameter preservation for creators and combinators.
src/AggregateFunctions/IAggregateFunction.h Documents that getParameters() returns constructor parameters “as is”.
tests/queries/0_stateless/04109_timeseries_aggregate_function_parameter_type_mismatch.sql New regression test proving mismatched parameter types cause CANNOT_CONVERT_TYPE.
tests/queries/0_stateless/04109_timeseries_aggregate_function_parameter_type_mismatch.reference Expected output for the new test.
tests/queries/0_stateless/03254_timeseries_to_grid_aggregate_function_sparse.sql Disables randomized parallel replicas at test start for determinism.
tests/queries/0_stateless/03254_timeseries_instant_value_aggregate_functions.sql Similar test determinism tweaks + settings adjustments.
tests/queries/0_stateless/03254_timeseries_instant_value_aggregate_functions.reference Updates expected type-name outputs reflecting preserved parameter types.

[toDateTime64('2024-01-01 00:00:10', 3, 'UTC'),
toDateTime64('2024-01-01 00:00:20', 3, 'UTC')]::Array(DateTime64(3, 'UTC')),
[1.0, 2.0]::Array(Float64)
); -- { serverError CANNOT_CONVERT_TYPE }

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.

I also added a test from report #102319 to document that this CANNOT_CONVERT_TYPE exception is an expected behavior and not a bug.

@vitlibar
vitlibar force-pushed the resubmit-preserve-parameter-types-in-timeseries-agg-functions branch from 737f05d to 288461d Compare April 23, 2026 09:05
@vitlibar
vitlibar requested a review from Copilot April 23, 2026 09:06

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

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated the Unit tests (asan_ubsan, function_prop_fuzzer) failure on bb036d1.

Verdict: not caused by this PR — pre-existing test-infrastructure race in the stuck-thread teardown path.

Root cause

Looking at the job log:

  • Total stats line says: stuck threads: 1
  • One worker was wedged for 374s inside an arrayResize(...) SQL invocation (the actual Thread is stuck while ... line is logged just above the stack trace)
  • Then we get this in teardown:
src/Functions/tests/gtest_functions_stress.cpp:2222: Failure
Value of: failure_details.empty()
  Actual: false
Expected: true
1 threads got stuck

Logical error: 'prev.thread_id == curr.thread_id'.
2. src/Common/ThreadProfileEvents.h:88: RUsageCounters::incrementProfileEvents(...)
3. ThreadStatus::updatePerformanceCounters()
4. ThreadStatus::finalizePerformanceCounters()
5. ThreadStatus::detachFromGroup()
6. ? (std::function call)
7. FunctionsStressTestThread::~FunctionsStressTestThread()
8. std::vector<FunctionsStressTestThread,...>::__destroy_vector::operator()()
9. FunctionsStress_stress_Test::TestBody()

The flow:

  1. The watchdog detects a stuck thread, the test prints Thread is stuck while ... and ASSERT_TRUE fails.
  2. Control returns from TestBody, which destroys std::vector<FunctionsStressTestThread> threads.
  3. For each entry, ~FunctionsStressTestThread destroys members in reverse declaration order. std::optional<ThreadStatus> thread_status (declared after std::thread thread) is destroyed first, on the test's main thread.
  4. ~ThreadStatus() → deleter() (set in ThreadStatus::attachToGroup at ThreadStatusExt.cpp:497) → detachFromGroup → finalizePerformanceCounters → updatePerformanceCounters → RUsageCounters::updateProfileEvents(*last_rusage, ...) → current() reads RUSAGE_THREAD for the test main thread → incrementProfileEvents(prev, curr, ...) → chassert(prev.thread_id == curr.thread_id) fires (ThreadProfileEvents.h:88) because last_rusage->thread_id is the worker's TID and curr.thread_id is the main thread's TID.

For a normally-stopping worker this can't happen — the run loop ends with thread_status.reset(); // must be done from this thread at line ~1244. A stuck worker is frozen inside the loop and never reaches that reset.

The chassert masks the actual failure (1 threads got stuck), which is why the symptom looks like a sanitizer/UBSan finding instead of a watchdog timeout report.

This is not the timeseries-aggregate-types change

The PR touches AggregateFunctions/* (TimeSeries, factory, KS test, MannWhitney, IAggregateFunction). The crash:

  • happens in ~ThreadStatus / RUsageCounters (Common, Interpreters infrastructure)
  • the stuck function was arrayResize, unrelated to anything modified here
  • triggers only when a worker wedges inside any function long enough for the watchdog timeout

Cross-PR data:

  • function_prop_fuzzer total in 30 days: 2 failures, 5190 OK runs, 1 distinct PR (PR Validate IN tuple/subquery column count mismatch in analyzer #97540, also unrelated to this code path) — extremely rare, ~0.04% rate.
  • RUsageCounters::incrementProfileEvents chassert across all checks in 90 days: 103 hits, 4 PRs, 0 master — the same teardown race, surfacing in Stress test (amd_debug/arm_asan_ubsan), Integration tests (amd_msan, ...), and now this function_prop_fuzzer job. Always tied to a stuck/abandoned worker thread, never to the actual code under test.

Proposed fix (separate PR, follow-up)

The fix belongs in tests/gtest_functions_stress.cpp, not in this PR. Once we know a worker is stuck we have three problems:

  1. std::thread::~thread() on a joinable thread calls std::terminate.
  2. ~ThreadStatus() from the wrong thread fires the incrementProfileEvents chassert (and would also fire chassert(current_thread == this) at ThreadStatus.cpp:277).
  3. The detached worker is still reading members of FunctionsStressTestThread (operation, mutex, function_stats, ...), so destroying those is UB.

The cleanest minimal patch is to skip the unsafe cleanup once stuck_threads > 0: detach the OS threads so ~thread is a no-op, leak the threads vector via a static, then let gtest's ASSERT_TRUE surface the real failure. Sketch:

String failure_details = reportResults(total_stats, stuck_threads);

writeSignalIDtoSignalPipe(SignalListener::StopThread);
signal_listener_thread.join();
HandledSignals::instance().reset();

if (stuck_threads > 0)
{
    // Stuck workers are still inside SQL evaluation; we cannot run their destructors
    // from this thread without (a) ~ThreadStatus tripping the cross-thread chassert
    // in RUsageCounters::incrementProfileEvents, (b) ~thread() calling std::terminate,
    // (c) UB from concurrent access to FunctionsStressTestThread members.
    // Detach the OS threads and intentionally leak the vector — the process is about
    // to fail the test anyway.
    for (auto & t : threads)
        if (t.thread.joinable())
            t.thread.detach();
    static std::vector<FunctionsStressTestThread> leaked;
    leaked = std::move(threads);
}

ASSERT_TRUE(failure_details.empty()) << failure_details;

I'll send this as a separate PR shortly. This PR should be unblocked by a CI rerun once the fix lands (or if you want to merge first, the failure is unrelated and is hiding the watchdog's actual 1 threads got stuck message).

Reproducing the underlying stuck-thread case is non-deterministic — arrayResize happens to be the trigger here, but any function that allocates a lot can wedge under asan_ubsan and exceed the 30s shutdown timeout. I'll validate the fix against an asan_ubsan build and force a stuck thread by injecting a sleep in one worker.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, thanks! Please send a PR.

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — already filed: #103982 (May 4, before this thread).

Fix: wraps FunctionsStressTestThread in std::unique_ptr. When a worker is stuck:

  • detach its std::thread (avoids std::terminate from ~std::thread on a joinable thread)
  • defer unique_ptr release until after signal_listener_thread is joined (avoids data race with request_shutdown which iterates threads)
  • intentionally leak the heap-allocated state — the still-running stuck worker keeps using context/thread_group/mutex/function_stats safely; the leak is bounded by process exit

This avoids the prev.thread_id == curr.thread_id chassert in ~ThreadStatus that was hiding the actual "thread is stuck" failure message.

CI on #103982: all 35+ relevant checks pass (asan/tsan/msan/ubsan unit tests, AST fuzzer, BuzzHouse, builds). Only red is the chronic "Docs check / Generate system tables documentation" flaky which fails in 30+ unrelated PRs (separate task).

Could you take a look when you have a moment?

@alexey-milovidov

Copy link
Copy Markdown
Member

Now we have to update the branch here. We can't merge with red checks.

@clickhouse-gh clickhouse-gh Bot 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.

Submitting pending review to allow new inline comments

@vitlibar

vitlibar commented May 7, 2026

Copy link
Copy Markdown
Member Author

PR / Finish Workflow (pull_request) failed with

[2026-05-07 07:21:00] WARNING: Failed to start log export (from: Stateless tests (amd_tsan, s3 storage, parallel, 2/2))

@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (39/39) | lost baseline coverage: 4 line(s) · Uncovered code

Full report · Diff report

@vitlibar

Copy link
Copy Markdown
Member Author

@groeneai Investigate CI failures

@groeneai

Copy link
Copy Markdown
Collaborator

@vitlibar — investigated all CI failures on a57841fc. All are chronic / non-PR-caused. Detail below per check.

1. AST fuzzer (amd_debug, targeted, old_compatibility) — Logical error: 'Inconsistent AST formatting: the original AST...' (STID: 1941-1bfa) — CHRONIC, fix merged

Chronic trunk bug in ParserAllCollectionsOfLiterals (accepted collection literals like (NULL), [NULL], {{{{a:1}}}} as data-type arguments → invalid Literal_Tuple_(NULL) AST nodes → AST round-trip mismatch). Fixed by PR #104520 (Reject collection literals as data-type arguments (STID 1941-1bfa)), merged 2026-05-10 19:43 UTC by @alexey-milovidov. Your PR's CI ran on 2026-05-09 23:00 — before the fix landed. Rebase on master will eliminate it. CIDB last 14 days, master-only count: 0.

2. Fast test (arm_darwin) — Server died on 02169_map_functions, 02515_analyzer_null_for_empty, 01109_sc0rp10_string_hash_map_zero_bytes — CHRONIC arm_darwin infrastructure

The macOS native Fast test runner has been broadly unstable. In the 4-hour window around your run (2026-05-09 22:00 → 2026-05-10 02:00 UTC), CIDB shows 24 unrelated PRs hit "Server died" / ConnectionRefusedError in Fast test (arm_darwin), each on different random tests:

PR failures sample tests
101218 5 03142_untuple_crash, 04003_grace_hash_join_with_totals, …
104475 4 04093_text_index_separate_analysis, 01660_join_or_inner, …
100177 4 02481_analyzer_optimize_aggregation_arithmetics, …
104474 4 03170_float_schema_inference_small_block, …
96978 4 02788_current_schemas_function, 02050_clickhouse_client_local_exception, …
103428 3 02169_map_functions, 01109_sc0rp10_string_hash_map_zero_bytes, 02515_analyzer_null_for_empty
… 18 more PRs …

Reported tests are whatever happened to be running when the macOS server crashed — they're random, not predictive. None of your 3 tests touch aggregate functions / Array combinator / TimeSeries. Today (2026-05-11), 30+ more unrelated PRs hit the same pattern. Pure environment noise.

3. Finish Workflow / Post Hooks (2026-05-09 20:22, 2026-05-07 ×3) + Docker server image / clickhouse-server:head-alpine-arm64 (2026-05-07) — Infrastructure

Workflow finalization steps + Alpine ARM64 docker build pipeline. Not test failures, not caused by your diff.


Recommendation

For context — STID 4870 family (the bug this PR fixes) continues to recur on master almost daily (most recent: STID 4870-4f07 on Stress test (experimental, serverfuzz, azure, amd_msan), sha 12b7a618d1ea7a5f29b58d846fb979490904c2f5, 2026-05-09). PR is mergeable, blocked only on review.

Session: cron:clickhouse-ci-task-worker:20260511-121500

@vitlibar

Copy link
Copy Markdown
Member Author

So the only real CI failure was Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) and it has been already fixed

@vitlibar
vitlibar added this pull request to the merge queue May 11, 2026
Merged via the queue into ClickHouse:master with commit 9f7bd11 May 11, 2026
163 of 165 checks passed
@vitlibar
vitlibar deleted the resubmit-preserve-parameter-types-in-timeseries-agg-functions branch May 11, 2026 13:06
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

@vitlibar @alexey-milovidov — status update on the STID 4870 family after this fix was reverted by #104672 on 2026-05-12 12:49 UTC.

Public master regressed immediately after the revert

Date STID 4870 family master hits
2026-05-11 (this PR merged 13:06 UTC) 2 (all before merge)
2026-05-11 13:06 → 2026-05-12 12:49 (fix active, 23h) 0
2026-05-12 (revert day) 5
2026-05-13 10
2026-05-14 3
2026-05-15 (so far) 1

Sub-STIDs hitting master post-revert: 4870-4f07, 4870-4d73, 4870-4f21. Total: 19 master hits in the 3 days since the revert, plus continuing PR-side noise. The fix was demonstrably working — zero master hits during the fix-active window.

The re-land in #104812 is stalled only by chronic flakes

#104812 is a clean re-land (identical diff). Its CI on f6373ac3 failed on five chronic issues, none caused by the diff:

Failure 30-day cross-PR
AST fuzzer (amd_debug, targeted) — STID 1941-1bfa Multi-subvariant chronic. Only some fixed by #104520; CODEC-with-tuple and JOIN-construct subvariants still hit master post-fix (3 master hits 2026-05-11/12)
Fast test (arm_darwin) — 00439_fixed_string_filter, 03047_on_fly_mutations_prewhere Pure macOS infra noise: 448 failures / 134 PRs / 356 distinct random tests on 2026-05-13 alone
WasmEdge MSan — 02346_text_index_queries Issue #104866 family — 45 hits, 41 PRs
SQLancer — TLPAggregate / TLPDistinct / TLPGroupBy Chronic SQLancer correctness family — 532 hits, 197 PRs, 51 master
Unit tests (tsan, function_prop_fuzzer) — FunctionsStress.stress, AllTests Chronic — 546 hits, 144 PRs, 38 master (separate FunctionsStress family)

Question / offer

If #104812 is being held back specifically over 03254_timeseries_instant_value_aggregate_functions_backward_compatibility flakiness in clickhouse-private#56458, would it be workable to land the public fix while tracking the private flake separately? The public invariant (IAggregateFunction::getParameters() returning the parameters used to construct it) is fundamental and the regression rate (≈6 master hits/day post-revert) is significant.

Happy to (a) investigate the private flake if you can share the failure signature/log, or (b) take a swing at the remaining chronic STID 1941-1bfa subvariants (PR #104991 addresses one — the NOT-tuple CODEC variant — but there are JOIN and aggregation-list variants still surfacing).

Session: cron:clickhouse-ci-task-worker:20260515-094500

zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Sep 4, 2026
…, mannWhitneyUTest

These aggregate functions accept parameters but constructed their base with an
empty parameter array, so getParameters() returned []. The -Array combinator
does not transform parameters and asserts wrapper.parameters == nested params,
so e.g. groupArrayMovingSumArray(42)([1,2,3]) aborted with a LOGICAL_ERROR.
Pass the parameters to the base constructor (the fix the ClickHouse#104812 TODO asked for).
Parameters are plain UInt64/String literals, so this does not reintroduce the
type-equality issue that reverted ClickHouse#103428.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🍃 green ci 🌿 Fixing flaky tests in CI 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.

5 participants