Files

10 KiB
Raw Permalink Blame History

NEW Algorithms subsystem

Status: NEW design; no Algorithms source directory/target is claimed to exist. All tasks are PLANNED. Source baseline: f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24.

Existing algorithms and extraction candidates

Containers Graph already includes BFS, DFS, topological sorting, reachability and unweighted BFS shortest paths on its owning directed-graph structure. DisjointSet uses path compression and union/rank-style bookkeeping; it remains a container with algorithmic methods. PriorityQueue maintains key-to-heap indices. Text Diff supplies a generic span-based Myers edit engine plus text adapters. Math sampling uses standard ranges shuffle over an allocated index pool. These do not establish a current common Algorithms API.

Existing graph, disjoint-set, priority-queue, diff, and random suites are migration fixtures. Coverage reported partial parsing at PriorityQueue line 23 and Diff lines 30/96; these ranges and the relevant implementations were read directly. Graph-derived relationships are navigation hints, not proof that every algorithmic precondition is enforced.

Scope and acyclic dependency decision

Algorithms is native, standard-library-first foundation under C-01/C-05. It owns reusable algorithms whose explicit work budgets, graph views or edit semantics add value beyond std::ranges. Do not reimplement standard sort, binary search, transform, reductions, heaps, or a parallel execution runtime merely for naming consistency. Containers/Text may depend on Algorithms; Algorithms imports neither, avoiding an extraction cycle. It may use Core traits, small local expected error enums and standard PMR supplied by the caller. Optional Functional/Memory adapters are separate downward dependencies; no Log/Runtime/Async imports. Checked distance/size arithmetic may use Math's narrow Numeric interface after M-MATH-02; Math itself imports neither Algorithms nor Containers. This prerequisite does not pull dynamic matrices or random-generation headers into algorithm APIs.

NEW proposed paths: include/Void/Algorithms/Graph.hpp, Diff.hpp, TopK.hpp, src/Algorithms/module.cmake, tests/standalone/Algorithms/. No files or test commands for them exist yet. PriorityQueue/DisjointSet ownership remains Containers; Algorithms uses standard priority_queue/vector scratch rather than pulling the owning types back in.

NEW graph port and result shapes

Illustrative NEW API:

namespace Void::Algorithms {
struct WorkLimits {
  std::size_t max_vertices = 65536;
  std::size_t max_edges = 262144;
  std::size_t max_scratch_bytes = 16 * 1024 * 1024;
};
enum class AlgorithmError { limit, invalid_vertex, invalid_weight,
                            overflow, cancelled, inconsistent_view, allocation_failed };
struct Topology {
  std::vector<std::uint32_t> order;
  std::vector<std::uint32_t> cycle; // one witness if cyclic
};
template<class IndexedGraphView>
std::expected<Topology, AlgorithmError>
topological_order(const IndexedGraphView&, WorkLimits, std::stop_token = {});
}

The graph view contract supplies vertex_count() and repeatable out_edges(vertex) with dense indices [0,V); edge views supply target and weight only when required. The caller owns immutable input through the call. Concurrent mutation is invalid; an optional version stamp lets adapters detect changes and return inconsistent_view. No references to temporary edge ranges escape. Containers supplies an adapter from arbitrary vertex keys to dense stable indices; its mapping allocation is charged by that adapter, not hidden from memory reports.

Use iterative BFS/DFS with visited arrays and explicit stacks, avoiding recursion depth as input control. Topological sorting uses Kahn's indegrees and FIFO ready vertices in input order; if not all vertices are emitted, iterative colored DFS over remaining vertices returns a concrete cycle witness. Stable results require stable input ordering; unordered container iteration is not secretly normalized. Dijkstra accepts finite nonnegative weights, checked distance addition and lazy duplicate heap entries. Each heap admission counts against scratch, including duplicates. Negative weights reject; Bellman–Ford is outside the initial gate. An unreachable target returns an empty optional path inside a successful result, distinct from resource exhaustion or invalid graph.

Work budgets count scanned edges and vertices before expanding scratch. Check stop at least every 1,024 edge visits and each outer iteration. Pure result-building operations publish only complete results. Visitor variants document already-delivered callbacks on cancellation/failure, run without internal locks, and do not claim to undo effects. Owned scratch allocation failure returns allocation_failed without a partial owning result; exceptions from caller predicates/visitors propagate unless explicitly adapted. No worker, scheduler or forceful callback interruption is introduced.

