aboutsummaryrefslogtreecommitdiff
path: root/icing/file/portable-file-backed-proto-log_test.cc
blob: cc70151b3c126c35f12a8df2e7bc94b93afc5085 (plain)
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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
// Copyright (C) 2019 Google LLC
//
// Licensed 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.

#include "icing/file/portable-file-backed-proto-log.h"

#include <cstdint>
#include <cstdlib>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "icing/document-builder.h"
#include "icing/file/filesystem.h"
#include "icing/file/mock-filesystem.h"
#include "icing/portable/equals-proto.h"
#include "icing/proto/document.pb.h"
#include "icing/testing/common-matchers.h"
#include "icing/testing/tmp-directory.h"

namespace icing {
namespace lib {

namespace {

using ::icing::lib::portable_equals_proto::EqualsProto;
using ::testing::A;
using ::testing::Eq;
using ::testing::Gt;
using ::testing::HasSubstr;
using ::testing::Not;
using ::testing::NotNull;
using ::testing::Pair;
using ::testing::Return;

using Header = PortableFileBackedProtoLog<DocumentProto>::Header;

Header ReadHeader(Filesystem filesystem, const std::string& file_path) {
  Header header;
  filesystem.PRead(file_path.c_str(), &header, sizeof(Header),
                   /*offset=*/0);
  return header;
}

void WriteHeader(Filesystem filesystem, const std::string& file_path,
                 Header& header) {
  filesystem.Write(file_path.c_str(), &header, sizeof(Header));
}

class PortableFileBackedProtoLogTest : public ::testing::Test {
 protected:
  // Adds a user-defined default construct because a const member variable may
  // make the compiler accidentally delete the default constructor.
  // https://stackoverflow.com/a/47368753
  PortableFileBackedProtoLogTest() {}

  void SetUp() override {
    file_path_ = GetTestTempDir() + "/proto_log";
    filesystem_.DeleteFile(file_path_.c_str());
  }

  void TearDown() override { filesystem_.DeleteFile(file_path_.c_str()); }

  const Filesystem filesystem_;
  std::string file_path_;
  bool compress_ = true;
  int32_t compression_level_ =
      PortableFileBackedProtoLog<DocumentProto>::kDeflateCompressionLevel;
  int64_t max_proto_size_ = 256 * 1024;  // 256 KiB
};

TEST_F(PortableFileBackedProtoLogTest, Initialize) {
  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));
  EXPECT_THAT(create_result.proto_log, NotNull());
  EXPECT_FALSE(create_result.has_data_loss());
  EXPECT_FALSE(create_result.recalculated_checksum);

  // Can't recreate the same file with different options.
  ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                  &filesystem_, file_path_,
                  PortableFileBackedProtoLog<DocumentProto>::Options(
                      !compress_, max_proto_size_, compression_level_)),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));
}

TEST_F(PortableFileBackedProtoLogTest, InitializeValidatesOptions) {
  // max_proto_size must be greater than 0
  int invalid_max_proto_size = 0;
  ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                  &filesystem_, file_path_,
                  PortableFileBackedProtoLog<DocumentProto>::Options(
                      compress_, invalid_max_proto_size, compression_level_)),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));

  // max_proto_size must be under 16 MiB
  invalid_max_proto_size = 16 * 1024 * 1024;
  ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                  &filesystem_, file_path_,
                  PortableFileBackedProtoLog<DocumentProto>::Options(
                      compress_, invalid_max_proto_size, compression_level_)),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));

  // compression_level must be between 0 and 9 inclusive
  int invalid_compression_level = -1;
  ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                  &filesystem_, file_path_,
                  PortableFileBackedProtoLog<DocumentProto>::Options(
                      compress_, max_proto_size_, invalid_compression_level)),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));

  // compression_level must be between 0 and 9 inclusive
  invalid_compression_level = 10;
  ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                  &filesystem_, file_path_,
                  PortableFileBackedProtoLog<DocumentProto>::Options(
                      compress_, max_proto_size_, invalid_compression_level)),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));
}

TEST_F(PortableFileBackedProtoLogTest, ReservedSpaceForHeader) {
  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));

  // With no protos written yet, the log should be minimum the size of the
  // reserved header space.
  ASSERT_EQ(filesystem_.GetFileSize(file_path_.c_str()),
            PortableFileBackedProtoLog<DocumentProto>::kHeaderReservedBytes);
}

