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

realm / realm-core / 1781

27 Oct 2023 08:04AM UTC coverage: 91.571% (-0.006%) from 91.577%
1781

push

Evergreen

jedelbo
Make undefined sanitizer work on Linux

94324 of 173642 branches covered (0.0%)

18 of 22 new or added lines in 1 file covered. (81.82%)

91 existing lines in 16 files now uncovered.

230614 of 251843 relevant lines covered (91.57%)

7124896.29 hits per line

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

61.71
/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,949,422✔
70
    }
11,949,422✔
71

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

75
    bool operator<(const Discriminant& other) const
76
    {
33,972✔
77
        return timestamp == other.timestamp ? (client_file_ident < other.client_file_ident)
17,942✔
78
                                            : timestamp < other.timestamp;
33,578✔
79
    }
33,972✔
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,324✔
104
    }
832,324✔
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
    {
36,472✔
124
        // Rely on the parser having checked the consistency of the interned strings
18,244✔
125
        return m_changeset->get_string(intern_string);
36,472✔
126
    }
36,472✔
127

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

133
    const Discriminant& timestamp() const
134
    {
67,940✔
135
        return m_discriminant;
67,940✔
136
    }
67,940✔
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);
×
163
        instr.path.m_path.clear();
×
164
        instr.path.m_path.reserve(other.path.size());
×
165
        for (auto& element : other.path.m_path) {
×
166
            auto push = util::overload{
×
167
                [&](uint32_t index) {
×
168
                    instr.path.m_path.push_back(index);
×
169
                },
×
170
                [&](InternString str) {
×
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,116,712✔
181
        was_discarded = false;
11,116,712✔
182
        was_replaced = false;
11,116,712✔
183
        m_path_len = instr.path_length();
11,116,712✔
184
    }
11,116,712✔
185
};
186

187
struct TransformerImpl::MajorSide : TransformerImpl::Side {
188
    MajorSide(Transformer& transformer)
189
        : Side(transformer)
190
    {
416,164✔
191
    }
416,164✔
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,614,160✔
201
        REALM_ASSERT(position >= m_changeset->begin());
8,614,160✔
202
        REALM_ASSERT(position != m_changeset->end());
8,614,160✔
203
        m_position = position;
8,614,160✔
204
        skip_tombstones();
8,614,160✔
205
        REALM_ASSERT(position != m_changeset->end());
8,614,160✔
206

4,289,486✔
207
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
8,614,160✔
208

4,289,486✔
209
        Side::init_with_instruction(get());
8,614,160✔
210
    }
8,614,160✔
211

212
    void skip_tombstones() noexcept final
213
    {
37,051,350✔
214
        while (m_position != m_changeset->end() && !*m_position) {
37,052,794✔
215
            ++m_position;
1,444✔
216
        }
1,444✔
217
    }
37,051,350✔
218

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

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

232
    size_t get_object_ids_in_current_instruction(_impl::ChangesetIndex::GlobalID* ids, size_t max_ids)
233
    {
7,717,132✔
234
        return _impl::get_object_ids_in_instruction(*m_changeset, get(), ids, max_ids);
7,717,132✔
235
    }
7,717,132✔
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,166✔
246
    }
416,166✔
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,614,338✔
261
        return Position{m_conflict_ranges};
8,614,338✔
262
    }
8,614,338✔
263

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

269
    void update_changeset_pointer() noexcept
270
    {
15,744,008✔
271
        if (REALM_LIKELY(m_position != end())) {
15,744,008✔
272
            m_changeset = m_position.m_outer->first;
2,690,360✔
273
        }
2,690,360✔
274
        else {
13,053,648✔
275
            m_changeset = nullptr;
13,053,648✔
276
        }
13,053,648✔
277
    }
15,744,008✔
278

279
    void skip_tombstones() noexcept final
280
    {
15,942,142✔
281
        if (m_position != end() && *m_position)
15,942,142✔
282
            return;
5,156,260✔
283
        skip_tombstones_slow();
10,785,882✔
284
    }
10,785,882✔
285

286
    REALM_NOINLINE void skip_tombstones_slow() noexcept
287
    {
10,786,412✔
288
        while (m_position != end() && !*m_position) {
11,410,080✔
289
            ++m_position;
623,668✔
290
        }
623,668✔
291
        update_changeset_pointer();
10,786,412✔
292
    }
10,786,412✔
293

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

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

309
    void init_with_instruction(Position position)
310
    {
2,503,214✔
311
        // REALM_ASSERT(position >= Position(m_conflict_ranges));
1,300,896✔
312
        REALM_ASSERT(position != end());
2,503,214✔
313
        m_position = position;
2,503,214✔
314
        update_changeset_pointer();
2,503,214✔
315
        skip_tombstones();
2,503,214✔
316
        REALM_ASSERT(position != end());
2,503,214✔
317

1,300,896✔
318
        m_discriminant = Discriminant{m_changeset->origin_timestamp, m_changeset->origin_file_ident};
2,503,214✔
319

1,300,896✔
320
        Side::init_with_instruction(get());
2,503,214✔
321
    }
2,503,214✔
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,166✔
617
    }
416,166✔
618

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

4,948,638✔
624
        while (m_major_side.m_position != m_major_side.m_changeset->end()) {
18,526,308✔
625
            m_major_side.init_with_instruction(m_major_side.m_position);
8,614,176✔
626

4,289,494✔
627
            set_conflict_ranges();
8,614,176✔
628
            m_minor_end = m_minor_side.end();
8,614,176✔
629
            m_minor_side.m_position = m_minor_side.begin();
8,614,176✔
630
            transform_major();
8,614,176✔
631

4,289,494✔
632
            if (!m_major_side.was_discarded)
8,614,176✔
633
                // Discarding the instruction moves to the next one.
4,255,292✔
634
                m_major_side.next_instruction();
8,547,798✔
635
            m_major_side.skip_tombstones();
8,614,176✔
636
        }
8,614,176✔
637
    }
9,912,132✔
638

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

4,289,464✔
643
        if (_impl::is_schema_change(instr)) {
8,614,010✔
644
            ///
455,428✔
645
            /// CONFLICT GROUP: Everything touching that class
455,428✔
646
            ///
455,428✔
647
            auto ranges = index.get_everything();
897,132✔
648
            if (!ranges->empty()) {
897,132✔
649
#if REALM_DEBUG // LCOV_EXCL_START
336,512✔
650
                if (m_trace) {
663,076✔
651
                    std::cerr << TERM_RED << "Conflict group: Everything (due to schema change)\n" << TERM_RESET;
×
652
                }
×
653
#endif // REALM_DEBUG LCOV_EXCL_STOP
663,076✔
654
            }
663,076✔
655
            return ranges;
897,132✔
656
        }
