• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

realm / realm-core / 1866

24 Nov 2023 08:47PM UTC coverage: 91.684% (-0.004%) from 91.688%
1866

push

Evergreen

web-flow
Expand stacktrace buffer for tsan (#7167)

Change the default from 2 to 4 to help with 'failed to restore the stack' situation.
Also, dump stacktrace for ubsan.

92398 of 169288 branches covered (0.0%)

231686 of 252700 relevant lines covered (91.68%)

6247839.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.5
/src/realm/sync/noinst/client_reset.cpp
1
///////////////////////////////////////////////////////////////////////////
2
//
3
// Copyright 2021 Realm Inc.
4
//
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
16
//
17
////////////////////////////////////////////////////////////////////////////
18

19
#include <realm/transaction.hpp>
20
#include <realm/dictionary.hpp>
21
#include <realm/object_converter.hpp>
22
#include <realm/table_view.hpp>
23
#include <realm/set.hpp>
24

25
#include <realm/sync/history.hpp>
26
#include <realm/sync/changeset_parser.hpp>
27
#include <realm/sync/instruction_applier.hpp>
28
#include <realm/sync/noinst/client_history_impl.hpp>
29
#include <realm/sync/noinst/client_reset.hpp>
30
#include <realm/sync/noinst/client_reset_recovery.hpp>
31
#include <realm/sync/subscriptions.hpp>
32

33
#include <realm/util/compression.hpp>
34

35
#include <algorithm>
36
#include <chrono>
37
#include <vector>
38

39
using namespace realm;
40
using namespace _impl;
41
using namespace sync;
42

43
namespace realm {
44

45
std::ostream& operator<<(std::ostream& os, const ClientResyncMode& mode)
46
{
22,518✔
47
    switch (mode) {
22,518✔
48
        case ClientResyncMode::Manual:
✔
49
            os << "Manual";
×
50
            break;
×
51
        case ClientResyncMode::DiscardLocal:
11,186✔
52
            os << "DiscardLocal";
11,186✔
53
            break;
11,186✔
54
        case ClientResyncMode::Recover:
11,224✔
55
            os << "Recover";
11,224✔
56
            break;
11,224✔
57
        case ClientResyncMode::RecoverOrDiscard:
108✔
58
            os << "RecoverOrDiscard";
108✔
59
            break;
108✔
60
    }
22,518✔
61
    return os;
22,518✔
62
}
22,518✔
63

64
} // namespace realm
65

66
namespace realm::_impl::client_reset {
67

68
static inline bool should_skip_table(const Transaction& group, TableKey key)
69
{
241,200✔
70
    return !group.table_is_public(key);
241,200✔
71
}
241,200✔
72

73
void transfer_group(const Transaction& group_src, Transaction& group_dst, util::Logger& logger,
74
                    bool allow_schema_additions)
75
{
7,316✔
76
    logger.debug("transfer_group, src size = %1, dst size = %2, allow_schema_additions = %3", group_src.size(),
7,316✔
77
                 group_dst.size(), allow_schema_additions);
7,316✔
78

3,658✔
79
    // Turn off the sync history tracking during state transfer since it will be thrown
3,658✔
80
    // away immediately after anyways. This reduces the memory footprint of a client reset.
3,658✔
81
    ClientReplication* client_repl = dynamic_cast<ClientReplication*>(group_dst.get_replication());
7,316✔
82
    REALM_ASSERT_RELEASE(client_repl);
7,316✔
83
    TempShortCircuitReplication sync_history_guard(*client_repl);
7,316✔
84

3,658✔
85
    // Find all tables in dst that should be removed.
3,658✔
86
    std::set<std::string> tables_to_remove;
7,316✔
87
    for (auto table_key : group_dst.get_table_keys()) {
32,936✔
88
        if (should_skip_table(group_dst, table_key))
32,936✔
89
            continue;
15,384✔
90
        StringData table_name = group_dst.get_table_name(table_key);
17,552✔
91
        logger.debug("key = %1, table_name = %2", table_key.value, table_name);
17,552✔
92
        ConstTableRef table_src = group_src.get_table(table_name);
17,552✔
93
        if (!table_src) {
17,552✔
94
            logger.debug("Table '%1' will be removed", table_name);
40✔
95
            tables_to_remove.insert(table_name);
40✔
96
            continue;
40✔
97
        }
40✔
98
        // Check whether the table type is the same.
8,756✔
99
        TableRef table_dst = group_dst.get_table(table_key);
17,512✔
100
        auto pk_col_src = table_src->get_primary_key_column();
17,512✔
101
        auto pk_col_dst = table_dst->get_primary_key_column();
17,512✔
102
        bool has_pk_src = bool(pk_col_src);
17,512✔
103
        bool has_pk_dst = bool(pk_col_dst);
17,512✔
104
        if (has_pk_src != has_pk_dst) {
17,512✔
105
            throw ClientResetFailed(util::format("Client reset requires a primary key column in %1 table '%2'",
×
106
                                                 (has_pk_src ? "dest" : "source"), table_name));
×
107
        }
×
108
        if (!has_pk_src)
17,512✔
109
            continue;
648✔
110

8,432✔
111
        // Now the tables both have primary keys. Check type.
8,432✔
112
        if (pk_col_src.get_type() != pk_col_dst.get_type()) {
16,864✔
113
            throw ClientResetFailed(
4✔
114
                util::format("Client reset found incompatible primary key types (%1 vs %2) on '%3'",
4✔
115
                             pk_col_src.get_type(), pk_col_dst.get_type(), table_name));
4✔
116
        }
4✔
117
        // Check collection type, nullability etc. but having an index doesn't matter;
8,430✔
118
        ColumnAttrMask pk_col_src_attr = pk_col_src.get_attrs();
16,860✔
119
        ColumnAttrMask pk_col_dst_attr = pk_col_dst.get_attrs();
16,860✔
120
        pk_col_src_attr.reset(ColumnAttr::col_attr_Indexed);
16,860✔
121
        pk_col_dst_attr.reset(ColumnAttr::col_attr_Indexed);
16,860✔
122
        if (pk_col_src_attr != pk_col_dst_attr) {
16,860✔
123
            throw ClientResetFailed(
×
124
                util::format("Client reset found incompatible primary key attributes (%1 vs %2) on '%3'",
×
125
                             pk_col_src.value, pk_col_dst.value, table_name));
×
126
        }
×
127
        // Check name.
8,430✔
128
        StringData pk_col_name_src = table_src->get_column_name(pk_col_src);
16,860✔
129
        StringData pk_col_name_dst = table_dst->get_column_name(pk_col_dst);
16,860✔
130
        if (pk_col_name_src != pk_col_name_dst) {
16,860✔
131
            throw ClientResetFailed(
×
132
                util::format("Client reset requires equal pk column names but '%1' != '%2' on '%3'", pk_col_name_src,
×
133
                             pk_col_name_dst, table_name));
×
134
        }
×
135
        // The table survives.
8,430✔
136
        logger.debug("Table '%1' will remain", table_name);
16,860✔
137
    }
16,860✔
138

3,658✔
139
    // If there have been any tables marked for removal stop.
3,658✔
140
    // We consider two possible options for recovery:
3,658✔
141
    // 1: Remove the tables. But this will generate destructive schema
3,658✔
142
    //    schema changes that the local Realm cannot advance through.
3,658✔
143
    //    Since this action will fail down the line anyway, give up now.
3,658✔
144
    // 2: Keep the tables locally and ignore them. But the local app schema
3,658✔
145
    //    still has these classes and trying to modify anything in them will
3,658✔
146
    //    create sync instructions on tables that sync doesn't know about.
3,658✔
147
    // As an exception in recovery mode, we assume that the corresponding
3,658✔
148
    // additive schema changes will be part of the recovery upload. If they
3,658✔
149
    // are present, then the server can choose to allow them (if in dev mode).
3,658✔
150
    // If they are not present, then the server will emit an error the next time
3,658✔
151
    // a value is set on the unknown property.
3,658✔
152
    if (!allow_schema_additions && !tables_to_remove.empty()) {
7,314✔
153
        std::string names_list;
16✔
154
        for (const std::string& table_name : tables_to_remove) {
24✔
155
            names_list += Group::table_name_to_class_name(table_name);
24✔
156
            names_list += ", ";
24✔
157
        }
24✔
158
        if (names_list.size() > 2) {
16✔
159
            // remove the final ", "
8✔
160
            names_list = names_list.substr(0, names_list.size() - 2);
16✔
161
        }
16✔
162
        throw ClientResetFailed(
16✔
163
            util::format("Client reset cannot recover when classes have been removed: {%1}", names_list));
16✔
164
    }
16✔
165

3,648✔
166
    // Create new tables in dst if needed.
3,648✔
167
    for (auto table_key : group_src.get_table_keys()) {
25,092✔
168
        if (should_skip_table(group_src, table_key))
25,092✔
169
            continue;
7,596✔
170
        ConstTableRef table_src = group_src.get_table(table_key);
17,496✔
171
        StringData table_name = table_src->get_name();
17,496✔
172
        auto pk_col_src = table_src->get_primary_key_column();
17,496✔
173
        TableRef table_dst = group_dst.get_table(table_name);
17,496✔
174
        if (!table_dst) {
17,496✔
175
            // Create the table.
16✔
176
            if (table_src->is_embedded()) {
32✔
177
                REALM_ASSERT(!pk_col_src);
16✔
178
                group_dst.add_table(table_name, Table::Type::Embedded);
16✔
179
            }
16✔
180
            else {
16✔
181
                REALM_ASSERT(pk_col_src); // a sync table will have a pk
16✔
182
                auto pk_col_src = table_src->get_primary_key_column();
16✔
183
                DataType pk_type = DataType(pk_col_src.get_type());
16✔
184
                StringData pk_col_name = table_src->get_column_name(pk_col_src);
16✔
185
                group_dst.add_table_with_primary_key(table_name, pk_type, pk_col_name, pk_col_src.is_nullable(),
16✔
186
                                                     table_src->get_table_type());
16✔
187
            }
16✔
188
        }
32✔
189
    }
17,496✔
190

3,648✔
191
    // Now the class tables are identical.
3,648✔
192
    size_t num_tables;
7,296✔
193
    {
7,296✔
194
        size_t num_tables_src = 0;
7,296✔
195
        for (auto table_key : group_src.get_table_keys()) {
25,092✔
196
            if (!should_skip_table(group_src, table_key))
25,092✔
197
                ++num_tables_src;
17,496✔
198
        }
25,092✔
199
        size_t num_tables_dst = 0;
7,296✔
200
        for (auto table_key : group_dst.get_table_keys()) {
32,840✔
201
            if (!should_skip_table(group_dst, table_key))
32,840✔
202
                ++num_tables_dst;
17,512✔
203
        }
32,840✔
204
        REALM_ASSERT_EX(allow_schema_additions || num_tables_src == num_tables_dst, num_tables_src, num_tables_dst);
7,296✔
205
        num_tables = num_tables_src;
7,296✔
206
    }
7,296✔
207
    logger.debug("The number of tables is %1", num_tables);
7,296✔
208

3,648✔
209
    // Remove columns in dst if they are absent in src.
3,648✔
210
    for (auto table_key : group_src.get_table_keys()) {
25,088✔
211
        if (should_skip_table(group_src, table_key))
25,088✔
212
            continue;
7,596✔
213
        ConstTableRef table_src = group_src.get_table(table_key);
17,492✔
214
        StringData table_name = table_src->get_name();
17,492✔
215
        TableRef table_dst = group_dst.get_table(table_name);
17,492✔
216
        REALM_ASSERT(table_dst);
17,492✔
217
        std::vector<std::string> columns_to_remove;
17,492✔
218
        for (ColKey col_key : table_dst->get_column_keys()) {
56,240✔
219
            StringData col_name = table_dst->get_column_name(col_key);
56,240✔
220
            ColKey col_key_src = table_src->get_column_key(col_name);
56,240✔
221
            if (!col_key_src) {
56,240✔
222
                columns_to_remove.push_back(col_name);
32✔
223
                continue;
32✔
224
            }
32✔
225
        }
56,240✔
226
        if (!allow_schema_additions && !columns_to_remove.empty()) {
17,492✔
227
            std::string columns_list;
4✔
228
            for (const std::string& col_name : columns_to_remove) {
12✔
229
                columns_list += col_name;
12✔
230
                columns_list += ", ";
12✔
231
            }
12✔
232
            throw ClientResetFailed(
4✔
233
                util::format("Client reset cannot recover when columns have been removed from '%1': {%2}", table_name,
4✔
234
                             columns_list));
4✔
235
        }
4✔
236
    }
17,492✔
237

3,648✔
238
    // Add columns in dst if present in src and absent in dst.
3,648✔
239
    for (auto table_key : group_src.get_table_keys()) {
25,068✔
240
        if (should_skip_table(group_src, table_key))
25,068✔
241
            continue;
7,596✔
242
        ConstTableRef table_src = group_src.get_table(table_key);
17,472✔
243
        StringData table_name = table_src->get_name();
17,472✔
244
        TableRef table_dst = group_dst.get_table(table_name);
17,472✔
245
        REALM_ASSERT(table_dst);
17,472✔
246
        for (ColKey col_key : table_src->get_column_keys()) {
56,252✔
247
            StringData col_name = table_src->get_column_name(col_key);
56,252✔
248
            ColKey col_key_dst = table_dst->get_column_key(col_name);
56,252✔
249
            if (!col_key_dst) {
56,252✔
250
                DataType col_type = table_src->get_column_type(col_key);
128✔
251
                bool nullable = col_key.is_nullable();
128✔
252
                auto search_index_type = table_src->search_index_type(col_key);
128✔
253
                logger.trace("Create column, table = %1, column name = %2, "
128✔
254
                             " type = %3, nullable = %4, search_index = %5",
128✔
255
                             table_name, col_name, col_key.get_type(), nullable, search_index_type);
128✔
256
                ColKey col_key_dst;
128✔
257
                if (Table::is_link_type(col_key.get_type())) {
128✔
258
                    ConstTableRef target_src = table_src->get_link_target(col_key);
48✔
259
                    TableRef target_dst = group_dst.get_table(target_src->get_name());
48✔
260
                    if (col_key.is_list()) {
48✔
261
                        col_key_dst = table_dst->add_column_list(*target_dst, col_name);
16✔
262
                    }
16✔
263
                    else if (col_key.is_set()) {
32✔
264
                        col_key_dst = table_dst->add_column_set(*target_dst, col_name);
×
265
                    }
×
266
                    else if (col_key.is_dictionary()) {
32✔
267
                        DataType key_type = table_src->get_dictionary_key_type(col_key);
8✔
268
                        col_key_dst = table_dst->add_column_dictionary(*target_dst, col_name, key_type);
8✔
269
                    }
8✔
270
                    else {
24✔
271
                        REALM_ASSERT(!col_key.is_collection());
24✔
272
                        col_key_dst = table_dst->add_column(*target_dst, col_name);
24✔
273
                    }
24✔
274
                }
48✔
275
                else if (col_key.is_list()) {
80✔
276
                    col_key_dst = table_dst->add_column_list(col_type, col_name, nullable);
8✔
277
                }
8✔
278
                else if (col_key.is_set()) {
72✔
279
                    col_key_dst = table_dst->add_column_set(col_type, col_name, nullable);
8✔
280
                }
8✔
281
                else if (col_key.is_dictionary()) {
64✔
282
                    DataType key_type = table_src->get_dictionary_key_type(col_key);
8✔
283
                    col_key_dst = table_dst->add_column_dictionary(col_type, col_name, nullable, key_type);
8✔
284
                }
8✔
285
                else {
56✔
286
                    REALM_ASSERT(!col_key.is_collection());
56✔
287
                    col_key_dst = table_dst->add_column(col_type, col_name, nullable);
56✔
288
                }
56✔
289

64✔
290
                if (search_index_type != IndexType::None)
128✔
291
                    table_dst->add_search_index(col_key_dst, search_index_type);
×
292
            }
128✔
293
            else {
56,124✔
294
                // column preexists in dest, make sure the types match
28,062✔
295
                if (col_key.get_type() != col_key_dst.get_type()) {
56,124✔
296
                    throw ClientResetFailed(util::format(
8✔
297
                        "Incompatable column type change detected during client reset for '%1.%2' (%3 vs %4)",
8✔
298
                        table_name, col_name, col_key.get_type(), col_key_dst.get_type()));
8✔
299
                }
8✔
300
                ColumnAttrMask src_col_attrs = col_key.get_attrs();
56,116✔
301
                ColumnAttrMask dst_col_attrs = col_key_dst.get_attrs();
56,116✔
302
                src_col_attrs.reset(ColumnAttr::col_attr_Indexed);
56,116✔
303
                dst_col_attrs.reset(ColumnAttr::col_attr_Indexed);
56,116✔
304
                // make sure the attributes such as collection type, nullability etc. match
28,058✔
305
                // but index equality doesn't matter here.
28,058✔
306
                if (src_col_attrs != dst_col_attrs) {
56,116✔
307
                    throw ClientResetFailed(util::format(
×
308
                        "Incompatable column attribute change detected during client reset for '%1.%2' (%3 vs %4)",
×
309
                        table_name, col_name, col_key.value, col_key_dst.value));
×
310
                }
×
311
            }
56,116✔
312
        }
56,252✔
313
    }
17,472✔
314

3,646✔
315
    // Now the schemas are identical.
3,646✔
316

3,646✔
317
    // Remove objects in dst that are absent in src.
3,646✔
318
    for (auto table_key : group_src.get_table_keys()) {
25,028✔
319
        if (should_skip_table(group_src, table_key))
25,028✔
320
            continue;
7,572✔
321
        auto table_src = group_src.get_table(table_key);
17,456✔
322
        // There are no primary keys in embedded tables but this is ok, because
8,728✔
323
        // embedded objects are tied to the lifetime of top level objects.
8,728✔
324
        if (table_src->is_embedded())
17,456✔
325
            continue;
664✔
326
        StringData table_name = table_src->get_name();
16,792✔
327
        logger.debug("Removing objects in '%1'", table_name);
16,792✔
328
        auto table_dst = group_dst.get_table(table_name);
16,792✔
329

8,396✔
330
        auto pk_col = table_dst->get_primary_key_column();
16,792✔
331
        REALM_ASSERT_DEBUG(pk_col); // sync realms always have a pk
16,792✔
332
        std::vector<std::pair<Mixed, ObjKey>> objects_to_remove;
16,792✔
333
        for (auto obj : *table_dst) {
24,738✔
334
            auto pk = obj.get_any(pk_col);
24,738✔
335
            if (!table_src->find_primary_key(pk)) {
24,738✔
336
                objects_to_remove.emplace_back(pk, obj.get_key());
938✔
337
            }
938✔
338
        }
24,738✔
339
        for (auto& pair : objects_to_remove) {
8,864✔
340
            logger.debug("  removing '%1'", pair.first);
938✔
341
            table_dst->remove_object(pair.second);
938✔
342
        }
938✔
343
    }
16,792✔
344

3,642✔
345
    // We must re-create any missing objects that are absent in dst before trying to copy
3,642✔
346
    // their properties because creating them may re-create any dangling links which would
3,642✔
347
    // otherwise cause inconsistencies when re-creating lists of links.
3,642✔
348
    for (auto table_key : group_src.get_table_keys()) {
25,028✔
349
        ConstTableRef table_src = group_src.get_table(table_key);
25,028✔
350
        auto table_name = table_src->get_name();
25,028✔
351
        if (should_skip_table(group_src, table_key) || table_src->is_embedded())
25,028✔
352
            continue;
8,236✔
353
        TableRef table_dst = group_dst.get_table(table_name);
16,792✔
354
        auto pk_col = table_src->get_primary_key_column();
16,792✔
355
        REALM_ASSERT(pk_col);
16,792✔
356
        logger.debug("Creating missing objects for table '%1', number of rows = %2, "
16,792✔
357
                     "primary_key_col = %3, primary_key_type = %4",
16,792✔
358
                     table_name, table_src->size(), pk_col.get_index().val, pk_col.get_type());
16,792✔
359
        for (const Obj& src : *table_src) {
24,476✔
360
            bool created = false;
24,476✔
361
            table_dst->create_object_with_primary_key(src.get_primary_key(), &created);
24,476✔
362
            if (created) {
24,476✔
363
                logger.debug("   created %1", src.get_primary_key());
676✔
364
            }
676✔
365
        }
24,476✔
366
    }
16,792✔
367

3,642✔
368
    converters::EmbeddedObjectConverter embedded_tracker;
7,284✔
369
    // Now src and dst have identical schemas and all the top level objects are created.
3,642✔
370
    // What is left to do is to diff all properties of the existing objects.
3,642✔
371
    // Embedded objects are created on the fly.
3,642✔
372
    for (auto table_key : group_src.get_table_keys()) {
25,028✔
373
        if (should_skip_table(group_src, table_key))
25,028✔
374
            continue;
7,572✔
375
        ConstTableRef table_src = group_src.get_table(table_key);
17,456✔
376
        // Embedded objects don't have a primary key, so they are handled
8,728✔
377
        // as a special case when they are encountered as a link value.
8,728✔
378
        if (table_src->is_embedded())
17,456✔
379
            continue;
664✔
380
        StringData table_name = table_src->get_name();
16,792✔
381
        TableRef table_dst = group_dst.get_table(table_name);
16,792✔
382
        REALM_ASSERT_EX(allow_schema_additions || table_src->get_column_count() == table_dst->get_column_count(),
16,792✔
383
                        allow_schema_additions, table_src->get_column_count(), table_dst->get_column_count());
16,792✔
384
        auto pk_col = table_src->get_primary_key_column();
16,792✔
385
        REALM_ASSERT(pk_col);
16,792✔
386
        logger.debug("Updating values for table '%1', number of rows = %2, "
16,792✔
387
                     "number of columns = %3, primary_key_col = %4, "
16,792✔
388
                     "primary_key_type = %5",
16,792✔
389
                     table_name, table_src->size(), table_src->get_column_count(), pk_col.get_index().val,
16,792✔
390
                     pk_col.get_type());
16,792✔
391

8,396✔
392
        converters::InterRealmObjectConverter converter(table_src, table_dst, &embedded_tracker);
16,792✔
393

8,396✔
394
        for (const Obj& src : *table_src) {
24,476✔
395
            auto src_pk = src.get_primary_key();
24,476✔
396
            // create the object - it should have been created above.
12,238✔
397
            auto dst = table_dst->get_object_with_primary_key(src_pk);
24,476✔
398
            REALM_ASSERT(dst);
24,476✔
399

12,238✔
400
            bool updated = false;
24,476✔
401
            converter.copy(src, dst, &updated);
24,476✔
402
            if (updated) {
24,476✔
403
                logger.debug("  updating %1", src_pk);
7,712✔
404
            }
7,712✔
405
        }
24,476✔
406
        embedded_tracker.process_pending();
16,792✔
407
    }
16,792✔
408
}
7,284✔
409

410
// A table without a "class_" prefix will not generate sync instructions.
411
constexpr static std::string_view s_meta_reset_table_name("client_reset_metadata");
412
constexpr static std::string_view s_pk_col_name("id");
413
constexpr static std::string_view s_version_column_name("version");
414
constexpr static std::string_view s_timestamp_col_name("event_time");
415
constexpr static std::string_view s_reset_type_col_name("type_of_reset");
416
constexpr int64_t metadata_version = 1;
417

418
void remove_pending_client_resets(Transaction& wt)
419
{
212✔
420
    if (auto table = wt.get_table(s_meta_reset_table_name); table && !table->is_empty()) {
212✔
421
        table->clear();
212✔
422
    }
212✔
423
}
212✔
424

425
util::Optional<PendingReset> has_pending_reset(const Transaction& rt)
426
{
17,420✔
427
    ConstTableRef table = rt.get_table(s_meta_reset_table_name);
17,420✔
428
    if (!table || table->size() == 0) {
17,420✔
429
        return util::none;
16,656✔
430
    }
16,656✔
431
    ColKey timestamp_col = table->get_column_key(s_timestamp_col_name);
764✔
432
    ColKey type_col = table->get_column_key(s_reset_type_col_name);
764✔
433
    ColKey version_col = table->get_column_key(s_version_column_name);
764✔
434
    REALM_ASSERT(timestamp_col);
764✔
435
    REALM_ASSERT(type_col);
764✔
436
    REALM_ASSERT(version_col);
764✔
437
    if (table->size() > 1) {
764✔
438
        // this may happen if a future version of this code changes the format and expectations around reset metadata.
439
        throw ClientResetFailed(
×
440
            util::format("Previous client resets detected (%1) but only one is expected.", table->size()));
×
441
    }
×
442
    Obj first = *table->begin();
764✔
443
    REALM_ASSERT(first);
764✔
444
    PendingReset pending;
764✔
445
    int64_t version = first.get<int64_t>(version_col);
764✔
446
    pending.time = first.get<Timestamp>(timestamp_col);
764✔
447
    if (version > metadata_version) {
764✔
448
        throw ClientResetFailed(util::format("Unsupported client reset metadata version: %1 vs %2, from %3", version,
×
449
                                             metadata_version, pending.time));
×
450
    }
×
451
    int64_t type = first.get<int64_t>(type_col);
764✔
452
    if (type == 0) {
764✔
453
        pending.type = ClientResyncMode::DiscardLocal;
436✔
454
    }
436✔
455
    else if (type == 1) {
328✔
456
        pending.type = ClientResyncMode::Recover;
328✔
457
    }
328✔
458
    else {
×
459
        throw ClientResetFailed(
×
460
            util::format("Unsupported client reset metadata type: %1 from %2", type, pending.time));
×
461
    }
×
462
    return pending;
764✔
463
}
764✔
464

465
void track_reset(Transaction& wt, ClientResyncMode mode)
466
{
7,344✔
467
    REALM_ASSERT(mode != ClientResyncMode::Manual);
7,344✔
468
    TableRef table = wt.get_table(s_meta_reset_table_name);
7,344✔
469
    ColKey version_col, timestamp_col, type_col;
7,344✔
470
    if (!table) {
7,344✔
471
        table = wt.add_table_with_primary_key(s_meta_reset_table_name, type_ObjectId, s_pk_col_name);
7,300✔
472
        REALM_ASSERT(table);
7,300✔
473
        version_col = table->add_column(type_Int, s_version_column_name);
7,300✔
474
        timestamp_col = table->add_column(type_Timestamp, s_timestamp_col_name);
7,300✔
475
        type_col = table->add_column(type_Int, s_reset_type_col_name);
7,300✔
476
    }
7,300✔
477
    else {
44✔
478
        version_col = table->get_column_key(s_version_column_name);
44✔
479
        timestamp_col = table->get_column_key(s_timestamp_col_name);
44✔
480
        type_col = table->get_column_key(s_reset_type_col_name);
44✔
481
    }
44✔
482
    REALM_ASSERT(version_col);
7,344✔
483
    REALM_ASSERT(timestamp_col);
7,344✔
484
    REALM_ASSERT(type_col);
7,344✔
485
    int64_t mode_val = 0; // Discard
7,344✔
486
    if (mode == ClientResyncMode::Recover || mode == ClientResyncMode::RecoverOrDiscard) {
7,344✔
487
        mode_val = 1; // Recover
3,688✔
488
    }
3,688✔
489

3,672✔
490
    if (table->size() > 1) {
7,344✔
491
        // this may happen if a future version of this code changes the format and expectations around reset metadata.
492
        throw ClientResetFailed(
×
493
            util::format("Previous client resets detected (%1) but only one is expected.", table->size()));
×
494
    }
×
495
    table->create_object_with_primary_key(ObjectId::gen(),
7,344✔
496
                                          {{version_col, metadata_version},
7,344✔
497
                                           {timestamp_col, Timestamp(std::chrono::system_clock::now())},
7,344✔
498
                                           {type_col, mode_val}});
7,344✔
499

3,672✔
500
    wt.commit_and_continue_writing();
7,344✔
501
}
7,344✔
502

503
static ClientResyncMode reset_precheck_guard(Transaction& wt, ClientResyncMode mode, bool recovery_is_allowed,
504
                                             util::Logger& logger)
505
{
7,344✔
506
    if (auto previous_reset = has_pending_reset(wt)) {
7,344✔
507
        logger.info("A previous reset was detected of type: '%1' at: %2", previous_reset->type, previous_reset->time);
32✔
508
        switch (previous_reset->type) {
32✔
509
            case ClientResyncMode::Manual:
✔
510
                REALM_UNREACHABLE();
511
            case ClientResyncMode::DiscardLocal:
12✔
512
                throw ClientResetFailed(util::format("A previous '%1' mode reset from %2 did not succeed, "
12✔
513
                                                     "giving up on '%3' mode to prevent a cycle",
12✔
514
                                                     previous_reset->type, previous_reset->time, mode));
12✔
515
            case ClientResyncMode::Recover:
20✔
516
                switch (mode) {
20✔
517
                    case ClientResyncMode::Recover:
8✔
518
                        throw ClientResetFailed(util::format("A previous '%1' mode reset from %2 did not succeed, "
8✔
519
                                                             "giving up on '%3' mode to prevent a cycle",
8✔
520
                                                             previous_reset->type, previous_reset->time, mode));
8✔
521
                    case ClientResyncMode::RecoverOrDiscard:
8✔
522
                        mode = ClientResyncMode::DiscardLocal;
8✔
523
                        logger.info("A previous '%1' mode reset from %2 downgrades this mode ('%3') to DiscardLocal",
8✔
524
                                    previous_reset->type, previous_reset->time, mode);
8✔
525
                        remove_pending_client_resets(wt);
8✔
526
                        break;
8✔
527
                    case ClientResyncMode::DiscardLocal:
4✔
528
                        remove_pending_client_resets(wt);
4✔
529
                        // previous mode Recover and this mode is Discard, this is not a cycle yet
2✔
530
                        break;
4✔
531
                    case ClientResyncMode::Manual:
✔
532
                        REALM_UNREACHABLE();
533
                }
20✔
534
                break;
16✔
535
            case ClientResyncMode::RecoverOrDiscard:
10✔
536
                throw ClientResetFailed(util::format("Unexpected previous '%1' mode reset from %2 did not "
×
537
                                                     "succeed, giving up on '%3' mode to prevent a cycle",
×
538
                                                     previous_reset->type, previous_reset->time, mode));
×
539
        }
7,324✔
540
    }
7,324✔
541
    if (!recovery_is_allowed) {
7,324✔
542
        if (mode == ClientResyncMode::Recover) {
24✔
543
            throw ClientResetFailed(
4✔
544
                "Client reset mode is set to 'Recover' but the server does not allow recovery for this client");
4✔
545
        }
4✔
546
        else if (mode == ClientResyncMode::RecoverOrDiscard) {
20✔
547
            logger.info("Client reset in 'RecoverOrDiscard' is choosing 'DiscardLocal' because the server does not "
12✔
548
                        "permit recovery for this client");
12✔
549
            mode = ClientResyncMode::DiscardLocal;
12✔
550
        }
12✔
551
    }
24✔
552
    track_reset(wt, mode);
7,322✔
553
    return mode;
7,320✔
554
}
7,324✔
555

556
LocalVersionIDs perform_client_reset_diff(DB& db_local, DB& db_remote, sync::SaltedFileIdent client_file_ident,
557
                                          util::Logger& logger, ClientResyncMode mode, bool recovery_is_allowed,
558
                                          bool* did_recover_out, sync::SubscriptionStore* sub_store,
559
                                          util::FunctionRef<void(int64_t)> on_flx_version_complete)
560
{
7,344✔
561
    auto wt_local = db_local.start_write();
7,344✔
562
    auto actual_mode = reset_precheck_guard(*wt_local, mode, recovery_is_allowed, logger);
7,344✔
563
    bool recover_local_changes =
7,344✔
564
        actual_mode == ClientResyncMode::Recover || actual_mode == ClientResyncMode::RecoverOrDiscard;
7,344✔
565

3,672✔
566
    logger.info("Client reset: path_local = %1, "
7,344✔
567
                "client_file_ident = (ident: %2, salt: %3), "
7,344✔
568
                "remote_path = %4, requested_mode = %5, recovery_is_allowed = %6, "
7,344✔
569
                "actual_mode = %7, will_recover = %8",
7,344✔
570
                db_local.get_path(), client_file_ident.ident, client_file_ident.salt, db_remote.get_path(), mode,
7,344✔
571
                recovery_is_allowed, actual_mode, recover_local_changes);
7,344✔
572

3,672✔
573
    auto& repl_local = dynamic_cast<ClientReplication&>(*db_local.get_replication());
7,344✔
574
    auto& history_local = repl_local.get_history();
7,344✔
575
    history_local.ensure_updated(wt_local->get_version());
7,344✔
576
    SaltedFileIdent orig_file_ident = history_local.get_client_file_ident(*wt_local);
7,344✔
577
    VersionID old_version_local = wt_local->get_version_of_current_transaction();
7,344✔
578

3,672✔
579
    auto& repl_remote = dynamic_cast<ClientReplication&>(*db_remote.get_replication());
7,344✔
580
    auto& history_remote = repl_remote.get_history();
7,344✔
581

3,672✔
582
    sync::SaltedVersion fresh_server_version = {0, 0};
7,344✔
583
    {
7,344✔
584
        SyncProgress remote_progress;
7,344✔
585
        sync::version_type remote_version_unused;
7,344✔
586
        SaltedFileIdent remote_ident_unused;
7,344✔
587
        history_remote.get_status(remote_version_unused, remote_ident_unused, remote_progress);
7,344✔
588
        fresh_server_version = remote_progress.latest_server_version;
7,344✔
589
    }
7,344✔
590

3,672✔
591
    if (!recover_local_changes) {
7,344✔
592
        auto rt_remote = db_remote.start_read();
3,644✔
593
        // transform the local Realm such that all public tables become identical to the remote Realm
1,822✔
594
        transfer_group(*rt_remote, *wt_local, logger, false);
3,644✔
595

1,822✔
596
        // now that the state of the fresh and local Realms are identical,
1,822✔
597
        // reset the local sync history and steal the fresh Realm's ident
1,822✔
598
        history_local.set_client_reset_adjustments(wt_local->get_version(), client_file_ident, fresh_server_version,
3,644✔
599
                                                   BinaryData());
3,644✔
600

1,822✔
601
        int64_t subscription_version = 0;
3,644✔
602
        if (sub_store) {
3,644✔
603
            subscription_version = sub_store->set_active_as_latest(*wt_local);
48✔
604
        }
48✔
605

1,822✔
606
        wt_local->commit_and_continue_as_read();
3,644✔
607
        if (did_recover_out) {
3,644✔
608
            *did_recover_out = false;
196✔
609
        }
196✔
610
        on_flx_version_complete(subscription_version);
3,644✔
611

1,822✔
612
        VersionID new_version_local = wt_local->get_version_of_current_transaction();
3,644✔
613
        logger.info("perform_client_reset_diff is done: old_version = (version: %1, index: %2), "
3,644✔
614
                    "new_version = (version: %3, index: %4)",
3,644✔
615
                    old_version_local.version, old_version_local.index, new_version_local.version,
3,644✔
616
                    new_version_local.index);
3,644✔
617
        return LocalVersionIDs{old_version_local, new_version_local};
3,644✔
618
    }
3,644✔
619

1,850✔
620
    auto remake_active_subscription = [&]() {
3,700✔
621
        if (!sub_store) {
68✔
622
            return;
×
623
        }
×
624
        auto subs = sub_store->get_active();
68✔
625
        int64_t before_version = subs.version();
68✔
626
        auto mut_subs = subs.make_mutable_copy();
68✔
627
        mut_subs.update_state(sync::SubscriptionSet::State::Complete);
68✔
628
        auto sub = std::move(mut_subs).commit();
68✔
629
        on_flx_version_complete(sub.version());
68✔
630
        logger.info("Recreated the active subscription set in the complete state (%1 -> %2)", before_version,
68✔
631
                    sub.version());
68✔
632
    };
68✔
633

1,850✔
634
    auto frozen_pre_local_state = db_local.start_frozen();
3,700✔
635
    auto local_changes = history_local.get_local_changes(wt_local->get_version());
3,700✔
636
    logger.info("Local changesets to recover: %1", local_changes.size());
3,700✔
637

1,850✔
638
    auto wt_remote = db_remote.start_write();
3,700✔
639

1,850✔
640
    BinaryData recovered_changeset;
3,700✔
641

1,850✔
642
    // FLX with recovery has to be done in multiple commits, which is significantly different than other modes
1,850✔
643
    if (sub_store) {
3,700✔
644
        // In FLX recovery, save a copy of the pending subscriptions for later. This
36✔
645
        // needs to be done before they are wiped out by remake_active_subscription()
36✔
646
        std::vector<SubscriptionSet> pending_subscriptions = sub_store->get_pending_subscriptions();
72✔
647
        // transform the local Realm such that all public tables become identical to the remote Realm
36✔
648
        transfer_group(*wt_remote, *wt_local, logger, recover_local_changes);
72✔
649
        // now that the state of the fresh and local Realms are identical,
36✔
650
        // reset the local sync history.
36✔
651
        // Note that we do not set the new file ident yet! This is done in the last commit.
36✔
652
        history_local.set_client_reset_adjustments(wt_local->get_version(), orig_file_ident, fresh_server_version,
72✔
653
                                                   recovered_changeset);
72✔
654
        // The local Realm is committed. There are no changes to the remote Realm.
36✔
655
        wt_remote->rollback_and_continue_as_read();
72✔
656
        wt_local->commit_and_continue_as_read();
72✔
657
        // Make a copy of the active subscription set and mark it as
36✔
658
        // complete. This will cause all other subscription sets to become superceded.
36✔
659
        remake_active_subscription();
72✔
660
        // Apply local changes interleaved with pending subscriptions in separate commits
36✔
661
        // as needed. This has the consequence that there may be extra notifications along
36✔
662
        // the way to the final state, but since separate commits are necessary, this is
36✔
663
        // unavoidable.
36✔
664
        wt_local = db_local.start_write();
72✔
665
        RecoverLocalChangesetsHandler handler{*wt_local, *frozen_pre_local_state, logger};
72✔
666
        handler.process_changesets(local_changes, std::move(pending_subscriptions)); // throws on error
72✔
667
        // The new file ident is set as part of the final commit. This is to ensure that if
36✔
668
        // there are any exceptions during recovery, or the process is killed for some
36✔
669
        // reason, the client reset cycle detection will catch this and we will not attempt
36✔
670
        // to recover again. If we had set the ident in the first commit, a Realm which was
36✔
671
        // partially recovered, but interrupted may continue sync the next time it is
36✔
672
        // opened with only partially recovered state while having lost the history of any
36✔
673
        // offline modifications.
36✔
674
        history_local.set_client_file_ident_in_wt(wt_local->get_version(), client_file_ident);
72✔
675
        wt_local->commit_and_continue_as_read();
72✔
676
    }
72✔
677
    else {
3,628✔
678
        // In PBS recovery, the strategy is to apply all local changes to the remote realm first,
1,814✔
679
        // and then transfer the modified state all at once to the local Realm. This creates a
1,814✔
680
        // nice side effect for notifications because only the minimal state change is made.
1,814✔
681
        RecoverLocalChangesetsHandler handler{*wt_remote, *frozen_pre_local_state, logger};
3,628✔
682
        handler.process_changesets(local_changes, {}); // throws on error
3,628✔
683
        ChangesetEncoder& encoder = repl_remote.get_instruction_encoder();
3,628✔
684
        const sync::ChangesetEncoder::Buffer& buffer = encoder.buffer();
3,628✔
685
        recovered_changeset = {buffer.data(), buffer.size()};
3,628✔
686

1,814✔
687
        // transform the local Realm such that all public tables become identical to the remote Realm
1,814✔
688
        transfer_group(*wt_remote, *wt_local, logger, recover_local_changes);
3,628✔
689

1,814✔
690
        // now that the state of the fresh and local Realms are identical,
1,814✔
691
        // reset the local sync history and steal the fresh Realm's ident
1,814✔
692
        history_local.set_client_reset_adjustments(wt_local->get_version(), client_file_ident, fresh_server_version,
3,628✔
693
                                                   recovered_changeset);
3,628✔
694

1,814✔
695
        // Finally, the local Realm is committed. The changes to the remote Realm are discarded.
1,814✔
696
        wt_remote->rollback_and_continue_as_read();
3,628✔
697
        wt_local->commit_and_continue_as_read();
3,628✔
698
    }
3,628✔
699

1,850✔
700
    if (did_recover_out) {
3,700✔
701
        *did_recover_out = true;
136✔
702
    }
136✔
703
    VersionID new_version_local = wt_local->get_version_of_current_transaction();
3,700✔
704
    logger.info("perform_client_reset_diff is done, old_version.version = %1, "
3,700✔
705
                "old_version.index = %2, new_version.version = %3, "
3,700✔
706
                "new_version.index = %4",
3,700✔
707
                old_version_local.version, old_version_local.index, new_version_local.version,
3,700✔
708
                new_version_local.index);
3,700✔
709

1,850✔
710
    return LocalVersionIDs{old_version_local, new_version_local};
3,700✔
711
}
3,700✔
712

713
} // namespace realm::_impl::client_reset
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc