Skip to content

GH-55758: [Python] Buggy top_k_unstable/bottom_k_unstable - #55759

Open
AlenkaF wants to merge 2 commits into
apache:mainfrom
AlenkaF:buggy-top_k_unstable-bottom_k_unstable
Open

AlenkaF wants to merge 2 commits into
apache:mainfrom
AlenkaF:buggy-top_k_unstable-bottom_k_unstable

Conversation

@AlenkaF

@AlenkaF AlenkaF commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Rationale for this change

top_k_unstable/bottom_k_unstable functions behavior is buggy.

What changes are included in this PR?

New _select_k_sort_keys helper is defined to update the current handling of options in top_k_unstable/bottom_k_unstable functions.

Are these changes tested?

Yes.

Are there any user-facing changes?

No.

Was AI used for this PR?

Yes, I used Claude to write up changes I wanted and to add a test. I have revised the suggestion and run the checks.

PR code and description written by:

  • Human
  • AI

Reviewed before submission by:

  • Human
  • AI
  • Not reviewed

@AlenkaF
AlenkaF requested review from raulcd and rok as code owners November 24, 2026 13:03
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:03

Copilot AI 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.

🟢 Approval recommended

No active review issues remain for the changes centralizing PyArrow’s top- and bottom-k option handling.

No open issues 🎉

What changed in this PR

This PR addresses GH-55758 by centralizing option handling for PyArrow’s top_k_unstable and bottom_k_unstable functions.

Changes:

  • Adds a shared helper that defaults table sort keys’ null placement to "at_end".
  • Validates option types and matching lengths, and rejects sort keys for Arrow array inputs without mutating caller-provided lists.
  • Updates parameter documentation and adds regression tests for defaults and validation errors.
File Description
python/​pyarrow/​tests/​test_compute.py Adds regression tests for default null placement, invalid options, and list preservation.
python/​pyarrow/​compute.py Introduces shared option handling, updates both wrappers, and clarifies their documentation.

Review effort: Balanced

@AlenkaF
AlenkaF requested a review from tadeja November 30, 2026 05:14
Comment thread python/pyarrow/compute.py Resolved
Comment thread python/pyarrow/tests/test_compute.py Resolved
Comment thread python/pyarrow/tests/test_compute.py Resolved
Comment thread python/pyarrow/tests/test_compute.py Resolved

@tadeja tadeja left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some remaining suggestions for array-like inputs, bytes, sort_keys="a" on arrays.
I hope this looks clear enough :)

Comment thread python/pyarrow/compute.py
raise TypeError(
"sort_keys and null_placements must be list-like, not str")

if isinstance(values, (pa.Array, pa.ChunkedArray)):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Array-like inputs like lists silently accept sort_keys but checking for table-like inputs instead would fix this:

Suggested change
if isinstance(values, (pa.Array, pa.ChunkedArray)):
if not isinstance(values, (pa.Table, pa.RecordBatch)):

Without the fix such example incorrectly succeeds:

import pyarrow.compute as pc
pc.top_k_unstable([1, 2, None, 0], 2, sort_keys=["a"])

And this example fails but shouldn't:

pc.top_k_unstable([1, 2, None, 0], k=2)
# pyarrow.lib.ArrowInvalid: select_k_unstable requires a non-empty `sort_keys`

pc.select_k_unstable(table, k=k, sort_keys=[("unknown", "ascending", "at_end")])


def test_top_k_bottom_k_():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
def test_top_k_bottom_k_():
def test_top_k_bottom_k():

Typo?

Comment thread python/pyarrow/compute.py
Comment on lines +571 to +579
if isinstance(sort_keys, str) or isinstance(null_placements, str):
raise TypeError(
"sort_keys and null_placements must be list-like, not str")

if isinstance(values, (pa.Array, pa.ChunkedArray)):
if sort_keys is not None:
raise ValueError(
"sort_keys is only supported for table-like input")
if null_placements is None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One more edge case which produces TypeError instead of ValueError

import pyarrow as pa
import pyarrow.compute as pc
pc.top_k_unstable(pa.array([1, 2, None, 0]), k=2, sort_keys="a")

TypeError: sort_keys and null_placements must be list-like, not str

This can be fixed by reordering these checks like so:

diff --git a/python/pyarrow/compute.py b/python/pyarrow/compute.py
@@ -568,14 +568,18 @@ def fill_null(values, fill_value):
 
 
 def _select_k_sort_keys(values, sort_keys, null_placements, order):
-    if isinstance(sort_keys, str) or isinstance(null_placements, str):
+    is_array_like = not isinstance(values, (pa.Table, pa.RecordBatch))
+    if is_array_like and sort_keys is not None:
+        raise ValueError(
+            "sort_keys is only supported for table-like input")
+
+    if (isinstance(sort_keys, (str, bytes)) or
+            isinstance(null_placements, (str, bytes))):
         raise TypeError(
-            "sort_keys and null_placements must be list-like, not str")
+            "sort_keys and null_placements must be list-like, "
+            "not str or bytes")
 
-    if isinstance(values, (pa.Array, pa.ChunkedArray)):
-        if sort_keys is not None:
-            raise ValueError(
-                "sort_keys is only supported for table-like input")
+    if is_array_like:
         if null_placements is None:
             return [("dummy", order, "at_end")]

... which results in correct ValueError: sort_keys is only supported for table-like input

Plus extra check on (str, bytes) prevents second edge case b"a" from becoming column indices ([97]).

Comment thread python/pyarrow/compute.py
@@ -584,9 +613,11 @@ def top_k_unstable(
The number of `k` elements to keep.
sort_keys : List-like

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

sort_keys here and in bottom_k_unstable could be indicated as optional and field references mentioned for clarity.

    sort_keys : List-like, optional
        Column names or field references to order by when input is table-like
        data. Required for table-like input. Not supported for array-like input.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Python] Buggy top_k_unstable/bottom_k_unstable

3 participants