Repository navigation
fix: correct JSON comparison precedence - #28086
Conversation
d8c89f0 to
92c39e8
Compare
92c39e8 to
d0c96de
Compare
aptend
left a comment
There was a problem hiding this comment.
Deep review of exact head c939dbf against base 6e5f82f. I audited the complete 24-file/10-commit diff, the final c939 increment, all six historical reviews, all issue comments and author replies, and all three current inline threads. The SQL precedence correction, scalar/nonscalar BVT scope, JSON numeric peer grouping, whole-column-cache removal, NULL fast path, and JSON zone-map fail-open behavior are sound, but these blockers remain independently reproducible.
-
[P1][retained-data merge compatibility] pkg/vm/engine/tae/mergesort/aobj_merger.go:64-67 and merger.go:401-404 switch JSON mergers from the base raw GenericLess relation to CompareByteJsonPhysical, which is the old writer relation. Existing objects already produced by the base raw merger are not sorted under that new relation. A base-reachable run is [100], [0,0]: raw ByteJSON orders it that way, while CompareByteJsonPhysical orders [0,0] first. In an exact-head review test I merged that two-row legacy run with a current [50] run; MergeAObj returned [50], [100], [0,0], and the monotonicity assertion failed at [100] then [0,0]. The committed regression at mergesort_test.go:186-203 calls its input oldObject but gives it only one row, so it cannot exercise a legacy internal order. Trigger: upgrade a cluster that has already compacted a JSON CLUSTER BY object, then merge it again after this change. Impact: the merger consumes a run that violates its heap precondition and persists another unsorted object, breaking the physical sort contract across generations. Keep this SQL fix from changing the merger relation, or provide an explicit versioned normalization/read-compatibility path for both old writer-sorted and old merger-sorted runs. Test actual multi-row retained output through both MergeAObj and mergeObjs.
-
[P1][cross-type comparison CPU regression] CompareByteJson deliberately performs recursive full-document validation whenever a container crosses a type-rank boundary (pkg/container/bytejson/types.go:250-267). Direct comparisons in pkg/sql/plan/function/func_compare.go:985-1035 invoke that public comparator once per selected row, so a reusable boolean constant still causes every wide array row to be fully traversed before the rank result is returned. With the committed benchmark harness extended only by array/boolean and reversed cases, 1024 rows with 2049-element arrays measured 37.3-38.0 us/op for array-vs-array first-element difference, but 13.23-13.40 ms/op for array-vs-boolean in both directions, about 350x. The reachable SQL shape is WHERE j < CAST(false AS JSON), directly in this issue scope. Establish validity at the actual decode/admission boundary and reuse it, or otherwise route engine-owned valid values through the trusted constant-time rank path. Add both cross-type directions to the base/final performance gate; another type-specific shortcut would not close the invariant.
-
[P2][comparison total-order contract] Header-only admission for same-rank containers at types.go:238-271 can return on an early child difference without discovering a malformed later child, while a cross-rank comparison fully validates the same document. An exact-head probe corrupted only the second child of A=[0,0], then compared it with B=[1,0] and C=false: CompareByteJson returned A<B=-1, B<C=-1, but A>C=1. A is rejected by IsValidByteJson, yet its classification changes with the comparison partner. Trigger: malformed retained/internal ByteJSON reaches direct comparison, partitioning, or sorting. Impact: a non-transitive comparator can violate sort and peer-partition assumptions; it also conflicts with the document-level malformed fallback used by canonical hash keys. Classify validity once at a boundary and reuse one trusted/fallback domain consistently rather than doing pair-dependent partial validation.
Validation on the exact head: make thirdparties passed. Ordinary tests passed for bytejson, keycodec, objectio/mergeutil, partition, sort, window, SQL function, readutil, and TAE mergesort. Race tests passed for bytejson, keycodec, partition, and sort. The two temporary counterexample tests failed with the exact outputs above and were removed. The focused benchmark passed; git diff --check and a clean-worktree check passed. Current required GitHub checks are complete and green, but they do not cover these counterexamples.
aunjgr
left a comment
There was a problem hiding this comment.
Review of commit c939dbf0775c33037969b69d8fc07bc8579550aa.
[design gate] This has grown beyond a local precedence correction into a major separation of SQL and persisted physical JSON comparison, with more than 500 non-generated production lines across ByteJSON validation, canonical hash keys, sorting/partitioning, window comparison, pruning, and object merge consumers. I could not find an applicable approved versioned design in the PR or its artifacts; the existing prepared_json_comparison design covers a different contract. Provide a design and independent approval for ordering/equality consistency, trusted versus malformed inputs, preservation of existing persisted sort order, mixed-version operation, and hot-path validation cost. The physical merge regressions are useful evidence, but cannot replace the required design review. This is a gate decision, not a claim that a runtime counterexample was reproduced.
Evidence: source review and existing passing CI for this commit; no new local test run was performed for this review.
|
CR follow-up on exact implementation head The requested distinct design phase is now available as Draft #28315, document revision Fresh source-matched local CGo verification passed ten named existing regressions covering malformed comparison/hash domains, nonfinite numbers/nonminimal prefixes, and retained MergeAObj order. A new boundary probe still fails: corrupt the second child of Consequently the current body’s “admitted by the type layer” statement is not established. Design section 4 proposes the correction; no new implementation has been pushed, no semantic PASS is claimed, and the CR threads remain open. The ordinary |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of exact head 19d8c39598f4db81c69d005be2c9718866ff7c2c: request changes. I read the complete proposed v1 design, prior findings/follow-up and the current SQL/public/trusted comparator boundaries. Moving the design into this PR makes the artifact reviewable; it does not close the explicitly acknowledged implementation defect.
[P1] Establish JSON payload admission before using the unchecked SQL comparator
pkg/sql/plan/function/func_compare.go:881-885 still assumes engine-owned T_json vectors have been validated and invokes CompareByteJsonTrusted. The trusted implementation in pkg/container/bytejson/types.go:336-342 dispatches by rank and can return after the first differing child, without classifying the complete document. Meanwhile ByteJson.Unmarshal at bytejson.go:134-138 still has the validation TODO, and neither the vector admission/decode paths nor a validated-source certificate are added by this PR. T_json plus valid vector framing is not proof that all JSON descendants are valid.
The source-matched counterexample already documented in the author's CR follow-up remains reachable by the unchanged admission path: corrupt the second child of [0,0], construct/serialize a T_json vector and decode it with checked UnmarshalBinary, then compare with [1,0]. The SQL trusted comparator returns true from the first child, but complete public comparison classifies the left document invalid and orders it after the valid document. SQL ordering/hash consumers therefore do not share the comparison domain promised by the design. This is an internal/disk/wire corruption fixture, not a claim that ordinary SQL can create malformed bytes.
Please implement the section-4 admission invariant before the trusted call becomes eligible: complete payload validation before publishing raw constant/append/replace values and checked decoded vectors; explicit immutable validated-source proofs for bypass/union paths; errors before visible row/metadata publication. Retain public raw fallback for deliberately arbitrary ByteJSON callers. Do not fix this by validating every document repeatedly inside the hot comparator, since that would reintroduce the previously measured cross-rank/early-exit performance regression. Add the actual checked-decode -> SQL-comparison counterexample as a failing-before/passing-after boundary regression and measure admission cost separately.
The SQL/physical separation direction remains reasonable: preserve the legacy writer relation and each raw merger relation without claiming a migration, and explicitly require homogeneous query semantics during rollout. The missing second merger terminal test is useful closure work, but I am not adding a separate blocker merely because that test is absent. Likewise, independent design approval alone would not repair the concrete unvalidated-input path above. The current design accurately marks that work as proposed and incomplete.
Evidence boundary: current-source inspection plus the existing source-matched reproduction and the unchanged admission/SQL call sites; no new local CGo/BVT execution or fresh corruption reproduction is claimed. Green CI does not invalidate this uncovered boundary. No additional independently confirmed lock/wait/resource-lifecycle blocker is raised in this review.
|
CR repair pushed as The new admission blocker is fixed with complete validation before raw JSON vector writes and checked decode publication, including encoder output, selected rows, legacy V1 framing and immutable copy/cache preconditions. The exact checked-decode counterexample fails with the old admission files restored and passes after the repair. Existing public malformed fallback, finite-number/shortest-prefix/hash contracts and SQL/physical separation are retained. Both physical merge paths now have terminal coverage. The new ordinary mergeObjs regression performs real object writing/checked readback across two merge generations; it passes on the pre-change base and final code, while the incompatible-comparator mutation fails. Local validation: relevant full CGo suites passed; identical base/final direct benchmarks include both cross-type directions and separate admission cost; the service version was verified as this commit and normal mo-tester comparison passed twice with clean reports/logs/cleanup. Schema-v7 semantic preflight and diff checks passed. New-head CI and external review/QA approval are not claimed. The version-2 design is in this PR. @aunjgr, independent approval of admission-time corruption errors, preserved physical relations and homogeneous query rollout is still needed. Implementation and local preflight do not replace your design decision. @XuPeng-SH @aptend, please re-review the repaired head. The existing Ready state is preserved; issue #28039 stays open pending QA. |
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head a9796da81b1a3b4e86f00e90623a3ef8de22945b against base 6e5f82f568b1ec3e013e8d4ab9031b2360300b84, following my prior review at c939dbf0775c33037969b69d8fc07bc8579550aa. I re-read all historical reviews, inline threads and author replies, checked the incremental admission changes and the complete 35-file diff, and verified the old raw-merger compatibility, hot-path validation and pair-dependent total-order findings are closed. Two blockers remain.
-
The new checked admission validator has exponential worst-case CPU in encoded input size; see the inline P1. This prevents me from accepting the design's current resource-bound tradeoff. I do accept admission-time corruption errors, preservation of the existing physical relation/no-migration policy, and the homogeneous query rollout assumption.
-
The exact head does not pass required unit tests. Both
Matrixone CI / UT Test on Ubuntu/x86andMatrixone UT Coverage / UT Coverage on Ubuntu/x86fail because the new T_json admission rejects existing raw fixtures withinvalid input: invalid JSON vector payload. The failures spanpkg/fulltext2,pkg/frontend,pkg/sql/colexec,pkg/sql/colexec/aggexec,pkg/sql/colexec/fill,pkg/tools/checkpointtool, andpkg/vm/engine/tae/db/test(the latter panics inTestIscpMeta). On the exact worktree I reproducedTestLoadedContainsPkTypes/jsonandTestColumnBufferRoundTripwith the same error. All affected T_json construction sites need encoded ByteJSON fixtures or an explicitly supported conversion boundary, and the required UTs need to be green before approval.
Validation on this exact head: make thirdparties and make -C cgo passed. Focused/ordinary tests passed for bytejson validation, bytejson, vector, keycodec, sort, partition, SQL functions, readutil, window, mergeutil and TAE mergesort. A temporary exponential-work counterexample passed with the measurements in the inline comment and was removed; the worktree is clean and git diff --check passes.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-review of a9796da, including the complete version-2 design and the admission delta from my 19d8c39 review. Admission-before-trusted-comparison is the correct architecture, and the earlier missing-admission finding is addressed. I accept the scoped no-migration physical-order policy and the explicitly homogeneous-query rollout assumption. I cannot accept the admission resource policy as currently implemented.
[P1] Bound validator work by serialized input, not expanded aliased descendants
Independently reproduced the current pkg/internal/bytejsonvalidate/validate.go unchanged in an isolated stdlib-only Go test. Two child entries point to the same nested suffix at each level. At 18 wrapping levels the document is only 342 bytes, yet Container accepts it and invokes the scalar callback 524,288 times. The ordinary two-literal control passes with exactly two visits. Each 18-byte wrapping layer doubles the work. This is an executable complexity counterexample, not a timing guess or a fresh native decoder run.
Because the PR installs this recursion on raw T_json admission and checked disk/wire decode, a tiny malformed/adversarial representation can monopolize CPU before publication. Merely documenting expanded B or unspecified depth in section 6 does not bound the production input cost.
Please either reject overlapping/noncanonical child ranges under a compatibility-proven encoding contract, or memoize validated typed ranges with bounded state; also enforce an explicit depth/work policy or use an iterative bounded traversal. Keep complete descendant validation at admission, not inside each hot comparison. Add aliased-range and deep-chain counterexamples with deterministic work counters, malformed/valid controls, and no-publication assertions. Re-measure admission separately from steady-state comparisons.
[P1] Repair the existing T_json consumers/fixtures rejected by the new admission contract
Current-head Ubuntu UT and UT coverage fail. The existing review identifies invalid JSON vector payload failures across fulltext2/frontend/colexec and other suites, with exact-head reproductions for TestLoadedContainsPkTypes/json and TestColumnBufferRoundTrip. These are not unrelated flaky checks: the new validator changes their accepted construction path. Audit failing production/test call sites, use encoded ByteJSON where T_json is intended, and do not weaken the admission guard or relabel invalid fixtures as trusted. Run the affected complete packages and required UT producer checks on the repaired head.
Validation: isolated exact-source validator regression fails as above (0.005s package run); valid control passes. Author-reported exact-head CGo/BVT/merger and performance evidence was reused, not rerun. Design decision for this revision: REQUEST_CHANGES on the resource-bound contract; previously closed physical-merge and hot-comparison findings remain closed.
|
CR repair submitted at Bounded admission
Before Genuine UT failuresInspected exact failed job Complete affected packages pass, including Frontend and TAE db/test. Complete function, bytejson, vector, keycodec, sort, partition, window, readutil, mergeutil and mergesort suites pass. Focused admission Admission and steady-state comparison were measured separately on Darwin/arm64: median admission small55.24ns / wide13.024us, both0 allocations; the 1024-row array/boolean comparison batch is about10us with0 allocations. These are local microbenchmarks, not a deployment throughput claim. No descendant validation or full-column cache was added to SQL comparison. Whole-diff semantic review: PENDING; the previous overall PASS is withdrawn (see evidence correction below). Local evidence is retained under Learning Decision: NO_CHANGE for bounded admission and typed-fixture authenticity under existing R2/R5/R7; no permanent instruction changes. Evidence correction — 2026-09-08Evidence correction (2026-09-08): the whole-diff semantic PASS previously reported here is withdrawn. The manifest generator copied expected results into observed results and set PASS unconditionally; the validator checked declarations and coverage structure, not their truth. Individual executable results are separate evidence and are being checked against their exact content and test assertions. Overall semantic review is PENDING. This correction does not claim that all tests were invalid or that the code repair failed. Current-head CI, reviewer approval and applicable design/QA gates remain separate. |
|
Evidence correction and independent revalidation — 2026-09-08 Current head: This commit adds regression assertions only. All production content is unchanged from acb817e. Raw-admission failures preserve existing state and the same vector accepts a subsequent valid append. Binary/copy/reader/legacy/selected checked-decode failures are followed by a successful retry on the same target; raw-copy construction returns nil on failure and a valid separately freed vector on retry. Existing mpool-zero assertions remain. Canonical RANK/DENSE_RANK SQL now asserts that 1 and 1.0 are peers before 2. Verified local evidence:
Coverage diagnosis for the preceding acb817e head: GitHub UT Coverage failed in TestIssue23861FulltextSnapshotRestore at the SNAPSHOT feature-registry multiple-result guard. Dependent Coverage failed its prerequisite check. The signature matches existing #28259, including a documented recurrence after #28262 (already present in this head). This is not a measured drop in coverage percentage. Precise transaction interleaving in that run remains unproven. The named SNAPSHOT test passed in local ordinary and CI-tagged execution. However, the full local issues package with -short -tags=matrixone_test returned FAIL: TestIssue27666CDCWatermarkWriteSerializesWithDrop/writer_wins hit its waiter-observation deadline. The other 310 test terminal events passed. This distinct CDC failure has historical context in #28282, but this head already contains #28283; the new occurrence is retained as an unresolved diagnostic failure, not silently excused. The isolated CI-tagged CDC test passes on the same content. That does not erase the full-suite failure or prove its precise cause; no assertions or timeout thresholds were changed. Version3 of the integrated design still needs independent approval. @aunjgr @aptend @XuPeng-SH: please re-review the bounded admission/resource policy, unchanged physical writer/raw-merger relations, malformed fallback and homogeneous-query rollout contract on this head. Earlier physical-policy acceptance and local tests are not a substitute for your version3 decision. Closed design PR #28315 remains closed. Whole-diff schema-v7 mapping/review remains PENDING. New-head CI, independent design/review approval and QA remain separate gates; no merge-readiness claim is made. Original logs, current failures, source hashes, commit binding and the claim ledger are retained locally under pr28093-28086-evidence-audit. This is the continuing correction summary, updated in place. |
|
Exact-head evidence update for PR #28086 (2026-09-09)
CI action_performed: none. current_ci_resolution: unresolved — the required Ubuntu/x86 UT result is a runner/job termination rather than a confirmed product assertion failure; a fresh required check result is still needed. The existing CHANGES_REQUESTED/design-approval and QA gates remain open. The previously addressed blocking findings have been revalidated; please re-review the handled implementation blockers. |
|
Published the reviewed follow-up at commit
Ready state and issue/QA state are unchanged. |
…28086-20260909 # Conflicts: # pkg/container/vector/vector.go
|
CR follow-up on exact merged-sync head
Please re-review the current head against the two formal CRs: bounded validator work and complete checked admission for typed/decoded consumers. The PR remains Ready; QA and independent approval gates remain open. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of exact head 98e61b4 against f0c31cd, including the complete current change map, prior REQUEST_CHANGES findings, version-3 design and current admission/comparison/order/hash/pruning consumers. No confirmed merge-blocking finding remains.
Design-first decision: PASS for docs/design/json_sql_physical_order.md version 3 at this exact document commit. I completed that phase before resuming implementation approval. I explicitly accept admission-time corruption errors, the serialized-byte shared traversal budget and 100-container depth policy (a documented tightening for retained/raw values), preservation of BOTH pre-existing physical relations without migration, and the homogeneous query-executing CN rollout/drain requirement. This approval is not evidence of mixed-version SQL correctness or QA acceptance. The stale pending/version-2 record in section 9 can now be updated to link this exact-revision independent decision.
The two prior blockers are closed:
- The validator now charges container tables, object keys and scalar payloads against one root serialized-byte budget before further traversal/validation, and rejects depth above 100. Aliased child ranges cannot cause exponentially expanded work. I independently copied the exact stdlib-only validator and committed tests into a temporary directory and ran them: TestContainerBoundsAliasedDescendantWork and TestContainerBoundsNesting both PASS, including canonical-tree and 100/101-level controls. This was a real exact-source executable check, not a timing inference or a manifest PASS declaration.
- The affected T_json fixtures now supply encoded ByteJSON through real checked admission, and explicit corruption probes are identified as such. Raw append/replace/encoder and six checked decoder paths retain rejection-before-publication, valid reuse after rejection, NULL controls and terminal mpool cleanup assertions. The ObjectIO typed constructor now uses AppendBytes rather than treating encoded bytes as a fixed element. Current-head Linux UT and UT Coverage are successful (run 34310535843), resolving the prior required-test failure blocker.
The current implementation maintains separate SQL rank/numeric-peer semantics, public malformed-value fallback, and trusted admitted-value comparison. SQL NULL and null-safe equality remain distinct from JSON null; mixed JSON/BOOL and prepared-comparison dispatch retain their existing coercion paths. Numeric peers feed consistent canonical keys and ORDER BY/window partitioning. Raw JSON zone-map value predicates fail open while null-count pruning remains useful. The writer relation and raw merger relation are intentionally not unified. The current regression matrix includes direct precedence pairs, malformed later-child classification, numeric precision, multi-key and RANK/DENSE_RANK peers, retained physical-run write/readback and pruning counterexamples. No additional confirmed lifecycle, concurrency or hot-comparison resource defect was found.
Evidence limits: the independent run here was the isolated validator suite; I did not rerun native/full-package, real-service BVT, MySQL differential or benchmark workloads. Exact-head UT/coverage/SCA and individually described author execution evidence were reused. I did not rely on the withdrawn automatically asserted whole-diff semantic PASS. Keep #28039 open for the explicitly required versioned QA and homogeneous-CN rollout acceptance; review approval does not close those operational gates.
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head 98e61b4b4e18f929c74db65c18793e0b1ed2a280 against f0c31cd4b830be32442cf329e0a3fb08aa9c16c3. No confirmed merge-blocking finding remains.
The review covers the 48-file change map: SQL precedence and exact numeric/hash equality; physical writer and raw merger relations; ordering/window peers; JSON pruning; raw/checked vector admission, immutable cache/copy preconditions, failed publication and cleanup; and the changed fixtures and regressions.
I verified the independent version-3 design approval at this exact head. The accepted homogeneous query-CN rollout, admission-time corruption errors, byte-work/depth bounds, and preservation of both existing physical relations remain explicit constraints; this is not approval of arbitrary mixed-version SQL correctness or completion of QA.
Evidence reused: exact-head successful CI, checked admission/reuse/race tests, ordering/hash/peer cases, and two-generation merge/write/readback evidence. No additional cluster or native test run was performed for this review. Head, open/non-draft state and passing applicable CI were rechecked before submission.
aptend
left a comment
There was a problem hiding this comment.
Deep re-review of exact head 98e61b4b4e18f929c74db65c18793e0b1ed2a280 against base f0c31cd4b830be32442cf329e0a3fb08aa9c16c3, including all prior reviews, inline comments, replies and resolved threads, the incremental changes since my last reviewed head a9796da81b1a3b4e86f00e90623a3ef8de22945b, and the complete current diff.
No merge-blocking finding remains. The two blockers from my previous review are closed: the admission validator now shares a serialized-byte work budget and enforces a 100-container depth bound, preventing aliased descendant expansion; the invalid T_json fixtures and construction paths are repaired, and exact-head required CI is green. I independently checked admission/no-publication/retry behavior, comparator/hash/order/peer/pruning consistency, physical writer versus raw merger separation, and the two-generation readback coverage.
I accept v3's explicit constraints: admission-time corruption errors, bounded and depth-limited raw admission, preservation of both existing physical relations without migration, and homogeneous query-CN rollout/drain. This approval is not mixed-version SQL correctness or final QA acceptance; keep #28039 open for versioned QA.
Local exact-head validation passed: make thirdparties, make -C cgo, and package tests for bytejsonvalidate, bytejson, vector, keycodec, sort, partition, function, readutil, objectio/mergeutil, TAE mergesort, and window. git diff --check also passed.
What type of PR is this?
Which issue(s) this PR fixes:
issue #28039
What this PR does / why we need it:
Correct SQL JSON precedence while keeping persisted writer ordering and both raw TAE merger relations unchanged. JSON value-based zone-map pruning fails open; null-count pruning remains available. Numeric peer equality agrees with canonical hash keys.
MIN/MAX(JSON)remains unsupported andMIN/MAX(NULL)retains its previous type.Raw JSON vector writes now validate every descendant before publishing a row. Checked binary, copied, reader, selected-row, legacy and raw-copy decoders reject corrupt non-NULL payloads before publication. Encoders validate their emitted bytes; failed appends/replacements preserve visible state. Same-type copies/unions and the existing sealed objectio V2 cache retain explicit immutable admitted-source preconditions. Direct SQL comparison therefore uses the trusted comparator without a full descendant walk per comparison or a full-column cache. Public ByteJSON comparison/hash retain deterministic raw fallback for malformed diagnostic values.
Version 3 of the design records these admission owners, unchanged physical relations, resource-policy limits and the homogeneous-query rollout requirement. The separate design PR #28315 is closed and its document is consolidated here. Independent design approval remains pending; local repair/preflight is not that approval.
Validation for
396d983ec8e4027b86b4c92f425a862fcb9e2bf7:QA required: yes. This changes visible SQL comparison/order/hash behavior and corruption handling. Automated coverage reaches direct SQL, multi-key/numeric peers, pruning, checked admission and real merger object readback. Independent design approval, required current-head CI, review approval, and versioned QA on homogeneous query-executing CNs remain required. Keep #28039 open until explicit QA acceptance; this PR does not request issue closure.
Evidence correction — 2026-09-08
Evidence correction (2026-09-08): the whole-diff semantic PASS previously reported here is withdrawn. The manifest generator copied expected results into observed results and set PASS unconditionally; the validator checked declarations and coverage structure, not their truth. Individual executable results are separate evidence and are being checked against their exact content and test assertions. Overall semantic review is PENDING. This correction does not claim that all tests were invalid or that the code repair failed. Current-head CI, reviewer approval and applicable design/QA gates remain separate.