ruvix-vecgraph 0.1.0

Kernel-resident vector and graph stores for RuVix Cognition Kernel (ADR-087)
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
//! Witness log for kernel vector/graph mutations.
//!
//! Every successful proof-gated mutation emits a witness record to the kernel's
//! append-only log. This provides:
//!
//! - Complete audit trail for all mutations
//! - Foundation for deterministic replay
//! - Verification of attestation chains
//!
//! # Design (from ADR-087 Section 3.2)
//!
//! - Every successful syscall that mutates state emits a witness record
//! - The witness log is append-only (never truncated or modified)
//! - Witness entries contain the proof attestation and mutation metadata

use ruvix_region::backing::MemoryBacking;
use ruvix_region::AppendOnlyRegion;
use ruvix_types::{GraphMutation, KernelError, ProofAttestation, RegionHandle, VectorKey};

use crate::Result;

/// Entry type for the witness log.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum WitnessEntryType {
    /// Vector store mutation.
    VectorMutation = 1,
    /// Graph store mutation.
    GraphMutation = 2,
    /// Store creation.
    StoreCreation = 3,
    /// Store destruction.
    StoreDestruction = 4,
}

impl WitnessEntryType {
    /// Converts from a raw u8 value.
    #[inline]
    #[must_use]
    pub const fn from_u8(value: u8) -> Option<Self> {
        match value {
            1 => Some(Self::VectorMutation),
            2 => Some(Self::GraphMutation),
            3 => Some(Self::StoreCreation),
            4 => Some(Self::StoreDestruction),
            _ => None,
        }
    }
}

/// A witness entry in the mutation log.
///
/// Fixed-size structure for efficient append and read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct WitnessEntry {
    /// Type of witness entry.
    pub entry_type: WitnessEntryType,

    /// Padding for alignment.
    _padding: [u8; 3],

    /// Store ID that was mutated.
    pub store_id: u32,

    /// Sequence number within this store.
    pub sequence: u64,

    /// The proof attestation (82 bytes in ADR-047, padded here).
    pub attestation: ProofAttestation,

    /// Hash of the previous witness entry (chain verification).
    pub prev_hash: [u8; 32],

    /// Timestamp in nanoseconds.
    pub timestamp_ns: u64,
}

impl WitnessEntry {
    /// Size of a witness entry in bytes.
    pub const SIZE: usize = core::mem::size_of::<Self>();

    /// Creates a new witness entry.
    #[inline]
    #[must_use]
    pub const fn new(
        entry_type: WitnessEntryType,
        store_id: u32,
        sequence: u64,
        attestation: ProofAttestation,
        prev_hash: [u8; 32],
        timestamp_ns: u64,
    ) -> Self {
        Self {
            entry_type,
            _padding: [0; 3],
            store_id,
            sequence,
            attestation,
            prev_hash,
            timestamp_ns,
        }
    }

    /// Computes a simple hash of this entry for chaining.
    ///
    /// In a real implementation, this would use SHA-256 or similar.
    #[must_use]
    pub fn compute_hash(&self) -> [u8; 32] {
        // Simple hash combining all fields
        // In production, use a proper cryptographic hash
        let mut hash = [0u8; 32];

        // Mix in entry data
        hash[0] = self.entry_type as u8;
        hash[1..5].copy_from_slice(&self.store_id.to_le_bytes());
        hash[5..13].copy_from_slice(&self.sequence.to_le_bytes());
        hash[13..21].copy_from_slice(&self.timestamp_ns.to_le_bytes());

        // XOR with attestation proof_term_hash
        for i in 0..32 {
            hash[i] ^= self.attestation.proof_term_hash[i];
        }

        // XOR with prev_hash
        for i in 0..32 {
            hash[i] ^= self.prev_hash[i];
        }

        hash
    }

    /// Serializes the entry to bytes.
    #[must_use]
    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
        // SAFETY: WitnessEntry is repr(C) with no padding issues
        unsafe { core::mem::transmute_copy(self) }
    }

    /// Deserializes an entry from bytes.
    ///
    /// Returns `None` if the bytes are invalid.
    #[must_use]
    pub fn from_bytes(bytes: &[u8; Self::SIZE]) -> Option<Self> {
        // Validate entry type
        let entry_type = WitnessEntryType::from_u8(bytes[0])?;

        // SAFETY: We've validated the entry type
        let mut entry: Self = unsafe { core::mem::transmute_copy(bytes) };
        entry.entry_type = entry_type;
        Some(entry)
    }
}

/// Witness log for tracking mutations.
pub struct WitnessLog<B: MemoryBacking> {
    /// The append-only region backing the log.
    region: AppendOnlyRegion<B>,

    /// Hash of the last entry (for chain verification).
    last_hash: [u8; 32],

    /// Current sequence number.
    sequence: u64,

    /// Store ID this log tracks.
    store_id: u32,
}

