9.6 KiB
Functional completion and error contracts
Status: planning only; feature tasks are PLANNED. Source baseline:
f1f9ba375b22abf1adcc7c550ec21ac20895c0a4, inspected 2026-11-24.
Existing surface
Result.hpp defines
Void::Result::Result<T, E = Error> as std::expected<T,E>, with Failure, ok,
fail and with_context. Error stores
a message and shared immutable cause chain; it has no current machine-readable category.
Keep the standard expected monadic operations rather than wrapping them in a new result
class. Existing namespace facts also include Void::Either for
Either and
Opt, and Void::Pipeline for
Pipeline,
Curry and
Memo.
Retry has delay policies, jitter and a
steady elapsed budget, but sleeps synchronously and uses zero for unlimited elapsed
time. Its zero-attempt path can return a default-constructed result without calling the
operation. Memoized::get_cache() uses a function-local static map, so instance ownership
and concurrency need deliberate migration. The reflection
diagnostic bridge includes Core Meta,
while the module declaration lists no dependency.
Result tests,
memo tests,
retry tests, and
jitter tests establish useful
fixtures. Scoped graph coverage reported no recorded parser gaps here; source was also
read because graph cleanliness is not completeness evidence.
Owner and dependency decisions
Functional owns error categories and exception/domain adapters under
C-02. It imports no Async, Runtime, Log or Containers. Core stays
below Functional; optional reflection formatting has the NEW interface target
Void::FunctionalCoreFormatting, exporting Functional and Core dependencies. Its
headers never create a reverse Core→Functional bridge; base Void::Functional retains
no Core requirement. Time owns clocks; Functional's pure retry
decision engine accepts times as values and never owns a timer. Async/Resilience own
asynchronous waiting, task cancellation and policy composition above this layer.
Native templates plus standard expected/optional/variant are the backend. No external
functional framework or general policy runtime is justified.
NEW error shape and adapters
These illustrative NEW additions extend include/Void/Functional/Error.hpp and add
NEW include/Void/Functional/Adapters.hpp; existing Result<T> remains an alias.
namespace Void::Result {
enum class ErrorKind {
invalid_argument, not_found, conflict, cancelled, timeout, overloaded,
unsupported, io, corrupt, exhausted, internal
};
struct ErrorCode { std::uint32_t domain; std::int32_t value; };
// Compact failure descriptor; expected's value branch represents success.
struct Status { ErrorKind kind; ErrorCode code; };
// NEW members on Error:
// explicit Error(Status) noexcept; // no diagnostic allocation
// ErrorKind kind() const noexcept;
// ErrorCode code() const noexcept;
// std::error_code system_code() const noexcept;
// Error with_context(std::string) const&;
template<class T, class E, class Map>
Result<T> adapt(std::expected<T,E>, Map&& map_error);
template<class F, class Map>
auto try_invoke(F&&, Map&& map_exception);
}
The library reserves domain 0 for generic classifications; domain numeric registration
is documented by Functional, not generated by hashing type names. Preserve domain code,
system code, root category and causes through context wrapping. Human strings are never
parsed to decide retryability. Old Error(string) maps to internal with an unspecified
domain code; callers should migrate to typed construction. Domain errors such as
Numeric::Error may remain small enums and use explicit adapters at integration edges.
adapt invokes its mapper only on failure and supports move-only values and void.
try_invoke catches only exceptions accepted by its caller-provided mapper; unrecognized
exceptions rethrow. std::bad_alloc propagates by default. No automatic catch-all turns
programmer errors into empty values. A C ABI adapter catches at its boundary and emits
fixed status codes with explicitly owned diagnostic storage under C-09.
NEW error context limits default to 16 frames, 1 KiB per message and 16 KiB total rendered
diagnostics. Truncation is visible and preserves the original classification. A compact
Status carrying only kind/code provides an allocation-free boundary for Memory and
low-memory paths; enriching it with strings is separate and fallible. Cause copying is
immutable and bounded; destructor traversal must not recurse through unbounded chains.
Pure retry and callable ownership
NEW RetryState::next(now, last_error) returns either stop, attempt, or an absolute
next-attempt time. Defaults: three total attempts and a 30-second total budget; explicit
no_deadline is required for unlimited time. Zero attempts is invalid. Backoff arithmetic
saturates at a configured cap before overflow, rejects negative durations/nonfinite
multipliers, and accepts an injected URBG for reproducible jitter. A stop request or
expired admission deadline prevents the next attempt; the policy cannot interrupt an
already-running callback or reverse its side effects. Retryability is a supplied
predicate and retrying writes still requires the caller's idempotency contract.
Retain the synchronous retry adapter temporarily, explicitly named as blocking. A
Time-clock/sleeper adapter belongs in a separate Time-dependent header; Async supplies
its own awaiting adapter. This prevents foundational retry code from importing execution.
Memoization becomes per-instance with an explicit key/result signature, default 1,024
entries and FIFO eviction. Recursive calls mark an entry as computing; a repeated key
returns conflict rather than infinite recursion. Exceptions and failed expected results
are not cached by default. Concurrent memoization is a separate externally synchronized
adapter, not a hidden mutex in every callable. Pipeline/curry forwarding preserves
move-only callables, return references only when the underlying callable does, and
documents captured-reference lifetime. Standard ranges remain the default sequence API.
Ordered backlog
| Task | Phase; dependencies | Implementation scope and acceptance | Recommended role |
|---|---|---|---|
| M-FUNCTIONAL-01 | P0; current source | Lock existing expected alias, context rendering, namespace and exception behavior; compile minimal and reflection bridge consumers independently. | sol_implementer |
| M-FUNCTIONAL-02 | P1; M-FUNCTIONAL-01 | Add compact Status, stable categories/domain codes, bounded context and explicit adapters; root classification survives 16 frames and allocation-free status paths allocate zero. | astra_implementer |
| M-FUNCTIONAL-03 | P1; M-FUNCTIONAL-02; Time clock contract | Extract pure retry decisions and retain named blocking adapter; fake-time tests prove exact attempt counts, deadlines, jitter bounds and no zero-attempt success. | sol_implementer |
| M-FUNCTIONAL-04 | P2; M-FUNCTIONAL-01–02 | Replace static memo caches with bounded instance caches and recursive-key detection; same callable type with different captures cannot share values. | sol_implementer |
| M-FUNCTIONAL-05 | P2; M-FUNCTIONAL-01 | Complete Either/Opt/Pipeline/Curry move/ref-qualified behavior and declared Core bridge dependency; move-only, void and constexpr consumers compile. | sol_implementer |
| M-FUNCTIONAL-06 | P2; M-FUNCTIONAL-02–05 | Publish migration adapters, error-domain registry and integration examples for Async/Data/Binary; no dependency cycle and installed minimal consumers pass. | sol_implementer |
Evidence and migration gates
CURRENT verification is the inspected source/test inventory and parent-recorded baseline; no tests were rerun for these documents. PROPOSED tests add category-preserving adaptation, void/move-only expected, known/unknown exceptions, cause-limit truncation, allocator failure while enriching Status, two memo instances, recursive duplicate keys, failed compute cleanup, zero attempts, deadline-at-admission and saturated backoff. Async owns cancellation-race tests for its retry adapter; synchronous policy tests do not prove preemption or timely shutdown of arbitrary callbacks.
Measure successful expected chains separately from failures with context, memo hit/miss and eviction distributions, and callable compile cost. Follow PERFORMANCE for p50/p95/p99, allocations, throughput, RSS/CPU and build cost; do not compare a throwing diagnostic-heavy failure with an allocation-free status without reporting that work difference.
The major migration changes Error layout, memo ownership and retry defaults explicitly. Keep legacy blocking/zero-unlimited policy wrappers named and documented for one transition; never silently reuse old static caches. No serialized error object becomes a wire contract: RPC owns its versioned mapping. Rollback selects the old major with no persistent-data conversion, but mixed-major ABI objects cannot cross plugin boundaries. See VALIDATION, DEPENDENCIES, DELIVERY and requirements for integrated gates.