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
// Included inside repository::tests to reuse the real sparse-replica bootstrap.
mod upload_plan_profile {
    use super::*;
    use crate::storage::ProjectedValue;
    use std::sync::atomic::AtomicBool;
    use std::time::Instant;

    #[derive(Clone, Debug, Default, serde::Serialize)]
    struct ReadCounts {
        all_space_returned_bytes: u64,
        commit_header_keys: u64,
        change_value_keys: u64,
        change_value_bytes: u64,
        delta_segment_keys: u64,
        delta_segment_bytes: u64,
    }

    #[derive(Clone, Default)]
    struct ProfileStorage {
        inner: Memory,
        armed: Arc<AtomicBool>,
        counts: Arc<Mutex<ReadCounts>>,
    }

    struct ProfileRead {
        inner: MemoryRead,
        armed: Arc<AtomicBool>,
        counts: Arc<Mutex<ReadCounts>>,
    }

    impl Storage for ProfileStorage {
        type Read<'a>
            = ProfileRead
        where
            Self: 'a;
        type Write<'a>
            = MemoryWrite
        where
            Self: 'a;

        async fn acquire_session(
            &self,
        ) -> Result<crate::storage::StorageSessionToken, StorageError> {
            self.inner.acquire_session().await
        }

        async fn begin_read(&self, options: ReadOptions) -> Result<Self::Read<'_>, StorageError> {
            Ok(ProfileRead {
                inner: self.inner.begin_read(options).await?,
                armed: Arc::clone(&self.armed),
                counts: Arc::clone(&self.counts),
            })
        }