897,132✔
657
        else {
7,716,878✔
658
            ///
3,834,036✔
659
            /// CONFLICT GROUP: Everything touching the involved objects,
3,834,036✔
660
            /// including schema changes.
3,834,036✔
661
            ///
3,834,036✔
662
            _impl::ChangesetIndex::GlobalID major_ids[2];
7,716,878✔
663
            size_t num_major_ids = m_major_side.get_object_ids_in_current_instruction(major_ids, 2);
7,716,878✔
664
            REALM_ASSERT(num_major_ids <= 2);
7,716,878✔
665
            REALM_ASSERT(num_major_ids >= 1);
7,716,878✔
666
#if REALM_DEBUG // LCOV_EXCL_START
3,834,036✔
667
            if (m_trace) {
7,716,878✔
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,716,878✔
680
            auto ranges = index.get_modifications_for_object(major_ids[0]);
7,716,878✔
681
            if (num_major_ids == 2) {
7,716,878✔
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,716,878✔
687
        }
7,716,878✔
688
    }
8,614,010✔
689

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

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

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

711
    void discard_minor()
712
    {
65,866✔
713
        m_minor_side.was_discarded = true;
65,866✔
714
        m_minor_side.m_position = m_minor_side.m_changeset_index->erase_instruction(m_minor_side.m_position);
65,866✔
715
        m_minor_side.m_changeset->set_dirty(true);
65,866✔
716
        m_minor_side.update_changeset_pointer();
65,866✔
717
    }
65,866✔
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,614,274✔
821
        m_minor_side.skip_tombstones();
8,614,274✔
822

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

4,289,594✔
828
        while (m_minor_side.m_position != m_minor_end) {
11,051,010✔
829
            m_minor_side.init_with_instruction(m_minor_side.m_position);
2,503,186✔
830

1,300,860✔
831
#if defined(REALM_DEBUG) // LCOV_EXCL_START Debug tracing
2,503,186✔
832
            if (m_trace) {
2,503,186✔
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,503,186✔
841
#endif // LCOV_EXCL_STOP REALM_DEBUG
2,503,186✔
842
                merge_instructions(m_major_side, m_minor_side);
2,503,186✔
843
#if defined(REALM_DEBUG) // LCOV_EXCL_START
2,503,186✔
844
            }
2,503,186✔
845
#endif // LCOV_EXCL_STOP REALM_DEBUG
2,503,186✔
846

1,300,860✔
847
            if (m_major_side.was_discarded)
2,503,186✔
848
                break;
66,450✔
849
            if (!m_minor_side.was_discarded)
2,436,736✔
850
                // Discarding an instruction moves to the next one.
1,241,546✔
851
                m_minor_side.next_instruction();
2,388,984✔
852
            m_minor_side.skip_tombstones();
2,436,736✔
853
        }
2,436,736✔
854
    }
8,614,274✔
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,912,270✔
863
    m_transformer.set_next_major_changeset(changeset);
9,912,270✔
864
}
9,912,270✔
865
void TransformerImpl::MajorSide::discard()
866
{
66,448✔
867
    m_transformer.discard_major();
66,448✔
868
}
66,448✔
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,866✔
880
    m_transformer.discard_minor();
65,866✔
881
}
65,866✔
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
{
44✔
897
    throw sync::TransformError{std::move(msg)};
44✔
898
}
44✔
899

900
template <class... Params>
901
REALM_NORETURN void bad_merge(const char* msg, Params&&... params)
902
{
44✔
903
    throw_bad_merge(util::format(msg, std::forward<Params>(params)...));
44✔
904
}
44✔
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,175,900✔
925
    }
1,175,900✔
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,248,550✔
933
        // FIXME: Optimize string comparison by building a map of InternString values up front.
658,528✔
934
        return m_left_side.m_changeset->get_string(left) == m_right_side.m_changeset->get_string(right);
1,248,550✔
935
    }
1,248,550✔
936

937
    bool same_key(const Instruction::PrimaryKey& left, const Instruction::PrimaryKey& right) const noexcept
938
    {
296,846✔
939
        // FIXME: Once we can compare string by InternString map lookups,
156,412✔
940
        // compare the string components of the keys using that.
156,412✔
941
        PrimaryKey left_key = m_left_side.m_changeset->get_key(left);
296,846✔
942
        PrimaryKey right_key = m_right_side.m_changeset->get_key(right);
296,846✔
943
        return left_key == right_key;
296,846✔
944
    }
296,846✔
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;
×
958
            case Type::Dictionary:
✔
959
                return true;
×
960
            case Type::ObjectValue:
✔
961
                return true;
×
962
            case Type::GlobalKey:
✔
963
                return left.data.key == right.data.key;
×
964
            case Type::Int:
24✔
965
                return left.data.integer == right.data.integer;
24✔
966
            case Type::Bool:
✔
967
                return left.data.boolean == right.data.boolean;
×
968
            case Type::String:
16✔
969
                return m_left_side.get_string(left.data.str) == m_right_side.get_string(right.data.str);
16✔
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:
✔
973
                return left.data.timestamp == right.data.timestamp;
×
974
            case Type::Float:
16✔
975
                return left.data.fnum == right.data.fnum;
16✔
976
            case Type::Double:
✔
977
                return left.data.dnum == right.data.dnum;
×
978
            case Type::Decimal:
✔
979
                return left.data.decimal == right.data.decimal;
×
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
    {
1,720✔
1000
        const auto& pred = util::overload{
1,720✔
1001
            [&](uint32_t lhs, uint32_t rhs) {
1,636✔
1002
                return lhs == rhs;
1,552✔
1003
            },
1,552✔
1004
            [&](InternString lhs, InternString rhs) {
970✔
1005
                return same_string(lhs, rhs);
168✔
1006
            },
168✔
1007
            [&](const auto&, const auto&) {
886✔
1008
                // FIXME: Paths contain incompatible element types. Should we raise an
1009
                // error here?
1010
                return false;
×
1011
            },
×
1012
        };
1,720✔
1013
        return mpark::visit(pred, left, right);
1,720✔
1014
    }
1,720✔
1015

1016
    bool same_path(const Instruction::Path& left, const Instruction::Path& right) const noexcept
1017
    {
11,226✔
1018
        if (left.size() == right.size()) {
11,226✔
1019
            for (size_t i = 0; i < left.size(); ++i) {
11,488✔
1020
                if (!same_path_element(left[i], right[i])) {
1,712✔
1021
                    return false;
1,380✔
1022
                }
1,380✔
1023
            }
1,712✔
1024
            return true;
10,482✔
1025
        }
70✔
1026
        return false;
70✔
1027
    }
70✔
1028

1029
    bool same_table(const Instruction::TableInstruction& left,
1030
                    const Instruction::TableInstruction& right) const noexcept
1031
    {
1,167,454✔
1032
        return same_string(left.table, right.table);
1,167,454✔
1033
    }
1,167,454✔
1034

1035
    bool same_object(const Instruction::ObjectInstruction& left,
1036
                     const Instruction::ObjectInstruction& right) const noexcept
1037
    {
957,832✔
1038
        return same_table(left, right) && same_key(left.object, right.object);
957,832✔
1039
    }
957,832✔
1040

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

1057
    bool same_field(const Instruction::PathInstruction& left,
1058
                    const Instruction::PathInstruction& right) const noexcept
1059
    {
206,292✔
1060
        return same_object(left, right) && same_string(left.field, right.field);
206,292✔
1061
    }
206,292✔
1062

1063
    bool same_path(const Instruction::PathInstruction& left, const Instruction::PathInstruction& right) const noexcept
1064
    {
25,864✔
1065
        return same_field(left, right) && same_path(left.path, right.path);
25,864✔
1066
    }
25,864✔
1067

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

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

1088
    bool same_container(const Instruction::PathInstruction& left,
1089
                        const Instruction::PathInstruction& right) const noexcept
1090
    {
147,238✔
1091
        return same_field(left, right) && same_container(left.path, right.path);
147,238✔
1092
    }
147,238✔
1093

1094
    // NOTE: `is_prefix_of()` should only return true if the left is a strictly
1095
    // shorter path than the right, and the entire left path is the initial
1096
    // sequence of the right.
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
    {
153,320✔
1105
        return same_table(left, right);
153,320✔
1106
    }
153,320✔
1107

1108
    bool is_prefix_of(const Instruction::AddColumn&, const Instruction::TableInstruction&) const noexcept
1109
    {
×
1110
        // Right side is a schema instruction.
×
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
    {
229,100✔
1140
        return same_object(left, right);
229,100✔
1141
    }
229,100✔
1142

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

1150
    bool is_prefix_of(const Instruction::PathInstruction& left,
1151
                      const Instruction::PathInstruction& right) const noexcept
1152
    {
33,166✔
1153
        if (left.path.size() < right.path.size() && same_field(left, right)) {
33,166✔
1154
            for (size_t i = 0; i < left.path.size(); ++i) {
248✔
1155
                if (!same_path_element(left.path[i], right.path[i])) {
8✔
1156
                    return false;
8✔
1157
                }
8✔
1158
            }
8✔
1159
            return true;
244✔
1160
        }
32,918✔
1161
        return false;
32,918✔
1162
    }
32,918✔
1163

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

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
    {
24✔
1224
        REALM_ASSERT(left.path.size() != 0);
24✔
1225
        REALM_ASSERT(left.path.size() < right.path.size());
24✔
1226
        REALM_ASSERT(mpark::holds_alternative<uint32_t>(left.path.back()));
24✔
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");
×
1230
        }
×
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
1236
    {
×
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
    {
760,234✔
1278
    }
760,234✔
1279
    MergeBase(MergeBase&&) = delete;
1280
};
1281

1282
#define DEFINE_MERGE(A, B)                                                                                           \
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
            {                                                                                                        \
760,232✔
1298
            }                                                                                                        \
760,232✔
1299
            void do_merge();                                                                                         \
1300
        };                                                                                                           \
1301
        template <class LeftSide, class RightSide>                                                                   \
1302
        static inline void merge(A& left, B& right, LeftSide& left_side, RightSide& right_side)                      \
1303
        {                                                                                                            \
760,234✔
1304
            DoMerge<LeftSide, RightSide> do_merge{left, right, left_side, right_side};                               \
760,234✔
1305
            do_merge.do_merge();                                                                                     \
760,234✔
1306
        }                                                                                                            \
760,234✔
1307
    };                                                                                                               \
1308
    template <class LeftSide, class RightSide>                                                                       \
1309
    void Merge<A, B>::DoMerge<LeftSide, RightSide>::do_merge()
1310

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 */                                                                                           \
1,687,096✔
1321
        }                                                                                                            \
1,687,096✔
1322
    }
1323

1324

1325
#define DEFINE_NESTED_MERGE(A)                                                                                       \
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
            {                                                                                                        \
415,666✔
1341
            }                                                                                                        \
415,666✔
1342
            void do_merge();                                                                                         \
1343
        };                                                                                                           \
1344
        template <class B, class OuterSide, class InnerSide>                                                         \
1345
        static inline void merge(A& outer, B& inner, OuterSide& outer_side, InnerSide& inner_side)                   \
1346
        {                                                                                                            \
415,666✔
1347
            DoMerge<B, OuterSide, InnerSide> do_merge{outer, inner, outer_side, inner_side};                         \
415,666✔
1348
            do_merge.do_merge();                                                                                     \
415,666✔
1349
        }                                                                                                            \
415,666✔
1350
    };                                                                                                               \
1351
    template <class B, class OuterSide, class InnerSide>                                                             \
1352
    void MergeNested<A>::DoMerge<B, OuterSide, InnerSide>::do_merge()
1353

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 */                                                                                           \
612,232✔
1360
        }                                                                                                            \
612,232✔
1361
    }
1362

1363
// Implementation that reverses order.
1364
template <class A, class B>
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
    {
864,994✔
1371
        Merge<B, A>::merge(right, left, right_side, left_side);
864,994✔
1372
    }
864,994✔
1373
};
1374

1375
///
1376
///  GET READY!
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
{
14,670✔
1401
    if (same_table(left, right)) {
14,670✔
1402
        StringData left_name = left_side.get_string(left.table);
7,628✔
1403
        if (auto left_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&left.type)) {
7,628✔
1404
            if (auto right_spec = mpark::get_if<Instruction::AddTable::TopLevelTable>(&right.type)) {
7,500✔
1405
                StringData left_pk_name = left_side.get_string(left_spec->pk_field);
7,500✔
1406
                StringData right_pk_name = right_side.get_string(right_spec->pk_field);
7,500✔
1407
                if (left_pk_name != right_pk_name) {
7,500✔
1408
                    bad_merge(
6✔
1409
                        "Schema mismatch: '%1' has primary key '%2' on one side, but primary key '%3' on the other.",
6✔
1410
                        left_name, left_pk_name, right_pk_name);
6✔
1411
                }
6✔
1412

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

3,768✔
1420
                if (left_spec->pk_nullable != right_spec->pk_nullable) {
7,500✔
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);
8✔
1424
                }
8✔
1425

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

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

1448
DEFINE_MERGE(Instruction::EraseTable, Instruction::AddTable)
1449
{
4,156✔
1450
    if (same_table(left, right)) {
4,156✔
1451
        right_side.discard();
×
1452
    }
×
1453
}
4,156✔
1454

1455
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::AddTable);
1456
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::AddTable);
1457
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::AddTable);
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
{
153,320✔
1472
    if (is_prefix_of(outer, inner)) {
153,320!
1473
        inner_side.discard();
34,648✔
1474
    }
34,648✔
1475
}
153,320✔
1476

1477
DEFINE_MERGE(Instruction::EraseTable, Instruction::EraseTable)
1478
{
1,292✔
1479
    if (same_table(left, right)) {
1,292✔
1480
        left_side.discard();
308✔
1481
        right_side.discard();
308✔
1482
    }
308✔
1483
}
1,292✔
1484

1485
// Handled by nesting rule.
1486
DEFINE_MERGE_NOOP(Instruction::CreateObject, Instruction::EraseTable);
1487
DEFINE_MERGE_NOOP(Instruction::EraseObject, Instruction::EraseTable);
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
{
8,392✔
1493
    // AddColumn on an erased table handled by nesting.
4,288✔
1494

4,288✔
1495
    if (left.type == Instruction::Payload::Type::Link && same_string(left.link_target_table, right.table)) {
8,392!
1496
        // Erase of a table where the left side adds a link column targeting it.
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);
×
1500
        right_side.prepend(erase_column);
×
1501
        left_side.discard();
×
1502
    }
×
1503
}
8,392✔
1504

1505
// Handled by nested rule.
1506
DEFINE_MERGE_NOOP(Instruction::EraseColumn, Instruction::EraseTable);
1507
DEFINE_MERGE_NOOP(Instruction::ArrayInsert, Instruction::EraseTable);
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
{
385,504✔
1525
    if (same_object(left, right)) {
385,504✔
1526
        // CONFLICT: Create and Erase of the same object.
8,010✔
1527
        //
8,010✔
1528
        // RESOLUTION: Erase always wins.
8,010✔
1529
        right_side.discard();
16,032✔
1530
    }
16,032✔
1531
}
385,504✔
1532

1533
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::CreateObject);
1534
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::CreateObject);
1535
DEFINE_MERGE_NOOP(Instruction::AddColumn, Instruction::CreateObject);
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
{
229,100✔
1549
    if (is_prefix_of(outer, inner)) {
229,100!
1550
        // Erase always wins.
10,954✔
1551
        inner_side.discard();
21,028✔
1552
    }
21,028✔
1553
}
229,100✔
1554

1555
DEFINE_MERGE(Instruction::EraseObject, Instruction::EraseObject)
1556
{
136,936✔
1557
    if (same_object(left, right)) {
136,936✔
1558
        // We keep the most recent erase. This prevents the situation where a
6,912✔
1559
        // high number of EraseObject instructions in the past trumps a
6,912✔
1560
        // Erase-Create pair in the future.
6,912✔
1561
        if (right_side.timestamp() < left_side.timestamp()) {
14,372✔
1562
            right_side.discard();
7,186✔
1563
        }
7,186✔
1564
        else {
7,186✔
1565
            left_side.discard();
7,186✔
1566
        }
7,186✔
1567
    }
14,372✔
1568
}
136,936✔
1569

1570
// Handled by nested merge.
1571
DEFINE_MERGE_NOOP(Instruction::Update, Instruction::EraseObject);
1572
DEFINE_MERGE_NOOP(Instruction::AddInteger, Instruction::EraseObject);
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
{
32,596✔
1587
    using Type = Instruction::Payload::Type;
32,596✔
1588

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

18,476✔
1595
    // Setting a value higher up in the hierarchy overwrites any modification to
18,476✔
1596
    // the inner value, regardless of when this happened.
18,476✔
1597
    if (is_prefix_of(outer, inner)) {
32,532!
1598
        inner_side.discard();
80✔
1599
    }
80✔
1600
}
32,532✔
1601

1602
DEFINE_MERGE(Instruction::Update, Instruction::Update)
1603
{
23,656✔
1604
    // The two instructions are at the same level of nesting.
13,534✔
1605

13,534✔
1606
    using Type = Instruction::Payload::Type;
23,656✔
1607

13,534✔
1608
    if (same_path(left, right)) {
23,656✔
1609
        bool left_is_default = false;
9,142✔
1610
        bool right_is_default = false;
9,142✔
1611
        if (!(left.is_array_update() == right.is_array_update())) {
9,142✔
1612
            bad_merge(left_side, left, "Merge error: left.is_array_update() == right.is_array_update()");
×
1613
        }
×
1614

5,304✔
1615
        if (!left.is_array_update()) {
9,142✔
1616
            if (right.is_array_update()) {
8,916✔
1617
                bad_merge(right_side, right, "Merge error: !right.is_array_update()");
×
1618
            }
×
1619
            left_is_default = left.is_default;
8,916✔
1620
            right_is_default = right.is_default;
8,916✔
1621
        }
8,916✔
1622
        else if (!(left.prior_size == right.prior_size)) {
226✔
1623
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
1624
        }
×
1625

5,304✔
1626
        if (left.value.type != right.value.type) {
9,142✔
1627
            // Embedded object / dictionary creation should always lose to an
120✔
1628
            // Update(value), because these structures are nested, and we need to
120✔
1629
            // discard any update inside the structure.
120✔
1630
            if (left.value.type == Type::Dictionary || left.value.type == Type::ObjectValue) {
248✔
1631
                left_side.discard();
24✔
1632
                return;
24✔
1633
            }
24✔
1634
            else if (right.value.type == Type::Dictionary || right.value.type == Type::ObjectValue) {
224✔
1635
                right_side.discard();
24✔
1636
                return;
24✔
1637
            }
24✔
1638
        }
9,094✔
1639

5,280✔
1640
        // CONFLICT: Two updates of the same element.
5,280✔
1641
        //
5,280✔
1642
        // RESOLUTION: Suppress the effect of the UPDATE operation with the lower
5,280✔
1643
        // timestamp. Note that the timestamps can never be equal. This is
5,280✔
1644
        // achieved on both sides by discarding the received UPDATE operation if
5,280✔
1645
        // it has a lower timestamp than the previously applied UPDATE operation.
5,280✔
1646
        if (left_is_default == right_is_default) {
9,094✔
1647
            if (left_side.timestamp() < right_side.timestamp()) {
8,928✔
1648
                left_side.discard(); // --->
4,704✔
1649
            }
4,704✔
1650
            else {
4,224✔
1651
                right_side.discard(); // <---
4,224✔
1652
            }
4,224✔
1653
        }
8,928✔
1654
        else {
166✔
1655
            if (left_is_default) {
166✔
1656
                left_side.discard();
88✔
1657
            }
88✔
1658
            else {
78✔
1659
                right_side.discard();
78✔
1660
            }
78✔
1661
        }
166✔
1662
    }
9,094✔
1663
}
23,656✔
1664

1665
DEFINE_MERGE(Instruction::AddInteger, Instruction::Update)
1666
{
1,958✔
1667
    // The two instructions are at the same level of nesting.
1,178✔
1668

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

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

204✔
1680
        bool right_is_default = !right.is_array_update() && right.is_default;
392✔
1681

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

132✔
1691
            // Wrapping add
132✔
1692
            uint64_t ua = uint64_t(right.value.data.integer);
260✔
1693
            uint64_t ub = uint64_t(left.value);
260✔
1694
            right.value.data.integer = int64_t(ua + ub);
260✔
1695
        }
260✔
1696
        else {
72✔
1697
            left_side.discard();
72✔
1698
        }
72✔
1699
    }
392✔
1700
}
1,958✔
1701

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

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

1711
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::Update)
1712
{
51,018✔
1713
    if (same_container(left, right)) {
51,018✔
1714
        REALM_ASSERT(right.is_array_update());
9,492✔
1715
        if (!(left.prior_size == right.prior_size)) {
9,492✔
1716
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
1717
        }
×
1718
        if (!(left.index() <= left.prior_size)) {
9,492✔
1719
            bad_merge(left_side, left, "Merge error: left.index() <= left.prior_size");
×
1720
        }
×
1721
        if (!(right.index() < right.prior_size)) {
9,492✔
1722
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
1723
        }
×
1724
        right.prior_size += 1;
9,492✔
1725
        if (right.index() >= left.index()) {
9,492✔
1726
            right.index() += 1; // --->
3,948✔
1727
        }
3,948✔
1728
    }
9,492✔
1729
}
51,018✔
1730

1731
DEFINE_MERGE(Instruction::ArrayMove, Instruction::Update)
1732
{
24✔
1733
    if (same_container(left, right)) {
24✔
1734
        REALM_ASSERT(right.is_array_update());
×
1735

1736
        if (!(left.index() < left.prior_size)) {
×
1737
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
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
}
24✔
1747

1748
DEFINE_MERGE(Instruction::ArrayErase, Instruction::Update)
1749
{
10,450✔
1750
    if (same_container(left, right)) {
10,450✔
1751
        REALM_ASSERT(right.is_array_update());
2,648✔
1752
        if (!(left.prior_size == right.prior_size)) {
2,648✔
1753
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
1754
        }
×
1755
        if (!(left.index() < left.prior_size)) {
2,648✔
1756
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
1757
        }
×
1758
        if (!(right.index() < right.prior_size)) {
2,648✔
1759
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
1760
        }
×
1761

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

1,380✔
1767
        if (left.index() == right.index()) {
2,648✔
1768
            // CONFLICT: Update of a removed element.
172✔
1769
            //
172✔
1770
            // RESOLUTION: Discard the UPDATE operation received on the right side.
172✔
1771
            right_side.discard();
496✔
1772
        }
496✔
1773
        else if (right.index() > left.index()) {
2,152✔
1774
            right.index() -= 1;
1,044✔
1775
        }
1,044✔
1776
    }
2,648✔
1777
}
10,450✔
1778

1779
// Handled by nested rule
1780
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::Update);
1781
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::Update);
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
{
36,180✔
1805
    if (same_column(left, right)) {
36,180✔
1806
        StringData left_name = left_side.get_string(left.field);
9,964✔
1807
        if (left.type != right.type) {
9,964✔
1808
            bad_merge(
6✔
1809
                "Schema mismatch: Property '%1' in class '%2' is of type %3 on one side and type %4 on the other.",
6✔
1810
                left_name, left_side.get_string(left.table), get_type_name(left.type), get_type_name(right.type));
6✔
1811
        }
6✔
1812

4,940✔
1813
        if (left.nullable != right.nullable) {
9,964✔
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
        }
8✔
1817

4,940✔
1818
        if (left.collection_type != right.collection_type) {
9,964✔
1819
            auto collection_type_name = [](Instruction::AddColumn::CollectionType type) -> const char* {
×
1820
                switch (type) {
×
1821
                    case Instruction::AddColumn::CollectionType::Single:
×
1822
                        return "single value";
×
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,940✔
1840
        if (left.type == Instruction::Payload::Type::Link) {
9,964✔
1841
            StringData left_target = left_side.get_string(left.link_target_table);
1,930✔
1842
            StringData right_target = right_side.get_string(right.link_target_table);
1,930✔
1843
            if (left_target != right_target) {
1,930✔
1844
                bad_merge("Schema mismatch: Link property '%1' in class '%2' points to class '%3' on one side and to "
6✔
1845
                          "'%4' on the other.",
6✔
1846
                          left_name, left_side.get_string(left.table), left_target, right_target);
6✔
1847
            }
6✔
1848
        }
1,930✔
1849

4,940✔
1850
        // Name, type, nullability and link targets match -- discard both
4,940✔
1851
        // sides and proceed.
4,940✔
1852
        left_side.discard();
9,964✔
1853
        right_side.discard();
9,964✔
1854
    }
9,964✔
1855
}
36,180✔
1856

1857
DEFINE_MERGE(Instruction::EraseColumn, Instruction::AddColumn)
1858
{
×
1859
    if (same_column(left, right)) {
×
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
{
16✔
1895
    if (is_container_prefix_of(outer, inner)) {
16!
1896
        auto& index = corresponding_index_in_path(outer, inner);
16✔
1897
        if (index >= outer.index()) {
16!
1898
            index += 1;
8✔
1899
        }
8✔
1900
    }
16✔
1901
}
16✔
1902

1903
DEFINE_MERGE(Instruction::ArrayInsert, Instruction::ArrayInsert)
1904
{
58,540✔
1905
    if (same_container(left, right)) {
58,540✔
1906
        if (!(left.prior_size == right.prior_size)) {
17,324✔
1907
            bad_merge(right_side, right, "Exception: left.prior_size == right.prior_size");
×
1908
        }
×
1909
        left.prior_size++;
17,324✔
1910
        right.prior_size++;
17,324✔
1911

8,806✔
1912
        if (left.index() > right.index()) {
17,324✔
1913
            left.index() += 1; // --->
3,546✔
1914
        }
3,546✔
1915
        else if (left.index() < right.index()) {
13,778✔
1916
            right.index() += 1; // <---
3,550✔
1917
        }
3,550✔
1918
        else { // left index == right index
10,228✔
1919
            // CONFLICT: Two element insertions at the same position.
5,208✔
1920
            //
5,208✔
1921
            // Resolution: Place the inserted elements in order of increasing
5,208✔
1922
            // timestamp. Note that the timestamps can never be equal.
5,208✔
1923
            if (left_side.timestamp() < right_side.timestamp()) {
10,228✔
1924
                right.index() += 1;
5,110✔
1925
            }
5,110✔
1926
            else {
5,118✔
1927
                left.index() += 1;
5,118✔
1928
            }
5,118✔
1929
        }
10,228✔
1930
    }
17,324✔
1931
}
58,540✔
1932

1933
DEFINE_MERGE(Instruction::ArrayMove, Instruction::ArrayInsert)
1934
{
×
1935
    if (same_container(left, right)) {
×
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
{
24,374✔
1970
    if (same_container(left, right)) {
24,374✔
1971
        if (!(left.prior_size == right.prior_size)) {
8,396✔
1972
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
1973
        }
×
1974
        if (!(left.index() < left.prior_size)) {
8,396✔
1975
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
1976
        }
×
1977
        if (!(right.index() <= right.prior_size)) {
8,396✔
1978
            bad_merge(left_side, left, "Merge error: right.index() <= right.prior_size");
×
1979
        }
×
1980

4,150✔
1981
        left.prior_size++;
8,396✔
1982
        right.prior_size--;
8,396✔
1983
        if (right.index() <= left.index()) {
8,396✔
1984
            left.index() += 1; // --->
3,612✔
1985
        }
3,612✔
1986
        else {
4,784✔
1987
            right.index() -= 1; // <---
4,784✔
1988
        }
4,784✔
1989
    }
8,396✔
1990
}
24,374✔
1991

1992
// Handled by nested rules
1993
DEFINE_MERGE_NOOP(Instruction::Clear, Instruction::ArrayInsert);
1994
DEFINE_MERGE_NOOP(Instruction::SetInsert, Instruction::ArrayInsert);
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
{
28✔
2010
    if (same_container(left, right)) {
28✔
2011
        if (!(left.prior_size == right.prior_size)) {
28✔
2012
            bad_merge(left_side, left, "Merge error: left.prior_size == right.prior_size");
×
2013
        }
×
2014
        if (!(left.index() < left.prior_size)) {
28✔
2015
            bad_merge(left_side, left, "Merge error: left.index() < left.prior_size");
×
2016
        }
×
2017
        if (!(right.index() < right.prior_size)) {
28✔
2018
            bad_merge(right_side, right, "Merge error: right.index() < right.prior_size");
×
2019
        }
×
2020
        if (!(left.ndx_2 < left.prior_size)) {
28✔
2021
            bad_merge(left_side, left, "Merge error: left.ndx_2 < left.prior_size");
×
2022
        }
×
2023
        if (!(right.ndx_2 < right.prior_size)) {
28✔
2024
            bad_merge(right_side, right, "Merge error: right.ndx_2 < right.prior_size");
×
2025
        }
×
2026

14✔
2027
        if (left.index() < right.index()) {
28✔
2028
            right.index() -= 1; // <---
4✔
2029
        }
4✔
2030
        else if (left.index() > right.index()) {
24✔
2031
            left.index() -= 1; // --->
4✔
2032
        }
4✔
2033
        else {
20✔
2034
            // CONFLICT: Two movements of same element.
10✔
2035
            //
10✔
2036
            // RESOLUTION: Respect the MOVE operation associated with the higher
10✔
2037
            // timestamp. If the previously applied MOVE operation has the higher
10✔
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()) {
20✔
2042
                right.index() = left.ndx_2; // <---
12✔
2043
                left_side.discard();        // --->
12✔
2044
                if (right.index() == right.ndx_2) {
12✔
2045
                    right_side.discard(); // <---
×
2046
                }
×
2047
            }
12✔
2048
            else {
8✔
2049
                left.index() = right.ndx_2; // --->
8✔
2050
                if (left.index() == left.ndx_2) {
8✔
2051
                    left_side.discard(); // --->
×
2052
                }
×
2053
                right_side.discard(); // <---
8✔
2054
            }
8✔
2055
            return;
20✔
2056
        }
20✔
2057

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

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

4✔
2074
        // Left insertion vs right insertion
4✔
2075
        if (left.ndx_2 < right.ndx_2) {
8✔
2076
            right.ndx_2 += 1; // <---
4✔
2077
        }
4✔
2078
        else if (left.ndx_2 > right.ndx_2) {
4✔
2079
            left.ndx_2 += 1; // --->
4✔
2080
        }
4✔
2081
        else { // left.ndx_2 == right.ndx_2
×
2082
            // CONFLICT: Two elements moved to the same position
2083
            //
2084
            // RESOLUTION: Place the moved elements in order of increasing
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) {
8✔
2095
            left_side.discard(); // --->
×
2096
        }
×
2097
        if (right.index() == right.ndx_2) {
8✔
2098
            right_side.discard(); // <---
×
2099
        }
×
2100
    }
8✔
2101
}
28✔
2102

2103
DEFINE_MERGE(Instruction::ArrayErase, Instruction::ArrayMove)
2104
{
×
2105
    if (same_container(left, right)) {
×
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
{
8✔
2160
    if (is_prefix_of(outer, inner)) {
8!
2161
        // Erase of subtree - inner instruction touches the subtree.
2162
        inner_side.discard();
×
2163
    }
×
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);
8✔
2167
        if (outer.index() < index) {
8!
2168
            index -= 1;
8✔
2169
        }
8✔
2170
        else {
×
2171
            REALM_ASSERT(index != outer.index());
×
2172
        }
×
2173
    }
8✔
2174
}
8✔
2175

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

634✔
2189
        left.prior_size -= 1;
1,160✔
2190
        right.prior_size -= 1;
1,160✔
2191

634✔
2192
        if (left.index() > right.index()) {
1,160✔
2193
            left.index() -= 1; // --->
454✔
2194
        }
454✔
2195
        else if (left.index() < right.index()) {
706✔
2196
            right.index() -= 1; // <---
458✔
2197
        }
458✔
2198
        else { // left.index() == right.index()
248✔
2199
            // CONFLICT: Two removals of the same element.
108✔
2200
            //
108✔
2201
            // RESOLUTION: On each side, discard the received REMOVE operation.
108✔
2202
            left_side.discard();  // --->
248✔
2203
            right_side.discard(); // <---
248✔
2204
        }
248✔
2205
    }
1,160✔
2206
}
2,804✔
2207

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

2213

2214
/// Clear rules
2215

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

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

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

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

2255

2256
/// SetInsert rules
2257

2258
DEFINE_NESTED_MERGE_NOOP(Instruction::SetInsert);
2259

2260
DEFINE_MERGE(Instruction::SetInsert, Instruction::SetInsert)
2261
{
156✔
2262
    if (same_path(left, right)) {
156✔
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,
76✔
2266
        // do nothing.
76✔
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)) {
152✔
2272
            if (left_side.timestamp() < right_side.timestamp()) {
24✔
2273
                left_side.discard();
12✔
2274
            }
12✔
2275
            else {
12✔
2276
                right_side.discard();
12✔
2277
            }
12✔
2278
        }
24✔
2279
    }
152✔
2280
}
156✔
2281

2282
DEFINE_MERGE(Instruction::SetErase, Instruction::SetInsert)
2283
{
64✔
2284
    if (same_path(left, right)) {
64✔
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
32✔
2288
        // timestamp. Otherwise, do nothing.
32✔
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)) {
64✔
UNCOV
2293
            if (left_side.timestamp() < right_side.timestamp()) {
×
UNCOV
2294
                left_side.discard();
×
UNCOV
2295
            }
×
2296
            else {
×
2297
                right_side.discard();
×
2298
            }
×
UNCOV
2299
        }
×
2300
    }
64✔
2301
}
64✔
2302

