본문으로 건너뛰기
cccskills
무료GitHub에 공개

clickhouse-aggregatingmergetree-state-merge

Fix ClickHouse query errors when querying AggregatingMergeTree tables that use state functions. Use when: (1) Query fails with type mismatch on AggregateFunction columns, (2) Using sum/count on columns created with sumState/countState/uniqState, (3) Creating views that JOIN with materialized views using AggregatingMergeTree, (4) Getting unexpected results from aggregate columns that show as AggregateFunction(sum, ...) type. The *State() functions store intermediate aggregate states, not final values - you must use *Merge() functions to finalize them.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.6 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

ClickHouse AggregatingMergeTree State/Merge Pattern

Problem

When querying tables or materialized views that use AggregatingMergeTree with state functions (sumState, uniqState, countState), queries fail or return wrong results because the columns contain aggregate state objects, not regular numeric values.

Context / Trigger Conditions

  • Query fails with type errors when using sum() on AggregateFunction columns
  • Creating views that query AggregatingMergeTree materialized views
  • Column types show as AggregateFunction(sum, UInt64) instead of UInt64
  • Migration creates a view joining with an existing aggregating materialized view
  • Getting NULL or unexpected values when aggregating pre-aggregated columns

Root Cause

AggregatingMergeTree stores intermediate aggregate states, not final values. When you define:

CREATE MATERIALIZED VIEW stats
ENGINE = AggregatingMergeTree()
ORDER BY (user_id)
AS SELECT
    user_id,
    sumState(amount) as total_amount,      -- AggregateFunction(sum, UInt64)
    uniqState(session_id) as unique_sessions, -- AggregateFunction(uniq, String)
    countState() as event_count           -- AggregateFunction(count)
FROM events
GROUP BY user_id;

The columns total_amount, unique_sessions, and event_count are NOT regular numbers. They're binary blobs representing the intermediate state of the aggregation.

Wrong:

SELECT user_id, sum(total_amount) FROM stats GROUP BY user_id;
-- Error: cannot use sum() on AggregateFunction type

Correct:

SELECT user_id, sumMerge(total_amount) FROM stats GROUP BY user_id;
-- Returns the finalized numeric value

Solution

Mapping State Functions to Merge Functions

State FunctionMerge FunctionPurpose
sumState(x)sumMerge(x)Sum aggregation
countState()countMerge(x)Count aggregation
uniqState(x)uniqMerge(x)Unique count (HyperLogLog)
avgState(x)avgMerge(x)Average
minState(x)minMerge(x)Minimum
maxState(x)maxMerge(x)Maximum
anyState(x)anyMerge(x)Any value
groupArrayState(x)groupArrayMerge(x)Array aggregation

Example Fix

Before (broken):

CREATE VIEW leaderboard AS
SELECT
    stats.user_id,
    sum(stats.daily_views) AS views,        -- WRONG
    sum(stats.daily_unique) AS uniques,     -- WRONG
    sum(stats.videos_watched) AS videos     -- WRONG
FROM daily_stats stats
GROUP BY stats.user_id;

After (fixed):

CREATE VIEW leaderboard AS
SELECT
    stats.user_id,
    sumMerge(stats.daily_views) AS views,        -- Correct
    uniqMerge(stats.daily_unique) AS uniques,    -- Correct
    countMerge(stats.videos_watched) AS videos   -- Correct
FROM daily_stats stats
GROUP BY stats.user_id;

Identifying Affected Columns

Check the table schema to see which columns are aggregate states:

DESCRIBE TABLE your_table;

Output shows column types like:

daily_views       AggregateFunction(sum, UInt64)
daily_unique      AggregateFunction(uniq, String)
videos_watched    AggregateFunction(count)

Any column with AggregateFunction(...) type requires the corresponding *Merge() function.

Verification

  1. Check your materialized view definition for *State() functions
  2. Ensure all queries use matching *Merge() functions
  3. Test the query returns expected numeric values, not NULL or binary blobs
-- Should return actual numbers
SELECT sumMerge(total_views), uniqMerge(unique_visitors)
FROM aggregated_stats
WHERE stat_date >= today() - 7;

Example

Migration 020 (creates the aggregating table):

CREATE MATERIALIZED VIEW creator_daily_stats
ENGINE = AggregatingMergeTree()
ORDER BY (video_author_pubkey, stat_date)
AS SELECT
    video_author_pubkey,
    toDate(created_at) as stat_date,
    sumState(view_count) as daily_views,           -- State function
    uniqState(viewer_hash) as daily_unique_viewers, -- State function
    sumState(toFloat64(total_loops)) as daily_loops,-- State function
    countState() as videos_watched                  -- State function
FROM view_counts
GROUP BY video_author_pubkey, toDate(created_at);

Migration 033 (queries the aggregating table - FIXED):

CREATE VIEW leaderboard_creators_day AS
SELECT
    cds.video_author_pubkey AS pubkey,
    p.name,
    sumMerge(cds.daily_views) AS views,            -- Merge function
    uniqMerge(cds.daily_unique_viewers) AS unique_viewers, -- Merge function
    sumMerge(cds.daily_loops) AS loops,            -- Merge function
    countMerge(cds.videos_watched) AS videos_with_views -- Merge function
FROM creator_daily_stats cds
LEFT JOIN user_profiles p ON cds.video_author_pubkey = p.pubkey
WHERE cds.stat_date >= today() - 1
GROUP BY cds.video_author_pubkey, p.name
ORDER BY views DESC;

Notes

  • SummingMergeTree is different: It stores regular values and sums them during merges. With SummingMergeTree, you use regular sum() in queries. Only AggregatingMergeTree uses the State/Merge pattern.

  • Why use AggregatingMergeTree?: For unique counts (uniq), you can't simply sum the counts from different parts—that would overcount. AggregatingMergeTree preserves the HyperLogLog state so merging gives correct unique counts across partitions.

  • Performance: The *Merge() functions are efficient—they're designed to combine pre-computed aggregate states, not reprocess raw data.

  • Migration ordering matters: If migration A creates an AggregatingMergeTree view, and migration B creates a view that queries it, migration B must use *Merge() functions.

References

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

divinevideo/divine-mobile2652026년 10월 23일 업데이트

divinevideo의 스킬 모두 보기

이 스킬의 문제 신고