liminal-server 0.24.1

Standalone server for the liminal messaging bus
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
use super::{
    MergedSourcePosition, ObserverProgressLineage, ObserverProgressOccurrence,
    ObserverProgressSourceIdentity, ObserverProgressSourceMetadata, ObserverProgressSourceWitness,
    ObserverProgressWitnessState, validate_metadata,
};
use crate::server::participant::production::restore_checkpoint::{
    CheckpointError, CheckpointPositions,
};
use crate::server::participant::production::state::checkpoint_body::invalid;
use liminal_protocol::lifecycle::{ObserverProgressProjection, OwnerCheckpointRestoreError};
use liminal_protocol::lifecycle::{ObserverProjectionCheckpointKind, RestoredLifecycle};
use liminal_protocol::wire::{ConversationId, DeliverySeq};
use std::collections::{BTreeMap, BTreeSet};

#[derive(Debug, thiserror::Error)]
#[error("native observer checkpoint source refused: {0:?}")]
struct NativeObserverSourceError(OwnerCheckpointRestoreError);

fn native_error(source: OwnerCheckpointRestoreError) -> CheckpointError {
    CheckpointError::LiveState {
        source: Box::new(NativeObserverSourceError(source)),
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
struct SavedWitness {
    projection: Vec<u8>,
    source: Vec<u8>,
    merged_position: MergedSourcePosition,
    metadata: ObserverProgressSourceMetadata,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct SavedState {
    version: u8,
    conversation_id: ConversationId,
    witnesses: Vec<SavedWitness>,
    pruned_sources: Vec<SavedWitness>,
    occurrences: Vec<ObserverProgressOccurrence>,
    lineage_progress: Vec<(ObserverProgressLineage, DeliverySeq)>,
    last_merged_position: Option<MergedSourcePosition>,
    pruned_through: DeliverySeq,
}

impl ObserverProgressSourceWitness {
    fn saved(&self) -> Result<SavedWitness, CheckpointError> {
        self.validate_source(self.metadata.occurrence.conversation_id())?;
        Ok(SavedWitness {
            projection: self.projection.encode_checkpoint().to_vec(),
            source: self
                .projection
                .encode_checkpoint_source()
                .map_err(|_| self.missing_source())?,
            merged_position: self.merged_position,
            metadata: self.metadata,
        })
    }

    const fn missing_source(&self) -> CheckpointError {
        CheckpointError::MissingObserverProgressProjectionSource {
            conversation_id: self.metadata.occurrence.conversation_id(),
            participant_id: Some(self.metadata.occurrence.participant_id()),
            base_log_head: Some(self.merged_position.base_log_head),
            extension_sequence: Some(self.merged_position.extension_sequence),
            witness_progress: Some(self.progress()),
            pruned_through: None,
            encoded_section_bytes: None,
        }
    }

    fn validate_source(&self, conversation_id: ConversationId) -> Result<(), CheckpointError> {
        validate_metadata(self.progress(), self.metadata)
            .map_err(|_| invalid("observer witness metadata"))?;
        if self.projection.conversation_id() != conversation_id
            || self.metadata.occurrence.conversation_id() != conversation_id
            || self.merged_position != self.metadata.source.merged_position()
            || self.projection.checkpoint_source_participant_id()
                != Some(self.metadata.occurrence.participant_id())
        {
            return Err(self.missing_source());
        }
        let matches = matches!(
            (
                self.projection.checkpoint_source_kind(),
                self.metadata.occurrence,
            ),
            (
                Some(
                    ObserverProjectionCheckpointKind::DetachedTerminal
                        | ObserverProjectionCheckpointKind::DiedTerminal,
                ),
                ObserverProgressOccurrence::AttachedTerminal { .. }
                    | ObserverProgressOccurrence::DetachedTerminal { .. }
                    | ObserverProgressOccurrence::DiedTerminal { .. },
            ) | (
                Some(ObserverProjectionCheckpointKind::ParticipantAck),
                ObserverProgressOccurrence::ParticipantAck { .. },
            ) | (
                Some(ObserverProjectionCheckpointKind::MarkerAck),
                ObserverProgressOccurrence::MarkerAck { .. },
            ) | (
                Some(ObserverProjectionCheckpointKind::Leave),
                ObserverProgressOccurrence::Leave { .. },
            ) | (
                Some(ObserverProjectionCheckpointKind::RecoveredFate),
                ObserverProgressOccurrence::RecoveredFate { .. },
            )
        );
        if !matches {
            return Err(self.missing_source());
        }
        let associated = match self.metadata.occurrence {
            ObserverProgressOccurrence::DetachedTerminal { .. } => {
                self.projection.checkpoint_source_kind()
                    == Some(ObserverProjectionCheckpointKind::DetachedTerminal)
            }
            ObserverProgressOccurrence::DiedTerminal { .. } => {
                self.projection.checkpoint_source_kind()
                    == Some(ObserverProjectionCheckpointKind::DiedTerminal)
            }
            ObserverProgressOccurrence::RecoveredFate { binding_epoch, .. } => {
                self.projection.checkpoint_source_binding_epoch() == Some(binding_epoch)
            }
            _ => true,
        };
        if !associated {
            return Err(self.missing_source());
        }

        self.projection
            .encode_checkpoint_source()
            .map_err(|_| self.missing_source())?;
        Ok(())
    }
}

impl SavedWitness {
    fn restore(
        self,
        positions: &CheckpointPositions,
        lifecycle: &RestoredLifecycle,
    ) -> Result<ObserverProgressSourceWitness, CheckpointError> {
        let projection = lifecycle
            .restore_checkpoint_observer_projection(
                &self.source,
                self.metadata.occurrence.participant_id(),
            )
            .map_err(native_error)?;
        let projection =
            ObserverProgressProjection::restore_checkpoint(&self.projection, projection)
                .map_err(native_error)?;
        let witness = ObserverProgressSourceWitness {
            projection,
            merged_position: self.merged_position,
            metadata: self.metadata,
        };
        witness.validate_source(positions.conversation_id)?;
        let valid = match witness.metadata.source {
            ObserverProgressSourceIdentity::Base { sequence, .. } => {
                sequence < positions.next_log_sequence
            }
            ObserverProgressSourceIdentity::Extension {
                base_log_head,
                extension_sequence,
                ..
            } => {
                base_log_head <= positions.next_log_sequence
                    && extension_sequence < positions.extension_sequence
            }
        };
        if !valid || witness.progress() > positions.observer_progress {
            return Err(invalid("observer witness checkpoint coverage"));
        }
        Ok(witness)
    }
}

impl ObserverProgressWitnessState {
    pub(in crate::server::participant::production) fn validate_checkpoint_sources(
        &self,
        conversation_id: ConversationId,
    ) -> Result<(), CheckpointError> {
        if self.active_visit {
            return Err(invalid("observer active source visit"));
        }
        if self.pruned_through != 0 && self.pruned_sources.is_empty() {
            return Err(CheckpointError::MissingObserverProgressProjectionSource {
                conversation_id,
                participant_id: None,
                base_log_head: None,
                extension_sequence: None,
                witness_progress: None,
                pruned_through: Some(self.pruned_through),
                encoded_section_bytes: None,
            });
        }
        for witness in self.witnesses.iter().chain(self.pruned_sources.values()) {
            witness.validate_source(conversation_id)?;
        }
        self.validate_checkpoint_bookkeeping()
    }

    pub(in crate::server::participant::production) fn validate_checkpoint_lifecycle(
        &self,
        lifecycle: &RestoredLifecycle,
    ) -> Result<(), CheckpointError> {
        for witness in self.witnesses.iter().chain(self.pruned_sources.values()) {
            let source = witness
                .projection
                .encode_checkpoint_source()
                .map_err(|_| witness.missing_source())?;
            let restored = lifecycle
                .restore_checkpoint_observer_projection(
                    &source,
                    witness.metadata.occurrence.participant_id(),
                )
                .map_err(native_error)?;
            if restored.encode_checkpoint() != witness.projection.encode_checkpoint() {
                return Err(invalid("observer capture projection association"));
            }
        }
        Ok(())
    }

    fn validate_checkpoint_bookkeeping(&self) -> Result<(), CheckpointError> {
        if !self
            .witnesses
            .windows(2)
            .all(|pair| pair[0].merged_position < pair[1].merged_position)
        {
            return Err(invalid("observer witness source order"));
        }
        let mut lineage = BTreeMap::new();
        let mut occurrences = BTreeSet::new();
        let mut recovered = BTreeMap::new();
        let mut positions = BTreeSet::new();
        for witness in self.pruned_sources.values().chain(self.witnesses.iter()) {
            if !positions.insert(witness.merged_position) {
                return Err(invalid("observer duplicate merged source"));
            }
            let previous = lineage.insert(
                witness.metadata.lineage,
                (witness.progress(), witness.merged_position),
            );
            if previous.is_some_and(|(progress, position)| {
                progress > witness.progress() || position >= witness.merged_position
            }) {
                return Err(invalid("observer source lineage regression"));
            }
            if witness.metadata.occurrence.prunable() {
                if witness.progress() > self.pruned_through {
                    occurrences.insert(witness.metadata.occurrence);
                }
            } else {
                let ObserverProgressOccurrence::RecoveredFate {
                    participant_id,
                    binding_epoch,
                    ..
                } = witness.metadata.occurrence
                else {
                    return Err(invalid("observer recovered occurrence"));
                };
                if recovered
                    .insert(participant_id, witness.metadata.occurrence)
                    .is_some_and(|previous: ObserverProgressOccurrence| match previous {
                        ObserverProgressOccurrence::RecoveredFate {
                            binding_epoch: held,
                            ..
                        } => binding_epoch.capability_generation <= held.capability_generation,
                        _ => true,
                    })
                {
                    return Err(invalid("observer recovered source generation"));
                }
            }
        }
        occurrences.extend(recovered.into_values());
        let lineage: BTreeMap<_, _> = lineage
            .into_iter()
            .map(|(key, (progress, _))| (key, progress))
            .collect();
        // Two bookkeeping maps are checked against the witnesses; each
        // refuses under its own name, so a refused crossing says which one
        // drifted (the door refused conversation 2's checkpoints under the
        // one shared name from 11 October 23:43).
        if lineage != self.lineage_progress {
            return Err(invalid(
                "observer bookkeeping source association: lineage progress",
            ));
        }
        if occurrences != self.occurrences {
            return Err(invalid(
                "observer bookkeeping source association: occurrences",
            ));
        }
        if positions.last().copied() != self.last_merged_position {
            return Err(invalid("observer last merged source"));
        }
        let pruned_maximum = self
            .pruned_sources
            .values()
            .map(ObserverProgressSourceWitness::progress)
            .max()
            .unwrap_or(0);
        if pruned_maximum != self.pruned_through {
            return Err(invalid("observer pruned source association"));
        }
        self.validate_pruned_source_lineages()
    }

    fn validate_pruned_source_lineages(&self) -> Result<(), CheckpointError> {
        for (lineage, source) in &self.pruned_sources {
            if source.metadata.lineage != *lineage || source.progress() > self.pruned_through {
                return Err(invalid("observer pruned lineage source"));
            }
        }
        if !self.pruned_sources.is_empty()
            && self
                .witnesses
                .iter()
                .any(|witness| witness.progress() <= self.pruned_through)
        {
            return Err(invalid("observer witness below prune boundary"));
        }
        Ok(())
    }

    fn checkpoint_maximum(&self) -> DeliverySeq {
        self.witnesses
            .iter()
            .chain(self.pruned_sources.values())
            .map(ObserverProgressSourceWitness::progress)
            .max()
            .unwrap_or(0)
    }

    pub(in crate::server::participant::production) fn encode_checkpoint(
        &self,
        conversation_id: ConversationId,
        observer_progress: DeliverySeq,
    ) -> Result<Vec<u8>, CheckpointError> {
        self.validate_checkpoint_sources(conversation_id)?;
        if self.checkpoint_maximum() != observer_progress {
            return Err(invalid("observer capture maximum"));
        }
        if self.checkpoint_is_pristine() {
            return Ok(Vec::new());
        }
        let state = SavedState {
            version: 1,
            conversation_id,
            witnesses: self
                .witnesses
                .iter()
                .map(ObserverProgressSourceWitness::saved)
                .collect::<Result<_, _>>()?,
            pruned_sources: self
                .pruned_sources
                .values()
                .map(ObserverProgressSourceWitness::saved)
                .collect::<Result<_, _>>()?,
            occurrences: self.occurrences.iter().copied().collect(),
            lineage_progress: self
                .lineage_progress
                .iter()
                .map(|(&lineage, &progress)| (lineage, progress))
                .collect(),
            last_merged_position: self.last_merged_position,
            pruned_through: self.pruned_through,
        };
        serde_json::to_vec(&state).map_err(|_| invalid("observer witness encoding"))
    }

    pub(in crate::server::participant::production) fn decode_checkpoint(
        bytes: &[u8],
        positions: &CheckpointPositions,
        lifecycle: &RestoredLifecycle,
    ) -> Result<Self, CheckpointError> {
        if bytes.is_empty() {
            if positions.observer_progress != 0 {
                return Err(invalid("missing observer witness state"));
            }
            return Ok(Self::new());
        }
        let saved: SavedState =
            serde_json::from_slice(bytes).map_err(|_| invalid("observer witness framing"))?;
        if saved.version != 1
            || saved.conversation_id != positions.conversation_id
            || serde_json::to_vec(&saved)
                .map_err(|_| invalid("observer witness canonical encoding"))?
                != bytes
        {
            return Err(invalid("observer witness canonical association"));
        }
        let mut state = Self::new();
        state.witnesses = saved
            .witnesses
            .into_iter()
            .map(|witness| witness.restore(positions, lifecycle))
            .collect::<Result<_, _>>()?;
        for saved in saved.pruned_sources {
            let witness = saved.restore(positions, lifecycle)?;
            if state
                .pruned_sources
                .last_key_value()
                .is_some_and(|(last, _)| *last >= witness.metadata.lineage)
            {
                return Err(invalid("observer pruned source order"));
            }
            state
                .pruned_sources
                .insert(witness.metadata.lineage, witness);
        }
        if !saved.occurrences.windows(2).all(|pair| pair[0] < pair[1])
            || !saved
                .lineage_progress
                .windows(2)
                .all(|pair| pair[0].0 < pair[1].0)
        {
            return Err(invalid("observer bookkeeping order"));
        }
        state.occurrences = saved.occurrences.into_iter().collect();
        state.lineage_progress = saved.lineage_progress.into_iter().collect();
        state.last_merged_position = saved.last_merged_position;
        state.pruned_through = saved.pruned_through;
        state.validate_checkpoint_sources(positions.conversation_id)?;
        let maximum = state
            .witnesses
            .iter()
            .chain(state.pruned_sources.values())
            .map(ObserverProgressSourceWitness::progress)
            .max()
            .unwrap_or(0);
        if maximum != positions.observer_progress {
            return Err(invalid("observer checkpoint maximum"));
        }
        if state.encode_checkpoint(positions.conversation_id, positions.observer_progress)? != bytes
        {
            return Err(invalid("observer checkpoint recapture"));
        }
        Ok(state)
    }
}

pub(super) mod epoch {
    use liminal_protocol::wire::{BindingEpoch, ConnectionIncarnation, Generation};
    use serde::{Deserialize, Serialize};

    pub(in crate::server::participant::production::observer_progress) fn serialize<
        S: serde::Serializer,
    >(
        epoch: &BindingEpoch,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        (
            epoch.connection_incarnation.server_incarnation,
            epoch.connection_incarnation.connection_ordinal,
            epoch.capability_generation.get(),
        )
            .serialize(serializer)
    }

    pub(in crate::server::participant::production::observer_progress) fn deserialize<
        'de,
        D: serde::Deserializer<'de>,
    >(
        deserializer: D,
    ) -> Result<BindingEpoch, D::Error> {
        let (server, ordinal, generation): (u64, u64, u64) =
            Deserialize::deserialize(deserializer)?;
        let generation = Generation::new(generation)
            .ok_or_else(|| serde::de::Error::custom("observer binding generation is zero"))?;
        Ok(BindingEpoch::new(
            ConnectionIncarnation::new(server, ordinal),
            generation,
        ))
    }
}