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
//! Tests for the commit/push/pull/status lifecycle of an installed package.

use super::*;

use test_log::test;

use aws_sdk_s3::primitives::ByteStream;

use crate::io::remote::mocks::MockRemote;
use crate::io::storage::StorageExt;
use crate::lineage::DomainLineageIo;
use crate::lineage::Home;
use crate::lineage::PackageLineageIo;
use crate::object_hash::ObjectHash;
use crate::paths::DomainPaths;

#[test(tokio::test)]
async fn test_spamming_commit_writes() -> 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", "history").into();
    let test_hash = "deadbeef".to_string();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;
    // Initialize domain lineage file
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/history": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "bucket",
                        "namespace": "test/history",
                        "hash": "{}",
                        "catalog": "test.quilt.dev"
                    }},
                    "base_hash": "{}",
                    "latest_hash": "{}",
                    "paths": {{}}
                }}}},
            "home": "/tmp/working_dir"
            }}"#,
        test_hash, "foo", "bar"
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Copy manifest to the expected path
    let test_manifest_path = paths.installed_manifest(&namespace, &test_hash);
    let test_manifest = r#"{"version": "v0"}"#;
    storage
        .write_byte_stream(
            &test_manifest_path,
            ByteStream::from_static(test_manifest.as_bytes()),
        )
        .await?;

    let domain_lineage_io = DomainLineageIo::new(paths.lineage());

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

    // Make 10 commits with different content
    let mut expected_hashes = Vec::new();
    for i in 0..10 {
        let commit = package
            .commit(
                format!("Commit new1 {i}"),
                UserMeta::Set(serde_json::json!({ "count": i })),
                None,
                None,
            )
            .await?;
        expected_hashes.insert(i, commit.hash);
    }

    // Remove last, cause it's the "current" hash, not a part of `prev_hashes`
    expected_hashes.pop();

    let commit_state = package.lineage().await?.commit.unwrap();

    assert_eq!(commit_state.prev_hashes.len(), 9);
    // let hashes_to_assert: Vec<String> = expected_hashes.into_iter().rev().collect();
    assert_eq!(
        commit_state.prev_hashes,
        expected_hashes.into_iter().rev().collect::<Vec<String>>()
    );

    Ok(())
}

/// Scenario A: diverged with an unpushed local commit. The user lands on
/// the merge page because someone else moved `latest` past our install
/// base, and we have a local commit on top of that base. `certify_latest`
/// must push our commit and then tag the resulting remote hash as
/// `latest` — not roll the tag back to the install-time hash.
#[test(tokio::test)]
async fn test_certify_latest_pushes_pending_commit_then_tags() -> 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", "diverged").into();
    let bucket = "b";

    // L is the rebuilt-manifest hash that push will produce from an empty
    // manifest with header user_meta=null. Using a known fixture keeps
    // push's "rebuilt hash must equal commit hash" check happy without
    // wiring real objects.
    let local_hash = crate::fixtures::top_hash::EMPTY_NULL_TOP_HASH;
    let install_hash = "I_HASH";
    let other_hash = "N_HASH";

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

    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/diverged": {{
                    "commit": {{
                        "timestamp": "2024-01-01T00:00:00Z",
                        "hash": "{local_hash}",
                        "prev_hashes": []
                    }},
                    "remote": {{
                        "bucket": "{bucket}",
                        "namespace": "test/diverged",
                        "hash": "{install_hash}"
                    }},
                    "base_hash": "{install_hash}",
                    "latest_hash": "{other_hash}",
                    "paths": {{}}
                }}
            }},
            "home": "/tmp/working_dir"
        }}"#
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Local installed manifest at the commit hash — push reads it via
    // `self.manifest()`. These exact bytes are what make the rebuild
    // produce `EMPTY_NULL_TOP_HASH` (matching `local_hash` above); any
    // change to the manifest serialization or top-hash algorithm will
    // surface as a push-side "rebuilt hash != commit hash" failure
    // rather than at the final `latest_body` assertion.
    let local_manifest = b"{\"version\":\"v0\",\"message\":\"\",\"user_meta\":null}\n".to_vec();
    storage
        .write_byte_stream(
            &paths.installed_manifest(&namespace, local_hash),
            local_manifest.clone().into(),
        )
        .await?;

    // Pre-cache the install-time remote manifest so push's `flow::browse`
    // call for the previous remote_uri succeeds without a remote round-trip.
    let install_manifest_uri = ManifestUri {
        bucket: bucket.to_string(),
        namespace: namespace.clone(),
        hash: install_hash.to_string(),
        origin: None,
    };
    storage
        .write_byte_stream(
            paths.cached_manifest(&install_manifest_uri),
            local_manifest.into(),
        )
        .await?;

    // Remote `latest` tag points at someone else's hash — this is what
    // makes the state Diverged.
    remote
        .put_object(
            None,
            &S3Uri::try_from(
                format!("s3://{bucket}/.quilt/named_packages/test/diverged/latest").as_str(),
            )?,
            other_hash.as_bytes().to_vec(),
        )
        .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.certify_latest().await?;

    // Remote `latest` now points at the user's revision (L), not the
    // teammate's (N) and not the install-time hash (I).
    let latest_uri = S3Uri::try_from(
        format!("s3://{bucket}/.quilt/named_packages/test/diverged/latest").as_str(),
    )?;
    let latest_body = package
        .remote
        .get_object_stream(None, &latest_uri)
        .await?
        .body
        .collect()
        .await?
        .to_vec();
    assert_eq!(latest_body, local_hash.as_bytes());

    let lineage = package.lineage().await?;
    assert_eq!(lineage.base_hash, local_hash);
    assert_eq!(lineage.latest_hash, local_hash);
    assert!(lineage.commit.is_none(), "push should have consumed commit");

    Ok(())
}

