Merge pull request 'Bounded sparse 3D pages with atomic revision-checked batches (#14)' (#30) from issue/14-sparse-page-table into main

This commit was merged in pull request #30.
This commit is contained in:
faumaray committed 2026-12-03 08:08:33 +00:00
commit b381d682c8
2 files changed
+516

No files matched your search

+323
View File
@@ -0,0 +1,323 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <span>
#include <utility>
#include <vector>
namespace Void::Containers
{
/// Finite sparse 3D page table with revision-checked atomic edit batches.
///
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
/// demand (a missing page reads as `empty` with revision 0) and bounded by
/// `Limits::max_pages`. `apply` validates every precondition, budget and
/// revision before touching the table; on failure nothing changes.
///
/// Batch semantics:
/// - Duplicate cell addresses in one batch are rejected.
/// - An edit whose value equals the current cell does not allocate a page and
/// does not bump a revision.
/// - `expected_revision` is checked against the page revision at batch start
/// (0 for a missing page).
/// - A changed page whose revision is already the maximum fails the batch.
/// - The result lists changed pages sorted by page identity with their new
/// revisions.
///
/// Single-threaded by contract; callers synchronize concurrent access.
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
{
public:
static_assert(PageSize > 0);
static constexpr std::size_t kPageSize = PageSize;
static constexpr std::size_t kCellsPerPage =
PageSize * PageSize * PageSize;
using Revision = std::uint64_t;
struct PageId {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const PageId&) const noexcept = default;
[[nodiscard]] bool
operator==(const PageId&) const noexcept = default;
};
struct CellAddress {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const CellAddress&) const noexcept = default;
[[nodiscard]] bool
operator==(const CellAddress&) const noexcept = default;
};
struct Edit {
CellAddress address;
Cell value;
std::optional<Revision> expected_revision{};
[[nodiscard]] bool
operator==(const Edit&) const = default;
};
struct Limits {
std::size_t max_pages{1024};
};
enum class EditStatus : std::uint8_t {
committed = 0,
/// A page's expected revision did not match the current one.
stale_revision,
/// A changed page already has the maximum revision.
revision_exhausted,
/// The batch would allocate more pages than the budget allows.
page_budget_exceeded,
/// The same cell address appears twice in the batch.
duplicate_edit,
};
struct ChangedPage {
PageId page;
Revision revision{0};
[[nodiscard]] bool
operator==(const ChangedPage&) const = default;
};
struct EditResult {
EditStatus status{EditStatus::committed};
std::vector<ChangedPage> changed{};
[[nodiscard]] bool committed() const noexcept
{
return status == EditStatus::committed;
}
};
struct PageState {
PageId page;
Revision revision{0};
std::array<Cell, kCellsPerPage> cells{};
[[nodiscard]] bool operator==(const PageState&) const = default;
};
struct State {
std::vector<PageState> pages;
[[nodiscard]] bool operator==(const State&) const = default;
};
explicit SparsePageTable(Limits limits = Limits{},
Cell empty = Cell{})
: limits_(limits)
, empty_(std::move(empty))
{
}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] const Cell& empty_value() const noexcept
{
return empty_;
}
[[nodiscard]] std::size_t page_count() const noexcept
{
return pages_.size();
}
/// Cell value; a missing page yields `empty_value()`.
[[nodiscard]] Cell get(CellAddress address) const
{
const auto [id, offset] = locate(address);
const auto found = pages_.find(id);
if (found == pages_.end()) {
return empty_;
}
return found->second.cells[offset];
}
/// Page revision, or `nullopt` when the page is not allocated.
[[nodiscard]] std::optional<Revision>
page_revision(PageId page) const
{
const auto found = pages_.find(page);
if (found == pages_.end()) {
return std::nullopt;
}
return found->second.revision;
}
/// Apply all edits or none.
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
{
if (edits.empty()) {
return EditResult{};
}
std::set<CellAddress> seen;
std::map<PageId, std::vector<const Edit*>> grouped;
for (const auto& edit : edits) {
if (!seen.insert(edit.address).second) {
return EditResult{.status =
EditStatus::duplicate_edit};
}
grouped[page_of(edit.address)].push_back(&edit);
}
std::map<PageId, bool> changes;
std::size_t new_pages = 0;
for (const auto& [id, page_edits] : grouped) {
const auto found = pages_.find(id);
const Page* page =
found == pages_.end() ? nullptr : &found->second;
const Revision revision = page == nullptr ? 0
: page->revision;
for (const Edit* edit : page_edits) {
if (edit->expected_revision.has_value() &&
*edit->expected_revision != revision) {
return EditResult{
.status = EditStatus::stale_revision};
}
}
bool changed = false;
for (const Edit* edit : page_edits) {
const auto offset = offset_of(edit->address);
const Cell& current =
page == nullptr ? empty_ : page->cells[offset];
if (!(current == edit->value)) {
changed = true;
break;
}
}
if (!changed) {
continue;
}
if (revision ==
std::numeric_limits<Revision>::max()) {
return EditResult{
.status = EditStatus::revision_exhausted};
}
changes.emplace(id, true);
if (page == nullptr) {
++new_pages;
}
}
if (pages_.size() + new_pages > limits_.max_pages) {
return EditResult{.status =
EditStatus::page_budget_exceeded};
}
EditResult result;
for (const auto& [id, changed] : changes) {
(void)changed;
auto& page = pages_[id];
for (const Edit* edit : grouped.at(id)) {
page.cells[offset_of(edit->address)] = edit->value;
}
++page.revision;
result.changed.push_back(
ChangedPage{.page = id, .revision = page.revision});
}
return result;
}
[[nodiscard]] State save() const
{
State state;
state.pages.reserve(pages_.size());
for (const auto& [id, page] : pages_) {
state.pages.push_back(PageState{
.page = id, .revision = page.revision, .cells = page.cells});
}
return state;
}
/// Restore saved pages. Rejects duplicate page ids, more pages than the
/// limit, or a page with no revision left for an edit.
[[nodiscard]] static std::optional<SparsePageTable>
restore(State state, Limits limits = Limits{},
Cell empty = Cell{})
{
if (state.pages.size() > limits.max_pages) {
return std::nullopt;
}
SparsePageTable table{limits, std::move(empty)};
for (auto& saved : state.pages) {
if (!table.pages_
.emplace(saved.page,
Page{.cells = saved.cells,
.revision = saved.revision})
.second) {
return std::nullopt;
}
}
return table;
}
private:
struct Page {
std::array<Cell, kCellsPerPage> cells{};
Revision revision{0};
};
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
split(std::int64_t coordinate)
{
constexpr auto size = static_cast<std::int64_t>(PageSize);
std::int64_t page = coordinate / size;
std::int64_t offset = coordinate % size;
if (offset < 0) {
--page;
offset += size;
}
return {page, static_cast<std::size_t>(offset)};
}
[[nodiscard]] static PageId page_of(CellAddress address)
{
return PageId{.x = split(address.x).first,
.y = split(address.y).first,
.z = split(address.z).first};
}
[[nodiscard]] static std::size_t offset_of(CellAddress address)
{
const auto [px, ox] = split(address.x);
const auto [py, oy] = split(address.y);
const auto [pz, oz] = split(address.z);
(void)px;
(void)py;
(void)pz;
return (oz * PageSize + oy) * PageSize + ox;
}
[[nodiscard]] static std::pair<PageId, std::size_t>
locate(CellAddress address)
{
return {page_of(address), offset_of(address)};
}
Limits limits_{};
Cell empty_{};
std::map<PageId, Page> pages_;
};
} // namespace Void::Containers
@@ -0,0 +1,193 @@
#include <Void/Containers/SparsePageTable.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <limits>
#include <optional>
#include <vector>
namespace
{
using Table = Void::Containers::SparsePageTable<std::uint32_t, 2>;
using Address = Table::CellAddress;
using Changed = Table::ChangedPage;
using Edit = Table::Edit;
using EditStatus = Table::EditStatus;
using Page = Table::PageId;
using Revision = Table::Revision;
constexpr std::uint32_t kEmpty = 0;
[[nodiscard]] Address at(std::int64_t x, std::int64_t y = 0,
std::int64_t z = 0)
{
return Address{.x = x, .y = y, .z = z};
}
[[nodiscard]] Page page(std::int64_t x, std::int64_t y = 0,
std::int64_t z = 0)
{
return Page{.x = x, .y = y, .z = z};
}
[[nodiscard]] Edit edit(Address address, std::uint32_t value,
std::optional<Revision> expected = std::nullopt)
{
return Edit{.address = address,
.value = value,
.expected_revision = expected};
}
[[nodiscard]] bool same_changes(const std::vector<Changed>& lhs,
const std::vector<Changed>& rhs)
{
return lhs == rhs;
}
} // namespace
Void::Testing::Test sparse_page_edit_spans_adjacent_pages()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(1), 7), edit(at(2), 8)};
auto result = table.apply(edits);
Void::Testing::require(result.committed());
Void::Testing::require(result.changed.size() == 2);
// Changed pages are reported in page order.
Void::Testing::expect(result.changed[0] ==
Changed{.page = page(0), .revision = 1});
Void::Testing::expect(result.changed[1] ==
Changed{.page = page(1), .revision = 1});
Void::Testing::expect_eq(table.get(at(1)), 7u);
Void::Testing::expect_eq(table.get(at(2)), 8u);
Void::Testing::expect_eq(table.page_count(), std::size_t{2});
}
Void::Testing::Test sparse_page_batch_is_atomic_on_stale_revision()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit first[] = {edit(at(1), 7)};
Void::Testing::require(table.apply(first).committed());
const Edit batch[] = {edit(at(0), 1, Revision{1}),
edit(at(2), 9, Revision{5})};
auto result = table.apply(batch);
Void::Testing::expect(result.status == EditStatus::stale_revision);
// Neither page changed.
Void::Testing::expect_eq(table.get(at(0)), kEmpty);
Void::Testing::expect_eq(table.get(at(1)), 7u);
Void::Testing::expect_eq(table.get(at(2)), kEmpty);
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
Void::Testing::expect(!table.page_revision(page(1)).has_value());
}
Void::Testing::Test sparse_page_budget_exceeded()
{
Table table{Table::Limits{.max_pages = 1}};
const Edit edits[] = {edit(at(0), 1), edit(at(2), 2)};
auto result = table.apply(edits);
Void::Testing::expect(result.status == EditStatus::page_budget_exceeded);
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
}
Void::Testing::Test sparse_page_revision_exhausted()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit first[] = {edit(at(0), 1)};
Void::Testing::require(table.apply(first).committed());
auto state = table.save();
Void::Testing::require(state.pages.size() == 1);
state.pages[0].revision = std::numeric_limits<Revision>::max();
auto restored = Table::restore(state, Table::Limits{.max_pages = 4});
Void::Testing::require(restored.has_value());
const Edit second[] = {edit(at(0), 2)};
auto result = restored->apply(second);
Void::Testing::expect(result.status == EditStatus::revision_exhausted);
Void::Testing::expect_eq(restored->get(at(0)), 1u);
}
Void::Testing::Test sparse_page_duplicate_edit_rejected()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(0), 1), edit(at(0), 2)};
auto result = table.apply(edits);
Void::Testing::expect(result.status == EditStatus::duplicate_edit);
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
}
Void::Testing::Test sparse_page_unchanged_value_does_not_bump()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit noop[] = {edit(at(0), kEmpty)};
auto first = table.apply(noop);
Void::Testing::require(first.committed());
Void::Testing::expect(first.changed.empty());
Void::Testing::expect_eq(table.page_count(), std::size_t{0});
const Edit write[] = {edit(at(0), 5)};
Void::Testing::require(table.apply(write).committed());
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
const Edit repeat[] = {edit(at(0), 5)};
auto again = table.apply(repeat);
Void::Testing::require(again.committed());
Void::Testing::expect(again.changed.empty());
Void::Testing::expect_eq(*table.page_revision(page(0)), Revision{1});
}
Void::Testing::Test sparse_page_permuted_batch_matches()
{
Table first{Table::Limits{.max_pages = 4}};
Table second{Table::Limits{.max_pages = 4}};
const std::vector<Edit> ordered{edit(at(0), 1), edit(at(1), 2),
edit(at(2), 3), edit(at(5), 4)};
std::vector<Edit> permuted{ordered[2], ordered[0], ordered[3], ordered[1]};
auto a = first.apply(ordered);
auto b = second.apply(permuted);
Void::Testing::require(a.committed() && b.committed());
Void::Testing::expect(same_changes(a.changed, b.changed));
for (const auto& edit : ordered) {
Void::Testing::expect_eq(first.get(edit.address),
second.get(edit.address));
}
}
Void::Testing::Test sparse_page_negative_coordinates()
{
Table table{Table::Limits{.max_pages = 4}};
const Edit edits[] = {edit(at(-1), 3), edit(at(-2), 4), edit(at(-3), 5)};
auto result = table.apply(edits);
Void::Testing::require(result.committed());
// PageSize 2: -1 and -2 live in page -1 (offsets 1 and 0); -3 in page -2.
Void::Testing::expect_eq(*table.page_revision(page(-1)), Revision{1});
Void::Testing::expect_eq(*table.page_revision(page(-2)), Revision{1});
Void::Testing::expect_eq(table.get(at(-1)), 3u);
Void::Testing::expect_eq(table.get(at(-2)), 4u);
Void::Testing::expect_eq(table.get(at(-3)), 5u);
}
Void::Testing::Test sparse_page_restore_rejects_invalid_state()
{
Table::State duplicate;
duplicate.pages.push_back(
Table::PageState{.page = page(0), .revision = 1});
duplicate.pages.push_back(
Table::PageState{.page = page(0), .revision = 2});
Void::Testing::expect(
!Table::restore(duplicate, Table::Limits{.max_pages = 4}).has_value());
Table::State too_many;
too_many.pages.push_back(
Table::PageState{.page = page(0), .revision = 1});
too_many.pages.push_back(
Table::PageState{.page = page(1), .revision = 1});
Void::Testing::expect(
!Table::restore(too_many, Table::Limits{.max_pages = 1}).has_value());
}