TEST_F(PortableFileBackedProtoLogTest, WriteProtoTooLarge) {
  int max_proto_size = 1;
  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size, compression_level_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.has_data_loss());

  DocumentProto document = DocumentBuilder().SetKey("namespace", "uri").Build();

  // Proto is too large for the max_proto_size_in
  ASSERT_THAT(proto_log->WriteProto(document),
              StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT));
}

TEST_F(PortableFileBackedProtoLogTest, ReadProtoWrongKProtoMagic) {
  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.has_data_loss());

  // Write a proto
  DocumentProto document = DocumentBuilder().SetKey("namespace", "uri").Build();

  ICING_ASSERT_OK_AND_ASSIGN(int64_t file_offset,
                             proto_log->WriteProto(document));

  // The 4 bytes of metadata that just doesn't have the same kProtoMagic
  // specified in file-backed-proto-log.h
  uint32_t wrong_magic = 0x7E000000;

  // Sanity check that we opened the file correctly
  int fd = filesystem_.OpenForWrite(file_path_.c_str());
  ASSERT_GT(fd, 0);

  // Write the wrong kProtoMagic in, kProtoMagics are stored at the beginning of
  // a proto entry.
  filesystem_.PWrite(fd, file_offset, &wrong_magic, sizeof(wrong_magic));

  ASSERT_THAT(proto_log->ReadProto(file_offset),
              StatusIs(libtextclassifier3::StatusCode::INTERNAL));
}

TEST_F(PortableFileBackedProtoLogTest, ReadWriteUncompressedProto) {
  int last_offset;
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/false, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write the first proto
    DocumentProto document1 =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    ICING_ASSERT_OK_AND_ASSIGN(int written_position,
                               proto_log->WriteProto(document1));

    int document1_offset = written_position;

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(written_position),
                IsOkAndHolds(EqualsProto(document1)));

    // Write a second proto that's close to the max size. Leave some room for
    // the rest of the proto properties.
    std::string long_str(max_proto_size_ - 1024, 'a');
    DocumentProto document2 = DocumentBuilder()
                                  .SetKey("namespace2", "uri2")
                                  .AddStringProperty("long_str", long_str)
                                  .Build();

    ICING_ASSERT_OK_AND_ASSIGN(written_position,
                               proto_log->WriteProto(document2));

    int document2_offset = written_position;
    last_offset = written_position;
    ASSERT_GT(document2_offset, document1_offset);

    // Check the second proto
    ASSERT_THAT(proto_log->ReadProto(written_position),
                IsOkAndHolds(EqualsProto(document2)));

    ICING_ASSERT_OK(proto_log->PersistToDisk());
  }

  {
    // Make a new proto_log with the same file_path, and make sure we
    // can still write to the same underlying file.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/false, max_proto_size_, compression_level_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write a third proto
    DocumentProto document3 =
        DocumentBuilder().SetKey("namespace3", "uri3").Build();

    ASSERT_THAT(recreated_proto_log->WriteProto(document3),
                IsOkAndHolds(Gt(last_offset)));
  }
}

TEST_F(PortableFileBackedProtoLogTest, ReadWriteCompressedProto) {
  int last_offset;

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write the first proto
    DocumentProto document1 =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    ICING_ASSERT_OK_AND_ASSIGN(int written_position,
                               proto_log->WriteProto(document1));

    int document1_offset = written_position;

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(written_position),
                IsOkAndHolds(EqualsProto(document1)));

    // Write a second proto that's close to the max size. Leave some room for
    // the rest of the proto properties.
    std::string long_str(max_proto_size_ - 1024, 'a');
    DocumentProto document2 = DocumentBuilder()
                                  .SetKey("namespace2", "uri2")
                                  .AddStringProperty("long_str", long_str)
                                  .Build();

    ICING_ASSERT_OK_AND_ASSIGN(written_position,
                               proto_log->WriteProto(document2));

    int document2_offset = written_position;
    last_offset = written_position;
    ASSERT_GT(document2_offset, document1_offset);

    // Check the second proto
    ASSERT_THAT(proto_log->ReadProto(written_position),
                IsOkAndHolds(EqualsProto(document2)));

    ICING_ASSERT_OK(proto_log->PersistToDisk());
  }

  {
    // Make a new proto_log with the same file_path, and make sure we
    // can still write to the same underlying file.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_, compression_level_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write a third proto
    DocumentProto document3 =
        DocumentBuilder().SetKey("namespace3", "uri3").Build();

    ASSERT_THAT(recreated_proto_log->WriteProto(document3),
                IsOkAndHolds(Gt(last_offset)));
  }
}

