lix 0.15.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
use std::collections::VecDeque;
#[cfg(not(test))]
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicBool, AtomicU64};
#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tokio::sync::{Semaphore, oneshot};
use tracing::{Instrument as _, instrument::WithSubscriber as _};

use super::{
    Transaction, TransactionCommitOutcome, commit_transaction_cohort,
    transaction_is_file_cohort_eligible, transactions_can_share_cohort,
};
use crate::LixError;
use crate::functions::FunctionContext;
use crate::observe_invalidation::ObserveInvalidation;
use crate::storage_adapter::Storage;
use crate::telemetry::{
    ActiveTelemetrySpan, SpanContext, TelemetryAttribute, TelemetryContext, TelemetrySink,
    Status, TRANSACTION_NOTIFY, TRANSACTION_STORAGE, TRANSACTION_WAIT,
    current_telemetry_context, next_commit_cohort_id,
};

const COMMIT_QUEUE_CAPACITY: usize = 256;
const COMMIT_COHORT_CAPACITY: usize = 256;
struct CommitRequest<StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    transaction: Transaction<StorageImpl>,
    runtime_functions: FunctionContext,
    result: oneshot::Sender<Result<TransactionCommitOutcome, LixError>>,
    file_cohort_eligible: bool,
    telemetry_context: Option<TelemetryContext>,
    wait_span: Option<ActiveTelemetrySpan>,
    tracing_parent: tracing::Span,
    tracing_dispatch: tracing::Dispatch,
    _capacity: tokio::sync::OwnedSemaphorePermit,
}

#[derive(Clone)]
pub(crate) struct CommitCoordinator<StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    inner: Arc<CommitCoordinatorInner<StorageImpl>>,
}

struct CommitCoordinatorInner<StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    collaboration_write_gate: Arc<tokio::sync::Mutex<()>>,
    observe_invalidation: Arc<ObserveInvalidation>,
    capacity: Arc<Semaphore>,
    telemetry: Option<Arc<dyn TelemetrySink>>,
    checkpoint_gc_running: AtomicBool,
    checkpoint_gc_not_before_sequence: AtomicU64,
    state: Mutex<CommitCoordinatorState<StorageImpl>>,
    #[cfg(test)]
    stats: CommitCoordinatorStats,
}

struct CommitCoordinatorState<StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    running: bool,
    queue: VecDeque<CommitRequest<StorageImpl>>,
}

impl<StorageImpl> Default for CommitCoordinatorState<StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    fn default() -> Self {
        Self {
            running: false,
            queue: VecDeque::new(),
        }
    }
}

#[cfg(test)]
#[derive(Default)]
struct CommitCoordinatorStats {
    cohort_count: AtomicUsize,
    commit_count: AtomicUsize,
    max_cohort_size: AtomicUsize,
    checkpoint_gc_post_commit_hooks: AtomicUsize,
}

