Implement descriptors with suspension and dump support #1110
<!-- branch-diff -->
Branch diff: descriptor-protocol
| Commit | Message | Production | Test | Docs | Other |
| --- | --- | --: | --: | --: | --: |
| df2672def | Implement descriptors with su… | +1264 -181 | +702 -11 | +25 -17 | +0 -0 |
| 1bd27e525 | Fix descriptor review finding… | +42 -29 | +164 -0 | +12 -12 | +0 -0 |
| bd3000155 | Restore fast paths for ordina… | +309 -60 | +115 -0 | +0 -0 | +0 -0 |
| a79f4d059 | Optimize attribute lookup and… | +257 -48 | +167 -0 | +0 -0 | +0 -0 |
| 35d1fa164 | Clarify descriptor lookup nam… | +110 -96 | +0 -0 | +0 -0 | +0 -0 |
| 50bce6ed8 | Address descriptor lookup rev… | +37 -39 | +0 -0 | +6 -6 | +0 -0 |
| | TOTAL | +1739 -173 | +1148 -11 | +33 -25 | +0 -0 |
<!-- cubic:v=b0fab775-9177-4aa5-b349-0558f9ea4cac -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":9} -->
P1: Dataclass construction rejects a data-descriptor setter as soon as it suspends. Run the initializer's descriptor setter through a resumable continuation, or document and consistently enforce this unsupported case.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/modules/dataclasses/mod.rs, line 843:
<comment>Dataclass construction rejects a data-descriptor setter as soon as it suspends. Run the initializer's descriptor setter through a resumable continuation, or document and consistently enforce this unsupported case.</comment>
<file context>
@@ -817,14 +825,27 @@ fn run_post_init<'h>(instance_id: HeapId, class: &HeapRead<'h, Class>, vm: &mut
+ vm.heap.inc_ref(instance_id);
+ let object = Value::Ref(instance_id);
+ defer_drop!(object, vm);
+ let result = descriptor::mutate(member, object, Some(value), vm)?.require_synchronous(vm)?;
+ result.drop_with(vm);
+ continue;
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:v=cf0bbb23-dbd5-4b41-9474-e989d2195758 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P2: This supported-feature entry leaves docs/limitations/language.md saying that decorators do not work on methods. Update that stale limitation in the same PR so users are not given contradictory subset documentation.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/index.md, line 34:
<comment>This supported-feature entry leaves `docs/limitations/language.md` saying that decorators do not work on methods. Update that stale limitation in the same PR so users are not given contradictory subset documentation.</comment>
<file context>
@@ -31,6 +31,7 @@ They exist for development and for agents debugging code that runs on Monty; mos
- List, dict and set comprehensions
- `try` / `except` / `else` / `finally`, `raise ... from ...`
- `for`, `while`, `if` / `elif` / `else`, `break`, `continue`, `pass`, `assert`, `global`, `nonlocal`, `return`
+- Descriptors, `property`, `classmethod`, `staticmethod`, and decorators on methods
- `with` statements, for files and for classes implementing `__enter__` / `__exit__`
- `match` statements with every PEP 634 pattern kind and guards, see [match.md](match.md)
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:v=0bb2e4e1-f607-4b79-baa3-1d182669c642 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":7} -->
P2: Check the synthesized __name__ case before descriptor dispatch. Otherwise a class-dict descriptor named __name__ sends calls through descriptor::call_attr, whose argument packing can reject duplicate keywords before the metaclass-like synthesized string is handled.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/class.rs, line 191:
<comment>Check the synthesized `__name__` case before descriptor dispatch. Otherwise a class-dict descriptor named `__name__` sends calls through `descriptor::call_attr`, whose argument packing can reject duplicate keywords before the metaclass-like synthesized string is handled.</comment>
<file context>
@@ -184,6 +188,16 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Class> {
}
fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult<CallResult> {
+ let member = super::instance::class_member(self.id(), attr.as_str(vm.interns), vm);
+ defer_drop!(member, vm);
+ if member
</file context>
</details>
let member = (attr.as_str(vm.interns) != "__name__")
.then(|| super::instance::class_member(self.id(), attr.as_str(vm.interns), vm))
.flatten();
✅ Addressed in bd30001
<!-- cubic:v=77b00d6c-032a-4ea6-a482-2ae0f99d82bb -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P2: This change removes delattr, property, classmethod, and staticmethod from the unimplemented list without adding them to an implemented list, contradicting this page’s promise that every unlisted builtin raises NameError. Add delattr to the implemented builtin functions and the three descriptor constructors to the implemented type constructors (or another explicit implemented section).
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/builtins.md, line 30:
<comment>This change removes `delattr`, `property`, `classmethod`, and `staticmethod` from the unimplemented list without adding them to an implemented list, contradicting this page’s promise that every unlisted builtin raises `NameError`. Add `delattr` to the implemented builtin functions and the three descriptor constructors to the implemented type constructors (or another explicit implemented section).</comment>
<file context>
@@ -25,10 +25,9 @@ These raise `NameError`:
+- **Inheritance**: `super`.
- **Construction / coercion**: `bytearray`, `memoryview`, `object`, `ascii`.
-- **Other**: `callable`, `delattr`, `issubclass`, `aiter`, `anext`.
+- **Other**: `callable`, `issubclass`, `aiter`, `anext`.
`super()` is the biggest practical omission: with no class inheritance either
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:v=606feca7-7d6a-4eb8-8488-566dfc9a5a0d -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":9} -->
P2: Deleting a missing attribute from a user-defined class reports the wrong class name because this passes the literal "type" to attribute_error_type. Pass the class object's actual name, as Class::py_getattr does, so delattr(C, 'missing') identifies C.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/builtins/delattr.rs, line 59:
<comment>Deleting a missing attribute from a user-defined class reports the wrong class name because this passes the literal `"type"` to `attribute_error_type`. Pass the class object's actual name, as `Class::py_getattr` does, so `delattr(C, 'missing')` identifies `C`.</comment>
<file context>
@@ -0,0 +1,67 @@
+ false
+ };
+ if class {
+ Err(ExcType::attribute_error_type("type", attr.as_str(vm.interns)))
+ } else {
+ Err(ExcType::attribute_error(
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:review-summary:start -->
All reported issues were addressed across 39 files
<!-- cubic:review-summary:end -->
<sub>Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_a2b85eb0e22f7dbe946cecc80166e1c2d19062218a261935293c0bd4d4311758:df2672def42b1dbc8a77fe767bc233da03695705:e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- cubic:v=6e9584ab-e856-4e10-8066-66457b8bb2c4 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":9} -->
P2: Do not treat an AttributeError raised by a descriptor getter as lookup absence. Distinguish a missing class/instance member before invoking its getter, or propagate getter exceptions and return None only for a genuinely absent attribute.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/instance.rs, line 690:
<comment>Do not treat an `AttributeError` raised by a descriptor getter as lookup absence. Distinguish a missing class/instance member before invoking its getter, or propagate getter exceptions and return `None` only for a genuinely absent attribute.</comment>
<file context>
@@ -631,64 +652,43 @@ impl HeapItem for BoundMethod {
+ let attr = EitherStr::Heap(attr.to_owned());
+ match instance_getattr(self_id, &attr, vm) {
+ Ok(result) => result.require_synchronous(vm).map(Some),
+ Err(RunError::Exc(exc)) if exc.exc.exc_type() == ExcType::AttributeError => Ok(None),
+ Err(error) => Err(error),
}
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:v=fdae301a-fbb1-4058-b2d5-c810d27be9a8 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":9} -->
P2: classmethod and staticmethod wrappers raise AttributeError for __doc__ instead of exposing the wrapped function's documentation. Preserve and return the wrapped function's __doc__ for these descriptor kinds.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/builtin_descriptor.rs, line 340:
<comment>`classmethod` and `staticmethod` wrappers raise `AttributeError` for `__doc__` instead of exposing the wrapped function's documentation. Preserve and return the wrapped function's `__doc__` for these descriptor kinds.</comment>
<file context>
@@ -0,0 +1,401 @@
+ self.id(),
+ vm,
+ )
+ } else if matches!(name, "__func__" | "__wrapped__") {
+ descriptor.values[0].clone_with_heap(vm)
+ } else {
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/fdae301a-fbb1-4058-b2d5-c810d27be9a8" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=abca51ff-0ee8-4e95-ba6d-b4900423329f -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P2: An omitted property docstring is incorrectly stored as None; derive __doc__ from fget.__doc__ when the explicit doc argument is absent.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/builtin_descriptor.rs, line 77:
<comment>An omitted `property` docstring is incorrectly stored as `None`; derive `__doc__` from `fget.__doc__` when the explicit `doc` argument is absent.</comment>
<file context>
@@ -0,0 +1,401 @@
+ fget.unwrap_or(Value::None),
+ fset.unwrap_or(Value::None),
+ fdel.unwrap_or(Value::None),
+ doc.unwrap_or(Value::None),
+ ],
+ },
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/abca51ff-0ee8-4e95-ba6d-b4900423329f" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=541a6834-9b34-41a2-a36d-29352f4c50d6 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P2: classmethod.__get__(None) and staticmethod.__get__(None) incorrectly succeed because the invalid (None, None) receiver check is limited to properties. Reject that receiver pair before dispatching all builtin descriptor kinds.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/builtin_descriptor.rs, line 128:
<comment>`classmethod.__get__(None)` and `staticmethod.__get__(None)` incorrectly succeed because the invalid `(None, None)` receiver check is limited to properties. Reject that receiver pair before dispatching all builtin descriptor kinds.</comment>
<file context>
@@ -0,0 +1,401 @@
+ let HeapData::BuiltinDescriptor(descriptor) = vm.heap.get(id) else {
+ unreachable!()
+ };
+ match descriptor.kind {
+ Type::StaticMethod => Ok(CallResult::Value(descriptor.values[0].clone_with_heap(vm))),
+ Type::ClassMethod => {
</file context>
</details>
if matches!(instance, Value::None) && owner.is_none_or(|v| matches!(v, Value::None)) {
return Err(ExcType::type_error("__get__(None, None) is invalid"));
}
match descriptor.kind {
✅ Addressed in 1bd27e5
<!-- cubic:v=bd18b0dc-120e-4a2a-a84a-dd8c31402c0c -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":8} -->
P2: Custom descriptor hooks do not honor descriptor binding for __get__ itself. Route the hook through the same suspendable binding path used by __set__, otherwise staticmethod/classmethod __get__ implementations receive incorrect arguments or fail.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/descriptor.rs, line 132:
<comment>Custom descriptor hooks do not honor descriptor binding for `__get__` itself. Route the hook through the same suspendable binding path used by `__set__`, otherwise staticmethod/classmethod `__get__` implementations receive incorrect arguments or fail.</comment>
<file context>
@@ -0,0 +1,356 @@
+ args: vec![value.clone_with_heap(vm.heap), receiver, Value::Ref(owner)],
+ kwargs: KwargsValues::Empty,
+ };
+ return vm.call_function(getter, args);
+ }
+ Ok(CallResult::Value(match instance {
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/bd18b0dc-120e-4a2a-a84a-dd8c31402c0c" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=5dac36e4-3f97-4277-92bb-32162e563e64 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P3: Keep the new StaticStrings variants alphabetized as documented; Fset currently precedes Fdel. Reorder them to Fdel, Fget, Fset to preserve the enum’s maintenance invariant.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/intern.rs, line 927:
<comment>Keep the new `StaticStrings` variants alphabetized as documented; `Fset` currently precedes `Fdel`. Reorder them to `Fdel`, `Fget`, `Fset` to preserve the enum’s maintenance invariant.</comment>
<file context>
@@ -923,6 +923,9 @@ pub enum StaticStrings {
/// `field(doc=...)`, CPython's per-field docstring.
Doc,
+ Fget,
+ Fset,
+ Fdel,
/// `sys.dont_write_bytecode` attribute.
</file context>
</details>
✅ Addressed in 1bd27e5
<!-- cubic:v=98bbd5f1-7b56-4e7f-904f-a305c70f498d -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P3: The synthesized initializer does not invoke arbitrary descriptors and cannot suspend through a data-descriptor setter. Describe this as synchronous data-descriptor dispatch; otherwise the limitation overstates descriptor support and omits a user-visible suspension divergence.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/dataclasses.md, line 102:
<comment>The synthesized initializer does not invoke arbitrary descriptors and cannot suspend through a data-descriptor setter. Describe this as synchronous data-descriptor dispatch; otherwise the limitation overstates descriptor support and omits a user-visible suspension divergence.</comment>
<file context>
@@ -97,7 +99,7 @@ field after a defaulted one
text differs; the value and its equality match CPython.
- **A class-body `__setattr__` never runs for the synthesized `__init__`**,
- which writes fields straight into the instance `__dict__`. This is the
+ which honors descriptors but otherwise writes to the instance `__dict__`. This is the
never-dispatched attribute hook described in [classes.md](classes.md) rather than
something dataclass-specific, so `@dataclass` does not reject it.
</file context>
</details>
which synchronously dispatches data descriptors but otherwise writes to the instance `__dict__`. This is the
✅ Addressed in 1bd27e5
<!-- cubic:v=8a989883-d9a9-4203-bdc8-40ee35fc0ff8 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P3: This bullet now documents a supported del obj.attr form inside a section whose introduction says every listed statement is rejected at compile time. Qualify the bullet as unsupported forms, or move the supported form out of this section.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/limitations/language.md, line 21:
<comment>This bullet now documents a supported `del obj.attr` form inside a section whose introduction says every listed statement is rejected at compile time. Qualify the bullet as unsupported forms, or move the supported form out of this section.</comment>
<file context>
@@ -13,17 +13,12 @@ any code runs.
`list` rather than a lazy iterator, a known temporary divergence; see
`iter__generator_expr_type.py`.
-- **`del` statements** — neither `del x` nor `del d[k]` parse.
+- **`del` statements** — `del x`, `del d[k]`, and multiple targets are unsupported; `del obj.attr` is supported.
- **`try*` / `except*` exception groups** — PEP 654 syntax rejected.
- **`type` aliases** (PEP 695 `type Foo = int`).
</file context>
</details>
- **Unsupported `del` forms** — `del x`, `del d[k]`, and multiple targets are rejected at parse time; `del obj.attr` is supported.
✅ Addressed in 1bd27e5
<!-- cubic:v=0fc68930-dd5b-496a-8ef6-e48c1427ecc2 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P3: delattr(obj, 1) drops the offending type from its TypeError, unlike the other attribute builtins and Python's error contract. Include name.py_type_name(vm) in this message.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/builtins/delattr.rs, line 21:
<comment>`delattr(obj, 1)` drops the offending type from its TypeError, unlike the other attribute builtins and Python's error contract. Include `name.py_type_name(vm)` in this message.</comment>
<file context>
@@ -0,0 +1,67 @@
+ return Err(ExcType::type_error_arg_count("delattr", 2, args.len()));
+ };
+ let Some(attr) = name.as_either_str(vm.heap).map(|s| s.resolve_interned(vm.interns)) else {
+ return Err(ExcType::type_error("attribute name must be string"));
+ };
+ if let Some(class) = descriptor::descriptor_class(object, vm)
</file context>
</details>
return Err(ExcType::type_error(format!("attribute name must be string, not '{}'", name.py_type_name(vm))));
✅ Addressed in 1bd27e5
<!-- cubic:v=ff94b4ef-43bd-4513-bd25-efd06e305a03 -->
<!-- cubic:review-run=e8aed5c7-e941-5df3-9bbb-f25c372b00c7 -->
<!-- metadata:{"confidence":10} -->
P3: Update the parser documentation: class methods now accept and apply decorators, but parse_function_def and parse_class_def still say method decorators are rejected. Stale scope documentation can cause later changes to preserve the old behavior accidentally.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/parse.rs, line 1140:
<comment>Update the parser documentation: class methods now accept and apply decorators, but `parse_function_def` and `parse_class_def` still say method decorators are rejected. Stale scope documentation can cause later changes to preserve the old behavior accidentally.</comment>
<file context>
@@ -1113,26 +1132,15 @@ impl<'a, 'i> Parser<'a, 'i> {
self.reject_class_body_walrus(default)?;
}
}
+ for decorator in &function.decorator_list {
+ self.reject_class_body_walrus(&decorator.expression)?;
+ }
</file context>
</details>
✅ Addressed in 1bd27e5
Medium: Property getter chains bypass recursion limits
An untrusted script can build the chain below and trigger a native stack overflow, aborting the worker—or the host process when embedding the Rust interpreter—despite configured recursion limits. Each getter re-enters protocol_get through call_function, BoundMethod::py_call, and protocol_call without pushing a VM frame or reserving native re-entry. Guard this dispatch with enter_run_reentry/RunReentryGuard, or use a continuation.
p = property(len)
for _ in range(10000):
p = property(p.__get__)
p.__get__([])
PR overview
All previously flagged issues have been addressed. No open security concerns remain on this pull request.
Security review
No open security issues remain on this pull request.
Fixed/addressed: 1 · PR risk: 0/10
Codecov Report
:x: Patch coverage is
84.14097% with 180 lines in your changes missing coverage. Please review.| Files with missing lines | Patch % | Lines |
|---|---|---|
| crates/monty/src/types/builtin\_descriptor.rs | 76.92% | 47 Missing and 13 partials :warning: |
| crates/monty/src/types/instance.rs | 78.68% | 50 Missing and 2 partials :warning: |
| crates/monty/src/types/descriptor.rs | 91.60% | 14 Missing and 8 partials :warning: |
| crates/monty/src/builtins/delattr.rs | 76.08% | 7 Missing and 4 partials :warning: |
| crates/monty/src/bytecode/vm/mod.rs | 74.07% | 6 Missing and 1 partial :warning: |
| crates/monty/src/bytecode/vm/pattern.rs | 92.77% | 4 Missing and 2 partials :warning: |
| crates/monty/src/heap\_data.rs | 16.66% | 4 Missing and 1 partial :warning: |
| crates/monty/src/modules/dataclasses/mod.rs | 82.14% | 1 Missing and 4 partials :warning: |
| crates/monty/src/parse.rs | 86.36% | 1 Missing and 2 partials :warning: |
| crates/monty/src/bytecode/vm/call.rs | 75.00% | 1 Missing and 1 partial :warning: |
| ... and 4 more | |
:loudspeaker: Thoughts on this report? Let us know!
_Auto response from AI running Codex fix-pr-comments:_
I checked this against CPython 3.14: with a property stored under __name__, Named.__name__(x=1, **{'x': 2}) raises the duplicate-keyword TypeError before testing whether the synthesized string is callable. Monty does the same (its callable label differs). Moving the special case ahead of argument handling would change this to a not-callable error, so I am retaining the current order.
_Auto response from AI running Codex fix-pr-comments:_
CPython 3.14 also invokes the type's raw __get__ hook: a staticmethod hook receives (descriptor, instance, owner), while a classmethod hook raises TypeError: 'classmethod' object is not callable. I verified both cases against Monty. Binding __get__ like __set__ would introduce a CPython divergence, so no change is needed here.
_Auto response from AI running Codex fix-pr-comments:_
Getter docstring inference is an intentional, already documented subset limitation in docs/limitations/classes.md under Descriptor limitations: pass doc= explicitly. Function objects themselves do not expose __doc__ in Monty (documented in language.md), and this PR does not add function metadata support. I am retaining that documented limitation in this PR.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Kept the synthesized dataclass initializer synchronous, consistent with its existing default-factory and post-init restrictions. The limitation now explicitly covers data-descriptor setters. Added regression coverage for native properties and custom descriptors that attempt external/OS calls, repeat the rejection, then successfully construct another instance and continue the REPL. Ordinary attribute assignment still supports suspension and dump/restore.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Removed the stale but not on methods wording from the language page's supported-functions list; it now includes decorators on functions and methods.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Added delattr to the implemented functions and property, classmethod, and staticmethod to the implemented type constructors.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Missing class-attribute deletion now uses the class object's actual name. Added a regression asserting type object 'Record' has no attribute 'missing'.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
The synchronous lookup now checks whether the member exists before invoking its descriptor. Exceptions raised by a present descriptor propagate, including immediate AttributeError from a property without a getter. Added repr and equality regressions for that case.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Wrapper metadata copying remains an intentional subset limitation, consistent with function objects not exposing __doc__. The descriptor limitations already said other function metadata is not copied; I made __doc__ explicit there to remove ambiguity. Full function metadata support is outside this PR.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Moved the (None, None) validation before dispatching by descriptor kind. Regression coverage checks both omitted and explicit None owners for all three constructors, plus valid class-only access.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Placed Fdel/Fget in alphabetical order after Fanout, and Fset after FrozenSet. Static-string entries persist as text, so this preserves existing dumps; the version 13 fixture still loads and resumes.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
The dataclass limitation now specifically describes synchronous data-descriptor setter dispatch and explicitly lists suspension as unsupported in the synthesized initializer. Added coverage for rejected external/OS calls and successful use after the rejection.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
Narrowed this bullet to unsupported del forms only: name deletion, subscription deletion, and multiple targets.
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
_Auto response from AI running Codex fix-pr-comments:_
Prepared locally; changes have not been pushed yet.
The error now includes the offending Python type, matching the other attribute builtins. Added a regression for delattr(Record(), 1).
Validation: 953 Rust tests and 704 fixtures passed, including version 13 dump compatibility; Rust and Python lint passed.
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will not alter performance
✅ 116 untouched benchmarks ⏩ 78 skipped benchmarks[^skipped]
---
<sub>Comparing <code>jaheba:descriptor-protocol</code> (50bce6e) with <code>main</code> (d45587e)</sub>
<a href="https://app.codspeed.io/pydantic/monty/branches/jaheba%3Adescriptor-protocol?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 78 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
jaheba
Implement Python descriptors for sandbox classes, including
property,classmethod, andstaticmethod. Attribute reads honor data descriptor precedence, and writes/deletes dispatch descriptor hooks. Class creation calls__set_name__in namespace order.Descriptor hooks run through ordinary VM frames so external calls and OS calls can suspend and resume. This also covers
getattr,hasattr, and class patterns with descriptor-backed__match_args__, including dump/restore during metadata lookup and subsequent attribute reads.New dumps use version 14; version 13 dumps remain supported, with a regression test loading and resuming the existing version 13 fixture. Legacy CallAttr opcodes remain unchanged. This branch starts from upstream main and is independent of #1089 and the method-call implementation.
Validation:
memory-model-checks.memory-model-checksandref-count-return.<!-- This is an auto-generated description by cubic. -->
---
Summary by cubic
Implements Python descriptors —
property,classmethod, andstaticmethod— for sandbox classes. Attribute reads honor data descriptor precedence, writes and deletes dispatch descriptor hooks, class creation calls__set_name__in namespace order, anddelnow works on attributes instead of raisingNotImplementedError. Descriptor-free classes keep their fast attribute paths, and class patterns without descriptor-backed__match_args__keep their fast path.getattr,hasattr, match patterns with descriptor-backed__match_args__, and the newdelattrbuiltin.<sup>Written for commit 50bce6ed84384155a3812c0bfcbf55ed8428855e. Summary will update on new commits.</sup>
<a href="https://cubic.dev/pr/pydantic/monty/pull/1110?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->