← Back to Pull requests

Make class proxies hashable and compare them as the sandbox does #1310

Closed
unknown closed this pull request without merging on Nov 18, 2026 18:57 UTC
View on GitHub
unknown unknown commented on Nov 12, 2026 09:42 UTC
Author

Problem

MontyClassProxy (the host-side stand-in for a sandbox class instance) defined __eq__ without __hash__, so CPython made it unhashable.
A sandbox result that was a set or frozenset of class instances, or a dict keyed by them, failed to convert with TypeError: unhashable type.
MontyClassTypeProxy had the same gap.

The existing __eq__ (class name + is_dataclass + every attribute) also disagreed with the sandbox: two distinct instances of a plain class compare unequal in the sandbox (identity) but compared equal on the host.
Adding a hash on top of that __eq__ would have silently merged distinct sandbox objects in a returned set or dict.

Change

The worker now reports how each sandbox class compares and hashes, and the host proxy follows that rule where it can replay it without running sandbox code.

  • monty-types: ClassTypeNode gains eq: ClassEq (Identity / Fields / Custom) and hash: ClassHash (Identity / Fields / Unhashable / Custom), defaulting to identity.

  • monty (object_bridge.rs): sandbox classes fill them in on export, read the same way Instance::py_hash and instance_user_eq dispatch; the field lists come from the @dataclass-generated __eq__ / __hash__. Host classes always send identity.

  • monty-proto: four additive fields on Type (6–9: eq, eq_fields, hash, hash_fields). The zero value is identity, so older peers keep identity behaviour; an unknown enum value decodes as custom.

  • Python proxy: MontyClassProxy.__eq__ / __hash__ follow the rule; a non-proxy operand returns NotImplemented. MontyClassTypeProxy gains __hash__ over the class id.

  • Identity fallback: where the sandbox's answer would need sandbox code (a user-defined __eq__ or __hash__, in a plain class or a dataclass body), the proxy compares and hashes by instance id instead of approximating. The one exception is a user __hash__ beside a generated __eq__ (row 12): an id hash would give equal proxies different hashes, so it hashes the fields __eq__ compares. The hash always follows the proxy's ==: a frozen dataclass with a body __eq__ (row 11) compares by id, so it hashes by id rather than by its generated field hash, which could differ between two snapshots of one object. A class with __eq__ and no __hash__ stays unhashable.

  • Proxies cache their hash and == memoises equal proxy pairs, so a result graph of shared nested dataclasses hashes and compares in linear time on the host (it was exponential, outside any worker limit). Proxies share one class header per class node.

  • Proxy hashing raises RecursionError past 1000 nested proxies. CPython's hash() has no recursion guard (== does), and a dataclass chain with a non-recursive sandbox __hash__ returned as a dict key segfaulted the host at 100k nodes. The depth error is not cached.

  • Cached hash errors share their message through the class header: the unhashable TypeError and missing-field AttributeError embed the sandbox-chosen class name, and one copy per instance let a small result grow the host by gigabytes.

  • MontyClassProxy.attributes (and MontyClassTypeProxy.attributes) now returns a copy, so a host edit cannot change a proxy's ==, or its hash while it is in a set or dict. Edits were already not applied to a live sandbox object; they no longer reach the copy a restored session rebuilds from the proxy either.

  • JS (napi and wasm) sends identity; JS proxies compare by reference and the WIT record is unchanged.

  • Docs: _monty.pyi, limitations/classes.md, limitations/host-values.md, docs/host-objects.md.
  • Notes for review

  • PROTOCOL_VERSION is not bumped: the change is additive and an older peer that ignores the fields gets identity, which fits its doc comment. Maintainer's call.

  • monty-private: any ClassTypeNode { .. } struct literal there (e.g. in monty-cpython) needs eq / hash. A CPython worker could also fill in real rules from its classes.

  • Behaviour changes, which need a release note:

  • - Two distinct plain-class instances with equal attributes no longer compare equal on the host.
    - A class with a user-defined __eq__ (rows 2, 3, 10, 11, 13, and a dataclass field holding one, row 18) now compares by id on the host. Before, it compared every attribute, which matched the sandbox only when the user __eq__ did the same: Money(5) == Money(5) across two proxies was True, it is now False. Compare in the sandbox for the real answer.
    - Editing proxy.attributes no longer changes anything.
  • monty-js / wasm changes are compile- and clippy-checked only; make test-js / make test-wasm were not run.
  • Host vs sandbox, before and after

    "id" is the object's boundary uuid. "Before" is empty where the behaviour did not change.

    Sandbox class instances (MontyClassProxy)

    | # | Class | Sandbox == / hash | Host now | Now | Before |
    |---|---|---|---|---|---|
    | 1 | Plain class | identity / identity | id / id | Same | == differed: distinct objects with equal attributes were equal. Hash differed: TypeError |
    | 2 | __eq__ only | user / unhashable | id / TypeError | == differs | == differed (attribute comparison; agreed only when the user __eq__ compared all attributes). Hash same |
    | 3 | __eq__ + __hash__ | user / user | id / id | == differs | == differed (as 2). Hash differed: TypeError |
    | 4 | __hash__ only | identity / user | id / id | Same | == differed (as 1). Hash differed: TypeError |
    | 5 | __hash__ = None, no __eq__ | identity / unhashable | id / TypeError | Same | == differed (as 1). Hash same |
    | 6 | @dataclass | fields / unhashable | fields / TypeError | Same | == mostly same: it compared all attributes, not only fields, and compared classes by name. Hash same |
    | 7 | @dataclass(frozen=True) | fields / fields | fields / fields | Same | == mostly same (as 6). Hash differed: TypeError |
    | 8 | @dataclass(eq=False) | identity / identity | id / id | Same | == differed (as 1). Hash differed |
    | 9 | @dataclass(eq=False, frozen=True) | identity / identity | id / id | Same | == differed. Hash differed |
    | 10 | @dataclass + body __eq__ | user / unhashable | id / TypeError | == differs | == differed (as 2). Hash same |
    | 11 | @dataclass(frozen=True) + body __eq__ | user / fields | id / id | == differs | == differed. Hash differed |
    | 12 | @dataclass + body __hash__ | fields / user | fields / hash of the hashable fields | Same | == mostly same. Hash differed |
    | 13 | @dataclass + body __eq__ + __hash__ | user / user | id / id | == differs | == differed. Hash differed |
    | 14 | compare=False, hash=False, unsafe_hash, order | rejected by the sandbox | — | Not possible | |

    Host hash values never equal the sandbox's; only consistency with == matters.

    Fields inside a dataclass

    | # | Field holds | Now | Before |
    |---|---|---|---|
    | 15 | Builtin values | Same | |
    | 16 | Another dataclass | Same | |
    | 17 | A plain-class instance | Same | Differed: distinct inner objects with equal attributes were equal |
    | 18 | An instance with a user __eq__ | Differs: that field compares by id | Differed, though it agreed when the user __eq__ compared all attributes (e.g. P(Money(5)) == P(Money(5)) was True, as in the sandbox) |
    | 19 | A value that crosses as repr text | Differs | |
    | 20 | Nothing: a field the instance never set | Same (AttributeError) when the class has no default for it; differs when it does: the sandbox reads the class-level default, the host raises AttributeError | Differed: no error; compared as a missing dict key |
    | 21 | A cycle back to itself | Differs: the back-reference crosses as the string '...', so two distinct self-referencing instances compare equal on the host; the sandbox raises RecursionError | |

    Other situations

    | # | Situation | Now | Before |
    |---|---|---|---|
    | 22 | Same object returned in two separate results | is differs; == and hash same unless a dataclass field changed in between or holds NaN: each proxy is a snapshot compared by its fields, where the sandbox's self is other says equal | is differed; == same unless attributes changed between the two results; hash TypeError |
    | 23 | proxy == 5 | Differs when the class has a user __eq__ | |
    | 24 | Proxy vs an instance of another class whose reflected __eq__ returns True | Differs | |
    | 25 | Two classes with the same name | Same | Differed: equal when their attributes matched |
    | 26 | Host edits proxy.attributes of a frozen dataclass | Same: attributes returns a copy, so the proxy is unaffected | Differed: == changed |
    | 27 | Returned set, frozenset or dict containing proxies | Same | Differed: conversion failed with MontyRuntimeError: ... cannot convert the result to a Python value: ... unhashable |

    Host-defined classes sent in with ClassInstance

    | # | Situation | Now | Before |
    |---|---|---|---|
    | 28 | Returned in the same session (the original object) | Same | |
    | 29 | Returned after a restore (proxy) | Differs for host classes that compare by value; same for identity classes | Differed for host classes that compare by identity; mostly same for value classes (host dataclasses) |

    Class objects

    | # | Value | Now | Before |
    |---|---|---|---|
    | 30 | Host class, same session | Same | |
    | 31 | Host class or type(x) after a restore (MontyClassTypeProxy) | Same | == same; hash differed (TypeError, so they couldn't go in sets) |
    | 32 | Sandbox class object (A) | Differs (crosses as text) | |

    What still differs, and whether it can be fixed

  • Rows 2, 3, 10, 11, 13, 18, 23, 24 (a user-defined __eq__): not fixable on the host without running sandbox code, so by design the proxy falls back to identity rather than guess. Comparing attributes instead (the old behaviour) would let a returned set or dict silently drop an element whenever a user __eq__ calls attribute-equal objects unequal. The exact answer is session.feed_run('a == b', inputs=...) while both objects are still referenced in the sandbox.

  • Rows 19 and 21 (values crossing as text, including cycle placeholders): the wire carries no structure or identity to compare.

  • Row 20 with a class default: fixable by exporting each dataclass field's class-level default; left out as more wire surface than the case justifies.

  • Row 29: fixable in a follow-up, by having the Python host send its class's eq/hash rule and keeping it in HostClassType (a dumped type, so a #[serde(default)] field).

  • Rows 22 (is across results, via a per-session weak proxy cache) and 32 (sandbox class objects as MontyClassTypeProxy rather than text): fixable, but they change what users get back, so they need a maintainer decision.
  • Tests

  • crates/monty-python/tests/test_class_instance.py: 18 new tests and a rewritten test_proxy_equality (147 passed), covering rows 1, 2, 3, 6, 7, 10, 11, 12, 13, 16, 17, 20, 21, 22, 23, 25, 26, 27 and 31. Rows 4, 5, 8 and 9 have no dedicated test. Three more cover the hash depth guard and shared error messages.

  • monty-proto: differential test for unknown rule values; the oracle mirror and budget tests carry the new fields.

  • cargo nextest run -p monty -p monty-runtime -p monty-proto -p monty-types, make lint-rs, make lint-py (including stubtest), make lint-md pass; make generate-proto is in sync.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: rewitt94 Review duration: 9195m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1310"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository