Skip to content

Commit de67f1f

Browse files
committed
Support frozenset literal constants without a VirtualMachine
Assisted-by: Claude Code:claude-sonnet-5
1 parent 393689d commit de67f1f

5 files changed

Lines changed: 303 additions & 8 deletions

File tree

‎crates/common/src/hash.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ pub struct HashSecret {
3131
k1: u64,
3232
}
3333

34+
impl core::fmt::Debug for HashSecret {
35+
/// Redacted - `k0`/`k1` are hash-DoS-mitigation key material, not diagnostic data.
36+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37+
f.debug_struct("HashSecret").finish_non_exhaustive()
38+
}
39+
}
40+
3441
impl BuildHasher for HashSecret {
3542
type Hasher = SipHasher24;
3643

‎crates/vm/src/builtins/code.rs‎

Lines changed: 151 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,110 @@ fn is_name_chars(value: &crate::common::wtf8::Wtf8) -> bool {
281281
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
282282
}
283283

284+
/// Structural hash for an object built from a compile-time constant, without a `VirtualMachine`
285+
/// - safe because none of these types can have a custom `__hash__`. Must agree with each type's
286+
/// real `Hashable` impl, notably matching across the numeric tower (`hash(1) == hash(1.0)`),
287+
/// since `1` and `1.0` must land in the same frozenset-constant bucket.
288+
fn const_hash(ctx: &Context, obj: &PyObject) -> crate::common::hash::PyHash {
289+
use crate::common::hash;
290+
use crate::builtins::{PyBool, PyBytes, PyComplex, PyFloat, PyInt, PyStr, PyTuple};
291+
292+
if let Some(b) = obj.downcast_ref::<PyBool>() {
293+
hash::hash_bigint(b.0.as_bigint())
294+
} else if let Some(int) = obj.downcast_ref::<PyInt>() {
295+
hash::hash_bigint(int.as_bigint())
296+
} else if let Some(float) = obj.downcast_ref::<PyFloat>() {
297+
hash::hash_float(float.to_f64()).unwrap_or_else(|| hash::hash_object_id(obj.get_id()))
298+
} else if let Some(complex) = obj.downcast_ref::<PyComplex>() {
299+
let value = complex.to_complex64();
300+
let re_hash =
301+
hash::hash_float(value.re).unwrap_or_else(|| hash::hash_object_id(obj.get_id()));
302+
let im_hash =
303+
hash::hash_float(value.im).unwrap_or_else(|| hash::hash_object_id(obj.get_id()));
304+
let core::num::Wrapping(ret) =
305+
core::num::Wrapping(re_hash) + core::num::Wrapping(im_hash) * core::num::Wrapping(hash::IMAG);
306+
hash::fix_sentinel(ret)
307+
} else if let Some(s) = obj.downcast_ref::<PyStr>() {
308+
// Matches `PyStr::hash` - strings hash their WTF-8 bytes, not a validated `&str`.
309+
ctx.hash_secret.hash_bytes(s.as_bytes())
310+
} else if let Some(b) = obj.downcast_ref::<PyBytes>() {
311+
ctx.hash_secret.hash_bytes(b.as_bytes())
312+
} else if let Some(t) = obj.downcast_ref::<PyTuple>() {
313+
let hashes = t
314+
.as_slice()
315+
.iter()
316+
.map(|e| Ok::<_, core::convert::Infallible>(const_hash(ctx, e)));
317+
match hash::hash_tuple(hashes) {
318+
Ok(h) => h,
319+
Err(never) => match never {},
320+
}
321+
} else if let Some(fs) = obj.downcast_ref::<PyFrozenSet>() {
322+
let mut acc = hash::FrozenSetHash::new(fs.elements().len());
323+
for e in fs.elements() {
324+
acc.add(const_hash(ctx, &e));
325+
}
326+
acc.finish()
327+
} else if obj.is(ctx.none.as_object()) {
328+
// Matches `Hashable for PyNone`.
329+
0xFCA86420_u64 as hash::PyHash
330+
} else {
331+
// `Ellipsis` (no custom `__hash__`) and anything else - identity-based, same as the
332+
// default object hash a real VM would compute for it.
333+
hash::hash_object_id(obj.get_id())
334+
}
335+
}
336+
337+
/// Structural equality for compile-time constant objects, matching Python equality - including
338+
/// numeric-tower cross-type equality (`1 == 1.0 == True`) - without a `VirtualMachine`. Safe
339+
/// because none of these types can have a custom `__eq__`.
340+
fn const_eq(a: &PyObject, b: &PyObject) -> bool {
341+
use crate::common::float_ops;
342+
use crate::builtins::{PyBool, PyBytes, PyFloat, PyInt, PyStr, PyTuple};
343+
344+
if a.is(b) {
345+
return true;
346+
}
347+
let a_bigint = a
348+
.downcast_ref::<PyBool>()
349+
.map(|b| b.0.as_bigint())
350+
.or_else(|| a.downcast_ref::<PyInt>().map(|i| i.as_bigint()));
351+
let b_bigint = b
352+
.downcast_ref::<PyBool>()
353+
.map(|b| b.0.as_bigint())
354+
.or_else(|| b.downcast_ref::<PyInt>().map(|i| i.as_bigint()));
355+
if let (Some(x), Some(y)) = (a_bigint, b_bigint) {
356+
return x == y;
357+
}
358+
if let (Some(x), Some(y)) = (a_bigint, b.downcast_ref::<PyFloat>()) {
359+
return float_ops::eq_int(y.to_f64(), x);
360+
}
361+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyFloat>(), b_bigint) {
362+
return float_ops::eq_int(x.to_f64(), y);
363+
}
364+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyFloat>(), b.downcast_ref::<PyFloat>()) {
365+
return x.to_f64() == y.to_f64();
366+
}
367+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyStr>(), b.downcast_ref::<PyStr>()) {
368+
return x.as_bytes() == y.as_bytes();
369+
}
370+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyBytes>(), b.downcast_ref::<PyBytes>()) {
371+
return x.as_bytes() == y.as_bytes();
372+
}
373+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyTuple>(), b.downcast_ref::<PyTuple>()) {
374+
return x.as_slice().len() == y.as_slice().len()
375+
&& x.as_slice()
376+
.iter()
377+
.zip(y.as_slice())
378+
.all(|(e1, e2)| const_eq(e1, e2));
379+
}
380+
if let (Some(x), Some(y)) = (a.downcast_ref::<PyFrozenSet>(), b.downcast_ref::<PyFrozenSet>()) {
381+
let (xe, ye) = (x.elements(), y.elements());
382+
return xe.len() == ye.len() && xe.iter().all(|e1| ye.iter().any(|e2| const_eq(e1, e2)));
383+
}
384+
// `None`/`Ellipsis` are canonical singletons already handled by the identity check above.
385+
false
386+
}
387+
284388
impl ConstantBag for PyObjBag<'_> {
285389
type Constant = Literal;
286390