TEST_F(PortableFileBackedProtoLogTest, ReadWriteDifferentCompressionLevel) {
  int document1_offset;
  int document2_offset;
  int document3_offset;

  // The first proto to write that's close to the max size. Leave some room for
  // the rest of the proto properties.
  std::string long_str(max_proto_size_ - 1024, 'a');
  DocumentProto document1 = DocumentBuilder()
                                .SetKey("namespace1", "uri1")
                                .AddStringProperty("long_str", long_str)
                                .Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace2", "uri2").Build();
  DocumentProto document3 =
      DocumentBuilder().SetKey("namespace3", "uri3").Build();

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_,
                /*compression_level_in=*/3)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write the first proto
    ICING_ASSERT_OK_AND_ASSIGN(document1_offset,
                               proto_log->WriteProto(document1));

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document1_offset),
                IsOkAndHolds(EqualsProto(document1)));

    ICING_ASSERT_OK(proto_log->PersistToDisk());
  }

  // Make a new proto_log with the same file_path but different compression
  // level, and make sure we can still read from and write to the same
  // underlying file.
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_,
                /*compression_level_in=*/9)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Check the first proto
    ASSERT_THAT(recreated_proto_log->ReadProto(document1_offset),
                IsOkAndHolds(EqualsProto(document1)));

    // Write a second proto
    ICING_ASSERT_OK_AND_ASSIGN(document2_offset,
                               recreated_proto_log->WriteProto(document2));

    ASSERT_GT(document2_offset, document1_offset);

    // Check the second proto
    ASSERT_THAT(recreated_proto_log->ReadProto(document2_offset),
                IsOkAndHolds(EqualsProto(document2)));

    ICING_ASSERT_OK(recreated_proto_log->PersistToDisk());
  }

  // One more time but with 0 compression level
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_,
                /*compression_level=*/0)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Check the first proto
    ASSERT_THAT(recreated_proto_log->ReadProto(document1_offset),
                IsOkAndHolds(EqualsProto(document1)));

    // Check the second proto
    ASSERT_THAT(recreated_proto_log->ReadProto(document2_offset),
                IsOkAndHolds(EqualsProto(document2)));

    // Write a third proto
    ICING_ASSERT_OK_AND_ASSIGN(document3_offset,
                               recreated_proto_log->WriteProto(document3));

    ASSERT_GT(document3_offset, document2_offset);

    // Check the third proto
    ASSERT_THAT(recreated_proto_log->ReadProto(document3_offset),
                IsOkAndHolds(EqualsProto(document3)));
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       WriteDifferentCompressionLevelDifferentSizes) {
  int document_log_size_with_compression_3;
  int document_log_size_with_no_compression;

  // The first proto to write that's close to the max size. Leave some room for
  // the rest of the proto properties.
  std::string long_str(max_proto_size_ - 1024, 'a');
  DocumentProto document1 = DocumentBuilder()
                                .SetKey("namespace1", "uri1")
                                .AddStringProperty("long_str", long_str)
                                .Build();

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_,
                /*compression_level_in=*/3)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write the proto
    ICING_ASSERT_OK(proto_log->WriteProto(document1));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    document_log_size_with_compression_3 =
        filesystem_.GetFileSize(file_path_.c_str());
  }

  // Delete the proto_log so we can reuse the file_path
  filesystem_.DeleteFile(file_path_.c_str());

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_,
                /*compression_level_in=*/0)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write the proto
    ICING_ASSERT_OK(proto_log->WriteProto(document1));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    document_log_size_with_no_compression =
        filesystem_.GetFileSize(file_path_.c_str());

    // Uncompressed document file size should be larger than original compressed
    // document file size
    ASSERT_GT(document_log_size_with_no_compression,
              document_log_size_with_compression_3);
  }
}

TEST_F(PortableFileBackedProtoLogTest, CorruptHeader) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());
  }

  int corrupt_checksum = 24;

  // Write the corrupted header
  Header header = ReadHeader(filesystem_, file_path_);
  header.SetHeaderChecksum(corrupt_checksum);
  WriteHeader(filesystem_, file_path_, header);

  {
    // Reinitialize the same proto_log
    ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                    &filesystem_, file_path_,
                    PortableFileBackedProtoLog<DocumentProto>::Options(
                        compress_, max_proto_size_, compression_level_)),
                StatusIs(libtextclassifier3::StatusCode::INTERNAL,
                         HasSubstr("Invalid header checksum")));
  }
}