impl<B: MemoryBacking> WitnessLog<B> {
    /// Creates a new witness log.
    ///
    /// # Arguments
    ///
    /// * `backing` - Memory backing for the region
    /// * `max_entries` - Maximum number of entries to store
    /// * `handle` - Region handle for capability checking
    /// * `store_id` - Store ID this log tracks
    pub fn new(
        backing: B,
        max_entries: usize,
        handle: RegionHandle,
        store_id: u32,
    ) -> Result<Self> {
        let max_size = max_entries
            .checked_mul(WitnessEntry::SIZE)
            .ok_or(KernelError::InvalidArgument)?;

        let region = AppendOnlyRegion::new(backing, max_size, handle)?;

        Ok(Self {
            region,
            last_hash: [0u8; 32],
            sequence: 0,
            store_id,
        })
    }

    /// Records a vector mutation in the witness log.
    pub fn record_vector_mutation(
        &mut self,
        _key: VectorKey,
        attestation: ProofAttestation,
        timestamp_ns: u64,
    ) -> Result<WitnessEntry> {
        let entry = WitnessEntry::new(
            WitnessEntryType::VectorMutation,
            self.store_id,
            self.sequence,
            attestation,
            self.last_hash,
            timestamp_ns,
        );

        self.append_entry(entry)
    }

    /// Records a graph mutation in the witness log.
    pub fn record_graph_mutation(
        &mut self,
        _mutation: &GraphMutation,
        attestation: ProofAttestation,
        timestamp_ns: u64,
    ) -> Result<WitnessEntry> {
        // Include mutation kind in sequence for disambiguation
        let entry = WitnessEntry::new(
            WitnessEntryType::GraphMutation,
            self.store_id,
            self.sequence,
            attestation,
            self.last_hash,
            timestamp_ns,
        );

        self.append_entry(entry)
    }

    /// Records store creation.
    pub fn record_store_creation(
        &mut self,
        attestation: ProofAttestation,
        timestamp_ns: u64,
    ) -> Result<WitnessEntry> {
        let entry = WitnessEntry::new(
            WitnessEntryType::StoreCreation,
            self.store_id,
            self.sequence,
            attestation,
            self.last_hash,
            timestamp_ns,
        );

        self.append_entry(entry)
    }

    /// Appends an entry to the log.
    fn append_entry(&mut self, entry: WitnessEntry) -> Result<WitnessEntry> {
        let bytes = entry.to_bytes();
        self.region.append(&bytes)?;

        // Update chain hash
        self.last_hash = entry.compute_hash();
        self.sequence = self.sequence.wrapping_add(1);

        Ok(entry)
    }

