quilt-rs 0.34.0

Rust library for accessing Quilt data packages.
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
//! Tests for configuring a package's remote via `set_remote`.

use super::*;

use test_log::test;

use aws_sdk_s3::primitives::ByteStream;

use crate::io::remote::WorkflowIntent;
use crate::io::remote::mocks::MockRemote;
use crate::lineage::DomainLineageIo;
use crate::lineage::Home;
use crate::lineage::PackageLineageIo;
use crate::manifest::ManifestHeader;
use crate::object_hash::ObjectHash;
use crate::paths::DomainPaths;
use crate::workflow::RuleViolation;
use crate::workflow::WorkflowValidationError;

#[test(tokio::test)]
async fn test_set_remote_on_local_package() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "local").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/local": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    let lineage = package.lineage().await?;
    let remote_uri = lineage
        .remote_uri
        .as_ref()
        .expect("remote_uri should be set");
    assert_eq!(
        remote_uri.origin.as_ref().unwrap().to_string(),
        "example.com"
    );
    assert_eq!(remote_uri.bucket, "my-bucket");
    assert_eq!(remote_uri.hash, "");

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_empty_bucket_error() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "local").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/local": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    let result = package
        .set_remote(
            String::new(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await;

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Bucket cannot be empty"),
        "Error should mention empty bucket"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_rejects_unreachable_bucket() -> Res {
    use crate::error::RemoteCatalogError;

    /// Remote that rejects any `verify_bucket` call — models the case
    /// where the user typed a bucket that doesn't resolve on S3.
    struct BadBucketRemote;

    impl Remote for BadBucketRemote {
        async fn exists(&self, _host: Option<&Host>, _s3_uri: &S3Uri) -> Res<bool> {
            unreachable!("test only exercises verify_bucket")
        }
        async fn get_object_stream(
            &self,
            _host: Option<&Host>,
            _s3_uri: &S3Uri,
        ) -> Res<crate::io::remote::RemoteObjectStream> {
            unreachable!("test only exercises verify_bucket")
        }
        async fn resolve_url(&self, _host: Option<&Host>, _s3_uri: &S3Uri) -> Res<S3Uri> {
            unreachable!("test only exercises verify_bucket")
        }
        async fn put_object(
            &self,
            _host: Option<&Host>,
            _s3_uri: &S3Uri,
            _contents: impl Into<aws_sdk_s3::primitives::ByteStream>,
        ) -> Res {
            unreachable!("test only exercises verify_bucket")
        }
        async fn upload_file(
            &self,
            _host_config: &crate::io::remote::HostConfig,
            _source_path: impl AsRef<std::path::Path>,
            _dest_uri: &S3Uri,
            _size: u64,
        ) -> Res<(S3Uri, ObjectHash)> {
            unreachable!("test only exercises verify_bucket")
        }
        async fn host_config(&self, _host: Option<&Host>) -> Res<crate::io::remote::HostConfig> {
            Ok(crate::io::remote::HostConfig::default())
        }
        async fn verify_bucket(&self, bucket: &str) -> Res {
            Err(RemoteCatalogError::BucketUnreachable(bucket.to_string()).into())
        }
    }

    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let namespace: Namespace = ("test", "badbucket").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/badbucket": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote: BadBucketRemote,
        storage,
        namespace,
    };

    let result = package
        .set_remote(
            "typo-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await;

    assert!(result.is_err());
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("typo-bucket") && msg.contains("not reachable"),
        "error should name the bucket and say it's unreachable, got: {msg}"
    );

    // The remote must NOT have been persisted — pre-flight should fail
    // before any lineage write.
    let lineage = package.lineage().await?;
    assert!(
        lineage.remote_uri.is_none(),
        "remote_uri should not be persisted when verify_bucket fails",
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_rejects_change_on_pushed_package() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "overwrite").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/overwrite": {
                "commit": null,
                "remote": {
                    "bucket": "old-bucket",
                    "namespace": "test/overwrite",
                    "hash": "abc123",
                    "origin": "old.host"
                },
                "base_hash": "abc123",
                "latest_hash": "abc123",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    let result = package
        .set_remote(
            "new-bucket".to_string(),
            Some("new.host".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await;

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Cannot change remote"),
        "Should reject changing remote on a pushed package"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_is_idempotent_on_pushed_package() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "idempotent").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/idempotent": {
                "commit": null,
                "remote": {
                    "bucket": "my-bucket",
                    "namespace": "test/idempotent",
                    "hash": "abc123",
                    "origin": "my.host"
                },
                "base_hash": "abc123",
                "latest_hash": "abc123",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    // Same bucket+origin as existing — should be a no-op
    package
        .set_remote(
            "my-bucket".to_string(),
            Some("my.host".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    let lineage = package.lineage().await?;
    let remote_uri = lineage
        .remote_uri
        .as_ref()
        .expect("remote_uri should be set");
    assert_eq!(remote_uri.hash, "abc123", "hash should be preserved");

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_overwrites_unpushed_remote() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "unpushed").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/unpushed": {
                "commit": null,
                "remote": {
                    "bucket": "old-bucket",
                    "namespace": "test/unpushed",
                    "hash": "",
                    "origin": "old.host"
                },
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    package
        .set_remote(
            "new-bucket".to_string(),
            Some("new.host".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    let lineage = package.lineage().await?;
    let remote_uri = lineage
        .remote_uri
        .as_ref()
        .expect("remote_uri should be set");
    assert_eq!(remote_uri.origin.as_ref().unwrap().to_string(), "new.host");
    assert_eq!(remote_uri.bucket, "new-bucket");
    assert_eq!(remote_uri.hash, "", "hash should remain empty");

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_recommits_existing_commit() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "recommit").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    // Start with no remote and no commit
    let lineage_json = r#"{
        "packages": {
            "test/recommit": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Write a file to package home so commit has something to pick up
    let package_home = home.join(namespace.to_string());
    storage.create_dir_all(&package_home).await?;
    storage
        .write_byte_stream(
            package_home.join("data.txt"),
            ByteStream::from_static(b"hello world"),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace: namespace.clone(),
    };

    // Commit the package (no remote yet, uses default HostConfig)
    let commit = package
        .commit(
            "Initial commit".to_string(),
            UserMeta::Set(serde_json::json!({"key": "value"})),
            None,
            None,
        )
        .await?;
    let hash_before = commit.hash.clone();

    // Now set_remote — this should trigger recommit.
    // MockRemote returns HostConfig::default() (SHA256 chunked), same as the
    // initial commit, so the row hashes stay the same. But the manifest is
    // rebuilt (e.g. workflow may change), and the lineage prev_hashes are updated.
    package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    let lineage = package.lineage().await?;

    // Remote should be set
    let remote_uri = lineage
        .remote_uri
        .as_ref()
        .expect("remote_uri should be set");
    assert_eq!(
        remote_uri.origin.as_ref().unwrap().to_string(),
        "example.com"
    );
    assert_eq!(remote_uri.bucket, "my-bucket");

    // Recommit should have produced a new commit
    let new_commit = lineage.commit.as_ref().expect("commit should exist");
    assert_eq!(
        new_commit.prev_hashes.first(),
        Some(&hash_before),
        "Old hash should be in prev_hashes after recommit"
    );

    // The new manifest should be readable with preserved message and meta
    let manifest_path = package
        .paths
        .installed_manifest(&namespace, &new_commit.hash);
    let manifest = Manifest::from_path(&package.storage, &manifest_path).await?;
    assert_eq!(
        manifest.header.message,
        Some("Initial commit".to_string()),
        "Message should be preserved after recommit"
    );
    assert_eq!(
        manifest.header.user_meta,
        Some(serde_json::json!({"key": "value"})),
        "User meta should be preserved after recommit"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_resolve_workflow_without_remote_is_none_for_every_intent() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "noremote").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let lineage_json = r#"{
        "packages": {
            "test/noremote": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    for intent in [
        WorkflowIntent::BucketDefault,
        WorkflowIntent::NoWorkflow,
        WorkflowIntent::Named("foo".to_string()),
    ] {
        assert!(
            package.resolve_workflow(intent.clone()).await?.is_none(),
            "no-remote short-circuit should return None for {intent:?}"
        );
    }

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_recommit_picks_up_bucket_default() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "bucketdefault").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    // The target bucket declares a `default_workflow`.
    let config_uri: S3Uri = "s3://my-bucket/.quilt/workflows/config.yml".parse()?;
    let config = r"
version: '1'
default_workflow: foo
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";
    let schema_uri: S3Uri = "s3://my-bucket/schemas/test.json".parse()?;
    remote
        .put_object(None, &config_uri, config.as_bytes().to_vec())
        .await?;
    remote.put_object(None, &schema_uri, b"{}".to_vec()).await?;

    // Start with no remote and no commit
    let lineage_json = r#"{
        "packages": {
            "test/bucketdefault": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Write a file to package home so commit has something to pick up
    let package_home = home.join(namespace.to_string());
    storage.create_dir_all(&package_home).await?;
    storage
        .write_byte_stream(
            package_home.join("data.txt"),
            ByteStream::from_static(b"hello world"),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace: namespace.clone(),
    };

    // Commit the package locally (no remote yet, so no workflow stamped)
    package
        .commit(
            "Initial commit".to_string(),
            UserMeta::Set(serde_json::json!({"key": "value"})),
            None,
            None,
        )
        .await?;

    // set_remote triggers recommit, which must stamp the bucket default.
    let outcome = package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;
    assert!(
        outcome.resolution_warning.is_none(),
        "a clean bucket-default resolution must not produce a warning"
    );

    let lineage = package.lineage().await?;
    let new_commit = lineage.commit.as_ref().expect("commit should exist");
    let manifest_path = package
        .paths
        .installed_manifest(&namespace, &new_commit.hash);
    let manifest = Manifest::from_path(&package.storage, &manifest_path).await?;

    let workflow = manifest
        .header
        .workflow
        .expect("recommit should stamp a workflow from the bucket default");
    assert_eq!(
        workflow.id.expect("workflow id should be set").id,
        "foo",
        "recommit should pick up the bucket's default_workflow"
    );

    Ok(())
}

/// `set_remote` against a governed bucket must fetch the workflows config
/// exactly once: resolution and the recommit workflow gate share the single
/// fetched/parsed config rather than each downloading it. The `gate` workflow
/// declares a permissive metadata schema, so both the config and the schema
/// document are fetched — and each exactly once.
#[test(tokio::test)]
async fn test_set_remote_fetches_config_and_schema_once() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", "fetchonce").into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let config_uri_str = "s3://my-bucket/.quilt/workflows/config.yml";
    let schema_uri_str = "s3://my-bucket/schemas/test.json";
    let config_uri: S3Uri = config_uri_str.parse()?;
    let config = r"
version: '1'
default_workflow: foo
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";
    let schema_uri: S3Uri = schema_uri_str.parse()?;
    remote
        .put_object(None, &config_uri, config.as_bytes().to_vec())
        .await?;
    remote.put_object(None, &schema_uri, b"{}".to_vec()).await?;

    let lineage_json = r#"{
        "packages": {
            "test/fetchonce": {
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {}
            }
        },
        "home": "/tmp/working_dir"
    }"#;
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let package_home = home.join(namespace.to_string());
    storage.create_dir_all(&package_home).await?;
    storage
        .write_byte_stream(
            package_home.join("data.txt"),
            ByteStream::from_static(b"hello world"),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace: namespace.clone(),
    };

    package
        .commit(
            "Initial commit".to_string(),
            UserMeta::Set(serde_json::json!({"key": "value"})),
            None,
            None,
        )
        .await?;

    package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    assert_eq!(
        package.remote.get_object_count(config_uri_str),
        1,
        "config.yml must be fetched exactly once across set_remote"
    );
    assert_eq!(
        package.remote.get_object_count(schema_uri_str),
        1,
        "the schema document must be fetched exactly once across set_remote"
    );

    Ok(())
}

/// Set up a locally-committed package against a bucket whose config declares a
/// `foo` workflow but no `default_workflow`, run `set_remote` with `intent`, and
/// return the recommitted manifest's header. The absence of `default_workflow`
/// is what lets the assertions distinguish the caller's chosen intent from the
/// bucket-default fallback. The config sets `is_workflow_required: false` so
/// these tests exercise stamping mechanics only — an id-less record is
/// admissible and the workflow gate never interferes (enforcement of a
/// required workflow has its own tests below).
async fn recommit_manifest_for_intent(slug: &str, intent: WorkflowIntent) -> Res<ManifestHeader> {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", slug).into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    // The target bucket declares `foo` but no `default_workflow`, so the
    // no-gesture (BucketDefault) path would stamp an id-less record.
    let config_uri: S3Uri = "s3://my-bucket/.quilt/workflows/config.yml".parse()?;
    let config = r"
version: '1'
is_workflow_required: false
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";
    let schema_uri: S3Uri = "s3://my-bucket/schemas/test.json".parse()?;
    remote
        .put_object(None, &config_uri, config.as_bytes().to_vec())
        .await?;
    remote.put_object(None, &schema_uri, b"{}".to_vec()).await?;

    let lineage_json = format!(
        r#"{{
        "packages": {{
            "test/{slug}": {{
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {{}}
            }}
        }},
        "home": "/tmp/working_dir"
    }}"#
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let package_home = home.join(namespace.to_string());
    storage.create_dir_all(&package_home).await?;
    storage
        .write_byte_stream(
            package_home.join("data.txt"),
            ByteStream::from_static(b"hello world"),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace: namespace.clone(),
    };

    package
        .commit(
            "Initial commit".to_string(),
            UserMeta::Set(serde_json::json!({"key": "value"})),
            None,
            None,
        )
        .await?;

    package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            intent,
        )
        .await?;

    let lineage = package.lineage().await?;
    let new_commit = lineage.commit.as_ref().expect("commit should exist");
    let manifest_path = package
        .paths
        .installed_manifest(&namespace, &new_commit.hash);
    let manifest = Manifest::from_path(&package.storage, &manifest_path).await?;
    Ok(manifest.header)
}

/// The workflows config used by the `package_with_config` tests unless they
/// need another one: a `foo` workflow, no `default_workflow`, and (since
/// `is_workflow_required` is omitted) a workflow required by default.
const FOO_CONFIG: &str = r"
version: '1'
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";

/// Build a locally-committed package (message "Initial commit", metadata
/// `{"key": "value"}`) against a bucket serving the given workflows `config`,
/// with `schema` stored at `s3://my-bucket/schemas/test.json`, ready for a
/// `set_remote` call. The returned temp-dir guards must be kept alive for the
/// package's storage to remain valid.
async fn package_with_config(
    slug: &str,
    config: &str,
    schema: &[u8],
) -> Res<(
    InstalledPackage<LocalStorage, MockRemote>,
    tempfile::TempDir,
    tempfile::TempDir,
)> {
    let (home, temp_dir1) = Home::from_temp_dir()?;
    let (paths, temp_dir2) = DomainPaths::from_temp_dir()?;

    let storage = LocalStorage::new();
    let remote = MockRemote::default();
    let namespace: Namespace = ("test", slug).into();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;

    let config_uri: S3Uri = "s3://my-bucket/.quilt/workflows/config.yml".parse()?;
    let schema_uri: S3Uri = "s3://my-bucket/schemas/test.json".parse()?;
    remote
        .put_object(None, &config_uri, config.as_bytes().to_vec())
        .await?;
    remote
        .put_object(None, &schema_uri, schema.to_vec())
        .await?;

    let lineage_json = format!(
        r#"{{
        "packages": {{
            "test/{slug}": {{
                "commit": null,
                "remote": null,
                "base_hash": "",
                "latest_hash": "",
                "paths": {{}}
            }}
        }},
        "home": "/tmp/working_dir"
    }}"#
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    let package_home = home.join(namespace.to_string());
    storage.create_dir_all(&package_home).await?;
    storage
        .write_byte_stream(
            package_home.join("data.txt"),
            ByteStream::from_static(b"hello world"),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());
    let package = InstalledPackage {
        lineage: PackageLineageIo::new(domain_lineage_io, namespace.clone()),
        paths,
        remote,
        storage,
        namespace,
    };

    package
        .commit(
            "Initial commit".to_string(),
            UserMeta::Set(serde_json::json!({"key": "value"})),
            None,
            None,
        )
        .await?;

    Ok((package, temp_dir1, temp_dir2))
}

#[test(tokio::test)]
async fn test_set_remote_propagates_named_workflow_error() -> Res {
    // An explicit `Named` gesture whose id isn't in the bucket config must make
    // `set_remote` fail loudly rather than silently swallowing the recommit
    // error (the user's workflow choice would otherwise be dropped).
    let (package, _t1, _t2) = package_with_config("named-error", FOO_CONFIG, b"{}").await?;

    let result = package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::Named("nope".to_string()),
        )
        .await;

    assert!(
        result.is_err(),
        "an explicit Named intent with an unknown id must surface the recommit error"
    );
    assert!(
        result.unwrap_err().to_string().contains("Workflow nope"),
        "error should name the unresolved workflow"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_swallows_bucket_default_recommit_error() -> Res {
    // The no-gesture `BucketDefault` path stays best-effort for *resolution*
    // failures: the bucket's `default_workflow` names a workflow that is not
    // declared, so the recommit cannot resolve it — `set_remote` still
    // succeeds, the remote is saved, and the hiccup is only logged. (Validity
    // is never best-effort: a workflow *rejection* propagates — see
    // `test_set_remote_bucket_default_validation_error_propagates`.)
    let config = r"
version: '1'
default_workflow: ghost
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";
    let (package, _t1, _t2) = package_with_config("bucketdefault-ok", config, b"{}").await?;

    let outcome = package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await?;

    // The silent best-effort failure is now surfaced: the outcome carries a
    // resolution warning naming the reason, so the caller (CLI/quilt-sync) can
    // tell the user instead of leaving them ungoverned until push time.
    let warning = outcome
        .resolution_warning
        .expect("a failed bucket-default resolution must surface a warning");
    assert!(
        warning.contains("ghost"),
        "the warning must carry the underlying reason, got: {warning}"
    );
    assert!(
        !warning.contains("Remote catalog error"),
        "the warning must be the unwrapped inner reason, not the error chain, got: {warning}"
    );

    let lineage = package.lineage().await?;
    assert!(
        lineage.remote_uri.is_some(),
        "remote should be persisted on the BucketDefault path"
    );
    let commit = lineage.commit.as_ref().expect("commit should still exist");
    let manifest_path = package
        .paths
        .installed_manifest(&package.namespace, &commit.hash);
    let manifest = Manifest::from_path(&package.storage, &manifest_path).await?;
    assert!(
        manifest.header.workflow.is_none(),
        "no workflow may be stamped when the bucket default fails to resolve"
    );

    Ok(())
}

/// Snapshot of a package's persistent state used to assert that a rejected
/// `set_remote` leaves everything intact.
async fn assert_nothing_persisted(
    package: &InstalledPackage<LocalStorage, MockRemote>,
    hash_before: &str,
    manifests_before: usize,
) -> Res {
    let lineage = package.lineage().await?;
    assert!(
        lineage.remote_uri.is_none(),
        "a rejected set_remote must not persist the remote"
    );
    let commit = lineage.commit.as_ref().expect("commit should still exist");
    assert_eq!(
        commit.hash, hash_before,
        "a rejected set_remote must not change the commit"
    );
    assert!(
        commit.prev_hashes.is_empty(),
        "a rejected set_remote must not record a recommit in prev_hashes"
    );

    // The previous manifest must still be present and loadable, its header
    // untouched (no workflow was ever stamped on it), and no new manifest
    // file may have appeared.
    let manifests_dir = package.paths.installed_manifests_dir(&package.namespace);
    let manifest_path = package
        .paths
        .installed_manifest(&package.namespace, hash_before);
    let manifest = Manifest::from_path(&package.storage, &manifest_path).await?;
    assert!(
        manifest.header.workflow.is_none(),
        "the previous manifest's header must be unchanged"
    );
    let manifests_after = std::fs::read_dir(&manifests_dir)?.count();
    assert_eq!(
        manifests_after, manifests_before,
        "a rejected set_remote must not write a new manifest"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_no_workflow_against_required_bucket_is_rejected() -> Res {
    // FOO_CONFIG omits `is_workflow_required`, which defaults to true: the
    // bucket requires a workflow. An explicit `NoWorkflow` gesture resolves to
    // an id-less record, which the gate rejects — and a rejected set_remote
    // persists NOTHING: no remote, no new commit, no new manifest.
    let (package, _t1, _t2) = package_with_config("noworkflow-required", FOO_CONFIG, b"{}").await?;

    let lineage = package.lineage().await?;
    let hash_before = lineage.commit.as_ref().expect("committed").hash.clone();
    let manifests_dir = package.paths.installed_manifests_dir(&package.namespace);
    let manifests_before = std::fs::read_dir(&manifests_dir)?.count();

    let err = package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::NoWorkflow,
        )
        .await
        .unwrap_err();

    assert!(
        matches!(
            &err,
            Error::WorkflowValidation(WorkflowValidationError::Rejected(violations))
                if violations.contains(&RuleViolation::WorkflowRequired)
        ),
        "expected a WorkflowRequired rejection, got: {err:?}"
    );
    assert_nothing_persisted(&package, &hash_before, manifests_before).await?;

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_bucket_default_validation_error_propagates() -> Res {
    // The bucket's `default_workflow` resolves fine, but its metadata_schema
    // requires an `owner` the committed package does not carry. Unlike a
    // resolution failure, a validation rejection is NOT best-effort on the
    // BucketDefault path: set_remote fails and persists nothing.
    let config = r"
version: '1'
default_workflow: foo
workflows:
  foo:
    name: Foo
    metadata_schema: bar
schemas:
  bar:
    url: s3://my-bucket/schemas/test.json
";
    let schema = br#"{"type": "object", "required": ["owner"]}"#;
    let (package, _t1, _t2) = package_with_config("bucketdefault-invalid", config, schema).await?;

    let lineage = package.lineage().await?;
    let hash_before = lineage.commit.as_ref().expect("committed").hash.clone();
    let manifests_dir = package.paths.installed_manifests_dir(&package.namespace);
    let manifests_before = std::fs::read_dir(&manifests_dir)?.count();

    let err = package
        .set_remote(
            "my-bucket".to_string(),
            Some("example.com".parse()?),
            WorkflowIntent::BucketDefault,
        )
        .await
        .unwrap_err();

    assert!(
        matches!(
            &err,
            Error::WorkflowValidation(WorkflowValidationError::Rejected(violations))
                if matches!(&violations[..], [RuleViolation::MetadataInvalid(_)])
        ),
        "expected a MetadataInvalid rejection, got: {err:?}"
    );
    assert_nothing_persisted(&package, &hash_before, manifests_before).await?;

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_stamps_named_workflow() -> Res {
    // `Named("foo")` must stamp `foo` even though the bucket declares no default.
    let header =
        recommit_manifest_for_intent("named", WorkflowIntent::Named("foo".to_string())).await?;

    let workflow = header
        .workflow
        .expect("recommit should stamp the named workflow");
    assert_eq!(
        workflow.id.expect("workflow id should be set").id,
        "foo",
        "recommit should stamp the caller's chosen workflow, not the bucket default"
    );

    Ok(())
}

#[test(tokio::test)]
async fn test_set_remote_stamps_no_workflow() -> Res {
    // `NoWorkflow` must produce an explicit id-less record when a config exists.
    let header = recommit_manifest_for_intent("noworkflow", WorkflowIntent::NoWorkflow).await?;

    let workflow = header
        .workflow
        .expect("recommit should stamp an id-less workflow when a config is present");
    assert!(
        workflow.id.is_none(),
        "NoWorkflow must not resolve any workflow id"
    );

    Ok(())
}