Repository navigation
Implemented aggregate function mergedJSONPatch - #108349
Conversation
|
Workflow [PR], commit [9b679a5] Summary: ✅
AI ReviewSummaryThis PR adds the Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 293/332 (88.25%) · Uncovered code |
…ding LeastSupertypeOnError::Dynamic
…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.
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. |
| 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()) |
There was a problem hiding this comment.
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.
…kHouse into aggregate-MergedJSONPatch
| // 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 |
There was a problem hiding this comment.
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.
|
Hi @larryluogit @Avogar — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
Changelog category (leave one):
Changelog entry
Implement aggregate function
mergedJSONPatchfor 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.
mergedJSONPatchprovides RFC 7396-style last-write-wins merge semantics for JSON values in aggregate form, including support formergedJSONPatch,mergedJSONPatchState, andmergedJSONPatchMerge, and usage inAggregatingMergeTree.Implementation highlights:
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
26.8.1.1094(included in26.8and later)