2303

2304
/// SetErase rules.
2305

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
{
2,447,328✔
2338
    Merge<Left, Right>::merge(left, right, left_side, right_side);
2,447,328✔
2339
}
2,447,328✔
2340

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

2347
void TransformerImpl::Transformer::merge_instructions(MajorSide& their_side, MinorSide& our_side)
2348
{
2,503,124✔
2349
    // FIXME: Find a way to avoid heap-copies of the path.
1,300,824✔
2350
    Instruction their_before = their_side.get();
2,503,124✔
2351
    Instruction our_before = our_side.get();
2,503,124✔
2352

1,300,824✔
2353
    if (their_side.get().get_if<Instruction::Update>()) {
2,503,124✔
2354
        REALM_ASSERT(their_side.m_path_len > 2);
161,688✔
2355
    }
161,688✔
2356
    if (our_side.get().get_if<Instruction::Update>()) {
2,503,124✔
2357
        REALM_ASSERT(our_side.m_path_len > 2);
206,402✔
2358
    }
206,402✔
2359
    if (their_side.get().get_if<Instruction::EraseObject>()) {
2,503,124✔
2360
        REALM_ASSERT(their_side.m_path_len == 2);
508,670✔
2361
    }
508,670✔
2362
    if (our_side.get().get_if<Instruction::EraseObject>()) {
2,503,124✔
2363
        REALM_ASSERT(our_side.m_path_len == 2);
585,542✔
2364
    }
585,542✔
2365

1,300,824✔
2366
    // Update selections on the major side (outer loop) according to events on
1,300,824✔
2367
    // the minor side (inner loop). The selection may only be impacted if the
1,300,824✔
2368
    // instruction level is lower (i.e. at a higher point in the hierarchy).
1,300,824✔
2369
    if (our_side.m_path_len < their_side.m_path_len) {
2,503,124✔
2370
        merge_nested(our_side, their_side);
423,216✔
2371
        if (their_side.was_discarded)
423,216✔
2372
            return;
27,984✔
2373
    }
2,079,908✔
2374
    else if (our_side.m_path_len > their_side.m_path_len) {
2,079,908✔
2375
        merge_nested(their_side, our_side);
604,682✔
2376
        if (our_side.was_discarded)
604,682✔
2377
            return;
27,932✔
2378
    }
2,447,208✔
2379

1,270,990✔
2380
    if (!their_side.was_discarded && !our_side.was_discarded) {
2,447,236✔
2381
        // Even if the instructions were nested, we must still perform a regular
1,271,004✔
2382
        // merge, because link-related instructions contain information from higher
1,271,004✔
2383
        // levels (both rows, columns, and tables).
1,271,004✔
2384
        //
1,271,004✔
2385
        // FIXME: This condition goes away when dangling links are implemented.
1,271,004✔
2386
        their_side.get().visit([&](auto& their_instruction) {
2,447,322✔
2387
            our_side.get().visit([&](auto& our_instruction) {
2,447,330✔
2388
                merge_instructions_2(their_instruction, our_instruction, their_side, our_side);
2,447,330✔
2389
            });
2,447,330✔
2390
        });
2,447,322✔
2391
    }
2,447,218✔
2392

1,270,990✔
2393
    // Note: `left` and/or `right` may be dangling at this point due to
1,270,990✔
2394
    // discard/prepend. However, if they were not discarded, their iterators are
1,270,990✔
2395
    // required to point to an instruction of the same type.
1,270,990✔
2396
    if (!their_side.was_discarded && !their_side.was_replaced) {
2,447,208✔
2397
        const auto& their_after = their_side.get();
2,408,808✔
2398
        if (!(their_after == their_before)) {
2,408,808✔
2399
            their_side.m_changeset->set_dirty(true);
32,600✔
2400
        }
32,600✔
2401
    }
2,408,808✔
2402

1,270,990✔
2403
    if (!our_side.was_discarded && !our_side.was_replaced) {
2,447,208✔
2404
        const auto& our_after = our_side.get();
2,409,338✔
2405
        if (!(our_after == our_before)) {
2,409,338✔
2406
            our_side.m_changeset->set_dirty(true);
32,604✔
2407
        }
32,604✔
2408
    }
2,409,338✔
2409
}
2,447,208✔
2410

