Skip to content

Add _heapq module#8059

Open
ShaharNaveh wants to merge 10 commits into
RustPython:mainfrom
ShaharNaveh:heapq-module
Open

Add _heapq module#8059
ShaharNaveh wants to merge 10 commits into
RustPython:mainfrom
ShaharNaveh:heapq-module

Conversation

@ShaharNaveh

@ShaharNaveh ShaharNaveh commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Summary

Summary by CodeRabbit

  • New Features

    • Added a heap queue module to the standard library providing priority-queue operations (push, pop, replace, push-pop, heapify) for both min-heap and max-heap variants. Exposed as a standard-library module for direct use; heapify uses an optimized path for very large lists.
  • Bug Fixes

    • Improved robustness: operations now detect and raise clear errors when lists change during operations or when invalid indices are encountered.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 011ad60b-a21b-4db0-8087-3873c3516741

📥 Commits

Reviewing files that changed from the base of the PR and between d5fb59a and 7ed324d.

📒 Files selected for processing (1)
  • crates/stdlib/src/_heapq.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/stdlib/src/_heapq.rs

📝 Walkthrough

Walkthrough

Adds a Rust-backed _heapq stdlib module implementing min-heap and max-heap operations (sift-up/sift-down, push/pop/replace/pushpop/heapify), a cache-friendly heapify path for large lists, and registers the module in stdlib definitions.

Changes

Heap Module Implementation

Layer / File(s) Summary
Module Foundation and Setup
crates/stdlib/src/_heapq.rs, crates/stdlib/src/lib.rs
Module entrypoint, VM/list/comparison imports, and stdlib registration (mod _heapq; and _heapq::module_def(ctx)).
Min-heap primitives and operations
crates/stdlib/src/_heapq.rs
Implements siftdown/siftup, generic push internals, and exports heappush, heappop, heapreplace, heappushpop, heapify with large-list cache-friendly heapify path.
Max-heap primitives and operations
crates/stdlib/src/_heapq.rs
Implements siftdown_max/siftup_max and exports heappush_max, heappop_max, heapreplace_max, heappushpop_max, heapify_max.
Module Registration
crates/stdlib/src/lib.rs
Adds _heapq::module_def(ctx) to stdlib module definitions for multi-phase init.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant heappush
  participant siftup
  participant PyList
  Caller->>heappush: heappush(heap, item)
  heappush->>PyList: append item
  heappush->>siftup: restore heap invariant
  siftup->>PyList: compare & swap using rich_compare_bool
  siftup->>heappush: finished
  heappush->>Caller: return
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • youknowone

Poem

