aboutsummaryrefslogtreecommitdiff
path: root/icing/icing-search-engine_backwards_compatibility_test.cc
blob: 2574313d428b3e69e9f331df15be2c61adab5877 (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
// Copyright (C) 2022 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 <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <utility>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "icing/absl_ports/str_cat.h"
#include "icing/document-builder.h"
#include "icing/file/filesystem.h"
#include "icing/icing-search-engine.h"
#include "icing/portable/endian.h"
#include "icing/portable/equals-proto.h"
#include "icing/portable/platform.h"
#include "icing/schema-builder.h"
#include "icing/testing/common-matchers.h"
#include "icing/testing/jni-test-helpers.h"
#include "icing/testing/test-data.h"
#include "icing/testing/tmp-directory.h"

namespace icing {
namespace lib {

namespace {

using ::icing::lib::portable_equals_proto::EqualsProto;
using ::testing::Eq;

constexpr TermMatchType::Code MATCH_EXACT = TermMatchType::EXACT_ONLY;
constexpr PropertyConfigProto::Cardinality::Code CARDINALITY_OPTIONAL =
    PropertyConfigProto::Cardinality::OPTIONAL;
constexpr StringIndexingConfig::TokenizerType::Code TOKENIZER_PLAIN =
    StringIndexingConfig::TokenizerType::PLAIN;

// For mocking purpose, we allow tests to provide a custom Filesystem.
class TestIcingSearchEngine : public IcingSearchEngine {
 public:
  TestIcingSearchEngine(const IcingSearchEngineOptions& options,
                        std::unique_ptr<const Filesystem> filesystem,
                        std::unique_ptr<const IcingFilesystem> icing_filesystem,
                        std::unique_ptr<Clock> clock,
                        std::unique_ptr<JniCache> jni_cache)
      : IcingSearchEngine(options, std::move(filesystem),
                          std::move(icing_filesystem), std::move(clock),
                          std::move(jni_cache)) {}
};

std::string GetTestBaseDir() { return GetTestTempDir() + "/icing"; }

class IcingSearchEngineBackwardsCompatibilityTest : public testing::Test {
 protected:
  void SetUp() override {
    filesystem_.CreateDirectoryRecursively(GetTestBaseDir().c_str());
  }

  void TearDown() override {
    filesystem_.DeleteDirectoryRecursively(GetTestBaseDir().c_str());
  }

  const Filesystem* filesystem() const { return &filesystem_; }

 private:
  Filesystem filesystem_;
};

ScoringSpecProto GetDefaultScoringSpec() {
  ScoringSpecProto scoring_spec;
  scoring_spec.set_rank_by(ScoringSpecProto::RankingStrategy::DOCUMENT_SCORE);
  return scoring_spec;
}

std::string GetTestDataDir(std::string_view test_subdir) {
  if (IsAndroidX86()) {
    return GetTestFilePath(
        absl_ports::StrCat("icing/testdata/", test_subdir,
                           "/icing_search_engine_android_x86"));
  } else if (IsAndroidArm()) {
    return GetTestFilePath(
        absl_ports::StrCat("icing/testdata/", test_subdir,
                           "/icing_search_engine_android_arm"));
  } else if (IsIosPlatform()) {
    return GetTestFilePath(absl_ports::StrCat("icing/testdata/",
                                              test_subdir,
                                              "/icing_search_engine_ios"));
  } else {
    return GetTestFilePath(absl_ports::StrCat("icing/testdata/",
                                              test_subdir,
                                              "/icing_search_engine_linux"));
  }
}

TEST_F(IcingSearchEngineBackwardsCompatibilityTest,
       MigrateToPortableFileBackedProtoLog) {
  // Copy the testdata files into our IcingSearchEngine directory
  std::string dir_without_portable_log = GetTestDataDir("not_portable_log");

  // Create dst directory that we'll initialize the IcingSearchEngine over.
  std::string base_dir = GetTestBaseDir() + "_migrate";
  ASSERT_THAT(filesystem()->DeleteDirectoryRecursively(base_dir.c_str()), true);
  ASSERT_THAT(filesystem()->CreateDirectoryRecursively(base_dir.c_str()), true);

  ASSERT_TRUE(filesystem()->CopyDirectory(dir_without_portable_log.c_str(),
                                          base_dir.c_str(),
                                          /*recursive=*/true));

  IcingSearchEngineOptions icing_options;
  icing_options.set_base_dir(base_dir);

  IcingSearchEngine icing(icing_options, GetTestJniCache());
  InitializeResultProto init_result = icing.Initialize();
  EXPECT_THAT(init_result.status(), ProtoIsOk());
  EXPECT_THAT(init_result.initialize_stats().document_store_data_status(),
              Eq(InitializeStatsProto::NO_DATA_LOSS));
  EXPECT_THAT(init_result.initialize_stats().document_store_recovery_cause(),
              Eq(InitializeStatsProto::LEGACY_DOCUMENT_LOG_FORMAT));
  EXPECT_THAT(init_result.initialize_stats().schema_store_recovery_cause(),
              Eq(InitializeStatsProto::NONE));
  // The main and lite indexes are in legacy formats and therefore will need to
  // be rebuilt from scratch.
  EXPECT_THAT(init_result.initialize_stats().index_restoration_cause(),
              Eq(InitializeStatsProto::IO_ERROR));

  // Set up schema, this is the one used to validate documents in the testdata
  // files. Do not change unless you're also updating the testdata files.
  SchemaProto schema =
      SchemaBuilder()
          .AddType(SchemaTypeConfigBuilder()
                       .SetType("email")
                       .AddProperty(
                           PropertyConfigBuilder()
                               .SetName("subject")
                               .SetDataTypeString(MATCH_EXACT, TOKENIZER_PLAIN)
                               .SetCardinality(CARDINALITY_OPTIONAL))
                       .AddProperty(
                           PropertyConfigBuilder()
                               .SetName("body")
                               .SetDataTypeString(MATCH_EXACT, TOKENIZER_PLAIN)
                               .SetCardinality(CARDINALITY_OPTIONAL)))
          .Build();

  // Make sure our schema is still the same as we expect. If not, there's
  // definitely no way we're getting the documents back that we expect.
  GetSchemaResultProto expected_get_schema_result_proto;
  expected_get_schema_result_proto.mutable_status()->set_code(StatusProto::OK);
  *expected_get_schema_result_proto.mutable_schema() = schema;
  ASSERT_THAT(icing.GetSchema(), EqualsProto(expected_get_schema_result_proto));

  // These are the documents that are stored in the testdata files. Do not
  // change unless you're also updating the testdata files.
  DocumentProto document1 = DocumentBuilder()
                                .SetKey("namespace1", "uri1")
                                .SetSchema("email")
                                .SetCreationTimestampMs(10)
                                .AddStringProperty("subject", "foo")
                                .AddStringProperty("body", "bar")
                                .Build();

  DocumentProto document2 = DocumentBuilder()
                                .SetKey("namespace1", "uri2")
                                .SetSchema("email")
                                .SetCreationTimestampMs(20)
                                .SetScore(321)
                                .AddStringProperty("body", "baz bat")
                                .Build();

  DocumentProto document3 = DocumentBuilder()
                                .SetKey("namespace2", "uri1")
                                .SetSchema("email")
                                .SetCreationTimestampMs(30)
                                .SetScore(123)
                                .AddStringProperty("subject", "phoo")
                                .Build();

  // Document 1 and 3 were put normally, and document 2 was deleted in our
  // testdata files.
  EXPECT_THAT(icing
                  .Get(document1.namespace_(), document1.uri(),
                       GetResultSpecProto::default_instance())
                  .document(),
              EqualsProto(document1));
  EXPECT_THAT(icing
                  .Get(document2.namespace_(), document2.uri(),
                       GetResultSpecProto::default_instance())
                  .status(),
              ProtoStatusIs(StatusProto::NOT_FOUND));
  EXPECT_THAT(icing
                  .Get(document3.namespace_(), document3.uri(),
                       GetResultSpecProto::default_instance())
                  .document(),
              EqualsProto(document3));

  // Searching for "foo" should get us document1.
  SearchSpecProto search_spec;
  search_spec.set_term_match_type(TermMatchType::PREFIX);
  search_spec.set_query("foo");

  SearchResultProto expected_document1;
  expected_document1.mutable_status()->set_code(StatusProto::OK);
  *expected_document1.mutable_results()->Add()->mutable_document() = document1;

  SearchResultProto actual_results =
      icing.Search(search_spec, GetDefaultScoringSpec(),
                   ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results,
              EqualsSearchResultIgnoreStatsAndScores(expected_document1));

  // Searching for "baz" would've gotten us document2, except it got deleted.
  // Make sure that it's cleared from our index too.
  search_spec.set_query("baz");

  SearchResultProto expected_no_documents;
  expected_no_documents.mutable_status()->set_code(StatusProto::OK);

  actual_results = icing.Search(search_spec, GetDefaultScoringSpec(),
                                ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results,
              EqualsSearchResultIgnoreStatsAndScores(expected_no_documents));

  // Searching for "phoo" should get us document3.
  search_spec.set_query("phoo");

  SearchResultProto expected_document3;
  expected_document3.mutable_status()->set_code(StatusProto::OK);
  *expected_document3.mutable_results()->Add()->mutable_document() = document3;

  actual_results = icing.Search(search_spec, GetDefaultScoringSpec(),
                                ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results,
              EqualsSearchResultIgnoreStatsAndScores(expected_document3));
}

TEST_F(IcingSearchEngineBackwardsCompatibilityTest, MigrateToLargerScale) {
  // Copy the testdata files into our IcingSearchEngine directory
  std::string test_data_dir = GetTestDataDir("icing_scale_migration");

  // Create dst directory that we'll initialize the IcingSearchEngine over.
  std::string base_dir = GetTestBaseDir() + "_migrate";
  ASSERT_THAT(filesystem()->DeleteDirectoryRecursively(base_dir.c_str()), true);
  ASSERT_THAT(filesystem()->CreateDirectoryRecursively(base_dir.c_str()), true);

  ASSERT_TRUE(filesystem()->CopyDirectory(test_data_dir.c_str(),
                                          base_dir.c_str(),
                                          /*recursive=*/true));

  IcingSearchEngineOptions icing_options;
  icing_options.set_base_dir(base_dir);

  IcingSearchEngine icing(icing_options, GetTestJniCache());
  InitializeResultProto init_result = icing.Initialize();
  EXPECT_THAT(init_result.status(), ProtoIsOk());
  EXPECT_THAT(init_result.initialize_stats().document_store_data_status(),
              Eq(InitializeStatsProto::NO_DATA_LOSS));
  // No recovery is required for the document store.
  EXPECT_THAT(init_result.initialize_stats().document_store_recovery_cause(),
              Eq(InitializeStatsProto::NONE));
  EXPECT_THAT(init_result.initialize_stats().schema_store_recovery_cause(),
              Eq(InitializeStatsProto::NONE));
  // The main and lite indexes are in legacy formats and therefore will need to
  // be rebuilt from scratch.
  EXPECT_THAT(init_result.initialize_stats().index_restoration_cause(),
              Eq(InitializeStatsProto::IO_ERROR));

  // Verify that the schema stored in the index matches the one that we expect.
  // Do not change unless you're also updating the testdata files.
  SchemaProto expected_schema =
      SchemaBuilder()
          .AddType(SchemaTypeConfigBuilder()
                       .SetType("email")
                       .AddProperty(
                           PropertyConfigBuilder()
                               .SetName("subject")
                               .SetDataTypeString(MATCH_EXACT, TOKENIZER_PLAIN)
                               .SetCardinality(CARDINALITY_OPTIONAL))
                       .AddProperty(
                           PropertyConfigBuilder()
                               .SetName("body")
                               .SetDataTypeString(MATCH_EXACT, TOKENIZER_PLAIN)
                               .SetCardinality(CARDINALITY_OPTIONAL)))
          .Build();

  // Make sure our schema is still the same as we expect. If not, there's
  // definitely no way we're getting the documents back that we expect.
  GetSchemaResultProto expected_get_schema_result_proto;
  expected_get_schema_result_proto.mutable_status()->set_code(StatusProto::OK);
  *expected_get_schema_result_proto.mutable_schema() = expected_schema;
  ASSERT_THAT(icing.GetSchema(), EqualsProto(expected_get_schema_result_proto));

  // These are the documents that are stored in the testdata files. Do not
  // change unless you're also updating the testdata files.
  DocumentProto expected_document1 = DocumentBuilder()
                                         .SetKey("namespace1", "uri1")
                                         .SetSchema("email")
                                         .SetCreationTimestampMs(10)
                                         .AddStringProperty("subject", "foo")
                                         .AddStringProperty("body", "bar")
                                         .Build();

  DocumentProto expected_deleted_document2 =
      DocumentBuilder()
          .SetKey("namespace1", "uri2")
          .SetSchema("email")
          .SetCreationTimestampMs(20)
          .SetScore(321)
          .AddStringProperty("body", "baz bat")
          .Build();

  DocumentProto expected_document3 = DocumentBuilder()
                                         .SetKey("namespace2", "uri1")
                                         .SetSchema("email")
                                         .SetCreationTimestampMs(30)
                                         .SetScore(123)
                                         .AddStringProperty("subject", "phoo")
                                         .Build();

  // Document 1 and 3 were put normally, and document 2 was deleted in our
  // testdata files.
  EXPECT_THAT(
      icing
          .Get(expected_document1.namespace_(), expected_document1.uri(),
               GetResultSpecProto::default_instance())
          .document(),
      EqualsProto(expected_document1));
  EXPECT_THAT(icing
                  .Get(expected_deleted_document2.namespace_(),
                       expected_deleted_document2.uri(),
                       GetResultSpecProto::default_instance())
                  .status(),
              ProtoStatusIs(StatusProto::NOT_FOUND));
  EXPECT_THAT(
      icing
          .Get(expected_document3.namespace_(), expected_document3.uri(),
               GetResultSpecProto::default_instance())
          .document(),
      EqualsProto(expected_document3));

  // Searching for "foo" should get us document1.
  SearchSpecProto search_spec;
  search_spec.set_term_match_type(TermMatchType::PREFIX);
  search_spec.set_query("foo");

  SearchResultProto expected_document1_search;
  expected_document1_search.mutable_status()->set_code(StatusProto::OK);
  *expected_document1_search.mutable_results()->Add()->mutable_document() =
      expected_document1;

  SearchResultProto actual_results =
      icing.Search(search_spec, GetDefaultScoringSpec(),
                   ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results, EqualsSearchResultIgnoreStatsAndScores(
                                  expected_document1_search));

  // Searching for "baz" would've gotten us document2, except it got deleted.
  // Make sure that it's cleared from our index too.
  search_spec.set_query("baz");

  SearchResultProto expected_no_documents;
  expected_no_documents.mutable_status()->set_code(StatusProto::OK);

  actual_results = icing.Search(search_spec, GetDefaultScoringSpec(),
                                ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results,
              EqualsSearchResultIgnoreStatsAndScores(expected_no_documents));

  // Searching for "phoo" should get us document3.
  search_spec.set_query("phoo");

  SearchResultProto expected_document3_search;
  expected_document3_search.mutable_status()->set_code(StatusProto::OK);
  *expected_document3_search.mutable_results()->Add()->mutable_document() =
      expected_document3;

  actual_results = icing.Search(search_spec, GetDefaultScoringSpec(),
                                ResultSpecProto::default_instance());
  EXPECT_THAT(actual_results, EqualsSearchResultIgnoreStatsAndScores(
                                  expected_document3_search));
}

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