/// Scenario B: diverged because our prior push uploaded the manifest but
/// `push_package` declined to certify (`latest` had moved between
/// `base_hash` and our push). With `commit = None`, `certify_latest`
/// must skip the push and tag the already-pushed hash as `latest`.
#[test(tokio::test)]
async fn test_certify_latest_skips_push_when_no_pending_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", "pushed").into();
    let bucket = "b";

    let pushed_hash = "X_HASH";
    let other_hash = "Y_HASH";

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

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

    // Remote `latest` tag currently points at someone else's hash.
    remote
        .put_object(
            None,
            &S3Uri::try_from(
                format!("s3://{bucket}/.quilt/named_packages/test/pushed/latest").as_str(),
            )?,
            other_hash.as_bytes().to_vec(),
        )
        .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.certify_latest().await?;

    // Remote `latest` now points at the previously-pushed revision (X).
    let latest_uri = S3Uri::try_from(
        format!("s3://{bucket}/.quilt/named_packages/test/pushed/latest").as_str(),
    )?;
    let latest_body = package
        .remote
        .get_object_stream(None, &latest_uri)
        .await?
        .body
        .collect()
        .await?
        .to_vec();
    assert_eq!(latest_body, pushed_hash.as_bytes());

    // No manifest was uploaded as part of certification — push was skipped.
    assert!(
        !package
            .remote
            .exists(
                None,
                &S3Uri::try_from(format!("s3://{bucket}/.quilt/packages/{pushed_hash}").as_str(),)?,
            )
            .await?,
        "push should be skipped when there is no pending commit",
    );

    let lineage = package.lineage().await?;
    assert_eq!(lineage.base_hash, pushed_hash);
    assert_eq!(lineage.latest_hash, pushed_hash);
    assert!(lineage.commit.is_none());

    Ok(())
}