TEST_F(PortableFileBackedProtoLogTest, DifferentMagic) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());

    // Corrupt the magic that's stored at the beginning of the header.
    int invalid_magic = -1;
    ASSERT_THAT(invalid_magic, Not(Eq(Header::kMagic)));

    // Write the corrupted header
    Header header = ReadHeader(filesystem_, file_path_);
    header.SetMagic(invalid_magic);
    WriteHeader(filesystem_, file_path_, header);
  }

  {
    // Reinitialize the same proto_log
    ASSERT_THAT(PortableFileBackedProtoLog<DocumentProto>::Create(
                    &filesystem_, file_path_,
                    PortableFileBackedProtoLog<DocumentProto>::Options(
                        compress_, max_proto_size_, compression_level_)),
                StatusIs(libtextclassifier3::StatusCode::INTERNAL,
                         HasSubstr("Invalid header kMagic")));
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       UnableToDetectCorruptContentWithoutDirtyBit) {
  // This is intentional that we can't detect corruption. We're trading off
  // earlier corruption detection for lower initialization latency. By not
  // calculating the checksum on initialization, we can initialize much faster,
  // but at the cost of detecting corruption. Note that even if we did detect
  // corruption, there was nothing we could've done except throw an error to
  // clients. We'll still do that, but at some later point when the log is
  // attempting to be accessed and we can't actually deserialize a proto from
  // it. See the description in cl/374278280 for more details.

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    // Write and persist an document.
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    // "Corrupt" the content written in the log.
    document.set_uri("invalid");
    std::string serialized_document = document.SerializeAsString();
    ASSERT_TRUE(filesystem_.PWrite(file_path_.c_str(), document_offset,
                                   serialized_document.data(),
                                   serialized_document.size()));
  }

  {
    // We can recover, and we don't have data loss.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());
    EXPECT_THAT(create_result.data_loss, Eq(DataLoss::NONE));
    EXPECT_FALSE(create_result.recalculated_checksum);

    // We still have the corrupted content in our file, we didn't throw
    // everything out.
    EXPECT_THAT(
        filesystem_.GetFileSize(file_path_.c_str()),
        Gt(PortableFileBackedProtoLog<DocumentProto>::kHeaderReservedBytes));
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       DetectAndThrowOutCorruptContentWithDirtyBit) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder()
            .SetKey("namespace1", "uri1")
            .AddStringProperty("string_property", "foo", "bar")
            .Build();

    // Write and persist the protos
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                IsOkAndHolds(EqualsProto(document)));
  }

  {
    // "Corrupt" the content written in the log. Make the corrupt document
    // smaller than our original one so we don't accidentally write past our
    // file.
    DocumentProto document =
        DocumentBuilder().SetKey("invalid_namespace", "invalid_uri").Build();
    std::string serialized_document = document.SerializeAsString();
    ASSERT_TRUE(filesystem_.PWrite(
        file_path_.c_str(),
        PortableFileBackedProtoLog<DocumentProto>::kHeaderReservedBytes,
        serialized_document.data(), serialized_document.size()));

    Header header = ReadHeader(filesystem_, file_path_);

    // Set dirty bit to true to reflect that something changed in the log.
    header.SetDirtyFlag(true);
    header.SetHeaderChecksum(header.CalculateHeaderChecksum());

    WriteHeader(filesystem_, file_path_, header);
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_TRUE(create_result.has_data_loss());
    EXPECT_THAT(create_result.data_loss, Eq(DataLoss::COMPLETE));

    // We had to recalculate the checksum to detect the corruption.
    EXPECT_TRUE(create_result.recalculated_checksum);

    // We lost everything, file size is back down to the header.
    EXPECT_THAT(
        filesystem_.GetFileSize(file_path_.c_str()),
        Eq(PortableFileBackedProtoLog<DocumentProto>::kHeaderReservedBytes));

    // At least the log is no longer dirty.
    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest, DirtyBitFalseAlarmKeepsData) {
  DocumentProto document =
      DocumentBuilder().SetKey("namespace1", "uri1").Build();
  int64_t document_offset;
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(document_offset,
                               proto_log->WriteProto(document));

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                IsOkAndHolds(EqualsProto(document)));
  }

  {
    Header header = ReadHeader(filesystem_, file_path_);

    // Simulate the dirty flag set as true, but no data has been changed yet.
    // Maybe we crashed between writing the dirty flag and erasing a proto.
    header.SetDirtyFlag(true);
    header.SetHeaderChecksum(header.CalculateHeaderChecksum());

    WriteHeader(filesystem_, file_path_, header);
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());

    // Even though nothing changed, the false alarm dirty bit should have
    // triggered us to recalculate our checksum.
    EXPECT_TRUE(create_result.recalculated_checksum);

    // Check that our document still exists even though dirty bit was true.
    EXPECT_THAT(proto_log->ReadProto(document_offset),
                IsOkAndHolds(EqualsProto(document)));

    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       PersistToDiskKeepsPersistedDataAndTruncatesExtraData) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace1", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace2", "uri2").Build();
  int document1_offset, document2_offset;
  int log_size;

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Write and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(document1_offset,
                               proto_log->WriteProto(document1));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    // Write, but don't explicitly persist the second proto
    ICING_ASSERT_OK_AND_ASSIGN(document2_offset,
                               proto_log->WriteProto(document2));

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document1_offset),
                IsOkAndHolds(EqualsProto(document1)));
    ASSERT_THAT(proto_log->ReadProto(document2_offset),
                IsOkAndHolds(EqualsProto(document2)));

    log_size = filesystem_.GetFileSize(file_path_.c_str());
    ASSERT_GT(log_size, 0);

    // PersistToDisk happens implicitly during the destructor.
  }

  {
    // The header rewind position and checksum aren't updated in this "system
    // crash" scenario.

    std::string bad_proto =
        "some incomplete proto that we didn't finish writing before the "
        "system crashed";
    filesystem_.PWrite(file_path_.c_str(), log_size, bad_proto.data(),
                       bad_proto.size());

    // Double check that we actually wrote something to the underlying file
    ASSERT_GT(filesystem_.GetFileSize(file_path_.c_str()), log_size);
  }

  {
    // We can recover, but we have data loss
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_TRUE(create_result.has_data_loss());
    ASSERT_THAT(create_result.data_loss, Eq(DataLoss::PARTIAL));
    ASSERT_FALSE(create_result.recalculated_checksum);

    // Check that everything was persisted across instances
    ASSERT_THAT(proto_log->ReadProto(document1_offset),
                IsOkAndHolds(EqualsProto(document1)));
    ASSERT_THAT(proto_log->ReadProto(document2_offset),
                IsOkAndHolds(EqualsProto(document2)));

    // We correctly rewound to the last good state.
    ASSERT_EQ(log_size, filesystem_.GetFileSize(file_path_.c_str()));
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       DirtyBitIsFalseAfterPutAndPersistToDisk) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    // Write and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                IsOkAndHolds(EqualsProto(document)));
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));

    // We previously persisted to disk so everything should be in a perfect
    // state.
    EXPECT_FALSE(create_result.has_data_loss());
    EXPECT_FALSE(create_result.recalculated_checksum);

    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       DirtyBitIsFalseAfterDeleteAndPersistToDisk) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    // Write, delete, and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));
    ICING_ASSERT_OK(proto_log->EraseProto(document_offset));
    ICING_ASSERT_OK(proto_log->PersistToDisk());

    // The proto has been erased.
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                StatusIs(libtextclassifier3::StatusCode::NOT_FOUND));
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));

    // We previously persisted to disk so everything should be in a perfect
    // state.
    EXPECT_FALSE(create_result.has_data_loss());
    EXPECT_FALSE(create_result.recalculated_checksum);

    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest, DirtyBitIsFalseAfterPutAndDestructor) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    // Write and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));

    // Check that what we read is what we wrote
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                IsOkAndHolds(EqualsProto(document)));

    // PersistToDisk is implicitly called as part of the destructor and
    // PersistToDisk will clear the dirty bit.
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));

    // We previously persisted to disk so everything should be in a perfect
    // state.
    EXPECT_FALSE(create_result.has_data_loss());
    EXPECT_FALSE(create_result.recalculated_checksum);

    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest,
       DirtyBitIsFalseAfterDeleteAndDestructor) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    DocumentProto document =
        DocumentBuilder().SetKey("namespace1", "uri1").Build();

    // Write, delete, and persist the first proto
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document_offset,
                               proto_log->WriteProto(document));
    ICING_ASSERT_OK(proto_log->EraseProto(document_offset));

    // The proto has been erased.
    ASSERT_THAT(proto_log->ReadProto(document_offset),
                StatusIs(libtextclassifier3::StatusCode::NOT_FOUND));

    // PersistToDisk is implicitly called as part of the destructor and
    // PersistToDisk will clear the dirty bit.
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));

    // We previously persisted to disk so everything should be in a perfect
    // state.
    EXPECT_FALSE(create_result.has_data_loss());
    EXPECT_FALSE(create_result.recalculated_checksum);

    Header header = ReadHeader(filesystem_, file_path_);
    EXPECT_FALSE(header.GetDirtyFlag());
  }
}

