Skip to content

Commit aec533b

Browse files
committed
Apply interpreter settings before deriving runtime configuration
Assisted-by: Codex:GPT-6
1 parent 38b90f2 commit aec533b

3 files changed

Lines changed: 106 additions & 26 deletions

File tree

‎crates/capi/src/pylifecycle.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ pub extern "C" fn Py_InitializeEx(_initsigs: c_int) {
4545
*interp = unsafe {
4646
builder
4747
.add_native_modules(&defs)
48-
.configure(|config| {
48+
.configure_paths(|paths| {
4949
let path = rustpython_pylib::LIB_PATH.to_owned();
5050

51-
config.paths.stdlib_dir = Some(path.clone());
52-
config.paths.module_search_paths.insert(0, path);
51+
paths.stdlib_dir = Some(path.clone());
52+
paths.module_search_paths.insert(0, path);
5353
})
5454
.build()
5555
.into()

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

Lines changed: 96 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::{
44
Context, PyConfig, PyGlobalState, VirtualMachine,
55
owned::OwnedVm,
66
runtime::{self, InterpreterWhence},
7-
setting::Settings,
7+
setting::{Paths, Settings},
88
thread,
99
};
1010
use crate::{
@@ -15,7 +15,7 @@ use alloc::collections::BTreeMap;
1515
use core::sync::atomic::Ordering;
1616

1717
type InitFunc = Box<dyn FnOnce(&VirtualMachine)>;
18-
type ConfigFunc = Box<dyn FnOnce(&mut PyConfig)>;
18+
type PathConfigFunc = Box<dyn FnOnce(&mut Paths)>;
1919

2020
/// Exit code used when stdout/stderr flush fails during interpreter shutdown.
2121
/// Matches CPython's behavior (see cpython/Python/pylifecycle.c).
@@ -41,7 +41,7 @@ pub struct InterpreterBuilder {
4141
module_defs: Vec<&'static builtins::PyModuleDef>,
4242
frozen_modules: Vec<(&'static str, FrozenModule)>,
4343
init_hooks: Vec<InitFunc>,
44-
config_hooks: Vec<ConfigFunc>,
44+
path_hooks: Vec<PathConfigFunc>,
4545
}
4646

4747
/// Options for constructing a main or sub-interpreter VM.
@@ -51,7 +51,7 @@ struct InitializeVmOpts<'a> {
5151
module_defs: Vec<&'static builtins::PyModuleDef>,
5252
frozen_modules: Vec<(&'static str, FrozenModule)>,
5353
init_hooks: Vec<InitFunc>,
54-
config_hooks: Vec<ConfigFunc>,
54+
path_hooks: Vec<PathConfigFunc>,
5555
is_main: bool,
5656
whence: InterpreterWhence,
5757
/// When `Some`, reuse parent module_defs/frozen/config seeds for a subinterpreter.
@@ -70,7 +70,7 @@ where
7070
module_defs,
7171
frozen_modules,
7272
init_hooks,
73-
config_hooks,
73+
path_hooks,
7474
is_main,
7575
whence,
7676
parent_state,
@@ -98,11 +98,11 @@ where
9898
} else {
9999
// First top-level interpreter wins. Later seeds are ignored.
100100
super::init_hash_secret(settings.hash_seed);
101-
let paths = getpath::init_path_config(&settings);
102-
let mut config = PyConfig::new(settings, paths);
103-
for hook in config_hooks {
104-
hook(&mut config);
101+
let mut paths = getpath::init_path_config(&settings);
102+
for hook in path_hooks {
103+
hook(&mut paths);
105104
}
105+
let config = PyConfig::new(settings, paths);
106106

107107
// Build module_defs map from builtin modules + additional modules
108108
let mut all_module_defs: BTreeMap<&'static str, &'static builtins::PyModuleDef> =
@@ -284,7 +284,7 @@ fn create_subinterpreter_from_parent(
284284
module_defs: Vec::new(),
285285
frozen_modules: Vec::new(),
286286
init_hooks: Vec::new(),
287-
config_hooks: Vec::new(),
287+
path_hooks: Vec::new(),
288288
is_main: false,
289289
whence: InterpreterWhence::Stdlib,
290290
parent_state: Some(&parent.state),
@@ -320,14 +320,25 @@ impl InterpreterBuilder {
320320
module_defs: Vec::new(),
321321
frozen_modules: Vec::new(),
322322
init_hooks: Vec::new(),
323-
config_hooks: Vec::new(),
323+
path_hooks: Vec::new(),
324324
}
325325
}
326326

327-
/// Configure Rust-owned settings and paths before creating runtime objects.
327+
/// Modify settings immediately, before deriving paths or the hash secret.
328+
///
329+
/// Calls to this method and [`Self::settings`] take effect in call order.
328330
#[must_use]
329-
pub fn configure(mut self, configure: impl FnOnce(&mut PyConfig) + 'static) -> Self {
330-
self.config_hooks.push(Box::new(configure));
331+
pub fn configure(mut self, configure: impl FnOnce(&mut Settings)) -> Self {
332+
configure(&mut self.settings);
333+
self
334+
}
335+
336+
/// Customize paths derived from the final settings during [`Self::build`].
337+
///
338+
/// Hooks run in registration order, before runtime objects are created.
339+
#[must_use]
340+
pub fn configure_paths(mut self, configure: impl FnOnce(&mut Paths) + 'static) -> Self {
341+
self.path_hooks.push(Box::new(configure));
331342
self
332343
}
333344

@@ -442,7 +453,7 @@ impl InterpreterBuilder {
442453
module_defs: self.module_defs,
443454
frozen_modules: self.frozen_modules,
444455
init_hooks: self.init_hooks,
445-
config_hooks: self.config_hooks,
456+
path_hooks: self.path_hooks,
446457
is_main: true,
447458
whence: InterpreterWhence::Runtime,
448459
parent_state: None,
@@ -530,7 +541,7 @@ impl Interpreter {
530541
module_defs: Vec::new(),
531542
frozen_modules: Vec::new(),
532543
init_hooks: Vec::new(),
533-
config_hooks: Vec::new(),
544+
path_hooks: Vec::new(),
534545
is_main: true,
535546
whence: InterpreterWhence::Runtime,
536547
parent_state: None,
@@ -2268,6 +2279,75 @@ for _ in range(40):
22682279
});
22692280
}
22702281

2282+
#[test]
2283+
fn builder_configuration_precedes_runtime_initialization() {
2284+
const CHILD: &str = "RUSTPYTHON_TEST_CONFIGURED_HASH_SEED";
2285+
if crate::host_env::os::var_os(CHILD).is_none() {
2286+
// A fresh process is needed because the first interpreter fixes the
2287+
// hash secret for every subsequent interpreter in that process.
2288+
#[expect(
2289+
clippy::disallowed_methods,
2290+
reason = "the test harness must restart itself with a fresh process hash secret"
2291+
)]
2292+
let output = std::process::Command::new(std::env::current_exe().unwrap())
2293+
.args([
2294+
"--exact",
2295+
concat!(
2296+
module_path!(),
2297+
"::builder_configuration_precedes_runtime_initialization"
2298+
)
2299+
.strip_prefix("rustpython_vm::")
2300+
.unwrap(),
2301+
])
2302+
.env(CHILD, "1")
2303+
.output()
2304+
.unwrap();
2305+
assert!(
2306+
output.status.success(),
2307+
"{}\n{}",
2308+
String::from_utf8_lossy(&output.stdout),
2309+
String::from_utf8_lossy(&output.stderr)
2310+
);
2311+
return;
2312+
}
2313+
2314+
let interp = Interpreter::builder(Settings {
2315+
hash_seed: Some(7),
2316+
..Settings::default()
2317+
})
2318+
.configure_paths(|paths| {
2319+
assert_eq!(paths.module_search_paths[0], "configured_path");
2320+
paths.module_search_paths.insert(0, "explicit_path".into());
2321+
paths.stdlib_dir = Some("explicit_stdlib".into());
2322+
})
2323+
.configure(|settings| {
2324+
settings.hash_seed = Some(8);
2325+
settings.path_list = vec!["configured_path".into()];
2326+
})
2327+
.configure_paths(|paths| {
2328+
assert_eq!(paths.module_search_paths[0], "explicit_path");
2329+
})
2330+
.build();
2331+
2332+
interp.enter(|vm| {
2333+
let expected = crate::common::hash::HashSecret::new(8);
2334+
assert_eq!(
2335+
vm.ctx
2336+
.new_str("configured hash seed")
2337+
.as_object()
2338+
.hash(vm)
2339+
.unwrap(),
2340+
expected.hash_str("configured hash seed")
2341+
);
2342+
let paths = &vm.state.config.paths;
2343+
assert_eq!(paths.stdlib_dir.as_deref(), Some("explicit_stdlib"));
2344+
let sys_path = vm.sys_module.get_attr("path", vm).unwrap();
2345+
let sys_path: Vec<String> = sys_path.try_into_value(vm).unwrap();
2346+
assert_eq!(sys_path, paths.module_search_paths);
2347+
assert_eq!(&sys_path[..2], ["explicit_path", "configured_path"]);
2348+
});
2349+
}
2350+
22712351
/// Set and `for` literals become frozenset constants. Materializing them
22722352
/// needs the VM so element hashing can run.
22732353
#[cfg(feature = "compiler")]

‎src/interpreter.rs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ impl InterpreterBuilderExt for InterpreterBuilder {
2323
feature = "freeze-stdlib" => {
2424
builder
2525
.add_frozen_modules(rustpython_pylib::FROZEN_STDLIB)
26-
.configure(set_frozen_stdlib_dir)
26+
.configure_paths(set_frozen_stdlib_dir)
2727
}
28-
_ => builder.configure(setup_dynamic_stdlib),
28+
_ => builder.configure_paths(setup_dynamic_stdlib),
2929
}
3030
}
3131
}
@@ -55,13 +55,13 @@ fn install_default_tls_provider(_vm: &crate::VirtualMachine) {
5555

5656
/// Set stdlib_dir for frozen standard library
5757
#[cfg(all(feature = "stdlib", feature = "freeze-stdlib"))]
58-
fn set_frozen_stdlib_dir(config: &mut rustpython_vm::vm::PyConfig) {
59-
config.paths.stdlib_dir = Some(rustpython_pylib::LIB_PATH.to_owned());
58+
fn set_frozen_stdlib_dir(paths: &mut rustpython_vm::vm::Paths) {
59+
paths.stdlib_dir = Some(rustpython_pylib::LIB_PATH.to_owned());
6060
}
6161

6262
/// Setup dynamic standard library loading from filesystem
6363
#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
64-
fn setup_dynamic_stdlib(config: &mut rustpython_vm::vm::PyConfig) {
64+
fn setup_dynamic_stdlib(config: &mut rustpython_vm::vm::Paths) {
6565
let paths: Vec<String> = collect_stdlib_paths()
6666
.into_iter()
6767
.map(|p| {
@@ -82,12 +82,12 @@ fn setup_dynamic_stdlib(config: &mut rustpython_vm::vm::PyConfig) {
8282

8383
// Set stdlib_dir to the first stdlib path if available
8484
if let Some(first_path) = paths.first() {
85-
config.paths.stdlib_dir = Some(first_path.clone());
85+
config.stdlib_dir = Some(first_path.clone());
8686
}
8787

8888
// Insert at the beginning so stdlib comes before user paths
8989
for path in paths.into_iter().rev() {
90-
config.paths.module_search_paths.insert(0, path);
90+
config.module_search_paths.insert(0, path);
9191
}
9292
}
9393

0 commit comments

Comments
 (0)