NEW diff and bounded selection

The generic diff engine accepts spans, an equality predicate, edit-distance and scratch limits, returning index ranges instead of copied payloads. Text owns line splitting, patch escaping and human formatting. Default combined input cap is 65,536 elements, distance cap 4,096 and scratch 16 MiB. Index arithmetic is size_t with checked conversion where signed diagonals are needed. Trace storage reserves only after budget admission. Hitting a limit returns limit; a separately named coarse-replacement strategy may be added by Text, never silently substituted as a minimal edit script.

Myers trace reconstruction is the initial native implementation to preserve fixtures. A linear-space divide/reconstruct implementation is a P3 capability gate with the same deterministic tie-breaking and independent script-application tests. No claimed universal complexity improvement ignores output size or predicate cost.

NEW streaming top_k retains k elements in a standard heap (default k≤1,024, maximum 65,536, 16 MiB scratch), tracks arrival index for stable tie-breaking, and reports k=0 as empty success without allocation. Caller comparator must define strict weak order. The output policy is explicit ascending/descending and sorted after ingestion. This supports histogram ranking and bounded diagnostics; it does not replace ordinary partial_sort for in-memory spans. Math remains owner of probability sampling and RNGs.

Task DAG

Task Phase; dependencies Scope and acceptance Recommended role
S-ALGORITHMS-01 P0; extraction source/tests Record traversal order, path/cycle and diff tie-breaking fixtures; approve one-way Containers/Text→Algorithms adapters. astra_implementer
S-ALGORITHMS-02 P1; S-ALGORITHMS-01 Add indexed graph view, work budgets and iterative traversals/topology; stable input yields stable order and cyclic graphs include valid witnesses. sol_implementer
S-ALGORITHMS-03 P2; S-ALGORITHMS-02; M-MATH-02 Add bounded shortest paths; negative/nonfinite weights reject, overflow reports and unreachable targets are distinct. sol_implementer
S-ALGORITHMS-04 P2; S-ALGORITHMS-01 Extract bounded Myers engine and keep Text adapters; replay transforms source to target and all caps fail before excess allocation. sol_implementer
S-ALGORITHMS-05 P2; S-ALGORITHMS-01 Add streaming top-k and instrumentation-free progress counters; reference sorting confirms values/ties and retained scratch stays bounded. sol_implementer
S-ALGORITHMS-06 P3; S-ALGORITHMS-02–05; measured large-diff profile Implement linear-space diff only behind conformance/performance gate; publish isolated consumers and compare real graph/diff/top-k workloads. astra_implementer

Verification, compatibility and limits

CURRENT verification is source/test inspection and the parent baseline; no new Algorithms test or benchmark was executed. PROPOSED property tests generate bounded graphs and compare reachability/path cost with simple exhaustive small-graph references; validate every cycle edge and topological relation. Include self-loops, disconnected graphs, parallel edges, zero weights, invalid targets, cancellation and view-version changes. Diff tests compare minimal edit lengths against dynamic programming on small sequences, then replay scripts on large/adversarial inputs. Top-k compares full standard sorting, including repeated keys and k greater than input size. Allocation fault injection must leave owning inputs untouched. Sanitizers check index/lifetime bugs; deterministic work counters prove budget enforcement independent of machine speed.

PERFORMANCE profiles sparse/dense dependency graphs, short/long equal prefix diffs, worst-case dissimilar spans and streaming ranking. Measure p50/p95/p99, throughput, predicate calls, allocations, scratch peaks, RSS/CPU and build cost. External algorithm libraries may be reference oracles in development only after separate dependency approval; initial shipped Algorithms has no external package requirement.

Migration keeps Graph member methods and Void::Diff forwarding wrappers through the major transition. Borrowed index-range results must not be confused with the old owning copied edits. Rollback uses old wrapper implementations; no persisted format changes are involved. New consumers need the Algorithms component declared rather than relying on whole-library tests to supply it. See VALIDATION, DEPENDENCIES, DELIVERY, requirements, Containers, Text and Math.