Spaces:
Running
Running
File size: 7,581 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 | #ifndef SINCEKIT_BATCH_H_INCLUDED
#define SINCEKIT_BATCH_H_INCLUDED
#include "sincekit.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <vector>
namespace sincekit {
struct BatchRow {
std::uint64_t revision;
std::uint32_t id;
bool deleted;
};
struct BatchPlan {
std::uint64_t revision = 0;
std::vector<BatchRow> rows;
std::vector<std::size_t> prefix_lengths;
};
namespace batch_detail {
// Reservation uses known upper bounds, then caps the guess at four rows per
// reader and 256 KiB on usual 16-byte BatchRow targets. Heavy overwrite churn
// can make the true row count much smaller than the revision interval.
template<class SourceIndex>
inline std::size_t initial_rows(const SourceIndex& index, std::uint64_t since, std::size_t readers) {
auto hint = static_cast<std::size_t>(std::min<std::uint64_t>(
std::min<std::size_t>(index.capacity(), 16384), index.revision() - since));
return hint / 4 >= readers ? 4 * readers : hint;
}
inline unsigned count_bits(std::uint64_t bits) noexcept {
#if defined(__GNUC__) || defined(__clang__)
return static_cast<unsigned>(__builtin_popcountll(bits));
#else
bits -= (bits >> 1) & 0x5555555555555555ULL;
bits = (bits & 0x3333333333333333ULL) + ((bits >> 2) & 0x3333333333333333ULL);
bits = (bits + (bits >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
return static_cast<unsigned>((bits * 0x0101010101010101ULL) >> 56);
#endif
}
struct RankWord {
std::uint64_t bits = 0;
std::size_t before = 0;
};
inline std::size_t prefix_rank(const std::vector<BatchRow>& rows, std::size_t begin,
std::size_t end, std::uint64_t cursor) {
if (begin == end || cursor >= rows[begin].revision) return begin;
if (cursor < rows[end - 1].revision) return end;
if (cursor >= rows[begin + 1].revision) return begin + 1;
// Every step tests a fixed offset from the last known qualifying row.
auto first = begin + 1;
auto length = end - first;
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;
}
} // namespace batch_detail
// Plan a shared delivery to readers of one source and authorization domain.
// SourceIndex supplies capacity(), revision(), and since(). Its since()
// traversal emits unique latest revisions in strictly descending order.
// Reader i needs exactly rows[0 .. prefix_lengths[i]), newest first. Rows are
// owned, and may outlive the Index. Use the Index's synchronization rules while
// building the plan. Advance an individual cursor only after its delivery.
//
// For U distinct changed slots and R readers, one traversal collects U rows.
// Contiguous revisions and dense windows with enough readers take O(U + R).
// Sparse batches with many readers use up to 256 revision-age buckets, then
// search within each cursor's bucket. Other queries use a direct binary search.
// Worst-case time is O(U + R log(U + 1)). Total memory is O(U + R), independent
// of the number of logical deliveries. Applying every row at every reader can
// still cost their sum. A single reader can use Index::since without allocating.
template<class SourceIndex>
inline BatchPlan since_many(const SourceIndex& index, const std::vector<std::uint64_t>& cursors) {
BatchPlan plan;
plan.revision = index.revision();
if (cursors.empty()) {
return plan;
}
const auto bounds = std::minmax_element(cursors.begin(), cursors.end());
const auto oldest_cursor = *bounds.first;
if (*bounds.second > plan.revision) {
throw std::out_of_range("sincekit: cursor exceeds current revision");
}
plan.rows.reserve(batch_detail::initial_rows(index, oldest_cursor, cursors.size()));
index.since(oldest_cursor, [&](std::uint32_t id, std::uint64_t rev, bool deleted) {
plan.rows.push_back({rev, id, deleted});
});
const auto n = plan.rows.size();
if (oldest_cursor == *bounds.second || n == 0) {
plan.prefix_lengths.assign(cursors.size(), n);
return plan;
}
plan.prefix_lengths.resize(cursors.size());
// Age zero is the newest revision. Each age occurs at most once.
const auto max_age = plan.revision - plan.rows.back().revision;
if (max_age == n - 1) {
for (std::size_t i = 0; i < cursors.size(); ++i) {
plan.prefix_lengths[i] = static_cast<std::size_t>(
std::min<std::uint64_t>(plan.revision - cursors[i], n));
}
return plan;
}
// A bit records a live latest revision (including tombstones). Popcount then
// answers a prefix-rank query without probing the row vector. Bound startup
// work by both row count and reader count so sparse epochs fit in memory.
const auto words = max_age / 64 + 1;
if (cursors.size() >= 64 && n / 16 <= cursors.size() &&
words <= n && words <= cursors.size()) {
std::vector<batch_detail::RankWord> directory(static_cast<std::size_t>(words));
for (const auto& row : plan.rows) {
const auto age = plan.revision - row.revision;
directory[static_cast<std::size_t>(age / 64)].bits |=
std::uint64_t{1} << (age % 64);
}
std::size_t before = 0;
for (auto& word : directory) {
word.before = before;
before += batch_detail::count_bits(word.bits);
}
for (std::size_t i = 0; i < cursors.size(); ++i) {
const auto cutoff = plan.revision - cursors[i];
if (cutoff > max_age) {
plan.prefix_lengths[i] = n;
} else {
const auto& word = directory[static_cast<std::size_t>(cutoff / 64)];
const auto mask = (std::uint64_t{1} << (cutoff % 64)) - 1;
plan.prefix_lengths[i] = word.before + batch_detail::count_bits(word.bits & mask);
}
}
return plan;
}
if (words > n && n >= 2 && n <= cursors.size() && cursors.size() >= 64) {
// Partition sparse revision ages into at most 256 ranges.
// An empty bucket resolves in one lookup even when long idle intervals
// separate several clusters of recently overwritten keys.
const auto limit = std::min<std::size_t>(n, 256);
unsigned shift = 0;
while ((max_age >> shift) >= limit) ++shift;
const auto buckets = static_cast<std::size_t>(max_age >> shift) + 1;
std::vector<std::size_t> offsets(buckets + 1);
for (const auto& row : plan.rows) {
const auto age = plan.revision - row.revision;
++offsets[1 + static_cast<std::size_t>(age >> shift)];
}
for (std::size_t b = 1; b <= buckets; ++b) offsets[b] += offsets[b - 1];
for (std::size_t i = 0; i < cursors.size(); ++i) {
const auto age = plan.revision - cursors[i];
if (age > max_age) {
plan.prefix_lengths[i] = n;
} else {
const auto b = static_cast<std::size_t>(age >> shift);
plan.prefix_lengths[i] = batch_detail::prefix_rank(
plan.rows, offsets[b], offsets[b + 1], cursors[i]);
}
}
return plan;
}
for (std::size_t i = 0; i < cursors.size(); ++i) {
plan.prefix_lengths[i] = batch_detail::prefix_rank(plan.rows, 0, n, cursors[i]);
}
return plan;
}
} // namespace sincekit
#endif // SINCEKIT_BATCH_H_INCLUDED
|