Merge pull request 'Atomic reservations and repeatable transfers in an account ledger (#8)' (#24) from issue/8-account-ledger into main

This commit was merged in pull request #24.
This commit is contained in:
faumaray committed 2026-12-03 08:08:22 +00:00
commit 6c5c2dcd93
2 files changed
+643

No files matched your search

+416
View File
@@ -0,0 +1,416 @@
#pragma once
#include <algorithm>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Void::Containers
{
using LedgerQuantity = std::uint64_t;
using LedgerAccountKey = std::string;
using LedgerOperationId = std::string;
struct LedgerDebit {
LedgerAccountKey account;
LedgerQuantity quantity{0};
[[nodiscard]] auto operator<=>(const LedgerDebit&) const noexcept = default;
[[nodiscard]] bool operator==(const LedgerDebit&) const noexcept = default;
};
enum class LedgerStatus : std::uint8_t {
committed = 0,
/// The operation already committed; the recorded outcome is returned.
replayed,
insufficient_balance,
capacity_exhausted,
overflow,
unknown_operation,
unknown_account,
/// Operation id reused with a different request or a forbidden phase.
invalid_state,
/// A released reservation cannot be delivered.
released,
limit_exceeded,
};
enum class ReservationPhase : std::uint8_t {
held = 0,
delivered,
released,
};
struct LedgerResult {
LedgerStatus status{LedgerStatus::unknown_operation};
ReservationPhase phase{ReservationPhase::held};
LedgerOperationId operation;
[[nodiscard]] bool committed() const noexcept
{
return status == LedgerStatus::committed ||
status == LedgerStatus::replayed;
}
[[nodiscard]] bool operator==(const LedgerResult&) const noexcept = default;
};
struct LedgerLimits {
std::size_t max_accounts{1024};
std::size_t max_operations{4096};
};
/// In-memory, restorable account ledger with atomic multi-account
/// reservations and repeatable transfers.
///
/// Accounts are caller-keyed and carry an owner, a balance and a capacity.
/// `reserve` debits one or more accounts atomically into a held reservation;
/// `transfer` gives the reserved quantity to a destination account (the next
/// owner); `release` returns it to the sources without changing ownership.
///
/// Every committed phase is recorded under its operation id, so repeating the
/// same request returns the recorded outcome instead of applying it twice.
/// The state is a plain value: `save()` can be persisted and `restore()`d, and
/// a replay after restoring a partially completed transfer still applies once.
/// Failed attempts (insufficient balance, capacity, overflow) change nothing
/// and are not recorded, so they can be retried after conditions change.
///
/// Single-threaded by contract; callers synchronize concurrent access.
class AccountLedger
{
public:
using Limits = LedgerLimits;
struct AccountState {
std::string owner;
LedgerQuantity balance{0};
LedgerQuantity capacity{
std::numeric_limits<LedgerQuantity>::max()};
[[nodiscard]] auto
operator<=>(const AccountState&) const noexcept = default;
[[nodiscard]] bool
operator==(const AccountState&) const noexcept = default;
};
struct OperationState {
/// Normalized (aggregated and sorted) debits of the reservation.
std::vector<LedgerDebit> sources;
ReservationPhase phase{ReservationPhase::held};
LedgerAccountKey destination;
[[nodiscard]] auto
operator<=>(const OperationState&) const noexcept = default;
[[nodiscard]] bool
operator==(const OperationState&) const noexcept = default;
};
struct State {
std::map<LedgerAccountKey, AccountState> accounts;
std::map<LedgerOperationId, OperationState> operations;
[[nodiscard]] auto
operator<=>(const State&) const noexcept = default;
[[nodiscard]] bool
operator==(const State&) const noexcept = default;
};
explicit AccountLedger(Limits limits = Limits{}) : limits_(limits) {}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] bool create_account(const LedgerAccountKey& key,
std::string owner,
LedgerQuantity balance = 0,
LedgerQuantity capacity =
std::numeric_limits<
LedgerQuantity>::max())
{
if (balance > capacity ||
accounts_.size() >= limits_.max_accounts ||
accounts_.contains(key)) {
return false;
}
accounts_.emplace(key,
AccountState{.owner = std::move(owner),
.balance = balance,
.capacity = capacity});
return true;
}
[[nodiscard]] bool set_capacity(const LedgerAccountKey& key,
LedgerQuantity capacity)
{
const auto found = accounts_.find(key);
if (found == accounts_.end() ||
found->second.balance > capacity) {
return false;
}
found->second.capacity = capacity;
return true;
}
[[nodiscard]] std::optional<AccountState>
account(const LedgerAccountKey& key) const
{
const auto found = accounts_.find(key);
if (found == accounts_.end()) {
return std::nullopt;
}
return found->second;
}
/// Sum of all balances plus quantities held in reservations.
[[nodiscard]] LedgerQuantity total() const
{
LedgerQuantity sum = 0;
for (const auto& [key, account] : accounts_) {
(void)key;
sum += account.balance;
}
for (const auto& [id, operation] : operations_) {
(void)id;
if (operation.phase == ReservationPhase::held) {
for (const auto& debit : operation.sources) {
sum += debit.quantity;
}
}
}
return sum;
}
[[nodiscard]] std::size_t account_count() const noexcept
{
return accounts_.size();
}
[[nodiscard]] std::size_t operation_count() const noexcept
{
return operations_.size();
}
/// Atomically debit every source into a held reservation.
[[nodiscard]] LedgerResult
reserve(const LedgerOperationId& operation,
std::vector<LedgerDebit> debits)
{
for (const auto& debit : debits) {
if (debit.account.empty() || debit.quantity == 0) {
return LedgerResult{.status = LedgerStatus::invalid_state,
.operation = operation};
}
}
auto normalized = normalize(std::move(debits));
if (!normalized.has_value()) {
return LedgerResult{.status = LedgerStatus::overflow,
.operation = operation};
}
if (const auto existing = operations_.find(operation);
existing != operations_.end()) {
if (existing->second.sources != *normalized) {
return LedgerResult{.status = LedgerStatus::invalid_state,
.phase = existing->second.phase,
.operation = operation};
}
return LedgerResult{.status = LedgerStatus::replayed,
.phase = existing->second.phase,
.operation = operation};
}
if (operations_.size() >= limits_.max_operations) {
return LedgerResult{.status = LedgerStatus::limit_exceeded,
.operation = operation};
}
for (const auto& debit : *normalized) {
const auto found = accounts_.find(debit.account);
if (found == accounts_.end()) {
return LedgerResult{
.status = LedgerStatus::unknown_account,
.operation = operation};
}
if (found->second.balance < debit.quantity) {
return LedgerResult{
.status = LedgerStatus::insufficient_balance,
.operation = operation};
}
}
// All preconditions hold: apply every debit.
for (const auto& debit : *normalized) {
accounts_.at(debit.account).balance -= debit.quantity;
}
operations_.emplace(operation,
OperationState{.sources = std::move(*normalized),
.phase = ReservationPhase::held,
.destination = {}});
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::held,
.operation = operation};
}
/// Return a held reservation to its sources. Ownership is unchanged.
[[nodiscard]] LedgerResult release(const LedgerOperationId& operation)
{
const auto found = operations_.find(operation);
if (found == operations_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_operation,
.operation = operation};
}
if (found->second.phase == ReservationPhase::released) {
return LedgerResult{.status = LedgerStatus::replayed,
.phase = ReservationPhase::released,
.operation = operation};
}
if (found->second.phase == ReservationPhase::delivered) {
return LedgerResult{
.status = LedgerStatus::invalid_state,
.phase = ReservationPhase::delivered,
.operation = operation};
}
for (const auto& debit : found->second.sources) {
accounts_.at(debit.account).balance += debit.quantity;
}
found->second.phase = ReservationPhase::released;
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::released,
.operation = operation};
}
/// Deliver a held reservation to `destination` (the next owner).
/// On capacity/overflow failure nothing changes and the reservation
/// stays held, so the caller can retry or release it.
[[nodiscard]] LedgerResult
transfer(const LedgerOperationId& operation,
const LedgerAccountKey& destination)
{
const auto found = operations_.find(operation);
if (found == operations_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_operation,
.operation = operation};
}
if (found->second.phase == ReservationPhase::released) {
return LedgerResult{.status = LedgerStatus::released,
.phase = ReservationPhase::released,
.operation = operation};
}
if (found->second.phase == ReservationPhase::delivered) {
return LedgerResult{
.status = found->second.destination == destination
? LedgerStatus::replayed
: LedgerStatus::invalid_state,
.phase = ReservationPhase::delivered,
.operation = operation};
}
const auto target = accounts_.find(destination);
if (target == accounts_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_account,
.phase = ReservationPhase::held,
.operation = operation};
}
LedgerQuantity quantity = 0;
for (const auto& debit : found->second.sources) {
if (debit.quantity >
std::numeric_limits<LedgerQuantity>::max() - quantity) {
return LedgerResult{.status = LedgerStatus::overflow,
.phase = ReservationPhase::held,
.operation = operation};
}
quantity += debit.quantity;
}
if (quantity >
target->second.capacity - target->second.balance) {
return LedgerResult{.status = LedgerStatus::capacity_exhausted,
.phase = ReservationPhase::held,
.operation = operation};
}
target->second.balance += quantity;
found->second.phase = ReservationPhase::delivered;
found->second.destination = destination;
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::delivered,
.operation = operation};
}
[[nodiscard]] State save() const
{
return State{.accounts = accounts_, .operations = operations_};
}
/// Rebuild a ledger from `save()` output. Rejects states that violate
/// the limits or the balance/capacity and reservation invariants.
[[nodiscard]] static std::optional<AccountLedger>
restore(State state, Limits limits = Limits{})
{
if (state.accounts.size() > limits.max_accounts ||
state.operations.size() > limits.max_operations) {
return std::nullopt;
}
for (const auto& [key, account] : state.accounts) {
(void)key;
if (account.balance > account.capacity) {
return std::nullopt;
}
}
for (const auto& [id, operation] : state.operations) {
(void)id;
if (operation.sources.empty()) {
return std::nullopt;
}
for (const auto& debit : operation.sources) {
if (!state.accounts.contains(debit.account)) {
return std::nullopt;
}
}
if (operation.phase == ReservationPhase::delivered &&
!state.accounts.contains(operation.destination)) {
return std::nullopt;
}
}
AccountLedger ledger{limits};
ledger.accounts_ = std::move(state.accounts);
ledger.operations_ = std::move(state.operations);
return ledger;
}
private:
[[nodiscard]] static std::optional<std::vector<LedgerDebit>>
normalize(std::vector<LedgerDebit> debits)
{
std::map<LedgerAccountKey, LedgerQuantity> aggregated;
for (const auto& debit : debits) {
LedgerQuantity& sum = aggregated[debit.account];
if (debit.quantity >
std::numeric_limits<LedgerQuantity>::max() - sum) {
return std::nullopt;
}
sum += debit.quantity;
}
std::vector<LedgerDebit> normalized;
normalized.reserve(aggregated.size());
for (auto& [account, quantity] : aggregated) {
normalized.push_back(
LedgerDebit{.account = std::move(account),
.quantity = quantity});
}
return normalized;
}
Limits limits_{};
std::map<LedgerAccountKey, AccountState> accounts_;
std::map<LedgerOperationId, OperationState> operations_;
};
} // namespace Void::Containers
@@ -0,0 +1,227 @@
#include <Void/Containers/AccountLedger.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <limits>
#include <string>
#include <vector>
namespace
{
using Void::Containers::AccountLedger;
using Void::Containers::LedgerDebit;
using Void::Containers::LedgerQuantity;
using Void::Containers::LedgerStatus;
using Void::Containers::ReservationPhase;
[[nodiscard]] LedgerDebit debit(std::string account, LedgerQuantity quantity)
{
return LedgerDebit{.account = std::move(account), .quantity = quantity};
}
[[nodiscard]] LedgerQuantity balance(const AccountLedger& ledger,
const std::string& account)
{
return ledger.account(account)->balance;
}
} // namespace
Void::Testing::Test account_ledger_reserve_transfer_conserves_total()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 10, 10));
Void::Testing::require(ledger.create_account("b", "bob", 0, 10));
auto reserved = ledger.reserve("op1", {debit("a", 4)});
Void::Testing::expect(reserved.status == LedgerStatus::committed);
Void::Testing::expect(reserved.phase == ReservationPhase::held);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{6});
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
auto delivered = ledger.transfer("op1", "b");
Void::Testing::expect(delivered.status == LedgerStatus::committed);
Void::Testing::expect(delivered.phase == ReservationPhase::delivered);
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
Void::Testing::expect_eq(ledger.account("b")->owner, std::string{"bob"});
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
// Repeating the same delivery applies nothing twice.
auto replay = ledger.transfer("op1", "b");
Void::Testing::expect(replay.status == LedgerStatus::replayed);
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
Void::Testing::expect_eq(ledger.total(), LedgerQuantity{10});
// A different destination for the same operation is a conflict.
auto conflict = ledger.transfer("op1", "a");
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{4});
}
Void::Testing::Test account_ledger_two_claimants_last_unit()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 1));
Void::Testing::expect(ledger.reserve("first", {debit("a", 1)}).status ==
LedgerStatus::committed);
auto second = ledger.reserve("second", {debit("a", 1)});
Void::Testing::expect(second.status == LedgerStatus::insufficient_balance);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{0});
Void::Testing::expect(ledger.release("first").status ==
LedgerStatus::committed);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{1});
Void::Testing::expect(ledger.reserve("second", {debit("a", 1)}).status ==
LedgerStatus::committed);
}
Void::Testing::Test account_ledger_multi_account_reservation_is_atomic()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 5));
Void::Testing::require(ledger.create_account("b", "bob", 1));
auto failed = ledger.reserve("op", {debit("a", 3), debit("b", 2)});
Void::Testing::expect(failed.status == LedgerStatus::insufficient_balance);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{5});
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{1});
Void::Testing::expect_eq(ledger.operation_count(), std::size_t{0});
}
Void::Testing::Test account_ledger_cancel_before_pickup()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 7));
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
auto released = ledger.release("op");
Void::Testing::expect(released.status == LedgerStatus::committed);
Void::Testing::expect(released.phase == ReservationPhase::released);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
Void::Testing::expect(ledger.release("op").status == LedgerStatus::replayed);
Void::Testing::expect(ledger.transfer("op", "a").status ==
LedgerStatus::released);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
}
Void::Testing::Test account_ledger_cancel_during_delivery()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 7));
Void::Testing::require(ledger.create_account("b", "bob", 0, 2));
Void::Testing::require(ledger.reserve("op", {debit("a", 3)}).committed());
auto blocked = ledger.transfer("op", "b");
Void::Testing::expect(blocked.status == LedgerStatus::capacity_exhausted);
Void::Testing::expect(blocked.phase == ReservationPhase::held);
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
// The reservation is still held and can be cancelled.
Void::Testing::expect(ledger.release("op").status ==
LedgerStatus::committed);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{7});
}
Void::Testing::Test account_ledger_replay_after_restore()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 10));
Void::Testing::require(ledger.create_account("b", "bob", 0));
Void::Testing::require(ledger.reserve("op", {debit("a", 4)}).committed());
const auto partially_completed = ledger.save();
auto restored = AccountLedger::restore(partially_completed);
Void::Testing::require(restored.has_value());
Void::Testing::expect(restored->transfer("op", "b").status ==
LedgerStatus::committed);
Void::Testing::expect_eq(balance(*restored, "b"), LedgerQuantity{4});
const auto delivered = restored->save();
auto after_delivery = AccountLedger::restore(delivered);
Void::Testing::require(after_delivery.has_value());
Void::Testing::expect(after_delivery->transfer("op", "b").status ==
LedgerStatus::replayed);
Void::Testing::expect_eq(balance(*after_delivery, "b"), LedgerQuantity{4});
// Restoring the earlier snapshot replays the delivery exactly once.
auto replay_world = AccountLedger::restore(partially_completed);
Void::Testing::require(replay_world.has_value());
Void::Testing::expect(replay_world->transfer("op", "b").status ==
LedgerStatus::committed);
Void::Testing::expect_eq(balance(*replay_world, "b"), LedgerQuantity{4});
}
Void::Testing::Test account_ledger_overflow_is_rejected()
{
constexpr auto kMax = std::numeric_limits<LedgerQuantity>::max();
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a1", "alice", kMax));
Void::Testing::require(ledger.create_account("a2", "alice", kMax));
Void::Testing::require(ledger.create_account("b", "bob", 0));
Void::Testing::require(
ledger.reserve("op", {debit("a1", kMax), debit("a2", kMax)})
.committed());
// The reserved total cannot be represented in one quantity.
auto overflowed = ledger.transfer("op", "b");
Void::Testing::expect(overflowed.status == LedgerStatus::overflow);
Void::Testing::expect_eq(balance(ledger, "b"), LedgerQuantity{0});
Void::Testing::expect(ledger.release("op").status ==
LedgerStatus::committed);
}
Void::Testing::Test account_ledger_operation_id_conflict()
{
AccountLedger ledger;
Void::Testing::require(ledger.create_account("a", "alice", 10));
Void::Testing::require(ledger.reserve("op", {debit("a", 1)}).committed());
auto conflict = ledger.reserve("op", {debit("a", 2)});
Void::Testing::expect(conflict.status == LedgerStatus::invalid_state);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
}
Void::Testing::Test account_ledger_account_limits()
{
AccountLedger ledger;
Void::Testing::expect(!ledger.create_account("a", "alice", 5, 4));
Void::Testing::require(ledger.create_account("a", "alice", 5, 10));
Void::Testing::expect(!ledger.create_account("a", "other", 0, 10));
Void::Testing::expect(!ledger.set_capacity("a", 4));
Void::Testing::require(ledger.set_capacity("a", 8));
}
Void::Testing::Test account_ledger_operation_limit()
{
AccountLedger ledger{AccountLedger::Limits{.max_accounts = 4,
.max_operations = 1}};
Void::Testing::require(ledger.create_account("a", "alice", 10));
Void::Testing::require(ledger.reserve("one", {debit("a", 1)}).committed());
auto limited = ledger.reserve("two", {debit("a", 1)});
Void::Testing::expect(limited.status == LedgerStatus::limit_exceeded);
Void::Testing::expect_eq(balance(ledger, "a"), LedgerQuantity{9});
}
Void::Testing::Test account_ledger_restore_rejects_invalid_state()
{
AccountLedger::State bad_balance;
bad_balance.accounts.emplace(
"a", AccountLedger::AccountState{.owner = "alice",
.balance = 5,
.capacity = 4});
Void::Testing::expect(!AccountLedger::restore(bad_balance).has_value());
AccountLedger::State dangling_operation;
dangling_operation.accounts.emplace(
"a", AccountLedger::AccountState{.owner = "alice", .balance = 1});
dangling_operation.operations.emplace(
"op", AccountLedger::OperationState{
.sources = {debit("missing", 1)},
.phase = ReservationPhase::held,
.destination = {}});
Void::Testing::expect(!AccountLedger::restore(dangling_operation).has_value());
}