Skip to content

🐛 fix(xpath): keep [N] with later predicates linear - #2446

Merged
gaborbernat merged 1 commit into
tox-dev:mainfrom
gaborbernat:fix/positional-predicate-2444
Nov 17, 2026
Merged

gaborbernat merged 1 commit into
tox-dev:mainfrom
gaborbernat:fix/positional-predicate-2444

Conversation

@gaborbernat

Copy link
Copy Markdown
Member

An XPath step whose positional predicate is not its last predicate, such as ancestor::b[1][@x], walked its whole axis again for every context node. On a long document the total work grew with the square of the document size, even when the selected node sat next to the context.

The first positional predicate now selects the node, and the predicates after it judge only that node, where position() and last() are 1 as they would be for the step's own single selection. The walk memo and the positional index answer these forms, so axis::name[N][predicate] costs the same as axis::name[predicate][N]. The plain walk stays for forms that do not select by position.

document = parse(html)
document.xpath("//a[ancestor::b[1][@x]]")  # walked the whole ancestor axis per <a>; now it takes the nearest <b> and checks its @x

The new work_steps tests cover each axis (ancestor, ancestor-or-self, preceding, following, preceding-sibling, following-sibling, descendant) with [1], [2] and [last()] followed by a predicate, and check that the linear tests fail before the change. The correctness tests compare each form with the same selection written through a position() > 0 barrier, which keeps the plain walk, and they also run the form inside an outer predicate.

Fixes #2444

A positional predicate that was not the last predicate of its step fell
back to walking the whole axis for each context node. A predicate such as
ancestor::b[1][@x] now takes the nearest node from the walk memo or the
positional index, and the predicates after it judge that one node.

Fixes tox-dev#2444
@gaborbernat gaborbernat added the bug Something isn't working label Nov 17, 2026
@gaborbernat
gaborbernat enabled auto-merge (squash) November 17, 2026 14:49
@codspeed

codspeed Bot commented Nov 17, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 581 untouched benchmarks
⏩ 90 skipped benchmarks1


Comparing gaborbernat:fix/positional-predicate-2444 (c438f75) with main (4f37baf)

Open in CodSpeed

Footnotes

  1. 90 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@gaborbernat
gaborbernat merged commit c90c665 into tox-dev:main Nov 17, 2026
66 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

XPath positional predicate before another predicate takes quadratic steps

1 participant