littlegraph-core 0.2.1

Embedded openCypher graph database backed by Neo4j record storage
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use crate::error::{Neo4jStoreError, Result};
use crate::value::Properties;

use super::dynamic::{read_u32, DynamicStore};
use super::page::{PageLayout, RecordReader};
use super::Neo4jStoreFormat;

const NODE_RECORD_SIZE: usize = 15;
const DYNAMIC_LABEL_FLAG: u64 = 0x80_0000_0000;
const LABEL_BODY_MASK: u64 = 0x0f_ffff_ffff;
const LONG_PROPERTY_TYPE: u8 = 6;
const MAX_RELATIONSHIP_REFERENCE: u64 = 0x07_ffff_ffff;
const MAX_PROPERTY_REFERENCE: u64 = 0x0f_ffff_ffff;
const MAX_LABEL_FIELD: u64 = 0xff_ffff_ffff;

#[derive(Clone, Debug, Default)]
pub(super) struct NodeCatalog {
    pub(super) records: Vec<NodeRecord>,
    pub(super) label_index: BTreeMap<String, Vec<u64>>,
}

#[derive(Clone, Debug, PartialEq)]
pub(super) struct NodeRecord {
    pub(super) neo4j_id: u64,
    pub(super) next_property: Option<u64>,
    pub(super) next_relationship: Option<u64>,
    pub(super) dense: bool,
    pub(super) labels: Vec<String>,
    pub(super) properties: Properties,
}

struct DecodedNodeRecord {
    next_property: Option<u64>,
    next_relationship: Option<u64>,
    dense: bool,
    label_field: u64,
}

pub(super) fn load(
    database_directory: &Path,
    format: Neo4jStoreFormat,
    label_tokens: &BTreeMap<u32, String>,
) -> Result<NodeCatalog> {
    let node_path = database_directory.join("neostore.nodestore.db");
    let layout = PageLayout::new(&node_path, format, NODE_RECORD_SIZE)?;
    let mut reader = RecordReader::open(&node_path, "node", layout)?;
    let label_store_path = database_directory.join("neostore.nodestore.db.labels");
    let mut dynamic_labels = None;
    let mut records = Vec::new();
    let mut label_index: BTreeMap<String, Vec<u64>> = BTreeMap::new();

    for neo4j_id in 0..reader.record_count() {
        let bytes = reader.read(neo4j_id)?;
        if bytes[0] & 1 == 0 {
            continue;
        }
        let decoded = decode_record(&bytes);
        let label_ids = if decoded.label_field & DYNAMIC_LABEL_FLAG == 0 {
            decode_inline_labels(decoded.label_field)
        } else {
            if dynamic_labels.is_none() {
                dynamic_labels = Some(DynamicStore::open(
                    &label_store_path,
                    format,
                    "dynamic node label",
                )?);
            }
            let store = dynamic_labels.as_mut().ok_or_else(|| {
                invalid_node(&reader, neo4j_id, "dynamic label store was not opened")
            })?;
            decode_dynamic_labels(store, decoded.label_field & LABEL_BODY_MASK, neo4j_id)?
        };

        let mut labels = Vec::with_capacity(label_ids.len());
        let mut seen = BTreeSet::new();
        for label_id in label_ids {
            if !seen.insert(label_id) {
                return Err(invalid_node(
                    &reader,
                    neo4j_id,
                    format!("duplicate label token ID {label_id}"),
                ));
            }
            let label = label_tokens.get(&label_id).ok_or_else(|| {
                invalid_node(
                    &reader,
                    neo4j_id,
                    format!("unknown label token ID {label_id}"),
                )
            })?;
            labels.push(label.clone());
            label_index.entry(label.clone()).or_default().push(neo4j_id);
        }
        records.push(NodeRecord {
            neo4j_id,
            next_property: decoded.next_property,
            next_relationship: decoded.next_relationship,
            dense: decoded.dense,
            labels,
            properties: Properties::new(),
        });
    }
    Ok(NodeCatalog {
        records,
        label_index,
    })
}

fn decode_record(bytes: &[u8]) -> DecodedNodeRecord {
    let header = bytes[0];
    let next_relationship_low = read_u32(&bytes[1..5]);
    let next_property_low = read_u32(&bytes[5..9]);
    let relationship_modifier = ((header & 0x0e) as u64) << 31;
    let property_modifier = ((header & 0xf0) as u64) << 28;
    let label_field = read_u32(&bytes[9..13]) as u64 | (bytes[13] as u64) << 32;
    DecodedNodeRecord {
        next_property: decode_reference(next_property_low, property_modifier),
        next_relationship: decode_reference(next_relationship_low, relationship_modifier),
        dense: bytes[14] & 1 != 0,
        label_field,
    }
}

fn decode_reference(low: u32, modifier: u64) -> Option<u64> {
    if modifier == 0 && low == u32::MAX {
        None
    } else {
        Some(modifier | low as u64)
    }
}

#[allow(dead_code)]
pub(super) fn encode_record(
    next_property: Option<u64>,
    next_relationship: Option<u64>,
    dense: bool,
    label_field: u64,
) -> std::result::Result<[u8; NODE_RECORD_SIZE], String> {
    let next_property =
        encode_reference(next_property, MAX_PROPERTY_REFERENCE, "node next-property")?;
    let next_relationship = encode_reference(
        next_relationship,
        MAX_RELATIONSHIP_REFERENCE,
        "node next-relationship",
    )?;
    if label_field > MAX_LABEL_FIELD {
        return Err(format!(
            "node label field {label_field} exceeds the 40-bit record field"
        ));
    }

    let mut bytes = [0_u8; NODE_RECORD_SIZE];
    bytes[0] = 1 | ((next_relationship >> 31) as u8 & 0x0e) | ((next_property >> 28) as u8 & 0xf0);
    bytes[1..5].copy_from_slice(&(next_relationship as u32).to_be_bytes());
    bytes[5..9].copy_from_slice(&(next_property as u32).to_be_bytes());
    bytes[9..13].copy_from_slice(&(label_field as u32).to_be_bytes());
    bytes[13] = (label_field >> 32) as u8;
    bytes[14] = u8::from(dense);
    Ok(bytes)
}

pub(super) fn encode_inline_label_field(label_ids: &[u32]) -> std::result::Result<u64, String> {
    if label_ids.len() > 7 {
        return Err("more than 7 labels require dynamic node-label records".to_owned());
    }
    if label_ids.is_empty() {
        return Ok(0);
    }
    let mut label_ids = label_ids.to_vec();
    label_ids.sort_unstable();
    if label_ids.windows(2).any(|pair| pair[0] == pair[1]) {
        return Err("node labels contain a duplicate token ID".to_owned());
    }
    let label_count = label_ids.len();
    let bits_per_label = 36 / label_count;
    let limit = 1_u64 << bits_per_label;
    let mut body = 0_u64;
    for (position, label_id) in label_ids.into_iter().enumerate() {
        if label_id as u64 >= limit {
            return Err(format!(
                "label token ID {label_id} does not fit {bits_per_label} inline bits"
            ));
        }
        body |= (label_id as u64) << (position * bits_per_label);
    }
    Ok((label_count as u64) << 36 | body)
}

pub(super) fn encode_dynamic_label_payload(
    node_id: u64,
    label_ids: &[u32],
) -> std::result::Result<Vec<u8>, String> {
    if label_ids.is_empty() {
        return Err("dynamic node-label array cannot be empty".to_owned());
    }
    let mut values = Vec::with_capacity(label_ids.len() + 1);
    values.push(node_id);
    values.extend(label_ids.iter().map(|id| *id as u64));
    let bits_per_value = values
        .iter()
        .map(|value| (64 - value.leading_zeros()) as usize)
        .max()
        .unwrap_or(1)
        .max(1);
    let total_bits = values
        .len()
        .checked_mul(bits_per_value)
        .ok_or_else(|| "dynamic node-label bit length overflow".to_owned())?;
    let body_len = total_bits.div_ceil(8);
    let bits_in_last_byte = match total_bits % 8 {
        0 => 8,
        remainder => remainder,
    };
    let mut bytes = vec![0_u8; 3 + body_len];
    bytes[0] = LONG_PROPERTY_TYPE;
    bytes[1] = bits_in_last_byte as u8;
    bytes[2] = bits_per_value as u8;
    for (index, value) in values.into_iter().enumerate() {
        for bit in 0..bits_per_value {
            bytes[3 + (index * bits_per_value + bit) / 8] |=
                (((value >> bit) & 1) as u8) << ((index * bits_per_value + bit) % 8);
        }
    }
    Ok(bytes)
}

fn encode_reference(
    reference: Option<u64>,
    maximum: u64,
    field: &str,
) -> std::result::Result<u64, String> {
    let Some(reference) = reference else {
        return Ok(u32::MAX as u64);
    };
    if reference > maximum {
        return Err(format!(
            "{field} reference {reference} exceeds its record field"
        ));
    }
    if reference == u32::MAX as u64 {
        return Err(format!(
            "{field} reference {reference} conflicts with the no-reference sentinel"
        ));
    }
    Ok(reference)
}

pub(super) fn read_with_next_property(
    database_directory: &Path,
    format: Neo4jStoreFormat,
    record_id: u64,
    next_property: u64,
) -> Result<[u8; NODE_RECORD_SIZE]> {
    let mut bytes = read_record(database_directory, format, record_id)?;
    set_next_property(&mut bytes, next_property);
    Ok(bytes)
}

pub(super) fn read_record(
    database_directory: &Path,
    format: Neo4jStoreFormat,
    record_id: u64,
) -> Result<[u8; NODE_RECORD_SIZE]> {
    let path = database_directory.join("neostore.nodestore.db");
    let layout = PageLayout::new(&path, format, NODE_RECORD_SIZE)?;
    let mut reader = RecordReader::open(&path, "node", layout)?;
    let bytes: [u8; NODE_RECORD_SIZE] = reader
        .read(record_id)?
        .try_into()
        .expect("record reader returns the configured size");
    Ok(bytes)
}

pub(super) fn set_next_property(bytes: &mut [u8; NODE_RECORD_SIZE], next_property: u64) {
    bytes[0] = (bytes[0] & 0x0f) | ((next_property >> 28) as u8 & 0xf0);
    bytes[5..9].copy_from_slice(&(next_property as u32).to_be_bytes());
}

#[allow(dead_code)]
pub(super) fn set_dense_relationship_head(
    bytes: &mut [u8; NODE_RECORD_SIZE],
    relationship_group_id: u64,
) -> std::result::Result<(), String> {
    let encoded = encode_reference(
        Some(relationship_group_id),
        MAX_RELATIONSHIP_REFERENCE,
        "dense node relationship-group",
    )?;
    bytes[0] = (bytes[0] & 0xf1) | ((encoded >> 31) as u8 & 0x0e);
    bytes[1..5].copy_from_slice(&(encoded as u32).to_be_bytes());
    bytes[14] |= 1;
    Ok(())
}

pub(super) fn read_with_next_relationship(
    database_directory: &Path,
    format: Neo4jStoreFormat,
    record_id: u64,
    next_relationship: u64,
) -> Result<[u8; NODE_RECORD_SIZE]> {
    let path = database_directory.join("neostore.nodestore.db");
    let layout = PageLayout::new(&path, format, NODE_RECORD_SIZE)?;
    let mut reader = RecordReader::open(&path, "node", layout)?;
    let mut bytes: [u8; NODE_RECORD_SIZE] = reader
        .read(record_id)?
        .try_into()
        .expect("record reader returns the configured size");
    set_next_relationship(&mut bytes, next_relationship);
    Ok(bytes)
}

pub(super) fn set_next_relationship(bytes: &mut [u8; NODE_RECORD_SIZE], next_relationship: u64) {
    bytes[0] = (bytes[0] & 0xf1) | ((next_relationship >> 31) as u8 & 0x0e);
    bytes[1..5].copy_from_slice(&(next_relationship as u32).to_be_bytes());
}

pub(super) fn label_field(bytes: &[u8; NODE_RECORD_SIZE]) -> u64 {
    read_u32(&bytes[9..13]) as u64 | (bytes[13] as u64) << 32
}

pub(super) fn set_label_field(bytes: &mut [u8; NODE_RECORD_SIZE], label_field: u64) {
    bytes[9..13].copy_from_slice(&(label_field as u32).to_be_bytes());
    bytes[13] = (label_field >> 32) as u8;
}