        async fn begin_write(
            &self,
            options: WriteOptions,
        ) -> Result<Self::Write<'_>, StorageError> {
            self.inner.begin_write(options).await
        }

        async fn watch_for_changes(
            &self,
        ) -> Result<crate::storage::StorageChangeWatch, StorageError> {
            self.inner.watch_for_changes().await
        }
    }

    impl StorageRead for ProfileRead {
        fn snapshot_cache_key(&self) -> Option<u128> {
            self.inner.snapshot_cache_key()
        }

        async fn get_many(
            &self,
            requests: &[GetManyRequest<'_>],
        ) -> Result<GetManyResult, StorageError> {
            let result = self.inner.get_many(requests).await?;
            if self.armed.load(Ordering::Relaxed) {
                let mut counts = self.counts.lock().unwrap();
                let mut offset = 0;
                for request in requests {
                    let values = &result.values[offset..offset + request.keys.len()];
                    offset += request.keys.len();
                    let bytes = values
                        .iter()
                        .flatten()
                        .map(|value| match value {
                            ProjectedValue::FullValue(bytes) => bytes.len() as u64,
                            ProjectedValue::KeyOnly => 0,
                        })
                        .sum::<u64>();
                    counts.all_space_returned_bytes += bytes;
                    // Physical epoch banks reserve the top two space-ID bits.
                    if is_logical_space(request.space, COMMIT_SPACE) {
                        counts.commit_header_keys += request.keys.len() as u64;
                    } else if is_logical_space(request.space, crate::changelog::CHANGE_SPACE) {
                        counts.change_value_keys += request.keys.len() as u64;
                        counts.change_value_bytes += bytes;
                    } else if is_logical_space(
                        request.space,
                        crate::tracked_state::TRACKED_STATE_COMMIT_DELTA_SEGMENT_SPACE,
                    ) {
                        counts.delta_segment_keys += request.keys.len() as u64;
                        counts.delta_segment_bytes += bytes;
                    }
                }
            }
            Ok(result)
        }

        async fn begin_scan(
            &self,
            space: StorageSpace,
            range: KeyRange,
            options: BeginScanOptions,
        ) -> Result<ScanCursor<'_>, StorageError> {
            self.inner.begin_scan(space, range, options).await
        }
    }

    async fn replica(authority: &Lix<Memory>) -> (Lix<ProfileStorage>, ProfileStorage) {
        let snapshot = authority.pull_sync_repository(None, 1).await.unwrap();
        let (branch_id, _) = default_head(&snapshot);
        let (history, rows, checkpoint_roots) = snapshot_parts(authority, &snapshot).await;
        let storage = ProfileStorage::default();
        Engine::initialize_with_main_branch_id(storage.clone(), Some(&branch_id))
            .await
            .unwrap();
        crate::migration::admit_repository(&storage, None).await.unwrap();
        let mut replica = open_lix().with_storage(storage.clone()).await.unwrap();
        replica
            .set_sync_role(crate::sync::SyncRole::Replica)
            .unwrap();
        replica
            .try_install_initial_sync_snapshot(
                TEST_REMOTE,
                crate::ANONYMOUS_ACCOUNT_ID,
                &snapshot,
                &history.commits,
                &history.commit_headers,
                &rows,
                &checkpoint_roots,
            )
            .await
            .unwrap();
        install_publication_fence_responder_for_test(&mut replica);
        (replica, storage)
    }

    #[derive(Debug, Default, serde::Serialize)]
    struct DrainProfile {
        catch_up_micros: u128,
        retained_plan: bool,
        commit_payload_load_calls: u64,
        whole_process_vm_hwm_kib: Option<u64>,
        pages: usize,
        commits: usize,
        ref_updates: usize,
        planning_micros: u128,
        maximum_page_planning_micros: u128,
        emitted_members_json_bytes: usize,
        planning_reads: ReadCounts,
        maximum_ack_frontier: usize,
        final_ack_frontier: usize,
        final_receipt_json_bytes: usize,
    }

    async fn frontier(replica: &Lix<ProfileStorage>) -> (usize, usize) {
        let read = replica
            .storage_adapter()
            .begin_read(StorageReadOptions::default())
            .await
            .unwrap();
        let state = load_replica_state(&read).await.unwrap().0.unwrap();
        (
            state.authority_known_commit_ids.len(),
            serde_json::to_vec(&state).unwrap().len(),
        )
    }

    async fn drain(
        authority: &Lix<Memory>,
        replica: &Lix<ProfileStorage>,
        storage: &ProfileStorage,
        limit: usize,
        retained_plan: bool,
    ) -> DrainProfile {
        *storage.counts.lock().unwrap() = ReadCounts::default();
        let mut profile = DrainProfile::default();
        profile.retained_plan = retained_plan;
        let mut cache = None;
        let mut emitted = BTreeSet::new();
        let catch_up_started = Instant::now();
        loop {
            storage.armed.store(true, Ordering::Relaxed);
            let started = Instant::now();
            let (request, payload_loads) =
                crate::sync::upload_metrics::measure_commit_payload_loads(async {
                    if retained_plan {
                        replica
                            .build_sync_push_with_plan(TEST_REMOTE, limit, &mut cache)
                            .await
                    } else {
                        replica.build_sync_push(TEST_REMOTE, limit).await
                    }
                })
                .await;
            let elapsed = started.elapsed().as_micros();
            storage.armed.store(false, Ordering::Relaxed);
            profile.planning_micros += elapsed;
            profile.commit_payload_load_calls += payload_loads;
            profile.maximum_page_planning_micros =
                profile.maximum_page_planning_micros.max(elapsed);
            let Some(request) = request.unwrap() else {
                break;
            };
            assert!(request.commits.len() + request.ref_updates.len() <= limit);
            profile.pages += 1;
            profile.commits += request.commits.len();
            profile.ref_updates += request.ref_updates.len();
            for commit in &request.commits {
                assert!(
                    emitted.insert(commit.commit_id.clone()),
                    "accepted payload must not be resent"
                );
                profile.emitted_members_json_bytes +=
                    serde_json::to_vec(&commit.members).unwrap().len();
            }
            let receipt = authority.push_sync_repository(&request).await.unwrap();
            let cursor = replica
                .load_sync_repository_cursor(TEST_REMOTE)
                .await
                .unwrap()
                .unwrap();
            let response = authority
                .pull_sync_repository(Some(cursor), crate::sync::MAX_SYNC_REQUEST_ITEMS)
                .await
                .unwrap();
            replica
                .apply_sync_repository_pull(TEST_REMOTE, &response)
                .await
                .unwrap();
            assert!(
                replica
                    .load_sync_repository_cursor(TEST_REMOTE)
                    .await
                    .unwrap()
                    .unwrap()
                    >= receipt.cursor
            );
            if retained_plan {
                let plan = cache.as_mut().expect("successful page retains its plan");
                plan.acknowledge().unwrap();
                if plan.is_complete() {
                    cache = None;
                    replica.clear_converged_sync_frontier().await.unwrap();
                }
            }
            let (count, bytes) = frontier(replica).await;
            profile.maximum_ack_frontier = profile.maximum_ack_frontier.max(count);
            profile.final_ack_frontier = count;
            profile.final_receipt_json_bytes = bytes;
        }
        // The terminal planning call can retire the last converged frontier.
        let (count, bytes) = frontier(replica).await;
        profile.final_ack_frontier = count;
        profile.final_receipt_json_bytes = bytes;
        profile.catch_up_micros = catch_up_started.elapsed().as_micros();
        profile.planning_reads = storage.counts.lock().unwrap().clone();
        // Cumulative high-water mark includes fixture construction and all prior
        // tests in this process. This is deliberately not a planner peak metric.
        profile.whole_process_vm_hwm_kib = whole_process_vm_hwm_kib();
        profile
    }

    fn whole_process_vm_hwm_kib() -> Option<u64> {
        let status = std::fs::read_to_string("/proc/self/status").ok()?;
        status.lines().find_map(|line| {
            line.strip_prefix("VmHWM:")?
                .split_whitespace()
                .next()?
                .parse()
                .ok()
        })
    }

    #[tokio::test]
    async fn upload_profile_counts_only_planning_and_preserves_page_boundaries() {
        let authority = open_lix().await.unwrap();
        let (replica, storage) = replica(&authority).await;
        for index in 0..33 {
            write_key_value(&replica, "profile", &format!("value-{index}")).await;
        }
        let profile = drain(&authority, &replica, &storage, 8, false).await;
        assert_eq!(profile.commits, 33);
        assert!(profile.pages >= 5);
        assert!(profile.planning_reads.commit_header_keys > 0);
        assert!(profile.planning_reads.all_space_returned_bytes > 0);
        assert_eq!(profile.commit_payload_load_calls, 33);
        assert!(profile.emitted_members_json_bytes > 0);
        assert!(
            profile.maximum_ack_frontier <= 1,
            "linear acknowledgments retain one frontier tip"
        );
        assert_eq!(read_key_value(&authority, "profile").await, "value-32");
    }

    #[tokio::test]
    async fn upload_profile_retained_wave_reads_headers_and_payloads_linearly() {
        let authority = open_lix().await.unwrap();
        let (replica, storage) = replica(&authority).await;
        for index in 0..65 {
            write_key_value(&replica, "profile", &format!("value-{index}")).await;
        }
        let profile = drain(&authority, &replica, &storage, 8, true).await;
        assert_eq!(profile.commits, 65);
        assert_eq!(profile.pages, 9);
        assert_eq!(profile.commit_payload_load_calls, 65);
        assert!(profile.planning_reads.commit_header_keys > 0);
        assert!(
            profile.planning_reads.commit_header_keys <= 8 * 65,
            "retaining a wave must avoid rewalking its graph for every page: {profile:?}"
        );
        assert_eq!(profile.final_ack_frontier, 0);
        assert_eq!(read_key_value(&authority, "profile").await, "value-64");
    }

    /// Run explicitly with --ignored --nocapture. Fixture writes and authority
    /// processing are excluded from planning time and point-read counters.
    /// Storage bytes are encoded backend reads, not a claimed decoder census.
    #[tokio::test]
    #[ignore = "explicit upload scaling profile: builds 512/2048/8192-commit queues"]
    async fn upload_plan_scaling_profile() {
        let retained_plan = std::env::var("LIX_UPLOAD_PROFILE_CACHED").as_deref() == Ok("1");
        let sizes = std::env::var("LIX_UPLOAD_PROFILE_SIZES")
            .ok()
            .map(|value| {
                value
                    .split(',')
                    .map(|size| size.parse::<usize>().unwrap())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_else(|| vec![512, 2048, 8192]);
        for count in sizes {
            let authority = open_lix().await.unwrap();
            let (replica, storage) = replica(&authority).await;
            let payload = "x".repeat(1024);
            for index in 0..count {
                write_key_value(&replica, "profile", &format!("{index}:{payload}")).await;
            }
            let profile = drain(
                &authority,
                &replica,
                &storage,
                crate::sync::MAX_SYNC_REQUEST_ITEMS,
                retained_plan,
            )
            .await;
            assert_eq!(profile.commits, count);
            assert!(profile.maximum_ack_frontier <= 1);
            assert_eq!(
                read_key_value(&authority, "profile").await,
                format!("{}:{payload}", count - 1)
            );
            println!(
                "UPLOAD_PLAN_PROFILE {}",
                serde_json::json!({"queue_commits": count, "page_limit": crate::sync::MAX_SYNC_REQUEST_ITEMS, "profile": profile})
            );
        }
    }

    #[tokio::test]
    #[ignore = "explicit repeated checkpoint acknowledgment frontier profile"]
    async fn upload_checkpoint_frontier_profile() {
        let retained_plan = std::env::var("LIX_UPLOAD_PROFILE_CACHED").as_deref() == Ok("1");
        for scoped in [false, true] {
            let authority = open_lix().await.unwrap();
            let (replica, storage) = replica(&authority).await;
            let mut waves = Vec::new();
            for wave in 0..32 {
                for index in 0..4 {
                    write_key_value(&replica, "checkpoint-profile", &format!("{wave}:{index}"))
                        .await;
                }
                let sql = if scoped {
                    "SELECT commit_id FROM lix_create_checkpoint(ARRAY(SELECT row_ref FROM lix_diff('lix_key_value')))"
                } else {
                    "SELECT commit_id FROM lix_create_checkpoint()"
                };
                let checkpoint = replica.execute(sql, &[]).await.unwrap().rows()[0]
                    .get::<String>("commit_id")
                    .unwrap();
                let profile = drain(&authority, &replica, &storage, 2, retained_plan).await;
                let remote_checkpoint = authority
                    .execute("SELECT working_base_commit_id AS id FROM lix_branch WHERE id = lix_active_branch_id()", &[])
                    .await
                    .unwrap()
                    .rows()[0]
                    .get::<String>("id")
                    .unwrap();
                assert_eq!(remote_checkpoint, checkpoint);
                assert_eq!(
                    read_key_value(&authority, "checkpoint-profile").await,
                    format!("{wave}:3")
                );
                waves.push(serde_json::json!({"wave": wave + 1, "profile": profile}));
            }
            println!(
                "UPLOAD_FRONTIER_PROFILE {}",
                serde_json::json!({"scoped": scoped, "waves": waves})
            );
        }
    }
}