#ifndef SINCEKIT_BATCH_H_INCLUDED #define SINCEKIT_BATCH_H_INCLUDED #include "sincekit.h" #include #include #include #include #include namespace sincekit { struct BatchRow { std::uint64_t revision; std::uint32_t id; bool deleted; }; struct BatchPlan { std::uint64_t revision = 0; std::vector rows; std::vector 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 inline std::size_t initial_rows(const SourceIndex& index, std::uint64_t since, std::size_t readers) { auto hint = static_cast(std::min( std::min(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(__builtin_popcountll(bits)); #else bits -= (bits >> 1) & 0x5555555555555555ULL; bits = (bits & 0x3333333333333333ULL) + ((bits >> 2) & 0x3333333333333333ULL); bits = (bits + (bits >> 4)) & 0x0f0f0f0f0f0f0f0fULL; return static_cast((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& 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 inline BatchPlan since_many(const SourceIndex& index, const std::vector& 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::min(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 directory(static_cast(words)); for (const auto& row : plan.rows) { const auto age = plan.revision - row.revision; directory[static_cast(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(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(n, 256); unsigned shift = 0; while ((max_age >> shift) >= limit) ++shift; const auto buckets = static_cast(max_age >> shift) + 1; std::vector offsets(buckets + 1); for (const auto& row : plan.rows) { const auto age = plan.revision - row.revision; ++offsets[1 + static_cast(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(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