Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/src/Progmasoft/ChoiceShrinker.cpp
blob: ab8613ed75e66efeffb14c00effdc53f7bc38de5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Copyright (c) 2026 Progmasoft.
// SPDX-License-Identifier: MPL-2.0 WITH AdditionRef-Progmasoft-Exception-2.0
#include <Progmasoft/Catch3/Strategy/Engine.hpp>

#include <algorithm>
#include <array>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>

namespace Progmasoft::Catch3::Detail
{

    bool
    IsSimpler(const std::vector<std::uint64_t> &candidate,
              const std::vector<std::uint64_t> &current) noexcept
    {
        if (candidate.size() != current.size())
        {
            return candidate.size() < current.size();
        }
        return std::lexicographical_compare(
            candidate.begin(), candidate.end(), current.begin(), current.end());
    }

    namespace
    {

        constexpr std::string_view kTokenPrefix = "c3.";

        /// Replays candidates against the current best and keeps the
        /// simplest failing one. Every replay counts against the budget.
        class Shrinker final
        {
        public:
            using StillFails
                = std::function<std::optional<std::vector<std::uint64_t>>(
                    const std::vector<std::uint64_t> &)>;

            Shrinker(std::vector<std::uint64_t> failing,
                     std::size_t budget,
                     const StillFails &stillFails)
                : current_(std::move(failing))
                , budget_(budget)
                , stillFails_(stillFails)
            {}

            [[nodiscard]] std::vector<std::uint64_t>
            Run(std::size_t &calls)
            {
                bool improved = true;
                while (improved && !Spent())
                {
                    improved = false;
                    improved |= DeleteBlocks();
                    improved |= ZeroBlocks();
                    improved |= MinimizeChoices();
                    improved |= SortNeighbours();
                    improved |= MoveBetweenNeighbours();
                }
                calls = calls_;
                return current_;
            }

        private:
            static constexpr std::array<std::size_t, 5> kBlockSizes
                = { 16, 8, 4, 2, 1 };

            [[nodiscard]] bool
            Spent() const noexcept
            {
                return calls_ >= budget_;
            }

            /// Replays a candidate; true when it fails and the sequence it
            /// consumed is simpler than the current one, which it replaces.
            bool
            Try(const std::vector<std::uint64_t> &candidate)
            {
                if (Spent() || !IsSimpler(candidate, current_))
                {
                    return false;
                }
                ++calls_;
                auto consumed = stillFails_(candidate);
                if (!consumed.has_value() || !IsSimpler(*consumed, current_))
                {
                    return false;
                }
                current_ = std::move(*consumed);
                return true;
            }

            bool
            DeleteBlocks()
            {
                bool improved = false;
                for (const std::size_t block : kBlockSizes)
                {
                    // From the end, so that a deletion does not move the
                    // blocks still to be tried.
                    for (std::size_t index = current_.size();
                         index-- > 0 && !Spent();)
                    {
                        if (index + block > current_.size())
                        {
                            continue;
                        }
                        auto candidate = current_;
                        candidate.erase(
                            candidate.begin()
                                + static_cast<std::ptrdiff_t>(index),
                            candidate.begin()
                                + static_cast<std::ptrdiff_t>(index + block));
                        improved |= Try(candidate);
                    }
                }
                return improved;
            }

            bool
            ZeroBlocks()
            {
                bool improved = false;
                for (const std::size_t block : kBlockSizes)
                {
                    for (std::size_t index = 0;
                         index + block <= current_.size() && !Spent();
                         ++index)
                    {
                        const auto first = current_.begin()
                                           + static_cast<std::ptrdiff_t>(index);
                        if (std::all_of(first,
                                        first
                                            + static_cast<std::ptrdiff_t>(block),
                                        [](std::uint64_t value) {
                                            return value == 0;
                                        }))
                        {
                            continue;
                        }
                        auto candidate = current_;
                        std::fill_n(candidate.begin()
                                        + static_cast<std::ptrdiff_t>(index),
                                    block,
                                    0U);
                        improved |= Try(candidate);
                    }
                }
                return improved;
            }

            /// Lowers each choice as far as the failure allows, assuming
            /// that a smaller choice is usually still failing when a larger
            /// one is: a binary search between 0 and the current value.
            bool
            MinimizeChoices()
            {
                bool improved = false;
                for (std::size_t index = 0;
                     index < current_.size() && !Spent();
                     ++index)
                {
                    std::uint64_t high = current_[index];
                    if (high == 0)
                    {
                        continue;
                    }
                    if (TryValue(index, 0))
                    {
                        improved = true;
                        continue;
                    }
                    std::uint64_t low = 0;
                    while (low + 1U < high && !Spent()
                           && index < current_.size())
                    {
                        const std::uint64_t middle = low + (high - low) / 2U;
                        if (TryValue(index, middle))
                        {
                            high = middle;
                            improved = true;
                        }
                        // Binary search assumes that failures are monotone
                        // in the choice; a filter or a parity condition
                        // breaks that, so the neighbour gets a chance too:
                        // with only even values passing a filter, an odd
                        // middle would otherwise stop the search.
                        else if (middle + 1U < high
                                 && TryValue(index, middle + 1U))
                        {
                            high = middle + 1U;
                            improved = true;
                        }
                        else
                        {
                            low = middle + 1U;
                        }
                    }
                    // A few single steps below the result, once: 104 -> 102
                    // when only even values pass. The next round of passes
                    // repeats the search from there.
                    for (std::uint64_t step = 1; step <= 8 && !Spent()
                                                 && index < current_.size()
                                                 && current_[index] >= step;
                         ++step)
                    {
                        if (TryValue(index, current_[index] - step))
                        {
                            improved = true;
                            break;
                        }
                    }
                }
                return improved;
            }

            bool
            TryValue(std::size_t index, std::uint64_t value)
            {
                if (index >= current_.size() || current_[index] <= value)
                {
                    return false;
                }
                auto candidate = current_;
                candidate[index] = value;
                return Try(candidate);
            }

            bool
            SortNeighbours()
            {
                bool improved = false;
                for (std::size_t index = 0;
                     index + 1U < current_.size() && !Spent();
                     ++index)
                {
                    if (current_[index] <= current_[index + 1U])
                    {
                        continue;
                    }
                    auto candidate = current_;
                    std::swap(candidate[index], candidate[index + 1U]);
                    improved |= Try(candidate);
                }
                return improved;
            }

            /// Moves one unit from a choice to one of the next few: the
            /// sequence gets lexicographically smaller while a sum such as
            /// x + y > 10 keeps failing.
            bool
            MoveBetweenNeighbours()
            {
                bool improved = false;
                for (std::size_t index = 0;
                     index < current_.size() && !Spent();
                     ++index)
                {
                    for (std::size_t offset = 1;
                         offset <= 4 && index + offset < current_.size()
                         && !Spent();
                         ++offset)
                    {
                        if (current_[index] == 0
                            || current_[index + offset] == UINT64_MAX)
                        {
                            break;
                        }
                        auto candidate = current_;
                        --candidate[index];
                        ++candidate[index + offset];
                        improved |= Try(candidate);
                    }
                }
                return improved;
            }

            std::vector<std::uint64_t> current_;
            std::size_t budget_;
            std::size_t calls_ = 0;
            const StillFails &stillFails_;
        };

    } // namespace

    std::vector<std::uint64_t>
    ShrinkChoices(
        std::vector<std::uint64_t> failing,
        std::size_t budget,
        const std::function<std::optional<std::vector<std::uint64_t>>(
            const std::vector<std::uint64_t> &)> &stillFails,
        std::size_t &calls)
    {
        Shrinker shrinker(std::move(failing), budget, stillFails);
        return shrinker.Run(calls);
    }

    std::string
    EncodeChoices(std::size_t size, const std::vector<std::uint64_t> &choices)
    {
        // c3.<size>.<choice>-<choice>-... with each number in base 36: short
        // enough to paste from a CI log, and only characters that survive
        // shells and C++ string literals unescaped.
        std::string token(kTokenPrefix);
        std::array<char, 24> buffer{};
        const auto append = [&](std::uint64_t value) {
            const auto end = std::to_chars(
                                 buffer.data(), buffer.data() + buffer.size(),
                                 value, 36)
                                 .ptr;
            token.append(buffer.data(), end);
        };
        append(size);
        token += '.';
        for (std::size_t index = 0; index < choices.size(); ++index)
        {
            if (index != 0)
            {
                token += '-';
            }
            append(choices[index]);
        }
        return token;
    }

    std::optional<DecodedChoices>
    DecodeChoices(std::string_view token)
    {
        if (token.substr(0, kTokenPrefix.size()) != kTokenPrefix)
        {
            return std::nullopt;
        }
        token.remove_prefix(kTokenPrefix.size());
        const auto parse = [](std::string_view text)
            -> std::optional<std::uint64_t> {
            std::uint64_t value = 0;
            const auto result = std::from_chars(
                text.data(), text.data() + text.size(), value, 36);
            if (text.empty() || result.ec != std::errc()
                || result.ptr != text.data() + text.size())
            {
                return std::nullopt;
            }
            return value;
        };
        const auto dot = token.find('.');
        if (dot == std::string_view::npos)
        {
            return std::nullopt;
        }
        const auto size = parse(token.substr(0, dot));
        if (!size.has_value() || *size > 100U)
        {
            return std::nullopt;
        }
        DecodedChoices decoded;
        decoded.Size = static_cast<std::size_t>(*size);
        std::string_view rest = token.substr(dot + 1U);
        while (!rest.empty())
        {
            const auto dash = rest.find('-');
            const auto value = parse(rest.substr(0, dash));
            if (!value.has_value())
            {
                return std::nullopt;
            }
            decoded.Choices.push_back(*value);
            if (dash == std::string_view::npos)
            {
                break;
            }
            rest.remove_prefix(dash + 1U);
            if (rest.empty())
            {
                return std::nullopt;
            }
        }
        return decoded;
    }

} // namespace Progmasoft::Catch3::Detail