Skip to content

feat(proc-macro): Tier-2 native proc-macro link-time _DECLS export and BZPM v1 guest harness - #2893

Merged
mteacher360 merged 6 commits into
mainfrom
feat/tier2-native-pm-harness
Nov 29, 2026
Merged

mteacher360 merged 6 commits into
mainfrom
feat/tier2-native-pm-harness

Conversation

@mteacher360

Copy link
Copy Markdown
Collaborator

Summary

Implements Tier-2 Native Proc-Macro PR 2 of 4 (guest side paired with host PR #2891): link-time _DECLS C-ABI accessors in blaze-scope + the self-contained native proc-macro executable guest harness (NATIVE_PROC_MACRO_HARNESS) in blaze-cli speaking Blaze's BZPM v1 binary protocol over inherited CHILD_FD (fd 3) — zero rustc, zero lld, zero dlopen/dlsym.

Changes

  1. crates/blaze-scope/src/task/lower.rs & crates/blaze-scope/src/task/mod.rs:
    • Extended proc_macro_harness_text to 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() -> usize
    • Added deterministic key helpers PROC_MACRO_DECLS_FN, PROC_MACRO_DECLS_LEN_FN, proc_macro_decls_fn_key, and proc_macro_decls_len_fn_key.
    • Added unit test link_time_decls_accessors_emit_on_native_and_stay_gated_off_on_wasm covering native emission, non-binding hygiene, wasm64/wasm32 suppression, and empty proc-macro crates.
  2. crates/blaze-cli/src/native_pm_harness.rs & crates/blaze-cli/src/main.rs:
    • Added self-contained NATIVE_PROC_MACRO_HARNESS source constant (uses only core + std + libc read/write on fd 3 + link-time __blaze_pm_decls/__blaze_pm_decls_len).
    • Matches PR feat(proc-macro): Tier-2 confined native.bin host, binary IPC protocol, and start_served_confined #2891's BZPM v1 wire protocol bit-for-bit (MAGIC = *b"BZPM", PROTO_VERSION = 1, PREFIX = 4 big-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 pinned Buffer/Closure/Config/Client #[repr(C)] ABI).
    • Overrides #[unsafe(no_mangle)] pub unsafe extern "C" fn getenv guarded by IN_EXPAND: AtomicBool, thread-local IN_RPC re-entrancy guard, CHANNEL_LOCK: Mutex<()>, and per-expansion ENV_POOL cleared after each expansion so std::env::var reads are served and tracked per-expansion without interfering with startup or leaking across warm worker reuse.
    • Wraps (client.run)(config) inside std::panic::catch_unwind (plus !info.can_unwind() panic hook fallback) so panicking proc-macros send Panic(msg) and leave the persistent worker alive for subsequent Expand frames until Shutdown or EOF (exit 0).

Verification (zero rustc invocations)

  • cargo test -p blaze-scope -- --test-threads=4: 500 passed, 0 failed (including proc_macro_harness native + 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 own engine_check — full blaze-scope + blaze-lower + blaze-typeck + blaze-borrowck against the pinned toolchain on both NATIVE_PROC_MACRO_HARNESS and a proc-macro crate emitting _DECLS + __blaze_pm_decls + __blaze_pm_decls_len with 0 findings)
    • bridge_repr_c_layouts_match_pinned_proc_macro_sources
    • wire_constants_match_channel_and_bzpm_v1_spec
    • bzpm_v1_wire_frame_encoding_and_decoding_bit_for_bit
    • wasm64_compile_proc_macro_with_real_toolchain_imports_env_var_and_reads_cargo_pkg_version
  • cargo check -p blaze-cli --bin blaze --no-default-features: pass.
  • All 5 ratchets (stops, casts, clones, allocs, ambient) vs origin/main: 0 net new sites.
  • domains and rustcsites: green (0 new rustc sites).
  • git merge-tree --write-tree origin/main HEAD: clean.

@mteacher360

Copy link
Copy Markdown
Collaborator Author

Codex (@codex) review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T04:32:53.817992Z 01a7b65 Manual request
ℹ️ About Codex in GitHub

Your 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +413 to +416
IN_EXPAND.store(true, Ordering::Release);
let guard = ExpandGuard;
let result = panic::catch_unwind(AssertUnwindSafe(|| unsafe {
(client.run)(config).into_vec()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +100 to +101
IN_EXPAND.store(false, Ordering::Release);
ENV_POOL.lock().unwrap_or_else(|e| e.into_inner()).clear();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +290 to +292
let val_bytes = &body[6..];
if std::str::from_utf8(val_bytes).is_err() {
std::process::exit(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +253 to +254
#[unsafe(no_mangle)]
pub unsafe extern "C" fn getenv(name: *const c_char) -> *mut c_char {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +265 to +266
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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)
@mteacher360

Copy link
Copy Markdown
Collaborator Author

Addressed all 5 Codex Round 1 findings:

  1. Enter package working directory on every Expand (TAG_CURRENT_DIR / TAG_CURRENT_DIR_VAL): Captures initial_dir at startup, queries TAG_CURRENT_DIR -> TAG_CURRENT_DIR_VAL via enter_working_directory() before every Client::run invocation (restoring initial_dir before relative paths and failing closed via TAG_PANIC if set_current_dir fails), and restores initial_dir in ExpandGuard::drop.
  2. Eliminate concurrent getenv vs ExpandGuard::drop UAF + DST with planted-bug controls: Added Dekker-ordered ACTIVE_ENV_CALLS (ActiveEnvGuard::try_enter() increments before checking IN_EXPAND; ExpandGuard::drop clears IN_EXPAND and drains ACTIVE_ENV_CALLS == 0 before clearing overlay and sending Output/Panic) combined with a deduplicated stable-address EnvState.arena that never frees returned C-strings while the worker is alive (bounded by 4 MiB / 8192 entries, retiring the worker cleanly after sending Output/Panic on cap). Added dst_concurrent_getenv_overlay_and_expand_drain_oracle_with_planted_controls covering 64 seeded interleavings with 4 planted-bug controls (FreeArenaOnExpandEnd, SkipDrainActiveCalls, LeakOverlayAcrossExpansions, SkipEnterWorkingDir).
  3. Preserve arbitrary non-UTF-8 Unix environment/path bytes: Removed from_utf8 checks in getenv, fetch_host_env, setenv, unsetenv, and enter_working_directory (OsStr::from_bytes); getenv forwards raw CStr::to_bytes() and copies raw non-NUL host bytes directly into NUL-terminated storage.
  4. Interpose whole-environment enumeration (__blaze_environ_walked): Clears ambient process environ to EMPTY_ENVIRON ([NULL]) at startup and after every expansion, and defines #[unsafe(no_mangle)] pub unsafe extern "C" fn __blaze_environ_walked() to fail closed via TAG_PANIC + clean exit during active expansions so std::env::vars() / vars_os() can never read an untracked ambient environment or pollute expansion cache keys.
  5. Honor per-expansion set_var / remove_var overlay: Interposes setenv and unsetenv into EnvState.overlay (raw byte keys/values backed by the stable arena, respecting overwrite == 0), consulted first by getenv and cleared after ACTIVE_ENV_CALLS drains to 0 so mutations never leak into libc environ or subsequent expansions.

Codex (@codex) review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +139 to +142
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +594 to +596
fn main() {
// Clear ambient process `environ` immediately so no startup variables can ever be observed.
unsafe { reset_process_environ() };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@mteacher360

Copy link
Copy Markdown
Collaborator Author

Addressed all 3 Codex Round 2 findings:

  1. P1 — Exercise the REAL production concurrency code in the DST: Extracted the exact production EnvState, EnvRuntime, ActiveEnvGuard, and ExpandGuard (Dekker SeqCst drain + stable-address arena + overlay) into crates/blaze-cli/guest/native_pm_env_core.rs.in, included verbatim into NATIVE_PROC_MACRO_HARNESS via include_str! AND compiled directly into native_pm_harness::tests via include!. Replaced the sequential model with dst_prod_env_runtime_concurrent_interleavings_and_planted_controls, which drives the exact production EnvRuntime / ActiveEnvGuard / ExpandGuard across real concurrent OS threads (std::thread::scope) and seeded phase barriers (16 seeds x 4 epochs x 3 workers) alongside planted-bug controls (SkipDrainBeforeOutput, ClearArenaOnExpandEnd, LeakOverlayAcrossExpansions) on the real EnvRuntime.
  2. P2 — Enforce the arena cap BEFORE allocating: EnvState::intern_capped checks BOTH arena.len() >= max_entries and arena_bytes + want_len > max_bytes before allocating or storing any new entry (deduplicating already-interned values first so repeat lookups at cap still succeed with 0 extra bytes/entries). On cap hit, retire_worker is set and setenv returns -1 (ENOMEM) immediately without updating the overlay (while getenv fails closed via TAG_PANIC + clean exit). Added prod_env_runtime_enforces_pre_alloc_caps_pre_main_isolation_and_raw_bytes proving neither cap can ever be exceeded during a single expansion.
  3. P1 — Clear ambient environ before static initializers & fail closed unconditionally on __blaze_environ_walked: Added an early constructor (BLAZE_PM_EARLY_ENVIRON_INIT in #[unsafe(link_section = ".init_array.00101")] on Linux and #[unsafe(link_section = "__DATA,__mod_init_func")] on Apple) calling reset_process_environ() before user static initializers run, and made __blaze_environ_walked() fail closed unconditionally — resetting environ, sending TAG_PANIC + exit(0) if inside Expand, and terminating immediately via _exit(101) if invoked outside Expand (e.g., from a static initializer before main).

Verified with zero rustc invocations (blaze-scope: 509/509 pass, blaze-cli native_pm_harness + wasm64_compile: 31/31 pass including Blaze engine_check on the full assembled harness, --no-default-features check pass, 0 net new ratchet sites across stops/casts/clones/allocs/ambient, domains and rustcsites green, clean merge-tree vs origin/main).

Codex (@codex) review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +135 to +136
if self.in_expand.load(std::sync::atomic::Ordering::SeqCst) {
Some(ActiveEnvGuard { rt: self })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +122 to +125
#[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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +426 to +428
Ok(()) => 0,
Err(()) => -1,
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +1368 to +1370
if !real_shelf.join(std::format!("{tc_id}")).exists() {
let _ = std::fs::remove_dir_all(&scratch);
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +236 to +239
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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@mteacher360

Copy link
Copy Markdown
Collaborator Author

Addressed all 7 Codex Round 3 findings (matching PR #2891's strict one-shot per-expansion worker model 1:1):

  1. P1 — Strict one-shot process isolation (eliminates cross-expansion thread leakage by construction) & 3. P1 — Zero custom lock-free atomics: Switched NATIVE_PROC_MACRO_HARNESS to strict one-shot execution: after Hello/HelloAck, handles at most one Expand (or Shutdown/EOF), runs Client::run under catch_unwind, acquires the single STATE: Mutex<EnvCore> (serializing with any in-flight getenv/setenv/unsetenv/dispatch_call), latches EnvPhase::PostExpand permanently, sends Output or Panic while holding STATE, and terminates immediately via _exit(0). With zero custom lock-free atomics and no second expansion ever possible, detached threads can neither emit post-Output frames nor contaminate another expansion. Replaced the OS-thread test with the deterministic dst_prod_env_core_deterministic_oracle_and_planted_controls over the exact production EnvCore (64 seeds + 3 planted controls: AllowSecondExpand, UncappedOverlay, FreeArenaOnFinish).
  2. P1 — Order early environ reset before Mach-O AND ELF user initializers: Placed BLAZE_PM_EARLY_ENVIRON_INIT unconditionally in #[unsafe(link_section = ".init_array.00000")], which blaze-ladder (parse_init_section) parses to priority Some(0) and blaze-export (layout.rs:418-423, macho.rs:799, elf.rs:452) sorts strictly BEFORE every user Rust initializer (__DATA,__mod_init_func / .init_array -> u32::MAX, .init_array.101..65535) and BEFORE native C archive initializers on both Mach-O and ELF. Added early_environ_init_priority_zero_precedes_user_inits_on_macos_and_linux proving via blaze_export::export that priority 0 occupies slot 0 on both Platform::MacosArm64 and Platform::LinuxArm64 even with a lexicographically maximal symbol ([0xff; 32]).
  3. P2 — Bound overlay names & entries in pre-allocation cap: EnvCore now tracks arena.len() + overlay.len() and arena_bytes + overlay_key_bytes and validates the combined delta before allocating either arena value or overlay key in getenv_capped, setenv_capped (atomically, so a rejected setenv never leaks an orphaned arena slot), and unsetenv_capped. Added unit tests covering repeated distinct unsetenv, repeated distinct setenv with a deduplicated value, and atomic rollback at cap.
  4. P2 — Set thread-local errno on setenv/unsetenv rejection: Added typed EnvError::{InvalidName, OutOfMemory, NotInExpand} mapping to POSIX EINVAL (22) / ENOMEM (12) / EPERM (1), written via __errno_location() (Linux) / __error() (Apple) before returning -1.
  5. P2 — Never silently skip the real-toolchain engine_check test: Marked blaze_engine_check_typechecks_and_borrowchecks_harness_and_pm_decls_with_real_toolchain with #[ignore = "needs installed pinned toolchain under $HOME/.blaze/v2/toolchain"] (matching wasm64_compile.rs) and replaced the silent early returns with explicit expect/assert! failures when HOME or the shelf entry is missing. Verified live with --ignored (ok · 2 files checked).
  6. P2 — Eliminate overwrite == false TOCTOU race: The entire lookup_overlay -> fetch_host_env_locked -> defensive recheck -> budget check -> commit executes atomically under the single STATE: Mutex<EnvCore> lock, so a concurrent setenv(..., 1) can never be overwritten by an older setenv(..., 0).

Verified with zero rustc invocations (blaze-scope: 509/509 pass; blaze-cli native_pm_harness + wasm64_compile: 31/31 pass + --ignored real-toolchain engine_check pass; --no-default-features pass; 0 new sites across stops/casts/clones/allocs/ambient/homes/dups/domains/rustcsites; clean merge-tree vs origin/main).

Codex (@codex) review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +150 to +152
#[used]
#[unsafe(link_section = ".init_array.00000")]
static BLAZE_PM_EARLY_ENVIRON_INIT: extern "C" fn() = blaze_pm_early_clear_environ;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +157 to +160
/// 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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@mteacher360

Copy link
Copy Markdown
Collaborator Author

Addressed both Codex Round 4 P1 findings in 55e92192ba:

  1. Expansion context active before user static initializers (native_pm_harness.rs / guest/native_pm_env_core.rs.in):

    • Priority-0 BLAZE_PM_EARLY_ENVIRON_INIT (.init_array.00000, verified ahead of all user Rust/C initializers on both ELF DT_INIT_ARRAY and Mach-O __DATA_CONST,__mod_init_func) now clears environ AND completes the one-shot BZPM v1 startup handshake (Hello/HelloAck, single Expand decode, CurrentDir/CurrentDirVal -> raw chdir, and EnvPhase::PreExpand -> EnvPhase::InExpand) before any user .init_array / __mod_init_func / linked C archive initializer runs.
    • User initializers calling getenv or current_dir now observe real host-tracked expansion values (TAG_ENV_VAR recorded on the wire) and the package working directory; Shutdown/EOF, out-of-bounds macro index, or chdir failure exits immediately before user initializers ever run. main() calls early_init_once() idempotently and takes pending_expand.
    • Added unit test early_init_provides_tracked_env_and_cwd_before_user_initializers.
  2. Bounded-DPOR model checking of the exact production one-shot mutex (blaze_check):

    • Moved the full production OneShotEnvRuntime<M: EnvMutex> + EnvWire protocol & lifecycle methods into crates/blaze-cli/guest/native_pm_env_core.rs.in (100% safe Rust), instantiated with StdEnvMutex(std::sync::Mutex<EnvCore>) + FdEnvWire in the guest binary and CheckEnvMutex(blaze_check::sync::Mutex<EnvCore>) + yielding MockWire in tests.
    • Added blaze_check_interleaves_production_oneshot_mutex_and_catches_planted_defects exploring concurrent main + detached worker interleavings directly over the production OneShotEnvRuntime, verifying zero interleaved/torn CHILD_FD frames, zero post-Output EnvVar/Dispatch traffic, linearizable setenv(..., overwrite = false), and live arena slots — plus 3 planted-bug controls (FinishSendOutsideLock, FinishSkipPhaseLatch, SetenvUnlockDuringHostCheck) deterministically caught by blaze_check.

Verification

  • cargo test -p blaze-cli --bin blaze -- native_pm_harness wasm64_compile --test-threads=4: 33 passed, 0 failed
  • cargo test -p blaze-cli --bin blaze -- blaze_engine_check_typechecks_and_borrowchecks_harness_and_pm_decls_with_real_toolchain --ignored --nocapture --test-threads=4: 1 passed (ok · 2 files checked · 8.6 s · 432 rebuilt)
  • cargo check -p blaze-cli --bin blaze --no-default-features: pass
  • cargo test -p blaze-scope -- --test-threads=4: 509 passed, 0 failed
  • Ratchets (stops, casts, clones, allocs, ambient, rustcsites, domains): 0 new sites/findings; merge-clean against origin/main.

Codex (@codex) review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +354 to +355
#[unsafe(link_section = ".init_array.00000")]
static BLAZE_PM_EARLY_ENVIRON_INIT: extern "C" fn() = blaze_pm_early_clear_environ;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@mteacher360

Copy link
Copy Markdown
Collaborator Author

Addressed the sole Codex Round 5 P1 finding in 01a7b65eef:

  • Exporter-reserved bootstrap slot (blaze_export::ProgramIn::bootstrap_init) strictly ahead of every user-expressible initializer:
    • Added ProgramIn::bootstrap_init: Option<Symbol> (default None for all existing callers) and ExportError::BootstrapInitNotPlaced in crates/blaze-export.
    • In crates/blaze-export/src/layout.rs (InitPlan::bootstrap_init_fn) and export.rs, blaze-export places bootstrap_init in its own dedicated slot of ELF DT_INIT_ARRAY (slot 0 on Linux) and Mach-O __DATA_CONST,__mod_init_func (slot 0 without TLS, or immediately after blaze-export's synthesized TLS setup) — strictly BEFORE every InitStatic (including user .init_array.00000 regardless of symbol ordering) and before all native C archive Inits. User crates cannot express or tie this slot via #[link_section].
    • Removed #[unsafe(link_section = ".init_array.00000")] from NATIVE_PROC_MACRO_HARNESS and replaced it with #[unsafe(no_mangle)] pub extern "C" fn __blaze_pm_early_environ_init() (NATIVE_PM_BOOTSTRAP_INIT_SYMBOL).
    • Updated early_environ_init_bootstrap_precedes_priority_zero_user_inits_on_macos_and_linux to export an adversarial user .init_array.00000 initializer with symbol [0x00; 32] against a bootstrap function with symbol [0xff; 32] on both Mach-O arm64 and ELF arm64, verifying bootstrap_init always occupies slot 0 ahead of user .init_array.00000 and that missing bootstrap symbols return ExportError::BootstrapInitNotPlaced.

Verification

  • cargo test -p blaze-export --lib -- --test-threads=4 + cargo check -p blaze-export --all-targets: 57 passed, 0 failed
  • cargo test -p blaze-cli --bin blaze -- native_pm_harness wasm64_compile --test-threads=4: 33 passed, 0 failed
  • cargo test -p blaze-cli --bin blaze -- blaze_engine_check_typechecks_and_borrowchecks_harness_and_pm_decls_with_real_toolchain --ignored --nocapture --test-threads=4: 1 passed (ok · 2 files checked · 8.8 s · 429 rebuilt)
  • cargo check -p blaze-cli --bin blaze --no-default-features: pass
  • cargo test -p blaze-scope -- --test-threads=4: 509 passed, 0 failed
  • Ratchets (stops, casts, clones, allocs, ambient, rustcsites, domains): 0 new sites/findings; merge-clean against origin/main.

Codex (@codex) review

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 01a7b65eef

ℹ️ 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".

@mteacher360
mteacher360 merged commit 9f0bda3 into main Nov 29, 2026
2 of 6 checks passed
@mteacher360
mteacher360 deleted the feat/tier2-native-pm-harness branch November 29, 2026 04:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant