sochdb-core 2.0.8

SochDB core primitives (TOON format, storage internals, transactions)
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Binary edge key encoding for the graph overlay.
//!
//! Replaces the previous UTF-8 string key format with compact binary keys
//! that support efficient prefix scans and maintain lexicographic ordering.
//!
//! # Key Layout
//!
//! All keys start with a one-byte tag that identifies the key type:
//!
//! | Tag  | Kind          | Format                                                        |
//! |------|---------------|---------------------------------------------------------------|
//! | 0x01 | Node          | `[0x01][ns_hash: 4B][table_hash: 4B][tag: 1B][id_bytes]`     |
//! | 0x02 | Edge          | `[0x02][ns_hash: 4B][from_key...][et_hash: 4B][to_key...]`   |
//! | 0x03 | Reverse Index | `[0x03][ns_hash: 4B][et_hash: 4B][to_key...][from_key...]`   |
//!
//! Where `from_key` / `to_key` are `[table_hash: 4B][tag: 1B][id_bytes]` (the RecordId key).
//!
//! The namespace hash ensures graphs in different namespaces never collide.
//! All hashes are FNV-1a 32-bit, big-endian encoded for sort ordering.

use crate::record_id::RecordId;
use crate::soch::SochValue;

/// Tag bytes for key type discrimination.
const TAG_NODE: u8 = 0x01;
const TAG_EDGE: u8 = 0x02;
const TAG_REVERSE: u8 = 0x03;

/// Length-prefixed sub-key: `[len: u16 BE][bytes]`.
/// Used to delimit variable-length RecordId keys within edge keys.
fn write_length_prefixed(buf: &mut Vec<u8>, data: &[u8]) {
    assert!(data.len() <= u16::MAX as usize, "sub-key too long");
    buf.extend_from_slice(&(data.len() as u16).to_be_bytes());
    buf.extend_from_slice(data);
}

/// Read a length-prefixed sub-key, returning `(bytes, rest)`.
fn read_length_prefixed(data: &[u8]) -> Option<(&[u8], &[u8])> {
    if data.len() < 2 {
        return None;
    }
    let len = u16::from_be_bytes([data[0], data[1]]) as usize;
    let rest = &data[2..];
    if rest.len() < len {
        return None;
    }
    Some((&rest[..len], &rest[len..]))
}

/// FNV-1a 32-bit hash (same as RecordId::table_hash, duplicated to avoid coupling).
fn fnv1a_32(bytes: &[u8]) -> u32 {
    let mut hash: u32 = 0x811c9dc5;
    for &b in bytes {
        hash ^= b as u32;
        hash = hash.wrapping_mul(0x01000193);
    }
    hash
}

/// Build a node storage key.
///
/// Format: `[0x01][ns_hash: 4B][record_id_key]`
pub fn node_key(namespace: &str, record_id: &RecordId) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let rid_key = record_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + rid_key.len());
    key.push(TAG_NODE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key.extend_from_slice(&rid_key);
    key
}

/// Build a node prefix for scanning all nodes in a namespace.
///
/// Format: `[0x01][ns_hash: 4B]`
pub fn node_prefix(namespace: &str) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let mut key = Vec::with_capacity(5);
    key.push(TAG_NODE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key
}

/// Build a node prefix for scanning all nodes of a specific table in a namespace.
///
/// Format: `[0x01][ns_hash: 4B][table_hash: 4B]`
pub fn node_table_prefix(namespace: &str, table: &str) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let tbl_prefix = RecordId::table_prefix(table);
    let mut key = Vec::with_capacity(1 + 4 + tbl_prefix.len());
    key.push(TAG_NODE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key.extend_from_slice(&tbl_prefix);
    key
}

/// Build an edge storage key.
///
/// Format: `[0x02][ns_hash: 4B][from_key_len: 2B][from_key][et_hash: 4B][to_key_len: 2B][to_key]`
pub fn edge_key(namespace: &str, from_id: &RecordId, edge_type: &str, to_id: &RecordId) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let et_hash = fnv1a_32(edge_type.as_bytes());
    let from_key = from_id.to_key();
    let to_key = to_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + 2 + from_key.len() + 4 + 2 + to_key.len());
    key.push(TAG_EDGE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    write_length_prefixed(&mut key, &from_key);
    key.extend_from_slice(&et_hash.to_be_bytes());
    write_length_prefixed(&mut key, &to_key);
    key
}