2411

2412
template <class OuterSide, class InnerSide>
2413
void TransformerImpl::Transformer::merge_nested(OuterSide& outer_side, InnerSide& inner_side)
2414
{
1,027,898✔
2415
    outer_side.get().visit([&](auto& outer) {
1,027,896✔
2416
        inner_side.get().visit([&](auto& inner) {
1,027,898✔
2417
            merge_nested_2(outer, inner, outer_side, inner_side);
1,027,898✔
2418
        });
1,027,898✔
2419
    });
1,027,896✔
2420
}
1,027,898✔
2421

2422

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

209,220✔
2442
    _impl::ChangesetIndex their_index;
416,168✔
2443
    size_t their_num_instructions = 0;
416,168✔
2444
    size_t our_num_instructions = 0;
416,168✔
2445

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

219,898✔
2456
        their_index.scan_changeset(their_changesets[i]);
439,018✔
2457
    }
439,018✔
2458
    for (size_t i = 0; i < our_size; ++i) {
10,328,368✔
2459
        Changeset& our_changeset = *our_changesets[i];
9,912,200✔
2460
        size_t num_instructions = our_changeset.size();
9,912,200✔
2461
        our_num_instructions += num_instructions;
9,912,200✔
2462
        logger.trace("Scanning local changeset [%1/%2] (%3 instructions)", i + 1, our_size, num_instructions);
9,912,200✔
2463

4,948,668✔
2464
        their_index.scan_changeset(our_changeset);
9,912,200✔
2465
    }
9,912,200✔
2466

209,220✔
2467
    // Build the index.
209,220✔
2468
    for (size_t i = 0; i < their_size; ++i) {
855,182✔
2469
        logger.trace("Indexing incoming changeset [%1/%2] (%3 instructions)", i + 1, their_size,
439,014✔
2470
                     their_changesets[i].size());
439,014✔
2471
        their_index.add_changeset(their_changesets[i]);
439,014✔
2472
    }
439,014✔
2473

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

