Skip to content

Implemented aggregate function mergedJSONPatch - #108349

Merged
Avogar merged 74 commits into
ClickHouse:masterfrom
ClibMouse:aggregate-MergedJSONPatch
Aug 10, 2026
Merged

Avogar merged 74 commits into
ClickHouse:masterfrom
ClibMouse:aggregate-MergedJSONPatch

Conversation

@larryluogit

@larryluogit larryluogit commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry

Implement aggregate function mergedJSONPatch for RFC 7396-style merge-patch aggregation over JSON values, including state merge support and AggregatingMergeTree usage. Users can aggregate a JSON column using a timestamp or another ordering column as the sort key to compute the latest state.

This PR implements AggregateFunctionMergedJSONPatch.

mergedJSONPatch provides RFC 7396-style last-write-wins merge semantics for JSON values in aggregate form, including support for mergedJSONPatch, mergedJSONPatchState, and mergedJSONPatchMerge, and usage in AggregatingMergeTree.

Implementation highlights:

  • stores the effective merged view ordered by sort key
  • minimizes the aggregate state memory footprint
  • resolves conflicts across equal, ancestor, and descendant paths
  • supports aggregate state serialization and deserialization
  • reconstructs the final JSON result from the retained effective entries
  • handles array replacement semantics consistently with RFC 7396
  • avoids NO_COMMON_TYPE for mixed arrays (e.g. ["text", {"k": 1}]) by adding LeastSupertypeOnError::Dynamic — a new policy for getLeastSupertype and FieldToDataType that falls back to Dynamic (instead of throwing) when element types have no common supertype; ColumnDynamic::insert and SerializationDynamic::serializeBinary now use this policy so mixed arrays round-trip through ColumnDynamic without loss and without affecting other callers

Known limitation:

explicit null object members are not preserved in the finalized JSON result because ColumnObject drops null-valued object members on insertion

Version info

  • Merged into: 26.8.1.1094 (included in 26.8 and later)

@alesapin alesapin added the can be tested Allows running workflows for external contributors label Jun 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b679a5]

Summary: ✅


AI Review

Summary

This PR adds the mergedJSONPatch aggregate family and the supporting Dynamic fallback needed to preserve mixed JSON arrays. Most of the earlier implementation bugs are now fixed or explicitly narrowed by the current documentation, but two correctness issues remain in the current head: nullable sort_keys are still silently skipped by the internal Null combinator, and JSON / Object sort keys are still accepted even though they are compared with Field ordering rather than ClickHouse's column ordering. Verdict: request changes until those sort-key contracts are either enforced or fixed.

Findings

❌ Blockers

  • [src/AggregateFunctions/AggregateFunctionMergedJSONPatch.cpp:455] Nullable sort_keys still do not participate in ordering. AggregateFunctionFactory wraps any nullable argument in the internal Null combinator (src/AggregateFunctions/AggregateFunctionFactory.cpp:101-129), and AggregateFunctionNullVariadic::add drops the row as soon as the sort_key is NULL (src/AggregateFunctions/Combinators/AggregateFunctionNull.h:600-618). That means the comments/tests at tests/queries/0_stateless/04408_merged_json_patch_aggregate.sql:416-500 are documenting behavior the function does not implement: if every competing row has NULL sort_key, the aggregate skips them all instead of keeping one patch by NULL < non-NULL ordering. Fix by either rejecting Nullable sort keys up front or handling null ordering inside mergedJSONPatch without the generic Null combinator.
  • [src/AggregateFunctions/AggregateFunctionMergedJSONPatch.cpp:469] JSON / Object sort keys are still accepted even though the function says "Use a scalar sort key." DataTypeObject::isComparable returns true (src/DataTypes/DataTypeObject.h:55), so this path falls through to KeyGeneric, materializes the key with ColumnObject::operator[] as Field::Object (src/Columns/ColumnObject.cpp:260-285), and then compares winners with Field::operator< (src/Core/Field.cpp:251-278) instead of ColumnObject::compareAt (src/Columns/ColumnObject.cpp:2359-2374). That gives different ordering for accepted input, including nested NaN values, so the aggregate can keep a different winner than ordinary ClickHouse ordering would. Fix by rejecting Object / JSON sort keys here, matching the docs, or by comparing them with the original column comparator rather than Field ordering.
