scientific-workflow 0.7.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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! Logged integration coverage for standard project configuration.
//!
//! Run with:
//!
//! ```text
//! cargo test --test configuration_workflow -- --nocapture
//! ```

use std::error::Error;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use scientific_workflow::prelude::basics::*;
use serde::Serialize;
use serde::ser::Error as _;
use serde_json::Value;

static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);

struct UnencodableSelector;

impl Serialize for UnencodableSelector {
    fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        Err(S::Error::custom("intentional selector encoding failure"))
    }
}

struct TempWorkspace {
    root: PathBuf,
}

impl TempWorkspace {
    fn new() -> Self {
        let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "scientific-workflow-configuration-{}-{sequence}",
            std::process::id()
        ));
        fs::create_dir(&root).unwrap();
        Self { root }
    }

    fn project(&self, name: &str) -> PathBuf {
        self.root.join(name)
    }
}

impl Drop for TempWorkspace {
    fn drop(&mut self) {
        if let Err(error) = fs::remove_dir_all(&self.root) {
            eprintln!("[cleanup] {}: {error}", self.root.display());
        }
    }
}

fn fixture_project(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/configuration")
        .join(name)
}

fn write_project(root: &Path, fixed: &[u8], sweep: &[u8], paths: &[u8]) {
    let configuration = root.join("config");
    fs::create_dir_all(&configuration).unwrap();
    fs::write(configuration.join("fixed.json"), fixed).unwrap();
    fs::write(configuration.join("sweep.json"), sweep).unwrap();
    fs::write(configuration.join("paths.json"), paths).unwrap();
}

fn assert_send_sync<T: Send + Sync>() {}

#[test]
fn model_owned_schema_removes_the_project_state_file() {
    let workspace = TempWorkspace::new();
    let root = workspace.project("model-owned-schema");
    write_project(
        &root,
        br#"{"iterations":10}"#,
        br#"{"mode":"cartesian","axes":{}}"#,
        br#"{"recordings":"recordings"}"#,
    );
    let schema_path = fixture_project("cartesian_project").join("config/state.json");
    let schema = SystemStateSchema::load_json_template(&schema_path).unwrap();

    assert!(matches!(
        ScientificProject::load(&root),
        Err(ScientificProjectError::State(
            StateError::TemplateRead { .. }
        ))
    ));

    let project = ScientificProject::load_with_state_schema(&root, schema).unwrap();
    assert_eq!(project.task_count(), 1);
    assert_eq!(project.state_schema().template_path(), schema_path);
    assert!(project.state_schema().contains_field("population"));
    assert_eq!(
        project.resolve_path("recordings").unwrap(),
        root.join("recordings")
    );
    assert!(!root.join("config/state.json").exists());
}