#[test(tokio::test)]
async fn test_manifest_recovery_from_corruption() -> 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", "recovery").into();
    let test_hash = "deadbeef".to_string();

    paths
        .scaffold_for_installing(&storage, &home, &namespace)
        .await?;
    paths.scaffold_for_caching(&storage, "test-bucket").await?;

    // Initialize domain lineage file
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/recovery": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "test-bucket",
                        "namespace": "test/recovery",
                        "hash": "{}",
                        "catalog": null
                    }},
                    "base_hash": "{}",
                    "latest_hash": "{}",
                    "paths": {{}}
                }}}},
            "home": "/tmp/working_dir"
            }}"#,
        test_hash, "foo", "bar"
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Set up a valid cached manifest
    let reference_manifest = crate::fixtures::manifest::path();
    let manifest_uri = ManifestUri {
        bucket: "test-bucket".to_string(),
        namespace: namespace.clone(),
        hash: test_hash.clone(),
        origin: None,
    };
    let cached_manifest = paths.cached_manifest(&manifest_uri);
    storage.copy(reference_manifest?, cached_manifest).await?;

    // Create a corrupted installed manifest
    let installed_manifest = paths.installed_manifest(&namespace, &test_hash);
    storage
        .write_byte_stream(
            &installed_manifest,
            ByteStream::from_static(b"corrupted data"),
        )
        .await?;

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

    // This should succeed by recovering from cache despite corrupted installed manifest
    let result = package.manifest().await;
    assert!(
        result.is_ok(),
        "Should recover from cache when installed is corrupted"
    );

    // Verify the corrupted file was replaced with good data
    let fixed_manifest_content = storage.read_bytes(&installed_manifest).await?;
    assert!(
        fixed_manifest_content.len() > 10,
        "Installed manifest should be fixed"
    );
    assert!(
        !fixed_manifest_content.starts_with(b"corrupted"),
        "Should no longer be corrupted"
    );

    Ok(())
}

/// A remote that always returns `LoginRequired`, simulating a logged-out user.
struct LoggedOutRemote;

impl crate::io::remote::Remote for LoggedOutRemote {
    async fn exists(&self, _host: Option<&Host>, _s3_uri: &S3Uri) -> Res<bool> {
        Err(Error::Login(LoginError::Required(None)))
    }
    async fn get_object_stream(
        &self,
        _host: Option<&Host>,
        _s3_uri: &S3Uri,
    ) -> Res<crate::io::remote::RemoteObjectStream> {
        Err(Error::Login(LoginError::Required(None)))
    }
    async fn resolve_url(&self, _host: Option<&Host>, _s3_uri: &S3Uri) -> Res<S3Uri> {
        Err(Error::Login(LoginError::Required(None)))
    }
    async fn put_object(
        &self,
        _host: Option<&Host>,
        _s3_uri: &S3Uri,
        _contents: impl Into<aws_sdk_s3::primitives::ByteStream>,
    ) -> Res {
        Err(Error::Login(LoginError::Required(None)))
    }
    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)> {
        Err(Error::Login(LoginError::Required(None)))
    }
    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 {
        Ok(())
    }
}

/// A remote that refuses every read with `AccessDenied`, simulating a role
/// that cannot reach the bucket. Distinct from [`LoggedOutRemote`]: the
/// credentials are valid, the request arrived, and it was refused.
struct DeniedRemote;

impl crate::io::remote::Remote for DeniedRemote {
    async fn exists(&self, _host: Option<&Host>, s3_uri: &S3Uri) -> Res<bool> {
        Err(denied(s3_uri))
    }
    async fn get_object_stream(
        &self,
        _host: Option<&Host>,
        s3_uri: &S3Uri,
    ) -> Res<crate::io::remote::RemoteObjectStream> {
        Err(denied(s3_uri))
    }
    async fn resolve_url(&self, _host: Option<&Host>, s3_uri: &S3Uri) -> Res<S3Uri> {
        Err(denied(s3_uri))
    }
    async fn put_object(
        &self,
        _host: Option<&Host>,
        s3_uri: &S3Uri,
        _contents: impl Into<aws_sdk_s3::primitives::ByteStream>,
    ) -> Res {
        Err(denied(s3_uri))
    }
    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)> {
        Err(denied(dest_uri))
    }
    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 {
        Ok(())
    }
}

fn denied(s3_uri: &S3Uri) -> Error {
    crate::error::S3Error::new(crate::error::S3ErrorKind::AccessDenied(s3_uri.to_string())).into()
}

