Skip to content

fix: support bounded XPath aggregates and MySQL predicate context - #29362

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29329-xpath
Sep 25, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29329-xpath

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI

Which issue(s) this PR fixes:

Fixes #29329

What this PR does / why we need it:

EXTRACTVALUE previously rejected MySQL-compatible sum(path), count(path)=integer, and [position()=last()]. This PR adds those expressions to the existing bounded XPath evaluator, preserves per-row resource limits, and makes scalar UpdateXML targets return NULL. It also aligns numeric text parsing and formatting with MySQL for the tested subset.

The latest review follow-up fixes the shared intermediate-result owner. With nested matching contexts, a single path can reach the same node more than once; its occurrence order also controls later positional predicates. The evaluator now preserves the ordered occurrence stream through each step. An explicit | union deduplicates before numeric aggregation, ordinary ExtractValue displays each node once, and UpdateXML replaces only when the raw path selects exactly one occurrence. The parent axis keeps its existing document-order deduplication. Each added occurrence is charged to the existing work and scratch budgets; no general XPath framework, cache, or new shared state was added.

Examples against MySQL 8.0.44:

  • <a><a><b>1</b></a></a> with sum(//a//b) returns 2; sum(//a//b|//a//b) returns 1.
  • <r><a><a><b>1</b></a></a><a><b>2</b></a></r> with //a/*[1][position()=last()] returns 1; the prior PR head returned 2 and targeted the wrong element in UpdateXML.

Design and validation

  • Rev4 design, content SHA-256 14c2a9b6fcc3ff4ab487f2c04d4d1b9e10f2ee7bd048d0d7bc30cb9eac90971b, was independently reviewed before the production change: GPT-6 medium, PASS. It defines encounter order, overlapping occurrences, explicit union, parent-axis behavior, output boundaries, and resource limits.
  • Pre-fix focused regression: four new cases failed on the old head (overlapping count/sum, nested positional selection). The same focused cases, the overlap-budget test, and the full owning pkg/sql/plan/function package pass after the fix using the repository mo-cgo-test wrapper and task-built native artifacts (make -j8 cgo).
  • Independent MySQL 8.0.44 oracle: 1,163 accepted expressions from a saved 1,793-case probe matrix match the updated evaluator exactly; before the fix, 52 accepted-query mismatches clustered in the two corrected semantic families. MySQL-rejected syntax was excluded from that comparison. Targeted UpdateXML cases were independently checked with MySQL.
  • Real local mo-service built from the fixed worktree using make build-with-prebuilt-native. mo-tester normal result comparison ran test/distributed/cases/function/func_xml.test twice on the same task-owned instance: 71/71 success, 0 failed, 0 ignored or abnormal on each run. Metadata comparison was enabled. The test database residue was 0 after each run; the instance was stopped and ports closed.
  • Incremental static closure: changed Go package ./pkg/sql/plan/function; go vet passed, golangci-lint v2.6.2 with --new-from-rev fdfbea4fb7125d538d8675d725ace17811760023 reported 0 issues. gofmt and git diff --check passed.
  • Source-only evaluator benchmark on the same 1,000-sibling document (Go 1.26.4, Linux/amd64, GOMAXPROCS=1, 3×100 iterations): /a/b and count(/a/b) went from 40 to 28 allocs/op and 79,760 to 50,472 B/op; /a/b[1] went from 18 to 17 allocs/op and 29,360 to 25,272 B/op. CPU timings also fell in this microbenchmark. This measures the evaluator only, not service throughput.
  • Independent GPT-6 medium full-diff review found no code blockers; final evidence review completed after BVT/static/benchmark results. The previous exact-head CI passed UT, SCA and BVT. The new commit's CI is pending; local validation above is terminal and no CI wait is required.

Risk and rollback

The compatibility subset still rejects unsupported XPath syntax explicitly. Overlapping paths may now reach the documented per-row work/scratch limit earlier, which bounds amplification. No wire, catalog, storage, or process-shared state changed. Revert the final occurrence-stream commit to restore the previous behavior.

@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 →

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 24, 2026
@mergify mergify Bot added kind/bug Something isn't working kind/enhancement kind/test-ci labels Sep 24, 2026
@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-29329-xpath branch from 41f2f21 to 74e4cc7 Compare September 24, 2026 17:45
@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-29329-xpath branch from 9be5b79 to 48b81c0 Compare September 25, 2026 02:03
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 25, 2026
@XuPeng-SH XuPeng-SH changed the title fix: support bounded XPath aggregates and comparisons fix: support bounded XPath aggregates and MySQL predicate context Sep 25, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review — recommendation: REQUEST_CHANGES

Reviewed head 5c5fbe080eb430996df28da3a36e528c56af26f9, declared-base/merge-base fdfbea4fb7125d538d8675d725ace17811760023; freshly fetched main was 426cf10b000b6a828e8c69f1af26082f26036ed3. Two P2 correctness findings are attached inline: intermediate context ordering for chained predicates, and lost overlapping descendant occurrences in the new sum() input. Both have small deterministic MySQL counterexamples inside the supported syntax.

Evidence

  • Independently compared the exact-head XML parser/evaluator and its existing numeric formatter with an isolated MySQL 8.0.44 oracle. Of 1,793 generated probes, 1,163 were accepted by MySQL; the 52 successful-query discrepancies reduce to the two semantic families above, including pre-existing count variants. MySQL-rejected self/parent-predicate syntax was excluded from these findings. Saved minimal reproductions were rerun separately. Compared the base evaluator to distinguish existing gaps from new behavior.
  • These local probes compile copied source with only the package declaration changed, plus the exact existing numeric formatting helpers; they are evaluator-level evidence, not a local full-server/BVT run.
  • Reused current-head CI: SCA and Ubuntu UT passed. The UT log explicitly selects the owning function package in the -race heavy stage and records its terminal status 0. The pessimistic BVT log confirms function/func_xml.test actually ran: 67 total, 67 successful, 0 failed/ignored. Those tests omit the counterexamples above.
  • Read all eight changed files and traced scalar parsing, numeric conversion/formatting, shared ExtractValue/UpdateXML consumers, limits/cancellation, malformed-input/warning behavior and test-vector ownership. No additional blocking lifecycle, boundedness or common-path performance finding. The author’s 1,000-sibling allocation evidence remains applicable to the unchanged common-path shape; this is not a broad throughput claim. git diff --check passes and the review worktree is clean.

The bounded evaluator and reuse of the existing formatter are appropriate in scope. These gaps call for targeted context-sequence fixes and small oracle-backed UT/BVT cases; they do not justify a general XPath framework. The original issue's three simple examples are covered, but the newly supported composition is not yet correct.

Submitted as a COMMENT review because the authenticated account is also the PR author and GitHub disallows requesting changes on one's own PR. The recommendation remains REQUEST_CHANGES.

if ok {
filtered = append(filtered, c)
if match {
candidate.position = len(filtered) + 1

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve XPath context order before renumbering chained predicates

The new global survivor positions use the order of records, but earlier steps rebuild current in node-ID/document order. This loses MySQL's context enumeration order when //a includes both nested and sibling a nodes. Minimal supported input:

SELECT EXTRACTVALUE(
  '<r><a><a><b>1</b></a></a><a><b>2</b></a></r>',
  '//a/*[1][position()=last()]');

MySQL 8.0.44 returns 1; the exact-head evaluator returns 2. //a//b[1][position()=last()] has the same failure. The wrong unique node also flows into UpdateXML's source-span replacement, so this changes which element is replaced. Preserve the reference context order through intermediate steps before assigning subsequent predicate positions, with focused nested-plus-sibling extraction/update regressions. The existing flat multi-parent tests do not exercise this ordering.

return float64(len(ids)), nil
}
var total float64
for _, id := range ids {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Retain overlapping descendant occurrences for the new sum evaluator

ids comes from evaluatePaths, which collapses matches into seen/selected boolean sets. MySQL's aggregate input can contain repeated occurrences when descendant contexts overlap:

SELECT EXTRACTVALUE('<a><a><b>1</b></a></a>', 'sum(//a//b)');

MySQL 8.0.44 returns 2; this head returns 1 because the same b is reachable through both a contexts but contributes only once. As a control, sum(//a//b|//a//b) returns 1 in both engines: an explicit union does deduplicate. Keep the aggregate occurrence semantics distinct from union/output deduplication, retaining the existing work/scratch bounds, and cover both cases. The analogous count() discrepancy already exists in the base; this finding concerns the newly introduced sum() contract.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of 566c195e65ad4e9b807bf996c549c4b3b6d9de56.

Result: no blocking findings in this PR; recommend merge once required CI checks pass. The two P2 findings from the review of 5c5fbe080e are addressed. Submitted as COMMENT because the authenticated account is also the PR author.

Scope and design

Reviewed every hunk in all eight changed files and traced the shared ExtractValue/UpdateXML consumers. The declared base and merge-base are fdfbea4fb7125d538d8675d725ace17811760023; freshly fetched main is ce7f84dabc563fa5bb29c648e8b02aa6581b608b. The relevant XML owners, test helper and module dependencies are unchanged between that merge-base and fetched main. The detached review worktree is clean and git diff --check passes.

The public XPath expansion triggers the design gate. The Rev4 design, SHA-256 14c2a9b6fcc3ff4ab487f2c04d4d1b9e10f2ee7bd048d0d7bc30cb9eac90971b, matches the design-first approval recorded in the PR. The implementation follows its occurrence-order, union, parent-axis and resource-limit decisions. No additional framework or architectural expansion is needed.

Correctness, cleanup and bounds

Closure Review result
Original issue #29329 sum, aggregate/integer comparisons and composed position predicates use the shared evaluator. Original outputs 3 / 1 / 2, nearby controls, integer precision, numeric text conversion and scalar UpdateXML behavior are covered.
Overlapping contexts and predicate order Individual paths preserve ordered occurrences through subsequent steps; explicit union deduplicates. Parent-axis uniqueness remains explicit. This closes both the undercounted sum and the incorrect later positional selection. ExtractValue deduplicates displayed nodes, while UpdateXML checks raw match cardinality before byte-preserving replacement.
Q1: ownership Compiled programs belong to an invocation; document/scratch belong to one row; output is copied to the caller-owned result. No new external resources or retained state. The earlier UT cleanup omission is fixed, and expected vectors in FunctionTestCase.Run now have deferred release.
Q2: termination No new goroutines, locks or I/O. Parser/evaluator budget checks observe cancellation. Review probes cover cancellation in sum and in the right aggregate of a comparison, with live controls.
Q3: growth Existing input/AST/depth/node/output limits remain. Each occurrence and filtering pass consumes work/scratch budget. Overlap amplification terminates at the per-row limits; errors propagate rather than becoming XML warnings or partial success.
Public/error/test contracts NULL/XPath precedence, malformed XML warnings, masked rows, prepared recompile, terminal-text update mapping and metadata were traced. Existing UT/BVT fixtures are reused; no extra cluster setup or sleep-based synchronization was introduced.

Validation and performance

  • Reused the saved focused, budget and full owning-package runs (full package 15.474s), vet and lint (0 issues). The saved evaluator/tokenizer source and numeric formatter were compared with the reviewed source; the original validation worktree is clean at this exact head.
  • Reused real-service, normal-comparison XML BVT runs: 71/71 passed twice on the same instance, with metadata comparison and recorded teardown checks. Case execution was 1.776s / 2.732s. These are public-path evidence, separate from the source probes below.
  • Independently rebuilt the current source-level evaluator and reran the saved MySQL 8.0.44 matrix: 1,163 MySQL-accepted expressions, zero mismatches. The previous 52 mismatches are gone.
  • A fresh isolated MySQL 8.0.44 oracle checked composition through parent/self/attribute/text and later predicates: 855 accepted expressions, 843 matching, 12 pre-existing discrepancies described below. Additional UpdateXML consumer probes: 15/15 match, including overlapping targets, union, terminal text and scalar NULL results. The oracle container had no network/host ports and was removed after validation.
  • New review-only deterministic unhappy-path probes: 9/9 passed (0.002s), covering normal output, exhausted work budget and cancellation for sum and both sides of aggregate comparisons. These and the compatibility probes compile copied exact parser/evaluator source with CGO_ENABLED=0; they supplement the reused native package/service runs and do not replace them.
  • Reused exact-source evaluator microbenchmarks: /a/b and count(/a/b) decreased from 40 to 28 allocs/op, 79,760 to 50,472 B/op; /a/b[1] decreased from 18 to 17 allocs/op. Removing unconditional per-step bitmap scans explains the improvement. This measures evaluation only, not parsing or service throughput. The bounded helpers and single-group fast path have a concrete purpose; no overengineering concern found.
  • Current-head CI run: shared build and UT coverage passed. Downloaded coverage report confirms producer exit 0. UT/race, SCA and both active BVT jobs are still running at submission and are not counted as passed. The author’s local validation remains the available evidence for those completed local checks.

Separate existing compatibility gap

The 12 new comparison differences all reduce to attribute followed by terminal text(): for example, ExtractValue('<a k="7">8</a>', '/a/@k/text()') returns an empty string in MO and 7 in MySQL. A separately built exact merge-base evaluator produces the same result as this head for all 12 cases. This is an existing attribute/text semantic gap, not a regression from this PR or evidence that the two P2 fixes failed; it should not be silently included in an all-expressions-compatible claim. No additional scope or external issue was created by this review.

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 kind/enhancement kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Compatibility]: EXTRACTVALUE rejects MySQL XPath aggregate and composed expressions

3 participants