Files
faumarayandClaude Opus 5.5 7f95f89d52 chore(wave11): plan execution-path backfill, reserve error codes, update area plans
- Audit roadmap vs TASKS (D-033); scope Wave 11 to M-FUNCTIONAL-03, M-TIME-03,
  M-ASYNC-04/05, S-IO-03/04, S-RUNTIME-02/03 (D-034..D-036)
- Schedule VoidForge upstream requests after Wave 11 (D-037)
- Persist planner output, PREFLIGHT findings and contract addendum (D-038)
- Add AsyncErrorCode::closed, IoErrorCode::sync_failed,
  RuntimeErrorCode::{self_join, shutdown_incomplete}
- Update Functional/IO/Runtime area plans and MIGRATION per C-13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:31:14 +03:00

155 lines
10 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Functional completion and error contracts
Status: planning only; feature tasks are **PLANNED**. Source baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
## Existing surface
[Result.hpp](../../../include/Void/Functional/Result.hpp) defines
`Void::Result::Result<T, E = Error>` as `std::expected<T,E>`, with `Failure`, `ok`,
`fail` and `with_context`. [Error](../../../include/Void/Functional/Error.hpp) 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](../../../include/Void/Functional/Either.hpp) and
[Opt](../../../include/Void/Functional/Opt.hpp), and `Void::Pipeline` for
[Pipeline](../../../include/Void/Functional/Pipeline.hpp),
[Curry](../../../include/Void/Functional/Curry.hpp) and
[Memo](../../../include/Void/Functional/Memo.hpp).
[Retry](../../../include/Void/Functional/Retry.hpp) 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](../../../include/Void/Functional/Detail/Repr.hpp) includes Core Meta,
while [the module declaration](../../../src/Functional/module.cmake) lists no dependency.
[Result tests](../../../tests/standalone/Functional/ResultContext.cpp),
[memo tests](../../../tests/standalone/Functional/Memo.cpp),
[retry tests](../../../tests/standalone/Functional/Retry.cpp), and
[jitter tests](../../../tests/standalone/Functional/RetryJitter.cpp) 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](../ARCHITECTURE.md). 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.
```cpp
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` exposes `begin(now)`, `next(now, outcome)` and `resume(now)`: `next`
returns `stop` or `wait_until(absolute time)`; `begin`/`resume` return `attempt` or `stop`.
Callers map their error to `AttemptOutcome` with a supplied classifier. 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; the default engine is seeded from
`std::random_device`. 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 1.x `retry`/`retry_while` unchanged, including the zero-attempt default-result
defect (recorded for Wave C). NEW `retry_blocking` takes injected `now`/`sleep` callables,
so Functional stays standard-library-only and no Time-dependent retry header exists.
Async supplies `Async::retry_async` over `TimerQueue`. This prevents foundational retry
code from importing execution (W11 decision D-038).
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](../PERFORMANCE.md) 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](../MIGRATION.md) 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](../VALIDATION.md),
[DEPENDENCIES](../DEPENDENCIES.md), [DELIVERY](../DELIVERY.md) and
[requirements](../REQUIREMENTS.md) for integrated gates.