Skip to content

Fix compatibility of Tuple's hash function #3460

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

Merged
merged 1 commit into from
Jun 27, 2025

Conversation

TeamTamoad
Copy link
Contributor

@TeamTamoad TeamTamoad commented Nov 27, 2021

Change hash function implementation of Tuple to compatible with CPython's implementation.

Summary by CodeRabbit

  • Bug Fixes
    • Updated tuple hashing to use a new algorithm that produces platform-specific hash values, improving consistency with expected hash outputs.
    • Adjusted tests so that tuple hash tests are now required to pass, reflecting the improved hashing implementation.

Copy link
Member

@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

The change looks great, but by looking at the CI result, range() hash must follow the reuslt of tuple. Could you also update range.__hash__ in the same way?

You can extract hash function like fn tuple_hash(elements: &[PyObjectRef], vm: &VirtualMachine) and call it form PyTuple::hash like tuple_hash(zelf.as_slice())

@youknowone
Copy link
Member

The new bug is bug of exec. Somehow when __hash__ is added by exec, it doesn't run update_slot.
As the result, the upper test passes but the lower test fails

import dataclasses

@dataclasses.dataclass(unsafe_hash=True)
class X:
    pass


a = X().__hash__()
b = ().__hash__()
assert a == b, '{} {}'.format(a, b)

a = hash(X())
b = hash(())
assert a == b, '{} {}'.format(a, b)

@youknowone
Copy link
Member

@coolreader18 do you have any idea?

Copy link

coderabbitai bot commented Jun 27, 2025

Walkthrough

The updates remove the @unittest.expectedFailure decorator from a tuple hash test in the Python test suite and replace the tuple hash function in the Rust backend with a new, custom implementation. The new hash function uses platform-dependent constants and a custom mixing algorithm for tuple elements.

Changes

File(s) Change Summary
Lib/test/test_tuple.py Removed @unittest.expectedFailure decorator and comment from test_hash_exact in TupleTest.
vm/src/builtins/tuple.rs Replaced tuple hash function with a custom implementation using platform-dependent constants.
vm/src/builtins/tuple.rs (import) Expanded import to include PyUHash from the hash module.

Poem

In tupleland, a hash anew,
With primes and spins, the numbers grew.
No longer failing, tests now pass,
As rabbits code with gentle sass.
From Python's lair to Rusty den,
We hash our tuples once again!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a81533 and 8b0f88e.

📒 Files selected for processing (2)
  • Lib/test/test_tuple.py (0 hunks)
  • vm/src/builtins/tuple.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_tuple.py
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When a test fails due to unsupported Python syntax or features, keep the test as '@unittest.expectedFailure' and document the reason, rather than modifying the test logic or data.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: To find unimplemented methods and contribution opportunities, run './whats_left.py' in the RustPython repository.
vm/src/builtins/tuple.rs (3)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Use the macro system (such as 'pyclass', 'pymodule', 'pyfunction') when implementing Python functionality in Rust for RustPython.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Follow Rust best practices for error handling and memory management in all RustPython Rust code.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
🔇 Additional comments (2)
vm/src/builtins/tuple.rs (2)

2-5: LGTM: Import change supports new hash implementation

The addition of PyUHash import is necessary for the new tuple hash function implementation.


594-629: Verify hash algorithm constants and implementation against CPython

The new tuple hash implementation uses platform-specific constants and a custom combining algorithm that should match CPython's behavior exactly. However, the PR comments indicate there may still be compatibility issues with dataclasses and exec-related scenarios.

Please verify that:

  1. The constants (PRIME1, PRIME2, PRIME5, ROTATE) match CPython's tuple hash implementation exactly
  2. The algorithm steps are identical to CPython's implementation
  3. The magic constant 3527539 in the final addition is correct
#!/bin/bash
# Description: Search for CPython's tuple hash implementation for comparison
# Expected: Find references to similar constants and algorithm structure

# Search for tuple hash implementation patterns
rg -A 10 -B 5 "tuple.*hash|hash.*tuple" --type rust

# Look for any existing hash-related tests that might be affected
rg -A 5 -B 5 "test.*hash.*tuple|tuple.*test.*hash" --type rust

The exec-related issue mentioned in the PR comments suggests this implementation may not fully resolve the compatibility problem. Consider addressing the dataclass hash inconsistency described in the PR discussion.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Member

@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

Great, I have no idea which certain point made the changes, but it now works!

@youknowone youknowone merged commit 2ea77b4 into RustPython:main Jun 27, 2025
11 of 12 checks passed
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.

2 participants