/// Build an edge prefix for scanning all edges from a node.
///
/// Format: `[0x02][ns_hash: 4B][from_key_len: 2B][from_key]`
pub fn edge_from_prefix(namespace: &str, from_id: &RecordId) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let from_key = from_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + 2 + from_key.len());
    key.push(TAG_EDGE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    write_length_prefixed(&mut key, &from_key);
    key
}

/// Build an edge prefix for scanning edges of a specific type from a node.
///
/// Format: `[0x02][ns_hash: 4B][from_key_len: 2B][from_key][et_hash: 4B]`
pub fn edge_from_type_prefix(namespace: &str, from_id: &RecordId, edge_type: &str) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let et_hash = fnv1a_32(edge_type.as_bytes());
    let from_key = from_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + 2 + from_key.len() + 4);
    key.push(TAG_EDGE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    write_length_prefixed(&mut key, &from_key);
    key.extend_from_slice(&et_hash.to_be_bytes());
    key
}

/// Build an edge prefix for scanning all edges in a namespace.
///
/// Format: `[0x02][ns_hash: 4B]`
pub fn edge_prefix(namespace: &str) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let mut key = Vec::with_capacity(5);
    key.push(TAG_EDGE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key
}

/// Build a reverse index key.
///
/// Format: `[0x03][ns_hash: 4B][et_hash: 4B][to_key_len: 2B][to_key][from_key_len: 2B][from_key]`
pub fn reverse_key(
    namespace: &str,
    edge_type: &str,
    to_id: &RecordId,
    from_id: &RecordId,
) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let et_hash = fnv1a_32(edge_type.as_bytes());
    let to_key = to_id.to_key();
    let from_key = from_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + 4 + 2 + to_key.len() + 2 + from_key.len());
    key.push(TAG_REVERSE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key.extend_from_slice(&et_hash.to_be_bytes());
    write_length_prefixed(&mut key, &to_key);
    write_length_prefixed(&mut key, &from_key);
    key
}

/// Build a reverse index prefix for all edges of a given type pointing to a node.
///
/// Format: `[0x03][ns_hash: 4B][et_hash: 4B][to_key_len: 2B][to_key]`
pub fn reverse_type_to_prefix(namespace: &str, edge_type: &str, to_id: &RecordId) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let et_hash = fnv1a_32(edge_type.as_bytes());
    let to_key = to_id.to_key();
    let mut key = Vec::with_capacity(1 + 4 + 4 + 2 + to_key.len());
    key.push(TAG_REVERSE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key.extend_from_slice(&et_hash.to_be_bytes());
    write_length_prefixed(&mut key, &to_key);
    key
}

/// Build a reverse index prefix for all reverse entries in a namespace.
///
/// Format: `[0x03][ns_hash: 4B]`
pub fn reverse_prefix(namespace: &str) -> Vec<u8> {
    let ns_hash = fnv1a_32(namespace.as_bytes());
    let mut key = Vec::with_capacity(5);
    key.push(TAG_REVERSE);
    key.extend_from_slice(&ns_hash.to_be_bytes());
    key
}

/// Decoded edge key components.
#[derive(Debug, Clone)]
pub struct DecodedEdgeKey {
    pub from_key: Vec<u8>,
    pub edge_type_hash: u32,
    pub to_key: Vec<u8>,
}

/// Decode an edge key (tag 0x02) into its components.
///
/// Returns None if the key is malformed or not an edge key.
pub fn decode_edge_key(key: &[u8]) -> Option<DecodedEdgeKey> {
    if key.is_empty() || key[0] != TAG_EDGE {
        return None;
    }
    let rest = &key[1..]; // skip tag
    if rest.len() < 4 {
        return None;
    }
    let rest = &rest[4..]; // skip ns_hash

    let (from_key, rest) = read_length_prefixed(rest)?;
    if rest.len() < 4 {
        return None;
    }
    let et_hash = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]);
    let rest = &rest[4..];
    let (to_key, _rest) = read_length_prefixed(rest)?;

    Some(DecodedEdgeKey {
        from_key: from_key.to_vec(),
        edge_type_hash: et_hash,
        to_key: to_key.to_vec(),
    })
}

