lbug 0.16.1

An in-process property graph database management system built for query speed and scalability
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
#include "storage/table/column_chunk_data.h"

#include <algorithm>

#include "common/data_chunk/sel_vector.h"
#include "common/exception/copy.h"
#include "common/null_mask.h"
#include "common/serializer/deserializer.h"
#include "common/serializer/serializer.h"
#include "common/system_config.h"
#include "common/type_utils.h"
#include "common/types/types.h"
#include "common/vector/value_vector.h"
#include "expression_evaluator/expression_evaluator.h"
#include "storage/buffer_manager/buffer_manager.h"
#include "storage/buffer_manager/memory_manager.h"
#include "storage/buffer_manager/spill_result.h"
#include "storage/buffer_manager/spiller.h"
#include "storage/compression/compression.h"
#include "storage/compression/float_compression.h"
#include "storage/enums/residency_state.h"
#include "storage/stats/column_stats.h"
#include "storage/table/column.h"
#include "storage/table/column_chunk_metadata.h"
#include "storage/table/compression_flush_buffer.h"
#include "storage/table/list_chunk_data.h"
#include "storage/table/string_chunk_data.h"
#include "storage/table/struct_chunk_data.h"
#include <format>

using namespace lbug::common;
using namespace lbug::evaluator;
using namespace lbug::transaction;