fn decode_inline_labels(label_field: u64) -> Vec<u32> {
    let count = ((label_field >> 36) & 0x0f) as usize;
    if count == 0 {
        return Vec::new();
    }
    let bits_per_label = 36 / count;
    let mask = (1_u64 << bits_per_label) - 1;
    let mut body = label_field & LABEL_BODY_MASK;
    let mut labels = Vec::with_capacity(count);
    for _ in 0..count {
        labels.push((body & mask) as u32);
        body >>= bits_per_label;
    }
    labels
}

fn decode_dynamic_labels(
    store: &mut DynamicStore,
    first_record_id: u64,
    node_id: u64,
) -> Result<Vec<u32>> {
    let context =
        format!("node {node_id} dynamic label chain starting at record {first_record_id}");
    let bytes = store.read_chain(first_record_id, &context)?;
    if bytes.len() < 3 {
        return Err(store.invalid(
            first_record_id,
            &context,
            "dynamic label array is missing its 3-byte numeric header",
        ));
    }
    if bytes[0] != LONG_PROPERTY_TYPE {
        return Err(store.invalid(
            first_record_id,
            &context,
            format!("dynamic label array has type {}, expected LONG", bytes[0]),
        ));
    }
    let bits_in_last_byte = bytes[1] as usize;
    let bits_per_value = bytes[2] as usize;
    if !(1..=8).contains(&bits_in_last_byte) || !(1..=64).contains(&bits_per_value) {
        return Err(store.invalid(
            first_record_id,
            &context,
            format!(
                "invalid numeric array header: last-byte bits {bits_in_last_byte}, value bits {bits_per_value}"
            ),
        ));
    }
    let body = &bytes[3..];
    if body.is_empty() {
        return Err(store.invalid(first_record_id, &context, "dynamic label array is empty"));
    }
    let total_bits = body
        .len()
        .checked_mul(8)
        .and_then(|bits| bits.checked_sub(8 - bits_in_last_byte))
        .ok_or_else(|| {
            store.invalid(
                first_record_id,
                &context,
                "dynamic label bit length overflow",
            )
        })?;
    if total_bits % bits_per_value != 0 {
        return Err(store.invalid(
            first_record_id,
            &context,
            "dynamic label array ends with a partial value",
        ));
    }
    let value_count = total_bits / bits_per_value;
    if value_count == 0 {
        return Err(store.invalid(
            first_record_id,
            &context,
            "dynamic label array has no node ID",
        ));
    }

    let stored_node_id = read_bits(body, 0, bits_per_value);
    if stored_node_id != node_id {
        return Err(store.invalid(
            first_record_id,
            &context,
            format!("dynamic label array belongs to node {stored_node_id}"),
        ));
    }
    let mut labels = Vec::with_capacity(value_count - 1);
    for index in 1..value_count {
        let value = read_bits(body, index * bits_per_value, bits_per_value);
        let label_id = u32::try_from(value).map_err(|_| {
            store.invalid(
                first_record_id,
                &context,
                format!("label token ID {value} does not fit in u32"),
            )
        })?;
        labels.push(label_id);
    }
    Ok(labels)
}

fn read_bits(bytes: &[u8], offset: usize, width: usize) -> u64 {
    let mut value = 0_u64;
    for bit in 0..width {
        let source = offset + bit;
        let set = (bytes[source / 8] >> (source % 8)) & 1;
        value |= (set as u64) << bit;
    }
    value
}