/// Decoded reverse index key components.
#[derive(Debug, Clone)]
pub struct DecodedReverseKey {
    pub edge_type_hash: u32,
    pub to_key: Vec<u8>,
    pub from_key: Vec<u8>,
}

/// Decode a reverse index key (tag 0x03) into its components.
pub fn decode_reverse_key(key: &[u8]) -> Option<DecodedReverseKey> {
    if key.is_empty() || key[0] != TAG_REVERSE {
        return None;
    }
    let rest = &key[1..];
    if rest.len() < 4 {
        return None;
    }
    let rest = &rest[4..]; // skip ns_hash
    if rest.len() < 4 {
        return None;
    }
    let et_hash = u32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]);
    let rest = &rest[4..];
    let (to_key, rest) = read_length_prefixed(rest)?;
    let (from_key, _rest) = read_length_prefixed(rest)?;

    Some(DecodedReverseKey {
        edge_type_hash: et_hash,
        to_key: to_key.to_vec(),
        from_key: from_key.to_vec(),
    })
}

/// Encode a `HashMap<String, SochValue>` as a compact binary value.
///
/// Format: `[num_entries: u32 BE] { [key_len: u16 BE][key_utf8][value_json_len: u32 BE][value_json] }*`
///
/// Uses JSON for individual SochValues as a pragmatic choice — the hot path is keys,
/// and values are typically small property bags. A future optimization can replace this
/// with PackedRow encoding without changing the key format.
pub fn encode_properties(props: &std::collections::HashMap<String, SochValue>) -> Vec<u8> {
    let mut buf = Vec::new();
    buf.extend_from_slice(&(props.len() as u32).to_be_bytes());
    for (k, v) in props {
        let key_bytes = k.as_bytes();
        buf.extend_from_slice(&(key_bytes.len() as u16).to_be_bytes());
        buf.extend_from_slice(key_bytes);
        // Encode SochValue as JSON for now (pragmatic; PackedRow upgrade later)
        let val_json = serde_json::to_vec(v).unwrap_or_default();
        buf.extend_from_slice(&(val_json.len() as u32).to_be_bytes());
        buf.extend_from_slice(&val_json);
    }
    buf
}

/// Decode a `HashMap<String, SochValue>` from compact binary encoding.
pub fn decode_properties(data: &[u8]) -> Option<std::collections::HashMap<String, SochValue>> {
    if data.len() < 4 {
        return None;
    }
    let num = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
    let mut offset = 4;
    let mut map = std::collections::HashMap::with_capacity(num);

    for _ in 0..num {
        if offset + 2 > data.len() {
            return None;
        }
        let key_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
        offset += 2;
        if offset + key_len > data.len() {
            return None;
        }
        let key = std::str::from_utf8(&data[offset..offset + key_len])
            .ok()?
            .to_string();
        offset += key_len;

        if offset + 4 > data.len() {
            return None;
        }
        let val_len = u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]) as usize;
        offset += 4;
        if offset + val_len > data.len() {
            return None;
        }
        let val: SochValue = serde_json::from_slice(&data[offset..offset + val_len]).ok()?;
        offset += val_len;

        map.insert(key, val);
    }

    Some(map)
}

/// Encode a node value (node_type + properties) as binary.
///
/// Format: `[type_len: u16 BE][type_utf8][properties_bytes]`
pub fn encode_node_value(
    node_type: &str,
    props: &std::collections::HashMap<String, SochValue>,
) -> Vec<u8> {
    let type_bytes = node_type.as_bytes();
    let props_bytes = encode_properties(props);
    let mut buf = Vec::with_capacity(2 + type_bytes.len() + props_bytes.len());
    buf.extend_from_slice(&(type_bytes.len() as u16).to_be_bytes());
    buf.extend_from_slice(type_bytes);
    buf.extend_from_slice(&props_bytes);
    buf
}

/// Decode a node value into (node_type, properties).
pub fn decode_node_value(
    data: &[u8],
) -> Option<(String, std::collections::HashMap<String, SochValue>)> {
    if data.len() < 2 {
        return None;
    }
    let type_len = u16::from_be_bytes([data[0], data[1]]) as usize;
    if data.len() < 2 + type_len {
        return None;
    }
    let node_type = std::str::from_utf8(&data[2..2 + type_len])
        .ok()?
        .to_string();
    let props = decode_properties(&data[2 + type_len..])?;
    Some((node_type, props))
}

