lix 0.18.0

Embeddable version control for apps and AI agents.
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
//! Real canonical HTTP handler and client dispatcher, with a lost body ACK.
use super::*;
use crate::server_protocol::{LixServerProtocol, ServerProtocolBody, ServerProtocolContext};
use crate::sync::http::{HttpSyncTransport, RawHttpClient, RawHttpRequest, RawHttpResponse};
use crate::sync::{SyncTransportFuture, partial_merge_runtime::prepare_descriptor_with_merge};
use http_body_util::BodyExt;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
#[derive(Clone)]
struct Client {
    server: LixServerProtocol<Memory>,
    lose_body: Arc<AtomicBool>,
}
impl RawHttpClient for Client {
    fn send(&self, request: RawHttpRequest) -> SyncTransportFuture<'_, RawHttpResponse> {
        Box::pin(async move {
            let retained = request.url.ends_with("/sync/retained-bodies");
            let mut builder = http::Request::builder()
                .method(request.method)
                .uri(request.url);
            for (name, value) in request.headers {
                builder = builder.header(name, value);
            }
            let response = self
                .server
                .handle(
                    builder
                        .body(ServerProtocolBody::from(request.body.unwrap_or_default()))
                        .unwrap(),
                    ServerProtocolContext::anonymous(),
                )
                .await;
            let status = response.status();
            let body = response
                .into_body()
                .collect()
                .await
                .map_err(|e| LixError::unknown(e.to_string()))?
                .to_bytes()
                .to_vec();
            assert!(body.len() <= request.response_limit);
            if retained && status.is_success() && self.lose_body.swap(false, Ordering::SeqCst) {
                return Err(LixError::new(
                    "TEST_LOST_BODY_ACK",
                    "authority committed body wave before connection failed",
                ));
            }
            Ok(RawHttpResponse {
                status: status.as_u16(),
                status_text: status.to_string(),
                body,
            })
        })
    }
}
#[derive(Clone)]
struct CountPublicationRequests {
    inner: Client,
    requests: Arc<std::sync::Mutex<Vec<String>>>,
    blob_reply: Arc<std::sync::Mutex<Option<Vec<crate::sync::SyncBlobManifest>>>>,
}
impl RawHttpClient for CountPublicationRequests {
    fn send(&self, request: RawHttpRequest) -> SyncTransportFuture<'_, RawHttpResponse> {
        if request.method == "GET" && request.url.contains("/sync/blob?") {
            if let Some(reply) = self.blob_reply.lock().unwrap().clone() {
                return Box::pin(async move {
                    Ok(RawHttpResponse {
                        status: 200,
                        status_text: "OK".into(),
                        body: serde_json::to_vec(&reply).unwrap(),
                    })
                });
            }
        }
        if request.url.ends_with("/sync/push")
            || (request.method != "GET"
                && (request.url.contains("/sync/blob") || request.url.contains("/sync/chunk")))
        {
            self.requests.lock().unwrap().push(request.url.clone());
        }
        self.inner.send(request)
    }
}
#[tokio::test]
async fn http_dispatcher_recovers_lost_wave_and_preserves_newer_local_edit() {
    lost_wave_with_pending_edit(false, PendingScenario::Ordinary, 1).await;
}

#[tokio::test]
async fn http_dispatcher_accepts_current_authority_and_preserves_newer_local_edit() {
    lost_wave_with_pending_edit(true, PendingScenario::Ordinary, 1).await;
}

#[tokio::test]
async fn http_dispatcher_accepts_global_drift_and_preserves_newer_local_edit() {
    lost_wave_with_pending_edit(true, PendingScenario::GlobalBeforeReceipt, 1).await;
}

#[tokio::test]
async fn http_dispatcher_settles_after_global_drift_with_newer_local_edit() {
    lost_wave_with_pending_edit(true, PendingScenario::GlobalAfterReceipt, 1).await;
}

#[tokio::test]
async fn local_branch_creation_between_pending_selected_edits_converges() {
    lost_wave_with_pending_edit(true, PendingScenario::LocalBranch, 1).await;
}