/// The latest-hash pointer read is the *first* thing a narrow role hits, so
/// it is the most common shape of a denial in practice. `status` swallows
/// every other refresh failure by design — that is what lets the app work
/// offline on stale lineage — but swallowing this one leaves the UI unable
/// to tell the user why the row will not sync, and sends it looking for an
/// auth problem that does not exist.
#[test(tokio::test)]
async fn test_status_propagates_access_denied_from_the_latest_hash_read() -> Res {
    let (home, _temp_dir1) = Home::from_temp_dir()?;
    let (paths, _temp_dir2) = DomainPaths::from_temp_dir()?;

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

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

    // An installed package with a remote and a manifest already on disk, so
    // the only remote read `status` needs is the latest-hash pointer.
    let installed_hash = "abcdef";
    let lineage_json = format!(
        r#"{{
        "packages": {{
            "test/denied": {{
                "commit": null,
                "remote": {{
                    "bucket": "locked",
                    "namespace": "test/denied",
                    "hash": "{installed_hash}",
                    "origin": "nightly.quilttest.com"
                }},
                "base_hash": "{installed_hash}",
                "latest_hash": "{installed_hash}",
                "paths": {{}}
            }}
        }},
        "home": "/tmp/working_dir"
    }}"#
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;
    storage
        .write_byte_stream(
            &paths.installed_manifest(&namespace, installed_hash),
            ByteStream::from_static(br#"{"version": "v0"}"#),
        )
        .await?;

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

    let result = package.status(None).await;

    let Err(err) = result else {
        panic!("a denied latest-hash read must not report a healthy status");
    };
    assert!(
        err.is_access_denied(),
        "the denial must survive as a typed denial, not a warning: {err}"
    );

    Ok(())
}

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

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

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

    // Package with remote configured but never pushed (empty hash)
    let lineage_json = r#"{
        "packages": {
            "test/needslogin": {
                "commit": null,
                "remote": {
                    "bucket": "my-bucket",
                    "namespace": "test/needslogin",
                    "hash": "",
                    "origin": "nightly.quilttest.com"
                },
                "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: LoggedOutRemote,
        storage,
        namespace,
    };

    // status() should propagate LoginRequired so the UI can show a Login button
    let result = package.status(None).await;
    assert!(
        matches!(result, Err(Error::Login(LoginError::Required(_)))),
        "Expected LoginRequired error, got: {result:?}"
    );

    Ok(())
}

/// Pull must refresh `latest_hash` from the remote before evaluating
/// `flow::pull`'s `base_hash == latest_hash` guard. Before the
/// "Stop writing lineage from `InstalledPackage::status`" refactor, a
/// prior `status` call would persist the refreshed `latest_hash`, so
/// disk was reliably fresh when `pull` ran. Without that persist,
/// the disk-stale `latest_hash` always equalled `base_hash` and
/// pull short-circuited with "already up-to-date" — both the
/// autosync watcher's pull branch and the manual Pull button were
/// affected.
#[test(tokio::test)]
async fn test_pull_refreshes_latest_hash_when_remote_moved() -> 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", "pull_refresh").into();
    let bucket = "bkt";
    let install_hash = "INSTALL_HASH";
    let new_hash = "NEW_HASH";

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

    // Disk lineage at the install-time hash: latest_hash == base_hash
    // == remote.hash. Without the refresh inside `pull` this state
    // alone short-circuits the up-to-date guard.
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/pull_refresh": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "{bucket}",
                        "namespace": "test/pull_refresh",
                        "hash": "{install_hash}",
                        "catalog": "test.quilt.dev"
                    }},
                    "base_hash": "{install_hash}",
                    "latest_hash": "{install_hash}",
                    "paths": {{}}
                }}
            }},
            "home": "{}"
        }}"#,
        home.as_ref().display(),
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Installed manifest at the install-time hash so `package.manifest()`
    // can resolve.
    storage
        .write_byte_stream(
            paths.installed_manifest(&namespace, install_hash),
            ByteStream::from_static(br#"{"version": "v0"}"#),
        )
        .await?;

    // Remote `latest` tag has moved past the install — this is the
    // exact state that broke after the read-only-status refactor.
    remote
        .put_object(
            None,
            &S3Uri::try_from(
                format!("s3://{bucket}/.quilt/named_packages/test/pull_refresh/latest").as_str(),
            )?,
            new_hash.as_bytes().to_vec(),
        )
        .await?;

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

    // Pull will eventually fail downstream — we have not staged the
    // manifest at `new_hash`, so `cache_remote_manifest` will return a
    // NotFound — but the *specific* error we are guarding against is
    // "package is already up-to-date". Any other failure mode proves
    // the refresh-then-check path ran.
    let err = package
        .pull(None)
        .await
        .expect_err("pull should fail downstream on the missing NEW_HASH manifest");
    let msg = err.to_string();
    assert!(
        !msg.contains("already up-to-date"),
        "pull must refresh latest_hash before the up-to-date guard; got: {msg}"
    );

    Ok(())
}