TEST_F(PortableFileBackedProtoLogTest, Iterator) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace", "uri2").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.has_data_loss());

  {
    // Empty iterator
    auto iterator = proto_log->GetIterator();
    ASSERT_THAT(iterator.Advance(),
                StatusIs(libtextclassifier3::StatusCode::OUT_OF_RANGE));
  }

  {
    // Iterates through some documents
    ICING_ASSERT_OK(proto_log->WriteProto(document1));
    ICING_ASSERT_OK(proto_log->WriteProto(document2));
    auto iterator = proto_log->GetIterator();
    // 1st proto
    ICING_ASSERT_OK(iterator.Advance());
    ASSERT_THAT(proto_log->ReadProto(iterator.GetOffset()),
                IsOkAndHolds(EqualsProto(document1)));
    // 2nd proto
    ICING_ASSERT_OK(iterator.Advance());
    ASSERT_THAT(proto_log->ReadProto(iterator.GetOffset()),
                IsOkAndHolds(EqualsProto(document2)));
    // Tries to advance
    ASSERT_THAT(iterator.Advance(),
                StatusIs(libtextclassifier3::StatusCode::OUT_OF_RANGE));
  }

  {
    // Iterator with bad filesystem
    ScopedFd sfd(filesystem_.OpenForRead(file_path_.c_str()));
    MockFilesystem mock_filesystem;
    ON_CALL(mock_filesystem, GetFileSize(A<int>()))
        .WillByDefault(Return(Filesystem::kBadFileSize));
    PortableFileBackedProtoLog<DocumentProto>::Iterator bad_iterator(
        mock_filesystem, sfd.get(), /*initial_offset=*/0);
    ASSERT_THAT(bad_iterator.Advance(),
                StatusIs(libtextclassifier3::StatusCode::OUT_OF_RANGE));
  }
}

