scientific-workflow 0.18.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use crate::protocol::{Outcome, Status};
use crate::{
    WorkflowError,
    artifact::{ArtifactRole, RunManifest, StorageLocation},
    storage::{Store, atomic_json, run_id},
    study::StudyPlan,
    workspace::WorkspaceLease,
};
use serde::{Deserialize, Serialize};
use std::{
    io,
    path::{Path, PathBuf},
    process::{Command, Stdio},
    time::{Duration, Instant},
};
/// Durable identity and local socket of an independent engine process.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RunHandle {
    /// UTC run namespace at the destination.
    pub run_id: String,
    /// Unix socket for all live status and controls.
    pub socket: PathBuf,
    /// External local workspace, containing the recovery journal.
    pub workspace: PathBuf,
    /// Host binding for safe cleanup of disposable local copies.
    pub host_id: String,
    /// Authored input folder; execution leaves it unchanged.
    pub input: PathBuf,
    /// Authoritative destination; contains credential profile references only.
    pub storage: StorageLocation,
}
impl RunHandle {
    /// Connects to a live engine without owning its lifecycle.
    pub fn client(&self) -> io::Result<crate::client::RunClient> {
        crate::client::RunClient::connect(&self.socket)
    }
    /// Waits for a terminal outcome; a stale running snapshot never implies success.
    pub fn wait(&self) -> io::Result<Status> {
        match self.client().and_then(|c| c.wait()) {
            Ok(status) => Ok(status),
            Err(error) => {
                let status: Status = Store::open(&self.storage)?
                    .json(&format!("{}/records/status.json", self.run_id))?;
                if status.outcome.terminal() {
                    Ok(status)
                } else {
                    Err(error)
                }
            }
        }
    }
}
#[derive(Serialize, Deserialize)]
pub(super) struct LaunchSpec {
    pub handle: RunHandle,
    pub input: PathBuf,
    pub manifest: RunManifest,
    pub max_bytes: u64,
    pub path: std::ffi::OsString,
}
pub(crate) fn start(input: &Path) -> Result<RunHandle, WorkflowError> {
    start_mode(input, false)
}
pub(super) fn start_mode(input: &Path, capture_only: bool) -> Result<RunHandle, WorkflowError> {
    let input = input.canonicalize()?;
    if input.join("campaign.json").is_file() {
        let campaign = crate::campaign::CampaignPlan::load(&input)?;
        campaign.check()?;
        let software = campaign
            .declaration
            .studies
            .iter()
            .map(|m| {
                if m.runner.is_absolute() {
                    m.runner.clone()
                } else {
                    input.join(&m.runner)
                }
            })
            .collect::<Vec<_>>();
        return start_prepared(
            &input,
            campaign.settings,
            software,
            Vec::new(),
            Default::default(),
            None,
            "campaign",
            capture_only,
        );
    }
    let study = StudyPlan::load(&input)?;
    crate::runtime::check_prerequisites(&study)?;
    let settings = study.runtime_settings().clone();
    let verification = study
        .verification()
        .map(|v| v.resolve(&input))
        .transpose()
        .map_err(crate::study::StudyError::from)?;
    let mut software = study
        .phases()
        .iter()
        .flat_map(|p| p.tasks())
        .flat_map(|t| [t.program_path(), t.python_script()].into_iter().flatten())
        .map(Path::to_path_buf)
        .collect::<Vec<_>>();
    if let Some(program) = &verification {
        software.push(program.program().to_path_buf());
        if let Some(script) = program.python_script() {
            software.push(script.to_path_buf());
        }
    }
    let mut python = study
        .phases()
        .iter()
        .flat_map(|p| p.tasks())
        .filter_map(|t| t.program_declaration())
        .filter(|p| p.capture_key().is_some())
        .cloned()
        .collect::<Vec<_>>();
    if let Some(program) = verification
        && program.capture_key().is_some()
    {
        python.push(program);
    }
    start_prepared(
        &input,
        settings,
        software,
        python,
        study.reproduction().clone(),
        Some(study),
        "study",
        capture_only,
    )
}
fn collision_id(id: &str) -> String {
    let (base, sequence) = id.split_once('-').map_or((id, 0), |(base, sequence)| {
        (base, sequence.parse::<u64>().unwrap_or(0))
    });
    format!("{base}-{:04}", sequence + 1)
}
// A reserved run must remain discoverable even when capture or launch fails.
struct StartupRecord {
    store: Store,
    root: PathBuf,
    manifest: RunManifest,
    armed: bool,
}
impl Drop for StartupRecord {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        if std::fs::File::open(self.root.join("records/status.json"))
            .ok()
            .and_then(|f| serde_json::from_reader::<_, Status>(f).ok())
            .is_some_and(|s| s.outcome.terminal())
        {
            return;
        }
        self.manifest.outcome = Outcome::Failed;
        let status = Status {
            version: crate::protocol::VERSION,
            run_id: self.manifest.run_id.clone(),
            sequence: 0,
            updated_at: crate::storage::utc_now(),
            pid: std::process::id(),
            outcome: Outcome::Failed,
            pause_reason: None,
            control: "finished".into(),
            study: None,
            tasks: Default::default(),
            allocations: serde_json::json!({}),
            message: Some(
                "capture or engine startup failed; inspect the launch error and retained workspace"
                    .into(),
            ),
            wall_ms: 0,
            active_ms: 0,
        };
        let _ = atomic_json(&self.root.join("records/status.json"), &status);
        let _ = self.store.put_json(
            &format!("{}/records/status.json", self.manifest.run_id),
            &status,
            &self.root,
            false,
        );
        let _ = self.store.put_json(
            &format!("{}/manifest.json", self.manifest.run_id),
            &self.manifest,
            &self.root,
            false,
        );
        let _ = crate::registry::index_manifest(&self.store, &self.manifest, &self.root);
    }
}
#[allow(clippy::too_many_arguments)]
fn start_prepared(
    input: &Path,
    settings: crate::config::RuntimeSettings,
    software: Vec<PathBuf>,
    python: Vec<crate::config::ResolvedProgramTask>,
    reproduction: crate::config::ReproductionSpecification,
    expected: Option<StudyPlan>,
    kind: &str,
    capture_only: bool,
) -> Result<RunHandle, WorkflowError> {
    let store = Store::open(&settings.storage)?;
    let mut id = run_id();
    let mut lease;
    loop {
        lease = match WorkspaceLease::create(&settings.workspace.root, &id) {
            Ok(lease) => lease,
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
                id = collision_id(&id);
                continue;
            }
            Err(error) => return Err(error.into()),
        };
        let marker = serde_json::json!({"format":"scientific-workflow-reservation.v1","run_id":id});
        match store.put_json(
            &format!("{id}/reservation.json"),
            &marker,
            &lease.root,
            true,
        ) {
            Ok(()) => break,
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                id = collision_id(&id);
            }
            Err(e) => return Err(e.into()),
        }
    }
    let root = lease.root.clone();
    let initial = RunManifest {
        format: "scientific-workflow-run.v1".into(),
        run_id: id.clone(),
        kind: kind.into(),
        scientific_identity: crate::artifact::digest_bytes(b""),
        artifacts: Default::default(),
        capture_complete: false,
        outcome: Outcome::Starting,
        removed: Vec::new(),
    };
    let mut startup = StartupRecord {
        store: store.clone(),
        root: root.clone(),
        manifest: initial,
        armed: true,
    };
    store.put_json(
        &format!("{id}/manifest.json"),
        &startup.manifest,
        &root,
        false,
    )?;

    let _budget = crate::workspace::CaptureBudget::new(&root, settings.workspace.max_bytes.get())?;
    let captured = root.join("inputs");
    std::fs::create_dir(&captured)?;
    let mut artifacts = Default::default();
    crate::provenance::capture_tree(&store, input, "inputs", Some(&captured), &mut artifacts)?;
    if let Some(expected) = expected {
        expected
            .verify_capture(&captured)
            .map_err(crate::study::StudyError::from)?;
    }
    crate::workspace::check_capacity()?;
    if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
        return Err(io::Error::other("captured input exceeds workspace budget").into());
    }
    let executable = std::env::current_exe()?.canonicalize()?;
    let runner = root.join("reproduction/software/runner");
    crate::provenance::capture_file(
        &store,
        &executable,
        "reproduction/software/runner",
        Some(&runner),
        &mut artifacts,
        ArtifactRole::Reproduction,
    )?;
    crate::provenance::capture_libraries(&store, &executable, &root, &mut artifacts)?;
    let mut python_bindings = std::collections::BTreeMap::new();
    for program in python {
        if let Some(key) = program.capture_key()
            && python_bindings.contains_key(key)
        {
            continue;
        }
        if let Some((key, value)) =
            crate::provenance::capture_python(&store, &program, &root, &mut artifacts)?
        {
            python_bindings.insert(key, value);
        }
    }
    let mut bindings = std::collections::BTreeMap::new();
    let numerical = crate::provenance::capture_environment(&reproduction.environment)?;
    let mut input_bindings = std::collections::BTreeMap::new();
    for (name, source) in reproduction.inputs {
        crate::artifact::validate_key(&name)?;
        let key = format!("reproduction/external-inputs/{name}");
        if let Some(locator) = settings.input_bindings.get(&name) {
            let selected = locator.open()?;
            for reference in selected.references() {
                let relative = reference
                    .key
                    .strip_prefix(&locator.prefix)
                    .ok_or_else(|| io::Error::other("input reference escapes its selection"))?;
                let target = format!("{key}{relative}");
                let copied = store.copy_reference(
                    &target,
                    selected.reader(relative.trim_start_matches('/'))?,
                    reference,
                    ArtifactRole::Reproduction,
                )?;
                artifacts.insert(target, copied);
            }
        } else {
            let source = if source.is_absolute() {
                source
            } else {
                input.join(source)
            }
            .canonicalize()?;
            if source.is_dir() {
                crate::provenance::capture_tree(&store, &source, &key, None, &mut artifacts)?;
            } else {
                crate::provenance::capture_file(
                    &store,
                    &source,
                    &key,
                    None,
                    &mut artifacts,
                    ArtifactRole::Reproduction,
                )?;
            }
        }
        input_bindings.insert(
            name,
            crate::artifact::ArtifactLocator {
                storage: settings.storage.clone(),
                run_id: id.clone(),
                prefix: key,
            },
        );
    }
    for (i, source) in reproduction.software.into_iter().enumerate() {
        let source = if source.is_absolute() {
            source
        } else {
            input.join(source)
        }
        .canonicalize()?;
        let key = format!(
            "reproduction/software/declared-{i}/{}",
            source
                .file_name()
                .ok_or_else(|| io::Error::other("software source requires a file or folder name"))?
                .to_string_lossy()
        );
        let target = root.join(&key);
        if source.is_dir() {
            crate::provenance::capture_software_tree(
                &store,
                &source,
                &key,
                &target,
                &mut artifacts,
            )?;
        } else {
            crate::provenance::capture_file(
                &store,
                &source,
                &key,
                Some(&target),
                &mut artifacts,
                ArtifactRole::Reproduction,
            )?;
            crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
        }
        bindings.insert(source, target);
    }
    for source in software {
        let source = source.canonicalize()?;
        if source
            .strip_prefix(input)
            .is_ok_and(|p| captured.join(p).is_file())
        {
            continue;
        }
        crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
        let digest = crate::artifact::digest_reader(std::fs::File::open(&source)?)?.0;
        let key = format!(
            "reproduction/software/{digest}/{}",
            source.file_name().unwrap().to_string_lossy()
        );
        let local = root.join(&key);
        if let std::collections::btree_map::Entry::Vacant(entry) = bindings.entry(source.clone()) {
            crate::provenance::capture_file(
                &store,
                &source,
                &key,
                Some(&local),
                &mut artifacts,
                ArtifactRole::Reproduction,
            )?;
            entry.insert(local);
        }
    }
    // Retain exact authored inputs; a separate execution view binds external software.
    let effective = root.join("execution-input");
    std::fs::create_dir(&effective)?;
    copy_tree(&captured, &effective)?;
    let runtime_path = effective.join(if kind == "campaign" {
        "runtime.json"
    } else {
        "wf_configs/runtime.json"
    });
    let mut runtime: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(&runtime_path)?)?;
    if kind == "study" {
        runtime["input_bindings"] = serde_json::to_value(&input_bindings)?;
    }
    if let Some(environment) = python_bindings.get("standard-npy") {
        let mut environment = environment.clone();
        environment.as_object_mut().unwrap().remove("manager");
        runtime["npy_environment"] = environment;
    }
    runtime["workspace"]["root"] = root.join("work").to_string_lossy().into_owned().into();
    atomic_json(&runtime_path, &runtime)?;
    if kind == "study" {
        let path = effective.join("wf_configs/study.json");
        let mut study: serde_json::Value = serde_json::from_reader(std::fs::File::open(&path)?)?;
        if let Some(phases) = study["phases"].as_object_mut() {
            for phase in phases.values_mut() {
                if let Some(tasks) = phase
                    .get_mut("tasks")
                    .and_then(serde_json::Value::as_array_mut)
                {
                    for task in tasks {
                        if let Some(python) = task.get_mut("python") {
                            let key = crate::config::python_capture_key(python.clone())
                                .map_err(crate::study::StudyError::from)?;
                            if let Some(environment) = python_bindings.get(&key) {
                                python["environment"] = environment.clone();
                            }
                        }
                    }
                }
            }
        }
        if let Some(python) = study.pointer_mut("/verification/python") {
            let key = crate::config::python_capture_key(python.clone())
                .map_err(crate::study::StudyError::from)?;
            if let Some(environment) = python_bindings.get(&key) {
                python["environment"] = environment.clone();
            }
        }
        atomic_json(&path, &study)?;
    }
    rewrite_paths(
        &effective.join(if kind == "campaign" {
            "campaign.json"
        } else {
            "wf_configs/study.json"
        }),
        &bindings,
        input,
        &effective,
    )?;
    for file in ["wf_configs/parameters.json", "wf_configs/study.json"] {
        let path = effective.join(file);
        if path.exists() {
            rewrite_paths(&path, &bindings, input, &effective)?;
        }
    }
    crate::provenance::capture_tree(
        &store,
        &effective,
        "reproduction/effective-inputs",
        None,
        &mut artifacts,
    )?;
    let numerical_path = root.join("reproduction/environment/numerical.json");
    atomic_json(&numerical_path, &numerical)?;
    crate::provenance::capture_file(
        &store,
        &numerical_path,
        "reproduction/environment/numerical.json",
        None,
        &mut artifacts,
        ArtifactRole::Reproduction,
    )?;
    let environment = serde_json::json!({"os":std::env::consts::OS,"arch":std::env::consts::ARCH,"runner_sha256":crate::artifact::digest_reader(std::fs::File::open(&runner)?)?.0,"software_bindings":bindings,"seed_algorithm":"scientific-workflow.seed.v1"});
    let environment_path = root.join("reproduction/environment/manifest.json");
    atomic_json(&environment_path, &environment)?;
    crate::provenance::capture_file(
        &store,
        &environment_path,
        "reproduction/environment/manifest.json",
        None,
        &mut artifacts,
        ArtifactRole::Reproduction,
    )?;
    if kind == "campaign" {
        super::campaign::capture_members(
            &store,
            &root,
            &effective,
            &settings.storage,
            &mut artifacts,
        )?;
        if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
            return Err(
                io::Error::other("campaign capture exceeds its explicit workspace budget").into(),
            );
        }
    }
    let science = artifacts
        .iter()
        .filter(|(key, _)| {
            !key.ends_with("runtime.json")
                && (!key.starts_with("reproduction/environment/")
                    || *key == "reproduction/environment/numerical.json")
                && !key.starts_with("reproduction/effective-inputs/")
        })
        .map(|(k, r)| (k.clone(), r.sha256.clone()))
        .collect::<std::collections::BTreeMap<_, _>>();
    let scientific_identity = crate::artifact::digest_bytes(&serde_json::to_vec(&science)?);
    let manifest = RunManifest {
        format: "scientific-workflow-run.v1".into(),
        run_id: id.clone(),
        kind: kind.into(),
        scientific_identity,
        artifacts,
        capture_complete: true,
        outcome: Outcome::Starting,
        removed: Vec::new(),
    };
    startup.manifest = manifest.clone();
    store.put_json(&format!("{id}/manifest.json"), &manifest, &root, false)?;
    crate::registry::index_manifest(&store, &manifest, &root)?;
    let mut socket = root.join("engine.sock");
    if socket.as_os_str().len() > 100 {
        // Campaign workspaces are nested; Unix socket endpoints have a much
        // shorter platform limit than ordinary paths.
        let socket_root =
            std::env::temp_dir().join(format!("workflow-sockets-{}", unsafe { libc::geteuid() }));
        std::fs::create_dir_all(&socket_root)?;
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let metadata = std::fs::symlink_metadata(&socket_root)?;
        if metadata.file_type().is_symlink() || metadata.uid() != unsafe { libc::geteuid() } {
            return Err(
                io::Error::other("socket directory must be owned by the current user").into(),
            );
        }
        std::fs::set_permissions(&socket_root, std::fs::Permissions::from_mode(0o700))?;
        socket = socket_root.join(format!("{id}.sock"));
        if socket.as_os_str().len() > 100 {
            return Err(io::Error::other("temporary socket directory is too long").into());
        }
    }
    let handle = RunHandle {
        run_id: id,
        workspace: root.clone(),
        socket,
        storage: settings.storage,
        host_id: crate::workspace::host_id(),
        input: input.into(),
    };
    let mut paths = bindings
        .values()
        .filter_map(|p| {
            if p.is_dir() {
                Some(p.join("bin"))
            } else {
                p.parent().map(Path::to_path_buf)
            }
        })
        .collect::<Vec<_>>();
    paths.extend(std::env::split_paths(
        &std::env::var_os("PATH").unwrap_or_default(),
    ));
    let captured_path = std::env::join_paths(paths).map_err(io::Error::other)?;
    let spec = LaunchSpec {
        handle: handle.clone(),
        input: effective,
        manifest,
        max_bytes: settings.workspace.max_bytes.get(),
        path: captured_path,
    };
    atomic_json(&root.join("launch.json"), &spec)?;
    atomic_json(&root.join("handle.json"), &handle)?;
    store.put_json(
        &format!("{}/records/handle.json", handle.run_id),
        &handle,
        &root,
        false,
    )?;
    drop(lease);
    if !capture_only {
        spawn_prepared(&handle)?;
    }
    startup.armed = false;
    Ok(handle)
}
pub(super) fn spawn_prepared(handle: &RunHandle) -> Result<(), WorkflowError> {
    let root = handle.workspace.clone();
    let spec: LaunchSpec = serde_json::from_reader(std::fs::File::open(root.join("launch.json"))?)?;
    let numerical =
        crate::provenance::read_environment(&root.join("reproduction/environment/numerical.json"))?;
    let log = std::fs::OpenOptions::new()
        .create_new(true)
        .write(true)
        .open(root.join("engine.log"))?;
    let mut command = Command::new(root.join("reproduction/software/runner"));
    command
        .env("PATH", spec.path)
        .arg("--workflow-engine")
        .arg(root.join("launch.json"))
        .current_dir(&root)
        .env("WORKFLOW_RUN_HANDLE", root.join("handle.json"))
        .env("LD_LIBRARY_PATH", root.join("reproduction/libraries"))
        .env("PYTHONDONTWRITEBYTECODE", "1")
        .stdin(Stdio::null())
        .stdout(Stdio::from(log.try_clone()?))
        .stderr(Stdio::from(log));
    crate::provenance::apply_environment(&mut command, &numerical);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        unsafe {
            command.pre_exec(|| {
                if libc::setsid() < 0 {
                    return Err(io::Error::last_os_error());
                }
                Ok(())
            });
        }
    }
    let mut child = command.spawn()?;
    let started = Instant::now();
    loop {
        if handle.client().is_ok() {
            break;
        }
        if let Some(status) = child.try_wait()? {
            return Err(io::Error::other(format!(
                "engine failed startup ({status}); inspect {}",
                root.join("engine.log").display()
            ))
            .into());
        }
        if started.elapsed() > Duration::from_secs(60) {
            let _ = child.kill();
            return Err(
                io::Error::new(io::ErrorKind::TimedOut, "engine readiness timed out").into(),
            );
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    Ok(())
}
pub(super) fn copy_tree(from: &Path, to: &Path) -> io::Result<()> {
    for e in std::fs::read_dir(from)? {
        let e = e?;
        let target = to.join(e.file_name());
        if e.file_type()?.is_dir() {
            std::fs::create_dir(&target)?;
            copy_tree(&e.path(), &target)?;
        } else {
            crate::workspace::reserve_copy(&target, e.metadata()?.len())?;
            std::fs::copy(e.path(), target)?;
        }
    }
    Ok(())
}
pub(super) fn rewrite_paths(
    path: &Path,
    bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
    original: &Path,
    effective: &Path,
) -> io::Result<()> {
    fn visit(
        value: &mut serde_json::Value,
        bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
        original: &Path,
        effective: &Path,
    ) {
        match value {
            serde_json::Value::String(s) => {
                let path = Path::new(s);
                if let Some((source, bound)) = bindings
                    .iter()
                    .filter(|(source, _)| path.starts_with(source))
                    .max_by_key(|(source, _)| source.components().count())
                {
                    let relative = path.strip_prefix(source).unwrap();
                    *s = if relative.as_os_str().is_empty() {
                        bound.clone()
                    } else {
                        bound.join(relative)
                    }
                    .to_string_lossy()
                    .into_owned();
                } else if let Ok(relative) = path.strip_prefix(original) {
                    *s = effective.join(relative).to_string_lossy().into_owned();
                }
            }
            serde_json::Value::Object(o) => {
                for v in o.values_mut() {
                    visit(v, bindings, original, effective);
                }
            }
            serde_json::Value::Array(a) => {
                for v in a {
                    visit(v, bindings, original, effective);
                }
            }
            _ => {}
        }
    }
    let mut value = serde_json::from_slice(&std::fs::read(path)?).map_err(io::Error::other)?;
    visit(&mut value, bindings, original, effective);
    atomic_json(path, &value)
}