File size: 12,686 Bytes
ef8334d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// g++ -O3 -DNDEBUG -std=c++17 -Iinclude bench/fanout.cpp -o fanout && ./fanout
// CSV reports medians of 9 interleaved trials, in microseconds per plan.
// Each independent visit only increments a counter. Factored algorithms build
// owned rows and per-reader lengths. Wire transfer and payload fetch are excluded.
#include "sincekit_batch.h"

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

namespace {

using sincekit::BatchPlan;
using sincekit::BatchRow;
using sincekit::Index;
using Cursors = std::vector<std::uint64_t>;
volatile std::uint64_t sink = 0;

std::size_t fixed_step_rank(const std::vector<BatchRow>& rows, std::uint64_t cursor) {
    if (rows.empty() || rows.front().revision <= cursor) return 0;
    if (rows.size() == 1 || rows[1].revision <= cursor) return 1;
    if (rows.back().revision > cursor) return rows.size();
    std::size_t first = 0;
    auto length = rows.size();
    while (length > 1) {
        const auto half = length / 2;
        const auto middle = first + half;
        first = rows[middle].revision > cursor ? middle : first;
        length -= half;
    }
    return first + 1;
}

template<bool FixedStep>
BatchPlan binary_plan(const Index& index, const Cursors& cursors) {
    BatchPlan plan;
    plan.revision = index.revision();
    if (cursors.empty()) return plan;
    const auto bounds = std::minmax_element(cursors.begin(), cursors.end());
    if (*bounds.second > plan.revision) throw std::out_of_range("future cursor");
    plan.rows.reserve(sincekit::batch_detail::initial_rows(index, *bounds.first, cursors.size()));
    index.since(*bounds.first, [&](auto id, auto rev, auto deleted) {
        plan.rows.push_back({rev, id, deleted});
    });
    if (*bounds.first == *bounds.second || plan.rows.empty()) {
        plan.prefix_lengths.assign(cursors.size(), plan.rows.size());
        return plan;
    }
    plan.prefix_lengths.resize(cursors.size());
    for (std::size_t i = 0; i < cursors.size(); ++i) {
        if constexpr (FixedStep) {
            plan.prefix_lengths[i] = fixed_step_rank(plan.rows, cursors[i]);
        } else {
            auto it = std::lower_bound(plan.rows.begin(), plan.rows.end(), cursors[i],
                [](const BatchRow& row, auto cursor) { return row.revision > cursor; });
            plan.prefix_lengths[i] = static_cast<std::size_t>(it - plan.rows.begin());
        }
    }
    return plan;
}

// Sort cursors once, then advance a single pointer over newest-first rows.
// Ascending and descending input orders avoid the permutation allocation.
BatchPlan sweep_plan(const Index& index, const Cursors& cursors) {
    BatchPlan plan;
    plan.revision = index.revision();
    if (cursors.empty()) return plan;
    const auto bounds = std::minmax_element(cursors.begin(), cursors.end());
    if (*bounds.second > plan.revision) throw std::out_of_range("future cursor");
    plan.rows.reserve(sincekit::batch_detail::initial_rows(index, *bounds.first, cursors.size()));
    index.since(*bounds.first, [&](auto id, auto rev, auto deleted) {
        plan.rows.push_back({rev, id, deleted});
    });
    if (*bounds.first == *bounds.second || plan.rows.empty()) {
        plan.prefix_lengths.assign(cursors.size(), plan.rows.size());
        return plan;
    }
    plan.prefix_lengths.resize(cursors.size());
    std::size_t count = 0;
    auto assign = [&](std::size_t reader, std::uint64_t cursor) {
        while (count < plan.rows.size() && plan.rows[count].revision > cursor) ++count;
        plan.prefix_lengths[reader] = count;
    };
    if (std::is_sorted(cursors.begin(), cursors.end(), std::greater<std::uint64_t>{})) {
        for (std::size_t i = 0; i < cursors.size(); ++i) assign(i, cursors[i]);
    } else if (std::is_sorted(cursors.begin(), cursors.end())) {
        for (std::size_t i = cursors.size(); i != 0; --i) assign(i - 1, cursors[i - 1]);
    } else {
        std::vector<std::pair<std::uint64_t, std::size_t>> ordered;
        ordered.reserve(cursors.size());
        for (std::size_t i = 0; i < cursors.size(); ++i) ordered.emplace_back(cursors[i], i);
        std::sort(ordered.begin(), ordered.end(), std::greater<>{});
        for (const auto& reader : ordered) assign(reader.second, reader.first);
    }
    return plan;
}

// Escape both buffers so that the timed binary, sweep, and adaptive paths
// must materialize the same plan contents.
inline void observe(const void* p, const void* q) {
#if defined(__GNUC__) || defined(__clang__)
    asm volatile("" : : "g"(p), "g"(q) : "memory");
#else
    static const void* volatile observed[2];
    observed[0] = p;
    observed[1] = q;
    std::atomic_signal_fence(std::memory_order_seq_cst);
#endif
}

std::uint64_t independent_count(const Index& index, const Cursors& cursors) {
    std::uint64_t count = 0;
    for (auto cursor : cursors) index.since(cursor, [&](auto, auto, auto) { ++count; });
    return count;
}

std::uint64_t logical_count(const BatchPlan& plan) {
    observe(plan.rows.data(), plan.prefix_lengths.data());
    return std::accumulate(plan.prefix_lengths.begin(), plan.prefix_lengths.end(), std::uint64_t{0});
}

void verify(const Index& index, const Cursors& cursors, const BatchPlan& plan) {
    if (binary_plan<false>(index, cursors).prefix_lengths != plan.prefix_lengths ||
        binary_plan<true>(index, cursors).prefix_lengths != plan.prefix_lengths ||
        sweep_plan(index, cursors).prefix_lengths != plan.prefix_lengths) {
        throw std::runtime_error("binary reference disagrees");
    }
    for (std::size_t reader = 0; reader < cursors.size(); ++reader) {
        std::size_t n = 0;
        index.since(cursors[reader], [&](auto id, auto rev, auto deleted) {
            const auto& row = plan.rows.at(n++);
            if (row.id != id || row.revision != rev || row.deleted != deleted) {
                throw std::runtime_error("row mismatch");
            }
        });
        if (n != plan.prefix_lengths.at(reader)) throw std::runtime_error("reader length mismatch");
    }
}

void run(const std::string& name, const Index& index, const Cursors& cursors, int repetitions, bool raw) {
    auto plan = sincekit::since_many(index, cursors);
    verify(index, cursors, plan);
    const auto expected = logical_count(plan);
    std::array<std::vector<double>, 5> times;
    // Rotate the first algorithm, and verify each timed trial's logical count.
    for (int trial = 0; trial <= 9; ++trial) {
        for (std::size_t j = 0; j < times.size(); ++j) {
            const auto method = (j + static_cast<std::size_t>(trial)) % times.size();
            std::uint64_t sum = 0;
            auto start = std::chrono::steady_clock::now();
            for (int repetition = 0; repetition < repetitions; ++repetition) {
                observe(&index, cursors.data());
                switch (method) {
                case 0: sum += independent_count(index, cursors); break;
                case 1: sum += logical_count(binary_plan<false>(index, cursors)); break;
                case 2: sum += logical_count(binary_plan<true>(index, cursors)); break;
                case 3: sum += logical_count(sweep_plan(index, cursors)); break;
                case 4: sum += logical_count(sincekit::since_many(index, cursors)); break;
                }
            }
            auto duration = std::chrono::steady_clock::now() - start;
            if (sum != expected * static_cast<std::uint64_t>(repetitions)) {
                throw std::runtime_error("timed result mismatch");
            }
            sink = sink + sum;
            if (trial != 0) {
                times[method].push_back(std::chrono::duration<double, std::micro>(duration).count() /
                                        repetitions);
            }
        }
    }
    auto print = [&](const std::string& trial, std::size_t position) {
        std::cout << name << ',' << trial << ',' << repetitions << ',' << cursors.size()
                  << ',' << plan.rows.size() << ',' << expected;
        for (const auto& sample : times) {
            std::cout << ',' << std::fixed << std::setprecision(4) << sample[position];
        }
        std::cout << '\n';
    };
    if (raw) {
        for (std::size_t i = 0; i < times[0].size(); ++i) print(std::to_string(i + 1), i);
    } else {
        for (auto& sample : times) std::sort(sample.begin(), sample.end());
        print("median", times[0].size() / 2);
    }
}

}  // namespace

