somatize-core 0.5.1

Core types and traits for the Soma computational graph runtime
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
//! Virtual values — lazy references to data that can be materialized on demand.
//!
//! Instead of eagerly loading all intermediate results, [`VirtualValue`]
//! keeps references (Materialized, Cached, Deferred, Stream) and only
//! materializes when a filter actually needs the data.

use crate::cache::CacheKey;
use crate::schema::Schema;
use crate::value::Value;
use serde::{Deserialize, Serialize};
use std::fmt;

/// A lazy reference to a value that can be materialized on demand.
///
/// This is the core of Soma's data virtualization. Instead of computing
/// and storing every intermediate result, values are represented as
/// references that carry enough information to:
///
/// - Inspect schema without loading data
/// - Check whether the data is already available
/// - Compute it when needed
///
/// Like Denodo's data virtualization, but for computation rather than SQL.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum VirtualValue {
    /// Already computed and in memory. Ready to use.
    Materialized {
        /// The concrete value.
        value: Value,
        /// Its schema (inferred or declared).
        schema: Schema,
    },

    /// Stored in cache (K/V store). Can be loaded on demand.
    Cached {
        /// Key to load the value from the cache store.
        key: CacheKey,
        /// Schema, known without loading the data.
        schema: Schema,
    },

    /// Not computed yet. Carries the "recipe" to produce it:
    /// which node produces it, and what its cache key would be.
    Deferred {
        /// The node whose execution would produce this value.
        producer_node_id: String,
        /// Where the value will land once computed.
        cache_key: CacheKey,
        /// Expected schema of the eventual value.
        schema: Schema,
    },

    /// A stream that materializes chunk by chunk.
    Stream {
        /// Identifier of the stream source producing the chunks.
        source_id: String,
        /// Schema of each chunk.
        schema: Schema,
    },
}

/// Status of a VirtualValue without inspecting the actual data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueStatus {
    /// In memory, ready to use.
    InMemory,
    /// On disk/cache, needs loading.
    OnDisk,
    /// Not computed, needs execution.
    NotComputed,
    /// Streaming, partial data.
    Streaming,
}

impl VirtualValue {
    /// Create a materialized value with auto-inferred schema.
    pub fn materialized(value: Value) -> Self {
        let schema = Self::infer_schema(&value);
        Self::Materialized { value, schema }
    }

    /// Create a materialized value with explicit schema.
    pub fn materialized_with_schema(value: Value, schema: Schema) -> Self {
        Self::Materialized { value, schema }
    }

    /// Create a cached reference.
    pub fn cached(key: CacheKey, schema: Schema) -> Self {
        Self::Cached { key, schema }
    }

    /// Create a deferred (not yet computed) reference.
    pub fn deferred(
        producer_node_id: impl Into<String>,
        cache_key: CacheKey,
        schema: Schema,
    ) -> Self {
        Self::Deferred {
            producer_node_id: producer_node_id.into(),
            cache_key,
            schema,
        }
    }

    /// Get the schema without materializing the value.
    pub fn schema(&self) -> &Schema {
        match self {
            Self::Materialized { schema, .. }
            | Self::Cached { schema, .. }
            | Self::Deferred { schema, .. }
            | Self::Stream { schema, .. } => schema,
        }
    }

    /// Get the current status.
    pub fn status(&self) -> ValueStatus {
        match self {
            Self::Materialized { .. } => ValueStatus::InMemory,
            Self::Cached { .. } => ValueStatus::OnDisk,
            Self::Deferred { .. } => ValueStatus::NotComputed,
            Self::Stream { .. } => ValueStatus::Streaming,
        }
    }

    /// Get the materialized value if already in memory.
    pub fn as_value(&self) -> Option<&Value> {
        match self {
            Self::Materialized { value, .. } => Some(value),
            _ => None,
        }
    }

    /// Get the cache key (if this value is cached or deferred).
    pub fn cache_key(&self) -> Option<&CacheKey> {
        match self {
            Self::Cached { key, .. } | Self::Deferred { cache_key: key, .. } => Some(key),
            _ => None,
        }
    }

    /// Materialize from a cache store. Returns the value if found, None if not cached.
    pub fn try_load(
        &self,
        cache: &dyn crate::cache::CacheStore,
    ) -> crate::error::Result<Option<Value>> {
        match self {
            Self::Materialized { value, .. } => Ok(Some(value.clone())),
            Self::Cached { key, .. } => cache.get(key),
            Self::Deferred { cache_key, .. } => cache.get(cache_key),
            _ => Ok(None),
        }
    }