TEST_F(PortableFileBackedProtoLogTest, ComputeChecksum) {
  DocumentProto document = DocumentBuilder().SetKey("namespace", "uri").Build();
  Crc32 checksum;

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    ICING_EXPECT_OK(proto_log->WriteProto(document));

    ICING_ASSERT_OK_AND_ASSIGN(checksum, proto_log->ComputeChecksum());

    // Calling it twice with no changes should get us the same checksum
    EXPECT_THAT(proto_log->ComputeChecksum(), IsOkAndHolds(Eq(checksum)));
  }

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Checksum should be consistent across instances
    EXPECT_THAT(proto_log->ComputeChecksum(), IsOkAndHolds(Eq(checksum)));

    // PersistToDisk shouldn't affect the checksum value
    ICING_EXPECT_OK(proto_log->PersistToDisk());
    EXPECT_THAT(proto_log->ComputeChecksum(), IsOkAndHolds(Eq(checksum)));

    // Check that modifying the log leads to a different checksum
    ICING_EXPECT_OK(proto_log->WriteProto(document));
    EXPECT_THAT(proto_log->ComputeChecksum(), IsOkAndHolds(Not(Eq(checksum))));
  }
}

TEST_F(PortableFileBackedProtoLogTest, EraseProtoShouldSetZero) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.has_data_loss());

  // Writes and erases proto
  ICING_ASSERT_OK_AND_ASSIGN(int64_t document1_offset,
                             proto_log->WriteProto(document1));
  ICING_ASSERT_OK(proto_log->EraseProto(document1_offset));

  // Checks if the erased area is set to 0.
  int64_t file_size = filesystem_.GetFileSize(file_path_.c_str());
  ICING_ASSERT_OK_AND_ASSIGN(
      MemoryMappedFile mmapped_file,
      MemoryMappedFile::Create(filesystem_, file_path_,
                               MemoryMappedFile::Strategy::READ_ONLY));

  // document1_offset + sizeof(int) is the start byte of the proto where
  // sizeof(int) is the size of the proto metadata.
  ICING_ASSERT_OK(
      mmapped_file.Remap(document1_offset + sizeof(int), file_size - 1));
  for (size_t i = 0; i < mmapped_file.region_size(); ++i) {
    ASSERT_THAT(mmapped_file.region()[i], Eq(0));
  }
}

