diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 100c636..9eb8a58 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -109,6 +109,46 @@ fn parse_args( Ok((config, admin, positional)) } +/// mimalloc reads its options once, before `main`. With `MIMALLOC_ALLOW_THP=0` it also returns +/// freed memory in small pieces, about 7% less RSS on top of the prctl. Self-update replaces only +/// the binary, never the unit, so the server sets it itself: `serve` re-runs itself once with the +/// variable set (same PID, so systemd is unaffected). An explicit value is left alone, and +/// short-lived commands such as `hook` skip the extra exec. +fn reexec_with_allocator_env(raw: &[std::ffi::OsString]) { + const VAR: &str = "MIMALLOC_ALLOW_THP"; + if std::env::var_os(VAR).is_some() { + return; + } + let mut words = raw.iter(); + let mut command = None; + while let Some(arg) = words.next() { + match arg.to_str() { + Some("--config") => { + words.next(); + } + Some("--admin") => {} + _ => { + command = Some(arg); + break; + } + } + } + if command.is_some_and(|c| c != "serve") { + return; + } + let exe = match std::env::current_exe() { + Ok(exe) => exe, + Err(e) => { + eprintln!("forge: cannot find the executable to set {VAR}: {e}"); + return; + } + }; + use std::os::unix::process::CommandExt; + // exec only returns on failure; the server then runs on without the variable. + let e = std::process::Command::new(exe).args(raw).env(VAR, "0").exec(); + eprintln!("forge: cannot re-run with {VAR}=0: {e}"); +} + fn main() -> ExitCode { // The sandbox helpers must start before any runtime or subscriber exists. if forge_runner::cli::is_sandbox_invocation() { @@ -126,6 +166,7 @@ fn main() -> ExitCode { if let Err(e) = nix::sys::prctl::set_thp_disable(true) { eprintln!("forge: cannot disable transparent huge pages: {e}"); } + reexec_with_allocator_env(&raw); let runtime = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() diff --git a/deploy/forge.service b/deploy/forge.service index 6f58c0b..eefd41f 100644 --- a/deploy/forge.service +++ b/deploy/forge.service @@ -10,9 +10,6 @@ Type=simple User=forge Group=forge Environment=FORGE_CONFIG=/etc/forge/forge.toml -# forge turns transparent huge pages off itself at start; this also makes the allocator return -# memory in small pieces, which keeps a further ~7% off the resident size. -Environment=MIMALLOC_ALLOW_THP=0 ExecStart=/usr/local/bin/forge serve WorkingDirectory=/var/lib/forge Restart=on-failure