Skip to main content

gen_models/
sample_metadata.rs

1use gen_core::Sha256Hash;
2use rusqlite::{Row, params, types::Type};
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use thiserror::Error;
6
7use crate::{ModelSelect, db::GraphConnection};
8
9/// A typed sample metadata value.
10///
11/// Postcard persists enum variant indices. Preserve this order and append new variants.
12#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
13pub enum MetadataValue {
14    /// A text value.
15    Text(String),
16    /// A signed 64-bit integer.
17    Integer(i64),
18    /// A finite double-precision value.
19    Float(f64),
20    /// A boolean value.
21    Boolean(bool),
22}
23
24/// One metadata value associated with a sample and key.
25#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, ModelSelect)]
26#[model_select(
27    table = "sample_metadata",
28    select = "hash, sample_name, key, value",
29    from_row = SampleMetadata::from_row
30)]
31pub struct SampleMetadata {
32    /// Content hash including the sample, key, value type, and value.
33    #[model_select(primary_key)]
34    pub hash: Sha256Hash,
35    /// The sample's primary key in the samples table.
36    pub sample_name: String,
37    /// The metadata key, unique within the sample.
38    pub key: String,
39    /// Exactly one typed metadata value.
40    #[model_select(skip)]
41    pub value: MetadataValue,
42}
43
44/// Errors storing sample metadata.
45#[derive(Debug, Error, PartialEq)]
46pub enum SampleMetadataError {
47    /// The database rejected the operation.
48    #[error(transparent)]
49    Database(#[from] rusqlite::Error),
50    /// The metadata value could not be serialized.
51    #[error(transparent)]
52    Serialization(#[from] postcard::Error),
53    /// Metadata floats must remain valid in all supported export formats.
54    #[error("sample metadata float values must be finite")]
55    NonFiniteFloat,
56}
57
58impl SampleMetadata {
59    /// Store a new value; an existing key for this sample causes a uniqueness error.
60    pub fn create(
61        conn: &GraphConnection,
62        sample_name: &str,
63        key: &str,
64        value: &MetadataValue,
65    ) -> Result<Self, SampleMetadataError> {
66        Self::store(conn, sample_name, key, value, false)
67    }
68
69    /// Store a value, replacing the value and content hash for an existing sample key.
70    pub fn upsert(
71        conn: &GraphConnection,
72        sample_name: &str,
73        key: &str,
74        value: &MetadataValue,
75    ) -> Result<Self, SampleMetadataError> {
76        Self::store(conn, sample_name, key, value, true)
77    }
78
79    fn store(
80        conn: &GraphConnection,
81        sample_name: &str,
82        key: &str,
83        value: &MetadataValue,
84        replace: bool,
85    ) -> Result<Self, SampleMetadataError> {
86        let value = match value {
87            MetadataValue::Float(float) if !float.is_finite() => {
88                return Err(SampleMetadataError::NonFiniteFloat);
89            }
90            MetadataValue::Float(float) if *float == 0.0 => MetadataValue::Float(0.0),
91            value => value.clone(),
92        };
93        let encoded_value = postcard::to_stdvec(&value)?;
94
95        // Length prefixes and a type tag keep field boundaries and numeric types distinct.
96        let mut hasher = Sha256::new();
97        for field in [sample_name, key] {
98            hasher.update((field.len() as u64).to_be_bytes());
99            hasher.update(field.as_bytes());
100        }
101        match &value {
102            MetadataValue::Text(text) => {
103                hasher.update([0]);
104                hasher.update(text.as_bytes());
105            }
106            MetadataValue::Integer(integer) => {
107                hasher.update([1]);
108                hasher.update(integer.to_be_bytes());
109            }
110            MetadataValue::Float(float) => {
111                hasher.update([2]);
112                hasher.update(float.to_bits().to_be_bytes());
113            }
114            MetadataValue::Boolean(boolean) => {
115                hasher.update([3]);
116                hasher.update([u8::from(*boolean)]);
117            }
118        }
119        let hash = Sha256Hash(hasher.finalize().into());
120        let mut sql = String::from(
121            "INSERT INTO sample_metadata
122             (hash, sample_name, key, value)
123             VALUES (?1, ?2, ?3, ?4)",
124        );
125        if replace {
126            sql.push_str(
127                " ON CONFLICT(sample_name, key) DO UPDATE SET
128                  hash = excluded.hash, value = excluded.value",
129            );
130        }
131        conn.execute(&sql, params![hash, sample_name, key, encoded_value])?;
132        Ok(Self {
133            hash,
134            sample_name: sample_name.to_string(),
135            key: key.to_string(),
136            value,
137        })
138    }
139
140    fn from_row(row: &Row<'_>) -> rusqlite::Result<Self> {
141        let encoded_value: Vec<u8> = row.get(3)?;
142        let (value, remaining) = postcard::take_from_bytes::<MetadataValue>(&encoded_value)
143            .map_err(|error| {
144                rusqlite::Error::FromSqlConversionFailure(3, Type::Blob, Box::new(error))
145            })?;
146        if !remaining.is_empty() {
147            return Err(rusqlite::Error::InvalidQuery);
148        }
149        if matches!(&value, MetadataValue::Float(float) if !float.is_finite()) {
150            return Err(rusqlite::Error::FromSqlConversionFailure(
151                3,
152                Type::Blob,
153                Box::new(SampleMetadataError::NonFiniteFloat),
154            ));
155        }
156        Ok(Self {
157            hash: row.get(0)?,
158            sample_name: row.get(1)?,
159            key: row.get(2)?,
160            value,
161        })
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use rusqlite::params;
168
169    use crate::{
170        sample::{NewSample, Sample},
171        sample_metadata::{MetadataValue, SampleMetadata, SampleMetadataError},
172        test_helpers::get_connection,
173    };
174
175    #[test]
176    fn test_sample_metadata_upsert_replaces_type_and_hash() {
177        let conn = get_connection(None).expect("should open database");
178        Sample::create(
179            &conn,
180            NewSample {
181                name: "sample",
182                ..Default::default()
183            },
184        )
185        .expect("should create sample");
186        let original = SampleMetadata::upsert(
187            &conn,
188            "sample",
189            "Score",
190            &MetadataValue::Text("pending".to_string()),
191        )
192        .expect("should insert metadata");
193        let updated =
194            SampleMetadata::upsert(&conn, "sample", "Score", &MetadataValue::Float(90.68))
195                .expect("should update metadata");
196        assert_ne!(original.hash, updated.hash);
197        assert_eq!(
198            SampleMetadata::select(&conn)
199                .load()
200                .expect("should load metadata"),
201            vec![updated.clone()],
202        );
203        let repeated =
204            SampleMetadata::upsert(&conn, "sample", "Score", &MetadataValue::Float(90.68))
205                .expect("should repeat update");
206        assert_eq!(updated, repeated);
207    }
208
209    #[test]
210    fn test_sample_metadata_boolean_hash_and_type_changes() {
211        let conn = get_connection(None).expect("should open database");
212        Sample::create(
213            &conn,
214            NewSample {
215                name: "sample",
216                ..Default::default()
217            },
218        )
219        .expect("should create sample");
220        let mut hashes = Vec::new();
221        for value in [
222            MetadataValue::Integer(1),
223            MetadataValue::Boolean(true),
224            MetadataValue::Boolean(false),
225            MetadataValue::Text("false".to_string()),
226            MetadataValue::Float(0.0),
227        ] {
228            let metadata = SampleMetadata::upsert(&conn, "sample", "flag", &value)
229                .expect("should replace metadata type");
230            assert!(
231                !hashes.contains(&metadata.hash),
232                "typed values should have distinct hashes"
233            );
234            hashes.push(metadata.hash);
235            assert_eq!(
236                SampleMetadata::select(&conn)
237                    .load()
238                    .expect("should load metadata"),
239                vec![metadata]
240            );
241        }
242    }
243
244    #[test]
245    fn test_sample_metadata_round_trip_and_uniqueness() {
246        let conn = get_connection(None).expect("should open database");
247        Sample::create(
248            &conn,
249            NewSample {
250                name: "sample",
251                ..Default::default()
252            },
253        )
254        .expect("should create sample");
255        for (key, value) in [
256            ("text", MetadataValue::Text("1".to_string())),
257            ("integer", MetadataValue::Integer(i64::MAX)),
258            ("float", MetadataValue::Float(1.25)),
259            ("true", MetadataValue::Boolean(true)),
260            ("false", MetadataValue::Boolean(false)),
261        ] {
262            let metadata = SampleMetadata::create(&conn, "sample", key, &value)
263                .expect("should create metadata");
264            let loaded = SampleMetadata::select(&conn)
265                .sample_name("sample")
266                .key(key)
267                .load()
268                .expect("should load metadata");
269            assert_eq!(loaded, vec![metadata]);
270            assert!(
271                SampleMetadata::create(&conn, "sample", key, &MetadataValue::Integer(2)).is_err()
272            );
273        }
274        assert!(
275            SampleMetadata::create(&conn, "missing", "key", &MetadataValue::Integer(1)).is_err()
276        );
277        for float in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
278            assert!(matches!(
279                SampleMetadata::create(&conn, "sample", "invalid", &MetadataValue::Float(float)),
280                Err(SampleMetadataError::NonFiniteFloat)
281            ));
282        }
283    }
284
285    #[test]
286    fn test_sample_metadata_database_value_constraints() {
287        let conn = get_connection(None).expect("should open database");
288        Sample::create(
289            &conn,
290            NewSample {
291                name: "sample",
292                ..Default::default()
293            },
294        )
295        .expect("should create sample");
296        for value in ["NULL", "'invalid'", "1", "1.5"] {
297            let sql = format!(
298                "INSERT INTO sample_metadata (hash, sample_name, key, value)
299                 VALUES (?1, 'sample', 'key', {value})"
300            );
301            assert!(conn.execute(&sql, params![vec![0u8; 32]]).is_err());
302        }
303    }
304
305    #[test]
306    fn test_sample_metadata_rejects_invalid_encoded_values() {
307        let conn = get_connection(None).expect("should open database");
308        Sample::create(
309            &conn,
310            NewSample {
311                name: "sample",
312                ..Default::default()
313            },
314        )
315        .expect("should create sample");
316        let mut trailing_bytes =
317            postcard::to_stdvec(&MetadataValue::Boolean(true)).expect("should encode boolean");
318        trailing_bytes.push(0);
319        let mut invalid_values = vec![vec![], vec![255], vec![3, 2], trailing_bytes];
320        for float in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
321            invalid_values.push(
322                postcard::to_stdvec(&MetadataValue::Float(float))
323                    .expect("should encode non-finite float for corruption test"),
324            );
325        }
326        for encoded_value in invalid_values {
327            conn.execute(
328                "INSERT INTO sample_metadata (hash, sample_name, key, value)
329                 VALUES (?1, 'sample', 'key', ?2)",
330                params![vec![0u8; 32], encoded_value],
331            )
332            .expect("should insert corrupt metadata");
333            assert!(SampleMetadata::select(&conn).load().is_err());
334            conn.execute("DELETE FROM sample_metadata", [])
335                .expect("should remove corrupt metadata");
336        }
337    }
338
339    #[test]
340    fn test_sample_metadata_persisted_encoding() {
341        // These bytes define the stored format independently of Rust enum refactors.
342        for (value, encoded_value) in [
343            (MetadataValue::Text("x".to_string()), vec![0, 1, b'x']),
344            (MetadataValue::Integer(-1), vec![1, 1]),
345            (
346                MetadataValue::Float(1.0),
347                vec![2, 0, 0, 0, 0, 0, 0, 240, 63],
348            ),
349            (MetadataValue::Boolean(false), vec![3, 0]),
350            (MetadataValue::Boolean(true), vec![3, 1]),
351        ] {
352            assert_eq!(
353                postcard::to_stdvec(&value).expect("should encode value"),
354                encoded_value
355            );
356            assert_eq!(
357                postcard::from_bytes::<MetadataValue>(&encoded_value)
358                    .expect("should decode stored value"),
359                value
360            );
361        }
362    }
363
364    #[test]
365    fn test_sample_metadata_hash_encoding() {
366        let conn = get_connection(None).expect("should open database");
367        for name in ["a", "ab"] {
368            Sample::create(
369                &conn,
370                NewSample {
371                    name,
372                    ..Default::default()
373                },
374            )
375            .expect("should create sample");
376        }
377        let text = SampleMetadata::create(&conn, "a", "bc", &MetadataValue::Text("1".to_string()))
378            .expect("should create text");
379        SampleMetadata::select(&conn)
380            .delete_by_ids([text.hash])
381            .expect("should delete metadata");
382        let integer = SampleMetadata::create(&conn, "a", "bc", &MetadataValue::Integer(1))
383            .expect("should create integer");
384        SampleMetadata::select(&conn)
385            .delete_by_ids([integer.hash])
386            .expect("should delete metadata");
387        let float = SampleMetadata::create(&conn, "a", "bc", &MetadataValue::Float(1.0))
388            .expect("should create float");
389        assert_ne!(text.hash, integer.hash);
390        assert_ne!(integer.hash, float.hash);
391        let other = SampleMetadata::create(&conn, "ab", "c", &MetadataValue::Float(1.0))
392            .expect("should create metadata for sample 'ab' with key 'c'");
393        assert_ne!(
394            float.hash, other.hash,
395            "sample/key pairs ('a', 'bc') and ('ab', 'c') should hash differently even though both concatenate to 'abc'"
396        );
397        let zero = SampleMetadata::create(&conn, "a", "zero", &MetadataValue::Float(-0.0))
398            .expect("should create zero");
399        SampleMetadata::select(&conn)
400            .delete_by_ids([zero.hash])
401            .expect("should delete zero");
402        let positive_zero = SampleMetadata::create(&conn, "a", "zero", &MetadataValue::Float(0.0))
403            .expect("should recreate zero");
404        assert_eq!(zero.hash, positive_zero.hash);
405    }
406}