#[test]
fn nested_fixed_and_sweep_documents_merge_at_unique_leaf_paths() {
    let workspace = TempWorkspace::new();
    let root = workspace.project("nested-parameters");
    write_project(
        &root,
        br#"{
            "kernel":{"kind":"power_law","cutoff":1.0},
            "pairing_rng":{"seed":17},
            "literal_shape":[4,8]
        }"#,
        br#"{
            "mode":"cartesian",
            "axes":{
                "kernel":{"mu":{"values":[0.2,0.8]}},
                "matrix":{"scale":{"values":[0.25,0.5]}}
            }
        }"#,
        br#"{}"#,
    );

    let project = ProjectConfig::load(&root).unwrap();
    assert_eq!(project.task_count(), 4);
    assert_eq!(project.parameters().fixed_parameter_count(), 4);
    assert_eq!(project.parameters().sweep_parameter_count(), 2);
    assert_eq!(
        project.parameters().fixed_keys().collect::<Vec<_>>(),
        [
            "/kernel/kind",
            "/kernel/cutoff",
            "/pairing_rng/seed",
            "/literal_shape"
        ]
    );
    assert_eq!(
        project.parameters().sweep_keys().collect::<Vec<_>>(),
        ["/kernel/mu", "/matrix/scale"]
    );

    let combinations = project
        .task_configs()
        .map(|task| {
            (
                task.decode_value::<f64>("/kernel/mu").unwrap(),
                task.decode_value::<f64>("/matrix/scale").unwrap(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(
        combinations,
        [(0.2, 0.25), (0.2, 0.5), (0.8, 0.25), (0.8, 0.5)]
    );

    let task = project.task_config(2).unwrap();
    let kernel: Value = task.decode_value("/kernel").unwrap();
    assert_eq!(kernel["kind"], "power_law");
    assert_eq!(kernel["cutoff"], 1.0);
    assert_eq!(kernel["mu"], 0.8);
    assert!(task.value("kernel.mu").is_none());
    assert!(task.value("kernel").is_none());
    let resolved: Value = serde_json::from_str(&task.parameters().to_json().unwrap()).unwrap();
    assert_eq!(resolved["kernel"], kernel);
    assert!(resolved.get("/kernel/mu").is_none());

    let resolved_path = workspace.root.join("resolved-task.json");
    task.write_resolved_json(&resolved_path).unwrap();
    task.write_resolved_json(&resolved_path).unwrap();
    let complete: Value = serde_json::from_slice(&fs::read(&resolved_path).unwrap()).unwrap();
    assert_eq!(complete["parameters"]["kernel"], kernel);
    assert_eq!(complete["paths"], serde_json::json!({}));
    fs::write(&resolved_path, b"{}\n").unwrap();
    assert!(matches!(
        task.write_resolved_json(&resolved_path),
        Err(ConfigurationError::ResolvedTaskConfigConflict { .. })
    ));

    let composite_root = workspace.project("composite-axis");
    write_project(
        &composite_root,
        br#"{}"#,
        br#"{
            "mode":"cases",
            "cases":[
                {"species":{"num_taxa":128,"interaction":{"path_key":"interaction_K_128"}}},
                {"species":{"num_taxa":256,"interaction":{"path_key":"interaction_K_256"}}}
            ]
        }"#,
        br#"{}"#,
    );
    let composite = ProjectConfig::load(&composite_root).unwrap();
    assert_eq!(composite.task_count(), 2);
    let species: Value = composite
        .task_config(1)
        .unwrap()
        .decode_value("/species")
        .unwrap();
    assert_eq!(species["num_taxa"], 256);
    assert_eq!(species["interaction"]["path_key"], "interaction_K_256");

    let conflict_root = workspace.project("nested-conflict");
    write_project(
        &conflict_root,
        br#"{"kernel":{"mu":0.4}}"#,
        br#"{"mode":"cartesian","axes":{"kernel":{"mu":{"values":[0.2,0.8]}}}}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&conflict_root),
        Err(ConfigurationError::FixedSweepKeyConflict { key, .. }) if key == "/kernel/mu"
    ));
}

#[test]
fn project_configuration_expands_round_trips_and_rejects_ambiguity() {
    assert_send_sync::<ParameterSpace>();
    assert_send_sync::<TaskParameters>();
    assert_send_sync::<TaskParametersIter>();
    assert_send_sync::<TaskConfig>();
    assert_send_sync::<TaskConfigIter>();
    assert_send_sync::<MatchingTaskConfigIter>();
    assert_send_sync::<ProjectPaths>();
    assert_send_sync::<ProjectConfig>();
    assert_send_sync::<ScientificProject>();
    assert_send_sync::<ExecutionScope>();

    let cartesian_root = fixture_project("cartesian_project");
    let scientific_project = ScientificProject::load(&cartesian_root).unwrap();
    assert_eq!(scientific_project.state_schema().len(), 2);
    assert!(
        scientific_project
            .state_schema()
            .contains_field("population")
    );
    assert_eq!(scientific_project.parameters().task_count(), 6);
    assert_eq!(scientific_project.task_count(), 6);
    assert_eq!(scientific_project.task_configs().count(), 6);
    assert_eq!(scientific_project.task_config(5).unwrap().task_ordinal(), 5);
    assert_eq!(
        scientific_project
            .task_configs_matching("/temperature", 300.0)
            .unwrap()
            .count(),
        3
    );
    assert!(matches!(
        scientific_project.unique_task_config_matching("/temperature", 300.0),
        Err(ConfigurationError::AmbiguousTaskConfiguration { key })
            if key == "/temperature"
    ));
    assert_eq!(
        scientific_project.resolve_path("output_root").unwrap(),
        cartesian_root.join("results")
    );
    assert!(format!("{scientific_project:?}").contains("state_fields"));
    let project = ProjectConfig::load(&cartesian_root).unwrap();
    assert_eq!(project.task_count(), 6);
    assert_eq!(project.project_root(), cartesian_root);
    assert_eq!(
        project.configuration_directory(),
        cartesian_root.join("config")
    );
    let parameters = project.parameters();
    assert_eq!(
        parameters.configuration_directory(),
        cartesian_root.join("config")
    );
    assert_eq!(parameters.fixed_parameter_count(), 4);
    assert_eq!(parameters.sweep_parameter_count(), 2);
    assert_eq!(parameters.parameter_count(), 6);
    assert_eq!(parameters.task_count(), 6);
    assert!(parameters.contains_parameter("/temperature"));
    assert!(!parameters.contains_parameter("missing"));
    assert_eq!(
        parameters.fixed_keys().collect::<Vec<_>>(),
        [
            "/physical_time_increment",
            "/lattice_shape",
            "/solver/method",
            "/solver/tolerance"
        ]
    );
    assert_eq!(
        parameters.sweep_keys().collect::<Vec<_>>(),
        ["/temperature", "/seed"]
    );
    assert_eq!(
        parameters.fixed_source_json(),
        fs::read(cartesian_root.join("config/fixed.json"))
            .unwrap()
            .as_slice()
    );
    assert_eq!(
        parameters.sweep_source_json(),
        fs::read(cartesian_root.join("config/sweep.json"))
            .unwrap()
            .as_slice()
    );
    println!(
        "[load] fixed={} swept={} parameters={} tasks={} paths={}",
        parameters.fixed_parameter_count(),
        parameters.sweep_parameter_count(),
        parameters.parameter_count(),
        parameters.task_count(),
        project.paths().len()
    );

    let combinations = parameters
        .tasks()
        .map(|task| {
            (
                task.task_ordinal(),
                task.decode_value::<f64>("/temperature").unwrap(),
                task.decode_value::<u64>("/seed").unwrap(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(
        combinations,
        [
            (0, 280.0, 7),
            (1, 280.0, 11),
            (2, 280.0, 13),
            (3, 300.0, 7),
            (4, 300.0, 11),
            (5, 300.0, 13),
        ]
    );

    let complete_configs = project
        .task_configs()
        .map(|task| {
            (
                task.task_ordinal(),
                task.decode_value::<f64>("/temperature").unwrap(),
                task.decode_value::<u64>("/seed").unwrap(),
                task.resolve_path("output_root").unwrap(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(complete_configs.len(), 6);
    assert_eq!(complete_configs[0].0, 0);
    assert_eq!(complete_configs[5].0, 5);
    assert_eq!(complete_configs[0].1, 280.0);
    assert_eq!(complete_configs[5].2, 13);
    assert!(
        complete_configs
            .iter()
            .all(|task| task.3 == cartesian_root.join("results"))
    );

    let matching = project
        .task_configs_matching("/temperature", 280.0)
        .unwrap();
    assert_eq!(matching.size_hint(), (0, Some(6)));
    let selected = matching
        .map(|task| task.decode_value::<u64>("/seed").unwrap())
        .collect::<Vec<_>>();
    assert_eq!(selected, [7, 11, 13]);
    assert!(matches!(
        project.unique_task_config_matching("/temperature", 280.0),
        Err(ConfigurationError::AmbiguousTaskConfiguration { key })
            if key == "/temperature"
    ));
    assert!(matches!(
        project.unique_task_config_matching("/temperature", 999.0),
        Err(ConfigurationError::NoMatchingTaskConfiguration { key })
            if key == "/temperature"
    ));
    assert!(matches!(
        project.task_configs_matching("/solver", "euler"),
        Err(ConfigurationError::UnknownSweepParameter { key }) if key == "/solver"
    ));
    let selector_error = project
        .task_configs_matching("/temperature", UnencodableSelector)
        .unwrap_err();
    assert!(matches!(
        selector_error,
        ConfigurationError::EncodeTaskSelection { ref key, .. }
            if key == "/temperature"
    ));
    assert!(selector_error.source().unwrap().is::<serde_json::Error>());

    let complete = project.task_config(4).unwrap();
    let complete_clone = complete.clone();
    assert_eq!(complete.task_ordinal(), 4);
    assert_eq!(complete.parameters().task_ordinal(), 4);
    assert_eq!(complete.paths().len(), 3);
    assert_eq!(complete.require_value("/temperature").unwrap(), 300.0);
    assert_eq!(
        complete.value("/solver").unwrap(),
        complete_clone.value("/solver").unwrap()
    );
    assert!(std::ptr::eq(
        complete.value("/solver/method").unwrap(),
        complete_clone.value("/solver/method").unwrap()
    ));
    assert!(std::ptr::eq(
        complete.paths().path("output_root").unwrap(),
        complete_clone.paths().path("output_root").unwrap()
    ));
    assert!(format!("{complete:?}").contains("task_ordinal"));
    let detached_tasks = project.clone().task_configs();
    assert_eq!(detached_tasks.size_hint(), (6, Some(6)));
    let mut copied_tasks = detached_tasks.clone();
    assert_eq!(copied_tasks.next().unwrap().task_ordinal(), 0);
    assert_eq!(detached_tasks.count(), 6);
    assert!(format!("{copied_tasks:?}").contains("parameters"));
    assert!(
        format!(
            "{:?}",
            project
                .task_configs_matching("/temperature", 300.0)
                .unwrap()
        )
        .contains("/temperature")
    );
    println!(
        "[task-config] all={} selected={} shared_paths=true exact_match=true ambiguity_rejected=true",
        complete_configs.len(),
        selected.len()
    );
    println!(
        "[cartesian] tasks={} last_axis_fastest=true first=({}, {}) last=({}, {})",
        combinations.len(),
        combinations[0].1,
        combinations[0].2,
        combinations[5].1,
        combinations[5].2
    );

    let first = parameters.task(0).unwrap();
    let second = parameters.task(1).unwrap();
    let (dt, shape, solver, temperature, seed): (f64, Vec<u64>, Value, f64, u64) = first
        .decode_values((
            "/physical_time_increment",
            "/lattice_shape",
            "/solver",
            "/temperature",
            "/seed",
        ))
        .unwrap();
    assert_eq!(dt, 0.125);
    assert_eq!(shape, [4, 8]);
    assert_eq!(solver["method"], "rk4");
    assert_eq!((temperature, seed), (280.0, 7));
    let twelve: (u64, u64, u64, u64, u64, u64, u64, u64, u64, u64, u64, u64) = first
        .decode_values((
            "/seed", "/seed", "/seed", "/seed", "/seed", "/seed", "/seed", "/seed", "/seed",
            "/seed", "/seed", "/seed",
        ))
        .unwrap();
    assert_eq!(twelve, (7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7));
    let copied = first.clone();
    assert_eq!(first.task_ordinal(), 0);
    assert_eq!(first.len(), 6);
    assert!(!first.is_empty());
    assert!(first.contains("/solver"));
    assert!(!first.contains("unknown"));
    assert_eq!(
        first.keys().collect::<Vec<_>>(),
        [
            "/physical_time_increment",
            "/lattice_shape",
            "/solver/method",
            "/solver/tolerance",
            "/temperature",
            "/seed"
        ]
    );
    assert_eq!(first.iter().count(), 6);
    assert!(std::ptr::eq(
        first.value("/physical_time_increment").unwrap(),
        second.value("/physical_time_increment").unwrap()
    ));
    assert!(std::ptr::eq(
        first.value("/temperature").unwrap(),
        second.value("/temperature").unwrap()
    ));
    assert!(std::ptr::eq(
        first.value("/seed").unwrap(),
        copied.value("/seed").unwrap()
    ));
    assert_eq!(
        first.require_value("/lattice_shape").unwrap(),
        &serde_json::json!([4, 8])
    );
    assert_eq!(
        first.decode_value::<Vec<usize>>("/lattice_shape").unwrap(),
        [4, 8]
    );
    let resolved_json = first.to_json().unwrap();
    let resolved: Value = serde_json::from_str(&resolved_json).unwrap();
    assert_eq!(resolved["physical_time_increment"], 0.125);
    assert_eq!(resolved["temperature"], 280.0);
    assert_eq!(resolved["seed"], 7);
    let key_positions = [
        resolved_json.find("physical_time_increment").unwrap(),
        resolved_json.find("lattice_shape").unwrap(),
        resolved_json.find("solver").unwrap(),
        resolved_json.find("temperature").unwrap(),
        resolved_json.find("seed").unwrap(),
    ];
    assert!(key_positions.windows(2).all(|pair| pair[0] < pair[1]));
    assert!(format!("{parameters:?}").contains("task_count"));
    assert!(format!("{first:?}").contains("task_ordinal"));
    println!("[ownership] leaf_values_shared=true nested_documents_rehydrated_lazily=true");

    let mut owning_iter = parameters.tasks();
    assert_eq!(owning_iter.size_hint(), (6, Some(6)));
    let mut copied_iter = owning_iter.clone();
    assert_eq!(owning_iter.next().unwrap().task_ordinal(), 0);
    assert_eq!(copied_iter.next().unwrap().task_ordinal(), 0);
    assert!(format!("{owning_iter:?}").contains("next"));
    let independent_iter = project.parameters().tasks();
    let project_clone = project.clone();
    drop(project);
    assert_eq!(independent_iter.count(), 6);
    let (separated_parameters, separated_paths) = project_clone.clone().into_parts();
    assert_eq!(separated_parameters.task_count(), 6);
    assert_eq!(separated_paths.len(), 3);

    let paths = project_clone.paths();
    assert_eq!(paths.project_root(), cartesian_root);
    assert_eq!(
        paths.source_path(),
        cartesian_root.join("config/paths.json")
    );
    assert_eq!(
        paths.source_json(),
        fs::read(cartesian_root.join("config/paths.json"))
            .unwrap()
            .as_slice()
    );
    assert!(!paths.is_empty());
    assert!(paths.contains("input_data"));
    assert_eq!(paths.path("input_data"), Some(Path::new("data/input.json")));
    assert_eq!(
        paths.require_path("output_root").unwrap(),
        Path::new("results")
    );
    assert_eq!(
        paths.resolve_path("input_data").unwrap(),
        cartesian_root.join("data/input.json")
    );
    assert_eq!(
        paths.keys().collect::<Vec<_>>(),
        ["input_data", "output_root", "cache"]
    );
    assert_eq!(paths.iter().count(), 3);
    assert!(format!("{paths:?}").contains("entries"));
    println!(
        "[paths] declared={} relative_resolution=true canonicalization=false existence_check=false",
        paths.len()
    );

    let workspace = TempWorkspace::new();
    let generated_scope =
        ExecutionScope::create_generated(workspace.project("recordings")).unwrap();
    assert!(generated_scope.directory().is_dir());
    assert!(generated_scope.created_at_utc().unwrap().ends_with('Z'));
    let task_recording = generated_scope.task_recording_directory(12);
    assert!(task_recording.ends_with("task-000012"));
    assert!(!task_recording.exists());
    let semantic_recording = generated_scope
        .named_task_recording_directory("K=600-mode=default-mu=0.20-sys=0")
        .unwrap();
    assert!(semantic_recording.ends_with("K=600-mode=default-mu=0.20-sys=0"));
    let nested_recording = generated_scope
        .named_task_recording_directory("K=600/kernel=flat_scale=0.25")
        .unwrap();
    assert!(nested_recording.ends_with("K=600/kernel=flat_scale=0.25"));
    assert!(matches!(
        generated_scope.named_task_recording_directory("../unsafe"),
        Err(ExecutionScopeError::InvalidName { .. })
    ));
    let reopened = ExecutionScope::open_existing(generated_scope.directory()).unwrap();
    assert_eq!(reopened.directory(), generated_scope.directory());
    assert_eq!(reopened.created_at_utc(), None);
    let named_scope =
        ExecutionScope::create_named(workspace.project("recordings"), "reference-run").unwrap();
    assert!(named_scope.directory().ends_with("reference-run"));
    assert!(matches!(
        ExecutionScope::create_named(workspace.project("recordings"), "../unsafe"),
        Err(ExecutionScopeError::InvalidName { .. })
    ));
    let deterministic =
        ExecutionScope::open_or_create(workspace.project("deterministic-recordings")).unwrap();
    assert!(
        deterministic
            .directory()
            .ends_with("deterministic-recordings")
    );
    assert_eq!(deterministic.created_at_utc(), None);
    println!(
        "[execution-scope] generated={} named={} task_path={} timestamp_managed=true",
        generated_scope.directory().display(),
        named_scope.directory().display(),
        task_recording.display()
    );
    let copied_root = workspace.project("copied");
    project_clone.write_source_config(&copied_root).unwrap();
    for name in ["fixed.json", "sweep.json", "paths.json"] {
        assert_eq!(
            fs::read(cartesian_root.join("config").join(name)).unwrap(),
            fs::read(copied_root.join("config").join(name)).unwrap()
        );
    }
    let copied_project = ProjectConfig::load(&copied_root).unwrap();
    assert_eq!(copied_project.parameters().task_count(), 6);
    let overwrite = project_clone
        .write_source_config(&copied_root)
        .expect_err("exact export must never replace an existing config directory");
    assert!(matches!(
        overwrite,
        ConfigurationError::WriteConfigurationFile { ref path, .. }
            if path == &copied_root.join("config")
    ));
    assert_eq!(
        overwrite
            .source()
            .and_then(|source| source.downcast_ref::<io::Error>())
            .map(io::Error::kind),
        Some(io::ErrorKind::AlreadyExists)
    );
    println!(
        "[round-trip] fixed_bytes=true sweep_bytes=true paths_bytes=true reload=true overwrite_rejected=true"
    );

    let bounds = separated_parameters.task(6).unwrap_err();
    assert!(matches!(
        bounds,
        ConfigurationError::TaskOrdinalOutOfBounds {
            ordinal: 6,
            task_count: 6
        }
    ));
    assert!(matches!(
        first.require_value("/unknown"),
        Err(ConfigurationError::UnknownTaskParameter { task_ordinal: 0, key })
            if key == "/unknown"
    ));
    let decode = first.decode_value::<String>("/temperature").unwrap_err();
    assert!(matches!(
        decode,
        ConfigurationError::DecodeTaskParameter { task_ordinal: 0, ref key, .. }
            if key == "/temperature"
    ));
    assert!(decode.source().unwrap().is::<serde_json::Error>());
    assert!(matches!(
        separated_paths.require_path("unknown"),
        Err(ConfigurationError::UnknownProjectPath { key }) if key == "unknown"
    ));
    println!("[lookup-errors] bounds=true missing=true type=true path=true");

    let cases_root = fixture_project("cases_project");
    let cases = ProjectConfig::load(&cases_root).unwrap();
    assert_eq!(cases.parameters().task_count(), 3);
    assert_eq!(
        cases.parameters().sweep_keys().collect::<Vec<_>>(),
        ["/temperature", "/physical_time_increment"]
    );
    let correlated = cases
        .parameters()
        .tasks()
        .map(|task| {
            (
                task.decode_value::<f64>("/temperature").unwrap(),
                task.decode_value::<f64>("/physical_time_increment")
                    .unwrap(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(correlated, [(275.0, 0.2), (290.0, 0.1), (310.0, 0.05)]);
    let unique = cases
        .unique_task_config_matching("/temperature", 290.0)
        .unwrap();
    assert_eq!(unique.task_ordinal(), 1);
    assert_eq!(
        unique
            .decode_value::<f64>("/physical_time_increment")
            .unwrap(),
        0.1
    );
    assert_eq!(
        cases
            .parameters()
            .task(1)
            .unwrap()
            .keys()
            .collect::<Vec<_>>(),
        [
            "/lattice_shape",
            "/integrator",
            "/temperature",
            "/physical_time_increment"
        ]
    );
    println!(
        "[cases] tasks={} correlated=true key_order_normalized=true",
        correlated.len()
    );

    let fixed_only_root = workspace.project("fixed-only");
    write_project(
        &fixed_only_root,
        br#"{}"#,
        br#"{"mode":"cartesian","axes":{}}"#,
        br#"{}"#,
    );
    let fixed_only = ProjectConfig::load(&fixed_only_root).unwrap();
    assert_eq!(fixed_only.parameters().task_count(), 1);
    let empty_task = fixed_only.parameters().task(0).unwrap();
    assert!(empty_task.is_empty());
    assert_eq!(empty_task.to_json().unwrap(), "{}");
    assert!(fixed_only.paths().is_empty());

    let duplicate_root = workspace.project("duplicate");
    write_project(
        &duplicate_root,
        br#"{"solver":{"method":"rk4","method":"euler"}}"#,
        br#"{"mode":"cartesian","axes":{}}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&duplicate_root),
        Err(ConfigurationError::DuplicateConfigurationKey { key, .. }) if key == "method"
    ));

    let overlap_root = workspace.project("overlap");
    write_project(
        &overlap_root,
        br#"{"temperature":300}"#,
        br#"{"mode":"cartesian","axes":{"temperature":{"values":[280,300]}}}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&overlap_root),
        Err(ConfigurationError::FixedSweepKeyConflict { key, .. })
            if key == "/temperature"
    ));

    let legacy_axes_root = workspace.project("legacy-axes");
    write_project(
        &legacy_axes_root,
        br#"{}"#,
        br#"{"mode":"cartesian","axes":[{"name":"temperature","values":[280,300]}]}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&legacy_axes_root),
        Err(ConfigurationError::InvalidConfigurationDocument { ref path, .. })
            if path == &legacy_axes_root.join("config/sweep.json")
    ));

    let object_candidate_root = workspace.project("cartesian-object-candidate");
    write_project(
        &object_candidate_root,
        br#"{}"#,
        br#"{
            "mode":"cartesian",
            "axes":{
                "species":{"values":[
                    {"num_taxa":128,"interaction":{"path_key":"K_128"}},
                    {"interaction":{"path_key":"K_256"},"num_taxa":256}
                ]},
                "scale":{"values":[0.5,1.0]}
            }
        }"#,
        br#"{}"#,
    );
    let object_candidates = ProjectConfig::load(&object_candidate_root).unwrap();
    assert_eq!(object_candidates.task_count(), 4);
    assert_eq!(
        object_candidates
            .parameters()
            .sweep_keys()
            .collect::<Vec<_>>(),
        ["/species", "/scale"]
    );
    let species: Value = object_candidates
        .task_config(2)
        .unwrap()
        .decode_value("/species")
        .unwrap();
    assert_eq!(species["num_taxa"], 256);
    assert_eq!(species["interaction"]["path_key"], "K_256");
    assert_eq!(
        object_candidates
            .task_config(2)
            .unwrap()
            .decode_value::<f64>("/scale")
            .unwrap(),
        0.5
    );
    assert_eq!(
        object_candidates
            .task_configs_matching(
                "/species",
                serde_json::json!({
                    "num_taxa": 256,
                    "interaction": {"path_key": "K_256"}
                }),
            )
            .unwrap()
            .count(),
        2
    );

    let inconsistent_object_root = workspace.project("inconsistent-cartesian-object-candidate");
    write_project(
        &inconsistent_object_root,
        br#"{}"#,
        br#"{"mode":"cartesian","axes":{"species":{"values":[{"num_taxa":128},{"num_taxa":256,"label":"K=256"}]}}}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&inconsistent_object_root),
        Err(ConfigurationError::InvalidConfigurationDocument { ref path, ref reason })
            if path == &inconsistent_object_root.join("config/sweep.json")
                && reason.contains("same flattened key set")
    ));

    let inconsistent_root = workspace.project("inconsistent");
    write_project(
        &inconsistent_root,
        br#"{}"#,
        br#"{"mode":"cases","cases":[{"a":1},{"b":2}]}"#,
        br#"{}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&inconsistent_root),
        Err(ConfigurationError::InvalidConfigurationDocument { ref path, .. })
            if path == &inconsistent_root.join("config/sweep.json")
    ));

    let invalid_path_root = workspace.project("invalid-path");
    write_project(
        &invalid_path_root,
        br#"{}"#,
        br#"{"mode":"cartesian","axes":{}}"#,
        br#"{"output_root":42}"#,
    );
    assert!(matches!(
        ProjectConfig::load(&invalid_path_root),
        Err(ConfigurationError::InvalidConfigurationDocument { ref path, .. })
            if path == &invalid_path_root.join("config/paths.json")
    ));
    println!(
        "[validation] fixed_only=true nested_duplicate=true overlap=true legacy_axes_rejected=true object_candidates=true inconsistent_object_candidates_rejected=true inconsistent_cases=true invalid_path=true"
    );
    println!("[result] configuration_workflow=passed");
}