impl<StorageImpl> CommitCoordinator<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    pub(crate) fn new(
        collaboration_write_gate: Arc<tokio::sync::Mutex<()>>,
        observe_invalidation: Arc<ObserveInvalidation>,
        telemetry: Option<Arc<dyn TelemetrySink>>,
    ) -> Self {
        Self {
            inner: Arc::new(CommitCoordinatorInner {
                collaboration_write_gate,
                observe_invalidation,
                capacity: Arc::new(Semaphore::new(COMMIT_QUEUE_CAPACITY)),
                telemetry,
                checkpoint_gc_running: AtomicBool::new(false),
                checkpoint_gc_not_before_sequence: AtomicU64::new(0),
                state: Mutex::new(CommitCoordinatorState::default()),
                #[cfg(test)]
                stats: CommitCoordinatorStats::default(),
            }),
        }
    }

    /// Coalesces repository-wide checkpoint maintenance across every session
    /// sharing this coordinator. Foreground checkpoints only attempt this
    /// atomic transition; they never wait for maintenance ownership.
    pub(crate) fn try_begin_checkpoint_gc(&self, checkpoint_sequence: u64) -> bool {
        if checkpoint_sequence
            < self
                .inner
                .checkpoint_gc_not_before_sequence
                .load(Ordering::Acquire)
        {
            return false;
        }
        self.inner
            .checkpoint_gc_running
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok()
    }

    #[cfg(test)]
    pub(crate) fn record_checkpoint_gc_post_commit_hook(&self) {
        self.inner
            .stats
            .checkpoint_gc_post_commit_hooks
            .fetch_add(1, Ordering::Relaxed);
    }

    #[cfg(test)]
    pub(crate) fn checkpoint_gc_post_commit_hooks(&self) -> usize {
        self.inner
            .stats
            .checkpoint_gc_post_commit_hooks
            .load(Ordering::Relaxed)
    }

    /// Process-local fallback when even the durable failure counter loses its
    /// CAS race. This keeps sustained contention from immediately launching a
    /// fresh full repository plan at the next checkpoint.
    pub(crate) fn defer_checkpoint_gc_until(&self, checkpoint_sequence: u64) {
        self.inner
            .checkpoint_gc_not_before_sequence
            .fetch_max(checkpoint_sequence, Ordering::AcqRel);
    }

    pub(crate) fn finish_checkpoint_gc(&self) {
        self.inner
            .checkpoint_gc_running
            .store(false, Ordering::Release);
    }

    pub(crate) async fn commit(
        &self,
        transaction: Transaction<StorageImpl>,
        runtime_functions: FunctionContext,
    ) -> Result<TransactionCommitOutcome, LixError> {
        let wait_span = self.inner.telemetry.as_ref().and_then(|sink| {
            ActiveTelemetrySpan::start_if_enabled(
                sink,
                &TRANSACTION_WAIT,
                vec![TelemetryAttribute::string(
                    "lix.wait.reason",
                    "commit_coordinator",
                )],
            )
        });
        let capacity_future = Arc::clone(&self.inner.capacity).acquire_owned();
        let capacity_result = match wait_span.as_ref() {
            Some(span) => span.instrument(capacity_future).await,
            None => capacity_future.await,
        };
        let capacity = match capacity_result {
            Ok(capacity) => capacity,
            Err(_) => {
                if let Some(span) = wait_span {
                    span.finish(Status::error("commit coordinator closed"), Vec::new());
                }
                return Err(coordinator_closed());
            }
        };
        let file_cohort_eligible = transaction_is_file_cohort_eligible(&transaction);
        let telemetry_context = wait_span
            .as_ref()
            .map(ActiveTelemetrySpan::telemetry_context)
            .or_else(current_telemetry_context);
        let (result, receive) = oneshot::channel();
        let leads = self.enqueue(CommitRequest {
            transaction,
            runtime_functions,
            result,
            file_cohort_eligible,
            telemetry_context,
            wait_span,
            tracing_parent: tracing::Span::current(),
            tracing_dispatch: tracing::dispatcher::get_default(Clone::clone),
            _capacity: capacity,
        });
        if leads {
            #[cfg(not(target_family = "wasm"))]
            if let Err(error) = self.spawn_driver() {
                self.fail_queued(error);
            }
            #[cfg(target_family = "wasm")]
            self.drive().await;
        }
        let receive_result = receive.await;
        let outcome = match receive_result {
            Ok(outcome) => outcome,
            Err(_) => {
                return Err(coordinator_closed());
            }
        };
        outcome
    }

    #[cfg(not(target_family = "wasm"))]
    fn spawn_driver(&self) -> Result<(), LixError> {
        let coordinator = self.clone();
        crate::background_task::spawn("lix-commit-coordinator", move || async move {
            // `background_task` block_on-pins this future on a default 2 MiB
            // thread. Keep `drive` itself on the heap so commit wrappers cannot
            // inflate that stack.
            Box::pin(coordinator.drive()).await;
        })
    }

    fn enqueue(&self, request: CommitRequest<StorageImpl>) -> bool {
        {
            let mut state = self
                .inner
                .state
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            state.queue.push_back(request);
            if state.running {
                false
            } else {
                state.running = true;
                true
            }
        }
    }

    #[cfg(not(target_family = "wasm"))]
    fn fail_queued(&self, error: LixError) {
        let requests = {
            let mut state = self
                .inner
                .state
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            state.running = false;
            state.queue.drain(..).collect::<Vec<_>>()
        };
        for request in requests {
            if let Some(span) = request.wait_span {
                span.finish(
                    Status::error(error.code.clone()),
                    vec![TelemetryAttribute::string("error.type", error.code.clone())],
                );
            }
            let _ = request.result.send(Err(error.clone()));
        }
    }

    async fn drive(&self) {
        let mut driver = CommitDriverGuard::new(&self.inner);
        #[cfg(target_family = "wasm")]
        tokio::task::yield_now().await;
        loop {
            let mut cohort = {
                let mut state = self
                    .inner
                    .state
                    .lock()
                    .unwrap_or_else(|error| error.into_inner());
                let take = state.queue.len().min(COMMIT_COHORT_CAPACITY);
                if take == 0 {
                    state.running = false;
                    driver.disarm();
                    return;
                }
                let compatible = state
                    .queue
                    .front()
                    .map(|leader| {
                        state
                            .queue
                            .iter()
                            .take(take)
                            .take_while(|candidate| {
                                transactions_can_share_cohort(
                                    &leader.transaction,
                                    &candidate.transaction,
                                    leader.file_cohort_eligible,
                                    candidate.file_cohort_eligible,
                                )
                            })
                            .count()
                    })
                    .unwrap_or(0);
                // An ineligible request is an intentional singleton and may
                // not poison the compatible semantic wave behind it.
                let take = compatible.max(1);
                state.queue.drain(..take).collect::<Vec<_>>()
            };
            #[cfg(test)]
            {
                self.inner
                    .stats
                    .cohort_count
                    .fetch_add(1, Ordering::Relaxed);
                self.inner
                    .stats
                    .commit_count
                    .fetch_add(cohort.len(), Ordering::Relaxed);
                self.inner
                    .stats
                    .max_cohort_size
                    .fetch_max(cohort.len(), Ordering::Relaxed);
            }
            let _gate = self
                .inner
                .collaboration_write_gate
                .lock()
                .instrument(tracing::debug_span!(
                    target: "lix_transaction",
                    "lix.transaction.commit_cohort",
                    cohort_size = cohort.len(),
                ))
                .await;
            for request in &mut cohort {
                if let Some(span) = request.wait_span.take() {
                    span.finish(Status::Unset, Vec::new());
                }
            }
            let transaction_count = cohort.len();
            let telemetry_context = cohort_telemetry_context(&cohort);
            let tracing_parent = cohort.first().map_or_else(tracing::Span::none, |request| {
                request.tracing_parent.clone()
            });
            let tracing_dispatch = cohort
                .first()
                .map(|request| request.tracing_dispatch.clone());
            let mut senders = Vec::with_capacity(transaction_count);
            let mut inputs = Vec::with_capacity(cohort.len());
            let mut checkpoint_gc_sequences = Vec::with_capacity(cohort.len());
            for request in cohort {
                senders.push((request.result, request._capacity));
                checkpoint_gc_sequences.push(request.transaction.checkpoint_gc_sequence());
                inputs.push((request.transaction, request.runtime_functions));
            }
            let commit_and_notify = async {
                let outcomes = Box::pin(commit_transaction_cohort(inputs)).await;
                if let Some(outcome) = outcomes.iter().find_map(|result| result.as_ref().ok()) {
                    let notify = ActiveTelemetrySpan::start_current(
                        &TRANSACTION_NOTIFY,
                        vec![TelemetryAttribute::i64(
                            "lix.transaction.count",
                            i64::try_from(transaction_count).unwrap_or(i64::MAX),
                        )],
                    );
                    let _entered = notify.as_ref().map(ActiveTelemetrySpan::enter);
                    self.inner
                        .observe_invalidation
                        .bump_if_storage_changed(&outcome.storage_stats);
                    drop(_entered);
                    if let Some(notify) = notify {
                        notify.finish(Status::Unset, Vec::new());
                    }
                }
                outcomes
            }
            .instrument(tracing_parent);
            let commit_and_notify = match tracing_dispatch {
                Some(dispatch) => commit_and_notify.with_subscriber(dispatch),
                None => commit_and_notify.with_current_subscriber(),
            };
            let mut outcomes = match telemetry_context.as_ref() {
                Some(context) => Box::pin(context.instrument(commit_and_notify)).await,
                None => Box::pin(commit_and_notify).await,
            };
            for (outcome, checkpoint_gc_sequence) in
                outcomes.iter_mut().zip(checkpoint_gc_sequences)
            {
                if let Ok(outcome) = outcome {
                    *outcome = TransactionCommitOutcome {
                        checkpoint_gc_sequence,
                        ..TransactionCommitOutcome::default()
                    };
                }
            }
            debug_assert_eq!(outcomes.len(), senders.len());
            for ((sender, _capacity), outcome) in senders.into_iter().zip(outcomes) {
                let _ = sender.send(outcome);
            }
        }
    }

    #[cfg(test)]
    fn stats(&self) -> (usize, usize, usize) {
        (
            self.inner.stats.cohort_count.load(Ordering::Relaxed),
            self.inner.stats.commit_count.load(Ordering::Relaxed),
            self.inner.stats.max_cohort_size.load(Ordering::Relaxed),
        )
    }
}