/// `pull_outcome` is the network-light dry-run the watcher/UI call before
/// routing a pull. A `Behind` package whose `latest` manifest is fetchable and
/// drops a tracked path (with no local changes) classifies as a clean surgical
/// update — never `UpToDate`.
#[test(tokio::test)]
async fn test_pull_outcome_behind_returns_non_up_to_date() -> 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", "pull_outcome").into();
    let bucket = "bkt";
    let install_hash = "INSTALL_HASH";
    let new_hash = "NEW_HASH";

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

    // Disk lineage at the install-time hash: latest_hash == base_hash. The
    // remote `latest` tag (staged below) has moved, so `status`'s refresh
    // turns this into a `Behind` state.
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/pull_outcome": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "{bucket}",
                        "namespace": "test/pull_outcome",
                        "hash": "{install_hash}",
                        "catalog": "test.quilt.dev"
                    }},
                    "base_hash": "{install_hash}",
                    "latest_hash": "{install_hash}",
                    "paths": {{}}
                }}
            }},
            "home": "{}"
        }}"#,
        home.as_ref().display(),
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Installed (base) manifest with one tracked row so the `base → latest`
    // delta is non-empty.
    let base_manifest = concat!(
        "{\"version\":\"v0\",\"message\":\"\",\"user_meta\":null}\n",
        "{\"logical_key\":\"a.txt\",\"physical_keys\":[\"s3://bkt/a.txt\"],",
        "\"hash\":{\"type\":\"sha2-256-chunked\",",
        "\"value\":\"47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=\"},",
        "\"size\":0,\"meta\":null}\n",
    );
    storage
        .write_byte_stream(
            paths.installed_manifest(&namespace, install_hash),
            ByteStream::from(base_manifest.as_bytes().to_vec()),
        )
        .await?;

    // Remote `latest` tag has moved past the install → `Behind`.
    remote
        .put_object(
            None,
            &S3Uri::try_from(
                format!("s3://{bucket}/.quilt/named_packages/test/pull_outcome/latest").as_str(),
            )?,
            new_hash.as_bytes().to_vec(),
        )
        .await?;

    // The `latest` manifest is fetchable and drops `a.txt` (remote removal),
    // so the delta is non-empty and — with no local changes — resolves to a
    // clean surgical update.
    remote
        .put_object(
            None,
            &S3Uri::try_from(format!("s3://{bucket}/.quilt/packages/{new_hash}").as_str())?,
            b"{\"version\":\"v0\"}".to_vec(),
        )
        .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 outcome = package.pull_outcome(None).await?;
    assert!(
        matches!(
            outcome,
            PullOutcome::CleanUpdate | PullOutcome::KeepsLocalChanges { .. }
        ),
        "expected a non-up-to-date outcome, got: {outcome:?}"
    );

    Ok(())
}

