Skip to content

Prevent __class__ reassignment across incompatible layouts#6521

Merged
youknowone merged 6 commits intomainfrom
copilot/fix-class-attribute-panic
Dec 26, 2025
Merged

Prevent __class__ reassignment across incompatible layouts#6521
youknowone merged 6 commits intomainfrom
copilot/fix-class-attribute-panic

Conversation

Copy link
Contributor

Copilot AI commented Dec 25, 2025

  • Guard class setter to reject incompatible layouts while still permitting module-style class swaps (e.g., lazy modules and request modules) when their layouts match, avoiding panics and keeping import/ensurepip flows working.
  • Move the regression coverage for layout-mismatch errors into extra_tests/snippets/builtin_type.py and remove the Rust-side unit test per review feedback.
  • Ran targeted rustpython-vm test to verify the build after the guard adjustment.
Original prompt

This section details on the original issue you should resolve

<issue_title>Panic when setting class with different layout</issue_title>
<issue_description>## Summary
Setting object's class attribute to a type with different layout cause panic

thread 'main' panicked at 'index out of bounds: the len is 0 but the index is 0', vm/src/object/core.rs:813:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

which is an error in cpython

TypeError: __class__ assignment: 'TypeB' object layout differs from 'TypeA'

Detailed Explanation

class TypeA:
    def __init__(self) -> None:
        self.a = 1

class TypeB:
    __slots__ = "b"
    def __init__(self) -> None:
        self.b = 2

obj = TypeA()
assert obj.a == 1

obj.__class__ = TypeB
print(obj.b)
```</issue_description>

<agent_instructions>payload type_id() must be cheked</agent_instructions>

## Comments on the Issue (you are @copilot in this section)

<comments>
<comment_new><author>@youknowone</author><body>
maybe similar thing cause both this one and  RustPython/RustPython#1979</body></comment_new>
</comments>


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced validation for dynamic class reassignment to enforce object layout compatibility.
    • Now raises TypeError when attempting to reassign an instance to a class with incompatible layout, slot differences, or dict-slot presence mismatches.
  • Tests

    • Added test coverage for class layout compatibility constraints and dynamic class reassignment scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

Loading
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.

Panic when setting __class__ with different layout

2 participants