Repository navigation
feat(proc-macro): Tier-2 native proc-macro link-time _DECLS export and BZPM v1 guest harness - #2893
Conversation
…d BZPM v1 guest harness
|
Codex (@codex) review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfbc6f1e2e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| IN_EXPAND.store(true, Ordering::Release); | ||
| let guard = ExpandGuard; | ||
| let result = panic::catch_unwind(AssertUnwindSafe(|| unsafe { | ||
| (client.run)(config).into_vec() |
There was a problem hiding this comment.
Enter the package directory before invoking each macro
When this persistent worker serves a workspace member—or follows a macro that changed the process directory—it invokes the client without ever sending TAG_CURRENT_DIR or calling set_current_dir, so std::env::current_dir() and relative file accesses observe the worker's ambient or stale directory. The existing WASM guests call enter_working_directory before every expansion; this path must likewise obtain and enter the host-provided package directory so macro output does not depend on an untracked machine path.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
| IN_EXPAND.store(false, Ordering::Release); | ||
| ENV_POOL.lock().unwrap_or_else(|e| e.into_inner()).clear(); |
There was a problem hiding this comment.
Drain active getenv calls before clearing their storage
If a proc macro spawns a thread that has passed the IN_EXPAND check and the main macro function returns while that thread is completing getenv, this drop can free an entry in ENV_POOL after getenv returns its pointer but before std copies the pointed-to C string, causing a use-after-free. Track and drain in-flight calls, or otherwise give returned storage a lifetime that cannot end concurrently; the required interleaving DST should cover this return/clear race.
AGENTS.md reference: AGENTS.md:L125-L128
Useful? React with 👍 / 👎.
| let val_bytes = &body[6..]; | ||
| if std::str::from_utf8(val_bytes).is_err() { | ||
| std::process::exit(1); |
There was a problem hiding this comment.
Preserve non-UTF-8 environment bytes
When the host returns a valid Unix environment value containing non-UTF-8 bytes, this terminates the worker even though std::env::var_os accepts arbitrary non-NUL OsString bytes. The value can be copied directly into the NUL-terminated buffer; similarly, the request path should forward CStr::to_bytes() rather than silently treating a non-UTF-8 variable name as unset, otherwise valid proc macros fail under this native backend.
AGENTS.md reference: AGENTS.md:L113-L117
Useful? React with 👍 / 👎.
| #[unsafe(no_mangle)] | ||
| pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char { |
There was a problem hiding this comment.
Interpose whole-environment reads
When a proc macro calls std::env::vars_os(), this getenv override is bypassed: the pinned Unix std implementation traverses environ directly and only notifies an interposer through the optional __blaze_environ_walked hook, which this harness does not define. The expansion therefore sees the warm worker's startup environment rather than its per-expansion environment and records no dependency, so generated tokens can be cached under a key that omits every enumerated variable; route enumeration through the host or seed and track the complete expansion environment.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
| let _chan = CHANNEL_LOCK.lock().unwrap_or_else(|e| e.into_inner()); | ||
| if send_framed_bytes(TAG_ENV_VAR, name_str.as_bytes()).is_err() { |
There was a problem hiding this comment.
Honor per-expansion environment mutations
When valid proc-macro code calls set_var or remove_var and then reads that variable, those operations update libc's environ, but this override unconditionally asks the host and returns the original granted value instead. This makes var_os() disagree with vars_os() and can also leave mutations visible to later expansions in the persistent worker; maintain a per-expansion mutation overlay that is consulted by reads and discarded after the call.
AGENTS.md reference: AGENTS.md:L113-L117
Useful? React with 👍 / 👎.
… drain/arena, raw bytes, environ_walked, env overlay)
|
Addressed all 5 Codex Round 1 findings:
Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a76df624e6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| HoldingReturnedPtr { slot_id: usize, expected: std::vec::Vec<u8> }, | ||
| } | ||
|
|
||
| fn run_dst(seed: u64, plant: SimPlant) -> Result<(), std::string::String> { |
There was a problem hiding this comment.
Exercise production interleavings in the concurrency DST
The purported DST is a separate sequential state model and never invokes ActiveEnvGuard, ExpandGuard, or their atomics. Removing the production drain or weakening its ordering would therefore leave all 64 seeds and planted controls green, because those controls only modify the model; the getenv/expansion race remains without the required production-level interleaving proof.
AGENTS.md reference: AGENTS.md:L125-L128
Useful? React with 👍 / 👎.
| self.arena_bytes = self.arena_bytes.saturating_add(boxed.len()); | ||
| self.arena.push(boxed); | ||
| if self.arena_bytes > MAX_ENV_ARENA_BYTES || self.arena.len() > MAX_ENV_ARENA_ENTRIES { | ||
| RETIRE_WORKER.store(true, Ordering::Release); |
There was a problem hiding this comment.
Enforce the arena cap before allocating
When a proc macro repeatedly calls set_var with distinct values, intern allocates and retains each value before checking the cap, and RETIRE_WORKER is not acted on until the expansion finishes. The macro can therefore continue growing the arena arbitrarily after 4 MiB or 8192 entries and exhaust the worker before it can send its result; reject further interning as soon as the next allocation would exceed either bound.
AGENTS.md reference: AGENTS.md:L67-L67
Useful? React with 👍 / 👎.
| fn main() { | ||
| // Clear ambient process `environ` immediately so no startup variables can ever be observed. | ||
| unsafe { reset_process_environ() }; |
There was a problem hiding this comment.
Clear ambient environment before static initializers run
This reset occurs in main, after ELF/Mach-O static initializers from the proc-macro crate or linked native dependencies have already executed. If such an initializer calls std::env::vars_os(), __blaze_environ_walked returns because IN_EXPAND is false and the initializer can traverse the still-ambient environ, cache a value, and later affect macro output without any EnvVar request entering the expansion key; launch with an empty environment or install the reset before all user initializers.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
…arena cap, pre-init environ clearing)
|
Addressed all 3 Codex Round 2 findings:
Verified with zero Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 372c81997a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| if self.in_expand.load(std::sync::atomic::Ordering::SeqCst) { | ||
| Some(ActiveEnvGuard { rt: self }) |
There was a problem hiding this comment.
Bind environment calls to their originating expansion
If expansion A detaches a thread that calls getenv after A returns, this process-global flag either silently returns “unset” between expansions or admits the thread while expansion B is active. In the latter case its EnvVar request is recorded in B's key, and the thread can cache the value in proc-macro static state later consumed by expansion C without C's key containing that input. The runtime must prevent threads from one expansion from making environment calls in another expansion rather than treating every thread as belonging to whichever expansion is currently active.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
| #[cfg(target_vendor = "apple")] | ||
| #[used] | ||
| #[unsafe(link_section = "__DATA,__mod_init_func")] | ||
| static BLAZE_PM_EARLY_ENVIRON_INIT: extern "C" fn() = blaze_pm_early_clear_environ; |
There was a problem hiding this comment.
Order the reset before Mach-O user initializers
On macOS this unsuffixed __mod_init_func entry has no priority: the exporter sorts such entries by symbol (crates/blaze-export/src/layout.rs:403-422), so a proc-macro crate's own initializer can run before this reset. If that initializer accesses the raw environ symbol directly, it can cache ambient startup values without any host dependency entering the expansion key. Launch the child with an empty environment or reserve a loader slot that is guaranteed to precede every user initializer.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
| ) | ||
| .map_err(|()| std::format!("seed {seed} epoch {epoch}: setenv failed"))?; | ||
|
|
||
| thread::scope(|s| { |
There was a problem hiding this comment.
Model-check the production atomics instead of using OS threads
The fresh replacement now invokes the production EnvRuntime, but thread::scope plus barriers and yield_now is still a nondeterministic real-thread test that forces only one hand-authored race; it cannot enumerate or replay the atomic schedules that would expose weakened ordering or a missed entry/drain interleaving. The repository requires concurrent atomics to run under blaze-check with replayable schedules and planted controls, so this does not provide the required DST proof.
AGENTS.md reference: AGENTS.md:L125-L128
Useful? React with 👍 / 👎.
| return; | ||
| } | ||
| } | ||
| self.overlay.push((name.to_vec(), slot)); |
There was a problem hiding this comment.
Bound overlay names as well as arena values
The advertised arena limits do not bound this allocation: a macro can call unsetenv for arbitrarily many distinct names, or repeatedly setenv distinct names to one deduplicated value, and each call stores another uncapped name.to_vec() while consuming no additional arena entry or arena bytes. A single expansion can therefore grow the overlay until the worker is OOM despite both cap checks continuing to pass; include overlay names and entries in the pre-allocation limit.
AGENTS.md reference: AGENTS.md:L67-L67
Useful? React with 👍 / 👎.
| Ok(()) => 0, | ||
| Err(()) => -1, | ||
| } |
There was a problem hiding this comment.
Set errno when setenv rejects an update
When the arena cap is reached—or when the name is invalid—this exported setenv returns -1 without setting errno. POSIX callers are entitled to observe ENOMEM or EINVAL, and std::env::set_var also converts the current errno into its panic message; leaving an unrelated stale errno makes valid proc-macro code observe the wrong failure. Return a typed cause from the core and set the platform's thread-local errno before returning.
AGENTS.md reference: AGENTS.md:L113-L117
Useful? React with 👍 / 👎.
| if !real_shelf.join(std::format!("{tc_id}")).exists() { | ||
| let _ = std::fs::remove_dir_all(&scratch); | ||
| return; |
There was a problem hiding this comment.
Fail when the real-toolchain test cannot run
On CI or developer machines where HOME is unset or the pinned toolchain shelf has not already been populated, this test returns successfully without running engine_check; the suite therefore reports the full harness type/borrow check as passed even though it was skipped. Provision the required toolchain or make the missing prerequisite an explicit failure/ignored test rather than silently turning this coverage into a no-op.
AGENTS.md reference: AGENTS.md:L65-L65
Useful? React with 👍 / 👎.
| let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); | ||
| match state.intern_capped(val_bytes, max_bytes, max_entries) { | ||
| Ok(slot) => { | ||
| state.set_overlay(name_bytes, Some(slot)); |
There was a problem hiding this comment.
Recheck overwrite=false after the host lookup
With concurrent callers, the existence check is no longer valid when this lock is reacquired. For example, thread A can begin setenv("K", "A", 0), observe no overlay or host value, then thread B can complete setenv("K", "B", 1) before A reaches this block; A nevertheless overwrites B with A. Neither legal ordering of these overlapping POSIX calls produces that result, because B's overwrite wins if A is ordered first and A must be a no-op if B is ordered first. Recheck the overlay while holding this final lock before committing an overwrite == false update.
AGENTS.md reference: AGENTS.md:L113-L117
Useful? React with 👍 / 👎.
…ressing Codex R3 findings
|
Addressed all 7 Codex Round 3 findings (matching PR #2891's strict one-shot per-expansion worker model 1:1):
Verified with zero Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c735679218
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| #[used] | ||
| #[unsafe(link_section = ".init_array.00000")] | ||
| static BLAZE_PM_EARLY_ENVIRON_INIT: extern "C" fn() = blaze_pm_early_clear_environ; |
There was a problem hiding this comment.
Provide expansion context before user initializers
When a proc-macro crate or linked native archive has an initializer that reads getenv or current_dir and caches the result for the macro, this priority-zero hook empties environ before that initializer, while getenv_capped suppresses the host lookup during PreExpand and enter_working_directory runs only later in main. Such a macro therefore observes an artificial unset value or the launcher's ambient directory instead of the expansion environment/package directory that pinned Rust would expose; seed the per-expansion environment and working directory before executing the image's user initializers.
AGENTS.md reference: AGENTS.md:L113-L117
Useful? React with 👍 / 👎.
| /// Single lock serializing all `EnvCore` transitions and `CHILD_FD` wire I/O (zero custom | ||
| /// lock-free atomics: once `finish_expand` transitions to `EnvPhase::PostExpand` and emits | ||
| /// `Output`/`Panic`, no detached thread can emit another frame or touch the host). | ||
| static STATE: Mutex<EnvCore> = Mutex::new(EnvCore::new()); |
There was a problem hiding this comment.
Interleave the production one-shot mutex in the DST
The fresh one-shot rewrite replaces the atomics with STATE, but the claimed DST still constructs a private EnvCore and executes every operation sequentially; it never runs this mutex, the exported interposers, a detached call racing macro return, or the finish_expand/frame-send handoff. Removing this lock or moving the final transition outside it would leave all 64 seeds and all three planted controls green, so the concurrent production mechanism still lacks the required interleaving proof.
AGENTS.md reference: AGENTS.md:L125-L128
Useful? React with 👍 / 👎.
…ext & blaze-check DPOR DST)
|
Addressed both Codex Round 4 P1 findings in
Verification
Codex (@codex) review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55e92192ba
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| #[unsafe(link_section = ".init_array.00000")] | ||
| static BLAZE_PM_EARLY_ENVIRON_INIT: extern "C" fn() = blaze_pm_early_clear_environ; |
There was a problem hiding this comment.
Reserve bootstrap ordering ahead of priority-zero user entries
When a proc-macro crate declares its own #[used] static in .init_array.00000, this section does not guarantee that the harness runs first: parse_init_section accepts the same priority for user code, and blaze-export breaks equal-priority ties by symbol. Such an initializer can therefore cache ambient environment or cwd before the reset, handshake, and chdir, leaving that input absent from the expansion key. Fresh evidence beyond the earlier initializer issue is this equal-priority tie, rather than the ordinary or priority-101 entries covered by the new test; reserve an exporter-only bootstrap slot or otherwise establish tracked context before every user-expressible initializer.
AGENTS.md reference: AGENTS.md:L121-L123
Useful? React with 👍 / 👎.
…ad of .init_array.00000
|
Addressed the sole Codex Round 5 P1 finding in
Verification
Codex (@codex) review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback". |
Summary
Implements Tier-2 Native Proc-Macro PR 2 of 4 (guest side paired with host PR #2891): link-time
_DECLSC-ABI accessors inblaze-scope+ the self-contained native proc-macro executable guest harness (NATIVE_PROC_MACRO_HARNESS) inblaze-clispeaking Blaze'sBZPMv1 binary protocol over inheritedCHILD_FD(fd 3) — zerorustc, zerolld, zerodlopen/dlsym.Changes
crates/blaze-scope/src/task/lower.rs&crates/blaze-scope/src/task/mod.rs:proc_macro_harness_textto emit link-time C-ABI accessors alongside_DECLS, gated with#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]so wasm32/wasm64 proc-macro builds have zero extra items or exports:#[unsafe(export_name = "__blaze_pm_decls")] pub extern "C" fn __blaze_pm_decls() -> *const ::proc_macro::bridge::client::Client#[unsafe(export_name = "__blaze_pm_decls_len")] pub extern "C" fn __blaze_pm_decls_len() -> usizePROC_MACRO_DECLS_FN,PROC_MACRO_DECLS_LEN_FN,proc_macro_decls_fn_key, andproc_macro_decls_len_fn_key.link_time_decls_accessors_emit_on_native_and_stay_gated_off_on_wasmcovering native emission, non-binding hygiene, wasm64/wasm32 suppression, and empty proc-macro crates.crates/blaze-cli/src/native_pm_harness.rs&crates/blaze-cli/src/main.rs:NATIVE_PROC_MACRO_HARNESSsource constant (uses onlycore+std+ libcread/writeon fd 3 + link-time__blaze_pm_decls/__blaze_pm_decls_len).BZPMv1 wire protocol bit-for-bit (MAGIC = *b"BZPM",PROTO_VERSION = 1,PREFIX = 4big-endian frame length,MAX_FRAME_BYTES = 64 MiB,CHILD_FD = 3, little-endian body fields,Hello/HelloAck,Expand,Dispatch/Reply,EnvVar/EnvVal,CurrentDir/CurrentDirVal,Output,Panic,Shutdown, and pinnedBuffer/Closure/Config/Client#[repr(C)]ABI).#[unsafe(no_mangle)] pub unsafe extern "C" fn getenvguarded byIN_EXPAND: AtomicBool, thread-localIN_RPCre-entrancy guard,CHANNEL_LOCK: Mutex<()>, and per-expansionENV_POOLcleared after each expansion sostd::env::varreads are served and tracked per-expansion without interfering with startup or leaking across warm worker reuse.(client.run)(config)insidestd::panic::catch_unwind(plus!info.can_unwind()panic hook fallback) so panicking proc-macros sendPanic(msg)and leave the persistent worker alive for subsequentExpandframes untilShutdownor EOF (exit 0).Verification (zero
rustcinvocations)cargo test -p blaze-scope -- --test-threads=4: 500 passed, 0 failed (includingproc_macro_harnessnative + wasm64/wasm32 + empty-crate tests).cargo test -p blaze-cli --bin blaze -- native_pm_harness wasm64_compile --test-threads=4: 29 passed, 0 failed, including:blaze_engine_check_typechecks_and_borrowchecks_harness_and_pm_decls_with_real_toolchain(runs Blaze's ownengine_check— fullblaze-scope+blaze-lower+blaze-typeck+blaze-borrowckagainst the pinned toolchain on bothNATIVE_PROC_MACRO_HARNESSand a proc-macro crate emitting_DECLS+__blaze_pm_decls+__blaze_pm_decls_lenwith 0 findings)bridge_repr_c_layouts_match_pinned_proc_macro_sourceswire_constants_match_channel_and_bzpm_v1_specbzpm_v1_wire_frame_encoding_and_decoding_bit_for_bitwasm64_compile_proc_macro_with_real_toolchain_imports_env_var_and_reads_cargo_pkg_versioncargo check -p blaze-cli --bin blaze --no-default-features: pass.stops,casts,clones,allocs,ambient) vsorigin/main: 0 net new sites.domainsandrustcsites: green (0 newrustcsites).git merge-tree --write-tree origin/main HEAD: clean.