@@ -320,13 +424,18 @@ impl ConstantBag for PyObjBag<'_> {
320424
.into_ref(ctx)
321425
.into()
322426
}
323-
BorrowedConstant::Frozenset { elements: _ } => {
324-
// Creating a frozenset requires VirtualMachine for element hashing.
325-
// PyObjBag only has Context, so we cannot construct PyFrozenSet here.
326-
// Frozenset constants from .pyc are handled by PyMarshalBag which has VM access.
327-
unimplemented!(
328-
"frozenset constant in PyObjBag::make_constant requires VirtualMachine"
329-
)
427+
BorrowedConstant::Frozenset { elements } => {
428+
let elements_with_hashes = elements
429+
.iter()
430+
.map(|constant| {
431+
let obj = self.make_constant(constant.borrow_constant()).0;
432+
let hash = const_hash(ctx, &obj);
433+
(obj, hash)
434+
})
435+
.collect();
436+
PyFrozenSet::from_constant_elements(elements_with_hashes, const_eq)
437+
.into_ref(ctx)
438+
.into()
330439
}
331440
BorrowedConstant::None => ctx.none(),
332441
BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(),
@@ -1736,3 +1845,38 @@ impl<'a> LineTableReader<'a> {
17361845
pub(crate) fn init(ctx: &'static Context) {
17371846
PyCode::extend_class(ctx, ctx.types.code_type);
17381847
}
1848+
1849+
#[cfg(test)]
1850+
mod tests {
1851+
use crate::Interpreter;
1852+
1853+
/// Exercises `PyObjBag` specifically (`Context`, no `VirtualMachine`) via `ctx.new_code`,
1854+
/// not `vm.compile`/`PyVmBag` - a frozenset literal constant used to panic here.
1855+
#[test]
1856+
fn context_only_frozenset_constant() {
1857+
Interpreter::without_stdlib(Default::default()).enter(|vm| {
1858+
let source = "\
1859+
x = frozenset({1, 2, 3})
1860+
assert 1 in x and 2 in x and 3 in x and 4 not in x
1861+
assert len(x) == 3
1862+
1863+
# numeric tower: 1 == 1.0 == True must collapse to a single element, matching real Python.
1864+
y = frozenset({1, 1.0, True})
1865+
assert len(y) == 1
1866+
assert 1 in y and 1.0 in y and True in y
1867+
1868+
z = frozenset({'a', 'b', 'a'})
1869+
assert len(z) == 2
1870+
1871+
w = frozenset({(1, 'a'), (1, 'a'), (2, 'b')})
1872+
assert len(w) == 2
1873+
";
1874+
let opts = vm.compile_opts();
1875+
let code = crate::compiler::compile(source, crate::compiler::Mode::Exec, "<test>", opts)
1876+
.expect("compile should succeed");
1877+
let code_ref = vm.ctx.new_code(code);
1878+
let scope = vm.new_scope_with_builtins();
1879+
vm.run_code_obj(code_ref, scope).unwrap();
1880+
});
1881+
}
1882+
}

‎crates/vm/src/builtins/set.rs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,20 @@ impl PyFrozenSet {
111111
})
112112
}
113113

114+
/// Build directly from constant-literal elements with precomputed hashes, without a
115+
/// `VirtualMachine` - used by `PyObjBag::make_constant`, which only has a `Context`. Safe
116+
/// because a constant frozenset can only ever contain elements whose equality can't involve
117+
/// a custom `__eq__` (ints/floats/bools/strings/bytes/tuples/frozensets/None/...).
118+
pub(crate) fn from_constant_elements(
119+
elements: Vec<(PyObjectRef, PyHash)>,
120+
key_eq: impl Fn(&PyObject, &PyObject) -> bool,
121+
) -> Self {
122+
Self {
123+
inner: PySetInner::from_constant_elements(elements, key_eq),
124+
..Default::default()
125+
}
126+
}
127+
114128
pub fn elements(&self) -> Vec<PyObjectRef> {
115129
self.inner.elements()
116130
}
@@ -196,6 +210,18 @@ impl PySetInner {
196210
Ok(set)
197211
}
198212

213+
/// See [`PyFrozenSet::from_constant_elements`].
214+
pub(super) fn from_constant_elements(
215+
elements: Vec<(PyObjectRef, PyHash)>,
216+
key_eq: impl Fn(&PyObject, &PyObject) -> bool,
217+
) -> Self {
218+
let set = Self::default();
219+
for (obj, hash) in elements {
220+
set.content.insert_no_vm(obj, hash, (), &key_eq);
221+
}
222+
set
223+
}
224+
199225
/// Build a set from an arbitrary object, reusing stored hashes when the
200226
/// source is a set/frozenset/dict.
201227
fn from_object(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {

‎crates/vm/src/dict_inner.rs‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,118 @@ impl<T: Clone> Dict<T> {
564564
Ok(stored_index)
565565
}
566566

567+
/// Store a key using a caller-supplied equality closure instead of full `DictKey`/VM
568+
/// dispatch - for keys (e.g. compile-time constant literals) whose equality never needs
569+
/// `__eq__`, so no `VirtualMachine` is required at all.
570+
///
571+
/// `hash` must be `key`'s real hash under the algorithm real objects of its type use, or
572+
/// lookups against this entry from a VM-dispatched caller will never find it. `key_eq` must
573+
/// agree with Python equality for `key`'s type - notably the numeric tower, where
574+
/// `1 == 1.0 == True` and must compare (and already hash) equal.
575+
pub(crate) fn insert_no_vm(
576+
&self,
577+
key: PyObjectRef,
578+
hash: HashValue,
579+
value: T,
580+
key_eq: impl Fn(&PyObject, &PyObject) -> bool,
581+
) {
582+
loop {
583+
let (entry_index, index_index) = self.lookup_no_vm(&key, hash, &key_eq);
584+
let mut inner = self.write();
585+
if let Some(index) = entry_index.index() {
586+
// Update existing key
587+
if let Some(entry) = inner.entries.get_mut(index) {
588+
let Some(entry) = entry.as_mut() else {
589+
// The dict was changed since we did lookup. Let's try again.
590+
continue;
591+
};
592+
if entry.index == index_index {
593+
entry.value = value;
594+
return;
595+
}
596+
// stuff shifted around, let's try again
597+
continue;
598+
}
599+
// The dict was changed since we did lookup. Let's try again.
600+
continue;
601+
}
602+
// New key - validate slot is still what lookup found
603+
if inner.indices.get(index_index) != Some(&entry_index) {
604+
// Dict was resized since lookup, retry
605+
continue;
606+
}
607+
self.invalidate_keys_version();
608+
inner.unchecked_push(index_index, hash, key, value, entry_index);
609+
return;
610+
}
611+
}
612+
613+
/// [`Self::lookup`], but the collision-resolution equality check is a caller-supplied
614+
/// closure instead of `DictKey::key_eq`, so no `VirtualMachine` is required.
615+
fn lookup_no_vm(
616+
&self,
617+
key: &PyObject,
618+
hash_value: HashValue,
619+
key_eq: &impl Fn(&PyObject, &PyObject) -> bool,
620+
) -> LookupResult {
621+
let mut idxs = None;
622+
let mut free_slot = None;
623+
loop {
624+
let (entry_key, ret) = {
625+
let inner = self.read();
626+
let mask = (inner.indices.len() - 1) as i64;
627+
let idxs = idxs.get_or_insert_with(|| GenIndexes::new(hash_value, mask));
628+
if idxs.mask != mask {
629+
// Dict was resized since last probe, restart
630+
*idxs = GenIndexes::new(hash_value, mask);
631+
free_slot = None;
632+
}
633+
loop {
634+
let index_index = idxs.next();
635+
let index_entry = *unsafe {
636+
// Safety: index_index is generated
637+
inner.indices.get_unchecked(index_index)
638+
};
639+
match index_entry {
640+
IndexEntry::DUMMY => {
641+
if free_slot.is_none() {
642+
free_slot = Some(index_index);
643+
}
644+
}
645+
IndexEntry::FREE => {
646+
let idxs = match free_slot {
647+
Some(free) => (IndexEntry::DUMMY, free),
648+
None => (IndexEntry::FREE, index_index),
649+
};
650+
return idxs;
651+
}
652+
idx => {
653+
let entry = unsafe {
654+
// Safety: DUMMY and FREE are already handled above.
655+
// i is always valid and entry always exists.
656+
let i = idx.index().unwrap_unchecked();
657+
inner.entries.get_unchecked(i).as_ref().unwrap_unchecked()
658+
};
659+
let ret = (idx, index_index);
660+
if key.is(&entry.key) {
661+
return ret;
662+
} else if entry.hash == hash_value {
663+
break (entry.key.clone(), ret);
664+
} else {
665+
// entry mismatch
666+
}
667+
}
668+
}
669+
}
670+
};
671+
// This comparison needs to be done outside the lock.
672+
if key_eq(key, &entry_key) {
673+
return ret;
674+
}
675+
// hash collision, continue probing
676+
}
677+
}
678+
567679
pub(crate) fn contains<K: DictKey + ?Sized>(
568680
&self,
569681
vm: &VirtualMachine,

‎crates/vm/src/vm/context.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::{
1515
type_::PyAttributes,
1616
},
1717
class::StaticType,
18-
common::rc::PyRc,
18+
common::{hash::HashSecret, rc::PyRc},
1919
exceptions,
2020
function::{
2121
HeapMethodDef, IntoPyGetterFunc, IntoPyNativeFn, IntoPySetterFunc, PyMethodDef,
@@ -55,6 +55,11 @@ pub struct Context {
5555
pub(crate) slot_new_wrapper: PyMethodDef,
5656
pub names: ConstName,
5757
// GC module state (callbacks and garbage lists)
58+
/// The process-wide hash secret - same seed `VirtualMachine::state.hash_secret` uses by
59+
/// default (`process_hash_secret_seed`), so a `str`/`bytes` hashed here and one hashed
60+
/// through a VM agree. Diverges only if an embedder overrides a specific VM's `hash_seed`,
61+
/// which nothing built from `Context` alone (e.g. constant-folded code) can see.
62+
pub(crate) hash_secret: HashSecret,
5863
}
5964

6065
macro_rules! declare_const_name {
@@ -422,6 +427,7 @@ impl Context {
422427
string_pool,
423428
slot_new_wrapper,
424429
names,
430+
hash_secret: HashSecret::new(crate::vm::process_hash_secret_seed()),
425431
}
426432
}
427433

0 commit comments

Comments
 (0)