Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

reduce fsyncs during worker creation (#3287)

kt3034e94a2cb6
diff --git a/crates/pa-daemon/src/descriptor.rs b/crates/pa-daemon/src/descriptor.rs
index 574b0bebca..596888af6e 100644
--- a/crates/pa-daemon/src/descriptor.rs
+++ b/crates/pa-daemon/src/descriptor.rs
@@ -270,9 +270,46 @@ fn write_file_atomic_at(path: &Path, content: &str, sync: TempSync) -> Result<()
let _ = pa_core::platform::perms::restrict_file(&temp);
pa_core::platform::rename_onto(&temp, path)
.with_context(|| format!("persist {}", path.display()))?;
+ #[cfg(test)]
+ atomic_write_probe::record(path, sync);
Ok(())
}
+/// Test-only served-path witness for the atomic writes: the durability
+/// class of a write is not observable in the persisted bytes (the
+/// temp-file sync differs, not the content), so the supervision oracles
+/// take the recorded classes here and assert the intended writer
+/// actually served a launch.
+#[cfg(test)]
+pub(crate) mod atomic_write_probe {
+ use super::{PathBuf, TempSync};
+ use std::sync::Mutex;
+
+ static RECORDED: Mutex<Vec<(PathBuf, TempSync)>> = Mutex::new(Vec::new());
+
+ /// Record one successful atomic write's path and durability class.
+ pub(crate) fn record(path: &std::path::Path, sync: TempSync) {
+ RECORDED
+ .lock()
+ .expect("atomic write probe")
+ .push((path.to_path_buf(), sync));
+ }
+
+ /// Drain the recorded writes under one root (an oracle's descriptor
+ /// path or its directory), leaving every other record in place:
+ /// cargo runs tests in parallel, so a process-wide drain would
+ /// steal a parallel oracle's records and fail its durability
+ /// assertions.
+ pub(crate) fn take_under(root: &std::path::Path) -> Vec<(PathBuf, TempSync)> {
+ let mut recorded = RECORDED.lock().expect("atomic write probe");
+ let (under, rest): (Vec<_>, Vec<_>) = recorded
+ .drain(..)
+ .partition(|(path, _)| path.starts_with(root));
+ *recorded = rest;
+ under
+ }
+}
+
/// Persist the worker descriptor atomically with a fresh `updated_at`
/// stamp.
///
@@ -281,10 +318,27 @@ fn write_file_atomic_at(path: &Path, content: &str, sync: TempSync) -> Result<()
/// Returns an error when the descriptor cannot be serialized or the
/// atomic write to `path` fails.
pub fn persist_worker(path: &Path, descriptor: &WorkerDescriptor) -> Result<()> {
+ persist_worker_at(path, descriptor, TempSync::Synced)
+}
+
+/// The one persist body behind both durability classes: the same fresh
+/// `updated_at` stamp and atomic rename, differing only in the
+/// temp-file sync — `TempSync`, the single optional-fsync source of
+/// truth the write family already dispatches on.
+///
+/// # Errors
+///
+/// Returns an error when the descriptor cannot be serialized or the
+/// atomic write to `path` fails.
+pub(crate) fn persist_worker_at(
+ path: &Path,
+ descriptor: &WorkerDescriptor,
+ sync: TempSync,
+) -> Result<()> {
let mut descriptor = descriptor.clone();
descriptor.updated_at = crate::util::now_iso();
let content = serde_json::to_string_pretty(&descriptor)?;
- write_file_atomic(path, &content)
+ write_file_atomic_at(path, &content, sync)
}
/// The identity-pending side record (the descriptor store's own
@@ -449,6 +503,44 @@ mod tests {
);
}
+ #[test]
+ fn persist_worker_at_unsynced_stamps_and_round_trips() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("w.json");
+ let descriptor: WorkerDescriptor = serde_json::from_value(json!({
+ "version": 2,
+ "workerId": "wspawn",
+ "pid": 4242,
+ "socketPath": "/tmp/w.sock",
+ "recoveryJournalPath": "/tmp/w.recovery.jsonl",
+ "supervisorSocketPath": "/tmp/d.sock",
+ "authenticationToken": "tok",
+ "rootActiveSessionId": "wspawn",
+ "createdAt": "2026-10-01T00:00:00Z",
+ "updatedAt": "2026-10-01T00:00:00Z",
+ "lifecycle": "starting",
+ "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ persist_worker_at(&path, &descriptor, TempSync::Unsynced).expect("persist");
+ let persisted: WorkerDescriptor =
+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).expect("parse");
+ // The spawn record carries the same content the durable persist
+ // would (the stamp included) — only the pre-rename fsync differs.
+ assert_eq!(persisted.worker_id, "wspawn");
+ assert_eq!(persisted.pid, 4242);
+ assert_eq!(persisted.lifecycle, WorkerLifecycle::Starting);
+ assert_ne!(
+ persisted.updated_at, descriptor.updated_at,
+ "the fresh updated_at stamp rides the spawn record"
+ );
+ assert!(
+ std::fs::read_dir(dir.path()).unwrap().count() == 1,
+ "the temp file must not survive the rename"
+ );
+ }
+
#[test]
fn persisted_supervisor_config_round_trips_through_the_unsynced_write() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rs
index 40349dad05..8f91305e60 100644
--- a/crates/pa-daemon/src/supervisor.rs
+++ b/crates/pa-daemon/src/supervisor.rs
@@ -34,6 +34,8 @@ mod supervision;
#[cfg(test)]
mod handshake_tests;
#[cfg(test)]
+mod spawn_record_tests;
+#[cfg(test)]
mod tests;
// STABLE_LIFETIME_MS is read only by this facade's in-file test modules (via the module's
@@ -87,7 +89,7 @@ use tokio::sync::{broadcast, mpsc, oneshot};
use crate::backpressure::RouteAdmission;
use crate::descriptor::{
create_command_payload, load_descriptors, persist_supervisor_config, persist_worker,
- PersistedSupervisorConfig, SUPERVISOR_CONFIG_FILE_NAME,
+ persist_worker_at, PersistedSupervisorConfig, TempSync, SUPERVISOR_CONFIG_FILE_NAME,
};
use crate::engine::EngineModelSelection;
use crate::framing::{write_frame, PrivateFrameReader, DEFAULT_PRIVATE_FRAME_LIMITS};
@@ -129,6 +131,12 @@ pub struct Supervisor {
/// never unlinked by this process. `None` until `run` binds (named
/// pipes keep `None`: there is no file to stat).
bound_socket_identity: std::sync::Mutex<Option<socket::SocketIdentity>>,
+ /// The per-supervisor launch-probe budget override: `None` rides the
+ /// process-wide env seam (`PA_DAEMON_WORKER_CONNECT_TIMEOUT_MS`),
+ /// a pinned budget keeps a launch oracle's probe immediate without
+ /// mutating that env var (a set value would leak into every
+ /// parallel test's launch).
+ worker_connect_budget: std::sync::Mutex<Option<Duration>>,
/// The durable session-binding table (the stale-active-id rebind
/// surface): every active id the supervisor has routed stays
/// addressable through its session's durable identity, so a client
@@ -295,6 +303,7 @@ impl Supervisor {
options,
descriptor_dir,
bound_socket_identity: std::sync::Mutex::new(None),
+ worker_connect_budget: std::sync::Mutex::new(None),
session_bindings: crate::session_bindings::SessionBindingTable::new(),
opening_files: std::sync::Mutex::new(std::collections::HashMap::new()),
telemetry: std::sync::Mutex::new(None),
diff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rs
index e31401ffcc..ceb5fb4b56 100644
--- a/crates/pa-daemon/src/supervisor/adoption.rs
+++ b/crates/pa-daemon/src/supervisor/adoption.rs
@@ -4,7 +4,7 @@
use std::sync::Arc;
use super::{
- anyhow, json, load_descriptors, persist_worker, response_failure, response_success, socket,
+ anyhow, json, load_descriptors, response_failure, response_success, socket,
worker_connect_deadline, Context, DaemonCommand, DaemonResponse, DaemonWorkerLifecycle,
Duration, Ordering, Path, PathBuf, ResidentWorker, Result, Supervisor, Value,
WorkerRegistration,
@@ -473,7 +473,14 @@ impl Supervisor {
descriptor.root_session_id.as_deref(),
descriptor.session_file.as_deref(),
);
- let _ = persist_worker(&resident.descriptor_path, &descriptor);
+ // The registration refreshes the resident in memory only — no
+ // persist here. The spawn record already carries the
+ // launch-time identity (pid, socket), and the create-completion
+ // persist (`launch_worker`'s post-create write) owns the next
+ // durable state — `Ready` with the session identity — as the
+ // metadata-survival barrier. The boot scan adopts a live worker
+ // socket-first regardless of the recorded lifecycle, and a dead
+ // worker's recovery replays the durable create command.
let durable_session_id = match registration.session_id.clone() {
Some(session_id) => Some(session_id),
None => descriptor
diff --git a/crates/pa-daemon/src/supervisor/handshake_tests.rs b/crates/pa-daemon/src/supervisor/handshake_tests.rs
index 9d13a01b73..89c0bc7a99 100644
--- a/crates/pa-daemon/src/supervisor/handshake_tests.rs
+++ b/crates/pa-daemon/src/supervisor/handshake_tests.rs
@@ -1,8 +1,6 @@
-//! The worker-handshake boundary oracles (the launch-storm wedge class,
-//! 2026-09-28): the handshake owns its channel privately until the auth
-//! answer installs it for routing — the TS `pendingClient`/`worker.client`
-//! boundary. Split from `tests.rs` at the file-size advisory (the worker
-//! test mass precedent: one family per module).
+//! The worker-handshake boundary oracles: the handshake owns its channel
+//! privately until the auth answer installs it for routing — the TS
+//! `pendingClient`/`worker.client` boundary (one family per module).
use super::*;
@@ -160,14 +158,11 @@ async fn handshake_channel_stays_private_until_auth_answers() {
);
}
-/// The launch-storm wedge oracle (2026-09-28): a registration that lands
-/// mid-handshake must not kill the launch. Pre-fix, the registration
-/// path's roster refresh routed `get_state` onto the same unauthenticated
-/// connection the launch's `worker_auth` was handshakeing on; the worker
-/// answered the refresh as the failed unauthenticated FIRST command and
-/// closed the connection, stranding the handshake for the whole connect
-/// budget — a fully-healthy worker failing its launch "did not come up in
-/// time" (a warm ~12.5% rate on the four-launch e2e storm). Served-path:
+/// A registration that lands mid-handshake must not kill the launch:
+/// the registration's roster refresh routes onto its own authenticated
+/// channel once the handshake installs it, while the handshake's
+/// `worker_auth` keeps the unauthenticated connection to itself until
+/// the answer arrives. Served-path:
/// the wire carries EXACTLY the auth frame (no route rides the private
/// channel), the registration itself succeeds, and the launch completes.
#[tokio::test]
@@ -223,8 +218,7 @@ async fn a_mid_handshake_registration_cannot_kill_the_handshake() {
.expect("request id")
.to_string();
- // The registration lands while the handshake is still in flight — the
- // exact interleave that wedged the launch pre-fix.
+ // The registration lands while the handshake is still in flight.
let command = DaemonCommand::WorkerRegister {
id: None,
active_session_id: "w-wedge".to_string(),
@@ -269,11 +263,11 @@ async fn a_mid_handshake_registration_cannot_kill_the_handshake() {
);
}
-/// The install guard's TOCTOU pin (the Macroscope HIGH finding on the
-/// first PR head): a stale connect that passed its epoch check before a
-/// newer connection installed must never overwrite the newer channel —
-/// the recheck happens under the channel lock, so the stale install is
-/// dropped and the newer channel stays routable.
+/// The install guard's TOCTOU pin: a stale connect that passed its
+/// epoch check before a newer connection installed must never
+/// overwrite the newer channel — the recheck happens under the channel
+/// lock, so the stale install is dropped and the newer channel stays
+/// routable.
#[tokio::test]
async fn a_stale_epoch_never_overwrites_the_installed_channel() {
let dir = std::env::temp_dir().join(format!("pa-install-{}", uuid::Uuid::new_v4()));
diff --git a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs b/crates/pa-daemon/src/supervisor/spawn_record_tests.rs
new file mode 100644
index 0000000000..d2b312c022
--- /dev/null
+++ b/crates/pa-daemon/src/supervisor/spawn_record_tests.rs
@@ -0,0 +1,230 @@
+//! The spawn-record durability oracles: the descriptor writes around a
+//! worker's create and relaunch — the fresh create's unsynced spawn
+//! record, the relaunch's synced one, and the known-resident
+//! registration's in-memory refresh — witnessed on the REAL launch
+//! paths through the atomic-write probe (the durability class is not
+//! observable in the persisted bytes).
+
+use super::*;
+
+/// The witness supervisor for the launch oracles: a per-test uuid
+/// tempdir whose descriptor dir is the probe's drain root, with the
+/// launch-probe budget pinned to 1 ms. No live worker ever answers —
+/// the launch fails at the probe, after the spawn record served.
+fn spawn_record_witness(tag: &str) -> (Arc<Supervisor>, std::path::PathBuf) {
+ let dir = std::env::temp_dir().join(format!("pa-spawnrec-{tag}-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ let supervisor = Arc::new(
+ Supervisor::new(SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir,
+ })
+ .expect("supervisor"),
+ );
+ supervisor.pin_worker_connect_budget_for_tests(Duration::from_millis(1));
+ (supervisor, dir)
+}
+
+/// A known-resident registration refreshes the resident's descriptor in
+/// memory and writes nothing to disk: the spawn record stays the on-disk
+/// state until the create-completion persist owns the next durable
+/// write.
+#[tokio::test]
+async fn a_known_resident_registration_writes_nothing_to_disk() {
+ let dir = std::env::temp_dir().join(format!("pa-regskip-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ let supervisor = Arc::new(
+ Supervisor::new(SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir: agent_dir.clone(),
+ })
+ .expect("supervisor"),
+ );
+ let descriptor_path = dir.join("w-regskip.json");
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({
+ "version": 2,
+ "workerId": "w-regskip",
+ "pid": 4242,
+ "socketPath": "/tmp/w-regskip.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "reg-token",
+ "rootActiveSessionId": "w-regskip",
+ "createdAt": "2026-10-01T00:00:00Z",
+ "updatedAt": "2026-10-01T00:00:00Z",
+ "lifecycle": "starting",
+ "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ // The spawn record in the fresh-create shape (the atomic rename,
+ // no fsync), from the same descriptor value the resident owns.
+ crate::descriptor::persist_worker_at(
+ &descriptor_path,
+ &descriptor,
+ crate::descriptor::TempSync::Unsynced,
+ )
+ .expect("the spawn record lands");
+ let spawn_record = std::fs::read(&descriptor_path).expect("the spawn record is on disk");
+ let resident =
+ ResidentWorker::new("w-regskip".to_string(), descriptor, descriptor_path.clone());
+ supervisor.registry.insert(Arc::clone(&resident)).await;
+
+ let command = DaemonCommand::WorkerRegister {
+ id: None,
+ active_session_id: "w-regskip".to_string(),
+ session_id: None,
+ socket_path: "/tmp/w-regskip-live.sock".to_string(),
+ worker_instance_id: "inst-live".to_string(),
+ token: "reg-token".to_string(),
+ pid: 4242,
+ rest: Map::default(),
+ };
+ let response = supervisor
+ .handle_worker_register("r1", "worker_register", &command)
+ .await;
+ assert!(
+ response.success,
+ "the registration itself succeeds: {response:?}"
+ );
+
+ // DISK: byte-identical to the spawn record — the registration writes
+ // nothing; the create-completion persist owns the next durable state.
+ let after = std::fs::read(&descriptor_path).expect("the spawn record stays readable");
+ assert_eq!(
+ after, spawn_record,
+ "the registration must not write the descriptor"
+ );
+
+ // MEMORY: the resident's live identity still refreshes (the routing
+ // surfaces read it) — the registration is not a no-op, only its
+ // durable write is gone.
+ let descriptor = resident.descriptor.lock().await;
+ assert_eq!(descriptor.lifecycle, DaemonWorkerLifecycle::Ready);
+ assert_eq!(
+ descriptor.socket_path, "/tmp/w-regskip-live.sock",
+ "the live socket refreshes in memory"
+ );
+ assert_eq!(
+ descriptor.worker_instance_id.as_deref(),
+ Some("inst-live"),
+ "the live instance id refreshes in memory"
+ );
+}
+
+/// A relaunch REPLACES an established, already-durable descriptor, so
+/// its spawn record is the synced persist — a torn unsynced replacement
+/// could lose the descriptor's whole payload (the recovery journal
+/// pointer and the durable create command the next boot's revival
+/// replays). The oracle drives the real relaunch path; it fails at the
+/// worker probe (nothing listens on the per-test socket), after the
+/// spawn record served.
+#[tokio::test]
+async fn a_relaunch_spawn_record_serves_the_durable_persist() {
+ let (supervisor, dir) = spawn_record_witness("relaunch");
+ let descriptor_path = dir.join("w-relaunch.json");
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({
+ "version": 2,
+ "workerId": "w-relaunch",
+ "pid": 4242,
+ "socketPath": dir.join("w-relaunch.sock").to_string_lossy(),
+ "recoveryJournalPath": "/tmp/w-relaunch.recovery.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "spawnrec-token",
+ "rootActiveSessionId": "w-relaunch",
+ "createdAt": "2026-10-01T00:00:00Z",
+ "updatedAt": "2026-10-01T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ let resident = ResidentWorker::new(
+ "w-relaunch".to_string(),
+ descriptor,
+ descriptor_path.clone(),
+ );
+ supervisor.registry.insert(Arc::clone(&resident)).await;
+
+ let _ = crate::descriptor::atomic_write_probe::take_under(&descriptor_path);
+ let outcome = supervisor.relaunch_worker(&resident).await;
+ assert!(
+ outcome.is_err(),
+ "no live worker: the relaunch fails at the probe, after the spawn record served"
+ );
+ let writes = crate::descriptor::atomic_write_probe::take_under(&descriptor_path);
+ let spawn_records: Vec<_> = writes
+ .iter()
+ .filter(|(path, _)| path == &descriptor_path)
+ .collect();
+ assert!(
+ !spawn_records.is_empty(),
+ "the relaunch wrote its spawn record"
+ );
+ assert!(
+ spawn_records
+ .iter()
+ .all(|(_, sync)| matches!(sync, TempSync::Synced)),
+ "the relaunch's spawn record is the synced persist: {spawn_records:?}"
+ );
+ // The record's content is the spawn-time `Starting` state either
+ // class writes; the durability class is the probe's business.
+ let persisted: DaemonWorkerDescriptor = serde_json::from_str(
+ &std::fs::read_to_string(&descriptor_path).expect("the spawn record is readable"),
+ )
+ .expect("parse the spawn record");
+ assert_eq!(persisted.lifecycle, DaemonWorkerLifecycle::Starting);
+ assert!(persisted.pid > 0, "the spawned pid rides the record");
+}
+
+/// A fresh create's spawn record keeps the unsynced TS `persistWorker`
+/// shape (TS's `writeFileAtomicSync` fsync is opt-in and the descriptor
+/// family never requests it); the create-completion persist
+/// (`launch_worker`'s post-create write) re-establishes the durable
+/// write as the metadata-survival barrier. The oracle drives the real
+/// launch path; it fails at the worker probe (no live worker), after
+/// the spawn record served.
+#[tokio::test]
+async fn a_fresh_create_spawn_record_keeps_the_unsynced_shape() {
+ let (supervisor, dir) = spawn_record_witness("freshcreate");
+ let create = DaemonCommand::Create {
+ id: None,
+ session_path: Some(dir.join("s.jsonl").to_string_lossy().to_string()),
+ continue_recent: None,
+ no_session: None,
+ name: Some("faux".to_string()),
+ config: None,
+ telemetry_disabled: None,
+ runtime_metadata: None,
+ lifecycle: None,
+ env: None,
+ launch_env: None,
+ rest: Map::default(),
+ };
+
+ let _ = crate::descriptor::atomic_write_probe::take_under(&supervisor.descriptor_dir);
+ let outcome = supervisor.launch_worker(&create, None).await;
+ assert!(
+ outcome.is_err(),
+ "no live worker: the fresh launch fails at the probe"
+ );
+ let writes = crate::descriptor::atomic_write_probe::take_under(&supervisor.descriptor_dir);
+ let spawn_records: Vec<_> = writes
+ .iter()
+ .filter(|(path, _)| path.starts_with(&supervisor.descriptor_dir))
+ .collect();
+ assert!(
+ !spawn_records.is_empty(),
+ "the fresh create wrote its spawn record"
+ );
+ assert!(
+ spawn_records
+ .iter()
+ .all(|(_, sync)| matches!(sync, TempSync::Unsynced)),
+ "the fresh create's spawn record stays the unsynced TS shape: {spawn_records:?}"
+ );
+}
diff --git a/crates/pa-daemon/src/supervisor/supervision.rs b/crates/pa-daemon/src/supervisor/supervision.rs
index d3da85e889..e8087d7a41 100644
--- a/crates/pa-daemon/src/supervisor/supervision.rs
+++ b/crates/pa-daemon/src/supervisor/supervision.rs
@@ -3,11 +3,11 @@
use super::routing::fail_unsent_request;
use super::{
anyhow, connect_transport, create_command_payload, json, mpsc, persist_worker,
- probe_worker_socket, util, worker_connect_deadline, write_frame, Arc, Child, ClientRouting,
- Command, Context, DaemonWorkerLifecycle, Duration, Ordering, PathBuf, PrivateFrameReader,
- ResidentWorker, Result, RouteAdmission, Supervisor, TypedCreateRejection, Value, WorkerReply,
- WorkerRequest, DEFAULT_PRIVATE_FRAME_LIMITS, LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS,
- WORKER_AUTH_FLOOR_MS,
+ persist_worker_at, probe_worker_socket, util, write_frame, Arc, Child, ClientRouting, Command,
+ Context, DaemonWorkerLifecycle, Duration, Ordering, PathBuf, PrivateFrameReader,
+ ResidentWorker, Result, RouteAdmission, Supervisor, TempSync, TypedCreateRejection, Value,
+ WorkerReply, WorkerRequest, DEFAULT_PRIVATE_FRAME_LIMITS, LONG_ROUTE_TIMEOUT_MS,
+ ROUTE_TIMEOUT_MS, WORKER_AUTH_FLOOR_MS,
};
use crate::lease::is_process_alive;
use crate::registry::WorkerRelay;
@@ -240,8 +240,14 @@ impl Supervisor {
// nothing).
self.declare_compaction_terminal(resident, || resident.compaction.observe_worker_gone())
.await;
- let deadline = worker_connect_deadline();
- let child = self.spawn_worker_process(resident, deadline).await?;
+ let deadline = self.connect_deadline();
+ // The relaunch REPLACES an established, already-durable
+ // descriptor: its spawn record keeps the synced persist (the
+ // fresh create is the only launch class that rides the unsynced
+ // TS `persistWorker` shape).
+ let child = self
+ .spawn_worker_process(resident, deadline, TempSync::Synced)
+ .await?;
if let Err(error) = self.connect_worker(resident, deadline).await {
// Never leave a spawned-but-unwired worker process behind.
let mut child = child;
@@ -415,6 +421,7 @@ impl Supervisor {
self: &Arc<Self>,
resident: &Arc<ResidentWorker>,
connect_deadline: tokio::time::Instant,
+ spawn_record_sync: TempSync,
) -> Result<Child> {
// One env definition for spawn and for the update roster's
// `launch_env` row (spec §8: "env snapshot to respawn the worker
@@ -480,7 +487,20 @@ impl Supervisor {
descriptor.pid = u64::from(child_pid);
descriptor.process_start_id = crate::protocol::process_start_id(child_pid);
descriptor.lifecycle = DaemonWorkerLifecycle::Starting;
- let _ = persist_worker(&resident.descriptor_path, &descriptor);
+ // The spawn record's durability is per launch class
+ // (`spawn_record_sync`): a fresh create rides the TS
+ // `persistWorker` shape — the atomic rename without the
+ // pre-rename fsync (TS's `writeFileAtomicSync` fsync is
+ // opt-in and the descriptor family never requests it) — and
+ // the create-completion persist (`launch_worker`'s
+ // post-create write) re-establishes the durable write as the
+ // metadata-survival barrier. A relaunch REPLACES an
+ // established, already-durable descriptor: it keeps the
+ // synced persist, because a torn unsynced replacement would
+ // lose the descriptor's whole payload — the recovery journal
+ // pointer and the durable create command the next boot's
+ // revival replays.
+ let _ = persist_worker_at(&resident.descriptor_path, &descriptor, spawn_record_sync);
}
// Probe the worker socket until it accepts connections. A worker that
diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
index c6abfbe11d..20c53c811f 100644
--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
@@ -12,7 +12,7 @@ use super::{
anyhow, create_command_payload, json, persist_worker, socket, util, Arc, Context,
DaemonCommand, DaemonWorkerDescriptor, DaemonWorkerLifecycle, DurableDaemonCreateCommand,
Duration, EngineModelSelection, Map, Ordering, Path, ResidentWorker, Result, RouteAdmission,
- Supervisor, TypedCreateRejection, Value, LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS,
+ Supervisor, TempSync, TypedCreateRejection, Value, LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS,
};
use crate::lease::is_process_alive;
use crate::protocol::{response_failure, response_success, DaemonResponse};
@@ -329,11 +329,16 @@ impl Supervisor {
// self-registers on boot, and the registration handler must find its
// identity in the registry (registration races the create replay).
self.registry.insert(Arc::clone(&resident)).await;
- let deadline = worker_connect_deadline();
+ let deadline = self.connect_deadline();
// A failed launch never leaves its half-registered resident behind:
// a later stale-id rebind (or resolve) must not select a worker
- // that cannot route.
- let child = match self.spawn_worker_process(&resident, deadline).await {
+ // that cannot route. The spawn record rides the unsynced TS
+ // `persistWorker` shape on this fresh create (the relaunch paths
+ // keep the synced persist).
+ let child = match self
+ .spawn_worker_process(&resident, deadline, TempSync::Unsynced)
+ .await
+ {
Ok(child) => child,
Err(error) => {
self.registry.remove(&worker_id).await;
@@ -925,6 +930,33 @@ pub(super) fn worker_connect_deadline() -> tokio::time::Instant {
.unwrap_or_else(|| now + Duration::from_millis(DEFAULT_WORKER_CONNECT_TIMEOUT_MS))
}
+impl Supervisor {
+ /// The launch-probe deadline: the supervisor's pinned budget when
+ /// one is set, else the process-wide env seam.
+ pub(super) fn connect_deadline(&self) -> tokio::time::Instant {
+ let budget = *self
+ .worker_connect_budget
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ match budget {
+ Some(budget) => tokio::time::Instant::now() + budget,
+ None => worker_connect_deadline(),
+ }
+ }
+
+ /// Test-only: pin this supervisor's launch-probe budget so a launch
+ /// oracle fails its probe immediately without mutating the
+ /// process-wide env var (a set value would leak into every parallel
+ /// test's launch).
+ #[cfg(test)]
+ pub(crate) fn pin_worker_connect_budget_for_tests(&self, budget: Duration) {
+ *self
+ .worker_connect_budget
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(budget);
+ }
+}
+
/// The real graceful-stop transport (spec §5 `Stopping`): the routed
/// `shutdown` request - the worker's handler is the flush barrier (it
/// persists the recovery journal and finalizes telemetry before replying) -