209,220✔
2479
#if REALM_DEBUG // LCOV_EXCL_START
209,220✔
2480
    if (trace) {
416,168✔
2481
        std::cerr << TERM_YELLOW << "\n=> PEER " << std::hex << local_file_ident
×
2482
                  << " merging "
×
2483
                     "changeset(s)/from peer(s):\n";
×
2484
        for (size_t i = 0; i < their_size; ++i) {
×
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

209,220✔
2519
    for (size_t i = 0; i < our_size; ++i) {
10,328,384✔
2520
        logger.trace(
9,912,216✔
2521
            "Transforming local changeset [%1/%2] through %3 incoming changeset(s) with %4 conflict group(s)", i + 1,
9,912,216✔
2522
            our_size, their_size, their_index.get_num_conflict_groups());
9,912,216✔
2523
        Changeset* our_changeset = our_changesets[i];
9,912,216✔
2524

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

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

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

209,220✔
2541
#if REALM_DEBUG // LCOV_EXCL_START
209,220✔
2542
    if (trace) {
416,168✔
2543
        for (size_t i = 0; i < our_size; ++i) {
×
2544
            std::cerr << TERM_CYAN << "\nRECIPROCAL CHANGESET AFTER MERGE:\n" << TERM_RESET;
×
2545
            our_changesets[i]->print(std::cerr);
×
2546
            std::cerr << '\n';
×
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
416,168✔
2555
}
416,168✔
2556

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

227,246✔
2565
    std::vector<Changeset*> our_changesets;
452,602✔
2566

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

227,246✔
2572
    try {
452,602✔
2573
        while (p != parsed_changesets_end) {
910,288✔
2574
            // Find the range of incoming changesets that share the same
230,008✔
2575
            // last_integrated_local_version, which means we can merge them in one go.
230,008✔
2576
            auto same_base_range_end = std::find_if(p + 1, parsed_changesets_end, [&](auto& changeset) {
249,454✔
2577
                return p->last_integrated_remote_version != changeset.last_integrated_remote_version;
35,856✔
2578
            });
35,856✔
2579

230,008✔
2580
            version_type begin_version = p->last_integrated_remote_version;
457,686✔
2581
            version_type end_version = current_local_version;
457,686✔
2582
            for (;;) {
10,369,876✔
2583
                HistoryEntry history_entry;
10,369,876✔
2584
                version_type version = history.find_history_entry(begin_version, end_version, history_entry);
10,369,876✔
2585
                if (version == 0)
10,369,876✔
2586
                    break; // No more local changesets
457,696✔
2587

4,948,660✔
2588
                Changeset& our_changeset = get_reciprocal_transform(history, local_file_ident, version,
9,912,180✔
2589
                                                                    history_entry); // Throws
9,912,180✔
2590
                our_changesets.push_back(&our_changeset);
9,912,180✔
2591

4,948,660✔
2592
                begin_version = version;
9,912,180✔
2593
            }
9,912,180✔
2594

230,008✔
2595
            bool must_apply_all = false;
457,686✔
2596

230,008✔
2597
            if (!our_changesets.empty()) {
457,686✔
2598
                merge_changesets(local_file_ident, &*p, same_base_range_end - p, our_changesets.data(),
416,168✔
2599
                                 our_changesets.size(), logger); // Throws
416,168✔
2600
                // We need to apply all transformed changesets if at least one reciprocal changeset was modified
209,220✔
2601
                // during OT.
209,220✔
2602
                must_apply_all = std::any_of(our_changesets.begin(), our_changesets.end(), [](const Changeset* c) {
9,086,024✔
2603
                    return c->is_dirty();
9,086,024✔
2604
                });
9,086,024✔
2605
            }
416,168✔
2606

230,008✔
2607
            auto continue_applying = true;
457,686✔
2608
            for (; p != same_base_range_end && continue_applying; ++p) {
946,108✔
2609
                // It is safe to stop applying the changesets if:
243,644✔
2610
                //      1. There are no reciprocal changesets
243,644✔
2611
                //      2. No reciprocal changeset was modified
243,644✔
2612
                continue_applying = changeset_applier(p) || must_apply_all;
488,422!
2613
            }
488,422✔
2614
            if (!continue_applying) {
457,686✔
2615
                break;
×
2616
            }
×
2617

230,008✔
2618
            our_changesets.clear(); // deliberately not releasing memory
457,686✔
2619
        }
457,686✔
2620
    }
452,602✔
2621
    catch (...) {
227,272✔
2622
        // If an exception was thrown while merging, the transform cache will
18✔
2623
        // be polluted. This is a problem since the same cache object is reused
18✔
2624
        // by multiple invocations to transform_remote_changesets(), so we must
18✔
2625
        // clear the cache before rethrowing.
18✔
2626
        //
18✔
2627
        // Note that some valid changesets can still cause exceptions to be
18✔
2628
        // thrown by the merge algorithm, namely incompatible schema changes.
18✔
2629
        m_reciprocal_transform_cache.clear();
44✔
2630
        throw;
44✔
2631
    }
44✔
2632

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

227,234✔
2637
    return p - parsed_changesets.begin();
452,566✔
2638
}
452,566✔
2639

2640

2641
Changeset& TransformerImpl::get_reciprocal_transform(TransformHistory& history, file_ident_type local_file_ident,
2642
                                                     version_type version, const HistoryEntry& history_entry)
2643
{
9,912,206✔
2644
    auto& changeset = m_reciprocal_transform_cache[version]; // Throws
9,912,206✔
2645
    if (changeset.empty()) {
9,912,206✔
2646
        bool is_compressed = false;
9,886,498✔
2647
        ChunkedBinaryData data = history.get_reciprocal_transform(version, is_compressed);
9,886,498✔
2648
        ChunkedBinaryInputStream in{data};
9,886,498✔
2649
        if (is_compressed) {
9,886,498✔
2650
            size_t total_size;
44,300✔
2651
            auto decompressed = util::compression::decompress_nonportable_input_stream(in, total_size);
44,300✔
2652
            REALM_ASSERT(decompressed);
44,300✔
2653
            sync::parse_changeset(*decompressed, changeset); // Throws
44,300✔
2654
        }
44,300✔
2655
        else {
9,842,198✔
2656
            sync::parse_changeset(in, changeset); // Throws
9,842,198✔
2657
        }
9,842,198✔
2658

4,934,894✔
2659
        changeset.version = version;
9,886,498✔
2660
        changeset.last_integrated_remote_version = history_entry.remote_version;
9,886,498✔
2661
        changeset.origin_timestamp = history_entry.origin_timestamp;
9,886,498✔
2662
        file_ident_type origin_file_ident = history_entry.origin_file_ident;
9,886,498✔
2663
        if (origin_file_ident == 0)
9,886,498✔
2664
            origin_file_ident = local_file_ident;
5,656,088✔
2665
        changeset.origin_file_ident = origin_file_ident;
9,886,498✔
2666
    }
9,886,498✔
2667
    return changeset;
9,912,206✔
2668
}
9,912,206✔
2669

2670

2671
void TransformerImpl::flush_reciprocal_transform_cache(TransformHistory& history)
2672
{
452,564✔
2673
    auto changesets = std::move(m_reciprocal_transform_cache);
452,564✔
2674
    m_reciprocal_transform_cache.clear();
452,564✔
2675
    ChangesetEncoder::Buffer output_buffer;
452,564✔
2676
    for (const auto& [version, changeset] : changesets) {
9,885,168✔
2677
        if (changeset.is_dirty()) {
9,885,168✔
2678
            encode_changeset(changeset, output_buffer); // Throws
87,608✔
2679
            BinaryData data{output_buffer.data(), output_buffer.size()};
87,608✔
2680
            history.set_reciprocal_transform(version, data); // Throws
87,608✔
2681
            output_buffer.clear();
87,608✔
2682
        }
87,608✔
2683
    }
9,885,168✔
2684
}
452,564✔
2685

2686
} // namespace _impl
2687

2688
namespace sync {
2689
std::unique_ptr<Transformer> make_transformer()
2690
{
18,278✔
2691
    return std::make_unique<_impl::TransformerImpl>(); // Throws
18,278✔
2692
}
18,278✔
2693

2694

2695
void parse_remote_changeset(const Transformer::RemoteChangeset& remote_changeset, Changeset& parsed_changeset)
2696
{
488,414✔
2697
    // origin_file_ident = 0 is currently used to indicate an entry of local
243,572✔
2698
    // origin.
243,572✔
2699
    REALM_ASSERT(remote_changeset.origin_file_ident != 0);
488,414✔
2700
    REALM_ASSERT(remote_changeset.remote_version != 0);
488,414✔
2701

243,572✔
2702
    ChunkedBinaryInputStream remote_in{remote_changeset.data};
488,414✔
2703
    parse_changeset(remote_in, parsed_changeset); // Throws
488,414✔
2704

243,572✔
2705
    parsed_changeset.version = remote_changeset.remote_version;
488,414✔
2706
    parsed_changeset.last_integrated_remote_version = remote_changeset.last_integrated_local_version;
488,414✔
2707
    parsed_changeset.origin_timestamp = remote_changeset.origin_timestamp;
488,414✔
2708
    parsed_changeset.origin_file_ident = remote_changeset.origin_file_ident;
488,414✔
2709
    parsed_changeset.original_changeset_size = remote_changeset.original_changeset_size;
488,414✔
2710
}
488,414✔
2711

2712
} // namespace sync
2713
} // namespace realm
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