A rabbit hops in, code in paw,
Sifts the heap without a flaw,
Min and max in tidy rows,
Rust-made tunnels where data flows—
Hop, compile, and watch it soar! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add _heapq module' directly and clearly describes the main change in the pull request, which is the addition of a new Rust-backed Python extension module for heap queue operations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ShaharNaveh ShaharNaveh marked this pull request as ready for review June 8, 2026 15:01

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/stdlib/src/_heapq.rs`:
- Around line 211-250: In heappushpop, capture the list size before calling
top.rich_compare_bool (e.g., let n = lst.borrow_vec().len()), then after the
rich_compare_bool call re-check the size (lst.borrow_vec().len()) and if it
differs return Err(vm.new_runtime_error("list changed size during comparison"))
to mirror CPython's check; place this check between the rich_compare_bool call
and the subsequent logic that assumes the list size (before proceeding to
swap/borrow_vec_mut() and siftup), referencing the heappushpop function, the
rich_compare_bool invocation, and the use of
lst.borrow_vec()/lst.borrow_vec_mut().
- Around line 477-516: In heappushpop_max, after calling
item.rich_compare_bool(&top, PyComparisonOp::Lt, vm) re-check the heap size
because the comparison may execute Python code that mutates the list;
specifically, after the cmp is computed, re-borrow the list/vector and if it is
now empty return item (mirroring the min-heap heappushpop fix), otherwise
refresh the current top element or ensure correct behavior before proceeding to
replace vec[0], then continue with the existing replacement and siftup_max call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c19e0ae4-3550-4c74-8a04-700bb83e10d1

📥 Commits

Reviewing files that changed from the base of the PR and between 51c97b9 and 676729d.

📒 Files selected for processing (2)
  • crates/stdlib/src/_heapq.rs
  • crates/stdlib/src/lib.rs

Comment on lines +211 to +250
#[pyfunction]
fn heappushpop(
heap: PyObjectRef,
item: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let lst = heap.downcast::<PyList>().map_err(|obj| {
vm.new_type_error(format!(
"heappushpop() argument 1 must be list, not {}",
obj.class().name()
))
})?;

let top = {
let vec = lst.borrow_vec();
match vec.first() {
Some(v) => v.clone(),
None => return Ok(item),
}
};

let cmp = top.rich_compare_bool(&item, PyComparisonOp::Lt, vm)?;
if !cmp {
return Ok(item);
}

let returnitem = {
let mut vec = lst.borrow_vec_mut();
let root = match vec.first() {
Some(v) => v.clone(),
None => return Err(vm.new_index_error("index out of range")),
};

vec[0] = item;
root
};

siftup(&lst, 0, vm)?;
Ok(returnitem)
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing size change check after comparison.

The rich_compare_bool call (line 232) invokes user code that could modify the list. CPython's heappushpop checks for size change after comparison before proceeding:

if (n != PyList_GET_SIZE(heap)) {
    PyErr_SetString(PyExc_RuntimeError, "list changed size during iteration");
    return NULL;
}

Without this check, if the list is modified during comparison, subsequent operations may behave unexpectedly.

🔧 Proposed fix
+    let size = lst.__len__();
     let cmp = top.rich_compare_bool(&item, PyComparisonOp::Lt, vm)?;
+    if size != lst.__len__() {
+        return Err(vm.new_runtime_error("list changed size during iteration"));
+    }
     if !cmp {
         return Ok(item);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/stdlib/src/_heapq.rs` around lines 211 - 250, In heappushpop, capture
the list size before calling top.rich_compare_bool (e.g., let n =
lst.borrow_vec().len()), then after the rich_compare_bool call re-check the size
(lst.borrow_vec().len()) and if it differs return Err(vm.new_runtime_error("list
changed size during comparison")) to mirror CPython's check; place this check
between the rich_compare_bool call and the subsequent logic that assumes the
list size (before proceeding to swap/borrow_vec_mut() and siftup), referencing
the heappushpop function, the rich_compare_bool invocation, and the use of
lst.borrow_vec()/lst.borrow_vec_mut().

Comment on lines +477 to +516
#[pyfunction]
fn heappushpop_max(
heap: PyObjectRef,
item: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let lst = heap.downcast::<PyList>().map_err(|obj| {
vm.new_type_error(format!(
"heappushpop_max() argument 1 must be list, not {}",
obj.class().name()
))
})?;

let top = {
let vec = lst.borrow_vec();
match vec.first() {
Some(v) => v.clone(),
None => return Ok(item),
}
};

let cmp = item.rich_compare_bool(&top, PyComparisonOp::Lt, vm)?;
if !cmp {
return Ok(item);
}

let returnitem = {
let mut vec = lst.borrow_vec_mut();
let root = match vec.first() {
Some(v) => v.clone(),
None => return Err(vm.new_index_error("index out of range")),
};

vec[0] = item;
root
};

siftup_max(&lst, 0, vm)?;
Ok(returnitem)
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing size change check after comparison (same issue as min-heap variant).

Consistent with the min-heap heappushpop, the max-heap variant also lacks a size-change check after rich_compare_bool (line 498).

🔧 Proposed fix
+    let size = lst.__len__();
     let cmp = item.rich_compare_bool(&top, PyComparisonOp::Lt, vm)?;
+    if size != lst.__len__() {
+        return Err(vm.new_runtime_error("list changed size during iteration"));
+    }
     if !cmp {
         return Ok(item);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/stdlib/src/_heapq.rs` around lines 477 - 516, In heappushpop_max,
after calling item.rich_compare_bool(&top, PyComparisonOp::Lt, vm) re-check the
heap size because the comparison may execute Python code that mutates the list;
specifically, after the cmp is computed, re-borrow the list/vector and if it is
now empty return item (mirroring the min-heap heappushpop fix), otherwise
refresh the current top element or ensure correct behavior before proceeding to
replace vec[0], then continue with the existing replacement and siftup_max call.

@ShaharNaveh ShaharNaveh changed the title Basic _heapq module Add _heapq module Jun 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant