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

realm / realm-core / github_pull_request_275914

25 Sep 2023 03:10PM UTC coverage: 92.915% (+1.7%) from 91.215%
github_pull_request_275914

Pull #6073

Evergreen

jedelbo
Merge tag 'v13.21.0' into next-major

"Feature/Bugfix release"
Pull Request #6073: Merge next-major

96928 of 177706 branches covered (0.0%)

8324 of 8714 new or added lines in 122 files covered. (95.52%)

181 existing lines in 28 files now uncovered.

247505 of 266379 relevant lines covered (92.91%)

7164945.17 hits per line

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

71.09
/src/realm/sync/transform.cpp
1
#include <algorithm>
2
#include <functional>
3
#include <utility>
4
#include <vector>
5
#include <map>
6
#include <sstream>
7
#include <fstream>
8

9
#if REALM_DEBUG
10
#include <iostream> // std::cerr used for debug tracing
11
#include <mutex>    // std::unique_lock used for debug tracing
12
#endif              // REALM_DEBUG
13

14
#include <realm/util/buffer.hpp>
15
#include <realm/string_data.hpp>
16
#include <realm/data_type.hpp>
17
#include <realm/mixed.hpp>
18
#include <realm/column_fwd.hpp>
19
#include <realm/db.hpp>
20
#include <realm/impl/transact_log.hpp>
21
#include <realm/replication.hpp>
22
#include <realm/sync/instructions.hpp>
23
#include <realm/sync/protocol.hpp>
24
#include <realm/sync/transform.hpp>
25
#include <realm/sync/changeset_parser.hpp>
26
#include <realm/sync/changeset_encoder.hpp>
27
#include <realm/sync/noinst/changeset_index.hpp>
28
#include <realm/sync/noinst/protocol_codec.hpp>
29
#include <realm/util/logger.hpp>
30

31
namespace realm {
32

33
namespace {
34

35
#if REALM_DEBUG
36
#if defined(_MSC_VER)
37
#define TERM_RED ""
38
#define TERM_YELLOW ""
39
#define TERM_CYAN ""
40
#define TERM_MAGENTA ""
41
#define TERM_GREEN ""
42
#define TERM_BOLD ""
43
#define TERM_RESET ""
44
#else
45
#define TERM_RED "\x1b[31;22m"
×
46
#define TERM_YELLOW "\x1b[33;22m"
×
47
#define TERM_CYAN "\x1b[36;22m"
×
48
#define TERM_MAGENTA "\x1b[35;22m"
×
49
#define TERM_GREEN "\x1b[32;22m"
50
#define TERM_BOLD "\x1b[1m"
51
#define TERM_RESET "\x1b[39;49;22m"
×
52
#endif
53
#endif
54

55
} // unnamed namespace
56

57
using namespace realm;
58
using namespace realm::sync;
59
using namespace realm::util;
60

61
namespace _impl {
62

63
struct TransformerImpl::Discriminant {
64
    timestamp_type timestamp;
65
    file_ident_type client_file_ident;
66
    Discriminant(timestamp_type t, file_ident_type p)
67
        : timestamp(t)
68
        , client_file_ident(p)
69
    {
11,917,438✔
70
    }
11,917,438✔
71

72
    Discriminant(const Discriminant&) = default;
73
    Discriminant& operator=(const Discriminant&) = default;
74

75
    bool operator<(const Discriminant& other) const
76
    {
32,388✔
77
        return timestamp == other.timestamp ? (client_file_ident < other.client_file_ident)
17,164✔
78
                                            : timestamp < other.timestamp;
31,878✔
79
    }
32,388✔
80

81
    bool operator==(const Discriminant& other) const
82
    {
×
83
        return timestamp == other.timestamp && client_file_ident == other.client_file_ident;
×
84
    }
×
85
    bool operator!=(const Discriminant& other) const
86
    {
×
87
        return !((*this) == other);
×
88
    }
×
89
};
90

91
struct TransformerImpl::Side {
92
    Transformer& m_transformer;
93
    Changeset* m_changeset = nullptr;
94
    Discriminant m_discriminant;
95

96
    bool was_discarded = false;
97
    bool was_replaced = false;
98
    size_t m_path_len = 0;
99

100
    Side(Transformer& transformer)
101
        : m_transformer(transformer)
102
        , m_discriminant(0, 0)
103
    {
832,348✔
104
    }
832,348✔
105

106
    virtual void skip_tombstones() noexcept = 0;
107
    virtual void next_instruction() noexcept = 0;
108
    virtual Instruction& get() noexcept = 0;
109

110
    void substitute(const Instruction& instr)
111
    {
×
112
        was_replaced = true;
×
113
        get() = instr;
×
114
    }
×
115

116
    StringData get_string(StringBufferRange range) const
117
    {
32✔
118
        // Relying on the transaction parser to only provide valid StringBufferRanges.
16✔
119
        return m_changeset->get_string(range);
32✔
120
    }
32✔
121

122
    StringData get_string(InternString intern_string) const
123
    {
34,954✔
124
        // Rely on the parser having checked the consistency of the interned strings
17,314✔
125
        return m_changeset->get_string(intern_string);
34,954✔
126
    }
34,954✔
127

128
    InternString intern_string(StringData data) const
129
    {
×
130
        return m_changeset->intern_string(data);
×
131
    }
×
132

133
    const Discriminant& timestamp() const
134
    {
64,776✔
135
        return m_discriminant;
64,776✔
136
    }
64,776✔
137

138
    InternString adopt_string(const Side& other_side, InternString other_string)
139
    {
×
140
        // FIXME: This needs to change if we choose to compare strings through a
141
        // mapping of InternStrings.
142
        StringData string = other_side.get_string(other_string);
×
143
        return intern_string(string);
×
144
    }
×
145

146
    Instruction::PrimaryKey adopt_key(const Side& other_side, const Instruction::PrimaryKey& other_key)
147
    {
×
148
        if (auto str = mpark::get_if<InternString>(&other_key)) {
×
149
            return adopt_string(other_side, *str);
×
150
        }
×
151
        else {
×
152
            // Non-string keys do not need to be adopted.
×
153
            return other_key;
×
154
        }
×
155
    }
×
156

157
    void adopt_path(Instruction::PathInstruction& instr, const Side& other_side,
158
                    const Instruction::PathInstruction& other)
159
    {
×
160
        instr.table = adopt_string(other_side, other.table);
×
161
        instr.object = adopt_key(other_side, other.object);
×
162
        instr.field = adopt_string(other_side, other.field);
×
NEW
163
        instr.path.m_path.clear();
×
NEW
164
        instr.path.m_path.reserve(other.path.size());
×
NEW
165
        for (auto& element : other.path.m_path) {
×
166
            auto push = util::overload{
×
167
                [&](uint32_t index) {
×
NEW
168
                    instr.path.m_path.push_back(index);
×
169
                },
×
170
                [&](InternString str) {
×
NEW
171
                    instr.path.m_path.push_back(adopt_string(other_side, str));
×
172
                },
×
173
            };
×
174
            mpark::visit(push, element);
×
175
        }
×
176
    }
×
177

178
protected:
179
    void init_with_instruction(const Instruction& instr) noexcept
180
    {
11,084,928✔
181
        was_discarded = false;
11,084,928✔
182
        was_replaced = false;
11,084,928✔
183
        m_path_len = instr.path_length();
11,084,928✔
184
    }
11,084,928✔
185
};
186

187
struct TransformerImpl::MajorSide : TransformerImpl::Side {
188
    MajorSide(Transformer& transformer)
189
        : Side(transformer)
190
    {
416,176✔
191
    }
416,176✔
192

193
    void set_next_changeset(Changeset* changeset) noexcept;
194
    void discard();
195
    void prepend(Instruction operation);
196
    template <class InputIterator>
197
    void prepend(InputIterator begin, InputIterator end);
198

199
    void init_with_instruction(Changeset::iterator position) noexcept
200
    {
8,522,246✔
201
        REALM_ASSERT(position >= m_changeset->begin());
8,522,246✔
202
        REALM_ASSERT(position != m_changeset->end());
8,522,246✔
203
        m_position = position;
8,522,246✔
204
        skip_tombstones();
8,522,246✔
205
        REALM_ASSERT(position != m_changeset->end());
8,522,246✔
206

4,260,734✔
207
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
8,522,246✔
208

4,260,734✔
209
        Side::init_with_instruction(get());
8,522,246✔
210
    }
8,522,246✔
211

212
    void skip_tombstones() noexcept final
213
    {
36,727,178✔
214
        while (m_position != m_changeset->end() && !*m_position) {
36,728,666✔
215
            ++m_position;
1,488✔
216
        }
1,488✔
217
    }
36,727,178✔
218

219
    void next_instruction() noexcept final
220
    {
8,456,226✔
221
        REALM_ASSERT(m_position != m_changeset->end());
8,456,226✔
222
        do {
8,456,358✔
223
            ++m_position;
8,456,358✔
224
        } while (m_position != m_changeset->end() && !*m_position);
8,456,358✔
225
    }
8,456,226✔
226

227
    Instruction& get() noexcept final
228
    {
38,426,826✔
229
        return **m_position;
38,426,826✔
230
    }
38,426,826✔
231

232
    size_t get_object_ids_in_current_instruction(_impl::ChangesetIndex::GlobalID* ids, size_t max_ids)
233
    {
7,634,794✔
234
        return _impl::get_object_ids_in_instruction(*m_changeset, get(), ids, max_ids);
7,634,794✔
235
    }
7,634,794✔
236

237
    Changeset::iterator m_position;
238
};
239

240
struct TransformerImpl::MinorSide : TransformerImpl::Side {
241
    using Position = _impl::ChangesetIndex::RangeIterator;
242

243
    MinorSide(Transformer& transformer)
244
        : Side(transformer)
245
    {
416,174✔
246
    }
416,174✔
247

248
    void discard();
249
    void prepend(Instruction operation);
250
    template <class InputIterator>
251
    void prepend(InputIterator begin, InputIterator end);
252

253
    void substitute(const Instruction& instr)
254
    {
×
255
        was_replaced = true;
×
256
        get() = instr;
×
257
    }
×
258

259
    Position begin() noexcept
260
    {
8,522,450✔
261
        return Position{m_conflict_ranges};
8,522,450✔
262
    }
8,522,450✔
263

264
    Position end() noexcept
265
    {
59,355,722✔
266
        return Position{m_conflict_ranges, Position::end_tag{}};
59,355,722✔
267
    }
59,355,722✔
268

269
    void update_changeset_pointer() noexcept
270
    {
15,832,104✔
271
        if (REALM_LIKELY(m_position != end())) {
15,832,104✔
272
            m_changeset = m_position.m_outer->first;
2,749,224✔
273
        }
2,749,224✔
274
        else {
13,082,880✔
275
            m_changeset = nullptr;
13,082,880✔
276
        }
13,082,880✔
277
    }
15,832,104✔
278

279
    void skip_tombstones() noexcept final
280
    {
16,030,516✔
281
        if (m_position != end() && *m_position)
16,030,516✔
282
            return;
5,276,248✔
283
        skip_tombstones_slow();
10,754,268✔
284
    }
10,754,268✔
285

286
    REALM_NOINLINE void skip_tombstones_slow() noexcept
287
    {
10,754,844✔
288
        while (m_position != end() && !*m_position) {
11,402,476✔
289
            ++m_position;
647,632✔
290
        }
647,632✔
291
        update_changeset_pointer();
10,754,844✔
292
    }
10,754,844✔
293

294
    void next_instruction() noexcept final
295
    {
2,448,902✔
296
        REALM_ASSERT(m_position != end());
2,448,902✔
297
        ++m_position;
2,448,902✔
298
        update_changeset_pointer();
2,448,902✔
299
        skip_tombstones();
2,448,902✔
300
    }
2,448,902✔
301

302
    Instruction& get() noexcept final
303
    {
16,313,636✔
304
        Instruction* instr = *m_position;
16,313,636✔
305
        REALM_ASSERT(instr != nullptr);
16,313,636✔
306
        return *instr;
16,313,636✔
307
    }
16,313,636✔
308

309
    void init_with_instruction(Position position)
310
    {
2,563,054✔
311
        // REALM_ASSERT(position >= Position(m_conflict_ranges));
1,289,248✔
312
        REALM_ASSERT(position != end());
2,563,054✔
313
        m_position = position;
2,563,054✔
314
        update_changeset_pointer();
2,563,054✔
315
        skip_tombstones();
2,563,054✔
316
        REALM_ASSERT(position != end());
2,563,054✔
317

1,289,248✔
318
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
2,563,054✔
319

1,289,248✔
320
        Side::init_with_instruction(get());
2,563,054✔
321
    }
2,563,054✔
322

323
    _impl::ChangesetIndex::RangeIterator m_position;
324
    _impl::ChangesetIndex* m_changeset_index = nullptr;
325
    _impl::ChangesetIndex::Ranges* m_conflict_ranges = nullptr;
326
};
327

328
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug utilities
329

330
struct TransformerImpl::MergeTracer {
331
public:
332
    Side& m_minor;
333
    Side& m_major;
334
    const Changeset& m_minor_log;
335
    const Changeset& m_major_log;
336
    Instruction minor_before;
337
    Instruction major_before;
338

339
    // field => pair(original_value, change)
340
    struct Diff {
341
        std::map<std::string, std::pair<int64_t, int64_t>> numbers;
342
        std::map<std::string, std::pair<std::string, std::string>> strings;
343

344
        bool empty() const noexcept
345
        {
×
346
            return numbers.empty() && strings.empty();
×
347
        }
×
348
    };
349

350
    explicit MergeTracer(Side& minor, Side& major)
351
        : m_minor(minor)
352
        , m_major(major)
353
        , m_minor_log(*minor.m_changeset)
354
        , m_major_log(*major.m_changeset)
355
        , minor_before(minor.get())
356
        , major_before(major.get())
357
    {
×
358
    }
×
359

360
    struct FieldTracer : sync::Changeset::Reflector::Tracer {
361
        std::string m_name;
362
        std::map<std::string, std::string, std::less<>> m_fields;
363

364
        const Changeset* m_changeset = nullptr;
365

366
        void set_changeset(const Changeset* changeset) override
367
        {
×
368
            m_changeset = changeset;
×
369
        }
×
370

371
        StringData get_string(InternString str)
372
        {
×
373
            return m_changeset->get_string(str);
×
374
        }
×
375

376
        void name(StringData n) override
377
        {
×
378
            m_name = n;
×
379
        }
×
380

381
        void path(StringData n, InternString table, const Instruction::PrimaryKey& pk,
382
                  util::Optional<InternString> field, const Instruction::Path* path) override
383
        {
×
384
            std::stringstream ss;
×
385
            m_changeset->print_path(ss, table, pk, field, path);
×
386
            m_fields.emplace(n, ss.str());
×
387
        }
×
388

389
        void field(StringData n, InternString str) override
390
        {
×
391
            m_fields.emplace(n, get_string(str));
×
392
        }
×
393

394
        void field(StringData n, Instruction::Payload::Type type) override
395
        {
×
396
            m_fields.emplace(n, get_type_name(type));
×
397
        }
×
398

399
        void field(StringData n, Instruction::AddColumn::CollectionType type) override
400
        {
×
401
            m_fields.emplace(n, get_collection_type(type));
×
402
        }
×
403

404
        void field(StringData n, const Instruction::PrimaryKey& key) override
405
        {
×
406
            auto real_key = m_changeset->get_key(key);
×
407
            std::stringstream ss;
×
408
            ss << format_pk(real_key);
×
409
            m_fields.emplace(n, ss.str());
×
410
        }
×
411

412
        void field(StringData n, const Instruction::Payload& value) override
413
        {
×
414
            std::stringstream ss;
×
415
            m_changeset->print_value(ss, value);
×
416
            m_fields.emplace(n, ss.str());
×
417
        }
×
418

419
        void field(StringData n, const Instruction::Path& value) override
420
        {
×
421
            std::stringstream ss;
×
422
            m_changeset->print_path(ss, value);
×
423
            m_fields.emplace(n, ss.str());
×
424
        }
×
425

426
        void field(StringData n, uint32_t value) override
427
        {
×
428
            std::stringstream ss;
×
429
            ss << value;
×
430
            m_fields.emplace(n, ss.str());
×
431
        }
×
432
    };
433

434
    struct PrintDiffTracer : sync::Changeset::Reflector::Tracer {
435
        std::ostream& m_os;
436
        const FieldTracer& m_before;
437
        bool m_first = true;
438
        const Changeset* m_changeset = nullptr;
439

440
        PrintDiffTracer(std::ostream& os, const FieldTracer& before)
441
            : m_os(os)
442
            , m_before(before)
443
        {
×
444
        }
×
445

446
        void set_changeset(const Changeset* changeset) override
447
        {
×
448
            m_changeset = changeset;
×
449
        }
×
450

451
        StringData get_string(InternString str) const noexcept
452
        {
×
453
            return m_changeset->get_string(str);
×
454
        }
×
455

456
        void name(StringData n) override
457
        {
×
458
            m_os << std::left << std::setw(16) << std::string(n);
×
459
        }
×
460

461
        void path(StringData n, InternString table, const Instruction::PrimaryKey& pk,
462
                  util::Optional<InternString> field, const Instruction::Path* path) override
463
        {
×
464
            std::stringstream ss;
×
465
            m_changeset->print_path(ss, table, pk, field, path);
×
466
            diff_field(n, ss.str());
×
467
        }
×
468

469
        void field(StringData n, InternString str) override
470
        {
×
471
            diff_field(n, get_string(str));
×
472
        }
×
473

474
        void field(StringData n, Instruction::Payload::Type type) override
475
        {
×
476
            diff_field(n, get_type_name(type));
×
477
        }
×
478

479
        void field(StringData n, Instruction::AddColumn::CollectionType type) override
480
        {
×
481
            diff_field(n, get_collection_type(type));
×
482
        }
×
483

484
        void field(StringData n, const Instruction::PrimaryKey& value) override
485
        {
×
486
            std::stringstream ss;
×
487
            ss << format_pk(m_changeset->get_key(value));
×
488
            diff_field(n, ss.str());
×
489
        }
×
490

491
        void field(StringData n, const Instruction::Payload& value) override
492
        {
×
493
            std::stringstream ss;
×
494
            m_changeset->print_value(ss, value);
×
495
            diff_field(n, ss.str());
×
496
        }
×
497

498
        void field(StringData n, const Instruction::Path& value) override
499
        {
×
500
            std::stringstream ss;
×
501
            m_changeset->print_path(ss, value);
×
502
            diff_field(n, ss.str());
×
503
        }
×
504

505
        void field(StringData n, uint32_t value) override
506
        {
×
507
            std::stringstream ss;
×
508
            ss << value;
×
509
            diff_field(n, ss.str());
×
510
        }
×
511

512
        void diff_field(StringData name, std::string value)
513
        {
×
514
            std::stringstream ss;
×
515
            ss << name << "=";
×
516
            auto it = m_before.m_fields.find(name);
×
517
            if (it == m_before.m_fields.end() || it->second == value) {
×
518
                ss << value;
×
519
            }
×
520
            else {
×
521
                ss << it->second << "->" << value;
×
522
            }
×
523
            if (!m_first) {
×
524
                m_os << ", ";
×
525
            }
×
526
            m_os << ss.str();
×
527
            m_first = false;
×
528
        }
×
529
    };
530

531
    static void print_instr(std::ostream& os, const Instruction& instr, const Changeset& changeset)
532
    {
×
533
        Changeset::Printer printer{os};
×
534
        Changeset::Reflector reflector{printer, changeset};
×
535
        instr.visit(reflector);
×
536
    }
×
537

538
    bool print_diff(std::ostream& os, bool print_unmodified, const Instruction& before, const Changeset& before_log,
539
                    Side& side) const
540
    {
×
541
        if (side.was_discarded) {
×
542
            print_instr(os, before, before_log);
×
543
            os << " (DISCARDED)";
×
544
        }
×
545
        else if (side.was_replaced) {
×
546
            print_instr(os, before, before_log);
×
547
            os << " (REPLACED)";
×
548
        }
×
549
        else {
×
550
            Instruction after = side.get();
×
551
            if (print_unmodified || (before != after)) {
×
552
                FieldTracer before_tracer;
×
553
                before_tracer.set_changeset(&before_log);
×
554
                PrintDiffTracer after_tracer{os, before_tracer};
×
555
                Changeset::Reflector before_reflector{before_tracer, *side.m_changeset};
×
556
                Changeset::Reflector after_reflector{after_tracer, *side.m_changeset};
×
557
                before.visit(before_reflector);
×
558
                after.visit(after_reflector); // This prints the diff'ed instruction
×
559
            }
×
560
            else {
×
561
                os << "(=)";
×
562
            }
×
563
        }
×
564
        return true;
×
565
    }
×
566

567
    void print_diff(std::ostream& os, bool print_unmodified) const
568
    {
×
569
        bool must_print_minor = m_minor.was_discarded || m_minor.was_replaced;
×
570
        if (!must_print_minor) {
×
571
            Instruction minor_after = m_minor.get();
×
572
            must_print_minor = (minor_before != minor_after);
×
573
        }
×
574
        bool must_print_major = m_major.was_discarded || m_major.was_replaced;
×
575
        if (!must_print_major) {
×
576
            Instruction major_after = m_major.get();
×
577
            must_print_major = (major_before != major_after);
×
578
        }
×
579
        bool must_print = (print_unmodified || must_print_minor || must_print_major);
×
580
        if (must_print) {
×
581
            std::stringstream ss_minor;
×
582
            std::stringstream ss_major;
×
583

584
            print_diff(ss_minor, true, minor_before, m_minor_log, m_minor);
×
585
            print_diff(ss_major, print_unmodified, major_before, m_major_log, m_major);
×
586

587
            os << std::left << std::setw(80) << ss_minor.str();
×
588
            os << ss_major.str() << "\n";
×
589
        }
×
590
    }
×
591

592
    void pad_or_ellipsis(std::ostream& os, const std::string& str, int width) const
593
    {
×
594
        // FIXME: Does not work with UTF-8.
×
595
        if (str.size() > size_t(width)) {
×
596
            os << str.substr(0, width - 1) << "~";
×
597
        }
×
598
        else {
×
599
            os << std::left << std::setw(width) << str;
×
600
        }
×
601
    }
×
602
};
603
#endif // LCOV_EXCL_STOP REALM_DEBUG
604

605

606
struct TransformerImpl::Transformer {
607
    MajorSide m_major_side;
608
    MinorSide m_minor_side;
609
    MinorSide::Position m_minor_end;
610
    bool m_trace;
611

612
    Transformer(bool trace)
613
        : m_major_side{*this}
614
        , m_minor_side{*this}
615
        , m_trace{trace}
616
    {
416,176✔
617
    }
416,176✔
618

619
    void transform()
620
    {
9,842,052✔
621
        m_major_side.m_position = m_major_side.m_changeset->begin();
9,842,052✔
622
        m_major_side.skip_tombstones();
9,842,052✔
623

4,925,992✔
624
        while (m_major_side.m_position != m_major_side.m_changeset->end()) {
18,364,328✔
625
            m_major_side.init_with_instruction(m_major_side.m_position);
8,522,276✔
626

4,260,758✔
627
            set_conflict_ranges();
8,522,276✔
628
            m_minor_end = m_minor_side.end();
8,522,276✔
629
            m_minor_side.m_position = m_minor_side.begin();
8,522,276✔
630
            transform_major();
8,522,276✔
631

4,260,758✔
632
            if (!m_major_side.was_discarded)
8,522,276✔
633
                // Discarding the instruction moves to the next one.
4,228,008✔
634
                m_major_side.next_instruction();
8,456,252✔
635
            m_major_side.skip_tombstones();
8,522,276✔
636
        }
8,522,276✔
637
    }
9,842,052✔
638

639
    _impl::ChangesetIndex::Ranges* get_conflict_ranges_for_instruction(const Instruction& instr)
640
    {
8,522,172✔
641
        _impl::ChangesetIndex& index = *m_minor_side.m_changeset_index;
8,522,172✔
642

4,260,788✔
643
        if (_impl::is_schema_change(instr)) {
8,522,172✔
644
            ///
437,832✔
645
            /// CONFLICT GROUP: Everything touching that class
437,832✔
646
            ///
437,832✔
647
            auto ranges = index.get_everything();
887,558✔
648
            if (!ranges->empty()) {
887,558✔
649
#if REALM_DEBUG // LCOV_EXCL_START
323,908✔
650
                if (m_trace) {
657,412✔
651
                    std::cerr << TERM_RED << "Conflict group: Everything (due to schema change)\n" << TERM_RESET;
×
652
                }
×
653
#endif // REALM_DEBUG LCOV_EXCL_STOP
657,412✔
654
            }
657,412✔
655
            return ranges;
887,558✔
656
        }
887,558✔
657
        else {
7,634,614✔
658
            ///
3,822,956✔
659
            /// CONFLICT GROUP: Everything touching the involved objects,
3,822,956✔
660
            /// including schema changes.
3,822,956✔
661
            ///
3,822,956✔
662
            _impl::ChangesetIndex::GlobalID major_ids[2];
7,634,614✔
663
            size_t num_major_ids = m_major_side.get_object_ids_in_current_instruction(major_ids, 2);
7,634,614✔
664
            REALM_ASSERT(num_major_ids <= 2);
7,634,614✔
665
            REALM_ASSERT(num_major_ids >= 1);
7,634,614✔
666
#if REALM_DEBUG // LCOV_EXCL_START
3,822,956✔
667
            if (m_trace) {
7,634,614✔
668
                std::cerr << TERM_RED << "Conflict group: ";
×
669
                if (num_major_ids == 0) {
×
670
                    std::cerr << "(nothing - no object references)";
×
671
                }
×
672
                for (size_t i = 0; i < num_major_ids; ++i) {
×
673
                    std::cerr << major_ids[i].table_name << "[" << format_pk(major_ids[i].object_id) << "]";
×
674
                    if (i + 1 != num_major_ids)
×
675
                        std::cerr << ", ";
×
676
                }
×
677
                std::cerr << "\n" << TERM_RESET;
×
678
            }
×
679
#endif // REALM_DEBUG LCOV_EXCL_STOP
7,634,614✔
680
            auto ranges = index.get_modifications_for_object(major_ids[0]);
7,634,614✔
681
            if (num_major_ids == 2) {
7,634,614✔
682
                // Check that the index has correctly joined the ranges for the
74✔
683
                // two object IDs.
74✔
684
                REALM_ASSERT(ranges == index.get_modifications_for_object(major_ids[1]));
148✔
685
            }
148✔
686
            return ranges;
7,634,614✔
687
        }
7,634,614✔
688
    }
8,522,172✔
689

690
    void set_conflict_ranges()
691
    {
8,522,212✔
692
        const auto& major_instr = m_major_side.get();
8,522,212✔
693
        m_minor_side.m_conflict_ranges = get_conflict_ranges_for_instruction(major_instr);
8,522,212✔
694
        /* m_minor_side.m_changeset_index->verify(); */
4,260,732✔
695
    }
8,522,212✔
696

697
    void set_next_major_changeset(Changeset* changeset) noexcept
698
    {
9,842,150✔
699
        m_major_side.m_changeset = changeset;
9,842,150✔
700
        m_major_side.m_position = changeset->begin();
9,842,150✔
701
        m_major_side.skip_tombstones();
9,842,150✔
702
    }
9,842,150✔
703

704
    void discard_major()
705
    {
66,096✔
706
        m_major_side.m_position = m_major_side.m_changeset->erase_stable(m_major_side.m_position);
66,096✔
707
        m_major_side.was_discarded = true; // This terminates the loop in transform_major();
66,096✔
708
        m_major_side.m_changeset->set_dirty(true);
66,096✔
709
    }
66,096✔
710

711
    void discard_minor()
712
    {
65,570✔
713
        m_minor_side.was_discarded = true;
65,570✔
714
        m_minor_side.m_position = m_minor_side.m_changeset_index->erase_instruction(m_minor_side.m_position);
65,570✔
715
        m_minor_side.m_changeset->set_dirty(true);
65,570✔
716
        m_minor_side.update_changeset_pointer();
65,570✔
717
    }
65,570✔
718

719
    template <class InputIterator>
720
    void prepend_major(InputIterator instr_begin, InputIterator instr_end)
721
    {
×
722
        REALM_ASSERT(*m_major_side.m_position); // cannot prepend a tombstone
×
723
        auto insert_position = m_major_side.m_position;
×
724
        m_major_side.m_position = m_major_side.m_changeset->insert_stable(insert_position, instr_begin, instr_end);
×
725
        m_major_side.m_changeset->set_dirty(true);
×
726
        size_t num_prepended = instr_end - instr_begin;
×
727
        transform_prepended_major(num_prepended);
×
728
    }
×
729

730
    void prepend_major(Instruction instr)
731
    {
×
732
        const Instruction* begin = &instr;
×
733
        const Instruction* end = begin + 1;
×
734
        prepend_major(begin, end);
×
735
    }
×
736

737
    template <class InputIterator>
738
    void prepend_minor(InputIterator instr_begin, InputIterator instr_end)
739
    {
×
740
        REALM_ASSERT(*m_minor_side.m_position); // cannot prepend a tombstone
×
741
        auto insert_position = m_minor_side.m_position.m_pos;
×
742
        m_minor_side.m_position.m_pos =
×
743
            m_minor_side.m_changeset->insert_stable(insert_position, instr_begin, instr_end);
×
744
        m_minor_side.m_changeset->set_dirty(true);
×
745
        size_t num_prepended = instr_end - instr_begin;
×
746
        // Go back to the instruction that initiated this prepend
747
        for (size_t i = 0; i < num_prepended; ++i) {
×
748
            ++m_minor_side.m_position;
×
749
        }
×
750
        REALM_ASSERT(m_minor_end == m_minor_side.end());
×
751
    }
×
752

753
    void prepend_minor(Instruction instr)
754
    {
×
755
        const Instruction* begin = &instr;
×
756
        const Instruction* end = begin + 1;
×
757
        prepend_minor(begin, end);
×
758
    }
×
759

760
    void transform_prepended_major(size_t num_prepended)
761
    {
×
762
        auto orig_major_was_discarded = m_major_side.was_discarded;
×
763
        auto orig_major_path_len = m_major_side.m_path_len;
×
764

765
        // Reset 'was_discarded', as it should refer to the prepended
766
        // instructions in the below, not the instruction that instigated the
767
        // prepend.
768
        m_major_side.was_discarded = false;
×
769
        REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
770

771
#if defined(REALM_DEBUG) // LCOV_EXCL_START
×
772
        if (m_trace) {
×
773
            std::cerr << std::setw(80) << " ";
×
774
            MergeTracer::print_instr(std::cerr, m_major_side.get(), *m_major_side.m_changeset);
×
775
            std::cerr << " (PREPENDED " << num_prepended << ")\n";
×
776
        }
×
777
#endif // REALM_DEBUG LCOV_EXCL_STOP
×
778

779
        for (size_t i = 0; i < num_prepended; ++i) {
×
780
            auto orig_minor_index = m_minor_side.m_position;
×
781
            auto orig_minor_was_discarded = m_minor_side.was_discarded;
×
782
            auto orig_minor_was_replaced = m_minor_side.was_replaced;
×
783
            auto orig_minor_path_len = m_minor_side.m_path_len;
×
784

785
            // Skip the instruction that initiated this prepend.
786
            if (!m_minor_side.was_discarded) {
×
787
                // Discarding an instruction moves to the next.
788
                m_minor_side.next_instruction();
×
789
            }
×
790

791
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
792
            m_major_side.init_with_instruction(m_major_side.m_position);
×
793
            REALM_ASSERT(!m_major_side.was_discarded);
×
794
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
795
            transform_major();
×
796
            if (!m_major_side.was_discarded) {
×
797
                // Discarding an instruction moves to the next.
798
                m_major_side.next_instruction();
×
799
            }
×
800
            REALM_ASSERT(m_major_side.m_position != m_major_side.m_changeset->end());
×
801

802
            m_minor_side.m_position = orig_minor_index;
×
803
            m_minor_side.was_discarded = orig_minor_was_discarded;
×
804
            m_minor_side.was_replaced = orig_minor_was_replaced;
×
805
            m_minor_side.m_path_len = orig_minor_path_len;
×
806
            m_minor_side.update_changeset_pointer();
×
807
        }
×
808

809
#if defined(REALM_DEBUG) // LCOV_EXCL_START
×
810
        if (m_trace) {
×
811
            std::cerr << TERM_CYAN << "(end transform of prepended major)\n" << TERM_RESET;
×
812
        }
×
813
#endif // REALM_DEBUG LCOV_EXCL_STOP
×
814

815
        m_major_side.was_discarded = orig_major_was_discarded;
×
816
        m_major_side.m_path_len = orig_major_path_len;
×
817
    }
×
818

819
    void transform_major()
820
    {
8,522,392✔
821
        m_minor_side.skip_tombstones();
8,522,392✔
822

4,260,854✔
823
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug tracing
8,522,392✔
824
        const bool print_noop_merges = false;
8,522,392✔
825
        bool new_major = true; // print an instruction every time we go to the next major regardless
8,522,392✔
826
#endif                         // LCOV_EXCL_STOP REALM_DEBUG
8,522,392✔
827

4,260,854✔
828
        while (m_minor_side.m_position != m_minor_end) {
11,019,342✔
829
            m_minor_side.init_with_instruction(m_minor_side.m_position);
2,563,046✔
830

1,289,238✔
831
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug tracing
2,563,046✔
832
            if (m_trace) {
2,563,046✔
833
                MergeTracer tracer{m_minor_side, m_major_side};
×
834
                merge_instructions(m_major_side, m_minor_side);
×
835
                if (new_major)
×
836
                    std::cerr << TERM_CYAN << "\n(new major round)\n" << TERM_RESET;
×
837
                tracer.print_diff(std::cerr, new_major || print_noop_merges);
×
838
                new_major = false;
×
839
            }
×
840
            else {
2,563,046✔
841
#endif // LCOV_EXCL_STOP REALM_DEBUG
2,563,046✔
842
                merge_instructions(m_major_side, m_minor_side);
2,563,046✔
843
#if defined(REALM_DEBUG) // LCOV_EXCL_START
2,563,046✔
844
            }
2,563,046✔
845
#endif // LCOV_EXCL_STOP REALM_DEBUG
2,563,046✔
846

1,289,238✔
847
            if (m_major_side.was_discarded)
2,563,046✔
848
                break;
66,096✔
849
            if (!m_minor_side.was_discarded)
2,496,950✔
850
                // Discarding an instruction moves to the next one.
1,232,392✔
851
                m_minor_side.next_instruction();
2,448,910✔
852
            m_minor_side.skip_tombstones();
2,496,950✔
853
        }
2,496,950✔
854
    }
8,522,392✔
855

856
    void merge_instructions(MajorSide& left, MinorSide& right);
857
    template <class OuterSide, class InnerSide>
858
    void merge_nested(OuterSide& outer, InnerSide& inner);
859
};
860

861
void TransformerImpl::MajorSide::set_next_changeset(Changeset* changeset) noexcept
862
{
9,842,158✔
863
    m_transformer.set_next_major_changeset(changeset);
9,842,158✔
864
}
9,842,158✔
865
void TransformerImpl::MajorSide::discard()
866
{
66,096✔
867
    m_transformer.discard_major();
66,096✔
868
}
66,096✔
869
void TransformerImpl::MajorSide::prepend(Instruction operation)
870
{
×
871
    m_transformer.prepend_major(std::move(operation));
×
872
}
×
873
template <class InputIterator>
874
void TransformerImpl::MajorSide::prepend(InputIterator begin, InputIterator end)
875
{
876
    m_transformer.prepend_major(std::move(begin), std::move(end));
877
}
878
void TransformerImpl::MinorSide::discard()
879
{
65,570✔
880
    m_transformer.discard_minor();
65,570✔
881
}
65,570✔
882
void TransformerImpl::MinorSide::prepend(Instruction operation)
883
{
×
884
    m_transformer.prepend_minor(std::move(operation));
×
885
}
×
886
template <class InputIterator>
887
void TransformerImpl::MinorSide::prepend(InputIterator begin, InputIterator end)
888
{
889
    m_transformer.prepend_minor(std::move(begin), std::move(end));
890
}
891
} // namespace _impl
892

893
namespace {
894

895
REALM_NORETURN void throw_bad_merge(std::string msg)
896
{
50✔
897
    throw sync::TransformError{std::move(msg)};
50✔
898
}
50✔
899

900
template <class... Params>
901
REALM_NORETURN void bad_merge(const char* msg, Params&&... params)
902
{
50✔
903
    throw_bad_merge(util::format(msg, std::forward<Params>(params)...));
50✔
904
}
50✔
905

906
REALM_NORETURN void bad_merge(_impl::TransformerImpl::Side& side, Instruction::PathInstruction instr,
907
                              const std::string& msg)
908
{
×
909
    std::stringstream ss;
×
910
    side.m_changeset->print_path(ss, instr.table, instr.object, instr.field, &instr.path);
×
911
    bad_merge("%1 (instruction target: %2). Please contact support.", msg, ss.str());
×
912
}
×
913

914
template <class LeftInstruction, class RightInstruction, class Enable = void>
915
struct Merge;
916
template <class Outer>
917
struct MergeNested;
918

919
struct MergeUtils {
920
    using TransformerImpl = _impl::TransformerImpl;
921
    MergeUtils(TransformerImpl::Side& left_side, TransformerImpl::Side& right_side)
922
        : m_left_side(left_side)
923
        , m_right_side(right_side)
924
    {
1,215,626✔
925
    }
1,215,626✔
926

927
    // CAUTION: All of these utility functions rely implicitly on the "left" and
928
    // "right" arguments corresponding to the left and right sides. If the
929
    // arguments are switched, mayhem ensues.
930

931
    bool same_string(InternString left, InternString right) const noexcept
932
    {
1,288,726✔
933
        // FIXME: Optimize string comparison by building a map of InternString values up front.
654,360✔
934
        return m_left_side.m_changeset->get_string(left) == m_right_side.m_changeset->get_string(right);
1,288,726✔
935
    }
1,288,726✔
936

937
    bool same_key(const Instruction::PrimaryKey& left, const Instruction::PrimaryKey& right) const noexcept
938
    {
305,778✔
939
        // FIXME: Once we can compare string by InternString map lookups,
156,786✔
940
        // compare the string components of the keys using that.
156,786✔
941
        PrimaryKey left_key = m_left_side.m_changeset->get_key(left);
305,778✔
942
        PrimaryKey right_key = m_right_side.m_changeset->get_key(right);
305,778✔
943
        return left_key == right_key;
305,778✔
944
    }
305,778✔
945

946
    bool same_payload(const Instruction::Payload& left, const Instruction::Payload& right)
947
    {
216✔
948
        using Type = Instruction::Payload::Type;
216✔
949

108✔
950
        if (left.type != right.type)
216✔
951
            return false;
160✔
952

28✔
953
        switch (left.type) {
56✔
954
            case Type::Null:
✔
955
                return true;
×
956
            case Type::Erased:
✔
957
                return true;
×
NEW
958
            case Type::Dictionary:
✔
NEW
959
                return true;
×
NEW
960
            case Type::ObjectValue:
✔
NEW
961
                return true;
×
962
            case Type::GlobalKey:
✔
963
                return left.data.key == right.data.key;
×
964
            case Type::Int:
12✔
965
                return left.data.integer == right.data.integer;
12✔
966
            case Type::Bool:
✔
967
                return left.data.boolean == right.data.boolean;
×
968
            case Type::String:
20✔
969
                return m_left_side.get_string(left.data.str) == m_right_side.get_string(right.data.str);
20✔
970
            case Type::Binary:
✔
971
                return m_left_side.get_string(left.data.binary) == m_right_side.get_string(right.data.binary);
×
972
            case Type::Timestamp:
8✔
973
                return left.data.timestamp == right.data.timestamp;
8✔
974
            case Type::Float:
8✔
975
                return left.data.fnum == right.data.fnum;
8✔
976
            case Type::Double:
✔
977
                return left.data.dnum == right.data.dnum;
×
978
            case Type::Decimal:
8✔
979
                return left.data.decimal == right.data.decimal;
8✔
980
            case Type::Link: {
✔
981
                if (!same_key(left.data.link.target, right.data.link.target)) {
×
982
                    return false;
✔
983
                }
×
984
                auto left_target = m_left_side.get_string(left.data.link.target_table);
✔
985
                auto right_target = m_right_side.get_string(right.data.link.target_table);
×
986
                return left_target == right_target;
×
987
            }
×
988
            case Type::ObjectId:
×
989
                return left.data.object_id == right.data.object_id;
×
990
            case Type::UUID:
×
991
                return left.data.uuid == right.data.uuid;
×
992
        }
✔
993

×
994
        bad_merge("Invalid payload type in instruction");
✔
995
    }
×
996

997
    bool same_path_element(const Instruction::Path::Element& left,
998
                           const Instruction::Path::Element& right) const noexcept
999
    {
954✔
1000
        const auto& pred = util::overload{
954✔
1001
            [&](uint32_t lhs, uint32_t rhs) {
954✔
1002
                return lhs == rhs;
870✔
1003
            },
1,812✔
1004
            [&](InternString lhs, InternString rhs) {
1,896✔
1005
                return same_string(lhs, rhs);
942✔
1006
            },
942✔
1007
            [&](const auto&, const auto&) {
1,812✔
1008
                // FIXME: Paths contain incompatible element types. Should we raise an
84✔
1009
                // error here?
84✔
1010
                return false;
84✔
UNCOV
1011
            },
×
1012
        };
954✔
1013
        return mpark::visit(pred, left, right);
954✔
1014
    }
954✔
1015

1016
    bool same_path(const Instruction::Path& left, const Instruction::Path& right) const noexcept
942✔
1017
    {
5,946✔
1018
        if (left.size() == right.size()) {
5,946✔
1019
            for (size_t i = 0; i < left.size(); ++i) {
5,216✔
1020
                if (!same_path_element(left[i], right[i])) {
950✔
1021
                    return false;
5,426✔
1022
                }
5,426✔
1023
            }
5,892✔
1024
            return true;
5,906✔
1025
        }
722✔
1026
        return false;
722✔
1027
    }
974✔
1028

4,004✔
1029
    bool same_table(const Instruction::TableInstruction& left,
34✔
1030
                    const Instruction::TableInstruction& right) const noexcept
34✔
1031
    {
611,456✔
1032
        return same_string(left.table, right.table);
611,422✔
1033
    }
611,422✔
1034

1035
    bool same_object(const Instruction::ObjectInstruction& left,
595,732✔
1036
                     const Instruction::ObjectInstruction& right) const noexcept
595,732✔
1037
    {
1,100,688✔
1038
        return same_table(left, right) && same_key(left.object, right.object);
504,956✔
1039
    }
504,956✔
1040

1041
    template <class Left, class Right>
484,686✔
1042
    bool same_column(const Left& left, const Right& right) const noexcept
484,686✔
1043
    {
501,878✔
1044
        if constexpr (std::is_convertible_v<const Right&, const Instruction::PathInstruction&>) {
17,192✔
1045
            const Instruction::PathInstruction& rhs = right;
17,192✔
1046
            return same_table(left, right) && same_string(left.field, rhs.field);
17,192✔
1047
        }
17,698✔
1048
        else if constexpr (std::is_convertible_v<const Right&, const Instruction::ObjectInstruction&>) {
34,890✔
1049
            // CreateObject/EraseObject do not have a column built in.
34,890✔
1050
            return false;
17,192!
1051
        }
17,192✔
1052
        else {
34,890✔
1053
            return same_table(left, right) && same_string(left.field, right.field);
17,192✔
1054
        }
34,890✔
1055
    }
34,890✔
1056

17,698✔
1057
    bool same_field(const Instruction::PathInstruction& left,
17,698!
1058
                    const Instruction::PathInstruction& right) const noexcept
17,698✔
1059
    {
139,058✔
1060
        return same_object(left, right) && same_string(left.field, right.field);
121,360✔
1061
    }
121,360✔
1062

1063
    bool same_path(const Instruction::PathInstruction& left, const Instruction::PathInstruction& right) const noexcept
107,734✔
1064
    {
121,676✔
1065
        return same_field(left, right) && same_path(left.path, right.path);
121,676✔
1066
    }
13,942✔
1067

1068
    bool same_container(const Instruction::Path& left, const Instruction::Path& right) const noexcept
12,790✔
1069
    {
35,882✔
1070
        // The instructions refer to the same container if the paths have the
35,882✔
1071
        // same length, and elements [0..n-1] are equal (so the last element is
23,092✔
1072
        // disregarded). If the path length is 1, this counts as referring to
23,092✔
1073
        // the same container.
42,304✔
1074
        if (left.size() == right.size()) {
23,092✔
1075
            if (left.size() == 0)
23,080✔
1076
                return true;
1077

23,080✔
1078
            for (size_t i = 0; i < left.size() - 1; ++i) {
42,292✔
1079
                if (!same_path_element(left[i], right[i])) {
19,200✔
1080
                    return false;
×
1081
                }
1082
            }
19,200✔
1083
            return true;
23,080!
1084
        }
12✔
1085
        return false;
12✔
1086
    }
12✔
1087

19,200✔
1088
    bool same_container(const Instruction::PathInstruction& left,
12✔
1089
                        const Instruction::PathInstruction& right) const noexcept
12✔
1090
    {
88,014✔
1091
        return same_field(left, right) && same_container(left.path, right.path);
88,002✔
1092
    }
88,002✔
1093

1094
    // NOTE: `is_prefix_of()` should only return true if the left is a strictly
76,370✔
1095
    // shorter path than the right, and the entire left path is the initial
76,370✔
1096
    // sequence of the right.
76,370✔
1097

1098
    bool is_prefix_of(const Instruction::AddTable& left, const Instruction::TableInstruction& right) const noexcept
1099
    {
1100
        return same_table(left, right);
1101
    }
1102

1103
    bool is_prefix_of(const Instruction::EraseTable& left, const Instruction::TableInstruction& right) const noexcept
1104
    {
80,024✔
1105
        return same_table(left, right);
80,024✔
1106
    }
80,024✔
1107

1108
    bool is_prefix_of(const Instruction::AddColumn&, const Instruction::TableInstruction&) const noexcept
83,520✔
1109
    {
83,520✔
1110
        // Right side is a schema instruction.
83,520✔
1111
        return false;
1112
    }
1113

1114
    bool is_prefix_of(const Instruction::EraseColumn&, const Instruction::TableInstruction&) const noexcept
1115
    {
×
1116
        // Right side is a schema instruction.
×
1117
        return false;
1118
    }
1119

1120
    bool is_prefix_of(const Instruction::AddColumn& left, const Instruction::ObjectInstruction& right) const noexcept
1121
    {
×
1122
        return same_column(left, right);
×
1123
    }
1124

1125
    bool is_prefix_of(const Instruction::EraseColumn& left,
1126
                      const Instruction::ObjectInstruction& right) const noexcept
1127
    {
×
1128
        return same_column(left, right);
1129
    }
1130

1131
    bool is_prefix_of(const Instruction::ObjectInstruction&, const Instruction::TableInstruction&) const noexcept
1132
    {
×
1133
        // Right side is a schema instruction.
×
1134
        return false;
1135
    }
1136

1137
    bool is_prefix_of(const Instruction::ObjectInstruction& left,
1138
                      const Instruction::PathInstruction& right) const noexcept
1139
    {
129,770✔
1140
        return same_object(left, right);
129,770✔
1141
    }
129,770✔
1142

1143
    bool is_prefix_of(const Instruction::PathInstruction&, const Instruction::TableInstruction&) const noexcept
118,432✔
1144
    {
118,432✔
1145
        // Path instructions can never be full prefixes of table-level instructions. Note that this also covers
118,432✔
1146
        // ObjectInstructions.
1147
        return false;
1148
    }
×
1149

1150
    bool is_prefix_of(const Instruction::PathInstruction& left,
1151
                      const Instruction::PathInstruction& right) const noexcept
1152
    {
19,404✔
1153
        if (left.path.size() < right.path.size() && same_field(left, right)) {
19,404✔
1154
            for (size_t i = 0; i < left.path.size(); ++i) {
160✔
1155
                if (!same_path_element(left.path[i], right.path[i])) {
4✔
1156
                    return false;
18,566✔
1157
                }
18,566✔
1158
            }
164✔
1159
            return true;
164✔
1160
        }
19,248✔
1161
        return false;
19,248✔
1162
    }
19,248✔
1163

156✔
1164
    // True if the left side is an instruction that touches a container within
18,402✔
1165
    // right's path. Equivalent to is_prefix_of, except the last element (the
18,402✔
1166
    // index) is not considered.
18,402✔
1167
    bool is_container_prefix_of(const Instruction::PathInstruction& left,
1168
                                const Instruction::PathInstruction& right) const
1169
    {
12✔
1170
        if (left.path.size() != 0 && left.path.size() < right.path.size() && same_field(left, right)) {
12✔
1171
            for (size_t i = 0; i < left.path.size() - 1; ++i) {
12✔
1172
                if (!same_path_element(left.path[i], right.path[i])) {
1173
                    return false;
12✔
1174
                }
12✔
1175
            }
12✔
1176
            return true;
12!
1177
        }
×
1178
        return false;
×
1179
    }
×
1180

12✔
1181
    bool is_container_prefix_of(const Instruction::PathInstruction&, const Instruction::TableInstruction&) const
1182
    {
×
1183
        return false;
×
1184
    }
1185

1186
    bool value_targets_table(const Instruction::Payload& value,
1187
                             const Instruction::TableInstruction& right) const noexcept
1188
    {
×
1189
        if (value.type == Instruction::Payload::Type::Link) {
1190
            StringData target_table = m_left_side.get_string(value.data.link.target_table);
1191
            StringData right_table = m_right_side.get_string(right.table);
1192
            return target_table == right_table;
×
1193
        }
×
1194
        return false;
×
1195
    }
×
1196

1197
    bool value_targets_object(const Instruction::Payload& value,
1198
                              const Instruction::ObjectInstruction& right) const noexcept
1199
    {
×
1200
        if (value_targets_table(value, right)) {
1201
            return same_key(value.data.link.target, right.object);
1202
        }
1203
        return false;
×
1204
    }
×
1205

1206
    bool value_targets_object(const Instruction::Update& left, const Instruction::ObjectInstruction& right) const
1207
    {
×
1208
        return value_targets_object(left.value, right);
×
1209
    }
1210

1211
    bool value_targets_object(const Instruction::ArrayInsert& left, const Instruction::ObjectInstruction& right) const
1212
    {
×
1213
        return value_targets_object(left.value, right);
×
1214
    }
1215

1216
    // When the left side has a shorter path, get the path component on the
1217
    // right that corresponds to the last component on the left.
1218
    //
1219
    // Note that this will only be used in the context of array indices, because
1220
    // those are the only path components that are modified during OT.
1221
    uint32_t& corresponding_index_in_path(const Instruction::PathInstruction& left,
1222
                                          Instruction::PathInstruction& right) const
1223
    {
12✔
1224
        REALM_ASSERT(left.path.size() != 0);
12✔
1225
        REALM_ASSERT(left.path.size() < right.path.size());
12✔
1226
        REALM_ASSERT(mpark::holds_alternative<uint32_t>(left.path.back()));
12✔
1227
        size_t index = left.path.size() - 1;
24✔
1228
        if (!mpark::holds_alternative<uint32_t>(right.path[index])) {
24✔
1229
            bad_merge("Inconsistent paths");
12✔
1230
        }
12✔
1231
        return mpark::get<uint32_t>(right.path[index]);
24✔
1232
    }
24✔
1233

1234
    uint32_t& corresponding_index_in_path(const Instruction::PathInstruction&,
1235
                                          const Instruction::TableInstruction&) const
12✔
1236
    {
12✔
1237
        // A path instruction can never have a shorter path than something that
1238
        // isn't a PathInstruction.
1239
        REALM_UNREACHABLE();
1240
    }
×
1241

1242
    void merge_get_vs_move(uint32_t& get_ndx, const uint32_t& move_from_ndx,
1243
                           const uint32_t& move_to_ndx) const noexcept
1244
    {
×
1245
        if (get_ndx == move_from_ndx) {
1246
            // CONFLICT: Update of a moved element.
1247
            //
1248
            // RESOLUTION: On the left side, use the MOVE operation to transform the
×
1249
            // UPDATE operation received from the right side.
×
1250
            get_ndx = move_to_ndx; // --->
1251
        }
1252
        else {
1253
            // Right update vs left remove
1254
            if (get_ndx > move_from_ndx) {
×
1255
                get_ndx -= 1; // --->
×
1256
            }
×
1257
            // Right update vs left insert
1258
            if (get_ndx >= move_to_ndx) {
×
1259
                get_ndx += 1; // --->
×
1260
            }
×
1261
        }
1262
    }
×
1263

1264
protected:
1265
    TransformerImpl::Side& m_left_side;
1266
    TransformerImpl::Side& m_right_side;
1267
};
1268

1269
template <class LeftInstruction, class RightInstruction>
1270
struct MergeBase : MergeUtils {
1271
    static const Instruction::Type A = Instruction::GetInstructionType<LeftInstruction>::value;
1272
    static const Instruction::Type B = Instruction::GetInstructionType<RightInstruction>::value;
1273
    static_assert(A >= B, "A < B. Please reverse the order of instruction types. :-)");
1274

1275
    MergeBase(TransformerImpl::Side& left_side, TransformerImpl::Side& right_side)
1276
        : MergeUtils(left_side, right_side)
1277
    {
386,192✔
1278
    }
386,192✔
1279
    MergeBase(MergeBase&&) = delete;
1280
};
1281

379,642✔
1282
#define DEFINE_MERGE(A, B)                                                                                           \
379,642✔
1283
    template <>                                                                                                      \
1284
    struct Merge<A, B> {                                                                                             \
1285
        template <class LeftSide, class RightSide>                                                                   \
1286
        struct DoMerge : MergeBase<A, B> {                                                                           \
1287
            A& left;                                                                                                 \
1288
            B& right;                                                                                                \
1289
            LeftSide& left_side;                                                                                     \
1290
            RightSide& right_side;                                                                                   \
1291
            DoMerge(A& left, B& right, LeftSide& left_side, RightSide& right_side)                                   \
1292
                : MergeBase<A, B>(left_side, right_side)                                                             \
1293
                , left(left)                                                                                         \
1294
                , right(right)                                                                                       \
1295
                , left_side(left_side)                                                                               \
1296
                , right_side(right_side)                                                                             \
1297
            {                                                                                                        \
386,192✔
1298
            }                                                                                                        \
386,192✔
1299
            void do_merge();                                                                                         \
1300
        };                                                                                                           \
1301
        template <class LeftSide, class RightSide>                                                                   \
379,642✔
1302
        static inline void merge(A& left, B& right, LeftSide& left_side, RightSide& right_side)                      \
379,642✔
1303
        {                                                                                                            \
386,192✔
1304
            DoMerge<LeftSide, RightSide> do_merge{left, right, left_side, right_side};                               \
386,192✔
1305
            do_merge.do_merge();                                                                                     \
386,192✔
1306
        }                                                                                                            \
386,192✔
1307
    };                                                                                                               \
379,640✔
1308
    template <class LeftSide, class RightSide>                                                                       \
379,640✔
1309
    void Merge<A, B>::DoMerge<LeftSide, RightSide>::do_merge()
379,640✔
1310

379,640✔
1311
#define DEFINE_MERGE_NOOP(A, B)                                                                                      \
1312
    template <>                                                                                                      \
1313
    struct Merge<A, B> {                                                                                             \
1314
        static const Instruction::Type left_type = Instruction::GetInstructionType<A>::value;                        \
1315
        static const Instruction::Type right_type = Instruction::GetInstructionType<B>::value;                       \
1316
        static_assert(left_type >= right_type,                                                                       \
1317
                      "left_type < right_type. Please reverse the order of instruction types. :-)");                 \
1318
        template <class LeftSide, class RightSide>                                                                   \
1319
        static inline void merge(A&, B&, LeftSide&, RightSide&)                                                      \
1320
        { /* Do nothing */                                                                                           \
874,234✔
1321
        }                                                                                                            \
874,234✔
1322
    }
1323

1324

864,308✔
1325
#define DEFINE_NESTED_MERGE(A)                                                                                       \
864,308✔
1326
    template <>                                                                                                      \
1327
    struct MergeNested<A> {                                                                                          \
1328
        template <class B, class OuterSide, class InnerSide>                                                         \
1329
        struct DoMerge : MergeUtils {                                                                                \
1330
            A& outer;                                                                                                \
1331
            B& inner;                                                                                                \
1332
            OuterSide& outer_side;                                                                                   \
1333
            InnerSide& inner_side;                                                                                   \
1334
            DoMerge(A& outer, B& inner, OuterSide& outer_side, InnerSide& inner_side)                                \
1335
                : MergeUtils(outer_side, inner_side)                                                                 \
1336
                , outer(outer)                                                                                       \
1337
                , inner(inner)                                                                                       \
1338
                , outer_side(outer_side)                                                                             \
1339
                , inner_side(inner_side)                                                                             \
1340
            {                                                                                                        \
229,238✔
1341
            }                                                                                                        \
229,238✔
1342
            void do_merge();                                                                                         \
1343
        };                                                                                                           \
1344
        template <class B, class OuterSide, class InnerSide>                                                         \
220,554✔
1345
        static inline void merge(A& outer, B& inner, OuterSide& outer_side, InnerSide& inner_side)                   \
220,554✔
1346
        {                                                                                                            \
229,238✔
1347
            DoMerge<B, OuterSide, InnerSide> do_merge{outer, inner, outer_side, inner_side};                         \
229,238✔
1348
            do_merge.do_merge();                                                                                     \
229,238✔
1349
        }                                                                                                            \
229,238✔
1350
    };                                                                                                               \
220,554✔
1351
    template <class B, class OuterSide, class InnerSide>                                                             \
220,554✔
1352
    void MergeNested<A>::DoMerge<B, OuterSide, InnerSide>::do_merge()
220,554✔
1353

220,554✔
1354
#define DEFINE_NESTED_MERGE_NOOP(A)                                                                                  \
1355
    template <>                                                                                                      \
1356
    struct MergeNested<A> {                                                                                          \
1357
        template <class B, class OuterSide, class InnerSide>                                                         \
1358
        static inline void merge(const A&, const B&, const OuterSide&, const InnerSide&)                             \
1359
        { /* Do nothing */                                                                                           \
322,408✔
1360
        }                                                                                                            \
322,408✔
1361
    }
1362

1363
// Implementation that reverses order.
317,936✔
1364
template <class A, class B>
317,936✔
1365
struct Merge<A, B,
1366
             typename std::enable_if<(Instruction::GetInstructionType<A>::value <
1367
                                      Instruction::GetInstructionType<B>::value)>::type> {
1368
    template <class LeftSide, class RightSide>
1369
    static void merge(A& left, B& right, LeftSide& left_side, RightSide& right_side)
1370
    {
455,878✔
1371
        Merge<B, A>::merge(right, left, right_side, left_side);
455,878✔
1372
    }
455,878✔
1373
};
1374

442,168✔
1375
///
442,168✔
1376
///  GET READY!
442,168✔
1377
///
1378
///  Realm supports 14 instructions at the time of this writing. Each
1379
///  instruction type needs one rule for each other instruction type. We only
1380
///  define one rule to handle each combination (A vs B and B vs A are handle by
1381
///  a single rule).
1382
///
1383
///  This gives (14 * (14 + 1)) / 2 = 105 merge rules below.
1384
///
1385
///  Merge rules are ordered such that the second instruction type is always of
1386
///  a lower enum value than the first.
1387
///
1388
///  Nested merge rules apply when one instruction has a strictly longer path
1389
///  than another. All instructions that have a path of the same length will
1390
///  meet each other through regular merge rules, regardless of whether they
1391
///  share a prefix.
1392
///
1393

1394

1395
/// AddTable rules
1396

1397
DEFINE_NESTED_MERGE_NOOP(Instruction::AddTable);
1398

1399
DEFINE_MERGE(Instruction::AddTable, Instruction::AddTable)
1400
{
6,898✔
1401
    if (same_table(left, right)) {
6,898✔
1402
        StringData left_name = left_side.get_string(left.table);
3,622✔
1403
        if (auto left_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&left.type)) {
3,622✔
1404
            if (auto right_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&right.type)) {
10,630✔
1405
                StringData left_pk_name = left_side.get_string(left_spec->pk_field);
10,630✔
1406
                StringData right_pk_name = right_side.get_string(right_spec->pk_field);
7,262✔
1407
                if (left_pk_name != right_pk_name) {
7,262✔
1408
                    bad_merge(
3,642✔
1409
                        "Schema mismatch: '%1' has primary key '%2' on one side, but primary key '%3' on the other.",
3,642✔
1410
                        left_name, left_pk_name, right_pk_name);
3,642✔
1411
                }
3,642✔
1412

3,566✔
1413
                if (left_spec->pk_type != right_spec->pk_type) {
3,566✔
1414
                    bad_merge("Schema mismatch: '%1' has primary key '%2', which is of type %3 on one side and type "
8✔
1415
                              "%4 on the other.",
8✔
1416
                              left_name, left_pk_name, get_type_name(left_spec->pk_type),
4✔
1417
                              get_type_name(right_spec->pk_type));
3,644✔
1418
                }
8✔
1419

3,566✔
1420
                if (left_spec->pk_nullable != right_spec->pk_nullable) {
3,566✔
1421
                    bad_merge("Schema mismatch: '%1' has primary key '%2', which is nullable on one side, but not "
8✔
1422
                              "the other.",
8✔
1423
                              left_name, left_pk_name);
4✔
1424
                }
3,644✔
1425

3,566✔
1426
                if (left_spec->is_asymmetric != right_spec->is_asymmetric) {
3,566✔
1427
                    bad_merge("Schema mismatch: '%1' is asymmetric on one side, but not on the other.", left_name);
6✔
1428
                }
6✔
1429
            }
3,562✔
1430
            else {
3,640✔
1431
                bad_merge("Schema mismatch: '%1' has a primary key on one side, but not on the other.", left_name);
2✔
1432
            }
2✔
1433
        }
7,202✔
1434
        else if (mpark::get_if<Instruction::AddTable::EmbeddedTable>(&left.type)) {
60✔
1435
            if (!mpark::get_if<Instruction::AddTable::EmbeddedTable>(&right.type)) {
60✔
1436
                bad_merge("Schema mismatch: '%1' is an embedded table on one side, but not the other.", left_name);
×
1437
            }
3,640✔
1438
        }
120✔
1439

3,682✔
1440
        // Names are the same, PK presence is the same, and if there is a primary
3,622✔
1441
        // key, its name, type, and nullability are the same. Discard both sides.
3,622✔
1442
        left_side.discard();
3,682✔
1443
        right_side.discard();
3,622✔
1444
        return;
3,622✔
1445
    }
3,622✔
1446
}
10,598✔
1447

3,700✔
1448
DEFINE_MERGE(Instruction::EraseTable, Instruction::AddTable)
3,700✔
1449
{
5,416✔
1450
    if (same_table(left, right)) {
8,784✔
1451
        right_side.discard();
1452
    }
1453
}
3,716✔
1454

2,000✔
1455
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::AddTable);
1456
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::AddTable);
1457
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::AddTable);
2,000✔
1458
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::AddTable);
1459
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::AddTable);
1460
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::AddTable);
1461
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddTable);
1462
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddTable);
1463
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddTable);
1464
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddTable);
1465
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddTable);
1466
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddTable);
1467

1468
/// EraseTable rules
1469

1470
DEFINE_NESTED_MERGE(Instruction::EraseTable)
1471
{
80,024✔
1472
    if (is_prefix_of(outer, inner)) {
80,024✔
1473
        inner_side.discard();
17,380✔
1474
    }
17,380✔
1475
}
163,544✔
1476

83,520!
1477
DEFINE_MERGE(Instruction::EraseTable, Instruction::EraseTable)
19,000✔
1478
{
19,636✔
1479
    if (same_table(left, right)) {
84,156✔
1480
        left_side.discard();
132✔
1481
        right_side.discard();
132✔
1482
    }
892✔
1483
}
1,396✔
1484

168✔
1485
// Handled by nesting rule.
168✔
1486
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::EraseTable);
168✔
1487
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::EraseTable);
760✔
1488
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::EraseTable);
1489
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::EraseTable);
1490

1491
DEFINE_MERGE(Instruction::AddColumn, Instruction::EraseTable)
1492
{
3,980✔
1493
    // AddColumn on an erased table handled by nesting.
3,980✔
1494

3,980✔
1495
    if (left.type == Instruction::Payload::Type::Link && same_string(left.link_target_table, right.table)) {
3,980✔
1496
        // Erase of a table where the left side adds a link column targeting it.
4,436✔
1497
        Instruction::EraseColumn erase_column;
1498
        erase_column.table = right_side.adopt_string(left_side, left.table);
1499
        erase_column.field = right_side.adopt_string(left_side, left.field);
4,436!
1500
        right_side.prepend(erase_column);
1501
        left_side.discard();
×
1502
    }
×
1503
}
3,980✔
1504

1505
// Handled by nested rule.
1506
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::EraseTable);
1507
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseTable);
4,436✔
1508
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseTable);
1509
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseTable);
1510
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseTable);
1511
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseTable);
1512
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseTable);
1513

1514

1515
/// CreateObject rules
1516

1517
// CreateObject cannot interfere with instructions that have a longer path.
1518
DEFINE_NESTED_MERGE_NOOP(Instruction::CreateObject);
1519

1520
// CreateObject is idempotent.
1521
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::CreateObject);
1522

1523
DEFINE_MERGE(Instruction::EraseObject, Instruction::CreateObject)
1524
{
188,452✔
1525
    if (same_object(left, right)) {
188,452✔
1526
        // CONFLICT: Create and Erase of the same object.
7,830✔
1527
        //
7,830✔
1528
        // RESOLUTION: Erase always wins.
199,618✔
1529
        right_side.discard();
199,618✔
1530
    }
7,830✔
1531
}
188,452✔
1532

1533
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::CreateObject);
7,538✔
1534
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::CreateObject);
7,538✔
1535
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::CreateObject);
191,788✔
1536
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::CreateObject);
1537
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::CreateObject);
1538
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::CreateObject);
1539
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::CreateObject);
1540
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::CreateObject);
1541
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::CreateObject);
1542
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::CreateObject);
1543

1544

1545
/// Erase rules
1546

1547
DEFINE_NESTED_MERGE(Instruction::EraseObject)
1548
{
129,770✔
1549
    if (is_prefix_of(outer, inner)) {
129,770✔
1550
        // Erase always wins.
11,282✔
1551
        inner_side.discard();
11,282✔
1552
    }
129,714✔
1553
}
248,202!
1554

1555
DEFINE_MERGE(Instruction::EraseObject, Instruction::EraseObject)
10,718✔
1556
{
76,092✔
1557
    if (same_object(left, right)) {
183,806✔
1558
        // We keep the most recent erase. This prevents the situation where a
7,112✔
1559
        // high number of EraseObject instructions in the past trumps a
7,112✔
1560
        // Erase-Create pair in the future.
73,844✔
1561
        if (right_side.timestamp() < left_side.timestamp()) {
73,844✔
1562
            right_side.discard();
3,556✔
1563
        }
3,556✔
1564
        else {
3,556✔
1565
            left_side.discard();
10,564✔
1566
        }
7,060✔
1567
    }
10,616✔
1568
}
68,878✔
1569

3,504✔
1570
// Handled by nested merge.
3,504✔
1571
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::EraseObject);
7,008✔
1572
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::EraseObject);
66,732✔
1573
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::EraseObject);
1574
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::EraseObject);
1575
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseObject);
1576
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseObject);
1577
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseObject);
1578
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseObject);
1579
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseObject);
1580
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseObject);
1581

1582

1583
/// Set rules
1584

1585
DEFINE_NESTED_MERGE(Instruction::Update)
1586
{
19,182✔
1587
    using Type = Instruction::Payload::Type;
19,182✔
1588

19,182✔
1589
    if (outer.value.type == Type::ObjectValue || outer.value.type == Type::Dictionary) {
19,182✔
1590
        // Creating an embedded object or a dictionary is an idempotent
18,286✔
1591
        // operation, and should not eliminate updates to the subtree.
18,286✔
1592
        return;
32✔
1593
    }
18,286!
1594

19,150✔
1595
    // Setting a value higher up in the hierarchy overwrites any modification to
19,150✔
1596
    // the inner value, regardless of when this happened.
19,182✔
1597
    if (is_prefix_of(outer, inner)) {
19,182✔
1598
        inner_side.discard();
40✔
1599
    }
40✔
1600
}
19,150✔
1601

18,222!
1602
DEFINE_MERGE(Instruction::Update, Instruction::Update)
40✔
1603
{
12,674✔
1604
    // The two instructions are at the same level of nesting.
30,856✔
1605

12,634✔
1606
    using Type = Instruction::Payload::Type;
12,634✔
1607

23,914✔
1608
    if (same_path(left, right)) {
12,634✔
1609
        bool left_is_default = false;
3,934✔
1610
        bool right_is_default = false;
15,214✔
1611
        if (!(left.is_array_update() == right.is_array_update())) {
3,934✔
1612
            bad_merge(left_side, left, "Merge error: left.is_array_update() == right.is_array_update()");
11,280✔
1613
        }
3,616✔
1614

7,550✔
1615
        if (!left.is_array_update()) {
7,550✔
1616
            if (right.is_array_update()) {
3,738✔
1617
                bad_merge(right_side, right, "Merge error: !right.is_array_update()");
×
1618
            }
1619
            left_is_default = left.is_default;
7,354✔
1620
            right_is_default = right.is_default;
7,150✔
1621
        }
3,738✔
1622
        else if (!(left.prior_size == right.prior_size)) {
196✔
1623
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
3,412✔
1624
        }
3,412✔
1625

7,346✔
1626
        if (left.value.type != right.value.type) {
4,138✔
1627
            // Embedded object / dictionary creation should always lose to an
128✔
1628
            // Update(value), because these structures are nested, and we need to
128✔
1629
            // discard any update inside the structure.
128✔
1630
            if (left.value.type == Type::Dictionary || left.value.type == Type::ObjectValue) {
3,744✔
1631
                left_side.discard();
12✔
1632
                return;
12✔
1633
            }
12✔
1634
            else if (right.value.type == Type::Dictionary || right.value.type == Type::ObjectValue) {
236✔
1635
                right_side.discard();
24✔
1636
                return;
24✔
1637
            }
24✔
1638
        }
4,018✔
1639

3,922✔
1640
        // CONFLICT: Two updates of the same element.
3,922✔
1641
        //
3,922✔
1642
        // RESOLUTION: Suppress the effect of the UPDATE operation with the lower
7,502✔
1643
        // timestamp. Note that the timestamps can never be equal. This is
3,910✔
1644
        // achieved on both sides by discarding the received UPDATE operation if
3,910✔
1645
        // it has a lower timestamp than the previously applied UPDATE operation.
3,910✔
1646
        if (left_is_default == right_is_default) {
3,910✔
1647
            if (left_side.timestamp() < right_side.timestamp()) {
3,822✔
1648
                left_side.discard(); // --->
1,954✔
1649
            }
1,954✔
1650
            else {
5,460✔
1651
                right_side.discard(); // <---
5,384✔
1652
            }
3,796✔
1653
        }
5,750✔
1654
        else {
1,676✔
1655
            if (left_is_default) {
1,676✔
1656
                left_side.discard();
1,634✔
1657
            }
3,562✔
1658
            else {
118✔
1659
                right_side.discard();
118✔
1660
            }
80✔
1661
        }
126✔
1662
    }
3,948✔
1663
}
12,672✔
1664

38✔
1665
DEFINE_MERGE(Instruction::AddInteger, Instruction::Update)
76✔
1666
{
4,774✔
1667
    // The two instructions are at the same level of nesting.
12,462✔
1668

1,182✔
1669
    if (same_path(left, right)) {
1,182✔
1670
        // CONFLICT: Add vs Set of the same element.
1,596✔
1671
        //
212✔
1672
        // RESOLUTION: If the Add was later than the Set, add its value to
212✔
1673
        // the payload of the Set instruction. Otherwise, discard it.
1,596✔
1674

212✔
1675
        if (!(right.value.type == Instruction::Payload::Type::Int || right.value.is_null())) {
212✔
1676
            bad_merge(right_side, right,
1677
                      "Merge error: right.value.type == Instruction::Payload::Type::Int || right.value.is_null()");
1678
        }
1679

480✔
1680
        bool right_is_default = !right.is_array_update() && right.is_default;
212✔
1681

212✔
1682
        // Note: AddInteger survives SetDefault, regardless of timestamp.
212✔
1683
        if (right_side.timestamp() < left_side.timestamp() || right_is_default) {
212✔
1684
            if (right.value.is_null()) {
424✔
1685
                // The AddInteger happened "after" the Set(null). This becomes a
28✔
1686
                // no-op, but if the server later integrates a Set(int) that
28✔
1687
                // came-before the AddInteger, it will be taken into account again.
296✔
1688
                return;
228✔
1689
            }
28✔
1690

128✔
1691
            // Wrapping add
128✔
1692
            uint64_t ua = uint64_t(right.value.data.integer);
156✔
1693
            uint64_t ub = uint64_t(left.value);
156✔
1694
            right.value.data.integer = int64_t(ua + ub);
128✔
1695
        }
128✔
1696
        else {
228✔
1697
            left_side.discard();
228✔
1698
        }
228✔
1699
    }
384✔
1700
}
1,250✔
1701

68✔
1702
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::Update);
68✔
1703

268✔
1704
DEFINE_MERGE(Instruction::EraseColumn, Instruction::Update)
1,384✔
1705
{
1706
    if (same_column(left, right)) {
1707
        right_side.discard();
1708
    }
1709
}
×
1710

×
1711
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::Update)
1712
{
30,020✔
1713
    if (same_container(left, right)) {
30,020✔
1714
        REALM_ASSERT(right.is_array_update());
5,156✔
1715
        if (!(left.prior_size == right.prior_size)) {
5,156✔
1716
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
26,938✔
1717
        }
26,938✔
1718
        if (!(left.index() <= left.prior_size)) {
9,640✔
1719
            bad_merge(left_side, left, "Merge error: left.index() <= left.prior_size");
4,484✔
1720
        }
×
1721
        if (!(right.index() < right.prior_size)) {
5,156✔
1722
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
4,484✔
1723
        }
×
1724
        right.prior_size += 1;
5,156✔
1725
        if (right.index() >= left.index()) {
9,640✔
1726
            right.index() += 1; // --->
2,224✔
1727
        }
2,224✔
1728
    }
9,640✔
1729
}
34,504✔
1730

1,976✔
1731
DEFINE_MERGE(Instruction::ArrayMove, Instruction::Update)
1,976✔
1732
{
4,496✔
1733
    if (same_container(left, right)) {
26,950✔
1734
        REALM_ASSERT(right.is_array_update());
1735

1736
        if (!(left.index() < left.prior_size)) {
12✔
1737
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
12✔
1738
        }
×
1739
        if (!(right.index() < right.prior_size)) {
1740
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
1741
        }
×
1742

×
1743
        // FIXME: This marks both sides as dirty, even when they are unmodified.
×
1744
        merge_get_vs_move(right.index(), left.index(), left.ndx_2);
×
1745
    }
×
1746
}
12✔
1747

1748
DEFINE_MERGE(Instruction::ArrayErase, Instruction::Update)
1749
{
6,424✔
1750
    if (same_container(left, right)) {
6,436✔
1751
        REALM_ASSERT(right.is_array_update());
1,500✔
1752
        if (!(left.prior_size == right.prior_size)) {
1,500✔
1753
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
5,400✔
1754
        }
5,400✔
1755
        if (!(left.index() < left.prior_size)) {
2,800✔
1756
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
1,300✔
1757
        }
×
1758
        if (!(right.index() < right.prior_size)) {
1,500✔
1759
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
1,300✔
1760
        }
×
1761

1,500✔
1762
        // CONFLICT: Update of a removed element.
2,800✔
1763
        //
1,500✔
1764
        // RESOLUTION: Discard the UPDATE operation received on the right side.
1,500✔
1765
        right.prior_size -= 1;
1,500✔
1766

1,500✔
1767
        if (left.index() == right.index()) {
1,500✔
1768
            // CONFLICT: Update of a removed element.
328✔
1769
            //
1,628✔
1770
            // RESOLUTION: Discard the UPDATE operation received on the right side.
328✔
1771
            right_side.discard();
1,628✔
1772
        }
328✔
1773
        else if (right.index() > left.index()) {
1,172✔
1774
            right.index() -= 1;
528✔
1775
        }
812✔
1776
    }
1,784✔
1777
}
7,440✔
1778

604✔
1779
// Handled by nested rule
604✔
1780
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::Update);
1,300✔
1781
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::Update);
5,400✔
1782
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::Update);
1783

1784

1785
/// AddInteger rules
1786

1787
DEFINE_NESTED_MERGE_NOOP(Instruction::AddInteger);
1788
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::AddInteger);
1789
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::AddInteger);
1790
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::AddInteger);
1791
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddInteger);
1792
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddInteger);
1793
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddInteger);
1794
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddInteger);
1795
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddInteger);
1796
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddInteger);
1797

1798

1799
/// AddColumn rules
1800

1801
DEFINE_NESTED_MERGE_NOOP(Instruction::AddColumn);
1802

1803
DEFINE_MERGE(Instruction::AddColumn, Instruction::AddColumn)
1804
{
17,192✔
1805
    if (same_column(left, right)) {
17,192✔
1806
        StringData left_name = left_side.get_string(left.field);
4,832✔
1807
        if (left.type != right.type) {
4,832✔
1808
            bad_merge(
17,702✔
1809
                "Schema mismatch: Property '%1' in class '%2' is of type %3 on one side and type %4 on the other.",
17,702✔
1810
                left_name, left_side.get_string(left.table), get_type_name(left.type), get_type_name(right.type));
4,928✔
1811
        }
4,928✔
1812

4,836✔
1813
        if (left.nullable != right.nullable) {
4,836✔
1814
            bad_merge("Schema mismatch: Property '%1' in class '%2' is nullable on one side and not on the other.",
8✔
1815
                      left_name, left_side.get_string(left.table));
8✔
1816
        }
4✔
1817

9,756✔
1818
        if (left.collection_type != right.collection_type) {
4,836✔
1819
            auto collection_type_name = [](Instruction::AddColumn::CollectionType type) -> const char* {
4✔
1820
                switch (type) {
4✔
1821
                    case Instruction::AddColumn::CollectionType::Single:
1822
                        return "single value";
4,924✔
1823
                    case Instruction::AddColumn::CollectionType::List:
×
1824
                        return "list";
×
1825
                    case Instruction::AddColumn::CollectionType::Dictionary:
×
1826
                        return "dictionary";
×
1827
                    case Instruction::AddColumn::CollectionType::Set:
×
1828
                        return "set";
×
1829
                }
×
1830
                REALM_TERMINATE("");
×
1831
            };
×
1832

×
1833
            std::stringstream ss;
×
1834
            const char* left_type = collection_type_name(left.collection_type);
×
1835
            const char* right_type = collection_type_name(right.collection_type);
×
1836
            bad_merge("Schema mismatch: Property '%1' in class '%2' is a %3 on one side, and a %4 on the other.",
1837
                      left_name, left_side.get_string(left.table), left_type, right_type);
×
1838
        }
×
1839

4,832✔
1840
        if (left.type == Instruction::Payload::Type::Link) {
4,832✔
1841
            StringData left_target = left_side.get_string(left.link_target_table);
862✔
1842
            StringData right_target = right_side.get_string(right.link_target_table);
862✔
1843
            if (left_target != right_target) {
862✔
1844
                bad_merge("Schema mismatch: Link property '%1' in class '%2' points to class '%3' on one side and to "
4,928✔
1845
                          "'%4' on the other.",
866✔
1846
                          left_name, left_side.get_string(left.table), left_target, right_target);
866✔
1847
            }
866✔
1848
        }
866✔
1849

4,836✔
1850
        // Name, type, nullability and link targets match -- discard both
4,836✔
1851
        // sides and proceed.
4,836✔
1852
        left_side.discard();
5,694✔
1853
        right_side.discard();
4,832✔
1854
    }
4,832✔
1855
}
17,192✔
1856

4,924✔
1857
DEFINE_MERGE(Instruction::EraseColumn, Instruction::AddColumn)
4,924✔
1858
{
4,924✔
1859
    if (same_column(left, right)) {
17,698✔
1860
        right_side.discard();
1861
    }
1862
}
×
1863

×
1864
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::AddColumn);
1865
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::AddColumn);
1866
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::AddColumn);
1867
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::AddColumn);
1868
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::AddColumn);
1869
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::AddColumn);
1870

1871

1872
/// EraseColumn rules
1873

1874
DEFINE_NESTED_MERGE_NOOP(Instruction::EraseColumn);
1875

1876
DEFINE_MERGE(Instruction::EraseColumn, Instruction::EraseColumn)
1877
{
1878
    if (same_column(left, right)) {
1879
        left_side.discard();
1880
        right_side.discard();
1881
    }
×
1882
}
×
1883

1884
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseColumn);
1885
DEFINE_MERGE_NOOP(Instruction::ArrayMove, Instruction::EraseColumn);
1886
DEFINE_MERGE_NOOP(Instruction::ArrayErase, Instruction::EraseColumn);
1887
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::EraseColumn);
1888
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::EraseColumn);
1889
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::EraseColumn);
1890

1891
/// ArrayInsert rules
1892

1893
DEFINE_NESTED_MERGE(Instruction::ArrayInsert)
1894
{
8✔
1895
    if (is_container_prefix_of(outer, inner)) {
8✔
1896
        auto& index = corresponding_index_in_path(outer, inner);
8✔
1897
        if (index >= outer.index()) {
8✔
1898
            index += 1;
12✔
1899
        }
12!
1900
    }
16✔
1901
}
16!
1902

4✔
1903
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::ArrayInsert)
4✔
1904
{
34,094✔
1905
    if (same_container(left, right)) {
34,094✔
1906
        if (!(left.prior_size == right.prior_size)) {
10,206✔
1907
            bad_merge(right_side, right, "Exception: left.prior_size == right.prior_size");
1908
        }
30,274✔
1909
        left.prior_size++;
40,480✔
1910
        right.prior_size++;
18,952✔
1911

10,206✔
1912
        if (left.index() > right.index()) {
10,206✔
1913
            left.index() += 1; // --->
11,108✔
1914
        }
11,108✔
1915
        else if (left.index() < right.index()) {
7,844✔
1916
            right.index() += 1; // <---
11,110✔
1917
        }
4,280✔
1918
        else { // left index == right index
7,396✔
1919
            // CONFLICT: Two element insertions at the same position.
12,310✔
1920
            //
7,398✔
1921
            // Resolution: Place the inserted elements in order of increasing
7,398✔
1922
            // timestamp. Note that the timestamps can never be equal.
10,392✔
1923
            if (left_side.timestamp() < right_side.timestamp()) {
5,480✔
1924
                right.index() += 1;
2,738✔
1925
            }
2,738✔
1926
            else {
2,742✔
1927
                left.index() += 1;
7,654✔
1928
            }
5,196✔
1929
        }
7,934✔
1930
    }
12,664✔
1931
}
36,544✔
1932

2,458✔
1933
DEFINE_MERGE(Instruction::ArrayMove, Instruction::ArrayInsert)
4,912✔
1934
{
8,746✔
1935
    if (same_container(left, right)) {
30,274✔
1936
        left.prior_size += 1;
1937

1938
        // Left insertion vs right removal
×
1939
        if (right.index() > left.index()) {
×
1940
            right.index() -= 1; // --->
×
1941
        }
1942
        else {
1943
            left.index() += 1; // <---
×
1944
        }
×
1945

×
1946
        // Left insertion vs left insertion
×
1947
        if (right.index() < left.ndx_2) {
×
1948
            left.ndx_2 += 1; // <---
×
1949
        }
1950
        else if (right.index() > left.ndx_2) {
1951
            right.index() += 1; // --->
×
1952
        }
×
1953
        else { // right.index() == left.ndx_2
×
1954
            // CONFLICT: Insertion and movement to same position.
×
1955
            //
×
1956
            // RESOLUTION: Place the two elements in order of increasing
×
1957
            // timestamp. Note that the timestamps can never be equal.
×
1958
            if (left_side.timestamp() < right_side.timestamp()) {
1959
                left.ndx_2 += 1; // <---
1960
            }
1961
            else {
1962
                right.index() += 1; // --->
×
1963
            }
×
1964
        }
×
1965
    }
×
1966
}
×
1967

1968
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayInsert)
1969
{
15,518✔
1970
    if (same_container(left, right)) {
15,518✔
1971
        if (!(left.prior_size == right.prior_size)) {
5,422✔
1972
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
1973
        }
12,468✔
1974
        if (!(left.index() < left.prior_size)) {
17,890✔
1975
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
4,126✔
1976
        }
×
1977
        if (!(right.index() <= right.prior_size)) {
5,422✔
1978
            bad_merge(left_side, left, "Merge error: right.index() <= right.prior_size");
4,126✔
1979
        }
×
1980

5,422✔
1981
        left.prior_size++;
9,548✔
1982
        right.prior_size--;
5,422✔
1983
        if (right.index() <= left.index()) {
5,422✔
1984
            left.index() += 1; // --->
2,426✔
1985
        }
6,552✔
1986
        else {
7,122✔
1987
            right.index() -= 1; // <---
7,122✔
1988
        }
4,762✔
1989
    }
7,188✔
1990
}
17,878✔
1991

2,360✔
1992
// Handled by nested rules
2,360✔
1993
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayInsert);
4,126✔
1994
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayInsert);
12,468✔
1995
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayInsert);
1996

1997

1998
/// ArrayMove rules
1999

2000
DEFINE_NESTED_MERGE(Instruction::ArrayMove)
2001
{
2002
    if (is_container_prefix_of(outer, inner)) {
2003
        auto& index = corresponding_index_in_path(outer, inner);
2004
        merge_get_vs_move(outer.index(), index, outer.ndx_2);
2005
    }
×
2006
}
×
2007

2008
DEFINE_MERGE(Instruction::ArrayMove, Instruction::ArrayMove)
2009
{
14✔
2010
    if (same_container(left, right)) {
14✔
2011
        if (!(left.prior_size == right.prior_size)) {
14✔
2012
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
2013
        }
14✔
2014
        if (!(left.index() < left.prior_size)) {
28✔
2015
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
14✔
2016
        }
×
2017
        if (!(right.index() < right.prior_size)) {
14✔
2018
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
14✔
2019
        }
×
2020
        if (!(left.ndx_2 < left.prior_size)) {
14✔
2021
            bad_merge(left_side, left, "Merge error: left.ndx_2 < left.prior_size");
14✔
2022
        }
×
2023
        if (!(right.ndx_2 < right.prior_size)) {
14✔
2024
            bad_merge(right_side, right, "Merge error: right.ndx_2 < right.prior_size");
14✔
2025
        }
×
2026

14✔
2027
        if (left.index() < right.index()) {
28✔
2028
            right.index() -= 1; // <---
2✔
2029
        }
2✔
2030
        else if (left.index() > right.index()) {
12✔
2031
            left.index() -= 1; // --->
16✔
2032
        }
4✔
2033
        else {
12✔
2034
            // CONFLICT: Two movements of same element.
22✔
2035
            //
12✔
2036
            // RESOLUTION: Respect the MOVE operation associated with the higher
12✔
2037
            // timestamp. If the previously applied MOVE operation has the higher
20✔
2038
            // timestamp, discard the received MOVE operation, otherwise use the
10✔
2039
            // previously applied MOVE operation to transform the received MOVE
10✔
2040
            // operation. Note that the timestamps are never equal.
10✔
2041
            if (left_side.timestamp() < right_side.timestamp()) {
10✔
2042
                right.index() = left.ndx_2; // <---
6✔
2043
                left_side.discard();        // --->
6✔
2044
                if (right.index() == right.ndx_2) {
6✔
2045
                    right_side.discard(); // <---
10✔
2046
                }
6✔
2047
            }
12✔
2048
            else {
10✔
2049
                left.index() = right.ndx_2; // --->
4✔
2050
                if (left.index() == left.ndx_2) {
4✔
2051
                    left_side.discard(); // --->
6✔
2052
                }
4✔
2053
                right_side.discard(); // <---
8✔
2054
            }
8✔
2055
            return;
10✔
2056
        }
10✔
2057

8✔
2058
        // Left insertion vs right removal
8✔
2059
        if (left.ndx_2 > right.index()) {
14✔
2060
            left.ndx_2 -= 1; // --->
12✔
2061
        }
2✔
2062
        else {
2✔
2063
            right.index() += 1; // <---
6✔
2064
        }
4✔
2065

6✔
2066
        // Left removal vs right insertion
6✔
2067
        if (left.index() < right.ndx_2) {
6✔
2068
            right.ndx_2 -= 1; // <---
4✔
2069
        }
2✔
2070
        else {
2✔
2071
            left.index() += 1; // --->
6✔
2072
        }
4✔
2073

6✔
2074
        // Left insertion vs right insertion
6✔
2075
        if (left.ndx_2 < right.ndx_2) {
6✔
2076
            right.ndx_2 += 1; // <---
4✔
2077
        }
2✔
2078
        else if (left.ndx_2 > right.ndx_2) {
2✔
2079
            left.ndx_2 += 1; // --->
6✔
2080
        }
4✔
2081
        else { // left.ndx_2 == right.ndx_2
2✔
2082
            // CONFLICT: Two elements moved to the same position
2✔
2083
            //
2✔
2084
            // RESOLUTION: Place the moved elements in order of increasing
2✔
2085
            // timestamp. Note that the timestamps can never be equal.
×
2086
            if (left_side.timestamp() < right_side.timestamp()) {
2087
                right.ndx_2 += 1; // <---
2088
            }
2089
            else {
2090
                left.ndx_2 += 1; // --->
×
2091
            }
×
2092
        }
×
2093

4✔
2094
        if (left.index() == left.ndx_2) {
4✔
2095
            left_side.discard(); // --->
×
2096
        }
×
2097
        if (right.index() == right.ndx_2) {
4✔
2098
            right_side.discard(); // <---
4✔
2099
        }
×
2100
    }
4✔
2101
}
18✔
2102

2103
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayMove)
2104
{
4✔
2105
    if (same_container(left, right)) {
14✔
2106
        if (!(left.prior_size == right.prior_size)) {
2107
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
2108
        }
×
2109
        if (!(left.index() < left.prior_size)) {
×
2110
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
2111
        }
×
2112
        if (!(right.index() < right.prior_size)) {
×
2113
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
2114
        }
×
2115

×
2116
        right.prior_size -= 1;
×
2117

×
2118
        if (left.index() == right.index()) {
×
2119
            // CONFLICT: Removal of a moved element.
2120
            //
×
2121
            // RESOLUTION: Discard the received MOVE operation on the left side, and
2122
            // use the previously applied MOVE operation to transform the received
×
2123
            // REMOVE operation on the right side.
2124
            left.index() = right.ndx_2; // --->
2125
            right_side.discard();       // <---
2126
        }
2127
        else {
2128
            // Left removal vs right removal
×
2129
            if (left.index() > right.index()) {
×
2130
                left.index() -= 1; // --->
×
2131
            }
×
2132
            else {                  // left.index() < right.index()
2133
                right.index() -= 1; // <---
×
2134
            }
×
2135
            // Left removal vs right insertion
×
2136
            if (left.index() >= right.ndx_2) {
×
2137
                left.index() += 1; // --->
×
2138
            }
×
2139
            else {
2140
                right.ndx_2 -= 1; // <---
×
2141
            }
×
2142

×
2143
            if (right.index() == right.ndx_2) {
×
2144
                right_side.discard(); // <---
×
2145
            }
×
2146
        }
2147
    }
×
2148
}
×
2149

2150
// Handled by nested rule.
2151
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayMove);
2152
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayMove);
2153
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayMove);
2154

2155

2156
/// ArrayErase rules
2157

2158
DEFINE_NESTED_MERGE(Instruction::ArrayErase)
2159
{
4✔
2160
    if (is_prefix_of(outer, inner)) {
4✔
2161
        // Erase of subtree - inner instruction touches the subtree.
2162
        inner_side.discard();
2163
    }
4✔
2164
    else if (is_container_prefix_of(outer, inner)) {
8!
2165
        // Erase of a sibling element in the container - adjust the path.
4✔
2166
        auto& index = corresponding_index_in_path(outer, inner);
4✔
2167
        if (outer.index() < index) {
4✔
2168
            index -= 1;
8!
2169
        }
4✔
2170
        else {
4✔
2171
            REALM_ASSERT(index != outer.index());
4!
2172
        }
4✔
2173
    }
8✔
2174
}
4✔
2175

×
2176
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayErase)
2177
{
1,932✔
2178
    if (same_container(left, right)) {
1,932✔
2179
        if (!(left.prior_size == right.prior_size)) {
782✔
2180
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
2181
        }
1,264✔
2182
        if (!(left.index() < left.prior_size)) {
2,046✔
2183
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
530✔
2184
        }
×
2185
        if (!(right.index() < right.prior_size)) {
782✔
2186
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
530✔
2187
        }
×
2188

782✔
2189
        left.prior_size -= 1;
1,312✔
2190
        right.prior_size -= 1;
782✔
2191

782✔
2192
        if (left.index() > right.index()) {
782✔
2193
            left.index() -= 1; // --->
846✔
2194
        }
846✔
2195
        else if (left.index() < right.index()) {
466✔
2196
            right.index() -= 1; // <---
848✔
2197
        }
538✔
2198
        else { // left.index() == right.index()
368✔
2199
            // CONFLICT: Two removals of the same element.
458✔
2200
            //
370✔
2201
            // RESOLUTION: On each side, discard the received REMOVE operation.
370✔
2202
            left_side.discard();  // --->
236✔
2203
            right_side.discard(); // <---
148✔
2204
        }
148✔
2205
    }
782✔
2206
}
2,016✔
2207

88✔
2208
// Handled by nested rules.
88✔
2209
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayErase);
530✔
2210
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayErase);
1,264✔
2211
DEFINE_MERGE_NOOP(Instruction::SetErase, Instruction::ArrayErase);
2212

2213

2214
/// Clear rules
2215

2216
DEFINE_NESTED_MERGE(Instruction::Clear)
2217
{
250✔
2218
    // Note: Clear instructions do not have an index in their path.
250✔
2219
    if (is_prefix_of(outer, inner)) {
250✔
2220
        inner_side.discard();
116✔
2221
    }
452✔
2222
}
250✔
2223

336!
2224
DEFINE_MERGE(Instruction::Clear, Instruction::Clear)
116✔
2225
{
124✔
2226
    if (same_path(left, right)) {
344✔
2227
        // CONFLICT: Two clears of the same container.
8✔
2228
        //
8✔
2229
        // RESOLUTION: Discard the clear with the lower timestamp. This has the
16✔
2230
        // effect of preserving insertions that came after the clear from the
16✔
2231
        // side that has the higher timestamp.
8✔
2232
        if (left_side.timestamp() < right_side.timestamp()) {
8✔
2233
            left_side.discard();
6✔
2234
        }
6✔
2235
        else {
2✔
2236
            right_side.discard();
10✔
2237
        }
8✔
2238
    }
14✔
2239
}
10✔
2240

2✔
2241
DEFINE_MERGE(Instruction::SetInsert, Instruction::Clear)
2✔
2242
{
12✔
2243
    if (same_path(left, right)) {
12✔
2244
        left_side.discard();
2✔
2245
    }
2✔
2246
}
8✔
2247

4!
2248
DEFINE_MERGE(Instruction::SetErase, Instruction::Clear)
2✔
2249
{
6✔
2250
    if (same_path(left, right)) {
8✔
2251
        left_side.discard();
2✔
2252
    }
2✔
2253
}
8✔
2254

4!
2255

2✔
2256
/// SetInsert rules
2✔
2257

4✔
2258
DEFINE_NESTED_MERGE_NOOP(Instruction::SetInsert);
2259

2260
DEFINE_MERGE(Instruction::SetInsert, Instruction::SetInsert)
2261
{
78✔
2262
    if (same_path(left, right)) {
78✔
2263
        // CONFLICT: Two inserts into the same set.
76✔
2264
        //
76✔
2265
        // RESOLUTION: If the values are the same, discard the insertion with the lower timestamp. Otherwise,
154✔
2266
        // do nothing.
154✔
2267
        //
76✔
2268
        // NOTE: Set insertion is idempotent. Keeping the instruction with the higher timestamp is necessary
76✔
2269
        // because we want to maintain associativity in the case where intermittent erases (as ordered by
76✔
2270
        // timestamp) arrive at a later point in time.
76✔
2271
        if (same_payload(left.value, right.value)) {
76✔
2272
            if (left_side.timestamp() < right_side.timestamp()) {
12✔
2273
                left_side.discard();
6✔
2274
            }
6✔
2275
            else {
82✔
2276
                right_side.discard();
18✔
2277
            }
12✔
2278
        }
18✔
2279
    }
82✔
2280
}
84✔
2281

6✔
2282
DEFINE_MERGE(Instruction::SetErase, Instruction::SetInsert)
12✔
2283
{
108✔
2284
    if (same_path(left, right)) {
110✔
2285
        // CONFLICT: Insertion and erase in the same set.
32✔
2286
        //
32✔
2287
        // RESOLUTION: If the inserted/erased values are the same, discard the instruction with the lower
64✔
2288
        // timestamp. Otherwise, do nothing.
64✔
2289
        //
32✔
2290
        // Note: Set insertion and erase are both idempotent. Keeping the instruction with the higher
32✔
2291
        // timestamp is necessary because we want to maintain associativity.
32✔
2292
        if (same_payload(left.value, right.value)) {
32✔
2293
            if (left_side.timestamp() < right_side.timestamp()) {
2294
                left_side.discard();
2295
            }
2296
            else {
32✔
2297
                right_side.discard();
×
2298
            }
×
2299
        }
×
2300
    }
32✔
2301
}
32✔
2302

2303

2304
/// SetErase rules.
32✔
2305

32✔
2306
DEFINE_NESTED_MERGE_NOOP(Instruction::SetErase);
2307

2308
DEFINE_MERGE(Instruction::SetErase, Instruction::SetErase)
2309
{
2310
    if (same_path(left, right)) {
2311
        // CONFLICT: Two erases in the same set.
2312
        //
2313
        // RESOLUTION: If the values are the same, discard the instruction with the lower timestamp.
×
2314
        // Otherwise, do nothing.
×
2315
        if (left.value == right.value) {
2316
            if (left_side.timestamp() < right_side.timestamp()) {
2317
                left_side.discard();
2318
            }
2319
            else {
×
2320
                right_side.discard();
×
2321
            }
×
2322
        }
×
2323
    }
×
2324
}
×
2325

2326

2327
///
2328
/// END OF MERGE RULES!
2329
///
2330

2331
} // namespace
2332

2333
namespace _impl {
2334
template <class Left, class Right>
2335
void merge_instructions_2(Left& left, Right& right, TransformerImpl::MajorSide& left_side,
2336
                          TransformerImpl::MinorSide& right_side)
2337
{
1,260,426✔
2338
    Merge<Left, Right>::merge(left, right, left_side, right_side);
1,260,426✔
2339
}
1,260,426✔
2340

2341
template <class Outer, class Inner, class OuterSide, class InnerSide>
1,243,948✔
2342
void merge_nested_2(Outer& outer, Inner& inner, OuterSide& outer_side, InnerSide& inner_side)
1,243,948✔
2343
{
1,795,594✔
2344
    MergeNested<Outer>::merge(outer, inner, outer_side, inner_side);
551,646✔
2345
}
551,646✔
2346

2347
void TransformerImpl::Transformer::merge_instructions(MajorSide& their_side, MinorSide& our_side)
538,490✔
2348
{
1,827,730✔
2349
    // FIXME: Find a way to avoid heap-copies of the path.
1,827,730✔
2350
    Instruction their_before = their_side.get();
1,289,240✔
2351
    Instruction our_before = our_side.get();
1,289,240✔
2352

2,563,032✔
2353
    if (their_side.get().get_if<Instruction::Update>()) {
1,289,240✔
2354
        REALM_ASSERT(their_side.m_path_len > 2);
1,363,182✔
2355
    }
1,363,182✔
2356
    if (our_side.get().get_if<Instruction::Update>()) {
1,289,240✔
2357
        REALM_ASSERT(our_side.m_path_len > 2);
1,390,660✔
2358
    }
200,972✔
2359
    if (their_side.get().get_if<Instruction::EraseObject>()) {
1,373,344✔
2360
        REALM_ASSERT(their_side.m_path_len == 2);
1,531,630✔
2361
    }
365,860✔
2362
    if (our_side.get().get_if<Instruction::EraseObject>()) {
1,397,262✔
2363
        REALM_ASSERT(our_side.m_path_len == 2);
1,563,716✔
2364
    }
544,816✔
2365

1,544,132✔
2366
    // Update selections on the major side (outer loop) according to events on
2,563,032✔
2367
    // the minor side (inner loop). The selection may only be impacted if the
1,579,444✔
2368
    // instruction level is lower (i.e. at a higher point in the hierarchy).
1,579,444✔
2369
    if (our_side.m_path_len < their_side.m_path_len) {
1,289,240✔
2370
        merge_nested(our_side, their_side);
224,598✔
2371
        if (their_side.was_discarded)
224,598✔
2372
            return;
14,422✔
2373
    }
2,338,434✔
2374
    else if (our_side.m_path_len > their_side.m_path_len) {
1,288,416✔
2375
        merge_nested(their_side, our_side);
550,822✔
2376
        if (our_side.was_discarded)
341,998✔
2377
            return;
1,064,414✔
2378
    }
2,310,440✔
2379

1,575,138✔
2380
    if (!their_side.was_discarded && !our_side.was_discarded) {
1,575,138✔
2381
        // Even if the instructions were nested, we must still perform a regular
1,275,340✔
2382
        // merge, because link-related instructions contain information from higher
2,504,334✔
2383
        // levels (both rows, columns, and tables).
1,260,416✔
2384
        //
2,504,348✔
2385
        // FIXME: This condition goes away when dangling links are implemented.
1,260,416✔
2386
        their_side.get().visit([&](auto& their_instruction) {
1,260,428✔
2387
            our_side.get().visit([&](auto& our_instruction) {
1,260,428✔
2388
                merge_instructions_2(their_instruction, our_instruction, their_side, our_side);
1,260,426✔
2389
            });
1,260,426✔
2390
        });
2,504,370✔
2391
    }
2,504,364✔
2392

2,504,370✔
2393
    // Note: `left` and/or `right` may be dangling at this point due to
2,504,370✔
2394
    // discard/prepend. However, if they were not discarded, their iterators are
2,504,364✔
2395
    // required to point to an instruction of the same type.
2,504,350✔
2396
    if (!their_side.was_discarded && !their_side.was_replaced) {
1,260,422✔
2397
        const auto& their_after = their_side.get();
1,241,986✔
2398
        if (!(their_after == their_before)) {
1,241,986✔
2399
            their_side.m_changeset->set_dirty(true);
19,498✔
2400
        }
1,263,416✔
2401
    }
2,467,576✔
2402

2,486,012✔
2403
    if (!our_side.was_discarded && !our_side.was_replaced) {
1,276,580✔
2404
        const auto& our_after = our_side.get();
1,258,260✔
2405
        if (!(our_after == our_before)) {
2,467,692✔
2406
            our_side.m_changeset->set_dirty(true);
19,500✔
2407
        }
1,263,418✔
2408
    }
2,468,076✔
2409
}
2,486,396✔
2410

16,160✔
2411

16,160✔
2412
template <class OuterSide, class InnerSide>
1,225,974✔
2413
void TransformerImpl::Transformer::merge_nested(OuterSide& outer_side, InnerSide& inner_side)
1,243,918✔
2414
{
551,646✔
2415
    outer_side.get().visit([&](auto& outer) {
551,646✔
2416
        inner_side.get().visit([&](auto& inner) {
551,646✔
2417
            merge_nested_2(outer, inner, outer_side, inner_side);
551,646✔
2418
        });
1,090,136✔
2419
    });
1,090,136✔
2420
}
1,090,136✔
2421

538,490✔
2422

538,490✔
2423
void TransformerImpl::merge_changesets(file_ident_type local_file_ident, Changeset* their_changesets,
538,490✔
2424
                                       size_t their_size, Changeset** our_changesets, size_t our_size,
538,490✔
2425
                                       util::Logger& logger)
2426
{
210,102✔
2427
    REALM_ASSERT(their_size != 0);
210,102✔
2428
    REALM_ASSERT(our_size != 0);
210,102✔
2429
    bool trace = false;
210,102✔
2430
#if REALM_DEBUG && !REALM_UWP
416,172✔
2431
    // FIXME: Not thread-safe (use config parameter instead and confine environment reading to test/test_all.cpp)
416,172✔
2432
    const char* trace_p = ::getenv("UNITTEST_TRACE_TRANSFORM");
416,172✔
2433
    trace = (trace_p && StringData{trace_p} != "no");
416,172✔
2434
    static std::mutex trace_mutex;
416,172✔
2435
    util::Optional<std::unique_lock<std::mutex>> l;
210,102✔
2436
    if (trace) {
416,172✔
2437
        l = std::unique_lock<std::mutex>{trace_mutex};
206,070!
2438
    }
206,070✔
2439
#endif
416,172✔
2440
    Transformer transformer{trace};
416,172✔
2441

210,102✔
2442
    _impl::ChangesetIndex their_index;
210,102✔
2443
    size_t their_num_instructions = 0;
416,172✔
2444
    size_t our_num_instructions = 0;
416,172✔
2445

210,102✔
2446
    // Loop through all instructions on both sides and build conflict groups.
416,172✔
2447
    // This causes the index to merge ranges that are connected by instructions
416,172✔
2448
    // on the left side, but which aren't connected on the right side.
416,172✔
2449
    // FIXME: The conflict groups can be persisted as part of the changeset to
210,102✔
2450
    // skip this step in the future.
210,102✔
2451
    for (size_t i = 0; i < their_size; ++i) {
431,104✔
2452
        size_t num_instructions = their_changesets[i].size();
221,002✔
2453
        their_num_instructions += num_instructions;
221,002✔
2454
        logger.trace("Scanning incoming changeset [%1/%2] (%3 instructions)", i + 1, their_size, num_instructions);
221,002✔
2455

645,700✔
2456
        their_index.scan_changeset(their_changesets[i]);
439,630✔
2457
    }
439,630✔
2458
    for (size_t i = 0; i < our_size; ++i) {
5,354,742✔
2459
        Changeset& our_changeset = *our_changesets[i];
4,926,012✔
2460
        size_t num_instructions = our_changeset.size();
5,144,640✔
2461
        our_num_instructions += num_instructions;
5,144,640✔
2462
        logger.trace("Scanning local changeset [%1/%2] (%3 instructions)", i + 1, our_size, num_instructions);
10,048,156✔
2463

9,842,086✔
2464
        their_index.scan_changeset(our_changeset);
9,842,086✔
2465
    }
9,842,086✔
2466

5,126,176✔
2467
    // Build the index.
210,102✔
2468
    for (size_t i = 0; i < their_size; ++i) {
5,347,176✔
2469
        logger.trace("Indexing incoming changeset [%1/%2] (%3 instructions)", i + 1, their_size,
5,137,074✔
2470
                     their_changesets[i].size());
221,000✔
2471
        their_index.add_changeset(their_changesets[i]);
221,000✔
2472
    }
645,700✔
2473

428,732✔
2474
    logger.debug("Finished changeset indexing (incoming: %1 changeset(s) / %2 instructions, local: %3 "
428,732✔
2475
                 "changeset(s) / %4 instructions, conflict group(s): %5)",
428,732✔
2476
                 their_size, their_num_instructions, our_size, our_num_instructions,
428,732✔
2477
                 their_index.get_num_conflict_groups());
210,102✔
2478

416,172✔
2479
#if REALM_DEBUG // LCOV_EXCL_START
416,172✔
2480
    if (trace) {
416,172✔
2481
        std::cerr << TERM_YELLOW << "\n=> PEER " << std::hex << local_file_ident
206,070✔
2482
                  << " merging "
2483
                     "changeset(s)/from peer(s):\n";
2484
        for (size_t i = 0; i < their_size; ++i) {
206,070✔
2485
            std::cerr << "Changeset version " << std::dec << their_changesets[i].version << " from peer "
×
2486
                      << their_changesets[i].origin_file_ident << " at timestamp "
×
2487
                      << their_changesets[i].origin_timestamp << "\n";
×
2488
        }
×
2489
        std::cerr << "Transforming through local changeset(s):\n";
×
2490
        for (size_t i = 0; i < our_size; ++i) {
×
2491
            std::cerr << "Changeset version " << our_changesets[i]->version << " from peer "
×
2492
                      << our_changesets[i]->origin_file_ident << " at timestamp "
×
2493
                      << our_changesets[i]->origin_timestamp << "\n";
×
2494
        }
×
2495

×
2496
        for (size_t i = 0; i < our_size; ++i) {
×
2497
            std::cerr << TERM_RED << "\nLOCAL (RECIPROCAL) CHANGESET BEFORE MERGE:\n" << TERM_RESET;
×
2498
            our_changesets[i]->print(std::cerr);
×
2499
        }
2500

×
2501
        for (size_t i = 0; i < their_size; ++i) {
×
2502
            std::cerr << TERM_RED << "\nINCOMING CHANGESET BEFORE MERGE:\n" << TERM_RESET;
×
2503
            their_changesets[i].print(std::cerr);
×
2504
        }
2505

×
2506
        std::cerr << TERM_MAGENTA << "\nINCOMING CHANGESET INDEX:\n" << TERM_RESET;
×
2507
        their_index.print(std::cerr);
×
2508
        std::cerr << '\n';
×
2509
        their_index.verify();
2510

×
2511
        std::cerr << TERM_YELLOW << std::setw(80) << std::left << "MERGE TRACE (incoming):"
×
2512
                  << "MERGE TRACE (local):\n"
×
2513
                  << TERM_RESET;
×
2514
    }
2515
#else
2516
    static_cast<void>(local_file_ident);
2517
#endif // REALM_DEBUG LCOV_EXCL_STOP
2518

210,102✔
2519
    for (size_t i = 0; i < our_size; ++i) {
5,136,110✔
2520
        logger.trace(
4,926,008✔
2521
            "Transforming local changeset [%1/%2] through %3 incoming changeset(s) with %4 conflict group(s)", i + 1,
4,926,008✔
2522
            our_size, their_size, their_index.get_num_conflict_groups());
4,926,008✔
2523
        Changeset* our_changeset = our_changesets[i];
10,048,174✔
2524

9,842,104✔
2525
        transformer.m_major_side.set_next_changeset(our_changeset);
9,842,104✔
2526
        // MinorSide uses the index to find the Changeset.
9,842,104✔
2527
        transformer.m_minor_side.m_changeset_index = &their_index;
9,842,104✔
2528
        transformer.transform(); // Throws
4,926,008✔
2529
    }
9,842,104✔
2530

210,102✔
2531
    logger.debug("Finished transforming %1 local changesets through %2 incoming changesets (%3 vs %4 "
5,126,198✔
2532
                 "instructions, in %5 conflict groups)",
5,126,198✔
2533
                 our_size, their_size, our_num_instructions, their_num_instructions,
5,126,198✔
2534
                 their_index.get_num_conflict_groups());
210,102✔
2535

416,172✔
2536
#if REALM_DEBUG // LCOV_EXCL_START
416,172✔
2537
    // Check that the index is still valid after transformation.
416,172✔
2538
    their_index.verify();
416,172✔
2539
#endif // REALM_DEBUG LCOV_EXCL_STOP
210,102✔
2540

210,102✔
2541
#if REALM_DEBUG // LCOV_EXCL_START
210,102✔
2542
    if (trace) {
416,172✔
2543
        for (size_t i = 0; i < our_size; ++i) {
206,070✔
2544
            std::cerr << TERM_CYAN << "\nRECIPROCAL CHANGESET AFTER MERGE:\n" << TERM_RESET;
2545
            our_changesets[i]->print(std::cerr);
2546
            std::cerr << '\n';
206,070✔
2547
        }
×
2548
        for (size_t i = 0; i < their_size; ++i) {
×
2549
            std::cerr << TERM_CYAN << "INCOMING CHANGESET AFTER MERGE:\n" << TERM_RESET;
×
2550
            their_changesets[i].print(std::cerr);
×
2551
            std::cerr << '\n';
×
2552
        }
×
2553
    }
×
2554
#endif // LCOV_EXCL_STOP REALM_DEBUG
210,102✔
2555
}
210,102✔
2556

2557
size_t TransformerImpl::transform_remote_changesets(TransformHistory& history, file_ident_type local_file_ident,
2558
                                                    version_type current_local_version,
206,070✔
2559
                                                    util::Span<Changeset> parsed_changesets,
206,070✔
2560
                                                    util::UniqueFunction<bool(const Changeset*)> changeset_applier,
2561
                                                    util::Logger& logger)
2562
{
228,324✔
2563
    REALM_ASSERT(local_file_ident != 0);
228,324✔
2564

228,324✔
2565
    std::vector<Changeset*> our_changesets;
228,324✔
2566

453,146✔
2567
    // p points to the beginning of a range of changesets that share the same
453,146✔
2568
    // "base", i.e. are based on the same local version.
228,324✔
2569
    auto p = parsed_changesets.begin();
453,146✔
2570
    auto parsed_changesets_end = parsed_changesets.end();
228,324✔
2571

228,324✔
2572
    try {
228,324✔
2573
        while (p != parsed_changesets_end) {
684,552✔
2574
            // Find the range of incoming changesets that share the same
456,228✔
2575
            // last_integrated_local_version, which means we can merge them in one go.
231,406✔
2576
            auto same_base_range_end = std::find_if(p + 1, parsed_changesets_end, [&](auto& changeset) {
456,228✔
2577
                return p->last_integrated_remote_version != changeset.last_integrated_remote_version;
468,324✔
2578
            });
16,624✔
2579

231,406✔
2580
            version_type begin_version = p->last_integrated_remote_version;
251,314✔
2581
            version_type end_version = current_local_version;
251,314✔
2582
            for (;;) {
5,177,332✔
2583
                HistoryEntry history_entry;
5,157,424✔
2584
                version_type version = history.find_history_entry(begin_version, end_version, history_entry);
5,384,302✔
2585
                if (version == 0)
5,384,302✔
2586
                    break; // No more local changesets
5,374,340✔
2587

10,068,936✔
2588
                Changeset& our_changeset = get_reciprocal_transform(history, local_file_ident, version,
10,068,936✔
2589
                                                                    history_entry); // Throws
10,068,936✔
2590
                our_changesets.push_back(&our_changeset);
5,152,888✔
2591

4,926,010✔
2592
                begin_version = version;
9,842,058✔
2593
            }
9,842,058✔
2594

5,147,454✔
2595
            bool must_apply_all = false;
231,406✔
2596

5,147,454✔
2597
            if (!our_changesets.empty()) {
5,147,454✔
2598
                merge_changesets(local_file_ident, &*p, same_base_range_end - p, our_changesets.data(),
210,104✔
2599
                                 our_changesets.size(), logger); // Throws
436,982✔
2600
                // We need to apply all transformed changesets if at least one reciprocal changeset was modified
210,104✔
2601
                // during OT.
436,982✔
2602
                must_apply_all = std::any_of(our_changesets.begin(), our_changesets.end(), [](const Changeset* c) {
4,700,400✔
2603
                    return c->is_dirty();
4,700,400✔
2604
                });
4,494,328✔
2605
            }
210,104✔
2606

4,740,766✔
2607
            auto continue_applying = true;
4,740,766✔
2608
            for (; p != same_base_range_end && continue_applying; ++p) {
4,985,696✔
2609
                // It is safe to stop applying the changesets if:
451,002✔
2610
                //      1. There are no reciprocal changesets
244,930✔
2611
                //      2. No reciprocal changeset was modified
471,808✔
2612
                continue_applying = changeset_applier(p) || must_apply_all;
716,506✔
2613
            }
244,930✔
2614
            if (!continue_applying) {
231,406✔
2615
                break;
2616
            }
244,698!
2617

476,104✔
2618
            our_changesets.clear(); // deliberately not releasing memory
458,284✔
2619
        }
231,406✔
2620
    }
228,324✔
2621
    catch (...) {
228,324✔
2622
        // If an exception was thrown while merging, the transform cache will
226,902✔
2623
        // be polluted. This is a problem since the same cache object is reused
226,902✔
2624
        // by multiple invocations to transform_remote_changesets(), so we must
224,846✔
2625
        // clear the cache before rethrowing.
50✔
2626
        //
24✔
2627
        // Note that some valid changesets can still cause exceptions to be
24✔
2628
        // thrown by the merge algorithm, namely incompatible schema changes.
24✔
2629
        m_reciprocal_transform_cache.clear();
24✔
2630
        throw;
24✔
2631
    }
24✔
2632

228,300✔
2633
    // NOTE: Any exception thrown during flushing *MUST* lead to rollback of
228,326✔
2634
    // the current transaction.
228,326✔
2635
    flush_reciprocal_transform_cache(history); // Throws
228,326✔
2636

228,300✔
2637
    return p - parsed_changesets.begin();
228,300✔
2638
}
228,300✔
2639

224,796✔
2640

2641
Changeset& TransformerImpl::get_reciprocal_transform(TransformHistory& history, file_ident_type local_file_ident,
224,796✔
2642
                                                     version_type version, const HistoryEntry& history_entry)
224,796✔
2643
{
4,926,042✔
2644
    auto& changeset = m_reciprocal_transform_cache[version]; // Throws
4,926,042✔
2645
    if (changeset.empty()) {
4,926,042✔
2646
        bool is_compressed = false;
4,909,638✔
2647
        ChunkedBinaryData data = history.get_reciprocal_transform(version, is_compressed);
9,825,684✔
2648
        ChunkedBinaryInputStream in{data};
9,825,684✔
2649
        if (is_compressed) {
9,825,684✔
2650
            size_t total_size;
4,927,032✔
2651
            auto decompressed = util::compression::decompress_nonportable_input_stream(in, total_size);
4,927,032✔
2652
            REALM_ASSERT(decompressed);
4,927,032✔
2653
            sync::parse_changeset(*decompressed, changeset); // Throws
4,927,032✔
2654
        }
47,196✔
2655
        else {
4,910,854✔
2656
            sync::parse_changeset(in, changeset); // Throws
4,910,854✔
2657
        }
4,910,854✔
2658

4,933,844✔
2659
        changeset.version = version;
9,789,474✔
2660
        changeset.last_integrated_remote_version = history_entry.remote_version;
9,789,474✔
2661
        changeset.origin_timestamp = history_entry.origin_timestamp;
9,789,474✔
2662
        file_ident_type origin_file_ident = history_entry.origin_file_ident;
4,909,638✔
2663
        if (origin_file_ident == 0)
9,813,680✔
2664
            origin_file_ident = local_file_ident;
7,720,302✔
2665
        changeset.origin_file_ident = origin_file_ident;
9,813,680✔
2666
    }
9,813,680✔
2667
    return changeset;
9,830,084✔
2668
}
7,740,100✔
2669

4,904,042✔
2670

4,904,042✔
2671
void TransformerImpl::flush_reciprocal_transform_cache(TransformHistory& history)
4,916,046✔
2672
{
5,144,346✔
2673
    auto changesets = std::move(m_reciprocal_transform_cache);
228,300✔
2674
    m_reciprocal_transform_cache.clear();
228,300✔
2675
    ChangesetEncoder::Buffer output_buffer;
228,300✔
2676
    for (const auto& [version, changeset] : changesets) {
5,133,922✔
2677
        if (changeset.is_dirty()) {
5,133,922✔
2678
            encode_changeset(changeset, output_buffer); // Throws
271,690✔
2679
            BinaryData data{output_buffer.data(), output_buffer.size()};
271,690✔
2680
            history.set_reciprocal_transform(version, data); // Throws
4,950,608✔
2681
            output_buffer.clear();
4,950,608✔
2682
        }
90,614✔
2683
    }
4,952,846✔
2684
}
272,020✔
2685

43,720✔
2686
} // namespace _impl
43,720✔
2687

4,903,714✔
2688
namespace sync {
224,796✔
2689
std::unique_ptr<Transformer> make_transformer()
2690
{
8,998✔
2691
    return std::make_unique<_impl::TransformerImpl>(); // Throws
8,998✔
2692
}
8,998✔
2693

2694

9,218✔
2695
void parse_remote_changeset(const Transformer::RemoteChangeset& remote_changeset, Changeset& parsed_changeset)
9,218✔
2696
{
254,158✔
2697
    // origin_file_ident = 0 is currently used to indicate an entry of local
244,940✔
2698
    // origin.
244,940✔
2699
    REALM_ASSERT(remote_changeset.origin_file_ident != 0);
244,940✔
2700
    REALM_ASSERT(remote_changeset.remote_version != 0);
489,718✔
2701

244,940✔
2702
    ChunkedBinaryInputStream remote_in{remote_changeset.data};
244,940✔
2703
    parse_changeset(remote_in, parsed_changeset); // Throws
489,718✔
2704

489,718✔
2705
    parsed_changeset.version = remote_changeset.remote_version;
244,940✔
2706
    parsed_changeset.last_integrated_remote_version = remote_changeset.last_integrated_local_version;
489,718✔
2707
    parsed_changeset.origin_timestamp = remote_changeset.origin_timestamp;
489,718✔
2708
    parsed_changeset.origin_file_ident = remote_changeset.origin_file_ident;
244,940✔
2709
    parsed_changeset.original_changeset_size = remote_changeset.original_changeset_size;
489,718✔
2710
}
489,718✔
2711

244,778✔
2712
} // namespace sync
244,778✔
2713
} // namespace realm
244,778✔
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

© 2025 Coveralls, Inc