    /// Upgrade this reference: if Deferred, check cache; if Cached, load.
    /// Returns a new VirtualValue that may be closer to Materialized.
    pub fn resolve(&self, cache: &dyn crate::cache::CacheStore) -> crate::error::Result<Self> {
        match self {
            Self::Materialized { .. } => Ok(self.clone()),
            Self::Cached { key, schema } => {
                if let Some(value) = cache.get(key)? {
                    Ok(Self::Materialized {
                        value,
                        schema: schema.clone(),
                    })
                } else {
                    Ok(self.clone()) // still cached but value missing
                }
            }
            Self::Deferred {
                cache_key, schema, ..
            } => {
                if let Some(value) = cache.get(cache_key)? {
                    Ok(Self::Materialized {
                        value,
                        schema: schema.clone(),
                    })
                } else {
                    Ok(self.clone()) // still deferred
                }
            }
            _ => Ok(self.clone()),
        }
    }

    /// Infer schema from a concrete Value.
    fn infer_schema(value: &Value) -> Schema {
        match value {
            Value::Tensor { values: _, shape } => Schema {
                dtype: crate::schema::DataType::Float64,
                shape: Some(
                    shape
                        .iter()
                        .map(|&d| crate::schema::Dimension::Fixed(d))
                        .collect(),
                ),
            },
            Value::Text(_) => Schema::text(),
            Value::Json(_) => Schema::json(),
            Value::Bytes(_) | Value::Object(_) => Schema::bytes(),
            Value::Empty => Schema::dynamic(crate::schema::DataType::Float64),
        }
    }
}

impl fmt::Display for VirtualValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Materialized { schema, value } => {
                write!(f, "Materialized({schema}, size={})", value.size())
            }
            Self::Cached { key, schema } => {
                write!(f, "Cached({schema}, key={key})")
            }
            Self::Deferred {
                producer_node_id,
                schema,
                ..
            } => {
                write!(f, "Deferred({schema}, producer={producer_node_id})")
            }
            Self::Stream { source_id, schema } => {
                write!(f, "Stream({schema}, source={source_id})")
            }
        }
    }
}