Tests
  • ⚠️ Add a focused regression where every row in a group has NULL sort_key; the current mixed NULL/non-NULL cases pass even when the function simply drops every NULL row.
  • ⚠️ Add a regression that mergedJSONPatch(json, json_sort_key) is rejected, or if object sort keys are intentionally supported, one that proves their ordering matches ORDER BY sort_key for nested floats / NaN.
Final Verdict
  • Status: ⚠️ Request changes

LLVM Coverage Report

Metric Baseline Current Δ
Lines 81.00% 86.60% +5.60%
Functions 91.30% 91.90% +0.60%
Branches 73.10% 78.80% +5.70%

Changed lines: Changed C/C++ lines covered: 293/332 (88.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 24, 2026
Comment thread src/DataTypes/FieldToDataType.cpp Resolved
…row conflict corruption

When a JSON column has typed schema like JSON(a UInt32, `a.b` UInt32) and
a row contains only {"a":42}, the typed column for `a.b` holds its default
value (0). The SortedPathsIterator yields both a=42 and a.b=0 for that row.

Without this fix, feeding a.b=0 into insertPathValue triggers conflict
resolution: a.b is a descendant of a, so the existing a=42 entry is erased
and replaced by a.b=0. The final result is missing a=42.

The fix mirrors how SortedPathsIterator already skips null dynamic paths:
skip typed paths where path_info.column->isDefaultAt(path_info.row) is true.
A default typed path was never written for this row, so including it in the
aggregation state causes spurious conflict resolution across paths from the
same input row.

After the fix, a=42 is preserved in the state. The result column's fallback
loop still calls insertDefault() for a.b (keeping column size invariant),
which produces {"a":42,"a":{"b":0}} - this is the same output that
toJSONString() produces directly on the typed JSON column, confirming
correctness.

Also adds a test case for this scenario and updates the reference file.
…escription

The CI style check (check 01) flags any line starting with 1-3 spaces
followed by two non-space characters as a potential indentation error.
The LIMITATIONS list continuation lines used 3-space indentation inside
the R"(...)" raw string, which triggered that check. Changed to 4-space
indentation so the raw string content passes the heuristic.
…t key

The previous code called serializeValueIntoArena(row_num, arena, ...) to
build a deterministic sort key for the one-argument form of mergedJSONPatch.
That wrote the entire serialized JSON row into the aggregate Arena, which
lives for the lifetime of the aggregate state. Even rows whose entries are
later shadowed by newer writes left their full serialization behind, causing
arena memory to grow with the number of processed rows rather than with the
effective merged state size.

The fix computes the sort key by hashing the row into a stack-allocated
SipHash via updateHashWithValue and stores the resulting UInt128 digest
directly in the SortKey Field. No arena bytes are written; the 16-byte
digest is held inside the Field value inline storage. The hash is
collision-resistant enough for ordering purposes and the UInt128 Field type
round-trips correctly through encodeField/decodeField.
The previous fix for the JSON(a UInt32, `a.b` UInt32) conflicting-path
problem used isDefaultAt to skip typed paths at their column default.
That was incorrect: a genuine {"a":0} write (where 0 is the UInt32 default)
would be dropped, allowing an older {"a":5} to survive. That breaks the
last-write-wins contract for any typed path whose new value equals the
column default.

Root cause: addKeyValuePairs called insertPathValue for each path
incrementally, so intra-row paths with the same sort key could erase
each other via eraseShadowedEntries. Processing "a.b" after "a" would
erase "a" because its sort_key <= sort_key of "a.b" (they are equal).

Fix: process each row in two phases against a snapshot of the
pre-existing state (entries.size() before the row is processed):

  Phase 1 - filter: for each leaf collected from the row, call
    hasNewerConflictingEntryIn(path, sort_key, existing_count)
    which only scans the pre-row entries. Siblings from the same
    row are invisible and cannot block each other.

  Phase 2 - commit: for each survivor, erase conflicting pre-existing
    entries via eraseShadowedEntriesIn(path, sort_key, existing_count)
    (again scoped to pre-row entries only), then push the new entry
    via pushLeafEntry which bypasses the re-check so that already-
    inserted siblings from the same row are not consulted.

This restores correct behavior for both cases:
- JSON(a UInt32, `a.b` UInt32) with {"a":42}: a=42 is retained
  alongside the schema-mandated a.b=0; neither sibling erases the other.
- JSON(a UInt32) with {"a":5} (older) then {"a":0} (newer): a=0 wins
  because the genuine newer write is no longer silently dropped.

The isDefaultAt guard is removed entirely; the two-phase approach
handles both scenarios correctly without inspecting column defaults.
The previous fix (two-phase row insertion) protected addKeyValuePairs from
intra-row sibling erasure, but merge() and deserialize() still replayed
entries one-by-one through insertPathValue / insertLeafEntry.

A valid state can contain conflicting-path siblings at the same sort key
(e.g. 'a' and 'a.b' from JSON(a UInt32, `a.b` UInt32)). When replayed
sequentially, insertLeafEntry's eraseShadowedEntries used sort_key <= K,
which erased the already-inserted sibling 'a=42' when processing 'a.b=0',
because their sort keys were equal. That made mergedJSONPatchMerge() and
AggregatingMergeTree finalization differ from direct aggregation.

Fix: introduce insertBatchAtomic, which all three call sites now use:
  - collectLeaves (called from addKeyValuePairs) builds a LeafRef batch.
  - merge() builds a LeafRef batch from other.entries.
  - deserialize() reads into a LeafRef batch before inserting.

insertBatchAtomic snapshots existing_count = entries.size() before the
batch starts and scopes every conflict check and erasure to the prefix
entries[0..existing_count). Batch members are invisible to each other
during both the filter phase (hasNewerConflicting) and the erase phase
(eraseShadowedEntries), so siblings from the same batch/state cannot
erase each other regardless of their sort-key relationship.

insertPathValue / insertLeafEntry are now only called from insertBatchAtomic
(via pushLeafEntry), not directly from merge or deserialize.
…3 split)

