Skip to main content

mj_controller/controller/
provisioning.rs

1//! Session provisioning, rollback, and worker-side Git bootstrap.
2
3use std::collections::{BTreeMap, HashMap};
4use std::path::{Path, PathBuf};
5use std::process::{Command, Stdio};
6use std::sync::{Arc, Mutex, OnceLock};
7use std::time::Instant;
8
9use anyhow::{Context, Result, bail, ensure};
10
11use mj_core::config::{TargetTemplate, atomic_write, data_dir};
12use mj_core::state::{SessionState, State, TargetLocator};
13
14use crate::targets::{
15    self, CommandExecutor, CommandOutput, CommandSpec, ProvisionStage, ProvisionStageGuard,
16};
17
18use super::backend::{
19    ContainerOverrides, TargetCheck, backend_locator, backend_session_bundle, backend_target,
20    configure_github_token_environment, preflight_target, use_github_https_urls,
21};
22use super::git_cache;
23use super::readiness::{connect_started_worker, wait_for_native_session_in_stage};
24use super::worker_binary::{bridge_readiness_stage, start_worker_durably, worker_probe_diagnosis};
25use super::{Controller, execute_checked, now};
26
27const INHERITED_GIT_SETTINGS: &[&str] = &[
28    "diff.algorithm",
29    "fetch.prune",
30    "fetch.prunetags",
31    "init.defaultbranch",
32    "merge.conflictstyle",
33    "pull.ff",
34    "pull.rebase",
35    "push.autosetupremote",
36    "push.default",
37    "rebase.autostash",
38    "rerere.autoupdate",
39    "rerere.enabled",
40    "user.email",
41    "user.name",
42];
43
44/// How many sub-agent children may be brought up inside one container at the
45/// same time.
46///
47/// Starting a child means starting a harness, and a harness start inside a
48/// container is expensive, especially while its reviewer is active. Measured
49/// on a local Podman
50/// target, ten children started one after another each reached their harness
51/// in about seven seconds, while four started at once left two or three of
52/// them past the 300-second harness-startup wait. Admitting two at a time
53/// keeps a burst slower but finished, instead of fast and failed.
54const CONTAINER_START_ADMISSION: usize = 2;
55
56/// The admission gate for one container, created on first use.
57///
58/// Keyed by the container the children share. A bare target has no gate: a
59/// child there is an ordinary process on a whole machine, and twenty
60/// sequential and four concurrent starts measured 2.8 seconds each.
61pub(super) fn container_start_gate(
62    locator: &targets::TargetLocator,
63) -> Option<Arc<tokio::sync::Semaphore>> {
64    static GATES: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Semaphore>>>> = OnceLock::new();
65    let container = match locator {
66        targets::TargetLocator::LocalPodman { container_id, .. }
67        | targets::TargetLocator::LocalDocker { container_id, .. }
68        | targets::TargetLocator::AppleContainer { container_id, .. }
69        | targets::TargetLocator::SshPodman { container_id, .. }
70        | targets::TargetLocator::SshDocker { container_id, .. } => container_id.clone(),
71        targets::TargetLocator::LocalBare { .. }
72        | targets::TargetLocator::SshBare { .. }
73        | targets::TargetLocator::AwsEc2 { .. } => return None,
74    };
75    let gates = GATES.get_or_init(|| Mutex::new(HashMap::new()));
76    let mut gates = gates
77        .lock()
78        .unwrap_or_else(std::sync::PoisonError::into_inner);
79    Some(Arc::clone(gates.entry(container).or_insert_with(|| {
80        Arc::new(tokio::sync::Semaphore::new(CONTAINER_START_ADMISSION))
81    })))
82}
83
84/// Whether starting a child worker can be tried again.
85///
86/// Only a worker that provably never published its control socket qualifies:
87/// it owns no relay, no journal and no harness, so a second start cannot
88/// duplicate or corrupt work. A refusal is never retried, because it names a
89/// precondition that a second attempt would meet in exactly the same way, and
90/// a cancelled operation is not retried either.
91fn subagent_start_is_retryable(error: &anyhow::Error) -> bool {
92    if mj_core::refusal::Refusal::of(error).is_some() {
93        return false;
94    }
95    if format!("{error:#}").contains("operation cancelled") {
96        return false;
97    }
98    error
99        .downcast_ref::<super::readiness::WorkerStartupFailure>()
100        .is_some_and(|failure| !failure.reached_socket)
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(super) enum ProvisioningFailureDisposition {
105    /// A freshly registered session has no durable history to retain.
106    Discard,
107    /// Resume owns rollback to the archived record and checkpoint lineage.
108    Preserve,
109}
110
111impl Controller {
112    pub async fn provision_session_controlled_with_commit(
113        &mut self,
114        session_id: &str,
115        executor: &(impl CommandExecutor + Sync),
116        grant_commit: impl FnOnce() -> Result<()>,
117    ) -> Result<()> {
118        crate::worker_lifecycle::run(
119            session_id,
120            "provision session controlled with commit",
121            executor,
122            async {
123                crate::worker_lifecycle::require(session_id)?.verify_cached_target(&self.state)?;
124                let github_token = self
125                    .github_token_for_session(session_id)
126                    .await
127                    .context("resolve GitHub credentials for session")?;
128                let repositories = self
129                    .provision_session_target_with_failure_disposition(
130                        session_id,
131                        executor,
132                        github_token.as_deref(),
133                        ProvisioningFailureDisposition::Discard,
134                    )
135                    .await?;
136                let setup = execute_concurrent_lanes(
137                    || execute_repository_setup(&repositories, executor),
138                    || self.install_worker_payload(session_id, executor),
139                );
140                let result = match setup {
141                    Ok(((), (backend, worker_root))) => {
142                        self.connect_and_start_worker(
143                            session_id,
144                            executor,
145                            &backend,
146                            &worker_root,
147                            true,
148                        )
149                        .await
150                    }
151                    Err(error) => Err(error),
152                };
153                match result {
154                    Ok(native_session_id) => {
155                        if let Err(error) = grant_commit() {
156                            return Err(self.rollback_failed_new_session(session_id, error)?);
157                        }
158                        self.mark_worker_connected(session_id, native_session_id)
159                    }
160                    Err(error) => Err(self.rollback_failed_new_session(session_id, error)?),
161                }
162            },
163        )
164        .await
165    }
166
167    /// Start a child worker inside an already-provisioned parent target.
168    /// Repository, target, and mount setup belong exclusively to the parent.
169    pub async fn provision_subagent_session_controlled(
170        &mut self,
171        session_id: &str,
172        executor: &(impl CommandExecutor + Sync),
173    ) -> Result<()> {
174        crate::worker_lifecycle::run(
175            session_id,
176            "provision subagent session controlled",
177            executor,
178            async {
179                crate::worker_lifecycle::require(session_id)?.verify_cached_target(&self.state)?;
180                // One retry, and only for a worker that provably never published a
181                // control socket. Such a worker has no relay, no durable journal and
182                // no harness, so starting another over the same root cannot duplicate
183                // or corrupt anything. A spawn is issued by a model that cannot see
184                // the target, so a transient start failure it could have retried by
185                // hand is better retried here.
186                let mut attempts: Vec<String> = Vec::new();
187                loop {
188                    let (result, placement) =
189                        self.attempt_subagent_start(session_id, executor).await;
190                    let error = match result {
191                        Ok(native_session_id) => {
192                            return self.mark_worker_connected(session_id, native_session_id);
193                        }
194                        Err(error) => error,
195                    };
196                    let retry = attempts.is_empty() && subagent_start_is_retryable(&error);
197                    let error = match &placement {
198                        Some((backend, _)) => super::subagent_park::explain_process_exhaustion(
199                            error, backend, session_id,
200                        ),
201                        None => error,
202                    };
203                    attempts.push(format!("{error:#}"));
204                    let error = if attempts.len() > 1 {
205                        anyhow::anyhow!(
206                            "{}",
207                            attempts
208                                .iter()
209                                .enumerate()
210                                .map(|(index, error)| format!("attempt {}: {error}", index + 1))
211                                .collect::<Vec<_>>()
212                                .join("; ")
213                        )
214                    } else {
215                        error
216                    };
217                    let diagnostic = note_new_session_launch_failure(session_id, &error);
218                    let previous = self
219                        .state
220                        .sessions
221                        .get(session_id)
222                        .context("failed child disappeared")?
223                        .clone();
224                    let record = self.state.sessions.get_mut(session_id).unwrap();
225                    record.state = SessionState::StartupCleanup;
226                    record.updated_at = now();
227                    record.last_error = Some(format!("sub-agent startup failed: {diagnostic}"));
228                    self.persist_session_transition_or_restore(
229                        session_id,
230                        &previous,
231                        "record failed startup before teardown",
232                    )?;
233                    let cleanup = super::failed_launch_cleanup_executor();
234                    if let Err(cleanup_error) =
235                        self.finish_failed_startup_controlled(session_id, &cleanup, retry)
236                    {
237                        return Err(error.context(format!(
238                            "startup cleanup remains pending: {cleanup_error:#}"
239                        )));
240                    }
241                    if !retry {
242                        return Err(error);
243                    }
244                    tracing::warn!(
245                        session_id,
246                        error = format!("{error:#}"),
247                        "sub-agent worker never started and was stopped; retrying once"
248                    );
249                }
250            },
251        )
252        .await
253    }
254
255    /// Finish a failed startup without reopening its relay or replaying work.
256    pub(crate) fn cleanup_failed_startup_controlled(
257        &mut self,
258        session_id: &str,
259        executor: &impl CommandExecutor,
260    ) -> Result<()> {
261        self.finish_failed_startup_controlled(session_id, executor, false)
262    }
263
264    fn finish_failed_startup_controlled(
265        &mut self,
266        session_id: &str,
267        executor: &impl CommandExecutor,
268        retry_after_stop: bool,
269    ) -> Result<()> {
270        crate::worker_lifecycle::run_blocking(
271            session_id,
272            "finish failed startup controlled",
273            executor,
274            || {
275                let previous = self
276                    .state
277                    .sessions
278                    .get(session_id)
279                    .context("cleanup session disappeared")?
280                    .clone();
281                ensure!(
282                    previous.state == SessionState::StartupCleanup,
283                    "session is not awaiting startup cleanup"
284                );
285                let child = self.state.subagents.contains_key(session_id);
286                ensure!(
287                    !retry_after_stop || child,
288                    "only unaccepted child startup may retry"
289                );
290                let outcome = (|| -> Result<()> {
291                    if let Some(locator) = &previous.target {
292                        let backend = backend_locator(locator, &previous, &self.config)?;
293                        if child {
294                            let root = targets::worker_root(&backend, session_id)?;
295                            super::worker_binary::stop_worker(
296                                &crate::worker_lifecycle::require(session_id)?,
297                                executor,
298                                &backend,
299                                &root,
300                            )?;
301                        } else {
302                            targets::close_plan(&backend, session_id)?.execute(executor)?;
303                        }
304                    }
305                    if !child {
306                        self.cleanup_new_session_worktree_after_failure(session_id, executor)?;
307                    }
308                    Ok(())
309                })();
310                let record = self.state.sessions.get_mut(session_id).unwrap();
311                record.updated_at = now();
312                let cause = previous
313                    .last_error
314                    .as_deref()
315                    .unwrap_or("startup failed")
316                    .split("; startup cleanup failed:")
317                    .next()
318                    .unwrap()
319                    .to_owned();
320                match &outcome {
321                    Ok(()) => {
322                        record.state = if retry_after_stop {
323                            SessionState::Provisioning
324                        } else {
325                            SessionState::Error
326                        };
327                        record.last_error = (!retry_after_stop).then_some(cause);
328                        if !child {
329                            record.target = None;
330                        }
331                    }
332                    Err(error) => {
333                        record.last_error =
334                            Some(format!("{cause}; startup cleanup failed: {error:#}"));
335                    }
336                }
337                let record = self.state.sessions.get_mut(session_id).unwrap();
338                if outcome.is_ok() && child && !retry_after_stop {
339                    record.archived = true;
340                }
341                if let Err(error) = crate::database::save_startup_cleanup_outcome(
342                    record,
343                    outcome.is_ok() && child && !retry_after_stop,
344                ) {
345                    self.state.sessions.insert(session_id.to_owned(), previous);
346                    return Err(error).context("record startup cleanup outcome");
347                }
348                outcome
349            },
350        )
351    }
352
353    /// One start of a child worker: place it, install its files, and wait for
354    /// its relay. The placement is returned even on failure, because the
355    /// caller needs it to stop a worker that may be half up.
356    async fn attempt_subagent_start(
357        &mut self,
358        session_id: &str,
359        executor: &(impl CommandExecutor + Sync),
360    ) -> (
361        Result<Option<String>>,
362        Option<(targets::TargetLocator, String)>,
363    ) {
364        // Placement failures must reach the same failure arm as startup
365        // failures; otherwise the child record stays `Provisioning` forever.
366        match self.worker_placement(session_id) {
367            Ok((backend, worker_root)) => {
368                let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
369                let prepared = self
370                    .prepare_worker_files(session_id, &backend, &worker_root, syncing)
371                    .and_then(|()| self.prepare_subagent_report_dir(session_id, &backend, syncing));
372                let result = match prepared {
373                    Ok(()) => {
374                        // Held across the harness startup wait, which is the
375                        // part that does not survive a crowd.
376                        let gate = container_start_gate(&backend);
377                        let _admitted = match &gate {
378                            Some(gate) => gate.acquire().await.ok(),
379                            None => None,
380                        };
381                        self.connect_and_start_worker(
382                            session_id,
383                            executor,
384                            &backend,
385                            &worker_root,
386                            false,
387                        )
388                        .await
389                    }
390                    Err(error) => Err(error),
391                };
392                (result, Some((backend, worker_root)))
393            }
394            Err(error) => (Err(error), None),
395        }
396    }
397
398    fn rollback_failed_new_session(
399        &mut self,
400        session_id: &str,
401        error: anyhow::Error,
402    ) -> Result<anyhow::Error> {
403        self.rollback_failed_new_session_with(
404            session_id,
405            error,
406            // Rollback must remain possible after the foreground operation's
407            // cancellation token has been set.
408            &super::failed_launch_cleanup_executor(),
409        )
410    }
411
412    fn rollback_failed_new_session_with(
413        &mut self,
414        session_id: &str,
415        error: anyhow::Error,
416        target_cleanup_executor: &impl CommandExecutor,
417    ) -> Result<anyhow::Error> {
418        let session = self
419            .state
420            .sessions
421            .get(session_id)
422            .with_context(|| format!("unknown session {session_id}"))?
423            .clone();
424        // The failure goes on record before anything the record points at is
425        // removed. Removing the worker and its checkout can outlast a daemon
426        // that is stopping, and a daemon that exits partway would otherwise
427        // leave a record naming a worker that no longer exists, which every
428        // later daemon keeps reconnecting to. A failed record that still
429        // names its target is one Destroy knows how to clean up.
430        let original = note_new_session_launch_failure(session_id, &error);
431        apply_failed_new_session_launch(&mut self.state, session_id, &original);
432        self.persist_session_transition_or_restore(
433            session_id,
434            &session,
435            "record the failed launch before removing its target",
436        )
437        .map_err(|persist_error| {
438            persist_error.context(format!(
439                "{original}; its target was left in place because the failure could not be recorded"
440            ))
441        })?;
442        let target_cleanup = match session.target.as_ref() {
443            Some(locator) => (|| -> Result<()> {
444                let backend = backend_locator(locator, &session, &self.config)?;
445                targets::close_plan(&backend, session_id)?
446                    .execute(target_cleanup_executor)
447                    .map(|_| ())
448            })(),
449            None => Ok(()),
450        };
451        // A failed stop leaves the harness able to write its checkout. Keep
452        // that checkout until a later cleanup confirms process termination.
453        let cleanup_error = target_cleanup
454            .and_then(|()| {
455                self.cleanup_new_session_worktree_after_failure(session_id, target_cleanup_executor)
456            })
457            .err()
458            .map(|error| format!("{error:#}"));
459        if let Some(cleanup_error) = &cleanup_error {
460            tracing::warn!(
461                session_id,
462                error = %cleanup_error,
463                "new-session rollback cleanup reported failures"
464            );
465        }
466        let failure = apply_failed_new_session_rollback(
467            &mut self.state,
468            session_id,
469            &original,
470            cleanup_error,
471        );
472        self.persist_session_state(session_id)?;
473        Ok(failure)
474    }
475
476    pub(super) async fn provision_session_with_failure_disposition(
477        &mut self,
478        session_id: &str,
479        executor: &(impl CommandExecutor + Sync),
480        github_token: Option<&str>,
481        failure_disposition: ProvisioningFailureDisposition,
482    ) -> Result<()> {
483        let repositories = self
484            .provision_session_target_with_failure_disposition(
485                session_id,
486                executor,
487                github_token,
488                failure_disposition,
489            )
490            .await?;
491        match execute_repository_setup(&repositories, executor) {
492            Ok(()) => Ok(()),
493            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
494                Err(self.rollback_failed_new_session(session_id, error)?)
495            }
496            Err(error) => Err(error),
497        }
498    }
499
500    async fn provision_session_target_with_failure_disposition(
501        &mut self,
502        session_id: &str,
503        executor: &(impl CommandExecutor + Sync),
504        github_token: Option<&str>,
505        failure_disposition: ProvisioningFailureDisposition,
506    ) -> Result<targets::CommandPlan> {
507        crate::worker_lifecycle::run(session_id, "provision session target with failure disposition", executor, async {
508        let session = self
509            .state
510            .sessions
511            .get(session_id)
512            .with_context(|| format!("unknown session {session_id}"))?
513            .clone();
514        if session.state != SessionState::Provisioning {
515            bail!("session {session_id} is not provisioning");
516        }
517        if let Some(plan) = self.adopt_prepared_ec2_destination(session_id)? {
518            return Ok(plan);
519        }
520        let preparation = (|| {
521            let selected = self
522                .config
523                .targets
524                .get(&session.target_template_id)
525                .context("target template disappeared before provisioning")?;
526            // Before the runtime is recorded, so a container never starts
527            // without an entry whose secret is missing.
528            selected.ensure_ready(&session.target_template_id)?;
529            self.config
530                .profiles
531                .get(&session.last_profile)
532                .context("harness profile disappeared before provisioning")?
533                .ensure_ready(&session.last_profile)?;
534            let runtime = mj_core::state::TargetRuntimeSettings::from(selected);
535            if let Some(recorded) = &session.target_runtime {
536                ensure!(
537                    recorded == &runtime,
538                    "target access settings changed before provisioning; retry with the selected target"
539                );
540            } else {
541                self.state
542                    .sessions
543                    .get_mut(session_id)
544                    .unwrap()
545                    .target_runtime = Some(runtime);
546                self.persist_session_state(session_id)?;
547            }
548            let template = self
549                .config
550                .targets
551                .get(&session.target_template_id)
552                .context("target template disappeared during provisioning")?;
553            let profile = self
554                .config
555                .profiles
556                .get(&session.last_profile)
557                .context("harness profile disappeared during provisioning")?;
558            super::worker_binary::preflight_worker_binary(template, executor)?;
559            super::worker_binary::preflight_harness(template, profile, executor)?;
560            self.prepare_managed_raw_worktree(session_id, executor)
561        })();
562        let created_worktree = match preparation {
563            Ok(created) => created,
564            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
565                return Err(self.fail_new_session_with_cleanup(session_id, error, executor)?);
566            }
567            Err(error) => return Err(error),
568        };
569        let session = self
570            .state
571            .sessions
572            .get(session_id)
573            .expect("session retained after managed worktree preparation")
574            .clone();
575        // Keep planning, preflight, creation, and locator discovery in one
576        // result so the caller's failure disposition applies to every error.
577        let result = (|| {
578            let template = self
579                .config
580                .targets
581                .get(&session.target_template_id)
582                .context("target template disappeared during provisioning")?;
583            if matches!(template, TargetTemplate::AwsEc2 { .. }) {
584                for resource in &session.additional_mounts {
585                    ensure!(
586                        resource.source.is_dir(),
587                        "attached resource source is not a directory: {}",
588                        resource.source.display()
589                    );
590                }
591            }
592            let mut target = backend_target(
593                template,
594                session.resource_allocation.as_ref(),
595                ContainerOverrides::for_session(&session),
596            )?;
597            let mut runtime_mounts = if matches!(target, targets::TargetTemplate::AwsEc2(_)) {
598                Vec::new()
599            } else {
600                session.additional_mounts.clone()
601            };
602            // The mounts this container runs with, not the ones the session
603            // stores: a forced downgrade belongs to the host the container
604            // lands on, so it is decided here every time and never written
605            // over the user's choice.
606            for notice in enforce_overlay_capable_mounts(&target, &mut runtime_mounts, executor) {
607                executor.notify_notice(&notice);
608            }
609            let mut bundle = if session.project_directory.is_some() {
610                None
611            } else if let Some(bundle) = self.move_destination_bundle(session_id)? {
612                Some(bundle)
613            } else if failure_disposition == ProvisioningFailureDisposition::Preserve {
614                Some(super::network_git::checkpoint_bundle(&session)?)
615            } else {
616                Some(backend_session_bundle(&session, &self.config, executor)?)
617            };
618            let container_github_token =
619                github_token.filter(|_| configure_github_token_environment(&mut target));
620            if container_github_token.is_some()
621                && let Some(bundle) = bundle.as_mut()
622            {
623                use_github_https_urls(bundle);
624            }
625            preflight_target(template, executor, TargetCheck::Launch)?;
626            let resource_name = crate::database::load_move_operation(session_id)?
627                .filter(|op| {
628                    op.workspace_transfer.is_some()
629                        && op.phase == mj_core::state::MovePhase::ResumingDestination
630                })
631                .map(|op| targets::move_resource_name(session_id, &op.operation_id))
632                .unwrap_or_else(|| targets::resource_name(session_id))?;
633            let moving_workspace = resource_name != targets::resource_name(session_id)?;
634            let prepared_cache = bundle
635                .as_mut()
636                .filter(|_| !moving_workspace)
637                .and_then(|bundle| {
638                    git_cache::prepare(
639                        &target,
640                        session_id,
641                        bundle,
642                        &mut runtime_mounts,
643                        container_github_token,
644                        executor,
645                    )
646                });
647            // Mounts are fixed when the container is created, so the build
648            // cache is decided here, before the provisioning plan is built.
649            let build_cache = super::mbx::prepare(
650                &target,
651                &session,
652                bundle.as_ref(),
653                prepared_cache.as_ref(),
654                &mut runtime_mounts,
655                executor,
656            );
657            let provision = if let Some(project_directory) = &session.project_directory {
658                targets::provision_bare_project_plan(
659                    &target,
660                    session_id,
661                    &project_directory.to_string_lossy(),
662                )
663            } else {
664                bundle
665                    .as_ref()
666                    .context("project bundle disappeared during provisioning")
667                    .and_then(|bundle| {
668                        targets::provision_plan_named(
669                            &target,
670                            session_id,
671                            bundle,
672                            &runtime_mounts,
673                            session.container_workspace.as_deref(),
674                            &resource_name,
675                        )
676                    })
677            };
678            let mut provision = match provision {
679                Ok(provision) => provision,
680                Err(error) => {
681                    if let Some(cache) = &prepared_cache {
682                        let _ = cache.cleanup(executor);
683                    }
684                    return Err(error);
685                }
686            };
687            if let Some(token) = container_github_token
688                && let Err(error) =
689                    provision.provide_target_environment_secret(&target, "GH_TOKEN", token)
690            {
691                if let Some(cache) = &prepared_cache {
692                    let _ = cache.cleanup(executor);
693                }
694                return Err(error);
695            }
696
697            let started = Instant::now();
698            let result = provision_target_creation_named(
699                &provision,
700                &target,
701                session_id,
702                executor,
703                &resource_name,
704                |outputs| {
705                    super::backend::locator_after_provision_named(
706                        template,
707                        &target,
708                        session_id,
709                        outputs.first(),
710                        executor,
711                        &resource_name,
712                    )
713                },
714            )
715            .map(|(locator, remainder)| (locator, remainder, bundle, build_cache));
716            if result.is_err()
717                && let Some(cache) = &prepared_cache
718            {
719                if let Some(locator) =
720                    provisioned_locator_named(&target, session_id, None, &resource_name)
721                {
722                    let _ = targets::close_plan(&locator, session_id)
723                        .and_then(|plan| plan.execute(executor).map(|_| ()));
724                } else {
725                    let _ = cache.cleanup(executor);
726                }
727            }
728            tracing::debug!(
729                session_id,
730                elapsed_ms = started.elapsed().as_millis(),
731                "provisioning plan execution completed"
732            );
733            result
734        })();
735        let result = match result {
736            Err(error)
737                if created_worktree
738                    && failure_disposition == ProvisioningFailureDisposition::Discard =>
739            {
740                return Err(self.fail_new_session_with_cleanup(session_id, error, executor)?);
741            }
742            Err(error) if failure_disposition == ProvisioningFailureDisposition::Preserve => {
743                Err(error)
744            }
745            Err(error) => {
746                // This arm (no managed worktree to unwind) is the one a
747                // provisioning failure such as a dropped target connection
748                // hits; record the diagnostic and the session-id log here too.
749                let detail = note_new_session_launch_failure(session_id, &error);
750                {
751                    let record = self.state.sessions.get_mut(session_id).unwrap();
752                    record.state = SessionState::Error;
753                    record.target = None;
754                    record.updated_at = super::now();
755                    record.last_error = Some(format!("session provisioning failed: {detail}"));
756                }
757                return match self.persist_session_state(session_id) {
758                    Ok(()) => Err(error),
759                    Err(persistence_error) => Err(error.context(format!(
760                        "persist removal of failed provisioning session {session_id}: {persistence_error:#}"
761                    ))),
762                };
763            }
764            Ok((locator, remainder, bundle, build_cache)) => {
765                apply_new_session_provisioning_result(&mut self.state, session_id, Ok(locator))?;
766                self.state
767                    .sessions
768                    .get_mut(session_id)
769                    .expect("session retained after provisioning")
770                    .build_cache = build_cache;
771                let session = &self.state.sessions[session_id];
772                let backend = backend_locator(
773                    session
774                        .target
775                        .as_ref()
776                        .context("provisioned target disappeared")?,
777                    session,
778                    &self.config,
779                )?;
780                if matches!(backend, targets::TargetLocator::AwsEc2 { .. }) {
781                    targets::provision_on_locator_plan(
782                        &backend,
783                        session_id,
784                        bundle
785                            .as_ref()
786                            .context("AWS provisioning requires a project bundle")?,
787                    )
788                } else {
789                    Ok(remainder)
790                }
791            }
792        };
793        let result = match result {
794            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
795                return Err(self.rollback_failed_new_session(session_id, error)?);
796            }
797            result => result,
798        };
799        if result.is_ok()
800            && let Some(session) = self.state.sessions.get(session_id)
801            && let Some(directory) = session
802                .managed_worktree
803                .as_ref()
804                .map(|worktree| worktree.source_project_directory.clone())
805                .or_else(|| session.project_directory.clone())
806            && let Some(template) = self.config.targets.get(&session.target_template_id)
807        {
808            let host = match template {
809                TargetTemplate::LocalBare => Some("local"),
810                TargetTemplate::SshBare { ssh, .. } => Some(ssh.host.as_str()),
811                _ => None,
812            };
813            if let Some(host) = host {
814                self.state.remember_project_directory(host, &directory);
815                crate::database::remember_project_directory(host, &directory)?;
816            }
817        }
818        self.persist_session_state(session_id)?;
819        result
820
821        }).await
822    }
823
824    pub fn mark_worker_connected(
825        &mut self,
826        session_id: &str,
827        native_session_id: Option<String>,
828    ) -> Result<()> {
829        let session = self
830            .state
831            .sessions
832            .get(session_id)
833            .with_context(|| format!("unknown session {session_id}"))?;
834        if session.target.is_none() {
835            bail!("session {session_id} has no provisioned target");
836        }
837        let updated_at = now();
838        crate::database::mark_session_worker_connected(
839            session_id,
840            native_session_id.as_deref(),
841            &updated_at,
842        )?;
843        let session = self
844            .state
845            .sessions
846            .get_mut(session_id)
847            .expect("session disappeared after its worker connection was saved");
848        session.state = SessionState::Running;
849        if native_session_id.is_some() {
850            session.native_session_id = native_session_id;
851        }
852        session.updated_at = updated_at;
853        session.last_error = None;
854        Ok(())
855    }
856
857    fn install_worker_payload(
858        &self,
859        session_id: &str,
860        executor: &impl CommandExecutor,
861    ) -> Result<(targets::TargetLocator, String)> {
862        // Worker/profile installation is independent of repository cloning.
863        let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
864        let (backend, worker_root) = self.worker_placement(session_id)?;
865        self.prepare_worker_files(session_id, &backend, &worker_root, syncing)?;
866        install_attached_resources(&self.state, session_id, &backend, &worker_root, syncing)?;
867        Ok((backend, worker_root))
868    }
869
870    async fn connect_and_start_worker(
871        &self,
872        session_id: &str,
873        executor: &impl CommandExecutor,
874        backend: &targets::TargetLocator,
875        worker_root: &str,
876        initialize_workspace: bool,
877    ) -> Result<Option<String>> {
878        crate::worker_lifecycle::run(session_id, "connect and start worker", executor, async {
879            let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
880            if initialize_workspace {
881                install_inherited_git_settings(executor, backend, session_id)?;
882                self.initialize_network_workspaces(session_id, backend, syncing)?;
883            }
884            let session = self
885                .state
886                .sessions
887                .get(session_id)
888                .with_context(|| format!("unknown session {session_id}"))?;
889            let profile = self
890                .config
891                .profiles
892                .get(&session.last_profile)
893                .with_context(|| format!("unknown profile {}", session.last_profile))?;
894            let readiness_stage = bridge_readiness_stage(profile);
895            let reconnect = &targets::reconnect_plan(backend, session_id)?.commands[0];
896            let readiness = async {
897                let mut relay = {
898                    let _starting = ProvisionStageGuard::new(executor, ProvisionStage::Starting);
899                    start_worker_durably(
900                        &crate::worker_lifecycle::require(session_id)?,
901                        self.state.sessions[session_id]
902                            .target
903                            .as_ref()
904                            .context("worker start has no durable target")?,
905                        executor,
906                        backend,
907                        worker_root,
908                    )?;
909                    connect_started_worker(reconnect, session_id, executor, backend, worker_root)
910                        .await?
911                };
912                let native_session_id = wait_for_native_session_in_stage(
913                    &mut relay,
914                    executor,
915                    readiness_stage,
916                    profile.kind,
917                )
918                .await?;
919                let owner = crate::worker_lifecycle::require(session_id)?;
920                crate::database::finish_worker_restart(session_id, owner.operation_id())?;
921                Ok(Some(native_session_id))
922            }
923            .await;
924            match readiness {
925                Ok(native_session_id) => Ok(native_session_id),
926                Err(error) => {
927                    // The diagnosis reads the worker's state, so it runs before the
928                    // worker is stopped.
929                    let error = worker_probe_diagnosis(executor, backend, worker_root, error);
930                    Err(error)
931                }
932            }
933        })
934        .await
935    }
936}
937
938const MAX_LAUNCH_DIAGNOSTIC_BYTES: usize = 64 * 1024;
939
940const RETAINED_LAUNCH_DIAGNOSTICS: usize = 20;
941
942/// Record a failed new-session launch consistently across every failure arm:
943/// log the failure with the session id (so `logs/mj-*.log` names the session)
944/// and save the local diagnostic file. Returns the underlying error chain
945/// annotated with the diagnostic path, which the caller stores in `last_error`
946/// so the reason travels to `mj sessions`, `mj wait`, and `mj events`.
947pub(super) fn note_new_session_launch_failure(session_id: &str, error: &anyhow::Error) -> String {
948    note_new_session_launch_failure_in(&data_dir().join("diagnostics"), session_id, error)
949}
950
951fn note_new_session_launch_failure_in(
952    directory: &Path,
953    session_id: &str,
954    error: &anyhow::Error,
955) -> String {
956    let original = format!("{error:#}");
957    tracing::warn!(session_id, error = %original, "session launch failed");
958    match persist_launch_failure_to(directory, session_id, &original) {
959        Ok(path) => format!("{original}; full diagnostic saved to {}", path.display()),
960        Err(save_error) => {
961            format!("{original}; saving the local diagnostic failed: {save_error:#}")
962        }
963    }
964}
965
966fn persist_launch_failure_to(directory: &Path, session_id: &str, detail: &str) -> Result<PathBuf> {
967    mj_core::config::validate_id("session", session_id)?;
968    std::fs::create_dir_all(directory).with_context(|| {
969        format!(
970            "create launch diagnostics directory {}",
971            directory.display()
972        )
973    })?;
974    #[cfg(unix)]
975    {
976        use std::os::unix::fs::PermissionsExt;
977        std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))?;
978    }
979    let path = directory.join(format!("{session_id}-launch-error.txt"));
980    let detail = bounded_launch_diagnostic(detail);
981    let body = format!(
982        "Mjolnir session launch failure\nsession: {session_id}\nat: {}\n\n{detail}\n",
983        now()
984    );
985    atomic_write(&path, body.as_bytes())?;
986    prune_launch_diagnostics(directory)?;
987    Ok(path)
988}
989
990fn bounded_launch_diagnostic(detail: &str) -> String {
991    if detail.len() <= MAX_LAUNCH_DIAGNOSTIC_BYTES {
992        return detail.to_owned();
993    }
994    let mut head_end = MAX_LAUNCH_DIAGNOSTIC_BYTES / 4;
995    while !detail.is_char_boundary(head_end) {
996        head_end -= 1;
997    }
998    let tail_bytes = MAX_LAUNCH_DIAGNOSTIC_BYTES - head_end;
999    let mut tail_start = detail.len() - tail_bytes;
1000    while !detail.is_char_boundary(tail_start) {
1001        tail_start += 1;
1002    }
1003    format!(
1004        "{}\n\n[... launch diagnostic truncated ...]\n\n{}",
1005        &detail[..head_end],
1006        &detail[tail_start..]
1007    )
1008}
1009
1010fn prune_launch_diagnostics(directory: &Path) -> Result<()> {
1011    let mut diagnostics = Vec::new();
1012    for entry in std::fs::read_dir(directory)? {
1013        let entry = entry?;
1014        if !entry
1015            .file_name()
1016            .to_str()
1017            .is_some_and(|name| name.ends_with("-launch-error.txt"))
1018        {
1019            continue;
1020        }
1021        diagnostics.push((entry.metadata()?.modified()?, entry.path()));
1022    }
1023    diagnostics.sort_by_key(|entry| std::cmp::Reverse(entry.0));
1024    for (_, path) in diagnostics.into_iter().skip(RETAINED_LAUNCH_DIAGNOSTICS) {
1025        std::fs::remove_file(&path)
1026            .with_context(|| format!("prune old launch diagnostic {}", path.display()))?;
1027    }
1028    Ok(())
1029}
1030
1031fn apply_new_session_provisioning_result(
1032    state: &mut State,
1033    session_id: &str,
1034    result: Result<TargetLocator>,
1035) -> Result<()> {
1036    match result {
1037        Ok(locator) => {
1038            let record = state.sessions.get_mut(session_id).unwrap();
1039            record.target = Some(locator);
1040            // Provisioning has completed, but Running is reserved for a
1041            // successful worker handshake.
1042            record.state = SessionState::Disconnected;
1043            record.updated_at = now();
1044            record.last_error = None;
1045            Ok(())
1046        }
1047        Err(error) => {
1048            let record = state.sessions.get_mut(session_id).unwrap();
1049            record.state = SessionState::Error;
1050            record.target = None;
1051            record.updated_at = now();
1052            record.last_error = Some(format!("session provisioning failed: {error:#}"));
1053            Err(error)
1054        }
1055    }
1056}
1057
1058/// Mark a new session's launch failed while it still names its target, so the
1059/// record is true while the rollback removes that target.
1060fn apply_failed_new_session_launch(state: &mut State, session_id: &str, original_error: &str) {
1061    let record = state.sessions.get_mut(session_id).unwrap();
1062    record.state = SessionState::StartupCleanup;
1063    record.updated_at = now();
1064    record.last_error = Some(format!("worker bootstrap failed: {original_error}"));
1065}
1066
1067pub(super) fn apply_failed_new_session_rollback(
1068    state: &mut State,
1069    session_id: &str,
1070    original_error: &str,
1071    cleanup_error: Option<String>,
1072) -> anyhow::Error {
1073    match cleanup_error {
1074        None => {
1075            let record = state.sessions.get_mut(session_id).unwrap();
1076            record.state = SessionState::Error;
1077            record.target = None;
1078            record.updated_at = now();
1079            record.last_error = Some(format!("worker bootstrap failed: {original_error}"));
1080            anyhow::anyhow!("{original_error}; partial target removed and failed session retained")
1081        }
1082        Some(cleanup_error) => {
1083            let failure = format!(
1084                "{original_error}; cleanup of the failed session target failed: {cleanup_error}"
1085            );
1086            let record = state.sessions.get_mut(session_id).unwrap();
1087            record.state = SessionState::StartupCleanup;
1088            record.updated_at = now();
1089            record.last_error = Some(format!("worker bootstrap failed: {failure}"));
1090            anyhow::anyhow!(failure)
1091        }
1092    }
1093}
1094
1095pub(super) fn install_attached_resources(
1096    state: &State,
1097    session_id: &str,
1098    backend: &targets::TargetLocator,
1099    worker_root: &str,
1100    executor: &impl CommandExecutor,
1101) -> Result<()> {
1102    let targets::TargetLocator::AwsEc2 { .. } = backend else {
1103        return Ok(());
1104    };
1105    let session = state
1106        .sessions
1107        .get(session_id)
1108        .with_context(|| format!("unknown session {session_id}"))?;
1109    if session.additional_mounts.is_empty() {
1110        return Ok(());
1111    }
1112    for resource in &session.additional_mounts {
1113        let install = targets::command_on_locator(
1114            backend,
1115            session_id,
1116            vec![
1117                format!("{worker_root}/hel"),
1118                "worker".into(),
1119                "install-resource".into(),
1120                "--destination".into(),
1121                resource.destination.to_string_lossy().into_owned(),
1122            ],
1123            "stream attached resource",
1124        )?;
1125        mj_checkpoint::resources::stream_resource(&resource.source, |stream| {
1126            execute_checked_with_stdin(executor, &install, stream).map(|_| ())
1127        })
1128        .with_context(|| format!("stream attached resource {}", resource.source.display()))?;
1129    }
1130    Ok(())
1131}
1132
1133/// Run two independent target setup lanes at the same time and wait for both.
1134/// The first lane's failure wins deterministically when both fail, and neither
1135/// lane is abandoned while it may still own a transfer or subprocess.
1136pub(super) fn execute_concurrent_lanes<A: Send, B: Send>(
1137    first: impl FnOnce() -> Result<A> + Send,
1138    second: impl FnOnce() -> Result<B> + Send,
1139) -> Result<(A, B)> {
1140    std::thread::scope(|scope| {
1141        let owner = crate::worker_lifecycle::capture();
1142        let second = scope.spawn(move || match owner {
1143            Some(owner) => owner.scope_blocking(second),
1144            None => second(),
1145        });
1146        let first = first();
1147        let second = second.join().unwrap_or_else(|panic| {
1148            Err(anyhow::anyhow!(
1149                "concurrent target lane panicked: {}",
1150                targets::command_thread_panic_message(panic.as_ref())
1151            ))
1152        });
1153        match (first, second) {
1154            (Err(error), _) => Err(error),
1155            (Ok(_), Err(error)) => Err(error),
1156            (Ok(first), Ok(second)) => Ok((first, second)),
1157        }
1158    })
1159}
1160
1161fn execute_repository_setup(
1162    plan: &targets::CommandPlan,
1163    executor: &(impl CommandExecutor + Sync),
1164) -> Result<()> {
1165    if plan.commands.is_empty() {
1166        return Ok(());
1167    }
1168    let _cloning = ProvisionStageGuard::new(executor, ProvisionStage::Cloning);
1169    plan.execute_concurrent(executor).map(|_| ())
1170}
1171
1172/// Run a provisioning plan and discover the locator it produced, tearing the
1173/// target down again if anything after its creation fails.
1174///
1175/// Creation is the boundary that matters. A step that fails before the target
1176/// exists has left nothing behind; every failure after it — a later plan step
1177/// or locator discovery — owns a target no session record will point at.
1178#[cfg(test)]
1179fn provision_target(
1180    plan: &targets::CommandPlan,
1181    target: &targets::TargetTemplate,
1182    session_id: &str,
1183    executor: &(impl CommandExecutor + Sync),
1184    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1185) -> Result<TargetLocator> {
1186    let Some((creation, remainder)) = plan.split_at_target_creation() else {
1187        // Nothing this plan runs can leave a target behind.
1188        return discover(&plan.execute_concurrent(executor)?);
1189    };
1190    let mut outputs = creation.execute_concurrent(executor)?;
1191    let result = match remainder.execute_concurrent(executor) {
1192        Ok(rest) => {
1193            outputs.extend(rest);
1194            discover(&outputs)
1195        }
1196        Err(error) => Err(error),
1197    };
1198    result.map_err(|error| {
1199        match cleanup_failed_provision(target, session_id, outputs.first(), executor) {
1200            Some(note) => error.context(note),
1201            None => error,
1202        }
1203    })
1204}
1205
1206/// Bring the target into existence and return the commands that populate its
1207/// repositories. The caller may overlap that remainder with worker/profile
1208/// installation once it has persisted the discovered locator.
1209#[cfg(test)]
1210fn provision_target_creation(
1211    plan: &targets::CommandPlan,
1212    target: &targets::TargetTemplate,
1213    session_id: &str,
1214    executor: &(impl CommandExecutor + Sync),
1215    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1216) -> Result<(TargetLocator, targets::CommandPlan)> {
1217    provision_target_creation_named(
1218        plan,
1219        target,
1220        session_id,
1221        executor,
1222        &targets::resource_name(session_id)?,
1223        discover,
1224    )
1225}
1226
1227fn provision_target_creation_named(
1228    plan: &targets::CommandPlan,
1229    target: &targets::TargetTemplate,
1230    session_id: &str,
1231    executor: &(impl CommandExecutor + Sync),
1232    name: &str,
1233    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1234) -> Result<(TargetLocator, targets::CommandPlan)> {
1235    let Some((creation, remainder)) = plan.split_at_target_creation() else {
1236        // Nothing this plan runs can leave a target behind, so its commands
1237        // must still finish before the locator is usable.
1238        let outputs = crate::image_pull_gate::with_image_ready(target, executor, || {
1239            plan.execute_concurrent(executor)
1240        })?;
1241        return discover(&outputs).map(|locator| {
1242            (
1243                locator,
1244                targets::CommandPlan {
1245                    description: plan.description.clone(),
1246                    commands: Vec::new(),
1247                },
1248            )
1249        });
1250    };
1251    // Creating the container is what downloads the image on Docker, and the
1252    // probe just before it is what downloads it on Podman. Either way, a
1253    // background download of the same image must finish first.
1254    let outputs = crate::image_pull_gate::with_image_ready(target, executor, || {
1255        creation.execute_concurrent(executor)
1256    })?;
1257    discover(&outputs)
1258        .map(|locator| (locator, remainder))
1259        .map_err(|error| {
1260            match cleanup_failed_provision_named(
1261                target,
1262                session_id,
1263                outputs.first(),
1264                executor,
1265                name,
1266            ) {
1267                Some(note) => error.context(note),
1268                None => error,
1269            }
1270        })
1271}
1272
1273/// Best-effort teardown of a target whose creation succeeded but whose
1274/// provisioning failed before a locator was recorded. Returns a note
1275/// describing what happened for inclusion in the session error.
1276///
1277/// The teardown is the session's own close plan, so a failed launch and an
1278/// ordinary close can never disagree about what removing a target means.
1279#[cfg(test)]
1280fn cleanup_failed_provision(
1281    target: &targets::TargetTemplate,
1282    session_id: &str,
1283    create_output: Option<&CommandOutput>,
1284    executor: &impl CommandExecutor,
1285) -> Option<String> {
1286    cleanup_failed_provision_named(
1287        target,
1288        session_id,
1289        create_output,
1290        executor,
1291        &targets::resource_name(session_id).ok()?,
1292    )
1293}
1294
1295fn cleanup_failed_provision_named(
1296    target: &targets::TargetTemplate,
1297    session_id: &str,
1298    create_output: Option<&CommandOutput>,
1299    executor: &impl CommandExecutor,
1300    name: &str,
1301) -> Option<String> {
1302    let locator = provisioned_locator_named(target, session_id, create_output, name)?;
1303
1304    let leak = format!(
1305        "the resource may still exist; find it via its dev.mj.session={session_id} label/tag"
1306    );
1307    let cleanup = if name == targets::resource_name(session_id).ok()? {
1308        targets::close_plan(&locator, session_id)
1309    } else {
1310        targets::retire_move_target_plan(&locator, session_id)
1311    };
1312    let plan = match cleanup {
1313        Ok(plan) => plan,
1314        Err(error) => {
1315            tracing::warn!(
1316                session_id,
1317                error = format!("{error:#}"),
1318                "could not build provisioning cleanup plan"
1319            );
1320            return Some(format!("cleanup FAILED: {error:#}; {leak}"));
1321        }
1322    };
1323    let purpose = plan
1324        .commands
1325        .iter()
1326        .map(|command| command.purpose.clone())
1327        .collect::<Vec<_>>()
1328        .join("; ");
1329    let Err(error) = plan.execute(executor) else {
1330        return Some(format!("cleanup succeeded: {purpose}"));
1331    };
1332    match targets::cleanup_target_is_confirmed_absent(&locator, session_id, executor) {
1333        Ok(true) => Some(format!("cleanup succeeded: {purpose}")),
1334        Ok(false) => {
1335            tracing::warn!(
1336                session_id,
1337                error = format!("{error:#}"),
1338                "provisioning cleanup failed and the target may still exist"
1339            );
1340            Some(format!("cleanup FAILED ({purpose}): {error:#}; {leak}"))
1341        }
1342        Err(confirm_error) => {
1343            tracing::warn!(
1344                session_id,
1345                error = format!("{confirm_error:#}"),
1346                "could not confirm whether the failed provisioning target was removed"
1347            );
1348            Some(format!(
1349                "cleanup FAILED ({purpose}): {error:#}; checking whether it was removed also failed: {confirm_error:#}; {leak}"
1350            ))
1351        }
1352    }
1353}
1354
1355/// The locator a provisioning plan's creating command brought into existence.
1356///
1357/// Every target but AWS is named before its plan runs; an EC2 instance
1358/// reports its own ID in the launch response.
1359fn provisioned_locator_named(
1360    target: &targets::TargetTemplate,
1361    session_id: &str,
1362    create_output: Option<&CommandOutput>,
1363    name: &str,
1364) -> Option<targets::TargetLocator> {
1365    let container_id = || Some(name.to_owned());
1366
1367    Some(match target {
1368        // A bare project directory belongs to the user: provisioning creates
1369        // nothing that a failure could leak.
1370        targets::TargetTemplate::LocalBare => return None,
1371        targets::TargetTemplate::LocalPodman(container) => targets::TargetLocator::LocalPodman {
1372            borrowed_from: None,
1373            container_id: container_id()?,
1374            workspace_storage: targets::podman_workspace_locator_named(container, name).ok()?,
1375        },
1376        targets::TargetTemplate::LocalDocker(_) => targets::TargetLocator::LocalDocker {
1377            borrowed_from: None,
1378            container_id: container_id()?,
1379        },
1380        targets::TargetTemplate::AppleContainer(_) => targets::TargetLocator::AppleContainer {
1381            borrowed_from: None,
1382            container_id: container_id()?,
1383        },
1384        targets::TargetTemplate::SshPodman { ssh, container } => {
1385            targets::TargetLocator::SshPodman {
1386                borrowed_from: None,
1387                ssh: ssh.clone(),
1388                container_id: container_id()?,
1389                workspace_storage: targets::podman_workspace_locator_named(container, name).ok()?,
1390            }
1391        }
1392        targets::TargetTemplate::SshDocker { ssh, .. } => targets::TargetLocator::SshDocker {
1393            borrowed_from: None,
1394            ssh: ssh.clone(),
1395            container_id: container_id()?,
1396        },
1397        targets::TargetTemplate::SshBare { ssh, .. } => targets::TargetLocator::SshBare {
1398            ssh: ssh.clone(),
1399            workspace: targets::workspace_for(target, session_id).ok()?,
1400            worker_id: None,
1401        },
1402        targets::TargetTemplate::AwsEc2(aws) => targets::TargetLocator::AwsEc2 {
1403            profile: aws.profile.clone(),
1404            region: aws.region.clone(),
1405            instance_id: serde_json::from_slice::<serde_json::Value>(&create_output?.stdout)
1406                .ok()?
1407                .pointer("/Instances/0/InstanceId")?
1408                .as_str()?
1409                .to_owned(),
1410            ssh: aws.ssh.clone(),
1411            workspace: targets::workspace_for(target, session_id).ok()?,
1412        },
1413    })
1414}
1415
1416/// Attach read-only whatever the selected container overlay cannot hold, and
1417/// say so.
1418///
1419/// The filesystem is probed on the host that runs the container, because that
1420/// is where the overlay would be built. A probe that cannot answer leaves the
1421/// overlay alone: a failed probe is no evidence of an unsupported filesystem,
1422/// and refusing to provision over one would cost the user their session.
1423///
1424/// Apple's `container` engine already mounts every extra directory read-only,
1425/// and EC2 copies the directory instead of mounting it, so neither is probed.
1426pub(super) fn enforce_overlay_capable_mounts(
1427    target: &targets::TargetTemplate,
1428    mounts: &mut [targets::AdditionalMount],
1429    executor: &impl CommandExecutor,
1430) -> Vec<String> {
1431    let ssh = match target {
1432        targets::TargetTemplate::LocalPodman(_) | targets::TargetTemplate::LocalDocker(_) => None,
1433        targets::TargetTemplate::SshPodman { ssh, .. }
1434        | targets::TargetTemplate::SshDocker { ssh, .. } => Some(ssh),
1435        _ => return Vec::new(),
1436    };
1437    let overlaid = mounts
1438        .iter()
1439        .filter(|mount| mount.access == targets::MountAccess::Cow)
1440        .map(|mount| mount.source.clone())
1441        .collect::<Vec<_>>();
1442    if overlaid.is_empty() {
1443        return Vec::new();
1444    }
1445    // `stat` on this host cannot see what a VM-hosted Docker daemon mounts.
1446    if matches!(target, targets::TargetTemplate::LocalDocker(_)) {
1447        match targets::local_docker_vm_share(executor) {
1448            Ok(Some(reason)) => {
1449                return mounts
1450                    .iter_mut()
1451                    .filter(|mount| mount.access == targets::MountAccess::Cow)
1452                    .map(|mount| {
1453                        mount.access = mount.access.without_overlay();
1454                        format!(
1455                            "Mounted {} read-only: {reason}, which cannot back the \
1456                             copy-on-write overlay.",
1457                            mount.source.display()
1458                        )
1459                    })
1460                    .collect();
1461            }
1462            Ok(None) => {}
1463            Err(error) => tracing::warn!(
1464                error = format!("{error:#}"),
1465                "could not identify the Docker daemon platform; probing this host's filesystems"
1466            ),
1467        }
1468    }
1469    let filesystems = match targets::probe_filesystem_types(ssh, &overlaid, executor) {
1470        Ok(filesystems) => filesystems,
1471        Err(error) => {
1472            tracing::warn!(
1473                error = format!("{error:#}"),
1474                "could not probe attached-directory filesystems; preserving overlay mounts"
1475            );
1476            return vec![format!(
1477                "Could not read the filesystem under the attached directories, so they keep the \
1478                 copy-on-write overlay: {error:#}"
1479            )];
1480        }
1481    };
1482    let mut notices = Vec::new();
1483    for (mount, filesystem) in mounts
1484        .iter_mut()
1485        .filter(|mount| mount.access == targets::MountAccess::Cow)
1486        .zip(filesystems)
1487    {
1488        let Some(reason) = targets::overlay_unsupported_filesystem(&filesystem) else {
1489            continue;
1490        };
1491        mount.access = mount.access.without_overlay();
1492        notices.push(format!(
1493            "Mounted {} read-only: the overlay is unreliable on {filesystem} ({reason}).",
1494            mount.source.display()
1495        ));
1496    }
1497    notices
1498}
1499
1500/// Reports every command an installer issues as one launch stage, so progress
1501/// stays accurate without threading the stage through each `CommandSpec`.
1502/// A command that already names a stage keeps it.
1503pub(super) struct StagedExecutor<'a, E: CommandExecutor> {
1504    inner: &'a E,
1505    stage: ProvisionStage,
1506    _guard: ProvisionStageGuard<'a, E>,
1507}
1508
1509impl<'a, E: CommandExecutor> StagedExecutor<'a, E> {
1510    pub(crate) fn new(inner: &'a E, stage: ProvisionStage) -> Self {
1511        Self {
1512            inner,
1513            stage: stage.clone(),
1514            _guard: ProvisionStageGuard::new(inner, stage.clone()),
1515        }
1516    }
1517
1518    fn staged(&self, command: &CommandSpec) -> CommandSpec {
1519        if command.stage.is_some() {
1520            return command.clone();
1521        }
1522        command.clone().stage(self.stage.clone())
1523    }
1524}
1525
1526impl<E: CommandExecutor> CommandExecutor for StagedExecutor<'_, E> {
1527    fn execute(&self, command: &CommandSpec) -> Result<CommandOutput> {
1528        self.inner.execute(&self.staged(command))
1529    }
1530
1531    fn cancellation_requested(&self) -> bool {
1532        self.inner.cancellation_requested()
1533    }
1534
1535    fn stage_started(&self, stage: ProvisionStage) {
1536        self.inner.stage_started(stage);
1537    }
1538
1539    fn stage_finished(&self, stage: ProvisionStage) {
1540        self.inner.stage_finished(stage);
1541    }
1542
1543    fn notify_notice(&self, notice: &str) {
1544        self.inner.notify_notice(notice);
1545    }
1546
1547    fn execute_with_stdin(
1548        &self,
1549        command: &CommandSpec,
1550        input: &mut (dyn std::io::Read + Send),
1551    ) -> Result<CommandOutput> {
1552        self.inner.execute_with_stdin(&self.staged(command), input)
1553    }
1554}
1555
1556fn execute_checked_with_stdin(
1557    executor: &impl CommandExecutor,
1558    command: &CommandSpec,
1559    input: &mut (dyn std::io::Read + Send),
1560) -> Result<CommandOutput> {
1561    let output = executor.execute_with_stdin(command, input)?;
1562    if output.status != 0 {
1563        bail!(
1564            "{} failed with status {}: {}",
1565            command.purpose,
1566            output.status,
1567            String::from_utf8_lossy(&output.stderr)
1568        );
1569    }
1570    Ok(output)
1571}
1572
1573pub(super) fn install_inherited_git_settings(
1574    executor: &impl CommandExecutor,
1575    locator: &targets::TargetLocator,
1576    session_id: &str,
1577) -> Result<()> {
1578    let settings = if inherits_controller_git_settings(locator) {
1579        controller_git_settings()?
1580    } else {
1581        BTreeMap::new()
1582    };
1583    for command in inherited_git_setting_commands(locator, session_id, settings)? {
1584        execute_checked(executor, command)?;
1585    }
1586    Ok(())
1587}
1588
1589fn inherits_controller_git_settings(locator: &targets::TargetLocator) -> bool {
1590    !matches!(
1591        locator,
1592        targets::TargetLocator::LocalBare { .. } | targets::TargetLocator::SshBare { .. }
1593    )
1594}
1595
1596fn inherited_git_setting_commands(
1597    locator: &targets::TargetLocator,
1598    session_id: &str,
1599    settings: BTreeMap<String, String>,
1600) -> Result<Vec<CommandSpec>> {
1601    if matches!(locator, targets::TargetLocator::SshBare { .. }) {
1602        return Ok(Vec::new());
1603    }
1604    settings
1605        .into_iter()
1606        .map(|(key, value)| {
1607            let args = vec![
1608                "git".into(),
1609                "config".into(),
1610                "--global".into(),
1611                "--replace-all".into(),
1612                "--".into(),
1613                key.clone(),
1614                value,
1615            ];
1616            targets::command_on_locator(
1617                locator,
1618                session_id,
1619                args,
1620                format!("inherit Git setting {key}"),
1621            )
1622        })
1623        .collect()
1624}
1625
1626fn controller_git_settings() -> Result<BTreeMap<String, String>> {
1627    let output = match Command::new("git")
1628        .args(["config", "--global", "--includes", "--null", "--list"])
1629        .stdin(Stdio::null())
1630        .output()
1631    {
1632        Ok(output) => output,
1633        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
1634        Err(error) => return Err(error).context("read controller Git configuration"),
1635    };
1636    if !output.status.success() {
1637        bail!(
1638            "read controller Git configuration failed with status {}: {}",
1639            output.status,
1640            String::from_utf8_lossy(&output.stderr).trim()
1641        );
1642    }
1643    parse_inherited_git_settings(&output.stdout)
1644}
1645
1646fn parse_inherited_git_settings(output: &[u8]) -> Result<BTreeMap<String, String>> {
1647    let mut settings = BTreeMap::new();
1648    for entry in output
1649        .split(|byte| *byte == 0)
1650        .filter(|entry| !entry.is_empty())
1651    {
1652        let entry = std::str::from_utf8(entry).context("decode controller Git configuration")?;
1653        let (key, value) = entry
1654            .split_once('\n')
1655            .with_context(|| format!("controller Git returned malformed entry {entry:?}"))?;
1656        let key = key.to_ascii_lowercase();
1657        if INHERITED_GIT_SETTINGS.contains(&key.as_str()) {
1658            settings.insert(key, value.to_owned());
1659        }
1660    }
1661    Ok(settings)
1662}
1663
1664#[cfg(test)]
1665mod tests;