Skip to content

add json_merge_patch, json_merge_preserve - #25728

Merged
mergify[bot] merged 14 commits into
matrixorigin:mainfrom
daviszhen:0714-add-merge-xxx
Jul 17, 2026
Merged

mergify[bot] merged 14 commits into
matrixorigin:mainfrom
daviszhen:0714-add-merge-xxx

Conversation

@daviszhen

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #24738

What this PR does / why we need it:

增加 json_merge_patch, json_merge_preserve

@daviszhen
daviszhen requested a review from a user July 14, 2026 12:27
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify mergify Bot added the kind/bug Something isn't working label Jul 14, 2026
@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Jul 14, 2026
@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/L Denotes a PR that changes [500,999] lines labels Jul 17, 2026
@daviszhen

Copy link
Copy Markdown
Contributor Author

Correction to my earlier review: the author is right about JSON_MERGE_PATCH SQL-NULL semantics. MySQL intentionally allows a later non-object patch to recover a known result, so I withdraw the sticky-NULL finding. The current state machine and its SQL-NULL/JSON-null tests are correct.

Two independent performance/Q3 blockers remain on current head f6baf202901b0cbd756a01d7484f493757dd23bf:

  1. [P1] The depth limit does not bound allocation amplification (pkg/container/bytejson/bytejson_merge.go:112-202). Each recursive level serializes and copies the complete merged child again. The new depth-100 check bounds recursion count, but a legal wide leaf is still copied about 100 times. On this head, two valid depth-100 documents with 256 KiB string leaves measured:

    • PATCH: 27,362,096 B/op and succeeds
    • PRESERVE: 53,841,016 B/op, then returns the expected depth-101 error
      Thus a roughly 256 KiB row can allocate tens of MB, and the PRESERVE unhappy path performs the entire expensive construction before rejecting the result. Across a vector batch this remains an OOM/GC-amplification path. Please serialize the final tree once/use a mutable merge representation, or enforce a safe complexity/memory budget derived from both depth and payload size before allocating. Detect result-depth overflow during the merge rather than after constructing the full result. Add an informational deep-wide benchmark and deterministic early-rejection coverage.
  2. [P1] Build string accessors once per parameter (pkg/sql/plan/function/func_builtin_json.go:1645-1647). jsonMergeDocument calls vector.GenerateFunctionStrParameter(parameter) from the row × argument inner loop. A scalar-only probe (no object merge allocation) with 8,192 rows and two JSON arguments measured exactly 16,384 allocations per execution. Prebuild/reuse the wrappers before the row loop so accessor allocations scale with argument count per batch, not rows × arguments, and add an allocation/benchmark regression.

The functional matrix otherwise closes correctly: RFC 7396 object/scalar/array behavior, PRESERVE autowrap, SQL NULL versus JSON null, invalid JSON/type/arity, select-list materialization, function IDs, and depth boundaries are covered. Full pkg/container/bytejson and pkg/sql/plan/function tests plus focused race tests pass under the repository CGo wrapper. Q1/Q2 found no retained-resource leak or blocking/wait cycle.

本次修改主要解决两个性能问题:

  • 新增 row-scoped mutable JSON merge builder,PATCH/PRESERVE 合并期间不再反复序列化祖先节点,最终只编码一次,并在合并阶段提前拒绝 depth overflow。
  • SQL 参数 wrapper 移到 row loop 外复用,消除 row × argument 分配。

同时新增:

  • Vector exact-size direct sink,直接写最终 Varlena,并完整处理 Grow2 失败回滚。
  • Binary differential、随机语义、深宽输入、many-argument、allocation、depth 和 race 回归测试。

效果:256 KiB、depth-100 场景从约 27–54 MB/op 降至约 70–340 KB/op。相关包全量测试和 focused race 均通过。

@XuPeng-SH XuPeng-SH 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.

Re-reviewed current head 6f933aaf51bf99f597fa8366b281a19bba3afe40. The two previous Q3 blockers are fixed: the mutable plan encodes once, the PRESERVE depth overflow is rejected before output construction, and parameter accessors are now batch-scoped. One correctness blocker remains.

[P1] Validate every non-NULL JSON argument before the merge state machine can discard it.

MergeBuilder.Reset deliberately skips depth validation (pkg/container/bytejson/bytejson_merge_plan.go:132-141), and the SQL loops also bypass Merge for a PATCH object while the target is unknown and return early for PRESERVE on SQL NULL (pkg/sql/plan/function/func_builtin_json.go:1574-1593,1649-1657). Therefore current head accepts inputs that violate the new 100-level contract:

  • JSON_MERGE_PATCH(depth_101_object, '1') returns 1.
  • JSON_MERGE_PATCH(NULL, depth_101_object) returns SQL NULL.
  • JSON_MERGE_PRESERVE(depth_101_object, NULL) returns SQL NULL.