The previous implementation interleaved erasure and insertion per survivor:
for each survivor, erase shadowed pre-existing entries, then push the new
entry.  A positional index limit (j < existing_count) was used to protect
newly-inserted siblings from being erased by a later survivor's erase pass.

This broke when pushLeafEntry inserted a new entry at a sorted position
that fell *below* existing_count (e.g. inserting 'a=42' at index 0 when
existing_count=2). The next survivor ('a.b=0') then ran its erase pass
and saw j=0 < existing_count=2 → treated the just-inserted 'a=42' as a
pre-existing entry → erased it.

Repro: older {"a":5} (K=1) + newer {"a":42} (K=2), both typed
JSON(a UInt32, `a.b` UInt32). After processing K=1 the state is
[a=5, a.b=0]. Processing K=2: survivor[0]='a=42' erases both old
entries and pushes 'a=42' at index 0. survivor[1]='a.b=0' then erases
'a=42' (index 0 < existing_count=2). Finalization fills 'a' with the
column default → result is a=0, not a=42.

Fix: strictly separate phase 2 (all erasures) from phase 3 (all inserts).

  Phase 2: for each survivor, remove conflicting pre-existing entries.
    No insertions happen, so entries only contains pre-existing data
    throughout this entire pass. The j < existing_count guard is gone —
    it is guaranteed by construction that no batch entries are present.

  Phase 3: push all survivors after the state is fully cleaned.
    Batch siblings are not yet in entries, so pushLeafEntry cannot
    mis-identify them as pre-existing candidates for erasure.
The aggregate arena is a monotonic allocator that never reclaims individual
allocations. Path and value bytes written to the arena by pushLeafEntry
accumulated for the full lifetime of the aggregate group, even after the
corresponding Entry was erased. For a time-series key patched N times with
a 1 KB value, the arena held N KB instead of 1 KB.

Fix: replace StringSlice (arena pointer) with owned String in both
EncodedField::data and Entry::path. When an Entry is removed from the
entries vector, its String destructors free the bytes immediately. The
Arena is no longer written to at all by this aggregate function.

Consequences:
  - allocatesMemoryInArena() returns false (was incorrectly true).
  - The Arena & parameter is retained in the public add/merge/deserialize
    signatures (required by the aggregation framework) but is now ignored.
  - copyToArena, encodeFieldToArena, cloneEncodedField, and StringSlice
    are removed — they are no longer needed.
  - readEncodedField no longer takes an Arena & parameter.
  - All internal helpers (pushLeafEntry, insertLeafEntry, insertPathValue,
    insertBatchAtomic, addKeyValuePairs) drop their Arena & parameters.
@larryluogit
larryluogit requested a review from Avogar August 7, 2026 04:08
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 9b679a5 - the build was skipped, reused from cache, or predates profile upload.

@larryluogit
larryluogit requested a review from Avogar August 7, 2026 16:25

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

Looks great!

WhichDataType which_key(key_type->getTypeId());

// Reject composite and non-comparable types
if (which_key.isVariant() || which_key.isDynamic() || which_key.isTuple() || which_key.isArray() || which_key.isMap())

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.

JSON / Object sort keys still slip through this validator because WhichDataType also exposes isObject(), and DataTypeObject is comparable. Once that happens, mergedJSONPatch falls back to KeyGeneric, materializes the key through ColumnObject::get, and compares it via Field::operator< instead of ColumnObject::compareAt.

That changes the winner selection for accepted input. The NaN fix in KeyGeneric::less only applies when the whole Field is Float64, so nested values inside an object keep Field's nan_direction_hint = 1 ordering. A key like JSON(a Float64) can therefore keep the {"a": nan} row even though ClickHouse's column ordering would treat it as smaller than {"a": 1.0}. Please reject Object / JSON here as non-scalar, or switch object-key comparisons to the original column comparator and add a focused regression.

// Validate and dispatch sort-key type
// Mirror createWithTwoTypesSecond: numeric types, Date/DateTime with FieldType,
// String, or KeyGeneric for other comparable scalars.
// NOTE: Nullable(scalar) must always dispatch to KeyGeneric because KeyFixed and

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.

Nullable sort keys do not actually participate in ordering here. AggregateFunctionFactory strips Nullable and wraps any aggregate with nullable arguments in the internal Null combinator (src/AggregateFunctions/AggregateFunctionFactory.cpp:100-123), and AggregateFunctionNullVariadic::add just returns early when any nullable argument is NULL (src/AggregateFunctions/Combinators/AggregateFunctionNull.h:603-623). So a row whose sort_key is NULL never reaches this KeyGeneric path at all.

That makes the current contract wrong: the comments below and the new tests at tests/queries/0_stateless/04408_merged_json_patch_aggregate.sql:416-500 describe NULL < non-NULL ordering, but today mergedJSONPatch(patch, toNullable(version)) skips NULL-keyed rows entirely. The mixed null/non-null cases still pass only because "drop the NULL row" happens to choose the same winner. A case where every competing row has NULL sort_key will currently return the aggregate's empty-input result instead of keeping one of the patches. Please either reject Nullable sort keys up front, or add an own null adapter so NULL rows are preserved and compared explicitly.

@Avogar
Avogar added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit 7fc48be Aug 10, 2026
180 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@larryluogit
larryluogit deleted the aggregate-MergedJSONPatch branch August 10, 2026 13:39
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @larryluogit @Avogar — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

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.

8 participants