impl From<Value> for VirtualValue {
    fn from(value: Value) -> Self {
        Self::materialized(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::CacheKey;
    use crate::schema::{DataType, Schema};

    #[test]
    fn materialized_from_value() {
        let val = Value::tensor(vec![1.0, 2.0, 3.0], vec![3]);
        let vv = VirtualValue::materialized(val.clone());

        assert_eq!(vv.status(), ValueStatus::InMemory);
        assert_eq!(vv.as_value(), Some(&val));
        assert_eq!(vv.schema().dtype, DataType::Float64);
        assert_eq!(vv.schema().rank(), Some(1));
    }

    #[test]
    fn cached_reference() {
        let key = CacheKey::hash_data(b"test");
        let schema = Schema::vector(DataType::Float64, 100);
        let vv = VirtualValue::cached(key.clone(), schema.clone());

        assert_eq!(vv.status(), ValueStatus::OnDisk);
        assert_eq!(vv.cache_key(), Some(&key));
        assert_eq!(vv.schema(), &schema);
        assert!(vv.as_value().is_none());
    }

    #[test]
    fn deferred_reference() {
        let key = CacheKey::hash_data(b"deferred");
        let schema = Schema::batched(DataType::Float64, &[128]);
        let vv = VirtualValue::deferred("my_node", key.clone(), schema.clone());

        assert_eq!(vv.status(), ValueStatus::NotComputed);
        assert_eq!(vv.cache_key(), Some(&key));
        assert_eq!(vv.schema(), &schema);
    }

    #[test]
    fn schema_inferred_from_tensor() {
        let val = Value::tensor(vec![0.0; 12], vec![3, 4]);
        let vv = VirtualValue::materialized(val);
        assert_eq!(vv.schema().dtype, DataType::Float64);
        assert_eq!(vv.schema().rank(), Some(2));
    }

    #[test]
    fn schema_inferred_from_json() {
        let val = Value::json(serde_json::json!({"a": 1}));
        let vv = VirtualValue::materialized(val);
        assert_eq!(vv.schema().dtype, DataType::Json);
    }

    #[test]
    fn display_formatting() {
        let vv = VirtualValue::materialized(Value::tensor(vec![1.0], vec![1]));
        assert!(vv.to_string().contains("Materialized"));

        let vv = VirtualValue::cached(CacheKey::hash_data(b"k"), Schema::json());
        assert!(vv.to_string().contains("Cached"));

        let vv = VirtualValue::deferred("node_1", CacheKey::hash_data(b"k"), Schema::json());
        assert!(vv.to_string().contains("Deferred"));
    }

    #[test]
    fn from_value_conversion() {
        let val = Value::tensor(vec![1.0, 2.0], vec![2]);
        let vv: VirtualValue = val.clone().into();
        assert_eq!(vv.status(), ValueStatus::InMemory);
        assert_eq!(vv.as_value(), Some(&val));
    }

    #[test]
    fn resolve_materialized_stays_materialized() {
        use crate::cache::CacheStore;

        // Simple mock cache
        struct EmptyCache;
        impl CacheStore for EmptyCache {
            fn get(&self, _: &CacheKey) -> crate::error::Result<Option<Value>> {
                Ok(None)
            }
            fn put(&self, _: &CacheKey, _: &Value) -> crate::error::Result<()> {
                Ok(())
            }
            fn exists(&self, _: &CacheKey) -> crate::error::Result<bool> {
                Ok(false)
            }
            fn remove(&self, _: &CacheKey) -> crate::error::Result<()> {
                Ok(())
            }
            fn metadata(
                &self,
                _: &CacheKey,
            ) -> crate::error::Result<Option<crate::cache::EntryMeta>> {
                Ok(None)
            }
        }

        let val = Value::tensor(vec![1.0], vec![1]);
        let vv = VirtualValue::materialized(val);
        let resolved = vv.resolve(&EmptyCache).unwrap();
        assert_eq!(resolved.status(), ValueStatus::InMemory);
    }

    #[test]
    fn resolve_deferred_checks_cache() {
        use crate::cache::{CacheStore, EntryMeta};
        use std::collections::HashMap;
        use std::sync::Mutex;

        struct TestCache {
            store: Mutex<HashMap<CacheKey, Value>>,
        }
        impl TestCache {
            fn with(key: CacheKey, value: Value) -> Self {
                let mut store = HashMap::new();
                store.insert(key, value);
                Self {
                    store: Mutex::new(store),
                }
            }
        }
        impl CacheStore for TestCache {
            fn get(&self, key: &CacheKey) -> crate::error::Result<Option<Value>> {
                Ok(self.store.lock().unwrap().get(key).cloned())
            }
            fn put(&self, _: &CacheKey, _: &Value) -> crate::error::Result<()> {
                Ok(())
            }
            fn exists(&self, key: &CacheKey) -> crate::error::Result<bool> {
                Ok(self.store.lock().unwrap().contains_key(key))
            }
            fn remove(&self, _: &CacheKey) -> crate::error::Result<()> {
                Ok(())
            }
            fn metadata(&self, _: &CacheKey) -> crate::error::Result<Option<EntryMeta>> {
                Ok(None)
            }
        }

        let key = CacheKey::hash_data(b"cached_value");
        let expected = Value::tensor(vec![42.0], vec![1]);
        let cache = TestCache::with(key.clone(), expected.clone());

        // Deferred → resolve → Materialized (if found in cache)
        let vv = VirtualValue::deferred("producer", key, Schema::vector(DataType::Float64, 1));
        assert_eq!(vv.status(), ValueStatus::NotComputed);

        let resolved = vv.resolve(&cache).unwrap();
        assert_eq!(resolved.status(), ValueStatus::InMemory);
        assert_eq!(resolved.as_value(), Some(&expected));
    }

    #[test]
    fn serde_roundtrip() {
        let values = vec![
            VirtualValue::materialized(Value::tensor(vec![1.0], vec![1])),
            VirtualValue::cached(CacheKey::hash_data(b"k"), Schema::json()),
            VirtualValue::deferred(
                "n",
                CacheKey::hash_data(b"d"),
                Schema::vector(DataType::Float64, 10),
            ),
        ];
        for vv in values {
            let json = serde_json::to_string(&vv).unwrap();
            let deserialized: VirtualValue = serde_json::from_str(&json).unwrap();
            assert_eq!(vv.status(), deserialized.status());
            assert_eq!(vv.schema(), deserialized.schema());
        }
    }
}