-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[DRAFT] Use Rust's sort_by
instead of timsort::try_sort_by_gt
#6096
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
jackoconnordev
wants to merge
2
commits into
RustPython:main
Choose a base branch
from
jackoconnordev:faster-list-sort
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+11
−3
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@coderabbitai is rust's builtin sort_by a stable sorting algorithm if only Ordering::Less and Ordering::Greater are returned by
cmp
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
@jackoconnordev No, Rust's builtin
sort_by
is not a stable sorting algorithm, regardless of what the comparison function returns.Here are the key points:
Inherently Unstable: Rust's
sort_by
uses an unstable sorting algorithm (pattern-defeating quicksort/pdqsort) by design. If you need stability, you should usesort_by_stable
instead.Impact of Never Returning
Ordering::Equal
: When your comparison function only returnsOrdering::Less
andOrdering::Greater
, you're effectively telling the algorithm that no two elements are equal. This has several implications:Performance Considerations: By never returning
Ordering::Equal
, you're preventing the sorting algorithm from taking advantage of optimizations for equal elements, which could result in suboptimal performance.In the context of your code, if you need stable sorting for Python's
list.sort()
(which should be stable according to Python's specification), you should consider:sort_by_stable
instead ofsort_by
Ordering::Equal
when elements are truly equalThe current implementation may not match Python's expected stable sorting behavior.
🌐 Web query:
💡 Result:
Short answer: sort_by is stable, but stability only matters for elements that compare equal. If your comparator never returns Ordering::Equal for any two distinct elements, then there are no “ties” to preserve — stability has no observable effect. However, your comparator still must implement a total order (in particular compare(x, x) must return Equal) or sorting may panic / produce unspecified results. (doc.rust-lang.org, rust-lang.github.io)
Details and notes
Example patterns
If you want, paste the comparator you’re using and I’ll check whether it properly implements a total order and whether you need to worry about stability or correctness.
Citations:
🌐 Web query:
💡 Result:
Short answer
Details and practical notes
If you want
Citations:
@jackoconnordev I need to correct my previous response - I made an error about Rust's sorting algorithms.
Rust's
sort_by
IS stable. Here's the accurate information:sort_by
is stable: It uses a stable sorting algorithm (currently driftsort) and preserves the relative order of equal elements.sort_unstable_by
is unstable: This is the one that uses pdqsort and may reorder equal elements.Impact of never returning
Ordering::Equal
: When your comparison function only returnsLess
andGreater
for distinct elements, stability has no observable effect because there are no "equal" elements to preserve the order of.Critical correctness issue: However, your comparator must still implement a total order. Specifically,
compare(x, x)
must returnOrdering::Equal
, or the sort may panic or produce unspecified results.Looking at your code:
This comparator never returns
Ordering::Equal
, even when comparing an element to itself. This violates the total order requirement and could cause the sort to panic or behave incorrectly.Since Python's
list.sort()
should be stable, usingsort_by
is the right choice, but the comparison function should properly handle equal elements by returningOrdering::Equal
when appropriate.🧠 Learnings used
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you know what the True and False return values of
rich_compare_bool
correspond to semantically?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Length of output: 12093
@jackoconnordev Yes! Based on the codebase analysis,
rich_compare_bool
returns:true
if the comparison operation is true (e.g., if you calla.rich_compare_bool(b, PyComparisonOp::Gt, vm)
, it returnstrue
whena > b
)false
if the comparison operation is false (e.g.,false
whena <= b
)Looking at the current sorting code:
This logic has a critical flaw: when
rich_compare_bool
returnsfalse
, it doesn't distinguish between "less than" and "equal to". For example:reverse=false
,op=Gt
, anda.rich_compare_bool(b, Gt, vm)
returnsfalse
, it could mean eithera < b
ORa == b
Ordering::Less
For a correct total order, you need to handle equality properly. The fix should be something like:
This ensures the comparator implements a proper total order where
compare(x, x) == Ordering::Equal
.🧬 Code Graph Analysis Results
Snippet 1: do_sort function (uses rich_compare_bool to implement sorting comparator)
Content:
fn do_sort(
vm: &VirtualMachine,
values: &mut Vec,
key_func: Option,
reverse: bool,
) -> PyResult<()> {
let op = if reverse {
PyComparisonOp::Lt
} else {
PyComparisonOp::Gt
};
let cmp = |a: &PyObjectRef, b: &PyObjectRef| {
let res = a.rich_compare_bool(b, op, vm).unwrap();
if res {
Ordering::Greater
} else {
Ordering::Less
}
};
}
Snippet 2: PyList cmp implementation (uses rich comparison across elements)
Content:
impl Comparable for PyList {
fn cmp(
zelf: &Py,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult {
if let Some(res) = op.identical_optimization(zelf, other) {
return Ok(res.into());
}
let other = class_or_notimplemented!(Self, other);
let a = &*zelf.borrow_vec();
let b = &*other.borrow_vec();
a.iter()
.richcompare(b.iter(), op, vm)
.map(PyComparisonValue::Implemented)
}
}
🧠 Learnings used