Optimize XPath step#315
Conversation
There was a problem hiding this comment.
Pull request overview
This PR refactors XPath step evaluation in REXML::XPathParser to defer nodeset materialization and introduce axis “scan strategies” that can fast-path common predicate shapes (position-independent and simple positional predicates), improving performance for deep and wide-tree queries.
Changes:
- Reworked
stepto drive axis scans via[scanner_method, scanner_argument]and choose scanning strategies (:uniq,[op, value],:nodesets) based on predicate classification. - Added optimized scanners for
descendant(-or-self),ancestor(-or-self), and sibling axes, plus a shared fallback selection path. - Added/updated XPath predicate and sibling-axis tests, including float literal predicates and positional comparisons.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| lib/rexml/xpath_parser.rb | Implements deferred scanning/strategy selection in step, predicate classification, and optimized axis scanners. |
| test/xpath/test_predicate.rb | Adds coverage for float-literal positional predicates and variable-as-position predicates. |
| test/xpath/test_base.rb | Adds test for following-sibling::* with position() < N and adjusts nested-predicate test behavior. |
| test/xpath/test_axis_preceding_sibling.rb | Adds tests for preceding-sibling:: with < and <= position predicates. |
Comments suppressed due to low confidence (1)
lib/rexml/xpath_parser.rb:834
descendantaxis fast path callsraw_node.childrenwheninclude_selfis false without checking the node type or whetherchildrenexists. If the context node is not an element/document (e.g., an attribute node), this will raiseNoMethodError; previously it would just yield an empty descendant set. Guard this branch so it only iterateschildrenfor element/document nodes (or use the same node_type check as inrecursive).
raw_nodes.each do |raw_node|
if include_self
recursive.call(raw_node)
else
raw_node.children.each(&recursive)
end
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
6f94f2e to
c4a1440
Compare
c4a1440 to
67e3270
Compare
67e3270 to
593620b
Compare
| result = evaluate_predicate(predicate_expr.dclone, [result]).first || [] | ||
| end |
| end | ||
|
|
||
| def preceding_following_sibling(raw_nodes, tester, selector, reverse:) | ||
| raw_nodes = raw_nodes.select(&:parent) |
593620b to
65c5103
Compare
65c5103 to
15a8f52
Compare
15a8f52 to
020085a
Compare
020085a to
926e521
Compare
| raw_nodes.group_by(&:parent).flat_map do |parent, sibling_nodes| | ||
| anchors = {}.compare_by_identity | ||
| sibling_nodes.each {|sibling| anchors[sibling] = true } | ||
| children = parent.children | ||
| children = children.reverse if reverse | ||
| followings = children.drop_while {|child| !anchors.key?(child) }.drop(1) | ||
| anchor_indexes = { 0 => true } | ||
| last_anchor = 0 | ||
| index = 0 | ||
| matched = [] | ||
| followings.each do |node| | ||
| if tester.call(node) | ||
| case operator | ||
| when :== | ||
| matched << node if anchor_indexes.include?(index - value + 1) | ||
| when :< | ||
| matched << node if last_anchor > index - value + 1 | ||
| when :> | ||
| matched << node if index >= value | ||
| end | ||
| index += 1 | ||
| end | ||
| if anchors.key?(node) | ||
| anchor_indexes[index] = true | ||
| last_anchor = index | ||
| end | ||
| end | ||
| matched |
There was a problem hiding this comment.
No. In > case, index from the first anchor(always zero) is the possible maximum index among relative index from several anchor nodes. I modified the code a bit, and added source code comment that describe this.
| seen = {}.compare_by_identity | ||
| nodesets.each do |nodeset| | ||
| nodeset.each do |node| | ||
| raw_node = node.respond_to?(:raw_node) ? node.raw_node : node | ||
| seen[raw_node] = true | ||
| end | ||
| end | ||
| ordered = sort(seen.keys) | ||
| ordered.map.with_index(1) do |raw_node, position| | ||
| XPathNode.new(raw_node, position: position) | ||
| end |
There was a problem hiding this comment.
REXML previously skipped nodesets ordering when nodesets.size == 1, but it turned out that it was a bug. nodesets.first is sometimes sorted in reverse-document-order while the order should be document-order.
We can reduce sort in the future such as:
- Add an ordered/reverse-ordered/unordered flag to nodeset
- Sort only on the final result and before applying filter predicates
But this kind of separate optimization should be out of scope of this PR.
926e521 to
73dd670
Compare
73dd670 to
a6476a2
Compare
a6476a2 to
c2d8012
Compare
| if pre_predicates.any? | ||
| original_tester = tester | ||
| tester = -> (node) do | ||
| original_tester.call(node) && | ||
| pre_predicates.all? do |predicate_expr| | ||
| evaluate_predicate(predicate_expr.dclone, [[node]]).flatten.size == 1 | ||
| end | ||
| end | ||
| ordered_nodeset = sort(raw_nodes, order) | ||
| end |
| when :nodesets | ||
| nodesets = nodeset.map do |node| | ||
| parent = node.parent | ||
| index = parent.children.index(node) | ||
| reverse ? parent.children[0...index].reverse : parent.children[index + 1..-1] | ||
| end | ||
| non_optimized_nodesets_select(nodesets, tester, selector) |
There was a problem hiding this comment.
No. This is a non-optimizable slow path that needs O(n^2) calculation cost just like before.
| # Not working at all, so just return an empty nodesets for now. | ||
| # Needs Namespace-node class | ||
| [:iterate_nodesets, []] |
c2d8012 to
42c4307
Compare
42c4307 to
2f6ea03
Compare
| sort(seen.keys) | ||
| ensure | ||
| leave(:step, path_stack, new_nodeset) if @debug | ||
| leave(:step, path_stack, ordered) if @debug | ||
| end |
| operator, value = selector | ||
| nodeset.group_by(&:parent).flat_map do |parent, sibling_nodes| | ||
| anchors = {}.compare_by_identity | ||
| sibling_nodes.each {|sibling| anchors[sibling] = true } | ||
| children = parent.children | ||
| children = children.reverse if reverse | ||
| followings = children.drop_while {|child| !anchors.key?(child) }.drop(1) | ||
| anchor_indexes = { 0 => true } | ||
| last_anchor = 0 | ||
| index = 0 | ||
| matched = [] | ||
| followings.each do |node| | ||
| if tester.call(node) | ||
| case operator | ||
| when :== | ||
| matched << node if anchor_indexes.include?(index - value + 1) |
| when :nodesets | ||
| nodesets = nodeset.map do |node| | ||
| parent = node.parent | ||
| index = parent.children.index(node) | ||
| reverse ? parent.children[0...index].reverse : parent.children[index + 1..-1] | ||
| end | ||
| non_optimized_nodesets_select(nodesets, tester, selector) |
| nodeset = step(path_stack, any_type: :namespace) do | ||
| nodesets = [] | ||
| nodeset.each do |node| | ||
| raw_node = node.raw_node | ||
| case raw_node.node_type | ||
| case node.node_type | ||
| when :element | ||
| if @namespaces | ||
| nodesets << pre_defined_namespaces.merge(@namespaces) | ||
| else | ||
| nodesets << pre_defined_namespaces.merge(raw_node.namespaces) | ||
| nodesets << pre_defined_namespaces.merge(node.namespaces) | ||
| end | ||
| when :attribute | ||
| if @namespaces | ||
| nodesets << pre_defined_namespaces.merge(@namespaces) | ||
| else | ||
| nodesets << pre_defined_namespaces.merge(raw_node.element.namespaces) | ||
| nodesets << pre_defined_namespaces.merge(node.element.namespaces) | ||
| end | ||
| end | ||
| end | ||
| nodesets | ||
| # Not working at all, so just return an empty nodesets for now. | ||
| # Needs Namespace-node class | ||
| [:iterate_nodesets, []] | ||
| end |
If a predicate of xpath is position-independent, we don't need to create nodesets that has many duplicated nodes with different positions. Implements optimization of preceding-sibling/following-sibling with simple positional predicates as an example. We can add more optimizations for other axis in the future.
2f6ea03 to
739cba0
Compare
Depends on
#317(merged) and #320Refactor
stepso that nodeset materialization is deferred. Instead of building the full nodeset up front and filtering through predicates,each axis returns a scan descriptor (
[generator_name, generator_argument]), andsteppicks a scan strategy based on the predicates' shape.Predicates are classified into three groups:
[@a="1"],[name()="foo"],[@a=@b]:uniq— emit deduplicated matching nodes[N],[position()=N],[position()>N],[position()<N][op, value]— positional scan with one comparison[position()*@a],[last()-1], ...:nodesets— fall back to per-anchor nodesets + the previousevaluate_predicatepipelineMixed predicate lists are split: position-independent predicates before the first positional predicate are folded into the node test;
predicates after it are applied per-node on the result.
Each axis can implement zero, one, or all of the three strategies. If a strategy is not implemented, the generator falls back to producing
:nodesetsand the common slow path (non_optimized_raw_nodesets_select) handles dedup / positional filtering on flattened nodesets — i.e. thesame behavior as before this PR.
This pull request adds fast paths for:
descendant/descendant-or-self::uniq(single DFS with a seen-set; this is what speeds up//a//a//a//a)ancestor/ancestor-or-self::uniq(parent-chain walk with a seen-set)preceding-sibling/following-sibling::uniqand[op, value](sibling scan with anchor-index tracking)Other axes (
child,parent,self,attribute) keep the previous behavior via the fallback path; they can be optimized in follow-ups without changing call sites.Detail
For
//a//a//astyle queries, the previous code built nodesets keyed by each anchor, including the same descendant once per anchor. The new:uniqpath scans every node at most once per step.For
[position() > N]style predicates on wide trees (e.g.//a/preceding-sibling::*[position()>2]), we previously built the fullpreceding-sibling nodeset for each anchor and then ran
evaluate_predicate. The new[op, value]path scans children once per parent and usesanchor-index bookkeeping to recover per-anchor positions.
Note: general XPath cannot be linear — e.g.
*[position() * number(@a) % number(@b) = 1]is genuinely O(n²) — so the goal is only to add a fast-path for specific case: position-independent predicates and simple-positional predicates.Remove XPathNode
It turned out that we don't need XPathNode. We're just unnecessarily packing/re-packing to XPathNode.
Benchmark