    /// Returns the number of entries in the log.
    #[inline]
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.region.len() / WitnessEntry::SIZE
    }

    /// Returns the current sequence number.
    #[inline]
    #[must_use]
    pub const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Returns the hash of the last entry.
    #[inline]
    #[must_use]
    pub const fn last_hash(&self) -> [u8; 32] {
        self.last_hash
    }

    /// Returns the region handle.
    #[inline]
    #[must_use]
    pub fn handle(&self) -> RegionHandle {
        self.region.handle()
    }

    /// Returns the remaining capacity in entries.
    #[inline]
    #[must_use]
    pub fn remaining_entries(&self) -> usize {
        self.region.remaining() / WitnessEntry::SIZE
    }

    /// Checks if the log is full.
    #[inline]
    #[must_use]
    pub fn is_full(&self) -> bool {
        self.region.remaining() < WitnessEntry::SIZE
    }

    /// Returns the fill ratio (0.0 to 1.0).
    #[inline]
    #[must_use]
    pub fn fill_ratio(&self) -> f32 {
        self.region.fill_ratio()
    }

    /// Reads an entry by index.
    ///
    /// Returns `None` if the index is out of bounds.
    pub fn read_entry(&self, index: usize) -> Result<WitnessEntry> {
        let offset = index
            .checked_mul(WitnessEntry::SIZE)
            .ok_or(KernelError::InvalidArgument)?;

        let mut bytes = [0u8; WitnessEntry::SIZE];
        let read = self.region.read(offset, &mut bytes)?;

        if read < WitnessEntry::SIZE {
            return Err(KernelError::BufferTooSmall);
        }

        WitnessEntry::from_bytes(&bytes).ok_or(KernelError::InternalError)
    }

    /// Verifies the chain integrity from a starting index.
    ///
    /// Returns `true` if all entries chain correctly.
    pub fn verify_chain(&self, start_index: usize) -> Result<bool> {
        let count = self.entry_count();
        if start_index >= count {
            return Ok(true); // Empty range is valid
        }

        let mut prev_hash = if start_index == 0 {
            [0u8; 32]
        } else {
            let prev_entry = self.read_entry(start_index - 1)?;
            prev_entry.compute_hash()
        };

        for i in start_index..count {
            let entry = self.read_entry(i)?;

            if entry.prev_hash != prev_hash {
                return Ok(false);
            }

            prev_hash = entry.compute_hash();
        }

        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ruvix_region::backing::StaticBacking;

    fn create_test_attestation() -> ProofAttestation {
        ProofAttestation::new([1u8; 32], [2u8; 32], 1000, 0x00_01_00_00, 1, 0)
    }

    #[test]
    fn test_witness_entry_type() {
        assert_eq!(
            WitnessEntryType::from_u8(1),
            Some(WitnessEntryType::VectorMutation)
        );
        assert_eq!(
            WitnessEntryType::from_u8(2),
            Some(WitnessEntryType::GraphMutation)
        );
        assert_eq!(WitnessEntryType::from_u8(100), None);
    }

    #[test]
    fn test_witness_entry_serialization() {
        let entry = WitnessEntry::new(
            WitnessEntryType::VectorMutation,
            42,
            1,
            create_test_attestation(),
            [3u8; 32],
            1000,
        );

        let bytes = entry.to_bytes();
        let restored = WitnessEntry::from_bytes(&bytes).unwrap();

        assert_eq!(restored.entry_type, entry.entry_type);
        assert_eq!(restored.store_id, entry.store_id);
        assert_eq!(restored.sequence, entry.sequence);
        assert_eq!(restored.prev_hash, entry.prev_hash);
        assert_eq!(restored.timestamp_ns, entry.timestamp_ns);
    }

    #[test]
    fn test_witness_log_append() {
        let backing = StaticBacking::<8192>::new();
        let handle = RegionHandle::new(1, 0);
        let mut log = WitnessLog::new(backing, 10, handle, 1).unwrap();

        assert_eq!(log.entry_count(), 0);

        let attestation = create_test_attestation();
        let entry = log
            .record_vector_mutation(VectorKey::new(1), attestation, 1000)
            .unwrap();

        assert_eq!(entry.entry_type, WitnessEntryType::VectorMutation);
        assert_eq!(entry.sequence, 0);
        assert_eq!(log.entry_count(), 1);
        assert_eq!(log.sequence(), 1);
    }

    #[test]
    fn test_witness_log_chain() {
        let backing = StaticBacking::<8192>::new();
        let handle = RegionHandle::new(1, 0);
        let mut log = WitnessLog::new(backing, 10, handle, 1).unwrap();

        let attestation = create_test_attestation();

        // First entry
        let entry1 = log
            .record_vector_mutation(VectorKey::new(1), attestation, 1000)
            .unwrap();
        assert_eq!(entry1.prev_hash, [0u8; 32]); // First entry has zero prev_hash

        // Second entry
        let entry2 = log
            .record_vector_mutation(VectorKey::new(2), attestation, 2000)
            .unwrap();
        assert_eq!(entry2.prev_hash, entry1.compute_hash());

        // Third entry
        let entry3 = log
            .record_vector_mutation(VectorKey::new(3), attestation, 3000)
            .unwrap();
        assert_eq!(entry3.prev_hash, entry2.compute_hash());
    }

    #[test]
    fn test_witness_log_read_entry() {
        let backing = StaticBacking::<8192>::new();
        let handle = RegionHandle::new(1, 0);
        let mut log = WitnessLog::new(backing, 10, handle, 1).unwrap();

        let attestation = create_test_attestation();

        log.record_vector_mutation(VectorKey::new(1), attestation, 1000)
            .unwrap();
        log.record_vector_mutation(VectorKey::new(2), attestation, 2000)
            .unwrap();

        let entry0 = log.read_entry(0).unwrap();
        assert_eq!(entry0.sequence, 0);

        let entry1 = log.read_entry(1).unwrap();
        assert_eq!(entry1.sequence, 1);
    }

    #[test]
    fn test_witness_log_verify_chain() {
        let backing = StaticBacking::<8192>::new();
        let handle = RegionHandle::new(1, 0);
        let mut log = WitnessLog::new(backing, 10, handle, 1).unwrap();

        let attestation = create_test_attestation();

        for i in 0..5 {
            log.record_vector_mutation(VectorKey::new(i), attestation, i as u64 * 1000)
                .unwrap();
        }

        assert!(log.verify_chain(0).unwrap());
        assert!(log.verify_chain(2).unwrap());
    }

    #[test]
    fn test_witness_log_full() {
        let backing = StaticBacking::<512>::new();
        let handle = RegionHandle::new(1, 0);
        let mut log = WitnessLog::new(backing, 2, handle, 1).unwrap();

        let attestation = create_test_attestation();

        // Fill the log
        log.record_vector_mutation(VectorKey::new(1), attestation, 1000)
            .unwrap();
        log.record_vector_mutation(VectorKey::new(2), attestation, 2000)
            .unwrap();

        // Should be full now
        assert!(log.is_full());

        // Next append should fail
        let result = log.record_vector_mutation(VectorKey::new(3), attestation, 3000);
        assert_eq!(result, Err(KernelError::RegionFull));
    }
}