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
//! Acceptance/acknowledgement faults over canonical Memory. This wrapper owns
//! the Engine from construction; it never submits a proof to another engine.
use super::*;
use crate::storage_adapter::{
    MemoryRead, MemoryWrite, PutBatch, Storage, StorageCommitResult, StorageError, StorageKey,
    StorageKeyRange, StorageReadOptions, StorageSessionToken, StorageSpace, StorageWrite,
    StorageWriteOptions,
};
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::Duration;

#[derive(Clone, Default)]
struct AcceptanceFault {
    mode: Arc<AtomicU8>,
    owner_gate: Arc<crate::storage_adapter::StorageOwnerGate>,
    entered: Arc<tokio::sync::Notify>,
    release: Arc<tokio::sync::Notify>,
}
#[derive(Clone, Default)]
struct AcceptanceStorage {
    memory: Memory,
    fault: AcceptanceFault,
}
struct AcceptanceWrite {
    inner: MemoryWrite,
    fault: AcceptanceFault,
}
impl Storage for AcceptanceStorage {
    type Read<'a>
        = MemoryRead
    where
        Self: 'a;
    type Write<'a>
        = AcceptanceWrite
    where
        Self: 'a;
    async fn acquire_session(&self) -> Result<StorageSessionToken, StorageError> {
        self.memory.acquire_session().await
    }
    async fn acquire_partial_replica_owner(
        &self,
        token: StorageSessionToken,
    ) -> Result<crate::storage::StorageOwnerLease, StorageError> {
        self.memory.acquire_partial_replica_owner(token).await
    }
    async fn begin_read(&self, opts: StorageReadOptions) -> Result<Self::Read<'_>, StorageError> {
        self.memory.begin_read(opts).await
    }
    async fn begin_write(
        &self,
        opts: StorageWriteOptions,
    ) -> Result<Self::Write<'_>, StorageError> {
        Ok(AcceptanceWrite {
            inner: self.memory.begin_write(opts).await?,
            fault: self.fault.clone(),
        })
    }
}
impl StorageWrite for AcceptanceWrite {
    async fn put_many(
        &mut self,
        space: StorageSpace,
        entries: PutBatch,
    ) -> Result<(), StorageError> {
        self.inner.put_many(space, entries).await
    }
    async fn replace_many(
        &mut self,
        space: StorageSpace,
        entries: PutBatch,
    ) -> Result<(), StorageError> {
        self.inner.replace_many(space, entries).await
    }
    async fn delete_many(
        &mut self,
        space: StorageSpace,
        keys: &[StorageKey],
    ) -> Result<(), StorageError> {
        self.inner.delete_many(space, keys).await
    }
    async fn delete_range(
        &mut self,
        space: StorageSpace,
        range: StorageKeyRange,
    ) -> Result<(), StorageError> {
        self.inner.delete_range(space, range).await
    }
    async fn rollback(self) -> Result<(), StorageError> {
        self.inner.rollback().await
    }
    async fn commit(self) -> Result<StorageCommitResult, StorageError> {
        let result = self.inner.commit().await?;
        let mode = self.fault.mode.swap(0, Ordering::SeqCst);
        if mode != 0 {
            self.fault.entered.notify_one();
            self.fault.release.notified().await;
            if mode == 2 {
                return Err(StorageError::CommitOutcomeUnknown(
                    "injected after Memory accepted publication".into(),
                ));
            }
        }
        Ok(result)
    }
}