TEST_F(PortableFileBackedProtoLogTest, EraseProtoShouldReturnNotFound) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace", "uri2").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
      PortableFileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          PortableFileBackedProtoLog<DocumentProto>::Options(
              compress_, max_proto_size_, compression_level_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.has_data_loss());

  // Writes 2 protos
  ICING_ASSERT_OK_AND_ASSIGN(int64_t document1_offset,
                             proto_log->WriteProto(document1));
  ICING_ASSERT_OK_AND_ASSIGN(int64_t document2_offset,
                             proto_log->WriteProto(document2));

  // Erases the first proto
  ICING_ASSERT_OK(proto_log->EraseProto(document1_offset));

  // The first proto has been erased.
  ASSERT_THAT(proto_log->ReadProto(document1_offset),
              StatusIs(libtextclassifier3::StatusCode::NOT_FOUND));
  // The second proto should be returned.
  ASSERT_THAT(proto_log->ReadProto(document2_offset),
              IsOkAndHolds(EqualsProto(document2)));
}

TEST_F(PortableFileBackedProtoLogTest, ChecksumShouldBeCorrectWithErasedProto) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace", "uri2").Build();
  DocumentProto document3 =
      DocumentBuilder().SetKey("namespace", "uri3").Build();
  DocumentProto document4 =
      DocumentBuilder().SetKey("namespace", "uri4").Build();

  int64_t document2_offset;
  int64_t document3_offset;

  {
    // Erase data after the rewind position. This won't update the checksum
    // immediately.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Writes 3 protos
    ICING_ASSERT_OK_AND_ASSIGN(int64_t document1_offset,
                               proto_log->WriteProto(document1));
    ICING_ASSERT_OK_AND_ASSIGN(document2_offset,
                               proto_log->WriteProto(document2));
    ICING_ASSERT_OK_AND_ASSIGN(document3_offset,
                               proto_log->WriteProto(document3));

    // Erases the 1st proto, checksum won't be updated immediately because the
    // rewind position is 0.
    ICING_ASSERT_OK(proto_log->EraseProto(document1_offset));

    EXPECT_THAT(proto_log->ComputeChecksum(),
                IsOkAndHolds(Eq(Crc32(2175574628))));
  }  // New checksum is updated in destructor.

  {
    // Erase data before the rewind position. This will update the checksum
    // immediately.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Erases the 2nd proto that is now before the rewind position. Checksum
    // is updated.
    ICING_ASSERT_OK(proto_log->EraseProto(document2_offset));

    EXPECT_THAT(proto_log->ComputeChecksum(),
                IsOkAndHolds(Eq(Crc32(790877774))));
  }

  {
    // Append data and erase data before the rewind position. This will update
    // the checksum twice: in EraseProto() and destructor.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.has_data_loss());

    // Append a new document which is after the rewind position.
    ICING_ASSERT_OK(proto_log->WriteProto(document4));

    // Erases the 3rd proto that is now before the rewind position. Checksum
    // is updated.
    ICING_ASSERT_OK(proto_log->EraseProto(document3_offset));

    EXPECT_THAT(proto_log->ComputeChecksum(),
                IsOkAndHolds(Eq(Crc32(2344803210))));
  }  // Checksum is updated with the newly appended document.

  {
    // A successful creation means that the checksum matches.
    ICING_ASSERT_OK_AND_ASSIGN(
        PortableFileBackedProtoLog<DocumentProto>::CreateResult create_result,
        PortableFileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            PortableFileBackedProtoLog<DocumentProto>::Options(
                compress_, max_proto_size_, compression_level_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.has_data_loss());
  }
}

}  // namespace
}  // namespace lib
}  // namespace icing