From bfd6246d32c90c2b65809553f9b6e16392b031cd Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:36:10 +0300 Subject: [PATCH] feat(Algorithms): add indexed graph views, work budgets, and iterative traversals/topology (S-ALGORITHMS-02) --- include/Void/Algorithms/Graph.hpp | 786 ++++++++++++++++++++ src/Algorithms/module.cmake | 3 + tests/package/AlgorithmsOnly/CMakeLists.txt | 10 + tests/package/AlgorithmsOnly/main.cpp | 20 + tests/package/InstalledComponents.cmake | 5 + tests/standalone/Algorithms/Graph.cpp | 304 ++++++++ 6 files changed, 1128 insertions(+) create mode 100644 include/Void/Algorithms/Graph.hpp create mode 100644 src/Algorithms/module.cmake create mode 100644 tests/package/AlgorithmsOnly/CMakeLists.txt create mode 100644 tests/package/AlgorithmsOnly/main.cpp create mode 100644 tests/standalone/Algorithms/Graph.cpp diff --git a/include/Void/Algorithms/Graph.hpp b/include/Void/Algorithms/Graph.hpp new file mode 100644 index 0000000..9229ca9 --- /dev/null +++ b/include/Void/Algorithms/Graph.hpp @@ -0,0 +1,786 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Algorithms +{ + +struct WorkLimits { + std::size_t max_vertices{1'000'000}; + std::size_t max_steps{16'000'000}; + std::size_t max_scratch_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t cancel_check_interval{1024}; +}; + +struct AlgorithmError { + enum class Code { + invalid_input, + invalid_vertex, + limit_exceeded, + overflow, + cancelled, + concurrent_modification, + cycle_detected + }; + + Code code{Code::invalid_input}; + std::string message{}; + std::vector cycle{}; +}; + +struct TraversalResult { + static constexpr std::size_t npos = std::numeric_limits::max(); + + std::vector order{}; + std::vector parent{}; + std::vector depth{}; +}; + +struct ShortestPathResult { + static constexpr std::size_t npos = std::numeric_limits::max(); + + bool found{false}; + std::size_t distance{npos}; + std::vector path{}; +}; + +struct Topology { + std::vector order{}; + std::vector position{}; +}; + +template +concept IndexedGraphView = requires(const G& g, std::size_t u) { + { g.vertex_count() } -> std::convertible_to; + { g.neighbors(u) } -> std::ranges::input_range; + requires std::convertible_to, + std::size_t>; +}; + +template +concept HasVersionStamp = requires(const G& g) { + { g.version() }; + { g.version() == g.version() } -> std::convertible_to; +}; + +class AdjacencyView +{ +public: + AdjacencyView() noexcept = default; + + explicit AdjacencyView(std::span> lists) noexcept + : lists_(lists) + { + } + + explicit AdjacencyView(const std::vector>& lists) noexcept + : lists_(lists) + { + } + + [[nodiscard]] static std::expected + try_from_csr(std::span offsets, + std::span edges) + { + if (offsets.empty()) { + if (!edges.empty()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR edges present with empty offsets"}}; + } + return AdjacencyView{}; + } + if (offsets.front() != 0) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR offsets must start at 0"}}; + } + for (std::size_t i = 0; i + 1 < offsets.size(); ++i) { + if (offsets[i] > offsets[i + 1]) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR offsets must be monotonically non-decreasing"}}; + } + } + if (offsets.back() > edges.size()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR final offset exceeds edges span size"}}; + } + return AdjacencyView{offsets, edges}; + } + + [[nodiscard]] std::size_t vertex_count() const noexcept + { + if (is_csr_) { + return csr_offsets_.empty() ? 0 : (csr_offsets_.size() - 1); + } + return lists_.size(); + } + + [[nodiscard]] std::span neighbors(std::size_t u) const noexcept + { + if (is_csr_) { + if (u + 1 >= csr_offsets_.size()) { + return {}; + } + const std::size_t begin = csr_offsets_[u]; + const std::size_t end = csr_offsets_[u + 1]; + if (begin > end || end > csr_edges_.size()) { + return {}; + } + return csr_edges_.subspan(begin, end - begin); + } + if (u >= lists_.size()) { + return {}; + } + return lists_[u]; + } + +private: + AdjacencyView(std::span offsets, + std::span edges) noexcept + : csr_offsets_(offsets) + , csr_edges_(edges) + , is_csr_(true) + { + } + + std::span> lists_{}; + std::span csr_offsets_{}; + std::span csr_edges_{}; + bool is_csr_{false}; +}; + +namespace detail +{ + +template +[[nodiscard]] inline bool valid_vertex_index(T raw, std::size_t vertex_count) noexcept +{ + if constexpr (std::is_signed_v) { + if (raw < 0) { + return false; + } + } + return std::cmp_less(raw, vertex_count); +} + +[[nodiscard]] inline std::expected + checked_scratch_bytes(std::size_t count, + std::size_t bytes_per_element, + const WorkLimits& limits) +{ + const auto prod = Void::Numeric::checked_mul(count, bytes_per_element); + if (!prod.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "Scratch byte budget multiplication overflowed"}}; + } + if (*prod > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Estimated scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + return *prod; +} + +template +struct VersionSnapshot { +}; + +template + requires HasVersionStamp +struct VersionSnapshot { + using type = std::remove_cvref_t().version())>; + type initial{}; +}; + +template +[[nodiscard]] inline VersionSnapshot capture_version(const G& g) +{ + if constexpr (HasVersionStamp) { + return VersionSnapshot{g.version()}; + } else { + (void)g; + return VersionSnapshot{}; + } +} + +template +[[nodiscard]] inline std::expected + check_state(const G& g, + const VersionSnapshot& snap, + const std::stop_token& stop_token) +{ + if (stop_token.stop_requested()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cancelled, + "Algorithm cancelled via stop_token"}}; + } + if constexpr (HasVersionStamp) { + if (!(g.version() == snap.initial)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::concurrent_modification, + "Graph version changed during traversal"}}; + } + } else { + (void)g; + (void)snap; + } + return {}; +} + +[[nodiscard]] inline std::expected + advance_step(std::size_t& steps, const WorkLimits& limits) +{ + if (steps >= limits.max_steps) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Step count exceeded WorkLimits::max_steps"}}; + } + const auto next = Void::Numeric::checked_add(steps, std::size_t{1}); + if (!next.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "Step counter overflowed"}}; + } + steps = *next; + return {}; +} + +template +[[nodiscard]] inline std::expected + step_and_maybe_check(const G& g, + const VersionSnapshot& snap, + const std::stop_token& stop_token, + std::size_t& steps, + const WorkLimits& limits) +{ + if (auto s = advance_step(steps, limits); !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (limits.cancel_check_interval > 0 && + (steps % limits.cancel_check_interval) == 0) { + if (auto c = check_state(g, snap, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + } + return {}; +} + +} // namespace detail + +template +[[nodiscard]] std::expected + bfs(const G& graph, + std::size_t start, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start vertex index is out of range"}}; + } + + constexpr std::size_t kPerVertexBytes = + 4 * sizeof(std::size_t) + sizeof(std::uint8_t); + if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + std::vector visited(n, 0); + std::vector queue; + queue.reserve(n); + + TraversalResult result; + result.parent.assign(n, TraversalResult::npos); + result.depth.assign(n, TraversalResult::npos); + result.order.reserve(n); + + visited[start] = 1; + result.depth[start] = 0; + queue.push_back(start); + + std::size_t steps = 0; + std::size_t head = 0; + while (head < queue.size()) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + result.order.push_back(u); + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + visited[v] = 1; + result.parent[v] = u; + result.depth[v] = result.depth[u] + 1; + queue.push_back(v); + } + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return result; +} + +template +[[nodiscard]] std::expected + dfs(const G& graph, + std::size_t start, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start vertex index is out of range"}}; + } + + struct Frame { + std::size_t vertex; + std::size_t parent; + std::size_t depth; + }; + + constexpr std::size_t kBasePerVertexBytes = + 3 * sizeof(std::size_t) + sizeof(std::uint8_t); + const auto base_scratch = + detail::checked_scratch_bytes(n, kBasePerVertexBytes, limits); + if (!base_scratch.has_value()) { + return std::unexpected{std::move(base_scratch.error())}; + } + + std::vector visited(n, 0); + std::vector stack; + std::vector scratch_neighbors; + + TraversalResult result; + result.parent.assign(n, TraversalResult::npos); + result.depth.assign(n, TraversalResult::npos); + result.order.reserve(n); + + if (*base_scratch + sizeof(Frame) > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + stack.push_back(Frame{start, TraversalResult::npos, 0}); + + std::size_t steps = 0; + while (!stack.empty()) { + const Frame cur = stack.back(); + stack.pop_back(); + + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (visited[cur.vertex]) { + continue; + } + visited[cur.vertex] = 1; + result.parent[cur.vertex] = cur.parent; + result.depth[cur.vertex] = cur.depth; + result.order.push_back(cur.vertex); + + scratch_neighbors.clear(); + for (const auto raw_v : graph.neighbors(cur.vertex)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + scratch_neighbors.push_back(v); + const auto dyn_bytes = Void::Numeric::checked_mul( + stack.size() + scratch_neighbors.size(), sizeof(Frame)); + if (!dyn_bytes.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "DFS stack byte calculation overflowed"}}; + } + if (*base_scratch + *dyn_bytes > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + } + } + for (auto it = scratch_neighbors.rbegin(); it != scratch_neighbors.rend(); ++it) { + stack.push_back(Frame{*it, cur.vertex, cur.depth + 1}); + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return result; +} + +template +[[nodiscard]] std::expected + shortest_path_unweighted(const G& graph, + std::size_t start, + std::size_t target, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n || target >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start or target vertex index is out of range"}}; + } + + if (start == target) { + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return ShortestPathResult{ + .found = true, + .distance = 0, + .path = {start}, + }; + } + + constexpr std::size_t kPerVertexBytes = + 2 * sizeof(std::size_t) + sizeof(std::uint8_t); + if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + std::vector visited(n, 0); + std::vector parent(n, ShortestPathResult::npos); + std::vector queue; + queue.reserve(n); + + visited[start] = 1; + queue.push_back(start); + + bool reached = false; + std::size_t steps = 0; + std::size_t head = 0; + while (head < queue.size() && !reached) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + visited[v] = 1; + parent[v] = u; + queue.push_back(v); + if (v == target) { + reached = true; + break; + } + } + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + if (!reached) { + return ShortestPathResult{ + .found = false, + .distance = ShortestPathResult::npos, + .path = {}, + }; + } + + std::vector path; + for (std::size_t cur = target; cur != ShortestPathResult::npos; cur = parent[cur]) { + path.push_back(cur); + } + std::reverse(path.begin(), path.end()); + const std::size_t distance = path.empty() ? 0 : (path.size() - 1); + return ShortestPathResult{ + .found = true, + .distance = distance, + .path = std::move(path), + }; +} + +template +[[nodiscard]] std::expected + topological_order(const G& graph, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + + if (n == 0) { + return Topology{}; + } + + constexpr std::size_t kPerVertexBytes = 4 * sizeof(std::size_t); + const auto base_scratch = + detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + if (!base_scratch.has_value()) { + return std::unexpected{std::move(base_scratch.error())}; + } + + std::vector in_degree(n, 0); + std::size_t steps = 0; + for (std::size_t u = 0; u < n; ++u) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + const auto inc = Void::Numeric::checked_add(in_degree[v], std::size_t{1}); + if (!inc.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "In-degree counter overflowed"}}; + } + in_degree[v] = *inc; + } + } + + std::vector queue; + queue.reserve(n); + for (std::size_t u = 0; u < n; ++u) { + if (in_degree[u] == 0) { + queue.push_back(u); + } + } + + Topology topo; + topo.order.reserve(n); + topo.position.assign(n, 0); + + std::size_t head = 0; + while (head < queue.size()) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + topo.position[u] = topo.order.size(); + topo.order.push_back(u); + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (--in_degree[v] == 0) { + queue.push_back(v); + } + } + } + + if (topo.order.size() == n) { + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return topo; + } + + // Extract a deterministic cycle witness [u0, ..., uk, u0] via iterative 3-color DFS. + enum class Color : std::uint8_t { unvisited = 0, active = 1, done = 2 }; + struct CycleFrame { + std::size_t vertex; + std::size_t edge_begin; + std::size_t edge_end; + std::size_t edge_cursor; + }; + + const auto extra_colors = detail::checked_scratch_bytes(n, sizeof(Color), limits); + if (!extra_colors.has_value() || + *base_scratch + *extra_colors > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + + std::vector color(n, Color::unvisited); + std::vector stack; + std::vector edge_pool; + + auto push_frame = [&](std::size_t v) -> std::expected { + color[v] = Color::active; + const std::size_t begin = edge_pool.size(); + for (const auto raw_nxt : graph.neighbors(v)) { + if (!detail::valid_vertex_index(raw_nxt, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + edge_pool.push_back(static_cast(raw_nxt)); + } + const std::size_t end = edge_pool.size(); + const std::size_t dyn_bytes = + (stack.size() + 1) * sizeof(CycleFrame) + edge_pool.size() * sizeof(std::size_t); + if (*base_scratch + *extra_colors + dyn_bytes > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + stack.push_back(CycleFrame{v, begin, end, begin}); + return {}; + }; + + for (std::size_t seed = 0; seed < n; ++seed) { + if (in_degree[seed] == 0 || color[seed] != Color::unvisited) { + continue; + } + if (auto p = push_frame(seed); !p.has_value()) { + return std::unexpected{std::move(p.error())}; + } + + while (!stack.empty()) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + auto& top = stack.back(); + if (top.edge_cursor < top.edge_end) { + const std::size_t v = edge_pool[top.edge_cursor++]; + if (color[v] == Color::active) { + std::vector witness; + auto it = std::find_if(stack.begin(), stack.end(), [v](const CycleFrame& f) { + return f.vertex == v; + }); + for (; it != stack.end(); ++it) { + witness.push_back(it->vertex); + } + witness.push_back(v); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cycle_detected, + "Directed graph contains a cycle", + std::move(witness)}}; + } + if (color[v] == Color::unvisited) { + if (auto p = push_frame(v); !p.has_value()) { + return std::unexpected{std::move(p.error())}; + } + } + } else { + const std::size_t pop_begin = top.edge_begin; + color[top.vertex] = Color::done; + stack.pop_back(); + edge_pool.resize(pop_begin); + } + } + } + + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cycle_detected, + "Directed graph contains a cycle"}}; +} + +} // namespace Void::Algorithms \ No newline at end of file diff --git a/src/Algorithms/module.cmake b/src/Algorithms/module.cmake new file mode 100644 index 0000000..3cdfdc1 --- /dev/null +++ b/src/Algorithms/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Algorithms + INTERNAL_DEPS Core Math +) \ No newline at end of file diff --git a/tests/package/AlgorithmsOnly/CMakeLists.txt b/tests/package/AlgorithmsOnly/CMakeLists.txt new file mode 100644 index 0000000..e4cb483 --- /dev/null +++ b/tests/package/AlgorithmsOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidAlgorithmsOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Algorithms) + +add_executable(void_algorithms_only_consumer main.cpp) +target_link_libraries(void_algorithms_only_consumer PRIVATE Void::Algorithms) + +enable_testing() +add_test(NAME VoidAlgorithmsOnlyConsumer COMMAND void_algorithms_only_consumer) \ No newline at end of file diff --git a/tests/package/AlgorithmsOnly/main.cpp b/tests/package/AlgorithmsOnly/main.cpp new file mode 100644 index 0000000..7a62f47 --- /dev/null +++ b/tests/package/AlgorithmsOnly/main.cpp @@ -0,0 +1,20 @@ +#include + +#include + +int main() +{ + const std::vector> dag{ + {1, 2}, + {3}, + {3}, + {}, + }; + const Void::Algorithms::AdjacencyView view{dag}; + const auto sp = Void::Algorithms::shortest_path_unweighted(view, 0, 3); + const auto topo = Void::Algorithms::topological_order(view); + if (!sp || !sp->found || sp->distance != 2 || !topo || topo->order.size() != 4) { + return 1; + } + return 0; +} \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index a8bf104..043dab8 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -96,6 +96,11 @@ if(_has_binary) run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps}) endif() +has_modules(_has_algorithms Algorithms Math Core) +if(_has_algorithms) + run_consumer(AlgorithmsOnly "${install_prefix}" "AlgorithmsOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Algorithms/Graph.cpp b/tests/standalone/Algorithms/Graph.cpp new file mode 100644 index 0000000..a6b4579 --- /dev/null +++ b/tests/standalone/Algorithms/Graph.cpp @@ -0,0 +1,304 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +struct HugeMockGraph { + std::size_t count{0}; + [[nodiscard]] std::size_t vertex_count() const noexcept { return count; } + [[nodiscard]] std::span neighbors(std::size_t) const noexcept { return {}; } +}; + +struct VersionedChainGraph { + std::vector> adj; + mutable std::atomic ver{1}; + std::size_t mutate_after_reads{std::numeric_limits::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 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> adj; + std::stop_source* stop_src{nullptr}; + std::size_t cancel_after_reads{std::numeric_limits::max()}; + mutable std::size_t reads{0}; + + [[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); } + + [[nodiscard]] std::span 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> 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 offsets{0, 2, 4, 5, 6, 6, 6, 6}; + const std::vector 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 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> 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> 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> 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> 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::max()}; + const WorkLimits huge_v_limits{ + .max_vertices = std::numeric_limits::max(), + .max_scratch_bytes = std::numeric_limits::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> 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> 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> 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> 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); +} \ No newline at end of file