[BUG] get_top_k_scored_items returns all items when top_k is zero

Author: Afloat16Created Sep 29, 2026Updated Sep 29, 2026
Labelsbug

Problem and proposed change

The final selection uses a -k slice. For k=0, -0 equals 0, so the slice contains every item instead of an empty recommendation result. Return empty index/score arrays with shape (number_of_users, 0) and preserve their dtypes.

Reproduction

python
import numpy as np
from recommenders.utils.python_utils import get_top_k_scored_items
indices, scores = get_top_k_scored_items(np.array([[0.2, 0.7, 0.4]]), top_k=0)
print(indices.shape, scores.shape)
# Expected: (1, 0), (1, 0); actual: (1, 3), (1, 3)

Validation

Source: recommenders/utils/python_utils.py, Git blob 36fb3f8158ccafe68b4c3458d138c543e343a580; rechecked against current upstream. Focused before/after tests were rerun for this submission.

Complete standalone source module loaded with real dependencies; selected utility behaviors tested. Not the full project suite.

Before: 5 failed, 6 passed in 0.29s

After: 11 passed in 0.26s

Candidate patch

diff
--- a/recommenders/utils/python_utils.py
+++ b/recommenders/utils/python_utils.py
@@ -200,6 +200,8 @@
             "Number of items is less than top_k, limiting top_k to number of items"
         )
     k = min(top_k, scores.shape[1])
+    if k == 0:
+        return np.empty((scores.shape[0], 0), dtype=np.intp), np.empty((scores.shape[0], 0), dtype=scores.dtype)
 
     test_user_idx = np.arange(scores.shape[0])[:, None]
 

Platform: Linux, Python 3.12, NumPy/SciPy. Dense and CSR inputs, sorted/unsorted outputs, empty axes and positive-k controls were checked.

Willingness to contribute

  • Yes, I can contribute for this issue with guidance from Recommenders community.

Source: recommenders-team/recommenders