fn invalid_node(reader: &RecordReader, node_id: u64, message: impl Into<String>) -> crate::Error {
    Neo4jStoreError::InvalidRecord {
        path: PathBuf::from(reader.path()),
        record_type: "node".to_owned(),
        record_id: node_id,
        offset: reader.offset(node_id).unwrap_or(u64::MAX),
        context: format!("node {node_id}"),
        message: message.into(),
    }
    .into()
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use std::io::{Seek, SeekFrom, Write};

    use super::*;

    #[test]
    fn encodes_an_empty_in_use_node_record() {
        let bytes = encode_record(None, None, false, 0).unwrap();
        assert_eq!(bytes[0], 1);
        assert_eq!(&bytes[1..5], &u32::MAX.to_be_bytes());
        assert_eq!(&bytes[5..9], &u32::MAX.to_be_bytes());
        assert_eq!(&bytes[9..], &[0; 6]);

        let decoded = decode_record(&bytes);
        assert_eq!(decoded.next_property, None);
        assert_eq!(decoded.next_relationship, None);
        assert!(!decoded.dense);
        assert_eq!(decoded.label_field, 0);
    }

    #[test]
    fn node_record_codec_preserves_all_bit_fields() {
        let property = 0x0e_1234_5678;
        let relationship = 0x05_2345_6789;
        let label_field = 0xab_cdef_0123;
        let bytes = encode_record(Some(property), Some(relationship), true, label_field).unwrap();
        let decoded = decode_record(&bytes);
        assert_eq!(decoded.next_property, Some(property));
        assert_eq!(decoded.next_relationship, Some(relationship));
        assert!(decoded.dense);
        assert_eq!(decoded.label_field, label_field);
    }

    #[test]
    fn node_record_encoder_rejects_unrepresentable_fields() {
        assert!(encode_record(Some(MAX_PROPERTY_REFERENCE + 1), None, false, 0).is_err());
        assert!(encode_record(None, Some(MAX_RELATIONSHIP_REFERENCE + 1), false, 0).is_err());
        assert!(encode_record(None, None, false, MAX_LABEL_FIELD + 1).is_err());
        assert!(encode_record(Some(u32::MAX as u64), None, false, 0)
            .unwrap_err()
            .contains("sentinel"));
    }

    #[test]
    fn encodes_sorted_inline_label_ids() {
        let field = encode_inline_label_field(&[17, 2, 9]).unwrap();
        assert_eq!(decode_inline_labels(field), [2, 9, 17]);
        assert_eq!((field >> 36) & 0x0f, 3);
    }

    #[test]
    fn rejects_labels_that_require_dynamic_records() {
        assert!(encode_inline_label_field(&[0, 1, 2, 3, 4, 5, 6, 7])
            .unwrap_err()
            .contains("dynamic"));
        assert!(encode_inline_label_field(&[1, 1])
            .unwrap_err()
            .contains("duplicate"));
        assert!(encode_inline_label_field(&[64, 1, 2, 3, 4, 5, 6])
            .unwrap_err()
            .contains("does not fit"));
    }

    #[test]
    fn encodes_dynamic_labels_with_the_owning_node_id() {
        let payload =
            encode_dynamic_label_payload(900, &[2, 9, 17, 33, 65, 129, 257, 513]).unwrap();
        assert_eq!(payload[0], LONG_PROPERTY_TYPE);
        let width = payload[2] as usize;
        assert_eq!(read_bits(&payload[3..], 0, width), 900);
        assert_eq!(read_bits(&payload[3..], width, width), 2);
        assert_eq!(read_bits(&payload[3..], width * 8, width), 513);
    }
    use crate::neo4j_storage::dynamic::NO_NEXT_BLOCK;

    fn inline_field(labels: &[u32]) -> u64 {
        let bits_per_label = if labels.is_empty() {
            36
        } else {
            36 / labels.len()
        };
        let mut field = (labels.len() as u64) << 36;
        for (index, label) in labels.iter().enumerate() {
            field |= (*label as u64) << (index * bits_per_label);
        }
        field
    }

    fn node_record(
        next_relationship: Option<u64>,
        next_property: Option<u64>,
        dense: bool,
        label_field: u64,
    ) -> [u8; NODE_RECORD_SIZE] {
        let next_relationship = next_relationship.unwrap_or(u32::MAX as u64);
        let next_property = next_property.unwrap_or(u32::MAX as u64);
        let mut bytes = [0_u8; NODE_RECORD_SIZE];
        bytes[0] =
            1 | (((next_relationship >> 32) as u8) << 1) | (((next_property >> 32) as u8) << 4);
        bytes[1..5].copy_from_slice(&(next_relationship as u32).to_be_bytes());
        bytes[5..9].copy_from_slice(&(next_property as u32).to_be_bytes());
        bytes[9..13].copy_from_slice(&(label_field as u32).to_be_bytes());
        bytes[13] = (label_field >> 32) as u8;
        bytes[14] = u8::from(dense);
        bytes
    }

    fn encode_long_array(values: &[u64]) -> Vec<u8> {
        let bits_per_value = values
            .iter()
            .map(|value| (64 - value.leading_zeros()).max(1) as usize)
            .max()
            .unwrap_or(1);
        let total_bits = bits_per_value * values.len();
        let bits_in_last_byte = match total_bits % 8 {
            0 => 8,
            bits => bits,
        };
        let mut bytes = vec![0_u8; 3 + total_bits.div_ceil(8)];
        bytes[0] = LONG_PROPERTY_TYPE;
        bytes[1] = bits_in_last_byte as u8;
        bytes[2] = bits_per_value as u8;
        for (index, value) in values.iter().enumerate() {
            for bit in 0..bits_per_value {
                bytes[3 + (index * bits_per_value + bit) / 8] |=
                    (((value >> bit) & 1) as u8) << ((index * bits_per_value + bit) % 8);
            }
        }
        bytes
    }

    fn write_dynamic_label_store(path: &Path, format: Neo4jStoreFormat, data: &[u8]) {
        let record_size = 16_usize;
        let payload_size = record_size - 8;
        let layout = PageLayout::new(path, format, record_size).unwrap();
        let mut file = File::create(path).unwrap();
        file.write_all(&(record_size as u32).to_be_bytes()).unwrap();
        let chunks = data.chunks(payload_size).collect::<Vec<_>>();
        for (index, chunk) in chunks.iter().enumerate() {
            let id = index as u64 + 1;
            let next = (index + 1 < chunks.len()).then_some(id + 1);
            let next_value = next.unwrap_or(NO_NEXT_BLOCK as u64);
            let mut record = vec![0_u8; record_size];
            record[0] =
                0x10 | if index == 0 { 0 } else { 0x80 } | ((next_value >> 32) as u8 & 0x0f);
            record[1] = ((chunk.len() >> 16) & 0xff) as u8;
            record[2] = ((chunk.len() >> 8) & 0xff) as u8;
            record[3] = (chunk.len() & 0xff) as u8;
            record[4..8].copy_from_slice(&(next_value as u32).to_be_bytes());
            record[8..8 + chunk.len()].copy_from_slice(chunk);
            file.seek(SeekFrom::Start(layout.offset(id, path).unwrap()))
                .unwrap();
            file.write_all(&record).unwrap();
        }
    }

    #[test]
    fn decodes_node_reference_modifiers_dense_and_inline_labels() {
        let bytes = node_record(
            Some(0x07_1234_5678),
            Some(0x0f_89ab_cdef),
            true,
            inline_field(&[3, 9, 17]),
        );
        let decoded = decode_record(&bytes);
        assert_eq!(decoded.next_relationship, Some(0x07_1234_5678));
        assert_eq!(decoded.next_property, Some(0x0f_89ab_cdef));
        assert!(decoded.dense);
        assert_eq!(decode_inline_labels(decoded.label_field), vec![3, 9, 17]);

        let decoded = decode_record(&node_record(None, None, false, 0));
        assert_eq!(decoded.next_relationship, None);
        assert_eq!(decoded.next_property, None);
        assert!(!decoded.dense);
        assert!(decode_inline_labels(decoded.label_field).is_empty());
    }

    #[test]
    fn setting_dense_group_head_preserves_property_and_label_fields() {
        let mut bytes = encode_record(Some(17), Some(23), false, 0x12_3456_789a).unwrap();
        let property_and_labels = (bytes[0] & 0xf0, bytes[5..14].to_vec());
        set_dense_relationship_head(&mut bytes, 0x05_1234_5678).unwrap();
        let decoded = decode_record(&bytes);
        assert!(decoded.dense);
        assert_eq!(decoded.next_relationship, Some(0x05_1234_5678));
        assert_eq!(decoded.next_property, Some(17));
        assert_eq!(decoded.label_field, 0x12_3456_789a);
        assert_eq!(
            (bytes[0] & 0xf0, bytes[5..14].to_vec()),
            property_and_labels
        );
    }

    #[test]
    fn setting_property_head_preserves_other_node_fields() {
        let mut bytes = node_record(Some(0x07_1234_5678), None, true, inline_field(&[3, 9]));
        let before = bytes;
        set_next_property(&mut bytes, 0x0d_89ab_cdef);
        assert_eq!(decode_record(&bytes).next_property, Some(0x0d_89ab_cdef));
        assert_eq!(bytes[0] & 0x0f, before[0] & 0x0f);
        assert_eq!(&bytes[1..5], &before[1..5]);
        assert_eq!(&bytes[9..], &before[9..]);
    }

    #[test]
    fn setting_relationship_head_preserves_other_node_fields() {
        let mut bytes = node_record(None, Some(0x0d_89ab_cdef), true, inline_field(&[3, 9]));
        let before = bytes;
        set_next_relationship(&mut bytes, 0x07_1234_5678);
        assert_eq!(
            decode_record(&bytes).next_relationship,
            Some(0x07_1234_5678)
        );
        assert_eq!(bytes[0] & 0xf1, before[0] & 0xf1);
        assert_eq!(&bytes[5..], &before[5..]);
    }

    #[test]
    fn setting_label_field_preserves_other_node_fields() {
        let mut bytes = node_record(Some(0x07_1234_5678), Some(0x0d_89ab_cdef), true, 0);
        let before = bytes;
        let labels = encode_inline_label_field(&[3, 9, 17]).unwrap();
        set_label_field(&mut bytes, labels);
        assert_eq!(label_field(&bytes), labels);
        assert_eq!(&bytes[..9], &before[..9]);
        assert_eq!(bytes[14], before[14]);
    }

    #[test]
    fn loads_inline_nodes_and_skips_deleted_records() {
        let directory = tempfile::tempdir().unwrap();
        let node_path = directory.path().join("neostore.nodestore.db");
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&node_record(None, Some(4), false, inline_field(&[1, 2])));
        bytes.extend_from_slice(&[0_u8; NODE_RECORD_SIZE]);
        std::fs::write(&node_path, bytes).unwrap();
        let tokens = BTreeMap::from([(1, "Person".to_owned()), (2, "Admin".to_owned())]);

        let catalog = load(directory.path(), Neo4jStoreFormat::AlignedV5_0, &tokens).unwrap();
        assert_eq!(catalog.records.len(), 1);
        assert_eq!(catalog.records[0].neo4j_id, 0);
        assert_eq!(catalog.records[0].next_property, Some(4));
        assert_eq!(catalog.records[0].labels, ["Person", "Admin"]);
        assert_eq!(catalog.label_index["Admin"], [0]);
    }

    #[test]
    fn loads_dynamic_labels_and_checks_owning_node() {
        for format in [
            Neo4jStoreFormat::StandardV5_0,
            Neo4jStoreFormat::AlignedV5_0,
        ] {
            let directory = tempfile::tempdir().unwrap();
            let node_path = directory.path().join("neostore.nodestore.db");
            std::fs::write(
                &node_path,
                node_record(None, None, false, DYNAMIC_LABEL_FLAG | 1),
            )
            .unwrap();
            let label_path = directory.path().join("neostore.nodestore.db.labels");
            write_dynamic_label_store(&label_path, format, &encode_long_array(&[0, 2, 5, 9]));
            let tokens = BTreeMap::from([
                (2, "A".to_owned()),
                (5, "B".to_owned()),
                (9, "C".to_owned()),
            ]);

            let catalog = load(directory.path(), format, &tokens).unwrap();
            assert_eq!(catalog.records[0].labels, ["A", "B", "C"]);

            write_dynamic_label_store(&label_path, format, &encode_long_array(&[7, 2]));
            let error = load(directory.path(), format, &tokens).unwrap_err();
            assert!(error.to_string().contains("belongs to node 7"));
        }
    }

    #[test]
    fn rejects_unknown_and_duplicate_inline_label_tokens() {
        let directory = tempfile::tempdir().unwrap();
        let node_path = directory.path().join("neostore.nodestore.db");
        std::fs::write(
            &node_path,
            node_record(None, None, false, inline_field(&[1, 1])),
        )
        .unwrap();
        let tokens = BTreeMap::from([(1, "Known".to_owned())]);
        assert!(load(directory.path(), Neo4jStoreFormat::AlignedV5_0, &tokens).is_err());

        std::fs::write(
            &node_path,
            node_record(None, None, false, inline_field(&[2])),
        )
        .unwrap();
        let error = load(directory.path(), Neo4jStoreFormat::AlignedV5_0, &tokens).unwrap_err();
        assert!(error.to_string().contains("unknown label token ID 2"));
    }
}