MySQL parses each argument through get_json_wrapper with JsonDocumentDefaultDepthHandler before applying either the PATCH unknown-target skip or the PRESERVE NULL return, so all three cases raise the nesting-depth error. See the upstream parse path and merge loops: https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L315-L349, https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L3133-L3160, https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L3431-L3477.

Please validate every non-SQL-NULL document immediately after parsing, independently of whether it will later be merged, skipped, replaced, or followed by NULL. Add the three regressions above; retaining a separate final-result depth check is still necessary for PRESERVE autowrap.

Local verification otherwise passes: affected package tests, focused -race -count=10, and go vet. The depth-100/256 KiB benchmark is now about 340 KB/op for PATCH and 71 KB/op for the early PRESERVE error, versus the previous 27-54 MB/op.

@daviszhen

daviszhen commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Re-reviewed current head 6f933aaf51bf99f597fa8366b281a19bba3afe40. The two previous Q3 blockers are fixed: the mutable plan encodes once, the PRESERVE depth overflow is rejected before output construction, and parameter accessors are now batch-scoped. One correctness blocker remains.

[P1] Validate every non-NULL JSON argument before the merge state machine can discard it.

MergeBuilder.Reset deliberately skips depth validation (pkg/container/bytejson/bytejson_merge_plan.go:132-141), and the SQL loops also bypass Merge for a PATCH object while the target is unknown and return early for PRESERVE on SQL NULL (pkg/sql/plan/function/func_builtin_json.go:1574-1593,1649-1657). Therefore current head accepts inputs that violate the new 100-level contract:

  • JSON_MERGE_PATCH(depth_101_object, '1') returns 1.
  • JSON_MERGE_PATCH(NULL, depth_101_object) returns SQL NULL.
  • JSON_MERGE_PRESERVE(depth_101_object, NULL) returns SQL NULL.

MySQL parses each argument through get_json_wrapper with JsonDocumentDefaultDepthHandler before applying either the PATCH unknown-target skip or the PRESERVE NULL return, so all three cases raise the nesting-depth error. See the upstream parse path and merge loops: https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L315-L349, https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L3133-L3160, https://github.com/mysql/mysql-server/blob/8.0/sql/item_json_func.cc#L3431-L3477.

Please validate every non-SQL-NULL document immediately after parsing, independently of whether it will later be merged, skipped, replaced, or followed by NULL. Add the three regressions above; retaining a separate final-result depth check is still necessary for PRESERVE autowrap.

Local verification otherwise passes: affected package tests, focused -race -count=10, and go vet. The depth-100/256 KiB benchmark is now about 340 KB/op for PATCH and 71 KB/op for the early PRESERVE error, versus the previous 27-54 MB/op.

• 修改记录:

  • 修复所有非 SQL-NULL JSON 参数的深度校验遗漏。
  • Reset 现在校验输入深度,并维护 rootValid 状态。
  • PATCH 对 unknown 状态下被跳过的对象单独校验。
  • PRESERVE 保证参数在 NULL 短路前已通过 Reset/Merge 校验。
  • 保留最终结果深度校验,覆盖 PRESERVE autowrap。
  • 深度遍历改为固定栈,实现零堆分配。
  • 新增三个 SQL 回归用例及 builder/零分配测试。
  • 全量测试、race -count=10、针对性 go vet 均通过。

@XuPeng-SH XuPeng-SH 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.

Re-reviewed current head 99bb9fa after the depth-validation fix. The previous blocker is closed.

  • Every non-SQL-NULL input is now depth-validated before Reset, scalar replacement, an unknown PATCH state, or a PRESERVE NULL short-circuit can discard it.
  • Reset records the validated root, so Merge does not rescan it; the final materialized result remains validated.
  • The fixed 100-frame traversal rejects depth 101 before exceeding its bound and keeps validation allocation-free.
  • Q1: builder cleanup and sink rollback retain a single owner. Q2: this path introduces no waits. Q3: nesting, encoded size, and row-scoped memory remain bounded.

Verified locally:

  • full tests for bytejson, vector, and SQL plan/function
  • focused race tests, 10 repetitions
  • go vet for all affected packages
  • deep/wide merge benchmark

The added regressions directly cover all three previously reported discard/short-circuit cases. No remaining correctness, lifecycle, or performance blocker found.

@mergify mergify Bot added the queued label Jul 17, 2026
@mergify

mergify Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-17 13:26 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-17 15:16 UTC · at f4be1f97af992e227734f390117c650603e899aa · squash

This pull request spent 1 hour 50 minutes 12 seconds in the queue, including 1 hour 20 minutes 12 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants