Skip to content

Commit 5524276

Browse files
committed
Allow thread-state creation for externally owned interpreters
Keep compact construction roots alive with VM owners, publish only weak registry handles, and reuse thread-local initialization for main and subinterpreters. Preserve ordinary VM thread creation and current recursion settings without sharing mutable VM state. Assisted-by: OpenAI Codex:model-version-not-exposed
1 parent 17a679c commit 5524276

7 files changed

Lines changed: 150 additions & 22 deletions

File tree

‎crates/vm/src/stdlib/_testinternalcapi.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ mod _testinternalcapi {
730730
.new_thread()
731731
.run(|target| run_interpreter_source(source, target)))
732732
} else {
733-
let thread = crate::vm::runtime::owned_new_thread(id)
733+
let thread = crate::vm::runtime::new_interpreter_thread(id)
734734
.ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(vm, id))?;
735735
Ok(thread.run(|target| run_interpreter_source(source, target)))
736736
}
@@ -2075,7 +2075,7 @@ fn run_string_in_new_subinterp(
20752075
})?;
20762076
let id = crate::vm::runtime::store_owned_interpreter(interp);
20772077
let outcome = {
2078-
let thread = crate::vm::runtime::owned_new_thread(id)
2078+
let thread = crate::vm::runtime::new_interpreter_thread(id)
20792079
.ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(vm, id))?;
20802080
thread.run(|target| run_interpreter_source(source, target))
20812081
};

