clm-kernel 0.0.9

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
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
//! Large-Object Content-Defined Chunking, Streaming Range Reads & Anchored Pruning (Sprint 513)
//! Canonical Path: kernel/clm_rust_core/src/layer2/chunk_pruning.rs

use crate::cpn::mcard_token::TokenMCard;
use crate::cpn::token_namespace::MCardMarking;
use crate::layer0::mcard_record::{verify_record, MCardRecord, RecordVerification};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

pub const CHUNKER_ID: &str = "clm-cdc-v1";
pub const CHUNKER_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChunkDescriptor {
    pub index: usize,
    pub offset: usize,
    pub length: usize,
    pub qualified_ref: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChunkManifest {
    pub chunker_id: String,
    pub chunker_version: u32,
    pub min_size: usize,
    pub avg_size: usize,
    pub max_size: usize,
    pub total_bytes: usize,
    pub chunks: Vec<ChunkDescriptor>,
    pub algorithm: String,
}

impl ChunkManifest {
    pub fn to_canonical_bytes(&self) -> Vec<u8> {
        let chunks_json: Vec<serde_json::Value> = self
            .chunks
            .iter()
            .map(|c| {
                serde_json::json!({
                    "index": c.index,
                    "length": c.length,
                    "offset": c.offset,
                    "qualified_ref": c.qualified_ref,
                })
            })
            .collect();
        let doc = serde_json::json!({
            "algorithm": self.algorithm,
            "avg_size": self.avg_size,
            "chunker_id": self.chunker_id,
            "chunker_version": self.chunker_version,
            "chunks": chunks_json,
            "max_size": self.max_size,
            "min_size": self.min_size,
            "schema": "clm://layer2/chunk_manifest/v1",
            "total_bytes": self.total_bytes,
        });
        crate::domain::to_canonical_json_bytes(&doc)
    }

    pub fn to_mcard_record(&self) -> Result<MCardRecord, String> {
        MCardRecord::create(&self.to_canonical_bytes(), Some(&self.algorithm))
    }

    pub fn qualified_ref(&self) -> Result<String, String> {
        let rec = self.to_mcard_record()?;
        Ok(format!("{}:{}", self.algorithm, rec.hash))
    }
}

/// Deterministic cross-runtime CDC splitter (`clm-cdc-v1`, `INV-513-03`).
pub fn cdc_split_boundaries(
    data: &[u8],
    min_size: usize,
    avg_size: usize,
    max_size: usize,
) -> Vec<(usize, usize)> {
    let n = data.len();
    if n == 0 {
        return Vec::new();
    }
    let modulus = (avg_size.saturating_sub(min_size)).max(1) as u32;
    let mut slices = Vec::new();
    let mut chunk_start = 0usize;

    while chunk_start < n {
        let remaining = n - chunk_start;
        if remaining <= min_size {
            slices.push((chunk_start, remaining));
            break;
        }
        let limit = (chunk_start + max_size).min(n);
        let mut h: u32 = 0;
        let mut pos = chunk_start;
        while pos < limit {
            h = h.wrapping_mul(31).wrapping_add(data[pos] as u32);
            let span = pos - chunk_start + 1;
            if span >= min_size && (h.is_multiple_of(modulus) || (pos + 1) == limit) {
                slices.push((chunk_start, span));
                chunk_start = pos + 1;
                break;
            }
            pos += 1;
        }
    }
    slices
}

pub struct ChunkerProcessPCard {
    pub min_size: usize,
    pub avg_size: usize,
    pub max_size: usize,
    pub algorithm: String,
}

impl Default for ChunkerProcessPCard {
    fn default() -> Self {
        Self {
            min_size: 64,
            avg_size: 256,
            max_size: 1024,
            algorithm: "blake3".to_string(),
        }
    }
}

impl ChunkerProcessPCard {
    pub fn chunk_bytes(
        &self,
        data: &[u8],
    ) -> Result<(ChunkManifest, BTreeMap<String, MCardRecord>), String> {
        let mut store = BTreeMap::new();
        let boundaries = cdc_split_boundaries(data, self.min_size, self.avg_size, self.max_size);
        let mut chunks = Vec::with_capacity(boundaries.len());

        for (idx, (offset, length)) in boundaries.into_iter().enumerate() {
            let slice = &data[offset..offset + length];
            let rec = MCardRecord::create(slice, Some(&self.algorithm))?;
            let qref = format!("{}:{}", self.algorithm, rec.hash);
            store.insert(qref.clone(), rec);
            chunks.push(ChunkDescriptor {
                index: idx,
                offset,
                length,
                qualified_ref: qref,
            });
        }

        let manifest = ChunkManifest {
            chunker_id: CHUNKER_ID.to_string(),
            chunker_version: CHUNKER_VERSION,
            min_size: self.min_size,
            avg_size: self.avg_size,
            max_size: self.max_size,
            total_bytes: data.len(),
            chunks,
            algorithm: self.algorithm.clone(),
        };
        let m_rec = manifest.to_mcard_record()?;
        store.insert(format!("{}:{}", self.algorithm, m_rec.hash), m_rec);
        Ok((manifest, store))
    }
}

#[derive(Debug, Clone)]
pub struct StreamRangeResult {
    pub committed: bool,
    pub trapped_to_exception: bool,
    pub data: Vec<u8>,
    pub peak_buffer_bytes: usize,
    pub offending_ref: Option<String>,
    pub exception_token: Option<TokenMCard>,
}

pub struct StreamRangeProcessPCard {
    pub max_buffer_bytes: usize,
}

impl Default for StreamRangeProcessPCard {
    fn default() -> Self {
        Self {
            max_buffer_bytes: 262_144,
        }
    }
}

impl StreamRangeProcessPCard {
    pub fn read_range(
        &self,
        manifest: &ChunkManifest,
        store: &BTreeMap<String, MCardRecord>,
        start: usize,
        end: Option<usize>,
    ) -> StreamRangeResult {
        let target_end = end.unwrap_or(manifest.total_bytes).min(manifest.total_bytes);
        if start >= target_end || start >= manifest.total_bytes {
            return StreamRangeResult {
                committed: true,
                trapped_to_exception: false,
                data: Vec::new(),
                peak_buffer_bytes: 0,
                offending_ref: None,
                exception_token: None,
            };
        }

        let mut out = Vec::new();
        let mut peak_buf = 0usize;

        for desc in &manifest.chunks {
            let c_start = desc.offset;
            let c_end = desc.offset + desc.length;
            if c_end <= start || c_start >= target_end {
                continue;
            }
            let Some(rec) = store.get(&desc.qualified_ref) else {
                let exc_val = serde_json::json!({
                    "kind": "chunk_missing_exception",
                    "offending_ref": desc.qualified_ref,
                });
                let exc_tok = TokenMCard::from_json(
                    &exc_val,
                    "clm://type/storage/chunk_exception",
                    None,
                )
                .ok();
                return StreamRangeResult {
                    committed: false,
                    trapped_to_exception: true,
                    data: Vec::new(),
                    peak_buffer_bytes: peak_buf,
                    offending_ref: Some(desc.qualified_ref.clone()),
                    exception_token: exc_tok,
                };
            };

            let (algo, expected_hex) = desc
                .qualified_ref
                .split_once(':')
                .unwrap_or(("blake3", &desc.qualified_ref));
            let rec_ok = matches!(verify_record(rec), RecordVerification::DeclaredOk { .. });
            let digest_ok = crate::hash::raw_hash_bytes_for(algo, &rec.content)
                .map(|d| d.eq_ignore_ascii_case(expected_hex))
                .unwrap_or(false);

            if !rec_ok || !digest_ok {
                let exc_val = serde_json::json!({
                    "kind": "chunk_corrupt_exception",
                    "offending_ref": desc.qualified_ref,
                });
                let exc_tok = TokenMCard::from_json(
                    &exc_val,
                    "clm://type/storage/chunk_exception",
                    None,
                )
                .ok();
                return StreamRangeResult {
                    committed: false,
                    trapped_to_exception: true,
                    data: Vec::new(),
                    peak_buffer_bytes: peak_buf,
                    offending_ref: Some(desc.qualified_ref.clone()),
                    exception_token: exc_tok,
                };
            }

            peak_buf = peak_buf.max(rec.content.len());
            let rel_start = start.saturating_sub(c_start);
            let rel_end = (target_end - c_start).min(desc.length);
            out.extend_from_slice(&rec.content[rel_start..rel_end]);
        }

        StreamRangeResult {
            committed: true,
            trapped_to_exception: false,
            data: out,
            peak_buffer_bytes: peak_buf,
            offending_ref: None,
            exception_token: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruningReachabilityReport {
    pub reachable_refs: Vec<String>,
    pub candidate_refs: Vec<String>,
}

pub fn compute_reachability(
    all_object_refs: &BTreeSet<String>,
    handle_heads: &BTreeSet<String>,
    pinned_refs: &BTreeSet<String>,
    active_markings: &[MCardMarking],
    manifest_children: &BTreeMap<String, Vec<String>>,
) -> PruningReachabilityReport {
    let mut roots: BTreeSet<String> = handle_heads.union(pinned_refs).cloned().collect();
    for marking in active_markings {
        for refs in marking.by_place.values() {
            for qref in refs {
                roots.insert(qref.clone());
            }
        }
    }

    let mut reachable = BTreeSet::new();
    let mut stack: Vec<String> = roots.into_iter().collect();
    while let Some(cur) = stack.pop() {
        if reachable.contains(&cur) || !all_object_refs.contains(&cur) {
            continue;
        }
        reachable.insert(cur.clone());
        if let Some(children) = manifest_children.get(&cur) {
            for child in children {
                if !reachable.contains(child) {
                    stack.push(child.clone());
                }
            }
        }
    }

    let candidates: Vec<String> = all_object_refs.difference(&reachable).cloned().collect();
    PruningReachabilityReport {
        reachable_refs: reachable.into_iter().collect(),
        candidate_refs: candidates,
    }
}

#[derive(Debug, Clone)]
pub struct PruningAnchorResult {
    pub committed: bool,
    pub trapped_to_exception: bool,
    pub anchor_mcard: TokenMCard,
    pub archived_refs: Vec<String>,
    pub remaining_working_refs: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct AnchoredPruningProcessPCard;

impl AnchoredPruningProcessPCard {
    pub fn new() -> Self {
        Self
    }

    pub fn compute_reachability(
        &self,
        all_object_refs: &BTreeSet<String>,
        handle_heads: &BTreeSet<String>,
        pinned_refs: &BTreeSet<String>,
        active_markings: &[MCardMarking],
        manifest_children: &BTreeMap<String, Vec<String>>,
    ) -> PruningReachabilityReport {
        compute_reachability(
            all_object_refs,
            handle_heads,
            pinned_refs,
            active_markings,
            manifest_children,
        )
    }

    pub fn execute_anchored_prune(
        &self,
        working_store: &mut BTreeMap<String, MCardRecord>,
        report: &PruningReachabilityReport,
        sponsor_did: Option<&str>,
        archive_uri: Option<&str>,
        archive_store: Option<&mut BTreeMap<String, MCardRecord>>,
    ) -> PruningAnchorResult {
        let Some(did) = sponsor_did else {
            let exc_val = serde_json::json!({
                "error": "missing_operator_authorization",
                "kind": "pruning_exception"
            });
            let exc = TokenMCard::from_json(&exc_val, "clm://type/storage/pruning_exception", None)
                .expect("valid exception token");
            return PruningAnchorResult {
                committed: false,
                trapped_to_exception: true,
                anchor_mcard: exc,
                archived_refs: Vec::new(),
                remaining_working_refs: working_store.keys().cloned().collect(),
            };
        };

        if !did.starts_with("did:key:") && !did.starts_with("did:clm:") {
            let exc_val = serde_json::json!({
                "error": "missing_operator_authorization",
                "kind": "pruning_exception"
            });
            let exc = TokenMCard::from_json(&exc_val, "clm://type/storage/pruning_exception", None)
                .expect("valid exception token");
            return PruningAnchorResult {
                committed: false,
                trapped_to_exception: true,
                anchor_mcard: exc,
                archived_refs: Vec::new(),
                remaining_working_refs: working_store.keys().cloned().collect(),
            };
        }

        let Some(uri) = archive_uri else {
            let exc_val = serde_json::json!({
                "error": "missing_or_invalid_archive_uri",
                "kind": "pruning_exception"
            });
            let exc = TokenMCard::from_json(&exc_val, "clm://type/storage/pruning_exception", None)
                .expect("valid exception token");
            return PruningAnchorResult {
                committed: false,
                trapped_to_exception: true,
                anchor_mcard: exc,
                archived_refs: Vec::new(),
                remaining_working_refs: working_store.keys().cloned().collect(),
            };
        };

        if !uri.starts_with("mcard://archive/") {
            let exc_val = serde_json::json!({
                "error": "missing_or_invalid_archive_uri",
                "kind": "pruning_exception"
            });
            let exc = TokenMCard::from_json(&exc_val, "clm://type/storage/pruning_exception", None)
                .expect("valid exception token");
            return PruningAnchorResult {
                committed: false,
                trapped_to_exception: true,
                anchor_mcard: exc,
                archived_refs: Vec::new(),
                remaining_working_refs: working_store.keys().cloned().collect(),
            };
        }

        let mut archived = Vec::new();
        let mut target_archive = archive_store;
        for cref in &report.candidate_refs {
            if let Some(rec) = working_store.get(cref) {
                if let Some(ref mut arc) = target_archive {
                    arc.insert(cref.clone(), rec.clone());
                }
                archived.push(cref.clone());
            }
        }

        let anchor_payload = serde_json::json!({
            "archive_uri": uri,
            "archived_refs": archived,
            "reachable_refs": report.reachable_refs,
            "schema": "clm://layer2/pruning_anchor/v1",
            "sponsor_did": did,
        });

        let anchor_tok = TokenMCard::from_json(
            &anchor_payload,
            "clm://type/storage/pruning_anchor",
            None,
        ).expect("valid pruning anchor token");

        for cref in &archived {
            working_store.remove(cref);
        }
        working_store.insert(anchor_tok.qualified_hash(), anchor_tok.card.clone());

        PruningAnchorResult {
            committed: true,
            trapped_to_exception: false,
            anchor_mcard: anchor_tok,
            archived_refs: archived,
            remaining_working_refs: working_store.keys().cloned().collect(),
        }
    }
}