int main(int argc, char** argv) {
    if (argc > 2 || (argc == 2 && std::string(argv[1]) != "--raw")) {
        std::cerr << "usage: fanout [--raw]\n";
        return 2;
    }
    const bool raw = argc == 2;
    std::mt19937_64 rng(918219);
    std::cout << "scenario,trial,repetitions,readers,shared_rows,logical_deliveries,independent_count_us,"
                 "union_lower_bound_us,union_fixed_step_us,union_sorted_sweep_us,since_many_us\n";

    Index contiguous(8192);
    for (std::uint32_t i = 0; i < 8192; ++i) contiguous.touch(i);
    Cursors cursors(2048);
    for (auto& c : cursors) c = rng() % (contiguous.revision() + 1);
    run("contiguous_uniform_age", contiguous, cursors, 1, raw);

    Index churn(16384);
    for (int i = 0; i < 65536; ++i) {
        auto id = static_cast<std::uint32_t>(rng() % churn.capacity());
        if (rng() % 5 == 0) churn.erase(id);
        else churn.touch(id);
    }
    cursors.resize(4096);
    for (auto& c : cursors) c = rng() % (churn.revision() + 1);
    run("churn_uniform_age", churn, cursors, 1, raw);
    std::sort(cursors.begin(), cursors.end(), std::greater<>{});
    run("churn_presorted_age", churn, cursors, 1, raw);
    for (auto& c : cursors) {
        const auto age = (rng() % 20 != 0) ? rng() % 64 : rng() % (churn.revision() + 1);
        c = churn.revision() - age;
    }
    run("churn_95pct_recent", churn, cursors, 1, raw);

    Index sparse(256);
    for (std::uint32_t id = 0; id < 256; ++id) sparse.touch(id);
    for (int i = 0; i < 100000; ++i) sparse.touch(0);
    cursors.resize(2048);
    for (auto& c : cursors) c = rng() % (sparse.revision() + 1);
    cursors[0] = 0;
    run("sparse_old_gap", sparse, cursors, 100, raw);
    // Post-tuning holdouts for the long-gap workload. A fixed, independent
    // seed drives nine hot keys. The second stream has periodic cold writes.
    for (const bool heartbeat : {false, true}) {
        std::mt19937_64 heldout(3093553);
        Index multi(521);
        for (std::uint32_t id = 0; id < multi.capacity(); ++id) multi.touch(id);
        for (std::uint32_t t = 1; t <= 170000; ++t) {
            const auto id = heartbeat && t % 8191 == 0
                ? 9u + static_cast<std::uint32_t>(heldout() % 512)
                : static_cast<std::uint32_t>(heldout() % 9);
            multi.touch(id);
        }
        cursors.resize(3072);
        for (auto& c : cursors) {
            const auto age = heldout() % 4 == 0 ? heldout() % 512 :
                heldout() % (multi.revision() + 1);
            c = multi.revision() - age;
        }
        cursors[0] = 0;
        run(heartbeat ? "sparse_nine_hot_heartbeat" : "sparse_nine_hot",
            multi, cursors, 40, raw);
    }
    // Held back until after the sparse directory design was frozen. Hot keys
    // rotate, cold writes arrive in variable-length bursts, and many readers
    // share a cursor at a burst boundary.
    std::mt19937_64 shifted_rng(7314273);
    Index shifted(1024);
    for (std::uint32_t id = 0; id < shifted.capacity(); ++id) shifted.touch(id);
    Cursors burst_starts;
    std::uint32_t next_burst = 511;
    for (std::uint32_t t = 1; t <= 160000; ++t) {
        if (t == next_burst) {
            burst_starts.push_back(shifted.revision());
            const auto burst = 2 + shifted_rng() % 29;
            for (unsigned j = 0; j < burst; ++j) {
                shifted.touch(85 + static_cast<std::uint32_t>(shifted_rng() % 939));
            }
            next_burst += 503 + static_cast<std::uint32_t>(shifted_rng() % 8500);
        }
        const auto band = 17 * ((t / 29000) % 5);
        shifted.touch(band + static_cast<std::uint32_t>(shifted_rng() % 17));
    }
    cursors.resize(2048);
    for (auto& c : cursors) {
        if (shifted_rng() % 3 == 0) c = burst_starts[shifted_rng() % burst_starts.size()];
        else c = shifted_rng() % (shifted.revision() + 1);
    }
    cursors[0] = 0;
    run("sparse_rotating17_cold_bursts", shifted, cursors, 16, raw);
    run("one_reader_current", churn, {churn.revision()}, 1000, raw);
}