‎crates/vm/src/stdlib/sys.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1490,6 +1490,10 @@ pub mod sys {
14901490

14911491
if limit > recursion_depth {
14921492
vm.recursion_limit.set(limit);
1493+
#[cfg(feature = "threading")]
1494+
if let Some(factory) = &vm.thread_factory {
1495+
factory.recursion_limit.store(limit);
1496+
}
14931497
Ok(())
14941498
} else {
14951499
Err(vm.new_recursion_error(format!(

‎crates/vm/src/vm/crossinterp.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -973,7 +973,7 @@ where
973973
}
974974
let _guard = RunningGuard(&state);
975975

976-
let tvm = crate::vm::runtime::owned_new_thread(id)
976+
let tvm = crate::vm::runtime::new_interpreter_thread(id)
977977
.ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(caller, id))?;
978978
tvm.run(f)
979979
}

‎crates/vm/src/vm/interpreter.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,9 +247,17 @@ where
247247
if whence != InterpreterWhence::Unknown {
248248
let _vm_guard = thread::VmBootstrapGuard::new(&vm);
249249
vm.initialize();
250-
vm.state
251-
.ready
252-
.store(vm.startup_error.is_none(), Ordering::Release);
250+
}
251+
252+
if whence != InterpreterWhence::Unknown && vm.startup_error.is_none() {
253+
#[cfg(feature = "threading")]
254+
{
255+
let factory = alloc::sync::Arc::new(thread::InterpreterThreadFactory::new(&vm));
256+
vm.thread_factory = Some(factory.clone());
257+
runtime::publish_thread_factory(vm.state.interpreter_id, &factory);
258+
}
259+
// Publish readiness only after arbitrary-ID thread creation is available.
260+
vm.state.ready.store(true, Ordering::Release);
253261
}
254262

255263
// Clone global_state for Interpreter after all initialization is done

‎crates/vm/src/vm/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ pub const MAX_MEMORY_SIZE: usize = isize::MAX as usize;
8787
///
8888
/// To construct the main VM of an interpreter, use [`Interpreter`].
8989
pub struct VirtualMachine {
90+
#[cfg(feature = "threading")]
91+
pub(crate) thread_factory: Option<alloc::sync::Arc<thread::InterpreterThreadFactory>>,
9092
pub builtins: PyRef<PyModule>,
9193
pub sys_module: PyRef<PyModule>,
9294
pub ctx: PyRc<Context>,
@@ -1386,6 +1388,8 @@ impl VirtualMachine {
13861388
use_tracing: Cell::new(false),
13871389
what_event: Cell::new(None),
13881390
tracing_depth: Cell::new(0),
1391+
#[cfg(feature = "threading")]
1392+
thread_factory: None,
13891393
recursion_limit: Cell::new(if cfg!(debug_assertions) { 256 } else { 1000 }),
13901394
signal_handlers,
13911395
signal_rx: None,

‎crates/vm/src/vm/runtime.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ pub struct InterpreterInfo {
4848
}
4949

5050
struct RegistryEntry {
51+
#[cfg(feature = "threading")]
52+
thread_factory: alloc::sync::Weak<super::thread::InterpreterThreadFactory>,
5153
whence: InterpreterWhence,
5254
/// Weak handle so the registry does not keep interpreters alive.
5355
/// Type matches `PyRc` (Arc when threading, Rc otherwise).
@@ -338,6 +340,8 @@ fn insert_registry_entry(state: &PyRc<PyGlobalState>) {
338340
entries.insert(
339341
state.interpreter_id,
340342
RegistryEntry {
343+
#[cfg(feature = "threading")]
344+
thread_factory: alloc::sync::Weak::new(),
341345
whence: state.whence,
342346
state: PyRc::downgrade(state),
343347
},
@@ -375,6 +379,35 @@ pub fn lookup_interpreter(id: i64) -> Option<PyRc<PyGlobalState>> {
375379
entries.get(&id).and_then(|e| e.state.upgrade())
376380
}
377381

382+
#[cfg(feature = "threading")]
383+
pub(crate) fn publish_thread_factory(
384+
id: i64,
385+
factory: &alloc::sync::Arc<super::thread::InterpreterThreadFactory>,
386+
) {
387+
if let Some(entry) = registry().entries.lock().get_mut(&id) {
388+
entry.thread_factory = alloc::sync::Arc::downgrade(factory);
389+
}
390+
}
391+
392+
/// Create a fresh thread state for any live, initialized interpreter, including
393+
/// an externally owned main interpreter. Never execute or drop Python roots
394+
/// while holding the registry lock.
395+
#[cfg(feature = "threading")]
396+
pub(crate) fn new_interpreter_thread(id: i64) -> Option<super::thread::ThreadedVirtualMachine> {
397+
let (state, factory) = {
398+
let entries = registry().entries.lock();
399+
let entry = entries.get(&id)?;
400+
(entry.state.clone(), entry.thread_factory.clone())
401+
};
402+
let state = state.upgrade()?;
403+
if !state.ready.load(Ordering::Acquire) || state.finalizing.load(Ordering::Acquire) {
404+
return None;
405+
}
406+
// Thread attachment checks finalization again, closing the race with a
407+
// finalizer that starts after this lookup.
408+
Some(factory.upgrade()?.new_thread(state))
409+
}
410+
378411
/// List all currently registered (still-alive) interpreters.
379412
#[must_use]
380413
pub fn list_interpreters() -> Vec<InterpreterInfo> {

‎crates/vm/src/vm/thread.rs‎

Lines changed: 95 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1618,44 +1618,101 @@ impl VirtualMachine {
16181618

16191619
#[cfg(feature = "threading")]
16201620
pub(super) fn new_thread_vm(&self) -> Self {
1621-
let global_trace = self.state.global_trace_func.lock().clone();
1622-
let global_profile = self.state.global_profile_func.lock().clone();
1623-
let use_tracing = global_trace.is_some() || global_profile.is_some();
1621+
InterpreterThreadRoots::new(self).into_vm(
1622+
self.state.clone(),
1623+
self.recursion_limit.get(),
1624+
self.thread_factory.clone(),
1625+
)
1626+
}
1627+
}
1628+
1629+
/// Shared roots needed to create a thread state, without sharing any mutable
1630+
/// thread-local VM fields. VMs own this factory; the runtime registry is weak.
1631+
#[cfg(feature = "threading")]
1632+
pub(crate) struct InterpreterThreadFactory {
1633+
roots: InterpreterThreadRoots,
1634+
pub(crate) recursion_limit: crossbeam_utils::atomic::AtomicCell<usize>,
1635+
}
16241636

1637+
#[cfg(feature = "threading")]
1638+
#[derive(Clone)]
1639+
struct InterpreterThreadRoots {
1640+
builtins: crate::PyRef<crate::builtins::PyModule>,
1641+
sys_module: crate::PyRef<crate::builtins::PyModule>,
1642+
ctx: crate::common::rc::PyRc<crate::Context>,
1643+
wasm_id: Option<String>,
1644+
import_func: PyObjectRef,
1645+
importlib: PyObjectRef,
1646+
initialized: bool,
1647+
import_bootstrap_complete: bool,
1648+
callable_cache: super::CallableCache,
1649+
startup_error: Option<PyBaseExceptionRef>,
1650+
}
1651+
1652+
#[cfg(feature = "threading")]
1653+
impl InterpreterThreadRoots {
1654+
fn new(vm: &VirtualMachine) -> Self {
16251655
Self {
1626-
builtins: self.builtins.clone(),
1627-
sys_module: self.sys_module.clone(),
1628-
ctx: self.ctx.clone(),
1656+
builtins: vm.builtins.clone(),
1657+
sys_module: vm.sys_module.clone(),
1658+
ctx: vm.ctx.clone(),
1659+
wasm_id: vm.wasm_id.clone(),
1660+
import_func: vm.import_func.clone(),
1661+
importlib: vm.importlib.clone(),
1662+
initialized: vm.initialized,
1663+
import_bootstrap_complete: vm.import_bootstrap_complete,
1664+
callable_cache: vm.callable_cache.clone(),
1665+
startup_error: vm.startup_error.clone(),
1666+
}
1667+
}
1668+
1669+
fn into_vm(
1670+
self,
1671+
state: crate::common::rc::PyRc<PyGlobalState>,
1672+
recursion_limit: usize,
1673+
factory: Option<Arc<InterpreterThreadFactory>>,
1674+
) -> VirtualMachine {
1675+
let global_trace = state.global_trace_func.lock().clone();
1676+
let global_profile = state.global_profile_func.lock().clone();
1677+
let use_tracing = global_trace.is_some() || global_profile.is_some();
1678+
let profile_func = RefCell::new(global_profile.unwrap_or_else(|| self.ctx.none()));
1679+
let trace_func = RefCell::new(global_trace.unwrap_or_else(|| self.ctx.none()));
1680+
1681+
VirtualMachine {
1682+
thread_factory: factory,
1683+
builtins: self.builtins,
1684+
sys_module: self.sys_module,
1685+
ctx: self.ctx,
16291686
datastack: core::cell::UnsafeCell::new(crate::datastack::DataStack::new()),
1630-
wasm_id: self.wasm_id.clone(),
1687+
wasm_id: self.wasm_id,
16311688
exceptions: RefCell::default(),
1632-
import_func: self.import_func.clone(),
1633-
importlib: self.importlib.clone(),
1689+
import_func: self.import_func,
1690+
importlib: self.importlib,
16341691
import_timing: Cell::default(),
1635-
profile_func: RefCell::new(global_profile.unwrap_or_else(|| self.ctx.none())),
1636-
trace_func: RefCell::new(global_trace.unwrap_or_else(|| self.ctx.none())),
1692+
profile_func,
1693+
trace_func,
16371694
use_tracing: Cell::new(use_tracing),
16381695
what_event: Cell::new(None),
16391696
tracing_depth: Cell::new(0),
1640-
recursion_limit: self.recursion_limit.clone(),
1697+
recursion_limit: Cell::new(recursion_limit),
16411698
signal_handlers: core::cell::OnceCell::new(),
16421699
signal_rx: None,
16431700
repr_guards: RefCell::default(),
16441701
lazy_imports_resolving: RefCell::default(),
1645-
state: self.state.clone(),
1702+
state,
16461703
initialized: self.initialized,
16471704
import_bootstrap_complete: self.import_bootstrap_complete,
1648-
startup_error: self.startup_error.clone(),
1705+
startup_error: self.startup_error,
16491706
recursion_depth: Cell::new(0),
16501707
#[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))]
16511708
native_recursion_depth: Cell::new(0),
1652-
c_stack_soft_limit: Cell::new(Self::calculate_c_stack_soft_limit()),
1709+
c_stack_soft_limit: Cell::new(VirtualMachine::calculate_c_stack_soft_limit()),
16531710
async_gen_firstiter: RefCell::new(None),
16541711
async_gen_finalizer: RefCell::new(None),
16551712
asyncio_running_loop: RefCell::new(None),
16561713
asyncio_running_task: RefCell::new(None),
16571714
context_stack: RefCell::default(),
1658-
callable_cache: self.callable_cache.clone(),
1715+
callable_cache: self.callable_cache,
16591716
pending_tailcall_frame: Cell::new(None),
16601717
pending_tailcall_owner: core::cell::UnsafeCell::new(None),
16611718
pending_gen_resume: core::cell::UnsafeCell::new(None),
@@ -1664,3 +1721,25 @@ impl VirtualMachine {
16641721
}
16651722
}
16661723
}
1724+
1725+
#[cfg(feature = "threading")]
1726+
impl InterpreterThreadFactory {
1727+
pub(super) fn new(vm: &VirtualMachine) -> Self {
1728+
Self {
1729+
roots: InterpreterThreadRoots::new(vm),
1730+
recursion_limit: crossbeam_utils::atomic::AtomicCell::new(vm.recursion_limit.get()),
1731+
}
1732+
}
1733+
1734+
pub(crate) fn new_thread(
1735+
self: &Arc<Self>,
1736+
state: crate::common::rc::PyRc<PyGlobalState>,
1737+
) -> ThreadedVirtualMachine {
1738+
ThreadedVirtualMachine {
1739+
vm: self
1740+
.roots
1741+
.clone()
1742+
.into_vm(state, self.recursion_limit.load(), Some(self.clone())),
1743+
}
1744+
}
1745+
}

0 commit comments

Comments
 (0)