aboutsummaryrefslogtreecommitdiff
path: root/icing/file/file-backed-proto-log_test.cc
blob: fad5248a3ecc5a958904a576a80be3adc303dbe2 (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
// 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/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::Not;
using ::testing::NotNull;
using ::testing::Pair;
using ::testing::Return;

class FileBackedProtoLogTest : 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
  FileBackedProtoLogTest() {}

  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;
  int64_t max_proto_size_ = 256 * 1024;  // 256 KiB
};

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

  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size_)));
  EXPECT_THAT(create_result.proto_log, NotNull());
  EXPECT_FALSE(create_result.data_loss);

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

TEST_F(FileBackedProtoLogTest, WriteProtoTooLarge) {
  int max_proto_size = 1;
  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, ReadProtoWrongKProtoMagic) {
  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, ReadWriteUncompressedProto) {
  int last_offset;
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/false, max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/false, max_proto_size_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, ReadWriteCompressedProto) {
  int last_offset;

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(
                /*compress_in=*/true, max_proto_size_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, CorruptHeader) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto recreated_proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.data_loss);

    int corrupt_offset =
        offsetof(FileBackedProtoLog<DocumentProto>::Header, rewind_offset);
    // We should never rewind to a negative offset.
    int invalid_rewind_offset = -1;
    filesystem_.PWrite(file_path_.c_str(), corrupt_offset,
                       &invalid_rewind_offset, sizeof(invalid_rewind_offset));
  }

  {
    // Reinitialize the same proto_log
    ASSERT_THAT(FileBackedProtoLog<DocumentProto>::Create(
                    &filesystem_, file_path_,
                    FileBackedProtoLog<DocumentProto>::Options(
                        compress_, max_proto_size_)),
                StatusIs(libtextclassifier3::StatusCode::INTERNAL));
  }
}

TEST_F(FileBackedProtoLogTest, CorruptContent) {
  {
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    EXPECT_FALSE(create_result.data_loss);

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

    // Write and persist an document.
    ICING_ASSERT_OK_AND_ASSIGN(int 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();
    filesystem_.PWrite(file_path_.c_str(), document_offset,
                       serialized_document.data(), serialized_document.size());
  }

  {
    // We can recover, but we have data loss.
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_TRUE(create_result.data_loss);

    // Lost everything in the log since the rewind position doesn't help if
    // there's been data corruption within the persisted region
    ASSERT_EQ(filesystem_.GetFileSize(file_path_.c_str()),
              sizeof(FileBackedProtoLog<DocumentProto>::Header));
  }
}

TEST_F(FileBackedProtoLogTest, PersistToDisk) {
  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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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);
  }

  {
    // 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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_TRUE(create_result.data_loss);

    // 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(FileBackedProtoLogTest, Iterator) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace", "uri2").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.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
    MockFilesystem mock_filesystem;
    ON_CALL(mock_filesystem, GetFileSize(A<const char *>()))
        .WillByDefault(Return(Filesystem::kBadFileSize));
    FileBackedProtoLog<DocumentProto>::Iterator bad_iterator(
        mock_filesystem, file_path_, /*initial_offset=*/0);
    ASSERT_THAT(bad_iterator.Advance(),
                StatusIs(libtextclassifier3::StatusCode::OUT_OF_RANGE));
  }
}

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

  {
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, EraseProtoShouldSetZero) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.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());
  MemoryMappedFile mmapped_file(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.
  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(FileBackedProtoLogTest, EraseProtoShouldReturnNotFound) {
  DocumentProto document1 =
      DocumentBuilder().SetKey("namespace", "uri1").Build();
  DocumentProto document2 =
      DocumentBuilder().SetKey("namespace", "uri2").Build();

  ICING_ASSERT_OK_AND_ASSIGN(
      FileBackedProtoLog<DocumentProto>::CreateResult create_result,
      FileBackedProtoLog<DocumentProto>::Create(
          &filesystem_, file_path_,
          FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                     max_proto_size_)));
  auto proto_log = std::move(create_result.proto_log);
  ASSERT_FALSE(create_result.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(FileBackedProtoLogTest, 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(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(2293202502))));
  }  // New checksum is updated in destructor.

  {
    // Erase data before the rewind position. This will update the checksum
    // immediately.
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(639634028))));
  }

  {
    // Append data and erase data before the rewind position. This will update
    // the checksum twice: in EraseProto() and destructor.
    ICING_ASSERT_OK_AND_ASSIGN(
        FileBackedProtoLog<DocumentProto>::CreateResult create_result,
        FileBackedProtoLog<DocumentProto>::Create(
            &filesystem_, file_path_,
            FileBackedProtoLog<DocumentProto>::Options(compress_,
                                                       max_proto_size_)));
    auto proto_log = std::move(create_result.proto_log);
    ASSERT_FALSE(create_result.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(1990198693))));
  }  // Checksum is updated with the newly appended document.

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

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