/// Encode an edge value (from_table, from_id_display, edge_type, to_table, to_id_display + properties).
///
/// Format: `[edge_type_len: u16 BE][edge_type_utf8][from_rid_str_len: u16 BE][from_rid_str][to_rid_str_len: u16 BE][to_rid_str][properties_bytes]`
///
/// We store the full RecordId display strings so we can reconstitute them on read
/// without needing another lookup.
pub fn encode_edge_value(
    from_id: &RecordId,
    edge_type: &str,
    to_id: &RecordId,
    props: &std::collections::HashMap<String, SochValue>,
) -> Vec<u8> {
    let et_bytes = edge_type.as_bytes();
    let from_str = from_id.to_string();
    let from_bytes = from_str.as_bytes();
    let to_str = to_id.to_string();
    let to_bytes = to_str.as_bytes();
    let props_bytes = encode_properties(props);

    let mut buf = Vec::with_capacity(
        2 + et_bytes.len() + 2 + from_bytes.len() + 2 + to_bytes.len() + props_bytes.len(),
    );
    buf.extend_from_slice(&(et_bytes.len() as u16).to_be_bytes());
    buf.extend_from_slice(et_bytes);
    buf.extend_from_slice(&(from_bytes.len() as u16).to_be_bytes());
    buf.extend_from_slice(from_bytes);
    buf.extend_from_slice(&(to_bytes.len() as u16).to_be_bytes());
    buf.extend_from_slice(to_bytes);
    buf.extend_from_slice(&props_bytes);
    buf
}

/// Edge value decoded components.
#[derive(Debug, Clone)]
pub struct DecodedEdgeValue {
    pub edge_type: String,
    pub from_id: RecordId,
    pub to_id: RecordId,
    pub properties: std::collections::HashMap<String, SochValue>,
}