async fn prepared_fault_fixture() -> (
    Arc<Engine<AcceptanceStorage>>,
    SessionContext<AcceptanceStorage>,
    Arc<PartialReplicaState>,
    Arc<PartialReplicaState>,
    PreparedPartialPublication,
    AcceptanceFault,
    Lix<Memory>,
) {
    prepared_fault_fixture_with_deadline(None).await
}
async fn prepared_fault_fixture_with_deadline(
    short: Option<Duration>,
) -> (
    Arc<Engine<AcceptanceStorage>>,
    SessionContext<AcceptanceStorage>,
    Arc<PartialReplicaState>,
    Arc<PartialReplicaState>,
    PreparedPartialPublication,
    AcceptanceFault,
    Lix<Memory>,
) {
    let authority = open_lix().await.unwrap();
    authority
        .set_sync_role(crate::sync::SyncRole::Authority)
        .unwrap();
    authority
        .execute(
            "INSERT INTO lix_key_value (key,value) VALUES ('resident','before')",
            &[],
        )
        .await
        .unwrap();
    let old = Arc::new(
        PartialReplicaState::new(
            format!("https://example.test/lix/{}", authority.lix_id()),
            authority.active_account_id().into(),
            uuid::Uuid::now_v7().to_string(),
            authority.partial_replica_descriptor(None).await.unwrap(),
        )
        .unwrap(),
    );
    let backend = AcceptanceStorage::default();
    let fault = backend.fault.clone();
    let storage = StorageAdapter::new(backend);
    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 (mut engine, session) =
        Engine::new_partial_replica(storage.clone(), EngineOptions::new(), &old)
            .await
            .unwrap();
    engine.install_partial_owner(crate::engine::PartialOwnerLifetime::install(
        fault.owner_gate.try_acquire().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());
    execute_hydrating(
        &session,
        &storage,
        &old,
        &authority,
        "SELECT value FROM lix_key_value WHERE key='resident'",
        &[],
        &mut Fetches::default(),
    )
    .await
    .unwrap();
    authority
        .execute(
            "UPDATE lix_key_value SET value='remote' WHERE key='resident'",
            &[],
        )
        .await
        .unwrap();
    let next = Arc::new(
        old.with_descriptor_and_fresh_generations(
            authority.partial_replica_descriptor(None).await.unwrap(),
        )
        .unwrap(),
    );
    let prepared = prepare_hydrating(&engine, &old, next.clone(), &authority).await;
    let prepared = if let Some(duration) = short {
        drop(prepared);
        let deadline = crate::sync::http::CandidateBaselineDeadline::for_test(
            &next.baseline_lease().lease_id,
            duration,
        );
        prepare_hydrating_with_deadline(&engine, &old, next.clone(), &authority, deadline).await
    } else {
        prepared
    };
    (engine, session, old, next, prepared, fault, authority)
}

#[tokio::test]
async fn cancelled_publication_caller_retains_gates_until_acknowledgement() {
    tokio::time::timeout(Duration::from_secs(10),async {
        let (engine,session,old,next,prepared,fault,authority)=prepared_fault_fixture().await;
        fault.mode.store(1,Ordering::SeqCst);
        let mut caller=Box::pin(publish_prepared_partial(engine.clone(),prepared));
        tokio::select! {
            _=fault.entered.notified()=>{},
            result=&mut caller=>panic!("publication acknowledged before injected boundary: {result:?}"),
        }
        drop(caller);
        engine.partial_owner().close();
        assert!(matches!(fault.owner_gate.try_acquire(), Err(StorageError::InUse)),
            "cancelled caller and closed owner must not release accepted publication");
        assert_eq!(engine.sync_mode().partial_admission().as_deref(),Some(old.as_ref()));
        let storage=engine.storage();
        let read=storage.begin_read(Default::default()).await.unwrap();
        assert_eq!(crate::sync::partial_state::load_partial_replica_state(&read).await.unwrap().unwrap().0,*next);
        drop(read);
        let mut query=Box::pin(session.execute("SELECT value FROM lix_key_value WHERE key='resident'",&[]));
        assert!(tokio::time::timeout(Duration::from_millis(30),&mut query).await.is_err(),"direct SQL escaped publication gate before acknowledgement");
        fault.release.notify_one();
        let missing = query.await.unwrap_err();
        assert!(NativeObjectRef::from_missing_error(&missing).unwrap().is_some()
            || NativeMetadataRef::from_missing_error(&missing).unwrap().is_some(), "{missing:?}");
        // Gate acquisition by SQL establishes that the owned publisher finished
        // its ACK and state swap. Its final guard drop may be scheduled next.
        let _new_owner = loop {
            match fault.owner_gate.try_acquire() {
                Ok(owner) => break owner,
                Err(StorageError::InUse) => tokio::task::yield_now().await,
                Err(error) => panic!("unexpected owner acquisition error: {error}"),
            }
        };
        assert_eq!(engine.sync_mode().partial_admission().as_deref(),Some(next.as_ref()));
        let (reopened,fresh)=Engine::new_partial_replica(engine.storage(),EngineOptions::new(),&next).await.unwrap();
        reopened.sync_mode().admit_partial_replica(next.clone(),crate::sync::partial_replica_write_capability());
        assert!(value(execute_hydrating(&fresh, &reopened.storage(), &next, &authority,
            "SELECT value FROM lix_key_value WHERE key='resident'", &[], &mut Fetches::default()).await.unwrap()).contains("remote"));
    }).await.expect("publication cancellation test timed out");
}

#[tokio::test]
async fn accepted_unknown_publication_poison_blocks_sql_until_durable_reopen() {
    tokio::time::timeout(Duration::from_secs(10),async {
        let (engine,session,_,next,prepared,fault,authority)=prepared_fault_fixture().await;
        fault.mode.store(2,Ordering::SeqCst);
        let mut caller=Box::pin(publish_prepared_partial(engine.clone(),prepared));
        tokio::select! {
            _=fault.entered.notified()=>{},
            result=&mut caller=>panic!("publication acknowledged before injected boundary: {result:?}"),
        }
        fault.release.notify_one();
        let error=caller.await.unwrap_err();
        assert_eq!(error.code,LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN);
        for sql in ["SELECT value FROM lix_key_value WHERE key='resident'","UPDATE lix_key_value SET value='unsafe' WHERE key='resident'"] {
            assert_eq!(session.execute(sql,&[]).await.unwrap_err().code,LixError::CODE_STORAGE_COMMIT_OUTCOME_UNKNOWN);
        }
        let storage=engine.storage();
        let read=storage.begin_read(Default::default()).await.unwrap();
        let durable=crate::sync::partial_state::load_partial_replica_state(&read).await.unwrap().unwrap().0;
        assert_eq!(durable,*next);
        drop(read);
        let (reopened,fresh)=Engine::new_partial_replica(storage,EngineOptions::new(),&durable).await.unwrap();
        reopened.sync_mode().admit_partial_replica(Arc::new(durable),crate::sync::partial_replica_write_capability());
        assert!(value(execute_hydrating(&fresh, &reopened.storage(), &next, &authority,
            "SELECT value FROM lix_key_value WHERE key='resident'", &[], &mut Fetches::default()).await.unwrap()).contains("remote"));
    }).await.expect("unknown publication test timed out");
}

#[tokio::test]
async fn expired_candidate_waiting_for_write_gate_never_publishes_even_if_caller_cancelled() {
    for cancel in [false, true] {
        let (engine, _session, old, _next, prepared, _fault, _authority) =
            prepared_fault_fixture_with_deadline(Some(Duration::from_secs(2))).await;
        let held = engine.collaboration_write_gate().lock_owned().await;
        let mut caller = Box::pin(publish_prepared_partial(engine.clone(), prepared));
        // Poll the caller so it spawns its owned task, then establish that the
        // publisher has acquired exclusive interests and is waiting on held.
        assert!(
            tokio::time::timeout(Duration::from_millis(20), &mut caller)
                .await
                .is_err()
        );
        let registry = engine.sync_mode().read_interests().unwrap();
        assert!(
            tokio::time::timeout(Duration::from_millis(20), registry.begin_operation())
                .await
                .is_err()
        );
        if cancel {
            drop(caller);
            tokio::time::sleep(Duration::from_millis(2100)).await;
        } else {
            let error = tokio::time::timeout(Duration::from_secs(3), caller)
                .await
                .unwrap()
                .unwrap_err();
            assert_eq!(error.code, "LIX_PARTIAL_CANDIDATE_EXPIRED");
        }
        // Still hold the write gate: expiration must cancel the owned wait and
        // release the exclusive interest gate independently of caller lifetime.
        let operation = tokio::time::timeout(Duration::from_secs(1), registry.begin_operation())
            .await
            .unwrap();
        drop(operation);
        assert_eq!(
            engine.sync_mode().partial_admission().as_deref(),
            Some(old.as_ref())
        );
        let storage = engine.storage();
        let read = storage.begin_read(Default::default()).await.unwrap();
        assert_eq!(
            crate::sync::partial_state::load_partial_replica_state(&read)
                .await
                .unwrap()
                .unwrap()
                .0,
            *old
        );
        drop(read);
        drop(held);
        engine
            .sync_mode()
            .ensure_partial_admission_healthy()
            .unwrap();
    }
}

#[tokio::test]
async fn candidate_expiring_after_storage_acceptance_poison_blocks_live_sql() {
    let (engine, session, old, next, prepared, fault, _authority) =
        prepared_fault_fixture_with_deadline(Some(Duration::from_secs(2))).await;
    fault.mode.store(1, Ordering::SeqCst);
    let mut caller = Box::pin(publish_prepared_partial(engine.clone(), prepared));
    tokio::select! {
        _ = fault.entered.notified() => {},
        result = &mut caller => panic!("publication did not enter acceptance boundary: {result:?}"),
    }
    tokio::time::sleep(Duration::from_millis(2100)).await;
    fault.release.notify_one();
    let error = caller.await.unwrap_err();
    assert_eq!(error.code, "LIX_PARTIAL_CANDIDATE_EXPIRED");
    assert_eq!(
        engine.sync_mode().partial_admission().as_deref(),
        Some(old.as_ref())
    );
    for sql in [
        "SELECT value FROM lix_key_value WHERE key='resident'",
        "UPDATE lix_key_value SET value='unsafe' WHERE key='resident'",
    ] {
        assert_eq!(
            session.execute(sql, &[]).await.unwrap_err().code,
            "LIX_PARTIAL_CANDIDATE_EXPIRED"
        );
    }
    let storage = engine.storage();
    let read = storage.begin_read(Default::default()).await.unwrap();
    assert_eq!(
        crate::sync::partial_state::load_partial_replica_state(&read)
            .await
            .unwrap()
            .unwrap()
            .0,
        *next,
        "known accepted state remains the recovery source; it must not be rolled back"
    );
}

#[tokio::test]
async fn cancelled_publication_finishes_owned_branch_selector_after_ack() {
    let (engine, _session, old, next, prepared, fault, _authority) = prepared_fault_fixture().await;
    let selector = crate::session::SessionBranch::new(crate::GLOBAL_BRANCH_ID.into());
    let primary = Arc::new(tokio::sync::Mutex::new(()));
    let completion = crate::sync::PartialBranchSwitchCompletion {
        branch: selector.clone(),
        target: next.descriptor().selected_branch.branch_id.clone(),
        _primary_guard: Some(primary.clone().lock_owned().await),
        _session_guard: selector.begin_switch().await,
    };
    fault.mode.store(1, Ordering::SeqCst);
    let mut caller = Box::pin(publish_prepared_partial(
        engine.clone(),
        prepared.with_branch_switch_completion(completion),
    ));
    tokio::select! {
        _ = fault.entered.notified() => {},
        result = &mut caller => panic!("publication acknowledged before acceptance fault: {result:?}"),
    }
    drop(caller);
    engine.partial_owner().close();
    assert_eq!(selector.get().unwrap(), crate::GLOBAL_BRANCH_ID);
    assert_eq!(
        engine.sync_mode().partial_admission().as_deref(),
        Some(old.as_ref())
    );
    assert!(primary.try_lock().is_err());
    assert!(matches!(
        fault.owner_gate.try_acquire(),
        Err(StorageError::InUse)
    ));
    fault.release.notify_one();
    let _finished = tokio::time::timeout(Duration::from_secs(10), primary.lock())
        .await
        .unwrap();
    assert_eq!(
        selector.get().unwrap(),
        next.descriptor().selected_branch.branch_id
    );
    assert_eq!(
        engine.sync_mode().partial_admission().as_deref(),
        Some(next.as_ref())
    );
}