-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmanifest.py
More file actions
1399 lines (1204 loc) · 49.8 KB
/
manifest.py
File metadata and controls
1399 lines (1204 loc) · 49.8 KB
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import math
import threading
from abc import ABC, abstractmethod
from collections.abc import Iterator
from copy import copy
from enum import Enum
from types import TracebackType
from typing import (
Any,
Literal,
)
from cachetools import LRUCache
from pydantic_core import to_json
from pyiceberg.avro.codecs import AVRO_CODEC_KEY, AvroCompressionCodec
from pyiceberg.avro.file import AvroFile, AvroOutputFile
from pyiceberg.conversions import to_bytes
from pyiceberg.exceptions import ValidationError
from pyiceberg.io import FileIO, InputFile, OutputFile
from pyiceberg.observability import perf_timer
from pyiceberg.partitioning import PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.typedef import Record, TableVersion
from pyiceberg.types import (
BinaryType,
BooleanType,
IntegerType,
ListType,
LongType,
MapType,
NestedField,
PrimitiveType,
StringType,
StructType,
)
UNASSIGNED_SEQ = -1
DEFAULT_BLOCK_SIZE = 67108864 # 64 * 1024 * 1024
DEFAULT_READ_VERSION: Literal[2] = 2
INITIAL_SEQUENCE_NUMBER = 0
class DataFileContent(int, Enum):
DATA = 0
POSITION_DELETES = 1
EQUALITY_DELETES = 2
def __repr__(self) -> str:
"""Return the string representation of the DataFileContent class."""
return f"DataFileContent.{self.name}"
@staticmethod
def from_rest_type(content_type: str) -> DataFileContent:
"""Convert REST API content type string to DataFileContent.
Args:
content_type: REST API content type.
Returns:
The corresponding DataFileContent enum value.
Raises:
ValueError: If the content type is unknown.
"""
mapping = {
"data": DataFileContent.DATA,
"position-deletes": DataFileContent.POSITION_DELETES,
"equality-deletes": DataFileContent.EQUALITY_DELETES,
}
if content_type not in mapping:
raise ValueError(f"Invalid file content value: {content_type}")
return mapping[content_type]
class ManifestContent(int, Enum):
DATA = 0
DELETES = 1
def __repr__(self) -> str:
"""Return the string representation of the ManifestContent class."""
return f"ManifestContent.{self.name}"
class ManifestEntryStatus(int, Enum):
EXISTING = 0
ADDED = 1
DELETED = 2
def __repr__(self) -> str:
"""Return the string representation of the ManifestEntryStatus class."""
return f"ManifestEntryStatus.{self.name}"
class FileFormat(str, Enum):
AVRO = "AVRO"
PARQUET = "PARQUET"
ORC = "ORC"
PUFFIN = "PUFFIN"
@classmethod
def _missing_(cls, value: object) -> None | str:
for member in cls:
if member.value == str(value).upper():
return member
return None
def __repr__(self) -> str:
"""Return the string representation of the FileFormat class."""
return f"FileFormat.{self.name}"
DATA_FILE_TYPE: dict[int, StructType] = {
1: StructType(
NestedField(field_id=100, name="file_path", field_type=StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(
field_id=101,
name="file_format",
field_type=StringType(),
required=True,
doc="File format name: avro, orc, or parquet",
),
NestedField(
field_id=102,
name="partition",
field_type=StructType(),
required=True,
doc="Partition data tuple, schema based on the partition spec",
),
NestedField(field_id=103, name="record_count", field_type=LongType(), required=True, doc="Number of records in the file"),
NestedField(
field_id=104, name="file_size_in_bytes", field_type=LongType(), required=True, doc="Total file size in bytes"
),
NestedField(
field_id=105,
name="block_size_in_bytes",
field_type=LongType(),
required=True,
doc="Deprecated. Always write a default in v1. Do not write in v2.",
write_default=DEFAULT_BLOCK_SIZE,
),
NestedField(
field_id=108,
name="column_sizes",
field_type=MapType(key_id=117, key_type=IntegerType(), value_id=118, value_type=LongType()),
required=False,
doc="Map of column id to total size on disk",
),
NestedField(
field_id=109,
name="value_counts",
field_type=MapType(key_id=119, key_type=IntegerType(), value_id=120, value_type=LongType()),
required=False,
doc="Map of column id to total count, including null and NaN",
),
NestedField(
field_id=110,
name="null_value_counts",
field_type=MapType(key_id=121, key_type=IntegerType(), value_id=122, value_type=LongType()),
required=False,
doc="Map of column id to null value count",
),
NestedField(
field_id=137,
name="nan_value_counts",
field_type=MapType(key_id=138, key_type=IntegerType(), value_id=139, value_type=LongType()),
required=False,
doc="Map of column id to number of NaN values in the column",
),
NestedField(
field_id=125,
name="lower_bounds",
field_type=MapType(key_id=126, key_type=IntegerType(), value_id=127, value_type=BinaryType()),
required=False,
doc="Map of column id to lower bound",
),
NestedField(
field_id=128,
name="upper_bounds",
field_type=MapType(key_id=129, key_type=IntegerType(), value_id=130, value_type=BinaryType()),
required=False,
doc="Map of column id to upper bound",
),
NestedField(
field_id=131, name="key_metadata", field_type=BinaryType(), required=False, doc="Encryption key metadata blob"
),
NestedField(
field_id=132,
name="split_offsets",
field_type=ListType(element_id=133, element_type=LongType(), element_required=True),
required=False,
doc="Splittable offsets",
),
NestedField(field_id=140, name="sort_order_id", field_type=IntegerType(), required=False, doc="Sort order ID"),
),
2: StructType(
NestedField(
field_id=134,
name="content",
field_type=IntegerType(),
required=True,
doc="File format name: avro, orc, or parquet",
initial_default=DataFileContent.DATA,
),
NestedField(field_id=100, name="file_path", field_type=StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(
field_id=101,
name="file_format",
field_type=StringType(),
required=True,
doc="File format name: avro, orc, or parquet",
),
NestedField(
field_id=102,
name="partition",
field_type=StructType(),
required=True,
doc="Partition data tuple, schema based on the partition spec",
),
NestedField(field_id=103, name="record_count", field_type=LongType(), required=True, doc="Number of records in the file"),
NestedField(
field_id=104, name="file_size_in_bytes", field_type=LongType(), required=True, doc="Total file size in bytes"
),
NestedField(
field_id=108,
name="column_sizes",
field_type=MapType(key_id=117, key_type=IntegerType(), value_id=118, value_type=LongType()),
required=False,
doc="Map of column id to total size on disk",
),
NestedField(
field_id=109,
name="value_counts",
field_type=MapType(key_id=119, key_type=IntegerType(), value_id=120, value_type=LongType()),
required=False,
doc="Map of column id to total count, including null and NaN",
),
NestedField(
field_id=110,
name="null_value_counts",
field_type=MapType(key_id=121, key_type=IntegerType(), value_id=122, value_type=LongType()),
required=False,
doc="Map of column id to null value count",
),
NestedField(
field_id=137,
name="nan_value_counts",
field_type=MapType(key_id=138, key_type=IntegerType(), value_id=139, value_type=LongType()),
required=False,
doc="Map of column id to number of NaN values in the column",
),
NestedField(
field_id=125,
name="lower_bounds",
field_type=MapType(key_id=126, key_type=IntegerType(), value_id=127, value_type=BinaryType()),
required=False,
doc="Map of column id to lower bound",
),
NestedField(
field_id=128,
name="upper_bounds",
field_type=MapType(key_id=129, key_type=IntegerType(), value_id=130, value_type=BinaryType()),
required=False,
doc="Map of column id to upper bound",
),
NestedField(
field_id=131, name="key_metadata", field_type=BinaryType(), required=False, doc="Encryption key metadata blob"
),
NestedField(
field_id=132,
name="split_offsets",
field_type=ListType(element_id=133, element_type=LongType(), element_required=True),
required=False,
doc="Splittable offsets",
),
NestedField(
field_id=135,
name="equality_ids",
field_type=ListType(element_id=136, element_type=LongType(), element_required=True),
required=False,
doc="Field ids used to determine row equality in equality delete files.",
),
NestedField(
field_id=140,
name="sort_order_id",
field_type=IntegerType(),
required=False,
doc="ID representing sort order for this file",
),
),
3: StructType(
NestedField(
field_id=134,
name="content",
field_type=IntegerType(),
required=True,
doc="File format name: avro, orc, or parquet",
initial_default=DataFileContent.DATA,
),
NestedField(field_id=100, name="file_path", field_type=StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(
field_id=101,
name="file_format",
field_type=StringType(),
required=True,
doc="File format name: avro, orc, or parquet",
),
NestedField(
field_id=102,
name="partition",
field_type=StructType(),
required=True,
doc="Partition data tuple, schema based on the partition spec",
),
NestedField(field_id=103, name="record_count", field_type=LongType(), required=True, doc="Number of records in the file"),
NestedField(
field_id=104, name="file_size_in_bytes", field_type=LongType(), required=True, doc="Total file size in bytes"
),
NestedField(
field_id=108,
name="column_sizes",
field_type=MapType(key_id=117, key_type=IntegerType(), value_id=118, value_type=LongType()),
required=False,
doc="Map of column id to total size on disk",
),
NestedField(
field_id=109,
name="value_counts",
field_type=MapType(key_id=119, key_type=IntegerType(), value_id=120, value_type=LongType()),
required=False,
doc="Map of column id to total count, including null and NaN",
),
NestedField(
field_id=110,
name="null_value_counts",
field_type=MapType(key_id=121, key_type=IntegerType(), value_id=122, value_type=LongType()),
required=False,
doc="Map of column id to null value count",
),
NestedField(
field_id=137,
name="nan_value_counts",
field_type=MapType(key_id=138, key_type=IntegerType(), value_id=139, value_type=LongType()),
required=False,
doc="Map of column id to number of NaN values in the column",
),
NestedField(
field_id=125,
name="lower_bounds",
field_type=MapType(key_id=126, key_type=IntegerType(), value_id=127, value_type=BinaryType()),
required=False,
doc="Map of column id to lower bound",
),
NestedField(
field_id=128,
name="upper_bounds",
field_type=MapType(key_id=129, key_type=IntegerType(), value_id=130, value_type=BinaryType()),
required=False,
doc="Map of column id to upper bound",
),
NestedField(
field_id=131, name="key_metadata", field_type=BinaryType(), required=False, doc="Encryption key metadata blob"
),
NestedField(
field_id=132,
name="split_offsets",
field_type=ListType(element_id=133, element_type=LongType(), element_required=True),
required=False,
doc="Splittable offsets",
),
NestedField(
field_id=135,
name="equality_ids",
field_type=ListType(element_id=136, element_type=LongType(), element_required=True),
required=False,
doc="Field ids used to determine row equality in equality delete files.",
),
NestedField(
field_id=140,
name="sort_order_id",
field_type=IntegerType(),
required=False,
doc="ID representing sort order for this file",
),
NestedField(
field_id=142,
name="first_row_id",
field_type=LongType(),
required=False,
doc="The _row_id for the first row in the data file.",
),
NestedField(
field_id=143,
name="referenced_data_file",
field_type=StringType(),
required=False,
doc="Fully qualified location (URI with FS scheme) of a data file that all deletes reference",
),
NestedField(
field_id=144,
name="content_offset",
field_type=LongType(),
required=False,
doc="The offset in the file where the content starts.",
),
NestedField(
field_id=145,
name="content_size_in_bytes",
field_type=LongType(),
required=False,
doc="The length of a referenced content stored in the file; required if content_offset is present",
),
),
}
def data_file_with_partition(partition_type: StructType, format_version: TableVersion) -> StructType:
data_file_partition_type = StructType(
*[
NestedField(
field_id=field.field_id,
name=field.name,
field_type=field.field_type,
required=field.required,
)
for field in partition_type.fields
]
)
return StructType(
*[
NestedField(
field_id=102,
name="partition",
field_type=data_file_partition_type,
required=True,
doc="Partition data tuple, schema based on the partition spec",
)
if field.field_id == 102
else field
for field in DATA_FILE_TYPE[format_version].fields
]
)
class DataFile(Record):
@classmethod
def from_args(cls, _table_format_version: TableVersion = DEFAULT_READ_VERSION, **arguments: Any) -> DataFile:
struct = DATA_FILE_TYPE[_table_format_version]
return super()._bind(struct, **arguments)
@property
def content(self) -> DataFileContent:
return self._data[0]
@property
def file_path(self) -> str:
return self._data[1]
@property
def file_format(self) -> FileFormat:
return self._data[2]
@property
def partition(self) -> Record:
return self._data[3]
@property
def record_count(self) -> int:
return self._data[4]
@property
def file_size_in_bytes(self) -> int:
return self._data[5]
@property
def column_sizes(self) -> dict[int, int]:
return self._data[6]
@property
def value_counts(self) -> dict[int, int]:
return self._data[7]
@property
def null_value_counts(self) -> dict[int, int]:
return self._data[8]
@property
def nan_value_counts(self) -> dict[int, int]:
return self._data[9]
@property
def lower_bounds(self) -> dict[int, bytes]:
return self._data[10]
@property
def upper_bounds(self) -> dict[int, bytes]:
return self._data[11]
@property
def key_metadata(self) -> bytes | None:
return self._data[12]
@property
def split_offsets(self) -> list[int] | None:
return self._data[13]
@property
def equality_ids(self) -> list[int] | None:
return self._data[14]
@property
def sort_order_id(self) -> int | None:
return self._data[15]
# Spec ID should not be stored in the file
_spec_id: int
@property
def spec_id(self) -> int:
return self._spec_id
@spec_id.setter
def spec_id(self, value: int) -> None:
self._spec_id = value
def __setattr__(self, name: str, value: Any) -> None:
"""Assign a key/value to a DataFile."""
# The file_format is written as a string, so we need to cast it to the Enum
if name == "file_format":
value = FileFormat[value]
super().__setattr__(name, value)
def __hash__(self) -> int:
"""Return the hash of the file path."""
return hash(self.file_path)
def __eq__(self, other: Any) -> bool:
"""Compare the datafile with another object.
If it is a datafile, it will compare based on the file_path.
"""
return self.file_path == other.file_path if isinstance(other, DataFile) else False
MANIFEST_ENTRY_SCHEMAS = {
1: Schema(
NestedField(0, "status", IntegerType(), required=True),
NestedField(1, "snapshot_id", LongType(), required=True),
NestedField(2, "data_file", DATA_FILE_TYPE[1], required=True),
),
2: Schema(
NestedField(0, "status", IntegerType(), required=True),
NestedField(1, "snapshot_id", LongType(), required=False),
NestedField(3, "sequence_number", LongType(), required=False),
NestedField(4, "file_sequence_number", LongType(), required=False),
NestedField(2, "data_file", DATA_FILE_TYPE[2], required=True),
),
3: Schema(
NestedField(0, "status", IntegerType(), required=True),
NestedField(1, "snapshot_id", LongType(), required=False),
NestedField(3, "sequence_number", LongType(), required=False),
NestedField(4, "file_sequence_number", LongType(), required=False),
NestedField(2, "data_file", DATA_FILE_TYPE[3], required=True),
),
}
MANIFEST_ENTRY_SCHEMAS_STRUCT = {format_version: schema.as_struct() for format_version, schema in MANIFEST_ENTRY_SCHEMAS.items()}
def manifest_entry_schema_with_data_file(format_version: TableVersion, data_file: StructType) -> Schema:
return Schema(
*[
NestedField(2, "data_file", data_file, required=True) if field.field_id == 2 else field
for field in MANIFEST_ENTRY_SCHEMAS[format_version].fields
]
)
class ManifestEntry(Record):
@classmethod
def from_args(cls, _table_format_version: TableVersion = DEFAULT_READ_VERSION, **arguments: Any) -> ManifestEntry:
return super()._bind(**arguments, struct=MANIFEST_ENTRY_SCHEMAS_STRUCT[_table_format_version])
@property
def status(self) -> ManifestEntryStatus:
return self._data[0]
@status.setter
def status(self, value: ManifestEntryStatus) -> None:
self._data[0] = value
@property
def snapshot_id(self) -> int | None:
return self._data[1]
@snapshot_id.setter
def snapshot_id(self, value: int) -> None:
self._data[0] = value
@property
def sequence_number(self) -> int | None:
return self._data[2]
@sequence_number.setter
def sequence_number(self, value: int) -> None:
self._data[2] = value
@property
def file_sequence_number(self) -> int | None:
return self._data[3]
@file_sequence_number.setter
def file_sequence_number(self, value: int) -> None:
self._data[3] = value
@property
def data_file(self) -> DataFile:
return self._data[4]
@data_file.setter
def data_file(self, value: DataFile) -> None:
self._data[4] = value
PARTITION_FIELD_SUMMARY_TYPE = StructType(
NestedField(509, "contains_null", BooleanType(), required=True),
NestedField(518, "contains_nan", BooleanType(), required=False),
NestedField(510, "lower_bound", BinaryType(), required=False),
NestedField(511, "upper_bound", BinaryType(), required=False),
)
class PartitionFieldSummary(Record):
@classmethod
def from_args(cls, **arguments: Any) -> PartitionFieldSummary:
return super()._bind(**arguments, struct=PARTITION_FIELD_SUMMARY_TYPE)
@property
def contains_null(self) -> bool:
return self._data[0]
@property
def contains_nan(self) -> bool | None:
return self._data[1]
@property
def lower_bound(self) -> bytes | None:
return self._data[2]
@property
def upper_bound(self) -> bytes | None:
return self._data[3]
class PartitionFieldStats:
_type: PrimitiveType
_contains_null: bool
_contains_nan: bool
_min: Any | None
_max: Any | None
def __init__(self, iceberg_type: PrimitiveType) -> None:
self._type = iceberg_type
self._contains_null = False
self._contains_nan = False
self._min = None
self._max = None
def to_summary(self) -> PartitionFieldSummary:
return PartitionFieldSummary(
self._contains_null,
self._contains_nan,
to_bytes(self._type, self._min) if self._min is not None else None,
to_bytes(self._type, self._max) if self._max is not None else None,
)
def update(self, value: Any) -> None:
if value is None:
self._contains_null = True
elif isinstance(value, float) and math.isnan(value):
self._contains_nan = True
else:
if self._min is None:
self._min = value
self._max = value
else:
self._max = max(self._max, value)
self._min = min(self._min, value)
def construct_partition_summaries(spec: PartitionSpec, schema: Schema, partitions: list[Record]) -> list[PartitionFieldSummary]:
types = [field.field_type for field in spec.partition_type(schema).fields]
field_stats = [PartitionFieldStats(field_type) for field_type in types]
for partition_keys in partitions:
for i, field_type in enumerate(types):
if not isinstance(field_type, PrimitiveType):
raise ValueError(f"Expected a primitive type for the partition field, got {field_type}")
partition_key = partition_keys[i]
field_stats[i].update(partition_key)
return [field.to_summary() for field in field_stats]
MANIFEST_LIST_FILE_SCHEMAS: dict[int, Schema] = {
1: Schema(
NestedField(500, "manifest_path", StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(501, "manifest_length", LongType(), required=True),
NestedField(502, "partition_spec_id", IntegerType(), required=True),
NestedField(503, "added_snapshot_id", LongType(), required=True),
NestedField(504, "added_files_count", IntegerType(), required=False),
NestedField(505, "existing_files_count", IntegerType(), required=False),
NestedField(506, "deleted_files_count", IntegerType(), required=False),
NestedField(512, "added_rows_count", LongType(), required=False),
NestedField(513, "existing_rows_count", LongType(), required=False),
NestedField(514, "deleted_rows_count", LongType(), required=False),
NestedField(507, "partitions", ListType(508, PARTITION_FIELD_SUMMARY_TYPE, element_required=True), required=False),
NestedField(519, "key_metadata", BinaryType(), required=False),
),
2: Schema(
NestedField(500, "manifest_path", StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(501, "manifest_length", LongType(), required=True),
NestedField(502, "partition_spec_id", IntegerType(), required=True),
NestedField(517, "content", IntegerType(), required=True, initial_default=ManifestContent.DATA),
NestedField(515, "sequence_number", LongType(), required=True, initial_default=0),
NestedField(516, "min_sequence_number", LongType(), required=True, initial_default=0),
NestedField(503, "added_snapshot_id", LongType(), required=True),
NestedField(504, "added_files_count", IntegerType(), required=True),
NestedField(505, "existing_files_count", IntegerType(), required=True),
NestedField(506, "deleted_files_count", IntegerType(), required=True),
NestedField(512, "added_rows_count", LongType(), required=True),
NestedField(513, "existing_rows_count", LongType(), required=True),
NestedField(514, "deleted_rows_count", LongType(), required=True),
NestedField(507, "partitions", ListType(508, PARTITION_FIELD_SUMMARY_TYPE, element_required=True), required=False),
NestedField(519, "key_metadata", BinaryType(), required=False),
),
3: Schema(
NestedField(500, "manifest_path", StringType(), required=True, doc="Location URI with FS scheme"),
NestedField(501, "manifest_length", LongType(), required=True),
NestedField(502, "partition_spec_id", IntegerType(), required=True),
NestedField(517, "content", IntegerType(), required=True, initial_default=ManifestContent.DATA),
NestedField(515, "sequence_number", LongType(), required=True, initial_default=0),
NestedField(516, "min_sequence_number", LongType(), required=True, initial_default=0),
NestedField(503, "added_snapshot_id", LongType(), required=True),
NestedField(504, "added_files_count", IntegerType(), required=True),
NestedField(505, "existing_files_count", IntegerType(), required=True),
NestedField(506, "deleted_files_count", IntegerType(), required=True),
NestedField(512, "added_rows_count", LongType(), required=True),
NestedField(513, "existing_rows_count", LongType(), required=True),
NestedField(514, "deleted_rows_count", LongType(), required=True),
NestedField(507, "partitions", ListType(508, PARTITION_FIELD_SUMMARY_TYPE, element_required=True), required=False),
NestedField(519, "key_metadata", BinaryType(), required=False),
NestedField(520, "first_row_id", LongType(), required=False),
),
}
MANIFEST_LIST_FILE_STRUCTS = {format_version: schema.as_struct() for format_version, schema in MANIFEST_LIST_FILE_SCHEMAS.items()}
POSITIONAL_DELETE_SCHEMA = Schema(
NestedField(2147483546, "file_path", StringType()), NestedField(2147483545, "pos", IntegerType())
)
class ManifestFile(Record):
@classmethod
def from_args(cls, _table_format_version: TableVersion = DEFAULT_READ_VERSION, **arguments: Any) -> ManifestFile:
return super()._bind(**arguments, struct=MANIFEST_LIST_FILE_SCHEMAS[_table_format_version])
@property
def manifest_path(self) -> str:
return self._data[0]
@property
def manifest_length(self) -> int:
return self._data[1]
@property
def partition_spec_id(self) -> int:
return self._data[2]
@property
def content(self) -> ManifestContent:
return self._data[3]
@property
def sequence_number(self) -> int:
return self._data[4]
@sequence_number.setter
def sequence_number(self, value: int) -> None:
self._data[4] = value
@property
def min_sequence_number(self) -> int:
return self._data[5]
@min_sequence_number.setter
def min_sequence_number(self, value: int) -> None:
self._data[5] = value
@property
def added_snapshot_id(self) -> int | None:
return self._data[6]
@property
def added_files_count(self) -> int | None:
return self._data[7]
@property
def existing_files_count(self) -> int | None:
return self._data[8]
@property
def deleted_files_count(self) -> int | None:
return self._data[9]
@property
def added_rows_count(self) -> int | None:
return self._data[10]
@property
def existing_rows_count(self) -> int | None:
return self._data[11]
@property
def deleted_rows_count(self) -> int | None:
return self._data[12]
@property
def partitions(self) -> list[PartitionFieldSummary] | None:
return self._data[13]
@property
def key_metadata(self) -> bytes | None:
return self._data[14]
def has_added_files(self) -> bool:
return self.added_files_count is None or self.added_files_count > 0
def has_existing_files(self) -> bool:
return self.existing_files_count is None or self.existing_files_count > 0
def fetch_manifest_entry(self, io: FileIO, discard_deleted: bool = True) -> list[ManifestEntry]:
"""
Read the manifest entries from the manifest file.
Args:
io: The FileIO to fetch the file.
discard_deleted: Filter on live entries.
Returns:
An Iterator of manifest entries.
"""
with perf_timer("manifest.fetch_entries", manifest_path=self.manifest_path) as t:
input_file = io.new_input(self.manifest_path)
with AvroFile[ManifestEntry](
input_file,
MANIFEST_ENTRY_SCHEMAS[DEFAULT_READ_VERSION],
read_types={-1: ManifestEntry, 2: DataFile},
read_enums={0: ManifestEntryStatus, 101: FileFormat, 134: DataFileContent},
) as reader:
result = [
_inherit_from_manifest(entry, self)
for entry in reader
if not discard_deleted or entry.status != ManifestEntryStatus.DELETED
]
t.metric("entry_count", len(result))
return result
def __eq__(self, other: Any) -> bool:
"""Return the equality of two instances of the ManifestFile class."""
return self.manifest_path == other.manifest_path if isinstance(other, ManifestFile) else False
def __hash__(self) -> int:
"""Return the hash of manifest_path."""
return hash(self.manifest_path)
# Global cache for ManifestFile objects, keyed by manifest_path.
# This deduplicates ManifestFile objects across manifest lists, which commonly
# share manifests after append operations.
_manifest_cache: LRUCache[str, ManifestFile] = LRUCache(maxsize=128)
# Lock for thread-safe cache access
_manifest_cache_lock = threading.RLock()
def _manifests(io: FileIO, manifest_list: str) -> tuple[ManifestFile, ...]:
"""Read manifests from a manifest list, deduplicating ManifestFile objects via cache.
Caches individual ManifestFile objects by manifest_path. This is memory-efficient
because consecutive manifest lists typically share most of their manifests:
ManifestList1: [ManifestFile1]
ManifestList2: [ManifestFile1, ManifestFile2]
ManifestList3: [ManifestFile1, ManifestFile2, ManifestFile3]
With per-ManifestFile caching, each ManifestFile is stored once and reused.
Note: The manifest list file is re-read on each call. This is intentional to
keep the implementation simple and avoid O(N²) memory growth from caching
overlapping manifest list tuples. Re-reading is cheap since manifest lists
are small metadata files.
Args:
io: FileIO instance for reading the manifest list.
manifest_list: Path to the manifest list file.
Returns:
A tuple of ManifestFile objects.
"""
with perf_timer("manifest.read_list") as t:
file = io.new_input(manifest_list)
manifest_files = list(read_manifest_list(file))
result = []
cache_hits = 0
with _manifest_cache_lock:
for manifest_file in manifest_files:
manifest_path = manifest_file.manifest_path
if manifest_path in _manifest_cache:
result.append(_manifest_cache[manifest_path])
cache_hits += 1
else:
_manifest_cache[manifest_path] = manifest_file
result.append(manifest_file)
t.metric("manifest_count", len(result))
t.metric("cache_hits", cache_hits)
return tuple(result)
def read_manifest_list(input_file: InputFile) -> Iterator[ManifestFile]:
"""
Read the manifests from the manifest list.
Args:
input_file: The input file where the stream can be read from.
Returns:
An iterator of ManifestFiles that are part of the list.
"""
with AvroFile[ManifestFile](
input_file,
MANIFEST_LIST_FILE_SCHEMAS[DEFAULT_READ_VERSION],
read_types={-1: ManifestFile, 508: PartitionFieldSummary},
read_enums={517: ManifestContent},
) as reader:
yield from reader
def _inherit_from_manifest(entry: ManifestEntry, manifest: ManifestFile) -> ManifestEntry:
"""
Inherits properties from manifest file.
The properties that will be inherited are:
- sequence numbers
- partition spec id.
More information about inheriting sequence numbers: https://iceberg.apache.org/spec/#sequence-number-inheritance
Args:
entry: The manifest entry.
manifest: The manifest file.
Returns:
The manifest entry with properties inherited.
"""
# Inherit sequence numbers.
# The snapshot_id is required in V1, inherit with V2 when null
if entry.snapshot_id is None and manifest.added_snapshot_id is not None:
entry.snapshot_id = manifest.added_snapshot_id
# in v1 tables, the sequence number is not persisted and can be safely defaulted to 0
# in v2 tables, the sequence number should be inherited iff the entry status is ADDED
if entry.sequence_number is None and (manifest.sequence_number == 0 or entry.status == ManifestEntryStatus.ADDED):
entry.sequence_number = manifest.sequence_number
# in v1 tables, the file sequence number is not persisted and can be safely defaulted to 0
# in v2 tables, the file sequence number should be inherited iff the entry status is ADDED
if entry.file_sequence_number is None and (manifest.sequence_number == 0 or entry.status == ManifestEntryStatus.ADDED):