#[tokio::test]
async fn http_dispatcher_accepts_account_admission_during_pending_merge() {
    lost_wave_with_pending_edit(true, PendingScenario::AccountAdmission, 1).await;
}

#[tokio::test]
async fn http_dispatcher_pages_long_offline_history_against_divergent_authority() {
    lost_wave_with_pending_edit(true, PendingScenario::Ordinary, 1025).await;
}

#[tokio::test]
async fn http_dispatcher_pages_long_checkpoint_source_against_divergent_authority() {
    lost_wave_with_pending_edit(true, PendingScenario::Checkpoint, 1025).await;
}

#[tokio::test]
async fn http_dispatcher_pages_multiple_pending_checkpoints_against_divergent_authority() {
    lost_wave_with_pending_edit(true, PendingScenario::Checkpoints, 1025).await;
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum PendingScenario {
    Ordinary,
    GlobalBeforeReceipt,
    GlobalAfterReceipt,
    AccountAdmission,
    Checkpoint,
    Checkpoints,
    LocalBranch,
}

async fn advance_unrelated_global(authority: &Lix<Memory>) {
    authority
        .open_another_session()
        .with_branch(crate::GLOBAL_BRANCH_ID)
        .await
        .unwrap()
        .execute(
            "INSERT INTO lix_key_value(key,value) VALUES('global-race','changed')",
            &[],
        )
        .await
        .unwrap();
}

async fn lost_wave_with_pending_edit(
    advance_after_descriptor: bool,
    scenario: PendingScenario,
    offline_commits: usize,
) {
    let backing = Memory::new();
    let authority = open_lix().with_storage(backing.clone()).await.unwrap();
    authority
        .set_sync_role(crate::sync::SyncRole::Authority)
        .unwrap();
    authority
        .execute(
            "INSERT INTO lix_key_value(key,value) VALUES('local','B'),('remote','B')",
            &[],
        )
        .await
        .unwrap();
    let server = open_lix()
        .with_storage(backing)
        .serve()
        .with_embedded_lix_id()
        .await
        .unwrap();
    let lose_body = Arc::new(AtomicBool::new(true));
    let transport = HttpSyncTransport::connect_with(
        Client { server, lose_body },
        &format!("https://example.test/lix/{}", authority.lix_id()),
    )
    .await
    .unwrap();
    let wrapper = transport.partial_replica_descriptor(None).await.unwrap();
    let old = Arc::new(
        PartialReplicaState::from_leased(
            transport.protocol_url().into(),
            authority.active_account_id().into(),
            uuid::Uuid::now_v7().to_string(),
            wrapper.wire,
        )
        .unwrap(),
    );
    transport
        .bind_native_baseline_lease(old.baseline_lease())
        .unwrap();
    let storage = StorageAdapter::new(Memory::new());
    let read = storage.begin_read(Default::default()).await.unwrap();
    let mut writes = storage.new_write_set();
    let preconditions = stage_partial_bootstrap(&read, &mut writes, &old).unwrap();
    crate::init::stage_partial_repository_protocol(&mut writes);
    drop(read);
    storage
        .commit_write_set(
            writes,
            StorageWriteOptions {
                preconditions,
                await_durable: true,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let (engine, session) =
        Engine::new_partial_replica(storage.clone(), EngineOptions::new(), &old)
            .await
            .unwrap();
    let engine = Arc::new(engine);
    engine
        .sync_mode()
        .admit_partial_replica(old.clone(), crate::sync::partial_replica_write_capability());
    storage.admit_partial_replica_writer(crate::sync::partial_replica_write_capability());
    let mut fetches = Fetches::default();
    for sql in [
        "SELECT key,value FROM lix_key_value WHERE key IN ('local','remote')",
        "UPDATE lix_key_value SET value='L' WHERE key='local'",
    ] {
        execute_hydrating(&session, &storage, &old, &authority, sql, &[], &mut fetches)
            .await
            .unwrap();
    }
    for index in 1..offline_commits {
        session
            .execute(
                &format!("UPDATE lix_key_value SET value='offline-{index}' WHERE key='local'"),
                &[],
            )
            .await
            .unwrap();
        if scenario == PendingScenario::Checkpoints && index == offline_commits / 2 {
            execute_hydrating(
                &session, &storage, &old, &authority,
                "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_key_value')))",
                &[], &mut fetches,
            ).await.unwrap();
        }
    }
    let pending_checkpoint = if matches!(
        scenario,
        PendingScenario::Checkpoint | PendingScenario::Checkpoints
    ) {
        execute_hydrating(
            &session, &storage, &old, &authority,
            "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_key_value')))",
            &[], &mut fetches,
        ).await.unwrap();
        let read = storage.begin_read(Default::default()).await.unwrap();
        Some(
            crate::branch::BranchHeadControlContext::new()
                .reader(&read)
                .load(&old.descriptor().selected_branch.branch_id)
                .await
                .unwrap()
                .unwrap()
                .working_diff_checkpoint_commit_id
                .unwrap()
                .to_string(),
        )
    } else {
        None
    };
    prepare_baseline_jump_spines(&storage, &old, &authority, &mut fetches)
        .await
        .unwrap();
    // Serving installed durable authority ownership in another adapter.
    // Admit this test's existing authority handle through the same native owner.
    crate::sync::admit_sync_authority_storage(&authority.storage_adapter(), None)
        .await
        .unwrap();
    authority
        .execute("UPDATE lix_key_value SET value='R' WHERE key='remote'", &[])
        .await
        .unwrap();
    let captured_descriptor = transport.partial_replica_descriptor(None).await.unwrap();
    let captured_remote = captured_descriptor
        .wire
        .descriptor
        .selected_branch
        .head
        .commit_id
        .clone();
    if advance_after_descriptor {
        // Capture R, then accept R2 before the first retained wave reaches the
        // authority. Its otherwise valid immutable request must restart.
        authority
            .execute(
                "UPDATE lix_key_value SET value='R2' WHERE key='remote'",
                &[],
            )
            .await
            .unwrap();
    }
    let first = prepare_descriptor_with_merge(
        engine.clone(),
        old.clone(),
        &transport,
        captured_descriptor,
        crate::sync::partial_publication::PartialRecoveryPolicy::Normal,
    )
    .await;
    assert_eq!(first.err().unwrap().code, "TEST_LOST_BODY_ACK");
    let read = storage.begin_read(Default::default()).await.unwrap();
    let (pending, _, _) = crate::sync::partial_merge_state::load_partial_merge_state(
        &read,
        &old,
        &old.descriptor().selected_branch.branch_id,
    )
    .await
    .unwrap();
    let pending = pending.unwrap();
    assert!(pending.prepared_body_wave.is_some());
    assert_eq!(pending.accepted_body_tip, pending.request.base_commit_id);
    assert!(pending.authority_receipt.is_none());
    assert_eq!(
        pending.request.expected_authority_head_commit_id,
        captured_remote
    );
    drop(read);
    if scenario == PendingScenario::GlobalBeforeReceipt {
        advance_unrelated_global(&authority).await;
    } else if scenario == PendingScenario::AccountAdmission {
        authority
            .ensure_account(&uuid::Uuid::now_v7().to_string(), "new principal", "human")
            .await
            .unwrap();
    }
    let remote_checkpoint = if advance_after_descriptor {
        authority
            .execute(
                "UPDATE lix_key_value SET value='R3' WHERE key='remote'",
                &[],
            )
            .await
            .unwrap();
        authority.execute("SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_key_value')))", &[]).await.unwrap();
        Some(
            authority
                .partial_replica_descriptor(None)
                .await
                .unwrap()
                .selected_branch
                .checkpoint
                .commit_id,
        )
    } else {
        None
    };
    // Native foreground write stays offline while an exact remote wave is pending.
    session
        .execute("UPDATE lix_key_value SET value='L2' WHERE key='local'", &[])
        .await
        .unwrap();
    let created_branch = if scenario == PendingScenario::LocalBranch {
        let branch = global_during_merge::create_branch(&session, &storage, &old, &transport).await;
        execute_hydrating(
            &session,
            &storage,
            &old,
            &authority,
            "UPDATE lix_key_value SET value='L3' WHERE key='local'",
            &[],
            &mut Fetches::default(),
        )
        .await
        .unwrap();
        Some(branch)
    } else {
        None
    };
    // Recover the captured L result first; exact local CAS prevents adopting over L2.
    let second = prepare_descriptor_with_merge(
        engine.clone(),
        old.clone(),
        &transport,
        transport.partial_replica_descriptor(None).await.unwrap(),
        crate::sync::partial_publication::PartialRecoveryPolicy::Normal,
    )
    .await;
    let second_error = second.err().expect("newer local work remains pending");
    assert_eq!(
        second_error.code, "LIX_PARTIAL_REPLICA_MERGE_PENDING",
        "{second_error:?}"
    );
    if scenario == PendingScenario::GlobalAfterReceipt {
        advance_unrelated_global(&authority).await;
    }
    let mut rounds = 0;
    let prepared = loop {
        rounds += 1;
        assert!(
            rounds <= 8,
            "bounded prefixes must converge after writers stop"
        );
        if created_branch.is_some() {
            global_during_merge::upload_if_ready(&storage, &old, &transport).await;
        }
        let result = prepare_descriptor_with_merge(
            engine.clone(),
            old.clone(),
            &transport,
            transport.partial_replica_descriptor(None).await.unwrap(),
            crate::sync::partial_publication::PartialRecoveryPolicy::Normal,
        )
        .await;
        match result {
            Ok(crate::sync::partial_reconcile::PreparedDescriptor::Ready(prepared)) => {
                break prepared;
            }
            Err(error) if error.code == "LIX_PARTIAL_REPLICA_MERGE_PENDING" => {}
            Err(error)
                if created_branch.is_some()
                    && error.code == "LIX_PARTIAL_REPLICA_REBASE_REQUIRED" => {}
            Err(error) => panic!("prefix reconciliation failed: {error}"),
            Ok(_) => panic!("merged descriptor must be prepared"),
        }
    };
    if offline_commits > 1024 {
        assert!(rounds >= 4, "large local history must use bounded prefixes");
    }
    crate::sync::partial_publication::publish_prepared_partial(engine.clone(), prepared)
        .await
        .unwrap();
    // Publication installs coordinates; these consumers hydrate the newly
    // admitted basis before subsequent offline reads assert its contents.
    let current = engine.sync_mode().partial_admission().unwrap();
    let local = execute_hydrating(
        &session,
        &storage,
        &current,
        &authority,
        "SELECT value FROM lix_key_value WHERE key='local'",
        &[],
        &mut fetches,
    )
    .await
    .unwrap();
    let remote = execute_hydrating(
        &session,
        &storage,
        &current,
        &authority,
        "SELECT value FROM lix_key_value WHERE key='remote'",
        &[],
        &mut fetches,
    )
    .await
    .unwrap();
    assert!(format!("{local:?}").contains(if created_branch.is_some() { "L3" } else { "L2" }));
    if let Some(branch) = created_branch {
        assert!(
            authority
                .partial_replica_descriptor(Some(&branch))
                .await
                .is_ok(),
            "GLOBAL upload must publish the branch whose source was pending L2"
        );
        assert_eq!(
            session
                .execute("SELECT value FROM lix_key_value WHERE key='local'", &[])
                .await
                .unwrap()
                .rows(),
            authority
                .execute("SELECT value FROM lix_key_value WHERE key='local'", &[])
                .await
                .unwrap()
                .rows(),
        );
    }
    assert!(format!("{remote:?}").contains(if advance_after_descriptor { "R3" } else { "R" }));
    if let Some(checkpoint) = pending_checkpoint.or(remote_checkpoint) {
        assert_eq!(
            authority
                .partial_replica_descriptor(None)
                .await
                .unwrap()
                .selected_branch
                .checkpoint
                .commit_id,
            checkpoint,
            "only a newly captured checkpoint intent changes the authority checkpoint"
        );
    }
}

#[tokio::test]
async fn file_checkpoint_upload_retries_lost_ack_with_original_content() {
    Box::pin(file_checkpoint_upload_case(false, 1024 * 1024, false, None)).await;
}

#[tokio::test]
async fn file_checkpoint_upload_pages_offline_edits_and_repeated_checkpoints() {
    Box::pin(file_checkpoint_upload_case(true, 1024 * 1024, false, None)).await;
}

#[tokio::test]
async fn file_checkpoint_upload_pages_aggregate_wire_bytes() {
    Box::pin(file_checkpoint_upload_case(true, 8 * 1024, false, None)).await;
}

#[tokio::test]
async fn file_ordinary_upload_pages_aggregate_wire_bytes() {
    Box::pin(file_checkpoint_upload_case(true, 8 * 1024, true, None)).await;
}

#[tokio::test]
async fn checkpoint_publishes_cold_authority_blobs_without_hydrating_content() {
    Box::pin(file_checkpoint_upload_case(false, 1024 * 1024, false, Some(false))).await;
}

#[tokio::test]
async fn checkpoint_publishes_deferred_authority_blobs_without_hydrating_content() {
    Box::pin(file_checkpoint_upload_case(false, 1024 * 1024, false, Some(true))).await;
}

async fn file_checkpoint_upload_case(
    paging: bool,
    wire_budget: usize,
    ordinary_only: bool,
    cold_blob: Option<bool>,
) {
    let backing = Memory::new();
    let authority = open_lix().with_storage(backing.clone()).await.unwrap();
    authority
        .set_sync_role(crate::sync::SyncRole::Authority)
        .unwrap();
    authority
        .execute(
            "INSERT INTO lix_file(path,content) VALUES('/checkpoint.bin',$1)",
            &[Value::Blob(vec![17u8; 96 * 1024].into())],
        )
        .await
        .unwrap();
    if paging {
        authority
            .execute(
                "INSERT INTO lix_key_value(key,value) VALUES('checkpoint-excluded','before')",
                &[],
            )
            .await
            .unwrap();
    }
    let cold_content = vec![31u8; 96 * 1024];
    let cold_id = crate::binary_cas::CanonicalBlobManifest::from_bytes(&cold_content).blob_id;
    if cold_blob.is_some() {
        authority
            .execute(
                "INSERT INTO lix_file(path,content) VALUES('/cold.bin',$1)",
                &[Value::Blob(cold_content.clone().into())],
            )
            .await
            .unwrap();
    }
    let server = open_lix()
        .with_storage(backing)
        .serve()
        .with_embedded_lix_id()
        .await
        .unwrap();
    let publication_requests = Arc::new(std::sync::Mutex::new(Vec::new()));
    let blob_reply = Arc::new(std::sync::Mutex::new(None));
    let transport = HttpSyncTransport::connect_with(
        CountPublicationRequests {
            inner: Client {
                server,
                lose_body: Arc::new(AtomicBool::new(false)),
            },
            requests: Arc::clone(&publication_requests),
            blob_reply: blob_reply.clone(),
        },
        &format!("https://example.test/lix/{}", authority.lix_id()),
    )
    .await
    .unwrap();
    let wrapper = transport.partial_replica_descriptor(None).await.unwrap();
    let old = Arc::new(
        PartialReplicaState::from_leased(
            transport.protocol_url().into(),
            authority.active_account_id().into(),
            uuid::Uuid::now_v7().to_string(),
            wrapper.wire,
        )
        .unwrap(),
    );
    let storage = StorageAdapter::new(Memory::new());
    let read = storage.begin_read(Default::default()).await.unwrap();
    let mut writes = storage.new_write_set();
    let preconditions = stage_partial_bootstrap(&read, &mut writes, &old).unwrap();
    crate::init::stage_partial_repository_protocol(&mut writes);
    drop(read);
    storage
        .commit_write_set(
            writes,
            StorageWriteOptions {
                preconditions,
                await_durable: true,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let (engine, session) =
        Engine::new_partial_replica(storage.clone(), EngineOptions::new(), &old)
            .await
            .unwrap();
    let engine = Arc::new(engine);
    engine
        .sync_mode()
        .admit_partial_replica(old.clone(), crate::sync::partial_replica_write_capability());
    storage.admit_partial_replica_writer(crate::sync::partial_replica_write_capability());

    let mut fetches = Fetches::default();
    execute_hydrating(
        &session,
        &storage,
        &old,
        &authority,
        "SELECT id,path FROM lix_file WHERE path='/checkpoint.bin'",
        &[],
        &mut fetches,
    )
    .await
    .unwrap();
    if paging {
        execute_hydrating(
            &session,
            &storage,
            &old,
            &authority,
            "UPDATE lix_key_value SET value='still-pending' WHERE key='checkpoint-excluded'",
            &[],
            &mut fetches,
        )
        .await
        .unwrap();
    }
    let mut content = Vec::new();
    for checkpoint_index in 0..if paging { 2 } else { 1 } {
        for edit in 0..if paging { 40 } else { 1 } {
            content = vec![(43 + checkpoint_index * 41 + edit) as u8; 96 * 1024];
            execute_hydrating(
                &session,
                &storage,
                &old,
                &authority,
                "UPDATE lix_file SET content=$1 WHERE path='/checkpoint.bin'",
                &[Value::Blob(content.clone().into())],
                &mut fetches,
            )
            .await
            .unwrap();
        }
        if !ordinary_only {
            let checkpoint_sql = if cold_blob.is_some() {
                "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_file')))"
            } else {
                "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_file') WHERE to_path='/checkpoint.bin'))"
            };
            execute_hydrating(
                &session,
                &storage,
                &old,
                &authority,
                checkpoint_sql,
                &[],
                &mut fetches,
            )
            .await
            .unwrap();
        }
    }
    if paging {
        content = vec![199u8; 96 * 1024];
        execute_hydrating(
            &session,
            &storage,
            &old,
            &authority,
            "UPDATE lix_file SET content=$1 WHERE path='/checkpoint.bin'",
            &[Value::Blob(content.clone().into())],
            &mut fetches,
        )
        .await
        .unwrap();
    }
    let branch = &old.descriptor().selected_branch.branch_id;
    if let Some(deferred) = cold_blob {
        assert!(
            !crate::sync::partial_blob::manifest_is_resident(&storage, &old, cold_id)
                .await
                .unwrap()
        );
        let mut manifest = authority
            .get_sync_blob_manifest(&cold_id.to_hex())
            .await
            .unwrap()
            .unwrap();
        manifest.inline_bytes_base64 = None;
        if deferred {
            crate::sync::partial_blob::install_manifest(&storage, &old, cold_id, &manifest)
                .await
                .unwrap();
        }
        let mut unrelated = manifest.clone();
        unrelated.blob_id = "00".repeat(32);
        let mut malformed = manifest.clone();
        malformed.size_bytes += 1;
        let mut captured = None;
        for reply in [vec![], vec![unrelated], vec![malformed]] {
            *blob_reply.lock().unwrap() = Some(reply);
            let error = crate::sync::partial_upload_cycle::upload_partial_once(
                &storage,
                &old,
                branch,
                uuid::Uuid::now_v7().to_string(),
                32,
                wire_budget,
                |request| {
                    let (storage, old, transport) = (&storage, &old, &transport);
                    async move {
                        crate::sync::partial_blob_upload::push_partial_with_blobs(
                            storage, old, transport, &request,
                        )
                        .await
                    }
                },
            )
            .await
            .unwrap_err();
            assert_eq!(error.code, LixError::CODE_INVALID_PARAM);
            let read = storage.begin_read(Default::default()).await.unwrap();
            let (push, _, _) =
                crate::sync::partial_push_state::load_partial_push_state(&read, &old, branch)
                    .await
                    .unwrap();
            let pending = push
                .prepared
                .expect("unconfirmed content retains exact publication");
            if let Some(previous) = &captured {
                assert_eq!(previous, &pending);
            } else {
                captured = Some(pending);
            }
            assert!(publication_requests.lock().unwrap().is_empty());
        }
        *blob_reply.lock().unwrap() = None;
    }
    let first = crate::sync::partial_upload_cycle::upload_partial_once(
        &storage,
        &old,
        branch,
        uuid::Uuid::now_v7().to_string(),
        32,
        wire_budget,
        |request| {
            let (storage, old, transport) = (&storage, &old, &transport);
            async move {
                assert!(request.commits.len() <= 32);
                assert!(serde_json::to_vec(&request).unwrap().len() <= wire_budget);
                crate::sync::partial_blob_upload::push_partial_with_blobs(
                    storage, old, transport, &request,
                )
                .await?;
                Err(LixError::new(
                    "TEST_LOST_CHECKPOINT_ACK",
                    "authority accepted checkpoint before reply was lost",
                ))
            }
        },
    )
    .await
    .unwrap_err();
    assert_eq!(first.code, "TEST_LOST_CHECKPOINT_ACK");
    if !paging {
        let requests = publication_requests.lock().unwrap();
        assert_eq!(
            requests.len(),
            1,
            "96KiB checkpoint publication is one HTTP request: {requests:?}"
        );
        assert!(requests[0].ends_with("/sync/push"));
    }
    let read = storage.begin_read(Default::default()).await.unwrap();
    let (pending, _, _) =
        crate::sync::partial_push_state::load_partial_push_state(&read, &old, branch)
            .await
            .unwrap();
    let captured = pending
        .prepared
        .expect("lost response retains exact upload");
    drop(read);
    if paging {
        let too_small = crate::sync::partial_upload_cycle::upload_partial_once(
            &storage,
            &old,
            branch,
            uuid::Uuid::now_v7().to_string(),
            32,
            1,
            |_| async {
                panic!("a captured upload must not be recut or sent under a smaller retry budget")
            },
        )
        .await
        .unwrap_err();
        assert_eq!(too_small.code, "LIX_PARTIAL_UPLOAD_PREPARATION_REQUIRED");
        let read = storage.begin_read(Default::default()).await.unwrap();
        let (unchanged, _, _) =
            crate::sync::partial_push_state::load_partial_push_state(&read, &old, branch)
                .await
                .unwrap();
        assert_eq!(unchanged.prepared.as_ref(), Some(&captured));
    }
    assert!(
        crate::sync::partial_upload_cycle::upload_partial_once(
            &storage,
            &old,
            branch,
            uuid::Uuid::now_v7().to_string(),
            32,
            wire_budget,
            |request| {
                let (storage, old, transport) = (&storage, &old, &transport);
                async move {
                    crate::sync::partial_blob_upload::push_partial_with_blobs(
                        storage, old, transport, &request,
                    )
                    .await
                }
            },
        )
        .await
        .unwrap()
    );
    let mut extra_waves = 0;
    let mut lost_checkpoint_ack = false;
    if paging {
        assert_eq!(
            captured.target.checkpoint, captured.expected.checkpoint,
            "ordinary source prefix must retain authority checkpoint"
        );
        loop {
            let result = crate::sync::partial_upload_cycle::upload_partial_once(
                &storage,
                &old,
                branch,
                uuid::Uuid::now_v7().to_string(),
                32,
                wire_budget,
                |request| {
                    let (storage, old, transport, lost) =
                        (&storage, &old, &transport, &mut lost_checkpoint_ack);
                    async move {
                        assert!(request.commits.len() <= 32);
                        assert!(serde_json::to_vec(&request).unwrap().len() <= wire_budget);
                        let changes_checkpoint = request
                            .ref_updates
                            .iter()
                            .any(|r| r.checkpoint_commit_id != r.expected_checkpoint_commit_id);
                        let response = crate::sync::partial_blob_upload::push_partial_with_blobs(
                            storage, old, transport, &request,
                        )
                        .await?;
                        if changes_checkpoint && !*lost {
                            *lost = true;
                            return Err(LixError::new(
                                "TEST_LOST_CHECKPOINT_ACK",
                                "lost checkpoint wave ACK",
                            ));
                        }
                        Ok(response)
                    }
                },
            )
            .await;
            match result {
                Ok(false) => break,
                Ok(true) => {}
                Err(error) if error.code == "TEST_LOST_CHECKPOINT_ACK" => {
                    // The worker refreshes descriptors between retries. Exact
                    // authority coordinates recover this ACK before refusing to
                    // replace the still-newer local working state.
                    let refreshed = prepare_descriptor_with_merge(
                        engine.clone(),
                        old.clone(),
                        &transport,
                        transport.partial_replica_descriptor(None).await.unwrap(),
                        crate::sync::partial_publication::PartialRecoveryPolicy::Normal,
                    )
                    .await;
                    assert_eq!(
                        refreshed
                            .err()
                            .expect("newer local state remains pending")
                            .code,
                        "LIX_PARTIAL_REPLICA_REBASE_REQUIRED"
                    );
                    let read = storage.begin_read(Default::default()).await.unwrap();
                    let (recovered, _, _) =
                        crate::sync::partial_push_state::load_partial_push_state(
                            &read, &old, branch,
                        )
                        .await
                        .unwrap();
                    assert!(
                        recovered.prepared.is_none(),
                        "descriptor retry settles the exact accepted wave"
                    );
                }
                Err(error) => panic!("paged checkpoint upload: {error}"),
            }
            let excluded = authority
                .execute(
                    "SELECT value FROM lix_key_value WHERE key='checkpoint-excluded'",
                    &[],
                )
                .await
                .unwrap();
            assert_eq!(
                excluded.rows()[0]
                    .get::<serde_json::Value>("value")
                    .unwrap(),
                serde_json::json!("still-pending"),
                "intermediate selected checkpoints must preserve excluded working rows"
            );
            extra_waves += 1;
            assert!(
                extra_waves < 128,
                "checkpoint upload must make bounded progress"
            );
        }
        assert!(extra_waves >= 3);
        assert_eq!(lost_checkpoint_ack, !ordinary_only);
        if ordinary_only {
            assert_eq!(
                captured.target.checkpoint,
                old.descriptor().selected_branch.checkpoint.commit_id
            );
        }
    }
    let read = storage.begin_read(Default::default()).await.unwrap();
    let (settled, _, _) =
        crate::sync::partial_push_state::load_partial_push_state(&read, &old, branch)
            .await
            .unwrap();
    assert!(settled.prepared.is_none());
    if !paging {
        assert_eq!(settled.confirmed, captured.target);
    }
    let control = crate::branch::BranchHeadControlContext::new()
        .reader(&read)
        .load(branch)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(settled.confirmed.head, control.head_commit_id.to_string());
    assert_eq!(
        Some(settled.confirmed.checkpoint.clone()),
        control
            .working_diff_checkpoint_commit_id
            .map(|id| id.to_string())
    );
    drop(read);
    let descriptor = authority
        .partial_replica_descriptor(Some(branch))
        .await
        .unwrap();
    assert_eq!(
        descriptor.selected_branch.checkpoint.commit_id,
        settled.confirmed.checkpoint
    );
    let result = authority
        .execute(
            "SELECT content FROM lix_file WHERE path='/checkpoint.bin'",
            &[],
        )
        .await
        .unwrap();
    assert_eq!(result.rows()[0].get::<Vec<u8>>("content").unwrap(), content);
    if let Some(deferred) = cold_blob {
        let cold = authority
            .execute("SELECT content FROM lix_file WHERE path='/cold.bin'", &[])
            .await
            .unwrap();
        assert_eq!(
            cold.rows()[0].get::<Vec<u8>>("content").unwrap(),
            cold_content
        );

        assert_eq!(
            crate::sync::partial_blob::manifest_is_resident(&storage, &old, cold_id)
                .await
                .unwrap(),
            deferred
        );
        let chunks = crate::binary_cas::CanonicalBlobManifest::from_bytes(&cold_content).chunks;
        let read = storage.begin_read(Default::default()).await.unwrap();
        for chunk in chunks {
            assert!(
                crate::binary_cas::load_verified_chunk(&read, chunk.hash)
                    .await
                    .unwrap()
                    .is_none()
            );
            assert_eq!(
                crate::binary_cas::chunk_presence_many(&read, &[chunk.hash])
                    .await
                    .unwrap(),
                vec![false]
            );
        }
    }
}

mod retained_files;

mod conflict_file;

mod global_during_merge;
mod included_upload;

mod combined_body_limit;
mod large_blob_upload;

mod branch_switch_recovery;

mod transaction_hydration;

mod recovery_latency;

mod lazy_publication;

mod file_open_probe;

mod read_fulfillment_integration;