/// A local-only package (no `remote` in its lineage) has no `latest` tag to
/// resolve, so `pull_outcome` must short-circuit to `UpToDate` without touching
/// the network — never propagating the `NoRemote` error `remote()?` would raise.
#[test(tokio::test)]
async fn test_pull_outcome_local_no_remote_is_up_to_date() -> 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_no_remote").into();

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

    // No `remote` key → `remote_uri` is `None` → `UpstreamState::Local`.
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/local_no_remote": {{
                    "commit": null,
                    "base_hash": "",
                    "latest_hash": "",
                    "paths": {{}}
                }}
            }},
            "home": "{}"
        }}"#,
        home.as_ref().display(),
    );
    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,
    };

    assert!(matches!(
        package.pull_outcome(None).await?,
        PullOutcome::UpToDate
    ));

    Ok(())
}

/// A package diverged by hash (`remote.hash != base_hash` with a stale
/// `latest_hash` also differing from `base`) is `UpstreamState::Diverged` from
/// on-disk state alone — a purely lineage-local fact no tag read can cure.
/// `pull_outcome` must short-circuit to `UpToDate` WITHOUT any network, rather
/// than paying a manifest fetch + walk only to discard the result at the
/// post-walk `!= Behind` check.
#[test(tokio::test)]
async fn test_pull_outcome_diverged_by_hash_is_up_to_date_no_network() -> 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", "diverged_hash").into();
    let bucket = "bkt";
    let remote_hash = "R_HASH";
    let base_hash = "B_HASH";
    let latest_hash = "L_HASH";

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

    // remote.hash != base_hash and latest_hash != base_hash, no commit →
    // `UpstreamState::from` reports `Diverged` (ahead && behind) from disk.
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/diverged_hash": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "{bucket}",
                        "namespace": "test/diverged_hash",
                        "hash": "{remote_hash}",
                        "catalog": "test.quilt.dev"
                    }},
                    "base_hash": "{base_hash}",
                    "latest_hash": "{latest_hash}",
                    "paths": {{}}
                }}
            }},
            "home": "{}"
        }}"#,
        home.as_ref().display(),
    );
    storage
        .write_byte_stream(&paths.lineage(), lineage_json.as_bytes().to_vec().into())
        .await?;

    // Installed manifest at the current hash so that, WITHOUT the short-circuit,
    // `pull_outcome` would get past `manifest()` and pay for the tag read below.
    storage
        .write_byte_stream(
            paths.installed_manifest(&namespace, remote_hash),
            ByteStream::from_static(br#"{"version": "v0"}"#),
        )
        .await?;

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

    assert!(matches!(
        package.pull_outcome(None).await?,
        PullOutcome::UpToDate
    ));

    // No `latest` tag was resolved — the divergence was decided from lineage
    // alone, with zero remote calls.
    let tag_uri = format!("s3://{bucket}/.quilt/named_packages/test/diverged_hash/latest");
    assert_eq!(package.remote.get_object_count(&tag_uri), 0);

    Ok(())
}

/// A package with a remote whose hash was never pushed (empty `hash` and empty
/// `latest_hash`) is `UpstreamState::Local`: there is no `latest` tag on the
/// bucket yet. `pull_outcome` must report `UpToDate` without a tag read, rather
/// than propagating the `NotFound` that resolving the absent tag would raise.
#[test(tokio::test)]
async fn test_pull_outcome_never_pushed_remote_is_up_to_date() -> 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", "never_pushed").into();
    let bucket = "bkt";

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

    // Remote set but never pushed: empty `hash` + empty `latest_hash` →
    // `UpstreamState::Local`. No `latest` tag is staged on the mock remote, so
    // any tag read would 404.
    let lineage_json = format!(
        r#"{{
            "packages": {{
                "test/never_pushed": {{
                    "commit": null,
                    "remote": {{
                        "bucket": "{bucket}",
                        "namespace": "test/never_pushed",
                        "hash": "",
                        "catalog": "test.quilt.dev"
                    }},
                    "base_hash": "",
                    "latest_hash": "",
                    "paths": {{}}
                }}
            }},
            "home": "{}"
        }}"#,
        home.as_ref().display(),
    );
    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,
    };

    assert!(matches!(
        package.pull_outcome(None).await?,
        PullOutcome::UpToDate
    ));

    Ok(())
}