struct CommitDriverGuard<'a, StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    inner: &'a CommitCoordinatorInner<StorageImpl>,
    armed: bool,
}

impl<'a, StorageImpl> CommitDriverGuard<'a, StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    fn new(inner: &'a CommitCoordinatorInner<StorageImpl>) -> Self {
        Self { inner, armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl<StorageImpl> Drop for CommitDriverGuard<'_, StorageImpl>
where
    StorageImpl: Storage + 'static,
{
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let mut state = self
            .inner
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        state.running = false;
        state.queue.clear();
    }
}

fn cohort_telemetry_context<StorageImpl>(
    cohort: &[CommitRequest<StorageImpl>],
) -> Option<TelemetryContext>
where
    StorageImpl: Storage + 'static,
{
    attach_cohort_parent_contexts(cohort.iter().filter_map(|request| request.telemetry_context.clone()))
}

fn attach_cohort_parent_contexts(
    contexts: impl IntoIterator<Item = TelemetryContext>,
) -> Option<TelemetryContext> {
    let contexts = contexts.into_iter().collect::<Vec<_>>();
    let links = contexts
        .iter()
        .skip(1)
        .filter_map(TelemetryContext::as_link)
        .collect::<Vec<SpanContext>>();
    contexts.into_iter().next().map(|context| {
        context
            .with_commit_cohort_id(next_commit_cohort_id())
            .with_links(links)
    })
}

fn coordinator_closed() -> LixError {
    LixError::new(
        LixError::CODE_INTERNAL_ERROR,
        "transaction commit coordinator closed unexpectedly",
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage_adapter::Memory;
    use crate::telemetry::{CallbackTelemetrySink, TelemetryContext, new_span_context};

    #[test]
    fn cohort_context_uses_leader_as_parent_and_links_other_transactions() {
        let completed = Mutex::new(Vec::new());
        let captured = Arc::new(completed);
        let sink: Arc<dyn TelemetrySink> = Arc::new(CallbackTelemetrySink::new({
            let captured = Arc::clone(&captured);
            move |span| captured.lock().expect("spans").push(span)
        }));
        let parent_a = new_span_context(None);
        let parent_b = new_span_context(None);
        let context = attach_cohort_parent_contexts([
            TelemetryContext::for_test(Arc::clone(&sink), parent_a.clone()),
            TelemetryContext::for_test(Arc::clone(&sink), parent_b.clone()),
        ])
        .expect("cohort context");
        futures_lite::future::block_on(TelemetryContext::instrument(
            &context,
            async {
                let span = ActiveTelemetrySpan::start_current(
                    &TRANSACTION_STORAGE,
                    vec![TelemetryAttribute::i64("lix.transaction.count", 2)],
                )
                .expect("storage enabled");
                span.finish(Status::Unset, Vec::new());
            },
        ));
        let spans = captured.lock().expect("spans");
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0].start.name, "lix.transaction.storage");
        assert_eq!(
            spans[0]
                .start
                .parent_span_context
                .as_ref()
                .map(SpanContext::span_id),
            Some(parent_a.span_id())
        );
        assert_eq!(spans[0].start.links, vec![parent_b]);
        assert!(
            spans[0]
                .start
                .attributes
                .iter()
                .any(|attribute| attribute.key == "lix.commit_cohort_id")
        );
    }

    #[test]
    fn coordinator_capacity_accepts_realtime_collaboration_wave() {
        assert!(COMMIT_COHORT_CAPACITY >= 100);
        assert!(COMMIT_QUEUE_CAPACITY >= COMMIT_COHORT_CAPACITY);
        let coordinator = CommitCoordinator::<Memory>::new(
            Arc::new(tokio::sync::Mutex::new(())),
            Arc::new(ObserveInvalidation::new()),
            None,
        );
        assert_eq!(coordinator.stats(), (0, 0, 0));
    }
}