khive-db 0.16.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
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
use std::ffi::OsString;
use std::io;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::StoreSet;

pub const MAX_RECORD_BYTES: usize = 1_048_576;
pub const MAX_CONFIG_ID_BYTES: usize = 8192;
pub const MAX_PHASE_INTERVAL_MS: u64 = 86_400_000;

/// A closed observation is evidence, never an admission or recovery decision.
#[derive(Debug)]
pub enum ReadObservation {
    Missing,
    Verified(Box<Declaration>),
    Rejected(RecordRefusal),
}

#[derive(Debug, thiserror::Error)]
pub enum RecordRefusal {
    #[error("maintenance I/O: {0}")]
    Io(#[from] io::Error),
    #[error("maintenance record decoding: {0}")]
    Wire(#[from] serde_json::Error),
    #[error("maintenance record refused: {0}")]
    Invalid(&'static str),
    #[error("exact maintenance writer attribution is unsupported on this platform")]
    UnsupportedAttribution,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
    Closing,
    Quiescent,
    Migrating,
    Ready,
    FailedClosed,
}

/// Exact executable identity; this value never authorizes executing a wire path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ImageIdentity {
    Inode {
        device: u64,
        inode: u64,
    },
    Modified {
        before_epoch: bool,
        seconds: u64,
        nanoseconds: u32,
    },
}

impl ImageIdentity {
    fn validate(&self) -> Result<(), RecordRefusal> {
        match self {
            Self::Inode { inode: 0, .. } => Err(invalid("zero executable inode")),
            Self::Modified {
                before_epoch,
                seconds,
                nanoseconds,
            } if *nanoseconds >= 1_000_000_000
                || (*before_epoch && *seconds == 0 && *nanoseconds == 0) =>
            {
                Err(invalid("noncanonical executable timestamp"))
            }
            _ => Ok(()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetIdentity {
    start_path: PathBuf,
    image: ImageIdentity,
    config_id: String,
}

impl TargetIdentity {
    pub fn new(
        start_path: PathBuf,
        image: ImageIdentity,
        config_id: String,
    ) -> Result<Self, RecordRefusal> {
        validate_file_path(&start_path)?;
        image.validate()?;
        if config_id.len() > MAX_CONFIG_ID_BYTES {
            return Err(invalid("config identity too long"));
        }
        Ok(Self {
            start_path,
            image,
            config_id,
        })
    }
    pub fn start_path(&self) -> &Path {
        &self.start_path
    }
    pub fn image(&self) -> &ImageIdentity {
        &self.image
    }
    pub fn config_id(&self) -> &str {
        &self.config_id
    }
}

/// Static cooperative attribution, not cryptographic authentication or liveness.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CoordinatorIdentity {
    pub(super) uid: u32,
    pub(super) pid: u32,
    pub(super) boot_id: String,
    pub(super) start_ticks: u64,
    pub(super) image: ImageIdentity,
}

impl CoordinatorIdentity {
    pub fn uid(&self) -> u32 {
        self.uid
    }
    pub fn pid(&self) -> u32 {
        self.pid
    }
    pub fn boot_id(&self) -> &str {
        &self.boot_id
    }
    pub fn start_ticks(&self) -> u64 {
        self.start_ticks
    }
    pub fn image(&self) -> &ImageIdentity {
        &self.image
    }
    fn validate(&self, owner: u32) -> Result<(), RecordRefusal> {
        if self.uid != owner || self.pid == 0 || self.start_ticks == 0 {
            return Err(invalid("invalid coordinator attribution"));
        }
        validate_uuid(&self.boot_id)?;
        self.image.validate()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Declaration {
    pub(super) epoch: String,
    pub(super) sequence: u64,
    pub(super) phase: Phase,
    pub(super) stores: StoreSet,
    pub(super) target: TargetIdentity,
    pub(super) coordinator: CoordinatorIdentity,
    pub(super) capability_digest: [u8; 32],
    pub(super) phase_started_unix_ms: u64,
    pub(super) phase_deadline_unix_ms: u64,
    pub(super) failure_code: Option<String>,
}

impl Declaration {
    /// Parse strict wire data without establishing trust or granting admission.
    ///
    /// `expected_owner_uid` is caller-supplied comparison data, not a filesystem
    /// metadata result or proof of provenance. This performs no filesystem or
    /// process checks and proves neither publication history nor actual readiness.
    /// A parsed `Ready` phase is data, never authorization to release stores.
    pub fn parse_untrusted(bytes: &[u8], expected_owner_uid: u32) -> Result<Self, RecordRefusal> {
        decode(bytes, expected_owner_uid)
    }

    /// Encode validated wire data without publishing or granting admission.
    ///
    /// `expected_owner_uid` is caller-supplied comparison data. This performs no
    /// filesystem or process checks, proves no ownership or publisher attribution,
    /// and does not capture a writer identity or authorize releasing stores.
    pub fn encode_untrusted(&self, expected_owner_uid: u32) -> Result<Vec<u8>, RecordRefusal> {
        encode(self, expected_owner_uid)
    }

    pub fn epoch(&self) -> &str {
        &self.epoch
    }
    pub fn sequence(&self) -> u64 {
        self.sequence
    }
    pub fn phase(&self) -> Phase {
        self.phase
    }
    pub fn stores(&self) -> &StoreSet {
        &self.stores
    }
    pub fn target(&self) -> &TargetIdentity {
        &self.target
    }
    pub fn coordinator(&self) -> &CoordinatorIdentity {
        &self.coordinator
    }
    pub fn capability_digest(&self) -> &[u8; 32] {
        &self.capability_digest
    }
    pub fn phase_started_unix_ms(&self) -> u64 {
        self.phase_started_unix_ms
    }
    pub fn phase_deadline_unix_ms(&self) -> u64 {
        self.phase_deadline_unix_ms
    }
    pub fn failure_code(&self) -> Option<&str> {
        self.failure_code.as_deref()
    }

    pub(super) fn validate(&self, owner: u32) -> Result<(), RecordRefusal> {
        validate_uuid(&self.epoch)?;
        if self.sequence == 0 {
            return Err(invalid("zero sequence"));
        }
        self.coordinator.validate(owner)?;
        // Revalidate even internally constructed values at every publication boundary.
        TargetIdentity::new(
            self.target.start_path.clone(),
            self.target.image.clone(),
            self.target.config_id.clone(),
        )?;
        let interval = self
            .phase_deadline_unix_ms
            .checked_sub(self.phase_started_unix_ms)
            .ok_or_else(|| invalid("deadline precedes phase"))?;
        if interval == 0 || interval > MAX_PHASE_INTERVAL_MS {
            return Err(invalid("invalid phase deadline"));
        }
        match (self.phase, self.failure_code.as_deref()) {
            (Phase::FailedClosed, Some(code))
                if !code.is_empty()
                    && code.len() <= 64
                    && code
                        .bytes()
                        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') =>
            {
                Ok(())
            }
            (Phase::FailedClosed, _) => Err(invalid("invalid failure code")),
            (_, None) => Ok(()),
            _ => Err(invalid("failure code outside failed_closed")),
        }
    }
}

/// A participant is mandatory for public reads; prior bindings only tighten checks.
#[derive(Debug, Clone)]
pub struct ReadExpectation {
    pub(super) participant: Option<PathBuf>,
    epoch: Option<String>,
    stores: Option<StoreSet>,
    target: Option<TargetIdentity>,
    coordinator: Option<CoordinatorIdentity>,
}

impl ReadExpectation {
    pub fn participant(path: PathBuf) -> Result<Self, RecordRefusal> {
        validate_file_path(&path)?;
        Ok(Self {
            participant: Some(path),
            ..Self::writer()
        })
    }
    pub fn with_epoch(mut self, epoch: String) -> Result<Self, RecordRefusal> {
        validate_uuid(&epoch)?;
        self.epoch = Some(epoch);
        Ok(self)
    }
    pub fn with_stores(mut self, stores: StoreSet) -> Self {
        self.stores = Some(stores);
        self
    }
    pub fn with_target(mut self, target: TargetIdentity) -> Self {
        self.target = Some(target);
        self
    }
    pub fn with_coordinator(mut self, coordinator: CoordinatorIdentity) -> Self {
        self.coordinator = Some(coordinator);
        self
    }
    pub(super) fn writer() -> Self {
        Self {
            participant: None,
            epoch: None,
            stores: None,
            target: None,
            coordinator: None,
        }
    }
    pub(super) fn check(&self, record: &Declaration, parent: &Path) -> Result<(), RecordRefusal> {
        if record.stores.main().parent() != Some(parent)
            || self
                .participant
                .as_ref()
                .is_some_and(|p| !record.stores.paths().contains(p))
            || self.epoch.as_ref().is_some_and(|v| v != record.epoch())
            || self.stores.as_ref().is_some_and(|v| v != record.stores())
            || self.target.as_ref().is_some_and(|v| v != record.target())
            || self
                .coordinator
                .as_ref()
                .is_some_and(|v| v != record.coordinator())
        {
            return Err(invalid("record location or expected binding mismatch"));
        }
        Ok(())
    }
}

/// Coordinator identity is deliberately absent: the writer captures it itself.
#[derive(Debug)]
pub struct EpochDraft {
    pub epoch: String,
    pub stores: StoreSet,
    pub target: TargetIdentity,
    pub capability_digest: [u8; 32],
    pub phase_started_unix_ms: u64,
    pub phase_deadline_unix_ms: u64,
}

#[derive(Debug)]
pub struct PhaseAdvance {
    pub phase: Phase,
    pub phase_started_unix_ms: u64,
    pub phase_deadline_unix_ms: u64,
    pub failure_code: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireStores {
    main: Vec<u8>,
    paths: Vec<Vec<u8>>,
    digest: [u8; 32],
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireTarget {
    start_path: Vec<u8>,
    image: ImageIdentity,
    config_id: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WireDeclaration {
    version: u32,
    epoch: String,
    sequence: u64,
    phase: Phase,
    stores: WireStores,
    target: WireTarget,
    coordinator: CoordinatorIdentity,
    capability_digest: [u8; 32],
    phase_started_unix_ms: u64,
    phase_deadline_unix_ms: u64,
    // Option alone accepts an absent JSON field. Require its presence explicitly.
    #[serde(deserialize_with = "required_failure_code")]
    failure_code: Option<String>,
}

fn required_failure_code<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<String>, D::Error> {
    Option::<String>::deserialize(d)
}

pub(super) fn decode(bytes: &[u8], owner: u32) -> Result<Declaration, RecordRefusal> {
    if bytes.len() > MAX_RECORD_BYTES {
        return Err(invalid("record too large"));
    }
    let w: WireDeclaration = serde_json::from_slice(bytes)?;
    if w.version != 1 {
        return Err(invalid("unsupported record version"));
    }
    let paths: Vec<_> = w.stores.paths.into_iter().map(path).collect();
    let stores = StoreSet::from_canonical(path(w.stores.main), paths.clone())?;
    if stores.paths() != paths.as_slice() {
        return Err(invalid("noncanonical store paths"));
    }
    if stores.digest() != &w.stores.digest {
        return Err(invalid("store digest mismatch"));
    }
    let record = Declaration {
        epoch: w.epoch,
        sequence: w.sequence,
        phase: w.phase,
        stores,
        target: TargetIdentity::new(
            path(w.target.start_path),
            w.target.image,
            w.target.config_id,
        )?,
        coordinator: w.coordinator,
        capability_digest: w.capability_digest,
        phase_started_unix_ms: w.phase_started_unix_ms,
        phase_deadline_unix_ms: w.phase_deadline_unix_ms,
        failure_code: w.failure_code,
    };
    record.validate(owner)?;
    Ok(record)
}

pub(super) fn encode(record: &Declaration, owner: u32) -> Result<Vec<u8>, RecordRefusal> {
    record.validate(owner)?;
    let w = WireDeclaration {
        version: 1,
        epoch: record.epoch.clone(),
        sequence: record.sequence,
        phase: record.phase,
        stores: WireStores {
            main: bytes(record.stores.main()),
            paths: record.stores.paths().iter().map(|p| bytes(p)).collect(),
            digest: *record.stores.digest(),
        },
        target: WireTarget {
            start_path: bytes(record.target.start_path()),
            image: record.target.image.clone(),
            config_id: record.target.config_id.clone(),
        },
        coordinator: record.coordinator.clone(),
        capability_digest: record.capability_digest,
        phase_started_unix_ms: record.phase_started_unix_ms,
        phase_deadline_unix_ms: record.phase_deadline_unix_ms,
        failure_code: record.failure_code.clone(),
    };
    let result = serde_json::to_vec(&w)?;
    if result.len() > MAX_RECORD_BYTES {
        return Err(invalid("record too large"));
    }
    Ok(result)
}

pub(super) fn invalid(message: &'static str) -> RecordRefusal {
    RecordRefusal::Invalid(message)
}
pub(super) fn path(bytes: Vec<u8>) -> PathBuf {
    PathBuf::from(OsString::from_vec(bytes))
}
fn bytes(path: &Path) -> Vec<u8> {
    path.as_os_str().as_bytes().to_vec()
}
pub(super) fn validate_file_path(path: &Path) -> Result<(), RecordRefusal> {
    StoreSet::from_canonical(path.to_path_buf(), vec![path.to_path_buf()])?;
    Ok(())
}
fn validate_uuid(value: &str) -> Result<(), RecordRefusal> {
    let id = uuid::Uuid::parse_str(value).map_err(|_| invalid("noncanonical UUID"))?;
    if id.hyphenated().to_string() != value {
        return Err(invalid("noncanonical UUID"));
    }
    Ok(())
}