/// Decode an edge value.
pub fn decode_edge_value(data: &[u8]) -> Option<DecodedEdgeValue> {
    let mut offset = 0;

    // edge_type
    if offset + 2 > data.len() {
        return None;
    }
    let et_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
    offset += 2;
    if offset + et_len > data.len() {
        return None;
    }
    let edge_type = std::str::from_utf8(&data[offset..offset + et_len])
        .ok()?
        .to_string();
    offset += et_len;

    // from_id
    if offset + 2 > data.len() {
        return None;
    }
    let from_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
    offset += 2;
    if offset + from_len > data.len() {
        return None;
    }
    let from_str = std::str::from_utf8(&data[offset..offset + from_len]).ok()?;
    let from_id = RecordId::parse(from_str)?;
    offset += from_len;

    // to_id
    if offset + 2 > data.len() {
        return None;
    }
    let to_len = u16::from_be_bytes([data[offset], data[offset + 1]]) as usize;
    offset += 2;
    if offset + to_len > data.len() {
        return None;
    }
    let to_str = std::str::from_utf8(&data[offset..offset + to_len]).ok()?;
    let to_id = RecordId::parse(to_str)?;
    offset += to_len;

    // properties
    let props = decode_properties(&data[offset..])?;

    Some(DecodedEdgeValue {
        edge_type,
        from_id,
        to_id,
        properties: props,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // SochValue is already imported via `use crate::soch::SochValue` in the parent module

    #[test]
    fn test_node_key_format() {
        let rid = RecordId::new("person", 42);
        let key = node_key("agent_001", &rid);
        assert_eq!(key[0], TAG_NODE);
        // Namespace hash occupies bytes 1..5
        // RecordId key follows
        assert!(key.len() > 5);
    }

    #[test]
    fn test_node_prefix_is_prefix_of_node_key() {
        let rid = RecordId::new("person", 42);
        let key = node_key("agent_001", &rid);
        let prefix = node_prefix("agent_001");
        assert!(key.starts_with(&prefix));
    }

    #[test]
    fn test_edge_key_roundtrip() {
        let from = RecordId::new("user", 1);
        let to = RecordId::new("conv", 100);
        let key = edge_key("ns", &from, "STARTED", &to);
        let decoded = decode_edge_key(&key).unwrap();
        assert_eq!(decoded.from_key, from.to_key());
        assert_eq!(decoded.to_key, to.to_key());
        assert_eq!(decoded.edge_type_hash, fnv1a_32(b"STARTED"));
    }

    #[test]
    fn test_edge_from_prefix_is_prefix() {
        let from = RecordId::new("user", 1);
        let to = RecordId::new("conv", 100);
        let key = edge_key("ns", &from, "SENT", &to);
        let prefix = edge_from_prefix("ns", &from);
        assert!(key.starts_with(&prefix));
    }

    #[test]
    fn test_edge_from_type_prefix_is_prefix() {
        let from = RecordId::new("user", 1);
        let to = RecordId::new("conv", 100);
        let key = edge_key("ns", &from, "SENT", &to);
        let prefix = edge_from_type_prefix("ns", &from, "SENT");
        assert!(key.starts_with(&prefix));
    }

    #[test]
    fn test_reverse_key_roundtrip() {
        let from = RecordId::new("user", 1);
        let to = RecordId::new("msg", 42);
        let key = reverse_key("ns", "SENT", &to, &from);
        let decoded = decode_reverse_key(&key).unwrap();
        assert_eq!(decoded.from_key, from.to_key());
        assert_eq!(decoded.to_key, to.to_key());
        assert_eq!(decoded.edge_type_hash, fnv1a_32(b"SENT"));
    }

    #[test]
    fn test_reverse_prefix_is_prefix() {
        let from = RecordId::new("user", 1);
        let to = RecordId::new("msg", 42);
        let key = reverse_key("ns", "SENT", &to, &from);
        let prefix = reverse_type_to_prefix("ns", "SENT", &to);
        assert!(key.starts_with(&prefix));
    }

    #[test]
    fn test_encode_decode_properties() {
        let mut props = std::collections::HashMap::new();
        props.insert("name".to_string(), SochValue::Text("Alice".to_string()));
        props.insert("age".to_string(), SochValue::Int(30));
        props.insert("active".to_string(), SochValue::Bool(true));

        let encoded = encode_properties(&props);
        let decoded = decode_properties(&encoded).unwrap();

        assert_eq!(decoded.len(), 3);
        assert_eq!(
            decoded.get("name"),
            Some(&SochValue::Text("Alice".to_string()))
        );
        assert_eq!(decoded.get("age"), Some(&SochValue::Int(30)));
        assert_eq!(decoded.get("active"), Some(&SochValue::Bool(true)));
    }

    #[test]
    fn test_encode_decode_node_value() {
        let mut props = std::collections::HashMap::new();
        props.insert("email".to_string(), SochValue::Text("a@b.com".to_string()));

        let encoded = encode_node_value("User", &props);
        let (node_type, decoded_props) = decode_node_value(&encoded).unwrap();
        assert_eq!(node_type, "User");
        assert_eq!(
            decoded_props.get("email"),
            Some(&SochValue::Text("a@b.com".to_string()))
        );
    }

    #[test]
    fn test_encode_decode_edge_value() {
        let from = RecordId::new("user", 1);
        let to = RecordId::from_string("conv", "abc");
        let mut props = std::collections::HashMap::new();
        props.insert("weight".to_string(), SochValue::Float(0.95));

        let encoded = encode_edge_value(&from, "STARTED", &to, &props);
        let decoded = decode_edge_value(&encoded).unwrap();
        assert_eq!(decoded.edge_type, "STARTED");
        assert_eq!(decoded.from_id, from);
        assert_eq!(decoded.to_id, to);
        assert_eq!(
            decoded.properties.get("weight"),
            Some(&SochValue::Float(0.95))
        );
    }

    #[test]
    fn test_empty_properties() {
        let props = std::collections::HashMap::new();
        let encoded = encode_properties(&props);
        let decoded = decode_properties(&encoded).unwrap();
        assert!(decoded.is_empty());
    }

    #[test]
    fn test_different_namespaces_produce_different_keys() {
        let rid = RecordId::new("person", 1);
        let key1 = node_key("ns_a", &rid);
        let key2 = node_key("ns_b", &rid);
        assert_ne!(key1, key2);
    }
}