Skip to main content

qualia_client_core/
qapp_api.rs

1//! Zero-allocation scoped query execution boundary for Flutter qapps.
2//!
3//! Hot-path functions use stack/fixed buffers only. Heap allocation is confined
4//! to the FRB wrapper that copies geometry into a Dart `Float32List`.
5
6use qualia_core_db::{
7    daemon_graph, mini_parser, q_hash, wal::WriteAheadLog, webizen_bytecode, NQuin,
8};
9
10use crate::qapp_manifest::{get_compiled_capability, CompiledCapability};
11
12/// Maximum Quin results per scoped query (42MB Sentinel budget).
13pub const MAX_QUERY_RESULTS: usize = 2048;
14/// Float32 values emitted per matched Quin (six u64 lanes, no inline float tagging).
15pub const FLOATS_PER_QUIN: usize = 6;
16pub const SCOPED_QUERY_MAX_FLOATS: usize = MAX_QUERY_RESULTS * FLOATS_PER_QUIN;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ExecutionError {
20    UnregisteredApp,
21    SanctuaryOverrideRequired,
22    OutputBufferFull,
23    InvalidBytecode,
24    ClearanceViolation,
25}
26
27impl ExecutionError {
28    /// `str` form.
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::UnregisteredApp => "unregistered_app",
32            Self::SanctuaryOverrideRequired => "sanctuary_override_required",
33            Self::OutputBufferFull => "output_buffer_full",
34            Self::InvalidBytecode => "invalid_bytecode",
35            Self::ClearanceViolation => "clearance_violation",
36        }
37    }
38}
39
40/// Walk compiled bytecode and ensure bound operands stay inside declared ontology domains.
41pub fn verify_execution_scope(
42    caps: &CompiledCapability,
43    query_bytecode: &[u8],
44) -> Result<(), ExecutionError> {
45    let mut i = 0usize;
46    while i < query_bytecode.len() {
47        let opcode = query_bytecode[i];
48        match opcode {
49            mini_parser::OP_MATCH_SUBJECT
50            | mini_parser::OP_MATCH_PREDICATE
51            | mini_parser::OP_MATCH_OBJECT => {
52                if i + 9 > query_bytecode.len() {
53                    return Err(ExecutionError::InvalidBytecode);
54                }
55                let mut bytes = [0u8; 8];
56                bytes.copy_from_slice(&query_bytecode[i + 1..i + 9]);
57                let operand = u64::from_le_bytes(bytes);
58                if operand != 0 && !domain_permitted(caps, operand) {
59                    return Err(ExecutionError::SanctuaryOverrideRequired);
60                }
61                i += 9;
62            }
63            mini_parser::OP_HALT_IF_FALSE => i += 1,
64            mini_parser::OP_END => break,
65            _ => return Err(ExecutionError::InvalidBytecode),
66        }
67    }
68    Ok(())
69}
70
71#[inline]
72fn domain_permitted(caps: &CompiledCapability, hash: u64) -> bool {
73    if hash == caps.app_id_hash {
74        return true;
75    }
76    let count = caps.domain_count as usize;
77    for slot in caps.permitted_domains.iter().take(count) {
78        if *slot == hash {
79            return true;
80        }
81    }
82    false
83}
84
85fn wal_path() -> Option<String> {
86    let state = crate::state::APP_STATE.get()?;
87    let storage = state.config.lock().ok()?.storage_path.clone();
88    Some(format!("{storage}/qualia_global.wal"))
89}
90
91/// Append a conduct-violation Quin when a qapp breaches its compiled capability scope.
92pub fn append_sanctuary_violation(app_id_hash: u64, reason: &'static str) {
93    let mut quin = NQuin::new_conduct_violation(reason.as_bytes());
94    quin.subject = app_id_hash;
95    quin.predicate = q_hash("q42:conductViolation");
96    quin.context = q_hash("q42:qappSanctuaryOverride");
97    quin.parity = quin.subject ^ quin.predicate ^ quin.object ^ quin.context;
98
99    if let Some(path) = wal_path() {
100        if let Ok(mut wal) = WriteAheadLog::open(path) {
101            let _ = wal.append_mutation(&quin);
102        }
103    }
104}
105
106/// Map matched Quins into a flat `f32` lane for Dart `Float32List` rendering.
107/// Uses `f32::from_bits` on the low 32 bits — no scalar tagging in Quin objects.
108pub fn translate_quin_to_geometry(quin: &NQuin, out: &mut [f32], base: usize) -> usize {
109    if base + FLOATS_PER_QUIN > out.len() {
110        return 0;
111    }
112    out[base] = f32::from_bits(quin.subject as u32);
113    out[base + 1] = f32::from_bits(quin.predicate as u32);
114    out[base + 2] = f32::from_bits(quin.object as u32);
115    out[base + 3] = f32::from_bits(quin.context as u32);
116    out[base + 4] = f32::from_bits(quin.metadata as u32);
117    out[base + 5] = f32::from_bits(quin.parity as u32);
118    FLOATS_PER_QUIN
119}
120
121#[inline]
122fn result_passes_clearance(quin: &NQuin, clearance: u8) -> bool {
123    quin.get_sensitivity_byte() <= clearance
124}
125
126/// Hot-path scoped query — **must not allocate heap memory**.
127pub fn execute_scoped_query_in_place(
128    app_id_hash: u64,
129    query_bytecode: &[u8],
130    geometry_out: &mut [f32],
131) -> Result<usize, ExecutionError> {
132    let caps = get_compiled_capability(app_id_hash).ok_or(ExecutionError::UnregisteredApp)?;
133
134    if let Err(err @ ExecutionError::SanctuaryOverrideRequired) =
135        verify_execution_scope(&caps, query_bytecode)
136    {
137        append_sanctuary_violation(app_id_hash, err.as_str());
138        return Err(err);
139    }
140
141    let graph_guard = daemon_graph::graph_read_guard();
142    let db = graph_guard.as_slice();
143
144    let mut result_buffer = [NQuin::default(); MAX_QUERY_RESULTS];
145    let (match_count, _vm_cycles) =
146        webizen_bytecode::execute_program(query_bytecode, db, &mut result_buffer, None).map_err(
147            |e| match e {
148                webizen_bytecode::VmError::OutputBufferFull => ExecutionError::OutputBufferFull,
149                webizen_bytecode::VmError::InvalidProgram => ExecutionError::InvalidBytecode,
150                webizen_bytecode::VmError::HaltViolation => ExecutionError::InvalidBytecode,
151            },
152        )?;
153
154    let mut float_offset = 0usize;
155    for quin in &result_buffer[..match_count] {
156        if !result_passes_clearance(quin, caps.clearance_level) {
157            append_sanctuary_violation(app_id_hash, ExecutionError::ClearanceViolation.as_str());
158            return Err(ExecutionError::ClearanceViolation);
159        }
160        let written = translate_quin_to_geometry(quin, geometry_out, float_offset);
161        if written == 0 {
162            return Err(ExecutionError::OutputBufferFull);
163        }
164        float_offset += written;
165    }
166
167    Ok(float_offset)
168}
169
170/// FRB/diagnostic wrapper — may allocate when copying geometry for Dart.
171pub fn execute_scoped_query(
172    app_id_hash: u64,
173    query_bytecode: Vec<u8>,
174) -> Result<Vec<f32>, ExecutionError> {
175    let mut scratch = [0f32; SCOPED_QUERY_MAX_FLOATS];
176    let len = execute_scoped_query_in_place(app_id_hash, &query_bytecode, &mut scratch)?;
177    Ok(scratch[..len].to_vec())
178}
179
180/// Compile a wildcard anatomy graph query into fixed bytecode (install/boot helper).
181pub fn compile_wildcard_graph_query(program: &mut [u8; 1024]) -> Result<usize, ExecutionError> {
182    mini_parser::compile_ntriples_to_bytecode(b"?subject ?predicate ?object .", program)
183        .map_err(|_| ExecutionError::InvalidBytecode)
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use crate::qapp_manifest::{
190        compile_and_register_qapp, CapabilityClaims, HostMetadata, QappManifest,
191    };
192    use qualia_core_db::daemon_graph;
193
194    fn register_anatomy_app() -> u64 {
195        let manifest = QappManifest {
196            app_id: "did:qualia:qapp:anatomy".to_string(),
197            host_metadata: HostMetadata::default(),
198            capability_claims: CapabilityClaims {
199                required_ontologies: vec![
200                    "q42:anatomy".to_string(),
201                    "https://qualia.anatomy.example/ontology/bio#".to_string(),
202                ],
203                optional_remote_endpoints: vec![],
204                max_sensitivity_clearance: "0x00".to_string(),
205                required_pinn_models: vec![],
206                supports_ternary_quantization: false,
207            },
208        };
209        compile_and_register_qapp(manifest).unwrap()
210    }
211
212    #[test]
213    fn rejects_forbidden_domain_operands() {
214        let app_id_hash = register_anatomy_app();
215        let caps = get_compiled_capability(app_id_hash).unwrap();
216
217        let mut prog = [0u8; 64];
218        prog[0] = mini_parser::OP_MATCH_SUBJECT;
219        let forbidden = q_hash("q42:financial");
220        prog[1..9].copy_from_slice(&forbidden.to_le_bytes());
221        prog[9] = mini_parser::OP_END;
222
223        assert_eq!(
224            verify_execution_scope(&caps, &prog[..10]),
225            Err(ExecutionError::SanctuaryOverrideRequired)
226        );
227    }
228
229    #[test]
230    fn zero_allocation_scoped_query_hot_path() {
231        daemon_graph::init_daemon_graph("/tmp/qualia-qapp-test");
232        let app_id_hash = register_anatomy_app();
233
234        let mut prog = [0u8; 1024];
235        let prog_len =
236            mini_parser::compile_ntriples_to_bytecode(b"?subject ?predicate ?object .", &mut prog)
237                .unwrap();
238
239        let _profiler = dhat::Profiler::builder().testing().build();
240        let mut out = [0f32; 512];
241        let result = execute_scoped_query_in_place(app_id_hash, &prog[..prog_len], &mut out);
242        assert!(result.is_ok());
243        assert!(result.unwrap() > 0);
244
245        let stats = dhat::HeapStats::get();
246        assert_eq!(
247            stats.curr_blocks, 0,
248            "execute_scoped_query_in_place must not allocate on the heap"
249        );
250        assert_eq!(stats.curr_bytes, 0);
251    }
252}
253
254// ── DICOM split-ingest (Core 3) + volume query (FRB boundary) ─────────────────
255
256fn storage_root() -> Result<std::path::PathBuf, String> {
257    let state = crate::state::APP_STATE
258        .get()
259        .ok_or("APP_STATE not initialized")?;
260    Ok(std::path::PathBuf::from(
261        state
262            .config
263            .lock()
264            .map_err(|e| e.to_string())?
265            .storage_path
266            .clone(),
267    ))
268}
269
270/// Submit `.dcm` split-ingest to Core 3; returns lock-free job id.
271pub fn submit_dicom_ingest(file_path: String, patient_did_hash: u64) -> Result<u64, String> {
272    let root = storage_root()?;
273    qualia_core_db::dicom_ingest::init_core3_dicom_worker(root.clone());
274    qualia_core_db::dicom_ingest::submit_dicom_ingest(
275        &root,
276        std::path::Path::new(&file_path),
277        patient_did_hash,
278    )
279    .map_err(|e| e.to_string())
280}
281
282/// Poll Core 3 ingest status: 0=pending, 1=complete, 2=failed.
283pub fn dicom_ingest_status(job_id: u64) -> u8 {
284    qualia_core_db::dicom_ingest::dicom_ingest_status(job_id)
285}
286
287/// Memory-map read of ingested pixel payload (single copy for Dart `Uint8List`).
288pub fn execute_dicom_volume_query(
289    patient_did_hash: u64,
290    series_hash: u64,
291) -> Result<Vec<u8>, String> {
292    let root = storage_root()?;
293    let record = qualia_core_db::dicom_ingest::find_series_record(patient_did_hash, series_hash)
294        .ok_or_else(|| "DICOM series not found in ingest registry".to_string())?;
295    qualia_core_db::dicom_ingest::read_volume_bytes(&root, &record).map_err(|e| e.to_string())
296}
297
298/// Comorbidity verdicts using the in-process daemon graph (FRB-friendly).
299pub fn eval_comorbidity_json_from_daemon(
300    patient_did_hash: u64,
301    target_organ_hash: u64,
302) -> Result<String, String> {
303    let graph_guard = qualia_core_db::daemon_graph::graph_read_guard();
304    eval_comorbidity_json(patient_did_hash, target_organ_hash, graph_guard.as_slice())
305}
306
307/// Hot-path comorbidity evaluation — stack buffers only inside engine call.
308pub fn eval_comorbidity_json(
309    patient_did_hash: u64,
310    target_organ_hash: u64,
311    graph_quins: &[qualia_core_db::NQuin],
312) -> Result<String, String> {
313    use qualia_core_db::comorbidity_eval::{
314        eval_comorbidity, ComorbidityVerdict, MAX_COMORBIDITY_VERDICTS,
315    };
316
317    let mut out = [ComorbidityVerdict {
318        condition_hash: 0,
319        compounded_risk_milli: 0,
320        status: qualia_core_db::comorbidity_eval::ComorbidityStatus::Active,
321        _pad: [0; 3],
322    }; MAX_COMORBIDITY_VERDICTS];
323
324    let count = eval_comorbidity(patient_did_hash, target_organ_hash, graph_quins, &mut out)
325        .map_err(|e| format!("{e:?}"))?;
326
327    let verdicts: Vec<serde_json::Value> = out[..count]
328        .iter()
329        .map(|v| {
330            serde_json::json!({
331                "conditionHash": format!("{:#018x}", v.condition_hash),
332                "compoundedRiskMilli": v.compounded_risk_milli,
333                "status": v.status as u8,
334            })
335        })
336        .collect();
337
338    serde_json::to_string(&serde_json::json!({ "verdicts": verdicts })).map_err(|e| e.to_string())
339}