aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/erasure/lrc.h
blob: 15185a47f4577cf5e072d32d58dad1a7a05ce0d6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#pragma once

#include "helpers.h"

#include <library/cpp/sse/sse.h>

#include <library/cpp/yt/assert/assert.h>

#include <util/generic/array_ref.h>

#include <algorithm>
#include <optional>

namespace NErasure {

template <class TCodecTraits, class TBlobType = typename TCodecTraits::TBlobType>
static inline TBlobType Xor(const std::vector<TBlobType>& refs) {
    using TBufferType = typename TCodecTraits::TBufferType;
    size_t size = refs.front().Size();
    TBufferType result = TCodecTraits::AllocateBuffer(size); // this also fills the buffer with zeros
    for (const TBlobType& ref : refs) {
        const char* data = reinterpret_cast<const char*>(ref.Begin());
        size_t pos = 0;
#ifdef ARCADIA_SSE
        for (; pos + sizeof(__m128i) <= size; pos += sizeof(__m128i)) {
            __m128i* dst = reinterpret_cast<__m128i*>(result.Begin() + pos);
            const __m128i* src = reinterpret_cast<const __m128i*>(data + pos);
            _mm_storeu_si128(dst, _mm_xor_si128(_mm_loadu_si128(src), _mm_loadu_si128(dst)));
        }
#endif
        for (; pos < size; ++pos) {
            *(result.Begin() + pos) ^= data[pos];
        }
    }
    return TCodecTraits::FromBufferToBlob(std::move(result));
}

//! Locally Reconstructable Codes
/*!
 *  See https://www.usenix.org/conference/usenixfederatedconferencesweek/erasure-coding-windows-azure-storage
 *  for more details.
 */
template <int DataPartCount, int ParityPartCount, int WordSize, class TCodecTraits>
class TLrcCodecBase
    : public ICodec<typename TCodecTraits::TBlobType>
{
    static_assert(DataPartCount % 2 == 0, "Data part count must be even.");
    static_assert(ParityPartCount == 4, "Now we only support n-2-2 scheme for LRC codec");
    static_assert(1 + DataPartCount / 2 < (1 << (WordSize / 2)), "Data part count should be enough small to construct proper matrix.");
public:
    //! Main blob for storing data.
    using TBlobType = typename TCodecTraits::TBlobType;
    //! Main mutable blob for decoding data.
    using TMutableBlobType = typename TCodecTraits::TMutableBlobType;

    static constexpr ui64 RequiredDataAlignment = alignof(ui64);

    TLrcCodecBase() {
        Groups_[0] = MakeSegment(0, DataPartCount / 2);
        // Xor.
        Groups_[0].push_back(DataPartCount);

        Groups_[1] = MakeSegment(DataPartCount / 2, DataPartCount);
        // Xor.
        Groups_[1].push_back(DataPartCount + 1);

        constexpr int totalPartCount = DataPartCount + ParityPartCount;
        if constexpr (totalPartCount <= BitmaskOptimizationThreshold) {
            CanRepair_.resize(1 << totalPartCount);
            for (int mask = 0; mask < (1 << totalPartCount); ++mask) {
                TPartIndexList erasedIndices;
                for (size_t i = 0; i < totalPartCount; ++i) {
                    if ((mask & (1 << i)) == 0) {
                        erasedIndices.push_back(i);
                    }
                }
                CanRepair_[mask] = CalculateCanRepair(erasedIndices);
            }
        }
    }

    /*! Note that if you want to restore any internal data, blocks offsets must by WordSize * sizeof(long) aligned.
     * Though it is possible to restore unaligned data if no more than one index in each Group is failed. See unittests for this case.
     */
    std::vector<TBlobType> Decode(
        const std::vector<TBlobType>& blocks,
        const TPartIndexList& erasedIndices) const override
    {
        if (erasedIndices.empty()) {
            return std::vector<TBlobType>();
        }

        size_t blockLength = blocks.front().Size();
        for (size_t i = 1; i < blocks.size(); ++i) {
            YT_VERIFY(blocks[i].Size() == blockLength);
        }

        TPartIndexList indices = UniqueSortedIndices(erasedIndices);

        // We can restore one block by xor.
        if (indices.size() == 1) {
            int index = erasedIndices.front();
            for (size_t i = 0; i < 2; ++i) {
                if (Contains(Groups_[i], index)) {
                    return std::vector<TBlobType>(1, Xor<TCodecTraits>(blocks));
                }
            }
        }

        TPartIndexList recoveryIndices = GetRepairIndices(indices).value();
        // We can restore two blocks from different groups using xor.
        if (indices.size() == 2 &&
            indices.back() < DataPartCount + 2 &&
            recoveryIndices.back() < DataPartCount + 2)
        {
            std::vector<TBlobType> result;
            for (int index : indices) {
                for (size_t groupIndex = 0; groupIndex < 2; ++groupIndex) {
                    if (!Contains(Groups_[groupIndex], index)) {
                        continue;
                    }

                    std::vector<TBlobType> correspondingBlocks;
                    for (int pos : Groups_[groupIndex]) {
                        for (size_t i = 0; i < blocks.size(); ++i) {
                            if (recoveryIndices[i] != pos) {
                                continue;
                            }
                            correspondingBlocks.push_back(blocks[i]);
                        }
                    }

                    result.push_back(Xor<TCodecTraits>(correspondingBlocks));
                }
            }
            return result;
        }

        return FallbackToCodecDecode(blocks, std::move(indices));
    }

    bool CanRepair(const TPartIndexList& erasedIndices) const final {
        constexpr int totalPartCount = DataPartCount + ParityPartCount;
        if constexpr (totalPartCount <= BitmaskOptimizationThreshold) {
            int mask = (1 << (totalPartCount)) - 1;
            for (int index : erasedIndices) {
                mask -= (1 << index);
            }
            return CanRepair_[mask];
        } else {
            return CalculateCanRepair(erasedIndices);
        }
    }

    bool CanRepair(const TPartIndexSet& erasedIndicesMask) const final {
        constexpr int totalPartCount = DataPartCount + ParityPartCount;
        if constexpr (totalPartCount <= BitmaskOptimizationThreshold) {
            TPartIndexSet mask = erasedIndicesMask;
            return CanRepair_[mask.flip().to_ulong()];
        } else {
            TPartIndexList erasedIndices;
            for (size_t i = 0; i < erasedIndicesMask.size(); ++i) {
                if (erasedIndicesMask[i]) {
                    erasedIndices.push_back(i);
                }
            }
            return CalculateCanRepair(erasedIndices);
        }
    }

    std::optional<TPartIndexList> GetRepairIndices(const TPartIndexList& erasedIndices) const final {
        if (erasedIndices.empty()) {
            return TPartIndexList();
        }

        TPartIndexList indices = UniqueSortedIndices(erasedIndices);

        if (indices.size() > ParityPartCount) {
            return std::nullopt;
        }

        // One erasure from data or xor blocks.
        if (indices.size() == 1) {
            int index = indices.front();
            for (size_t i = 0; i < 2; ++i) {
                if (Contains(Groups_[i], index)) {
                    return Difference(Groups_[i], index);
                }
            }
        }

        // Null if we have 4 erasures in one group.
        if (indices.size() == ParityPartCount) {
            bool intersectsAny = true;
            for (size_t i = 0; i < 2; ++i) {
                if (Intersection(indices, Groups_[i]).empty()) {
                    intersectsAny = false;
                }
            }
            if (!intersectsAny) {
                return std::nullopt;
            }
        }

        // Calculate coverage of each group.
        int groupCoverage[2] = {};
        for (int index : indices) {
            for (size_t i = 0; i < 2; ++i) {
                if (Contains(Groups_[i], index)) {
                    ++groupCoverage[i];
                }
            }
        }

        // Two erasures, one in each group.
        if (indices.size() == 2 && groupCoverage[0] == 1 && groupCoverage[1] == 1) {
            return Difference(Union(Groups_[0], Groups_[1]), indices);
        }

        // Erasures in only parity blocks.
        if (indices.front() >= DataPartCount) {
            return MakeSegment(0, DataPartCount);
        }

        // Remove unnecessary xor parities.
        TPartIndexList result = Difference(0, DataPartCount + ParityPartCount, indices);
        for (size_t i = 0; i < 2; ++i) {
            if (groupCoverage[i] == 0 && indices.size() <= 3) {
                result = Difference(result, DataPartCount + i);
            }
        }
        return result;
    }

    int GetDataPartCount() const override {
        return DataPartCount;
    }

    int GetParityPartCount() const override {
        return ParityPartCount;
    }

    int GetGuaranteedRepairablePartCount() const override {
        return ParityPartCount - 1;
    }

    int GetWordSize() const override {
        return WordSize * sizeof(long);
    }

    virtual ~TLrcCodecBase() = default;

protected:
    // Indices of data blocks and corresponding xor (we have two xor parities).
    TConstArrayRef<TPartIndexList> GetXorGroups() const {
        return Groups_;
    }

    virtual std::vector<TBlobType> FallbackToCodecDecode(
        const std::vector<TBlobType>& /* blocks */,
        TPartIndexList /* erasedIndices */) const = 0;

    template <typename T>
    void InitializeGeneratorMatrix(T* generatorMatrix, const std::function<T(T)>& GFSquare) {
        for (int row = 0; row < ParityPartCount; ++row) {
            for (int column = 0; column < DataPartCount; ++column) {
                int index = row * DataPartCount + column;

                bool isFirstHalf = column < DataPartCount / 2;
                if (row == 0) generatorMatrix[index] = isFirstHalf ? 1 : 0;
                if (row == 1) generatorMatrix[index] = isFirstHalf ? 0 : 1;

                // Let alpha_i be coefficient of first half and beta_i of the second half.
                // Then matrix is non-singular iff:
                //   a) alpha_i, beta_j != 0
                //   b) alpha_i != beta_j
                //   c) alpha_i + alpha_k != beta_j + beta_l
                // for any i, j, k, l.
                if (row == 2) {
                    int shift = isFirstHalf ? 1 : (1 << (WordSize / 2));
                    int relativeColumn = isFirstHalf ? column : (column - (DataPartCount / 2));
                    generatorMatrix[index] = shift * (1 + relativeColumn);
                }

                // The last row is the square of the row before last.
                if (row == 3) {
                    auto prev = generatorMatrix[index - DataPartCount];
                    generatorMatrix[index] = GFSquare(prev);
                }
            }
        }
    }

private:
    bool CalculateCanRepair(const TPartIndexList& erasedIndices) const {
        TPartIndexList indices = UniqueSortedIndices(erasedIndices);
        if (indices.size() > ParityPartCount) {
            return false;
        }

        if (indices.size() == 1) {
            int index = indices.front();
            for (size_t i = 0; i < 2; ++i) {
                if (Contains(Groups_[i], index)) {
                    return true;
                }
            }
        }

        // If 4 indices miss in one block we cannot recover.
        if (indices.size() == ParityPartCount) {
            for (size_t i = 0; i < 2; ++i) {
                if (Intersection(indices, Groups_[i]).empty()) {
                    return false;
                }
            }
        }

        return true;
    }

    TPartIndexList Groups_[2];
    std::vector<bool> CanRepair_;
};

} // namespace NErasure