Skip to main content

qualia_client_core/api/
superblock.rs

1//! SuperBlock artifacts and views over unified v3 `.q42` volumes.
2
3#![allow(non_snake_case)]
4
5use serde::Serialize;
6use std::fs;
7use std::io::Read;
8use std::path::{Path, PathBuf};
9
10use qualia_core_db::q42_reader::read_c_q42_quins;
11use qualia_core_db::q42_volume::{
12    decode_superblock_quins, is_unified_volume, Q42Volume, SUPERBLOCK_SIZE,
13};
14
15#[derive(Debug, Clone, Serialize)]
16pub struct SuperBlockArtifact {
17    pub path: String,
18    pub display_name: String,
19    pub byte_size: u64,
20    pub block_count: u64,
21}
22
23#[derive(Debug, Clone, Serialize)]
24pub struct SuperBlockView {
25    pub source_path: String,
26    pub block_index: u64,
27    pub total_blocks: u64,
28    pub block_sequence_id: u64,
29    pub storage_owner_did: u64,
30    pub active_quin_count: u64,
31    pub validation_checksum: u32,
32    pub hardware_profile_flags: u32,
33    pub fea_mesh_index_id: u64,
34    pub raw_bytes: Vec<u8>,
35    pub quins: Vec<[u64; 6]>,
36}
37
38fn decode_u64(bytes: &[u8], start: usize) -> Result<u64, String> {
39    let end = start + 8;
40    let slice = bytes
41        .get(start..end)
42        .ok_or_else(|| format!("SuperBlock truncated at byte range {start}..{end}"))?;
43    let mut buf = [0u8; 8];
44    buf.copy_from_slice(slice);
45    Ok(u64::from_le_bytes(buf))
46}
47
48fn decode_u32(bytes: &[u8], start: usize) -> Result<u32, String> {
49    let end = start + 4;
50    let slice = bytes
51        .get(start..end)
52        .ok_or_else(|| format!("SuperBlock truncated at byte range {start}..{end}"))?;
53    let mut buf = [0u8; 4];
54    buf.copy_from_slice(slice);
55    Ok(u32::from_le_bytes(buf))
56}
57
58fn scan_q42_artifacts(root: &Path, out: &mut Vec<SuperBlockArtifact>) -> Result<(), String> {
59    if !root.is_dir() {
60        return Ok(());
61    }
62    for entry in fs::read_dir(root).map_err(|e| e.to_string())? {
63        let entry = entry.map_err(|e| e.to_string())?;
64        let path = entry.path();
65        if path.is_dir() {
66            scan_q42_artifacts(&path, out)?;
67            continue;
68        }
69        if path.extension().and_then(|v| v.to_str()) != Some("q42") {
70            continue;
71        }
72        let Some(name) = path.file_name().and_then(|v| v.to_str()) else {
73            continue;
74        };
75        if name.ends_with(".c.q42") {
76            continue;
77        }
78        let meta = entry.metadata().map_err(|e| e.to_string())?;
79        let block_count = artifact_block_count(&path, meta.len())?;
80        if block_count == 0 && meta.len() < SUPERBLOCK_SIZE as u64 {
81            // Empty roots still list; tiny non-volumes are skipped.
82            if is_unified_volume(&path).ok() != Some(true) {
83                continue;
84            }
85        }
86        out.push(SuperBlockArtifact {
87            path: path.to_string_lossy().into_owned(),
88            display_name: name.to_string(),
89            byte_size: meta.len(),
90            block_count,
91        });
92    }
93    Ok(())
94}
95
96fn artifact_block_count(path: &Path, byte_len: u64) -> Result<u64, String> {
97    if is_unified_volume(path).ok() == Some(true) {
98        let volume = Q42Volume::open(path).map_err(|e| e.to_string())?;
99        return Ok(volume.block_count());
100    }
101    if byte_len >= SUPERBLOCK_SIZE as u64 && byte_len % SUPERBLOCK_SIZE as u64 == 0 {
102        return Ok(byte_len / SUPERBLOCK_SIZE as u64);
103    }
104    if byte_len >= 16 {
105        return Ok(1);
106    }
107    Ok(0)
108}
109
110/// Lists superblock artifacts.
111pub fn list_superblock_artifacts() -> Result<Vec<SuperBlockArtifact>, String> {
112    let state = crate::state::APP_STATE.get().unwrap();
113    let storage = state.config.lock().unwrap().storage_path.clone();
114    let mut out = Vec::new();
115    scan_q42_artifacts(Path::new(&storage), &mut out)?;
116    out.sort_by(|a, b| {
117        a.display_name
118            .cmp(&b.display_name)
119            .then_with(|| a.path.cmp(&b.path))
120    });
121    Ok(out)
122}
123
124/// Gets superblock-view.
125pub fn get_superblock_view(
126    source_path: String,
127    block_index: u64,
128) -> Result<SuperBlockView, String> {
129    let path = PathBuf::from(&source_path);
130    if !path.is_file() {
131        return Err(format!("SuperBlock source not found: {}", path.display()));
132    }
133    if path.extension().and_then(|v| v.to_str()) != Some("q42") {
134        return Err("Block inspector expects a raw .q42 artifact".to_string());
135    }
136
137    if is_unified_volume(&path).ok() == Some(true) {
138        return view_unified_volume(&path, source_path, block_index);
139    }
140
141    let metadata = fs::metadata(&path).map_err(|e| e.to_string())?;
142    if metadata.len() >= SUPERBLOCK_SIZE as u64 && metadata.len() % SUPERBLOCK_SIZE as u64 == 0 {
143        return view_legacy_raw_pages(&path, source_path, block_index, metadata.len());
144    }
145
146    view_legacy_framed(&path, source_path, block_index)
147}
148
149fn view_unified_volume(
150    path: &Path,
151    source_path: String,
152    block_index: u64,
153) -> Result<SuperBlockView, String> {
154    let volume = Q42Volume::open(path).map_err(|e| e.to_string())?;
155    if volume
156        .volume_manifest()
157        .map_err(|e| e.to_string())?
158        .is_some()
159    {
160        return Err(
161            "This Q42 is a volume-set root (no local SuperBlocks). Open a data child segment."
162                .into(),
163        );
164    }
165    let total_blocks = volume.block_count();
166    if total_blocks == 0 {
167        return Err("Volume has no SuperBlocks".into());
168    }
169    if block_index >= total_blocks {
170        return Err(format!(
171            "Block index {block_index} is out of range for {total_blocks} blocks"
172        ));
173    }
174    let mut raw_bytes = vec![0u8; SUPERBLOCK_SIZE];
175    volume
176        .read_superblock_into(block_index as usize, &mut raw_bytes)
177        .map_err(|e| e.to_string())?;
178    view_from_decompressed(source_path, block_index, total_blocks, raw_bytes)
179}
180
181fn view_legacy_raw_pages(
182    path: &Path,
183    source_path: String,
184    block_index: u64,
185    file_len: u64,
186) -> Result<SuperBlockView, String> {
187    let total_blocks = file_len / SUPERBLOCK_SIZE as u64;
188    if block_index >= total_blocks {
189        return Err(format!(
190            "Block index {block_index} is out of range for {total_blocks} blocks"
191        ));
192    }
193    let mut file = fs::File::open(path).map_err(|e| e.to_string())?;
194    use std::io::Seek;
195    use std::io::SeekFrom;
196    file.seek(SeekFrom::Start(block_index * SUPERBLOCK_SIZE as u64))
197        .map_err(|e| e.to_string())?;
198    let mut raw_bytes = vec![0u8; SUPERBLOCK_SIZE];
199    file.read_exact(&mut raw_bytes).map_err(|e| e.to_string())?;
200    view_from_decompressed(source_path, block_index, total_blocks, raw_bytes)
201}
202
203fn view_legacy_framed(
204    path: &Path,
205    source_path: String,
206    block_index: u64,
207) -> Result<SuperBlockView, String> {
208    if block_index != 0 {
209        return Err("Legacy framed .q42 exposes a single logical block (index 0)".into());
210    }
211    let quins = read_c_q42_quins(path).map_err(|e| e.to_string())?;
212    if quins.is_empty() {
213        return Err("Legacy framed .q42 contained no Quins".into());
214    }
215    let packed: Vec<[u64; 6]> = quins
216        .iter()
217        .map(|q| {
218            [
219                q.subject,
220                q.predicate,
221                q.object,
222                q.context,
223                q.metadata,
224                q.parity,
225            ]
226        })
227        .collect();
228    Ok(SuperBlockView {
229        source_path,
230        block_index: 0,
231        total_blocks: 1,
232        block_sequence_id: 0,
233        storage_owner_did: 0,
234        active_quin_count: packed.len() as u64,
235        validation_checksum: 0,
236        hardware_profile_flags: 0,
237        fea_mesh_index_id: 0,
238        raw_bytes: Vec::new(),
239        quins: packed,
240    })
241}
242
243fn view_from_decompressed(
244    source_path: String,
245    block_index: u64,
246    total_blocks: u64,
247    raw_bytes: Vec<u8>,
248) -> Result<SuperBlockView, String> {
249    let block_sequence_id = decode_u64(&raw_bytes, 0)?;
250    let storage_owner_did = decode_u64(&raw_bytes, 8)?;
251    let decoded = decode_superblock_quins(&raw_bytes).map_err(|e| e.to_string())?;
252    let active_quin_count = decoded.len() as u64;
253    let validation_checksum = decode_u32(&raw_bytes, 24)?;
254    let hardware_profile_flags = decode_u32(&raw_bytes, 28)?;
255    let fea_mesh_index_id = decode_u64(&raw_bytes, 32)?;
256    let quins = decoded
257        .into_iter()
258        .map(|q| {
259            [
260                q.subject,
261                q.predicate,
262                q.object,
263                q.context,
264                q.metadata,
265                q.parity,
266            ]
267        })
268        .collect();
269    Ok(SuperBlockView {
270        source_path,
271        block_index,
272        total_blocks,
273        block_sequence_id,
274        storage_owner_did,
275        active_quin_count,
276        validation_checksum,
277        hardware_profile_flags,
278        fea_mesh_index_id,
279        raw_bytes,
280        quins,
281    })
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use qualia_core_db::q42_volume::write_sorted_quins_volume;
288    use qualia_core_db::NQuin;
289
290    fn sample_quin(object: u64) -> NQuin {
291        NQuin {
292            subject: 11,
293            predicate: 22,
294            object,
295            context: 33,
296            metadata: 0,
297            parity: NQuin::calculate_parity(11, 22, object, 33, 0),
298        }
299    }
300
301    #[test]
302    fn inspector_reads_unified_v3_block() {
303        let dir = tempfile::tempdir().unwrap();
304        let path = dir.path().join("body.q42");
305        write_sorted_quins_volume(&path, &[sample_quin(7), sample_quin(3)]).unwrap();
306        let view = get_superblock_view(path.to_string_lossy().into_owned(), 0).unwrap();
307        assert_eq!(view.total_blocks, 1);
308        assert_eq!(view.active_quin_count, 2);
309        assert_eq!(view.quins.len(), 2);
310        assert!(view.quins.iter().any(|q| q[2] == 3));
311        assert!(view.quins.iter().any(|q| q[2] == 7));
312    }
313}