Files
Library/tests/standalone/Algorithms/Graph.cpp
T

304 lines
12 KiB
C++

#include <Void/Algorithms/Graph.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stop_token>
#include <vector>
namespace
{
struct HugeMockGraph {
std::size_t count{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return count; }
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t) const noexcept { return {}; }
};
struct VersionedChainGraph {
std::vector<std::vector<std::size_t>> adj;
mutable std::atomic<std::uint64_t> ver{1};
std::size_t mutate_after_reads{std::numeric_limits<std::size_t>::max()};
mutable std::size_t reads{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); }
[[nodiscard]] std::uint64_t version() const noexcept
{
return ver.load(std::memory_order_acquire);
}
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
{
const std::size_t r = ++reads;
if (r >= mutate_after_reads) {
ver.fetch_add(1, std::memory_order_release);
}
return adj[u];
}
};
struct CancellingGraph {
std::vector<std::vector<std::size_t>> adj;
std::stop_source* stop_src{nullptr};
std::size_t cancel_after_reads{std::numeric_limits<std::size_t>::max()};
mutable std::size_t reads{0};
[[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); }
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
{
const std::size_t r = ++reads;
if (stop_src != nullptr && r >= cancel_after_reads) {
stop_src->request_stop();
}
return adj[u];
}
};
} // namespace
Void::Testing::Test graph_bfs_dfs_shortest_path_and_csr_views()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::bfs;
using Void::Algorithms::dfs;
using Void::Algorithms::shortest_path_unweighted;
// 0 -> {1, 2}, 1 -> {3, 4}, 2 -> {4}, 3 -> {5}, 4 -> {}, 5 -> {}, 6 (isolated)
const std::vector<std::vector<std::size_t>> adj{
{1, 2},
{3, 4},
{4},
{5},
{},
{},
{},
};
const AdjacencyView list_view{adj};
const auto bfs_res = bfs(list_view, 0);
Void::Testing::require(bfs_res.has_value());
Void::Testing::expect_eq(bfs_res->order.size(), std::size_t{6});
Void::Testing::expect_eq(bfs_res->order[0], std::size_t{0});
Void::Testing::expect_eq(bfs_res->depth[5], std::size_t{3});
Void::Testing::expect_eq(bfs_res->depth[6], Void::Algorithms::TraversalResult::npos);
Void::Testing::expect_eq(bfs_res->parent[4], std::size_t{1});
const auto dfs_res = dfs(list_view, 0);
Void::Testing::require(dfs_res.has_value());
Void::Testing::expect_eq(dfs_res->order.size(), std::size_t{6});
Void::Testing::expect_eq(dfs_res->order[0], std::size_t{0});
Void::Testing::expect_eq(dfs_res->order[1], std::size_t{1});
Void::Testing::expect_eq(dfs_res->order[2], std::size_t{3});
Void::Testing::expect_eq(dfs_res->order[3], std::size_t{5});
Void::Testing::expect_eq(dfs_res->order[4], std::size_t{4});
Void::Testing::expect_eq(dfs_res->order[5], std::size_t{2});
const auto sp_found = shortest_path_unweighted(list_view, 0, 5);
Void::Testing::require(sp_found.has_value());
Void::Testing::expect(sp_found->found);
Void::Testing::expect_eq(sp_found->distance, std::size_t{3});
Void::Testing::expect_eq(sp_found->path.size(), std::size_t{4});
Void::Testing::expect_eq(sp_found->path[0], std::size_t{0});
Void::Testing::expect_eq(sp_found->path[1], std::size_t{1});
Void::Testing::expect_eq(sp_found->path[2], std::size_t{3});
Void::Testing::expect_eq(sp_found->path[3], std::size_t{5});
const auto sp_self = shortest_path_unweighted(list_view, 2, 2);
Void::Testing::require(sp_self.has_value());
Void::Testing::expect(sp_self->found);
Void::Testing::expect_eq(sp_self->distance, std::size_t{0});
Void::Testing::expect_eq(sp_self->path.size(), std::size_t{1});
const auto sp_missing = shortest_path_unweighted(list_view, 0, 6);
Void::Testing::require(sp_missing.has_value());
Void::Testing::expect(!sp_missing->found);
Void::Testing::expect(sp_missing->path.empty());
// Equivalent CSR view validation
const std::vector<std::size_t> offsets{0, 2, 4, 5, 6, 6, 6, 6};
const std::vector<std::size_t> edges{1, 2, 3, 4, 4, 5};
const auto csr_res = AdjacencyView::try_from_csr(offsets, edges);
Void::Testing::require(csr_res.has_value());
const auto csr_sp = shortest_path_unweighted(*csr_res, 0, 4);
Void::Testing::require(csr_sp.has_value());
Void::Testing::expect_eq(csr_sp->distance, std::size_t{2});
// Malformed CSR rejected
const std::vector<std::size_t> bad_offsets{0, 3, 2};
Void::Testing::expect(
AdjacencyView::try_from_csr(bad_offsets, edges).error().code ==
AlgorithmError::Code::invalid_input);
}
Void::Testing::Test graph_topological_order_and_cycle_witness()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::topological_order;
// Empty graph is a valid DAG
const std::vector<std::vector<std::size_t>> empty_adj{};
const auto empty_topo = topological_order(AdjacencyView{empty_adj});
Void::Testing::require(empty_topo.has_value());
Void::Testing::expect(empty_topo->order.empty());
// DAG: 0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> {4}
const std::vector<std::vector<std::size_t>> dag{
{1, 2},
{3},
{3},
{4},
{},
};
const auto topo = topological_order(AdjacencyView{dag});
Void::Testing::require(topo.has_value());
Void::Testing::expect_eq(topo->order.size(), std::size_t{5});
for (std::size_t u = 0; u < dag.size(); ++u) {
for (const std::size_t v : dag[u]) {
Void::Testing::expect(topo->position[u] < topo->position[v]);
}
}
// Cyclic graph: 0 -> 1 -> 2 -> 3 -> 1 plus tail 4
const std::vector<std::vector<std::size_t>> cyclic{
{1},
{2},
{3},
{1, 4},
{},
};
const AdjacencyView cyclic_view{cyclic};
const auto cyc_res = topological_order(cyclic_view);
Void::Testing::expect(!cyc_res.has_value());
Void::Testing::expect(cyc_res.error().code == AlgorithmError::Code::cycle_detected);
const auto& witness = cyc_res.error().cycle;
Void::Testing::require(witness.size() >= 2);
Void::Testing::expect_eq(witness.front(), witness.back());
// Every consecutive pair in witness must be a real edge in the graph
for (std::size_t i = 0; i + 1 < witness.size(); ++i) {
const auto nbrs = cyclic_view.neighbors(witness[i]);
bool found_edge = false;
for (const std::size_t x : nbrs) {
if (x == witness[i + 1]) {
found_edge = true;
break;
}
}
Void::Testing::expect(found_edge);
}
// Self-loop cycle witness [u, u]
const std::vector<std::vector<std::size_t>> self_loop{{0}};
const auto self_res = topological_order(AdjacencyView{self_loop});
Void::Testing::expect(!self_res.has_value());
Void::Testing::expect(self_res.error().code == AlgorithmError::Code::cycle_detected);
Void::Testing::expect_eq(self_res.error().cycle.size(), std::size_t{2});
Void::Testing::expect_eq(self_res.error().cycle[0], std::size_t{0});
Void::Testing::expect_eq(self_res.error().cycle[1], std::size_t{0});
}
Void::Testing::Test graph_bounds_limits_overflow_and_deep_chain()
{
using Void::Algorithms::AdjacencyView;
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::WorkLimits;
using Void::Algorithms::bfs;
using Void::Algorithms::dfs;
using Void::Algorithms::shortest_path_unweighted;
using Void::Algorithms::topological_order;
// Overflow before scratch allocation on absurd vertex_count()
const HugeMockGraph huge{std::numeric_limits<std::size_t>::max()};
const WorkLimits huge_v_limits{
.max_vertices = std::numeric_limits<std::size_t>::max(),
.max_scratch_bytes = std::numeric_limits<std::size_t>::max(),
};
const auto ovf = bfs(huge, 0, huge_v_limits);
Void::Testing::expect(!ovf.has_value());
Void::Testing::expect(ovf.error().code == AlgorithmError::Code::overflow);
// Scratch memory limit exceeded cleanly
const std::vector<std::vector<std::size_t>> small{{1}, {}};
const auto small_scratch = bfs(
AdjacencyView{small},
0,
WorkLimits{.max_scratch_bytes = 8});
Void::Testing::expect(!small_scratch.has_value());
Void::Testing::expect(small_scratch.error().code == AlgorithmError::Code::limit_exceeded);
// Out-of-range neighbor index rejected safely without UB
const std::vector<std::vector<std::size_t>> bad_edge{{99}, {}};
const auto bad_nbr = bfs(AdjacencyView{bad_edge}, 0);
Void::Testing::expect(!bad_nbr.has_value());
Void::Testing::expect(bad_nbr.error().code == AlgorithmError::Code::invalid_vertex);
// Step budget limit exceeded cleanly
const std::vector<std::vector<std::size_t>> path4{{1}, {2}, {3}, {}};
const auto step_limited = bfs(
AdjacencyView{path4},
0,
WorkLimits{.max_steps = 2});
Void::Testing::expect(!step_limited.has_value());
Void::Testing::expect(step_limited.error().code == AlgorithmError::Code::limit_exceeded);
// Deep chain (> 100,000 vertices) runs iteratively with no stack overflow
constexpr std::size_t kDeepCount = 110'000;
std::vector<std::vector<std::size_t>> deep(kDeepCount);
for (std::size_t i = 0; i + 1 < kDeepCount; ++i) {
deep[i].push_back(i + 1);
}
const AdjacencyView deep_view{deep};
const auto deep_dfs = dfs(deep_view, 0);
Void::Testing::require(deep_dfs.has_value());
Void::Testing::expect_eq(deep_dfs->order.size(), kDeepCount);
Void::Testing::expect_eq(deep_dfs->depth[kDeepCount - 1], kDeepCount - 1);
const auto deep_topo = topological_order(deep_view);
Void::Testing::require(deep_topo.has_value());
Void::Testing::expect_eq(deep_topo->order.size(), kDeepCount);
Void::Testing::expect_eq(deep_topo->order.back(), kDeepCount - 1);
const auto deep_sp = shortest_path_unweighted(deep_view, 0, kDeepCount - 1);
Void::Testing::require(deep_sp.has_value());
Void::Testing::expect_eq(deep_sp->distance, kDeepCount - 1);
}
Void::Testing::Test graph_cancellation_and_version_mutation_checks()
{
using Void::Algorithms::AlgorithmError;
using Void::Algorithms::WorkLimits;
using Void::Algorithms::bfs;
using Void::Algorithms::topological_order;
// Concurrent version mutation detected mid-traversal
VersionedChainGraph mutated{
.adj = {{1}, {2}, {3}, {4}, {5}, {}},
.mutate_after_reads = 2,
};
const auto mod_res = bfs(
mutated,
0,
WorkLimits{.cancel_check_interval = 1});
Void::Testing::expect(!mod_res.has_value());
Void::Testing::expect(mod_res.error().code == AlgorithmError::Code::concurrent_modification);
// Cooperative cancellation via std::stop_token
std::stop_source src;
CancellingGraph cg{
.adj = {{1}, {2}, {3}, {4}, {}},
.stop_src = &src,
.cancel_after_reads = 2,
};
const auto cancel_res = topological_order(
cg,
WorkLimits{.cancel_check_interval = 1},
src.get_token());
Void::Testing::expect(!cancel_res.has_value());
Void::Testing::expect(cancel_res.error().code == AlgorithmError::Code::cancelled);
}