namespace lbug {
namespace storage {

void SegmentState::reclaimAllocatedPages(PageAllocator& pageAllocator) const {
    const auto& entry = metadata.pageRange;
    if (entry.startPageIdx != INVALID_PAGE_IDX) {
        pageAllocator.freePageRange(entry);
    }
    if (nullState) {
        nullState->reclaimAllocatedPages(pageAllocator);
    }
    for (const auto& child : childrenStates) {
        child.reclaimAllocatedPages(pageAllocator);
    }
}

static std::shared_ptr<CompressionAlg> getCompression(const LogicalType& dataType,
    bool enableCompression) {
    if (!enableCompression) {
        return std::make_shared<Uncompressed>(dataType);
    }
    switch (dataType.getPhysicalType()) {
    case PhysicalTypeID::INT128: {
        return std::make_shared<IntegerBitpacking<int128_t>>();
    }
    case PhysicalTypeID::INT64: {
        return std::make_shared<IntegerBitpacking<int64_t>>();
    }
    case PhysicalTypeID::INT32: {
        return std::make_shared<IntegerBitpacking<int32_t>>();
    }
    case PhysicalTypeID::INT16: {
        return std::make_shared<IntegerBitpacking<int16_t>>();
    }
    case PhysicalTypeID::INT8: {
        return std::make_shared<IntegerBitpacking<int8_t>>();
    }
    case PhysicalTypeID::INTERNAL_ID:
    case PhysicalTypeID::UINT64: {
        return std::make_shared<IntegerBitpacking<uint64_t>>();
    }
    case PhysicalTypeID::UINT32: {
        return std::make_shared<IntegerBitpacking<uint32_t>>();
    }
    case PhysicalTypeID::UINT16: {
        return std::make_shared<IntegerBitpacking<uint16_t>>();
    }
    case PhysicalTypeID::UINT8: {
        return std::make_shared<IntegerBitpacking<uint8_t>>();
    }
    case PhysicalTypeID::FLOAT: {
        return std::make_shared<FloatCompression<float>>();
    }
    case PhysicalTypeID::DOUBLE: {
        return std::make_shared<FloatCompression<double>>();
    }
    default: {
        return std::make_shared<Uncompressed>(dataType);
    }
    }
}

ColumnChunkData::ColumnChunkData(MemoryManager& mm, LogicalType dataType, uint64_t capacity,
    bool enableCompression, ResidencyState residencyState, bool hasNullData, bool initializeToZero)
    : residencyState{residencyState}, dataType{std::move(dataType)},
      enableCompression{enableCompression},
      numBytesPerValue{getDataTypeSizeInChunk(this->dataType)}, capacity{capacity}, numValues{0},
      inMemoryStats() {
    if (hasNullData) {
        nullData = std::make_unique<NullChunkData>(mm, capacity, enableCompression, residencyState);
    }
    initializeBuffer(this->dataType.getPhysicalType(), mm, initializeToZero);
    initializeFunction();
}

ColumnChunkData::ColumnChunkData(MemoryManager& mm, LogicalType dataType, bool enableCompression,
    const ColumnChunkMetadata& metadata, bool hasNullData, bool initializeToZero)
    : residencyState(ResidencyState::ON_DISK), dataType{std::move(dataType)},
      enableCompression{enableCompression},
      numBytesPerValue{getDataTypeSizeInChunk(this->dataType)}, capacity{0},
      numValues{metadata.numValues}, metadata{metadata} {
    if (hasNullData) {
        nullData = std::make_unique<NullChunkData>(mm, enableCompression, metadata);
    }
    initializeBuffer(this->dataType.getPhysicalType(), mm, initializeToZero);
    initializeFunction();
}

ColumnChunkData::ColumnChunkData(MemoryManager& mm, PhysicalTypeID dataType, bool enableCompression,
    const ColumnChunkMetadata& metadata, bool hasNullData, bool initializeToZero)
    : ColumnChunkData(mm, LogicalType::ANY(dataType), enableCompression, metadata, hasNullData,
          initializeToZero) {}

void ColumnChunkData::initializeBuffer(PhysicalTypeID physicalType, MemoryManager& mm,
    bool initializeToZero) {
    numBytesPerValue = getDataTypeSizeInChunk(physicalType);

    // Some columnChunks are much smaller than the 256KB minimum size used by allocateBuffer
    // Which would lead to excessive memory use, particularly in the partitioner
    buffer = mm.allocateBuffer(initializeToZero, getBufferSize(capacity));
}

void ColumnChunkData::initializeFunction() {
    const auto compression = getCompression(dataType, enableCompression);
    getMetadataFunction = GetCompressionMetadata(compression, dataType);
    flushBufferFunction = initializeFlushBufferFunction(compression);
}

ColumnChunkData::flush_buffer_func_t ColumnChunkData::initializeFlushBufferFunction(
    std::shared_ptr<CompressionAlg> compression) const {
    switch (dataType.getPhysicalType()) {
    case PhysicalTypeID::BOOL: {
        // Since we compress into memory, storage is the same as fixed-sized
        // values, but we need to mark it as being boolean compressed.
        return uncompressedFlushBuffer;
    }
    case PhysicalTypeID::STRING:
    case PhysicalTypeID::JSON:
    case PhysicalTypeID::INT64:
    case PhysicalTypeID::INT32:
    case PhysicalTypeID::INT16:
    case PhysicalTypeID::INT8:
    case PhysicalTypeID::INTERNAL_ID:
    case PhysicalTypeID::ARRAY:
    case PhysicalTypeID::LIST:
    case PhysicalTypeID::UINT64:
    case PhysicalTypeID::UINT32:
    case PhysicalTypeID::UINT16:
    case PhysicalTypeID::UINT8:
    case PhysicalTypeID::INT128: {
        return CompressedFlushBuffer(compression, dataType);
    }
    case PhysicalTypeID::DOUBLE: {
        return CompressedFloatFlushBuffer<double>(compression, dataType);
    }
    case PhysicalTypeID::FLOAT: {
        return CompressedFloatFlushBuffer<float>(compression, dataType);
    }
    default: {
        return uncompressedFlushBuffer;
    }
    }
}

void ColumnChunkData::resetToAllNull() {
    DASSERT(residencyState != ResidencyState::ON_DISK);
    if (nullData) {
        nullData->resetToAllNull();
    }
    resetInMemoryStats();
}

void ColumnChunkData::resetToEmpty() {
    DASSERT(residencyState != ResidencyState::ON_DISK);
    if (nullData) {
        nullData->resetToEmpty();
    }
    DASSERT(getBufferSize() == getBufferSize(capacity));
    memset(getData<uint8_t>(), 0x00, getBufferSize());
    numValues = 0;
    resetInMemoryStats();
}

static void updateInMemoryStats(ColumnChunkStats& stats, const ValueVector& values,
    uint64_t offset = 0, uint64_t numValues = std::numeric_limits<uint64_t>::max()) {
    const auto physicalType = values.dataType.getPhysicalType();
    const auto numValuesToCheck = std::min(numValues, values.state->getSelSize());
    stats.update(values, offset, numValuesToCheck, physicalType);
}

static void updateInMemoryStats(ColumnChunkStats& stats, const ColumnChunkData* values,
    uint64_t offset = 0, uint64_t numValues = std::numeric_limits<uint64_t>::max()) {
    const auto physicalType = values->getDataType().getPhysicalType();
    const auto numValuesToCheck = std::min(values->getNumValues(), numValues);
    const auto nullMask = values->getNullMask();
    stats.update(*values, offset, numValuesToCheck, physicalType);
}

MergedColumnChunkStats ColumnChunkData::getMergedColumnChunkStats() const {
    const CompressionMetadata& onDiskMetadata = metadata.compMeta;
    ColumnChunkStats stats = inMemoryStats;
    const auto physicalType = getDataType().getPhysicalType();
    const bool isStorageValueType =
        TypeUtils::visit(physicalType, []<typename T>(T) { return StorageValueType<T>; });
    if (isStorageValueType) {
        stats.update(onDiskMetadata.min, onDiskMetadata.max, physicalType);
    }
    return MergedColumnChunkStats{stats, !nullData || nullData->haveNoNullsGuaranteed(),
        nullData && nullData->haveAllNullsGuaranteed()};
}

void ColumnChunkData::updateStats(const ValueVector* vector, const SelectionView& selView) {
    if (selView.isUnfiltered()) {
        updateInMemoryStats(inMemoryStats, *vector);
    } else {
        TypeUtils::visit(
            getDataType().getPhysicalType(),
            [&]<StorageValueType T>(T) {
                std::optional<T> firstValue;
                // ValueVector::firstNonNull uses the vector's builtin selection vector, not the one
                // passed as an argument
                selView.forEachBreakWhenFalse([&](auto i) {
                    if (vector->isNull(i)) {
                        return true;
                    } else {
                        firstValue = vector->getValue<T>(i);
                        return false;
                    }
                });
                if (!firstValue) {
                    return;
                }
                T min = *firstValue, max = *firstValue;
                auto update = [&](sel_t pos) {
                    const auto val = vector->getValue<T>(pos);
                    if (val < min) {
                        min = val;
                    } else if (val > max) {
                        max = val;
                    }
                };
                if (vector->hasNoNullsGuarantee()) {
                    selView.forEach(update);
                } else {
                    selView.forEach([&](auto pos) {
                        if (!vector->isNull(pos)) {
                            update(pos);
                        }
                    });
                }
                inMemoryStats.update(StorageValue(min), StorageValue(max),
                    getDataType().getPhysicalType());
            },
            []<typename T>(T) { static_assert(!StorageValueType<T>); });
    }
}

void ColumnChunkData::resetInMemoryStats() {
    inMemoryStats.reset();
}

ColumnChunkMetadata ColumnChunkData::getMetadataToFlush() const {
    DASSERT(numValues <= capacity);
    StorageValue minValue = {}, maxValue = {};
    if (capacity > 0) {
        std::optional<NullMask> nullMask;
        if (nullData) {
            nullMask = nullData->getNullMask();
        }
        auto [min, max] =
            getMinMaxStorageValue(getData(), 0 /*offset*/, numValues, dataType.getPhysicalType(),
                nullMask.has_value() ? &*nullMask : nullptr, true /*valueRequiredIfUnsupported*/);
        minValue = min.value_or(StorageValue());
        maxValue = max.value_or(StorageValue());
    }
    DASSERT(getBufferSize() == getBufferSize(capacity));
    return getMetadataFunction(buffer->getBuffer(), numValues, minValue, maxValue);
}

void ColumnChunkData::append(ValueVector* vector, const SelectionView& selView) {
    DASSERT(vector->dataType.getPhysicalType() == dataType.getPhysicalType());
    copyVectorToBuffer(vector, numValues, selView);
    numValues += selView.getSelSize();
    updateStats(vector, selView);
}

void ColumnChunkData::append(const ColumnChunkData* other, offset_t startPosInOtherChunk,
    uint32_t numValuesToAppend) {
    DASSERT(other->dataType.getPhysicalType() == dataType.getPhysicalType());
    if (nullData) {
        DASSERT(nullData->getNumValues() == getNumValues());
        nullData->append(other->nullData.get(), startPosInOtherChunk, numValuesToAppend);
    }
    DASSERT(numValues + numValuesToAppend <= capacity);
    memcpy(getData<uint8_t>() + numValues * numBytesPerValue,
        other->getData<uint8_t>() + startPosInOtherChunk * numBytesPerValue,
        numValuesToAppend * numBytesPerValue);
    numValues += numValuesToAppend;
    updateInMemoryStats(inMemoryStats, other, startPosInOtherChunk, numValuesToAppend);
}

void ColumnChunkData::flush(PageAllocator& pageAllocator) {
    const auto preScanMetadata = getMetadataToFlush();
    auto allocatedEntry = pageAllocator.allocatePageRange(preScanMetadata.getNumPages());
    const auto flushedMetadata = flushBuffer(pageAllocator, allocatedEntry, preScanMetadata);
    setToOnDisk(flushedMetadata);
    if (nullData) {
        nullData->flush(pageAllocator);
    }
}

// Note: This function is not setting child/null chunk data recursively.
void ColumnChunkData::setToOnDisk(const ColumnChunkMetadata& otherMetadata) {
    residencyState = ResidencyState::ON_DISK;
    capacity = 0;
    // Note: We don't need to set the buffer to nullptr, as it allows ColumnChunkData to be resized.
    buffer = buffer->getMemoryManager()->allocateBuffer(true, 0 /*size*/);
    this->metadata = otherMetadata;
    this->numValues = otherMetadata.numValues;
    resetInMemoryStats();
}

ColumnChunkMetadata ColumnChunkData::flushBuffer(PageAllocator& pageAllocator,
    const PageRange& entry, const ColumnChunkMetadata& otherMetadata) const {
    const auto bufferSizeToFlush = getBufferSize(numValues);
    if (!otherMetadata.compMeta.isConstant() && bufferSizeToFlush != 0) {
        DASSERT(bufferSizeToFlush <= buffer->getBuffer().size_bytes());
        const auto bufferToFlush = buffer->getBuffer().subspan(0, bufferSizeToFlush);
        return flushBufferFunction(bufferToFlush, pageAllocator.getDataFH(), entry, otherMetadata);
    }
    DASSERT(otherMetadata.getNumPages() == 0);
    return otherMetadata;
}

uint64_t ColumnChunkData::getBufferSize(uint64_t capacity_) const {
    switch (dataType.getLogicalTypeID()) {
    case LogicalTypeID::BOOL: {
        // 8 values per byte, and we need a buffer size which is a
        // multiple of 8 bytes.
        return ceil(capacity_ / 8.0 / 8.0) * 8;
    }
    default: {
        return numBytesPerValue * capacity_;
    }
    }
}

void ColumnChunkData::initializeScanState(SegmentState& state, const Column* column) const {
    if (nullData) {
        DASSERT(state.nullState);
        nullData->initializeScanState(*state.nullState, column->getNullColumn());
    }
    state.column = column;
    if (residencyState == ResidencyState::ON_DISK) {
        state.metadata = metadata;
        state.numValuesPerPage = state.metadata.compMeta.numValues(LBUG_PAGE_SIZE, dataType);

        state.column->populateExtraChunkState(state);
    }
}

void ColumnChunkData::scan(ValueVector& output, offset_t offset, length_t length,
    sel_t posInOutputVector) const {
    DASSERT(offset + length <= numValues);
    if (nullData) {
        nullData->scan(output, offset, length, posInOutputVector);
    }
    memcpy(output.getData() + posInOutputVector * numBytesPerValue,
        getData() + offset * numBytesPerValue, numBytesPerValue * length);
}

void ColumnChunkData::lookup(offset_t offsetInChunk, ValueVector& output,
    sel_t posInOutputVector) const {
    DASSERT(offsetInChunk < capacity);
    output.setNull(posInOutputVector, isNull(offsetInChunk));
    if (!output.isNull(posInOutputVector)) {
        memcpy(output.getData() + posInOutputVector * numBytesPerValue,
            getData() + offsetInChunk * numBytesPerValue, numBytesPerValue);
    }
}

void ColumnChunkData::write(ColumnChunkData* chunk, ColumnChunkData* dstOffsets,
    RelMultiplicity multiplicity) {
    DASSERT(chunk->dataType.getPhysicalType() == dataType.getPhysicalType() &&
            dstOffsets->getDataType().getPhysicalType() == PhysicalTypeID::INTERNAL_ID &&
            chunk->getNumValues() == dstOffsets->getNumValues());
    for (auto i = 0u; i < dstOffsets->getNumValues(); i++) {
        const auto dstOffset = dstOffsets->getValue<offset_t>(i);
        DASSERT(dstOffset < capacity);
        memcpy(getData() + dstOffset * numBytesPerValue, chunk->getData() + i * numBytesPerValue,
            numBytesPerValue);
        numValues = dstOffset >= numValues ? dstOffset + 1 : numValues;
    }
    if (nullData || multiplicity == RelMultiplicity::ONE) {
        for (auto i = 0u; i < dstOffsets->getNumValues(); i++) {
            const auto dstOffset = dstOffsets->getValue<offset_t>(i);
            if (multiplicity == RelMultiplicity::ONE && isNull(dstOffset)) {
                throw CopyException(
                    std::format("Node with offset: {} can only have one neighbour due "
                                "to the MANY-ONE/ONE-ONE relationship constraint.",
                        dstOffset));
            }
            if (nullData) {
                nullData->setNull(dstOffset, chunk->isNull(i));
            }
        }
    }
    updateInMemoryStats(inMemoryStats, chunk);
}

// NOTE: This function is only called in LocalTable right now when
// performing out-of-place committing. LIST has a different logic for
// handling out-of-place committing as it has to be slided. However,
// this is unsafe, as this function can also be used for other purposes
// later. Thus, an assertion is added at the first line.
void ColumnChunkData::write(const ValueVector* vector, offset_t offsetInVector,
    offset_t offsetInChunk) {
    DASSERT(dataType.getPhysicalType() != PhysicalTypeID::BOOL &&
            dataType.getPhysicalType() != PhysicalTypeID::LIST &&
            dataType.getPhysicalType() != PhysicalTypeID::ARRAY);
    if (nullData) {
        nullData->setNull(offsetInChunk, vector->isNull(offsetInVector));
    }
    if (offsetInChunk >= numValues) {
        numValues = offsetInChunk + 1;
    }
    if (!vector->isNull(offsetInVector)) {
        memcpy(getData() + offsetInChunk * numBytesPerValue,
            vector->getData() + offsetInVector * numBytesPerValue, numBytesPerValue);
    }
    static constexpr uint64_t numValuesToWrite = 1;
    updateInMemoryStats(inMemoryStats, *vector, offsetInVector, numValuesToWrite);
}

void ColumnChunkData::write(const ColumnChunkData* srcChunk, offset_t srcOffsetInChunk,
    offset_t dstOffsetInChunk, offset_t numValuesToCopy) {
    DASSERT(srcChunk->dataType.getPhysicalType() == dataType.getPhysicalType());
    if ((dstOffsetInChunk + numValuesToCopy) >= numValues) {
        numValues = dstOffsetInChunk + numValuesToCopy;
    }
    memcpy(getData() + dstOffsetInChunk * numBytesPerValue,
        srcChunk->getData() + srcOffsetInChunk * numBytesPerValue,
        numValuesToCopy * numBytesPerValue);
    if (nullData) {
        DASSERT(srcChunk->getNullData());
        nullData->write(srcChunk->getNullData(), srcOffsetInChunk, dstOffsetInChunk,
            numValuesToCopy);
    }
    updateInMemoryStats(inMemoryStats, srcChunk, srcOffsetInChunk, numValuesToCopy);
}

void ColumnChunkData::resetNumValuesFromMetadata() {
    DASSERT(residencyState == ResidencyState::ON_DISK);
    numValues = metadata.numValues;
    if (nullData) {
        nullData->resetNumValuesFromMetadata();
        // FIXME(bmwinger): not always working
        // DASSERT(numValues == nullData->numValues);
    }
}

void ColumnChunkData::setToInMemory() {
    DASSERT(residencyState == ResidencyState::ON_DISK);
    DASSERT(capacity == 0 && getBufferSize() == 0);
    residencyState = ResidencyState::IN_MEMORY;
    numValues = 0;
    if (nullData) {
        nullData->setToInMemory();
    }
}

void ColumnChunkData::resize(uint64_t newCapacity) {
    const auto numBytesAfterResize = getBufferSize(newCapacity);
    if (numBytesAfterResize > getBufferSize()) {
        auto resizedBuffer = buffer->getMemoryManager()->allocateBuffer(false, numBytesAfterResize);
        auto bufferSize = getBufferSize();
        auto resizedBufferData = resizedBuffer->getBuffer().data();
        memcpy(resizedBufferData, buffer->getBuffer().data(), bufferSize);
        memset(resizedBufferData + bufferSize, 0, numBytesAfterResize - bufferSize);
        buffer = std::move(resizedBuffer);
    }
    if (nullData) {
        nullData->resize(newCapacity);
    }
    if (newCapacity > capacity) {
        capacity = newCapacity;
    }
}

void ColumnChunkData::resizeWithoutPreserve(uint64_t newCapacity) {
    const auto numBytesAfterResize = getBufferSize(newCapacity);
    if (numBytesAfterResize > getBufferSize()) {
        auto resizedBuffer = buffer->getMemoryManager()->allocateBuffer(false, numBytesAfterResize);
        buffer = std::move(resizedBuffer);
    }
    if (nullData) {
        nullData->resize(newCapacity);
    }
    if (newCapacity > capacity) {
        capacity = newCapacity;
    }
}

void ColumnChunkData::populateWithDefaultVal(ExpressionEvaluator& defaultEvaluator,
    uint64_t& numValues_, ColumnStats* newColumnStats) {
    auto numValuesAppended = 0u;
    const auto numValuesToPopulate = numValues_;
    while (numValuesAppended < numValuesToPopulate) {
        const auto numValuesToAppend =
            std::min(DEFAULT_VECTOR_CAPACITY, numValuesToPopulate - numValuesAppended);
        defaultEvaluator.evaluate(numValuesToAppend);
        auto resultVector = defaultEvaluator.resultVector.get();
        DASSERT(resultVector->state->getSelVector().getSelSize() == numValuesToAppend);
        append(resultVector, resultVector->state->getSelVector());
        if (newColumnStats) {
            newColumnStats->update(resultVector);
        }
        numValuesAppended += numValuesToAppend;
    }
}

void ColumnChunkData::copyVectorToBuffer(ValueVector* vector, offset_t startPosInChunk,
    const SelectionView& selView) {
    auto bufferToWrite = buffer->getBuffer().data() + startPosInChunk * numBytesPerValue;
    DASSERT(startPosInChunk + selView.getSelSize() <= capacity);
    const auto vectorDataToWriteFrom = vector->getData();
    if (nullData) {
        nullData->appendNulls(vector, selView, startPosInChunk);
    }
    if (selView.isUnfiltered()) {
        memcpy(bufferToWrite, vectorDataToWriteFrom, selView.getSelSize() * numBytesPerValue);
    } else {
        selView.forEach([&](auto pos) {
            memcpy(bufferToWrite, vectorDataToWriteFrom + pos * numBytesPerValue, numBytesPerValue);
            bufferToWrite += numBytesPerValue;
        });
    }
}

void ColumnChunkData::setNumValues(uint64_t numValues_) {
    DASSERT(numValues_ <= capacity);
    numValues = numValues_;
    if (nullData) {
        nullData->setNumValues(numValues_);
    }
}

bool ColumnChunkData::numValuesSanityCheck() const {
    if (nullData) {
        return numValues == nullData->getNumValues();
    }
    return numValues <= capacity;
}

bool ColumnChunkData::sanityCheck() const {
    if (nullData) {
        return nullData->sanityCheck() && numValuesSanityCheck();
    }
    return numValues <= capacity;
}

uint64_t ColumnChunkData::getEstimatedMemoryUsage() const {
    return buffer->getBuffer().size() + (nullData ? nullData->getEstimatedMemoryUsage() : 0);
}

void ColumnChunkData::serialize(Serializer& serializer) const {
    DASSERT(residencyState == ResidencyState::ON_DISK);
    serializer.writeDebuggingInfo("data_type");
    dataType.serialize(serializer);
    serializer.writeDebuggingInfo("metadata");
    metadata.serialize(serializer);
    serializer.writeDebuggingInfo("enable_compression");
    serializer.write<bool>(enableCompression);
    serializer.writeDebuggingInfo("has_null");
    serializer.write<bool>(nullData != nullptr);
    if (nullData) {
        serializer.writeDebuggingInfo("null_data");
        nullData->serialize(serializer);
    }
}

std::unique_ptr<ColumnChunkData> ColumnChunkData::deserialize(MemoryManager& memoryManager,
    Deserializer& deSer) {
    std::string key;
    ColumnChunkMetadata metadata;
    bool enableCompression = false;
    bool hasNull = false;
    bool initializeToZero = true;
    deSer.validateDebuggingInfo(key, "data_type");
    const auto dataType = LogicalType::deserialize(deSer);
    deSer.validateDebuggingInfo(key, "metadata");
    metadata = decltype(metadata)::deserialize(deSer);
    deSer.validateDebuggingInfo(key, "enable_compression");
    deSer.deserializeValue<bool>(enableCompression);
    deSer.validateDebuggingInfo(key, "has_null");
    deSer.deserializeValue<bool>(hasNull);
    auto chunkData = ColumnChunkFactory::createColumnChunkData(memoryManager, dataType.copy(),
        enableCompression, metadata, hasNull, initializeToZero);
    if (hasNull) {
        deSer.validateDebuggingInfo(key, "null_data");
        chunkData->nullData = NullChunkData::deserialize(memoryManager, deSer);
    }

    switch (dataType.getPhysicalType()) {
    case PhysicalTypeID::STRUCT: {
        StructChunkData::deserialize(deSer, *chunkData);
    } break;
    case PhysicalTypeID::STRING:
    case PhysicalTypeID::JSON: {
        StringChunkData::deserialize(deSer, *chunkData);
    } break;
    case PhysicalTypeID::ARRAY:
    case PhysicalTypeID::LIST: {
        ListChunkData::deserialize(deSer, *chunkData);
    } break;
    default: {
        // DO NOTHING.
    }
    }

    return chunkData;
}

void BoolChunkData::append(ValueVector* vector, const SelectionView& selView) {
    DASSERT(vector->dataType.getPhysicalType() == PhysicalTypeID::BOOL);
    for (auto i = 0u; i < selView.getSelSize(); i++) {
        const auto pos = selView[i];
        NullMask::setNull(getData<uint64_t>(), numValues + i, vector->getValue<bool>(pos));
    }
    if (nullData) {
        nullData->appendNulls(vector, selView, numValues);
    }
    numValues += selView.getSelSize();
    updateStats(vector, selView);
}

void BoolChunkData::append(const ColumnChunkData* other, offset_t startPosInOtherChunk,
    uint32_t numValuesToAppend) {
    NullMask::copyNullMask(other->getData<uint64_t>(), startPosInOtherChunk, getData<uint64_t>(),
        numValues, numValuesToAppend);
    if (nullData) {
        nullData->append(other->getNullData(), startPosInOtherChunk, numValuesToAppend);
    }
    numValues += numValuesToAppend;
    updateInMemoryStats(inMemoryStats, other, startPosInOtherChunk, numValuesToAppend);
}

void BoolChunkData::scan(ValueVector& output, offset_t offset, length_t length,
    sel_t posInOutputVector) const {
    DASSERT(offset + length <= numValues);
    if (nullData) {
        nullData->scan(output, offset, length, posInOutputVector);
    }
    for (auto i = 0u; i < length; i++) {
        output.setValue<bool>(posInOutputVector + i,
            NullMask::isNull(getData<uint64_t>(), offset + i));
    }
}

void BoolChunkData::lookup(offset_t offsetInChunk, ValueVector& output,
    sel_t posInOutputVector) const {
    DASSERT(offsetInChunk < capacity);
    output.setNull(posInOutputVector, nullData->isNull(offsetInChunk));
    if (!output.isNull(posInOutputVector)) {
        output.setValue<bool>(posInOutputVector,
            NullMask::isNull(getData<uint64_t>(), offsetInChunk));
    }
}

void BoolChunkData::write(ColumnChunkData* chunk, ColumnChunkData* dstOffsets, RelMultiplicity) {
    DASSERT(chunk->getDataType().getPhysicalType() == PhysicalTypeID::BOOL &&
            dstOffsets->getDataType().getPhysicalType() == PhysicalTypeID::INTERNAL_ID &&
            chunk->getNumValues() == dstOffsets->getNumValues());
    for (auto i = 0u; i < dstOffsets->getNumValues(); i++) {
        const auto dstOffset = dstOffsets->getValue<offset_t>(i);
        DASSERT(dstOffset < capacity);
        NullMask::setNull(getData<uint64_t>(), dstOffset, chunk->getValue<bool>(i));
        if (nullData) {
            nullData->setNull(dstOffset, chunk->getNullData()->isNull(i));
        }
        numValues = dstOffset >= numValues ? dstOffset + 1 : numValues;
    }
    updateInMemoryStats(inMemoryStats, chunk);
}

void BoolChunkData::write(const ValueVector* vector, offset_t offsetInVector,
    offset_t offsetInChunk) {
    DASSERT(vector->dataType.getPhysicalType() == PhysicalTypeID::BOOL);
    DASSERT(offsetInChunk < capacity);
    const auto valueToSet = vector->getValue<bool>(offsetInVector);
    setValue(valueToSet, offsetInChunk);
    if (nullData) {
        nullData->write(vector, offsetInVector, offsetInChunk);
    }
    numValues = offsetInChunk >= numValues ? offsetInChunk + 1 : numValues;
    if (!vector->isNull(offsetInVector)) {
        inMemoryStats.update(StorageValue{valueToSet}, dataType.getPhysicalType());
    }
}

void BoolChunkData::write(const ColumnChunkData* srcChunk, offset_t srcOffsetInChunk,
    offset_t dstOffsetInChunk, offset_t numValuesToCopy) {
    if (nullData) {
        nullData->write(srcChunk->getNullData(), srcOffsetInChunk, dstOffsetInChunk,
            numValuesToCopy);
    }
    if ((dstOffsetInChunk + numValuesToCopy) >= numValues) {
        numValues = dstOffsetInChunk + numValuesToCopy;
    }
    NullMask::copyNullMask(srcChunk->getData<uint64_t>(), srcOffsetInChunk, getData<uint64_t>(),
        dstOffsetInChunk, numValuesToCopy);
    updateInMemoryStats(inMemoryStats, srcChunk, srcOffsetInChunk, numValuesToCopy);
}

NullMask NullChunkData::getNullMask() const {
    return NullMask(
        std::span(getData<uint64_t>(), ceilDiv(capacity, NullMask::NUM_BITS_PER_NULL_ENTRY)),
        !noNullsGuaranteedInMem());
}

void NullChunkData::setNull(offset_t pos, bool isNull) {
    setValue(isNull, pos);
    // TODO(Guodong): Better let NullChunkData also support `append` a
    // vector.
}

void NullChunkData::write(const ValueVector* vector, offset_t offsetInVector,
    offset_t offsetInChunk) {
    const bool isNull = vector->isNull(offsetInVector);
    setValue(isNull, offsetInChunk);
}

void NullChunkData::write(const ColumnChunkData* srcChunk, offset_t srcOffsetInChunk,
    offset_t dstOffsetInChunk, offset_t numValuesToCopy) {
    if (numValuesToCopy == 0) {
        return;
    }
    DASSERT(srcChunk->getBufferSize() >= sizeof(uint64_t));
    copyFromBuffer(srcChunk->getData<uint64_t>(), srcOffsetInChunk, dstOffsetInChunk,
        numValuesToCopy);
}

void NullChunkData::append(const ColumnChunkData* other, offset_t startOffsetInOtherChunk,
    uint32_t numValuesToAppend) {
    write(other, startOffsetInOtherChunk, numValues, numValuesToAppend);
}

bool NullChunkData::haveNoNullsGuaranteed() const {
    return noNullsGuaranteedInMem() && !metadata.compMeta.max.get<bool>();
}

bool NullChunkData::haveAllNullsGuaranteed() const {
    return allNullsGuaranteedInMem() && metadata.compMeta.min.get<bool>();
}

void NullChunkData::serialize(Serializer& serializer) const {
    DASSERT(residencyState == ResidencyState::ON_DISK);
    serializer.writeDebuggingInfo("null_chunk_metadata");
    metadata.serialize(serializer);
}

std::unique_ptr<NullChunkData> NullChunkData::deserialize(MemoryManager& memoryManager,
    Deserializer& deSer) {
    std::string key;
    ColumnChunkMetadata metadata;
    deSer.validateDebuggingInfo(key, "null_chunk_metadata");
    metadata = decltype(metadata)::deserialize(deSer);
    // TODO: FIX-ME. enableCompression.
    return std::make_unique<NullChunkData>(memoryManager, true, metadata);
}

void NullChunkData::scan(ValueVector& output, offset_t offset, length_t length,
    sel_t posInOutputVector) const {
    output.setNullFromBits(getNullMask().getData(), offset, posInOutputVector, length);
}

void NullChunkData::appendNulls(const ValueVector* vector, const SelectionView& selView,
    offset_t startPosInChunk) {
    if (selView.isUnfiltered()) {
        copyFromBuffer(vector->getNullMask().getData(), 0, startPosInChunk, selView.getSelSize());
    } else {
        for (auto i = 0u; i < selView.getSelSize(); i++) {
            const auto pos = selView[i];
            setNull(startPosInChunk + i, vector->isNull(pos));
        }
    }
}

void InternalIDChunkData::append(ValueVector* vector, const SelectionView& selView) {
    switch (vector->dataType.getPhysicalType()) {
    case PhysicalTypeID::INTERNAL_ID: {
        copyVectorToBuffer(vector, numValues, selView);
    } break;
    case PhysicalTypeID::INT64: {
        copyInt64VectorToBuffer(vector, numValues, selView);
    } break;
    default: {
        UNREACHABLE_CODE;
    }
    }
    numValues += selView.getSelSize();
}

void InternalIDChunkData::copyVectorToBuffer(ValueVector* vector, offset_t startPosInChunk,
    const SelectionView& selView) {
    DASSERT(vector->dataType.getPhysicalType() == PhysicalTypeID::INTERNAL_ID);
    const auto relIDsInVector = reinterpret_cast<internalID_t*>(vector->getData());
    if (commonTableID == INVALID_TABLE_ID) {
        commonTableID = relIDsInVector[selView[0]].tableID;
    }
    for (auto i = 0u; i < selView.getSelSize(); i++) {
        const auto pos = selView[i];
        if (vector->isNull(pos)) {
            continue;
        }
        DASSERT(relIDsInVector[pos].tableID == commonTableID);
        memcpy(getData() + (startPosInChunk + i) * numBytesPerValue, &relIDsInVector[pos].offset,
            numBytesPerValue);
    }
}

void InternalIDChunkData::copyInt64VectorToBuffer(ValueVector* vector, offset_t startPosInChunk,
    const SelectionView& selView) const {
    DASSERT(vector->dataType.getPhysicalType() == PhysicalTypeID::INT64);
    for (auto i = 0u; i < selView.getSelSize(); i++) {
        const auto pos = selView[i];
        if (vector->isNull(pos)) {
            continue;
        }
        memcpy(getData() + (startPosInChunk + i) * numBytesPerValue,
            &vector->getValue<offset_t>(pos), numBytesPerValue);
    }
}

void InternalIDChunkData::scan(ValueVector& output, offset_t offset, length_t length,
    sel_t posInOutputVector) const {
    DASSERT(offset + length <= numValues);
    DASSERT(commonTableID != INVALID_TABLE_ID);
    internalID_t relID;
    relID.tableID = commonTableID;
    for (auto i = 0u; i < length; i++) {
        relID.offset = getValue<offset_t>(offset + i);
        output.setValue<internalID_t>(posInOutputVector + i, relID);
    }
}

void InternalIDChunkData::lookup(offset_t offsetInChunk, ValueVector& output,
    sel_t posInOutputVector) const {
    DASSERT(offsetInChunk < capacity);
    internalID_t relID;
    relID.offset = getValue<offset_t>(offsetInChunk);
    DASSERT(commonTableID != INVALID_TABLE_ID);
    relID.tableID = commonTableID;
    output.setValue<internalID_t>(posInOutputVector, relID);
}

void InternalIDChunkData::write(const ValueVector* vector, offset_t offsetInVector,
    offset_t offsetInChunk) {
    DASSERT(vector->dataType.getPhysicalType() == PhysicalTypeID::INTERNAL_ID);
    const auto relIDsInVector = reinterpret_cast<internalID_t*>(vector->getData());
    if (commonTableID == INVALID_TABLE_ID) {
        commonTableID = relIDsInVector[offsetInVector].tableID;
    }
    DASSERT(commonTableID == relIDsInVector[offsetInVector].tableID);
    if (!vector->isNull(offsetInVector)) {
        memcpy(getData() + offsetInChunk * numBytesPerValue, &relIDsInVector[offsetInVector].offset,
            numBytesPerValue);
    }
    if (offsetInChunk >= numValues) {
        numValues = offsetInChunk + 1;
    }
}

void InternalIDChunkData::append(const ColumnChunkData* other, offset_t startPosInOtherChunk,
    uint32_t numValuesToAppend) {
    ColumnChunkData::append(other, startPosInOtherChunk, numValuesToAppend);
    commonTableID = other->cast<InternalIDChunkData>().commonTableID;
}

std::optional<NullMask> ColumnChunkData::getNullMask() const {
    return nullData ? std::optional(nullData->getNullMask()) : std::nullopt;
}

std::unique_ptr<ColumnChunkData> ColumnChunkFactory::createColumnChunkData(MemoryManager& mm,
    LogicalType dataType, bool enableCompression, uint64_t capacity, ResidencyState residencyState,
    bool hasNullData, bool initializeToZero) {
    switch (dataType.getPhysicalType()) {
    case PhysicalTypeID::BOOL: {
        return std::make_unique<BoolChunkData>(mm, capacity, enableCompression, residencyState,
            hasNullData);
    }
    case PhysicalTypeID::INT64:
    case PhysicalTypeID::INT32:
    case PhysicalTypeID::INT16:
    case PhysicalTypeID::INT8:
    case PhysicalTypeID::UINT64:
    case PhysicalTypeID::UINT32:
    case PhysicalTypeID::UINT16:
    case PhysicalTypeID::UINT8:
    case PhysicalTypeID::INT128:
    case PhysicalTypeID::UINT128:
    case PhysicalTypeID::DOUBLE:
    case PhysicalTypeID::FLOAT:
    case PhysicalTypeID::INTERVAL: {
        return std::make_unique<ColumnChunkData>(mm, std::move(dataType), capacity,
            enableCompression, residencyState, hasNullData, initializeToZero);
    }
    case PhysicalTypeID::INTERNAL_ID: {
        return std::make_unique<InternalIDChunkData>(mm, capacity, enableCompression,
            residencyState);
    }
    case PhysicalTypeID::STRING:
    case PhysicalTypeID::JSON: {
        return std::make_unique<StringChunkData>(mm, std::move(dataType), capacity,
            enableCompression, residencyState);
    }
    case PhysicalTypeID::ARRAY:
    case PhysicalTypeID::LIST: {
        return std::make_unique<ListChunkData>(mm, std::move(dataType), capacity, enableCompression,
            residencyState);
    }
    case PhysicalTypeID::STRUCT: {
        return std::make_unique<StructChunkData>(mm, std::move(dataType), capacity,
            enableCompression, residencyState);
    }
    default:
        UNREACHABLE_CODE;
    }
}

std::unique_ptr<ColumnChunkData> ColumnChunkFactory::createColumnChunkData(MemoryManager& mm,
    LogicalType dataType, bool enableCompression, ColumnChunkMetadata& metadata, bool hasNullData,
    bool initializeToZero) {
    switch (dataType.getPhysicalType()) {
    case PhysicalTypeID::BOOL: {
        return std::make_unique<BoolChunkData>(mm, enableCompression, metadata, hasNullData);
    }
    case PhysicalTypeID::INT64:
    case PhysicalTypeID::INT32:
    case PhysicalTypeID::INT16:
    case PhysicalTypeID::INT8:
    case PhysicalTypeID::UINT64:
    case PhysicalTypeID::UINT32:
    case PhysicalTypeID::UINT16:
    case PhysicalTypeID::UINT8:
    case PhysicalTypeID::INT128:
    case PhysicalTypeID::UINT128:
    case PhysicalTypeID::DOUBLE:
    case PhysicalTypeID::FLOAT:
    case PhysicalTypeID::INTERVAL: {
        return std::make_unique<ColumnChunkData>(mm, std::move(dataType), enableCompression,
            metadata, hasNullData, initializeToZero);
    }
        // Physically, we only materialize offset of INTERNAL_ID, which is same as INT64,
    case PhysicalTypeID::INTERNAL_ID: {
        // INTERNAL_ID should never have nulls.
        return std::make_unique<InternalIDChunkData>(mm, enableCompression, metadata);
    }
    case PhysicalTypeID::STRING:
    case PhysicalTypeID::JSON: {
        return std::make_unique<StringChunkData>(mm, std::move(dataType), enableCompression,
            metadata);
    }
    case PhysicalTypeID::ARRAY:
    case PhysicalTypeID::LIST: {
        return std::make_unique<ListChunkData>(mm, std::move(dataType), enableCompression,
            metadata);
    }
    case PhysicalTypeID::STRUCT: {
        return std::make_unique<StructChunkData>(mm, std::move(dataType), enableCompression,
            metadata);
    }
    default:
        UNREACHABLE_CODE;
    }
}

bool ColumnChunkData::isNull(offset_t pos) const {
    return nullData && nullData->isNull(pos);
}

MemoryManager& ColumnChunkData::getMemoryManager() const {
    return *buffer->getMemoryManager();
}

uint8_t* ColumnChunkData::getData() const {
    return buffer->getBuffer().data();
}
uint64_t ColumnChunkData::getBufferSize() const {
    return buffer->getBuffer().size_bytes();
}

void ColumnChunkData::loadFromDisk() {
    buffer->getMemoryManager()->getBufferManager()->getSpillerOrSkip(
        [&](auto& spiller) { spiller.loadFromDisk(*this); });
}

SpillResult ColumnChunkData::spillToDisk() {
    SpillResult spilled{};
    buffer->getMemoryManager()->getBufferManager()->getSpillerOrSkip(
        [&](auto& spiller) { spilled = spiller.spillToDisk(*this); });
    return spilled;
}

void ColumnChunkData::reclaimStorage(PageAllocator& pageAllocator) {
    if (nullData) {
        nullData->reclaimStorage(pageAllocator);
    }
    if (residencyState == ResidencyState::ON_DISK) {
        if (metadata.getStartPageIdx() != INVALID_PAGE_IDX) {
            pageAllocator.freePageRange(metadata.pageRange);
        }
    }
}

uint64_t ColumnChunkData::getSizeOnDisk() const {
    // Probably could just return the actual size from the metadata if it's on-disk, but it's not
    // currently needed for on-disk segments
    DASSERT(ResidencyState::IN_MEMORY == residencyState);
    auto metadata = getMetadataToFlush();
    uint64_t nullSize = 0;
    if (nullData) {
        nullSize = nullData->getSizeOnDisk();
    }
    return metadata.getNumDataPages(dataType.getPhysicalType()) * common::LBUG_PAGE_SIZE + nullSize;
}

uint64_t ColumnChunkData::getSizeOnDiskInMemoryStats() const {
    // Probably could just return the actual size from the metadata if it's on-disk, but it's not
    // currently needed for on-disk segments
    DASSERT(ResidencyState::IN_MEMORY == residencyState);
    uint64_t nullSize = 0;
    if (nullData) {
        nullSize = nullData->getSizeOnDiskInMemoryStats();
    }
    auto metadata = getMetadataFunction(buffer->getBuffer(), numValues,
        inMemoryStats.min.value_or(StorageValue{}), inMemoryStats.max.value_or(StorageValue{}));
    return metadata.getNumDataPages(dataType.getPhysicalType()) * common::LBUG_PAGE_SIZE + nullSize;
}

std::vector<std::unique_ptr<ColumnChunkData>> ColumnChunkData::split(bool targetMaxSize) const {
    // FIXME(bmwinger): we either need to split recursively, or detect individual values which bring
    // the size above MAX_SEGMENT_SIZE, since this will still sometimes produce segments larger than
    // MAX_SEGMENT_SIZE
    auto maxSegmentSize = std::max(getMinimumSizeOnDisk(), common::StorageConfig::MAX_SEGMENT_SIZE);
    auto targetSize =
        targetMaxSize ? maxSegmentSize : std::min(getSizeOnDisk() / 2, maxSegmentSize);
    std::vector<std::unique_ptr<ColumnChunkData>> newSegments;
    uint64_t pos = 0;
    const uint64_t chunkSize = 64;
    uint64_t initialCapacity = std::min(chunkSize, numValues);
    while (pos < numValues) {
        std::unique_ptr<ColumnChunkData> newSegment =
            ColumnChunkFactory::createColumnChunkData(getMemoryManager(), getDataType().copy(),
                isCompressionEnabled(), initialCapacity, ResidencyState::IN_MEMORY, hasNullData());

        while (pos < numValues && newSegment->getSizeOnDiskInMemoryStats() <= targetSize) {
            if (newSegment->getNumValues() == newSegment->getCapacity()) {
                newSegment->resize(newSegment->getCapacity() * 2);
            }
            auto numValuesToAppendInChunk = std::min(numValues - pos, chunkSize);
            newSegment->append(this, pos, numValuesToAppendInChunk);
            pos += numValuesToAppendInChunk;
        }
        if (pos < numValues && newSegment->getNumValues() > chunkSize) {
            // Size exceeded target size, so we should drop the last batch added (unless they are
            // the only values)
            pos -= chunkSize;
            newSegment->truncate(newSegment->getNumValues() - chunkSize);
        }
        newSegments.push_back(std::move(newSegment));
    }
    return newSegments;
}

void ColumnChunkData::setNullData(std::unique_ptr<NullChunkData> nullData_) {
    nullData = std::move(nullData_);
}

std::unique_ptr<NullChunkData> ColumnChunkData::moveNullData() {
    return std::move(nullData);
}

ColumnChunkData::~ColumnChunkData() = default;

uint64_t ColumnChunkData::getMinimumSizeOnDisk() const {
    if (hasNullData() && nullData->getSizeOnDisk() > 0) {
        return 2 * LBUG_PAGE_SIZE;
    }
    return LBUG_PAGE_SIZE;
}

} // namespace storage
} // namespace lbug