Compare commits
233
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
549c7cfccb | ||
|
|
1f98938061 | ||
|
|
b9dc055baa | ||
|
|
b70306fb3a | ||
|
|
d5a2c9e718 | ||
|
|
91e7a90213 | ||
|
|
57ebf3130b | ||
|
|
504f259d02 | ||
|
|
cdc55a594e | ||
|
|
b386140899 | ||
|
|
23a899a892 | ||
|
|
cfa860f944 | ||
|
|
9ba4738415 | ||
|
|
aad91c7d01 | ||
|
|
21b1c8422d | ||
|
|
2da3971760 | ||
|
|
2489098478 | ||
|
|
1fec965c68 | ||
|
|
0f1cf89cfc | ||
|
|
50595bdabc | ||
|
|
03542d0d2f | ||
|
|
3010b8a913 | ||
|
|
55a1399e01 | ||
|
|
b3c1246291 | ||
|
|
3ce62c9cbd | ||
|
|
5e70ad2bc4 | ||
|
|
b8e6e924a8 | ||
|
|
ed4beba6e0 | ||
|
|
4a820748dd | ||
|
|
5c5fe96f11 | ||
|
|
17a23bf88a | ||
|
|
48e5e223af | ||
|
|
4b2bc8b25f | ||
|
|
cc41e5b1d9 | ||
|
|
404bf4ce2f | ||
|
|
80e6ed9afc | ||
|
|
d338305cc7 | ||
|
|
e40e2ca715 | ||
|
|
3990c77155 | ||
|
|
546628c5b9 | ||
|
|
4c0ebc76be | ||
|
|
28e253b49c | ||
|
|
520849f82e | ||
|
|
1bd729147f | ||
|
|
41e8c9c6ab | ||
|
|
b20425ded9 | ||
|
|
7f861fa78f | ||
|
|
96c5ddcb0c | ||
|
|
af8757080f | ||
|
|
d73a34d622 | ||
|
|
7d6834979e | ||
|
|
06e5bd5693 | ||
|
|
217b20e37a | ||
|
|
ac30650266 | ||
|
|
30ba0159ee | ||
|
|
92b30d2b14 | ||
|
|
e6aec57ad8 | ||
|
|
686f73ec9d | ||
|
|
0f2cab97d5 | ||
|
|
51bae9bfdf | ||
|
|
c21dbf5c93 | ||
|
|
61582ea461 | ||
|
|
c6d4a44394 | ||
|
|
6b9ccc5e9a | ||
|
|
f9eeb34369 | ||
|
|
1f137f101d | ||
|
|
183b8033fd | ||
|
|
fd763e4feb | ||
|
|
11fea2566a | ||
|
|
0ef4e3b9ac | ||
|
|
3253b8b4d4 | ||
|
|
a2a0e1a4c3 | ||
|
|
808b6d73df | ||
|
|
a4c0bee501 | ||
|
|
c6c0303ef8 | ||
|
|
1f92dd054e | ||
|
|
9ab482dc5d | ||
|
|
2c026ea30c | ||
|
|
dec48426ae | ||
|
|
3f71bfdd4a | ||
|
|
a26ba70e48 | ||
|
|
310fea8d7b | ||
|
|
2532485b38 | ||
|
|
3b1ef4b028 | ||
|
|
103523f04a | ||
|
|
a1308a41f8 | ||
|
|
7e5cf7379a | ||
|
|
7eaa96f9da | ||
|
|
797ea630a1 | ||
|
|
0e8ee1848d | ||
|
|
a29c9475f2 | ||
|
|
54d143be93 | ||
|
|
0002e74a7d | ||
|
|
0751a4155b | ||
|
|
86cb94c844 | ||
|
|
f8c62c9851 | ||
|
|
7d25251e21 | ||
|
|
06641947bd | ||
|
|
f0820b778f | ||
|
|
62df9b3d7f | ||
|
|
92d60231e5 | ||
|
|
2c8d853af0 | ||
|
|
1ba60d5d6a | ||
|
|
b1933d9906 | ||
|
|
9f8c56a7ee | ||
|
|
08a40ad5fc | ||
|
|
35774f18cc | ||
|
|
5d4589056a | ||
|
|
df4103700e | ||
|
|
4bc8a7c59b | ||
|
|
898968d7c6 | ||
|
|
6e636d23e3 | ||
|
|
77a2bce73f | ||
|
|
32569bbfef | ||
|
|
65185f251c | ||
|
|
fe231b0149 | ||
|
|
1335fa86c3 | ||
|
|
2501c4d7ac | ||
|
|
430deab07a | ||
|
|
7b3258a450 | ||
|
|
d51dd171ef | ||
|
|
44686a4444 | ||
|
|
f158d7b1cc | ||
|
|
62c2082fb3 | ||
|
|
29b46839fd | ||
|
|
72148da7b2 | ||
|
|
a6dd7fd927 | ||
|
|
7cfd30e550 | ||
|
|
9b773a4553 | ||
|
|
540c3d9117 | ||
|
|
74bd01aac5 | ||
|
|
a14d063598 | ||
|
|
a535f352d6 | ||
|
|
9ccfbf7838 | ||
|
|
963aface67 | ||
|
|
a40882522a | ||
|
|
ae7bedb755 | ||
|
|
be8dd73607 | ||
|
|
4ad13ce94f | ||
|
|
f146df97f4 | ||
|
|
f5842b97c8 | ||
|
|
add599917c | ||
|
|
2eb3bd230a | ||
|
|
b3c566ed4d | ||
|
|
d5cfd9cd7a | ||
|
|
aebc38791a | ||
|
|
c8f0113d48 | ||
|
|
12ba8d8e2c | ||
|
|
496d9fc582 | ||
|
|
5a74233a4d | ||
|
|
774df0fd1e | ||
|
|
f8e183b7ab | ||
|
|
216a14e6fa | ||
|
|
7686be1b23 | ||
|
|
71fcad80d3 | ||
|
|
905e44635e | ||
|
|
5d5a8bf345 | ||
|
|
fe6e2124ad | ||
|
|
f9bde1d19f | ||
|
|
65595362e2 | ||
|
|
43d94e2837 | ||
|
|
f6002c1996 | ||
|
|
706383e13f | ||
|
|
81e1d54ac3 | ||
|
|
f57b508b0a | ||
|
|
b381d682c8 | ||
|
|
8c576fdcbf | ||
|
|
63eecc32c7 | ||
|
|
86bde8b172 | ||
|
|
a0e4bfa941 | ||
|
|
6c5c2dcd93 | ||
|
|
86510f99f0 | ||
|
|
a5f21c6374 | ||
|
|
2474292462 | ||
|
|
34cfd9cb39 | ||
|
|
72733e2b93 | ||
|
|
dc18d64b18 | ||
|
|
caebb7f7f1 | ||
|
|
df2ed107e2 | ||
|
|
e8565c6857 | ||
|
|
2c6e4eab82 | ||
|
|
359e0630c7 | ||
|
|
025d97c6f6 | ||
|
|
08038000cc | ||
|
|
ba49098798 | ||
|
|
60860d167a | ||
|
|
5a076cd8f2 | ||
|
|
82c3558524 | ||
|
|
3953891511 | ||
|
|
ba3c5a6734 | ||
|
|
00eefe0521 | ||
|
|
b062e759ba | ||
|
|
dddcc2b2f0 | ||
|
|
7d0ed43f76 | ||
|
|
acd4ff40f0 | ||
|
|
f100b4c89e | ||
|
|
4f67fd2b93 | ||
|
|
2e8afc471b | ||
|
|
f3176c2b54 | ||
|
|
a4851c2c20 | ||
|
|
f2b002eb26 | ||
|
|
afd4d99a2d | ||
|
|
37c3cd4383 | ||
|
|
d30384d981 | ||
|
|
51ceb081ac | ||
|
|
7b0fea6095 | ||
|
|
3c018d6dad | ||
|
|
c6de7842f7 | ||
|
|
7bea7df46d | ||
|
|
50029e1f7b | ||
|
|
ef85ce07b7 | ||
|
|
1e752da590 | ||
|
|
b2c84114fe | ||
|
|
5c24f8e84f | ||
|
|
3ce21be53a | ||
|
|
09789ae141 | ||
|
|
7c1fd3cac1 | ||
|
|
4ea63844f0 | ||
|
|
99a1100bb1 | ||
|
|
95785ed47a | ||
|
|
c6789e7dbf | ||
|
|
26edf653e3 | ||
|
|
99203ce1f3 | ||
|
|
a8a9249101 | ||
|
|
7f95f89d52 | ||
|
|
38436b18c8 | ||
|
|
7d7d23ec0a | ||
|
|
f3f66e0c8c | ||
|
|
60ee28e4ca | ||
|
|
aaeab50758 | ||
|
|
ec8c0bd40a | ||
|
|
0cf187d664 | ||
|
|
65ad9b3f31 |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "VoidLibrary (GCC 16, CMake 4, Ninja)",
|
||||
"build": {
|
||||
"dockerfile": "../Dockerfile",
|
||||
"context": ".."
|
||||
},
|
||||
"workspaceFolder": "/src",
|
||||
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
|
||||
"remoteUser": "root",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.cmake-tools",
|
||||
"twxs.cmake"
|
||||
],
|
||||
"settings": {
|
||||
"cmake.generator": "Ninja",
|
||||
"cmake.configureSettings": {
|
||||
"CMAKE_CXX_COMPILER": "g++-16",
|
||||
"CMAKE_C_COMPILER": "gcc-16",
|
||||
"CMAKE_BUILD_TYPE": "Debug"
|
||||
},
|
||||
"C_Cpp.default.cppStandard": "c++26"
|
||||
}
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "cmake --version && g++-16 --version && ninja --version"
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# Windows builds: MSYS2 (native) and MinGW-w64 (cross)
|
||||
|
||||
## MSYS2 (native Windows, recommended for a full build)
|
||||
|
||||
Install the MINGW64 toolchain and the optional libraries used by the modules:
|
||||
|
||||
```bash
|
||||
pacman -S --needed base-devel \
|
||||
mingw-w64-x86_64-toolchain \
|
||||
mingw-w64-x86_64-cmake \
|
||||
mingw-w64-x86_64-ninja \
|
||||
mingw-w64-x86_64-boost \
|
||||
mingw-w64-x86_64-openssl \
|
||||
mingw-w64-x86_64-libsodium \
|
||||
mingw-w64-x86_64-libarchive \
|
||||
mingw-w64-x86_64-sqlite3 \
|
||||
mingw-w64-x86_64-lua
|
||||
```
|
||||
|
||||
Then, from a **MINGW64** shell (not the MSYS shell):
|
||||
|
||||
```bash
|
||||
cmake -B build -S . -G Ninja -DCMAKE_BUILD_TYPE=Debug
|
||||
cmake --build build
|
||||
ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- C++26 reflection requires GCC 16 or newer (`-freflection`). The build
|
||||
probes for it; on older GCC some reflection-only tests are skipped.
|
||||
- `Void::IO` currently has a POSIX (epoll) backend only; select the modules
|
||||
you need with `-DVOID_ENABLED_MODULES=...` if a module is not yet available
|
||||
on Windows.
|
||||
- The Windows branches of `Void::System` (paths, bounded reads, audio) are
|
||||
compiled by this configuration.
|
||||
|
||||
## MinGW-w64 cross build (Linux container)
|
||||
|
||||
`Dockerfile.mingw` uses the LLVM-MinGW toolchain (Clang + libc++ + the
|
||||
MinGW-w64 runtime) on top of Ubuntu, together with CMake 4 and Ninja. The
|
||||
matching devcontainer is in `.devcontainer/mingw/`.
|
||||
|
||||
```bash
|
||||
docker build -f Dockerfile.mingw -t voidlibrary-mingw .
|
||||
docker run --rm -v "$PWD:/src" -w /src voidlibrary-mingw bash -lc '
|
||||
cmake -B build-mingw -S . -G Ninja \
|
||||
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DVOID_ENABLE_TESTING=OFF \
|
||||
-DVOID_ENABLED_MODULES="Core;Functional;Containers;Math;Text;Algorithms;Unicode;Time;LogState"
|
||||
cmake --build build-mingw
|
||||
'
|
||||
```
|
||||
|
||||
Cross-compiling cannot use the host's Boost/OpenSSL/libsodium/libarchive/SQLite/
|
||||
Lua libraries. Modules that need them (or the POSIX-only IO backend) are
|
||||
therefore excluded from a cross build; use MSYS2 on Windows for those.
|
||||
|
||||
- The toolchain file accepts GCC- or Clang-based MinGW prefixes and picks
|
||||
whichever compiler exists.
|
||||
- `CMAKE_CXX_STANDARD` can be pinned for older toolchains
|
||||
(`-DCMAKE_CXX_STANDARD=23`); the build probes capabilities against the
|
||||
selected standard.
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "VoidLibrary (MinGW-w64 cross build)",
|
||||
"build": {
|
||||
"dockerfile": "../../Dockerfile.mingw",
|
||||
"context": "../.."
|
||||
},
|
||||
"workspaceFolder": "/src",
|
||||
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
|
||||
"remoteUser": "root",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.cmake-tools",
|
||||
"twxs.cmake"
|
||||
],
|
||||
"settings": {
|
||||
"cmake.generator": "Ninja",
|
||||
"cmake.configureSettings": {
|
||||
"CMAKE_TOOLCHAIN_FILE": "cmake/toolchains/mingw-w64.cmake",
|
||||
"CMAKE_BUILD_TYPE": "Debug"
|
||||
},
|
||||
"C_Cpp.default.cppStandard": "c++26"
|
||||
}
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "cmake --version && x86_64-w64-mingw32-g++ --version && ninja --version"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
build*
|
||||
.git
|
||||
.gitea
|
||||
.github
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
+31
-5
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(Void VERSION 1.2.1 LANGUAGES C CXX)
|
||||
project(Void VERSION 1.2.3 LANGUAGES C CXX)
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
|
||||
elseif(NOT DEFINED BUILD_SHARED_LIBS)
|
||||
@@ -14,11 +14,23 @@ option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
|
||||
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
|
||||
option(VOID_ENABLE_TSAN "Enable ThreadSanitizer (Clang/GCC)" OFF)
|
||||
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
|
||||
option(VOID_SCRIPT_ENABLE_LUA "Build the optional bounded Lua adapter" ON)
|
||||
option(VOID_FETCH_LUA "Fetch Lua 5.4 when no system package is found" ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
# C++26 is the default. Cross/toolchain-limited builds (e.g. MinGW-w64
|
||||
# with an older GCC) may pin a lower standard explicitly.
|
||||
if(NOT DEFINED CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
|
||||
if(NOT DEFINED CMAKE_CXX_MODULE_MAP_FORMAT)
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
set(CMAKE_CXX_MODULE_MAP_FORMAT "clang")
|
||||
else()
|
||||
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
|
||||
endif()
|
||||
endif()
|
||||
set(CXX_SCAN_FOR_MODULES OFF)
|
||||
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||
@@ -33,6 +45,7 @@ set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
|
||||
include(cmake/Capabilities.cmake)
|
||||
void_probe_capabilities()
|
||||
include(cmake/Module.cmake)
|
||||
include(cmake/Targets.cmake)
|
||||
|
||||
# Modules to configure, with the modules they need (INTERNAL_DEPS, followed
|
||||
# transitively); empty configures every module. OPTIONAL_DEPS are used only
|
||||
@@ -56,11 +69,14 @@ if(VOID_ENABLED_MODULES)
|
||||
list(APPEND _void_selected ${_void_module})
|
||||
if(EXISTS "${_void_module_file}")
|
||||
file(READ "${_void_module_file}" _void_text)
|
||||
# The words after INTERNAL_DEPS up to the next keyword or ')'.
|
||||
# Drop comments so prose between keywords is never parsed as a
|
||||
# dependency name, then read the words after INTERNAL_DEPS up to
|
||||
# the next keyword or ')'.
|
||||
string(REGEX REPLACE "#[^\n]*" "" _void_text "${_void_text}")
|
||||
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
|
||||
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
|
||||
foreach(_void_word IN LISTS _void_words)
|
||||
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS)$")
|
||||
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS|EXCLUDE_SOURCES_WIN32|EXCLUDE_SOURCES_UNIX)$")
|
||||
break()
|
||||
endif()
|
||||
list(APPEND _void_pending ${_void_word})
|
||||
@@ -71,6 +87,12 @@ if(VOID_ENABLED_MODULES)
|
||||
endif()
|
||||
|
||||
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
|
||||
if(_void_selected)
|
||||
# Fail on unsupported target/module combinations before resolving any
|
||||
# dependency, so a browser engine requesting native networking gets the
|
||||
# target message instead of a Boost/OpenSSL one.
|
||||
void_validate_target_modules(${_void_selected})
|
||||
endif()
|
||||
foreach(module_path ${children})
|
||||
if(_void_selected AND NOT module_path IN_LIST _void_selected)
|
||||
continue()
|
||||
@@ -84,6 +106,9 @@ foreach(module_path ${children})
|
||||
endif()
|
||||
endforeach()
|
||||
void_finalize_modules()
|
||||
void_validate_target_modules()
|
||||
void_write_target_manifest(
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake")
|
||||
void_report_capabilities()
|
||||
if(VOID_ENABLE_TESTING)
|
||||
|
||||
@@ -132,6 +157,7 @@ install(EXPORT ${EXPORT_SET_NAME}
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
|
||||
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
# Development image for VoidLibrary.
|
||||
#
|
||||
# Toolchain: GCC 16 (C++26 reflection), CMake 4, Ninja.
|
||||
# Optional dependencies used by the modules: Boost, OpenSSL, libsodium,
|
||||
# libarchive, SQLite3 and Lua 5.4.
|
||||
#
|
||||
# The image does not copy or build the sources: mount the repository at /src
|
||||
# (the devcontainer does this) and configure/build there.
|
||||
|
||||
FROM ubuntu:24.04
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ARG GCC_VERSION=16
|
||||
ARG CMAKE_VERSION=4.2.3
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
curl \
|
||||
git \
|
||||
gnupg \
|
||||
ninja-build \
|
||||
pkg-config \
|
||||
software-properties-common \
|
||||
libboost-all-dev \
|
||||
libssl-dev \
|
||||
libsodium-dev \
|
||||
libarchive-dev \
|
||||
libsqlite3-dev \
|
||||
liblua5.4-dev \
|
||||
zlib1g-dev \
|
||||
&& add-apt-repository -y ppa:ubuntu-toolchain-r/test \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
gcc-${GCC_VERSION} \
|
||||
g++-${GCC_VERSION} \
|
||||
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_VERSION} 100 \
|
||||
&& update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_VERSION} 100 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL -o /tmp/cmake.tar.gz \
|
||||
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
|
||||
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
|
||||
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
|
||||
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
|
||||
&& rm /tmp/cmake.tar.gz
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
CMD ["bash"]
|
||||
@@ -0,0 +1,29 @@
|
||||
# MinGW-w64 cross-build environment for VoidLibrary (Windows x64 from Linux).
|
||||
#
|
||||
# Uses the LLVM-MinGW toolchain (Clang + libc++ + MinGW-w64 runtime), which is
|
||||
# new enough for the C++26 features this project uses. Reflection is not
|
||||
# available on Clang, so the reflection-only tests are skipped exactly as on
|
||||
# any non-reflecting compiler.
|
||||
|
||||
FROM mstorsjo/llvm-mingw:latest
|
||||
|
||||
ARG CMAKE_VERSION=4.2.3
|
||||
|
||||
# The base image is Ubuntu 24.04 with CMake 3.28; Void requires CMake 4.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates curl git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL -o /tmp/cmake.tar.gz \
|
||||
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
|
||||
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
|
||||
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
|
||||
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
|
||||
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
|
||||
&& rm /tmp/cmake.tar.gz
|
||||
|
||||
ENV PATH="/opt/llvm-mingw/bin:${PATH}"
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
CMD ["bash"]
|
||||
@@ -48,6 +48,15 @@ ctest --test-dir build-asan
|
||||
|
||||
Format code with `clang-format -i <file>`.
|
||||
|
||||
## Supported targets
|
||||
|
||||
Void is qualified per target profile: Linux (reference), Linux/musl, the
|
||||
Windows client subset, and a browser/Wasm subset of the pure computation
|
||||
modules. The profile is detected from the toolchain, validated against the
|
||||
selected modules, and recorded in `void-target-manifest.cmake`. See
|
||||
[docs/targets.md](docs/targets.md) for the exact compiler/standard-library
|
||||
tuples, module allowlists and qualification status.
|
||||
|
||||
## Modules
|
||||
|
||||
Functionality is grouped into umbrella modules (one CMake target each).
|
||||
@@ -101,4 +110,7 @@ Tests are free functions or methods on a `Void::Testing::Fixture` subclass
|
||||
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
|
||||
Registration is automatic — the CMake test scanner parses each `.cpp` at
|
||||
configure time and generates the registration shim. Free-function tests can
|
||||
use `// @tag` and `// @skip` comment metadata.
|
||||
use `// @tag` and `// @skip` comment metadata. A file whose tests all need
|
||||
C++26 reflection can declare `// @requires-reflection`; it is skipped when
|
||||
the compiler lacks the `VOID_HAS_CXX26_REFLECTION` capability, because the
|
||||
scanner cannot evaluate `#ifdef` guards around test functions.
|
||||
@@ -33,7 +33,7 @@ function(void_probe_capabilities)
|
||||
endif()
|
||||
|
||||
cmake_push_check_state(RESET)
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
|
||||
check_cxx_source_compiles(
|
||||
"#include <expected>\nint main() { std::expected<int, int> e{0}; return *e; }\n"
|
||||
VOID_HAS_STD_EXPECTED
|
||||
@@ -46,10 +46,12 @@ function(void_probe_capabilities)
|
||||
endif()
|
||||
|
||||
cmake_push_check_state(RESET)
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26 -freflection")
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
|
||||
CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16 AND
|
||||
CMAKE_CXX_STANDARD GREATER_EQUAL 26)
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD} -freflection")
|
||||
else()
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
|
||||
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
|
||||
endif()
|
||||
check_cxx_source_compiles(
|
||||
"#include <meta>\nconsteval bool probe() { constexpr auto r = ^^int; return std::meta::is_type(r); }\nstatic_assert(probe());\nint main() { return 0; }\n"
|
||||
|
||||
@@ -265,6 +265,47 @@ function(void_fetch_dependency DEP_NAME)
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
if(DEP_NAME STREQUAL "Lua")
|
||||
if(TARGET Lua::Lua)
|
||||
return()
|
||||
endif()
|
||||
# Prefer a system Lua 5.4 development package.
|
||||
find_package(Lua 5.4 QUIET)
|
||||
if(LUA_FOUND)
|
||||
add_library(Lua::Lua INTERFACE IMPORTED)
|
||||
set_property(TARGET Lua::Lua PROPERTY
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}")
|
||||
set_property(TARGET Lua::Lua PROPERTY
|
||||
INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}")
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(NOT VOID_FETCH_LUA)
|
||||
message(FATAL_ERROR
|
||||
"[Void] Lua 5.4 not found and VOID_FETCH_LUA=OFF")
|
||||
endif()
|
||||
message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent")
|
||||
FetchContent_Declare(Lua
|
||||
URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
|
||||
URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
|
||||
SYSTEM
|
||||
)
|
||||
FetchContent_MakeAvailable(Lua)
|
||||
file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c")
|
||||
list(REMOVE_ITEM _void_lua_sources
|
||||
"${lua_SOURCE_DIR}/src/lua.c"
|
||||
"${lua_SOURCE_DIR}/src/luac.c")
|
||||
add_library(void_lua STATIC ${_void_lua_sources})
|
||||
set_target_properties(void_lua PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
C_STANDARD 99
|
||||
SYSTEM TRUE)
|
||||
target_include_directories(void_lua SYSTEM PUBLIC
|
||||
"${lua_SOURCE_DIR}/src")
|
||||
add_library(Lua::Lua ALIAS void_lua)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# FIXME: Add if needed external
|
||||
# if(DEP_NAME STREQUAL "glaze")
|
||||
# if(NOT glaze_POPULATED)
|
||||
|
||||
+18
-4
@@ -5,13 +5,27 @@ set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
|
||||
|
||||
function(void_add_module MODULE_NAME)
|
||||
cmake_parse_arguments(ARG "" ""
|
||||
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS"
|
||||
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS;EXCLUDE_SOURCES_WIN32;EXCLUDE_SOURCES_UNIX"
|
||||
${ARGN})
|
||||
|
||||
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
|
||||
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
|
||||
|
||||
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
|
||||
# Platform-specific source selection: a module may be fully portable at the
|
||||
# header level while some translation units only build on one platform.
|
||||
# Exclusions are relative to the module directory so callers do not depend
|
||||
# on the global source layout.
|
||||
if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32)
|
||||
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32)
|
||||
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||
endforeach()
|
||||
endif()
|
||||
if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX)
|
||||
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX)
|
||||
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
|
||||
endforeach()
|
||||
endif()
|
||||
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
|
||||
@@ -33,7 +47,7 @@ function(void_add_module MODULE_NAME)
|
||||
set(LIB_TYPE "INTERFACE")
|
||||
set(SCOPE "INTERFACE")
|
||||
add_library(${TGT} INTERFACE)
|
||||
target_compile_features(${TGT} INTERFACE cxx_std_26)
|
||||
target_compile_features(${TGT} INTERFACE cxx_std_${CMAKE_CXX_STANDARD})
|
||||
else()
|
||||
set(SCOPE "PUBLIC")
|
||||
if (MODULE_NAME STREQUAL "Testing")
|
||||
@@ -45,7 +59,7 @@ function(void_add_module MODULE_NAME)
|
||||
add_library(${TGT})
|
||||
endif()
|
||||
target_sources(${TGT} PRIVATE ${SRC})
|
||||
target_compile_features(${TGT} PUBLIC cxx_std_26)
|
||||
target_compile_features(${TGT} PUBLIC cxx_std_${CMAKE_CXX_STANDARD})
|
||||
endif()
|
||||
get_target_property(_module_target_type ${TGT} TYPE)
|
||||
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
|
||||
@@ -221,7 +235,7 @@ function(void_add_module MODULE_NAME)
|
||||
endif()
|
||||
|
||||
set_target_properties(${TGT} PROPERTIES
|
||||
CXX_STANDARD 26
|
||||
CXX_STANDARD ${CMAKE_CXX_STANDARD}
|
||||
CXX_STANDARD_REQUIRED ON
|
||||
CXX_EXTENSIONS OFF
|
||||
EXPORT_NAME ${MODULE_NAME}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
# Target qualification for VoidLibrary.
|
||||
#
|
||||
# A "target" is a platform profile with a known compiler/standard-library
|
||||
# tuple and an explicit set of modules that are expected to work there. The
|
||||
# profile is detected from the toolchain, can be overridden for
|
||||
# qualification runs with -DVOID_TARGET=..., and is validated against the
|
||||
# selected modules so unsupported combinations fail at configure time with a
|
||||
# useful message instead of deep inside a cross build.
|
||||
#
|
||||
# See docs/targets.md for the recorded tuples and their qualification status.
|
||||
|
||||
set(VOID_KNOWN_TARGETS linux linux-musl windows wasm)
|
||||
|
||||
set(VOID_TARGET "auto" CACHE STRING
|
||||
"Target profile: auto (detect from the toolchain), ${VOID_KNOWN_TARGETS}")
|
||||
set_property(CACHE VOID_TARGET PROPERTY STRINGS auto ${VOID_KNOWN_TARGETS})
|
||||
|
||||
# Browser/Wasm subset: pure computation modules only. Nothing here performs
|
||||
# native I/O, spawns processes, loads shared libraries, uses SQLite, or needs
|
||||
# C++26 reflection. Keep this list fail-closed: a module is added only after
|
||||
# it has been configured and compiled for wasm32-unknown-emscripten.
|
||||
# Qualified with Emscripten 6.0.9 (Clang 22, libc++) for configure, build,
|
||||
# install, consume and run under Node, including the test suite with
|
||||
# -pthread (see docs/targets.md).
|
||||
set(VOID_WASM_MODULES
|
||||
Algorithms
|
||||
Binary
|
||||
Containers
|
||||
Core
|
||||
Data
|
||||
Functional
|
||||
LogState
|
||||
Math
|
||||
Memory
|
||||
Testing
|
||||
TestingMock
|
||||
Text
|
||||
Time
|
||||
Unicode
|
||||
)
|
||||
|
||||
# Windows client subset: modules qualified with x86_64-w64-mingw32 (MinGW-w64).
|
||||
# Filled from the cross-build and Wine runtime observations in
|
||||
# docs/targets.md. IO is deliberately absent: it builds on Windows but its
|
||||
# native backend is Linux-only (EpollBackend), so only the mock backend works.
|
||||
set(VOID_WINDOWS_MODULES
|
||||
Algorithms
|
||||
Async
|
||||
Binary
|
||||
Containers
|
||||
Core
|
||||
Data
|
||||
Discovery
|
||||
Fsm
|
||||
Functional
|
||||
IO
|
||||
Log
|
||||
LogState
|
||||
Math
|
||||
Memory
|
||||
Messaging
|
||||
Observability
|
||||
ObservabilityHooks
|
||||
Scheduler
|
||||
Service
|
||||
Testing
|
||||
TestingMock
|
||||
Text
|
||||
Time
|
||||
Unicode
|
||||
)
|
||||
|
||||
function(void_detect_target out_var)
|
||||
if(NOT VOID_TARGET STREQUAL "auto")
|
||||
set(${out_var} "${VOID_TARGET}" PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(EMSCRIPTEN OR CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
|
||||
set(_target wasm)
|
||||
elseif(WIN32)
|
||||
set(_target windows)
|
||||
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
execute_process(
|
||||
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
|
||||
OUTPUT_VARIABLE _triple
|
||||
ERROR_QUIET
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
if(_triple MATCHES "musl" OR
|
||||
CMAKE_C_LIBRARY_ARCHITECTURE MATCHES "musl" OR
|
||||
CMAKE_C_FLAGS MATCHES "musl")
|
||||
set(_target linux-musl)
|
||||
else()
|
||||
set(_target linux)
|
||||
endif()
|
||||
else()
|
||||
set(_target unsupported)
|
||||
endif()
|
||||
set(${out_var} "${_target}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(_void_target_allowlist target out_var)
|
||||
if(target STREQUAL "wasm")
|
||||
set(${out_var} "${VOID_WASM_MODULES}" PARENT_SCOPE)
|
||||
elseif(target STREQUAL "windows")
|
||||
set(${out_var} "${VOID_WINDOWS_MODULES}" PARENT_SCOPE)
|
||||
else()
|
||||
# Linux and Linux/musl qualify every module: platform-specific code is
|
||||
# selected inside the module sources.
|
||||
set(${out_var} "" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Validate the detected/forced target against a module selection. Called
|
||||
# from the top-level CMakeLists as soon as the selection is expanded (before
|
||||
# any module dependency is resolved, so an unsupported browser-engine
|
||||
# combination fails with the target message, not a missing-package error),
|
||||
# and again after void_finalize_modules() for the all-modules default.
|
||||
# With no arguments the configured module list is validated.
|
||||
function(void_validate_target_modules)
|
||||
void_detect_target(_target)
|
||||
|
||||
if(_target STREQUAL "unsupported")
|
||||
message(FATAL_ERROR
|
||||
"[Void] Unsupported target '${CMAKE_SYSTEM_NAME} "
|
||||
"${CMAKE_SYSTEM_PROCESSOR}'. Known targets: ${VOID_KNOWN_TARGETS}. "
|
||||
"Pass -DVOID_TARGET=<target> only for a qualification run; "
|
||||
"see docs/targets.md.")
|
||||
endif()
|
||||
if(NOT _target IN_LIST VOID_KNOWN_TARGETS)
|
||||
message(FATAL_ERROR
|
||||
"[Void] Unknown VOID_TARGET='${_target}'. Known targets: "
|
||||
"${VOID_KNOWN_TARGETS}.")
|
||||
endif()
|
||||
|
||||
if(_target STREQUAL "wasm" AND VOID_ENABLE_TSAN)
|
||||
message(FATAL_ERROR
|
||||
"[Void] ThreadSanitizer is not supported on the wasm target; "
|
||||
"run native sanitizer builds separately (docs/targets.md).")
|
||||
endif()
|
||||
|
||||
if(ARGN)
|
||||
set(_modules ${ARGN})
|
||||
else()
|
||||
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
|
||||
endif()
|
||||
_void_target_allowlist(${_target} _allowed)
|
||||
if(_allowed)
|
||||
set(_rejected "")
|
||||
foreach(_module IN LISTS _modules)
|
||||
if(NOT _module IN_LIST _allowed)
|
||||
list(APPEND _rejected ${_module})
|
||||
endif()
|
||||
endforeach()
|
||||
if(_rejected)
|
||||
message(FATAL_ERROR
|
||||
"[Void] Modules not supported on target '${_target}': "
|
||||
"${_rejected}. Supported modules: ${_allowed}. "
|
||||
"Select a supported subset with -DVOID_ENABLED_MODULES=... "
|
||||
"or use a native target (docs/targets.md).")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED VOID_TARGET_DETECTED OR
|
||||
NOT VOID_TARGET_DETECTED STREQUAL _target)
|
||||
set(VOID_TARGET_DETECTED "${_target}" CACHE INTERNAL
|
||||
"Detected or forced Void target profile" FORCE)
|
||||
if(NOT VOID_TARGET STREQUAL "auto")
|
||||
message(STATUS "[Void] Target forced to '${_target}' by VOID_TARGET")
|
||||
else()
|
||||
message(STATUS "[Void] Target: ${_target}")
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Record the exact tuple this build was configured with. The manifest is
|
||||
# installed next to VoidConfig.cmake so consumers can inspect what they got,
|
||||
# and the qualification fixtures assert on it.
|
||||
function(void_write_target_manifest path)
|
||||
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
|
||||
list(JOIN _modules ";" _modules_value)
|
||||
|
||||
if(VOID_HAS_CXX26_REFLECTION)
|
||||
set(_reflection yes)
|
||||
else()
|
||||
set(_reflection no)
|
||||
endif()
|
||||
if(VOID_HAS_STD_EXPECTED)
|
||||
set(_expected yes)
|
||||
else()
|
||||
set(_expected no)
|
||||
endif()
|
||||
if(BUILD_SHARED_LIBS)
|
||||
set(_linkage shared)
|
||||
else()
|
||||
set(_linkage static)
|
||||
endif()
|
||||
|
||||
set(_sanitizers "")
|
||||
if(VOID_ENABLE_ASAN)
|
||||
list(APPEND _sanitizers ASan)
|
||||
endif()
|
||||
if(VOID_ENABLE_UBSAN)
|
||||
list(APPEND _sanitizers UBSan)
|
||||
endif()
|
||||
if(VOID_ENABLE_TSAN)
|
||||
list(APPEND _sanitizers TSan)
|
||||
endif()
|
||||
if(NOT _sanitizers)
|
||||
set(_sanitizers none)
|
||||
else()
|
||||
string(REPLACE ";" "+" _sanitizers "${_sanitizers}")
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
|
||||
OUTPUT_VARIABLE _triple
|
||||
ERROR_QUIET
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
set(_content
|
||||
"# Generated by VoidLibrary's build system (cmake/Targets.cmake).
|
||||
# Describes the exact target tuple this build was configured with.
|
||||
set(VOID_TARGET_MANIFEST_TARGET \"${VOID_TARGET_DETECTED}\")
|
||||
set(VOID_TARGET_MANIFEST_TARGET_ORIGIN \"${VOID_TARGET}\")
|
||||
set(VOID_TARGET_MANIFEST_TRIPLE \"${_triple}\")
|
||||
set(VOID_TARGET_MANIFEST_SYSTEM_NAME \"${CMAKE_SYSTEM_NAME}\")
|
||||
set(VOID_TARGET_MANIFEST_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")
|
||||
set(VOID_TARGET_MANIFEST_COMPILER_ID \"${CMAKE_CXX_COMPILER_ID}\")
|
||||
set(VOID_TARGET_MANIFEST_COMPILER_VERSION \"${CMAKE_CXX_COMPILER_VERSION}\")
|
||||
set(VOID_TARGET_MANIFEST_CXX_STANDARD \"${CMAKE_CXX_STANDARD}\")
|
||||
set(VOID_TARGET_MANIFEST_LINKAGE \"${_linkage}\")
|
||||
set(VOID_TARGET_MANIFEST_REFLECTION \"${_reflection}\")
|
||||
set(VOID_TARGET_MANIFEST_STD_EXPECTED \"${_expected}\")
|
||||
set(VOID_TARGET_MANIFEST_SANITIZERS \"${_sanitizers}\")
|
||||
set(VOID_TARGET_MANIFEST_TESTING \"${VOID_ENABLE_TESTING}\")
|
||||
set(VOID_TARGET_MANIFEST_WARNINGS_AS_ERRORS \"${VOID_WARNINGS_AS_ERRORS}\")
|
||||
set(VOID_TARGET_MANIFEST_MODULES \"${_modules_value}\")
|
||||
")
|
||||
file(WRITE "${path}" "${_content}")
|
||||
endfunction()
|
||||
@@ -22,6 +22,15 @@ set(fixture_class_name "")
|
||||
set(fixture_indent "")
|
||||
set(line_number 0)
|
||||
|
||||
# A Test/DisabledTest declaration may wrap across lines. These patterns let
|
||||
# the loop join such a declaration into one logical line instead of silently
|
||||
# dropping it (X-QA-03).
|
||||
set(_test_decl_regex "(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)")
|
||||
set(_test_decl_start_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]|$)")
|
||||
set(_test_decl_partial_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]+[A-Za-z_][A-Za-z0-9_]*)?[ \t]*\\(?[ \t]*$")
|
||||
set(pending_decl "")
|
||||
set(pending_decl_line 0)
|
||||
|
||||
# Accumulators for preceding comments
|
||||
set(current_tags "")
|
||||
set(current_skip "")
|
||||
@@ -33,6 +42,32 @@ foreach(line IN LISTS lines)
|
||||
string(REPLACE "__VOID_SCAN_SC__" ";" line "${line}")
|
||||
string(REPLACE "__VOID_SCAN_BS__" "\\" line "${line}")
|
||||
|
||||
# Join a wrapped test declaration before any other per-line handling so
|
||||
# tags/skip comments that precede it stay associated with it.
|
||||
set(registration_line ${line_number})
|
||||
if(pending_decl)
|
||||
string(APPEND pending_decl " ${line}")
|
||||
if(pending_decl MATCHES "${_test_decl_regex}")
|
||||
# Complete: process the joined declaration as one logical line.
|
||||
set(line "${pending_decl}")
|
||||
set(registration_line ${pending_decl_line})
|
||||
set(pending_decl "")
|
||||
elseif(pending_decl MATCHES "${_test_decl_partial_regex}")
|
||||
continue()
|
||||
else()
|
||||
# Not a wrapped test declaration after all; handle this line
|
||||
# normally and drop the accumulated prefix.
|
||||
set(pending_decl "")
|
||||
endif()
|
||||
elseif(line MATCHES "${_test_decl_start_regex}" AND NOT line MATCHES "${_test_decl_regex}")
|
||||
set(pending_decl "${line}")
|
||||
set(pending_decl_line ${line_number})
|
||||
if(pending_decl MATCHES "${_test_decl_partial_regex}")
|
||||
continue()
|
||||
endif()
|
||||
set(pending_decl "")
|
||||
endif()
|
||||
|
||||
# Parse preceding comments for @tag and @skip
|
||||
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
|
||||
if(_tag_match)
|
||||
@@ -129,11 +164,11 @@ foreach(line IN LISTS lines)
|
||||
|
||||
if(in_fixture_class)
|
||||
string(APPEND registrations
|
||||
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
)
|
||||
else()
|
||||
string(APPEND registrations
|
||||
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# CMake toolchain for cross-compiling to Windows x64 with MinGW-w64.
|
||||
#
|
||||
# Works with the GCC-based mingw-w64 package and with the LLVM-MinGW
|
||||
# toolchain (Dockerfile.mingw). Override the compiler paths for your install.
|
||||
#
|
||||
# Usage:
|
||||
# cmake -B build-mingw -S . -G Ninja \
|
||||
# -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||
# -DCMAKE_BUILD_TYPE=Debug
|
||||
|
||||
set(CMAKE_SYSTEM_NAME Windows)
|
||||
set(CMAKE_SYSTEM_PROCESSOR x86_64)
|
||||
|
||||
if(NOT DEFINED VOID_MINGW_PREFIX)
|
||||
set(VOID_MINGW_PREFIX x86_64-w64-mingw32)
|
||||
endif()
|
||||
|
||||
find_program(VOID_MINGW_CXX NAMES "${VOID_MINGW_PREFIX}-clang++"
|
||||
"${VOID_MINGW_PREFIX}-g++" REQUIRED)
|
||||
find_program(VOID_MINGW_C NAMES "${VOID_MINGW_PREFIX}-clang"
|
||||
"${VOID_MINGW_PREFIX}-gcc" REQUIRED)
|
||||
find_program(VOID_MINGW_RC NAMES "${VOID_MINGW_PREFIX}-windres")
|
||||
|
||||
set(CMAKE_CXX_COMPILER "${VOID_MINGW_CXX}")
|
||||
set(CMAKE_C_COMPILER "${VOID_MINGW_C}")
|
||||
if(VOID_MINGW_RC)
|
||||
set(CMAKE_RC_COMPILER "${VOID_MINGW_RC}")
|
||||
endif()
|
||||
|
||||
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
||||
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
||||
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
||||
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||
@@ -73,3 +73,23 @@ plans requiring updates. Do not record a proposal as user approval.
|
||||
| D-030 | Create dedicated git branch (`feat/roadmap-p0-p1-foundations`) and make focused commits per completed milestone/task; leave local untracked files (`.env`, `.serena/`, `WG.conf`, `keys`) untouched | CONFIRMED by user |
|
||||
| D-031 | Proceed continuously across roadmap waves without pausing for confirmation between waves, and merge verified waves locally into `main` (without pushing to remote) | CONFIRMED by user |
|
||||
| D-032 | Push verified `main` (and active feature branches) to `origin` (`git@git.faumaray.com:Void/VoidLibrary.git`) after each verified wave merge, superseding the local-only constraint in `D-031` | CONFIRMED by user ("dont forget to push") |
|
||||
|
||||
## Root decisions (2026-11-29)
|
||||
|
||||
These are root-owned sequencing decisions made under D-027/D-031 (continuous roadmap-order
|
||||
execution without pausing between waves). They are not new user approvals.
|
||||
|
||||
| ID | Decision | Contract / rationale |
|
||||
| --- | --- | --- |
|
||||
| D-033 | Gap audit: `STATE.md`'s "all P2 modules complete" was inaccurate. Against the roadmap task tables, 2 P1 tasks (`M-FUNCTIONAL-03`, `M-TIME-03`) and 40 P2 tasks remain open; pre-roadmap headers (`Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/{Retry,Memo}.hpp`, `Core/TypeMap.hpp`) are unchanged since `f1f9ba3`. | Roadmap order (D-027) and P2 outcome in `DELIVERY.md` |
|
||||
| D-034 | Wave 11 is the execution-path backfill (`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`) on `feat/roadmap-p2-wave11`. The platform half of the former "Wave 11" note (`P-NETWORKED-*`, `P-RELOADABLE-*`, `S-RPC-05`) is deferred because `P-*-02` require these Runtime/Async/IO lifecycle gates. `S-RPC-04` may ride along only if the planner finds it ready and file-disjoint. | G-EXEC, G-IO; C-03–C-06 |
|
||||
| D-035 | P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`) are not scheduled as separate waves; each follow-on spec records its observed baseline instead. Distributed `-01`/`-02` planning tasks stay with P4. | Avoids documentation-only waves; evidence lives in each task spec |
|
||||
| D-036 | Remaining foundation P2 tasks (Core, Functional-04..06, Containers, Math, Text, Data, Binary, Time-04/05, Algorithms, Unicode, Memory-05, Testing-04/05) form a later parallel wave after Wave 11. | Independent of the execution-path gate |
|
||||
| D-037 | VoidForge upstream requests (received 2026-11-29 from the VoidForge session on the user's behalf; source `VoidForge/docs/agent-workflow/VOIDLIBRARY_GAPS.md`) are scheduled as an out-of-band wave after Wave 11 and before the D-036 foundation wave, following the `VL-001`..`VL-013` precedent: first `VL-STREAM-01` + `VL-PROC-01` (P0), then `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01` (P1; MCP after STREAM), `VL-WIN-01` when the Windows runner needs it, and `VL-LUA-01`/`VL-STORE-01` (P2) later. Signatures are VoidLibrary-owned; peer proposals are inputs, not approvals. | Peer request is not user approval of scope beyond scheduling; licensing question escalated to the user |
|
||||
| D-038 | Wave 11 contracts adopted from `tasks/W11-PLAN-OUTPUT.md` as amended by `tasks/W11-PLAN-REV1-OUTPUT.md` after PREFLIGHT `tasks/W11-PREFLIGHT-OUTPUT.md` (CHANGES_REQUIRED: F1 P1, F2–F13 P2, P3 list). Accepted D-W11-01..04, 06..15; D-W11-05 modified per F9 (S-IO-03/opus owns the bounded shutdown core and poll-owner exclusion; S-IO-04/sonnet adds thin wrappers, `pump_until`, conformance). Root resolutions for F1 (file workers never call executors/user code except the injected syscall shim; `~Driver` is the only blocking teardown; destruction on a worker/inside a poll turn terminates with a diagnostic), F2 (epoll/eventfd close in backend destructor; `wake()` after shutdown is a no-op), F3–F6 (phase renumbering, per-call shutdown budgets, teardown in `~HostCore`, embedded borrowed resources never shut down), F7–F13 as in the addendum. Area plans `Functional.md`, `Runtime.md`, `IO.md` and `MIGRATION.md` updated per C-13. A1/B1 (Functional/Timer) may start before the PREFLIGHT re-review because the P1 is confined to IO/Runtime; re-review findings on F8/F12 are applied as corrections. | C-03–C-06, C-13; D-029 |
|
||||
| N-001 | Note (not a decision of this session): the VoidForge session reports (2026-11-29, Forge D46) that the user granted permission to distribute VoidLibrary with VOID Forge, including Forge-motivated additions, with no relicensing. VoidLibrary still has no LICENSE file; any license file or wording remains a user decision to be confirmed directly in a VoidLibrary session. | Relayed by peer session; not user input in this session |
|
||||
| D-039 | User reconfirmed in this session (2026-11-29, "i allow pushing to remote") that pushing to `origin` is allowed; consistent with D-032 (push verified `main` and active feature branches). `main` is pushed only after a wave is verified and merged, keeping it green for VoidForge, which tracks remote `main`. | CONFIRMED by user |
|
||||
| D-040 | PREFLIGHT-2 (`tasks/W11-PREFLIGHT-2-OUTPUT.md`) returned CHANGES_REQUIRED with N1–N6 (P2) and P3 lines, no P0/P1. Root resolutions are the mandatory amendment `tasks/W11-CONTRACT-R2.md` (destruction blocks until complete; embedded ManualExecutor pumping; shutdown polling/loop rules; File fd state machine; channel timer callbacks use shared waiter state; EventBus destruction gating). A1/B1 continue with documentation-only corrections. The re-review of R2 happens on the B2/B3/B4/A2/A3 specs before each dispatch. | C-03–C-06; D-038 |
|
||||
| D-041 | VoidForge wave order (after Wave 11, before the D-036 foundation wave): (1) `VL-STREAM-01`, `VL-PROC-01` (P0); (2) small P1 crypto/text items `VL-CRYPTO-01`, `VL-CRYPTO-02`, `VL-TEXT-01`, plus hygiene `VL-NET-W01`; (3) `VL-NET-02` (TLS client stream + SMTP); (4) `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01`; Sqlite items `VL-SQLITE-01..06` (G7 automatic-rollback detection first) after that. Root sequencing; peer requests are inputs, not user approvals. | D-037 |
|
||||
| D-042 | W11-SPEC-REVIEW-1 (`tasks/W11-SPEC-REVIEW-1-OUTPUT.md`) findings S1–S9 (S-IO-03) and A1–A3 (M-ASYNC-04), all P2, adopted verbatim as mandatory amendments in the two specs. S9 resolution: S-IO-03 (B2) owns and tests the public inline wrappers `Driver::begin_shutdown/shutdown(options)/quiescent/shutdown_complete`; S-IO-04 (A4) keeps `run()`, `Pump.hpp`, SystemAsync conformance and tests. Amended text is checked by the fresh post-implementation review rather than a third pre-dispatch review, since it is the reviewer's own replacement text. Worktree dispatches start with `git merge --ff-only <stated HEAD>` (X-WF-01). | C-03–C-06; D-038, D-040 |
|
||||
| D-043 | User reminder (2026-11-30): all wave work must end up in `main`. Each wave (Wave 11, then the VoidForge wave, then later waves) finishes with full RelWithDebInfo + ASan/UBSan + TSan verification on the integrated branch, a fresh adversarial review, a `--no-ff` merge into `main`, and a push of `main` (D-032/D-039). Feature-branch-only completion does not count as done. | CONFIRMED by user |
|
||||
@@ -1,8 +1,9 @@
|
||||
# Workflow state
|
||||
|
||||
Updated: 2026-11-27.
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave9` (from `main`
|
||||
at `3e25405`, merged Waves 1–8 + `VL-001`..`VL-013` and pushed to `origin/main`).
|
||||
Updated: 2026-12-01.
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave11` (from `main` at `38436b1`;
|
||||
Waves 1–11 + `VL-001`..`VL-013` complete and merging into `main`, pushed to `origin/main`).
|
||||
Current wave: **Wave 11 — execution-path backfill COMPLETE**; next: **Wave 12 — VoidForge upstream requests (`D-041`) + `X-QA-01..04`**.
|
||||
|
||||
## Completed objective
|
||||
|
||||
@@ -351,9 +352,37 @@ while leaving local untracked files untouched.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w9-asan`, 48 modules, `-Werror`): `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w9-tsan`, `Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`, 22 modules, `-Werror`): `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
### Wave 10 — P3 Core Subsystems: `Discovery`, `Scheduler`, `Messaging` (`feat/roadmap-p3-wave10`)
|
||||
|
||||
- **Specs & Error Domains (`0cf187d`)**: authored `S-DISCOVERY-01-04.md`, `S-SCHEDULER-01-04.md`, `S-MESSAGING-01-04.md`; reserved `kSchedulerErrorDomain = 31` and `kMessagingErrorDomain = 32` (`kDiscoveryErrorDomain = 30` reserved in Wave 9).
|
||||
- **`Discovery` & `DiscoveryRpc` (`ec8c0bd`, `S-DISCOVERY-01..04`)**: NEW zero-external-dep `Void::Discovery` subsystem (`Catalog` with pure thread-free construction, atomic `replace_static()`, provider generation resets, local RAII `Registration` handles with steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` overflow recovery + self-cancel + `SelfJoin` diagnosis, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` endpoint adapter preserving `expected_tls_name` / blocking TLS downgrades while keeping `RPC` independent; `DiscoveryOnly` consumer (`_no_external_deps`).
|
||||
- **`Scheduler` & `SchedulerStorage` (`aaeab50`, `S-SCHEDULER-01..04`)**: NEW zero-external-dep `Void::Scheduler` subsystem (monotonic min-heap ordered by `(due_time, sequence)`, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` with DST gap/fold & unknown-zone rejection without silent UTC fallback, O(1) backward-scanning `CoalesceLatest` over millions of missed slots, 100/pass `CatchUpBounded`, `Forbid`/`QueueOne`/`AllowBounded` overlap, exponential full-jitter retries & dead-letter acknowledgement, revision invalidation watermark, `close_and_join` returning incomplete report on deadline) + durable `Void::SchedulerStorage` (`StorageJobStore` on `Void::Storage::Engine` conditional batches, exclusive owner lock, unique civil-slot dedup, startup `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause without cursor loss); `SchedulerOnly` consumer (`_no_external_deps`).
|
||||
- **`Messaging`, `MessagingStorage`, & `MessagingRpc` (`60ee28e`, `S-MESSAGING-01..04`)**: NEW zero-external-dep `Void::Messaging` subsystem (explicit `PublishDurability::{Memory,Durable}`, `InMemoryQueue` rejecting `Durable`, `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`, competing & `SingleActive` groups, stale-receipt fencing & idempotent repeat ack, bounded retries -> DLQ, corrupt-payload quarantine) + `Void::MessagingStorage` (`StorageQueue` on `Void::Storage::Engine` conditional batches, restart `InFlight -> Pending` generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency ledger refusing silent eviction, `BlockAtQuota` default & clock-health expiry pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`); `MessagingOnly` consumer (`_no_external_deps`).
|
||||
- **Full-suite & sanitizer checks**:
|
||||
- Full integrated RelWithDebInfo (`/tmp/void-w10-full`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly` with `_no_external_deps`); `VoidFoundationBench` (`rev=60ee28e4ca9b`) recorded.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w10-asan`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w10-tsan`, `Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`, 23 modules, `-Werror`): `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
### Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`, verified & merged to `main`)
|
||||
|
||||
- **Planning & contracts (`7f95f89`, `a8a9249`, `99203ce`, `c6789e7`, `95785ed`, `4ea6384`, `7c1fd3c`, `09789ae`, `3ce21be`)**: `W11-PLAN-OUTPUT.md`, PREFLIGHT 1 & 2 (`W11-PLAN-REV1-OUTPUT.md`, `W11-CONTRACT-R2.md`), spec reviews (`D-038`, `D-040`, `D-042`), error code reservations, area plans (`Functional.md`, `Runtime.md`, `IO.md`, `MIGRATION.md`).
|
||||
- **Execution-path implementation**:
|
||||
- `M-FUNCTIONAL-03` (`26edf65`): pure retry policy state machine + `retry_blocking`.
|
||||
- `M-TIME-03` (`99a1100`, `5c24f8e`): injected-clock `TimerQueue` + saturation helpers + `retry_async`.
|
||||
- `M-ASYNC-04` (`b2c8411`): `ThreadExecutor`, `FuturePool`, `AsyncChannel`, bounded `parallel_for`, `Executor.hpp` `spawn()` race fix.
|
||||
- `S-IO-03` (`1e752da`): bounded positional `File` workers, sync, active-cancel, shutdown core, D1 retire-once fixes.
|
||||
- `M-ASYNC-05` (`ef85ce0`): `EventBus` injected/joined lifecycle + `Observable` reentrancy queue.
|
||||
- `S-IO-04` (`50029e1`): `Driver::run`, `Pump.hpp` `pump_until`, `SystemAsync` shutdown conformance.
|
||||
- `S-RUNTIME-02/03` (`7bea7df`): `Host` explicit start, readiness, reverse failed-start cleanup, phased shutdown (`Lifecycle.hpp`, `Detail/HostCore.hpp`, `Host.hpp`).
|
||||
- **Adversarial review & post-fix hardening (`c6de784`)**:
|
||||
- Fresh adversarial review (`925b2cd8-7c57-4121-b6c5-b925c6a434f6`) returned `CHANGES_REQUIRED` (1 P1 + 7 P2 + 1 P3) across `EventBus.hpp`, `Pump.hpp`, `Driver.hpp`, `EpollDriver.cpp`, and `HostCore.hpp`.
|
||||
- Resolved all 9 findings in `c6de784` with 10 regression tests (`EventBus::finish_entry_dispatch` + pumping `self_join`; `pump_until` / `Driver::run` / `run_reactor_loop` `steady_clock` idle pacing + `EpollBackend` `EPOLLIN` disarming; `MockBackend::try_acquire` shutdown/closing TOCTOU guard; `HostCore` `start_running`/mutex sync, `flushing_exporters` single-drain poll, embedded background-worker `shutdown_blocking`, and incomplete `stopping_io` worker count). Post-fix review: `READY`.
|
||||
- **Integrated post-fix verification (`c6de784`, `-DVOID_WARNINGS_AS_ERRORS=ON`)**:
|
||||
- Targeted TSan & Runtime (`verify_w11_fixes.sh` + `verify_runtime.sh`): `110/110 ✔` TSan (`599.1ms`), all 6 Runtime gates passed (`37/37 ✔`, `nosys` `ctest` `2/2`, TSan, ASan, zero `Void/System/` includes in `include/Void/Runtime/**`).
|
||||
- Full RelWithDebInfo (`/tmp/void-w11-full`, 55 modules): `VoidTests` `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`) in `25.13s`; `ctest` `2/2` in `110.10s` (`VoidTests` `25.01s`, `VoidInstalledComponentConsumers` `85.09s` across all `41` consumers); `VoidFoundationBench` (`rev=c6de7842f732`, `/tmp/void-w11-full/post-w11.json`): `harness_empty_loop` `0.40ns`, `core_uuid_parse_hyphenated` `26.06ns`, `core_uuid_to_string` `18.06ns`, `core_hash_fnv1a64_256b` `186.38ns`, `core_hash_murmur3_256b` `69.57ns`, `functional_result_ok_chain` `1.16ns`, `functional_error_with_context` `61.13ns`, `math_checked_add_loop` `0.50ns`, `containers_spsc_ring_push_pop` `9.33ns`, `containers_lru_get_put` `22.02ns`, `binary_reader_u64_be` `1.19ns`, `data_json_parse_small_object` `302.08ns`, `data_json_serialize_small_object` `170.90ns`.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w11-asan`, 55 modules): `VoidTests` `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`) in `67.61s`, `0` leaks, `0` UB.
|
||||
- Wave 11 Debug TSan (`/tmp/void-w11-tsan`, 21 modules): unfiltered `VoidTests` `1,035` (`1,032 ✔`, `3 ⊘`, `0 ✘`) in `34.78s`; 3x 169-test stress loop `169/169 ✔` (`2.12s`, `3.07s`, `2.14s`), `0` data races / lock-order warnings.
|
||||
|
||||
## Ownership and next step
|
||||
|
||||
Waves 1–9 (`P0`, `P1`, all `P2` functional modules and `VL-001`..`VL-013`) are
|
||||
complete, verified, and merged to `main` via `--no-ff`. Next roadmap phase:
|
||||
**P3** (new single-node subsystems `Discovery`, `Scheduler`, `Messaging` +
|
||||
`NetworkedApplications` / `ReloadableApplications` platform integrations).
|
||||
Waves 1–11 (`P0`, `P1` incl. `M-FUNCTIONAL-03`/`M-TIME-03`, P2 execution/operations/storage/lifecycle/network modules, `VL-001`..`VL-013`, and P3 core subsystems `Discovery`, `Scheduler`, `Messaging`) are complete, verified, merged into `main`, and pushed. Next: **Wave 12** VoidForge upstream requests (`D-041`: `VL-STREAM-01`, `VL-PROC-01`, `VL-CRYPTO-01/02`, `VL-TEXT-01`, `VL-NET-W01`, `VL-NET-02`, `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01`, `VL-SQLITE-01..06`, `VL-SEC-01`) + root QA backlog (`X-QA-01..04`); then remaining P2 foundation tasks (`D-036`), P3 (`S-RPC-04/05`, `NetworkedApplications`, `ReloadableApplications`), and P4.
|
||||
@@ -128,8 +128,78 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
|
||||
| M-SHORTURL-01..04 | Frozen `V1` ABI preserved + additive `Void::ShortUrl::V2` (`kShortUrlErrorDomain = 28`, URL/key validation, base62 rejection-sampled keys, civil expiry, tombstone non-reuse, 24h idempotency, `LocalProvider`, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (capability pre-checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer (`691808e`) | [M-SHORTURL-01-04](tasks/M-SHORTURL-01-04.md) | VERIFIED | Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing` `ShortUrl*` 5/5 ✔, `ctest` `2/2` (`36.84s` incl. `ShortUrlOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
| S-RPC-01..03 | NEW `Void::RPC` subsystem (`kRpcErrorDomain = 29`), Wire v1 big-endian binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` with `AuthHook`, schema negotiation, timeout clamping, sanitized handler exceptions, `Registration::unregister_and_drain()`, `RpcOnly` consumer (`5184d1c`) | [S-RPC-01-03](tasks/S-RPC-01-03.md) | VERIFIED | Standalone `Rpc` 2/2 ✔, `ctest` `2/2` (`36.84s` incl. `RpcOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
|
||||
## Wave 10 — P3 Core Subsystems: Discovery, Scheduler, Messaging (`feat/roadmap-p3-wave10`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| S-DISCOVERY-01..04 | NEW `Void::Discovery` (`kDiscoveryErrorDomain = 30`, pure `Catalog`, atomic `replace_static()`, provider generation resets, local RAII `Registration` + steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` + self-cancel + `SelfJoin`, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` (identity-preserving TLS refresh; `RPC` remains Discovery-free), `DiscoveryOnly` consumer (`ec8c0bd`) | [S-DISCOVERY-01-04](tasks/S-DISCOVERY-01-04.md) | VERIFIED | Standalone `Discovery;DiscoveryRpc;Testing` `5/5 ✔` (`9.4ms`), `ctest` `2/2` (`11.26s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔ / 4 ⊘` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
| S-SCHEDULER-01..04 | NEW `Void::Scheduler` (`kSchedulerErrorDomain = 31`, monotonic min-heap, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` DST gap/fold & unknown-zone rejection, O(1) `CoalesceLatest` over >2.6M missed minutes, 100/pass `CatchUpBounded`, overlap policies, retries/dead-letter, revision invalidation watermark, `close_and_join`) + durable `Void::SchedulerStorage` (`StorageJobStore` exclusive owner lock, unique civil-slot dedup, crash `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause), `SchedulerOnly` consumer (`aaeab50`) | [S-SCHEDULER-01-04](tasks/S-SCHEDULER-01-04.md) | VERIFIED | Standalone `Scheduler;SchedulerStorage;System;Testing` `5/5 ✔` (`167.3ms`), `ctest` `2/2` (`30.06s` incl. `SchedulerOnly` `_no_external_deps`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
| S-MESSAGING-01..04 | NEW `Void::Messaging` (`kMessagingErrorDomain = 32`, explicit `PublishDurability`, nondurable `InMemoryQueue`, `Pending -> InFlight(gen, visibility) -> Acked \| Pending \| DeadLetter`, competing/`SingleActive` groups, stale-receipt fencing, idempotent ack, retries/DLQ, corrupt quarantine) + `Void::MessagingStorage` (`StorageQueue` durable batches, restart generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency, `BlockAtQuota` & clock-health pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`), `MessagingOnly` consumer (`60ee28e`) | [S-MESSAGING-01-04](tasks/S-MESSAGING-01-04.md) | VERIFIED | Standalone `Messaging;MessagingStorage;MessagingRpc;System;Testing` `4/4 ✔` (`217.4ms`), `ctest` `2/2` (`31.73s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
|
||||
All workers share the checkout and have disjoint file ownership defined in their
|
||||
persisted task specifications. Root owns all cross-cutting files and resolves contract
|
||||
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
|
||||
operations. Configured roles use XHigh; runtime model identity is not independently
|
||||
verified by the available spawn response.
|
||||
|
||||
## Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`)
|
||||
|
||||
Baseline: `main` at `38436b1`; full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules):
|
||||
`VoidTests` 1,484 discovered (1,480 ✔, 4 ⊘, 0 ✘) in 26.99 s; `ctest` 2/2 (111.68 s).
|
||||
Post-fix integrated verification (`c6de784`): adversarial review (`CHANGES_REQUIRED`: 1 P1 + 7 P2 + 1 P3 on `7bea7df`) fixed in `c6de784` (+10 regression tests, post-fix review `READY`); full 55-module RelWithDebInfo `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`), `ctest` `2/2` (`110.10s`, `41` consumers), Debug ASan+UBSan `1,694` (`0` leaks/UB), Debug TSan `1,035` (`1,032 ✔`, `3 ⊘`) + 3×`169/169 ✔` stress loop (`0` races).
|
||||
Decisions: D-033..D-043.
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| W11-PLAN | Architecture/task plan + REV1 addendum + R2 contract | [W11-PLAN](tasks/W11-PLAN.md), [output](tasks/W11-PLAN-OUTPUT.md), [REV1](tasks/W11-PLAN-REV1-OUTPUT.md), [R2](tasks/W11-CONTRACT-R2.md) | DONE | PREFLIGHT 1 & 2 resolved via REV1/D-038 & R2/D-040; spec review S1–S9, A1–A3 adopted via D-042 |
|
||||
| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | VERIFIED (`26edf65`) | Review W11-REVIEW-A1 READY; ResilienceAsync subset 475 (472 ✔, 3 ⊘), filtered 43/43, ctest 2/2, TSan 40/40 (0 races), ASan+UBSan 40/40; verified in post-W11 full suite (`c6de784`) |
|
||||
| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b) | [spec](tasks/M-TIME-03.md), [B1b](tasks/M-TIME-03-B1b.md) | VERIFIED (`99a1100`, `5c24f8e`) | W11-REVIEW-B1 & B1b READY; root 697 (694 ✔, 3 ⊘), TSan 33/33 + 5×15/15, ASan 468 ✔; verified in post-W11 full/TSan suites (`c6de784`) |
|
||||
| M-ASYNC-04 | ThreadExecutor, FuturePool, AsyncChannel, bounded ParallelFor (A2) + `spawn()` race & ParallelFor last-ref fixes | [spec](tasks/M-ASYNC-04.md) | VERIFIED (`b2c8411`) | 109/109, TSan 6×47/47, ASan 46/46; verified in post-W11 full/ASan/TSan+3×stress suites (`c6de784`) |
|
||||
| M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions (A3) + post-review capture-lifetime & pumping self-join fixes | [spec](tasks/M-ASYNC-05.md) | VERIFIED (`ef85ce0`, `c6de784`) | Targeted TSan 110/110 ✔; verified in post-W11 full/ASan (`1,690 ✔`) & TSan (`1,032 ✔` + 3×`169/169 ✔`) |
|
||||
| S-IO-03 | Bounded positional file workers, sync, active-cancel, shutdown core, D1 fixes (B2) + `MockBackend::try_acquire` TOCTOU & epoll `EPOLLIN` fixes | [spec](tasks/S-IO-03.md) | VERIFIED (`1e752da`, `c6de784`) | IO 37/37, TSan 37/37 + 30 loops, ASan clean; post-fix `c6de784` full/ASan/TSan+3×stress (`1,690 ✔` / `1,032 ✔` + 3×`169/169 ✔`) |
|
||||
| S-IO-04 | `Driver::run`, `Pump.hpp` `pump_until`, SystemAsync shutdown conformance (A4) + steady_clock idle pacing fixes | [spec](tasks/S-IO-04.md) | VERIFIED (`50029e1`, `c6de784`) | Targeted & integrated post-W11 RelWithDebInfo, `ctest` 2/2 (`41` consumers), ASan+UBSan, & TSan+3×stress (`0` races) |
|
||||
| S-RUNTIME-02 | Explicit start, readiness, reverse failed-start cleanup + concurrent start/shutdown synchronization | [spec](tasks/S-RUNTIME-02-03.md) | VERIFIED (`7bea7df`, `c6de784`) | `verify_runtime.sh` 6/6 gates (incl. `nosys` & zero `Void/System/` includes), full/ASan/TSan+3×stress (`c6de784`) |
|
||||
| S-RUNTIME-03 | Structured shutdown, repeated join, exporter-before-executor ordering + embedded background-worker & poll exporter fixes | [spec](tasks/S-RUNTIME-02-03.md) | VERIFIED (`7bea7df`, `c6de784`) | `RuntimeStart`/`RuntimeSignals`/`RuntimeShutdown`/`RuntimeHost` `37/37 ✔` (RelWithDebInfo, TSan, ASan) & post-W11 full/ASan/TSan (`c6de784`) |
|
||||
|
||||
P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`): folded into follow-on
|
||||
specs' observed baselines (D-035); not separately scheduled.
|
||||
|
||||
## VoidForge upstream requests (scheduled after Wave 11; D-037)
|
||||
|
||||
| ID | Priority | Request (VoidLibrary owns final signatures) | State |
|
||||
| --- | --- | --- | --- |
|
||||
| VL-STREAM-01 | P0 | Duplex HTTP response streaming: `HttpServer` duplex route + scoped response writer (begin/write_some/finish), per-exchange cancel/deadline, chunked/fixed/bodyless framing, pre-header error vs post-header abort | PLANNED |
|
||||
| VL-PROC-01 | P0 | Binary subprocess session (argv-only, env allowlist, independent stdout/stderr drain, bounded buffering, NUL-safe, distinguishable EOF/exit/timeout/cancel/truncation) | PLANNED |
|
||||
| VL-WIN-01 | P0 (later) | Windows HANDLE backend for VL-PROC-01 and HttpClient file transfer; client-only Net selection | PLANNED (deferred until requested) |
|
||||
| VL-WASM-01 | P1 | Bounded `Text/Diff.hpp` (`DiffLimits`, checked sizes, work/memory caps, cancellation, explicit incomplete result, reflection-free build) | PLANNED |
|
||||
| VL-MCP-01 | P1 | Generic MCP foundations (envelope, bounded JSON-RPC framing, Streamable HTTP + stdio bindings, auth callback); depends on VL-STREAM-01; RPC untouched | PLANNED |
|
||||
| VL-TOML-01 | P1 | Qualify `Data/Toml` limits for dotted keys/table paths/inline tables; API change only with reproducer | PLANNED |
|
||||
| VL-LUA-01 | P2 | Sandboxed Lua runtime (allocation/step budgets, no ambient IO) | PLANNED (backend decision needed) |
|
||||
| VL-STORE-01 | P2 | Native Storage conformance support for Forge | PLANNED |
|
||||
| VL-SQLITE-01 | P2 (non-blocking) | Structural SQLite primary/extended result codes (distinguish UNIQUE/CONSTRAINT vs BUSY/LOCKED) instead of message-only (`Sqlite/Types.hpp`, `Sqlite.cpp`) | VERIFIED (`0e8ee18`, merged `797ea63`): native primary/extended codes carried in `Error::system_code()` with a SQLite error category and `sqlite_native_code()` accessor |
|
||||
| VL-SQLITE-02 | P2 (non-blocking) | Documented `Unknown` commit outcome for failed COMMIT under WAL I/O error (like `Storage` `Outcome::Unknown`) | VERIFIED (`7eaa96f`, merged `103523f`): `TransactionState::Unknown` for unprovable COMMIT outcomes, Active retained when SQLite leaves the transaction open, stale commit/rollback rejected |
|
||||
| VL-SEC-01 | P2 (non-blocking) | Public CSPRNG bytes API (e.g. `Security::random_bytes(std::span<unsigned char>)`) | VERIFIED (`54d143b`, merged `a29c947`): `Security::random_bytes` fills from libsodium, wipes on fault, empty buffer is a no-op |
|
||||
| VL-SQLITE-03 | P3 (non-blocking) | Per-connection, phase-targetable `ScopedFaultGuard` (incl. "COMMIT succeeded but reported failure") | VERIFIED (`3b1ef4b`, merged `2532485`): `FaultConfig::connection` and `FaultPhase` targeting prepare/step/exec/commit/checkpoint/close, isolation and phase-mismatch tests |
|
||||
| VL-SQLITE-04 | P3 (non-blocking) | Per-call busy-timeout override | VERIFIED (`7e5cf73`, merged `a1308a4`): scoped `BusyTimeoutOverride` with exact nested restore and negative-timeout rejection |
|
||||
| VL-NET-W01 | P2 (hygiene) | `src/Net/HttpServer.cpp:1797,1871` ignore `read()`/`write()` results (`-Wunused-result` under consumer flags, likely `_FORTIFY_SOURCE`); VoidLibrary's own `-Werror` build at `38436b1` passes | PLANNED |
|
||||
| VL-SQLITE-05 | P2 (non-blocking) | Write admission and `wal_checkpoint_recommended` use on-disk `-wal` size, which passive checkpoints never shrink, so `begin(Immediate)` stays `overloaded`; admit on un-checkpointed frames or truncate on admission failure (`Sqlite.cpp` ~:417-423, :1756-1762, :1918-1923) | PLANNED |
|
||||
| VL-SQLITE-06 | P2 (non-blocking) | `Statement::step`/`exec` do not detect SQLite automatic rollback (FULL/IOERR/NOMEM/BUSY/INTERRUPT) via `sqlite3_get_autocommit`, so `Transaction` stays `Active` and later statements run in autocommit (`Sqlite.cpp` ~:884-910) | PLANNED |
|
||||
|
||||
## Quality findings surfaced during Wave 11 (backlog, root-owned)
|
||||
|
||||
| ID | Finding | Source | State |
|
||||
| --- | --- | --- | --- |
|
||||
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | VERIFIED (`77a2bce`): `tests/CMakeLists.txt` applies `-Wall -Wextra -Wpedantic -Werror` to `VoidTests` (with `-Wno-subobject-linkage` for GCC coroutine-frame noise); exposed warnings fixed in `Core/Meta.hpp` and `Time/Bench.cpp` |
|
||||
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | VERIFIED (`430deab`, merged `2501c4d`): `TestResult::failed_assertions` is counted in `Assert.cpp` at record time and both Runner paths use it, keeping the bounded retention for reporting; regression test `testing_runner_counts_failure_after_retention_cap` failed before and passes after; follow-up `898968d` resets the tally in the TestingMock failure-capture helper |
|
||||
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | VERIFIED (`4bc8a7c`, merged `df41037`): `VoidTestScanner.cmake` joins wrapped `Test`/`DisabledTest` declarations; `ScannerWrapped` fixture covers wrapped return type, name and fixture member (4/4 discovered) |
|
||||
| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) |
|
||||
|
||||
## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041)
|
||||
|
||||
| ID | Priority | Request | State |
|
||||
| --- | --- | --- | --- |
|
||||
| VL-CRYPTO-01 | P1 | Generic `Crypto::hmac(HashAlgorithm, key, message)` incl. HMAC-SHA1 (TOTP RFC 6238/4226); RFC 2202 vectors | PLANNED |
|
||||
| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED |
|
||||
| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED |
|
||||
| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED |
|
||||
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | VERIFIED (`65185f2`): added `async_retry_backoff_stop_reason_mapping`, `async_retry_stop_poll_handshake_alternation` (stop-first and poll-first orders) and `async_retry_throwing_classifier_propagates` |
|
||||
@@ -297,3 +297,29 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
|
||||
| Wave 9 full Debug ASan+UBSan (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w9-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 48 modules | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB |
|
||||
| Wave 9 Debug TSan (`5184d1c`) | `dev cpp-gcc -p openssl -p libsodium` Debug TSan (`-Werror`, `/tmp/void-w9-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 22 modules (`Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`) | **PASSED**: `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-W9 Benchmark (`5184d1c`, `rev=5184d1cf8cdd`) | `/tmp/void-w9-full/benchmarks/VoidFoundationBench --json /tmp/void-w9-full/post-w9.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.49ns, `core_uuid_parse_hyphenated` 25.02ns, `core_uuid_to_string` 16.55ns, `core_hash_fnv1a64_256b` 183.63ns, `core_hash_murmur3_256b` 69.12ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.06ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.93ns, `containers_lru_get_put` 21.47ns, `binary_reader_u64_be` 1.15ns, `data_json_parse_small_object` 297.72ns, `data_json_serialize_small_object` 172.85ns |
|
||||
| Wave 10 `Discovery` & `DiscoveryRpc` standalone (`ec8c0bd`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m1`, `Discovery;DiscoveryRpc;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `9.4ms` (`Catalog` 4/4, `EndpointAdapter` 1/1); `ctest` `2/2` in `11.26s` (`VoidTests` `0.60s`, `VoidInstalledComponentConsumers` `10.66s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`) |
|
||||
| Wave 10 `Scheduler` & `SchedulerStorage` standalone (`aaeab50`) | `dev cpp-gcc -c` zero external deps RelWithDebInfo (`-Werror`, `/tmp/void-w10-m2`, `Scheduler;SchedulerStorage;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `167.3ms` (`Scheduler` 3/3, `StorageJobStore` 2/2); `ctest` `2/2` in `30.06s` (`VoidTests` `16.51s`, `VoidInstalledComponentConsumers` `13.54s` incl. `SchedulerOnly` `_no_external_deps`) |
|
||||
| Wave 10 `Messaging`, `MessagingStorage`, & `MessagingRpc` standalone (`60ee28e`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m3`, `Messaging;MessagingStorage;MessagingRpc;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `4/4 ✔` in `217.4ms` (`Messaging` 1/1, `StorageQueue` 2/2, `RpcAdapter` 1/1); `ctest` `2/2` in `31.73s` (`VoidTests` `16.09s`, `VoidInstalledComponentConsumers` `15.63s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`) |
|
||||
| Wave 10 integrated RelWithDebInfo + consumers (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w10-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly`) |
|
||||
| Wave 10 full Debug ASan+UBSan (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w10-asan`), 55 modules | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB |
|
||||
| Wave 10 Debug TSan (`60ee28e`) | `dev cpp-gcc -p openssl` Debug TSan (`-Werror`, `/tmp/void-w10-tsan`), 23 modules (`Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`) | **PASSED**: `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-W10 Benchmark (`60ee28e`, `rev=60ee28e4ca9b`) | `/tmp/void-w10-full/benchmarks/VoidFoundationBench --json /tmp/void-w10-full/post-w10.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.18ns, `core_uuid_to_string` 16.66ns, `core_hash_fnv1a64_256b` 182.46ns, `core_hash_murmur3_256b` 68.53ns, `functional_result_ok_chain` 1.14ns, `functional_error_with_context` 59.10ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.87ns, `binary_reader_u64_be` 1.14ns, `data_json_parse_small_object` 287.18ns, `data_json_serialize_small_object` 164.76ns |
|
||||
| Wave 11 adversarial review & targeted fixes (`c6de784`) | Fresh adversarial review (`925b2cd8-7c57-4121-b6c5-b925c6a434f6`) on `7bea7df` -> `c6de784` (`verify_w11_fixes.sh` + `verify_runtime.sh`: Debug TSan `Async;IO;Runtime;System;Testing` + 6 Runtime gates, `-Werror`) | Review `CHANGES_REQUIRED` (1 P1 + 7 P2 + 1 P3) resolved in `c6de784` (+10 regression tests); post-fix review `READY`. Targeted TSan `110/110 ✔` in `599.1ms`; `verify_runtime.sh` 6/6 gates passed (`37/37 ✔` RelWithDebInfo, `nosys` `ctest` 2/2, TSan, ASan `224.8ms`, zero `Void/System/` includes in `include/Void/Runtime/**`) |
|
||||
| Wave 11 integrated RelWithDebInfo + consumers (`c6de784`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w11-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,694` discovered (`1,690 ✔`, `4 ⊘` skipped, `0 ✘`) in `25.13s`; `ctest` `2/2` in `110.10s` (`VoidTests` `25.01s`, `VoidInstalledComponentConsumers` `85.09s` across all `41` consumers) |
|
||||
| Wave 11 full Debug ASan+UBSan (`c6de784`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w11-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 55 modules | **PASSED**: `1,694` discovered (`1,690 ✔`, `4 ⊘` skipped, `0 ✘`) in `67.61s`, `0` leaks, `0` UB |
|
||||
| Wave 11 Debug TSan + 3x stress loop (`c6de784`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w11-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 21 modules (`Async;IO;IPC;SystemAsync;Storage;Runtime;ConfigurationAsync;System;Testing`) | **PASSED**: unfiltered `1,035` (`1,032 ✔`, `3 ⊘` skipped, `0 ✘`) in `34.78s`; 3x Wave 11 stress loop `169/169 ✔` (`2.12s`, `3.07s`, `2.14s`), `0` data races / lock-order warnings |
|
||||
| Post-W11 Benchmark (`c6de784`, `rev=c6de7842f732`) | `/tmp/void-w11-full/benchmarks/VoidFoundationBench --json /tmp/void-w11-full/post-w11.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.06ns, `core_uuid_to_string` 18.06ns, `core_hash_fnv1a64_256b` 186.38ns, `core_hash_murmur3_256b` 69.57ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 61.13ns, `math_checked_add_loop` 0.50ns, `containers_spsc_ring_push_pop` 9.33ns, `containers_lru_get_put` 22.02ns, `binary_reader_u64_be` 1.19ns, `data_json_parse_small_object` 302.08ns, `data_json_serialize_small_object` 170.90ns |
|
||||
|
||||
## Applications-stack example sanitizer matrix
|
||||
|
||||
Built as installed-package consumers against the local Void install; every suite run
|
||||
with `halt_on_error=1` (ASan leak detection enabled).
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| Distributed host-graph ASan+UBSan (`91e7a90`) | Debug `-fsanitize=address,undefined`, `ASAN_OPTIONS=detect_leaks=1`, `UBSAN_OPTIONS=halt_on_error=1`: ctest `8/8` passed, `0` leaks, `0` UB |
|
||||
| Distributed host-graph TSan (`91e7a90`) | Debug `-fsanitize=thread`, `TSAN_OPTIONS=halt_on_error=1`: ctest `8/8` passed, `0` data races |
|
||||
| Reloadable host ASan+UBSan (`2da3971`) | Debug ASan+UBSan, leak detection on: ctest `7/7` passed, `0` leaks, `0` UB (includes real subprocess supervision tests) |
|
||||
| Networked KV ASan+UBSan (`57ebf31`) | Debug ASan+UBSan, leak detection on: ctest `7/7` passed, `0` leaks, `0` UB |
|
||||
| Networked KV TSan (`57ebf31`) | Debug `-fsanitize=thread`: ctest `7/7` passed, `0` data races |
|
||||
| Applications-stack workload baseline (`b70306f`) | `distributed_host_graph_bench --json <tmp>/host-graph-baseline.json` (Debug, warmup=3, 5 reps × 200 ops, p50/p95/p99 over all samples, 95% CI of the mean); ctest `9/9` | `kv_propose_3node` 2.74/9.25/15.67µs (mean 3.41µs, CI [3.25, 3.58]), `kv_quorum_read_3node` 0.43/0.49/0.52µs (mean 0.43µs), `queue_publish_claim_ack_3node` 66.7/117.3/125.0µs (mean 70.7µs), `http_peer_health_roundtrip` 255.6/395.7/1281.5µs (mean 292.8µs); no latency threshold asserted |
|
||||
@@ -0,0 +1,228 @@
|
||||
# M-ASYNC-04 — Bounded ThreadExecutor, FuturePool, cancellable AsyncChannel, bounded ParallelFor
|
||||
|
||||
Task ID: M-ASYNC-04
|
||||
Role: sonnet-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step A2. Repo VoidLibrary, branch `feat/roadmap-p2-wave11`. You work in an isolated
|
||||
git worktree of the HEAD given in your prompt (it includes M-FUNCTIONAL-03 and the M-TIME-03
|
||||
`Async/Timer.hpp`); cwd = worktree root. Never read the user's untracked files in the main checkout.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed.
|
||||
- Observed source (M-ASYNC-01 characterization folded in, D-035):
|
||||
- `include/Void/Async/Executor.hpp:58-113`: `Executor` base (`post`, `try_post`, `post_completion`,
|
||||
reservation API `supports_reservation/try_reserve_slot/commit_reserved/release_reserved`,
|
||||
`has_background_workers`, `is_executor_thread` via `detail::ExecutorThreadGuard` ~:86-96).
|
||||
`ManualExecutor` (:120-254) is the only executor; its bound excludes running work (:216-228) and
|
||||
`post()` bypasses the bound (:128-135). No thread-backed executor exists.
|
||||
- `include/Void/Async/ThreadPool.hpp` (`Void::Concurrency::ThreadPool`): `max_queue == 0` unbounded,
|
||||
bound counts only the queue, `submit` throws after stop, `try_submit` returns `nullopt` for both
|
||||
full and stopped; includes Log.
|
||||
- `include/Void/Async/Channel.hpp` (`Concurrency::Channel`): blocking only; out of scope (capacity-0
|
||||
deadlock is a recorded residual).
|
||||
- `include/Void/Async/ParallelFor.hpp` (`Void::Concurrency::parallel_for`): one future per index;
|
||||
on the first throwing `fut.get()` returns without joining the rest (lifetime hazard).
|
||||
- Root prep `7f95f89` added `AsyncErrorCode::closed = 9` (→ `ErrorKind::cancelled`).
|
||||
- M-TIME-03 provides `include/Void/Async/Timer.hpp` (`TimerQueue`, `TimerHandle`, `TimerEvent`,
|
||||
`schedule_at(when, callback(TimerEvent) noexcept)`; `cancel()==false` means fired-or-firing).
|
||||
- Requirements: roadmap row M-ASYNC-04 ("Bounded executors, cancellable channels, future pool adapter,
|
||||
ParallelFor | Bounds include running work; producer stop and close-drain deterministic; chunk
|
||||
errors join"); C-03..C-05; decisions D-038, D-040, D-W11-10, D-W11-13.
|
||||
- MANDATORY design sources: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-ASYNC-04,
|
||||
`W11-PLAN-REV1-OUTPUT.md` F7, F11, F12, P3 (ThreadExecutor), `W11-CONTRACT-R2.md` N5.
|
||||
Precedence R2 > REV1 > PLAN.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
NEW `include/Void/Async/ThreadExecutor.hpp`, `include/Void/Async/FuturePool.hpp`,
|
||||
`include/Void/Async/AsyncChannel.hpp`; EDIT `include/Void/Async/ParallelFor.hpp` (NEW bounded overload
|
||||
+ legacy overload joins all futures before rethrowing); NEW tests
|
||||
`tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`, `ThreadPool.hpp`, `Channel.hpp` changes;
|
||||
`async_wait_for_capacity` and channel byte budget (D-W11-13); EventBus/Observable (M-ASYNC-05);
|
||||
build files.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Async/{Executor,Operation,TaskScope,Task,ThreadPool,ParallelFor,Timer}.hpp`,
|
||||
`include/Void/Async/Detail/Types.hpp`, `tests/standalone/Async/{OperationScope,Executor,ParallelFor,ThreadPool}.cpp`,
|
||||
and the design sources in §1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/ThreadExecutor.hpp` (NEW), `include/Void/Async/FuturePool.hpp` (NEW),
|
||||
`include/Void/Async/AsyncChannel.hpp` (NEW), `include/Void/Async/ParallelFor.hpp`,
|
||||
`tests/standalone/Async/ThreadExecutor.cpp`, `tests/standalone/Async/FuturePool.cpp`,
|
||||
`tests/standalone/Async/AsyncChannel.cpp`, `tests/standalone/Async/ParallelForBounded.cpp` (all NEW tests).
|
||||
Forbidden: every other path. An IO worker may run concurrently in another worktree. No git
|
||||
commit/branch/stash/reset.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY:
|
||||
- ThreadExecutor: `create` starts no threads; `start()` once; a `before_worker_start(i)` hook error or
|
||||
a caught `std::system_error` from `std::thread` joins started workers and returns an error (shared
|
||||
path). Bound = queued + running normal-lane work (`max_admitted >= 1`); `try_post` → `overloaded`
|
||||
at the bound; a slot is released only after the resumed handle returns. Every resume runs inside
|
||||
`detail::ExecutorThreadGuard`. Legacy `post()` never rejects (counted; may exceed the bound); after
|
||||
`close()` legacy `post()` goes to the completion lane (counted). `post_completion` uses a reserved,
|
||||
prioritized lane that drains after `close()`. `join()` = close + drain both lanes until empty and
|
||||
nothing running + join; on a worker returns `self_join`. After join, posts resume inline on the
|
||||
caller (counted `inline_after_join`), never dropped. No drain cap (C-03); a self-reposting handle
|
||||
that prevents join is a documented caller error. `~ThreadExecutor` without join = close()+join();
|
||||
on its own worker → stderr diagnostic + `std::terminate`. NEW `idle()` (both lanes empty, nothing
|
||||
running). Reservation API implemented and compatible with `TaskScope`.
|
||||
- FuturePool: reserve-then-transfer; on rejection the callable is NOT moved; exceptions go to the
|
||||
future; bound includes running work.
|
||||
- AsyncChannel (F7 + N5): one mutex for buffer and both waiter lists; waiter nodes with state
|
||||
`{linked, claimed, cancelled, timed_out, closed}`; pairing sender/receiver happens in one critical
|
||||
section (unlink+claim the waiter, then move the value) so a value is always in exactly one place
|
||||
(sender node, buffer, or receiver slot). Stop callbacks and timer callbacks take the same lock:
|
||||
if still `linked` → unlink + `cancelled`/`timed_out` (sender keeps/gets back its value); if
|
||||
`claimed` → no-op. Timer callbacks capture shared waiter state (`shared_ptr` control block) or a
|
||||
`weak_ptr` to the channel + waiter id looked up under the lock — NEVER a raw pointer into a
|
||||
coroutine frame (N5). Every resume via `post_completion` after unlock. A wait with a deadline but
|
||||
no `timers` → `invalid_argument`. `close()` gives waiting senders `closed` + their value; receivers
|
||||
drain the buffer FIFO then get `closed`. `capacity == 0` → `invalid_argument` at create.
|
||||
- Bounded parallel_for: shared `detail::PForState` (decay-copied `F`, chunk counter, error slots);
|
||||
runners submitted with `try_submit`; if rejected the caller runs chunks inline; no new chunk after
|
||||
stop or (with `stop_on_error`) an error; the caller waits for EVERY submitted runner future
|
||||
(including never-started ones); reported error = lowest-indexed failed chunk; nested use on the
|
||||
same pool from a pool worker is documented unsupported. Legacy overload waits for all futures
|
||||
before rethrowing the first exception (D-W11-10).
|
||||
|
||||
|
||||
### Amendments from W11-SPEC-REVIEW-1 (MANDATORY; override earlier text where they differ)
|
||||
Source: `docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md` A1–A3 + P3 (decision D-042).
|
||||
- A2 no-worker join: admission before `start()` queues normally. When no worker is running,
|
||||
`join()` and the destructor drain both lanes inline on the caller under `ExecutorThreadGuard`
|
||||
(counted as `inline_after_join`) and never wait. `start()` after `close()` or after a successful
|
||||
`start()` → `invalid_argument`; after a failed `start()` it may be retried.
|
||||
- A3 reservations: a reserved slot counts in `admitted()` and in the bound; `try_reserve_slot` after
|
||||
`close()` → `stopped`; a reservation taken before `close()` stays binding (`commit_reserved` after
|
||||
`close()` enqueues normally); `join()` also waits until no reservation is outstanding.
|
||||
- P3: `make_async_error(ChannelError, ...)` is `inline`. AsyncChannel deadlines are judged by
|
||||
`timers->clock()`; check stop, then deadline, then "deadline without timers" → `invalid_argument`,
|
||||
before any state change (value returned in `SendFailure`); `TimerEvent::closed` → `cancelled`;
|
||||
`schedule_at` failure `overloaded` → `ChannelError::overloaded`, `stopped` → `cancelled`;
|
||||
`max_waiters` applies per direction, 0 → `invalid_argument`; frames hold `shared_from_this()`;
|
||||
never construct or destroy a `std::stop_callback` while holding the channel mutex; destroying a
|
||||
suspended Task is a caller error; the resume executor must outlive every pending resume; FIFO means
|
||||
per-producer order. TimerQueue facts (from the M-TIME-03 implementation): `cancel() == true`
|
||||
destroys the callback on the caller's thread before returning — so never call `TimerHandle::cancel()`
|
||||
while holding the channel mutex if the callback's destructor could take it; `cancel() == false`
|
||||
means fired-or-firing. parallel_for: at most `max_concurrency` chunks run at once (counting the
|
||||
caller when it runs inline); `Kind::rejected` is not produced in this wave; precedence
|
||||
`invalid_argument` > `failed` > `stopped`; `first >= last` → success; compute the range in the
|
||||
unsigned type of `I`. ThreadExecutor: `idle()`/`stats()` are snapshots; the switch to inline mode
|
||||
happens under the executor mutex; `admitted()` = queued + running + reserved. FuturePool: if
|
||||
creating the frame throws, release the slot and rethrow. `ExecutorThreadGuard` is at
|
||||
`Executor.hpp:32-51`. Stop and report if `Async/Timer.hpp` is missing or differs from M-TIME-03 §7.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Async {
|
||||
struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096};
|
||||
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{}; };
|
||||
struct ThreadExecutorStats { std::size_t queued, running, completion_queued;
|
||||
std::uint64_t rejected, legacy_posts, inline_after_join; };
|
||||
class ThreadExecutor final : public Executor { public:
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {});
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
void post(std::coroutine_handle<>) override;
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override;
|
||||
void post_completion(std::coroutine_handle<>) override;
|
||||
[[nodiscard]] bool supports_reservation() const noexcept override;
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
|
||||
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
|
||||
[[nodiscard]] bool has_background_workers() const noexcept override;
|
||||
void close() noexcept; [[nodiscard]] Void::Result::Result<void> join();
|
||||
[[nodiscard]] bool idle() const noexcept; [[nodiscard]] std::size_t admitted() const noexcept;
|
||||
[[nodiscard]] ThreadExecutorStats stats() const noexcept; ~ThreadExecutor() override; };
|
||||
class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept;
|
||||
template <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
|
||||
try_submit(F&& f); };
|
||||
enum class ChannelError : std::uint8_t { closed, empty, full, cancelled, timed_out, overloaded, invalid_argument };
|
||||
struct ChannelOptions { std::size_t capacity{1024}; std::size_t max_waiters{1024}; TimerQueue* timers{nullptr}; };
|
||||
template <class T> struct SendFailure { ChannelError error; T value; };
|
||||
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
|
||||
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
|
||||
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
|
||||
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
|
||||
[[nodiscard]] std::expected<T, ChannelError> try_receive();
|
||||
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
|
||||
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
|
||||
[[nodiscard]] inline Void::Result::Error make_async_error(ChannelError, std::string message = {});
|
||||
}
|
||||
namespace Void::Concurrency { // ParallelFor.hpp (NEW overload)
|
||||
struct ParallelForOptions { std::size_t grain{1}; std::size_t max_concurrency{0}; std::stop_token stop{}; bool stop_on_error{true}; };
|
||||
struct ParallelForError { enum class Kind : std::uint8_t { invalid_argument, rejected, stopped, failed } kind;
|
||||
std::size_t chunks_total{0}, chunks_started{0}, chunks_failed{0};
|
||||
std::optional<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
|
||||
template <std::integral I, std::invocable<I> F>
|
||||
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
|
||||
}
|
||||
```
|
||||
`ChannelError` maps into `kAsyncErrorDomain` via existing codes (`closed`→`AsyncErrorCode::closed`,
|
||||
`cancelled`→`cancelled`, `timed_out`→`timeout`, `overloaded`/`full`→`overloaded`, `empty`/`invalid_argument`→
|
||||
`invalid_argument`); the overload must not collide with existing `make_async_error` overloads.
|
||||
`max_concurrency == 0` = the pool's thread count; `grain == 0` → `invalid_argument`. Unchanged 1.x:
|
||||
`ManualExecutor`, `ThreadPool`, `Channel`, legacy `parallel_for` signatures, `spawn`, `schedule_on`.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: M-ASYNC-03 (done), M-TIME-03 Timer (gate G2, present in your base). Downstream:
|
||||
S-RUNTIME-02 uses `ThreadExecutor` (`create/start/close/join/idle/admitted/stats`), M-ASYNC-05 may use
|
||||
`ThreadExecutor` in tests. Keep §7 exactly. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stop vs send vs receive vs close vs timer races (TSan); move-only `T`; exceptions thrown by `T`'s move
|
||||
constructor (document strong guarantee where possible); bounded waiters; no busy-waiting in join;
|
||||
no user code under locks; hook throwing; zero workers rejected at create.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
Tests (all pass; TSan 0 races; ASan+UBSan 0 errors):
|
||||
- `ThreadExecutor.cpp`: `thread_executor_create_starts_no_threads`, `thread_executor_bound_includes_running_work`,
|
||||
`thread_executor_reservation_with_task_scope_preserves_task`, `thread_executor_completion_lane_bypasses_full_normal_lane`,
|
||||
`thread_executor_close_rejects_normal_drains_completion`, `thread_executor_join_self_join_on_worker`,
|
||||
`thread_executor_partial_start_failure_joins_started`, `thread_executor_system_error_path_shared_with_hook`,
|
||||
`thread_executor_legacy_post_spawn_schedule_on_compat`, `thread_executor_inline_after_join_counted`,
|
||||
`thread_executor_stress_tsan`.
|
||||
- `FuturePool.cpp`: `future_pool_overloaded_does_not_consume_callable`, `future_pool_stopped_after_close`,
|
||||
`future_pool_exception_in_future`, `future_pool_bound_includes_running`.
|
||||
- `AsyncChannel.cpp`: `channel_zero_capacity_invalid`, `channel_try_send_full_returns_value`,
|
||||
`channel_send_waits_resumes_on_receive`, `channel_producer_stop_returns_value_cancelled_once`,
|
||||
`channel_receiver_stop_after_claim_delivers_value_no_loss`, `channel_sender_stop_vs_receive_race_exactly_once_tsan`
|
||||
(10,000 iterations; multiset sent == received ∪ returned), `channel_close_wakes_senders_with_value_and_drains_receivers`,
|
||||
`channel_deadline_requires_timers`, `channel_deadline_times_out_once_manual_clock_poll`,
|
||||
`channel_timer_close_settles_waiter_cancelled`, `channel_timer_fire_after_waiter_destroyed_safe`,
|
||||
`channel_waiter_bound_overloaded`, `channel_move_only_values`, `channel_mpmc_fifo_tsan`,
|
||||
`channel_deadline_check_order_returns_value`.
|
||||
- Additional ThreadExecutor tests: `thread_executor_join_without_start_drains_inline`,
|
||||
`thread_executor_start_twice_and_after_close_invalid`, `thread_executor_reservation_across_close_binding`.
|
||||
- `ParallelForBounded.cpp`: `parallel_for_bounded_grain_and_concurrency_limit`,
|
||||
`parallel_for_bounded_stop_joins_started_no_new_chunks`, `parallel_for_bounded_errors_join_all_lowest_index_reported`,
|
||||
`parallel_for_bounded_zero_grain_invalid`, `parallel_for_bounded_rejected_pool_runs_inline`,
|
||||
`parallel_for_bounded_waits_all_submitted_runners`, `legacy_parallel_for_exception_joins_all`.
|
||||
- Existing `ParallelFor`, `ThreadPool`, `ThreadPoolBackpressure`, `Channel`, `OperationScope`, `Executor`,
|
||||
`Coro`, `TimerQueue` tests pass unchanged. `-Werror` clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4 --parallel 8 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor|Coro|TimerQueue)\." && ctest --test-dir /tmp/void-w11-async4 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-tsan --parallel 8 && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in ThreadExecutor FuturePool AsyncChannel ParallelForBounded; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-asan --parallel 8 && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions; no disabled warnings; no change to 1.x
|
||||
semantics other than D-W11-10. Stop and report BLOCKED if the contract needs a forbidden-file edit,
|
||||
the reservation API cannot be satisfied as specified, or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040 under user decisions D-027/D-029/D-031. Listed files only; no
|
||||
commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance
|
||||
criterion; commands with cwd/results (counts, TSan/ASan); checks not run; residual risks; integration
|
||||
notes (worktree path). Do not spawn children.
|
||||
@@ -0,0 +1,151 @@
|
||||
# M-ASYNC-05 — EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling
|
||||
|
||||
Task ID: M-ASYNC-05
|
||||
Role: sonnet-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step A3 (after A2 M-ASYNC-04 is committed). Repo VoidLibrary, branch
|
||||
`feat/roadmap-p2-wave11`. Isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘).
|
||||
- Observed source (M-ASYNC-01 characterization folded in):
|
||||
- `include/Void/Async/EventBus.hpp` (`Void::EventBus`): sync `publish` iterates the live vector without
|
||||
the lock (~:156-164) so subscribe/unsubscribe during dispatch is UB; Async mode starts a private
|
||||
thread in the constructor (~:43-48); the async snapshot copies `std::function`s so `unsubscribe`
|
||||
cannot retract queued copies (~:167-169); a handler exception escapes the worker loop and terminates
|
||||
(~:248-269); task queue and handler list unbounded (~:272-278); `Subscription::reset` does not join
|
||||
(~:115-121); `Subscription` holds a raw `EventBus*` (~:137-146); `flush()` returns void (~:193-201).
|
||||
- `include/Void/Async/Observable.hpp`: `Observable`/`Signal` iterate live vectors (~:74-77, :116-119);
|
||||
reentrant use is UB; no threading policy; on throw the value stays new (~:40-42).
|
||||
- Existing tests: `tests/standalone/Async/{EventBus,EventBusAsync,Observable}.cpp` (12/4/14).
|
||||
- Available from A2: `Async::ThreadExecutor` (bounded, `join`, `is_executor_thread`), `ManualExecutor`.
|
||||
- Requirements: roadmap row M-ASYNC-05 ("EventBus/Observable snapshot dispatch, joined subscriptions,
|
||||
injected scheduling | Reentrancy, callback throw and unsubscribe races leave no captured state in use
|
||||
after join"); C-03/C-05; decisions D-W11-06 (accepted with conditions), D-038, D-040 (N6, P3-8).
|
||||
- MANDATORY design sources: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-ASYNC-05,
|
||||
`W11-PLAN-REV1-OUTPUT.md` F12 + P3 (Observable/Signal, captured-state tests), `W11-CONTRACT-R2.md` N6.
|
||||
Precedence R2 > REV1 > PLAN.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
EDIT `include/Void/Async/EventBus.hpp` and `include/Void/Async/Observable.hpp`; NEW tests
|
||||
`tests/standalone/Async/EventBusJoin.cpp`, `tests/standalone/Async/ObservableReentrancy.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: Executor/Operation/TaskScope/ThreadExecutor changes, build files, other modules.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Async/{EventBus,Observable,Executor,TaskScope,ThreadExecutor}.hpp`, the three existing
|
||||
tests, and the design sources in §1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/EventBus.hpp`, `include/Void/Async/Observable.hpp`,
|
||||
`tests/standalone/Async/EventBusJoin.cpp` (NEW), `tests/standalone/Async/ObservableReentrancy.cpp` (NEW).
|
||||
Forbidden: every other path, including the existing EventBus/Observable test files. Other implementers
|
||||
work concurrently in other worktrees (IO; Runtime). No git operations except the authorized fast-forward.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY:
|
||||
- Subscription state in shared ownership; every dispatch (all modes) iterates a snapshot of entries and
|
||||
checks a per-entry live flag before invoking; callbacks run outside locks.
|
||||
- NEW `Mode::Injected` + `EventBus(Async::Executor&, BusOptions)`: no private thread; dispatch frames
|
||||
capture `shared_ptr<detail::BusCore>`; bounded subscriptions/admitted dispatches → `overloaded`;
|
||||
Injected and Async modes catch handler exceptions and route them to `error_sink` (outside locks),
|
||||
counting `callback_failures`; a throwing `error_sink` is caught and counted (D-W11-06 condition).
|
||||
Sync `publish` keeps 1.x exception propagation.
|
||||
- `Subscription::close_and_join()`: suppresses admitted-but-not-started deliveries, waits for in-flight
|
||||
callbacks on other threads, resets the handler (releasing captured state) before returning; on its own
|
||||
callback thread → `self_join` (self-unsubscribe via legacy `unsubscribe`/`reset` still works).
|
||||
- 1.x `unsubscribe` in `Mode::Async` still delivers already-queued copies (pinned test).
|
||||
- `EventBus::close_and_join()` / `close_and_join_pumping(ManualExecutor&)`; `flush_blocking()`
|
||||
(`self_join` on an executor thread or inside a bus callback; `invalid_argument` on a ManualExecutor);
|
||||
`flush_pumping(ManualExecutor&)`; legacy `flush()` in Injected mode calls `flush_blocking()` and
|
||||
discards the error (never deadlocks).
|
||||
- `~EventBus` (N6): gates every admitted-but-not-started delivery on every thread before returning
|
||||
(core `closed` flag checked under the core lock before each delivery starts); waits for callbacks
|
||||
running on OTHER threads, excluding the current thread's own in-progress callback (thread-local
|
||||
dispatch depth); documented residual: destroying a bus from inside a callback that another thread's
|
||||
callback waits on can deadlock (caller error). On a ManualExecutor it pumps (TaskScope pattern).
|
||||
- Observable/Signal (REV1 P3): documented single-threaded, not thread-safe, reentrancy-safe. For
|
||||
copyable `T` (`std::copy_constructible`): nested `set` updates the value immediately and queues
|
||||
`(old, new)` copies delivered FIFO after the current pass, bounded at
|
||||
`kMaxPendingNotifications = 1024`; overflow keeps the new value and counts a dropped notification;
|
||||
`try_set(T)` (copyable only) → `overloaded` without changing the value; `dropped_notifications()`.
|
||||
Move-only `T`: 1.x immediate recursive notification over a listener snapshot, no queue, no `try_set`.
|
||||
Unsubscribe during a pass skips that listener for the rest of the pass; subscribe during a pass is not
|
||||
in the current pass. On a throw: the value stays new, dispatch depth restored, that pass's queued
|
||||
notifications dropped and counted, exception propagates from the outermost `set`/`emit`.
|
||||
`Signal<Args...>` follows the same rule when all decayed `Args` are copyable (queue is `mutable`).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::EventBus {
|
||||
enum class Mode { Sync, Async, Injected }; // NEW enumerator appended
|
||||
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
|
||||
std::function<void(std::exception_ptr)> error_sink{}; };
|
||||
// EventBus additions (existing API unchanged):
|
||||
explicit EventBus(Void::Async::Executor& executor, BusOptions = {});
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
|
||||
[[nodiscard]] Void::Result::Result<void> flush_blocking();
|
||||
[[nodiscard]] Void::Result::Result<void> flush_pumping(Void::Async::ManualExecutor&);
|
||||
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
|
||||
// Subscription addition: [[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
}
|
||||
// Observable.hpp: inline constexpr std::size_t kMaxPendingNotifications = 1024;
|
||||
// Observable<T>: Void::Result::Result<void> try_set(T) requires std::copy_constructible<T>;
|
||||
// std::size_t dropped_notifications() const noexcept;
|
||||
```
|
||||
Errors use `Void::Async::make_async_error` codes (`overloaded`, `closed`, `self_join`, `invalid_argument`).
|
||||
If EventBus.hpp currently includes no Async headers, adding `Void/Async/Executor.hpp` is allowed (same
|
||||
module). Unchanged 1.x: every existing EventBus/Observable/Signal signature and their existing tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: A2 (ThreadExecutor) in your base. Downstream: none in this wave. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reentrant subscribe/unsubscribe/publish inside callbacks (ASan); unsubscribe vs dispatch races (TSan);
|
||||
callback throw in every mode; destruction on executor thread; captured-state release verified by a
|
||||
sentinel `shared_ptr` `use_count() == 1` after join; bounded queues; no user code under locks.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
- `EventBusJoin.cpp`: `bus_injected_no_private_thread_manual_pumping`, `bus_injected_subscription_limit_overloaded`,
|
||||
`bus_injected_dispatch_limit_overloaded`, `bus_close_and_join_waits_inflight_releases_capture_tsan`,
|
||||
`bus_unsubscribe_during_dispatch_prevents_later_admission`, `bus_self_unsubscribe_ok_self_join_rejected`,
|
||||
`bus_callback_throw_to_error_sink_others_run`, `bus_error_sink_throw_caught_and_counted`,
|
||||
`bus_legacy_async_unsubscribe_keeps_queued_copy`, `bus_sync_reentrant_subscribe_unsubscribe_asan`,
|
||||
`bus_publish_after_close_closed`, `bus_sync_unsubscribe_releases_captured_state`,
|
||||
`bus_legacy_async_unsubscribe_then_flush_releases_captured_state`,
|
||||
`bus_legacy_async_close_and_join_releases_capture_with_queued_copies`,
|
||||
`bus_destructor_gates_admitted_deliveries`, `bus_flush_blocking_self_join_and_manual_invalid`.
|
||||
- `ObservableReentrancy.cpp`: `observable_nested_set_fifo`, `observable_unsubscribe_in_listener_skips_rest`,
|
||||
`observable_subscribe_in_listener_not_current_pass`, `observable_try_set_overloaded_when_pending_full`,
|
||||
`observable_listener_throw_restores_state`, `observable_self_unsubscribe_releases_capture`,
|
||||
`observable_move_only_immediate_notification_compat`, `signal_reentrant_connect_disconnect_during_emit`.
|
||||
- Existing `EventBus`, `EventBusAsync`, `Observable` tests pass unchanged; TSan 0 races; ASan+UBSan 0
|
||||
errors; `-Werror` syntax checks clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm the new suites appear in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async5 --parallel 8 && /tmp/void-w11-async5/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\." && ctest --test-dir /tmp/void-w11-async5 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-async5-tsan --parallel 8 && /tmp/void-w11-async5-tsan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-async5-asan --parallel 8 && /tmp/void-w11-async5-asan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in EventBusJoin ObservableReentrancy; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done'
|
||||
```
|
||||
Also run the full `Async;Testing` VoidTests binary unfiltered once to catch regressions in other Async
|
||||
users (Fsm is not selected; root runs the full suite at integration).
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions; 1.x behavior changes limited to those recorded in
|
||||
MIGRATION (snapshot dispatch, nested FIFO for copyable, Async-mode exceptions counted). Stop and report
|
||||
BLOCKED if an existing EventBus/Observable test must change, or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only; no
|
||||
commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance
|
||||
criterion; commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -0,0 +1,202 @@
|
||||
# M-FUNCTIONAL-03 — Pure retry decisions and named blocking adapter
|
||||
|
||||
Task ID: M-FUNCTIONAL-03
|
||||
Role: sonnet-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step A1.
|
||||
- Repo: `/home/faumaray/Projects/VoidLibrary`, branch `feat/roadmap-p2-wave11`, HEAD `7f95f89`
|
||||
(root prep on `main` `38436b1`). You work in an isolated git worktree of `7f95f89`; your cwd is
|
||||
that worktree root. Do not touch the user's untracked files (`.env`, `WG.conf`, `keys`, `jev_token`).
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed.
|
||||
- Observed source (M-FUNCTIONAL-01 characterization folded in, D-035):
|
||||
- `include/Void/Functional/Retry.hpp` (tabs for indentation): backoff structs in milliseconds
|
||||
(`NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`), `JitterMode` + `Jittered`
|
||||
(thread_local `mt19937_64` seeded from `std::random_device`, ~:76-95), `Policy{max_attempts=3,
|
||||
max_elapsed=0 → unlimited}` (~:100-110), `Detail::backoff_sleep` hard-wired to
|
||||
`steady_clock::now()`/`sleep_for` (~:117-142), `retry`/`retry_or_throw`/`retry_while`; with
|
||||
`max_attempts == 0` legacy `retry` returns a default-constructed (successful) `expected` without
|
||||
calling `fn` (~:150-211).
|
||||
- `src/Functional/module.cmake` declares no `INTERNAL_DEPS` (D-015: standard-library-only).
|
||||
- Consumers: `include/Void/Resilience/AsyncPolicy.hpp` uses `Void::Retry::ExponentialBackoff`,
|
||||
`JitterMode` (lines ~6, 486, 533) — must stay source-compatible.
|
||||
- Tests: `tests/standalone/Functional/Retry.cpp` (14), `RetryJitter.cpp` (4).
|
||||
- Requirements: roadmap row M-FUNCTIONAL-03 (`docs/roadmap/modules/Functional.md` "Pure retry and
|
||||
callable ownership", updated in `7f95f89`); decisions D-029, D-038; contracts C-02, C-04.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Roadmap acceptance: "Extract pure retry decisions and retain named blocking adapter; fake-time
|
||||
tests prove exact attempt counts, deadlines, jitter bounds and no zero-attempt success."
|
||||
Deliver:
|
||||
1. NEW `include/Void/Functional/RetryState.hpp` — pure, standard-library-only decision engine.
|
||||
2. EDIT `include/Void/Functional/Retry.hpp` — include `RetryState.hpp`, relocate `JitterMode`
|
||||
definition into it (same name/namespace), add `SteadyNow`, `ThreadSleep`,
|
||||
`BlockingRetryOptions`, `retry_blocking`. All 1.x symbols keep identical behavior.
|
||||
3. NEW tests `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In: the above. Out: Time/Async adapters (`Async::retry_async` is M-TIME-03), changing any 1.x
|
||||
retry behavior (including the zero-attempt defect — pin it with a characterization test),
|
||||
Resilience changes, any build-file edit.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Functional/Retry.hpp` (all), `include/Void/Resilience/AsyncPolicy.hpp` (Retry uses),
|
||||
`tests/standalone/Functional/{Retry,RetryJitter}.cpp` (test style: `VOID_TEST`/assert macros,
|
||||
file stem = suite name), `src/Testing/Runner.cpp:209-225` (`--filter` is a regex over
|
||||
`suite.name`), `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-FUNCTIONAL-03 and
|
||||
`W11-PLAN-REV1-OUTPUT.md` F8/P3 (design source).
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`,
|
||||
`tests/standalone/Functional/RetryState.cpp` (NEW), `tests/standalone/Functional/RetryBlocking.cpp` (NEW).
|
||||
Forbidden: every other path (build files, other modules, docs). Another worker (M-TIME-03) runs
|
||||
concurrently in a different worktree and will later include `RetryState.hpp`; keep the interface
|
||||
exactly as specified. No git commit/branch/stash/reset; root integrates your diff.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. Create `RetryState.hpp` (namespace `Void::Retry`, includes only `<chrono> <cstdint> <expected>
|
||||
<optional> <random> <variant> <concepts> <limits> <cmath> <type_traits>` as needed; NO `<thread>`,
|
||||
NO `Void/...` include). Move `enum class JitterMode { Full, Equal };` here verbatim; remove it
|
||||
from `Retry.hpp` and `#include "Void/Functional/RetryState.hpp"` (match existing include style).
|
||||
2. Implement the interface in §7 with the fixed semantics below.
|
||||
3. Add the blocking adapter to `Retry.hpp` after the 1.x API, without touching 1.x bodies.
|
||||
4. Write the tests (§10). Build/run per §11 (configure/build in your worktree; build dir under
|
||||
`/tmp/void-w11-fn3*`).
|
||||
Fixed semantics (mandatory):
|
||||
- `create` validates via `validate`; deadline = `min(saturating_add(start, budget), admission_deadline)`
|
||||
when budget is a duration; with `no_deadline` deadline is `admission_deadline` (may be none).
|
||||
- `begin(now, stop)`: stop → `{stop, reason=stop_requested}`; `now >= deadline` →
|
||||
`deadline_exceeded`; else `{attempt}` and `attempts_started` becomes 1.
|
||||
- `next(now, outcome, stop)` checks in order: permanent → `not_retryable`; `attempts_started ==
|
||||
max_attempts` → `attempts_exhausted`; stop → `stop_requested`; else
|
||||
`at = saturating_add(now, jitter(backoff_delay(spec.backoff, attempts_started - 1)))`;
|
||||
`at >= deadline` → `deadline_exceeded`; else `{wait_until, at}`. `next` never returns `attempt`.
|
||||
- `resume(now, stop)`: re-checks stop and deadline, then `{attempt}` and increments `attempts_started`.
|
||||
- `succeed()` → `{stop, succeeded}`.
|
||||
- `backoff_delay(b, k)` = `initial * multiplier^k` saturated at `cap` before any integer conversion
|
||||
(compute in `long double`/`double`, clamp, then convert); never overflows; unjittered.
|
||||
- Full jitter: uniform integer ns in `[0, d]`; Equal: `d/2 + uniform[0, d - d/2]`.
|
||||
- Validation errors: `zero_attempts` (max_attempts == 0), `negative_duration` (initial/cap/budget
|
||||
< 0), `zero_budget` (budget duration == 0), `nonfinite_multiplier`, `multiplier_below_one`,
|
||||
`cap_below_initial`.
|
||||
- Default engine is seeded from `std::random_device` (F8): use `detail::seeded_engine<URBG>()`.
|
||||
- `retry_blocking`: invalid spec → `RetryError{config=err, attempts=0}` without calling `fn`;
|
||||
waits are `decision.at - options.now()` passed to `options.sleep(wait, options.stop)`; a `false`
|
||||
return (stopped) ends with `stop_requested` and no further attempt; the adapter never calls
|
||||
`sleep_until`. `last_error` holds the most recent `E` (empty iff no attempt ran). Value type may
|
||||
be move-only.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Retry { // RetryState.hpp (NEW)
|
||||
using SteadyTimePoint = std::chrono::steady_clock::time_point;
|
||||
enum class JitterMode { Full, Equal }; // EXISTING, relocated verbatim
|
||||
struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; };
|
||||
inline constexpr NoDeadline no_deadline{};
|
||||
struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
|
||||
std::chrono::nanoseconds cap{std::chrono::seconds{30}}; double multiplier{2.0};
|
||||
std::optional<JitterMode> jitter{}; };
|
||||
struct RetrySpec { std::uint32_t max_attempts{3}; // total, including the first
|
||||
std::variant<std::chrono::nanoseconds, NoDeadline> budget{std::chrono::seconds{30}};
|
||||
BackoffSpec backoff{}; };
|
||||
enum class RetryConfigError : std::uint8_t { zero_attempts, negative_duration, zero_budget,
|
||||
nonfinite_multiplier, multiplier_below_one, cap_below_initial };
|
||||
enum class RetryAction : std::uint8_t { attempt, wait_until, stop };
|
||||
enum class RetryStopReason : std::uint8_t { none, succeeded, attempts_exhausted, deadline_exceeded,
|
||||
not_retryable, stop_requested };
|
||||
enum class AttemptOutcome : std::uint8_t { retryable_failure, permanent_failure };
|
||||
struct RetryDecision { RetryAction action{RetryAction::stop}; SteadyTimePoint at{};
|
||||
RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; };
|
||||
[[nodiscard]] std::expected<void, RetryConfigError> validate(const RetrySpec&) noexcept;
|
||||
[[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept;
|
||||
[[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept;
|
||||
namespace detail { template <class G> G seeded_engine(); } // random_device seed if constructible
|
||||
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
|
||||
class RetryState { public:
|
||||
[[nodiscard]] static std::expected<RetryState, RetryConfigError> create(const RetrySpec&,
|
||||
SteadyTimePoint start, URBG urbg = detail::seeded_engine<URBG>(),
|
||||
std::optional<SteadyTimePoint> admission_deadline = std::nullopt);
|
||||
[[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision succeed() noexcept;
|
||||
[[nodiscard]] std::uint32_t attempts_started() const noexcept;
|
||||
[[nodiscard]] std::optional<SteadyTimePoint> deadline() const noexcept; };
|
||||
template <class E> struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0};
|
||||
std::optional<E> last_error{}; std::optional<RetryConfigError> config{}; };
|
||||
struct RetryEveryError { template <class E> constexpr AttemptOutcome operator()(const E&) const noexcept
|
||||
{ return AttemptOutcome::retryable_failure; } };
|
||||
}
|
||||
namespace Void::Retry { // Retry.hpp additions (NEW)
|
||||
struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } };
|
||||
struct ThreadSleep { bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // condition_variable_any + stop; false if stopped
|
||||
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep, class Classify = RetryEveryError,
|
||||
class URBG = std::mt19937_64>
|
||||
struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{};
|
||||
URBG urbg = detail::seeded_engine<URBG>(); std::stop_token stop{};
|
||||
std::optional<SteadyTimePoint> deadline{}; };
|
||||
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
|
||||
class Classify = RetryEveryError, class URBG = std::mt19937_64> // F() -> std::expected<T,E>
|
||||
[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn,
|
||||
BlockingRetryOptions<NowFn, SleepFn, Classify, URBG> options = {})
|
||||
-> std::expected<T, RetryError<E>>; // T,E deduced from F's result
|
||||
}
|
||||
```
|
||||
`ThreadSleep` may live inline in `Retry.hpp` (which already includes `<thread>`). Unchanged 1.x:
|
||||
`NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`,
|
||||
`Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: M-FUNCTIONAL-02 (done). Downstream: M-TIME-03 `Async::retry_async` consumes `RetryState`,
|
||||
`RetrySpec`, `RetryError`, `RetryEveryError`, `AttemptOutcome` exactly as above (gate G1). Root
|
||||
integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Saturating arithmetic near `time_point::max()`; multiplier 1e300 and `initial` near max; NaN/inf
|
||||
multiplier; negative durations; `max_attempts = UINT32_MAX` does not overflow counters; jitter on
|
||||
`d = 0`; deadline exactly equal to `at` counts as exceeded; no allocation in `RetryState`.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. `RetryState.cpp` tests: `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`),
|
||||
`retry_state_exact_three_attempts_default`, `retry_state_deadline_at_admission_prevents_first_attempt`,
|
||||
`retry_state_backoff_overshooting_deadline_stops`, `retry_state_no_deadline_explicit_marker`,
|
||||
`retry_state_backoff_saturates_without_overflow`, `retry_state_full_equal_jitter_bounds_and_seed_reproducibility`
|
||||
(seeded `mt19937_64{42}`; bounds + same-seed equality, not exact values),
|
||||
`retry_state_default_engine_jitter_in_bounds`, `retry_state_stop_prevents_next_attempt`,
|
||||
`retry_state_permanent_failure_stops`, `retry_state_saturating_add_near_max` — all pass.
|
||||
2. `RetryBlocking.cpp` tests (fake clock struct local to the test, no Time include, zero real sleeps):
|
||||
`retry_blocking_fake_clock_exact_waits_and_attempts`, `retry_blocking_zero_attempts_config_error_no_call`,
|
||||
`retry_blocking_expired_deadline_no_call_no_success`, `retry_blocking_last_error_and_attempt_count`,
|
||||
`retry_blocking_stop_during_sleep_no_extra_attempt`, `retry_blocking_permanent_failure_single_attempt`,
|
||||
`retry_blocking_move_only_value`, `legacy_retry_zero_attempts_behavior_pinned` (characterizes the
|
||||
1.x defect; comment says it is recorded for Wave C) — all pass.
|
||||
3. Existing `Retry`, `RetryJitter`, `AsyncPolicy` tests pass unchanged.
|
||||
4. `RetryState.hpp` contains no `<thread>` and no `Void/` include; `src/Functional/module.cmake` unchanged.
|
||||
5. `-DVOID_WARNINGS_AS_ERRORS=ON` clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Run from your worktree root (`$PWD`). `dev` must run with the sandbox disabled (the nix fetcher
|
||||
lock fails inside it). Expected: build exit 0, filtered tests all pass, ctest 2/2.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 --parallel 8 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res --parallel 8 && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^(AsyncPolicy|Retry|RetryJitter|RetryState|RetryBlocking)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-asan --parallel 8 && /tmp/void-w11-fn3-asan/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\."'
|
||||
rg -n "#include <thread>|Void/" include/Void/Functional/RetryState.hpp # expect no output
|
||||
```
|
||||
If a cmake option name differs (e.g. sanitizer flags), discover it in `CMakeLists.txt`/`cmake/Capabilities.cmake`
|
||||
and report the exact command used.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not edit outside write scope, weaken assertions, disable warnings, or change 1.x behavior. Stop
|
||||
and report BLOCKED if: the interface cannot compile as specified; a 1.x test needs changing; a
|
||||
build failure originates outside your files; the sanitizer option names cannot be found.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038 under user decisions D-027/D-029/D-031. Implementation of the listed
|
||||
files only; no commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Return task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per
|
||||
acceptance criterion; commands with cwd/results (test counts); checks not run; residual risks;
|
||||
integration notes (worktree path). Do not spawn children.
|
||||
@@ -0,0 +1,118 @@
|
||||
# M-TIME-03 (step B1b) — Async::retry_async over TimerQueue and deadline-domain conformance
|
||||
|
||||
Task ID: M-TIME-03
|
||||
Role: opus-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step B1b (gate G1 satisfied: M-FUNCTIONAL-03 committed `26edf65`; M-TIME-03 B1
|
||||
TimerQueue committed on the branch). Repo VoidLibrary, branch `feat/roadmap-p2-wave11`. You work
|
||||
in an isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘). Since then: A1 adds RetryState (23
|
||||
tests), B1 adds TimerQueue (15), DeadlineDomains (2), ClockSaturation (1).
|
||||
- Observed source:
|
||||
- `include/Void/Functional/RetryState.hpp`: `RetrySpec`, `RetryState<URBG>::create(spec, start, urbg,
|
||||
admission_deadline)`, `begin/next/resume/succeed` (stop decisions are final), `RetryError<E>{reason,
|
||||
attempts, last_error, config}`, `RetryEveryError`, `AttemptOutcome`, `detail::seeded_engine<G>()`.
|
||||
- `include/Void/Functional/Retry.hpp`: `retry_blocking` (reference shape for error mapping).
|
||||
- `include/Void/Async/Timer.hpp`: `TimerQueue::sleep_until(when, OperationOptions)` → `{}` on expiry
|
||||
after poll, `cancelled` on stop (only if the stop wins the timer cancel race; a stop after poll or
|
||||
close claimed the timer yields `{}`/`stopped`), `timeout` when `options.deadline < when`, `stopped`
|
||||
after close; resumes via `executor().post_completion`; `clock()` is the injected clock.
|
||||
- Requirements: roadmap row M-TIME-03 ("Validate injected-deadline domains with Async and blocking retry
|
||||
adapters; advancing manual time plus explicit polling expires an operation once"); C-03/C-04; D-038.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. NEW `include/Void/Async/Retry.hpp`: `Void::Async::retry_async`.
|
||||
2. NEW `tests/standalone/Async/AsyncRetry.cpp`.
|
||||
3. EDIT `tests/standalone/Async/DeadlineDomains.cpp`: add `deadline_domain_blocking_retry_manual_clock`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: changes to Timer.hpp, RetryState.hpp, Retry.hpp, Executor/Operation/TaskScope, build files.
|
||||
|
||||
## 4. Files to inspect
|
||||
The three headers above, `include/Void/Async/{Task,Executor,TaskScope}.hpp`, `include/Void/Async/Detail/Types.hpp`,
|
||||
`tests/standalone/Async/{TimerQueue,DeadlineDomains}.cpp`, `tests/standalone/Functional/RetryBlocking.cpp`,
|
||||
`docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-TIME-03.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/Retry.hpp` (NEW), `tests/standalone/Async/AsyncRetry.cpp` (NEW),
|
||||
`tests/standalone/Async/DeadlineDomains.cpp`.
|
||||
Forbidden: every other path. Other implementers work concurrently in other worktrees (IO files; Async
|
||||
ThreadExecutor/FuturePool/AsyncChannel/ParallelFor). No git operations except the root-authorized
|
||||
fast-forward in your prompt.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY semantics:
|
||||
- "now" is always `timers.clock().now()`; admission deadline = `options.deadline`; stop = `options.stop`.
|
||||
- Invalid spec → `RetryError{config=err, attempts=0}` without calling `fn`.
|
||||
- Loop: `begin(now, stop_requested)` → on `attempt` call `fn`; `fn` may return `std::expected<T,E>` or
|
||||
`Coro::Task<std::expected<T,E>>` (co_await it). Success → return `T` (also when stop was requested
|
||||
during the attempt). Failure → `next(now, classify(error), stop_requested)`.
|
||||
- On `wait_until(at)`: `co_await timers.sleep_until(at, OperationOptions{options.stop, options.deadline})`.
|
||||
After a `{}` sleep, ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself,
|
||||
which covers the TimerQueue choice where a late stop yields `{}`. Any sleep error ends the retry without
|
||||
calling `resume()` (amended after W11-REVIEW-B1b: resuming after `stopped`/`overloaded` would start
|
||||
attempts with no wait). Sleep result mapping: `{}` → resume;
|
||||
`cancelled` → stop with `stop_requested`; `timeout` → stop with `deadline_exceeded`; `stopped` (queue
|
||||
closed) → stop with `stop_requested` (documented: queue closure aborts the retry; no further attempt);
|
||||
`overloaded` → stop with `stop_requested` and document (no silent busy retry).
|
||||
- Never sleep with the host clock; never spin; no attempt after any stop decision; `last_error` holds
|
||||
the most recent `E` (empty iff no attempt ran).
|
||||
- Default URBG seeded via `Void::Retry::detail::seeded_engine<URBG>()`.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Async {
|
||||
template <class F, class Classify = Void::Retry::RetryEveryError, class URBG = std::mt19937_64>
|
||||
requires std::invocable<F&>
|
||||
[[nodiscard]] auto retry_async(Void::Retry::RetrySpec spec, F fn, TimerQueue& timers,
|
||||
OperationOptions options = {}, Classify classify = {},
|
||||
URBG urbg = Void::Retry::detail::seeded_engine<URBG>())
|
||||
-> Coro::Task<std::expected<T, Void::Retry::RetryError<E>>>; // T,E deduced from fn's (awaited) result
|
||||
}
|
||||
```
|
||||
The coroutine owns `fn`, `classify`, `urbg` and `spec` by value. `timers` (and its executor) must outlive
|
||||
the returned task (document).
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: A1 (`26edf65`), B1 (TimerQueue). Downstream: none in this wave beyond conformance. Root
|
||||
integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stop before first attempt; stop during `fn` (success preserved, no retry); stop during backoff; queue
|
||||
closed during backoff; deadline between attempts; zero attempts; move-only `T`/`E`/`F`; Task-returning
|
||||
`fn` that throws (exception propagates out of the retry task — document); manual clock far-future start.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. `AsyncRetry.cpp`: `async_retry_manual_clock_attempts_only_after_advance_and_poll`,
|
||||
`async_retry_total_deadline_expires_once`, `async_retry_stop_during_backoff_no_further_attempt`,
|
||||
`async_retry_success_after_stop_preserved`, `async_retry_zero_attempts_no_call`,
|
||||
`async_retry_task_returning_callable`, `async_retry_queue_closed_during_backoff_stops`,
|
||||
`async_retry_late_stop_after_timer_fired_no_further_attempt`, `async_retry_move_only_value` — all pass.
|
||||
2. `DeadlineDomains.cpp`: `deadline_domain_blocking_retry_manual_clock` (`retry_blocking` with
|
||||
`now = manual.now`, a sleep callable that advances the ManualClock) passes; existing 2 tests pass.
|
||||
3. Existing `TimerQueue`, `RetryState`, `RetryBlocking`, `OperationScope`, `Executor`, `Coro` pass.
|
||||
4. TSan 0 races and ASan+UBSan 0 errors on `AsyncRetry|DeadlineDomains|TimerQueue`.
|
||||
5. `-Werror` syntax check of the new/edited test files and `Async/Retry.hpp` clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm the new suite appears in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3b --parallel 8 && /tmp/void-w11-time3b/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue|RetryState|RetryBlocking|OperationScope|Executor|Coro)\." && ctest --test-dir /tmp/void-w11-time3b --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-time3b-tsan --parallel 8 && /tmp/void-w11-time3b-tsan/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-time3b-asan --parallel 8 && /tmp/void-w11-time3b-asan/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in Async/AsyncRetry Async/DeadlineDomains; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/$f.cpp || exit 1; done'
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions. Stop and report BLOCKED if the TimerQueue or
|
||||
RetryState contract is insufficient (needs a forbidden edit), or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only;
|
||||
no commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance
|
||||
criterion; commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -0,0 +1,166 @@
|
||||
# M-TIME-03 — Injected-deadline domains: Async TimerQueue and clock saturation (step B1)
|
||||
|
||||
Task ID: M-TIME-03
|
||||
Role: opus-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step B1 (TimerQueue part). The `Async::retry_async` part of M-TIME-03 is a
|
||||
separate later step (B1b) after M-FUNCTIONAL-03 integrates (gate G1); it is OUT of this assignment.
|
||||
- Repo: VoidLibrary, branch `feat/roadmap-p2-wave11`, HEAD `7f95f89`. You work in an isolated git
|
||||
worktree of `7f95f89`; cwd = worktree root. Never read the user's untracked files in the main checkout.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed.
|
||||
- Observed source:
|
||||
- `include/Void/Time/Clock.hpp`: `MonotonicClock{ using time_point = steady_clock::time_point; now() }`
|
||||
(:19-26), `ManualClock` starts at epoch 0 and is atomic (~:69-130), `remaining_until` (~:188-208).
|
||||
`src/Time/module.cmake` has no deps.
|
||||
- `include/Void/Async/Detail/Types.hpp`: `AdmissionError{overloaded, stopped, deadline_expired,
|
||||
invalid_argument, self_join}` (:15-21), `AsyncErrorCode` incl. NEW `closed = 9` (→cancelled, added
|
||||
in `7f95f89`), `OperationOptions{stop_token stop; optional<MonotonicClock::time_point> deadline}`
|
||||
(:45-48), `is_deadline_expired(options, clock = System)` (:50-56), `make_async_error`.
|
||||
- `include/Void/Async/Operation.hpp` (`OperationState`, `ResumeTicket`, backend refs, terminal
|
||||
state machine), `Executor.hpp` (`Executor::post_completion`, `ManualExecutor`, `ScheduleStatusAwaiter`
|
||||
checks deadline only in `await_ready/await_resume` ~:304-359), `Task.hpp` (`Coro::Task`),
|
||||
`TaskScope.hpp`. No timer primitive exists in `include/Void/Async`.
|
||||
- `src/Async/module.cmake`: `INTERNAL_DEPS Functional Time LogState` (unchanged by this task).
|
||||
- Requirements: roadmap row M-TIME-03 ("Validate injected-deadline domains with Async and blocking
|
||||
retry adapters; advancing manual time plus explicit polling expires an operation once"); C-03/C-04
|
||||
(one terminal result, injected clocks); decisions D-038 (F12), D-W11-01, D-W11-14.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. NEW `include/Void/Async/Timer.hpp`: `TimerQueue`, `TimerHandle`, `TimerEvent`, `TimerCallback`,
|
||||
`TimerQueueOptions` (header-only, like the rest of Async).
|
||||
2. EDIT `include/Void/Time/Clock.hpp`: NEW `saturating_add`, `deadline_after` helpers.
|
||||
3. NEW tests `tests/standalone/Async/TimerQueue.cpp`, `tests/standalone/Async/DeadlineDomains.cpp`
|
||||
(schedule_on/scope admission part only), `tests/standalone/Time/ClockSaturation.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In: the above. Out: `Async/Retry.hpp`/`retry_async` and `AsyncRetry.cpp` (step B1b), any change to
|
||||
existing Async/Time symbols or their default-argument clocks, Runtime-managed timer polling
|
||||
(D-W11-14), build files.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Async/{Operation,Executor,Task,TaskScope}.hpp`, `include/Void/Async/Detail/Types.hpp`,
|
||||
`include/Void/Time/Clock.hpp`, `tests/standalone/Async/{OperationScope,Executor}.cpp` (test style and
|
||||
ManualExecutor/ManualClock usage), `src/IO/EpollDriver.cpp:739-834` (how IO settles deadline expiry via
|
||||
an injected clock on poll — pattern to mirror), `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`
|
||||
§M-TIME-03 and `W11-PLAN-REV1-OUTPUT.md` F12 (design source).
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/Timer.hpp` (NEW), `include/Void/Time/Clock.hpp`,
|
||||
`tests/standalone/Async/TimerQueue.cpp` (NEW), `tests/standalone/Async/DeadlineDomains.cpp` (NEW),
|
||||
`tests/standalone/Time/ClockSaturation.cpp` (NEW).
|
||||
Forbidden: everything else, notably `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`,
|
||||
`Detail/Types.hpp`, Functional headers (M-FUNCTIONAL-03 is concurrently adding
|
||||
`Functional/RetryState.hpp` in another worktree), build files, docs. No git commit/branch/stash/reset.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. Add Clock helpers (overflow-safe; `saturating_add` clamps to `time_point::max()`/`min()`;
|
||||
`deadline_after(clock, d)` = `saturating_add(clock.now(), d)`; negative `d` allowed and saturates low).
|
||||
2. Implement `TimerQueue` as a stable min-heap of `(deadline, seq)` entries holding
|
||||
`shared_ptr<detail::TimerEntry>`; cancelled entries become tombstones; compact when tombstones
|
||||
exceed `max_timers` so heap size never exceeds `2 × max_timers`.
|
||||
3. `poll_expired()` reads `clock().now()` once, pops all due live entries in `(deadline, seq)` order
|
||||
under the lock, transitions each entry pending→fired atomically, then invokes callbacks OUTSIDE
|
||||
the lock. Nothing fires without an explicit `poll_expired()` call; no background thread.
|
||||
4. `sleep_until`/`sleep_for` awaitables: register a timer and a stop callback; settle through
|
||||
`OperationState` (or an equivalent single-terminal-result guard) so exactly one of
|
||||
{expired → `{}`, stop → `cancelled`, `options.deadline` earlier → `timeout`, `close` → `stopped`}
|
||||
wins; the continuation is always resumed via `executor().post_completion(handle)`, never inline
|
||||
from a stop callback or from `poll_expired` itself. Stop/deadline checks before admission return
|
||||
immediately (still via the awaitable's result, no suspension needed).
|
||||
5. `close()`: marks closed; every pending entry's callback runs once with `TimerEvent::closed`
|
||||
(sleepers settle `stopped`); later `schedule_at`/`sleep_*` return `stopped`. Destructor = close.
|
||||
The executor must outlive the queue (document).
|
||||
6. Tests per §10; build/run per §11.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Time { // Clock.hpp additions (NEW)
|
||||
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
|
||||
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
|
||||
}
|
||||
namespace Void::Async { // Timer.hpp (NEW)
|
||||
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 → invalid_argument
|
||||
enum class TimerEvent : std::uint8_t { expired, closed };
|
||||
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
|
||||
class TimerHandle { // move-only; holds shared_ptr<detail::TimerEntry>
|
||||
public: TimerHandle() noexcept = default;
|
||||
bool cancel() noexcept; // true ⇒ callback never runs; safe after queue destroyed
|
||||
[[nodiscard]] bool valid() const noexcept; };
|
||||
class TimerQueue { // non-copyable, non-movable
|
||||
public:
|
||||
using time_point = Void::Time::MonotonicClock::time_point;
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
|
||||
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
|
||||
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_event);
|
||||
[[nodiscard]] std::size_t poll_expired(); // returns callbacks fired
|
||||
[[nodiscard]] std::optional<time_point> next_deadline() const;
|
||||
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept; // 0 if due; uses injected now
|
||||
[[nodiscard]] std::size_t active_timers() const noexcept;
|
||||
void close() noexcept;
|
||||
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
|
||||
[[nodiscard]] Executor& executor() noexcept;
|
||||
~TimerQueue(); // = close()
|
||||
};
|
||||
}
|
||||
```
|
||||
Result errors use `make_async_error`: `overloaded` (at `max_timers` live timers), `stopped` (after
|
||||
close), `cancelled` (stop token), `timeout` (`options.deadline` reached first), `invalid_argument`.
|
||||
`schedule_at` returns `AdmissionError::{overloaded, stopped, invalid_argument}`. Callback exactly-once
|
||||
rule: runs exactly once with `expired` or `closed`, or never if `cancel()` returned true. If
|
||||
`std::move_only_function` is unavailable in the toolchain, report it (do not substitute silently).
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: M-TIME-02, M-ASYNC-02/03 (done). Downstream consumers (later steps): `AsyncChannel`
|
||||
deadlines (M-ASYNC-04, gate G2), `retry_async` (B1b), `IO::PumpOptions::timers` (S-IO-04). Keep the
|
||||
interface exactly as written. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stop vs poll vs close races (TSan), equal deadlines FIFO by seq, `when` in the past (fires on next
|
||||
poll), ManualClock starting at epoch 0 and at a far-future point, never compare manual-domain
|
||||
deadlines with the host clock, cancel during callback dispatch, callback that schedules a new timer
|
||||
(must not deadlock: callbacks run outside the lock), destruction with pending sleepers, tombstone
|
||||
growth bounded, no busy loops, no allocation per poll beyond the due batch.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. `TimerQueue.cpp`: `timer_manual_advance_and_poll_fires_exactly_once`,
|
||||
`timer_equal_deadlines_fire_in_submission_order`, `timer_not_fired_without_explicit_poll`,
|
||||
`timer_manual_epoch_deadline_not_compared_with_host_clock`, `timer_manual_clock_far_future_initial_point`,
|
||||
`timer_stop_before_admission_and_pending_cancelled_once`, `timer_stop_vs_poll_race_single_result_tsan`,
|
||||
`timer_capacity_overloaded_and_tombstone_bounded`, `timer_schedule_at_cancel_vs_fire_exclusive`,
|
||||
`timer_close_settles_pending_stopped`, `timer_wait_duration_uses_injected_now`,
|
||||
`timer_sleep_for_saturates`, `timer_handle_cancel_after_queue_destroyed_safe`,
|
||||
`timer_callback_schedules_new_timer_no_deadlock` — all pass.
|
||||
2. `DeadlineDomains.cpp`: `deadline_domain_schedule_on_and_scope_admission_injected_clock` and
|
||||
`deadline_domain_timer_and_operation_deadline_same_manual_clock` (an `OperationOptions.deadline` in
|
||||
the ManualClock domain expires a `sleep_until` once only after advance + poll) — pass.
|
||||
3. `ClockSaturation.cpp`: `clock_saturating_add_and_deadline_after_bounds` — passes.
|
||||
4. Existing `Clock`, `Stopwatch`, `OperationScope`, `Executor`, `Coro` tests pass unchanged.
|
||||
5. `-Werror` clean; Debug TSan run of the new suites reports 0 races; ASan+UBSan 0 errors.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = your worktree root. Run `dev` with the sandbox disabled (dangerouslyDisableSandbox) — nix
|
||||
fetcher lock fails inside it. Confirm the new suites appear in output (tests needing unselected
|
||||
modules are silently skipped).
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 --parallel 8 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor|Coro)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan --parallel 8 && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-asan --parallel 8 && /tmp/void-w11-time3-asan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation)\."'
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions or disabled warnings; no changes to existing
|
||||
Async/Time semantics. Stop and report BLOCKED if the contract needs an edit to a forbidden file (e.g.
|
||||
`Operation.hpp`), if `std::move_only_function` is unavailable, or a failure originates outside your files.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038 under user decisions D-027/D-029/D-031. Listed files only; no commits,
|
||||
pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance
|
||||
criterion; commands with cwd/results (test counts, TSan/ASan outcome); checks not run; residual
|
||||
risks; integration notes (worktree path). Do not spawn children.
|
||||
@@ -0,0 +1,39 @@
|
||||
# S-DISCOVERY-01..04 — Discovery Subsystem (Catalog, Leases, Watches, Selectors, Optional RPC Adapter)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Discovery` subsystem per `docs/roadmap/subsystems/Discovery.md` and `docs/roadmap/DEPENDENCIES.md`, plus the optional `Void::DiscoveryRpc` endpoint adapter living strictly above `RPC` and `Discovery`:
|
||||
|
||||
1. **`S-DISCOVERY-01` — Boundary, Error Domain, and Immutable Value Contracts**:
|
||||
- Module `src/Discovery/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero network, storage, or consensus dependencies.
|
||||
- Error domain `kDiscoveryErrorDomain = 30` with `DiscoveryErrorCode` covering validation, conflict, cap exhaustion, expiry, stale/unavailable freshness, cancellation, and self-join diagnosis.
|
||||
- Strict endpoint/attribute validation before publication (valid scheme/host/port, `weight > 0`, `max_attributes_per_record = 16`, `max_metadata_bytes_per_record = 4096`, `max_services = 1024`, `max_endpoints_per_service = 256`, `max_total_records = 10000`).
|
||||
2. **`S-DISCOVERY-02` — Pure Catalog, Atomic Static Snapshots, and Local RAII Registrations**:
|
||||
- Pure `Catalog` construction creating zero hidden threads.
|
||||
- Atomic candidate `replace_static()` rejecting invalid/conflicting candidates while preserving the active revision; explicit `provider_generation` bump resets revision domain and emits `ResyncRequired`.
|
||||
- Local move-only RAII `Registration` handles with explicit `LeasePolicy` (default 30s TTL / 10s renew interval via injected `MonotonicClock`; zero TTL rejected as `InvalidArgument`; unleased explicit mode valid until release; static entries never expire).
|
||||
- Duplicate `(service, instance)` returns `Conflict` without stealing existing handles.
|
||||
- Deterministic `resolve()` sorted by `instance`, filtering logically expired records before cleanup runs, respecting `ResolvePolicy::allow_stale` and `Freshness`.
|
||||
3. **`S-DISCOVERY-03` — Bounded Watches, Resync, Client Selectors, and Managed Renewal**:
|
||||
- Bounded `watch()` (`max_watches = 1024`, `max_events_per_watch = 64`, shared `16 MiB` event budget) emitting `InitialSnapshot`, serialized per-watch `Delta`, and explicit `ResyncRequired` + full latest `Snapshot` on overflow or provider-generation reset.
|
||||
- Callbacks run outside catalog and watch locks; `cancel()` stops new admission (including self-cancel inside a callback); `join()` drains admitted callbacks and diagnoses synchronous self-join (`SelfJoin`) instead of deadlocking.
|
||||
- `Catalog::shutdown_and_join()` removes local entries, cancels watches, and joins admitted callbacks; destructor only requests stop.
|
||||
- `WeightedRoundRobinSelector`, stable HRW `AffinitySelector`, and deterministic `ManagedLeaseRenewer`.
|
||||
4. **`S-DISCOVERY-04` — Optional RPC Integration (`DiscoveryRpc`)**:
|
||||
- Separate module `src/DiscoveryRpc/module.cmake` (`INTERNAL_DEPS Discovery RPC`) so `RPC` remains completely independent of `Discovery`.
|
||||
- `EndpointResolverClient` resolves endpoints from `Discovery::Catalog`, selects via client selector, preserves configured `expected_tls_name` / identity across IP/address refreshes (rejecting TLS scheme/identity downgrade), and executes unary calls via `Void::RPC::Client`.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Discovery/{Types,Catalog}.hpp`
|
||||
- `src/Discovery/{module.cmake,Catalog.cpp}`
|
||||
- `include/Void/DiscoveryRpc/EndpointAdapter.hpp`
|
||||
- `src/DiscoveryRpc/{module.cmake,EndpointAdapter.cpp}`
|
||||
- `tests/standalone/Discovery/Catalog.cpp`
|
||||
- `tests/standalone/DiscoveryRpc/EndpointAdapter.cpp`
|
||||
- `tests/package/DiscoveryOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Discovery;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `DiscoveryOnly` consumer with `_no_external_deps`.
|
||||
- `DiscoveryRpc` identity-preserving refresh + RPC round-trip tests; `RpcOnly` remains Discovery-free.
|
||||
- Deterministic fake-clock lease expiry/renewal, atomic bad/good config replacement, duplicate registration conflict, watch overflow -> `ResyncRequired`, self-cancel/self-join, and selector determinism.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,318 @@
|
||||
# S-IO-03 — Bounded positional file workers, sync, active cancel, safe shutdown core, epoll D1 fixes
|
||||
|
||||
Task ID: S-IO-03
|
||||
Role: opus-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step B2 (critical path). Repo VoidLibrary, branch `feat/roadmap-p2-wave11`.
|
||||
You work in an isolated git worktree of the HEAD given in your prompt; cwd = worktree root.
|
||||
Never read the user's untracked files (`.env`, `WG.conf`, `keys`, `jev_token`) in the main checkout.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed.
|
||||
- Observed source (cite-checked by planner and two PREFLIGHT reviews):
|
||||
- `include/Void/IO/Driver.hpp:59-105`: `Driver` (non-movable; `create(executor, BackendOptions,
|
||||
clock, pmr resource)`, `poll_once(max_wait)`, `wake`, `request_stop`, `shutdown_and_join`), no
|
||||
thread, no run loop, no file API. `~Driver` at `src/IO/EpollDriver.cpp:1737-1742` and
|
||||
`~EpollBackend` at `:953-963` both call `shutdown_and_join()` and ignore the result.
|
||||
- `include/Void/IO/Types.hpp`: `IoErrorCode` (incl. root-added `sync_failed = 12` → `ErrorKind::io`),
|
||||
`IoLimits{max_descriptors 4096, max_operations 8192, ..., file_workers 4, max_file_queue 256}`
|
||||
(:100-110), `validate_limits` ignores file fields (:112-124), `BackendOptions`, `DriverTelemetry`.
|
||||
- `include/Void/IO/Detail/Backend.hpp`: `DriverBackend` virtual interface; streams hold `weak_ptr`
|
||||
to the backend (:85-125); stop forwarders lock briefly (:279-285).
|
||||
- Epoll defects D1 (all CONFIRMED): (a) `complete_op_and_collect_tickets` releases the backend ref
|
||||
unconditionally (`EpollDriver.cpp:448`) though `retire_op_locked` is idempotent (:391-394);
|
||||
(b) cancel path (:1332-1351) doesn't skip retired ops (mock does, :770-781) — stop after the
|
||||
start-of-turn drain (:1053) while `drive_read/write` completes the op double-releases at the
|
||||
end-of-turn drain (:1173); (c) `::read`/`::send`/`::write` at :1466/:1549/:1560 run outside `mu_`
|
||||
without `in_execution` (mock-only, :653-671); (d) cross-thread `shutdown_and_join` (:1179-1238)
|
||||
completes ops mid-syscall and closes fds (:1221→:363) while a poller holds the integer (:1151).
|
||||
- `poll_once` early-returns once stopping (`:1056-1059`); mock `poll_once` ignores `max_wait`
|
||||
(:739-741); `IoErrorCode::busy` already means "concurrent op not allowed" (:533-540).
|
||||
- Consumers of `Driver`: IPC (`src/IPC/Session.cpp:1118-1129` bounded poll loop ignoring result),
|
||||
SystemAsync, CryptoAsync, Storage, ConfigurationAsync, Runtime tests.
|
||||
- Requirements: roadmap row S-IO-03 ("Bounded positional file workers, serialization, sync and
|
||||
active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync
|
||||
success/failure after stop remains authoritative in the sole result"); `docs/roadmap/subsystems/IO.md`
|
||||
(updated in `7f95f89`); contracts C-03..C-06; decisions D-038, D-040.
|
||||
- MANDATORY design sources (read fully): `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §S-IO-03,
|
||||
`W11-PLAN-REV1-OUTPUT.md` F1, F2, F9, F11, F13 and P3 (D1 seam), and `W11-CONTRACT-R2.md` N3, N4,
|
||||
P3-5, P3-9. Precedence: R2 > REV1 > PLAN. This spec restates the mandatory points.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. NEW `include/Void/IO/File.hpp`: `FileOpenOptions`, `SyncMode`, `FileSyscallResult`,
|
||||
`FileSyscalls` (injectable shim with `native()`), move-only `File`, `read_exact_at`, `write_all_at`.
|
||||
2. EDIT `include/Void/IO/Driver.hpp`: `open_file`, `adopt_file_fd`, `start_file_workers`,
|
||||
`run_file_work`, NEW free `is_io_worker_thread()`; `~Driver` becomes the only blocking teardown;
|
||||
public inline shutdown wrappers `begin_shutdown()`, `shutdown(Async::OperationOptions)`,
|
||||
`quiescent()`, `shutdown_complete()` (moved from S-IO-04 by D-042 so B2 can test its primitive).
|
||||
3. EDIT `include/Void/IO/Types.hpp`: append `BackendOptions::file_syscalls{nullptr}` (borrowed),
|
||||
`BackendOptions::before_file_worker_start{}`, `DriverTelemetry::{queued_file_requests,
|
||||
active_file_requests, file_workers_running, duplicate_completions_ignored}`, NEW
|
||||
`DriverShutdownReport`; `validate_limits` rejects `max_file_queue == 0`.
|
||||
4. EDIT `include/Void/IO/Detail/Backend.hpp`: file-submit virtuals + shutdown primitives
|
||||
(`begin_shutdown`, `advance_shutdown`, `shutdown_complete`, `quiescent`, `teardown_blocking`).
|
||||
5. EDIT `src/IO/EpollDriver.cpp`: D1 fixes, poll-owner exclusion, file completion lane, bounded
|
||||
shutdown core, F2 wake/close rules; NEW private `src/IO/FileWorkers.{hpp,cpp}`.
|
||||
6. NEW `tests/standalone/IO/IoFile.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In: the above, for both mock and epoll backends (file pool shared via the base backend).
|
||||
Out: `Driver::run` and `Pump.hpp`/`pump_until` (S-IO-04, step A4); Net
|
||||
adapter; io_uring; Runtime; any build-file edit; `Threads::Threads` (D-W11-08: IO already uses
|
||||
pthread calls without it; IOOnly consumer disables Threads lookup).
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/IO/{Types,Driver,Stream}.hpp`, `include/Void/IO/Detail/Backend.hpp`,
|
||||
`src/IO/EpollDriver.cpp` (all), `include/Void/Async/{Operation,Executor,TaskScope}.hpp`,
|
||||
`include/Void/Async/Detail/Types.hpp`, `tests/standalone/IO/IoDriver.cpp`,
|
||||
`tests/package/InstalledComponents.cmake:74-80` (IOOnly flags), `src/IPC/Session.cpp:1118-1129`,
|
||||
and the three design documents in §1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/IO/File.hpp` (NEW), `include/Void/IO/Driver.hpp`, `include/Void/IO/Types.hpp`,
|
||||
`include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.hpp` (NEW),
|
||||
`src/IO/FileWorkers.cpp` (NEW), `tests/standalone/IO/IoFile.cpp` (NEW).
|
||||
Forbidden: all other paths, including `src/IO/module.cmake`, Async headers, Runtime, SystemAsync,
|
||||
IPC, tests other than `IoFile.cpp`, build files, docs. Other workers may run concurrently in other
|
||||
worktrees on Async files. No git commit/branch/stash/reset.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Order: (1) D1 fixes + regression test first; (2) poll-owner exclusion; (3) file pool + File API;
|
||||
(4) bounded shutdown core + teardown; (5) remaining tests; (6) downstream builds.
|
||||
MANDATORY invariants:
|
||||
- D1: release the backend ref only if this call retired the op; cancel/expire paths skip retired
|
||||
ops; epoll marks an op `in_execution` under `mu_` before its syscall and shutdown/cancel never
|
||||
completes an op that is in execution (it records stop intent; the syscall's real result settles
|
||||
it). NEW `duplicate_completions_ignored` counts suppressed double retirements.
|
||||
- Poll owner: a dedicated `std::mutex poll_mu_`; `poll_once` first checks the thread-local
|
||||
polling marker (reentrant call → `busy`), then `try_lock`; failure → `IoErrorCode::busy`
|
||||
without touching any fd. Every turn drains cancels, control messages and file completions
|
||||
BEFORE any stop-flag early return. While stopping (not yet shut down) a turn with no work waits
|
||||
in `epoll_wait` up to `max_wait` (no spin). After shutdown completes `poll_once` returns 0
|
||||
without touching any fd.
|
||||
- File workers (F1): a worker performs exactly one syscall (native or the injected shim — the
|
||||
single documented exception allowed to run on workers; it must not call Driver/Executor/File
|
||||
APIs), then pushes `{request, result}` onto the shared completion queue under the pool mutex and
|
||||
wakes. Resume tickets are produced only by a poll turn via the existing
|
||||
`complete_op_and_collect_tickets` path. `run_file_work(n)` runs syscalls on the caller and only
|
||||
queues results. Workers hold `shared_ptr<detail::FileWorkerShared>`, never the backend.
|
||||
Thread-local `tl_io_worker_owner` set on workers; `is_io_worker_thread()` reads it.
|
||||
- Admission: closed driver / stopped / expired → rejected before queueing; `max_file_queue` bounds
|
||||
queued requests, `max_operations` bounds queued+active; either → `overloaded`; zero-length →
|
||||
`{0,false}` without a syscall; offset+length overflow → `invalid_argument`. Files count against
|
||||
`max_descriptors`.
|
||||
- Ordering: writes and syncs on one file run in admission order, one active at a time; reads may
|
||||
run concurrently. One syscall per request; EINTR retried; short transfer returns actual bytes;
|
||||
0-byte read of nonzero length = EOF.
|
||||
- Queued stop/expiry: removed, completes `cancelled`/`timeout`; writes/syncs carry
|
||||
`DomainOutcomeKind::not_committed`. Expiry checked by the driver clock in `poll_once` and again at
|
||||
worker dequeue.
|
||||
- Active stop/expiry: intent only; span/lease and telemetry retained; result = the syscall's actual
|
||||
outcome. Sync success after stop = success; sync failure → `sync_failed` + native errno +
|
||||
`DomainOutcomeKind::unknown`.
|
||||
- `start_file_workers()` explicit, once; the `before_file_worker_start(index)` hook error or a
|
||||
caught `std::system_error` joins already-started workers, returns `os_error` (system code when
|
||||
present), and allows retry.
|
||||
- File fd state (N4/F13): `detail::FileState` shared-owned, `enum {open, closing, closed}` under
|
||||
the pool mutex; handle drop / in-flight / `close_pending` transitions under that mutex; exactly
|
||||
one close enqueued (preallocated node inside `FileState`, reserved capacity bounded by
|
||||
`max_descriptors`); close executes on a worker or in `run_file_work`. `~File` wakes only via a
|
||||
weak→strong backend lock or the worker condvar, never a raw waker. Teardown closes remaining file
|
||||
fds after joining workers and marks them `closed`; afterwards File ops return `closed` without a
|
||||
syscall, `~File` does nothing, `close_and_join` returns success. `File::close_and_join(options)`
|
||||
is always admitted; deadline/stop expiry → `incomplete_shutdown`, File stays valid with fd and
|
||||
buffers retained; close syscall failure → `os_error`, fd treated as closed.
|
||||
- Shutdown core (F9/N3): backend `begin_shutdown()` (idempotent: sets the stopping flag, closes
|
||||
admission, cancels queued, stops active); `advance_shutdown(deadline, stop)` waits in ≤1 ms real
|
||||
slices re-reading the injected clock, releases `poll_mu_` between slices, runs its own turns only
|
||||
while holding poll ownership, wakes the current poller, returns the current
|
||||
`DriverShutdownReport` with `complete=false` on deadline or stop (not an error), returns
|
||||
`Async::make_async_error(AdmissionError::self_join)`-equivalent error if called on this backend's
|
||||
worker or inside its poll turn; dispatches resume tickets only after releasing poll ownership
|
||||
(P3-9). On completion: workers joined, op/descriptor fds closed, `wake_closed_` set (release).
|
||||
1.x `shutdown_and_join()` = `advance_shutdown(nullopt, {})` mapped to `Result<void>`.
|
||||
- F2: epoll fd and eventfd close only in `~EpollBackend`; `wake()` returns early if
|
||||
`wake_closed_` (acquire).
|
||||
- F1 teardown: `~EpollBackend`/`~MockBackend`/`~FileWorkers` never block; `~FileWorkers` finding
|
||||
a joinable thread prints a one-line stderr diagnostic and `std::terminate`s. `Driver::~Driver`
|
||||
calls `backend_->teardown_blocking()` (begin + advance to completion). `~Driver` on a file-worker
|
||||
thread or inside a poll turn of that backend → stderr diagnostic + `std::terminate`.
|
||||
|
||||
|
||||
### Amendments from W11-SPEC-REVIEW-1 (MANDATORY; override earlier text where they differ)
|
||||
Source: `docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md` S1–S9 + P3 (decision D-042).
|
||||
- S1 ownership handoff: before each slice `advance_shutdown` sets atomic `shutdown_waiting_` and
|
||||
calls `wake()`. While it is set, `poll_once` on any other thread returns `busy` before `try_lock`,
|
||||
touching no fd and not incrementing `turns`. It is cleared once `advance_shutdown` holds
|
||||
`poll_mu_`. Between slices, after `advance_shutdown` releases `poll_mu_`, other pollers may run turns.
|
||||
- S2 shutdown order (replaces the order implied above): (1) `begin_shutdown()` — `advance_shutdown`
|
||||
calls it itself; (2) wait until no queued or active file request and no op `in_execution`;
|
||||
(3) under `poll_mu_`, final drain of cancels, controls, file completions and close waiters;
|
||||
(4) join workers; (5) still under `poll_mu_`, close remaining file fds (mark `closed`, complete
|
||||
pending `close_and_join` waiters with success), then close op/descriptor fds; (6) set `shut_down_`
|
||||
(release), then `wake_closed_`; (7) release `poll_mu_`, then dispatch tickets. `self_join` misuse
|
||||
(`Async::make_async_error(Async::AdmissionError::self_join)`) is detected before any state change.
|
||||
`begin_shutdown` only records intent and wakes the poller; it never completes or dispatches.
|
||||
Document: the executor must outlive the Driver; an owned executor must not be joined before
|
||||
Driver teardown (P3-9).
|
||||
- S3 (replaces "Expiry checked ... again at worker dequeue"): expiry is checked with the driver
|
||||
clock in `poll_once`; the epoll wait bound includes the earliest queued-file deadline. At dequeue a
|
||||
worker checks, under the pool mutex and WITHOUT calling the clock, the request's stop flag and the
|
||||
expired mark set by the last turn; such a request completes `cancelled`/`timeout` with no syscall.
|
||||
- S4 observable contract: queued stop → `IoErrorCode::cancelled`, queued expiry →
|
||||
`IoErrorCode::timeout` (kIoErrorDomain), zero shim calls, unchanged file bytes; sync failure →
|
||||
`IoErrorCode::sync_failed` with `system_code() == std::error_code{errno, std::generic_category()}`.
|
||||
Internally settle with `try_commit_error(err, not_committed|unknown)`; tests do not assert the
|
||||
outcome kind. Retirement uses a retire-once path equivalent to `complete_op_and_collect_tickets`,
|
||||
generalized for `OperationState<void>` and the file outcome kinds.
|
||||
- S5 slots: a File occupies a `DescriptorSlot`, counts in `active_descriptors_`, bounded by
|
||||
`max_descriptors`; `File::id()` is that slot's `DescriptorId`. The slot has `fd = -1` and a
|
||||
file-kind flag; socket paths (interest updates, `close_fd` controls, stale-event checks, shutdown
|
||||
sweep) skip it. The file fd lives only in `FileState`.
|
||||
- S6 lifetimes: `FileState` holds `shared_ptr<detail::FileWorkerShared>` and `weak_ptr<DriverBackend>`,
|
||||
never raw pool/backend pointers. The raw-context waker is called only by workers, which are joined
|
||||
before the backend is destroyed.
|
||||
- S7 stop flag: `request_stop()` == `begin_shutdown()`, with idempotence on a separate
|
||||
`shutdown_begun_` flag. On mock, requests held by a token never block `advance_shutdown`;
|
||||
`finish_*` still completes them, and `teardown_blocking` completes any still held with
|
||||
`IoErrorCode::closed`.
|
||||
- S8 D1 counter: increment `duplicate_completions_ignored` each time a cancel, expiry or shutdown
|
||||
path meets an already-retired op and skips it. Retired ops are not purged from the cancel queue
|
||||
early. A turn's first `clock_.now()` comes after the start-of-turn cancel/control/file drain; the
|
||||
queued-file expiry scan reads the clock only when queued file requests have deadlines.
|
||||
- S9 (D-042): B2 owns and tests the public wrappers `begin_shutdown`, `shutdown(options)`,
|
||||
`quiescent`, `shutdown_complete` (inline in `Driver.hpp`). A4 adds only `run()`, `Pump.hpp`,
|
||||
SystemAsync conformance and its tests.
|
||||
- P3 clarifications: busy only if the polling marker equals THIS backend (save/restore it for nested
|
||||
turns of other drivers); mock `poll_once` still ignores `max_wait`; the only worker-side Driver call
|
||||
is detected (`shutdown_and_join`/`shutdown` → `self_join`); closed → `closed`, stop → `cancelled`,
|
||||
expired → `timeout` (as `submit_io`); `offset > OFF_MAX` or `offset+len > OFF_MAX` →
|
||||
`invalid_argument`; file requests count in the shared `active_operations_` until poll-turn
|
||||
retirement; reads are unordered relative to writes; a second `start_file_workers` →
|
||||
`invalid_argument`, `file_workers == 0` → success with no threads, after shutdown begins →
|
||||
`closed`, `run_file_work` while workers run → `busy`; `close_and_join` waits for (does not cancel)
|
||||
the file's queued/active requests, success invalidates the File, after an expired call the File is
|
||||
`valid()` but closing (new ops → `closed`, a repeat call waits); document the difference from
|
||||
`ByteStream::close_and_join`; `read_exact_at`/`write_all_at` mirror `Stream.hpp` composed transfers
|
||||
with the offset advancing and one deadline, a 0-byte pwrite with bytes remaining is an error (no
|
||||
loop); open flags: RDWR/WRONLY/RDONLY, neither read nor write → `invalid_argument`, `truncate`
|
||||
requires write, `exclusive` requires create, always `O_CLOEXEC`, runs on the caller's thread;
|
||||
`adopt_file_fd` takes ownership only on success; the injected shim must outlive Driver teardown.
|
||||
- Test file includes: `IoFile.cpp` may include only Void/{IO, Async, Time, Memory, Functional, Core,
|
||||
Testing} headers (otherwise it is silently skipped); write a local temp-dir helper.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::IO { // File.hpp (NEW)
|
||||
struct FileOpenOptions { bool read{true}, write{false}, create{false}, truncate{false}, exclusive{false};
|
||||
std::uint32_t mode{0600}; };
|
||||
enum class SyncMode : std::uint8_t { data, full };
|
||||
struct FileSyscallResult { std::int64_t value{0}; int error{0}; };
|
||||
class FileSyscalls { public: virtual ~FileSyscalls() = default;
|
||||
[[nodiscard]] virtual FileSyscallResult pread(int, std::span<std::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult pwrite(int, std::span<const std::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult sync(int, SyncMode) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult close(int) noexcept;
|
||||
[[nodiscard]] static FileSyscalls& native() noexcept; };
|
||||
class File { public: File() noexcept; File(File&&) noexcept; File& operator=(File&&) noexcept; ~File();
|
||||
[[nodiscard]] bool valid() const noexcept; [[nodiscard]] DescriptorId id() const noexcept;
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(SyncMode = SyncMode::full, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(Async::OperationOptions = {}); };
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> read_exact_at(File&, std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> write_all_at(File&, std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
}
|
||||
// Driver.hpp additions
|
||||
[[nodiscard]] Void::Result::Result<File> Driver::open_file(const std::filesystem::path&, FileOpenOptions = {});
|
||||
[[nodiscard]] Void::Result::Result<File> Driver::adopt_file_fd(int fd);
|
||||
[[nodiscard]] Void::Result::Result<void> Driver::start_file_workers();
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run_file_work(std::size_t max_requests = 1);
|
||||
[[nodiscard]] bool Void::IO::is_io_worker_thread() noexcept;
|
||||
void Driver::begin_shutdown() noexcept; // -> backend_->begin_shutdown()
|
||||
[[nodiscard]] Void::Result::Result<DriverShutdownReport> Driver::shutdown(Async::OperationOptions); // -> advance_shutdown(o.deadline, o.stop)
|
||||
[[nodiscard]] bool Driver::quiescent() const noexcept;
|
||||
[[nodiscard]] bool Driver::shutdown_complete() const noexcept;
|
||||
// Types.hpp additions
|
||||
struct DriverShutdownReport { bool complete{false}; std::size_t pending_operations{0},
|
||||
active_file_requests{0}, open_descriptors{0}, retained_buffer_bytes{0}; };
|
||||
// BackendOptions (append): FileSyscalls* file_syscalls{nullptr};
|
||||
// std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
|
||||
// DriverTelemetry (append): queued_file_requests, active_file_requests, file_workers_running,
|
||||
// duplicate_completions_ignored (std::size_t / std::uint64_t as fits existing fields)
|
||||
// detail::DriverBackend (append, pure virtual or with base impl):
|
||||
virtual void begin_shutdown() noexcept;
|
||||
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline, std::stop_token stop);
|
||||
[[nodiscard]] virtual bool shutdown_complete() const noexcept;
|
||||
[[nodiscard]] virtual bool quiescent() const noexcept;
|
||||
virtual void teardown_blocking() noexcept;
|
||||
```
|
||||
`ComposedTransferError`, `Transfer`, `DescriptorId`, `BufferLease` are existing IO types — reuse.
|
||||
Use existing namespace aliases/spellings for `Coro::Task` and `Void::Result::Result` as in `Stream.hpp`.
|
||||
Unchanged 1.x: every existing `Driver`/`ByteStream`/`BufferLease` signature and the IoDriver tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: S-IO-01/02 (done), root prep `7f95f89` (`sync_failed`). Downstream: S-IO-04 (A4) adds
|
||||
public wrappers over your backend primitives (gate G4); S-RUNTIME-02 (B3) uses
|
||||
`start_file_workers`, `is_io_worker_thread`. Keep §7 exactly. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
fd reuse after close during concurrent poll; buffer retention on active timeout; `open_file` uses
|
||||
`O_CLOEXEC` with ordinary `open(2)` path semantics (no new symlink policy); EINTR; ENOSPC/EIO surfaced as `os_error`; partial start; teardown with
|
||||
stalled worker (shim gated by a latch); no busy loops; no allocation in `~File`; TSan-clean.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
`IoFile.cpp` (isolated temp dir per test, no fixed paths): `io_file_native_roundtrip_isolated_tmpdir`,
|
||||
`io_file_short_write_preserves_progress_write_all_at`, `io_file_writes_syncs_serialized_admission_order`,
|
||||
`io_file_reads_concurrent_explicit_offsets`, `io_file_queue_and_ops_quota_overloaded`,
|
||||
`io_file_queued_cancel_not_committed_zero_effects`, `io_file_queued_deadline_expires_once_manual_clock_poll`,
|
||||
`io_file_active_timeout_retains_buffer_until_syscall_returns`, `io_file_sync_success_after_stop_is_success`,
|
||||
`io_file_sync_failure_after_stop_sync_failed_unknown_errno`, `io_file_manual_stepping_without_workers`,
|
||||
`io_file_shutdown_joins_stalled_worker_then_delivers`, `io_file_shutdown_from_worker_self_join`,
|
||||
`io_file_workers_partial_start_failure_joins_started`, `io_file_drop_with_inflight_defers_close_until_drained`,
|
||||
`io_file_close_and_join_expiry_incomplete_retains_then_completes`, `io_file_ops_after_teardown_closed_no_syscall`,
|
||||
`io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread`,
|
||||
`io_worker_thread_marker_only_on_file_workers`, `io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan`,
|
||||
`io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan`, `io_stop_after_completion_releases_backend_ref_once`,
|
||||
`io_epoll_stop_requested_at_deadline_scan_completes_once` (D1 seam: clock armed after submission,
|
||||
asserts single delivery and `duplicate_completions_ignored >= 1`), `io_file_eintr_retried_via_shim`,
|
||||
`io_file_zero_length_overflow_and_zero_queue_limit`, `io_file_counts_against_max_descriptors`,
|
||||
`io_file_workers_second_start_invalid`, `io_poll_once_after_shutdown_returns_zero`,
|
||||
`io_poll_once_reentrant_inline_resume_busy`, `io_shutdown_bounded_deadline_incomplete_then_complete`,
|
||||
`io_shutdown_stop_token_returns_incomplete_report`, `io_request_stop_then_shutdown_cancels_queued_files`,
|
||||
`io_mock_held_request_does_not_block_teardown`. All pass; existing `IoDriver` tests
|
||||
pass unchanged; downstream suites pass unfiltered; `-Werror`, TSan 0 races, ASan+UBSan 0 errors.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; run `dev` with the sandbox disabled. Confirm new suites appear in output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3 -G Ninja -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3 --parallel 8 && /tmp/void-w11-io3/tests/VoidTests --filter "^(IoFile|IoDriver)\." && ctest --test-dir /tmp/void-w11-io3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-tsan --parallel 8 && /tmp/void-w11-io3-tsan/tests/VoidTests --filter "^(IoFile|IoDriver)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-asan --parallel 8 && /tmp/void-w11-io3-asan/tests/VoidTests --filter "^(IoFile|IoDriver)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-users -G Ninja -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;CryptoAsync;Runtime;ConfigurationAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-users --parallel 8 && /tmp/void-w11-io3-users/tests/VoidTests && ctest --test-dir /tmp/void-w11-io3-users --output-on-failure --timeout 180'
|
||||
```
|
||||
Warnings check (VOID_WARNINGS_AS_ERRORS does not reach VoidTests TUs, X-QA-01):
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/IO/IoFile.cpp && for h in File Driver Types; do echo "#include <Void/IO/$h.hpp>" | g++ -std=c++26 -freflection -x c++ -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers - || exit 1; done'
|
||||
```
|
||||
CryptoAsync may need `-p openssl` on the `dev` line (`dev cpp-gcc -p openssl -c ...`); report the
|
||||
exact command used.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions; no disabled warnings; no Threads link. Stop
|
||||
and report BLOCKED if: a forbidden file must change; a downstream suite fails for reasons rooted in
|
||||
the new blocking `shutdown_and_join` semantics that need a consumer edit; any D1 fix cannot be made
|
||||
without changing a public 1.x signature; or two repair attempts at the same failing check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040 under user decisions D-027/D-029/D-031. Listed files only; no
|
||||
commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations (esp. any choice the
|
||||
design docs left to you); evidence per acceptance criterion; commands with cwd/results (test counts,
|
||||
TSan/ASan); checks not run; residual risks; integration notes (worktree path, primitives A4 should
|
||||
wrap). Do not spawn children.
|
||||
@@ -0,0 +1,134 @@
|
||||
# S-IO-04 — Embedded pumping (`Driver::run`, `pump_until`), joined-shutdown conformance
|
||||
|
||||
Task ID: S-IO-04
|
||||
Role: sonnet-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step A4 (gate G4: S-IO-03 committed). Repo VoidLibrary, branch
|
||||
`feat/roadmap-p2-wave11`. Isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘); the branch adds RetryState, TimerQueue,
|
||||
retry_async and S-IO-03 (IoFile 33 tests).
|
||||
- Observed source after S-IO-03 (see `docs/agent-workflow/tasks/S-IO-03.md` and its implementer notes):
|
||||
- `include/Void/IO/Driver.hpp`: `poll_once(max_wait)` returns `IoErrorCode::busy` for three causes
|
||||
(reentrant call on this backend, concurrent poller, shutdown taking over poll ownership) without
|
||||
touching fds; after shutdown completes it returns 0 immediately. Public inline wrappers
|
||||
`begin_shutdown()`, `shutdown(Async::OperationOptions)` → `DriverShutdownReport`, `quiescent()`,
|
||||
`shutdown_complete()`; `request_stop()` == `begin_shutdown()`. Shutdown dispatches resume tickets on the
|
||||
thread that called `shutdown()`, after releasing poll ownership; the executor must outlive the Driver.
|
||||
- Mock backend: `poll_once` ignores `max_wait` (never blocks); requests held by a `MockController`
|
||||
token keep `pending_operations > 0` even when the report says `complete == true`.
|
||||
- `include/Void/Async/Timer.hpp`: `TimerQueue::{poll_expired, wait_duration(max_wait), next_deadline}`.
|
||||
- `include/Void/Async/TaskScope.hpp`: `join_pumping` drains the executor but never polls IO.
|
||||
- SystemAsync `ProcessManager` borrows a `Driver` (`include/Void/System/AsyncProcess.hpp`,
|
||||
`src/SystemAsync/AsyncProcess.cpp`). Net does not use IO (Net adapter deferred, D-W11-07).
|
||||
- Requirements: roadmap row S-IO-04 ("Embedded pumping, joined shutdown, SystemAsync conformance (Net
|
||||
adapter deferred) | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net
|
||||
dependency"); C-03..C-06; decisions D-038, D-040 (N3 loop rules), D-042 (S9 split).
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. EDIT `include/Void/IO/Driver.hpp`: NEW inline `Driver::run(std::stop_token, std::chrono::nanoseconds max_wait = 5ms)`.
|
||||
2. NEW `include/Void/IO/Pump.hpp`: `PumpOptions`, `pump_until`.
|
||||
3. NEW tests `tests/standalone/IO/IoShutdown.cpp`, `tests/standalone/IO/IoPump.cpp`,
|
||||
`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: any change to `src/IO/*`, `include/Void/IO/{Types,File}.hpp`, `include/Void/IO/Detail/*`, Async
|
||||
headers, SystemAsync sources, Runtime, Net adapter, build files. If a defect in the S-IO-03 primitives is
|
||||
found, STOP and report it with a reproducer (root owns the fix).
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/IO/{Driver,Types,File,Stream}.hpp`, `include/Void/IO/Detail/Backend.hpp` (read-only),
|
||||
`include/Void/Async/{Timer,Executor,TaskScope}.hpp`, `include/Void/System/AsyncProcess.hpp`,
|
||||
`tests/standalone/IO/{IoDriver,IoFile}.cpp`, `tests/standalone/SystemAsync/*.cpp`,
|
||||
`docs/agent-workflow/tasks/W11-CONTRACT-R2.md` N3, `W11-PLAN-OUTPUT.md` §S-IO-04.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/IO/Driver.hpp` (only the NEW `run` declaration/definition), `include/Void/IO/Pump.hpp` (NEW),
|
||||
`tests/standalone/IO/IoShutdown.cpp` (NEW), `tests/standalone/IO/IoPump.cpp` (NEW),
|
||||
`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp` (NEW).
|
||||
Forbidden: every other path. Other implementers work concurrently in other worktrees (Async EventBus/
|
||||
Observable; Runtime). No git operations except the authorized fast-forward.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY:
|
||||
- `run(stop, max_wait)`: loop until `stop.stop_requested()` or `shutdown_complete()`; each iteration calls
|
||||
`poll_once(max_wait)`; on `busy` wait up to `max_wait` in ≤1 ms stop-aware slices and retry; on a mock
|
||||
backend (or any turn that did no work and returned immediately) wait up to `max_wait` stop-aware so the
|
||||
loop never busy-spins; propagate any other error; return the accumulated work count. Never closes,
|
||||
frees or joins anything.
|
||||
- `pump_until(driver, manual, done, options)`: loop: `done()` → return count; `options.operation.stop`
|
||||
requested → `cancelled`; `options.operation.deadline` reached per `driver.clock()` → `timeout`;
|
||||
`max_turns` exceeded → `IoErrorCode::exhausted`; otherwise one turn = `poll_once(wait)` with
|
||||
`wait = timers ? timers->wait_duration(max_wait) : max_wait` (0 when work is runnable), then
|
||||
`timers->poll_expired()` if set, then drain `manual`; `busy` handled as in `run`; exits when
|
||||
`shutdown_complete()` and `done()` still false → returns the current count (caller decides). Never frees
|
||||
work; all waits re-read the injected clock.
|
||||
- Shutdown conformance tests use the public S-IO-03 API only: an expired `shutdown(options)` returns
|
||||
`complete=false` and retains fds/buffers/workers; a repeat call completes after release; concurrent
|
||||
`run()` loop + `shutdown()` is TSan-clean and the run loop exits on `shutdown_complete()`.
|
||||
- Layering: no `Void/Runtime`, `Void/Net`, `Void/System` include in `include/Void/IO` or `src/IO`
|
||||
(SystemAsync test lives under `tests/standalone/SystemAsync/`).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::IO {
|
||||
// Driver.hpp (NEW member, inline)
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run(std::stop_token stop,
|
||||
std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
|
||||
// Pump.hpp (NEW)
|
||||
struct PumpOptions { std::chrono::nanoseconds max_wait{0}; std::size_t max_turns{1u << 20};
|
||||
Async::OperationOptions operation{}; Async::TimerQueue* timers{nullptr}; };
|
||||
template <class Done> requires std::predicate<Done&>
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(Driver&, Async::ManualExecutor&, Done&& done,
|
||||
PumpOptions = {});
|
||||
}
|
||||
```
|
||||
Errors: `IoErrorCode::{cancelled, timeout, exhausted}` via `make_io_error`; `busy` is never returned by
|
||||
`run`/`pump_until`. Unchanged: every existing Driver member.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: S-IO-03, M-TIME-03 (TimerQueue). Downstream: S-RUNTIME-03 `shutdown_pumping` uses `pump_until`
|
||||
(gate G5); the Runtime reactor follows the same `busy`/mock wait rules. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Spurious `busy` during shutdown handoff; mock never blocks; `max_wait == 0`; stop already requested;
|
||||
deadline already expired; timers with nothing due; `done()` true initially; executor work that posts more
|
||||
work; no allocation per turn; no busy loops (assert bounded iteration counts with a fake/injected clock).
|
||||
|
||||
## 10. Acceptance criteria
|
||||
- `IoShutdown.cpp`: `io_shutdown_expired_budget_incomplete_retains_stalled_file_worker`,
|
||||
`io_shutdown_pending_socket_read_retains_buffer_until_delivery`, `io_shutdown_repeated_idempotent_after_complete`,
|
||||
`io_shutdown_concurrent_with_run_loop_tsan`, `io_run_stops_on_token_and_on_shutdown`,
|
||||
`io_begin_shutdown_rejects_new_admission`, `io_run_busy_and_mock_wait_does_not_spin`.
|
||||
- `IoPump.cpp`: `io_pump_until_scope_join_mock`, `io_pump_until_deadline_injected_clock`,
|
||||
`io_pump_until_max_turns_exhausted`, `io_pump_until_drives_timer_queue`, `io_pump_until_stop_cancelled`,
|
||||
`io_pump_until_exits_after_shutdown_complete`.
|
||||
- `SystemAsyncShutdown.cpp`: `systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once`.
|
||||
- Existing `IoDriver`, `IoFile`, `SystemAsync` tests pass; TSan 0 races; ASan+UBSan 0 errors; `-Werror`
|
||||
syntax checks clean; layering `rg` empty; `git diff --stat -- src/IO/module.cmake` empty.
|
||||
- Test caveats: keep each test well under 1,000 assertions (X-QA-02; count in loops, assert once) and keep
|
||||
each test declaration on ONE line (X-QA-03).
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4 -G Ninja -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io4 --parallel 8 && /tmp/void-w11-io4/tests/VoidTests --filter "^(IoShutdown|IoPump|IoFile|IoDriver|SystemAsyncShutdown|SystemAsync)\." && ctest --test-dir /tmp/void-w11-io4 --output-on-failure --timeout 120'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-io4-tsan --parallel 8 && /tmp/void-w11-io4-tsan/tests/VoidTests --filter "^(IoShutdown|IoPump|SystemAsyncShutdown|IoFile)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-io4-asan --parallel 8 && /tmp/void-w11-io4-asan/tests/VoidTests --filter "^(IoShutdown|IoPump|SystemAsyncShutdown)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in IO/IoShutdown IO/IoPump SystemAsync/SystemAsyncShutdown; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/$f.cpp || exit 1; done'
|
||||
rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO # expect no output
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions. Stop and report BLOCKED with a reproducer if an
|
||||
S-IO-03 primitive misbehaves (deadlock, spin, wrong report), if SystemAsync needs a source change, or two
|
||||
repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only; no
|
||||
commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance
|
||||
criterion; commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -0,0 +1,41 @@
|
||||
# S-MESSAGING-01..04 — Messaging Subsystem (Delivery Model, Ephemeral Queue, Durable Storage Queue, Outbox/Inbox, RPC Adapter)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Messaging` subsystem, `Void::MessagingStorage` durable adapter + outbox/inbox helper, and `Void::MessagingRpc` remote adapter per `docs/roadmap/subsystems/Messaging.md` and `docs/roadmap/DEPENDENCIES.md`:
|
||||
|
||||
1. **`S-MESSAGING-01..02` — Delivery Model, Receipts, State Machine, and Bounded Ephemeral Queue**:
|
||||
- Module `src/Messaging/module.cmake` (`INTERNAL_DEPS Core Functional Binary Time Async`) with zero `Storage`, `Net`, or `RPC` dependency.
|
||||
- Error domain `kMessagingErrorDomain = 32` (`MessagingErrorCode`).
|
||||
- Explicit `PublishDurability::{Memory, Durable}`: `InMemoryQueue` strictly rejects `PublishDurability::Durable` (`UnsupportedDurability`) and `PublishReceipt` records exact durability so nondurable channels never claim durable success.
|
||||
- Native state machine `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`.
|
||||
- FIFO per-queue competing consumers and `ConsumerMode::SingleActive` (blocking group head on retry until ack).
|
||||
- Visibility timeout (default 30s, explicit extension up to 5m via injected `MonotonicClock`), stale-receipt fencing (`StaleReceipt`), idempotent repeat ack, retry bound (default 5 attempts, full jitter 1s..60s via injectable RNG), corrupt-payload quarantine, and bounded caps (768 KiB message, 8 KiB / 32 headers, 1024 queues, 32 groups/queue, 64 in-flight/group, 1024 waiting receives, 64 MiB transient payload budget).
|
||||
- Clean `close_and_join()` stopping admission, waking/cancelling waiting receives, and draining active deliveries.
|
||||
2. **`S-MESSAGING-03` — Durable Storage Queue (`MessagingStorage`)**:
|
||||
- Module `src/MessagingStorage/module.cmake` (`INTERNAL_DEPS Messaging Storage`).
|
||||
- `StorageQueue` persists payload, sequence, group state, delivery generation/attempt, DLQ records, and bounded 24h / 100k publish idempotency ledger via `Void::Storage::Engine` conditional batches (`Durability::Sync`).
|
||||
- At idempotency capacity, rejects new publish (`IdempotencyCapacityExceeded`) instead of silently evicting live contracts.
|
||||
- On restart/reopen, promotes all prior `InFlight` records to `Pending` with bumped generation so stale worker receipts fail with `StaleReceipt`, preserving attempt counters across restarts.
|
||||
- Atomic DLQ move (DLQ insert + source group removal in one `Storage::Batch`); when DLQ or persistent quota is full, keeps the message durable, drops zero data, blocks affected admission, and exposes `stuck_dlq_count()`.
|
||||
- Explicit `RetentionPolicy::BlockAtQuota` default (unread work never silently expired) vs opt-in `DropOldestLossy`, pausing expiry when civil clock health fails; `UnknownOutcome` surfaced on uncertain storage commit.
|
||||
3. **`S-MESSAGING-04` — Outbox/Inbox Local-Batch Helper and Remote RPC Adapter (`MessagingRpc`)**:
|
||||
- `OutboxInbox` helper in `MessagingStorage` enabling single-batch local business mutation + outbox insert and single-batch local effect + inbox dedup insert, with explicit documentation that external effects remain outside the local batch boundary.
|
||||
- Separate module `src/MessagingRpc/module.cmake` (`INTERNAL_DEPS Messaging RPC`) exposing `RpcQueueServer` and `RpcQueueClient` for remote `publish`, `receive`, `ack`, `nack`, and `query_receipt` over Wire v1 unary RPC.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Messaging/{Types,Queue}.hpp`
|
||||
- `src/Messaging/{module.cmake,Queue.cpp}`
|
||||
- `include/Void/MessagingStorage/{StorageQueue,OutboxInbox}.hpp`
|
||||
- `src/MessagingStorage/{module.cmake,StorageQueue.cpp}`
|
||||
- `include/Void/MessagingRpc/RpcAdapter.hpp`
|
||||
- `src/MessagingRpc/{module.cmake,RpcAdapter.cpp}`
|
||||
- `tests/standalone/Messaging/Messaging.cpp`
|
||||
- `tests/standalone/MessagingStorage/StorageQueue.cpp`
|
||||
- `tests/standalone/MessagingRpc/RpcAdapter.cpp`
|
||||
- `tests/package/MessagingOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Messaging;MessagingStorage;MessagingRpc;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `MessagingOnly` consumer with `_no_external_deps`.
|
||||
- Deterministic tests for ephemeral/durable separation, competing vs single-active ordering, visibility expiry & stale receipt fencing, idempotent ack/publish, restart recovery preserving attempts, poison -> atomic DLQ move, DLQ/quota/idempotency cap pressure, clock-health pause, outbox/inbox single-batch atomicity, and remote RPC round-trip.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,224 @@
|
||||
# S-RUNTIME-02/03 — Host start, readiness, failed-start cleanup, structured shutdown, joined teardown
|
||||
|
||||
Task ID: S-RUNTIME-02-03
|
||||
Role: opus-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package steps B3+B4 combined (same files, shared teardown core). Dispatched after M-ASYNC-04
|
||||
(ThreadExecutor), S-IO-03 and S-IO-04 (`pump_until`) are committed (gates G3, G5). Repo VoidLibrary,
|
||||
branch `feat/roadmap-p2-wave11`. Isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘).
|
||||
- Observed source:
|
||||
- `include/Void/Runtime/Host.hpp`: inert `Host` (movable, `~Host() = default`, header-only; `HostState`
|
||||
has no moved-from value; `started_worker_count()` always 0; `memory_budget()` dereferences
|
||||
`owned_budget_` which is null after a move — pre-existing hazard), `EmbeddedResources` (borrowed
|
||||
executor/io/clock), `ShutdownReport`, `HostBuilder`. `include/Void/Runtime/Options.hpp`:
|
||||
`RuntimeLimits`, `Options` (`file_workers`, `cpu_workers`, `total_timeout`, `drain_grace`,
|
||||
`export_flush_timeout`, …), `validate_options` (rejects `total_timeout <= 0`), `RuntimeErrorCode` incl.
|
||||
root-added `self_join = 8`, `shutdown_incomplete = 9` (both → `ErrorKind::conflict`).
|
||||
`include/Void/Runtime/ResourceGraph.hpp`: `ResourceKind` incl. `service`, `exporter`; `LifecyclePlan`
|
||||
with `startup_order`. Existing tests `tests/standalone/Runtime/RuntimeHost.cpp` pin `started_worker_count()
|
||||
== 0` after create and inert `add_resource` nodes.
|
||||
- Available after upstream steps: `Async::ThreadExecutor` (`create/start/close/join/idle/admitted/stats`,
|
||||
`before_worker_start` hook, `is_executor_thread`), `Async::TaskScope` (`stop_on_first_error` option),
|
||||
`Async::TimerQueue`; `IO::Driver` (`start_file_workers`, `run_file_work`, `poll_once` → `busy` rules,
|
||||
`shutdown(options)` → `DriverShutdownReport`, `shutdown_complete`, `quiescent`, `is_io_worker_thread()`,
|
||||
`BackendOptions::before_file_worker_start`, mock `poll_once` ignores `max_wait`), `IO::pump_until`.
|
||||
- System signal gate: `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp`; create before
|
||||
worker threads, destroy on the creating thread; off-thread destruction closes the fd but skips the mask
|
||||
restore, `src/System/SignalWatcher.cpp:27-37`). Runtime has NO System dependency (D-W11-04).
|
||||
- Requirements: roadmap rows S-RUNTIME-02 ("Explicit start, readiness and reverse failed-start cleanup |
|
||||
Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained") and
|
||||
S-RUNTIME-03 ("Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting
|
||||
| Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work
|
||||
reports incomplete without freeing resources"); `docs/roadmap/subsystems/Runtime.md` (updated in W11);
|
||||
C-03..C-06, C-09; decisions D-038, D-040, D-042.
|
||||
- MANDATORY design sources (precedence R2 > REV1 > PLAN): `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`
|
||||
§S-RUNTIME-02 and §S-RUNTIME-03; `W11-PLAN-REV1-OUTPUT.md` F3, F4, F5, F6, F11 and P3 (business scope,
|
||||
mock reactor spin, budget accounting test); `W11-CONTRACT-R2.md` N1, N2, N3, P3-1, P3-2, P3-3, P3-7, P3-8.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. NEW `include/Void/Runtime/Lifecycle.hpp`: `StartStep`, `SignalGate`, `HostContext`, `Component`,
|
||||
`StartOptions`, `ShutdownPhase`.
|
||||
2. NEW `include/Void/Runtime/Detail/HostCore.hpp`: all lifecycle state and teardown (Runtime stays header-only).
|
||||
3. EDIT `include/Void/Runtime/Host.hpp`: start/readiness/shutdown API, appended `ShutdownReport` fields,
|
||||
`HostBuilder::add_component`, moved-from rules.
|
||||
4. NEW tests `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals,RuntimeShutdown}.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: Runtime→System edge or production signal bridge (S-RUNTIME-04), managed resize/reload, host-managed
|
||||
TimerQueue polling (D-W11-14), any IO/Async/System source change, build files.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Runtime/*.hpp`, `src/Runtime/module.cmake`, `tests/standalone/Runtime/RuntimeHost.cpp`,
|
||||
`tests/package/RuntimeOnly/*`, `tests/package/InstalledComponents.cmake` (RuntimeOnly runs with
|
||||
`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`), `include/Void/Async/{ThreadExecutor,TaskScope,Executor,Timer}.hpp`,
|
||||
`include/Void/IO/{Driver,Pump,Types}.hpp`, `include/Void/Memory/BudgetResource.hpp`,
|
||||
`include/Void/System/SignalWatcher.hpp`, and the design sources in §1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Runtime/Host.hpp`, `include/Void/Runtime/Lifecycle.hpp` (NEW),
|
||||
`include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/RuntimeStart.cpp` (NEW),
|
||||
`tests/standalone/Runtime/RuntimeSignals.cpp` (NEW), `tests/standalone/Runtime/RuntimeShutdown.cpp` (NEW),
|
||||
`tests/package/RuntimeOnly/main.cpp` (optional smoke only).
|
||||
Forbidden: every other path, including `Options.hpp`, `ResourceGraph.hpp`, IO/Async/System files and
|
||||
`RuntimeHost.cpp` (stop and report if a change there is needed, P3-8). No git operations except the
|
||||
authorized fast-forward.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY start (S-RUNTIME-02):
|
||||
- `start(StartOptions)` once: `constructed → starting → running | failed_start`; records the owner thread.
|
||||
Steps in order, each pushing a cleanup action: (1) `signal_gate->install()` (track `gate_installed_`;
|
||||
borrowed gate must outlive the Host); (2) memory budget; (3) owned `ThreadExecutor{workers = cpu_workers,
|
||||
max_admitted = limits.max_cpu_tasks}` create + `start()` (forward `before_thread_start(cpu_executor, i)`
|
||||
into `before_worker_start`); (4) `IO::Driver::create` with `io.limits.file_workers = Options::file_workers`
|
||||
(Runtime is authoritative) and the memory budget as its pmr resource; (5) `start_file_workers()` (forward
|
||||
hook into `BackendOptions::before_file_worker_start`); (6) Runtime-owned reactor `std::thread` (catch
|
||||
`std::system_error`; `before_thread_start(reactor, 0)` hook; thread-local `tl_reactor` marker) looping
|
||||
`poll_once(5ms)`; on `busy`, or on a mock backend / a turn that did no work, wait up to 5 ms stop-aware
|
||||
(never spin); exits on reactor stop or `shutdown_complete()`; (7) components in `plan_.startup_order`, `start`
|
||||
called outside Host locks; (8) readiness: executor `try_post` probe plus one reactor turn within
|
||||
`readiness_timeout` → `running`, `is_ready() == true`. `before_step(step)` hook errors inject failure
|
||||
between steps; thread hooks inject failure within threaded steps.
|
||||
- Failure at any point: pop cleanups in reverse on the starting thread, bounded by `cleanup_timeout`
|
||||
(injected clock); state `failed_start`; return the error wrapped with context preserving the root
|
||||
`Status`. If cleanup does not finish in budget, resources are retained and the next `shutdown_blocking`
|
||||
or `~HostCore` continues. No thread or descriptor may remain after a completed cleanup.
|
||||
- Embedded mode (`create_embedded`): steps 3–6 are skipped (borrowed executor/driver/clock); no threads.
|
||||
- `started_worker_count()` reports real CPU + reactor + file threads.
|
||||
- Business work: `spawn(Task, OperationOptions)` into a business `TaskScope` with
|
||||
`TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`.
|
||||
MANDATORY shutdown (S-RUNTIME-03; REV1 F3/F4 phase list, R2 N1–N3):
|
||||
- Phases: 1 closing_admission, 2 draining (drain deadline fixed at first entry = min(total, start +
|
||||
drain_grace)), 3 cancelling, 4 joining_business, 5 stopping_components (non-exporters, dependents first),
|
||||
6 flushing_exporters (flush deadline fixed at first entry; expiry requests stop on exporter operations,
|
||||
sets `export_flush_expired`, keeps waiting), 7 releasing_components (drop every component `shared_ptr`, so
|
||||
exporters are destroyed here), 8 stopping_io (request reactor stop and JOIN the reactor, then
|
||||
`driver->shutdown(remaining)` from the shutdown thread; retain if incomplete), 9 stopping_workers (wait for
|
||||
`ThreadExecutor::idle()` within budget, then `join()`), 10 releasing (budgets, descriptors; signal gate
|
||||
`uninstall(on_owner_thread)` at most once), 11 stopped. Assert ordering
|
||||
`exporter_stopped < exporter_destroyed < executor_joined`.
|
||||
- Every entry point (`shutdown_blocking`, `poll_shutdown`, `shutdown_pumping`) computes its own budget
|
||||
`min(options.deadline, deadline_after(clock, total_timeout))`. In waiting phases 2, 4, 5, 6, 8, 9 a
|
||||
call-deadline expiry stops the sequence and returns `complete=false`, state `shutdown_incomplete`, phase
|
||||
recorded, all resources retained; the next call resumes at that phase. Drain expiry moves on to phase 3 and
|
||||
sets `drain_grace_expired`.
|
||||
- Component `stop()` tasks are launched through `post_completion` (never normal-lane admission), so a full
|
||||
queue cannot block them. Concurrent callers get the same final report; exactly one teardown.
|
||||
- `shutdown_blocking` on a Runtime worker/reactor/IO worker → `RuntimeErrorCode::self_join`;
|
||||
`shutdown_blocking` when the executor has no background workers (embedded) → `invalid_argument`;
|
||||
`shutdown_pumping` in managed mode → `invalid_argument`. Off-owner shutdown completes every phase except
|
||||
the gate release (`owner_release_pending = true`); a later owner-thread call or `~HostCore` calls
|
||||
`uninstall(this_thread == owner)`.
|
||||
- Embedded `shutdown_pumping(manual, options, timers)` drains business scope and components using
|
||||
`IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`; borrowed
|
||||
executor, driver, clock and memory are NEVER shut down, closed or joined.
|
||||
- `~HostCore` (teardown lives here so default move-assign is safe): managed — loop shutdown with no
|
||||
deadline cap until `complete` ("destruction blocks until complete"); embedded with a borrowed
|
||||
`ManualExecutor` (dynamic_cast) — loop `shutdown_pumping(manual)` until complete; embedded otherwise and
|
||||
incomplete — stderr diagnostic + `std::terminate`. On an OWNED Runtime worker/reactor/IO worker thread —
|
||||
stderr diagnostic + `std::terminate` (detection via owned executor `is_executor_thread()`, `tl_reactor`,
|
||||
`IO::is_io_worker_thread()`; never for a borrowed executor).
|
||||
- Moved-from Host: `valid() == false`; `state()` returns `stopped`; `is_running/is_ready` false;
|
||||
`started_worker_count()` 0; `executor()/io()` nullptr; `owner_thread()/last_shutdown_report()` nullopt;
|
||||
`start/shutdown_*/poll_shutdown` → `invalid_state`; `spawn` → `AdmissionError::stopped`; reference accessors
|
||||
(`options`, `lifecycle_plan`, `embedded_resources`, `memory_budget`) have precondition `valid()` (document,
|
||||
assert in debug). `HostCore` holds no pointers into `Host` members. Owned BudgetResource/executor/driver live
|
||||
until `~HostCore`.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Runtime {
|
||||
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
|
||||
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
|
||||
stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped };
|
||||
class SignalGate { public: virtual ~SignalGate() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
|
||||
virtual void uninstall(bool on_owner_thread) noexcept = 0; };
|
||||
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
|
||||
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
|
||||
class Component { public: virtual ~Component() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0;
|
||||
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
|
||||
struct StartOptions { SignalGate* signal_gate{nullptr};
|
||||
std::function<Void::Result::Result<void>(StartStep)> before_step{};
|
||||
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)> before_thread_start{};
|
||||
std::function<void(ShutdownPhase)> on_phase{};
|
||||
std::chrono::milliseconds readiness_timeout{5000}; std::chrono::milliseconds cleanup_timeout{5000}; };
|
||||
}
|
||||
// Host (EDIT): [[nodiscard]] Result<void> start(StartOptions = {}); bool is_ready() const noexcept; bool valid() const noexcept;
|
||||
// Async::Executor* executor() noexcept; IO::Driver* io() noexcept; std::optional<std::thread::id> owner_thread() const noexcept;
|
||||
// std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
|
||||
// void begin_shutdown() noexcept; Result<ShutdownReport> poll_shutdown(Async::OperationOptions = {});
|
||||
// Result<ShutdownReport> shutdown_blocking(Async::OperationOptions = {});
|
||||
// Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr);
|
||||
// std::optional<ShutdownReport> last_shutdown_report() const; std::size_t cpu_admitted() const noexcept;
|
||||
// lifecycle state in std::unique_ptr<detail::HostCore>.
|
||||
// ShutdownReport (EXISTING fields kept) + appended: ShutdownPhase phase; std::size_t pending_business_tasks,
|
||||
// pending_cpu_admitted, pending_io_operations, retained_buffer_bytes; bool drain_grace_expired,
|
||||
// export_flush_expired, owner_release_pending; bool complete (if not already present).
|
||||
// HostBuilder (EDIT): [[nodiscard]] Result<void> add_component(std::string id, ResourceKind,
|
||||
// std::shared_ptr<Component>, std::vector<std::string> deps = {}, bool critical = true);
|
||||
```
|
||||
Use existing `Result`/`make_runtime_error` spellings. Existing 1.x Host/HostBuilder API and `RuntimeHost` tests unchanged.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: M-ASYNC-04, S-IO-03, S-IO-04, M-TIME-03 (all in your base). Downstream: P-NETWORKED-02 /
|
||||
P-RELOADABLE-02 (later waves). Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Failure at every step and inside threaded steps (index 0 and last); thread-creation exceptions; pending
|
||||
SIGUSR2 must be drained before uninstall (otherwise default action kills VoidTests); `/proc/self/task` and
|
||||
`/proc/self/fd` deltas measured within a single test, Host telemetry primary; ManualClock + blocking waits
|
||||
re-read the injected clock in short slices; deterministic tests use `poll_shutdown` or expired deadlines
|
||||
rather than sleeps; full normal queue during shutdown; exporter waiting on a held mock read; RuntimeOnly
|
||||
consumer has Threads lookup disabled (libc with integrated pthreads assumed, as IO already does).
|
||||
|
||||
## 10. Acceptance criteria
|
||||
- `RuntimeStart.cpp`: `runtime_start_spawns_workers_only_on_start_ready`, `runtime_start_twice_invalid_state`,
|
||||
`runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds`, `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup`,
|
||||
`runtime_failed_start_component_cleanup_timeout_retains_then_completes`, `runtime_component_start_failure_unwinds_reverse`,
|
||||
`runtime_signal_gate_before_threads_uninstall_on_owner`, `runtime_signal_gate_uninstalled_at_most_once`,
|
||||
`runtime_embedded_start_no_threads`, `runtime_move_after_start_keeps_resources_valid`, `runtime_moved_from_host_safe_defaults`.
|
||||
- `RuntimeSignals.cpp` (includes `Void/System/SignalWatcher.hpp`; silently skipped without System; test-local
|
||||
SignalGate adapter over `Process::SignalWatcher`, SIGUSR2): `runtime_system_gate_mask_inherited_by_workers`,
|
||||
`runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`,
|
||||
`runtime_signal_during_start_stays_pending_and_is_drained`, `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`
|
||||
(restores the owner mask and drains SIGUSR2 before finishing).
|
||||
- `RuntimeShutdown.cpp`: `runtime_shutdown_concurrent_callers_single_teardown_tsan`,
|
||||
`runtime_shutdown_full_normal_queue_still_delivers_completion`,
|
||||
`runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (ordering log),
|
||||
`runtime_shutdown_stalled_business_task_incomplete_retains`, `runtime_shutdown_child_spawn_during_close_rejected`,
|
||||
`runtime_shutdown_budget_expired_caller_deadline_incomplete_then_resumes`,
|
||||
`runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`,
|
||||
`runtime_shutdown_on_worker_self_join`, `runtime_shutdown_non_owner_defers_gate_release`,
|
||||
`runtime_shutdown_embedded_pumping`, `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`,
|
||||
`runtime_embedded_shutdown_blocking_invalid_argument`, `runtime_managed_shutdown_pumping_invalid_argument`,
|
||||
`runtime_destructor_joins_after_start`, `runtime_destructor_blocks_until_complete_after_incomplete_shutdown`.
|
||||
- Existing `RuntimeHost` tests pass; `RuntimeOnly` consumer passes (ctest); TSan 0 races; ASan+UBSan 0 errors;
|
||||
`-Werror` syntax checks clean. Keep each test well under 1,000 assertions (X-QA-02) and each test declaration
|
||||
on ONE line (X-QA-03).
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt --parallel 8 && /tmp/void-w11-rt/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt --output-on-failure --timeout 180'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt-nosys --parallel 8 && /tmp/void-w11-rt-nosys/tests/VoidTests --filter "^(RuntimeStart|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt-nosys --output-on-failure --timeout 180'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-rt-tsan --parallel 8 && /tmp/void-w11-rt-tsan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-rt-asan --parallel 8 && /tmp/void-w11-rt-asan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in RuntimeStart RuntimeSignals RuntimeShutdown; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Runtime/$f.cpp || exit 1; done'
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions; no Runtime→System edge; no Threads link. Stop and report
|
||||
BLOCKED if an IO/Async primitive misbehaves (give a reproducer), a forbidden file must change, RuntimeHost tests
|
||||
must change, or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 under user decisions D-027/D-029/D-031. Listed files only; no
|
||||
commits, pushes or other side effects.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion;
|
||||
commands with cwd/results; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -0,0 +1,40 @@
|
||||
# S-SCHEDULER-01..04 — Scheduler Subsystem (Timers, Calendar, Durable Storage Store, Operator Controls)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Scheduler` subsystem and `Void::SchedulerStorage` durable adapter per `docs/roadmap/subsystems/Scheduler.md` and `docs/roadmap/DEPENDENCIES.md`:
|
||||
|
||||
1. **`S-SCHEDULER-01` — In-Memory Heap, Recurrence, Overlap, Cancellation & Shutdown**:
|
||||
- Module `src/Scheduler/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero `Storage` dependency.
|
||||
- Error domain `kSchedulerErrorDomain = 31` (`SchedulerErrorCode`).
|
||||
- Monotonic min-heap ordered by `(due_time, sequence)` using injected `MonotonicClock` and `CivilClock`, pure construction (no hidden background threads), and `Async::OperationOptions` for deadlines/cancellation.
|
||||
- One-shot, fixed-delay (advances from durable completion), and fixed-rate (advances from intended schedule time) schedules; `OverlapPolicy` (`Forbid`, `QueueOne`, `AllowBounded`); `RetryPolicy` (default 5 attempts, exponential backoff 1s..5m, x2, injectable full-jitter RNG); callbacks run outside scheduler/store locks.
|
||||
- `close_and_join()` stops materialization/dispatch, signals active handlers, joins within deadline, and returns `ShutdownReport` preserving running records on timeout.
|
||||
2. **`S-SCHEDULER-02` — Calendar Grammar, Explicit Timezones/DST, and Bounded Misfire**:
|
||||
- 5-field cron-like grammar (`minute hour day month weekday` with `*`, lists, ranges, steps; both day-of-month and weekday constraints apply).
|
||||
- Explicit `TimezoneRegistry` supporting `"UTC"`, fixed offsets (`+HH:MM`/`-HH:MM`), and explicit DST transition rules (`DstGapPolicy::Skip`/`NextValid`, `DstFoldPolicy::First`/`Second`/`Twice` with persisted `fold_index`). Unknown timezone fails with `UnsupportedTimezone` (never silent UTC fallback).
|
||||
- `MisfirePolicy` (`Skip`, `CoalesceLatest`, `CatchUpBounded` capped at `100` slots/job/pass while preserving remaining cursor state even across millions of missed slots).
|
||||
3. **`S-SCHEDULER-03` — Durable Persistence Port and `SchedulerStorage` Adapter**:
|
||||
- `JobStore` port + `InMemoryJobStore` (in `Scheduler`) and `StorageJobStore` (in `src/SchedulerStorage/module.cmake`, `INTERNAL_DEPS Scheduler Storage`) backed by `Void::Storage::Engine` conditional batches (`Durability::Sync`, 1 MiB batch cap).
|
||||
- Exclusive ownership lock rejecting second concurrent scheduler owner (`OwnershipLocked`).
|
||||
- Atomic occurrence materialization + cursor advance with unique `(job, revision, civil_slot, fold)` dedup key preventing duplicate materialization on wall-clock rollback.
|
||||
- Atomic `Pending -> Running` claim checking job tombstone and revision invalidation watermark in the same conditional batch; `Running -> Completed` / `Pending` / `Dead` transitions; `UnknownOutcome` surfaced faithfully on unknown storage write outcome.
|
||||
- Startup crash recovery returning `Running` occurrences to `Pending` with the exact same `OccurrenceId` (explicit at-least-once semantics).
|
||||
4. **`S-SCHEDULER-04` — Revision Updates, Tombstone Removal, Retention Caps, and Operator Inspection**:
|
||||
- `update_job()` bumps revision and atomically writes old-revision invalidation watermark so unstarted old occurrences are cancelled without racing active claims; failed updates leave prior policy intact.
|
||||
- `remove_job()` writes tombstone, stops admission, and requests stop for active handlers.
|
||||
- Retention count cap pauses materialization without advancing cursors or deleting unacknowledged work; dead occurrences require explicit `acknowledge_dead()` before pruning; bounded `prune_completed()` / `reclaim_invalidated()` and inspection APIs.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Scheduler/{Types,Calendar,Store,Scheduler}.hpp`
|
||||
- `src/Scheduler/{module.cmake,Calendar.cpp,Scheduler.cpp}`
|
||||
- `include/Void/SchedulerStorage/StorageJobStore.hpp`
|
||||
- `src/SchedulerStorage/{module.cmake,StorageJobStore.cpp}`
|
||||
- `tests/standalone/Scheduler/Scheduler.cpp`
|
||||
- `tests/standalone/SchedulerStorage/StorageJobStore.cpp`
|
||||
- `tests/package/SchedulerOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Scheduler;SchedulerStorage;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `SchedulerOnly` consumer with `_no_external_deps`.
|
||||
- Deterministic fake-clock ordering, overlap, retry/dead-letter, DST gap/fold/unknown-tz, millions-of-missed-slots coalesce/catch-up cap, crash/reopen recovery preserving `OccurrenceId`, revision watermark race, unknown outcome, and retention-cap cursor preservation tests.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Wave 11 contract amendment R2 (root resolutions of PREFLIGHT-2)
|
||||
|
||||
Source findings: [W11-PREFLIGHT-2-OUTPUT](W11-PREFLIGHT-2-OUTPUT.md). Base contracts:
|
||||
[W11-PLAN-OUTPUT](W11-PLAN-OUTPUT.md) amended by [W11-PLAN-REV1-OUTPUT](W11-PLAN-REV1-OUTPUT.md).
|
||||
These rules are MANDATORY text for the B2, B3, B4, A2, A3, A4 specs (decision D-040). Where this
|
||||
file and earlier documents disagree, this file wins.
|
||||
|
||||
## N1 — Host destruction and shutdown budgets (B3/B4)
|
||||
- `~HostCore` blocks until shutdown is complete: it loops an internal no-deadline shutdown
|
||||
(equivalent to repeated `shutdown_blocking({})` ignoring the total-timeout cap) until
|
||||
`complete == true`. Documented: "destruction blocks until complete".
|
||||
- `poll_shutdown(Async::OperationOptions = {})` takes options; every shutdown entry point
|
||||
(`shutdown_blocking`, `poll_shutdown`, `shutdown_pumping`) uses the same per-call budget
|
||||
`min(options.deadline, deadline_after(clock, total_timeout))`.
|
||||
- The budget test uses an already-expired caller deadline (or manual-clock deadline) with
|
||||
`shutdown_blocking`/`poll_shutdown`, so expiry is observable.
|
||||
- Waiting phases that return `complete=false` on call-deadline expiry: 2, 4, 5, 6, 8, 9 (P3-1).
|
||||
|
||||
## N2 — Embedded mode (B3/B4)
|
||||
- `shutdown_blocking` returns `RuntimeErrorCode::invalid_argument` when the Host's executor has
|
||||
no background workers (`!has_background_workers()`); `shutdown_pumping` in managed (owned
|
||||
executor) mode returns `invalid_argument` (the reactor owns polling).
|
||||
- `~HostCore` in embedded mode: if the borrowed executor is a `ManualExecutor`
|
||||
(`dynamic_cast`), it loops `shutdown_pumping(manual)` until complete; otherwise, if shutdown is
|
||||
not already complete, it prints a diagnostic and calls `std::terminate` (documented
|
||||
programmer error: embedded Host destroyed before shutdown completed).
|
||||
- The "destroyed on a Runtime worker" terminate check applies only to OWNED executors/reactor/
|
||||
IO workers; never to a borrowed executor's `is_executor_thread()`.
|
||||
|
||||
## N3 — Who polls during shutdown (B2, A4, B3/B4)
|
||||
- B2: every poll turn drains cancels, control messages and file completions BEFORE any
|
||||
stop-flag early return. `begin_shutdown` sets the existing stopping flag (admission closed).
|
||||
While stopping (but not yet shut down), a turn with no work waits in `epoll_wait` up to
|
||||
`max_wait` (wake fd stays registered) instead of returning immediately; it must not spin.
|
||||
- B2: after shutdown completes, `poll_once` returns 0 without touching any fd (F2), and
|
||||
`shutdown_complete()` is true; library loops must exit on it (below).
|
||||
- B2: `poll_once` checks the thread-local polling marker before `try_lock(poll_mu_)`; a
|
||||
reentrant call from inside a turn returns `busy` (no recursive try_lock UB).
|
||||
- B2: `advance_shutdown` releases `poll_mu_` between its ≤1 ms slices; other pollers may run
|
||||
turns in between (they only drain/dispatch). If its stop token fires it returns the current
|
||||
report with `complete=false` (not an error).
|
||||
- B2: when `advance_shutdown`/teardown dispatches resume tickets, it does so after releasing
|
||||
poll ownership (P3-9). Document: an owned executor must not be joined before the Driver is
|
||||
torn down.
|
||||
- A4: `Driver::run` and `pump_until` on `busy` wait up to `max_wait` (stop-aware, at most 1 ms
|
||||
slices) and retry; they exit when `shutdown_complete()` is true.
|
||||
- B3/B4: Runtime phase 8 first requests reactor stop and JOINS the reactor thread, then drives
|
||||
`driver->shutdown(remaining)` from the shutdown thread. The reactor loop also exits on
|
||||
`shutdown_complete()`; on `busy` it waits as A4's loops do.
|
||||
|
||||
## N4 — File descriptor state machine (B2)
|
||||
- `detail::FileState` has `enum { open, closing, closed }` guarded by the pool mutex; the
|
||||
handle-drop / in-flight count / `close_pending` transitions happen under that mutex, so
|
||||
exactly one close is enqueued and whoever closes the fd sets `closed`.
|
||||
- Driver teardown closes any still-open file fds after joining workers and marks them
|
||||
`closed`. Afterwards File reads/writes/syncs return `IoErrorCode::closed` without a syscall,
|
||||
`~File` does nothing, and `close_and_join` returns success immediately (idempotent).
|
||||
- Files count against `IoLimits::max_descriptors`; that bounds the reserved close capacity.
|
||||
The close request node is preallocated inside `FileState`, so `~File` (noexcept) never
|
||||
allocates.
|
||||
- `~File` wakes the poller only through a weak→strong backend lock or the worker condition
|
||||
variable, never through the raw waker pointer.
|
||||
|
||||
## N5 — Channel timer callbacks (A2; B1 documents)
|
||||
- B1 documents: `TimerHandle::cancel() == false` means the callback fired or is firing, not
|
||||
that it finished.
|
||||
- A2: an AsyncChannel timer callback captures shared waiter state (`shared_ptr` control block
|
||||
for the waiter) or a `weak_ptr` to the channel plus a waiter id looked up under the channel
|
||||
lock. It never holds a raw pointer into a coroutine frame.
|
||||
|
||||
## N6 — EventBus destruction (A3)
|
||||
- `~EventBus` gates every admitted-but-not-started delivery on every thread before returning
|
||||
(shared core `closed` flag checked under the core lock before each delivery starts).
|
||||
- It waits for callbacks running on OTHER threads to finish, excluding the current thread's own
|
||||
in-progress callback (thread-local dispatch depth). Residual documented: destroying a bus from
|
||||
inside a callback that another thread's callback waits on can deadlock (caller error).
|
||||
- A throwing `error_sink` is caught and counted (D-W11-06 condition, P3-8).
|
||||
|
||||
## P3 lines
|
||||
- P3-2 (B3/B4): owned `BudgetResource`, executor and driver objects live until `~HostCore`;
|
||||
NEW `[[nodiscard]] std::size_t Host::cpu_admitted() const noexcept` (0 when not started or
|
||||
embedded) for the budget test; a `BufferLease` must not outlive its resource.
|
||||
- P3-3 (B3/B4): the borrowed `SignalGate` must outlive the Host; Host tracks `gate_installed_`
|
||||
so `uninstall` runs at most once (failed-start cleanup and teardown cannot double-uninstall);
|
||||
the off-owner signal test restores the owner mask and drains SIGUSR2 before finishing.
|
||||
- P3-4 (root): MIGRATION records "concurrent `poll_once` returns `busy`" and "`~Driver` on a
|
||||
file worker or inside a poll turn terminates"; `Runtime.md` shows the `TimerQueue*` parameter
|
||||
on `shutdown_pumping`.
|
||||
- P3-5 (B2): the D1 seam clock is armed only after submission (`submit_io` reads the clock at
|
||||
`EpollDriver.cpp:503`).
|
||||
- P3-6 (A1): `seeded_engine` constructs with parentheses `G(std::random_device{}())` (sent).
|
||||
- P3-7 (B3): moved-from Host reference accessors (`options`, `lifecycle_plan`,
|
||||
`embedded_resources`) have precondition `valid()` (documented, asserted in debug); `HostCore`
|
||||
holds no pointers into `Host` members.
|
||||
- P3-8 (B3): stop-and-report if an IO edit is needed (IO files are owned elsewhere).
|
||||
@@ -0,0 +1,906 @@
|
||||
# W11-PLAN output (opus-planner, 2026-11-29)
|
||||
|
||||
Verbatim planner return for [W11-PLAN](W11-PLAN.md). Advisory input; root decisions are recorded in `DECISIONS.md`.
|
||||
|
||||
# W11-PLAN: execution-path backfill plan (opus-planner)
|
||||
|
||||
**Status: DONE.** The plan is ready for opus-reviewer PREFLIGHT. It is not approved, and I don't approve it myself. Nothing was written to the repository.
|
||||
|
||||
## Summary
|
||||
|
||||
- All eight tasks can be done without a forbidden dependency edge. **No `INTERNAL_DEPS` change is needed.**
|
||||
- The roadmap rows leave out four real dependencies:
|
||||
- The library has no thread-backed `Async::Executor`, so S-RUNTIME-02 depends on M-ASYNC-04.
|
||||
- The IO `Driver` has no file workers and no run loop, so S-RUNTIME-02 depends on S-IO-03 and S-RUNTIME-03 depends on S-IO-04.
|
||||
- Async has no timer primitive. M-TIME-03 adds one, and M-ASYNC-04's timed channel waits then depend on M-TIME-03.
|
||||
- **Existing IO defect.** The epoll backend can release one operation's backend reference twice. A cross-thread `shutdown_and_join` can also finish an operation and close its fd while another thread's `poll_once` is inside `::read`/`::write` on it. Both fixes are assigned to S-IO-03 (opus).
|
||||
- **Signal gate exists.** It is `Void::Process::SignalWatcher` in System. The plan uses it through a new Runtime port (`SignalGate`), so Runtime does not gain a System dependency.
|
||||
- **S-RPC-04: defer.** It is file-disjoint, but it is not a good ride-along (reasons below).
|
||||
- **Partition:** two packages by role. Package A is sonnet with the sol rows; package B is opus with the astra rows. A small root "contracts pre-commit" adds the new enumerators first, and five gates sequence the hand-offs between packages.
|
||||
|
||||
---
|
||||
|
||||
## 0. Cross-cutting evidence
|
||||
|
||||
- **Builds and consumers**
|
||||
- The selected-module list expands to its dependencies (`CMakeLists.txt:45-71`).
|
||||
- A test whose includes need an unselected header is skipped silently (`tests/CMakeLists.txt:12-41`). Every command below therefore enables all modules a new test includes.
|
||||
- `--filter` is a regex search over the test name or `suite.name`, where the suite is the file stem (`src/Testing/Runner.cpp:209-225`). Filters below use `^(Stem1|Stem2)\.`.
|
||||
- Warnings are `-Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers` (`cmake/Module.cmake:178`). Appending members to aggregates is therefore safe. Every enum switch must be completed; the only switches over the extended enums are the `make_*_error` mappers (`Async/Detail/Types.hpp:65-91,103-134`, `IO/Types.hpp:46-77`, `Runtime/Options.hpp:39-60`).
|
||||
- The installed consumers IOOnly and RuntimeOnly run with `-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE` (`tests/package/InstalledComponents.cmake:74-80,109-117`). Adding `Threads::Threads` to IO or Runtime would break them, so the plan doesn't (D-W11-08). IO already calls `pthread_sigmask` without it (`EpollDriver.cpp:47`).
|
||||
- **Executors**
|
||||
- The only executor in the library is `ManualExecutor` (`Async/Executor.hpp:120-254`).
|
||||
- Thread-backed executors exist only inside one test file (`tests/standalone/Async/OperationScope.cpp:25,135`).
|
||||
- `ManualExecutor` releases its slot before resuming (`Executor.hpp:226-228`), so its bound excludes running work. Its `post()` bypasses the bound (`:128-135`).
|
||||
- **IO**
|
||||
- No thread, no run loop, no file API (`IO/Driver.hpp:59-105`). The embedder drives it with `poll_once` (`EpollDriver.cpp:1843-1847`).
|
||||
- `IoLimits::file_workers` and `max_file_queue` (`IO/Types.hpp:106-107`) and `IoErrorCode::incomplete_shutdown` (`:32`) are declared but unused in `src/IO`.
|
||||
- **Epoll defects (D1)**
|
||||
- `complete_op_and_collect_tickets` releases the backend reference unconditionally (`EpollDriver.cpp:448`).
|
||||
- The cancel path does not skip operations that already finished (`:1332-1351`).
|
||||
- `drive_read`/`drive_write` call `::read` on `op->read_ptr` outside `mu_`, without marking the operation as executing (`:1462-1474`). `in_execution` is used only by the mock (`:653-671`).
|
||||
- Cross-thread `EpollBackend::shutdown_and_join` finishes unretired operations and closes their fds (`:1179-1238`, close at `:1221`).
|
||||
- Result: a stop arriving just after completion can double-release the reference, and shutdown racing a concurrent poller risks use-after-free or fd reuse. No test covers this; `io_epoll_cross_thread_wake_poll_and_stop_tsan` (`tests/standalone/IO/IoDriver.cpp:458-508`) stops the poller before teardown.
|
||||
- **Host**
|
||||
- Movable and returned by value, with `~Host() = default` (`Runtime/Host.hpp:88-94`).
|
||||
- Header-only (`src/Runtime/` holds only `module.cmake`).
|
||||
- `started_workers_` is always 0 (`:173`).
|
||||
- **Retry consumers:** ResilienceAsync uses `Void::Retry::ExponentialBackoff` and `JitterMode` (`Resilience/AsyncPolicy.hpp:6,486,533`), so these must stay source-compatible. Its `wait_with_stop` really sleeps in 5 ms slices while reading the injected clock (`:553-575`). That is out of scope and nothing here builds on it.
|
||||
|
||||
---
|
||||
|
||||
## 1. Per-task plans
|
||||
|
||||
### M-FUNCTIONAL-03: pure retry decisions and a named blocking adapter (sol → sonnet)
|
||||
|
||||
**Baseline**
|
||||
- `Functional/Retry.hpp` holds:
|
||||
- backoff types in milliseconds (`:18-68`)
|
||||
- `Jittered`, which uses a `thread_local mt19937_64` seeded from `random_device`, so results are not reproducible (`:76-95`)
|
||||
- `Policy{max_attempts=3, max_elapsed=0 meaning unlimited}` (`:100-110`)
|
||||
- `backoff_sleep`, hard-wired to `steady_clock::now()` and `sleep_for` (`:117-142`)
|
||||
- `retry`/`retry_while`, which start from a default-constructed result (`:156,197`). With `max_attempts == 0` they return a default-constructed `expected`, i.e. a success, without ever calling `fn` (`:150-170,190-211`).
|
||||
- `src/Functional/module.cmake` declares no dependencies.
|
||||
- Existing tests: `Retry.cpp` (14 tests) and `RetryJitter.cpp` (4 tests).
|
||||
|
||||
**Gap:** no pure decision engine, no injected time or URBG, no validation or saturation, no explicit `no_deadline`, zero attempts can succeed, and the blocking path is unnamed.
|
||||
|
||||
**Minimal scope**
|
||||
- A standard-library-only `RetryState`.
|
||||
- A `retry_blocking` that takes injected `now` and `sleep` callables. Using callables means no Time dependency (D-W11-02).
|
||||
- Every 1.x symbol keeps its behavior.
|
||||
|
||||
**NEW: `include/Void/Functional/RetryState.hpp`** (no `<thread>`, no Void includes). The 1.x `JitterMode` definition moves here, keeping its name and namespace.
|
||||
|
||||
```cpp
|
||||
namespace Void::Retry {
|
||||
using SteadyTimePoint = std::chrono::steady_clock::time_point;
|
||||
enum class JitterMode { Full, Equal }; // EXISTING, relocated
|
||||
struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; };
|
||||
inline constexpr NoDeadline no_deadline{};
|
||||
struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
|
||||
std::chrono::nanoseconds cap{std::chrono::seconds{30}};
|
||||
double multiplier{2.0}; std::optional<JitterMode> jitter{}; };
|
||||
struct RetrySpec { std::uint32_t max_attempts{3}; // total incl. first
|
||||
std::variant<std::chrono::nanoseconds, NoDeadline> budget{std::chrono::seconds{30}};
|
||||
BackoffSpec backoff{}; };
|
||||
enum class RetryConfigError : std::uint8_t { zero_attempts, negative_duration, zero_budget,
|
||||
nonfinite_multiplier, multiplier_below_one, cap_below_initial };
|
||||
enum class RetryAction : std::uint8_t { attempt, wait_until, stop };
|
||||
enum class RetryStopReason : std::uint8_t { none, succeeded, attempts_exhausted, deadline_exceeded,
|
||||
not_retryable, stop_requested };
|
||||
enum class AttemptOutcome : std::uint8_t { retryable_failure, permanent_failure };
|
||||
struct RetryDecision { RetryAction action{RetryAction::stop}; SteadyTimePoint at{};
|
||||
RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; };
|
||||
[[nodiscard]] std::expected<void, RetryConfigError> validate(const RetrySpec&) noexcept;
|
||||
[[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept; // saturating, unjittered
|
||||
[[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept;
|
||||
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
|
||||
class RetryState {
|
||||
public:
|
||||
[[nodiscard]] static std::expected<RetryState, RetryConfigError>
|
||||
create(const RetrySpec&, SteadyTimePoint start, URBG urbg = URBG{},
|
||||
std::optional<SteadyTimePoint> admission_deadline = std::nullopt); // deadline = min(start+budget, admission)
|
||||
[[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||||
[[nodiscard]] RetryDecision succeed() noexcept;
|
||||
[[nodiscard]] std::uint32_t attempts_started() const noexcept;
|
||||
[[nodiscard]] std::optional<SteadyTimePoint> deadline() const noexcept;
|
||||
};
|
||||
template <class E> struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0};
|
||||
std::optional<E> last_error{}; // empty iff no attempt ran
|
||||
std::optional<RetryConfigError> config{}; };
|
||||
struct RetryEveryError { template <class E> constexpr AttemptOutcome operator()(const E&) const noexcept
|
||||
{ return AttemptOutcome::retryable_failure; } };
|
||||
}
|
||||
```
|
||||
|
||||
**Fixed semantics**
|
||||
- `begin` returns `stop` for a stop request or `now >= deadline`; otherwise `attempt`.
|
||||
- `next` checks, in order:
|
||||
1. permanent failure → `not_retryable`
|
||||
2. `attempts == max` → `attempts_exhausted`
|
||||
3. stop requested → `stop_requested`
|
||||
4. Otherwise it computes `at = saturating_add(now, jitter(backoff_delay(k)))`. If `at >= deadline` it returns `deadline_exceeded`; else `wait_until(at)`.
|
||||
- `next` never returns `attempt` directly. `resume` re-checks stop and deadline and then returns `attempt`.
|
||||
- Full jitter draws uniformly from [0, d] ns. Equal jitter is d/2 plus a uniform draw from [0, d − d/2].
|
||||
- Backoff saturates at `cap` before conversion. Negative or non-finite inputs and `multiplier < 1` fail `create`.
|
||||
|
||||
**EDIT: `include/Void/Functional/Retry.hpp`** (add the include and these declarations; leave every 1.x body untouched)
|
||||
|
||||
```cpp
|
||||
struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } };
|
||||
struct ThreadSleep{ bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // cv_any+stop; false if stopped
|
||||
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep, class Classify = RetryEveryError,
|
||||
class URBG = std::mt19937_64>
|
||||
struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg{};
|
||||
std::stop_token stop{}; std::optional<SteadyTimePoint> deadline{}; };
|
||||
template <class F, class NowFn, class SleepFn, class Classify, class URBG> // F() -> std::expected<T,E>
|
||||
[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn, BlockingRetryOptions<NowFn,SleepFn,Classify,URBG> = {})
|
||||
-> std::expected<T, RetryError<E>>;
|
||||
```
|
||||
|
||||
- Waits are always `decision.at - options.now()`, measured in the injected domain. The adapter never calls `sleep_until(at)`.
|
||||
|
||||
**Unchanged 1.x:** `NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`, `Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`. The zero-attempt defect stays as it is (D-W11-03).
|
||||
|
||||
**Tests**
|
||||
- **NEW `tests/standalone/Functional/RetryState.cpp`:**
|
||||
- `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`)
|
||||
- `retry_state_exact_three_attempts_default`
|
||||
- `retry_state_deadline_at_admission_prevents_first_attempt`
|
||||
- `retry_state_backoff_overshooting_deadline_stops`
|
||||
- `retry_state_no_deadline_explicit_marker`
|
||||
- `retry_state_backoff_saturates_without_overflow` (multiplier 1e300, initial near max)
|
||||
- `retry_state_full_equal_jitter_bounds_and_seed_reproducibility` (bounds and same-seed equality only; no exact draws)
|
||||
- `retry_state_stop_prevents_next_attempt`
|
||||
- `retry_state_permanent_failure_stops`
|
||||
- `retry_state_saturating_add_near_max`
|
||||
- **NEW `tests/standalone/Functional/RetryBlocking.cpp`.** It uses a fake clock struct local to the test, with no Time include.
|
||||
- `retry_blocking_fake_clock_exact_waits_and_attempts` (zero real sleeps; recorded waits equal the backoff)
|
||||
- `retry_blocking_zero_attempts_config_error_no_call`
|
||||
- `retry_blocking_expired_deadline_no_call_no_success`
|
||||
- `retry_blocking_last_error_and_attempt_count`
|
||||
- `retry_blocking_stop_during_sleep_no_extra_attempt`
|
||||
- `retry_blocking_permanent_failure_single_attempt`
|
||||
- `retry_blocking_move_only_value`
|
||||
- `legacy_retry_zero_attempts_behavior_pinned`
|
||||
- Existing `Retry`, `RetryJitter` and `AsyncPolicy` tests must keep passing.
|
||||
|
||||
**Commands**
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^AsyncPolicy\."'
|
||||
rg -n "#include <thread>|Void/Time" include/Void/Functional/RetryState.hpp # expect no output
|
||||
```
|
||||
|
||||
### M-TIME-03: injected-deadline domains with Async and blocking retry adapters (astra → opus)
|
||||
|
||||
**Baseline**
|
||||
- Time: `ManualClock` starts at epoch 0 (`Time/Clock.hpp:69-130`); `remaining_until` is at `:188-208`; `src/Time/module.cmake` has no dependencies.
|
||||
- Async: `is_deadline_expired(options, clock = System)` (`Async/Detail/Types.hpp:49-55`) and `OperationState::is_deadline_expired` (`Operation.hpp:160-165`) default to the host clock. `ScheduleStatusAwaiter` checks the deadline only in `await_ready`/`await_resume` and never wakes on expiry (`Executor.hpp:304-359`). `include/Void/Async` has no timer.
|
||||
- IO already expires operations via the injected `clock_` on poll (`EpollDriver.cpp:739-834,1395-1443`), covered by `io_mock_stop_completion_races_and_clock_timeout`.
|
||||
|
||||
**Gap:** no awaitable timed wait that expires only through explicit polling, no Async retry adapter, and no conformance tests that manual-domain deadlines are never compared with the host clock.
|
||||
|
||||
**Minimal scope:**
|
||||
- An Async `TimerQueue` (a stable min-heap ordered by `(deadline, seq)`).
|
||||
- `Async::retry_async` built on `RetryState`.
|
||||
- Time saturation helpers.
|
||||
- Cross-adapter conformance tests.
|
||||
|
||||
**NEW: `include/Void/Async/Timer.hpp`**
|
||||
```cpp
|
||||
namespace Void::Async {
|
||||
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 invalid
|
||||
using TimerCallback = std::move_only_function<void() noexcept>;
|
||||
class TimerHandle { public: bool cancel() noexcept; /* move-only; true => callback never runs */ };
|
||||
class TimerQueue { // non-movable
|
||||
public:
|
||||
using time_point = Void::Time::MonotonicClock::time_point;
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
|
||||
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
|
||||
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_expire);
|
||||
[[nodiscard]] std::size_t poll_expired(); // fires due timers once, (deadline,seq) order, outside locks
|
||||
[[nodiscard]] std::optional<time_point> next_deadline() const;
|
||||
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept;
|
||||
[[nodiscard]] std::size_t active_timers() const noexcept;
|
||||
void close() noexcept; // pending -> stopped; new -> stopped
|
||||
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
|
||||
[[nodiscard]] Executor& executor() noexcept;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Fixed semantics for `sleep_until`**
|
||||
- Results: `{}` when `when` is reached and polled; `cancelled` on stop; `timeout` if `options.deadline` comes first; `overloaded` at `max_timers`; `stopped` after `close`.
|
||||
- Stop or expiry settles through `OperationState`, and the continuation is dispatched through `post_completion`. A stop callback never resumes inline.
|
||||
- Cancelled timers are tombstoned, and the heap is compacted so it never exceeds 2 × `max_timers`.
|
||||
- Destroying the queue settles pending sleeps with `stopped`. The executor must outlive the queue.
|
||||
|
||||
**NEW: `include/Void/Async/Retry.hpp`** (needs gate G1, i.e. A1 integrated)
|
||||
```cpp
|
||||
template <class F, class Classify = Void::Retry::RetryEveryError, class URBG = std::mt19937_64>
|
||||
[[nodiscard]] auto retry_async(Void::Retry::RetrySpec, F fn /* ()->expected<T,E> | Task<expected<T,E>> */,
|
||||
TimerQueue& timers, OperationOptions = {}, Classify = {}, URBG = URBG{})
|
||||
-> Coro::Task<std::expected<T, Void::Retry::RetryError<E>>>;
|
||||
```
|
||||
- "Now" comes from `timers.clock()`. The admission deadline is `options.deadline`.
|
||||
- If an attempt succeeds after stop was requested, the success is returned. After stop, nothing is retried.
|
||||
|
||||
**EDIT: `include/Void/Time/Clock.hpp`** (NEW helpers)
|
||||
```cpp
|
||||
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
|
||||
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
|
||||
```
|
||||
|
||||
**Unchanged:** every existing Time and Async symbol, including the default-argument clock parameters.
|
||||
|
||||
**Tests**
|
||||
- **NEW `tests/standalone/Async/TimerQueue.cpp`:**
|
||||
- `timer_manual_advance_and_poll_fires_exactly_once`
|
||||
- `timer_equal_deadlines_fire_in_submission_order`
|
||||
- `timer_not_fired_without_explicit_poll`
|
||||
- `timer_manual_epoch_deadline_not_compared_with_host_clock`
|
||||
- `timer_manual_clock_far_future_initial_point`
|
||||
- `timer_stop_before_admission_and_pending_cancelled_once`
|
||||
- `timer_stop_vs_poll_race_single_result_tsan`
|
||||
- `timer_capacity_overloaded_and_tombstone_bounded`
|
||||
- `timer_schedule_at_cancel_vs_fire_exclusive`
|
||||
- `timer_close_settles_pending_stopped`
|
||||
- `timer_wait_duration_uses_injected_now`
|
||||
- `timer_sleep_for_saturates`
|
||||
- **NEW `tests/standalone/Async/AsyncRetry.cpp`:**
|
||||
- `async_retry_manual_clock_attempts_only_after_advance_and_poll`
|
||||
- `async_retry_total_deadline_expires_once`
|
||||
- `async_retry_stop_during_backoff_no_further_attempt`
|
||||
- `async_retry_success_after_stop_preserved`
|
||||
- `async_retry_zero_attempts_no_call`
|
||||
- `async_retry_task_returning_callable`
|
||||
- **NEW `tests/standalone/Async/DeadlineDomains.cpp`:**
|
||||
- `deadline_domain_blocking_retry_manual_clock` (`now = manual.now`; the sleep callable advances the manual clock)
|
||||
- `deadline_domain_schedule_on_and_scope_admission_injected_clock`
|
||||
- **NEW `tests/standalone/Time/ClockSaturation.cpp`:** `clock_saturating_add_and_deadline_after_bounds`.
|
||||
|
||||
**Commands**
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains)\."'
|
||||
```
|
||||
|
||||
### M-ASYNC-04: bounded executors, cancellable channels, future pool adapter, ParallelFor (sol → sonnet)
|
||||
|
||||
**Baseline**
|
||||
- `Executor` base: `try_post`, `post_completion` and the reservation API (`Executor.hpp:58-113`). `ManualExecutor`'s bound excludes running work (`:226-228`). No threaded executor exists.
|
||||
- `Concurrency::ThreadPool` (`ThreadPool.hpp:20-187`):
|
||||
- `max_queue == 0` means unbounded (`:33-38`).
|
||||
- Its bound counts only the queue, because a task is popped before it runs (`:164-173`).
|
||||
- `submit` throws after stop (`:85-89`).
|
||||
- `try_submit` returns `nullopt` for both "full" and "stopped" (`:100-120`).
|
||||
- It includes Log (`:2`).
|
||||
- `Concurrency::Channel` (`Channel.hpp:13-116`): blocking only; `send(T)` consumes the value even when the channel is closed (`:24-35`); capacity 0 blocks forever (`:27-28`).
|
||||
- `parallel_for` (`ParallelFor.hpp:12-26`) creates one future per index, so submission is unbounded. On the first throwing `fut.get()` it returns without joining the remaining tasks.
|
||||
|
||||
**Gap:** no bound that includes running work, no coroutine channel, no explicit future adapter, and chunk errors don't join.
|
||||
|
||||
**Minimal scope:** NEW `ThreadExecutor`, `FuturePool`, `AsyncChannel`, and a bounded `parallel_for` overload. Capacity-waiting (`async_wait_for_capacity`) and the 4 MiB channel byte budget are deferred (D-W11-13).
|
||||
|
||||
**NEW: `include/Void/Async/ThreadExecutor.hpp`**
|
||||
```cpp
|
||||
namespace Void::Async {
|
||||
struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096}; // queued+running; >=1
|
||||
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{}; }; // fault-injection hook
|
||||
struct ThreadExecutorStats { std::size_t queued, running, completion_queued; std::uint64_t rejected, legacy_posts, inline_after_join; };
|
||||
class ThreadExecutor final : public Executor {
|
||||
public:
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {}); // no threads
|
||||
[[nodiscard]] Void::Result::Result<void> start(); // once; partial failure joins started workers
|
||||
void post(std::coroutine_handle<>) override; // never rejects; counted; may exceed bound (legacy)
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override; // overloaded if queued+running>=max
|
||||
void post_completion(std::coroutine_handle<>) override; // reserved lane; drains after close(); prioritized
|
||||
[[nodiscard]] bool supports_reservation() const noexcept override; // true
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
|
||||
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
|
||||
[[nodiscard]] bool has_background_workers() const noexcept override; // true
|
||||
void close() noexcept; // normal admission -> stopped
|
||||
[[nodiscard]] Void::Result::Result<void> join(); // close+drain+join; self_join on worker
|
||||
[[nodiscard]] std::size_t admitted() const noexcept; [[nodiscard]] ThreadExecutorStats stats() const noexcept;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Mandatory for `ThreadExecutor`**
|
||||
- Every resume runs inside `detail::ExecutorThreadGuard`; that is what `is_executor_thread` and self-join detection rely on.
|
||||
- A slot is released only after the resumed handle returns.
|
||||
- After `join`, `post` and `post_completion` resume inline on the caller (documented and counted). A handle is never dropped.
|
||||
|
||||
**NEW: `include/Void/Async/FuturePool.hpp`**
|
||||
```cpp
|
||||
class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept;
|
||||
template <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
|
||||
try_submit(F&& f); }; // reserve-then-transfer: f not moved on rejection; exceptions -> future
|
||||
```
|
||||
|
||||
**NEW: `include/Void/Async/AsyncChannel.hpp`**
|
||||
```cpp
|
||||
enum class ChannelError : std::uint8_t { closed, empty, full, cancelled, timed_out, overloaded, invalid_argument };
|
||||
struct ChannelOptions { std::size_t capacity{1024}; std::size_t max_waiters{1024}; TimerQueue* timers{nullptr}; };
|
||||
template <class T> struct SendFailure { ChannelError error; T value; };
|
||||
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
|
||||
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
|
||||
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
|
||||
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
|
||||
[[nodiscard]] std::expected<T, ChannelError> try_receive();
|
||||
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
|
||||
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
|
||||
[[nodiscard]] Void::Result::Error make_async_error(ChannelError, std::string message = {});
|
||||
```
|
||||
- A wait with a deadline but no `timers` returns `invalid_argument`.
|
||||
- `close()` hands waiting senders `closed` together with their value. Receivers drain the buffer in FIFO order, then get `closed`.
|
||||
- Resumption always goes through `post_completion`, outside locks.
|
||||
- The deadline part depends on gate G2.
|
||||
|
||||
**EDIT: `include/Void/Async/ParallelFor.hpp`**
|
||||
```cpp
|
||||
struct ParallelForOptions { std::size_t grain{1}; std::size_t max_concurrency{0}; std::stop_token stop{}; bool stop_on_error{true}; };
|
||||
struct ParallelForError { enum class Kind : std::uint8_t { invalid_argument, rejected, stopped, failed } kind;
|
||||
std::size_t chunks_total{0}, chunks_started{0}, chunks_failed{0};
|
||||
std::optional<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
|
||||
template <std::integral I, std::invocable<I> F>
|
||||
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
|
||||
```
|
||||
- `max_concurrency == 0` means the pool's thread count.
|
||||
- Runner tasks are submitted with `try_submit`; if rejected, the caller thread runs chunks itself.
|
||||
- No new chunk starts after a stop or (with `stop_on_error`) an error.
|
||||
- All started runners are always joined. The reported error is the lowest-indexed failed chunk.
|
||||
- D-W11-10: the 1.x overload should wait for all futures before rethrowing.
|
||||
|
||||
**Root pre-commit:** `AsyncErrorCode::closed = 9`, mapped to `ErrorKind::cancelled`.
|
||||
|
||||
**Unchanged:** `ManualExecutor`, `Concurrency::{ThreadPool, Channel}`, the existing `parallel_for` signatures, `spawn`, `schedule_on`.
|
||||
|
||||
**Tests (NEW, `tests/standalone/Async/`)**
|
||||
- **`ThreadExecutor.cpp`:**
|
||||
- `thread_executor_create_starts_no_threads`
|
||||
- `thread_executor_bound_includes_running_work` (1 worker, max 2: blocker running plus 1 queued → `overloaded`; release → accepted)
|
||||
- `thread_executor_reservation_with_task_scope_preserves_task`
|
||||
- `thread_executor_completion_lane_bypasses_full_normal_lane`
|
||||
- `thread_executor_close_rejects_normal_drains_completion`
|
||||
- `thread_executor_join_self_join_on_worker`
|
||||
- `thread_executor_partial_start_failure_joins_started`
|
||||
- `thread_executor_legacy_post_spawn_schedule_on_compat`
|
||||
- `thread_executor_stress_tsan`
|
||||
- **`FuturePool.cpp`:**
|
||||
- `future_pool_overloaded_does_not_consume_callable`
|
||||
- `future_pool_stopped_after_close`
|
||||
- `future_pool_exception_in_future`
|
||||
- `future_pool_bound_includes_running`
|
||||
- **`AsyncChannel.cpp`:**
|
||||
- `channel_zero_capacity_invalid`
|
||||
- `channel_try_send_full_returns_value`
|
||||
- `channel_send_waits_resumes_on_receive`
|
||||
- `channel_producer_stop_returns_value_cancelled_once`
|
||||
- `channel_close_wakes_senders_with_value_and_drains_receivers`
|
||||
- `channel_deadline_requires_timers`
|
||||
- `channel_deadline_times_out_once_manual_clock_poll`
|
||||
- `channel_waiter_bound_overloaded`
|
||||
- `channel_move_only_values`
|
||||
- `channel_mpmc_fifo_tsan`
|
||||
- `channel_stop_vs_send_race_single_outcome_tsan`
|
||||
- **`ParallelForBounded.cpp`:**
|
||||
- `parallel_for_bounded_grain_and_concurrency_limit`
|
||||
- `parallel_for_bounded_stop_joins_started_no_new_chunks`
|
||||
- `parallel_for_bounded_errors_join_all_lowest_index_reported`
|
||||
- `parallel_for_bounded_zero_grain_invalid`
|
||||
- `parallel_for_bounded_rejected_pool_runs_inline`
|
||||
- `legacy_parallel_for_exception_joins_all` (only if D-W11-10 is approved)
|
||||
|
||||
**Commands** (for each tag, `-Werror` on the default build, plus Debug TSan and ASan+UBSan build dirs)
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-async4 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-tsan && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-asan && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
|
||||
```
|
||||
|
||||
### M-ASYNC-05: EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling (sol → sonnet)
|
||||
|
||||
**Baseline**
|
||||
- `EventBus` (`EventBus.hpp:37-284`):
|
||||
- Sync `publish` iterates the live vector without the lock (`:156-164`). A handler that subscribes or unsubscribes during dispatch therefore causes undefined behavior.
|
||||
- Async mode starts a private thread in the constructor (`:43-48`).
|
||||
- The snapshot copies `std::function`s, so `unsubscribe` cannot retract queued copies (`:167-169`).
|
||||
- A handler exception escapes the worker loop, which terminates the process (`:248-269`).
|
||||
- The task queue and handler list are unbounded (`:272-278`).
|
||||
- `Subscription::reset` doesn't join (`:115-121`).
|
||||
- `Observable` and `Signal` iterate the live vectors (`Observable.hpp:74-77,116-119`); reentrant use is undefined behavior, and there is no threading policy.
|
||||
- Existing tests: `EventBus.cpp` (12), `EventBusAsync.cpp` (4), `Observable.cpp` (14).
|
||||
|
||||
**Gap:** per the row.
|
||||
|
||||
**Minimal scope:**
|
||||
- Subscription state held in `shared_ptr`, with snapshot dispatch gated per entry.
|
||||
- A new injected-executor mode.
|
||||
- Joins per subscription and per bus.
|
||||
- Bounded nested Observable notifications.
|
||||
|
||||
**NEW (EDIT `EventBus.hpp`)**
|
||||
```cpp
|
||||
namespace Void::EventBus {
|
||||
enum class Mode { Sync, Async, Injected }; // NEW enumerator
|
||||
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
|
||||
std::function<void(std::exception_ptr)> error_sink{}; }; // outside locks
|
||||
class EventBus { // EXISTING API unchanged, plus:
|
||||
explicit EventBus(Void::Async::Executor& executor, BusOptions = {}); // no private thread; internal TaskScope
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
|
||||
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
|
||||
class Subscription { /* EXISTING */ public: [[nodiscard]] Void::Result::Result<void> close_and_join(); };
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Semantics (D-W11-06)**
|
||||
- 1.x `unsubscribe` stops future publishes from including the handler. In `Mode::Async` it still delivers already-queued copies, as 1.x does.
|
||||
- NEW `Subscription::close_and_join` also suppresses admitted deliveries that have not started. It then waits for in-flight callbacks and resets the handler (releasing captured state) before returning.
|
||||
- Calling it from the subscription's own callback returns `self_join`. Self-unsubscribe is supported.
|
||||
- Callbacks run outside locks. Injected and Async modes catch callback exceptions and route them to `error_sink`, counting them. Sync `publish` still propagates exceptions as in 1.x.
|
||||
|
||||
**NEW (EDIT `Observable.hpp`)**
|
||||
- Documented policy: single-threaded, not thread-safe, safe for reentrancy.
|
||||
- `inline constexpr std::size_t kMaxPendingNotifications = 1024;`
|
||||
- `Observable::try_set(T) -> Result<void>` returns `overloaded` and leaves the value unchanged.
|
||||
- `dropped_notifications()`.
|
||||
- A nested `set` updates the value immediately and queues `(old, new)` copies, delivered in FIFO order after the current pass.
|
||||
- Unsubscribe during a pass skips that listener for the rest of the pass. Subscribing during a pass doesn't add the listener to the current pass.
|
||||
- A throwing listener: its exception propagates out of the outermost `set`/`emit`, after state is restored, and queued notifications are dropped and counted.
|
||||
- `Signal::emit` uses the same snapshot rules.
|
||||
|
||||
**Tests (NEW)**
|
||||
- **`tests/standalone/Async/EventBusJoin.cpp`:**
|
||||
- `bus_injected_no_private_thread_manual_pumping`
|
||||
- `bus_injected_subscription_limit_overloaded`
|
||||
- `bus_injected_dispatch_limit_overloaded`
|
||||
- `bus_close_and_join_waits_inflight_releases_capture_tsan` (sentinel `use_count == 1` after join)
|
||||
- `bus_unsubscribe_during_dispatch_prevents_later_admission`
|
||||
- `bus_self_unsubscribe_ok_self_join_rejected`
|
||||
- `bus_callback_throw_to_error_sink_others_run`
|
||||
- `bus_legacy_async_unsubscribe_keeps_queued_copy` (pins 1.x)
|
||||
- `bus_sync_reentrant_subscribe_unsubscribe_asan`
|
||||
- `bus_publish_after_close_closed`
|
||||
- **`tests/standalone/Async/ObservableReentrancy.cpp`:**
|
||||
- `observable_nested_set_fifo`
|
||||
- `observable_unsubscribe_in_listener_skips_rest`
|
||||
- `observable_subscribe_in_listener_not_current_pass`
|
||||
- `observable_try_set_overloaded_when_pending_full`
|
||||
- `observable_listener_throw_restores_state`
|
||||
- `observable_self_unsubscribe_releases_capture`
|
||||
- `signal_reentrant_connect_disconnect_during_emit`
|
||||
|
||||
**Commands:** same form as M-ASYNC-04 with `--filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."`, plus TSan and ASan dirs `/tmp/void-w11-async5{,-tsan,-asan}`.
|
||||
|
||||
### S-IO-03: bounded positional file workers, serialization, sync, active-cancel (astra → opus)
|
||||
|
||||
**Baseline:** see §0, including the D1 defects; there is no pread, pwrite or fsync anywhere in `src/IO`. `validate_limits` ignores the file fields (`IO/Types.hpp:110-122`).
|
||||
|
||||
**Gap:** the whole file path, plus a shutdown that joins workers safely.
|
||||
|
||||
**Minimal scope:**
|
||||
- A file worker pool in a NEW translation unit, shared by the mock and epoll backends through `BaseBackend`.
|
||||
- An injectable syscall shim.
|
||||
- Explicit worker start.
|
||||
- The D1 correctness fixes.
|
||||
|
||||
**NEW: `include/Void/IO/File.hpp`**
|
||||
```cpp
|
||||
namespace Void::IO {
|
||||
struct FileOpenOptions { bool read{true}, write{false}, create{false}, truncate{false}, exclusive{false}; std::uint32_t mode{0600}; };
|
||||
enum class SyncMode : std::uint8_t { data, full };
|
||||
struct FileSyscallResult { std::int64_t value{0}; int error{0}; };
|
||||
class FileSyscalls { public: virtual ~FileSyscalls() = default;
|
||||
[[nodiscard]] virtual FileSyscallResult pread(int, std::span<std::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult pwrite(int, std::span<const std::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult sync(int, SyncMode) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult close(int) noexcept;
|
||||
[[nodiscard]] static FileSyscalls& native() noexcept; };
|
||||
class File { public: /* move-only */ [[nodiscard]] bool valid() const noexcept; [[nodiscard]] DescriptorId id() const noexcept;
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(SyncMode = SyncMode::full, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(Async::OperationOptions = {}); };
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> read_exact_at(File&, std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> write_all_at(File&, std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
}
|
||||
```
|
||||
|
||||
**EDITs**
|
||||
- `Driver.hpp` gains:
|
||||
- `Result<File> open_file(const std::filesystem::path&, FileOpenOptions = {})`
|
||||
- `Result<File> adopt_file_fd(int)`
|
||||
- `Result<void> start_file_workers()` (explicit, once; D-W11-11)
|
||||
- `Result<std::size_t> run_file_work(std::size_t max_requests = 1)` (manual stepping when no workers are running)
|
||||
- `Types.hpp`:
|
||||
- `BackendOptions::file_syscalls{nullptr}` (appended; borrowed)
|
||||
- `DriverTelemetry` gains `queued_file_requests`, `active_file_requests`, `file_workers_running` (appended)
|
||||
- `validate_limits` rejects `max_file_queue == 0`
|
||||
- Root pre-commit: `IoErrorCode::sync_failed = 12`, mapped to `ErrorKind::io`
|
||||
- `Detail/Backend.hpp` gains file submit virtuals.
|
||||
- `EpollDriver.cpp` integrates the pool and the shutdown changes.
|
||||
- NEW `src/IO/FileWorkers.{hpp,cpp}`; the `.hpp` is private and not globbed.
|
||||
|
||||
**Fixed semantics**
|
||||
- **Admission:** a stopped or expired request, or a closed driver, is rejected before it is queued. `max_file_queue` counts queued requests; `max_operations` counts queued and active. Either limit returns `overloaded`. A zero-length request returns `{0, false}`. Offset plus length overflowing gives `invalid_argument`.
|
||||
- **Ordering:** writes and syncs on one file run in admission order, at most one active at a time. Reads may run concurrently. Each request is exactly one syscall, with EINTR retried. A short transfer returns the bytes actually moved; a 0-byte read of a nonzero length means EOF.
|
||||
- **Queued stop or expiry:** the request is removed and completes `cancelled` or `timeout`. Writes and syncs carry `DomainOutcomeKind::not_committed`. Expiry is checked by the driver clock in `poll_once` and again at worker dequeue.
|
||||
- **Active stop or expiry:** recorded as intent only. The span or lease and the telemetry stay retained, and the result is the syscall's actual outcome. A sync that succeeds after a stop is a success. A sync that fails returns `sync_failed` with the native errno and `DomainOutcomeKind::unknown`.
|
||||
- **`shutdown_and_join`** keeps its 1.x signature with extended behavior:
|
||||
1. Close admission.
|
||||
2. Cancel queued socket and file operations.
|
||||
3. Wait for in-flight syscalls and for any concurrent `poll_once` turn (poll-owner exclusion).
|
||||
4. Join the workers.
|
||||
5. Only then close the fds, epoll and eventfd.
|
||||
Called from a worker, or from inside poll dispatch, it returns `Async::make_async_error(AdmissionError::self_join)`.
|
||||
- **D1 fixes (mandatory):**
|
||||
- Release the backend reference only if this call retired the operation.
|
||||
- The cancel and expire paths skip retired operations.
|
||||
- Epoll marks an operation `in_execution` under `mu_` before its syscall.
|
||||
|
||||
**Tests: NEW `tests/standalone/IO/IoFile.cpp`**
|
||||
- `io_file_native_roundtrip_isolated_tmpdir`
|
||||
- `io_file_short_write_preserves_progress_write_all_at`
|
||||
- `io_file_writes_syncs_serialized_admission_order`
|
||||
- `io_file_reads_concurrent_explicit_offsets`
|
||||
- `io_file_queue_and_ops_quota_overloaded`
|
||||
- `io_file_queued_cancel_not_committed_zero_effects`
|
||||
- `io_file_queued_deadline_expires_once_manual_clock_poll`
|
||||
- `io_file_active_timeout_retains_buffer_until_syscall_returns`
|
||||
- `io_file_sync_success_after_stop_is_success`
|
||||
- `io_file_sync_failure_after_stop_sync_failed_unknown_errno`
|
||||
- `io_file_manual_stepping_without_workers`
|
||||
- `io_file_shutdown_joins_stalled_worker_then_delivers`
|
||||
- `io_file_shutdown_from_worker_self_join`
|
||||
- `io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan`
|
||||
- `io_stop_after_completion_releases_backend_ref_once`
|
||||
|
||||
**Commands**
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3 -G Ninja -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3 && /tmp/void-w11-io3/tests/VoidTests --filter "^(IoFile|IoDriver)\." && ctest --test-dir /tmp/void-w11-io3 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-tsan && /tmp/void-w11-io3-tsan/tests/VoidTests --filter "^(IoFile|IoDriver)\."'
|
||||
# also an ASan+UBSan dir with the same filter, plus downstream IO users unfiltered:
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-users -G Ninja -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-users && /tmp/void-w11-io3-users/tests/VoidTests && ctest --test-dir /tmp/void-w11-io3-users --output-on-failure --timeout 120'
|
||||
```
|
||||
|
||||
### S-IO-04: embedded pumping, joined shutdown, optional adapters (sol → sonnet)
|
||||
|
||||
**Baseline**
|
||||
- The only driving entry points are `poll_once`, `wake` and `request_stop` (`Driver.hpp:91-96`).
|
||||
- Embedded pumping today is hand-written loops (`IoDriver.cpp:490-499`). `TaskScope::join_pumping` drains the executor but never polls IO (`TaskScope.hpp:645-654`).
|
||||
- System adapter already exists: SystemAsync `ProcessManager` borrows a `Driver` (`System/AsyncProcess.hpp:61`, `src/SystemAsync/AsyncProcess.cpp:434`).
|
||||
- Net does not use IO at all (rg finds no `Void/IO` in `include/Void/Net` or `src/Net`).
|
||||
|
||||
**Minimal scope:** a bounded or repeatable `shutdown`, a `run` loop, a `pump_until` helper, and a SystemAsync conformance test. The Net adapter is deferred (D-W11-07).
|
||||
|
||||
**NEW**
|
||||
```cpp
|
||||
namespace Void::IO {
|
||||
struct DriverShutdownReport { bool complete{false}; std::size_t pending_operations{0}, active_file_requests{0},
|
||||
open_descriptors{0}, retained_buffer_bytes{0}; }; // Types.hpp
|
||||
void Driver::begin_shutdown() noexcept; // idempotent, never frees
|
||||
[[nodiscard]] Void::Result::Result<DriverShutdownReport> Driver::shutdown(Async::OperationOptions); // bounded; repeatable
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
|
||||
[[nodiscard]] bool Driver::quiescent() const noexcept;
|
||||
struct PumpOptions { std::chrono::nanoseconds max_wait{0}; std::size_t max_turns{1u << 20};
|
||||
Async::OperationOptions operation{}; Async::TimerQueue* timers{nullptr}; }; // NEW Pump.hpp
|
||||
template <class Done> requires std::predicate<Done&>
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(Driver&, Async::ManualExecutor&, Done&&, PumpOptions = {});
|
||||
}
|
||||
```
|
||||
|
||||
**Fixed semantics**
|
||||
- `shutdown` evaluates its deadline and stop in `driver.clock()`.
|
||||
- When it expires it returns `complete = false` and retains everything: no fd is closed, no buffer is released, and the workers stay alive.
|
||||
- It never runs a poll turn while another thread is inside `poll_once`.
|
||||
- A misuse case such as self-join is returned as an error.
|
||||
- `pump_until` returns `timeout`, `cancelled` or `exhausted` and never frees work.
|
||||
|
||||
**Tests (NEW)**
|
||||
- **`tests/standalone/IO/IoShutdown.cpp`:**
|
||||
- `io_shutdown_expired_budget_incomplete_retains_stalled_file_worker`
|
||||
- `io_shutdown_pending_socket_read_retains_buffer_until_delivery`
|
||||
- `io_shutdown_repeated_idempotent_after_complete`
|
||||
- `io_shutdown_concurrent_with_run_loop_tsan`
|
||||
- `io_run_stops_on_token_and_on_shutdown`
|
||||
- `io_begin_shutdown_rejects_new_admission`
|
||||
- **`tests/standalone/IO/IoPump.cpp`:**
|
||||
- `io_pump_until_scope_join_mock`
|
||||
- `io_pump_until_deadline_injected_clock`
|
||||
- `io_pump_until_max_turns_exhausted`
|
||||
- `io_pump_until_drives_timer_queue`
|
||||
- **`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`:** `systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once`.
|
||||
|
||||
**Commands:** `-DVOID_ENABLED_MODULES="IO;SystemAsync;Testing"`, `--filter "^(IoShutdown|IoPump|IoFile|IoDriver|SystemAsyncShutdown|SystemAsync)\."`, with a `-Werror` dir and a TSan dir (`/tmp/void-w11-io4{,-tsan}`), plus `ctest` (IOOnly and SystemAsyncOnly).
|
||||
|
||||
### S-RUNTIME-02: explicit start, readiness, reverse failed-start cleanup (astra → opus)
|
||||
|
||||
**Baseline:**
|
||||
- `Host` is inert (`Host.hpp:85-178`).
|
||||
- Options: `Options.hpp:89-96`. `Options::file_workers` duplicates `IoLimits::file_workers` (`:91` vs `IO/Types.hpp:106`). Note the existing exemption quirk for 4096 timers (`:149`).
|
||||
- `ResourceKind` includes `service` and `exporter` (`ResourceGraph.hpp:23-31`).
|
||||
- Pinned by tests: `started_worker_count() == 0` after `create` (`RuntimeHost.cpp:77-79`), and inert `add_resource` nodes (`:134-138`).
|
||||
|
||||
**Gap:** everything about start. The executor and file-worker prerequisites come from the hidden edges in the summary.
|
||||
|
||||
**NEW: `include/Void/Runtime/Lifecycle.hpp`** (plus `Detail/HostCore.hpp`; stays header-only, D-W11-09)
|
||||
```cpp
|
||||
namespace Void::Runtime {
|
||||
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
|
||||
class SignalGate { public: virtual ~SignalGate() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> install() = 0; // owner thread, before any Runtime thread
|
||||
virtual void uninstall() noexcept = 0; }; // same thread, after all Runtime threads joined
|
||||
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
|
||||
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
|
||||
class Component { public: virtual ~Component() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0; // outside Host locks
|
||||
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
|
||||
struct StartOptions { SignalGate* signal_gate{nullptr};
|
||||
std::function<Void::Result::Result<void>(StartStep)> before_step{};
|
||||
std::function<void(ShutdownPhase)> on_phase{}; // used by S-RUNTIME-03
|
||||
std::chrono::milliseconds readiness_timeout{5000}; };
|
||||
}
|
||||
// Host (EDIT): all lifecycle state in std::unique_ptr<detail::HostCore>; Host stays movable.
|
||||
[[nodiscard]] Void::Result::Result<void> start(StartOptions = {}); // once: constructed->starting->running|failed_start
|
||||
[[nodiscard]] bool is_ready() const noexcept; [[nodiscard]] Async::Executor* executor() noexcept;
|
||||
[[nodiscard]] IO::Driver* io() noexcept; [[nodiscard]] std::optional<std::thread::id> owner_thread() const noexcept;
|
||||
[[nodiscard]] std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
|
||||
~Host(); // non-default: reverse teardown on allowed thread
|
||||
// HostBuilder (EDIT):
|
||||
[[nodiscard]] Void::Result::Result<void> add_component(std::string id, ResourceKind, std::shared_ptr<Component>,
|
||||
std::vector<std::string> deps = {}, bool critical = true);
|
||||
```
|
||||
|
||||
**Root pre-commit:** `RuntimeErrorCode::self_join = 8` (→ `conflict`) and `shutdown_incomplete = 9` (→ `timeout`).
|
||||
|
||||
**Fixed start algorithm.** Each step pushes a cleanup action. On failure, the cleanups are popped in reverse on the starting thread, the state becomes `failed_start`, and the error is returned wrapped with context, preserving the root `Status`.
|
||||
1. Validate `constructed`; record the owner thread.
|
||||
2. `signal_gate->install()`.
|
||||
3. Memory budget.
|
||||
4. `ThreadExecutor{cpu_workers, max_admitted = limits.max_cpu_tasks}` → `start()`.
|
||||
5. `IO::Driver::create`, with `io.limits.file_workers = Options::file_workers` (Runtime is authoritative).
|
||||
6. `start_file_workers()`.
|
||||
7. A Runtime-owned reactor thread looping `poll_once(5ms)`.
|
||||
8. Components in `plan_.startup_order`.
|
||||
9. Readiness: an executor `try_post` probe plus one reactor turn → `running`.
|
||||
|
||||
Embedded mode skips steps 4–7 (no threads). `started_worker_count()` reports the real CPU, reactor and file threads.
|
||||
|
||||
**Tests (NEW)**
|
||||
- **`tests/standalone/Runtime/RuntimeStart.cpp`:**
|
||||
- `runtime_start_spawns_workers_only_on_start_ready`
|
||||
- `runtime_start_twice_invalid_state`
|
||||
- `runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds` (loop over `StartStep`; `/proc/self/task` and `/proc/self/fd` deltas are 0; a fresh Host then starts)
|
||||
- `runtime_component_start_failure_unwinds_reverse`
|
||||
- `runtime_signal_gate_before_threads_uninstall_on_owner` (fake gate)
|
||||
- `runtime_embedded_start_no_threads`
|
||||
- `runtime_move_after_start_keeps_resources_valid`
|
||||
- **`tests/standalone/Runtime/RuntimeSignals.cpp`.** It includes `Void/System/SignalWatcher.hpp`, so it runs only when System is enabled. It uses a test-local adapter around `Process::SignalWatcher` and SIGUSR2.
|
||||
- `runtime_system_gate_mask_inherited_by_workers`
|
||||
- `runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`
|
||||
- `runtime_signal_during_start_stays_pending_and_is_drained`
|
||||
|
||||
**Commands**
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2 -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt2 && /tmp/void-w11-rt2/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt2 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON 2>&1 | grep "Skipping.*RuntimeSignals" && cmake --build /tmp/void-w11-rt2-nosys && ctest --test-dir /tmp/void-w11-rt2-nosys --output-on-failure --timeout 60'
|
||||
# plus Debug TSan and ASan+UBSan dirs with "^(RuntimeStart|RuntimeSignals)\."
|
||||
```
|
||||
|
||||
### S-RUNTIME-03: structured shutdown, repeated join, exporter-before-executor ordering, budget accounting (astra → opus)
|
||||
|
||||
**NEW**
|
||||
```cpp
|
||||
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
|
||||
stopping_components, flushing_exporters, stopping_io, stopping_workers, releasing, stopped };
|
||||
// ShutdownReport (EXISTING fields kept) + appended: phase, pending_business_tasks, pending_cpu_admitted,
|
||||
// pending_io_operations, retained_buffer_bytes, drain_grace_expired, export_flush_expired, owner_release_pending
|
||||
void Host::begin_shutdown() noexcept;
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::poll_shutdown(); // non-blocking step
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_blocking(Async::OperationOptions = {}); // repeatable
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {});
|
||||
[[nodiscard]] std::optional<ShutdownReport> Host::last_shutdown_report() const;
|
||||
```
|
||||
|
||||
**Fixed semantics**
|
||||
- **Total deadline:** fixed at the first `begin_shutdown`, as `min(caller deadline, deadline_after(clock, total_timeout))`.
|
||||
- **Phase deadlines:** drain = `min(total, phase start + drain_grace)`; flush = `min(total, phase start + export_flush_timeout)`.
|
||||
- **Phase order:**
|
||||
1. Close business scope admission.
|
||||
2. Drain.
|
||||
3. Request stop on the business scope.
|
||||
4. Join it.
|
||||
5. Stop non-exporter components (dependents first).
|
||||
6. Stop exporters with the flush deadline. On expiry, request stop and set `export_flush_expired`, but keep IO, the reactor and the workers alive.
|
||||
7. `driver->shutdown(remaining)`; if incomplete, retain it.
|
||||
8. Stop and join the reactor, then `ThreadExecutor::join()`.
|
||||
9. Drop component references, so exporters are destroyed before the executor is torn down.
|
||||
10. Release budgets and fds. Signal-gate uninstall happens on the owner thread only; otherwise `owner_release_pending` is set and the next owner-thread call or `~Host` performs it.
|
||||
- **Mandatory mechanics:**
|
||||
- Component `stop` tasks are launched through `post_completion`, never through normal-lane admission, so a full queue cannot block them.
|
||||
- Expiry of the total budget returns `complete = false` and state `shutdown_incomplete`, retaining all resources. The next call continues from there.
|
||||
- Concurrent callers get the same final report, and there is exactly one teardown.
|
||||
- Calling `shutdown_blocking` on a Runtime worker returns `RuntimeErrorCode::self_join`.
|
||||
- Calling it from a non-owner thread completes every phase except the signal-gate release, as above.
|
||||
|
||||
**Tests: NEW `tests/standalone/Runtime/RuntimeShutdown.cpp`**
|
||||
- `runtime_shutdown_concurrent_callers_single_teardown_tsan`
|
||||
- `runtime_shutdown_full_normal_queue_still_delivers_completion`
|
||||
- `runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (exporter waits on a held mock read; total budget expires → incomplete, active ops 1, retained bytes > 0, threads alive; release → join again → complete; ordering log: `exporter_stopped < exporter_destroyed < executor_joined`)
|
||||
- `runtime_shutdown_stalled_business_task_incomplete_retains`
|
||||
- `runtime_shutdown_child_spawn_during_close_rejected`
|
||||
- `runtime_shutdown_budget_min_caller_policy_manual_clock` (`poll_shutdown`)
|
||||
- `runtime_shutdown_on_worker_self_join`
|
||||
- `runtime_shutdown_non_owner_defers_gate_release`
|
||||
- `runtime_shutdown_embedded_pumping`
|
||||
- `runtime_destructor_joins_after_start`
|
||||
|
||||
**Commands:** as S-RUNTIME-02, with `"^(RuntimeShutdown|RuntimeStart|RuntimeSignals|RuntimeHost)\."`, in `-Werror`, TSan and ASan dirs, plus `ctest` (RuntimeOnly).
|
||||
|
||||
---
|
||||
|
||||
## 2. Dependency graph and INTERNAL_DEPS check
|
||||
|
||||
```
|
||||
M-FUNCTIONAL-02✓ → M-FUNCTIONAL-03 ──(G1: RetryState)──→ M-TIME-03[Retry.hpp part]
|
||||
M-TIME-02✓ → M-TIME-03[Timer.hpp part] ──(G2: TimerQueue)──→ M-ASYNC-04[AsyncChannel deadlines]
|
||||
M-ASYNC-03✓ → M-ASYNC-04 → M-ASYNC-05
|
||||
M-ASYNC-04 ──(G3, hidden: ThreadExecutor)──→ S-RUNTIME-02
|
||||
S-IO-02✓ → S-IO-03 ──(G4, same files)──→ S-IO-04 (M-TIME-03 → S-IO-04 soft: PumpOptions::timers)
|
||||
S-IO-03 ──(hidden: start_file_workers, safe shutdown)──→ S-RUNTIME-02
|
||||
S-RUNTIME-01✓ → S-RUNTIME-02 → S-RUNTIME-03 ←(G5, hidden: Driver::shutdown(options))── S-IO-04
|
||||
{M-ASYNC-05, S-IO-04, S-RUNTIME-03} → P-NETWORKED-02 / P-RELOADABLE-02 gates
|
||||
```
|
||||
|
||||
**Critical path:** M-TIME-03 (Timer) → S-IO-03 → S-RUNTIME-02 → S-RUNTIME-03, with S-IO-04 needed before S-RUNTIME-03.
|
||||
|
||||
| Module | Change | Rule check against DEPENDENCIES.md |
|
||||
| --- | --- | --- |
|
||||
| Functional | none (stays empty) | Rule 1 and D-015: standard library only. `RetryState.hpp` includes no Void header. |
|
||||
| Time | none | Rule 1. The helpers are `std::chrono` only. No Time→Functional edge (D-W11-02). |
|
||||
| Async | none (Functional Time LogState) | Rule 2: no Log backend, no Runtime. New headers include only Async, Functional and Time. |
|
||||
| IO | none internal; no Threads (D-W11-08) | Rule 2: IO depends on Async; no System, Runtime or Net. |
|
||||
| Runtime | none (…Async IO) | Composes Async/IO/Time/Memory. No System edge; uses the `SignalGate` port. |
|
||||
| SystemAsync, tests only | none | "System may use IO". System appears in `RuntimeSignals.cpp` as a test include only; the file is skipped without System. |
|
||||
|
||||
## 3. Ownership partition
|
||||
|
||||
**Root-owned, before dispatch (W11-0 contracts pre-commit; single writer):**
|
||||
- `include/Void/Async/Detail/Types.hpp`: `AsyncErrorCode::closed = 9` plus its mapping case.
|
||||
- `include/Void/IO/Types.hpp`: the enum part only, `IoErrorCode::sync_failed = 12` plus its case.
|
||||
- `include/Void/Runtime/Options.hpp`: `RuntimeErrorCode::self_join = 8` and `shutdown_incomplete = 9` plus their cases.
|
||||
|
||||
**Root-owned throughout:**
|
||||
- `docs/agent-workflow/**` (task specs, TASKS, STATE, DECISIONS, VERIFICATION)
|
||||
- `CMakeLists.txt`, `cmake/*`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake` (no change planned)
|
||||
- `include/Void/Functional/Error.hpp` (no change planned; no new domains)
|
||||
- All integration, commits and merges
|
||||
|
||||
**Package A: sonnet-implementer (sol rows), run in order**
|
||||
|
||||
| Step | Task | Owned paths |
|
||||
| --- | --- | --- |
|
||||
| A1 | M-FUNCTIONAL-03 | `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`, `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp` |
|
||||
| A2 | M-ASYNC-04 | `include/Void/Async/ThreadExecutor.hpp`, `include/Void/Async/FuturePool.hpp`, `include/Void/Async/AsyncChannel.hpp` (all NEW), `include/Void/Async/ParallelFor.hpp`, `tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp`. Channel deadline waits wait for G2. |
|
||||
| A3 | M-ASYNC-05 | `include/Void/Async/EventBus.hpp`, `include/Void/Async/Observable.hpp`, `tests/standalone/Async/{EventBusJoin,ObservableReentrancy}.cpp` |
|
||||
| A4 | S-IO-04 (after G4: IO ownership passes from B to A) | `include/Void/IO/{Types,Driver,Pump(NEW)}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}`, `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `src/SystemAsync/*` (stop and report). |
|
||||
|
||||
**Package B: opus-implementer (astra rows), run in order**
|
||||
|
||||
| Step | Task | Owned paths |
|
||||
| --- | --- | --- |
|
||||
| B1 | M-TIME-03 | `include/Void/Async/Timer.hpp` (NEW), `include/Void/Async/Retry.hpp` (NEW, after G1), `include/Void/Time/Clock.hpp`, `tests/standalone/Async/{TimerQueue,AsyncRetry,DeadlineDomains}.cpp`, `tests/standalone/Time/ClockSaturation.cpp` |
|
||||
| B2 | S-IO-03 | `include/Void/IO/File.hpp` (NEW), `include/Void/IO/{Types,Driver}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}` (NEW), `tests/standalone/IO/IoFile.cpp` |
|
||||
| B3 | S-RUNTIME-02 (after G3 + B2) | `include/Void/Runtime/{Host,Lifecycle(NEW)}.hpp`, `include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals}.cpp`, `tests/package/RuntimeOnly/main.cpp` (optional smoke) |
|
||||
| B4 | S-RUNTIME-03 (after G5) | same Runtime files, plus `tests/standalone/Runtime/RuntimeShutdown.cpp` |
|
||||
|
||||
**Gate sequence (root integrates at each):**
|
||||
- G1: A1 merged, then B1 writes `Retry.hpp`.
|
||||
- G2: B1's `Timer.hpp` merged, then A2 adds channel deadlines.
|
||||
- G3: A2 merged, then B3.
|
||||
- G4: B2 merged, then A4.
|
||||
- G5: A4 merged, then B4.
|
||||
|
||||
No path is owned by both packages at the same time. No worker touches `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`, `ThreadPool.hpp` or `Channel.hpp`.
|
||||
|
||||
## 4. System signal gate (S-RUNTIME-02)
|
||||
|
||||
It exists:
|
||||
- `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp:16-43`). Its contract (`:13-15`): construct it before worker threads; destroy it on the creating thread.
|
||||
- `create` blocks the mask with `pthread_sigmask` and opens a `signalfd` with `SFD_CLOEXEC|SFD_NONBLOCK` (`src/System/SignalWatcher.cpp:74-90`).
|
||||
- `~Impl` closes the fd and restores the mask only when `pthread_equal(owner, self)` (`:27-37`). Off-thread destruction silently skips the restore.
|
||||
- It has been unchanged since before baseline (`3851aeb`).
|
||||
|
||||
Runtime has no System edge. The S-RUNTIME-01 spec excludes it, and the Runtime area plan doesn't list it, although DEPENDENCIES.md does not forbid it.
|
||||
|
||||
Minimal in-wave work:
|
||||
- The `SignalGate` port: installed as start step 1, uninstalled last on the owner thread, with deferred owner release if shutdown runs elsewhere.
|
||||
- A test-local adapter over `SignalWatcher` inside `RuntimeSignals.cpp`.
|
||||
- No System source changes.
|
||||
- A production bridge module (for example a NEW `RuntimeSystem` with deps Runtime+System, following the SystemAsync pattern) is deferred to S-RUNTIME-04 (D-W11-04).
|
||||
|
||||
## 5. S-RPC-04 verdict: do not ride along; defer to the P3 wave
|
||||
|
||||
**What is in place:**
|
||||
- S-RPC-03 is VERIFIED (`docs/agent-workflow/TASKS.md:129`).
|
||||
- The Net WebSocket pieces are present: codec and client (`Net/WebSocket.hpp:127-185`), server sessions (`Net/Server.hpp:205-300`), `add_websocket_route` (`Net/HttpServer.hpp:93-99`), and subprotocol negotiation (`WebSocket.hpp:37-45,127-130`).
|
||||
- It is file-disjoint from this wave (`include/Void/RPC`, `src/RPC`, `tests/standalone/RPC`).
|
||||
|
||||
**Why it should wait:**
|
||||
1. `WebSocketLimits::max_output_messages` and `max_output_bytes` (`WebSocket.hpp:32-33`) are never read in `src/Net`. Server sends are a synchronous `send_all` under a per-connection mutex (`src/Net/HttpServer.cpp:930-946`). So "no memory growth under stalled consumers", and a reserved control lane for CANCEL/TERMINAL, can't be guaranteed at the transport layer without a Net change or an explicit acceptance of blocking-send semantics.
|
||||
2. The client is synchronous (`WebSocket.hpp:166-170`). The planned `Task<Result<DuplexCall>>` API would naturally sit on M-ASYNC-04's `AsyncChannel`, which makes it dependent on this wave's output.
|
||||
3. It is an astra row and would compete with the opus critical path.
|
||||
4. It is P3, against D-027 ordering.
|
||||
|
||||
**Prerequisite for later:** a small Net task to enforce output budgets or a bounded non-blocking send queue, or a recorded decision to accept blocking sends.
|
||||
|
||||
## 6. Risks
|
||||
|
||||
- **D1 (high):** the existing epoll double reference release and the shutdown-versus-poller use-after-free / fd-reuse risk. It is fixed in S-IO-03 and needs TSan and ASan evidence.
|
||||
- **SIGUSR2 is fatal if left pending.** A blocked SIGUSR2 that is still pending when the mask is restored takes its default action and kills the VoidTests process. The signal tests must drain the signal via `poll()` before uninstalling.
|
||||
- **`/proc` counting:** thread and fd deltas can be disturbed by background threads from earlier tests. Measure deltas within a single test (tests run sequentially by default, `Runner.cpp:734-740`), with Host telemetry as the primary check.
|
||||
- **ThreadExecutor join while coroutines are still suspended elsewhere** falls back to inline resume. Runtime must reach driver quiescence before executor join; the S-RUNTIME-03 phase order enforces this.
|
||||
- **ManualClock with blocking waits:** `shutdown_blocking` and IO `shutdown` must re-evaluate the injected clock in short slices. Deterministic tests use `poll_shutdown` or expired deadlines rather than sleeps.
|
||||
- **Internal TaskScopes in destructors:** a `TaskScope` destructor pumps or blocks (`TaskScope.hpp:562-575`). EventBus (Injected mode) and Host must join their internal scopes before destruction.
|
||||
- **Behavior changes in 1.x:** Observable and Sync EventBus reentrancy used to be undefined behavior and now get defined semantics. Async-mode handler exceptions change from terminate to catch-and-count (needs D-W11-06 approval).
|
||||
- **Scope size:** B3 and B4 are the largest items and carry the highest schedule risk.
|
||||
- **Out of scope:** `Concurrency::Channel` with capacity 0 deadlocks (`Channel.hpp:17,27-28`), and Resilience `wait_with_stop` mixes real sleeps with the injected clock (`AsyncPolicy.hpp:553-575`).
|
||||
|
||||
## 7. Open decisions (recommendation for each)
|
||||
|
||||
| ID | Decision | Recommendation |
|
||||
| --- | --- | --- |
|
||||
| D-W11-01 | Where TimerQueue is owned | Async header `Async/Timer.hpp`, delivered by M-TIME-03 (astra) |
|
||||
| D-W11-02 | Clock/sleeper adapter placement | Callables injected into Functional; no Time→Functional edge and no Time retry header (resolves the Functional.md wording) |
|
||||
| D-W11-03 | Zero-attempt success in legacy `retry` | Keep unchanged (D-029), pin it with a test, and record it for the Wave C migration |
|
||||
| D-W11-04 | How the signal gate is wired | `SignalGate` port, no Runtime→System edge; production bridge deferred to S-RUNTIME-04 |
|
||||
| D-W11-05 | S-IO-03 (opus) then S-IO-04 (sonnet) in shared IO files | Accept serial hand-off at G4, with the risky shutdown and poll fixes placed in S-IO-03. No other role deviation. |
|
||||
| D-W11-06 | EventBus semantics | Legacy `unsubscribe` keeps delivering queued copies in Async mode; NEW `close_and_join` gates and joins; Async-mode handler exceptions go to `error_sink` (no terminate) |
|
||||
| D-W11-07 | Net adapter for IO | Defer. The System adapter is the existing SystemAsync, validated by the new shutdown test. |
|
||||
| D-W11-08 | `Threads::Threads` for IO and Runtime | Don't add it. Adding it would require changing IOOnly/RuntimeOnly flags in `InstalledComponents.cmake`. |
|
||||
| D-W11-09 | Runtime build shape | Stay header-only (`Detail/HostCore.hpp`), so packaging is unchanged |
|
||||
| D-W11-10 | Legacy `parallel_for` on exceptions | Join all futures before rethrowing; this fixes a lifetime hazard without changing the API |
|
||||
| D-W11-11 | When file workers start | Explicit `start_file_workers()`, so existing Driver users don't get hidden threads |
|
||||
| D-W11-12 | S-RPC-04 | Defer to the P3 wave, after a Net output-bounds task |
|
||||
| D-W11-13 | `async_wait_for_capacity` and the channel byte budget | Defer; neither is in the row acceptance |
|
||||
| D-W11-14 | Host-managed TimerQueue | Defer to S-RUNTIME-04 |
|
||||
| D-W11-15 | New enumerators | Root pre-commit before dispatch: `AsyncErrorCode::closed`, `IoErrorCode::sync_failed`, `RuntimeErrorCode::{self_join, shutdown_incomplete}` |
|
||||
|
||||
**Roadmap inconsistencies, all resolvable:**
|
||||
- The S-RUNTIME-02 and S-RUNTIME-03 rows omit their M-ASYNC-04 and S-IO-03/04 prerequisites; add the edges.
|
||||
- The area plan's awaited `Coro::Task` shutdown on the host's own executor would conflict with stopping that executor; the plan uses blocking and polling shutdown APIs instead.
|
||||
- Runtime and IO each define a `file_workers` setting; Runtime is authoritative.
|
||||
- The IO plan describes a "driver thread" but the code has none; S-IO-04 adds `run()`, and Runtime owns the reactor thread.
|
||||
|
||||
None of these contradicts D-001..D-036 or needs a forbidden edge.
|
||||
|
||||
## 8. Checks not run
|
||||
|
||||
- No builds or tests were run, and no probe was compiled. Every command above is proposed and unverified.
|
||||
- Graph and Serena tools weren't used, so no `check_index_coverage` either. All claims come from direct file reads and `rg`.
|
||||
- Not inspected in depth: the SystemAsync `ProcessManager` shutdown path, IPC and Storage test names (their commands run unfiltered), and `docs/roadmap/PERFORMANCE.md`.
|
||||
- Two C++ points are assumed, not compile-checked: that the `move_only_function` used by `TimerQueue` is available, and that `std::uniform_int_distribution` is consistent across toolchains (the tests assert bounds, not exact values).
|
||||
|
||||
**Files most relevant to this plan:**
|
||||
- `/home/faumaray/Projects/VoidLibrary/src/IO/EpollDriver.cpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/Executor.hpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/TaskScope.hpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Runtime/Host.hpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Functional/Retry.hpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/include/Void/System/SignalWatcher.hpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/src/System/SignalWatcher.cpp`
|
||||
- `/home/faumaray/Projects/VoidLibrary/tests/package/InstalledComponents.cmake`
|
||||
- `/home/faumaray/Projects/VoidLibrary/src/Net/HttpServer.cpp`
|
||||
@@ -0,0 +1,349 @@
|
||||
# W11-PLAN-REV1 contract addendum (opus-planner, 2026-11-29)
|
||||
|
||||
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
|
||||
|
||||
# W11-PLAN-REV1: contract addendum (deltas only)
|
||||
|
||||
**Status: DONE.** I accepted every root resolution, with three clarifications recorded at the end:
|
||||
- F5: the off-owner signal adapter should close its fd. That matches 1.x and avoids a descriptor leak.
|
||||
- F1(a): the injected `FileSyscalls` shim is the one exception to "workers never run user code".
|
||||
- Observable: queuing nested updates for copyable types is a 1.x ordering change that MIGRATION must record.
|
||||
|
||||
Nothing was written to the repository. The reviewer's findings aren't persisted separately: `W11-PREFLIGHT.md` is the review brief. I worked from your F1–F13 and P3 summary. Gates G1–G5 stay; G6 is new; the B2 and A4 file sets change (table at the end).
|
||||
|
||||
---
|
||||
|
||||
## F1 (P1) S-IO-03 teardown thread rule (owner B2)
|
||||
|
||||
**Invariants**
|
||||
- **(a)** A file worker performs one syscall (native or `FileSyscalls` shim) and nothing else. It then pushes `{request, result}` onto `FileWorkerShared::completions` under the shared mutex and calls the waker.
|
||||
- Resume tickets are produced only by a poll turn, which drains `completions` through the existing `complete_op_and_collect_tickets` / `dispatch_tickets` path.
|
||||
- `run_file_work()` executes one syscall on the caller's thread and only queues its result.
|
||||
- **(b)** Workers hold only `std::shared_ptr<detail::FileWorkerShared>` (queues, mutex/condvar, completion queue, and a waker given as function pointer plus context). They never hold `shared_ptr<DriverBackend>`.
|
||||
- The waker's raw backend pointer stays valid because workers are joined before the backend can be destroyed: `Driver::~Driver` and `shutdown_and_join` both join first.
|
||||
- **(c)** `~EpollBackend`, `~MockBackend` and `~FileWorkers` never block. `~FileWorkers` finding a joinable thread prints a diagnostic to stderr and calls `std::terminate`.
|
||||
- Today `~EpollBackend` blocks (`EpollDriver.cpp:953-955` calls `shutdown_and_join`); that call is removed.
|
||||
- `Driver::~Driver` (`:1737-1742`) becomes the blocking teardown: `backend_->teardown_blocking()`.
|
||||
- **(d)** Two thread-local markers detect misuse:
|
||||
- `tl_io_worker_owner` (a non-null pool pointer on worker threads)
|
||||
- `tl_polling_backend` (set while a thread runs that backend's `poll_once` turn)
|
||||
`~Driver` with either marker matching prints a one-line stderr diagnostic and calls `std::terminate`.
|
||||
- NEW, declared in `Driver.hpp` and defined in `FileWorkers.cpp`:
|
||||
```cpp
|
||||
[[nodiscard]] bool Void::IO::is_io_worker_thread() noexcept; // true on any Driver's file-worker thread
|
||||
```
|
||||
|
||||
**(e) Tests (`IoFile.cpp`)**
|
||||
- `io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread`: with `ManualExecutor`, `poll_once` dispatches a ticket and `exec.drain()` on the same thread resumes a coroutine that resets the `unique_ptr<Driver>`. Teardown must complete with no terminate.
|
||||
- `io_worker_thread_marker_only_on_file_workers`: a gated shim records `is_io_worker_thread()` as true inside `pread`; it is false on the main thread, inside the poll turn and inside executor drain. The terminate path is documented only; no death test, because the Runner has no fork-based death support (`src/Testing/Subprocess.cpp:142` only execs helpers).
|
||||
|
||||
## F2 epoll/eventfd lifetime (B2)
|
||||
|
||||
- The epoll fd and eventfd still close in `~EpollBackend`, as in 1.x (`:956-963`).
|
||||
- Shutdown closes only operation and descriptor fds, and only after it holds poll ownership.
|
||||
- `wake()` loads `std::atomic<bool> wake_closed_` (acquire) and returns if set. It is set (release) when shutdown completes.
|
||||
- Lock vs atomic: atomic is enough, and TSan-clean. `wake_fd_` is written only in the constructor (`:1255-1265`) and in `~EpollBackend`.
|
||||
- All `wake()` callers hold a shared owner: `Driver::backend_`, the `CancelForwarder` weak→lock at `:589-596`, and `StreamState::lock_backend` at `Backend.hpp:89-96`.
|
||||
- Workers are joined first.
|
||||
- So the destructor's write happens after every `wake()` call, through the `shared_ptr` control block's acq_rel ordering.
|
||||
- `poll_once` checks `shut_down_` (acquire) on entry and returns `0` before touching any fd. That keeps the 1.x return value (`:1057-1059` returns `work_done`).
|
||||
|
||||
## F3 / F4 Runtime shutdown phases and budgets (B4)
|
||||
|
||||
```cpp
|
||||
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
|
||||
stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped };
|
||||
```
|
||||
|
||||
**Phase order**
|
||||
|
||||
| # | Phase | What happens |
|
||||
| --- | --- | --- |
|
||||
| 1 | `closing_admission` | business scope closes admission |
|
||||
| 2 | `draining` | wait for the business scope to drain (deadline fixed at first entry) |
|
||||
| 3 | `cancelling` | request stop on the business scope |
|
||||
| 4 | `joining_business` | wait for the business scope to finish |
|
||||
| 5 | `stopping_components` | non-exporter components stop |
|
||||
| 6 | `flushing_exporters` | exporters stop (flush deadline fixed at first entry) |
|
||||
| 7 | `releasing_components` | drop every component `shared_ptr`, so exporters are destroyed here |
|
||||
| 8 | `stopping_io` | owned driver shuts down |
|
||||
| 9 | `stopping_workers` | wait for the owned executor to go idle within budget, then join the reactor and executor |
|
||||
| 10 | `releasing` | budgets and fds; signal gate on the owner thread |
|
||||
| 11 | `stopped` | |
|
||||
|
||||
- The ordering assertion `exporter_stopped < exporter_destroyed < executor_joined` stays.
|
||||
- **Per-call budget:** every `shutdown_blocking`, `poll_shutdown` and `shutdown_pumping` call uses `call_deadline = min(options.deadline, deadline_after(clock, total_timeout))` for the work that remains.
|
||||
- **Phase deadlines:** the drain and flush deadlines are fixed when their phase is first entered and stay expired afterwards.
|
||||
- Drain expiry moves on to phase 3 and sets `drain_grace_expired`.
|
||||
- Flush expiry requests stop on the exporter operations, sets `export_flush_expired`, and keeps waiting.
|
||||
- **Incomplete:** if `call_deadline` expires in a waiting phase (4, 5, 6, 8 or 9), the sequence stops and returns `complete=false`, with the phase and state recorded as `shutdown_incomplete`. The next call resumes at that phase.
|
||||
- NEW `[[nodiscard]] bool Async::ThreadExecutor::idle() const noexcept;` (both queues empty and nothing running), used by phase 9 so the executor join is never unbounded.
|
||||
|
||||
## F5 Host ownership (B3, with the B4 parts)
|
||||
|
||||
- All lifecycle state and teardown live in `detail::HostCore`, owned by `std::unique_ptr`. `~HostCore`:
|
||||
- if the host is started and not stopped, calls `shutdown_blocking({})` (unbounded);
|
||||
- then `gate->uninstall(this_thread == owner)`.
|
||||
Default move-assign is therefore safe.
|
||||
- **Moved-from Host** (`HostState` has no moved-from value, `Host.hpp:19-29`):
|
||||
- NEW `[[nodiscard]] bool valid() const noexcept;`
|
||||
- `state()` returns `stopped`; `is_running()` and `is_ready()` return false; `started_worker_count()` returns 0.
|
||||
- `executor()` and `io()` return `nullptr`; `owner_thread()` and `last_shutdown_report()` return `nullopt`.
|
||||
- `start`, `shutdown_*` and `poll_shutdown` return `RuntimeErrorCode::invalid_state`; `spawn` returns `AdmissionError::stopped`.
|
||||
- `clock()` stays safe through its System-clock fallback (`:147-151`).
|
||||
- `memory_budget()` has the precondition `valid()`. This is a pre-existing hazard: the 1.x code dereferences a null `owned_budget_` after a move (`:153-156`).
|
||||
- `~HostCore` running on a Runtime worker, the reactor or an IO worker prints a stderr diagnostic and calls `std::terminate`. Detection uses:
|
||||
- `executor->is_executor_thread()` (`Executor.hpp:86-96`)
|
||||
- a Runtime `tl_reactor` marker
|
||||
- `IO::is_io_worker_thread()`
|
||||
- **SignalGate shape:**
|
||||
```cpp
|
||||
class SignalGate { public: virtual ~SignalGate() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
|
||||
virtual void uninstall(bool on_owner_thread) noexcept = 0; }; // replaces uninstall()
|
||||
```
|
||||
- `shutdown_*` called off the owner thread leaves the gate installed (`owner_release_pending=true`). A later owner-thread call, or `~HostCore`, calls `uninstall(this_thread == owner)`.
|
||||
- The System test adapter destroys its `SignalWatcher` in both cases. 1.x closes the fd on any thread (`SignalWatcher.cpp:29-31`) but restores the mask only on the owner (`:32-36`). Off-owner teardown therefore cannot restore the owner's mask; document this.
|
||||
- Test: `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`, which checks the `/proc/self/fd` delta is 0 and that the owner's mask is still blocked.
|
||||
|
||||
## F6 Teardown follows ResourceOwnership (B4)
|
||||
|
||||
- An embedded or borrowed executor, driver, clock or memory resource is never shut down, closed or joined by the Host. Phases 8 and 9 are skipped for borrowed resources.
|
||||
- Signature:
|
||||
```cpp
|
||||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_pumping(
|
||||
Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr);
|
||||
```
|
||||
It drives progress with `IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`, so gate G5 stays.
|
||||
- Test: `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`. After shutdown the borrowed driver still accepts `create_mock_stream` and the executor still accepts `try_post`.
|
||||
|
||||
## F7 AsyncChannel arbitration (A2)
|
||||
|
||||
- One `std::mutex` covers the buffer and both waiter lists.
|
||||
- Waiter nodes live in the awaiter, inside the coroutine frame. Each holds `enum class WaiterState { linked, claimed, cancelled, timed_out, closed }`. A send waiter holds `std::optional<T> value`; a receive waiter holds `std::optional<T> slot`.
|
||||
- Pairing a sender with a receiver happens under the lock, in one critical section: unlink and claim the waiter, then move the value. A value is therefore always in exactly one place: the sender node, the buffer or the receiver slot. It is never in limbo.
|
||||
- Stop callbacks and timer callbacks take the same lock.
|
||||
- If the waiter is still `linked`, it is unlinked and set to `cancelled` or `timed_out`. A sender keeps its value and gets it back.
|
||||
- If it is already `claimed`, the callback does nothing. A sender gets success; a receiver gets the value that is already in its slot.
|
||||
- Every resume is dispatched through `post_completion` after unlock. Each sender gets success or its value back exactly once.
|
||||
- Tests:
|
||||
- `channel_receiver_stop_after_claim_delivers_value_no_loss`
|
||||
- `channel_sender_stop_vs_receive_race_exactly_once_tsan`: 10,000 iterations; the multiset of values sent equals values received plus values returned.
|
||||
- `channel_timer_close_settles_waiter_cancelled` (see F12)
|
||||
|
||||
## F8 Default URBG (A1, B1)
|
||||
|
||||
House convention: `Retry.hpp:89` seeds with `std::random_device`.
|
||||
|
||||
```cpp
|
||||
namespace Void::Retry::detail { template <class G> G seeded_engine()
|
||||
{ if constexpr (std::is_constructible_v<G, std::random_device::result_type>) return G{std::random_device{}()}; else return G{}; } }
|
||||
// RetryState::create(spec, start, URBG urbg = detail::seeded_engine<URBG>(), std::optional<SteadyTimePoint> = {})
|
||||
// BlockingRetryOptions::urbg default member init = detail::seeded_engine<URBG>(); retry_async param default likewise
|
||||
```
|
||||
|
||||
- Tests pass seeded `std::mt19937_64{42}` everywhere except `retry_state_default_engine_jitter_in_bounds`, which checks bounds only.
|
||||
|
||||
## F9 Revised D-W11-05: B2 owns the shutdown core, A4 owns thin wrappers
|
||||
|
||||
**B2 internal primitive in `detail::DriverBackend` (`Backend.hpp`):**
|
||||
```cpp
|
||||
virtual void begin_shutdown() noexcept = 0; // idempotent: close admission, cancel queued, stop active
|
||||
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
|
||||
std::optional<Void::Time::MonotonicClock::time_point> deadline, std::stop_token stop) = 0;
|
||||
[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0;
|
||||
[[nodiscard]] virtual bool quiescent() const noexcept = 0; // no owned ops/requests/in-flight syscalls
|
||||
virtual void teardown_blocking() noexcept = 0; // Driver::~Driver only
|
||||
```
|
||||
- B2 also owns `DriverShutdownReport` in `Types.hpp`, using the plan's fields.
|
||||
- 1.x `shutdown_and_join()` becomes `advance_shutdown(nullopt, {})` mapped to `Result<void>`.
|
||||
- `advance_shutdown` details:
|
||||
- Waits for the injected-clock deadline in ≤1 ms real slices, re-reading the clock each time.
|
||||
- Calls `wake()` to interrupt the current poller.
|
||||
- Runs its own poll turns only while it holds poll ownership.
|
||||
- Returns `self_join` if called on this backend's worker or inside its poll turn.
|
||||
- **Poll-owner exclusion** uses a dedicated `std::mutex poll_mu_`. `poll_once` tries the lock and returns `std::unexpected(make_io_error(IoErrorCode::busy, ...))` if it can't get it, without touching any fd.
|
||||
- I chose `busy` over `0` for three reasons: `busy` already means "concurrent op not allowed" (`EpollDriver.cpp:533-540`); the only library caller in a loop ignores the result (`IPC/Session.cpp:1128`); and a silent `0` would let a second `run()` loop spin.
|
||||
- Test: `io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan`.
|
||||
|
||||
**A4 public wrappers** (inline in `Driver.hpp`; A4 touches no `.cpp`):
|
||||
```cpp
|
||||
void begin_shutdown() noexcept; // -> backend_->begin_shutdown()
|
||||
[[nodiscard]] Void::Result::Result<DriverShutdownReport> shutdown(Async::OperationOptions); // -> advance_shutdown(o.deadline, o.stop)
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
|
||||
[[nodiscard]] bool quiescent() const noexcept;
|
||||
```
|
||||
A4 also delivers `Pump.hpp`/`pump_until`, the SystemAsync conformance test, and tests.
|
||||
|
||||
## F10 Roadmap and doc edits (root, before dispatch)
|
||||
|
||||
**`docs/roadmap/modules/Functional.md`**
|
||||
- **:95-96**: "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."
|
||||
- **:99**: append "; the default engine is seeded from `std::random_device`."
|
||||
- **:104-106**: "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`."
|
||||
|
||||
**`docs/roadmap/subsystems/Runtime.md`**
|
||||
- **:48-51**: "`Result<void> start(StartOptions); Async::Executor* executor(); IO::Driver* io(); Result<ShutdownReport> shutdown_blocking(Async::OperationOptions); Result<ShutdownReport> poll_shutdown(); Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions);` An awaited shutdown Task on the host's own executor is not offered, because it would self-join."
|
||||
- **:73**: "install the injected `SignalGate` (Runtime has no System dependency; System-backed adapter optional) on the owner thread"
|
||||
- **:77**: append "; off-owner teardown calls `uninstall(false)`, which cannot restore the owner's mask."
|
||||
- **:114-117**: "6. After cleanup/export callbacks and backend references retire, drop component/exporter references, then stop owned IO, the reactor and CPU/file workers, and release budgets, descriptors and the signal gate in reverse creation order. Borrowed executor, driver, clock and memory are never shut down or joined by the Host."
|
||||
- **:119**: "Each shutdown call observes min(caller deadline, now + total_timeout (30 s)) for remaining work. Drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete phase stops the sequence and the next call resumes there."
|
||||
- **:124-126**: "Destruction blocks to join only off Runtime threads. Destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error that terminates after a diagnostic."
|
||||
- **:159**: deps become "P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port)".
|
||||
- **:160**: deps become "P2 / S-RUNTIME-02, S-IO-04".
|
||||
|
||||
**`docs/roadmap/subsystems/IO.md`**
|
||||
- **:77-79**: "The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner) and owns interest updates and generations; a concurrent caller gets `busy` without touching descriptors. Producers wake the owner through eventfd. Runtime or the embedder supplies the thread (`Driver::run`, `pump_until`)."
|
||||
- **:92**: "Files use a bounded blocking worker pool started explicitly by `start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall or injected shim and queue its result; completions are delivered only by a poll turn."
|
||||
- **:118-120**: "Driver shutdown closes admission, cancels queued requests, stops active ones, waits for the poll owner and in-flight syscalls, drains completions, joins workers, then closes operation descriptors. Epoll and wake descriptors close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction on a file worker or inside a poll turn is a programmer error."
|
||||
- **:121-122**: "`File::close_and_join` returns `incomplete_shutdown` on expiry and retains the fd and buffers. A dropped File closes its fd after its last in-flight request drains."
|
||||
- **:154**: "optional System/Net adapters" becomes "SystemAsync conformance; Net adapter deferred (Net has no IO use)".
|
||||
|
||||
**`docs/roadmap/MIGRATION.md:61` (Async/IO row, append to the evidence cell)**
|
||||
"Recorded W11 changes:
|
||||
- `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers.
|
||||
- `validate_limits` rejects `max_file_queue == 0`.
|
||||
- Sync EventBus and Observable/Signal dispatch over snapshots; subscription changes take effect next pass.
|
||||
- Nested Observable/Signal updates for copyable types are queued FIFO.
|
||||
- Legacy `parallel_for` waits for all tasks before rethrowing.
|
||||
- Async-mode EventBus handler exceptions are counted instead of terminating.
|
||||
- Legacy `retry` zero-attempt result is kept until Wave C."
|
||||
|
||||
**DECISIONS:** amend D-W11-05 per F9, and add F1, F2 and F5 as root decisions.
|
||||
|
||||
## F11 Within-step failure coverage
|
||||
|
||||
- **IO (B2):** `BackendOptions::before_file_worker_start` (NEW, appended):
|
||||
```cpp
|
||||
std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
|
||||
```
|
||||
- `start_file_workers` treats a hook error exactly like a caught `std::system_error`: it joins the workers already started, returns `os_error` (with the system code when one exists), and allows a retry.
|
||||
- Test: `io_file_workers_partial_start_failure_joins_started`.
|
||||
- **ThreadExecutor (A2):** `start()` catches `std::system_error` from `std::thread` through the same path as `before_worker_start`.
|
||||
- **Runtime (B3):**
|
||||
```cpp
|
||||
struct StartOptions { /*...*/
|
||||
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)> before_thread_start{};
|
||||
std::chrono::milliseconds cleanup_timeout{5000}; };
|
||||
```
|
||||
- `before_thread_start` is forwarded to the executor and IO hooks and to the reactor's `std::thread` creation, which also catches `std::system_error`.
|
||||
- Failed-start component cleanup waits at most `cleanup_timeout` (injected clock). If it runs out, the state is `failed_start`, resources are retained, and the next `shutdown_blocking` or `~HostCore` continues the cleanup.
|
||||
- Tests:
|
||||
- `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup` (cpu_executor, file_workers and reactor, at index 0 and at the last index)
|
||||
- `runtime_failed_start_component_cleanup_timeout_retains_then_completes`
|
||||
- `thread_executor_system_error_path_shared_with_hook`
|
||||
|
||||
## F12 Shared-core lifetimes
|
||||
|
||||
- **EventBus (A3):**
|
||||
- Injected-mode dispatch frames capture `std::shared_ptr<detail::BusCore>`.
|
||||
- `~EventBus` closes admission. On an executor thread it does not wait: frames finish against the shared core. Off the executor it calls `close_and_join` (blocking, or pumping on `ManualExecutor`).
|
||||
- NEW `[[nodiscard]] Void::Result::Result<void> flush_blocking();` returns `self_join` on an executor thread or inside a bus callback, and `invalid_argument` on a `ManualExecutor` (`Executor.hpp:195`).
|
||||
- NEW `flush_pumping(ManualExecutor&)`.
|
||||
- Legacy `flush()` in Injected mode calls `flush_blocking()` and discards the error, because the 1.x signature returns `void` (`EventBus.hpp:193-201`). It never deadlocks.
|
||||
- **TimerQueue (B1):**
|
||||
```cpp
|
||||
enum class TimerEvent : std::uint8_t { expired, closed };
|
||||
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
|
||||
```
|
||||
- `TimerHandle` holds `shared_ptr<detail::TimerEntry>`, whose state is an atomic pending→{fired, cancelled} transition. `cancel()` is valid after the queue is destroyed.
|
||||
- The callback runs exactly once (`expired` or `closed`), or never if `cancel()` returned true. Queue close or destruction invokes pending callbacks with `closed`; AsyncChannel maps that to `cancelled`.
|
||||
- Test: `timer_handle_cancel_after_queue_destroyed_safe`.
|
||||
- **`parallel_for` (A2):**
|
||||
- Shared `detail::PForState` holds the decay-copied `F`, the chunk counter and the error slots.
|
||||
- The caller waits for every submitted runner future, including runners that were never started.
|
||||
- Nested use on the same pool from a pool worker is documented as unsupported.
|
||||
- Test: `parallel_for_bounded_waits_all_submitted_runners`.
|
||||
|
||||
## F13 File descriptor lifetime (B2)
|
||||
|
||||
- `detail::FileState` is shared-owned and holds the fd, the shim, the in-flight count, a `close_pending` flag and the per-file ordering lane. Every request holds a reference to it.
|
||||
- When the last handle drops:
|
||||
- with no requests in flight, an internal close request is enqueued, using reserved capacity outside `max_file_queue`;
|
||||
- otherwise `close_pending` is set, and the poll-turn retirement of the last request enqueues the close.
|
||||
- Close always executes on a worker, or in `run_file_work`. Teardown closes any remaining file fds after the workers are joined.
|
||||
- `File::close_and_join(options)` is always admitted.
|
||||
- Deadline or stop expiry returns `IoErrorCode::incomplete_shutdown`; the File stays valid with its fd and buffers retained, so the call can be repeated.
|
||||
- Success invalidates the File.
|
||||
- A close syscall failure returns `os_error`, and the fd is treated as closed.
|
||||
- This differs from `ByteStream::close_and_join`, which consumes the stream (`Stream.hpp:105`); document the difference.
|
||||
- Tests:
|
||||
- `io_file_drop_with_inflight_defers_close_until_drained`
|
||||
- `io_file_close_and_join_expiry_incomplete_retains_then_completes`
|
||||
|
||||
## P3 resolutions
|
||||
|
||||
- **`retry_blocking` template defaults (A1):** use defaulted function-template parameters, because deduction cannot read a default function argument:
|
||||
```cpp
|
||||
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
|
||||
class Classify = RetryEveryError, class URBG = std::mt19937_64>
|
||||
auto retry_blocking(const RetrySpec&, F&&, BlockingRetryOptions<NowFn, SleepFn, Classify, URBG> = {});
|
||||
```
|
||||
Tests spell the option types explicitly; aggregate CTAD is a convenience only.
|
||||
- **Observable/Signal (A3):**
|
||||
- `Observable<T>` with `std::copy_constructible<T>`: a nested `set` updates the value immediately and queues `(old, new)` copies, delivered FIFO after the current pass and bounded at 1,024. On overflow, `set` keeps the new value and counts a dropped notification. `try_set` (only when copyable) returns `overloaded` without changing the value.
|
||||
- Move-only `T`: the 1.x behavior stays — immediate recursive notification — but iteration runs over a listener snapshot. There is no queue and no `try_set`.
|
||||
- `Signal<Args...>` follows the same rule when `(std::copy_constructible<std::decay_t<Args>> && ...)`; the queue is a `mutable` member, since `emit` is `const`.
|
||||
- On a throw, the value stays the new value (as in 1.x, `Observable.hpp:40-42`), dispatch depth is restored, and that pass's queued notifications are dropped and counted.
|
||||
- **S-IO-03 downstream build:**
|
||||
```sh
|
||||
-DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;CryptoAsync;Runtime;ConfigurationAsync;Testing"
|
||||
```
|
||||
run unfiltered, plus `ctest`.
|
||||
- **Error-kind alignment:** `RuntimeErrorCode::shutdown_incomplete = 9` maps to `ErrorKind::conflict`, matching `IoErrorCode::incomplete_shutdown` (`IO/Types.hpp:51-53`). IO is unchanged. Root pre-commit.
|
||||
- **D1 regression seam (B2):**
|
||||
- Test `io_epoll_stop_requested_at_deadline_scan_completes_once` uses a clock whose `now()` requests stop. That `now()` call happens in the wait computation, only when the op has a deadline (`EpollDriver.cpp:1083,1098`).
|
||||
- The sequence:
|
||||
1. The socket already has data.
|
||||
2. The stop puts the cancel in the queue.
|
||||
3. `drive_read` sees the stop and completes the op (`:1452`).
|
||||
4. The end-of-turn cancel pass hits the same op (`:1173`).
|
||||
- NEW appended telemetry field `DriverTelemetry::duplicate_completions_ignored`. The test asserts a single delivery and a counter ≥ 1.
|
||||
- **Mock reactor spin (B3):** `MockBackend::poll_once` ignores `max_wait` (`EpollDriver.cpp:739-741`) and its `wake` only counts (`:637-640`).
|
||||
- The Runtime reactor (and A4's `Driver::run`) waits on a stop-aware condition variable for `max_wait` when the backend is mock and a turn did no work.
|
||||
- IO is unchanged, so the `IoDriver` test timing is untouched.
|
||||
- **Business scope:** `TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`, because the default is `true` (`TaskScope.hpp:32`).
|
||||
- **ThreadExecutor (A2):**
|
||||
- After `close()`, a legacy `post()` goes onto the completion lane and is counted.
|
||||
- `join()` drains until both lanes are empty and nothing is running. After join, posts resume inline and are counted.
|
||||
- No drain cap: abandoning a handle would strand a frame, which C-03 forbids (`ARCHITECTURE.md:63-64`, "owner until exactly one terminal result"). A handle that re-posts itself forever prevents join; that is documented as a caller error.
|
||||
- `~ThreadExecutor` without a prior join calls `close()` then `join()`. On its own worker it prints a diagnostic and terminates.
|
||||
- **Runtime worker detection** uses `IO::is_io_worker_thread()` (F1).
|
||||
- **Layering check (A4):**
|
||||
```sh
|
||||
rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO # expect no output
|
||||
git diff --stat -- src/IO/module.cmake # expect empty
|
||||
```
|
||||
- **Budget accounting (B4):** test `runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`.
|
||||
- The Host passes `memory_budget()` as the Driver's pmr resource (`Driver.hpp:69-74`).
|
||||
- An exporter holds a `BufferLease` across a stalled read.
|
||||
- While incomplete: `memory_budget().stats().requested_live > 0` (`BudgetResource.hpp:106`, `Memory/Resource.hpp:22-30`), and `executor()->admitted()` and `DriverTelemetry::owned_buffer_bytes` stay as they were.
|
||||
- After release and a second join: all three are 0.
|
||||
- **M-ASYNC-05 captured-state tests (A3):**
|
||||
- `bus_sync_unsubscribe_releases_captured_state`
|
||||
- `bus_legacy_async_unsubscribe_then_flush_releases_captured_state`
|
||||
- `bus_legacy_async_close_and_join_releases_capture_with_queued_copies`
|
||||
All three assert the sentinel's `use_count() == 1`.
|
||||
|
||||
## Revised gates and ownership (changes only)
|
||||
|
||||
**Gates**
|
||||
- G1–G5 as before.
|
||||
- G4 now hands A4 only `Driver.hpp` (inline wrappers), the NEW `Pump.hpp` and tests.
|
||||
- **G6 (new):** after A4 merges, all IO files are root-owned. B4 must stop and report if it needs an IO edit.
|
||||
|
||||
| Step | Owned-file delta |
|
||||
| --- | --- |
|
||||
| Root pre-commit | `RuntimeErrorCode::shutdown_incomplete` maps to `conflict` (changed from `timeout`) |
|
||||
| B1 | adds `TimerEvent` and the shared-state `TimerHandle` to `Async/Timer.hpp` |
|
||||
| B2 | adds to `IO/Driver.hpp`: `is_io_worker_thread`, `~Driver` teardown. Adds to `IO/Types.hpp`: `DriverShutdownReport`, `BackendOptions::before_file_worker_start`, `DriverTelemetry::duplicate_completions_ignored`. Adds to `IO/Detail/Backend.hpp`: the shutdown primitives. Also `src/IO/{EpollDriver.cpp, FileWorkers.{hpp,cpp}}` and `tests/standalone/IO/IoFile.cpp` |
|
||||
| A4 | `include/Void/IO/Driver.hpp` (inline wrappers only), `include/Void/IO/Pump.hpp` (NEW), `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `EpollDriver.cpp`, `Backend.hpp`, `Types.hpp`, `FileWorkers.*` (stop and report) |
|
||||
| B3 / B4 | `Runtime/Lifecycle.hpp` gains `SignalGate::uninstall(bool)`, `StartOptions::{before_thread_start, cleanup_timeout}` and the renumbered `ShutdownPhase`. `Host.hpp` gains `valid()` and the 3-argument `shutdown_pumping`. A2 additionally owns `ThreadExecutor::idle()` |
|
||||
|
||||
## Root resolutions I'd adjust (not silently changed)
|
||||
|
||||
1. **F5 adapter wording.** "Releases its fd ... only on the owner thread" doesn't match 1.x: `SignalWatcher` closes the fd on any thread (`SignalWatcher.cpp:29-31`). Keeping the fd open off-owner would leak it, because no later owner-thread call is guaranteed. I recommend closing the fd and skipping only the mask restore, exactly as 1.x does; the F5 section above specifies that.
|
||||
2. **F1(a) "workers never call user code".** The injected `FileSyscalls` shim runs on workers by design. It should be stated as the only exception: a syscall substitute that must not call Driver, Executor or File APIs.
|
||||
3. **Observable copyable queuing.** It changes 1.x nested-set ordering from recursive to FIFO for copyable types. That's acceptable, since the roadmap mandates the queue, but it must appear in the MIGRATION record; F10 includes it.
|
||||
|
||||
**Checks not run:** no builds or tests. All citations come from direct reads during this session.
|
||||
@@ -0,0 +1,125 @@
|
||||
# Wave 11 execution-path backfill — architecture and task plan
|
||||
|
||||
Task ID: W11-PLAN
|
||||
Role: opus-planner
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11`
|
||||
created from `main` at `38436b1` (Waves 1–10 merged at `7d7d23e`, pushed to `origin/main`).
|
||||
- Tracked tree clean. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`,
|
||||
`.vbs/`, dotfiles, `compile_commands.json`) are NOT task inputs; never read, copy or quote them.
|
||||
- Root gap analysis (2026-11-29): roadmap task tables list 300 tasks; `docs/agent-workflow/TASKS.md`
|
||||
marks Waves 1–10 done, but these execution-path tasks remain open and their pre-roadmap
|
||||
headers are untouched since baseline `f1f9ba3` (`git log f1f9ba3..HEAD` on
|
||||
`Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/Retry.hpp`
|
||||
shows no commits; `IO`/`Runtime` only received `S-IO-01/02` `673bb7e` and `S-RUNTIME-01` `1b3331e`):
|
||||
- P1 leftovers: `M-FUNCTIONAL-03`, `M-TIME-03`.
|
||||
- P2: `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`.
|
||||
- These gate `P-NETWORKED-02` / `P-RELOADABLE-02` ("Runtime/Async/IO lifecycle gates").
|
||||
- Requirement/contract references: `docs/roadmap/REQUIREMENTS.md` R-001..R-016,
|
||||
`docs/roadmap/ARCHITECTURE.md` C-01..C-14, gates G-ERROR/G-EXEC/G-IO in `DEPENDENCIES.md`.
|
||||
- Baseline full build/test of `main` is running separately under root; not your concern.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Produce an implementation-ready plan (returned as text, not written to files) for the eight
|
||||
tasks above, plus a readiness verdict for `S-RPC-04` (WebSocket streaming) as an optional
|
||||
ride-along. Deliverables in the reply:
|
||||
1. Per task: observed baseline (exact existing symbols/behavior with `path:line`), the gap
|
||||
against its roadmap row and area plan, and the minimal complete scope to satisfy the
|
||||
row's acceptance text.
|
||||
2. Per task: NEW public interfaces (C++ signatures, enums, error codes in existing domains,
|
||||
limits/defaults) marked NEW, and which existing 1.x APIs stay unchanged (D-029).
|
||||
3. Dependency graph between the eight tasks, and the module `INTERNAL_DEPS` changes, if any,
|
||||
with a check that every edge respects `DEPENDENCIES.md` target package rules.
|
||||
4. A partition into 2–3 worker packages with exclusive file ownership (exact paths), role
|
||||
(`astra_*` rows → opus-implementer, `sol_*` rows → sonnet-implementer), and order.
|
||||
Identify root-owned shared edits (e.g. `include/Void/Functional/Error.hpp`,
|
||||
`tests/package/InstalledComponents.cmake`, top-level `CMakeLists.txt`, `cmake/*`).
|
||||
5. Per task: concrete test list (test file paths, scenario names) mapping to acceptance text,
|
||||
and exact verification commands (module subset, filters) in the repository's form.
|
||||
6. Whether the "System signal gate" named by `S-RUNTIME-02` exists in current source
|
||||
(cite symbols), or what minimal in-wave work it implies without adding Runtime→System
|
||||
unless `DEPENDENCIES.md` permits it.
|
||||
7. Risks, open questions that need a root decision, and anything in the roadmap rows that
|
||||
is infeasible or contradictory, with a recommended resolution.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In scope: planning only for the eight tasks and the S-RPC-04 readiness note.
|
||||
Non-goals: editing files, writing specs, implementing code, running long builds, planning
|
||||
foundation P2 leftovers (Core/Math/Text/Data/Binary/…) or P3/P4 platforms.
|
||||
|
||||
## 4. Files to inspect
|
||||
- Roadmap: `docs/roadmap/modules/{Functional,Time,Async}.md`, `docs/roadmap/subsystems/{IO,Runtime,RPC}.md`,
|
||||
`docs/roadmap/{ARCHITECTURE,DEPENDENCIES,MIGRATION,VALIDATION,PERFORMANCE}.md`,
|
||||
`docs/roadmap/platforms/{NetworkedApplications,ReloadableApplications}.md` (gate wording only).
|
||||
- Prior specs for style/precedent: `docs/agent-workflow/tasks/{M-ASYNC-02-03,S-IO-01-02,S-RUNTIME-01,M-TIME-02,M-FUNCTIONAL-02,M-SYSTEM-01-05}.md`.
|
||||
- Source: `include/Void/Functional/{Retry,Error,Result}.hpp`, `src/Functional/module.cmake`;
|
||||
`include/Void/Time/{Clock,Stopwatch}.hpp`; `include/Void/Async/*.hpp`, `src/Async/module.cmake`;
|
||||
`include/Void/IO/{Types,Driver,Stream}.hpp`, `include/Void/IO/Detail/*`, `src/IO/{EpollDriver.cpp,module.cmake}`;
|
||||
`include/Void/Runtime/{Options,ResourceGraph,Host}.hpp`, `src/Runtime/module.cmake`;
|
||||
`include/Void/System/*` (signal handling), `include/Void/Net/*` (only for S-IO-04/S-RPC-04 adapters);
|
||||
existing tests under `tests/standalone/{Functional,Time,Async,IO,Runtime}/`;
|
||||
`cmake/Module.cmake`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake`.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Allowed commands: read-only `git`, `rg`, `ls`, `wc`, Serena/codebase-memory read tools. You may
|
||||
compile a tiny probe only under `/tmp/void-w11-plan-probe` if essential; do not touch the
|
||||
repository tree. `dev cpp-gcc ...` must run unsandboxed (nix fetcher lock); avoid it unless needed.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. Read each roadmap row and area-plan section; extract mandatory behavior and limits.
|
||||
2. Inspect the current headers/tests via Serena symbol tools; record what exists.
|
||||
3. Derive minimal complete NEW interfaces that layer beside 1.x APIs (Wave A+B, D-029).
|
||||
4. Check layering: Functional has zero `INTERNAL_DEPS` (D-015) — retry decisions must take
|
||||
injected time values or a template clock, not depend on `Time`; Async must not depend on
|
||||
Log backends or Runtime; IO must not depend on Runtime/Net/System; Runtime composes.
|
||||
5. Build the task DAG and the ownership partition minimizing cross-package header edits.
|
||||
6. Draft test scenarios that prove each acceptance sentence deterministically (manual clocks,
|
||||
mock IO backend) and TSan-relevant concurrency cases.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Use existing contracts: `Void::Functional::{Result,Error,Status,ErrorCode}`, domains
|
||||
`kTimeErrorDomain=4`, `kAsyncErrorDomain=7`, `kIoErrorDomain=8`, `kRuntimeErrorDomain=11`;
|
||||
`Void::Time::{MonotonicClock,ManualClock}`; Async `OperationOptions`/`TaskScope`/`Executor`;
|
||||
IO `Driver`/`BufferLease`; Runtime `Host`/`HostBuilder`/`ResourceGraph`. Any new error code
|
||||
must extend an existing domain enum; propose exact enumerator names.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: Waves 1–10 on `main`. Root owns integration, shared build files, and all commits.
|
||||
Implementers will be dispatched only after a fresh opus-reviewer PREFLIGHT of your plan.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Call out: exactly-one-terminal-result races, stop/expiry/completion permutations, buffer
|
||||
retention on active cancel, bounded queues including running work, reentrancy and
|
||||
unsubscribe-during-dispatch, failed-start reverse cleanup with no leaked threads/fds,
|
||||
signal-mask ownership, exporter-before-executor shutdown ordering, no user callbacks
|
||||
under locks, overflow-safe deadline arithmetic.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Each of the eight tasks has baseline, gap, NEW interface, tests and commands.
|
||||
2. DAG and INTERNAL_DEPS changes respect DEPENDENCIES.md rules (stated per edge).
|
||||
3. Ownership partition has no overlapping paths and lists root-owned shared files.
|
||||
4. S-RUNTIME-02 signal-gate question answered with cited symbols.
|
||||
5. S-RPC-04 readiness verdict with prerequisites cited.
|
||||
6. Open decisions listed with a recommendation each.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Not applicable for builds: planning-only. Cite `path:line` for every baseline claim. Command
|
||||
templates you propose must follow the observed form, e.g.
|
||||
`dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-<x> -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-<x> && /tmp/void-w11-<x>/tests/VoidTests --filter "<Pattern>*" && ctest --test-dir /tmp/void-w11-<x> --output-on-failure --timeout 60'`.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No repository edits, no commits, no network calls beyond local tools, no secrets. Stop and
|
||||
report if a roadmap requirement contradicts a recorded decision (D-001..D-032) or would need
|
||||
a new dependency edge forbidden by DEPENDENCIES.md.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decision under D-027/D-031 (continuous roadmap-order execution): Wave 11 is the
|
||||
execution-path backfill. Planning-only authorization; you do not approve your own plan.
|
||||
|
||||
## 14. Return format
|
||||
Return task ID; DONE/BLOCKED/PARTIAL; summary; per-task sections (baseline, gap, NEW
|
||||
interfaces, tests, commands); DAG; ownership partition; signal-gate answer; S-RPC-04 verdict;
|
||||
risks; open decisions with recommendations; checks not run. Do not spawn children.
|
||||
@@ -0,0 +1,162 @@
|
||||
# W11-PREFLIGHT-2 output (opus-reviewer, 2026-11-29)
|
||||
|
||||
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
|
||||
|
||||
**Task W11-PREFLIGHT-2. Verdict: CHANGES_REQUIRED.** The addendum and the root edits fix the first review's P1 (F1) and most of F2–F13. Six P2 gaps remain. One is a contradiction inside the addendum itself (N1). Four are gaps that the addendum's own resolutions create (N3–N6), and one is a state the addendum never covers (N2). All six can be fixed by adding sentences to the contract text. No re-plan, gate change or ownership change is needed.
|
||||
|
||||
- **Blocked until the text is amended:** B2 (N3, N4), B3/B4 (N1, N2, N3), A2's channel deadlines (N5; the rest of A2 can proceed), A3's EventBus work (N6). A4 picks up N3's loop rules when its spec is written.
|
||||
- **Not blocked:** A1 (M-FUNCTIONAL-03) can continue. B1 (M-TIME-03) can continue but needs one documentation-only note (N5). Neither needs an interface change.
|
||||
|
||||
Paths are relative to `/home/faumaray/Projects/VoidLibrary`. "Addendum" means `docs/agent-workflow/tasks/W11-PLAN-REV1-OUTPUT.md`; "plan" means `W11-PLAN-OUTPUT.md`.
|
||||
|
||||
## Item status
|
||||
|
||||
| Item | Status | Evidence / residual |
|
||||
|---|---|---|
|
||||
| F1 | RESOLVED | Workers only run a syscall and queue the result, so no completion runs on a worker. They hold a separate worker-pool object, never the backend. Backend destructors never block, and only `~Driver` does a blocking teardown, behind two terminate markers. Residual: P3-9. |
|
||||
| F2 | RESOLVED for sockets | The epoll and wake fds still close in the backend destructor (`EpollDriver.cpp:953-963`). Every socket-path `wake()` caller holds a strong reference (`:589-596`, `Backend.hpp:89-96`, `Stream.hpp:105-120`). The file path depends on N4. |
|
||||
| F3 | RESOLVED | Phase 7 drops the components before IO stops (phase 8) and before the executor is joined (phase 9). |
|
||||
| F4 | PARTIAL | The per-call budget fixes the zero-budget repeat call, but it contradicts the destructor rule (N1). Phase 2 is missing from the waiting-phase list (P3-1). |
|
||||
| F5 | PARTIAL | Moved-from rules are fine; gaps in N1, N2, P3-3 and P3-7. |
|
||||
| F6 | PARTIAL | Borrowed resources are skipped, but the embedded `ManualExecutor` path hangs (N2). |
|
||||
| F7 | PARTIAL | The single-lock claim/hand-off rule is sound. The timer callback can still reach a destroyed waiter (N5). |
|
||||
| F8 | RESOLVED | `seeded_engine` is in `M-FUNCTIONAL-03.md:114-142`. Nit: P3-6. |
|
||||
| F9 | PARTIAL | The routing fix is done. Choosing `busy` without loop rules creates N3. |
|
||||
| F10 | RESOLVED | The `7f95f89` doc edits match the addendum. Small gaps: P3-4. |
|
||||
| F11 | RESOLVED | The IO and executor start hooks plus `cleanup_timeout` cover failures inside a step (a later destructor finishes the cleanup, see N1). |
|
||||
| F12 | PARTIAL | `TimerHandle` shared state and the `parallel_for` shared state are fine. Gaps: N5 (timer) and N6 (EventBus). |
|
||||
| F13 | PARTIAL | The `FileState` deferred close is right in direction. The fd state machine is incomplete (N4). |
|
||||
|
||||
**First-review P3 items**
|
||||
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| `retry_blocking` template defaults | RESOLVED (`M-FUNCTIONAL-03.md:135-142`) |
|
||||
| Observable/Signal move-only and "state restored" | RESOLVED |
|
||||
| Downstream build list | RESOLVED |
|
||||
| Error-kind alignment | RESOLVED; observed in `Runtime/Options.hpp`, `shutdown_incomplete` maps to `conflict` |
|
||||
| D1 regression seam | RESOLVED (seam at `:1083`/`:1098`); see P3-5 |
|
||||
| Mock reactor spin | PARTIAL: the mock case is covered, the epoll cases are open (N3) |
|
||||
| Business scope `stop_on_first_error` | RESOLVED |
|
||||
| MIGRATION: `shutdown_and_join` blocks / `max_file_queue==0` / Sync snapshot / `parallel_for` | RESOLVED, all four observed in `MIGRATION.md:61` |
|
||||
| Unspecified: concurrent `poll_once` | PARTIAL (N3) |
|
||||
| Unspecified: IO file ownership after G5 | RESOLVED (G6) |
|
||||
| Unspecified: stop-and-report if an IO edit is needed | PARTIAL: stated for B4 and A4, not for B3 |
|
||||
| Unspecified: worker detection | RESOLVED (`is_io_worker_thread`) |
|
||||
| `ThreadExecutor` endless drain, destructor without join | RESOLVED |
|
||||
| Acceptance gaps (layering `rg`, within-step faults, ordering, budget test, receiver stop, legacy-mode captures) | RESOLVED; budget test lifetime in P3-2 |
|
||||
|
||||
**Named checks (§3)**
|
||||
|
||||
| Check | Answer |
|
||||
|---|---|
|
||||
| `busy` breaking existing callers | It does not. The only library loop that polls is `~Session` (`src/IPC/Session.cpp:1118-1129`): bounded to 1,000 iterations, result ignored. Every test drives a driver from one thread, and the one cross-thread test polls from only one thread (`IoDriver.cpp:458-508`). The hazard is in the new loops (N3). |
|
||||
| `wake_closed_` atomic argument | Sound. The last `shared_ptr` release orders the destructor after every `wake()`. The flag is effectively optional because the fd closes only in the destructor. The file wake path is not enumerated (N4). |
|
||||
| `FileState` reserved close capacity | Bounded only if files take descriptor slots. The addendum doesn't say so (N4). |
|
||||
| `ThreadExecutor::idle()` in phase 9 | Usable, but it is a snapshot, so "join never unbounded" is overstated (posts after the snapshot still extend the join). Safe in Runtime because phase 8 has already stopped IO dispatch. |
|
||||
|
||||
**Named hazards (§6.2)**
|
||||
|
||||
| Hazard | Answer |
|
||||
|---|---|
|
||||
| Raw waker pointer lifetime | Sound for workers: every backend destruction path goes through `~Driver`, which joins the workers first. `~File` must not use that waker (N4). |
|
||||
| `busy` and loop callers | See N3. |
|
||||
| Reserved close capacity unbounded | See N4. |
|
||||
| Phase-9 idle wait vs inline resume after join | Unreachable from IO, because phase 8 runs first. External posts (stop callbacks, user threads) resume inline; this is documented. |
|
||||
| `~HostCore` unbounded shutdown on destruction | Contradicted by the per-call budget (N1). Hangs in embedded mode (N2). |
|
||||
|
||||
**Planner adjustments**
|
||||
|
||||
| Adjustment | Verdict |
|
||||
|---|---|
|
||||
| Signal adapter closes its fd off the owner thread | Agree. It matches `src/System/SignalWatcher.cpp:27-37`, and `Runtime.md` is updated. Test hygiene: P3-3. |
|
||||
| Injected syscall shim as the one exception | Agree. `IO.md:94-96` is updated. |
|
||||
| Observable FIFO ordering change | Agree. It is recorded in `MIGRATION.md`. |
|
||||
|
||||
## New findings
|
||||
|
||||
**N1 (P2, observed contradiction): the destructor's shutdown is called "unbounded" but the budget rule caps it at 30 s.**
|
||||
- **Where:** addendum `:85` says "(unbounded)". Addendum `:75-79` caps every call at `min(deadline, now + total_timeout)` and returns `complete=false` on expiry. `validate_options` rejects `total_timeout <= 0`, so the cap can't be switched off. The failed-start continuation (`:230`) relies on the same path.
|
||||
- **What happens:** a stall longer than 30 s makes `~HostCore` return from the shutdown call incomplete. A joinable reactor `std::thread` then calls `std::terminate`. If it didn't, members would tear down while components still exist.
|
||||
- **Related:** `poll_shutdown()` takes no options, so its budget restarts on every call. The plan test `runtime_shutdown_budget_min_caller_policy_manual_clock (poll_shutdown)` (plan `:745`) can therefore never see an expiry.
|
||||
- **Fix:** `~HostCore` loops `shutdown_blocking({})` until `complete` (or calls an internal no-deadline variant). State "destruction blocks until complete". Move that test to `shutdown_blocking` with an expired or manual-clock deadline. Define how `poll_shutdown` relates to the budget.
|
||||
|
||||
**N2 (P2, inferred hang): embedded mode with a borrowed `ManualExecutor`.**
|
||||
- **Where:** `~HostCore` calls `shutdown_blocking`. Phase 4 then reaches `TaskScope::join_blocking`, which waits on a condition variable that nothing will ever pump (`include/Void/Async/TaskScope.hpp:289-303`). Component `stop()` tasks also need pumping.
|
||||
- **What happens:** destroying an unstopped embedded Host that has a business task or any component hangs forever.
|
||||
- **Second problem:** the terminate check uses `executor->is_executor_thread()`, which is true inside an ordinary `manual.drain()` of the borrowed executor.
|
||||
- **Fix:**
|
||||
- `shutdown_blocking` returns `invalid_argument` when the executor has no background workers, as `flush_blocking` already does.
|
||||
- `~HostCore` with a `ManualExecutor` pumps, following the `~TaskScope` pattern (`TaskScope.hpp:562-575`).
|
||||
- The terminate check applies only to owned executors.
|
||||
- `shutdown_pumping` in managed mode returns `invalid_argument`, because the reactor owns polling and `pump_until` would just get `busy`.
|
||||
|
||||
**N3 (P2, inferred spin plus one hang path): who polls during shutdown is never specified.**
|
||||
- **Spins:**
|
||||
- `busy` returns immediately, so the B3 reactor loop (`poll_once(5ms)`), A4's `Driver::run` and `pump_until` spin hot while `advance_shutdown` holds poll ownership.
|
||||
- The 1.x early return once stopping is set (`EpollDriver.cpp:1057-1059`) skips `epoll_wait`, so loops spin throughout the shutdown window.
|
||||
- After `shut_down_`, `poll_once` returns 0 immediately, so the reactor spins until phase 9 joins it.
|
||||
- **Hang:** the addendum doesn't say where file completions are drained relative to that early return. If the drain sits after `epoll_wait` (the natural place, next to `drain_wake_fd`), in-flight file requests are never retired. `quiescent()` then never becomes true, `advance_shutdown` never completes, and `teardown_blocking` in `~Driver` hangs.
|
||||
- **Undefined behaviour:** `try_lock` on `poll_mu_` by the thread that already owns it, reachable through an inline resume inside a turn.
|
||||
- **Fix, one sentence each:**
|
||||
- Cancels, controls and file completions drain before any stop-flag return.
|
||||
- Say whether `begin_shutdown` sets `stopping_`.
|
||||
- Library loops wait up to `max_wait` (stop-aware) on `busy` and exit on `shutdown_complete()`.
|
||||
- Choose one: phase 8 stops and joins the reactor before `advance_shutdown`, or the reactor exits on completion.
|
||||
- `advance_shutdown` either releases `poll_mu_` between its 1 ms slices or makes the other pollers park.
|
||||
- `poll_once` checks the thread-local polling marker before `try_lock`.
|
||||
- Define what `advance_shutdown` returns when its stop token fires.
|
||||
|
||||
**N4 (P2, inferred double close / use-after-free): the File fd state machine is incomplete (F13).**
|
||||
- **Missing invariants:**
|
||||
- The transitions between handle drop, in-flight count and `close_pending` happen under one mutex, so exactly one close is enqueued.
|
||||
- A File that outlives shutdown completion or `~Driver` holds an fd that teardown closed. A later `~File` or `close_and_join` must not close that number again, because it may now belong to someone else. Reads and writes must return `closed` without a syscall.
|
||||
- `close_and_join` after the workers are joined has nothing to run the close on ("close always executes on a worker or `run_file_work`").
|
||||
- `~File` must wake through a weak→strong backend lock or the worker condition variable, never the raw waker.
|
||||
- Reserved close capacity is not stated as bounded.
|
||||
- **Fix:**
|
||||
- Give `FileState` an `open → closing → closed` state under the pool mutex; whoever closes sets `closed`.
|
||||
- After completion, `close_and_join` returns at once and `~File` does nothing.
|
||||
- Files count against `max_descriptors`, which bounds the reserved close capacity.
|
||||
- Preallocate the close node inside `FileState`, so the `noexcept` `~File` path never allocates.
|
||||
|
||||
**N5 (P2, inferred use-after-free; affects B1, which is running): channel timer callbacks vs waiter nodes.**
|
||||
- **Where:** `M-TIME-03.md:63-65,89,113` says callbacks fire outside the lock after pending→fired, and that `cancel()` returning true means "never runs". It does not cover a callback that has fired and is still running. Addendum F7 puts waiter nodes in coroutine frames and has the timer callback "do nothing if claimed".
|
||||
- **What happens:** a sender claims the waiter, the receiver resumes and its `cancel()` returns false, its frame is destroyed, and the in-progress callback then reads the dead node.
|
||||
- **Fix:**
|
||||
- B1, documentation only: `cancel()==false` does not mean the callback has finished. B1 may continue.
|
||||
- A2: the timer callback captures shared waiter state, or the channel plus a waiter id that it looks up under the channel lock. It must never hold a raw pointer into a frame.
|
||||
|
||||
**N6 (P2, inferred use-after-free): `~EventBus` on an executor thread doesn't wait (F12).**
|
||||
- **Where:** `Subscription` holds a raw `EventBus*` (`include/Void/Async/EventBus.hpp:137-146`), and handlers commonly capture `EventBus&` to publish follow-up events.
|
||||
- **What happens:** frames already queued keep delivering after the destructor returns, and any handler that touches the bus hits a dead object.
|
||||
- **Fix:** `~EventBus` gates every admitted-but-not-started delivery on every thread before it returns. Either wait for callbacks running on other threads (excluding the current one, via a thread-local depth) or document that residual.
|
||||
|
||||
**P3 (each changes one spec line)**
|
||||
1. Add phase 2 to the list of phases that return incomplete when the call deadline expires. Today a caller deadline shorter than the drain grace is ambiguous.
|
||||
2. The owned BudgetResource, executor and driver objects must live until `~HostCore`.
|
||||
- The budget test reads `memory_budget()` and `admitted()` after `complete`, and `admitted()` needs `ThreadExecutor`, not `Executor*`.
|
||||
- A `BufferLease` that outlives its resource is a use-after-free.
|
||||
3. Signal gate:
|
||||
- The borrowed `signal_gate` must outlive the Host.
|
||||
- `uninstall` must be idempotent or tracked, because failed-start cleanup already uninstalls.
|
||||
- The off-owner signal test must restore the owner's mask and drain SIGUSR2 at the end.
|
||||
4. MIGRATION and Runtime.md:
|
||||
- Add "concurrent `poll_once` returns `busy`" and "`~Driver` on a file worker or inside a poll turn terminates" to MIGRATION.
|
||||
- `Runtime.md` is missing the `TimerQueue*` parameter on `shutdown_pumping`.
|
||||
5. The D1 seam clock must be armed after submission. `submit_io` reads the clock at `:503`, and a stop there takes the pre-queue path, so D1 never reproduces.
|
||||
6. Use `G(std::random_device{}())` (parentheses). Braces are a narrowing error for engines whose seed type is narrower than `unsigned`. Documentation-only for A1.
|
||||
7. Moved-from Host and HostCore:
|
||||
- The moved-from rules omit the reference accessors (`options`, `lifecycle_plan`, `embedded_resources`).
|
||||
- HostCore must not hold pointers into Host members, because Host is movable.
|
||||
8. Carry D-W11-06's condition into A3: a throwing `error_sink` is caught and counted. Add a B3 stop-and-report rule for IO edits.
|
||||
9. Teardown with an already-joined `ThreadExecutor` resumes continuations inline inside the shutdown's own poll turn. Either dispatch after releasing ownership, or document that the executor must not be joined before the Driver is torn down (the Runtime order already satisfies this).
|
||||
|
||||
## Re-review scope
|
||||
Only the amended text for N1–N6 and the P3 lines above. This can be checked on the B2, B3, B4, A2 and A3 task specs; no new planner round is needed.
|
||||
|
||||
## Checks not run
|
||||
- No builds, tests or compile probes. Everything above comes from direct `sed`/`rg` reads. No Serena or codebase-memory coverage checks.
|
||||
- Not read: `EpollDriver.cpp:1475-1640` (the rest of `drive_read` and `drive_write`), `ThreadPool.hpp`, `ResourceGraph.hpp`, the `RuntimeHost.cpp` tests, and TASKS/STATE.
|
||||
- `M-TIME-03.md` and `M-FUNCTIONAL-03.md` were only partly read.
|
||||
- A new commit, `a8a9249` (D-039), landed during the review. I checked it: it does not touch the W11 contracts.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Wave 11 PREFLIGHT re-review of the contract addendum
|
||||
|
||||
Task ID: W11-PREFLIGHT-2
|
||||
Role: opus-reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from `main`
|
||||
`38436b1`. Uncommitted root prep: workflow docs, roadmap area-plan edits
|
||||
(`docs/roadmap/{modules/Functional.md,subsystems/IO.md,subsystems/Runtime.md,MIGRATION.md}`), and new
|
||||
enumerators `AsyncErrorCode::closed=9` (→cancelled), `IoErrorCode::sync_failed=12` (→io),
|
||||
`RuntimeErrorCode::{self_join=8, shutdown_incomplete=9}` (→conflict). Untracked user files
|
||||
(`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`, `.vbs/`, dotfiles) are not inputs.
|
||||
- Baseline `38436b1`: `VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed.
|
||||
- First PREFLIGHT verdict CHANGES_REQUIRED: `docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md`.
|
||||
Original plan: `W11-PLAN-OUTPUT.md`. Planner addendum answering it: `W11-PLAN-REV1-OUTPUT.md`.
|
||||
Root disposition: `docs/agent-workflow/DECISIONS.md` D-038.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Fresh, independent verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the
|
||||
addendum plus root doc edits resolve findings F1–F13 and the P3 list without introducing new
|
||||
defects, so implementation specs can be written. Severity-ranked findings for anything still
|
||||
open or newly introduced.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In scope (from the first review's re-review scope): revised S-IO-03, S-IO-04, S-RUNTIME-03
|
||||
contracts (F1–F6, F9, F13); AsyncChannel, Retry, EventBus, TimerQueue invariants (F7, F8,
|
||||
F12); area-plan/MIGRATION edits (F10); the three planner adjustments (signal adapter closes
|
||||
fd off-owner; syscall shim exception; Observable FIFO ordering change). Also check the
|
||||
`poll_once` concurrent-caller choice (`busy`), the `wake_closed_` atomic argument, the
|
||||
`FileState` close-request reserved capacity, and `ThreadExecutor::idle()` use in phase 9.
|
||||
Non-goals: re-reviewing parts confirmed sound in the first review, style, other waves.
|
||||
|
||||
## 4. Files to inspect
|
||||
`docs/agent-workflow/tasks/{W11-PLAN-OUTPUT,W11-PREFLIGHT-OUTPUT,W11-PLAN-REV1-OUTPUT}.md`,
|
||||
`docs/agent-workflow/DECISIONS.md` (D-038), `git diff` of the root prep, and source cited by
|
||||
the addendum: `src/IO/EpollDriver.cpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`,
|
||||
`include/Void/IO/Detail/Backend.hpp`, `include/Void/Async/{Executor,Operation,TaskScope,EventBus,Observable}.hpp`,
|
||||
`include/Void/Runtime/{Host,Options}.hpp`, `src/System/SignalWatcher.cpp`, `src/IPC/Session.cpp`
|
||||
(poll_once result use), `include/Void/Memory/BudgetResource.hpp`.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Allowed commands: read-only `git`, `rg`, `ls`, `sed -n`, Serena/codebase-memory read tools; optional
|
||||
probes only under `/tmp/void-w11-preflight2-probe`. A root subset build runs in
|
||||
`/tmp/void-w11-prep`; do not touch it.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. For each F1–F13 and P3 item: state RESOLVED / PARTIAL / UNRESOLVED with evidence.
|
||||
2. Look for new hazards the resolutions introduce (e.g. raw waker pointer lifetime, `busy` from
|
||||
`poll_once` breaking existing callers that loop on it, reserved close capacity unbounded,
|
||||
phase-9 idle wait vs inline-resume after join, `~HostCore` unbounded shutdown on destruction).
|
||||
3. Check the area-plan edits are consistent with the addendum and with D-001..D-038.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Not applicable for new authorship: review the addendum's signatures as written.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
A1 (M-FUNCTIONAL-03) and B1 (M-TIME-03 Timer) may be dispatched in parallel with this review
|
||||
(D-038); report any finding affecting F8/F12 explicitly so root can correct them.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Same list as the first PREFLIGHT: fd reuse, signal masks, partial start, TaskScope destructor,
|
||||
ManualClock + blocking waits, inline resume after join, retained buffers, tombstones.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Verdict with justification. 2. Each F1–F13/P3 item marked RESOLVED/PARTIAL/UNRESOLVED.
|
||||
3. New findings have severity, location, trigger, impact, evidence, recommendation.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only inspection, e.g. `git diff -- docs/roadmap include/Void`, `rg -n "poll_once\(" src include`.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, commits or network; no spawning. Mark INSUFFICIENT_EVIDENCE rather than guess.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038 under user decisions D-027/D-031. Technical check only.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; verdict; per-item status table; new findings P0→P3; checks not run. Compact.
|
||||
@@ -0,0 +1,163 @@
|
||||
# W11-PREFLIGHT output (opus-reviewer, 2026-11-29)
|
||||
|
||||
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
|
||||
|
||||
**Task:** W11-PREFLIGHT. **Verdict: CHANGES_REQUIRED.**
|
||||
|
||||
The plan's direction is sound. The layering holds, no `INTERNAL_DEPS` change is needed, no two packages own a path at the same time, the gates G1–G5 contain no cycle, and almost every baseline claim matches the source. It is not yet complete enough to write specs from. There is one P1: the plan has no rule for what happens to driver teardown on a worker or poll thread. Eleven P2s need a fix or an explicit risk acceptance before dispatch.
|
||||
|
||||
Paths below are relative to `/home/faumaray/Projects/VoidLibrary`. "Plan" means `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`.
|
||||
|
||||
## P1
|
||||
|
||||
**F1. S-IO-03: no destructor or teardown-thread rule once the driver owns threads.** (Inferred defect if the spec is written as the plan reads.)
|
||||
- **Location:** plan :542-548. `Driver::~Driver` at `src/IO/EpollDriver.cpp:1737-1742` and `~EpollBackend` at :953-963 both call `shutdown_and_join()` and ignore the result.
|
||||
- **Evidence:**
|
||||
- `Driver::poll_once` (:1843-1847) does not hold its own reference to the backend during a turn.
|
||||
- Streams hold only a `weak_ptr` to the backend (`include/Void/IO/Detail/Backend.hpp:85-125`). Stop forwarders lock it briefly (:279-285). So the last owning reference can drop on any thread.
|
||||
- **Trigger:** the plan makes `shutdown_and_join` return `self_join` on a worker or during poll dispatch, and makes it block until the poll turn and the workers finish. Then either:
|
||||
- `~Driver` or `~EpollBackend` runs on a file worker or the poll thread. The self_join result is ignored, and a joinable `std::thread` is destroyed or joins itself, which calls `std::terminate`. Or the poll turn waits on itself and deadlocks.
|
||||
- The last backend reference drops on a worker or poller.
|
||||
- Also, after `ThreadExecutor::join` the plan resumes coroutines inline, so a coroutine can run on a file worker and destroy the `Driver` or a `File` there.
|
||||
- **Impact:** abort or deadlock on the main teardown path every 1.x IO user takes (IPC, SystemAsync, CryptoAsync, Storage, Runtime).
|
||||
- **Fix:** add mandatory invariants to the S-IO-03 spec:
|
||||
- Only `~Driver` does a blocking teardown. It defines what happens on a worker or poll thread: a documented programmer error such as `terminate`, or deferring the join to a safe owner.
|
||||
- `~EpollBackend` and `~FileWorkers` never block and never destroy a joinable thread.
|
||||
- Workers and pollers never hold the last owning reference to the backend, or the pool's state is owned separately.
|
||||
- Tests: Driver destroyed inside a coroutine resumed by poll dispatch, and inside a worker completion.
|
||||
|
||||
## P2
|
||||
|
||||
**F2. S-IO-03 shutdown step 5 opens a new fd-reuse hazard.**
|
||||
- **Location:** plan :547, "close the fds, epoll and eventfd".
|
||||
- **Evidence:** in 1.x, `epoll_fd_` and `wake_fd_` are closed only in `~EpollBackend` (:953-963). `wake()` reads a plain `int` and writes to it (:1033-1042). `enqueue_cancel` (:153-166) and `request_stop` call `wake()`.
|
||||
- **Trigger:** S-RUNTIME-03 phase 7 shuts the driver down, then phase 8 stops the reactor, which typically calls `wake()`. Late stop forwarders do the same. The write lands on a closed, possibly reused, integer fd. That is also a data race that TSan will report.
|
||||
- **Fix:** keep epoll/eventfd closure in the backend destructor (1.x placement), or guard `wake()` with a lock and a closed flag. After shutdown, `poll_once` must return before touching any fd. 1.x already returns early once `stopping_` is set (:1056-1058).
|
||||
|
||||
**F3. S-RUNTIME-03 contradicts itself on exporter vs executor order.**
|
||||
- Plan :729-730 joins the executor (phase 8) before dropping component references (phase 9).
|
||||
- The test at :742 asserts `exporter_destroyed < executor_joined`.
|
||||
- **Fix:** drop exporter/component references after their stop finishes and before reactor/executor join (this matches the row name), or change the assertion. Decide in the spec.
|
||||
|
||||
**F4. S-RUNTIME-03: a repeated join after expiry has no budget.**
|
||||
- Plan :719 fixes the total deadline at the first `begin_shutdown`. Plan :734 says the next call continues.
|
||||
- After the first expiry, every later `shutdown_blocking` has zero wait budget. Thread joins and executor progress need real waiting, so "release → join again → complete" (:742) becomes a busy loop or a flaky test.
|
||||
- **Fix:** after a total-budget expiry, later calls use the caller's new deadline. Expired phase deadlines (drain, flush) stay expired. Also say explicitly that an incomplete phase stops the sequence; plan :728 "if incomplete, retain it" is ambiguous.
|
||||
|
||||
**F5. Host lifecycle holes.**
|
||||
- **Move-assignment:** `Host& operator=(Host&&) = default` (`include/Void/Runtime/Host.hpp:91`) destroys the overwritten state through the `unique_ptr<HostCore>` without running `~Host`. If teardown lives in `~Host` (plan :661), move-assigning over a started Host leaks joinable threads, and `std::thread`'s destructor terminates. Put teardown in `~HostCore` or write a custom move-assignment.
|
||||
- **Moved-from Host:** accessors like `options()` and `state()` need defined behaviour when the core is null.
|
||||
- **`~Host` on a Runtime worker:** behaviour is unspecified. The roadmap calls it a detected programmer error.
|
||||
- **`~Host` off the owner thread:** a non-owner destructor cannot restore the mask, and `SignalWatcher` silently skips the restore off-thread (`src/System/SignalWatcher.cpp:27-37`). The plan (:731) must say whether the gate is leaked or uninstalled without a mask restore.
|
||||
|
||||
**F6. Embedded mode would shut down borrowed resources.**
|
||||
- Phase 7 calls `driver->shutdown()` and phase 8 joins the executor unconditionally (plan :728-729). In embedded mode both are borrowed (`include/Void/Runtime/Host.hpp:31-56`). The roadmap says borrowed resources must outlive final cleanup.
|
||||
- **Fix:** tear down by `ResourceOwnership`. Embedded `shutdown_pumping` drains only the business scope and components, and must drive IO and timers through `pump_until`; `TaskScope::join_pumping` never polls IO (`include/Void/Async/TaskScope.hpp:639-647`).
|
||||
|
||||
**F7. AsyncChannel: hand-off vs stop/close arbitration is unspecified (value-loss risk).**
|
||||
- Plan :327-344 states only the outcomes.
|
||||
- **Fix:** mandate that a waiter is claimed under the channel lock before a value moves; the stop callback must take the same lock to remove a waiter; a value is never in limbo; a sender gets either success or its value back, exactly once.
|
||||
- Add a receiver-stop test (no value lost).
|
||||
|
||||
**F8. Retry: the default URBG is deterministic.**
|
||||
- Plan :102, :137 and :228 default-construct `std::mt19937_64`, which always starts from the same fixed seed. Every process then draws the same jitter, which defeats jitter's purpose.
|
||||
- House convention seeds from `random_device` unless a deterministic seed is given (`include/Void/Functional/Retry.hpp:87`; `include/Void/Resilience/AsyncPolicy.hpp:487,525-529`).
|
||||
- **Fix:** seed from `random_device` by default; tests pass a seeded engine.
|
||||
|
||||
**F9. D-W11-05 routing: sonnet takes the riskiest code.**
|
||||
- A4 (sonnet) rewrites the bounded, repeatable shutdown, poll-owner exclusion, manual-clock-sliced waits and `run()` concurrency in the same `src/IO/EpollDriver.cpp` B2 just changed. That is astra-level work.
|
||||
- **Fix:** B2 delivers an internal deadline-aware shutdown/poll-owner primitive; A4 only adds the public wrappers, `pump_until` and tests. Or route that part to opus.
|
||||
|
||||
**F10. C-13: area plans must be updated before parallel work.**
|
||||
- The plan changes contracts in area plans:
|
||||
- Functional.md: the clock/sleeper adapter moves out of the separate Time header (D-W11-02).
|
||||
- Runtime.md: awaited shutdown becomes blocking/polling APIs; `file_workers` authority.
|
||||
- IO.md: the "driver thread" model.
|
||||
- Several row prerequisites change.
|
||||
- `docs/roadmap/ARCHITECTURE.md` C-13 (:246-252) requires the decision ledger and area plans to be updated before parallel implementation. `docs/roadmap/**` is missing from the root-owned list (plan :786-790). Add a root step before dispatch.
|
||||
|
||||
**F11. Within-step start failures are not covered (S-RUNTIME-02 acceptance).**
|
||||
- The `before_step` hook (plan :652, :686) only injects failure between steps.
|
||||
- Not specified or tested:
|
||||
- partial failure inside `start_file_workers()`
|
||||
- the reactor thread constructor throwing `std::system_error`
|
||||
- `std::thread` throwing inside `ThreadExecutor::start`
|
||||
- the stop budget for components during failed-start cleanup.
|
||||
- **Fix:** add an IO fault hook and `io_file_workers_partial_start_failure_joins_started`, catch thread-creation exceptions, and bound the cleanup.
|
||||
|
||||
**F12. Async lifetimes of borrowed objects.**
|
||||
- **EventBus (Injected mode):** `~TaskScope` skips joining when it runs on an executor thread (`include/Void/Async/TaskScope.hpp:562-575`). If `~EventBus` runs on a worker, dispatch frames can still touch the destroyed bus. Dispatch must reference only a shared core, or this must be a documented error. `flush()` semantics in Injected mode are also unspecified.
|
||||
- **TimerHandle:** move-only and may outlive its `TimerQueue` (plan :198-199). It needs shared control state.
|
||||
- **Bounded `parallel_for`:** "All started runners are always joined" (plan :358). Runners that were queued but not yet started would later touch the caller's stack. Either wait for all submitted runners (and document that nested use on the same pool is unsupported) or put runner state, including the copied `F`, in shared ownership.
|
||||
|
||||
**F13. File lifetime is unspecified.**
|
||||
- `~File` with requests still in flight must defer the fd close until they drain; otherwise the fd can be reused while a worker still uses it.
|
||||
- `File::close_and_join` on expiry should return `incomplete_shutdown` (exists at `include/Void/IO/Types.hpp:32`) and keep the fd and buffers.
|
||||
- The roadmap says workers keep the descriptor until the syscall returns.
|
||||
|
||||
## P3
|
||||
- **`retry_blocking` signature:** the template parameters have no defaults (plan :139-141), so `retry_blocking(spec, fn)` cannot deduce `NowFn` and the rest from the defaulted argument. Add the defaults.
|
||||
- **Observable/Signal:** queuing nested `(old, new)` notifications and arguments requires copyable `T`/`Args`, which breaks 1.x compile for move-only types (D-029). Also state "state restored" precisely: the value stays new, as in 1.x.
|
||||
- **S-IO-03 downstream build** (plan :576): omits CryptoAsync, Runtime and ConfigurationAsync, which also depend on IO.
|
||||
- **Error kinds:** Runtime `shutdown_incomplete` maps to `timeout`, but IO `incomplete_shutdown` maps to `conflict` (`include/Void/IO/Types.hpp:50-52`). Align them.
|
||||
- **D1 regression test needs a seam:** the double release isn't visible through the public API. Suggested deterministic trigger: an injected clock whose `now()` requests stop. That call happens between the step-1 drain and the event dispatch (:1083).
|
||||
- **Mock reactor spin:** the mock `poll_once` ignores `max_wait` (:739-740), so a Runtime reactor on a mock driver busy-spins under TSan.
|
||||
- **Host business scope:** the default `stop_on_first_error=true` (`include/Void/Async/TaskScope.hpp:32`) means one failing business task stops all of them, against the roadmap's per-component failure policy.
|
||||
- **MIGRATION records needed** ("observable behavior" row): `shutdown_and_join` now blocks and joins; `validate_limits` rejects `max_file_queue==0`; Sync EventBus becomes snapshot dispatch; legacy `parallel_for` waits for all tasks.
|
||||
- **Unspecified:** behaviour of concurrent `poll_once` callers; who owns IO files after G5; a stop-and-report rule if B3 or B4 needs an IO edit; how Runtime detects that it is running on a file worker.
|
||||
- **ThreadExecutor:** `join()` can drain forever if `post()` keeps re-posting after close. `~ThreadExecutor` without `join` is unspecified.
|
||||
|
||||
## D1 claims (all confirmed)
|
||||
- **(a) Unconditional release — CONFIRMED.** `complete_op_and_collect_tickets` releases at :448, even though `retire_op_locked` is idempotent (:391-394). `release_backend_ref` cannot be called twice safely (`include/Void/Async/Operation.hpp:185-193`); the count underflows.
|
||||
- **(b) Cancel path doesn't skip finished operations — CONFIRMED** (:1332-1351). The mock path does skip them (:770-781).
|
||||
- Precise trigger: a stop arrives after the start-of-turn drain (:1053) while `drive_read`/`drive_write` completes the operation (including their own stop check, :1453-1458 and :1527-1535). The end-of-turn drain (:1173) then releases a second time.
|
||||
- Impact the plan omits: if the waiting coroutine has not suspended yet, `try_arm_suspend` sees a non-zero count and the coroutine hangs forever. Otherwise the counter is silently corrupted.
|
||||
- **(c) Syscalls outside `mu_` without `in_execution` — CONFIRMED.** `::read` at :1466; `::send` and `::write` at :1549 and :1560. `in_execution` is used only by the mock (:653-671, 758, 774, 791, 847-850).
|
||||
- **(d) Cross-thread shutdown — CONFIRMED** (:1179-1238).
|
||||
- It finishes operations regardless of whether a syscall is in progress (:1186-1206). The caller can then free its buffer while `::read` is still writing into it.
|
||||
- It closes the fd (:1221 → :363) while the poller still holds the integer it read at :1151, so the number can be reused.
|
||||
- Additional facet: when `~Driver` is the shutdown path, the backend object itself can be destroyed mid-turn (F1).
|
||||
- **"No test covers it" — CONFIRMED.** `tests/standalone/IO/IoDriver.cpp:458-508` cancels a read that never becomes readable and joins the poller before teardown.
|
||||
|
||||
## Other source claims
|
||||
- **ManualExecutor bound — CONFIRMED.** `post` counts without a check (`include/Void/Async/Executor.hpp:128-135`); `run_one` decrements before resuming (:216-228).
|
||||
- **SignalWatcher — CONFIRMED** (`include/Void/System/SignalWatcher.hpp:13-15`; `src/System/SignalWatcher.cpp:27-37,74-90`).
|
||||
- **Host movable, default destructor, worker count always 0 — CONFIRMED** (`include/Void/Runtime/Host.hpp:88-92,173`).
|
||||
- **Threads flags — CONFIRMED** (`tests/package/InstalledComponents.cmake:73-79,104-112`; `cmake/VoidConfig.cmake.in:97`).
|
||||
- **Minor:** `tests/standalone/Async/OperationScope.cpp:135` is not a thread-backed executor; it wraps a ManualExecutor.
|
||||
|
||||
## D-W11-01..15
|
||||
|
||||
| ID | Recommendation |
|
||||
| --- | --- |
|
||||
| D-W11-01 | Accept |
|
||||
| D-W11-02 | Accept, and update Functional.md (F10) |
|
||||
| D-W11-03 | Accept; label the pinned test as defect characterization and record it for Wave C |
|
||||
| D-W11-04 | Accept. System requires Threads, so a Runtime→System edge would also break RuntimeOnly. Add the off-owner rules from F5 |
|
||||
| D-W11-05 | Modify (F9) |
|
||||
| D-W11-06 | Accept, provided a throwing `error_sink` is caught and counted and Sync propagation is unchanged; record the change |
|
||||
| D-W11-07 | Accept |
|
||||
| D-W11-08 | Accept, provided IOOnly/RuntimeOnly start a real worker thread with Threads disabled; record the libc-with-integrated-pthreads assumption (IO already relies on it at `src/IO/EpollDriver.cpp:47`) |
|
||||
| D-W11-09 | Accept |
|
||||
| D-W11-10 | Accept; it fixes a real use-after-free when caller-stack captures outlive a throw. Record the timing change |
|
||||
| D-W11-11 | Accept, plus partial-start semantics (F11) |
|
||||
| D-W11-12 | Accept (`max_output_*` unused in `src/Net`, confirmed) |
|
||||
| D-W11-13 | Accept; record that the C-05 defaults are deferred |
|
||||
| D-W11-14 | Accept; document that nothing polls a TimerQueue under managed Runtime, so channel deadlines and `retry_async` need caller-driven polling or `pump_until` |
|
||||
| D-W11-15 | Accept; align error kinds (P3) |
|
||||
|
||||
## Acceptance sentences not covered
|
||||
- **S-IO-04:** "no IO→Runtime/Net dependency" has no check. Add `rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO` (expect no output) plus a diff of `src/IO/module.cmake`.
|
||||
- **S-RUNTIME-02:** "failure at every creation/start step" only covers failures between steps (F11).
|
||||
- **S-RUNTIME-03:** "exporter-before-executor ordering" contradicts the phase order (F3). "Budget accounting" is ambiguous: only the shutdown budget is tested, not memory or admission permits.
|
||||
- **M-ASYNC-04:** no test for receiver-side cancellation.
|
||||
- **M-ASYNC-05:** "no captured state in use after join" is tested only for Injected mode, not the legacy Async or Sync modes.
|
||||
- M-FUNCTIONAL-03, M-TIME-03 and S-IO-03 are fully mapped.
|
||||
|
||||
## Checks not run
|
||||
- No builds or compile probes; every plan command is unverified.
|
||||
- No Serena or codebase-memory coverage checks; all evidence comes from direct `sed`/`rg` reads.
|
||||
- The advisor call timed out.
|
||||
- Not inspected: the SystemAsync `ProcessManager` shutdown path, IPC/Storage/CryptoAsync internals, `docs/roadmap/VALIDATION.md`, `docs/roadmap/PERFORMANCE.md`.
|
||||
|
||||
**Re-review scope:** the revised S-IO-03, S-IO-04 and S-RUNTIME-03 contracts (F1–F6, F9, F13), the AsyncChannel, Retry, EventBus and TimerQueue invariants (F7, F8, F12), and the area-plan updates (F10).
|
||||
@@ -0,0 +1,107 @@
|
||||
# Wave 11 PREFLIGHT review of the execution-path plan
|
||||
|
||||
Task ID: W11-PREFLIGHT
|
||||
Role: opus-reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from
|
||||
`main` `38436b1`. Only workflow docs changed so far (uncommitted): `docs/agent-workflow/{STATE,TASKS,DECISIONS}.md`,
|
||||
`docs/agent-workflow/tasks/W11-*.md`. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`,
|
||||
`.serena/`, `.vbs/`, dotfiles) are not inputs; never read or quote them.
|
||||
- Observed baseline: full RelWithDebInfo `-Werror` build of `38436b1` in `/tmp/void-w11-base`:
|
||||
`VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed; `ctest` 2/2 passed.
|
||||
- Subject: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (opus-planner output for
|
||||
`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`,
|
||||
`S-RUNTIME-02`, `S-RUNTIME-03`). Assignment it answered: `W11-PLAN.md`. Root decisions D-033..D-037 in
|
||||
`docs/agent-workflow/DECISIONS.md`. Contracts C-01..C-14 in `docs/roadmap/ARCHITECTURE.md`.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Independent PREFLIGHT verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the
|
||||
plan's contracts, ordering gates, ownership partition and failure semantics are correct and
|
||||
complete enough to write implementation specs. Deliver severity-ranked findings (P0–P3) with
|
||||
location, trigger, impact, evidence and recommended correction, plus a disposition
|
||||
recommendation for each open decision D-W11-01..D-W11-15.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In scope: contract soundness, missing or contradictory invariants, cross-file obligations,
|
||||
hidden dependencies, layering violations, 1.x compatibility (D-029), testability of every
|
||||
acceptance sentence, and the plan's factual claims about current source (especially the
|
||||
claimed epoll defects "D1" in `src/IO/EpollDriver.cpp`, the `ManualExecutor` bound,
|
||||
`SignalWatcher` behavior, `Host` movability, and installed-consumer Threads flags).
|
||||
Non-goals: writing code or specs, reviewing unrelated modules, style nits, re-planning
|
||||
other waves. Do not agree with the planner by default; verify claims in source.
|
||||
|
||||
## 4. Files to inspect
|
||||
- `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (subject) and `W11-PLAN.md` (its brief).
|
||||
- Roadmap rows/plans: `docs/roadmap/modules/{Functional,Time,Async}.md`,
|
||||
`docs/roadmap/subsystems/{IO,Runtime}.md`, `docs/roadmap/{DEPENDENCIES,ARCHITECTURE,MIGRATION}.md`.
|
||||
- Source cited by the plan: `include/Void/Functional/Retry.hpp`, `include/Void/Time/Clock.hpp`,
|
||||
`include/Void/Async/{Executor,Operation,TaskScope,ThreadPool,Channel,ParallelFor,EventBus,Observable}.hpp`,
|
||||
`include/Void/Async/Detail/Types.hpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`,
|
||||
`include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `include/Void/Runtime/*.hpp`,
|
||||
`include/Void/System/SignalWatcher.hpp`, `src/System/SignalWatcher.cpp`,
|
||||
`include/Void/Resilience/AsyncPolicy.hpp`, `src/SystemAsync/AsyncProcess.cpp`,
|
||||
`tests/package/InstalledComponents.cmake`, `tests/CMakeLists.txt`, `CMakeLists.txt`, `cmake/Module.cmake`,
|
||||
`src/Testing/Runner.cpp` (filter semantics), existing tests in `tests/standalone/{Functional,Async,IO,Runtime}/`.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Allowed commands: read-only `git`, `rg`, `ls`, `wc`, `sed -n`, Serena/codebase-memory read tools.
|
||||
Optional tiny compile probes only under `/tmp/void-w11-preflight-probe` (never in the repo);
|
||||
`dev cpp-gcc ...` works only unsandboxed. No repository writes, no commits.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. Verify every baseline claim the plan relies on against source (cite `path:line`).
|
||||
2. For each NEW interface, check: invariants stated, ownership/lifetime of borrowed objects,
|
||||
exactly-one-terminal-result, stop/expiry/completion races, callbacks outside locks,
|
||||
overflow-safe time arithmetic, bounded resources, error mapping into existing domains.
|
||||
3. Check gate order G1..G5 and the A/B partition for overlapping writes, impossible orders,
|
||||
or hidden edges the plan missed (e.g. Runtime needing Timer, Host move with live threads,
|
||||
IO `Types.hpp` edited by both root pre-commit and B2/A4).
|
||||
4. Check layering against `DEPENDENCIES.md` rules 1–2 and D-015 (Functional std-only),
|
||||
and installed consumers IOOnly/RuntimeOnly (`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`).
|
||||
5. Check 1.x compatibility: `JitterMode` relocation, `ExponentialBackoff` users in Resilience,
|
||||
EventBus/Observable behavior changes, legacy `parallel_for` change (D-W11-10).
|
||||
6. Check that each acceptance sentence of the eight roadmap rows maps to at least one
|
||||
deterministic test in the plan.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Not applicable for new authorship: you review the plan's proposed interfaces as written in
|
||||
`W11-PLAN-OUTPUT.md`. Existing contracts: `Void::Functional` error domains (`Error.hpp`),
|
||||
`Async::OperationOptions`/`AdmissionError`/`TaskScope`, `IO::Driver`/`BufferLease`, `Runtime::Host`.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root will convert your verdict into persisted per-package task specs. Blocking findings
|
||||
(P0/P1) must be resolved before dispatch; P2 need fix or explicit risk acceptance.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Pay particular attention to: fd reuse after close during concurrent poll, signal-mask
|
||||
inheritance and pending-signal default action, thread/fd leak on partial start failure,
|
||||
`TaskScope` destructor pumping/blocking, `ManualClock` + blocking waits, coroutine resume
|
||||
on a joined executor, retained buffers after shutdown timeout, unbounded tombstones.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Verdict stated with justification.
|
||||
2. Every finding has severity, location, trigger, impact, evidence, recommendation.
|
||||
3. Each D1 defect claim is CONFIRMED or REFUTED with cited lines.
|
||||
4. Each of D-W11-01..15 has an accept/modify/reject recommendation.
|
||||
5. Uncovered acceptance sentences (if any) are listed per task.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only inspection. Example: `rg -n "release_backend_ref|in_execution" src/IO/EpollDriver.cpp`,
|
||||
`sed -n 430,460p src/IO/EpollDriver.cpp`, `git log --oneline f1f9ba3..HEAD -- include/Void/Async`.
|
||||
Report any probe compile command and its exit status if you run one.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, commits or network. Stop and report INSUFFICIENT_EVIDENCE for any claim you cannot
|
||||
verify rather than guessing. Do not spawn agents.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decision D-034 (Wave 11 scope) under user decisions D-027/D-031. PREFLIGHT is a technical
|
||||
check; it neither approves scope nor authorizes commits.
|
||||
|
||||
## 14. Return format
|
||||
Return task ID; verdict; findings ranked P0→P3 (severity, location, trigger, impact,
|
||||
evidence, recommendation); D1 confirm/refute; D-W11-01..15 dispositions; uncovered
|
||||
acceptance sentences; checks not run. Compact bullets. Do not spawn children.
|
||||
@@ -0,0 +1,186 @@
|
||||
# W11-SPEC-REVIEW-1 output (opus-reviewer, 2026-11-29)
|
||||
|
||||
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
|
||||
|
||||
**Task W11-SPEC-REVIEW-1. Verdict: S-IO-03 is CHANGES_REQUIRED and M-ASYNC-04 is CHANGES_REQUIRED.**
|
||||
|
||||
There are no P0 or P1 findings. Every fix below is added spec text. None needs a re-plan, a change to ownership or reopening a D-W11 decision. Each finding says whether I saw it in the text and code ("observed") or worked out an interleaving ("inferred").
|
||||
|
||||
- **Blocks dispatch:** S-IO-03 S1–S8, plus a root decision on S9. M-ASYNC-04 A1–A3.
|
||||
- **Editorial:** all P3 items. They are clarifications and can be folded into the same edit.
|
||||
|
||||
Spec line numbers refer to `docs/agent-workflow/tasks/S-IO-03.md` and `docs/agent-workflow/tasks/M-ASYNC-04.md` as they are now.
|
||||
|
||||
## S-IO-03 (B2): CHANGES_REQUIRED
|
||||
|
||||
**S1 (P2, inferred): shutdown can be starved by a concurrent poller (§6 l.86-91, l.124-131).**
|
||||
- **Text:**
|
||||
- The spec requires a `std::mutex` acquired with `try_lock` (l.86-87).
|
||||
- While stopping, a turn with no work holds ownership inside `epoll_wait` for up to `max_wait` (l.89-90).
|
||||
- `advance_shutdown` takes ownership only between slices of at most 1 ms (l.125-127), and it must own the poll to close fds (l.131).
|
||||
- **Effect:** a poller loop re-locks within nanoseconds after each `wake()`, so `try_lock` almost never wins. The mandatory test `io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan` (l.211) and a cross-thread 1.x `shutdown_and_join` can stall for seconds or hang.
|
||||
- **Append to Shutdown core:** "Ownership handoff: before each slice `advance_shutdown` sets atomic `shutdown_waiting_` and calls `wake()`. While it is set, `poll_once` on any other thread returns `busy` before `try_lock`, touching no fd and not incrementing `turns`. It is cleared once `advance_shutdown` holds `poll_mu_`. Between slices, after `advance_shutdown` releases `poll_mu_`, other pollers may run turns (R2 N3)."
|
||||
|
||||
**S2 (P2, observed omission): completion order, final drain and fd-close ownership are unstated (l.124-132).**
|
||||
- REV1 F2 says shutdown closes operation and descriptor fds "only after it holds poll ownership" (W11-PLAN-REV1-OUTPUT.md:43). That sentence is missing from the spec.
|
||||
- The step order is not given. Inferred consequence: a completion pushed after the last drain is stranded, because after shutdown `poll_once` no longer touches anything.
|
||||
- **Replace l.131-132 with:** "Order: (1) `begin_shutdown()`. `advance_shutdown` calls it itself, because A4's `shutdown(options)` wraps only `advance_shutdown`. (2) Wait until no queued or active file request and no op `in_execution`. (3) Under `poll_mu_`, run a final drain of cancels, controls, file completions and close waiters. (4) Join workers. (5) Still under `poll_mu_`, close the remaining file fds (mark them `closed` and complete pending `close_and_join` waiters with success), then close op and descriptor fds. (6) Set `shut_down_` (release), then `wake_closed_`. (7) Release `poll_mu_`, then dispatch the tickets (P3-9). `self_join` misuse is detected before any state change. `begin_shutdown` only records intent and wakes the poller; it never completes or dispatches anything (F1(a))."
|
||||
|
||||
**S3 (P2, observed contradiction): l.107-108 has workers re-check expiry with the driver clock at dequeue.**
|
||||
- That conflicts with l.92-94, with D-038 ("file workers never call … user code except the injected syscall shim") and with IO.md:95-96. `MonotonicClock::now()` is injected user code. The D1 seam clock even requests stop from inside `now()`.
|
||||
- **Replace l.107-108 with:** "Expiry is checked with the driver clock in `poll_once`. The epoll wait bound includes the earliest queued-file deadline. At dequeue, a worker checks under the pool mutex, without calling the clock, the request's stop flag and the expired mark set by the last turn. Such a request completes `cancelled`/`timeout` with no syscall."
|
||||
- If the root prefers to keep the worker clock read, declare the clock a second documented exception that must be thread-safe. `ManualClock` is atomic (`Clock.hpp:129`).
|
||||
|
||||
**S4 (P2, observed; the tests cannot assert what they are named for): `DomainOutcomeKind` is not observable.**
|
||||
- `File` returns `Result<…>`, and `Error` carries only status and `system_code()` (`Functional/Error.hpp:136-235`). So `io_file_queued_cancel_not_committed_zero_effects` and `…sync_failed_unknown_errno` (l.202-205) cannot assert `not_committed` or `unknown`.
|
||||
- Also, "via the existing `complete_op_and_collect_tickets` path" (l.95-96) cannot work as is. That function is typed for `Transfer` and hard-codes `cancelled`/`failed` (`EpollDriver.cpp:421-447`).
|
||||
- **Add to §6:** "Observable contract:
|
||||
- Queued stop gives `IoErrorCode::cancelled`; queued expiry gives `IoErrorCode::timeout` (both kIoErrorDomain), with zero shim calls and unchanged file bytes.
|
||||
- Sync failure gives `IoErrorCode::sync_failed` with `system_code()==std::error_code{errno, std::generic_category()}`, matching `errno_code`.
|
||||
- Internally, settle with `try_commit_error(err, not_committed|unknown)`. `Result` does not expose that kind and tests do not assert it.
|
||||
- Retirement uses a retire-once path equivalent to `complete_op_and_collect_tickets`, generalized for `OperationState<void>` and the file outcome kinds."
|
||||
|
||||
**S5 (P2, observed omission plus inferred double close): it is unspecified whether files use the socket slot table (l.101-102, l.115-118).**
|
||||
- The shutdown sweep calls `release_slot_locked(idx, true)` on every in-use slot (`EpollDriver.cpp:1209-1223`), and that closes `slot.fd` (`:362-363`). If an implementer stores the file fd in a slot, the fd gets closed twice.
|
||||
- **Add:** "A File occupies a `DescriptorSlot`. It counts in `active_descriptors_`, is bounded by `max_descriptors`, and `File::id()` is that slot's `DescriptorId`. The slot has `fd = -1` and a file-kind flag, and socket paths (interest updates, `close_fd` controls, stale-event checks, the shutdown sweep) skip it. The file fd lives only in `FileState`."
|
||||
|
||||
**S6 (P2, inferred use-after-free): `~File` after `~Driver` must lock the pool mutex (l.115-123).**
|
||||
- **Add:** "`FileState` holds `shared_ptr<detail::FileWorkerShared>` and `weak_ptr<DriverBackend>`, never raw pool or backend pointers. The raw-context waker is called only by workers, which are joined before the backend is destroyed."
|
||||
|
||||
**S7 (P2, observed plus inferred hang): stop flag and mock held tokens.**
|
||||
- **Shared stop flag:** `request_stop()` already sets `stopping_` (`EpollDriver.cpp:282-286`). If `begin_shutdown`'s idempotence is keyed on that flag (l.124-125), a prior `request_stop()` makes it a no-op. Queued file requests are then never cancelled, and with manual stepping `~Driver` hangs.
|
||||
- **Mock held tokens:** 1.x mock shutdown skips held requests (`:847-851`). The `MockController` dies with the `Driver`, so if teardown waits for those requests it deadlocks.
|
||||
- **Add:** "`request_stop()` == `begin_shutdown()`, with idempotence on a separate `shutdown_begun_` flag. On mock, requests held by a token never block `advance_shutdown`; `finish_*` still completes them, and `teardown_blocking` completes any still held with `IoErrorCode::closed`."
|
||||
|
||||
**S8 (P2, observed ambiguity): the D1 seam test (l.212-213) can fail even with a correct fix.**
|
||||
- An implementation that purges retired ops from `cancel_queue_`, or that reads the clock before the start-of-turn drain, leaves `duplicate_completions_ignored == 0`.
|
||||
- **Add to the D1 bullet (l.82-85):** "Increment `duplicate_completions_ignored` each time a cancel, expiry or shutdown path meets an already-retired op and skips it. Retired ops are not purged from the cancel queue early. A turn's first `clock_.now()` comes after the start-of-turn cancel/control/file drain; the queued-file expiry scan reads the clock only when queued file requests have deadlines."
|
||||
|
||||
**S9 (P2, observed verification gap; needs a root decision): B2 cannot test the bounded primitive it owns.**
|
||||
- `advance_shutdown`'s deadline, stop, report and slice-release behaviour is reachable only as `advance_shutdown(nullopt, {})`, through `shutdown_and_join` and `~Driver` (`Driver.hpp:98-104`, `backend_` is private).
|
||||
- A4 may not edit `EpollDriver.cpp` (REV1:340, G6). A defect found in A4 therefore bounces back to the root.
|
||||
- **Choose one and write it into §10/§14:**
|
||||
- (a) Add a NEW test-only accessor in the `MockController` style.
|
||||
- (b) "B2 lists the unexercised primitive paths. A4's IoShutdown tests are the G4 acceptance gate before B2 is VERIFIED, and fixes found there are root-owned."
|
||||
|
||||
**P3 (editorial):**
|
||||
- **l.20-21:** fix the line citations. `StreamState`'s `weak_ptr` is at `Backend.hpp:80-116` (the file has 118 lines). The stop-forwarder lock is at `EpollDriver.cpp:589-596`.
|
||||
- **l.86-88:** "`busy` only if the marker equals this backend; save and restore it for nested turns of other drivers."
|
||||
- Give the busy test a deterministic hold point: the first poller is parked in a long `epoll_wait` after `turns` has incremented.
|
||||
- Add a test `io_poll_once_reentrant_inline_resume_busy`, using an executor whose `post_completion` resumes inline.
|
||||
- **l.89-90:** append "mock `poll_once` still ignores `max_wait` (REV1 P3)".
|
||||
- **l.92-94:** carve-out: "a Driver API called from a worker is detected (`shutdown_and_join` → `self_join`). This is the only worker-side Driver call, used by `io_file_shutdown_from_worker_self_join`."
|
||||
- **l.99-102:**
|
||||
- Error codes: closed → `closed`, stop → `cancelled`, expired → `timeout` (as `submit_io`, `:495-506`).
|
||||
- Overflow: `offset > OFF_MAX` or `offset+len > OFF_MAX` → `invalid_argument`.
|
||||
- Counting: file requests count in the shared `active_operations_` until poll-turn retirement.
|
||||
- **l.103-105:** "reads are unordered relative to writes".
|
||||
- **l.112-114:**
|
||||
- A second `start_file_workers` → `invalid_argument`.
|
||||
- `file_workers==0` → success with no threads.
|
||||
- After shutdown begins → `closed`.
|
||||
- `run_file_work` while workers run → `busy`.
|
||||
- **l.115-123:**
|
||||
- `close_and_join` waits for (and does not cancel) the file's queued and active requests. Success invalidates the File.
|
||||
- After an expired call, the File is `valid()` but closing. New ops return `closed`, and a repeat call waits.
|
||||
- Document the difference from `ByteStream::close_and_join` (`Stream.hpp:102-120`) (F13).
|
||||
- **l.128:** say exactly `Async::make_async_error(Async::AdmissionError::self_join)`.
|
||||
- **l.131:** add the P3-9 documentation requirement: "the executor must outlive the Driver; an owned executor must not be joined before Driver teardown."
|
||||
- **l.161-162:** `read_exact_at`/`write_all_at` mirror `Stream.hpp:126-180` with the offset advancing and one deadline. A 0-byte pwrite with bytes remaining returns an error; it must not loop.
|
||||
- **l.165-166:**
|
||||
- Flag map: RDWR/WRONLY/RDONLY; neither read nor write → `invalid_argument`; `truncate` requires write; `exclusive` requires create; always `O_CLOEXEC`; runs on the caller's thread.
|
||||
- `adopt_file_fd` takes ownership only on success.
|
||||
- **l.173:** the shim must outlive Driver teardown.
|
||||
- **§10:** add tests for EINTR via the shim, zero-length/overflow/`max_file_queue==0`, files counting against `max_descriptors`, a second start, and `poll_once` after shutdown returning 0.
|
||||
- **§5/§10:** `IoFile.cpp` may include only Void/{IO, Async, Time, Memory, Functional, Core, Testing} headers, or it is silently skipped (`tests/CMakeLists.txt:12-41`). `ScopedTempDir` is local to the CryptoAsync test file.
|
||||
|
||||
## M-ASYNC-04 (A2): CHANGES_REQUIRED
|
||||
|
||||
**A1 (P2, observed): "`-Werror` clean" is never actually checked (l.174, §11).**
|
||||
- The warning flags are `PRIVATE` and apply only to modules that have `.cpp` sources (`cmake/Module.cmake:176-178`). `src/Async` holds only `module.cmake`.
|
||||
- `VoidTests` gets no `-W` flags (`tests/CMakeLists.txt:113-123`; `cmake/VoidTesting.cmake` sets no compile options).
|
||||
- Sanitizers do reach the tests: they are `PUBLIC` through `Void::Testing` (`Module.cmake:184-209`), so the TSan and ASan runs are valid.
|
||||
- **Add to §11** (and to S-IO-03 for `IoFile.cpp`, optionally):
|
||||
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'for f in ThreadExecutor FuturePool AsyncChannel ParallelForBounded; do g++ -std=c++26 -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done'
|
||||
```
|
||||
|
||||
Add `-freflection` on GCC 16 or later, as `CMakeLists.txt:24-26` does.
|
||||
|
||||
**A2 (P2, inferred hang): `join()` and the destructor when no worker is running (l.61-71).**
|
||||
- If work is queued before `start()`, or after a failed `start()`, then `~ThreadExecutor` → `join()` waits for workers that do not exist.
|
||||
- **Add:** "Admission before `start()` queues normally. When no worker is running, `join()` and the destructor drain both lanes inline on the caller under `ExecutorThreadGuard` (counted as `inline_after_join`) and never wait. `start()` after `close()` or after a successful `start()` → `invalid_argument`. After a failed `start()` it may be retried."
|
||||
|
||||
**A3 (P2, inferred race): a reservation outstanding across `close()`/`join()`.**
|
||||
- `TaskScope` reserves and commits in separate steps (`TaskScope.hpp:679-732`), and FuturePool will do the same.
|
||||
- **Add:** "A reserved slot counts in `admitted()` and in the bound. `try_reserve_slot` after `close()` → `stopped`. A reservation taken before `close()` stays binding: `commit_reserved` after `close()` enqueues normally. `join()` also waits until no reservation is outstanding."
|
||||
|
||||
**P3 (editorial):**
|
||||
- **l.125:** must be `inline` (Async is header-only, so the ODR applies): `[[nodiscard]] inline Void::Result::Error make_async_error(ChannelError, std::string message = {});`
|
||||
- **l.75-84 (AsyncChannel):**
|
||||
- Deadlines and timers:
|
||||
- Deadlines are judged by `timers->clock()`.
|
||||
- Check stop, then deadline, then "deadline without timers" → `invalid_argument`, before any state change. The value is returned in `SendFailure`.
|
||||
- `TimerEvent::closed` → `cancelled` (REV1 F12; today only a test name implies it).
|
||||
- `schedule_at` failure: `overloaded` → `ChannelError::overloaded`, `stopped` → `cancelled`.
|
||||
- Waiters and lifetime:
|
||||
- `max_waiters` applies per direction; 0 → `invalid_argument`.
|
||||
- Frames hold `shared_from_this()`.
|
||||
- Never construct or destroy a `std::stop_callback` while holding the channel mutex.
|
||||
- Destroying a suspended Task is a caller error.
|
||||
- The resume executor must outlive every pending resume.
|
||||
- FIFO means per-producer order.
|
||||
- **l.85-90 (parallel_for):**
|
||||
- At most `max_concurrency` chunks run at once, counting the caller when it runs chunks inline.
|
||||
- `Kind::rejected` is not produced in this wave.
|
||||
- Precedence: `invalid_argument` > `failed` > `stopped`.
|
||||
- `first >= last` → success.
|
||||
- Compute the range in the unsigned type of `I`.
|
||||
- **ThreadExecutor:** `idle()`/`stats()` are snapshots. The switch to inline mode happens under the executor mutex. `admitted()` = queued + running + reserved.
|
||||
- **FuturePool:** if creating the frame throws, release the slot and rethrow.
|
||||
- **§12:** stop if `Async/Timer.hpp` is missing or differs from M-TIME-03 §7.
|
||||
- **l.16:** `ExecutorThreadGuard` is at `Executor.hpp:32-51`.
|
||||
|
||||
## R2 and carry-over coverage
|
||||
|
||||
| Spec | Item | Status |
|
||||
| --- | --- | --- |
|
||||
| S-IO-03 | N3 | Partial. All B2 bullets are present; the owned-executor documentation and handoff liveness are missing (S1, P3). |
|
||||
| S-IO-03 | N4 | Yes, l.115-123. S5 and S6 are needed to implement it without guessing. |
|
||||
| S-IO-03 | P3-5 | Yes, l.212-213, but see S8. |
|
||||
| S-IO-03 | P3-9 | Partial. Dispatch after release is there; the documentation is missing. |
|
||||
| S-IO-03 | F1 | Yes, but contradicted by l.107-108 (S3). |
|
||||
| S-IO-03 | F2 | Partial: fd close under poll ownership is missing (S2). |
|
||||
| S-IO-03 | F9 | Yes, except that `advance_shutdown` must begin shutdown implicitly (S2). |
|
||||
| S-IO-03 | F11 | Yes. |
|
||||
| S-IO-03 | F13 | Yes, except "success invalidates the File" and the ByteStream note (P3). |
|
||||
| M-ASYNC-04 | N5 | Yes, l.80-82. |
|
||||
| M-ASYNC-04 | F7 | Yes. |
|
||||
| M-ASYNC-04 | F11 | Yes. |
|
||||
| M-ASYNC-04 | F12 | Yes, except `TimerEvent::closed`→`cancelled` is implicit (P3). |
|
||||
| M-ASYNC-04 | REV1 P3 ThreadExecutor, `idle()` | Yes. |
|
||||
|
||||
## Write scope
|
||||
|
||||
The two specs' write sets are disjoint. Neither touches `Timer.hpp` (B1), Functional (A1) or Runtime (B3).
|
||||
|
||||
- **Driver.hpp:** it passes from B2 to A4 in sequence at G4 (REV1:339-340), so there is no concurrent ownership.
|
||||
- **No build edits needed:** `src/IO/FileWorkers.cpp` is picked up by the source glob (`Module.cmake:14`), so `module.cmake` needs no edit. `File.hpp` becomes a public header through the header glob.
|
||||
- **Commands select the new tests:** the module closures cover the includes, and the filters match the file stems (`Runner.cpp:205-225`), including `TimerQueue` (M-TIME-03.md:34).
|
||||
|
||||
## Checks executed and not run
|
||||
|
||||
- **Executed:** read-only reads of:
|
||||
- both specs, R2, REV1, the PLAN §§ for these tasks, PREFLIGHT-2, `IO.md`, `Async.md`;
|
||||
- all of `EpollDriver.cpp`, the IO headers, `Executor.hpp`, `Operation.hpp`, `Detail/Types.hpp`;
|
||||
- `TaskScope.hpp` (parts), `ThreadPool.hpp`, `ParallelFor.hpp`;
|
||||
- the cmake files and `tests/CMakeLists.txt`, the IoDriver tests and consumer tests;
|
||||
- M-TIME-03.md §§6-10 and DECISIONS D-034/038/040.
|
||||
- **Not run:** no builds, tests or compile probes.
|
||||
- `Timer.hpp` is not in the main checkout, so I checked it against M-TIME-03.md §7 only.
|
||||
- S-IO-04 and S-RUNTIME-02 specs do not exist yet, so disjointness was checked against PLAN §3 and the REV1 ownership tables.
|
||||
- No Serena or codebase-memory coverage checks; the hooks reported partial indexing, so I read the source directly.
|
||||
- **Residual for the A4 spec:** R2 N3 loops must exit on `shutdown_complete()`, but F9's public wrapper list has no public `Driver::shutdown_complete()`.
|
||||
|
||||
**Re-review scope:** only the amended text for S1–S9 and A1–A3.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Wave 11 spec review: S-IO-03 (B2) and M-ASYNC-04 (A2) against contract R2
|
||||
|
||||
Task ID: W11-SPEC-REVIEW-1
|
||||
Role: opus-reviewer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Repo `/home/faumaray/Projects/VoidLibrary`, branch `feat/roadmap-p2-wave11`, HEAD `99203ce`
|
||||
(prep `7f95f89`, docs `a8a9249`, R2 `99203ce`) on `main` `38436b1`. Untracked user files are not inputs.
|
||||
- PREFLIGHT-2 (`docs/agent-workflow/tasks/W11-PREFLIGHT-2-OUTPUT.md`) said the R2 amendment can be
|
||||
re-reviewed on the task specs. Root wrote `docs/agent-workflow/tasks/W11-CONTRACT-R2.md` and draft
|
||||
specs `docs/agent-workflow/tasks/S-IO-03.md` and `docs/agent-workflow/tasks/M-ASYNC-04.md`.
|
||||
- Design chain: `W11-PLAN-OUTPUT.md` → `W11-PLAN-REV1-OUTPUT.md` → `W11-CONTRACT-R2.md` (R2 wins).
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Verdict per spec (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE): is each spec complete,
|
||||
internally consistent, faithful to PLAN+REV1+R2, implementable without guessing, with acceptance
|
||||
tests covering the roadmap row and every mandatory invariant? Findings P0–P3 with exact spec line
|
||||
and the replacement text you recommend.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
In: the two specs, R2 items N3, N4, N5, P3-5, P3-9 as reflected in them, F1/F2/F7/F9/F11/F12/F13
|
||||
carry-over, verification commands (module lists, filters, sanitizer flags), write-scope
|
||||
disjointness between the two specs and versus S-IO-04/S-RUNTIME-02 later steps.
|
||||
Out: re-litigating accepted decisions D-W11-01..15; other specs.
|
||||
|
||||
## 4. Files to inspect
|
||||
The two specs, `W11-CONTRACT-R2.md`, `W11-PLAN-REV1-OUTPUT.md`, `W11-PLAN-OUTPUT.md`,
|
||||
`docs/roadmap/subsystems/IO.md`, `docs/roadmap/modules/Async.md`, and source they cite
|
||||
(`src/IO/EpollDriver.cpp`, `include/Void/IO/*`, `include/Void/Async/*`, `cmake/Module.cmake:14`,
|
||||
`CMakeLists.txt:13-15`, `tests/CMakeLists.txt`).
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: none
|
||||
Allowed: read-only `git`, `rg`, `sed -n`, Serena/codebase-memory reads. Two implementers (M-FUNCTIONAL-03,
|
||||
M-TIME-03) run in separate worktrees; ignore them.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
1. Diff each spec's mandatory list against PLAN/REV1/R2; list omissions or contradictions.
|
||||
2. Check every signature is consistent with existing types it names (`ComposedTransferError`,
|
||||
`Transfer`, `DescriptorId`, `BufferLease`, `Coro::Task`, `Void::Result::Result`, `ThreadPool`).
|
||||
3. Check acceptance tests are deterministic and map to invariants; flag untestable ones.
|
||||
4. Check commands will actually select the new tests (module closure; silent skip rule).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
Not applicable for authorship: review signatures written in the specs.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Root will fix the specs from your findings, set Status READY, lint, and dispatch.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
As listed in the specs §9; flag any missing hazard from PREFLIGHT-1/2.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Verdict per spec. 2. Findings with spec line + replacement text. 3. Explicit statement whether
|
||||
each R2 item relevant to the spec is fully reflected.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Read-only, e.g. `rg -n "ComposedTransferError|struct Transfer|DescriptorId" include/Void/IO`.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits, commits, network or spawning. INSUFFICIENT_EVIDENCE rather than guess.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040. Technical check only.
|
||||
|
||||
## 14. Return format
|
||||
Task ID; verdict per spec; findings P0→P3 with replacement text; R2 coverage statement; checks not
|
||||
run. Compact.
|
||||
@@ -58,7 +58,7 @@ the explicit path when a backward-compatible downgrade is impossible.
|
||||
| Core/Functional | Error categories, formatting adapters, foundation dependency cleanup | Existing representations and error chains; minimal consumer with optional packages absent |
|
||||
| Containers/Memory | Allocator-aware variants and changed invalidation/ownership | Move-only values, allocator lifetime, stable-handle/invalidation examples, old default behavior |
|
||||
| Data/Binary/Text | Exact integers, checked conversions, Unicode/limit policies | Large identifiers round-trip; overflow errors; old strict signed documents remain accepted/rejected identically |
|
||||
| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor |
|
||||
| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor. Recorded W11 changes: `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers; `validate_limits` rejects `max_file_queue == 0`; Sync EventBus and Observable/Signal dispatch over snapshots (subscription changes take effect next pass); nested Observable/Signal updates for copyable types are queued FIFO; legacy `parallel_for` waits for all tasks before rethrowing; Async-mode EventBus handler exceptions are counted instead of terminating; legacy `retry` zero-attempt result kept until Wave C; a concurrent `poll_once` caller gets `busy`; `~Driver` on a file worker or inside a poll turn terminates with a diagnostic |
|
||||
| Net | Secure TLS defaults, total deadlines, redirect and streaming/session APIs | Private-CA correct-host tests; wrong-host failure; explicit legacy override if offered; no fallback to insecure mode |
|
||||
| Service/Plugin | Reference convenience versus owning handles; new C ABI | Acquired old generation survives replacement; C/C++ paths have separate ABI tests and destruction ownership |
|
||||
| Fsm/Scheduler | Terminal-state consistency and supervised children | Faulted termination, race loser cleanup, state checkpoint restore; no coroutine-frame serialization |
|
||||
|
||||
@@ -92,18 +92,22 @@ immutable and bounded; destructor traversal must not recurse through unbounded c
|
||||
|
||||
## 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
|
||||
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. A stop request or
|
||||
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 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.
|
||||
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
|
||||
|
||||
@@ -74,9 +74,11 @@ semantics avoid requiring every dispatch to drain a descriptor completely; the f
|
||||
budget can yield while data remains ready. This follows the
|
||||
[Linux epoll interface](https://man7.org/linux/man-pages/man7/epoll.7.html).
|
||||
|
||||
One driver thread owns interest updates and descriptor generations. Producers submit
|
||||
bounded control messages and wake it through eventfd; an embedder may drive bounded
|
||||
`poll_once` turns instead. Dispatch up to 64 ready descriptors and 64 KiB/direction per
|
||||
The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner)
|
||||
and owns interest updates and generations; a concurrent caller gets `busy` without
|
||||
touching descriptors. Producers submit bounded control messages and wake the owner
|
||||
through eventfd. Runtime or the embedder supplies the thread (`Driver::run`,
|
||||
`pump_until`). Dispatch up to 64 ready descriptors and 64 KiB/direction per
|
||||
descriptor per turn before yielding. Enable writable interest only with pending writes
|
||||
to avoid idle busy loops. HUP/ERR still trigger final read/error inspection. Async
|
||||
completion tickets transfer continuations to the supplied executor outside driver locks.
|
||||
@@ -89,7 +91,10 @@ integer directly. Socket connect completion checks the socket error state; accep
|
||||
obey the same fairness/admission budget. Platform-specific endpoint conversion remains
|
||||
an IO/Net adapter detail until the Net endpoint contract is integrated.
|
||||
|
||||
Files initially use a bounded native blocking worker pool. Positional pread/pwrite
|
||||
Files initially use a bounded native blocking worker pool, started explicitly by
|
||||
`start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall (or
|
||||
an injected syscall shim, the single documented exception) and queue its result;
|
||||
completions are delivered only by a poll turn. Positional pread/pwrite
|
||||
avoids shared offset races; default writes/syncs for one file are serialized in admission
|
||||
order, and reads expose explicit offsets. Worker ownership retains descriptor and buffer
|
||||
until the syscall returns. Cancelled queued work is removed before execution; an active
|
||||
@@ -116,8 +121,12 @@ Only terminal delivery is arbitrated once; no callback is delivered merely becau
|
||||
arrived while backend access or outcome classification was still pending.
|
||||
|
||||
Driver shutdown closes admission, cancels queued requests, asks active requests to
|
||||
stop, drains readiness/control/completion lanes, joins file workers, then releases
|
||||
descriptors/wake resources. It must keep the executor alive until all completion tickets
|
||||
stop, waits for the poll owner and in-flight syscalls, drains readiness/control/completion
|
||||
lanes, joins file workers, then closes operation descriptors. Epoll and wake descriptors
|
||||
close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction
|
||||
on a file worker or inside a poll turn is a programmer error. `File::close_and_join`
|
||||
returns `incomplete_shutdown` on expiry and retains the fd and buffers; a dropped File
|
||||
closes its fd after its last in-flight request drains. It must keep the executor alive until all completion tickets
|
||||
drain. `close_and_join` cannot free buffers when its own deadline expires; return an
|
||||
incomplete-shutdown report through the owning driver and retain work. Blocking joins
|
||||
are off-driver/off-worker operations; embedded drivers pump until their scopes join.
|
||||
@@ -151,7 +160,7 @@ are not owned by this document.
|
||||
| S-IO-01 | P1 / Async operation ownership and Time clock gates | Portable transfer/error/driver API, buffer leases, descriptor and quota ownership | Mock backend completes/stops in every ordering with exactly one result and no borrowed-buffer escape / astra_implementer |
|
||||
| S-IO-02 | P1 / S-IO-01 | Level-triggered epoll driver, wake/control path, generation-safe close and stream operations | Fragmentation/EAGAIN/EINTR/HUP/fd reuse and full queues do not lose completion or busy-spin / astra_implementer |
|
||||
| S-IO-03 | P2 / S-IO-01 | Bounded positional file workers, serialization, sync and active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync success/failure after stop remains authoritative in the sole result / astra_implementer |
|
||||
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, optional System/Net adapters | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
|
||||
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, SystemAsync conformance (Net adapter deferred: Net has no IO use) | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
|
||||
| S-IO-05 | P3 / S-IO-04; performance harness | Optional io_uring capability/backend gate and portability conformance specification | Same tests pass; denied/unsupported capability falls back only before submission; profile evidence justifies enablement / astra_implementer |
|
||||
|
||||
## Validation, measurements and migration
|
||||
|
||||
@@ -45,10 +45,14 @@ struct Options {
|
||||
class Host { // owns managed resources
|
||||
public:
|
||||
static Result<Host> create(Options); // validates, starts no workers
|
||||
Result<void> start(); // explicit startup transaction
|
||||
Async::Executor& executor();
|
||||
IO::Driver& io();
|
||||
Coro::Task<Result<ShutdownReport>> shutdown(Async::OperationOptions);
|
||||
Result<void> start(StartOptions); // explicit startup transaction
|
||||
Async::Executor* executor();
|
||||
IO::Driver* io();
|
||||
Result<ShutdownReport> shutdown_blocking(Async::OperationOptions);
|
||||
Result<ShutdownReport> poll_shutdown(Async::OperationOptions); // non-blocking step
|
||||
Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions,
|
||||
Async::TimerQueue* timers = nullptr);
|
||||
// No awaited shutdown Task on the host's own executor: it would self-join (D-038).
|
||||
};
|
||||
// NEW EmbeddedResources borrows executor, IO driver, Time clock and Memory budget.
|
||||
}
|
||||
@@ -70,11 +74,13 @@ constructors remain inert; start is explicit and errors return before publicatio
|
||||
|
||||
Use a lifecycle graph of explicit resources, with required/optional dependencies and
|
||||
deterministic topological ordering. Default core order: validate limits/capabilities →
|
||||
establish signal handling on the designated owner thread → allocate budgets and queues →
|
||||
install the injected `SignalGate` on the designated owner thread (Runtime has no System
|
||||
dependency; a System-backed adapter is optional) → allocate budgets and queues →
|
||||
start CPU executor → start IO driver/file workers → start optional service/admission
|
||||
adapters → report ready. SignalWatcher is created before worker threads as required by
|
||||
[its contract](../../../include/Void/System/SignalWatcher.hpp), and is destroyed on
|
||||
the same creating thread after workers join.
|
||||
the same creating thread after workers join; off-owner teardown calls `uninstall(false)`,
|
||||
which closes the gate's descriptor but cannot restore the owner's mask.
|
||||
|
||||
Each start step returns a retained cleanup action. A failed step aborts its partial
|
||||
resources and unwinds previously successful starts in reverse dependency order.
|
||||
@@ -111,19 +117,23 @@ idempotent; callers join one retained result rather than issue competing stop pa
|
||||
data and requests cooperative cancellation, but all admitted backend activity must
|
||||
still quiesce. Expiry of the total shutdown budget returns shutdown_incomplete with
|
||||
exporter owners and their execution resources retained; a later join continues them.
|
||||
6. Only after cleanup/export callbacks and backend references retire, stop reactor and
|
||||
CPU/file workers and release budgets/descriptors/signal masks in reverse creation
|
||||
order. Observation failure cannot suppress cleanup or convert a failed operation
|
||||
6. After cleanup/export callbacks and backend references retire, drop component/exporter
|
||||
references, then stop owned IO, the reactor and CPU/file workers, and release budgets,
|
||||
descriptors and the signal gate in reverse creation order. Borrowed executor, driver,
|
||||
clock and memory are never shut down or joined by the Host. Observation failure cannot suppress cleanup or convert a failed operation
|
||||
into success. A timed-out flush is not evidence that its resources are releasable.
|
||||
|
||||
Default total shutdown observation budget is 30 seconds, shortened by caller options.
|
||||
Each shutdown call observes min(caller deadline, now + total_timeout) for remaining work;
|
||||
drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete
|
||||
phase stops the sequence and the next call resumes there.
|
||||
Expiry produces `shutdown_incomplete` containing pending owner IDs/counts and phase;
|
||||
the Host remains in joining with resources retained. It can be waited again or the
|
||||
application can choose explicit process termination. There is no forced thread kill,
|
||||
buffer release or dlclose. Borrowed resources must outlive final cleanup, not merely
|
||||
the first timed-out shutdown call. Destruction blocks to join only on an allowed
|
||||
off-worker owner thread; on a runtime worker, callers must await shutdown before
|
||||
destroying Host. Self-join misuse is detected as a programmer error. Process-level
|
||||
the first timed-out shutdown call. Destruction blocks to join only off Runtime threads;
|
||||
destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error
|
||||
that terminates after a diagnostic. Process-level
|
||||
hard-stop policy belongs to the application, not a hidden destructor timeout.
|
||||
|
||||
Uncaught task exceptions reach explicit scope/error sinks. Default failure policy
|
||||
@@ -156,8 +166,8 @@ Every row is PLANNED.
|
||||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||||
| --- | --- | --- | --- |
|
||||
| S-RUNTIME-01 | P1 / Async ownership, IO driver, Time/Memory ports | Inert Host options, borrowed/owned resource graph, dependency validation | No constructor starts workers; invalid bounds/cycles fail before external admission / sol_implementer |
|
||||
| S-RUNTIME-02 | P2 / S-RUNTIME-01; System signal gate | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
|
||||
| S-RUNTIME-03 | P2 / S-RUNTIME-02 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
|
||||
| S-RUNTIME-02 | P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port) | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
|
||||
| S-RUNTIME-03 | P2 / S-RUNTIME-02, S-IO-04 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
|
||||
| S-RUNTIME-04 | P3 / S-RUNTIME-03; Service/Configuration transaction gates | Optional managed adapters, transactional resize/reload and embedded examples | Same workload runs embedded/managed; failed resource prepare keeps active generation / sol_implementer |
|
||||
| S-RUNTIME-05 | P3 / S-RUNTIME-04; profile harness | Latency/throughput/footprint presets, inspection and tuning gates | Limits remain invariant per preset; measured p99/RSS/build cost reported with environment / astra_implementer |
|
||||
|
||||
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
# Target support
|
||||
|
||||
VoidLibrary is qualified per **target profile**: a platform, a compiler and
|
||||
standard library, the external dependencies that are expected to exist, and
|
||||
the set of modules that are expected to build there. The profile is detected
|
||||
from the toolchain at configure time, validated against the selected modules,
|
||||
and recorded in `void-target-manifest.cmake` (installed next to
|
||||
`VoidConfig.cmake`).
|
||||
|
||||
```bash
|
||||
# Native Linux (default)
|
||||
cmake -S . -B build -G Ninja -DVOID_ENABLE_TESTING=ON
|
||||
|
||||
# Force a profile for a qualification run (normally auto-detected)
|
||||
cmake -S . -B build-wasm -G Ninja -DVOID_TARGET=wasm \
|
||||
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
|
||||
|
||||
# Cross build (Windows client example)
|
||||
cmake -S . -B build-mingw -G Ninja \
|
||||
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
|
||||
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
|
||||
```
|
||||
|
||||
`VOID_TARGET` is `auto` by default. The recognized values are `linux`,
|
||||
`linux-musl`, `windows` and `wasm`; anything else fails at configure time with
|
||||
the list of known targets. `cmake/Targets.cmake` holds the allowlists and the
|
||||
validation rules.
|
||||
|
||||
## Manifest
|
||||
|
||||
Every configure writes `void-target-manifest.cmake`:
|
||||
|
||||
| Field | Meaning |
|
||||
|-------|---------|
|
||||
| `VOID_TARGET_MANIFEST_TARGET` | detected/forced profile (`linux`, `linux-musl`, `windows`, `wasm`) |
|
||||
| `VOID_TARGET_MANIFEST_TARGET_ORIGIN` | `auto` or the forced `VOID_TARGET` value |
|
||||
| `VOID_TARGET_MANIFEST_TRIPLE` | `CMAKE_C_COMPILER -dumpmachine` |
|
||||
| `VOID_TARGET_MANIFEST_SYSTEM_NAME` / `..._SYSTEM_PROCESSOR` | CMake system identification |
|
||||
| `VOID_TARGET_MANIFEST_COMPILER_ID` / `..._COMPILER_VERSION` | compiler tuple |
|
||||
| `VOID_TARGET_MANIFEST_CXX_STANDARD` | language standard |
|
||||
| `VOID_TARGET_MANIFEST_LINKAGE` | `shared` or `static` |
|
||||
| `VOID_TARGET_MANIFEST_REFLECTION` | C++26 reflection available (`yes`/`no`) |
|
||||
| `VOID_TARGET_MANIFEST_STD_EXPECTED` | `<expected>` available |
|
||||
| `VOID_TARGET_MANIFEST_SANITIZERS` | `none`, `ASan`, `UBSan`, `TSan` or a combination |
|
||||
| `VOID_TARGET_MANIFEST_TESTING` | `VOID_ENABLE_TESTING` |
|
||||
| `VOID_TARGET_MANIFEST_MODULES` | configured modules |
|
||||
|
||||
Consumers can read it after `find_package(Void)`:
|
||||
|
||||
```cmake
|
||||
include("${Void_DIR}/void-target-manifest.cmake")
|
||||
message(STATUS "Void target: ${VOID_TARGET_MANIFEST_TARGET}")
|
||||
```
|
||||
|
||||
## Qualified tuples
|
||||
|
||||
### Linux (qualified)
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Triple | `x86_64-unknown-linux-gnu` (NixOS, glibc) |
|
||||
| Compiler | GCC 16.2.0 (`dev cpp-gcc`) |
|
||||
| Standard library | libstdc++ 16 |
|
||||
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
|
||||
| Language | C++26, reflection `yes` (`-freflection`) |
|
||||
| Dependencies | Boost (headers/url/beast/asio), OpenSSL, SQLite3, Lua 5.4 (optional) |
|
||||
| Modules | all |
|
||||
| Observed | `Testing;Core` configure/build clean; `ctest` 3/3 (VoidTests, installed consumers, target qualification) |
|
||||
|
||||
The Linux profile is the reference target: every module is allowed and the
|
||||
per-module platform code selects the native implementation.
|
||||
|
||||
### Linux / musl (configure/build/install/consume qualified)
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Triple | `x86_64-alpine-linux-musl` (Alpine 3.23.8, musl 1.2.5-r24) |
|
||||
| Compiler | Alpine GCC 15.2.0 (Clang accepted by the allowlist) |
|
||||
| Standard library | libstdc++ with musl 1.2.5 |
|
||||
| CMake / generator | CMake 4.1.3, Ninja 1.13.2 |
|
||||
| Dependencies | `boost-dev` 1.84.0, `openssl-dev` 3.5.10, `sqlite-dev` 3.53.4, `lua5.4-dev` 5.4.8, `linux-headers` from apk |
|
||||
| Language | C++26, reflection `no` (GCC 15), `<expected>` `yes` |
|
||||
| Modules | `Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System SystemAsync Text Time` |
|
||||
| Observed | RelWithDebInfo with `-DVOID_WARNINGS_AS_ERRORS=ON` and `-DVOID_ENABLE_TESTING=OFF`: configure detected `linux-musl`, build passed, `cmake --install` to a prefix succeeded, and the isolated `TargetProfile` consumer configured, linked, and ran (`VoidTargetProfileConsumer` 1/1) recording `target=linux-musl triple=x86_64-alpine-linux-musl compiler=GNU-15.2.0 linkage=shared reflection=no`. Test suite with `-DVOID_ENABLE_TESTING=ON`: 1226 tests, 1221 passed, 5 skipped, 0 failed |
|
||||
|
||||
The test suite is qualified too: with `VOID_ENABLE_TESTING=ON` (modules
|
||||
`Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting
|
||||
IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System
|
||||
SystemAsync Testing Text Time`) the Alpine 3.23 container build ran
|
||||
**1226 tests: 1221 passed, 5 skipped, 0 failed**. Reflection-only tests are
|
||||
skipped through `// @requires-reflection`. The run also exposed a test bug in
|
||||
`Net/HttpDuplex.cpp` (`recv_until` consumed body bytes past the header
|
||||
marker); the helper now reads byte-wise and the duplex tests pass on musl and
|
||||
glibc.
|
||||
|
||||
Detection uses `CMAKE_C_COMPILER -dumpmachine` (or
|
||||
`CMAKE_C_LIBRARY_ARCHITECTURE`/`CMAKE_C_FLAGS`) matching `musl`. The profile is
|
||||
recognized and configured like Linux; musl-specific behaviour (subprocess
|
||||
`/proc`, `dl`, locale) must still be verified before claiming full support.
|
||||
|
||||
### Windows client (compile/install/consume + Wine runtime qualified)
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Triple | `x86_64-w64-mingw32` |
|
||||
| Compiler | MinGW-w64 GCC 16.2.0 |
|
||||
| Standard library | libstdc++ + mingw-w64 CRT (mcfgthread threading in the Nix wrapper) |
|
||||
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
|
||||
| Language | C++26, reflection `yes` |
|
||||
| Runtime | Wine 11.0 (`wine64`), no native Windows runner available |
|
||||
| Modules | `Algorithms Async Binary Containers Core Data Discovery Fsm Functional Log LogState Math Memory Messaging Observability ObservabilityHooks Scheduler Service Testing TestingMock Text Time Unicode` |
|
||||
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); `VoidTests.exe` under Wine: **1364 tests, 1360 passed, 4 skipped, 0 failed** |
|
||||
|
||||
Notes from the runtime run:
|
||||
|
||||
- `IO` is **not** in the Windows allowlist. It builds, but its native backend
|
||||
is Linux-only (`EpollBackend`); on Windows `Driver::create` returns
|
||||
`IoErrorCode::unsupported` unless the mock backend is selected. A Windows
|
||||
IO backend (IOCP) is a separate task.
|
||||
- `Observability` links after replacing the namespace-scope
|
||||
`inline thread_local` hook stack with a function-local `thread_local`
|
||||
accessor (MinGW emitted duplicate TLS init functions).
|
||||
- Test code is portable: POSIX-only descriptor assertions are guarded, the
|
||||
Log hardening test closes its `ifstream` before removing the file, and the
|
||||
subprocess-isolation test skips when `current_executable_path()` is not
|
||||
implemented (Windows has no subprocess isolation yet).
|
||||
- MinGW test builds need `-Wa,-mbig-obj`: the Fsm hardening test TU exceeds
|
||||
the COFF section limit with the default object format.
|
||||
- Runtime observations come from Wine, not a native Windows runner; a
|
||||
Windows CI runner should confirm them.
|
||||
|
||||
The Nix MinGW wrapper needs the mcfgthread include/library paths explicitly:
|
||||
|
||||
```bash
|
||||
MINGW=/nix/store/...-x86_64-w64-mingw32-gcc-wrapper-16.2.0/bin
|
||||
MCFG=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1/lib
|
||||
MCFGINC=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1-dev/include
|
||||
cmake -S . -B build-mingw -G Ninja \
|
||||
-DCMAKE_SYSTEM_NAME=Windows \
|
||||
-DCMAKE_C_COMPILER="$MINGW/x86_64-w64-mingw32-gcc" \
|
||||
-DCMAKE_CXX_COMPILER="$MINGW/x86_64-w64-mingw32-g++" \
|
||||
-DCMAKE_C_FLAGS="-I$MCFGINC" -DCMAKE_CXX_FLAGS="-I$MCFGINC" \
|
||||
-DCMAKE_EXE_LINKER_FLAGS="-L$MCFG" \
|
||||
-DCMAKE_SHARED_LINKER_FLAGS="-L$MCFG"
|
||||
```
|
||||
|
||||
A regular MinGW-w64 installation with winpthreads does not need those extra
|
||||
flags.
|
||||
|
||||
### Browser / Wasm subset (qualified)
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Triple | `wasm32-unknown-emscripten` |
|
||||
| Compiler | Emscripten 6.0.9 (Clang 22.1.8) |
|
||||
| Standard library | libc++ + Emscripten libc |
|
||||
| CMake / generator | CMake 4.5 via `emcmake`, Ninja, Node 24.22.3 as the test emulator |
|
||||
| Language | C++26 without reflection (`VOID_HAS_CXX26_REFLECTION=no`) |
|
||||
| Modules | `Algorithms Binary Containers Core Data Functional LogState Math Memory Testing TestingMock Text Time Unicode` |
|
||||
| Observed | library: configure, compile, install, consume and run under Node; tests: **901 tests, 895 passed, 6 skipped, 0 failed** under Node |
|
||||
|
||||
The allowlist is fail-closed: native networking (`Net`, `RPC`), processes and
|
||||
filesystem (`System`, `SystemAsync`), IPC, SQLite, plugins and anything that
|
||||
needs threads or reflection stay out. Do not add a module until it has been
|
||||
configured and compiled with `emcmake`.
|
||||
|
||||
Verified commands:
|
||||
|
||||
```bash
|
||||
# Library subset
|
||||
emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||
-DVOID_ENABLE_TESTING=OFF \
|
||||
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
|
||||
cmake --build build-wasm
|
||||
cmake --install build-wasm --prefix "$PWD/build-wasm-install"
|
||||
|
||||
# Consumer (the install lives outside the Emscripten sysroot)
|
||||
emcmake cmake -S tests/package/TargetProfile -B build-wasm-consumer -G Ninja \
|
||||
-DCMAKE_PREFIX_PATH="$PWD/build-wasm-install" \
|
||||
-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH \
|
||||
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||
-DVOID_EXPECTED_TARGET=wasm
|
||||
cmake --build build-wasm-consumer
|
||||
node build-wasm-consumer/void_target_profile_consumer.js
|
||||
```
|
||||
|
||||
`CMAKE_CXX_SCAN_FOR_MODULES=OFF` avoids CMake's C++20 module dependency
|
||||
scanner calling Emscripten's `emscan-deps`, which is not shipped by every
|
||||
Emscripten package. `CMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH` is needed
|
||||
because the Emscripten toolchain restricts package lookup to its sysroot.
|
||||
|
||||
The **test suite** is qualified with pthreads, exception handling and a
|
||||
larger stack:
|
||||
|
||||
```bash
|
||||
emcmake cmake -S . -B build-wasm-tests -G Ninja -DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
|
||||
-DBUILD_SHARED_LIBS=OFF \
|
||||
-DCMAKE_CXX_FLAGS="-fexceptions -pthread" \
|
||||
-DCMAKE_EXE_LINKER_FLAGS="-fexceptions -pthread -sSTACK_SIZE=16777216 \
|
||||
-sINITIAL_MEMORY=134217728 -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1073741824" \
|
||||
-DVOID_ENABLE_TESTING=ON \
|
||||
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
|
||||
cmake --build build-wasm-tests
|
||||
node build-wasm-tests/tests/VoidTests.js --no-color
|
||||
```
|
||||
|
||||
Static linking (`BUILD_SHARED_LIBS=OFF`) is required for exception handling
|
||||
across the test binary; `-fexceptions` enables catching, `-pthread` enables
|
||||
the threading tests, and the stack/memory flags accommodate the deepest
|
||||
recursive tests.
|
||||
|
||||
Portable fallbacks added for libc++ without the C++23/26 pieces:
|
||||
`Core/Publication` uses a mutex-protected `shared_ptr` when
|
||||
`__cpp_lib_atomic_shared_ptr` is absent, and `TestingMock` uses an internal
|
||||
move-only function wrapper when `__cpp_lib_move_only_function` is absent.
|
||||
|
||||
Reflection-dependent test files are gated with `// @requires-reflection`
|
||||
(Core/Meta, Core/FlagsReflect, Data/CsvReflect, Data/Reflect*,
|
||||
Functional/ResultReflectionFormat, Testing/ContainerFixture,
|
||||
TestingMock/Reflect, Configuration/Fsm annotation tests) and are skipped when
|
||||
`VOID_HAS_CXX26_REFLECTION` is false, so a non-reflecting compiler no longer
|
||||
fails on scanner-generated registrations for functions hidden by `#ifdef`.
|
||||
|
||||
Runtime observations use Node; a browser runner should confirm them.
|
||||
|
||||
## Sanitizers
|
||||
|
||||
Sanitizer builds are native-only qualification configurations, not target
|
||||
profiles: `VOID_ENABLE_ASAN`, `VOID_ENABLE_UBSAN` and `VOID_ENABLE_TSAN`
|
||||
instrument the host build and are recorded in the manifest. Production
|
||||
packages are built with sanitizers off. ASan+TSan is rejected; TSan is
|
||||
rejected on `wasm`.
|
||||
|
||||
## Qualification test
|
||||
|
||||
`tests/package/TargetQualification.cmake` (ctest
|
||||
`VoidTargetQualification`) installs the build tree and:
|
||||
|
||||
1. Consumes the install through `tests/package/TargetProfile`, asserting the
|
||||
manifest target/triple/compiler/linkage/reflection fields and running one
|
||||
Core behaviour.
|
||||
2. Rejects an unknown `VOID_TARGET`.
|
||||
3. Rejects a native module (`IPC`) and native networking (`Net`) on the
|
||||
`wasm` profile.
|
||||
4. Rejects a missing external dependency (`Sqlite` without SQLite3).
|
||||
5. Configures the pure wasm subset and asserts the manifest records
|
||||
`wasm`.
|
||||
@@ -0,0 +1,71 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(DistributedHostGraph LANGUAGES CXX)
|
||||
|
||||
# Reference platform component, built as an installed-package consumer so it
|
||||
# cannot accidentally rely on whole-repository linkage.
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Functional Net System)
|
||||
|
||||
add_library(distributed_host_graph STATIC
|
||||
src/cluster_fixture.cpp
|
||||
src/host_graph.cpp
|
||||
src/range_placement.cpp
|
||||
src/replicated_kv.cpp
|
||||
src/replicated_queue.cpp
|
||||
src/single_node.cpp)
|
||||
target_include_directories(distributed_host_graph PUBLIC include)
|
||||
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
|
||||
|
||||
add_executable(distributed_host_graph_test tests/host_graph_test.cpp)
|
||||
target_link_libraries(distributed_host_graph_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_single_node_test tests/single_node_test.cpp)
|
||||
target_link_libraries(distributed_single_node_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_replicated_kv_test tests/replicated_kv_test.cpp)
|
||||
target_link_libraries(distributed_replicated_kv_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_cluster_fixture_test tests/cluster_fixture_test.cpp)
|
||||
target_link_libraries(distributed_cluster_fixture_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_replicated_queue_test tests/replicated_queue_test.cpp)
|
||||
target_link_libraries(distributed_replicated_queue_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_operations_test tests/operations_test.cpp)
|
||||
target_link_libraries(distributed_operations_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_range_placement_test tests/range_placement_test.cpp)
|
||||
target_link_libraries(distributed_range_placement_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_cluster_queue_test tests/cluster_queue_test.cpp)
|
||||
target_link_libraries(distributed_cluster_queue_test PRIVATE distributed_host_graph)
|
||||
|
||||
add_executable(distributed_host_graph_bench benchmarks/host_graph_bench.cpp)
|
||||
target_link_libraries(distributed_host_graph_bench PRIVATE distributed_host_graph)
|
||||
|
||||
# Out-of-process voter agent and the multi-process acceptance harness that
|
||||
# spawns three of them.
|
||||
add_executable(distributed_voter_agent agents/voter_agent.cpp)
|
||||
target_link_libraries(distributed_voter_agent PRIVATE Void::Net)
|
||||
|
||||
add_executable(distributed_multi_process_test tests/multi_process_test.cpp)
|
||||
target_link_libraries(distributed_multi_process_test PRIVATE Void::Net Void::System)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test)
|
||||
add_test(NAME distributed_single_node COMMAND distributed_single_node_test)
|
||||
add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test)
|
||||
add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test)
|
||||
add_test(NAME distributed_replicated_queue COMMAND distributed_replicated_queue_test)
|
||||
add_test(NAME distributed_operations COMMAND distributed_operations_test)
|
||||
add_test(NAME distributed_range_placement COMMAND distributed_range_placement_test)
|
||||
add_test(NAME distributed_cluster_queue COMMAND distributed_cluster_queue_test)
|
||||
# Smoke-run the workload baseline; it reports numbers instead of asserting
|
||||
# latency thresholds.
|
||||
add_test(NAME distributed_host_graph_bench_smoke
|
||||
COMMAND distributed_host_graph_bench --quick)
|
||||
add_test(NAME distributed_multi_process
|
||||
COMMAND distributed_multi_process_test $<TARGET_FILE:distributed_voter_agent>)
|
||||
@@ -0,0 +1,611 @@
|
||||
// Out-of-process voter agent for the multi-process acceptance harness.
|
||||
//
|
||||
// Each agent owns one directory and durably persists its Raft-style state
|
||||
// (current term, vote, log, commit index) before replying to any RPC. The
|
||||
// parent harness drives elections and replication over authenticated HTTP;
|
||||
// killing an agent loses nothing acknowledged, and a restarted agent
|
||||
// recovers from disk.
|
||||
//
|
||||
// distributed_voter_agent --dir <path> --port <port|0> --token <token>
|
||||
//
|
||||
// The bound port is written to `<dir>/port` once the listener is up.
|
||||
// Keys and values are restricted to [A-Za-z0-9_.-] so the durable text format
|
||||
// stays unambiguous.
|
||||
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Entry = std::pair<std::uint64_t, std::uint64_t>; // term, index
|
||||
|
||||
struct LogEntry {
|
||||
std::uint64_t term{0};
|
||||
std::uint64_t index{0};
|
||||
std::string key;
|
||||
std::string value;
|
||||
|
||||
[[nodiscard]] bool operator==(const LogEntry&) const noexcept =
|
||||
default;
|
||||
};
|
||||
|
||||
[[nodiscard]] bool safe_token(std::string_view text)
|
||||
{
|
||||
return !text.empty() &&
|
||||
std::ranges::all_of(text, [](char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '_' || c == '.' ||
|
||||
c == '-';
|
||||
});
|
||||
}
|
||||
|
||||
void sync_directory(const std::filesystem::path& directory)
|
||||
{
|
||||
const int fd = ::open(directory.c_str(), O_RDONLY | O_DIRECTORY);
|
||||
if (fd >= 0) {
|
||||
(void)::fsync(fd);
|
||||
(void)::close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/// Durable voter state. Every mutation is persisted (write, fsync, rename,
|
||||
/// directory fsync) before the RPC returns success.
|
||||
class VoterStore
|
||||
{
|
||||
public:
|
||||
|
||||
explicit VoterStore(std::filesystem::path directory)
|
||||
: m_directory(std::move(directory))
|
||||
, m_path(m_directory / "voter.state")
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] bool load()
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (!std::filesystem::exists(m_path)) {
|
||||
return std::filesystem::create_directories(m_directory) ||
|
||||
std::filesystem::exists(m_directory);
|
||||
}
|
||||
std::ifstream in{m_path};
|
||||
if (!in.is_open()) {
|
||||
return false;
|
||||
}
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
std::istringstream fields{line};
|
||||
std::string tag;
|
||||
fields >> tag;
|
||||
if (tag == "term") {
|
||||
std::uint64_t term = 0;
|
||||
std::string voted;
|
||||
if (!(fields >> term >> voted)) {
|
||||
return false;
|
||||
}
|
||||
m_term = term;
|
||||
m_voted_for = voted == "-"
|
||||
? std::nullopt
|
||||
: std::optional<std::string>{voted};
|
||||
} else if (tag == "entry") {
|
||||
LogEntry entry;
|
||||
if (!(fields >> entry.term >> entry.index >> entry.key >>
|
||||
entry.value)) {
|
||||
return false;
|
||||
}
|
||||
m_log.push_back(std::move(entry));
|
||||
} else if (tag == "commit") {
|
||||
if (!(fields >> m_commit)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
reapply();
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t term() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_term;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t last_index() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_log.empty() ? 0 : m_log.back().index;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t last_term() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_log.empty() ? 0 : m_log.back().term;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t commit() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_commit;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t log_size() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_log.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string voted_for() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_voted_for.value_or("-");
|
||||
}
|
||||
|
||||
/// Grant a vote when the term allows it and the candidate's log is
|
||||
/// at least as up to date.
|
||||
[[nodiscard]] bool vote(std::uint64_t term, std::string_view candidate,
|
||||
std::uint64_t candidate_last_index,
|
||||
std::uint64_t candidate_last_term)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (term < m_term) {
|
||||
return false;
|
||||
}
|
||||
if (term > m_term) {
|
||||
m_term = term;
|
||||
m_voted_for.reset();
|
||||
if (!persist()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (m_voted_for.has_value() && *m_voted_for != candidate) {
|
||||
return false;
|
||||
}
|
||||
const std::uint64_t self_index =
|
||||
m_log.empty() ? 0 : m_log.back().index;
|
||||
const std::uint64_t self_term =
|
||||
m_log.empty() ? 0 : m_log.back().term;
|
||||
const bool up_to_date =
|
||||
candidate_last_term > self_term ||
|
||||
(candidate_last_term == self_term &&
|
||||
candidate_last_index >= self_index);
|
||||
if (!up_to_date) {
|
||||
return false;
|
||||
}
|
||||
m_voted_for = std::string{candidate};
|
||||
return persist();
|
||||
}
|
||||
|
||||
/// AppendEntries: returns the matched index on success.
|
||||
[[nodiscard]] std::optional<std::uint64_t> append(
|
||||
std::uint64_t term, std::uint64_t prev_index,
|
||||
std::uint64_t prev_term, std::uint64_t leader_commit,
|
||||
const std::vector<LogEntry>& entries)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (term < m_term) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (term > m_term) {
|
||||
m_term = term;
|
||||
m_voted_for.reset();
|
||||
}
|
||||
const std::uint64_t local_last =
|
||||
m_log.empty() ? 0 : m_log.back().index;
|
||||
if (prev_index > local_last) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::uint64_t local_term =
|
||||
prev_index == 0 ? 0 : m_log[prev_index - 1].term;
|
||||
if (local_term != prev_term) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::size_t position = static_cast<std::size_t>(prev_index);
|
||||
for (const auto& entry : entries) {
|
||||
if (position < m_log.size() &&
|
||||
m_log[position] == entry) {
|
||||
++position;
|
||||
continue;
|
||||
}
|
||||
m_log.resize(position);
|
||||
m_log.push_back(entry);
|
||||
++position;
|
||||
}
|
||||
if (leader_commit > m_commit) {
|
||||
m_commit = std::min(leader_commit,
|
||||
m_log.empty() ? 0 : m_log.back().index);
|
||||
}
|
||||
reapply();
|
||||
if (!persist()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return m_log.empty() ? 0 : m_log.back().index;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<LogEntry> entries_from(
|
||||
std::uint64_t index) const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
std::vector<LogEntry> out;
|
||||
for (const auto& entry : m_log) {
|
||||
if (entry.index >= index) {
|
||||
out.push_back(entry);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string> value(
|
||||
std::string_view key) const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto found = m_kv.find(key);
|
||||
if (found == m_kv.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void reapply()
|
||||
{
|
||||
m_kv.clear();
|
||||
for (const auto& entry : m_log) {
|
||||
if (entry.index > m_commit) {
|
||||
break;
|
||||
}
|
||||
if (entry.value == "-") {
|
||||
m_kv.erase(entry.key);
|
||||
} else {
|
||||
m_kv.insert_or_assign(entry.key, entry.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool persist()
|
||||
{
|
||||
std::string text;
|
||||
text += "term " + std::to_string(m_term) + " " +
|
||||
m_voted_for.value_or("-") + "\n";
|
||||
for (const auto& entry : m_log) {
|
||||
text += "entry " + std::to_string(entry.term) + " " +
|
||||
std::to_string(entry.index) + " " + entry.key + " " +
|
||||
entry.value + "\n";
|
||||
}
|
||||
text += "commit " + std::to_string(m_commit) + "\n";
|
||||
|
||||
const auto temporary = m_path.string() + ".tmp";
|
||||
{
|
||||
std::ofstream out{temporary, std::ios::trunc};
|
||||
if (!out.is_open()) {
|
||||
return false;
|
||||
}
|
||||
out << text;
|
||||
out.flush();
|
||||
if (!out.good()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const int fd = ::open(temporary.c_str(), O_RDONLY);
|
||||
if (fd < 0) {
|
||||
return false;
|
||||
}
|
||||
(void)::fsync(fd);
|
||||
(void)::close(fd);
|
||||
if (std::rename(temporary.c_str(), m_path.c_str()) != 0) {
|
||||
return false;
|
||||
}
|
||||
sync_directory(m_directory);
|
||||
return true;
|
||||
}
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::filesystem::path m_directory;
|
||||
std::filesystem::path m_path;
|
||||
std::uint64_t m_term{0};
|
||||
std::optional<std::string> m_voted_for;
|
||||
std::vector<LogEntry> m_log;
|
||||
std::uint64_t m_commit{0};
|
||||
std::map<std::string, std::string, std::less<>> m_kv;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
query(std::string_view text, std::string_view name)
|
||||
{
|
||||
std::size_t pos = 0;
|
||||
while (pos <= text.size()) {
|
||||
const std::size_t amp = text.find('&', pos);
|
||||
const std::string_view pair =
|
||||
text.substr(pos, amp == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: amp - pos);
|
||||
const std::size_t eq = pair.find('=');
|
||||
if (pair.substr(0, eq) == name) {
|
||||
return eq == std::string_view::npos ? std::string_view{}
|
||||
: pair.substr(eq + 1);
|
||||
}
|
||||
if (amp == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = amp + 1;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t> number(std::string_view text)
|
||||
{
|
||||
if (text.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::uint64_t value = 0;
|
||||
const auto parsed =
|
||||
std::from_chars(text.data(), text.data() + text.size(), value);
|
||||
if (parsed.ec != std::errc{}) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
|
||||
std::string body)
|
||||
{
|
||||
Void::Net::ServerResponse response;
|
||||
response.status = static_cast<std::uint16_t>(status);
|
||||
response.headers.push_back(
|
||||
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
std::filesystem::path directory;
|
||||
std::uint16_t port = 0;
|
||||
std::string token;
|
||||
long long parent{0};
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
if (arg == "--dir" && i + 1 < argc) {
|
||||
directory = argv[++i];
|
||||
} else if (arg == "--parent" && i + 1 < argc) {
|
||||
parent = std::strtoll(argv[++i], nullptr, 10);
|
||||
} else if (arg == "--port" && i + 1 < argc) {
|
||||
unsigned int value = 0;
|
||||
const auto parsed = std::from_chars(argv[i + 1],
|
||||
argv[i + 1] + std::strlen(argv[i + 1]),
|
||||
value);
|
||||
if (parsed.ec != std::errc{} || value > 65535U) {
|
||||
std::fprintf(stderr, "invalid --port\n");
|
||||
return 2;
|
||||
}
|
||||
port = static_cast<std::uint16_t>(value);
|
||||
++i;
|
||||
} else if (arg == "--token" && i + 1 < argc) {
|
||||
token = argv[++i];
|
||||
}
|
||||
}
|
||||
if (directory.empty() || token.empty()) {
|
||||
std::fprintf(stderr,
|
||||
"usage: distributed_voter_agent --dir <path> "
|
||||
"--port <port|0> --token <token>\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
VoterStore store{directory};
|
||||
if (!store.load()) {
|
||||
std::fprintf(stderr, "voter agent: failed to load durable state\n");
|
||||
return 3;
|
||||
}
|
||||
|
||||
Void::Net::HttpServerOptions options;
|
||||
options.bind_host = "127.0.0.1";
|
||||
options.port = port;
|
||||
options.max_concurrent_connections = 8;
|
||||
options.max_body_bytes = 64ULL * 1024ULL;
|
||||
Void::Net::HttpServer server{options};
|
||||
|
||||
auto guarded = [token](const Void::Net::ServerRequest& request)
|
||||
-> std::optional<Void::Net::ServerResponse> {
|
||||
const auto header = request.header("authorization");
|
||||
const std::string expected = "Bearer " + token;
|
||||
if (!header || *header != expected) {
|
||||
return text_response(401, "unauthorized");
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
|
||||
auto add = [&](Void::Net::Method method, const char* pattern, auto fn) {
|
||||
return server.add_route(
|
||||
method, pattern,
|
||||
[guarded, fn](const Void::Net::ServerRequest& request)
|
||||
-> Void::Net::RouteResult {
|
||||
if (auto denied = guarded(request)) {
|
||||
return Void::Result::ok(std::move(*denied));
|
||||
}
|
||||
return Void::Result::ok(fn(request));
|
||||
});
|
||||
};
|
||||
|
||||
auto registered = add(
|
||||
Void::Net::Method::Get, "/voter/state",
|
||||
[&store](const Void::Net::ServerRequest&) {
|
||||
return text_response(
|
||||
200, "term=" + std::to_string(store.term()) +
|
||||
" voted=" + store.voted_for() +
|
||||
" last_index=" + std::to_string(store.last_index()) +
|
||||
" last_term=" + std::to_string(store.last_term()) +
|
||||
" commit=" + std::to_string(store.commit()) +
|
||||
" entries=" + std::to_string(store.log_size()));
|
||||
});
|
||||
if (!registered) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/voter/vote",
|
||||
[&store](const Void::Net::ServerRequest& request) {
|
||||
const auto term = number(query(request.query, "term").value_or(""));
|
||||
const auto last_index =
|
||||
number(query(request.query, "last_index").value_or(""));
|
||||
const auto last_term =
|
||||
number(query(request.query, "last_term").value_or(""));
|
||||
const auto candidate = query(request.query, "candidate");
|
||||
if (!term || !last_index || !last_term || !candidate ||
|
||||
!safe_token(*candidate)) {
|
||||
return text_response(400, "bad vote request");
|
||||
}
|
||||
if (!store.vote(*term, *candidate, *last_index, *last_term)) {
|
||||
return text_response(409, "vote rejected");
|
||||
}
|
||||
return text_response(200, "granted");
|
||||
});
|
||||
if (!registered) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/voter/append",
|
||||
[&store](const Void::Net::ServerRequest& request) {
|
||||
const auto term = number(query(request.query, "term").value_or(""));
|
||||
const auto prev_index =
|
||||
number(query(request.query, "prev_index").value_or(""));
|
||||
const auto prev_term =
|
||||
number(query(request.query, "prev_term").value_or(""));
|
||||
const auto commit =
|
||||
number(query(request.query, "commit").value_or(""));
|
||||
if (!term || !prev_index || !prev_term || !commit) {
|
||||
return text_response(400, "bad append request");
|
||||
}
|
||||
std::vector<LogEntry> entries;
|
||||
std::size_t pos = 0;
|
||||
while (pos < request.body.size()) {
|
||||
const std::size_t end = request.body.find('\n', pos);
|
||||
const std::string_view line = std::string_view{request.body}.substr(
|
||||
pos, end == std::string::npos ? std::string::npos : end - pos);
|
||||
if (!line.empty()) {
|
||||
LogEntry entry;
|
||||
std::string key;
|
||||
std::string value;
|
||||
const std::size_t first = line.find(',');
|
||||
const std::size_t second =
|
||||
first == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: line.find(',', first + 1);
|
||||
const std::size_t third =
|
||||
second == std::string_view::npos
|
||||
? std::string_view::npos
|
||||
: line.find(',', second + 1);
|
||||
if (first == std::string_view::npos ||
|
||||
second == std::string_view::npos ||
|
||||
third == std::string_view::npos) {
|
||||
return text_response(400, "bad entry");
|
||||
}
|
||||
const auto entry_term = number(line.substr(0, first));
|
||||
const auto entry_index =
|
||||
number(line.substr(first + 1, second - first - 1));
|
||||
key = line.substr(second + 1, third - second - 1);
|
||||
value = line.substr(third + 1);
|
||||
if (!entry_term || !entry_index || !safe_token(key) ||
|
||||
!(safe_token(value) || value == "-")) {
|
||||
return text_response(400, "bad entry");
|
||||
}
|
||||
entry.term = *entry_term;
|
||||
entry.index = *entry_index;
|
||||
entry.key = key;
|
||||
entry.value = value;
|
||||
entries.push_back(std::move(entry));
|
||||
}
|
||||
if (end == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
const auto matched =
|
||||
store.append(*term, *prev_index, *prev_term, *commit, entries);
|
||||
if (!matched) {
|
||||
return text_response(409, "append rejected");
|
||||
}
|
||||
return text_response(200, "matched=" + std::to_string(*matched));
|
||||
});
|
||||
if (!registered) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Get, "/voter/value",
|
||||
[&store](const Void::Net::ServerRequest& request) {
|
||||
const auto key = query(request.query, "key");
|
||||
if (!key) {
|
||||
return text_response(400, "key required");
|
||||
}
|
||||
const auto value = store.value(*key);
|
||||
if (!value) {
|
||||
return text_response(404, "not found");
|
||||
}
|
||||
return text_response(200, *value);
|
||||
});
|
||||
if (!registered) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Get, "/voter/entries",
|
||||
[&store](const Void::Net::ServerRequest& request) {
|
||||
const auto from = number(query(request.query, "from").value_or("1"));
|
||||
if (!from) {
|
||||
return text_response(400, "from required");
|
||||
}
|
||||
std::string body;
|
||||
for (const auto& entry : store.entries_from(*from)) {
|
||||
body += std::to_string(entry.term) + "," +
|
||||
std::to_string(entry.index) + "," + entry.key + "," +
|
||||
entry.value + "\n";
|
||||
}
|
||||
return text_response(200, std::move(body));
|
||||
});
|
||||
if (!registered) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
if (auto started = server.start(); !started) {
|
||||
std::fprintf(stderr, "voter agent: failed to bind listener\n");
|
||||
return 5;
|
||||
}
|
||||
|
||||
{
|
||||
const auto port_path = directory / "port";
|
||||
std::ofstream out{port_path, std::ios::trunc};
|
||||
out << server.bound_port() << "\n";
|
||||
}
|
||||
|
||||
// Serve until the parent kills this process. An agent whose supervising
|
||||
// parent disappeared exits on its own so it can never orphan and hold the
|
||||
// harness's output pipes open.
|
||||
while (parent == 0 || ::getppid() == parent) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{200});
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
// Applications-stack workload baseline.
|
||||
//
|
||||
// Measures the replicated KV propose/quorum-read paths, the replicated
|
||||
// queue publish/claim/ack path and the three-listener HTTP fixture roundtrip.
|
||||
// Each case runs warmup, several repetitions, and reports p50/p95/p99 plus a
|
||||
// 95% confidence interval for the mean. No latency threshold is asserted:
|
||||
// numbers are workload baselines, per PERFORMANCE.md.
|
||||
//
|
||||
// host_graph_bench [--quick] [--json <path>]
|
||||
|
||||
#include "distributed_host/cluster_fixture.hpp"
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
#include "distributed_host/replicated_queue.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
void check(bool condition, const char* what)
|
||||
{
|
||||
if (!condition) {
|
||||
std::fprintf(stderr, "benchmark invariant failed: %s\n", what);
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
struct Stats {
|
||||
std::string name;
|
||||
std::size_t samples{0};
|
||||
double p50_ns{0};
|
||||
double p95_ns{0};
|
||||
double p99_ns{0};
|
||||
double mean_ns{0};
|
||||
double ci95_low_ns{0};
|
||||
double ci95_high_ns{0};
|
||||
double ops_per_sec{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] double percentile(std::vector<double> values, double p)
|
||||
{
|
||||
if (values.empty()) {
|
||||
return 0;
|
||||
}
|
||||
std::ranges::sort(values);
|
||||
const double rank = (p / 100.0) * static_cast<double>(values.size());
|
||||
auto index = static_cast<std::size_t>(std::ceil(rank));
|
||||
index = index == 0 ? 0 : index - 1;
|
||||
return values[std::min(index, values.size() - 1)];
|
||||
}
|
||||
|
||||
class Bench {
|
||||
public:
|
||||
|
||||
Bench(std::string name, std::size_t reps, std::size_t ops,
|
||||
std::size_t warmup = 3)
|
||||
: m_name(std::move(name)), m_reps(reps), m_ops(ops),
|
||||
m_warmup(warmup)
|
||||
{
|
||||
}
|
||||
|
||||
/// `fn` runs outside the timer for setup/epoch resets; `op` is the
|
||||
/// measured operation.
|
||||
void run(const std::function<void()>& setup,
|
||||
const std::function<void()>& op)
|
||||
{
|
||||
for (std::size_t i = 0; i < m_warmup; ++i) {
|
||||
setup();
|
||||
op();
|
||||
}
|
||||
m_samples.reserve(m_reps * m_ops);
|
||||
for (std::size_t rep = 0; rep < m_reps; ++rep) {
|
||||
std::size_t epoch = 0;
|
||||
for (std::size_t i = 0; i < m_ops; ++i) {
|
||||
if (epoch == 0) {
|
||||
setup();
|
||||
epoch = kEpochOps;
|
||||
}
|
||||
--epoch;
|
||||
const auto begin = Clock::now();
|
||||
op();
|
||||
const auto elapsed = Clock::now() - begin;
|
||||
m_samples.push_back(
|
||||
static_cast<double>(
|
||||
std::chrono::duration_cast<
|
||||
std::chrono::nanoseconds>(elapsed)
|
||||
.count()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Stats stats() const
|
||||
{
|
||||
Stats out;
|
||||
out.name = m_name;
|
||||
out.samples = m_samples.size();
|
||||
double total = 0;
|
||||
for (const double sample : m_samples) {
|
||||
total += sample;
|
||||
}
|
||||
out.mean_ns = m_samples.empty() ? 0 : total / m_samples.size();
|
||||
double variance = 0;
|
||||
for (const double sample : m_samples) {
|
||||
const double delta = sample - out.mean_ns;
|
||||
variance += delta * delta;
|
||||
}
|
||||
variance = m_samples.size() > 1
|
||||
? variance / (m_samples.size() - 1)
|
||||
: 0;
|
||||
const double standard_error =
|
||||
std::sqrt(variance / static_cast<double>(m_samples.size()));
|
||||
out.ci95_low_ns = std::max(0.0, out.mean_ns - 1.96 * standard_error);
|
||||
out.ci95_high_ns = out.mean_ns + 1.96 * standard_error;
|
||||
out.p50_ns = percentile(m_samples, 50);
|
||||
out.p95_ns = percentile(m_samples, 95);
|
||||
out.p99_ns = percentile(m_samples, 99);
|
||||
out.ops_per_sec =
|
||||
out.mean_ns > 0 ? 1e9 / out.mean_ns : 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static constexpr std::size_t kEpochOps = 32;
|
||||
|
||||
std::string m_name;
|
||||
std::size_t m_reps;
|
||||
std::size_t m_ops;
|
||||
std::size_t m_warmup;
|
||||
std::vector<double> m_samples;
|
||||
};
|
||||
|
||||
struct Options {
|
||||
bool quick{false};
|
||||
std::string json_path{};
|
||||
};
|
||||
|
||||
[[nodiscard]] Options parse_options(int argc, char** argv)
|
||||
{
|
||||
Options options;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string_view arg{argv[i]};
|
||||
if (arg == "--quick") {
|
||||
options.quick = true;
|
||||
} else if (arg == "--json" && i + 1 < argc) {
|
||||
options.json_path = argv[++i];
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
[[nodiscard]] DistributedHost::ReplicatedKvCluster
|
||||
fresh_cluster(std::string& leader)
|
||||
{
|
||||
DistributedHost::ReplicatedKvCluster cluster{{"a", "b", "c"}};
|
||||
check(cluster.elect("a").has_value(), "elect leader");
|
||||
leader = "a";
|
||||
return cluster;
|
||||
}
|
||||
|
||||
void append_json(std::string& out, const Stats& stats)
|
||||
{
|
||||
out += std::format(
|
||||
" \"{}\": {{\"samples\": {}, \"p50_ns\": {:.2f}, "
|
||||
"\"p95_ns\": {:.2f}, \"p99_ns\": {:.2f}, \"mean_ns\": {:.2f}, "
|
||||
"\"ci95_ns\": [{:.2f}, {:.2f}], \"ops_per_sec\": {:.2f}}}",
|
||||
stats.name, stats.samples, stats.p50_ns, stats.p95_ns, stats.p99_ns,
|
||||
stats.mean_ns, stats.ci95_low_ns, stats.ci95_high_ns,
|
||||
stats.ops_per_sec);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
const Options options = parse_options(argc, argv);
|
||||
const std::size_t reps = options.quick ? 1 : 5;
|
||||
const std::size_t ops = options.quick ? 16 : 200;
|
||||
|
||||
std::vector<Stats> results;
|
||||
|
||||
// ── replicated KV propose ─────────────────────────────────────────────
|
||||
{
|
||||
std::optional<ReplicatedKvCluster> cluster;
|
||||
std::string leader;
|
||||
std::uint64_t sequence = 0;
|
||||
Bench bench{"kv_propose_3node", reps, ops};
|
||||
bench.run(
|
||||
[&] {
|
||||
cluster = fresh_cluster(leader);
|
||||
sequence = 0;
|
||||
},
|
||||
[&] {
|
||||
const auto reply = cluster->propose(
|
||||
leader, "key-" + std::to_string(sequence), std::string{"value"});
|
||||
check(reply.outcome == KvWriteOutcome::Applied,
|
||||
"propose is majority-committed");
|
||||
++sequence;
|
||||
});
|
||||
results.push_back(bench.stats());
|
||||
}
|
||||
|
||||
// ── replicated KV quorum read ────────────────────────────────────────
|
||||
{
|
||||
std::string leader;
|
||||
auto cluster = fresh_cluster(leader);
|
||||
check(cluster.propose(leader, "hot", std::string{"value"}).outcome ==
|
||||
KvWriteOutcome::Applied,
|
||||
"seed value");
|
||||
Bench bench{"kv_quorum_read_3node", reps, ops * 5};
|
||||
bench.run([] {}, [&] {
|
||||
auto read = cluster.quorum_read(leader, "hot");
|
||||
check(read.has_value() && read->has_value(), "quorum read");
|
||||
});
|
||||
results.push_back(bench.stats());
|
||||
}
|
||||
|
||||
// ── replicated queue publish/claim/ack ───────────────────────────────
|
||||
{
|
||||
std::optional<ReplicatedKvCluster> cluster;
|
||||
std::optional<ReplicatedQueue> queue;
|
||||
std::uint64_t sequence = 0;
|
||||
QueueConfig config;
|
||||
config.max_jobs = 1000000;
|
||||
Bench bench{"queue_publish_claim_ack_3node", reps, ops};
|
||||
bench.run(
|
||||
[&] {
|
||||
std::string leader;
|
||||
cluster = fresh_cluster(leader);
|
||||
queue.emplace(*cluster, leader, config);
|
||||
sequence = 0;
|
||||
},
|
||||
[&] {
|
||||
const std::string key = "job-" + std::to_string(sequence++);
|
||||
auto id = queue->publish("payload", key);
|
||||
check(id.has_value(), "publish");
|
||||
auto claimed = queue->claim("worker");
|
||||
check(claimed.has_value() && claimed->has_value(), "claim");
|
||||
check(queue->ack("worker", *id).has_value(), "ack");
|
||||
});
|
||||
results.push_back(bench.stats());
|
||||
}
|
||||
|
||||
// ── HTTP fixture roundtrip ────────────────────────────────────────────
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
check(fixture.has_value(), "fixture create");
|
||||
check((*fixture)->start().has_value(), "fixture start");
|
||||
const std::string url = (*fixture)->endpoint("a") + "/peer/health";
|
||||
Void::Net::HttpClient client;
|
||||
const std::vector<Void::Net::Header> headers{
|
||||
Void::Net::Header{"authorization", "Bearer peer-secret"}};
|
||||
Bench bench{"http_peer_health_roundtrip", reps, ops};
|
||||
bench.run([] {}, [&] {
|
||||
auto response = client.get(url, headers);
|
||||
check(response.has_value() && response->status == 200,
|
||||
"http health roundtrip");
|
||||
});
|
||||
results.push_back(bench.stats());
|
||||
(*fixture)->stop();
|
||||
}
|
||||
|
||||
for (const auto& stats : results) {
|
||||
std::printf(
|
||||
"%-28s samples=%-6zu p50=%10.1fns p95=%10.1fns p99=%10.1fns "
|
||||
"mean=%10.1fns ci95=[%.1f, %.1f] %.0f ops/s\n",
|
||||
stats.name.c_str(), stats.samples, stats.p50_ns, stats.p95_ns,
|
||||
stats.p99_ns, stats.mean_ns, stats.ci95_low_ns, stats.ci95_high_ns,
|
||||
stats.ops_per_sec);
|
||||
}
|
||||
|
||||
if (!options.json_path.empty()) {
|
||||
std::ofstream out{options.json_path};
|
||||
check(out.is_open(), "open json output");
|
||||
out << "{\n \"reps\": " << reps << ", \"ops_per_rep\": " << ops
|
||||
<< ",\n \"cases\": {\n";
|
||||
for (std::size_t i = 0; i < results.size(); ++i) {
|
||||
std::string line;
|
||||
append_json(line, results[i]);
|
||||
out << line << (i + 1 == results.size() ? "\n" : ",\n");
|
||||
}
|
||||
out << " }\n}\n";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
#include "distributed_host/replicated_queue.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
struct ClusterFixtureConfig {
|
||||
/// Required bearer token for every peer and admin route.
|
||||
std::string token{"peer-secret"};
|
||||
std::size_t max_connections{8};
|
||||
std::chrono::milliseconds shutdown_grace{
|
||||
std::chrono::seconds{2}};
|
||||
/// Queue policy shared by every node handler.
|
||||
QueueConfig queue{};
|
||||
/// Bounded recorded outbox deliveries.
|
||||
std::size_t max_delivered{1024};
|
||||
};
|
||||
|
||||
/// Three-node replicated KV reference over real loopback HTTP listeners.
|
||||
///
|
||||
/// Each voter owns one `Void::Net::HttpServer`. Peer routes drive the
|
||||
/// deterministic replication core (elect, propose, read, heartbeat); an
|
||||
/// authenticated admin route models partitions for crash/partition
|
||||
/// histories. The transport is real; consensus timing is deterministic.
|
||||
///
|
||||
/// Routes (all require `Authorization: Bearer <token>`):
|
||||
/// GET /peer/health role/term/commit/applied
|
||||
/// POST /peer/elect become a candidate
|
||||
/// PUT /peer/propose?key=K body = value
|
||||
/// DELETE /peer/propose?key=K erase
|
||||
/// GET /peer/read?key=K consistent quorum read
|
||||
/// POST /peer/heartbeat replicate log and commit index
|
||||
/// POST /admin/partition?node=X&partition=N
|
||||
/// POST /admin/crash?node=X
|
||||
/// POST /admin/restart?node=X
|
||||
///
|
||||
/// Replicated worker queue over the same group:
|
||||
/// POST /queue/publish?key=K body = payload
|
||||
/// POST /queue/claim?consumer=C
|
||||
/// POST /queue/ack?consumer=C&id=J
|
||||
/// POST /queue/nack?consumer=C&id=J body = reason
|
||||
/// POST /queue/recover?consumer=C
|
||||
/// POST /queue/dispatch deliver pending outbox effects
|
||||
/// GET /queue/status?id=J
|
||||
/// GET /queue/dlq
|
||||
/// GET /queue/delivered
|
||||
class ClusterFixture
|
||||
{
|
||||
public:
|
||||
|
||||
ClusterFixture(const ClusterFixture&) = delete;
|
||||
ClusterFixture& operator=(const ClusterFixture&) = delete;
|
||||
ClusterFixture(ClusterFixture&&) = delete;
|
||||
ClusterFixture& operator=(ClusterFixture&&) = delete;
|
||||
~ClusterFixture();
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::unique_ptr<ClusterFixture>>
|
||||
create(ClusterFixtureConfig config = {});
|
||||
|
||||
/// Bind and start every listener. Construction alone opens none.
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
/// Bounded, idempotent shutdown of every listener.
|
||||
void stop() noexcept;
|
||||
|
||||
/// `http://127.0.0.1:<port>` for one voter, or an empty string
|
||||
/// when it is unknown or not listening.
|
||||
[[nodiscard]] std::string endpoint(std::string_view node) const;
|
||||
|
||||
[[nodiscard]] const std::vector<std::string>& voters() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct PeerServer {
|
||||
std::string id;
|
||||
std::unique_ptr<Void::Net::HttpServer> server;
|
||||
};
|
||||
|
||||
explicit ClusterFixture(ClusterFixtureConfig config);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
register_routes(PeerServer& peer);
|
||||
|
||||
ClusterFixtureConfig m_config;
|
||||
ReplicatedKvCluster m_cluster;
|
||||
mutable std::mutex m_mutex;
|
||||
std::vector<std::unique_ptr<PeerServer>> m_peers;
|
||||
std::vector<std::string> m_delivered;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,190 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
using NodeId = std::string;
|
||||
|
||||
struct HostConfig {
|
||||
std::string cluster{"cluster"};
|
||||
NodeId self{"node-1"};
|
||||
std::vector<NodeId> peers{};
|
||||
/// Require an available leader path before reporting write readiness.
|
||||
bool require_leader_readiness{true};
|
||||
/// Optional discovery publication; disabled means no adapter call.
|
||||
bool publish_discovery{true};
|
||||
std::chrono::milliseconds startup_deadline{
|
||||
std::chrono::seconds{5}};
|
||||
};
|
||||
|
||||
/// Readiness is per capability, not a single boolean:
|
||||
/// a follower may be live and readable while not accepting writes.
|
||||
enum class Readiness : std::uint8_t {
|
||||
Starting,
|
||||
/// Process is live but no leader path is known: reads by explicit
|
||||
/// policy only, never writes.
|
||||
FollowerHealthy,
|
||||
/// Leader path available and local state recovered.
|
||||
WriteReady,
|
||||
Stopping,
|
||||
Stopped,
|
||||
Failed
|
||||
};
|
||||
|
||||
enum class Role : std::uint8_t { Follower, Candidate, Leader };
|
||||
|
||||
[[nodiscard]] constexpr std::string_view
|
||||
readiness_name(Readiness readiness) noexcept
|
||||
{
|
||||
switch (readiness) {
|
||||
case Readiness::Starting: return "starting";
|
||||
case Readiness::FollowerHealthy: return "follower-healthy";
|
||||
case Readiness::WriteReady: return "write-ready";
|
||||
case Readiness::Stopping: return "stopping";
|
||||
case Readiness::Stopped: return "stopped";
|
||||
case Readiness::Failed: return "failed";
|
||||
}
|
||||
return "failed";
|
||||
}
|
||||
|
||||
struct HealthSnapshot {
|
||||
Readiness readiness{Readiness::Starting};
|
||||
Role role{Role::Follower};
|
||||
bool quorum_available{false};
|
||||
std::size_t started_components{0};
|
||||
std::string last_error;
|
||||
};
|
||||
|
||||
/// Storage boundary owned by the Storage subsystem in the real platform.
|
||||
/// Tests supply deterministic fakes; the host graph never implements it.
|
||||
class StorageBackend
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~StorageBackend() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> open() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> recover() = 0;
|
||||
virtual void close() noexcept = 0;
|
||||
};
|
||||
|
||||
/// Authenticated peer transport boundary.
|
||||
class PeerTransport
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~PeerTransport() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> listen() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
connect_peers(const std::vector<NodeId>& peers) = 0;
|
||||
virtual void close() noexcept = 0;
|
||||
};
|
||||
|
||||
/// Replication adapter supplying role and leader availability.
|
||||
class ReplicationAdapter
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ReplicationAdapter() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> start() = 0;
|
||||
[[nodiscard]] virtual Role role() const noexcept = 0;
|
||||
[[nodiscard]] virtual bool leader_available() const noexcept = 0;
|
||||
virtual void stop() noexcept = 0;
|
||||
};
|
||||
|
||||
/// Optional directory publication (Discovery). Failures are observation
|
||||
/// failures, never quorum votes.
|
||||
class DirectoryPublisher
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~DirectoryPublisher() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
publish(const NodeId& self) = 0;
|
||||
virtual void withdraw() noexcept = 0;
|
||||
};
|
||||
|
||||
/// Borrowed resources. The graph never owns or destroys them; they must
|
||||
/// outlive the graph through final join.
|
||||
struct HostResources {
|
||||
StorageBackend* storage{nullptr};
|
||||
PeerTransport* transport{nullptr};
|
||||
ReplicationAdapter* replication{nullptr};
|
||||
/// Optional: null disables discovery even when configured on.
|
||||
DirectoryPublisher* directory{nullptr};
|
||||
};
|
||||
|
||||
/// Single-node composition skeleton for the distributed reference host.
|
||||
///
|
||||
/// Startup is a dependency-ordered transaction: storage open/recover,
|
||||
/// peer transport, replication, readiness, then optional discovery. A
|
||||
/// failure unwinds started components in reverse order and preserves the
|
||||
/// original error. Construction starts nothing.
|
||||
class DistributedHostGraph
|
||||
{
|
||||
public:
|
||||
|
||||
DistributedHostGraph(const DistributedHostGraph&) = delete;
|
||||
DistributedHostGraph& operator=(const DistributedHostGraph&) = delete;
|
||||
DistributedHostGraph(DistributedHostGraph&& other) noexcept;
|
||||
DistributedHostGraph& operator=(DistributedHostGraph&&) = delete;
|
||||
~DistributedHostGraph();
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<DistributedHostGraph>
|
||||
compose(HostResources resources, HostConfig config = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
/// Stop external admission first, then components in reverse
|
||||
/// startup order. Idempotent and never destroys borrowed
|
||||
/// resources.
|
||||
void stop() noexcept;
|
||||
|
||||
[[nodiscard]] HealthSnapshot health() const;
|
||||
|
||||
[[nodiscard]] Readiness readiness() const noexcept
|
||||
{
|
||||
return m_readiness;
|
||||
}
|
||||
|
||||
/// Deterministic records used by tests and inspect: the exact
|
||||
/// order of component lifecycle calls.
|
||||
[[nodiscard]] const std::vector<std::string>& history() const noexcept
|
||||
{
|
||||
return m_history;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
DistributedHostGraph(HostResources resources, HostConfig config);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start_storage();
|
||||
[[nodiscard]] Void::Result::Result<void> start_transport();
|
||||
[[nodiscard]] Void::Result::Result<void> start_replication();
|
||||
[[nodiscard]] Void::Result::Result<void> publish_directory();
|
||||
/// Reverse-order unwind of everything recorded as started.
|
||||
void unwind() noexcept;
|
||||
|
||||
void record(std::string step);
|
||||
|
||||
HostResources m_resources;
|
||||
HostConfig m_config;
|
||||
std::vector<std::string> m_history;
|
||||
std::size_t m_started{0};
|
||||
bool m_storage_open{false};
|
||||
bool m_transport_live{false};
|
||||
bool m_replication_started{false};
|
||||
bool m_directory_published{false};
|
||||
bool m_stopped{false};
|
||||
Readiness m_readiness{Readiness::Starting};
|
||||
std::string m_last_error;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,261 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
// ── Backup / restore ────────────────────────────────────────────────────
|
||||
|
||||
/// Stable cluster identity that a backup carries. A restore rehearsal must
|
||||
/// retain it: restoring into a differently identified cluster would merge
|
||||
/// unrelated histories.
|
||||
struct ClusterIdentity {
|
||||
std::string cluster;
|
||||
std::vector<std::string> voters;
|
||||
|
||||
[[nodiscard]] bool operator==(const ClusterIdentity& other) const
|
||||
{
|
||||
return cluster == other.cluster &&
|
||||
std::ranges::is_permutation(voters, other.voters);
|
||||
}
|
||||
};
|
||||
|
||||
struct ClusterBackup {
|
||||
ClusterIdentity identity;
|
||||
/// Commit index observed when the backup was captured.
|
||||
std::uint64_t commit_index{0};
|
||||
/// Quorum-confirmed applied state at that point.
|
||||
std::map<std::string, std::string, std::less<>> state;
|
||||
};
|
||||
|
||||
/// Capture a consistent backup from a quorum-confirmed leader.
|
||||
[[nodiscard]] inline Void::Result::Result<ClusterBackup> capture_backup(
|
||||
ReplicatedKvCluster& cluster, std::string_view leader,
|
||||
ClusterIdentity identity)
|
||||
{
|
||||
auto snapshot = cluster.quorum_snapshot(leader);
|
||||
if (!snapshot) {
|
||||
return std::unexpected{std::move(snapshot).error()};
|
||||
}
|
||||
ClusterBackup backup;
|
||||
backup.identity = std::move(identity);
|
||||
backup.commit_index = cluster.committed_index();
|
||||
backup.state = std::move(*snapshot);
|
||||
return backup;
|
||||
}
|
||||
|
||||
/// Restore a backup into an empty, separately identified cluster.
|
||||
///
|
||||
/// The target identity must match the backup exactly. Every entry is
|
||||
/// written through the leader and must be majority-committed; a failed
|
||||
/// write stops the restore with the partial state left visible.
|
||||
[[nodiscard]] inline Void::Result::Result<std::size_t> restore_backup(
|
||||
ReplicatedKvCluster& cluster, std::string_view leader,
|
||||
const ClusterBackup& backup, const ClusterIdentity& target)
|
||||
{
|
||||
if (!(backup.identity == target)) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
"Restore: cluster identity does not match the backup"}};
|
||||
}
|
||||
std::size_t restored = 0;
|
||||
for (const auto& [key, value] : backup.state) {
|
||||
const KvWriteReply reply = cluster.propose(leader, key, value);
|
||||
if (reply.outcome != KvWriteOutcome::Applied) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
"Restore: entry was not majority-committed"}};
|
||||
}
|
||||
++restored;
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
// ── Trust rotation ──────────────────────────────────────────────────────
|
||||
|
||||
struct TrustGeneration {
|
||||
std::uint64_t id{0};
|
||||
std::vector<std::string> fingerprints;
|
||||
};
|
||||
|
||||
/// Overlapping trust generations for credential rotation.
|
||||
///
|
||||
/// Rotation validates the new generation while the old one stays trusted,
|
||||
/// so live connections drain without ever disabling verification. An empty
|
||||
/// trust set trusts nothing (fail closed).
|
||||
class TrustStore
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TrustStore(std::vector<std::string> initial_fingerprints = {})
|
||||
{
|
||||
if (!initial_fingerprints.empty()) {
|
||||
m_generations.push_back(
|
||||
TrustGeneration{m_next_id++, std::move(initial_fingerprints)});
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool trusted(std::string_view fingerprint) const noexcept
|
||||
{
|
||||
if (fingerprint.empty()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& generation : m_generations) {
|
||||
if (std::ranges::find(generation.fingerprints, fingerprint) !=
|
||||
generation.fingerprints.end()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Add a new trusted generation while keeping the old ones.
|
||||
/// Returns the new generation id.
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
begin_rotation(std::vector<std::string> new_fingerprints)
|
||||
{
|
||||
if (new_fingerprints.empty()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
"TrustStore: a rotation needs at least one fingerprint"}};
|
||||
}
|
||||
m_generations.push_back(
|
||||
TrustGeneration{m_next_id++, std::move(new_fingerprints)});
|
||||
return m_generations.back().id;
|
||||
}
|
||||
|
||||
/// Revoke every generation older than `generation` after the
|
||||
/// overlap drained. The chosen generation must be active.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
complete_rotation(std::uint64_t generation)
|
||||
{
|
||||
const auto found = std::ranges::find_if(
|
||||
m_generations, [generation](const TrustGeneration& candidate) {
|
||||
return candidate.id == generation;
|
||||
});
|
||||
if (found == m_generations.end()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::not_found,
|
||||
"TrustStore: unknown trust generation"}};
|
||||
}
|
||||
std::erase_if(m_generations,
|
||||
[generation](const TrustGeneration& candidate) {
|
||||
return candidate.id < generation;
|
||||
});
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t active_generations() const noexcept
|
||||
{
|
||||
return m_generations.size();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::vector<TrustGeneration> m_generations;
|
||||
std::uint64_t m_next_id{1};
|
||||
};
|
||||
|
||||
// ── Mixed-version rollout ──────────────────────────────────────────────
|
||||
|
||||
struct VersionPolicy {
|
||||
/// Format version this binary writes.
|
||||
std::uint32_t format_version{2};
|
||||
/// Oldest node version that can still read existing durable data.
|
||||
std::uint32_t min_reader{1};
|
||||
};
|
||||
|
||||
/// Per-voter version advertisement gate.
|
||||
///
|
||||
/// Readers may roll out first (every node must still read the durable
|
||||
/// format), and a new command is admitted only when every voter
|
||||
/// advertises support. Unknown voters are rejected rather than assumed
|
||||
/// current.
|
||||
class RolloutGate
|
||||
{
|
||||
public:
|
||||
|
||||
RolloutGate(std::vector<std::string> voters, VersionPolicy policy)
|
||||
: m_policy(policy)
|
||||
{
|
||||
for (auto& voter : voters) {
|
||||
m_advertised.emplace(std::move(voter), 0);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
report_version(std::string_view node, std::uint32_t version)
|
||||
{
|
||||
const auto found = m_advertised.find(node);
|
||||
if (found == m_advertised.end()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::not_found,
|
||||
"RolloutGate: unknown voter"}};
|
||||
}
|
||||
found->second = version;
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
admit_read(std::string_view node) const
|
||||
{
|
||||
const auto found = m_advertised.find(node);
|
||||
if (found == m_advertised.end()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::not_found,
|
||||
"RolloutGate: unknown voter"}};
|
||||
}
|
||||
if (found->second < m_policy.min_reader) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::unsupported,
|
||||
"RolloutGate: node cannot read the durable format"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/// A new command requires every voter to advertise it.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
admit_new_command(std::string_view node) const
|
||||
{
|
||||
if (m_advertised.find(node) == m_advertised.end()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::not_found,
|
||||
"RolloutGate: unknown voter"}};
|
||||
}
|
||||
for (const auto& [id, version] : m_advertised) {
|
||||
(void)id;
|
||||
if (version < m_policy.format_version) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::unsupported,
|
||||
"RolloutGate: not every voter advertises the new "
|
||||
"command"}};
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool all_advertised() const noexcept
|
||||
{
|
||||
return std::ranges::all_of(
|
||||
m_advertised, [this](const auto& entry) {
|
||||
return entry.second >= m_policy.format_version;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
VersionPolicy m_policy;
|
||||
std::map<std::string, std::uint32_t, std::less<>> m_advertised;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,163 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
/// Half-open key range `[start, end)`.
|
||||
struct KeyRange {
|
||||
std::string start;
|
||||
std::string end;
|
||||
|
||||
[[nodiscard]] bool contains(std::string_view key) const noexcept
|
||||
{
|
||||
return key >= start && key < end;
|
||||
}
|
||||
[[nodiscard]] bool valid() const noexcept { return start < end; }
|
||||
[[nodiscard]] bool operator==(const KeyRange&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct RangeOwnership {
|
||||
KeyRange range;
|
||||
std::string owner;
|
||||
|
||||
[[nodiscard]] bool operator==(const RangeOwnership&) const noexcept =
|
||||
default;
|
||||
};
|
||||
|
||||
enum class MovePhase : std::uint8_t {
|
||||
None,
|
||||
/// Writes for the range are rejected; reads stay with the source.
|
||||
Frozen,
|
||||
/// The target reported a complete verified copy; completing is safe.
|
||||
Verified,
|
||||
Completed,
|
||||
Aborted
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string_view move_phase_name(MovePhase phase) noexcept;
|
||||
|
||||
struct MoveRecord {
|
||||
std::uint64_t id{0};
|
||||
KeyRange range;
|
||||
std::string source;
|
||||
std::string target;
|
||||
MovePhase phase{MovePhase::None};
|
||||
std::size_t transferred{0};
|
||||
std::string note;
|
||||
};
|
||||
|
||||
/// Range ownership, freeze-based movement and replicated directory
|
||||
/// persistence.
|
||||
///
|
||||
/// Invariants:
|
||||
/// * ranges never overlap and every range has exactly one owner;
|
||||
/// * a range being moved rejects writes (reads remain with the source);
|
||||
/// * ownership switches only after the target's copy is verified;
|
||||
/// * crash recovery is deterministic: a verified move rolls forward,
|
||||
/// anything earlier rolls back, so ownership is never ambiguous.
|
||||
///
|
||||
/// Not thread-safe: the host serializes directory operations.
|
||||
class RangeDirectory
|
||||
{
|
||||
public:
|
||||
|
||||
explicit RangeDirectory(std::vector<std::string> voters);
|
||||
|
||||
[[nodiscard]] const std::vector<std::string>& voters() const noexcept
|
||||
{
|
||||
return m_voters;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
assign(KeyRange range, std::string owner);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
owner_of(std::string_view key) const;
|
||||
|
||||
[[nodiscard]] std::vector<RangeOwnership> ranges() const;
|
||||
|
||||
// ── movement ────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
begin_move(KeyRange range, std::string target);
|
||||
|
||||
/// Record entries copied to the target. Idempotent while frozen.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
transfer(std::uint64_t move_id, std::size_t entries);
|
||||
|
||||
/// The target certifies a complete copy of `entries` entries.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
verify(std::uint64_t move_id, std::size_t entries);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> complete(std::uint64_t move_id);
|
||||
void abort(std::uint64_t move_id, std::string reason) noexcept;
|
||||
|
||||
/// Write admission: rejected while the covering range is moving.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
admit_write(std::string_view key) const;
|
||||
|
||||
/// Reads stay with the source owner until completion.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
admit_read(std::string_view key) const;
|
||||
|
||||
// ── crash recovery ─────────────────────────────────────────────
|
||||
|
||||
enum class Recovery : std::uint8_t {
|
||||
None,
|
||||
RolledForward,
|
||||
RolledBack
|
||||
};
|
||||
|
||||
/// Resolve an interrupted move after a crash: verified copies are
|
||||
/// completed, anything earlier is aborted.
|
||||
[[nodiscard]] Void::Result::Result<Recovery>
|
||||
recover(std::uint64_t move_id);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<MoveRecord>
|
||||
move(std::uint64_t move_id) const;
|
||||
|
||||
// ── replicated directory persistence ───────────────────────────
|
||||
|
||||
/// Largest number of directory bytes accepted on load.
|
||||
static constexpr std::size_t max_directory_bytes = 64ULL * 1024ULL;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
persist(ReplicatedKvCluster& cluster, std::string_view leader,
|
||||
std::string_view key = default_key);
|
||||
|
||||
/// Replace the local directory from the replicated state. The
|
||||
/// loaded map is fully validated before it is installed.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
load(ReplicatedKvCluster& cluster, std::string_view leader,
|
||||
std::string_view key = default_key);
|
||||
|
||||
inline static constexpr std::string_view default_key =
|
||||
"__range_directory";
|
||||
|
||||
private:
|
||||
|
||||
struct ActiveMove {
|
||||
MoveRecord record;
|
||||
};
|
||||
|
||||
[[nodiscard]] bool known_voter(std::string_view owner) const;
|
||||
[[nodiscard]] const ActiveMove* active_for(const KeyRange& range) const;
|
||||
[[nodiscard]] ActiveMove* mutable_move(std::uint64_t move_id);
|
||||
[[nodiscard]] std::string encode() const;
|
||||
|
||||
std::vector<std::string> m_voters;
|
||||
std::map<std::string, RangeOwnership, std::less<>> m_ranges;
|
||||
std::map<std::uint64_t, ActiveMove> m_moves;
|
||||
std::uint64_t m_next_move{1};
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,157 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/host_graph.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
/// One replicated log entry. A missing value is an erase.
|
||||
struct KvLogEntry {
|
||||
std::uint64_t term{0};
|
||||
std::uint64_t index{0};
|
||||
std::string key;
|
||||
std::optional<std::string> value;
|
||||
};
|
||||
|
||||
enum class KvWriteOutcome : std::uint8_t {
|
||||
/// Majority-committed and applied: the only durable reply.
|
||||
Applied,
|
||||
/// The entry may exist locally but no majority acknowledged it. It is
|
||||
/// not durable and a later leader may overwrite it.
|
||||
NoQuorum,
|
||||
NotLeader,
|
||||
NodeDown
|
||||
};
|
||||
|
||||
struct KvWriteReply {
|
||||
KvWriteOutcome outcome{KvWriteOutcome::NoQuorum};
|
||||
std::uint64_t index{0};
|
||||
std::uint64_t term{0};
|
||||
};
|
||||
|
||||
/// Immutable inspection copy of one voter.
|
||||
struct KvNodeSnapshot {
|
||||
std::string id;
|
||||
bool alive{true};
|
||||
Role role{Role::Follower};
|
||||
std::uint64_t term{0};
|
||||
std::uint64_t commit_index{0};
|
||||
std::uint64_t applied_index{0};
|
||||
std::size_t log_size{0};
|
||||
std::optional<std::string> leader;
|
||||
std::map<std::string, std::string, std::less<>> kv;
|
||||
};
|
||||
|
||||
/// Deterministic single-group replicated key-value cluster.
|
||||
///
|
||||
/// Models the safety rules the reference distributed KV depends on
|
||||
/// without sockets, threads or clocks:
|
||||
/// * a write is replied Applied only after a majority of matching acks
|
||||
/// (durable reply), never on local append alone;
|
||||
/// * a leader in a minority cannot commit and is stepped down when it
|
||||
/// observes a higher term;
|
||||
/// * a consistent read is served only by a leader that confirms a
|
||||
/// majority in its term and has applied every committed entry;
|
||||
/// * committed entries survive crash/restart and are never overwritten.
|
||||
///
|
||||
/// The simulator is single-threaded; tests drive elections, proposals,
|
||||
/// partitions and crashes explicitly.
|
||||
class ReplicatedKvCluster
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ReplicatedKvCluster(std::vector<std::string> voters);
|
||||
|
||||
[[nodiscard]] const std::vector<std::string>& voters() const noexcept
|
||||
{
|
||||
return m_voters;
|
||||
}
|
||||
|
||||
/// Request a majority election for `candidate` in a new term.
|
||||
/// Fails without changing the cluster when no majority is
|
||||
/// reachable.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
elect(std::string_view candidate);
|
||||
|
||||
/// Append and replicate one command through `leader`. The reply is
|
||||
/// Applied only when a majority acknowledged the matching entry.
|
||||
[[nodiscard]] KvWriteReply propose(std::string_view leader,
|
||||
std::string key,
|
||||
std::optional<std::string> value);
|
||||
|
||||
/// Replicate the leader's log and commit index without appending a
|
||||
/// new command (the AppendEntries heartbeat). Followers in a newer
|
||||
/// term step the leader down.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
heartbeat(std::string_view leader);
|
||||
|
||||
/// Linearizable read: leader-only, majority-confirmed in the
|
||||
/// leader's term, after applying every committed entry.
|
||||
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
||||
quorum_read(std::string_view node, std::string_view key);
|
||||
|
||||
/// Quorum-confirmed copy of the leader's applied state. Used by
|
||||
/// compositions that must enumerate keys (e.g. the worker queue).
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::map<std::string, std::string, std::less<>>>
|
||||
quorum_snapshot(std::string_view node);
|
||||
|
||||
/// Crash/restart keep the durable log, term and vote.
|
||||
void crash(std::string_view node);
|
||||
void restart(std::string_view node);
|
||||
|
||||
/// Move a node to a partition id. Nodes only communicate within
|
||||
/// the same partition id.
|
||||
void set_partition(std::string_view node, int partition);
|
||||
|
||||
[[nodiscard]] std::optional<KvNodeSnapshot>
|
||||
snapshot(std::string_view node) const;
|
||||
|
||||
/// Highest commit index across live nodes.
|
||||
[[nodiscard]] std::uint64_t committed_index() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Node {
|
||||
std::string id;
|
||||
bool alive{true};
|
||||
int partition{0};
|
||||
Role role{Role::Follower};
|
||||
std::uint64_t term{0};
|
||||
std::optional<std::string> voted_for;
|
||||
std::optional<std::string> leader;
|
||||
std::vector<KvLogEntry> log;
|
||||
std::uint64_t commit_index{0};
|
||||
std::uint64_t applied_index{0};
|
||||
std::map<std::string, std::string, std::less<>> kv;
|
||||
};
|
||||
|
||||
[[nodiscard]] Node* find(std::string_view id);
|
||||
[[nodiscard]] const Node* find(std::string_view id) const;
|
||||
[[nodiscard]] bool reachable(const Node& a, const Node& b) const;
|
||||
[[nodiscard]] bool majority(std::size_t acks) const;
|
||||
/// True when `candidate` has a log at least as up to date as `voter`.
|
||||
[[nodiscard]] static bool log_up_to_date(const Node& candidate,
|
||||
const Node& voter);
|
||||
void apply_committed(Node& node);
|
||||
/// Majority-confirm `node` as leader in its term, then apply pending
|
||||
/// committed entries. Shared by quorum reads and snapshots.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
confirm_leader(Node& node);
|
||||
/// Copy the leader's log to one reachable follower. False when the
|
||||
/// follower cannot be brought in line (e.g. it is in a newer term).
|
||||
[[nodiscard]] bool replicate_to(Node& leader, Node& follower);
|
||||
|
||||
std::vector<std::string> m_voters;
|
||||
std::vector<Node> m_nodes;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,119 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
enum class JobState : std::uint8_t {
|
||||
Pending,
|
||||
InFlight,
|
||||
Done,
|
||||
Dead
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string_view job_state_name(JobState state) noexcept;
|
||||
|
||||
struct QueueJob {
|
||||
std::string id;
|
||||
std::string payload;
|
||||
JobState state{JobState::Pending};
|
||||
std::uint32_t attempts{0};
|
||||
std::string consumer;
|
||||
/// Set when the acknowledged effect still needs external
|
||||
/// delivery (the outbox).
|
||||
bool outbox_pending{false};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
struct QueueConfig {
|
||||
std::uint32_t max_attempts{3};
|
||||
std::size_t max_jobs{1024};
|
||||
std::size_t max_payload_bytes{64ULL * 1024ULL};
|
||||
};
|
||||
|
||||
/// Consumer-side effect delivery for dispatched outbox entries.
|
||||
using OutboxSink = std::function<void(const QueueJob&)>;
|
||||
|
||||
/// Worker-queue reference backed by one replicated KV group.
|
||||
///
|
||||
/// Semantics are at-least-once by contract:
|
||||
/// * `publish` is idempotent by caller key and replies only after the
|
||||
/// record is majority-committed; a lost reply is retried with the
|
||||
/// same key;
|
||||
/// * `claim` leases one job to a consumer (attempts incremented);
|
||||
/// * `ack` records the inbox outcome and the outbox entry in one
|
||||
/// replicated job record, so a redelivered ack cannot duplicate the
|
||||
/// effect;
|
||||
/// * `nack` requeues or dead-letters after `max_attempts`;
|
||||
/// * `recover_consumer` requeues or dead-letters a crashed
|
||||
/// consumer's in-flight jobs;
|
||||
/// * `dispatch_outbox` delivers effects externally. A crash between
|
||||
/// delivery and marking duplicates the effect: consumers must dedup
|
||||
/// on the job id.
|
||||
class ReplicatedQueue
|
||||
{
|
||||
public:
|
||||
|
||||
ReplicatedQueue(ReplicatedKvCluster& cluster, std::string leader,
|
||||
QueueConfig config = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
publish(std::string payload, std::string idempotency_key);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
|
||||
claim(std::string_view consumer);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
ack(std::string_view consumer, std::string_view job_id);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<QueueJob>
|
||||
nack(std::string_view consumer, std::string_view job_id,
|
||||
std::string reason);
|
||||
|
||||
/// Requeue (or dead-letter) every in-flight job of a crashed
|
||||
/// consumer. Returns the affected count.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
recover_consumer(std::string_view consumer);
|
||||
|
||||
/// Deliver pending outbox effects and mark them delivered.
|
||||
/// Returns the delivered count.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
dispatch_outbox(const OutboxSink& sink);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<QueueJob>>
|
||||
dead_letters();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<QueueJob>
|
||||
status(std::string_view job_id);
|
||||
|
||||
/// The leader endpoint used for every replicated operation.
|
||||
void set_leader(std::string leader)
|
||||
{
|
||||
m_leader = std::move(leader);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static std::string key_for(std::string_view id);
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
store(const QueueJob& job);
|
||||
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
|
||||
load(std::string_view job_id);
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::vector<std::pair<std::string, QueueJob>>>
|
||||
all_jobs();
|
||||
|
||||
ReplicatedKvCluster& m_cluster;
|
||||
std::string m_leader;
|
||||
QueueConfig m_config;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,161 @@
|
||||
#pragma once
|
||||
|
||||
#include "distributed_host/host_graph.hpp"
|
||||
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
/// Validated single-node configuration. Construction opens nothing.
|
||||
struct SingleNodeConfig {
|
||||
std::string peer_address{"127.0.0.1:0"};
|
||||
/// Required peer credential; an empty token fails closed.
|
||||
std::string peer_token{};
|
||||
std::chrono::milliseconds shutdown_grace{
|
||||
std::chrono::seconds{5}};
|
||||
std::size_t max_connections{16};
|
||||
std::size_t max_append_bytes{64ULL * 1024ULL};
|
||||
/// Bounded retained peer log entries.
|
||||
std::size_t max_log_entries{1024};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
/// Bounded in-memory replicated log served by the peer fixture. The
|
||||
/// single-node composition owns it; durable storage arrives with the
|
||||
/// multi-node reference in a later task.
|
||||
class PeerLog
|
||||
{
|
||||
public:
|
||||
|
||||
explicit PeerLog(std::size_t max_entries = 1024);
|
||||
|
||||
/// Append one opaque entry. Returns the assigned index (1-based).
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
append(std::string entry);
|
||||
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
[[nodiscard]] std::uint64_t last_index() const;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::size_t m_max_entries;
|
||||
std::vector<std::string> m_entries;
|
||||
};
|
||||
|
||||
/// Real authenticated peer transport over Void::Net::HttpServer.
|
||||
///
|
||||
/// Routes: `GET /peer/health` (bounded status, no secrets) and
|
||||
/// `POST /peer/append` (bearer-authenticated, bounded body). A missing or
|
||||
/// empty configured token rejects every request.
|
||||
class HttpPeerTransport final : public PeerTransport
|
||||
{
|
||||
public:
|
||||
|
||||
HttpPeerTransport(std::string address, std::string token,
|
||||
PeerLog& log, std::size_t max_connections,
|
||||
std::size_t max_append_bytes);
|
||||
~HttpPeerTransport() noexcept override;
|
||||
|
||||
HttpPeerTransport(const HttpPeerTransport&) = delete;
|
||||
HttpPeerTransport& operator=(const HttpPeerTransport&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> listen() override;
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
connect_peers(const std::vector<NodeId>& peers) override;
|
||||
void close() noexcept override;
|
||||
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept;
|
||||
[[nodiscard]] std::size_t connected_peers() const noexcept
|
||||
{
|
||||
return m_connected_peers;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool authorized(const Void::Net::ServerRequest& req)
|
||||
const noexcept;
|
||||
|
||||
std::string m_address;
|
||||
std::string m_token;
|
||||
PeerLog& m_log;
|
||||
std::size_t m_max_connections;
|
||||
std::size_t m_max_append_bytes;
|
||||
std::size_t m_connected_peers{0};
|
||||
std::unique_ptr<Void::Net::HttpServer> m_server{};
|
||||
};
|
||||
|
||||
/// Single-node replication adapter: a sole voter is always the leader
|
||||
/// while started. Multi-node election belongs to the Coordination plan.
|
||||
class SingleNodeReplication final : public ReplicationAdapter
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start() override;
|
||||
[[nodiscard]] Role role() const noexcept override
|
||||
{
|
||||
return m_running ? Role::Leader : Role::Follower;
|
||||
}
|
||||
[[nodiscard]] bool leader_available() const noexcept override
|
||||
{
|
||||
return m_running;
|
||||
}
|
||||
void stop() noexcept override { m_running = false; }
|
||||
|
||||
private:
|
||||
|
||||
bool m_running{false};
|
||||
};
|
||||
|
||||
/// Single-node reference composition: the host graph wired with the
|
||||
/// authenticated HTTP peer fixture and a leader-available replication
|
||||
/// adapter. Startup is bounded and rolls back in reverse order.
|
||||
class SingleNodeHost
|
||||
{
|
||||
public:
|
||||
|
||||
SingleNodeHost(const SingleNodeHost&) = delete;
|
||||
SingleNodeHost& operator=(const SingleNodeHost&) = delete;
|
||||
/// Movable: every component the host graph points at is heap-owned,
|
||||
/// so a move transfers ownership without changing addresses.
|
||||
SingleNodeHost(SingleNodeHost&&) noexcept = default;
|
||||
SingleNodeHost& operator=(SingleNodeHost&&) noexcept = default;
|
||||
~SingleNodeHost();
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SingleNodeHost>
|
||||
create(SingleNodeConfig config);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
void stop() noexcept;
|
||||
|
||||
[[nodiscard]] HealthSnapshot health() const;
|
||||
[[nodiscard]] std::uint16_t peer_port() const noexcept;
|
||||
[[nodiscard]] const std::vector<std::string>& history() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct NoopStorage final : StorageBackend {
|
||||
Void::Result::Result<void> open() override { return {}; }
|
||||
Void::Result::Result<void> recover() override { return {}; }
|
||||
void close() noexcept override {}
|
||||
};
|
||||
|
||||
explicit SingleNodeHost(SingleNodeConfig config);
|
||||
|
||||
SingleNodeConfig m_config;
|
||||
std::unique_ptr<PeerLog> m_log;
|
||||
std::unique_ptr<NoopStorage> m_storage;
|
||||
std::unique_ptr<HttpPeerTransport> m_transport;
|
||||
std::unique_ptr<SingleNodeReplication> m_replication;
|
||||
std::unique_ptr<DistributedHostGraph> m_graph;
|
||||
};
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,610 @@
|
||||
#include "distributed_host/cluster_fixture.hpp"
|
||||
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
|
||||
std::string body)
|
||||
{
|
||||
Void::Net::ServerResponse response;
|
||||
response.status = static_cast<std::uint16_t>(status);
|
||||
response.headers.push_back(
|
||||
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
|
||||
response.headers.push_back(
|
||||
Void::Net::Header{"cache-control", "no-store"});
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
|
||||
[[nodiscard]] int status_for(const Void::Result::Error& error) noexcept
|
||||
{
|
||||
using Kind = Void::Result::ErrorKind;
|
||||
switch (error.kind()) {
|
||||
case Kind::invalid_argument: return 400;
|
||||
case Kind::not_found: return 404;
|
||||
case Kind::conflict: return 409;
|
||||
case Kind::overloaded: return 503;
|
||||
case Kind::timeout: return 504;
|
||||
default: return 500;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool authorized(const Void::Net::ServerRequest& request,
|
||||
std::string_view token) noexcept
|
||||
{
|
||||
if (token.empty()) {
|
||||
return false;
|
||||
}
|
||||
const auto header = request.header("authorization");
|
||||
if (!header) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view scheme{"bearer "};
|
||||
if (header->size() <= scheme.size()) {
|
||||
return false;
|
||||
}
|
||||
const std::string_view word = header->substr(0, scheme.size() - 1);
|
||||
if (!(word == "Bearer" || word == "bearer") ||
|
||||
(*header)[scheme.size() - 1] != ' ') {
|
||||
return false;
|
||||
}
|
||||
return header->substr(scheme.size()) == token;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
query_value(std::string_view query, std::string_view name) noexcept
|
||||
{
|
||||
std::size_t pos = 0;
|
||||
while (pos <= query.size()) {
|
||||
const std::size_t amp = query.find('&', pos);
|
||||
const std::string_view pair = query.substr(
|
||||
pos, amp == std::string_view::npos ? std::string_view::npos
|
||||
: amp - pos);
|
||||
const std::size_t equals = pair.find('=');
|
||||
const std::string_view key = pair.substr(0, equals);
|
||||
if (key == name) {
|
||||
return equals == std::string_view::npos
|
||||
? std::string_view{}
|
||||
: pair.substr(equals + 1);
|
||||
}
|
||||
if (amp == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = amp + 1;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view role_name(Role role) noexcept
|
||||
{
|
||||
switch (role) {
|
||||
case Role::Leader: return "leader";
|
||||
case Role::Candidate: return "candidate";
|
||||
case Role::Follower: return "follower";
|
||||
}
|
||||
return "follower";
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
outcome_name(KvWriteOutcome outcome) noexcept
|
||||
{
|
||||
switch (outcome) {
|
||||
case KvWriteOutcome::Applied: return "applied";
|
||||
case KvWriteOutcome::NoQuorum: return "no-quorum";
|
||||
case KvWriteOutcome::NotLeader: return "not-leader";
|
||||
case KvWriteOutcome::NodeDown: return "node-down";
|
||||
}
|
||||
return "no-quorum";
|
||||
}
|
||||
|
||||
[[nodiscard]] int outcome_status(KvWriteOutcome outcome) noexcept
|
||||
{
|
||||
switch (outcome) {
|
||||
case KvWriteOutcome::Applied: return 200;
|
||||
case KvWriteOutcome::NotLeader: return 409;
|
||||
case KvWriteOutcome::NoQuorum: return 503;
|
||||
case KvWriteOutcome::NodeDown: return 503;
|
||||
}
|
||||
return 503;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ClusterFixture::ClusterFixture(ClusterFixtureConfig config)
|
||||
: m_config(std::move(config)), m_cluster({"a", "b", "c"})
|
||||
{
|
||||
}
|
||||
|
||||
ClusterFixture::~ClusterFixture()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<ClusterFixture>>
|
||||
ClusterFixture::create(ClusterFixtureConfig config)
|
||||
{
|
||||
if (config.token.empty()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
"ClusterFixture: a peer token is required (fail closed)"}};
|
||||
}
|
||||
auto fixture = std::unique_ptr<ClusterFixture>{
|
||||
new ClusterFixture{std::move(config)}};
|
||||
for (const auto& id : fixture->m_cluster.voters()) {
|
||||
auto peer = std::make_unique<PeerServer>();
|
||||
peer->id = id;
|
||||
Void::Net::HttpServerOptions options;
|
||||
options.bind_host = "127.0.0.1";
|
||||
options.port = 0;
|
||||
options.max_concurrent_connections =
|
||||
fixture->m_config.max_connections;
|
||||
peer->server = std::make_unique<Void::Net::HttpServer>(options);
|
||||
if (auto routes = fixture->register_routes(*peer); !routes) {
|
||||
return std::unexpected{std::move(routes).error()};
|
||||
}
|
||||
fixture->m_peers.push_back(std::move(peer));
|
||||
}
|
||||
return fixture;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ClusterFixture::register_routes(PeerServer& peer)
|
||||
{
|
||||
const std::string id = peer.id;
|
||||
Void::Net::HttpServer& server = *peer.server;
|
||||
const std::string token = m_config.token;
|
||||
|
||||
auto guarded = [this, token](
|
||||
const Void::Net::ServerRequest& request)
|
||||
-> std::optional<Void::Net::ServerResponse> {
|
||||
if (!authorized(request, token)) {
|
||||
return text_response(401, "unauthorized");
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
|
||||
auto add = [&](Void::Net::Method method, const char* pattern, auto fn)
|
||||
-> Void::Result::Result<void> {
|
||||
return server.add_route(
|
||||
method, pattern,
|
||||
[this, id, pattern, fn, guarded](
|
||||
const Void::Net::ServerRequest& request)
|
||||
-> Void::Net::RouteResult {
|
||||
if (auto denied = guarded(request)) {
|
||||
return Void::Result::ok(std::move(*denied));
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
return Void::Result::ok(fn(id, request, *this));
|
||||
});
|
||||
};
|
||||
|
||||
auto registered = add(
|
||||
Void::Net::Method::Get, "/peer/health",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
const auto state = fixture.m_cluster.snapshot(self);
|
||||
if (!state) {
|
||||
return text_response(404, "unknown node");
|
||||
}
|
||||
return text_response(
|
||||
200,
|
||||
std::format(
|
||||
"id={} role={} term={} commit={} applied={} alive={}",
|
||||
state->id, role_name(state->role), state->term,
|
||||
state->commit_index, state->applied_index,
|
||||
state->alive ? "true" : "false"));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/peer/elect",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
auto elected = fixture.m_cluster.elect(self);
|
||||
if (!elected) {
|
||||
return text_response(status_for(elected.error()),
|
||||
elected.error().message());
|
||||
}
|
||||
return text_response(200, "elected");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/peer/heartbeat",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
auto beat = fixture.m_cluster.heartbeat(self);
|
||||
if (!beat) {
|
||||
return text_response(status_for(beat.error()),
|
||||
beat.error().message());
|
||||
}
|
||||
return text_response(200, "ok");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
auto propose = [](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture,
|
||||
std::optional<std::string> value) {
|
||||
const auto key = query_value(request.query, "key");
|
||||
if (!key || key->empty()) {
|
||||
return text_response(400, "key required");
|
||||
}
|
||||
const KvWriteReply reply = fixture.m_cluster.propose(
|
||||
self, std::string{*key}, std::move(value));
|
||||
return text_response(
|
||||
outcome_status(reply.outcome),
|
||||
std::format("{} index={} term={}", outcome_name(reply.outcome),
|
||||
reply.index, reply.term));
|
||||
};
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Put, "/peer/propose",
|
||||
[propose](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
return propose(self, request, fixture,
|
||||
std::optional<std::string>{request.body});
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Delete, "/peer/propose",
|
||||
[propose](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
return propose(self, request, fixture, std::nullopt);
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Get, "/peer/read",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto key = query_value(request.query, "key");
|
||||
if (!key || key->empty()) {
|
||||
return text_response(400, "key required");
|
||||
}
|
||||
auto read =
|
||||
fixture.m_cluster.quorum_read(self, *key);
|
||||
if (!read) {
|
||||
return text_response(status_for(read.error()),
|
||||
read.error().message());
|
||||
}
|
||||
if (!read->has_value()) {
|
||||
return text_response(404, "not found");
|
||||
}
|
||||
return text_response(200, **read);
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/admin/partition",
|
||||
[](const std::string&,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto node = query_value(request.query, "node");
|
||||
const auto partition = query_value(request.query, "partition");
|
||||
if (!node || !partition) {
|
||||
return text_response(400, "node and partition required");
|
||||
}
|
||||
unsigned int value = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
partition->data(), partition->data() + partition->size(),
|
||||
value);
|
||||
if (parsed.ec != std::errc{}) {
|
||||
return text_response(400, "invalid partition");
|
||||
}
|
||||
fixture.m_cluster.set_partition(*node,
|
||||
static_cast<int>(value));
|
||||
return text_response(200, "ok");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/admin/crash",
|
||||
[](const std::string&,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto node = query_value(request.query, "node");
|
||||
if (!node) {
|
||||
return text_response(400, "node required");
|
||||
}
|
||||
fixture.m_cluster.crash(*node);
|
||||
return text_response(200, "ok");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/admin/restart",
|
||||
[](const std::string&,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto node = query_value(request.query, "node");
|
||||
if (!node) {
|
||||
return text_response(400, "node required");
|
||||
}
|
||||
fixture.m_cluster.restart(*node);
|
||||
return text_response(200, "ok");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/publish",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto key = query_value(request.query, "key");
|
||||
if (!key || key->empty()) {
|
||||
return text_response(400, "key required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto id = queue.publish(request.body, std::string{*key});
|
||||
if (!id) {
|
||||
return text_response(status_for(id.error()),
|
||||
id.error().message());
|
||||
}
|
||||
return text_response(200, "job=" + *id);
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/claim",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto consumer = query_value(request.query, "consumer");
|
||||
if (!consumer) {
|
||||
return text_response(400, "consumer required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto claimed = queue.claim(*consumer);
|
||||
if (!claimed) {
|
||||
return text_response(status_for(claimed.error()),
|
||||
claimed.error().message());
|
||||
}
|
||||
if (!claimed->has_value()) {
|
||||
return text_response(204, "");
|
||||
}
|
||||
return text_response(
|
||||
200,
|
||||
std::format("job={} payload={} attempts={}",
|
||||
(**claimed).id, (**claimed).payload,
|
||||
(**claimed).attempts));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/ack",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto consumer = query_value(request.query, "consumer");
|
||||
const auto id = query_value(request.query, "id");
|
||||
if (!consumer || !id) {
|
||||
return text_response(400, "consumer and id required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto acknowledged = queue.ack(*consumer, *id);
|
||||
if (!acknowledged) {
|
||||
return text_response(status_for(acknowledged.error()),
|
||||
acknowledged.error().message());
|
||||
}
|
||||
return text_response(200, "done");
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/nack",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto consumer = query_value(request.query, "consumer");
|
||||
const auto id = query_value(request.query, "id");
|
||||
if (!consumer || !id) {
|
||||
return text_response(400, "consumer and id required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto rejected = queue.nack(*consumer, *id, request.body);
|
||||
if (!rejected) {
|
||||
return text_response(status_for(rejected.error()),
|
||||
rejected.error().message());
|
||||
}
|
||||
return text_response(
|
||||
200, std::format("state={} attempts={}",
|
||||
job_state_name(rejected->state),
|
||||
rejected->attempts));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/recover",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto consumer = query_value(request.query, "consumer");
|
||||
if (!consumer) {
|
||||
return text_response(400, "consumer required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto recovered = queue.recover_consumer(*consumer);
|
||||
if (!recovered) {
|
||||
return text_response(status_for(recovered.error()),
|
||||
recovered.error().message());
|
||||
}
|
||||
return text_response(200,
|
||||
"recovered=" + std::to_string(*recovered));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Post, "/queue/dispatch",
|
||||
[](const std::string& self, const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto dispatched = queue.dispatch_outbox(
|
||||
[&fixture](const QueueJob& job) {
|
||||
if (fixture.m_delivered.size() <
|
||||
fixture.m_config.max_delivered) {
|
||||
fixture.m_delivered.push_back(job.id);
|
||||
}
|
||||
});
|
||||
if (!dispatched) {
|
||||
return text_response(status_for(dispatched.error()),
|
||||
dispatched.error().message());
|
||||
}
|
||||
return text_response(200,
|
||||
"delivered=" + std::to_string(*dispatched));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Get, "/queue/status",
|
||||
[](const std::string& self,
|
||||
const Void::Net::ServerRequest& request,
|
||||
ClusterFixture& fixture) {
|
||||
const auto id = query_value(request.query, "id");
|
||||
if (!id) {
|
||||
return text_response(400, "id required");
|
||||
}
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto job = queue.status(*id);
|
||||
if (!job) {
|
||||
return text_response(status_for(job.error()),
|
||||
job.error().message());
|
||||
}
|
||||
return text_response(
|
||||
200, std::format("state={} attempts={} outbox={} reason={}",
|
||||
job_state_name(job->state), job->attempts,
|
||||
job->outbox_pending ? 1 : 0, job->reason));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
registered = add(
|
||||
Void::Net::Method::Get, "/queue/dlq",
|
||||
[](const std::string& self, const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
ReplicatedQueue queue{fixture.m_cluster, self,
|
||||
fixture.m_config.queue};
|
||||
auto dead = queue.dead_letters();
|
||||
if (!dead) {
|
||||
return text_response(status_for(dead.error()),
|
||||
dead.error().message());
|
||||
}
|
||||
std::string body;
|
||||
for (const auto& job : *dead) {
|
||||
body += std::format("id={} attempts={} reason={}\n",
|
||||
job.id, job.attempts, job.reason);
|
||||
}
|
||||
return text_response(200, std::move(body));
|
||||
});
|
||||
if (!registered) {
|
||||
return registered;
|
||||
}
|
||||
|
||||
return add(
|
||||
Void::Net::Method::Get, "/queue/delivered",
|
||||
[](const std::string&, const Void::Net::ServerRequest&,
|
||||
ClusterFixture& fixture) {
|
||||
std::string body;
|
||||
for (const auto& id : fixture.m_delivered) {
|
||||
body += id;
|
||||
body += '\n';
|
||||
}
|
||||
return text_response(200, std::move(body));
|
||||
});
|
||||
}
|
||||
|
||||
Void::Result::Result<void> ClusterFixture::start()
|
||||
{
|
||||
std::size_t started = 0;
|
||||
for (auto& peer : m_peers) {
|
||||
if (auto listening = peer->server->start(); !listening) {
|
||||
for (std::size_t i = 0; i < started; ++i) {
|
||||
m_peers[i]->server->shutdown(m_config.shutdown_grace);
|
||||
}
|
||||
return listening;
|
||||
}
|
||||
++started;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void ClusterFixture::stop() noexcept
|
||||
{
|
||||
for (auto& peer : m_peers) {
|
||||
if (peer->server) {
|
||||
peer->server->shutdown(m_config.shutdown_grace);
|
||||
peer->server.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string ClusterFixture::endpoint(std::string_view node) const
|
||||
{
|
||||
for (const auto& peer : m_peers) {
|
||||
if (peer->id == node && peer->server &&
|
||||
peer->server->bound_port() != 0) {
|
||||
return "http://127.0.0.1:" +
|
||||
std::to_string(peer->server->bound_port());
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::vector<std::string>& ClusterFixture::voters() const noexcept
|
||||
{
|
||||
return m_cluster.voters();
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,299 @@
|
||||
#include "distributed_host/host_graph.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error unready(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::timeout,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string validate(const HostConfig& config)
|
||||
{
|
||||
if (config.cluster.empty()) {
|
||||
return "HostConfig: cluster must not be empty";
|
||||
}
|
||||
if (config.self.empty()) {
|
||||
return "HostConfig: self node id must not be empty";
|
||||
}
|
||||
for (const auto& peer : config.peers) {
|
||||
if (peer.empty()) {
|
||||
return "HostConfig: peer node id must not be empty";
|
||||
}
|
||||
if (peer == config.self) {
|
||||
return "HostConfig: self must not appear in the peer list";
|
||||
}
|
||||
}
|
||||
if (config.startup_deadline.count() <= 0) {
|
||||
return "HostConfig: startup_deadline must be positive";
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
DistributedHostGraph::DistributedHostGraph(HostResources resources,
|
||||
HostConfig config)
|
||||
: m_resources(resources), m_config(std::move(config))
|
||||
{
|
||||
}
|
||||
|
||||
DistributedHostGraph::~DistributedHostGraph()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
DistributedHostGraph::DistributedHostGraph(
|
||||
DistributedHostGraph&& other) noexcept
|
||||
: m_resources(other.m_resources)
|
||||
, m_config(std::move(other.m_config))
|
||||
, m_history(std::move(other.m_history))
|
||||
, m_started(other.m_started)
|
||||
, m_storage_open(other.m_storage_open)
|
||||
, m_transport_live(other.m_transport_live)
|
||||
, m_replication_started(other.m_replication_started)
|
||||
, m_directory_published(other.m_directory_published)
|
||||
, m_stopped(other.m_stopped)
|
||||
, m_readiness(other.m_readiness)
|
||||
, m_last_error(std::move(other.m_last_error))
|
||||
{
|
||||
// The moved-from graph no longer owns any live component, so its
|
||||
// destructor must not stop anything twice.
|
||||
other.m_started = 0;
|
||||
other.m_storage_open = false;
|
||||
other.m_transport_live = false;
|
||||
other.m_replication_started = false;
|
||||
other.m_directory_published = false;
|
||||
other.m_stopped = true;
|
||||
}
|
||||
|
||||
Void::Result::Result<DistributedHostGraph>
|
||||
DistributedHostGraph::compose(HostResources resources, HostConfig config)
|
||||
{
|
||||
if (const std::string error = validate(config); !error.empty()) {
|
||||
return std::unexpected{invalid(error)};
|
||||
}
|
||||
if (resources.storage == nullptr || resources.transport == nullptr ||
|
||||
resources.replication == nullptr) {
|
||||
return std::unexpected{invalid(
|
||||
"HostResources: storage, transport and replication are "
|
||||
"required")};
|
||||
}
|
||||
return DistributedHostGraph{resources, std::move(config)};
|
||||
}
|
||||
|
||||
void DistributedHostGraph::record(std::string step)
|
||||
{
|
||||
m_history.push_back(std::move(step));
|
||||
}
|
||||
|
||||
Void::Result::Result<void> DistributedHostGraph::start_storage()
|
||||
{
|
||||
if (auto opened = m_resources.storage->open(); !opened) {
|
||||
return opened;
|
||||
}
|
||||
record("storage.open");
|
||||
m_storage_open = true;
|
||||
++m_started;
|
||||
if (auto recovered = m_resources.storage->recover(); !recovered) {
|
||||
return recovered;
|
||||
}
|
||||
record("storage.recover");
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> DistributedHostGraph::start_transport()
|
||||
{
|
||||
if (auto listening = m_resources.transport->listen(); !listening) {
|
||||
return listening;
|
||||
}
|
||||
record("transport.listen");
|
||||
m_transport_live = true;
|
||||
++m_started;
|
||||
if (auto connected =
|
||||
m_resources.transport->connect_peers(m_config.peers);
|
||||
!connected) {
|
||||
return connected;
|
||||
}
|
||||
record("transport.connect_peers");
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> DistributedHostGraph::start_replication()
|
||||
{
|
||||
if (auto started = m_resources.replication->start(); !started) {
|
||||
return started;
|
||||
}
|
||||
record("replication.start");
|
||||
m_replication_started = true;
|
||||
++m_started;
|
||||
|
||||
const Role role = m_resources.replication->role();
|
||||
const bool leader = m_resources.replication->leader_available();
|
||||
if (m_config.require_leader_readiness && !leader) {
|
||||
m_readiness = Readiness::FollowerHealthy;
|
||||
return std::unexpected{unready(
|
||||
"DistributedHost: no leader path within the startup deadline")};
|
||||
}
|
||||
m_readiness = leader ? Readiness::WriteReady
|
||||
: Readiness::FollowerHealthy;
|
||||
record("replication.readiness");
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> DistributedHostGraph::publish_directory()
|
||||
{
|
||||
if (!m_config.publish_discovery || m_resources.directory == nullptr) {
|
||||
return {};
|
||||
}
|
||||
// Discovery is an observation adapter: a failure is recorded but
|
||||
// never weakens quorum or readiness.
|
||||
auto published = m_resources.directory->publish(m_config.self);
|
||||
record("directory.publish");
|
||||
if (!published) {
|
||||
m_last_error = published.error().message();
|
||||
return {};
|
||||
}
|
||||
m_directory_published = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> DistributedHostGraph::start()
|
||||
{
|
||||
if (m_stopped) {
|
||||
return std::unexpected{
|
||||
conflict("DistributedHost: graph was already stopped")};
|
||||
}
|
||||
if (m_started != 0) {
|
||||
return std::unexpected{
|
||||
conflict("DistributedHost: graph is already started")};
|
||||
}
|
||||
m_readiness = Readiness::Starting;
|
||||
m_last_error.clear();
|
||||
|
||||
auto storage = start_storage();
|
||||
if (!storage) {
|
||||
m_last_error = storage.error().message();
|
||||
m_readiness = Readiness::Failed;
|
||||
unwind();
|
||||
return storage;
|
||||
}
|
||||
auto transport = start_transport();
|
||||
if (!transport) {
|
||||
m_last_error = transport.error().message();
|
||||
m_readiness = Readiness::Failed;
|
||||
unwind();
|
||||
return transport;
|
||||
}
|
||||
auto replication = start_replication();
|
||||
if (!replication) {
|
||||
m_last_error = replication.error().message();
|
||||
m_readiness = Readiness::Failed;
|
||||
unwind();
|
||||
return replication;
|
||||
}
|
||||
if (auto directory = publish_directory(); !directory) {
|
||||
m_last_error = directory.error().message();
|
||||
m_readiness = Readiness::Failed;
|
||||
unwind();
|
||||
return directory;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void DistributedHostGraph::stop() noexcept
|
||||
{
|
||||
if (m_stopped) {
|
||||
return;
|
||||
}
|
||||
if (m_readiness != Readiness::Starting &&
|
||||
m_readiness != Readiness::Failed) {
|
||||
m_readiness = Readiness::Stopping;
|
||||
}
|
||||
// Reverse startup order, never destroying borrowed resources.
|
||||
if (m_directory_published) {
|
||||
m_resources.directory->withdraw();
|
||||
record("directory.withdraw");
|
||||
m_directory_published = false;
|
||||
}
|
||||
if (m_replication_started) {
|
||||
m_resources.replication->stop();
|
||||
record("replication.stop");
|
||||
m_replication_started = false;
|
||||
}
|
||||
if (m_transport_live) {
|
||||
m_resources.transport->close();
|
||||
record("transport.close");
|
||||
m_transport_live = false;
|
||||
}
|
||||
if (m_storage_open) {
|
||||
m_resources.storage->close();
|
||||
record("storage.close");
|
||||
m_storage_open = false;
|
||||
}
|
||||
m_stopped = true;
|
||||
m_started = 0;
|
||||
if (m_readiness != Readiness::Failed) {
|
||||
m_readiness = Readiness::Stopped;
|
||||
}
|
||||
}
|
||||
|
||||
void DistributedHostGraph::unwind() noexcept
|
||||
{
|
||||
// Rollback keeps the original failure visible in health().last_error.
|
||||
const std::string preserved = m_last_error;
|
||||
if (m_directory_published) {
|
||||
m_resources.directory->withdraw();
|
||||
record("directory.withdraw");
|
||||
m_directory_published = false;
|
||||
}
|
||||
if (m_replication_started) {
|
||||
m_resources.replication->stop();
|
||||
record("replication.stop");
|
||||
m_replication_started = false;
|
||||
}
|
||||
if (m_transport_live) {
|
||||
m_resources.transport->close();
|
||||
record("transport.close");
|
||||
m_transport_live = false;
|
||||
}
|
||||
if (m_storage_open) {
|
||||
m_resources.storage->close();
|
||||
record("storage.close");
|
||||
m_storage_open = false;
|
||||
}
|
||||
m_started = 0;
|
||||
m_last_error = preserved;
|
||||
}
|
||||
|
||||
HealthSnapshot DistributedHostGraph::health() const
|
||||
{
|
||||
HealthSnapshot snapshot;
|
||||
snapshot.readiness = m_readiness;
|
||||
snapshot.role = m_resources.replication != nullptr
|
||||
? m_resources.replication->role()
|
||||
: Role::Follower;
|
||||
snapshot.quorum_available =
|
||||
m_resources.replication != nullptr &&
|
||||
m_resources.replication->leader_available();
|
||||
snapshot.started_components = m_started;
|
||||
snapshot.last_error = m_last_error;
|
||||
return snapshot;
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,395 @@
|
||||
#include "distributed_host/range_placement.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error not_found(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error corrupt(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool overlapping(const KeyRange& a,
|
||||
const KeyRange& b) noexcept
|
||||
{
|
||||
return a.start < b.end && b.start < a.end;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool has_separator(std::string_view text) noexcept
|
||||
{
|
||||
return text.find_first_of("\t\n") != std::string_view::npos;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string_view move_phase_name(MovePhase phase) noexcept
|
||||
{
|
||||
switch (phase) {
|
||||
case MovePhase::None: return "none";
|
||||
case MovePhase::Frozen: return "frozen";
|
||||
case MovePhase::Verified: return "verified";
|
||||
case MovePhase::Completed: return "completed";
|
||||
case MovePhase::Aborted: return "aborted";
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
RangeDirectory::RangeDirectory(std::vector<std::string> voters)
|
||||
: m_voters(std::move(voters))
|
||||
{
|
||||
}
|
||||
|
||||
bool RangeDirectory::known_voter(std::string_view owner) const
|
||||
{
|
||||
return std::ranges::find(m_voters, owner) != m_voters.end();
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::assign(KeyRange range, std::string owner)
|
||||
{
|
||||
if (!range.valid() || has_separator(range.start) ||
|
||||
has_separator(range.end)) {
|
||||
return std::unexpected{
|
||||
invalid("RangeDirectory: invalid range bounds")};
|
||||
}
|
||||
if (!known_voter(owner)) {
|
||||
return std::unexpected{
|
||||
invalid("RangeDirectory: owner is not a configured voter")};
|
||||
}
|
||||
for (const auto& [start, ownership] : m_ranges) {
|
||||
if (overlapping(range, ownership.range)) {
|
||||
return std::unexpected{conflict(std::format(
|
||||
"RangeDirectory: range overlaps the existing [{}, {})",
|
||||
ownership.range.start, ownership.range.end))};
|
||||
}
|
||||
}
|
||||
m_ranges.emplace(range.start, RangeOwnership{range, std::move(owner)});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
RangeDirectory::owner_of(std::string_view key) const
|
||||
{
|
||||
// Highest range start <= key.
|
||||
auto candidate = m_ranges.upper_bound(std::string{key});
|
||||
if (candidate == m_ranges.begin()) {
|
||||
return std::unexpected{
|
||||
not_found("RangeDirectory: no range owns the key")};
|
||||
}
|
||||
--candidate;
|
||||
if (!candidate->second.range.contains(key)) {
|
||||
return std::unexpected{
|
||||
not_found("RangeDirectory: no range owns the key")};
|
||||
}
|
||||
return candidate->second.owner;
|
||||
}
|
||||
|
||||
std::vector<RangeOwnership> RangeDirectory::ranges() const
|
||||
{
|
||||
std::vector<RangeOwnership> out;
|
||||
out.reserve(m_ranges.size());
|
||||
for (const auto& [start, ownership] : m_ranges) {
|
||||
(void)start;
|
||||
out.push_back(ownership);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const RangeDirectory::ActiveMove*
|
||||
RangeDirectory::active_for(const KeyRange& range) const
|
||||
{
|
||||
for (const auto& [id, move] : m_moves) {
|
||||
(void)id;
|
||||
if (move.record.range == range &&
|
||||
(move.record.phase == MovePhase::Frozen ||
|
||||
move.record.phase == MovePhase::Verified)) {
|
||||
return &move;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
RangeDirectory::ActiveMove*
|
||||
RangeDirectory::mutable_move(std::uint64_t move_id)
|
||||
{
|
||||
const auto found = m_moves.find(move_id);
|
||||
return found == m_moves.end() ? nullptr : &found->second;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t>
|
||||
RangeDirectory::begin_move(KeyRange range, std::string target)
|
||||
{
|
||||
if (!known_voter(target)) {
|
||||
return std::unexpected{
|
||||
invalid("RangeDirectory: target is not a configured voter")};
|
||||
}
|
||||
if (active_for(range) != nullptr) {
|
||||
return std::unexpected{conflict(
|
||||
"RangeDirectory: the range already has an active move")};
|
||||
}
|
||||
auto owner = owner_of(range.start);
|
||||
if (!owner) {
|
||||
return std::unexpected{std::move(owner).error()};
|
||||
}
|
||||
const auto found = m_ranges.find(range.start);
|
||||
if (found == m_ranges.end() || !(found->second.range == range)) {
|
||||
return std::unexpected{not_found(
|
||||
"RangeDirectory: the range must match one assigned range")};
|
||||
}
|
||||
if (*owner == target) {
|
||||
return std::unexpected{
|
||||
conflict("RangeDirectory: target already owns the range")};
|
||||
}
|
||||
|
||||
MoveRecord record;
|
||||
record.id = m_next_move++;
|
||||
record.range = std::move(range);
|
||||
record.source = *owner;
|
||||
record.target = std::move(target);
|
||||
record.phase = MovePhase::Frozen;
|
||||
m_moves.emplace(record.id, ActiveMove{record});
|
||||
return record.id;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::transfer(std::uint64_t move_id, std::size_t entries)
|
||||
{
|
||||
ActiveMove* move = mutable_move(move_id);
|
||||
if (move == nullptr || move->record.phase != MovePhase::Frozen) {
|
||||
return std::unexpected{
|
||||
conflict("RangeDirectory: move is not frozen")};
|
||||
}
|
||||
move->record.transferred = entries;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::verify(std::uint64_t move_id, std::size_t entries)
|
||||
{
|
||||
ActiveMove* move = mutable_move(move_id);
|
||||
if (move == nullptr || move->record.phase != MovePhase::Frozen) {
|
||||
return std::unexpected{
|
||||
conflict("RangeDirectory: move is not frozen")};
|
||||
}
|
||||
if (entries != move->record.transferred) {
|
||||
return std::unexpected{conflict(
|
||||
"RangeDirectory: verified entry count does not match the "
|
||||
"transfer")};
|
||||
}
|
||||
move->record.phase = MovePhase::Verified;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> RangeDirectory::complete(std::uint64_t move_id)
|
||||
{
|
||||
ActiveMove* move = mutable_move(move_id);
|
||||
if (move == nullptr || move->record.phase != MovePhase::Verified) {
|
||||
return std::unexpected{
|
||||
conflict("RangeDirectory: move is not verified")};
|
||||
}
|
||||
const auto found = m_ranges.find(move->record.range.start);
|
||||
if (found == m_ranges.end() ||
|
||||
found->second.owner != move->record.source) {
|
||||
return std::unexpected{
|
||||
conflict("RangeDirectory: source no longer owns the range")};
|
||||
}
|
||||
found->second.owner = move->record.target;
|
||||
move->record.phase = MovePhase::Completed;
|
||||
return {};
|
||||
}
|
||||
|
||||
void RangeDirectory::abort(std::uint64_t move_id, std::string reason) noexcept
|
||||
{
|
||||
if (ActiveMove* move = mutable_move(move_id); move != nullptr) {
|
||||
if (move->record.phase == MovePhase::Frozen ||
|
||||
move->record.phase == MovePhase::Verified) {
|
||||
move->record.phase = MovePhase::Aborted;
|
||||
move->record.note = std::move(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::admit_write(std::string_view key) const
|
||||
{
|
||||
if (auto owned = owner_of(key); !owned) {
|
||||
return std::unexpected{std::move(owned).error()};
|
||||
}
|
||||
for (const auto& [id, move] : m_moves) {
|
||||
(void)id;
|
||||
if (move.record.range.contains(key) &&
|
||||
(move.record.phase == MovePhase::Frozen ||
|
||||
move.record.phase == MovePhase::Verified)) {
|
||||
return std::unexpected{conflict(
|
||||
"RangeDirectory: range is frozen for movement")};
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::admit_read(std::string_view key) const
|
||||
{
|
||||
if (auto owned = owner_of(key); !owned) {
|
||||
return std::unexpected{std::move(owned).error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<RangeDirectory::Recovery>
|
||||
RangeDirectory::recover(std::uint64_t move_id)
|
||||
{
|
||||
ActiveMove* move = mutable_move(move_id);
|
||||
if (move == nullptr) {
|
||||
return std::unexpected{
|
||||
not_found("RangeDirectory: unknown move")};
|
||||
}
|
||||
if (move->record.phase == MovePhase::Verified) {
|
||||
// The copy was verified before the crash: roll forward.
|
||||
if (auto completed = complete(move_id); !completed) {
|
||||
return std::unexpected{std::move(completed).error()};
|
||||
}
|
||||
return Recovery::RolledForward;
|
||||
}
|
||||
if (move->record.phase == MovePhase::Frozen) {
|
||||
// No complete copy is proven: roll back to the source.
|
||||
abort(move_id, "recovered after crash before verification");
|
||||
return Recovery::RolledBack;
|
||||
}
|
||||
return Recovery::None;
|
||||
}
|
||||
|
||||
Void::Result::Result<MoveRecord>
|
||||
RangeDirectory::move(std::uint64_t move_id) const
|
||||
{
|
||||
const auto found = m_moves.find(move_id);
|
||||
if (found == m_moves.end()) {
|
||||
return std::unexpected{not_found("RangeDirectory: unknown move")};
|
||||
}
|
||||
return found->second.record;
|
||||
}
|
||||
|
||||
std::string RangeDirectory::encode() const
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& [start, ownership] : m_ranges) {
|
||||
(void)start;
|
||||
out += ownership.range.start;
|
||||
out += '\t';
|
||||
out += ownership.range.end;
|
||||
out += '\t';
|
||||
out += ownership.owner;
|
||||
out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::persist(ReplicatedKvCluster& cluster,
|
||||
std::string_view leader, std::string_view key)
|
||||
{
|
||||
const std::string encoded = encode();
|
||||
if (encoded.size() > max_directory_bytes) {
|
||||
return std::unexpected{invalid(
|
||||
"RangeDirectory: directory exceeds max_directory_bytes")};
|
||||
}
|
||||
const KvWriteReply reply =
|
||||
cluster.propose(leader, std::string{key}, encoded);
|
||||
if (reply.outcome != KvWriteOutcome::Applied) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::exhausted,
|
||||
"RangeDirectory: directory write was not majority-committed"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
RangeDirectory::load(ReplicatedKvCluster& cluster,
|
||||
std::string_view leader, std::string_view key)
|
||||
{
|
||||
auto stored = cluster.quorum_read(leader, key);
|
||||
if (!stored) {
|
||||
return std::unexpected{std::move(stored).error()};
|
||||
}
|
||||
if (!stored->has_value()) {
|
||||
return std::unexpected{
|
||||
not_found("RangeDirectory: no persisted directory")};
|
||||
}
|
||||
const std::string& encoded = **stored;
|
||||
if (encoded.size() > max_directory_bytes) {
|
||||
return std::unexpected{
|
||||
corrupt("RangeDirectory: persisted directory is too large")};
|
||||
}
|
||||
|
||||
// Validate everything into a candidate map before installing it.
|
||||
std::map<std::string, RangeOwnership, std::less<>> candidate;
|
||||
std::size_t line_begin = 0;
|
||||
while (line_begin < encoded.size()) {
|
||||
const std::size_t line_end = encoded.find('\n', line_begin);
|
||||
if (line_end == std::string::npos) {
|
||||
return std::unexpected{
|
||||
corrupt("RangeDirectory: unterminated record")};
|
||||
}
|
||||
const std::string_view line = std::string_view{encoded}.substr(
|
||||
line_begin, line_end - line_begin);
|
||||
const std::size_t first = line.find('\t');
|
||||
const std::size_t second =
|
||||
first == std::string_view::npos ? std::string_view::npos
|
||||
: line.find('\t', first + 1);
|
||||
if (first == std::string_view::npos ||
|
||||
second == std::string_view::npos ||
|
||||
line.find('\t', second + 1) != std::string_view::npos) {
|
||||
return std::unexpected{
|
||||
corrupt("RangeDirectory: malformed record")};
|
||||
}
|
||||
RangeOwnership ownership;
|
||||
ownership.range.start = std::string{line.substr(0, first)};
|
||||
ownership.range.end =
|
||||
std::string{line.substr(first + 1, second - first - 1)};
|
||||
ownership.owner = std::string{line.substr(second + 1)};
|
||||
if (!ownership.range.valid() ||
|
||||
!known_voter(ownership.owner) ||
|
||||
candidate.contains(ownership.range.start)) {
|
||||
return std::unexpected{
|
||||
corrupt("RangeDirectory: invalid record")};
|
||||
}
|
||||
for (const auto& [start, existing] : candidate) {
|
||||
(void)start;
|
||||
if (overlapping(ownership.range, existing.range)) {
|
||||
return std::unexpected{
|
||||
corrupt("RangeDirectory: overlapping ranges")};
|
||||
}
|
||||
}
|
||||
candidate.emplace(ownership.range.start, std::move(ownership));
|
||||
line_begin = line_end + 1;
|
||||
}
|
||||
|
||||
m_ranges = std::move(candidate);
|
||||
// Interrupted moves do not survive a directory load.
|
||||
m_moves.clear();
|
||||
return {};
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,411 @@
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error no_quorum(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::overloaded,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error not_found(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error not_leader(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ReplicatedKvCluster::ReplicatedKvCluster(std::vector<std::string> voters)
|
||||
: m_voters(std::move(voters))
|
||||
{
|
||||
m_nodes.reserve(m_voters.size());
|
||||
for (const auto& id : m_voters) {
|
||||
Node node;
|
||||
node.id = id;
|
||||
// Sentinel entry keeps log indices 1-based and match the entry
|
||||
// index directly.
|
||||
node.log.push_back(KvLogEntry{.term = 0, .index = 0});
|
||||
m_nodes.push_back(std::move(node));
|
||||
}
|
||||
}
|
||||
|
||||
ReplicatedKvCluster::Node* ReplicatedKvCluster::find(std::string_view id)
|
||||
{
|
||||
for (auto& node : m_nodes) {
|
||||
if (node.id == id) {
|
||||
return &node;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const ReplicatedKvCluster::Node*
|
||||
ReplicatedKvCluster::find(std::string_view id) const
|
||||
{
|
||||
for (const auto& node : m_nodes) {
|
||||
if (node.id == id) {
|
||||
return &node;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool ReplicatedKvCluster::reachable(const Node& a, const Node& b) const
|
||||
{
|
||||
return a.alive && b.alive && a.partition == b.partition;
|
||||
}
|
||||
|
||||
bool ReplicatedKvCluster::majority(std::size_t acks) const
|
||||
{
|
||||
return acks > m_voters.size() / 2;
|
||||
}
|
||||
|
||||
bool ReplicatedKvCluster::log_up_to_date(const Node& candidate,
|
||||
const Node& voter)
|
||||
{
|
||||
const auto& last_candidate = candidate.log.back();
|
||||
const auto& last_voter = voter.log.back();
|
||||
if (last_candidate.term != last_voter.term) {
|
||||
return last_candidate.term > last_voter.term;
|
||||
}
|
||||
return last_candidate.index >= last_voter.index;
|
||||
}
|
||||
|
||||
void ReplicatedKvCluster::apply_committed(Node& node)
|
||||
{
|
||||
while (node.applied_index < node.commit_index &&
|
||||
node.applied_index + 1 < node.log.size()) {
|
||||
const KvLogEntry& entry = node.log[node.applied_index + 1];
|
||||
if (entry.value.has_value()) {
|
||||
node.kv.insert_or_assign(entry.key, *entry.value);
|
||||
} else {
|
||||
node.kv.erase(entry.key);
|
||||
}
|
||||
node.applied_index = entry.index;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ReplicatedKvCluster::elect(std::string_view candidate)
|
||||
{
|
||||
Node* self = find(candidate);
|
||||
if (self == nullptr) {
|
||||
return std::unexpected{
|
||||
not_found("ReplicatedKv: unknown voter")};
|
||||
}
|
||||
if (!self->alive) {
|
||||
return std::unexpected{
|
||||
no_quorum("ReplicatedKv: candidate is down")};
|
||||
}
|
||||
|
||||
self->term += 1;
|
||||
self->role = Role::Candidate;
|
||||
self->voted_for = self->id;
|
||||
self->leader.reset();
|
||||
|
||||
std::size_t votes = 1;
|
||||
for (auto& voter : m_nodes) {
|
||||
if (voter.id == self->id || !reachable(*self, voter)) {
|
||||
continue;
|
||||
}
|
||||
if (voter.term < self->term) {
|
||||
voter.term = self->term;
|
||||
voter.voted_for.reset();
|
||||
voter.role = Role::Follower;
|
||||
voter.leader.reset();
|
||||
}
|
||||
const bool can_vote =
|
||||
voter.term == self->term && !voter.voted_for.has_value();
|
||||
if (can_vote && log_up_to_date(*self, voter)) {
|
||||
voter.voted_for = self->id;
|
||||
++votes;
|
||||
}
|
||||
}
|
||||
|
||||
if (!majority(votes)) {
|
||||
self->role = Role::Follower;
|
||||
return std::unexpected{no_quorum(
|
||||
"ReplicatedKv: election did not reach a majority")};
|
||||
}
|
||||
self->role = Role::Leader;
|
||||
self->leader = self->id;
|
||||
for (auto& node : m_nodes) {
|
||||
if (node.id != self->id && reachable(*self, node) &&
|
||||
node.term <= self->term) {
|
||||
node.leader = self->id;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool ReplicatedKvCluster::replicate_to(Node& leader, Node& follower)
|
||||
{
|
||||
if (!reachable(leader, follower)) {
|
||||
return false;
|
||||
}
|
||||
if (follower.term > leader.term) {
|
||||
leader.role = Role::Follower;
|
||||
leader.leader.reset();
|
||||
return false;
|
||||
}
|
||||
if (follower.term < leader.term) {
|
||||
follower.term = leader.term;
|
||||
follower.voted_for.reset();
|
||||
follower.role = Role::Follower;
|
||||
}
|
||||
follower.leader = leader.id;
|
||||
|
||||
// Highest index where both logs agree, then overwrite the suffix.
|
||||
std::size_t match = 0;
|
||||
const std::size_t shared =
|
||||
std::min(follower.log.size(), leader.log.size()) - 1;
|
||||
for (std::size_t i = shared + 1; i-- > 0;) {
|
||||
if (follower.log[i].term == leader.log[i].term) {
|
||||
match = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
follower.log.resize(match + 1);
|
||||
for (std::size_t i = match + 1; i < leader.log.size(); ++i) {
|
||||
follower.log.push_back(leader.log[i]);
|
||||
}
|
||||
// AppendEntries carries the leader commit index: a follower that was
|
||||
// behind applies everything now proven committed.
|
||||
if (leader.commit_index > follower.commit_index) {
|
||||
follower.commit_index = std::min(
|
||||
leader.commit_index,
|
||||
static_cast<std::uint64_t>(follower.log.size() - 1));
|
||||
apply_committed(follower);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
KvWriteReply ReplicatedKvCluster::propose(std::string_view leader_id,
|
||||
std::string key,
|
||||
std::optional<std::string> value)
|
||||
{
|
||||
Node* leader = find(leader_id);
|
||||
if (leader == nullptr || !leader->alive) {
|
||||
return KvWriteReply{.outcome = KvWriteOutcome::NodeDown,
|
||||
.index = 0,
|
||||
.term = leader ? leader->term : 0};
|
||||
}
|
||||
if (leader->role != Role::Leader) {
|
||||
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
|
||||
.index = 0,
|
||||
.term = leader->term};
|
||||
}
|
||||
|
||||
KvLogEntry entry;
|
||||
entry.term = leader->term;
|
||||
entry.index = static_cast<std::uint64_t>(leader->log.size());
|
||||
entry.key = std::move(key);
|
||||
entry.value = std::move(value);
|
||||
leader->log.push_back(entry);
|
||||
|
||||
std::size_t acks = 1;
|
||||
for (auto& follower : m_nodes) {
|
||||
if (follower.id == leader->id) {
|
||||
continue;
|
||||
}
|
||||
if (replicate_to(*leader, follower)) {
|
||||
++acks;
|
||||
}
|
||||
if (leader->role != Role::Leader) {
|
||||
// A higher term was observed: the local append is not durable.
|
||||
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
|
||||
.index = entry.index,
|
||||
.term = leader->term};
|
||||
}
|
||||
}
|
||||
|
||||
if (!majority(acks)) {
|
||||
// Uncommitted: a later leader may truncate it. Never applied.
|
||||
return KvWriteReply{.outcome = KvWriteOutcome::NoQuorum,
|
||||
.index = entry.index,
|
||||
.term = leader->term};
|
||||
}
|
||||
|
||||
leader->commit_index = entry.index;
|
||||
apply_committed(*leader);
|
||||
for (auto& node : m_nodes) {
|
||||
if (node.id == leader->id || !reachable(*leader, node)) {
|
||||
continue;
|
||||
}
|
||||
// Only nodes whose log matches the committed entry may apply it.
|
||||
if (node.log.size() > entry.index &&
|
||||
node.log[entry.index].term == entry.term) {
|
||||
node.commit_index =
|
||||
std::max(node.commit_index, entry.index);
|
||||
apply_committed(node);
|
||||
}
|
||||
}
|
||||
return KvWriteReply{
|
||||
.outcome = KvWriteOutcome::Applied,
|
||||
.index = entry.index,
|
||||
.term = leader->term};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ReplicatedKvCluster::heartbeat(std::string_view leader_id)
|
||||
{
|
||||
Node* leader = find(leader_id);
|
||||
if (leader == nullptr) {
|
||||
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||
}
|
||||
if (!leader->alive || leader->role != Role::Leader) {
|
||||
return std::unexpected{
|
||||
not_leader("ReplicatedKv: heartbeat requires a leader")};
|
||||
}
|
||||
for (auto& follower : m_nodes) {
|
||||
if (follower.id != leader->id) {
|
||||
(void)replicate_to(*leader, follower);
|
||||
}
|
||||
}
|
||||
if (leader->role != Role::Leader) {
|
||||
return std::unexpected{not_leader(
|
||||
"ReplicatedKv: stepped down after a higher term")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ReplicatedKvCluster::confirm_leader(Node& node)
|
||||
{
|
||||
if (!node.alive) {
|
||||
return std::unexpected{no_quorum("ReplicatedKv: node is down")};
|
||||
}
|
||||
if (node.role != Role::Leader) {
|
||||
return std::unexpected{not_leader(
|
||||
"ReplicatedKv: consistent reads require a leader")};
|
||||
}
|
||||
// Confirm leadership in this term with a majority heartbeat.
|
||||
std::size_t acks = 1;
|
||||
for (auto& peer : m_nodes) {
|
||||
if (peer.id == node.id || !reachable(node, peer)) {
|
||||
continue;
|
||||
}
|
||||
if (peer.term > node.term) {
|
||||
node.role = Role::Follower;
|
||||
node.leader.reset();
|
||||
return std::unexpected{not_leader(
|
||||
"ReplicatedKv: stepped down after a higher term")};
|
||||
}
|
||||
++acks;
|
||||
}
|
||||
if (!majority(acks)) {
|
||||
return std::unexpected{no_quorum(
|
||||
"ReplicatedKv: no majority to confirm the read")};
|
||||
}
|
||||
// A quorum-confirmed leader has every committed entry; apply them.
|
||||
apply_committed(node);
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<std::string>>
|
||||
ReplicatedKvCluster::quorum_read(std::string_view node_id,
|
||||
std::string_view key)
|
||||
{
|
||||
Node* node = find(node_id);
|
||||
if (node == nullptr) {
|
||||
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||
}
|
||||
if (auto confirmed = confirm_leader(*node); !confirmed) {
|
||||
return std::unexpected{std::move(confirmed).error()};
|
||||
}
|
||||
const auto found = node->kv.find(key);
|
||||
if (found == node->kv.end()) {
|
||||
return std::optional<std::string>{};
|
||||
}
|
||||
return std::optional<std::string>{found->second};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::map<std::string, std::string, std::less<>>>
|
||||
ReplicatedKvCluster::quorum_snapshot(std::string_view node_id)
|
||||
{
|
||||
Node* node = find(node_id);
|
||||
if (node == nullptr) {
|
||||
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||
}
|
||||
if (auto confirmed = confirm_leader(*node); !confirmed) {
|
||||
return std::unexpected{std::move(confirmed).error()};
|
||||
}
|
||||
return node->kv;
|
||||
}
|
||||
|
||||
void ReplicatedKvCluster::crash(std::string_view node_id)
|
||||
{
|
||||
if (Node* node = find(node_id); node != nullptr) {
|
||||
node->alive = false;
|
||||
node->role = Role::Follower;
|
||||
node->leader.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicatedKvCluster::restart(std::string_view node_id)
|
||||
{
|
||||
if (Node* node = find(node_id); node != nullptr) {
|
||||
// Log, term, vote and applied state are durable.
|
||||
node->alive = true;
|
||||
node->role = Role::Follower;
|
||||
node->leader.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicatedKvCluster::set_partition(std::string_view node_id,
|
||||
int partition)
|
||||
{
|
||||
if (Node* node = find(node_id); node != nullptr) {
|
||||
node->partition = partition;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<KvNodeSnapshot>
|
||||
ReplicatedKvCluster::snapshot(std::string_view node_id) const
|
||||
{
|
||||
const Node* node = find(node_id);
|
||||
if (node == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
KvNodeSnapshot out;
|
||||
out.id = node->id;
|
||||
out.alive = node->alive;
|
||||
out.role = node->role;
|
||||
out.term = node->term;
|
||||
out.commit_index = node->commit_index;
|
||||
out.applied_index = node->applied_index;
|
||||
out.log_size = node->log.size();
|
||||
out.leader = node->leader;
|
||||
out.kv = node->kv;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::uint64_t ReplicatedKvCluster::committed_index() const
|
||||
{
|
||||
std::uint64_t highest = 0;
|
||||
for (const auto& node : m_nodes) {
|
||||
if (node.alive) {
|
||||
highest = std::max(highest, node.commit_index);
|
||||
}
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,495 @@
|
||||
#include "distributed_host/replicated_queue.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::array<std::byte, 4> kMagic{
|
||||
std::byte{'V'}, std::byte{'J'}, std::byte{'O'}, std::byte{'B'}};
|
||||
constexpr std::uint32_t kVersion{1};
|
||||
constexpr std::size_t kMaxIdBytes{128};
|
||||
constexpr std::size_t kMaxConsumerBytes{128};
|
||||
constexpr std::size_t kMaxReasonBytes{512};
|
||||
constexpr std::string_view kJobPrefix{"job/"};
|
||||
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error not_found(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error exhausted(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error corrupt(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
|
||||
{
|
||||
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
|
||||
{
|
||||
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::uint32_t& value) noexcept
|
||||
{
|
||||
if (pos + 4 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint32_t>(in[pos + i]);
|
||||
}
|
||||
pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::uint64_t& value) noexcept
|
||||
{
|
||||
if (pos + 8 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint64_t>(in[pos + i]);
|
||||
}
|
||||
pos += 8;
|
||||
return true;
|
||||
}
|
||||
|
||||
void append_string(std::vector<std::byte>& out, std::string_view text)
|
||||
{
|
||||
append_u32(out, static_cast<std::uint32_t>(text.size()));
|
||||
for (const char c : text) {
|
||||
out.push_back(static_cast<std::byte>(
|
||||
static_cast<unsigned char>(c)));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_string(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::string& out,
|
||||
std::size_t max_bytes) noexcept
|
||||
{
|
||||
std::uint32_t length = 0;
|
||||
if (!read_u32(in, pos, length) || length > max_bytes ||
|
||||
pos + length > in.size()) {
|
||||
return false;
|
||||
}
|
||||
out.clear();
|
||||
out.reserve(length);
|
||||
for (std::uint32_t i = 0; i < length; ++i) {
|
||||
out.push_back(static_cast<char>(
|
||||
std::to_integer<unsigned char>(in[pos + i])));
|
||||
}
|
||||
pos += length;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
|
||||
{
|
||||
std::uint64_t hash = 0xCBF29CE484222325ULL;
|
||||
for (const std::byte byte : bytes) {
|
||||
hash ^= std::to_integer<std::uint64_t>(byte);
|
||||
hash *= 0x100000001B3ULL;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::byte> encode_job(const QueueJob& job)
|
||||
{
|
||||
std::vector<std::byte> out;
|
||||
out.insert(out.end(), kMagic.begin(), kMagic.end());
|
||||
append_u32(out, kVersion);
|
||||
append_string(out, job.id);
|
||||
append_string(out, job.payload);
|
||||
out.push_back(static_cast<std::byte>(job.state));
|
||||
append_u32(out, job.attempts);
|
||||
append_string(out, job.consumer);
|
||||
out.push_back(std::byte{job.outbox_pending ? 1 : 0});
|
||||
append_string(out, job.reason);
|
||||
append_u64(out, checksum(out));
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<QueueJob>
|
||||
decode_job(std::span<const std::byte> bytes)
|
||||
{
|
||||
if (bytes.size() < kMagic.size() + 4 + 8 ||
|
||||
!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::size_t payload = bytes.size() - 8;
|
||||
std::uint64_t stored = 0;
|
||||
{
|
||||
std::size_t check_pos = payload;
|
||||
if (!read_u64(bytes, check_pos, stored) ||
|
||||
checksum(bytes.first(payload)) != stored) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
std::size_t pos = kMagic.size();
|
||||
std::uint32_t version = 0;
|
||||
if (!read_u32(bytes, pos, version) || version != kVersion) {
|
||||
return std::nullopt;
|
||||
}
|
||||
QueueJob job;
|
||||
if (!read_string(bytes, pos, job.id, kMaxIdBytes) ||
|
||||
!read_string(bytes, pos, job.payload, 1024ULL * 1024ULL) ||
|
||||
pos >= payload) {
|
||||
return std::nullopt;
|
||||
}
|
||||
job.state = static_cast<JobState>(
|
||||
std::to_integer<unsigned char>(bytes[pos++]));
|
||||
if (job.state != JobState::Pending &&
|
||||
job.state != JobState::InFlight &&
|
||||
job.state != JobState::Done && job.state != JobState::Dead) {
|
||||
return std::nullopt;
|
||||
}
|
||||
if (!read_u32(bytes, pos, job.attempts) ||
|
||||
!read_string(bytes, pos, job.consumer, kMaxConsumerBytes) ||
|
||||
pos >= payload) {
|
||||
return std::nullopt;
|
||||
}
|
||||
job.outbox_pending = std::to_integer<unsigned char>(bytes[pos++]) != 0;
|
||||
if (!read_string(bytes, pos, job.reason, kMaxReasonBytes) ||
|
||||
pos != payload) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string to_string(std::span<const std::byte> bytes)
|
||||
{
|
||||
return std::string{
|
||||
reinterpret_cast<const char*>(bytes.data()), bytes.size()};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string_view job_state_name(JobState state) noexcept
|
||||
{
|
||||
switch (state) {
|
||||
case JobState::Pending: return "pending";
|
||||
case JobState::InFlight: return "in-flight";
|
||||
case JobState::Done: return "done";
|
||||
case JobState::Dead: return "dead";
|
||||
}
|
||||
return "pending";
|
||||
}
|
||||
|
||||
ReplicatedQueue::ReplicatedQueue(ReplicatedKvCluster& cluster,
|
||||
std::string leader, QueueConfig config)
|
||||
: m_cluster(cluster), m_leader(std::move(leader)), m_config(config)
|
||||
{
|
||||
}
|
||||
|
||||
std::string ReplicatedQueue::key_for(std::string_view id)
|
||||
{
|
||||
return std::string{kJobPrefix} + std::string{id};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> ReplicatedQueue::store(const QueueJob& job)
|
||||
{
|
||||
const auto encoded = encode_job(job);
|
||||
const KvWriteReply reply = m_cluster.propose(
|
||||
m_leader, key_for(job.id), to_string(encoded));
|
||||
switch (reply.outcome) {
|
||||
case KvWriteOutcome::Applied:
|
||||
return {};
|
||||
case KvWriteOutcome::NoQuorum:
|
||||
return std::unexpected{exhausted(
|
||||
"ReplicatedQueue: write was not majority-committed")};
|
||||
case KvWriteOutcome::NotLeader:
|
||||
return std::unexpected{
|
||||
conflict("ReplicatedQueue: endpoint is not the leader")};
|
||||
case KvWriteOutcome::NodeDown:
|
||||
return std::unexpected{exhausted(
|
||||
"ReplicatedQueue: leader is down")};
|
||||
}
|
||||
return std::unexpected{
|
||||
exhausted("ReplicatedQueue: unknown commit outcome")};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<QueueJob>>
|
||||
ReplicatedQueue::load(std::string_view job_id)
|
||||
{
|
||||
auto stored = m_cluster.quorum_read(m_leader, key_for(job_id));
|
||||
if (!stored) {
|
||||
return std::unexpected{std::move(stored).error()};
|
||||
}
|
||||
if (!stored->has_value()) {
|
||||
return std::optional<QueueJob>{};
|
||||
}
|
||||
const auto bytes =
|
||||
std::as_bytes(std::span{(*stored)->data(), (*stored)->size()});
|
||||
auto decoded = decode_job(bytes);
|
||||
if (!decoded) {
|
||||
return std::unexpected{corrupt("ReplicatedQueue: corrupt job record")};
|
||||
}
|
||||
return std::optional<QueueJob>{std::move(*decoded)};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<std::pair<std::string, QueueJob>>>
|
||||
ReplicatedQueue::all_jobs()
|
||||
{
|
||||
auto snapshot = m_cluster.quorum_snapshot(m_leader);
|
||||
if (!snapshot) {
|
||||
return std::unexpected{std::move(snapshot).error()};
|
||||
}
|
||||
std::vector<std::pair<std::string, QueueJob>> jobs;
|
||||
for (const auto& [key, value] : *snapshot) {
|
||||
if (!key.starts_with(kJobPrefix)) {
|
||||
continue;
|
||||
}
|
||||
const auto bytes = std::as_bytes(std::span{value.data(), value.size()});
|
||||
auto decoded = decode_job(bytes);
|
||||
if (!decoded) {
|
||||
return std::unexpected{
|
||||
corrupt("ReplicatedQueue: corrupt job record")};
|
||||
}
|
||||
jobs.emplace_back(key, std::move(*decoded));
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
ReplicatedQueue::publish(std::string payload,
|
||||
std::string idempotency_key)
|
||||
{
|
||||
if (idempotency_key.empty() || idempotency_key.size() > kMaxIdBytes) {
|
||||
return std::unexpected{
|
||||
invalid("ReplicatedQueue: invalid idempotency key")};
|
||||
}
|
||||
if (payload.size() > m_config.max_payload_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("ReplicatedQueue: payload exceeds max_payload_bytes")};
|
||||
}
|
||||
auto jobs = all_jobs();
|
||||
if (!jobs) {
|
||||
return std::unexpected{std::move(jobs).error()};
|
||||
}
|
||||
for (const auto& [key, job] : *jobs) {
|
||||
(void)key;
|
||||
if (job.id == idempotency_key) {
|
||||
// Deduplicated: the caller's retry resolves to the same job.
|
||||
return idempotency_key;
|
||||
}
|
||||
}
|
||||
if (jobs->size() >= m_config.max_jobs) {
|
||||
return std::unexpected{
|
||||
exhausted("ReplicatedQueue: job cap reached")};
|
||||
}
|
||||
QueueJob job;
|
||||
job.id = idempotency_key;
|
||||
job.payload = std::move(payload);
|
||||
if (auto written = store(job); !written) {
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
return idempotency_key;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<QueueJob>>
|
||||
ReplicatedQueue::claim(std::string_view consumer)
|
||||
{
|
||||
if (consumer.empty()) {
|
||||
return std::unexpected{
|
||||
invalid("ReplicatedQueue: consumer must not be empty")};
|
||||
}
|
||||
auto jobs = all_jobs();
|
||||
if (!jobs) {
|
||||
return std::unexpected{std::move(jobs).error()};
|
||||
}
|
||||
for (auto& [key, job] : *jobs) {
|
||||
(void)key;
|
||||
if (job.state != JobState::Pending) {
|
||||
continue;
|
||||
}
|
||||
job.state = JobState::InFlight;
|
||||
job.consumer = std::string{consumer};
|
||||
++job.attempts;
|
||||
if (auto written = store(job); !written) {
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
return std::optional<QueueJob>{std::move(job)};
|
||||
}
|
||||
return std::optional<QueueJob>{};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ReplicatedQueue::ack(std::string_view consumer, std::string_view job_id)
|
||||
{
|
||||
auto job = load(job_id);
|
||||
if (!job) {
|
||||
return std::unexpected{std::move(job).error()};
|
||||
}
|
||||
if (!job->has_value()) {
|
||||
return std::unexpected{
|
||||
not_found("ReplicatedQueue: unknown job")};
|
||||
}
|
||||
if ((*job)->state == JobState::Done) {
|
||||
// Duplicate delivery: the inbox already recorded the outcome and
|
||||
// the outbox must not gain a second entry.
|
||||
return {};
|
||||
}
|
||||
if ((*job)->state != JobState::InFlight ||
|
||||
(*job)->consumer != consumer) {
|
||||
return std::unexpected{conflict(
|
||||
"ReplicatedQueue: job is not in flight for this consumer")};
|
||||
}
|
||||
(*job)->state = JobState::Done;
|
||||
(*job)->consumer.clear();
|
||||
(*job)->outbox_pending = true;
|
||||
return store(**job);
|
||||
}
|
||||
|
||||
Void::Result::Result<QueueJob>
|
||||
ReplicatedQueue::nack(std::string_view consumer, std::string_view job_id,
|
||||
std::string reason)
|
||||
{
|
||||
auto job = load(job_id);
|
||||
if (!job) {
|
||||
return std::unexpected{std::move(job).error()};
|
||||
}
|
||||
if (!job->has_value()) {
|
||||
return std::unexpected{
|
||||
not_found("ReplicatedQueue: unknown job")};
|
||||
}
|
||||
if ((*job)->state != JobState::InFlight ||
|
||||
(*job)->consumer != consumer) {
|
||||
return std::unexpected{conflict(
|
||||
"ReplicatedQueue: job is not in flight for this consumer")};
|
||||
}
|
||||
(*job)->reason = std::move(reason);
|
||||
(*job)->consumer.clear();
|
||||
if ((*job)->attempts >= m_config.max_attempts) {
|
||||
(*job)->state = JobState::Dead;
|
||||
} else {
|
||||
(*job)->state = JobState::Pending;
|
||||
}
|
||||
if (auto written = store(**job); !written) {
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
return **job;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
ReplicatedQueue::recover_consumer(std::string_view consumer)
|
||||
{
|
||||
auto jobs = all_jobs();
|
||||
if (!jobs) {
|
||||
return std::unexpected{std::move(jobs).error()};
|
||||
}
|
||||
std::size_t affected = 0;
|
||||
for (auto& [key, job] : *jobs) {
|
||||
(void)key;
|
||||
if (job.state != JobState::InFlight || job.consumer != consumer) {
|
||||
continue;
|
||||
}
|
||||
job.consumer.clear();
|
||||
if (job.attempts >= m_config.max_attempts) {
|
||||
job.state = JobState::Dead;
|
||||
job.reason = "consumer lost after final attempt";
|
||||
} else {
|
||||
job.state = JobState::Pending;
|
||||
}
|
||||
if (auto written = store(job); !written) {
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
++affected;
|
||||
}
|
||||
return affected;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t>
|
||||
ReplicatedQueue::dispatch_outbox(const OutboxSink& sink)
|
||||
{
|
||||
auto jobs = all_jobs();
|
||||
if (!jobs) {
|
||||
return std::unexpected{std::move(jobs).error()};
|
||||
}
|
||||
std::size_t delivered = 0;
|
||||
for (auto& [key, job] : *jobs) {
|
||||
(void)key;
|
||||
if (job.state != JobState::Done || !job.outbox_pending) {
|
||||
continue;
|
||||
}
|
||||
if (sink) {
|
||||
sink(job);
|
||||
}
|
||||
job.outbox_pending = false;
|
||||
if (auto written = store(job); !written) {
|
||||
// The effect was delivered but not marked: the next dispatch
|
||||
// delivers it again (at-least-once).
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
++delivered;
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<QueueJob>>
|
||||
ReplicatedQueue::dead_letters()
|
||||
{
|
||||
auto jobs = all_jobs();
|
||||
if (!jobs) {
|
||||
return std::unexpected{std::move(jobs).error()};
|
||||
}
|
||||
std::vector<QueueJob> dead;
|
||||
for (auto& [key, job] : *jobs) {
|
||||
(void)key;
|
||||
if (job.state == JobState::Dead) {
|
||||
dead.push_back(std::move(job));
|
||||
}
|
||||
}
|
||||
return dead;
|
||||
}
|
||||
|
||||
Void::Result::Result<QueueJob>
|
||||
ReplicatedQueue::status(std::string_view job_id)
|
||||
{
|
||||
auto job = load(job_id);
|
||||
if (!job) {
|
||||
return std::unexpected{std::move(job).error()};
|
||||
}
|
||||
if (!job->has_value()) {
|
||||
return std::unexpected{
|
||||
not_found("ReplicatedQueue: unknown job")};
|
||||
}
|
||||
return **job;
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,376 @@
|
||||
#include "distributed_host/single_node.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace DistributedHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument, std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error exhausted(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool parse_address(std::string_view address,
|
||||
std::string& host,
|
||||
std::uint16_t& port) noexcept
|
||||
{
|
||||
const auto colon = address.rfind(':');
|
||||
if (colon == std::string_view::npos || colon == 0 ||
|
||||
colon + 1 >= address.size()) {
|
||||
return false;
|
||||
}
|
||||
host = std::string{address.substr(0, colon)};
|
||||
const auto digits = address.substr(colon + 1);
|
||||
unsigned int value = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
digits.data(), digits.data() + digits.size(), value);
|
||||
if (parsed.ec != std::errc{} ||
|
||||
parsed.ptr != digits.data() + digits.size() || value > 65535U) {
|
||||
return false;
|
||||
}
|
||||
port = static_cast<std::uint16_t>(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Length-independent comparison: always scans the full candidate.
|
||||
[[nodiscard]] bool constant_time_equal(std::string_view a,
|
||||
std::string_view b) noexcept
|
||||
{
|
||||
unsigned char difference =
|
||||
static_cast<unsigned char>(a.size() == b.size() ? 0 : 1);
|
||||
for (std::size_t i = 0; i < b.size(); ++i) {
|
||||
const unsigned char left =
|
||||
i < a.size() ? static_cast<unsigned char>(a[i]) : 0;
|
||||
difference |= static_cast<unsigned char>(
|
||||
left ^ static_cast<unsigned char>(b[i]));
|
||||
}
|
||||
return difference == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool iequals_ascii(std::string_view a,
|
||||
std::string_view b) noexcept
|
||||
{
|
||||
if (a.size() != b.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < a.size(); ++i) {
|
||||
auto lower = [](char c) noexcept {
|
||||
return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a')
|
||||
: c;
|
||||
};
|
||||
if (lower(a[i]) != lower(b[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
|
||||
std::string body)
|
||||
{
|
||||
Void::Net::ServerResponse response;
|
||||
response.status = static_cast<std::uint16_t>(status);
|
||||
response.headers.push_back(
|
||||
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
|
||||
response.headers.push_back(Void::Net::Header{"cache-control", "no-store"});
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void> SingleNodeConfig::validate() const
|
||||
{
|
||||
std::string host;
|
||||
std::uint16_t port = 0;
|
||||
if (!parse_address(peer_address, host, port)) {
|
||||
return std::unexpected{
|
||||
invalid("SingleNodeConfig: peer_address must be host:port")};
|
||||
}
|
||||
if (peer_token.empty()) {
|
||||
return std::unexpected{invalid(
|
||||
"SingleNodeConfig: peer_token is required (fail closed)")};
|
||||
}
|
||||
if (max_connections == 0) {
|
||||
return std::unexpected{invalid(
|
||||
"SingleNodeConfig: max_connections must be positive")};
|
||||
}
|
||||
if (max_append_bytes == 0) {
|
||||
return std::unexpected{invalid(
|
||||
"SingleNodeConfig: max_append_bytes must be positive")};
|
||||
}
|
||||
if (max_log_entries == 0) {
|
||||
return std::unexpected{invalid(
|
||||
"SingleNodeConfig: max_log_entries must be positive")};
|
||||
}
|
||||
if (shutdown_grace.count() < 0) {
|
||||
return std::unexpected{invalid(
|
||||
"SingleNodeConfig: shutdown_grace must not be negative")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
PeerLog::PeerLog(std::size_t max_entries)
|
||||
: m_max_entries(max_entries)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t> PeerLog::append(std::string entry)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (m_entries.size() >= m_max_entries) {
|
||||
return std::unexpected{exhausted(
|
||||
"PeerLog: retained entry cap reached")};
|
||||
}
|
||||
m_entries.push_back(std::move(entry));
|
||||
return static_cast<std::uint64_t>(m_entries.size());
|
||||
}
|
||||
|
||||
std::size_t PeerLog::size() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_entries.size();
|
||||
}
|
||||
|
||||
std::uint64_t PeerLog::last_index() const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return static_cast<std::uint64_t>(m_entries.size());
|
||||
}
|
||||
|
||||
HttpPeerTransport::HttpPeerTransport(std::string address, std::string token,
|
||||
PeerLog& log,
|
||||
std::size_t max_connections,
|
||||
std::size_t max_append_bytes)
|
||||
: m_address(std::move(address))
|
||||
, m_token(std::move(token))
|
||||
, m_log(log)
|
||||
, m_max_connections(max_connections)
|
||||
, m_max_append_bytes(max_append_bytes)
|
||||
{
|
||||
}
|
||||
|
||||
HttpPeerTransport::~HttpPeerTransport() noexcept
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
bool HttpPeerTransport::authorized(
|
||||
const Void::Net::ServerRequest& req) const noexcept
|
||||
{
|
||||
if (m_token.empty()) {
|
||||
return false;
|
||||
}
|
||||
const auto header = req.header("authorization");
|
||||
if (!header) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view scheme{"bearer "};
|
||||
if (header->size() < scheme.size() ||
|
||||
!iequals_ascii(header->substr(0, scheme.size()), scheme)) {
|
||||
return false;
|
||||
}
|
||||
return constant_time_equal(header->substr(scheme.size()), m_token);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> HttpPeerTransport::listen()
|
||||
{
|
||||
if (m_server) {
|
||||
return std::unexpected{
|
||||
conflict("HttpPeerTransport: already listening")};
|
||||
}
|
||||
std::string host;
|
||||
std::uint16_t port = 0;
|
||||
if (!parse_address(m_address, host, port)) {
|
||||
return std::unexpected{
|
||||
invalid("HttpPeerTransport: address must be host:port")};
|
||||
}
|
||||
|
||||
Void::Net::HttpServerOptions options;
|
||||
options.bind_host = std::move(host);
|
||||
options.port = port;
|
||||
options.max_concurrent_connections = m_max_connections;
|
||||
options.max_body_bytes = m_max_append_bytes;
|
||||
auto server = std::make_unique<Void::Net::HttpServer>(options);
|
||||
|
||||
auto added = server->add_route(
|
||||
Void::Net::Method::Get, "/peer/health",
|
||||
[this](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
if (!authorized(req)) {
|
||||
return Void::Result::ok(
|
||||
text_response(401, "unauthorized"));
|
||||
}
|
||||
return Void::Result::ok(text_response(
|
||||
200, std::format("role=leader entries={} last_index={}",
|
||||
m_log.size(), m_log.last_index())));
|
||||
});
|
||||
if (!added) {
|
||||
return std::unexpected{std::move(added).error()};
|
||||
}
|
||||
added = server->add_route(
|
||||
Void::Net::Method::Post, "/peer/append",
|
||||
[this](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
if (!authorized(req)) {
|
||||
return Void::Result::ok(
|
||||
text_response(401, "unauthorized"));
|
||||
}
|
||||
if (req.body.empty()) {
|
||||
return Void::Result::ok(
|
||||
text_response(400, "empty entry"));
|
||||
}
|
||||
if (req.body.size() > m_max_append_bytes) {
|
||||
return Void::Result::ok(
|
||||
text_response(413, "entry too large"));
|
||||
}
|
||||
auto index = m_log.append(req.body);
|
||||
if (!index) {
|
||||
return Void::Result::ok(
|
||||
text_response(503, index.error().message()));
|
||||
}
|
||||
return Void::Result::ok(text_response(
|
||||
200, std::format("index={}", *index)));
|
||||
});
|
||||
if (!added) {
|
||||
return std::unexpected{std::move(added).error()};
|
||||
}
|
||||
if (auto started = server->start(); !started) {
|
||||
return started;
|
||||
}
|
||||
m_server = std::move(server);
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
HttpPeerTransport::connect_peers(const std::vector<NodeId>& peers)
|
||||
{
|
||||
// A single-node fixture has no outgoing peer connections; the count is
|
||||
// recorded for inspect and the multi-node transport is a later task.
|
||||
m_connected_peers = peers.size();
|
||||
return {};
|
||||
}
|
||||
|
||||
void HttpPeerTransport::close() noexcept
|
||||
{
|
||||
if (m_server) {
|
||||
m_server->shutdown(std::chrono::seconds{2});
|
||||
m_server.reset();
|
||||
}
|
||||
m_connected_peers = 0;
|
||||
}
|
||||
|
||||
std::uint16_t HttpPeerTransport::bound_port() const noexcept
|
||||
{
|
||||
return m_server ? m_server->bound_port() : 0;
|
||||
}
|
||||
|
||||
Void::Result::Result<void> SingleNodeReplication::start()
|
||||
{
|
||||
if (m_running) {
|
||||
return std::unexpected{
|
||||
conflict("SingleNodeReplication: already started")};
|
||||
}
|
||||
m_running = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
SingleNodeHost::SingleNodeHost(SingleNodeConfig config)
|
||||
: m_config(std::move(config))
|
||||
, m_log(std::make_unique<PeerLog>(m_config.max_log_entries))
|
||||
, m_storage(std::make_unique<NoopStorage>())
|
||||
{
|
||||
}
|
||||
|
||||
SingleNodeHost::~SingleNodeHost()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
Void::Result::Result<SingleNodeHost>
|
||||
SingleNodeHost::create(SingleNodeConfig config)
|
||||
{
|
||||
if (auto valid = config.validate(); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
SingleNodeHost host{std::move(config)};
|
||||
host.m_transport = std::make_unique<HttpPeerTransport>(
|
||||
host.m_config.peer_address, host.m_config.peer_token, *host.m_log,
|
||||
host.m_config.max_connections, host.m_config.max_append_bytes);
|
||||
host.m_replication = std::make_unique<SingleNodeReplication>();
|
||||
|
||||
HostResources resources;
|
||||
resources.storage = host.m_storage.get();
|
||||
resources.transport = host.m_transport.get();
|
||||
resources.replication = host.m_replication.get();
|
||||
|
||||
HostConfig graph_config;
|
||||
graph_config.cluster = "single-node";
|
||||
graph_config.self = "node-1";
|
||||
graph_config.peers = {};
|
||||
graph_config.publish_discovery = false;
|
||||
graph_config.startup_deadline = host.m_config.shutdown_grace;
|
||||
|
||||
auto graph =
|
||||
DistributedHostGraph::compose(resources, std::move(graph_config));
|
||||
if (!graph) {
|
||||
return std::unexpected{std::move(graph).error()};
|
||||
}
|
||||
host.m_graph =
|
||||
std::make_unique<DistributedHostGraph>(std::move(*graph));
|
||||
return host;
|
||||
}
|
||||
|
||||
Void::Result::Result<void> SingleNodeHost::start()
|
||||
{
|
||||
if (!m_graph) {
|
||||
return std::unexpected{
|
||||
conflict("SingleNodeHost: host was moved out")};
|
||||
}
|
||||
return m_graph->start();
|
||||
}
|
||||
|
||||
void SingleNodeHost::stop() noexcept
|
||||
{
|
||||
if (m_graph) {
|
||||
m_graph->stop();
|
||||
}
|
||||
}
|
||||
|
||||
HealthSnapshot SingleNodeHost::health() const
|
||||
{
|
||||
return m_graph ? m_graph->health() : HealthSnapshot{};
|
||||
}
|
||||
|
||||
std::uint16_t SingleNodeHost::peer_port() const noexcept
|
||||
{
|
||||
return m_transport ? m_transport->bound_port() : 0;
|
||||
}
|
||||
|
||||
const std::vector<std::string>& SingleNodeHost::history() const noexcept
|
||||
{
|
||||
static const std::vector<std::string> empty{};
|
||||
return m_graph ? m_graph->history() : empty;
|
||||
}
|
||||
} // namespace DistributedHost
|
||||
@@ -0,0 +1,184 @@
|
||||
#include "distributed_host/cluster_fixture.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
Void::Net::Header auth()
|
||||
{
|
||||
return Void::Net::Header{"authorization", "Bearer peer-secret"};
|
||||
}
|
||||
|
||||
Void::Net::Response
|
||||
send(Void::Net::HttpClient& client, Void::Net::Method method,
|
||||
const std::string& url, std::string body = {})
|
||||
{
|
||||
Void::Net::Request request;
|
||||
request.method = method;
|
||||
request.url = url;
|
||||
request.body = std::move(body);
|
||||
request.headers.push_back(auth());
|
||||
auto response = client.send(request);
|
||||
assert(response.has_value());
|
||||
return *response;
|
||||
}
|
||||
|
||||
void three_real_listeners_serve_the_replicated_kv()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
// Construction opens nothing.
|
||||
assert((*fixture)->endpoint("a").empty());
|
||||
assert((*fixture)->start().has_value());
|
||||
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
const std::string b = (*fixture)->endpoint("b");
|
||||
const std::string c = (*fixture)->endpoint("c");
|
||||
assert(!a.empty() && !b.empty() && !c.empty());
|
||||
assert(a != b && b != c && a != c);
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
// Every peer route is authenticated.
|
||||
auto anonymous = client.get(a + "/peer/health");
|
||||
assert(anonymous.has_value() && anonymous->status == 401);
|
||||
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").body ==
|
||||
"elected");
|
||||
auto proposed = send(client, Void::Net::Method::Put,
|
||||
a + "/peer/propose?key=k", "value");
|
||||
assert(proposed.status == 200);
|
||||
assert(proposed.body.starts_with("applied"));
|
||||
|
||||
auto read = client.get(a + "/peer/read?key=k", {auth()});
|
||||
assert(read.has_value());
|
||||
assert(read->status == 200);
|
||||
assert(read->body == "value");
|
||||
// The follower applied the committed entry but cannot serve a
|
||||
// consistent read.
|
||||
auto follower_read = client.get(b + "/peer/read?key=k", {auth()});
|
||||
assert(follower_read.has_value());
|
||||
assert(follower_read->status == 409);
|
||||
auto follower_write =
|
||||
send(client, Void::Net::Method::Put, b + "/peer/propose?key=k", "x");
|
||||
assert(follower_write.status == 409);
|
||||
|
||||
(*fixture)->stop();
|
||||
assert((*fixture)->endpoint("a").empty());
|
||||
}
|
||||
|
||||
void minority_leader_cannot_commit_or_read_over_http()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
const std::string b = (*fixture)->endpoint("b");
|
||||
const std::string c = (*fixture)->endpoint("c");
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/admin/partition?node=b&partition=1")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/admin/partition?node=c&partition=1")
|
||||
.status == 200);
|
||||
|
||||
auto proposed = send(client, Void::Net::Method::Put,
|
||||
a + "/peer/propose?key=k", "lost");
|
||||
assert(proposed.status == 503);
|
||||
assert(proposed.body.starts_with("no-quorum"));
|
||||
|
||||
auto read = client.get(a + "/peer/read?key=k", {auth()});
|
||||
assert(read.has_value());
|
||||
assert(read->status == 503);
|
||||
|
||||
// Heal and let the majority take over.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/partition?node=b&partition=0")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/partition?node=c&partition=0")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Put,
|
||||
b + "/peer/propose?key=k", "kept")
|
||||
.status == 200);
|
||||
auto read_after = client.get(b + "/peer/read?key=k", {auth()});
|
||||
assert(read_after.has_value());
|
||||
assert(read_after->status == 200);
|
||||
assert(read_after->body == "kept");
|
||||
|
||||
(*fixture)->stop();
|
||||
}
|
||||
|
||||
void crash_history_keeps_committed_replies()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
const std::string b = (*fixture)->endpoint("b");
|
||||
const std::string c = (*fixture)->endpoint("c");
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Put,
|
||||
a + "/peer/propose?key=committed", "1")
|
||||
.status == 200);
|
||||
|
||||
// One voter crashes: the majority still commits.
|
||||
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=c")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Put,
|
||||
a + "/peer/propose?key=second", "2")
|
||||
.status == 200);
|
||||
|
||||
// A second crash loses the majority: no durable reply.
|
||||
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=b")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Put,
|
||||
a + "/peer/propose?key=third", "3")
|
||||
.status == 503);
|
||||
|
||||
// Restart and re-elect: committed history is intact, the failed
|
||||
// proposal was never applied.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/restart?node=b")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
c + "/admin/restart?node=c")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
|
||||
200);
|
||||
auto first = client.get(b + "/peer/read?key=committed", {auth()});
|
||||
auto second = client.get(b + "/peer/read?key=second", {auth()});
|
||||
auto third = client.get(b + "/peer/read?key=third", {auth()});
|
||||
assert(first.has_value() && first->status == 200 &&
|
||||
first->body == "1");
|
||||
assert(second.has_value() && second->status == 200 &&
|
||||
second->body == "2");
|
||||
assert(third.has_value() && third->status == 404);
|
||||
|
||||
(*fixture)->stop();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
three_real_listeners_serve_the_replicated_kv();
|
||||
minority_leader_cannot_commit_or_read_over_http();
|
||||
crash_history_keeps_committed_replies();
|
||||
std::puts("distributed cluster fixture ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
#include "distributed_host/cluster_fixture.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
Void::Net::Header auth()
|
||||
{
|
||||
return Void::Net::Header{"authorization", "Bearer peer-secret"};
|
||||
}
|
||||
|
||||
Void::Net::Response send(Void::Net::HttpClient& client,
|
||||
Void::Net::Method method, const std::string& url,
|
||||
std::string body = {})
|
||||
{
|
||||
Void::Net::Request request;
|
||||
request.method = method;
|
||||
request.url = url;
|
||||
request.body = std::move(body);
|
||||
request.headers.push_back(auth());
|
||||
auto response = client.send(request);
|
||||
assert(response.has_value());
|
||||
return *response;
|
||||
}
|
||||
|
||||
Void::Net::Response get(Void::Net::HttpClient& client,
|
||||
const std::string& url)
|
||||
{
|
||||
auto response = client.get(url, {auth()});
|
||||
assert(response.has_value());
|
||||
return *response;
|
||||
}
|
||||
|
||||
void publish_claim_ack_dispatch_over_http()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
assert(!a.empty());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
|
||||
auto published = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=q1", "hello");
|
||||
assert(published.status == 200);
|
||||
assert(published.body == "job=q1");
|
||||
// Idempotent by key.
|
||||
auto duplicate = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=q1", "ignored");
|
||||
assert(duplicate.status == 200);
|
||||
assert(duplicate.body == "job=q1");
|
||||
|
||||
auto claimed = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w1");
|
||||
assert(claimed.status == 200);
|
||||
assert(claimed.body.find("job=q1") != std::string::npos);
|
||||
assert(claimed.body.find("payload=hello") != std::string::npos);
|
||||
assert(claimed.body.find("attempts=1") != std::string::npos);
|
||||
|
||||
auto empty = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w1");
|
||||
assert(empty.status == 204);
|
||||
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/ack?consumer=w1&id=q1")
|
||||
.status == 200);
|
||||
auto status = get(client, a + "/queue/status?id=q1");
|
||||
assert(status.status == 200);
|
||||
assert(status.body.find("state=done") != std::string::npos);
|
||||
assert(status.body.find("outbox=1") != std::string::npos);
|
||||
|
||||
// Duplicate ack does not create a second outbox entry.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/ack?consumer=w1&id=q1")
|
||||
.status == 200);
|
||||
|
||||
auto dispatched = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/dispatch");
|
||||
assert(dispatched.status == 200);
|
||||
assert(dispatched.body == "delivered=1");
|
||||
auto again =
|
||||
send(client, Void::Net::Method::Post, a + "/queue/dispatch");
|
||||
assert(again.body == "delivered=0");
|
||||
assert(get(client, a + "/queue/delivered").body == "q1\n");
|
||||
|
||||
// Every queue route is authenticated.
|
||||
auto anonymous = client.get(a + "/queue/dlq");
|
||||
assert(anonymous.has_value());
|
||||
assert(anonymous->status == 401);
|
||||
|
||||
(*fixture)->stop();
|
||||
}
|
||||
|
||||
void retry_then_dead_letter_over_http()
|
||||
{
|
||||
ClusterFixtureConfig config;
|
||||
config.queue.max_attempts = 2;
|
||||
auto fixture = ClusterFixture::create(config);
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=r1", "poison")
|
||||
.status == 200);
|
||||
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w")
|
||||
.status == 200);
|
||||
auto retried = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/nack?consumer=w&id=r1", "boom");
|
||||
assert(retried.status == 200);
|
||||
assert(retried.body == "state=pending attempts=1");
|
||||
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w")
|
||||
.status == 200);
|
||||
auto dead = send(client, Void::Net::Method::Post,
|
||||
a + "/queue/nack?consumer=w&id=r1", "boom again");
|
||||
assert(dead.status == 200);
|
||||
assert(dead.body == "state=dead attempts=2");
|
||||
|
||||
auto dlq = get(client, a + "/queue/dlq");
|
||||
assert(dlq.status == 200);
|
||||
assert(dlq.body.find("id=r1") != std::string::npos);
|
||||
assert(dlq.body.find("reason=boom again") != std::string::npos);
|
||||
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w")
|
||||
.status == 204);
|
||||
(*fixture)->stop();
|
||||
}
|
||||
|
||||
void partition_history_over_http()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
const std::string b = (*fixture)->endpoint("b");
|
||||
const std::string c = (*fixture)->endpoint("c");
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/admin/partition?node=b&partition=1")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/admin/partition?node=c&partition=1")
|
||||
.status == 200);
|
||||
|
||||
// Minority leader: no durable reply for the queue.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=p1", "lost")
|
||||
.status == 503);
|
||||
|
||||
// Heal and let the majority take over.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/partition?node=b&partition=0")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/partition?node=c&partition=0")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/queue/publish?key=p1", "kept")
|
||||
.status == 200);
|
||||
auto claimed = send(client, Void::Net::Method::Post,
|
||||
b + "/queue/claim?consumer=w");
|
||||
assert(claimed.status == 200);
|
||||
assert(claimed.body.find("payload=kept") != std::string::npos);
|
||||
|
||||
(*fixture)->stop();
|
||||
}
|
||||
|
||||
void crash_history_over_http()
|
||||
{
|
||||
auto fixture = ClusterFixture::create();
|
||||
assert(fixture.has_value());
|
||||
assert((*fixture)->start().has_value());
|
||||
const std::string a = (*fixture)->endpoint("a");
|
||||
const std::string b = (*fixture)->endpoint("b");
|
||||
const std::string c = (*fixture)->endpoint("c");
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
|
||||
200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=j1", "one")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/claim?consumer=w")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/ack?consumer=w&id=j1")
|
||||
.status == 200);
|
||||
|
||||
// One crash keeps the majority: j2 is durably published.
|
||||
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=c")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=j2", "two")
|
||||
.status == 200);
|
||||
|
||||
// A second crash loses the majority: j3 has no durable reply.
|
||||
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=b")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
a + "/queue/publish?key=j3", "three")
|
||||
.status == 503);
|
||||
|
||||
// Restart and re-elect: committed history is intact, the failed
|
||||
// publish left no record.
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
b + "/admin/restart?node=b")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post,
|
||||
c + "/admin/restart?node=c")
|
||||
.status == 200);
|
||||
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
|
||||
200);
|
||||
|
||||
assert(get(client, b + "/queue/status?id=j1").body.find("state=done") !=
|
||||
std::string::npos);
|
||||
assert(get(client, b + "/queue/status?id=j2")
|
||||
.body.find("state=pending") != std::string::npos);
|
||||
assert(get(client, b + "/queue/status?id=j3").status == 404);
|
||||
|
||||
auto reclaimed = send(client, Void::Net::Method::Post,
|
||||
b + "/queue/claim?consumer=w");
|
||||
assert(reclaimed.status == 200);
|
||||
assert(reclaimed.body.find("job=j2") != std::string::npos);
|
||||
|
||||
(*fixture)->stop();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
publish_claim_ack_dispatch_over_http();
|
||||
retry_then_dead_letter_over_http();
|
||||
partition_history_over_http();
|
||||
crash_history_over_http();
|
||||
std::puts("distributed cluster queue ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
#include "distributed_host/host_graph.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
/// Deterministic component fakes: they record nothing themselves (the
|
||||
/// graph's history is the ordered record) but can fail at a chosen step.
|
||||
struct FakeStorage final : StorageBackend {
|
||||
bool fail_open{false};
|
||||
bool fail_recover{false};
|
||||
int opens{0};
|
||||
int closes{0};
|
||||
|
||||
Void::Result::Result<void> open() override
|
||||
{
|
||||
++opens;
|
||||
if (fail_open) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io, "storage open failed"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Void::Result::Result<void> recover() override
|
||||
{
|
||||
if (fail_recover) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::corrupt,
|
||||
"storage recovery required"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
void close() noexcept override { ++closes; }
|
||||
};
|
||||
|
||||
struct FakeTransport final : PeerTransport {
|
||||
bool fail_listen{false};
|
||||
bool fail_connect{false};
|
||||
int closes{0};
|
||||
|
||||
Void::Result::Result<void> listen() override
|
||||
{
|
||||
if (fail_listen) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io, "listen failed"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Void::Result::Result<void>
|
||||
connect_peers(const std::vector<NodeId>& peers) override
|
||||
{
|
||||
if (fail_connect) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io, "peer connect failed"}};
|
||||
}
|
||||
(void)peers;
|
||||
return {};
|
||||
}
|
||||
void close() noexcept override { ++closes; }
|
||||
};
|
||||
|
||||
struct FakeReplication final : ReplicationAdapter {
|
||||
bool fail_start{false};
|
||||
bool leader{true};
|
||||
Role current_role{Role::Leader};
|
||||
int stops{0};
|
||||
|
||||
Void::Result::Result<void> start() override
|
||||
{
|
||||
if (fail_start) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::internal,
|
||||
"replication start failed"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Role role() const noexcept override { return current_role; }
|
||||
bool leader_available() const noexcept override { return leader; }
|
||||
void stop() noexcept override { ++stops; }
|
||||
};
|
||||
|
||||
struct FakeDirectory final : DirectoryPublisher {
|
||||
bool fail_publish{false};
|
||||
int published{0};
|
||||
int withdrawals{0};
|
||||
|
||||
Void::Result::Result<void> publish(const NodeId& self) override
|
||||
{
|
||||
(void)self;
|
||||
++published;
|
||||
if (fail_publish) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io, "directory unavailable"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
void withdraw() noexcept override { ++withdrawals; }
|
||||
};
|
||||
|
||||
struct World {
|
||||
FakeStorage storage;
|
||||
FakeTransport transport;
|
||||
FakeReplication replication;
|
||||
FakeDirectory directory;
|
||||
|
||||
HostResources resources()
|
||||
{
|
||||
return HostResources{&storage, &transport, &replication,
|
||||
&directory};
|
||||
}
|
||||
};
|
||||
|
||||
HostConfig config()
|
||||
{
|
||||
HostConfig cfg;
|
||||
cfg.cluster = "test-cluster";
|
||||
cfg.self = "node-1";
|
||||
cfg.peers = {"node-2", "node-3"};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
std::vector<std::string> expected_happy_start()
|
||||
{
|
||||
return {"storage.open", "storage.recover", "transport.listen",
|
||||
"transport.connect_peers", "replication.start",
|
||||
"replication.readiness", "directory.publish"};
|
||||
}
|
||||
|
||||
void compose_validates_configuration()
|
||||
{
|
||||
World world;
|
||||
HostConfig empty_cluster = config();
|
||||
empty_cluster.cluster.clear();
|
||||
assert(!DistributedHostGraph::compose(world.resources(), empty_cluster)
|
||||
.has_value());
|
||||
|
||||
HostConfig self_as_peer = config();
|
||||
self_as_peer.peers.push_back("node-1");
|
||||
assert(!DistributedHostGraph::compose(world.resources(), self_as_peer)
|
||||
.has_value());
|
||||
|
||||
HostConfig zero_deadline = config();
|
||||
zero_deadline.startup_deadline = std::chrono::milliseconds{0};
|
||||
assert(!DistributedHostGraph::compose(world.resources(), zero_deadline)
|
||||
.has_value());
|
||||
|
||||
HostResources incomplete{&world.storage, nullptr, &world.replication,
|
||||
nullptr};
|
||||
assert(!DistributedHostGraph::compose(incomplete, config()).has_value());
|
||||
}
|
||||
|
||||
void happy_path_starts_in_order_and_stops_in_reverse()
|
||||
{
|
||||
World world;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
|
||||
// Construction starts nothing.
|
||||
assert(graph->history().empty());
|
||||
assert(graph->readiness() == Readiness::Starting);
|
||||
|
||||
assert(graph->start().has_value());
|
||||
assert(graph->readiness() == Readiness::WriteReady);
|
||||
assert(graph->health().quorum_available);
|
||||
assert(graph->health().started_components == 3);
|
||||
assert(graph->history() == expected_happy_start());
|
||||
|
||||
graph->stop();
|
||||
const std::vector<std::string> expected_stop{
|
||||
"directory.withdraw", "replication.stop", "transport.close",
|
||||
"storage.close"};
|
||||
assert(graph->history().size() ==
|
||||
expected_happy_start().size() + expected_stop.size());
|
||||
assert(std::equal(expected_stop.begin(), expected_stop.end(),
|
||||
graph->history().end() - expected_stop.size()));
|
||||
assert(graph->readiness() == Readiness::Stopped);
|
||||
assert(graph->health().started_components == 0);
|
||||
assert(world.storage.closes == 1);
|
||||
assert(world.transport.closes == 1);
|
||||
assert(world.replication.stops == 1);
|
||||
|
||||
// Idempotent.
|
||||
graph->stop();
|
||||
assert(world.storage.closes == 1);
|
||||
}
|
||||
|
||||
void follower_is_healthy_but_not_write_ready()
|
||||
{
|
||||
World world;
|
||||
world.replication.leader = false;
|
||||
world.replication.current_role = Role::Follower;
|
||||
HostConfig cfg = config();
|
||||
cfg.require_leader_readiness = false;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), cfg);
|
||||
assert(graph.has_value());
|
||||
assert(graph->start().has_value());
|
||||
assert(graph->readiness() == Readiness::FollowerHealthy);
|
||||
assert(!graph->health().quorum_available);
|
||||
}
|
||||
|
||||
void missing_leader_path_fails_startup_and_unwinds()
|
||||
{
|
||||
World world;
|
||||
world.replication.leader = false;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
auto started = graph->start();
|
||||
assert(!started.has_value());
|
||||
assert(graph->readiness() == Readiness::Failed);
|
||||
assert(graph->health().last_error.find("no leader path") !=
|
||||
std::string::npos);
|
||||
|
||||
// Everything started before the failure is closed in reverse order.
|
||||
const std::vector<std::string> expected{
|
||||
"storage.open", "storage.recover", "transport.listen",
|
||||
"transport.connect_peers", "replication.start", "replication.stop",
|
||||
"transport.close", "storage.close"};
|
||||
assert(graph->history() == expected);
|
||||
assert(world.storage.closes == 1);
|
||||
assert(world.transport.closes == 1);
|
||||
assert(world.replication.stops == 1);
|
||||
}
|
||||
|
||||
void storage_recovery_failure_unwinds_opened_storage()
|
||||
{
|
||||
World world;
|
||||
world.storage.fail_recover = true;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
assert(!graph->start().has_value());
|
||||
assert(graph->readiness() == Readiness::Failed);
|
||||
assert(graph->health().last_error == "storage recovery required");
|
||||
const std::vector<std::string> expected{"storage.open",
|
||||
"storage.close"};
|
||||
assert(graph->history() == expected);
|
||||
assert(world.storage.closes == 1);
|
||||
}
|
||||
|
||||
void peer_connect_failure_keeps_original_error()
|
||||
{
|
||||
World world;
|
||||
world.transport.fail_connect = true;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
assert(!graph->start().has_value());
|
||||
assert(graph->health().last_error == "peer connect failed");
|
||||
assert(graph->readiness() == Readiness::Failed);
|
||||
const std::vector<std::string> expected{
|
||||
"storage.open", "storage.recover", "transport.listen",
|
||||
"transport.close", "storage.close"};
|
||||
assert(graph->history() == expected);
|
||||
}
|
||||
|
||||
void discovery_failure_does_not_weaken_quorum()
|
||||
{
|
||||
World world;
|
||||
world.directory.fail_publish = true;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
assert(graph->start().has_value());
|
||||
// Still write-ready: discovery is an observation adapter.
|
||||
assert(graph->readiness() == Readiness::WriteReady);
|
||||
assert(graph->health().quorum_available);
|
||||
assert(graph->health().last_error == "directory unavailable");
|
||||
assert(world.directory.published == 1);
|
||||
// Nothing to withdraw: the publication was never recorded.
|
||||
graph->stop();
|
||||
assert(world.directory.withdrawals == 0);
|
||||
}
|
||||
|
||||
void discovery_can_be_disabled()
|
||||
{
|
||||
World world;
|
||||
HostConfig cfg = config();
|
||||
cfg.publish_discovery = false;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), cfg);
|
||||
assert(graph.has_value());
|
||||
assert(graph->start().has_value());
|
||||
assert(world.directory.published == 0);
|
||||
for (const auto& step : graph->history()) {
|
||||
assert(step != "directory.publish");
|
||||
}
|
||||
}
|
||||
|
||||
void double_start_is_rejected()
|
||||
{
|
||||
World world;
|
||||
auto graph = DistributedHostGraph::compose(world.resources(), config());
|
||||
assert(graph.has_value());
|
||||
assert(graph->start().has_value());
|
||||
assert(!graph->start().has_value());
|
||||
graph->stop();
|
||||
assert(!graph->start().has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
compose_validates_configuration();
|
||||
happy_path_starts_in_order_and_stops_in_reverse();
|
||||
follower_is_healthy_but_not_write_ready();
|
||||
missing_leader_path_fails_startup_and_unwinds();
|
||||
storage_recovery_failure_unwinds_opened_storage();
|
||||
peer_connect_failure_keeps_original_error();
|
||||
discovery_failure_does_not_weaken_quorum();
|
||||
discovery_can_be_disabled();
|
||||
double_start_is_rejected();
|
||||
std::puts("distributed host graph ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
// Multi-process acceptance harness for the distributed KV reference.
|
||||
//
|
||||
// Spawns three independent voter-agent processes, drives elections and
|
||||
// quorum replication over authenticated HTTP, kills and restarts processes
|
||||
// with SIGKILL, and checks a single-client history: every acknowledged write
|
||||
// is observed by later reads and survives crash/restart, and a write without
|
||||
// a durable reply is never observed half-applied.
|
||||
//
|
||||
// multi_process_test <path-to-distributed_voter_agent>
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
|
||||
#include <csignal>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kToken{"peer-secret"};
|
||||
|
||||
struct Agent {
|
||||
std::string id;
|
||||
std::filesystem::path directory;
|
||||
std::uint16_t port{0};
|
||||
std::optional<Void::Process::Child> child;
|
||||
bool alive{false};
|
||||
};
|
||||
|
||||
struct LogEntry {
|
||||
std::uint64_t term{0};
|
||||
std::uint64_t index{0};
|
||||
std::string key;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct State {
|
||||
std::uint64_t term{0};
|
||||
std::uint64_t last_index{0};
|
||||
std::uint64_t last_term{0};
|
||||
std::uint64_t commit{0};
|
||||
std::size_t entries{0};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t>
|
||||
field(std::string_view text, std::string_view name)
|
||||
{
|
||||
const std::string needle = std::string{name} + "=";
|
||||
const std::size_t at = text.find(needle);
|
||||
if (at == std::string_view::npos) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::uint64_t value = 0;
|
||||
const char* begin = text.data() + at + needle.size();
|
||||
const auto parsed = std::from_chars(begin, text.data() + text.size(), value);
|
||||
if (parsed.ec != std::errc{}) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
class Harness
|
||||
{
|
||||
public:
|
||||
|
||||
Harness(std::string agent_binary, std::size_t count)
|
||||
{
|
||||
const auto root =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("void-mp-" + std::to_string(::getpid()));
|
||||
std::filesystem::remove_all(root);
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
Agent agent;
|
||||
agent.id = "node-" + std::to_string(i);
|
||||
agent.directory = root / agent.id;
|
||||
std::filesystem::create_directories(agent.directory);
|
||||
m_agents.push_back(std::move(agent));
|
||||
}
|
||||
m_agent_binary = std::move(agent_binary);
|
||||
}
|
||||
|
||||
~Harness()
|
||||
{
|
||||
for (auto& agent : m_agents) {
|
||||
if (agent.child && agent.alive) {
|
||||
(void)::kill(static_cast<pid_t>(agent.child->pid()),
|
||||
SIGKILL);
|
||||
(void)agent.child->wait_blocking(
|
||||
std::chrono::seconds{5});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool launch(std::size_t index)
|
||||
{
|
||||
Agent& agent = m_agents[index];
|
||||
std::filesystem::remove(agent.directory / "port");
|
||||
Void::Process::SpawnOptions options;
|
||||
options.executable = m_agent_binary;
|
||||
options.arguments = {"--dir", agent.directory.string(),
|
||||
"--port", "0", "--token",
|
||||
std::string{kToken}, "--parent",
|
||||
std::to_string(::getpid())};
|
||||
options.stdin_pipe = false;
|
||||
options.stdout_pipe = false;
|
||||
options.stderr_pipe = false;
|
||||
auto child = Void::Process::spawn(options);
|
||||
if (!child) {
|
||||
return false;
|
||||
}
|
||||
agent.child.emplace(std::move(*child));
|
||||
agent.alive = true;
|
||||
// The agent publishes its bound port once serving.
|
||||
for (int attempt = 0; attempt < 500; ++attempt) {
|
||||
const auto port_file = agent.directory / "port";
|
||||
if (std::filesystem::exists(port_file)) {
|
||||
std::FILE* file = std::fopen(port_file.c_str(), "r");
|
||||
if (file != nullptr) {
|
||||
unsigned int port = 0;
|
||||
const int matched = std::fscanf(file, "%u", &port);
|
||||
std::fclose(file);
|
||||
if (matched == 1) {
|
||||
agent.port = static_cast<std::uint16_t>(port);
|
||||
return agent.port != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds{10});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void kill(std::size_t index)
|
||||
{
|
||||
Agent& agent = m_agents[index];
|
||||
if (!agent.child || !agent.alive) {
|
||||
return;
|
||||
}
|
||||
(void)::kill(static_cast<pid_t>(agent.child->pid()), SIGKILL);
|
||||
(void)agent.child->wait_blocking(std::chrono::seconds{5});
|
||||
agent.child.reset();
|
||||
agent.alive = false;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string endpoint(std::size_t index) const
|
||||
{
|
||||
return "http://127.0.0.1:" +
|
||||
std::to_string(m_agents[index].port);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool alive(std::size_t index) const
|
||||
{
|
||||
return m_agents[index].alive;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const { return m_agents.size(); }
|
||||
|
||||
// ── RPC ─────────────────────────────────────────────────────────
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
get(std::size_t index, const std::string& path)
|
||||
{
|
||||
auto response = m_client.get(
|
||||
endpoint(index) + path,
|
||||
{Void::Net::Header{"authorization",
|
||||
"Bearer " + std::string{kToken}}});
|
||||
if (!response.has_value() || response->status != 200) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return response->body;
|
||||
}
|
||||
|
||||
[[nodiscard]] int post(std::size_t index, const std::string& path,
|
||||
std::string body = {})
|
||||
{
|
||||
Void::Net::Request request;
|
||||
request.method = Void::Net::Method::Post;
|
||||
request.url = endpoint(index) + path;
|
||||
request.body = std::move(body);
|
||||
request.headers.push_back(Void::Net::Header{
|
||||
"authorization", "Bearer " + std::string{kToken}});
|
||||
auto response = m_client.send(request);
|
||||
if (!response.has_value()) {
|
||||
return -1;
|
||||
}
|
||||
return response->status;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<State> state(std::size_t index)
|
||||
{
|
||||
auto body = get(index, "/voter/state");
|
||||
if (!body) {
|
||||
return std::nullopt;
|
||||
}
|
||||
State out;
|
||||
out.term = field(*body, "term").value_or(0);
|
||||
out.last_index = field(*body, "last_index").value_or(0);
|
||||
out.last_term = field(*body, "last_term").value_or(0);
|
||||
out.commit = field(*body, "commit").value_or(0);
|
||||
out.entries = static_cast<std::size_t>(
|
||||
field(*body, "entries").value_or(0));
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] int vote(std::size_t index, std::uint64_t term,
|
||||
std::string_view candidate,
|
||||
std::uint64_t last_index,
|
||||
std::uint64_t last_term)
|
||||
{
|
||||
return post(index,
|
||||
"/voter/vote?term=" + std::to_string(term) +
|
||||
"&candidate=" + std::string{candidate} +
|
||||
"&last_index=" + std::to_string(last_index) +
|
||||
"&last_term=" + std::to_string(last_term));
|
||||
}
|
||||
|
||||
[[nodiscard]] int append(std::size_t index, std::uint64_t term,
|
||||
std::uint64_t prev_index,
|
||||
std::uint64_t prev_term,
|
||||
std::uint64_t commit,
|
||||
std::string_view entries)
|
||||
{
|
||||
return post(index,
|
||||
"/voter/append?term=" + std::to_string(term) +
|
||||
"&prev_index=" + std::to_string(prev_index) +
|
||||
"&prev_term=" + std::to_string(prev_term) +
|
||||
"&commit=" + std::to_string(commit),
|
||||
std::string{entries});
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
value(std::size_t index, std::string_view key)
|
||||
{
|
||||
return get(index,
|
||||
"/voter/value?key=" + std::string{key});
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::string m_agent_binary;
|
||||
std::vector<Agent> m_agents;
|
||||
Void::Net::HttpClient m_client;
|
||||
};
|
||||
|
||||
/// Single-client linearizable reference: sequential operations, one
|
||||
/// leader at a time.
|
||||
class Driver
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Driver(Harness& harness) : m_harness(harness) {}
|
||||
|
||||
[[nodiscard]] bool elect(std::size_t candidate)
|
||||
{
|
||||
const auto candidate_state = m_harness.state(candidate);
|
||||
if (!candidate_state) {
|
||||
return false;
|
||||
}
|
||||
m_term = std::max(m_term, candidate_state->term) + 1;
|
||||
std::size_t votes = 0;
|
||||
for (std::size_t i = 0; i < m_harness.size(); ++i) {
|
||||
if (!m_harness.alive(i)) {
|
||||
continue;
|
||||
}
|
||||
if (m_harness.vote(i, m_term,
|
||||
"node-" + std::to_string(candidate),
|
||||
candidate_state->last_index,
|
||||
candidate_state->last_term) == 200) {
|
||||
++votes;
|
||||
}
|
||||
}
|
||||
if (votes * 2 <= m_harness.size()) {
|
||||
return false;
|
||||
}
|
||||
m_leader = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
enum class Write { Applied, NoQuorum, NotLeader };
|
||||
|
||||
[[nodiscard]] Write propose(std::string key, std::string value)
|
||||
{
|
||||
if (!m_leader.has_value() || !m_harness.alive(*m_leader)) {
|
||||
return Write::NotLeader;
|
||||
}
|
||||
const LogEntry entry{
|
||||
.term = m_term,
|
||||
.index = m_commit + 1,
|
||||
.key = std::move(key),
|
||||
.value = std::move(value)};
|
||||
const std::string line =
|
||||
std::to_string(entry.term) + "," +
|
||||
std::to_string(entry.index) + "," + entry.key + "," +
|
||||
entry.value + "\n";
|
||||
auto line_of = [](const LogEntry& e) {
|
||||
return std::to_string(e.term) + "," +
|
||||
std::to_string(e.index) + "," + e.key + "," + e.value +
|
||||
"\n";
|
||||
};
|
||||
std::size_t acks = 0;
|
||||
for (std::size_t i = 0; i < m_harness.size(); ++i) {
|
||||
if (!m_harness.alive(i)) {
|
||||
continue;
|
||||
}
|
||||
int status = m_harness.append(i, m_term, m_commit, m_prev_term,
|
||||
m_commit, line);
|
||||
if (status == 409) {
|
||||
// The follower is behind: back off to its last entry and
|
||||
// replay everything it is missing (Raft catch-up).
|
||||
const auto peer = m_harness.state(i);
|
||||
if (peer) {
|
||||
std::string catchup;
|
||||
for (const auto& acked : m_acknowledged) {
|
||||
if (acked.index > peer->last_index) {
|
||||
catchup += line_of(acked);
|
||||
}
|
||||
}
|
||||
catchup += line;
|
||||
status = m_harness.append(
|
||||
i, m_term, peer->last_index, peer->last_term,
|
||||
m_commit, catchup);
|
||||
}
|
||||
}
|
||||
if (status == 200) {
|
||||
++acks;
|
||||
}
|
||||
}
|
||||
if (acks * 2 <= m_harness.size()) {
|
||||
return Write::NoQuorum;
|
||||
}
|
||||
// Majority acknowledged: publish the commit index so every
|
||||
// reachable voter applies the entry (AppendEntries carries it).
|
||||
m_commit = entry.index;
|
||||
for (std::size_t i = 0; i < m_harness.size(); ++i) {
|
||||
if (!m_harness.alive(i)) {
|
||||
continue;
|
||||
}
|
||||
(void)m_harness.append(i, m_term, entry.index, entry.term,
|
||||
m_commit, {});
|
||||
}
|
||||
m_prev_term = entry.term;
|
||||
m_acknowledged.push_back(entry);
|
||||
return Write::Applied;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string> read(std::string_view key)
|
||||
{
|
||||
if (!m_leader.has_value() || !m_harness.alive(*m_leader)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
// Confirm leadership in this term with a majority heartbeat.
|
||||
std::size_t reachable = 0;
|
||||
for (std::size_t i = 0; i < m_harness.size(); ++i) {
|
||||
if (!m_harness.alive(i)) {
|
||||
continue;
|
||||
}
|
||||
const auto peer = m_harness.state(i);
|
||||
if (!peer || peer->term > m_term) {
|
||||
return std::nullopt;
|
||||
}
|
||||
++reachable;
|
||||
}
|
||||
if (reachable * 2 <= m_harness.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return m_harness.value(*m_leader, key);
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::vector<LogEntry>& acknowledged() const
|
||||
{
|
||||
return m_acknowledged;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
latest_acknowledged(std::string_view key) const
|
||||
{
|
||||
for (auto it = m_acknowledged.rbegin();
|
||||
it != m_acknowledged.rend(); ++it) {
|
||||
if (it->key == key) {
|
||||
return it->value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Harness& m_harness;
|
||||
std::uint64_t m_term{0};
|
||||
std::uint64_t m_commit{0};
|
||||
std::uint64_t m_prev_term{0};
|
||||
std::optional<std::size_t> m_leader;
|
||||
std::vector<LogEntry> m_acknowledged;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
if (argc < 2) {
|
||||
std::fprintf(stderr,
|
||||
"usage: multi_process_test <voter-agent-binary>\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
Harness harness{argv[1], 3};
|
||||
for (std::size_t i = 0; i < harness.size(); ++i) {
|
||||
assert(harness.launch(i));
|
||||
}
|
||||
Driver driver{harness};
|
||||
|
||||
// Majority election and a durable first write.
|
||||
assert(driver.elect(0));
|
||||
assert(driver.propose("k", "v1") == Driver::Write::Applied);
|
||||
assert(driver.read("k") == std::optional<std::string>{"v1"});
|
||||
|
||||
// One process dies: the write is still durably acknowledged.
|
||||
harness.kill(2);
|
||||
assert(driver.propose("k", "v2") == Driver::Write::Applied);
|
||||
assert(driver.read("k") == std::optional<std::string>{"v2"});
|
||||
|
||||
// A second death loses quorum: no durable reply, no readable value.
|
||||
harness.kill(1);
|
||||
assert(driver.propose("k", "v3") == Driver::Write::NoQuorum);
|
||||
assert(!driver.read("k").has_value());
|
||||
|
||||
// Restart the killed processes: durable state comes back from disk.
|
||||
assert(harness.launch(1));
|
||||
assert(harness.launch(2));
|
||||
// The recovered majority still holds every acknowledged write.
|
||||
assert(driver.elect(1));
|
||||
const auto recovered = driver.read("k");
|
||||
assert(recovered.has_value());
|
||||
// Never the unacknowledged write.
|
||||
assert(*recovered != "v3");
|
||||
assert(*recovered == driver.latest_acknowledged("k"));
|
||||
|
||||
// The recovered cluster keeps serving new writes.
|
||||
assert(driver.propose("k", "v4") == Driver::Write::Applied);
|
||||
assert(driver.read("k") == std::optional<std::string>{"v4"});
|
||||
assert(driver.propose("other", "x") == Driver::Write::Applied);
|
||||
assert(driver.read("other") == std::optional<std::string>{"x"});
|
||||
|
||||
// Every acknowledged entry is present on the restarted majority.
|
||||
for (std::size_t i = 0; i < harness.size(); ++i) {
|
||||
if (!harness.alive(i)) {
|
||||
continue;
|
||||
}
|
||||
const auto state = harness.state(i);
|
||||
assert(state.has_value());
|
||||
assert(state->last_index >= driver.acknowledged().back().index);
|
||||
}
|
||||
|
||||
std::puts("distributed multi-process acceptance ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "distributed_host/operations.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
ClusterIdentity identity()
|
||||
{
|
||||
return ClusterIdentity{"prod-cluster", {"a", "b", "c"}};
|
||||
}
|
||||
|
||||
void backup_and_restore_retains_identity_and_state()
|
||||
{
|
||||
ReplicatedKvCluster source{{"a", "b", "c"}};
|
||||
assert(source.elect("a").has_value());
|
||||
assert(source.propose("a", "x", std::string{"1"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
assert(source.propose("a", "y", std::string{"2"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
assert(source.propose("a", "z", std::string{"3"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
assert(source.propose("a", "y", std::nullopt).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
auto backup = capture_backup(source, "a", identity());
|
||||
assert(backup.has_value());
|
||||
assert(backup->identity == identity());
|
||||
assert(backup->commit_index == source.committed_index());
|
||||
assert(backup->state.size() == 2);
|
||||
assert(!backup->state.contains("y"));
|
||||
|
||||
// Restore rehearsal into a separately started cluster.
|
||||
ReplicatedKvCluster target{{"a", "b", "c"}};
|
||||
assert(target.elect("a").has_value());
|
||||
auto restored = restore_backup(target, "a", *backup, identity());
|
||||
assert(restored.has_value());
|
||||
assert(*restored == 2);
|
||||
|
||||
auto x = target.quorum_read("a", "x");
|
||||
auto z = target.quorum_read("a", "z");
|
||||
auto y = target.quorum_read("a", "y");
|
||||
assert(x.has_value() && x->has_value() && **x == "1");
|
||||
assert(z.has_value() && z->has_value() && **z == "3");
|
||||
assert(y.has_value() && !y->has_value());
|
||||
|
||||
// A different cluster identity is refused, so histories cannot merge.
|
||||
ClusterIdentity staging{"staging-cluster", {"a", "b", "c"}};
|
||||
assert(!restore_backup(target, "a", *backup, staging).has_value());
|
||||
ClusterIdentity fewer_voters{"prod-cluster", {"a", "b"}};
|
||||
assert(!restore_backup(target, "a", *backup, fewer_voters).has_value());
|
||||
}
|
||||
|
||||
void backup_without_quorum_fails()
|
||||
{
|
||||
ReplicatedKvCluster source{{"a", "b", "c"}};
|
||||
assert(source.elect("a").has_value());
|
||||
source.set_partition("b", 1);
|
||||
source.set_partition("c", 1);
|
||||
auto backup = capture_backup(source, "a", identity());
|
||||
assert(!backup.has_value());
|
||||
}
|
||||
|
||||
void trust_rotation_overlaps_then_revokes()
|
||||
{
|
||||
TrustStore trust{{"old-fp"}};
|
||||
assert(trust.trusted("old-fp"));
|
||||
assert(!trust.trusted("new-fp"));
|
||||
assert(!trust.trusted(""));
|
||||
|
||||
// Empty rotation is rejected: verification is never disabled.
|
||||
assert(!trust.begin_rotation({}).has_value());
|
||||
|
||||
auto generation = trust.begin_rotation({"new-fp"});
|
||||
assert(generation.has_value());
|
||||
// Overlap: both generations remain trusted while connections drain.
|
||||
assert(trust.trusted("old-fp"));
|
||||
assert(trust.trusted("new-fp"));
|
||||
assert(trust.active_generations() == 2);
|
||||
|
||||
assert(trust.complete_rotation(*generation).has_value());
|
||||
assert(!trust.trusted("old-fp"));
|
||||
assert(trust.trusted("new-fp"));
|
||||
assert(trust.active_generations() == 1);
|
||||
|
||||
assert(!trust.complete_rotation(99).has_value());
|
||||
|
||||
// An empty store trusts nothing.
|
||||
TrustStore empty;
|
||||
assert(!empty.trusted("anything"));
|
||||
}
|
||||
|
||||
void mixed_version_rollout_readers_first()
|
||||
{
|
||||
RolloutGate gate{{"a", "b", "c"},
|
||||
VersionPolicy{.format_version = 2, .min_reader = 1}};
|
||||
assert(!gate.all_advertised());
|
||||
|
||||
assert(gate.report_version("a", 2).has_value());
|
||||
assert(gate.report_version("b", 1).has_value());
|
||||
assert(gate.report_version("c", 1).has_value());
|
||||
|
||||
// Old readers can still read the durable format.
|
||||
assert(gate.admit_read("b").has_value());
|
||||
// But new commands wait for every voter.
|
||||
assert(!gate.admit_new_command("a").has_value());
|
||||
assert(!gate.all_advertised());
|
||||
|
||||
assert(gate.report_version("b", 2).has_value());
|
||||
assert(gate.report_version("c", 2).has_value());
|
||||
assert(gate.admit_new_command("a").has_value());
|
||||
assert(gate.all_advertised());
|
||||
|
||||
// Unknown voters are never assumed current.
|
||||
assert(!gate.report_version("d", 2).has_value());
|
||||
assert(!gate.admit_read("d").has_value());
|
||||
}
|
||||
|
||||
void reader_floor_is_enforced()
|
||||
{
|
||||
RolloutGate gate{{"a"}, VersionPolicy{.format_version = 2,
|
||||
.min_reader = 2}};
|
||||
assert(gate.report_version("a", 1).has_value());
|
||||
assert(!gate.admit_read("a").has_value());
|
||||
assert(gate.report_version("a", 2).has_value());
|
||||
assert(gate.admit_read("a").has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
backup_and_restore_retains_identity_and_state();
|
||||
backup_without_quorum_fails();
|
||||
trust_rotation_overlaps_then_revokes();
|
||||
mixed_version_rollout_readers_first();
|
||||
reader_floor_is_enforced();
|
||||
std::puts("distributed operations ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
#include "distributed_host/range_placement.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
RangeDirectory directory()
|
||||
{
|
||||
RangeDirectory dir{{"a", "b", "c"}};
|
||||
assert(dir.assign(KeyRange{"a", "m"}, "a").has_value());
|
||||
assert(dir.assign(KeyRange{"m", "z"}, "b").has_value());
|
||||
return dir;
|
||||
}
|
||||
|
||||
void ranges_do_not_overlap_and_must_have_known_owners()
|
||||
{
|
||||
auto dir = directory();
|
||||
assert(*dir.owner_of("apple") == "a");
|
||||
assert(*dir.owner_of("monkey") == "b");
|
||||
assert(!dir.owner_of("zebra").has_value()); // outside [a, z)
|
||||
|
||||
assert(!dir.assign(KeyRange{"l", "n"}, "c").has_value());
|
||||
assert(!dir.assign(KeyRange{"n", "p"}, "unknown").has_value());
|
||||
assert(!dir.assign(KeyRange{"p", "p"}, "a").has_value());
|
||||
assert(dir.ranges().size() == 2);
|
||||
}
|
||||
|
||||
void move_freezes_writes_until_completion()
|
||||
{
|
||||
auto dir = directory();
|
||||
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
|
||||
assert(move.has_value());
|
||||
|
||||
// Writes in the moving range are rejected; reads stay with the source.
|
||||
assert(!dir.admit_write("apple").has_value());
|
||||
assert(dir.admit_read("apple").has_value());
|
||||
assert(*dir.owner_of("apple") == "a");
|
||||
// Other ranges are unaffected.
|
||||
assert(dir.admit_write("monkey").has_value());
|
||||
|
||||
// Completion requires a verified copy.
|
||||
assert(!dir.complete(*move).has_value());
|
||||
assert(!dir.verify(*move, 5).has_value()); // nothing transferred
|
||||
assert(dir.transfer(*move, 3).has_value());
|
||||
assert(!dir.verify(*move, 2).has_value()); // count mismatch
|
||||
assert(dir.verify(*move, 3).has_value());
|
||||
assert(dir.complete(*move).has_value());
|
||||
|
||||
assert(*dir.owner_of("apple") == "c");
|
||||
assert(dir.admit_write("apple").has_value());
|
||||
const auto record = dir.move(*move);
|
||||
assert(record.has_value());
|
||||
assert(record->phase == MovePhase::Completed);
|
||||
assert(record->transferred == 3);
|
||||
}
|
||||
|
||||
void crash_before_verification_rolls_back()
|
||||
{
|
||||
auto dir = directory();
|
||||
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
|
||||
assert(move.has_value());
|
||||
assert(dir.transfer(*move, 2).has_value());
|
||||
|
||||
// Simulated restart of the move owner: no verified copy exists.
|
||||
auto recovered = dir.recover(*move);
|
||||
assert(recovered.has_value());
|
||||
assert(*recovered == RangeDirectory::Recovery::RolledBack);
|
||||
assert(*dir.owner_of("apple") == "a");
|
||||
assert(dir.admit_write("apple").has_value());
|
||||
assert(dir.move(*move)->phase == MovePhase::Aborted);
|
||||
}
|
||||
|
||||
void crash_after_verification_rolls_forward()
|
||||
{
|
||||
auto dir = directory();
|
||||
auto move = dir.begin_move(KeyRange{"m", "z"}, "a");
|
||||
assert(move.has_value());
|
||||
assert(dir.transfer(*move, 4).has_value());
|
||||
assert(dir.verify(*move, 4).has_value());
|
||||
|
||||
auto recovered = dir.recover(*move);
|
||||
assert(recovered.has_value());
|
||||
assert(*recovered == RangeDirectory::Recovery::RolledForward);
|
||||
assert(*dir.owner_of("monkey") == "a");
|
||||
assert(dir.admit_write("monkey").has_value());
|
||||
assert(dir.move(*move)->phase == MovePhase::Completed);
|
||||
}
|
||||
|
||||
void explicit_abort_restores_the_source()
|
||||
{
|
||||
auto dir = directory();
|
||||
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
|
||||
assert(move.has_value());
|
||||
dir.abort(*move, "operator cancelled");
|
||||
assert(*dir.owner_of("apple") == "a");
|
||||
assert(dir.admit_write("apple").has_value());
|
||||
assert(dir.move(*move)->note == "operator cancelled");
|
||||
// A completed move cannot be aborted.
|
||||
auto second = dir.begin_move(KeyRange{"a", "m"}, "c");
|
||||
assert(second.has_value());
|
||||
assert(dir.transfer(*second, 1).has_value());
|
||||
assert(dir.verify(*second, 1).has_value());
|
||||
assert(dir.complete(*second).has_value());
|
||||
dir.abort(*second, "too late");
|
||||
assert(*dir.owner_of("apple") == "c");
|
||||
}
|
||||
|
||||
void one_active_move_per_range()
|
||||
{
|
||||
auto dir = directory();
|
||||
assert(dir.begin_move(KeyRange{"a", "m"}, "c").has_value());
|
||||
auto second = dir.begin_move(KeyRange{"a", "m"}, "b");
|
||||
assert(!second.has_value());
|
||||
assert(second.error().kind() == Void::Result::ErrorKind::conflict);
|
||||
// Moving to the current owner is refused.
|
||||
auto same = dir.begin_move(KeyRange{"m", "z"}, "b");
|
||||
assert(!same.has_value());
|
||||
}
|
||||
|
||||
void directory_survives_a_replicated_restart()
|
||||
{
|
||||
ReplicatedKvCluster cluster{{"a", "b", "c"}};
|
||||
assert(cluster.elect("a").has_value());
|
||||
|
||||
auto original = directory();
|
||||
assert(original.persist(cluster, "a").has_value());
|
||||
|
||||
// A new directory instance loads the replicated ownership map.
|
||||
RangeDirectory restored{{"a", "b", "c"}};
|
||||
assert(restored.load(cluster, "a").has_value());
|
||||
assert(restored.ranges().size() == 2);
|
||||
assert(*restored.owner_of("apple") == "a");
|
||||
assert(*restored.owner_of("monkey") == "b");
|
||||
|
||||
// A directory whose voters do not include the stored owners is
|
||||
// rejected rather than partially installed.
|
||||
RangeDirectory narrower{{"a"}};
|
||||
assert(!narrower.load(cluster, "a").has_value());
|
||||
assert(narrower.ranges().empty());
|
||||
|
||||
// Corrupt persisted content is rejected.
|
||||
assert(cluster.propose("a", std::string{RangeDirectory::default_key},
|
||||
std::string{"broken-record\n"})
|
||||
.outcome == KvWriteOutcome::Applied);
|
||||
RangeDirectory corrupt_dir{{"a", "b", "c"}};
|
||||
assert(!corrupt_dir.load(cluster, "a").has_value());
|
||||
assert(corrupt_dir.ranges().empty());
|
||||
|
||||
// Persisting without quorum is not durable.
|
||||
cluster.set_partition("b", 1);
|
||||
cluster.set_partition("c", 1);
|
||||
assert(!original.persist(cluster, "a").has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
ranges_do_not_overlap_and_must_have_known_owners();
|
||||
move_freezes_writes_until_completion();
|
||||
crash_before_verification_rolls_back();
|
||||
crash_after_verification_rolls_forward();
|
||||
explicit_abort_restores_the_source();
|
||||
one_active_move_per_range();
|
||||
directory_survives_a_replicated_restart();
|
||||
std::puts("distributed range placement ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
#include "distributed_host/replicated_kv.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
ReplicatedKvCluster cluster()
|
||||
{
|
||||
return ReplicatedKvCluster{{"a", "b", "c"}};
|
||||
}
|
||||
|
||||
void leader_commits_with_a_majority()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
const auto reply = kv.propose("a", "key", std::string{"value"});
|
||||
assert(reply.outcome == KvWriteOutcome::Applied);
|
||||
assert(reply.index == 1);
|
||||
assert(kv.committed_index() == 1);
|
||||
|
||||
auto read = kv.quorum_read("a", "key");
|
||||
assert(read.has_value());
|
||||
assert(read->has_value());
|
||||
assert(**read == "value");
|
||||
|
||||
// Followers applied the committed entry too.
|
||||
assert(kv.snapshot("b")->kv.at("key") == "value");
|
||||
assert(kv.snapshot("c")->kv.at("key") == "value");
|
||||
assert(kv.snapshot("b")->applied_index ==
|
||||
kv.snapshot("b")->commit_index);
|
||||
}
|
||||
|
||||
void minority_leader_cannot_commit_or_read()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
kv.set_partition("b", 1);
|
||||
kv.set_partition("c", 1);
|
||||
|
||||
const auto reply = kv.propose("a", "key", std::string{"lost"});
|
||||
assert(reply.outcome == KvWriteOutcome::NoQuorum);
|
||||
// Never applied without a majority.
|
||||
assert(kv.snapshot("a")->kv.empty());
|
||||
|
||||
auto read = kv.quorum_read("a", "key");
|
||||
assert(!read.has_value());
|
||||
assert(read.error().kind() == Void::Result::ErrorKind::overloaded);
|
||||
}
|
||||
|
||||
void new_majority_elects_and_preserves_committed_history()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
assert(kv.propose("a", "key", std::string{"one"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
// Isolate the old leader; the other two form a majority.
|
||||
kv.set_partition("a", 1);
|
||||
assert(kv.elect("b").has_value());
|
||||
assert(kv.propose("b", "key", std::string{"two"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
// Heal: the next heartbeat from the new leader delivers the committed
|
||||
// entry and term to the stale node, which steps down.
|
||||
kv.set_partition("a", 0);
|
||||
assert(kv.heartbeat("b").has_value());
|
||||
assert(kv.snapshot("a")->role == Role::Follower);
|
||||
assert(kv.snapshot("a")->kv.at("key") == "two");
|
||||
|
||||
const auto stale = kv.propose("a", "key", std::string{"stale"});
|
||||
assert(stale.outcome == KvWriteOutcome::NotLeader);
|
||||
|
||||
auto read = kv.quorum_read("b", "key");
|
||||
assert(read.has_value() && read->has_value());
|
||||
assert(**read == "two");
|
||||
// Committed history was never lost on the old leader either.
|
||||
assert(kv.snapshot("a")->kv.at("key") == "two");
|
||||
}
|
||||
|
||||
void uncommitted_entry_is_overwritten_and_never_applied()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
kv.set_partition("b", 1);
|
||||
kv.set_partition("c", 1);
|
||||
|
||||
const auto ghost = kv.propose("a", "key", std::string{"ghost"});
|
||||
assert(ghost.outcome == KvWriteOutcome::NoQuorum);
|
||||
assert(!kv.snapshot("a")->kv.contains("key"));
|
||||
const std::size_t ghost_log = kv.snapshot("a")->log_size;
|
||||
|
||||
kv.set_partition("b", 0);
|
||||
kv.set_partition("c", 0);
|
||||
assert(kv.elect("b").has_value());
|
||||
assert(kv.propose("b", "key", std::string{"real"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
// The stale suffix was truncated and replaced, never applied.
|
||||
const auto old = kv.snapshot("a");
|
||||
assert(old->log_size <= ghost_log);
|
||||
assert(old->kv.at("key") == "real");
|
||||
auto read = kv.quorum_read("b", "key");
|
||||
assert(read.has_value() && read->has_value() && **read == "real");
|
||||
}
|
||||
|
||||
void crash_and_restart_preserve_committed_state()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
assert(kv.propose("a", "x", std::string{"1"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
assert(kv.propose("a", "y", std::string{"2"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
for (const auto& id : kv.voters()) {
|
||||
kv.crash(id);
|
||||
}
|
||||
for (const auto& id : kv.voters()) {
|
||||
kv.restart(id);
|
||||
}
|
||||
assert(kv.elect("c").has_value());
|
||||
auto x = kv.quorum_read("c", "x");
|
||||
auto y = kv.quorum_read("c", "y");
|
||||
assert(x.has_value() && x->has_value() && **x == "1");
|
||||
assert(y.has_value() && y->has_value() && **y == "2");
|
||||
}
|
||||
|
||||
void follower_cannot_serve_consistent_read()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
auto read = kv.quorum_read("b", "key");
|
||||
assert(!read.has_value());
|
||||
assert(read.error().kind() == Void::Result::ErrorKind::conflict);
|
||||
}
|
||||
|
||||
void election_without_majority_or_voter_fails()
|
||||
{
|
||||
auto kv = cluster();
|
||||
kv.set_partition("b", 1);
|
||||
kv.set_partition("c", 1);
|
||||
assert(!kv.elect("a").has_value());
|
||||
|
||||
auto unknown = kv.elect("nope");
|
||||
assert(!unknown.has_value());
|
||||
assert(unknown.error().kind() == Void::Result::ErrorKind::not_found);
|
||||
}
|
||||
|
||||
void write_requires_a_leader() {
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
assert(kv.propose("b", "key", std::string{"v"}).outcome ==
|
||||
KvWriteOutcome::NotLeader);
|
||||
assert(kv.propose("missing", "key", std::string{"v"}).outcome ==
|
||||
KvWriteOutcome::NodeDown);
|
||||
}
|
||||
|
||||
void deletes_replicate_as_tombstones()
|
||||
{
|
||||
auto kv = cluster();
|
||||
assert(kv.elect("a").has_value());
|
||||
assert(kv.propose("a", "key", std::string{"value"}).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
assert(kv.propose("a", "key", std::nullopt).outcome ==
|
||||
KvWriteOutcome::Applied);
|
||||
|
||||
auto read = kv.quorum_read("a", "key");
|
||||
assert(read.has_value());
|
||||
assert(!read->has_value());
|
||||
assert(!kv.snapshot("b")->kv.contains("key"));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
leader_commits_with_a_majority();
|
||||
minority_leader_cannot_commit_or_read();
|
||||
new_majority_elects_and_preserves_committed_history();
|
||||
uncommitted_entry_is_overwritten_and_never_applied();
|
||||
crash_and_restart_preserve_committed_state();
|
||||
follower_cannot_serve_consistent_read();
|
||||
election_without_majority_or_voter_fails();
|
||||
write_requires_a_leader();
|
||||
deletes_replicate_as_tombstones();
|
||||
std::puts("distributed replicated kv ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
#include "distributed_host/replicated_queue.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
struct World {
|
||||
ReplicatedKvCluster cluster{{"a", "b", "c"}};
|
||||
QueueConfig config{.max_attempts = 2, .max_jobs = 8};
|
||||
|
||||
World()
|
||||
{
|
||||
assert(cluster.elect("a").has_value());
|
||||
}
|
||||
|
||||
ReplicatedQueue queue()
|
||||
{
|
||||
return ReplicatedQueue{cluster, "a", config};
|
||||
}
|
||||
};
|
||||
|
||||
void publish_claim_ack_dispatches_one_effect()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
auto id = queue.publish("payload", "job-1");
|
||||
assert(id.has_value());
|
||||
|
||||
// Idempotent publish: the same key never creates a second job.
|
||||
auto duplicate = queue.publish("different", "job-1");
|
||||
assert(duplicate.has_value());
|
||||
assert(*duplicate == *id);
|
||||
|
||||
auto claimed = queue.claim("worker-1");
|
||||
assert(claimed.has_value() && claimed->has_value());
|
||||
assert((*claimed)->id == *id);
|
||||
assert((*claimed)->state == JobState::InFlight);
|
||||
assert((*claimed)->consumer == "worker-1");
|
||||
assert((*claimed)->attempts == 1);
|
||||
|
||||
// No other pending job.
|
||||
auto none = queue.claim("worker-1");
|
||||
assert(none.has_value() && !none->has_value());
|
||||
|
||||
assert(queue.ack("worker-1", *id).has_value());
|
||||
const auto done = queue.status(*id);
|
||||
assert(done.has_value());
|
||||
assert(done->state == JobState::Done);
|
||||
assert(done->outbox_pending);
|
||||
|
||||
// Duplicate ack: the inbox already recorded it, no second outbox row.
|
||||
assert(queue.ack("worker-1", *id).has_value());
|
||||
|
||||
int delivered = 0;
|
||||
auto dispatched = queue.dispatch_outbox([&](const QueueJob& job) {
|
||||
++delivered;
|
||||
assert(job.id == *id);
|
||||
assert(job.payload == "payload");
|
||||
});
|
||||
assert(dispatched.has_value());
|
||||
assert(*dispatched == 1);
|
||||
assert(delivered == 1);
|
||||
|
||||
// The outbox entry was marked delivered.
|
||||
auto redispatch = queue.dispatch_outbox(
|
||||
[&](const QueueJob&) { ++delivered; });
|
||||
assert(redispatch.has_value());
|
||||
assert(*redispatch == 0);
|
||||
assert(delivered == 1);
|
||||
}
|
||||
|
||||
void retries_then_dead_letters()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
auto id = queue.publish("poison", "retry-1");
|
||||
assert(id.has_value());
|
||||
|
||||
assert(queue.claim("w").has_value());
|
||||
auto retried = queue.nack("w", *id, "boom");
|
||||
assert(retried.has_value());
|
||||
assert(retried->state == JobState::Pending);
|
||||
assert(retried->attempts == 1);
|
||||
|
||||
assert(queue.claim("w").has_value());
|
||||
auto dead = queue.nack("w", *id, "boom again");
|
||||
assert(dead.has_value());
|
||||
assert(dead->state == JobState::Dead);
|
||||
assert(dead->attempts == 2);
|
||||
assert(dead->reason == "boom again");
|
||||
|
||||
auto letters = queue.dead_letters();
|
||||
assert(letters.has_value());
|
||||
assert(letters->size() == 1);
|
||||
assert((*letters)[0].id == *id);
|
||||
|
||||
// Dead jobs are no longer claimable.
|
||||
auto none = queue.claim("w");
|
||||
assert(none.has_value() && !none->has_value());
|
||||
}
|
||||
|
||||
void crashed_consumer_is_recovered()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
auto id = queue.publish("work", "recover-1");
|
||||
assert(id.has_value());
|
||||
|
||||
auto claimed = queue.claim("worker-1");
|
||||
assert(claimed.has_value() && claimed->has_value());
|
||||
|
||||
auto recovered = queue.recover_consumer("worker-1");
|
||||
assert(recovered.has_value());
|
||||
assert(*recovered == 1);
|
||||
// Recovery is idempotent: nothing is in flight any more.
|
||||
assert(*queue.recover_consumer("worker-1") == 0);
|
||||
|
||||
auto reclaimed = queue.claim("worker-2");
|
||||
assert(reclaimed.has_value() && reclaimed->has_value());
|
||||
assert((*reclaimed)->consumer == "worker-2");
|
||||
assert((*reclaimed)->attempts == 2);
|
||||
}
|
||||
|
||||
void final_attempt_recovery_dead_letters()
|
||||
{
|
||||
World world;
|
||||
world.config.max_attempts = 1;
|
||||
auto queue = world.queue();
|
||||
assert(queue.publish("work", "final-1").has_value());
|
||||
assert(queue.claim("worker-1").has_value());
|
||||
|
||||
auto recovered = queue.recover_consumer("worker-1");
|
||||
assert(recovered.has_value());
|
||||
assert(*recovered == 1);
|
||||
const auto job = queue.status("final-1");
|
||||
assert(job.has_value());
|
||||
assert(job->state == JobState::Dead);
|
||||
}
|
||||
|
||||
void no_quorum_write_is_never_durable()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
world.cluster.set_partition("b", 1);
|
||||
world.cluster.set_partition("c", 1);
|
||||
|
||||
auto published = queue.publish("lost", "loss-1");
|
||||
assert(!published.has_value());
|
||||
|
||||
world.cluster.set_partition("b", 0);
|
||||
world.cluster.set_partition("c", 0);
|
||||
// The failed publish was never applied.
|
||||
auto status = queue.status("loss-1");
|
||||
assert(!status.has_value());
|
||||
}
|
||||
|
||||
void ack_from_the_wrong_consumer_is_rejected()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
assert(queue.publish("work", "owner-1").has_value());
|
||||
assert(queue.claim("worker-1").has_value());
|
||||
|
||||
auto wrong = queue.ack("worker-2", "owner-1");
|
||||
assert(!wrong.has_value());
|
||||
assert(wrong.error().kind() == Void::Result::ErrorKind::conflict);
|
||||
assert(queue.ack("worker-1", "owner-1").has_value());
|
||||
}
|
||||
|
||||
void leader_change_requires_endpoint_update()
|
||||
{
|
||||
World world;
|
||||
auto queue = world.queue();
|
||||
assert(queue.publish("work", "move-1").has_value());
|
||||
|
||||
world.cluster.set_partition("a", 1);
|
||||
assert(world.cluster.elect("b").has_value());
|
||||
// The queue still points at the old leader: explicit failure, not a
|
||||
// silent write to a minority.
|
||||
auto stale = queue.publish("work", "move-2");
|
||||
assert(!stale.has_value());
|
||||
|
||||
queue.set_leader("b");
|
||||
auto moved = queue.publish("work", "move-2");
|
||||
assert(moved.has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
publish_claim_ack_dispatches_one_effect();
|
||||
retries_then_dead_letters();
|
||||
crashed_consumer_is_recovered();
|
||||
final_attempt_recovery_dead_letters();
|
||||
no_quorum_write_is_never_durable();
|
||||
ack_from_the_wrong_consumer_is_rejected();
|
||||
leader_change_requires_endpoint_update();
|
||||
std::puts("distributed replicated queue ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
#include "distributed_host/single_node.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace DistributedHost;
|
||||
|
||||
SingleNodeConfig config()
|
||||
{
|
||||
SingleNodeConfig cfg;
|
||||
cfg.peer_address = "127.0.0.1:0";
|
||||
cfg.peer_token = "peer-secret";
|
||||
cfg.shutdown_grace = std::chrono::seconds{2};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Void::Net::Header auth()
|
||||
{
|
||||
return Void::Net::Header{"authorization", "Bearer peer-secret"};
|
||||
}
|
||||
|
||||
void config_fails_closed_without_a_token()
|
||||
{
|
||||
SingleNodeConfig no_token;
|
||||
no_token.peer_token.clear();
|
||||
assert(!SingleNodeHost::create(no_token).has_value());
|
||||
|
||||
SingleNodeConfig bad_address;
|
||||
bad_address.peer_token = "x";
|
||||
bad_address.peer_address = "not-an-address";
|
||||
assert(!SingleNodeHost::create(bad_address).has_value());
|
||||
|
||||
SingleNodeConfig zero_entries = config();
|
||||
zero_entries.max_log_entries = 0;
|
||||
assert(!SingleNodeHost::create(zero_entries).has_value());
|
||||
}
|
||||
|
||||
void peer_fixture_requires_authentication_and_serves_bounded_state()
|
||||
{
|
||||
auto host = SingleNodeHost::create(config());
|
||||
assert(host.has_value());
|
||||
// Construction opens no listener.
|
||||
assert(host->peer_port() == 0);
|
||||
assert(host->history().empty());
|
||||
|
||||
assert(host->start().has_value());
|
||||
assert(host->health().readiness == Readiness::WriteReady);
|
||||
const std::uint16_t port = host->peer_port();
|
||||
assert(port != 0);
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(port);
|
||||
|
||||
// Both peer endpoints reject missing and wrong credentials.
|
||||
auto anonymous_health = client.get(base + "/peer/health");
|
||||
assert(anonymous_health.has_value());
|
||||
assert(anonymous_health->status == 401);
|
||||
auto wrong = client.get(
|
||||
base + "/peer/health",
|
||||
{Void::Net::Header{"authorization", "Bearer wrong"}});
|
||||
assert(wrong.has_value());
|
||||
assert(wrong->status == 401);
|
||||
|
||||
auto health = client.get(base + "/peer/health", {auth()});
|
||||
assert(health.has_value());
|
||||
assert(health->status == 200);
|
||||
assert(health->body.find("role=leader") != std::string::npos);
|
||||
assert(health->body.find("entries=0") != std::string::npos);
|
||||
// The credential never appears in a response.
|
||||
assert(health->body.find("peer-secret") == std::string::npos);
|
||||
|
||||
auto append = [&](std::string body) {
|
||||
Void::Net::Request request;
|
||||
request.method = Void::Net::Method::Post;
|
||||
request.url = base + "/peer/append";
|
||||
request.body = std::move(body);
|
||||
request.headers.push_back(auth());
|
||||
return client.send(request);
|
||||
};
|
||||
|
||||
auto anonymous = client.send(Void::Net::Request{
|
||||
.method = Void::Net::Method::Post,
|
||||
.url = base + "/peer/append",
|
||||
.body = "entry"});
|
||||
assert(anonymous.has_value());
|
||||
assert(anonymous->status == 401);
|
||||
|
||||
auto first = append("entry-one");
|
||||
assert(first.has_value());
|
||||
assert(first->status == 200);
|
||||
assert(first->body == "index=1");
|
||||
|
||||
auto second = append("entry-two");
|
||||
assert(second.has_value());
|
||||
assert(second->body == "index=2");
|
||||
|
||||
auto after = client.get(base + "/peer/health", {auth()});
|
||||
assert(after.has_value());
|
||||
assert(after->body.find("entries=2") != std::string::npos);
|
||||
|
||||
// Auth is required for the mutation even with a valid-looking path.
|
||||
auto wrong_method = client.get(base + "/peer/append", {auth()});
|
||||
assert(wrong_method.has_value());
|
||||
assert(wrong_method->status == 405);
|
||||
|
||||
host->stop();
|
||||
assert(host->peer_port() == 0);
|
||||
const auto closed = client.get(base + "/peer/health", {auth()});
|
||||
assert(!closed.has_value());
|
||||
|
||||
// Idempotent.
|
||||
host->stop();
|
||||
}
|
||||
|
||||
void bind_failure_rolls_back_in_reverse_order()
|
||||
{
|
||||
// Occupy a loopback port with a raw listener.
|
||||
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
assert(fd >= 0);
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0;
|
||||
assert(::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0);
|
||||
assert(::listen(fd, 4) == 0);
|
||||
socklen_t length = sizeof(addr);
|
||||
assert(::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &length) ==
|
||||
0);
|
||||
const std::uint16_t busy_port = ntohs(addr.sin_port);
|
||||
|
||||
SingleNodeConfig cfg = config();
|
||||
cfg.peer_address = "127.0.0.1:" + std::to_string(busy_port);
|
||||
auto host = SingleNodeHost::create(cfg);
|
||||
assert(host.has_value());
|
||||
|
||||
auto started = host->start();
|
||||
assert(!started.has_value());
|
||||
assert(host->health().readiness == Readiness::Failed);
|
||||
const std::vector<std::string> expected{
|
||||
"storage.open", "storage.recover", "storage.close"};
|
||||
assert(host->history() == expected);
|
||||
assert(host->peer_port() == 0);
|
||||
(void)::close(fd);
|
||||
}
|
||||
|
||||
void log_cap_is_bounded()
|
||||
{
|
||||
PeerLog log{2};
|
||||
assert(log.append("a").has_value());
|
||||
assert(log.append("b").has_value());
|
||||
auto rejected = log.append("c");
|
||||
assert(!rejected.has_value());
|
||||
assert(log.size() == 2);
|
||||
assert(log.last_index() == 2);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
config_fails_closed_without_a_token();
|
||||
peer_fixture_requires_authentication_and_serves_bounded_state();
|
||||
bind_failure_rolls_back_in_reverse_order();
|
||||
log_cap_is_bounded();
|
||||
std::puts("distributed single-node host ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(NetworkedKv LANGUAGES CXX)
|
||||
|
||||
# Reference application, built as an installed-package consumer so it cannot
|
||||
# accidentally rely on whole-repository linkage.
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Runtime Net Sqlite Messaging Scheduler Discovery)
|
||||
|
||||
add_library(networked_kv STATIC
|
||||
src/application.cpp
|
||||
src/http_api.cpp
|
||||
src/job_service.cpp
|
||||
src/memory_store.cpp
|
||||
src/service_directory.cpp
|
||||
src/sqlite_store.cpp)
|
||||
target_include_directories(networked_kv PUBLIC include)
|
||||
target_link_libraries(networked_kv PUBLIC Void::Net Void::Runtime Void::Sqlite Void::Messaging Void::Scheduler Void::Discovery)
|
||||
|
||||
add_executable(networked_kv_test tests/application_test.cpp)
|
||||
target_link_libraries(networked_kv_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_domain_test tests/domain_test.cpp)
|
||||
target_link_libraries(networked_kv_domain_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_http_test tests/http_api_test.cpp)
|
||||
target_link_libraries(networked_kv_http_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_sqlite_test tests/sqlite_store_test.cpp)
|
||||
target_link_libraries(networked_kv_sqlite_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_protocol_test tests/protocol_matrix_test.cpp)
|
||||
target_link_libraries(networked_kv_protocol_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_job_test tests/job_service_test.cpp)
|
||||
target_link_libraries(networked_kv_job_test PRIVATE networked_kv)
|
||||
|
||||
add_executable(networked_kv_directory_test tests/service_directory_test.cpp)
|
||||
target_link_libraries(networked_kv_directory_test PRIVATE networked_kv)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME networked_kv_lifecycle COMMAND networked_kv_test)
|
||||
add_test(NAME networked_kv_domain COMMAND networked_kv_domain_test)
|
||||
add_test(NAME networked_kv_http COMMAND networked_kv_http_test)
|
||||
add_test(NAME networked_kv_sqlite COMMAND networked_kv_sqlite_test)
|
||||
add_test(NAME networked_kv_protocol COMMAND networked_kv_protocol_test)
|
||||
add_test(NAME networked_kv_jobs COMMAND networked_kv_job_test)
|
||||
add_test(NAME networked_kv_directory COMMAND networked_kv_directory_test)
|
||||
@@ -0,0 +1,168 @@
|
||||
#pragma once
|
||||
|
||||
#include "networked_kv/domain.hpp"
|
||||
#include "networked_kv/http_api.hpp"
|
||||
#include "networked_kv/service_directory.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/Runtime/Host.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
/// Validated listener and request bounds for the reference service.
|
||||
/// Construction alone opens no socket or worker.
|
||||
struct NetworkedConfig {
|
||||
std::string listen_address{"127.0.0.1:0"};
|
||||
std::string admin_address{};
|
||||
/// Bearer token required on the data plane; empty fails closed.
|
||||
std::string bearer_token{};
|
||||
/// Durable SQLite KV path. Empty selects the in-memory profile.
|
||||
std::string storage_path{};
|
||||
std::uint32_t max_connections{64};
|
||||
std::size_t max_request_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_header_bytes{64ULL * 1024ULL};
|
||||
std::size_t max_scan_page{1000};
|
||||
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
|
||||
/// Optional Discovery-owned service directory. Registration is an
|
||||
/// observation dependency: its failure never stops the data plane.
|
||||
bool discovery_enabled{false};
|
||||
std::string discovery_service{"networked-kv"};
|
||||
std::string discovery_instance{};
|
||||
std::string discovery_host{"127.0.0.1"};
|
||||
std::chrono::milliseconds request_deadline{
|
||||
std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds shutdown_grace{
|
||||
std::chrono::seconds{5}};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
enum class ResourceOwnership : std::uint8_t { Embedded, Managed };
|
||||
|
||||
/// Module-owned resources supplied by the application.
|
||||
///
|
||||
/// Embedded mode borrows an already-running host and never shuts it down.
|
||||
/// Managed mode lets the application create and own the host.
|
||||
struct ApplicationResources {
|
||||
ResourceOwnership ownership{ResourceOwnership::Embedded};
|
||||
Void::Runtime::Host* borrowed_host{nullptr};
|
||||
Void::Runtime::Options runtime_options{};
|
||||
};
|
||||
|
||||
enum class ApplicationState : std::uint8_t {
|
||||
Created,
|
||||
Running,
|
||||
Stopping,
|
||||
Stopped,
|
||||
Failed
|
||||
};
|
||||
|
||||
struct HealthSnapshot {
|
||||
ApplicationState state{ApplicationState::Created};
|
||||
bool ready{false};
|
||||
bool managed{false};
|
||||
std::size_t started_workers{0};
|
||||
std::uint16_t bound_port{0};
|
||||
bool discovery_registered{false};
|
||||
std::string discovery_error;
|
||||
};
|
||||
|
||||
/// Composition surface for the networked key-value reference service.
|
||||
///
|
||||
/// This slice owns lifecycle and resource-mode policy only: it wires no
|
||||
/// HTTP endpoints yet and defines no competing executor, clock, logger or
|
||||
/// error type.
|
||||
class NetworkedApplication
|
||||
{
|
||||
public:
|
||||
|
||||
NetworkedApplication(const NetworkedApplication&) = delete;
|
||||
NetworkedApplication& operator=(const NetworkedApplication&) = delete;
|
||||
NetworkedApplication(NetworkedApplication&&) noexcept;
|
||||
NetworkedApplication& operator=(NetworkedApplication&&) noexcept;
|
||||
~NetworkedApplication();
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<NetworkedApplication>
|
||||
create(ApplicationResources resources, NetworkedConfig config);
|
||||
|
||||
/// Start serving. Managed mode creates and starts the owned host;
|
||||
/// embedded mode requires the borrowed host to already be running.
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
/// Stop serving. Idempotent and bounded. Managed mode shuts the
|
||||
/// owned host down; embedded mode leaves the borrowed host alone.
|
||||
[[nodiscard]] Void::Result::Result<Void::Runtime::ShutdownReport>
|
||||
stop();
|
||||
|
||||
[[nodiscard]] HealthSnapshot health() const;
|
||||
[[nodiscard]] const NetworkedConfig& config() const noexcept
|
||||
{
|
||||
return m_config;
|
||||
}
|
||||
/// Generation of the live configuration (starts at 1 after the first
|
||||
/// successful start; incremented by each applied reload).
|
||||
[[nodiscard]] std::uint64_t config_generation() const noexcept
|
||||
{
|
||||
return m_generation;
|
||||
}
|
||||
/// Parse/validate a complete candidate and apply the live-reloadable
|
||||
/// parts atomically: the bearer token and readiness gating. Listener
|
||||
/// addresses, backend selection, storage path and limits require a
|
||||
/// restart and are rejected with a conflict error while the
|
||||
/// application is running, leaving the old generation untouched.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
reload(NetworkedConfig candidate);
|
||||
/// Port the HTTP listener actually bound (0 when not listening).
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept;
|
||||
/// Port the administrative listener bound (0 when not listening).
|
||||
[[nodiscard]] std::uint16_t admin_bound_port() const noexcept;
|
||||
|
||||
/// Discovery directory when enabled (null otherwise). Owned by the
|
||||
/// application; valid until the next reload or stop.
|
||||
[[nodiscard]] ServiceDirectory* directory() noexcept
|
||||
{
|
||||
return m_directory.get();
|
||||
}
|
||||
[[nodiscard]] const ServiceDirectory* directory() const noexcept
|
||||
{
|
||||
return m_directory.get();
|
||||
}
|
||||
|
||||
/// Consistent operator backup of the durable profile. Fails when
|
||||
/// the in-memory profile is active.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
backup_storage(const std::string& destination);
|
||||
|
||||
/// Restore the durable profile from a backup. Quiesce clients first;
|
||||
/// the caller owns re-validation before routing traffic again.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
restore_storage(const std::string& source);
|
||||
|
||||
private:
|
||||
|
||||
NetworkedApplication() = default;
|
||||
void stop_owned_host() noexcept;
|
||||
|
||||
NetworkedConfig m_config{};
|
||||
ApplicationResources m_resources{};
|
||||
std::unique_ptr<Void::Runtime::Host> m_owned_host{};
|
||||
Void::Runtime::Host* m_host{nullptr};
|
||||
// Heap-owned so a moved application keeps the KvApi reference valid.
|
||||
std::unique_ptr<KvStore> m_store{};
|
||||
std::unique_ptr<KvApi> m_api{};
|
||||
std::unique_ptr<Void::Net::HttpServer> m_server{};
|
||||
std::unique_ptr<Void::Net::HttpServer> m_admin_server{};
|
||||
std::unique_ptr<ServiceDirectory> m_directory{};
|
||||
std::string m_discovery_error{};
|
||||
ApplicationState m_state{ApplicationState::Created};
|
||||
std::uint64_t m_generation{0};
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,158 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
using Version = std::uint64_t;
|
||||
|
||||
struct Limits {
|
||||
std::size_t max_key_bytes{512};
|
||||
std::size_t max_value_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_request_id_bytes{128};
|
||||
std::size_t max_scan_page{1000};
|
||||
std::size_t max_operation_records{1024};
|
||||
};
|
||||
|
||||
struct Entry {
|
||||
std::string value;
|
||||
Version version{1};
|
||||
};
|
||||
|
||||
enum class PreconditionKind : std::uint8_t { Absent, Version };
|
||||
|
||||
/// Explicit absent/version precondition for a mutation.
|
||||
struct Precondition {
|
||||
PreconditionKind kind{PreconditionKind::Absent};
|
||||
Version version{0};
|
||||
|
||||
[[nodiscard]] static Precondition absent() noexcept
|
||||
{
|
||||
return {};
|
||||
}
|
||||
[[nodiscard]] static Precondition at_version(Version value) noexcept
|
||||
{
|
||||
return {PreconditionKind::Version, value};
|
||||
}
|
||||
};
|
||||
|
||||
/// Idempotency key for a mutation. Replaying the same id returns the
|
||||
/// recorded outcome instead of applying the mutation twice.
|
||||
struct RequestId {
|
||||
std::string value;
|
||||
};
|
||||
|
||||
enum class WriteOutcome : std::uint8_t {
|
||||
Applied,
|
||||
Conflict,
|
||||
NotFound,
|
||||
/// The backend could not prove whether the write committed.
|
||||
Unknown
|
||||
};
|
||||
|
||||
struct WriteResult {
|
||||
WriteOutcome outcome{WriteOutcome::Unknown};
|
||||
Version version{0};
|
||||
};
|
||||
|
||||
struct ScanItem {
|
||||
std::string key;
|
||||
Entry entry;
|
||||
};
|
||||
|
||||
struct ScanPage {
|
||||
std::vector<ScanItem> items;
|
||||
/// Opaque cursor for the next page; empty when the scan is done.
|
||||
std::optional<std::string> next_cursor;
|
||||
};
|
||||
|
||||
/// Versioned key-value domain contract shared by storage backends.
|
||||
class KvStore
|
||||
{
|
||||
public:
|
||||
|
||||
KvStore() = default;
|
||||
KvStore(const KvStore&) = delete;
|
||||
KvStore& operator=(const KvStore&) = delete;
|
||||
virtual ~KvStore() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::optional<Entry>>
|
||||
get(std::string_view key) const = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<WriteResult>
|
||||
put(std::string_view key, std::string value,
|
||||
Precondition precondition, RequestId request) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<WriteResult>
|
||||
erase(std::string_view key, Precondition precondition,
|
||||
RequestId request) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<ScanPage>
|
||||
scan(std::optional<std::string_view> cursor,
|
||||
std::size_t limit = 0) const = 0;
|
||||
|
||||
/// Recorded outcome of a mutation request id, if it is still within
|
||||
/// the retention window. Absence is not proof that a write did not
|
||||
/// commit; callers must treat it as unknown.
|
||||
[[nodiscard]] virtual Void::Result::Result<std::optional<WriteResult>>
|
||||
lookup_operation(const RequestId& request) const = 0;
|
||||
};
|
||||
|
||||
/// Bounded in-memory reference backend. Durable backends implement the
|
||||
/// same contract without changing the domain semantics.
|
||||
class MemoryKvStore final : public KvStore
|
||||
{
|
||||
public:
|
||||
|
||||
explicit MemoryKvStore(Limits limits = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<Entry>>
|
||||
get(std::string_view key) const override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<WriteResult>
|
||||
put(std::string_view key, std::string value,
|
||||
Precondition precondition, RequestId request) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<WriteResult>
|
||||
erase(std::string_view key, Precondition precondition,
|
||||
RequestId request) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ScanPage>
|
||||
scan(std::optional<std::string_view> cursor,
|
||||
std::size_t limit = 0) const override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<WriteResult>>
|
||||
lookup_operation(const RequestId& request) const override;
|
||||
|
||||
[[nodiscard]] const Limits& limits() const noexcept
|
||||
{
|
||||
return m_limits;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
validate_key(std::string_view key) const;
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
validate_request(const RequestId& request) const;
|
||||
[[nodiscard]] std::optional<WriteResult>
|
||||
replay(const RequestId& request) const;
|
||||
void remember(const RequestId& request, const WriteResult& result);
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
Limits m_limits;
|
||||
std::map<std::string, Entry, std::less<>> m_entries;
|
||||
std::map<std::string, WriteResult, std::less<>> m_operations;
|
||||
std::vector<std::string> m_operation_order;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
|
||||
#include "networked_kv/domain.hpp"
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
struct HttpRequest {
|
||||
std::string method;
|
||||
std::string target;
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::string body;
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view name) const;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
int status{200};
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::string body;
|
||||
};
|
||||
|
||||
struct ApiConfig {
|
||||
std::string bearer_token;
|
||||
std::size_t max_body_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_scan_limit{1000};
|
||||
};
|
||||
|
||||
struct ApiMetrics {
|
||||
std::uint64_t requests{0};
|
||||
std::uint64_t unauthorized{0};
|
||||
std::uint64_t client_errors{0};
|
||||
std::uint64_t server_errors{0};
|
||||
std::uint64_t bytes_in{0};
|
||||
std::uint64_t bytes_out{0};
|
||||
};
|
||||
|
||||
/// Transport-agnostic HTTP application layer for the key-value service.
|
||||
///
|
||||
/// Net owns parsing and framing; this maps an already-parsed request to the
|
||||
/// KV domain, enforces bearer auth on the data plane, and exposes bounded
|
||||
/// admin views that never dump credentials or mutate data.
|
||||
class KvApi
|
||||
{
|
||||
public:
|
||||
|
||||
KvApi(KvStore& store, ApiConfig config);
|
||||
|
||||
[[nodiscard]] HttpResponse handle(const HttpRequest& request);
|
||||
|
||||
[[nodiscard]] HttpResponse admin(const HttpRequest& request) const;
|
||||
|
||||
void set_ready(bool ready) noexcept { m_ready = ready; }
|
||||
|
||||
/// Atomically replace the live-reloadable bearer token. In-flight
|
||||
/// requests read either the old or the new token, never a torn mix.
|
||||
void set_bearer_token(std::string token)
|
||||
{
|
||||
std::lock_guard lock{m_config_mutex};
|
||||
m_config.bearer_token = std::move(token);
|
||||
}
|
||||
|
||||
[[nodiscard]] ApiMetrics metrics() const noexcept { return m_metrics; }
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool authorized(const HttpRequest& request) const;
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_get(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_put(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_delete(std::string_view key, const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_scan(const HttpRequest& request);
|
||||
[[nodiscard]] HttpResponse
|
||||
kv_operation(std::string_view request_id);
|
||||
void note(const HttpResponse& response);
|
||||
|
||||
KvStore& m_store;
|
||||
ApiConfig m_config;
|
||||
mutable std::mutex m_config_mutex;
|
||||
bool m_ready{true};
|
||||
ApiMetrics m_metrics;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,123 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
struct JobServiceConfig {
|
||||
std::string queue_name{"jobs"};
|
||||
std::string group_name{"workers"};
|
||||
std::chrono::milliseconds visibility_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
/// Attempts before the queue dead-letters the job.
|
||||
std::uint32_t max_attempts{3};
|
||||
std::chrono::milliseconds retry_delay{
|
||||
std::chrono::milliseconds{50}};
|
||||
/// Bounded status records; the oldest is evicted beyond this.
|
||||
std::size_t max_tracked_jobs{1024};
|
||||
/// Memory is explicit for the in-memory profile; a durable queue
|
||||
/// profile passes Durable.
|
||||
Void::Messaging::PublishDurability publish_durability{
|
||||
Void::Messaging::PublishDurability::Memory};
|
||||
};
|
||||
|
||||
enum class JobState : std::uint8_t {
|
||||
Submitted,
|
||||
Running,
|
||||
Succeeded,
|
||||
RetryScheduled,
|
||||
DeadLettered,
|
||||
Unknown
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string_view job_state_name(JobState state) noexcept;
|
||||
|
||||
struct JobView {
|
||||
std::string id;
|
||||
JobState state{JobState::Unknown};
|
||||
std::uint32_t attempts{0};
|
||||
std::string last_error;
|
||||
};
|
||||
|
||||
/// Runs one delivered job. `attempt` starts at 1.
|
||||
using JobHandler = std::function<Void::Result::Result<void>(
|
||||
std::string_view payload, std::uint32_t attempt)>;
|
||||
|
||||
/// Durable-job reference composition over the Messaging queue contract.
|
||||
///
|
||||
/// Delivery semantics are the queue's (at-least-once with visibility
|
||||
/// timeout and DLQ after exhausted attempts); this service adds bounded
|
||||
/// job status tracking and a Scheduler-driven maintenance job. Workers
|
||||
/// must be idempotent per job id: a redelivery after a lost ack is
|
||||
/// possible by contract.
|
||||
class JobService
|
||||
{
|
||||
public:
|
||||
|
||||
JobService(Void::Messaging::Queue& queue, JobServiceConfig config = {});
|
||||
JobService(const JobService&) = delete;
|
||||
JobService& operator=(const JobService&) = delete;
|
||||
|
||||
/// Create the queue and consumer group. Idempotent for an
|
||||
/// existing compatible configuration.
|
||||
[[nodiscard]] Void::Result::Result<void> initialize();
|
||||
|
||||
/// Publish one job and return its stable id. The id is the
|
||||
/// queue's idempotency key, so a repeated publish of the same id
|
||||
/// is deduplicated by the queue.
|
||||
[[nodiscard]] Void::Result::Result<std::string> submit(std::string payload);
|
||||
|
||||
/// Receive at most one job, run the handler and ack or nack it.
|
||||
/// Returns the affected job view, or empty when no job is ready.
|
||||
/// A handler failure is recorded (retry or dead letter), not
|
||||
/// returned as an error; queue failures are.
|
||||
[[nodiscard]] Void::Result::Result<std::optional<JobView>>
|
||||
process_one(const JobHandler& handler);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<JobView>
|
||||
status(std::string_view id) const;
|
||||
|
||||
/// Reap expired in-flight deliveries back to pending (or the DLQ
|
||||
/// when attempts are exhausted). Driven by the Scheduler job.
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> maintain();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::vector<Void::Messaging::DeadLetterEntry>>
|
||||
dead_letters(std::size_t limit = 100) const;
|
||||
|
||||
/// Register a fixed-rate Scheduler job that runs `maintain()`.
|
||||
/// The scheduler is pure and thread-free: the caller drives it with
|
||||
/// tick()/dispatch_one(). Returns the scheduler job id.
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
schedule_maintenance(Void::Scheduler::Scheduler& scheduler,
|
||||
std::chrono::milliseconds period =
|
||||
std::chrono::seconds{30});
|
||||
|
||||
private:
|
||||
|
||||
void track(const JobView& view);
|
||||
|
||||
Void::Messaging::Queue& m_queue;
|
||||
JobServiceConfig m_config;
|
||||
std::uint64_t m_next_id{1};
|
||||
bool m_initialized{false};
|
||||
bool m_maintenance_registered{false};
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::map<std::string, JobView, std::less<>> m_jobs;
|
||||
std::deque<std::string> m_order;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Discovery/Catalog.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
struct ServiceDirectoryConfig {
|
||||
std::string service_name{"networked-kv"};
|
||||
/// Stable instance identity; required when the directory is enabled.
|
||||
std::string instance_id{};
|
||||
std::string advertise_host{"127.0.0.1"};
|
||||
std::string scheme{"http"};
|
||||
std::uint32_t weight{1};
|
||||
};
|
||||
|
||||
/// Thin adapter over the Discovery-owned `Catalog`.
|
||||
///
|
||||
/// The catalog is authoritative for registration, revision and resolution
|
||||
/// policy; this adapter only maps the reference service's endpoint into it.
|
||||
/// Discovery is an observation dependency: a provider that is stale or
|
||||
/// unavailable never stops the data plane and never counts as a quorum
|
||||
/// vote.
|
||||
class ServiceDirectory
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ServiceDirectory(ServiceDirectoryConfig config = {});
|
||||
ServiceDirectory(const ServiceDirectory&) = delete;
|
||||
ServiceDirectory& operator=(const ServiceDirectory&) = delete;
|
||||
ServiceDirectory(ServiceDirectory&&) noexcept = default;
|
||||
ServiceDirectory& operator=(ServiceDirectory&&) noexcept = default;
|
||||
~ServiceDirectory();
|
||||
|
||||
/// Register the live data-plane endpoint. Idempotent while the
|
||||
/// previous registration is active.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
register_endpoint(std::uint16_t port);
|
||||
|
||||
void deregister() noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::vector<Void::Discovery::EndpointRecord>>
|
||||
resolve(std::string_view service,
|
||||
Void::Discovery::ResolvePolicy policy = {}) const;
|
||||
|
||||
/// Adapter hook for an unavailable/stale upstream provider.
|
||||
void set_provider_health(
|
||||
Void::Discovery::Freshness freshness,
|
||||
std::optional<Void::Discovery::Error> provider_error =
|
||||
std::nullopt) noexcept;
|
||||
|
||||
[[nodiscard]] std::size_t active_records() const noexcept;
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept;
|
||||
[[nodiscard]] bool registered() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
ServiceDirectoryConfig m_config;
|
||||
Void::Discovery::Catalog m_catalog;
|
||||
Void::Discovery::Registration m_registration;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "networked_kv/domain.hpp"
|
||||
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string_view>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
/// Durable KV profile backed by Void::Sqlite.
|
||||
///
|
||||
/// Business rows and idempotency records are written in one explicit
|
||||
/// transaction, so a request either commits both or neither. Versions are
|
||||
/// checked inside that transaction.
|
||||
class SqliteKvStore final : public KvStore
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<SqliteKvStore>>
|
||||
open(const std::filesystem::path& path, Limits limits = {});
|
||||
|
||||
~SqliteKvStore() override = default;
|
||||
SqliteKvStore(const SqliteKvStore&) = delete;
|
||||
SqliteKvStore& operator=(const SqliteKvStore&) = delete;
|
||||
SqliteKvStore(SqliteKvStore&&) noexcept = default;
|
||||
SqliteKvStore& operator=(SqliteKvStore&&) noexcept = default;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<Entry>>
|
||||
get(std::string_view key) const override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<WriteResult>
|
||||
put(std::string_view key, std::string value,
|
||||
Precondition precondition, RequestId request) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<WriteResult>
|
||||
erase(std::string_view key, Precondition precondition,
|
||||
RequestId request) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ScanPage>
|
||||
scan(std::optional<std::string_view> cursor,
|
||||
std::size_t limit = 0) const override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<WriteResult>>
|
||||
lookup_operation(const RequestId& request) const override;
|
||||
|
||||
[[nodiscard]] const Limits& limits() const noexcept
|
||||
{
|
||||
return m_limits;
|
||||
}
|
||||
|
||||
/// Consistent operator backup through SQLite's online backup API.
|
||||
/// `destination` must not be the live database file.
|
||||
[[nodiscard]] Void::Result::Result<Void::Sqlite::BackupReport>
|
||||
backup_to(const std::filesystem::path& destination);
|
||||
|
||||
/// Restore this connection from a verified backup file. Callers
|
||||
/// must quiesce application traffic first; run domain checks before
|
||||
/// routing traffic to the restored contents.
|
||||
[[nodiscard]] Void::Result::Result<Void::Sqlite::BackupReport>
|
||||
restore_from(const std::filesystem::path& source);
|
||||
|
||||
private:
|
||||
|
||||
SqliteKvStore(Void::Sqlite::Database database, Limits limits);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> ensure_schema();
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
// prepare() is non-const, but the read-only KvStore methods are const.
|
||||
mutable Void::Sqlite::Database m_db;
|
||||
Limits m_limits;
|
||||
};
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,532 @@
|
||||
#include "networked_kv/application.hpp"
|
||||
|
||||
#include "networked_kv/sqlite_store.hpp"
|
||||
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <charconv>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error
|
||||
config_error(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error state_error(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool parse_address(std::string_view address, std::string& host,
|
||||
std::uint16_t& port) noexcept
|
||||
{
|
||||
const auto colon = address.rfind(':');
|
||||
if (colon == std::string_view::npos || colon == 0 ||
|
||||
colon + 1 >= address.size()) {
|
||||
return false;
|
||||
}
|
||||
host = std::string{address.substr(0, colon)};
|
||||
const auto digits = address.substr(colon + 1);
|
||||
unsigned int value = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
digits.data(), digits.data() + digits.size(), value);
|
||||
if (parsed.ec != std::errc{} ||
|
||||
parsed.ptr != digits.data() + digits.size() || value > 65535U) {
|
||||
return false;
|
||||
}
|
||||
port = static_cast<std::uint16_t>(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string method_name(Void::Net::Method method)
|
||||
{
|
||||
switch (method) {
|
||||
case Void::Net::Method::Get: return "GET";
|
||||
case Void::Net::Method::Post: return "POST";
|
||||
case Void::Net::Method::Put: return "PUT";
|
||||
case Void::Net::Method::Delete: return "DELETE";
|
||||
case Void::Net::Method::Patch: return "PATCH";
|
||||
case Void::Net::Method::Head: return "HEAD";
|
||||
case Void::Net::Method::Options: return "OPTIONS";
|
||||
}
|
||||
return "GET";
|
||||
}
|
||||
|
||||
[[nodiscard]] HttpRequest
|
||||
to_http_request(const Void::Net::ServerRequest& request)
|
||||
{
|
||||
HttpRequest out;
|
||||
out.method = method_name(request.method);
|
||||
out.target = request.path;
|
||||
if (!request.query.empty()) {
|
||||
out.target += '?';
|
||||
out.target += request.query;
|
||||
}
|
||||
for (const auto& header : request.headers) {
|
||||
out.headers[header.name] = header.value;
|
||||
}
|
||||
out.body = request.body;
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Net::ServerResponse
|
||||
to_server_response(const HttpResponse& response)
|
||||
{
|
||||
Void::Net::ServerResponse out;
|
||||
out.status = static_cast<std::uint16_t>(response.status);
|
||||
out.body = response.body;
|
||||
out.headers.reserve(response.headers.size());
|
||||
for (const auto& [name, value] : response.headers) {
|
||||
out.headers.push_back(Void::Net::Header{name, value});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Async::OperationOptions
|
||||
deadline_after(std::chrono::milliseconds grace)
|
||||
{
|
||||
Void::Async::OperationOptions options;
|
||||
options.deadline = Void::Time::SystemMonotonicClock::instance().now() +
|
||||
grace;
|
||||
return options;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<void> NetworkedConfig::validate() const
|
||||
{
|
||||
if (listen_address.empty()) {
|
||||
return std::unexpected{
|
||||
config_error("NetworkedConfig: listen_address must not be empty")};
|
||||
}
|
||||
if (max_connections == 0) {
|
||||
return std::unexpected{
|
||||
config_error("NetworkedConfig: max_connections must be positive")};
|
||||
}
|
||||
if (max_request_bytes == 0) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: max_request_bytes must be positive")};
|
||||
}
|
||||
if (max_header_bytes == 0) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: max_header_bytes must be positive")};
|
||||
}
|
||||
if (read_timeout.count() <= 0 || write_timeout.count() <= 0) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: read/write timeouts must be positive")};
|
||||
}
|
||||
if (max_scan_page == 0) {
|
||||
return std::unexpected{
|
||||
config_error("NetworkedConfig: max_scan_page must be positive")};
|
||||
}
|
||||
if (request_deadline.count() <= 0) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: request_deadline must be positive")};
|
||||
}
|
||||
if (shutdown_grace.count() < 0) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: shutdown_grace must not be negative")};
|
||||
}
|
||||
if (discovery_enabled && discovery_instance.empty()) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedConfig: discovery_instance is required when "
|
||||
"discovery is enabled")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
NetworkedApplication::NetworkedApplication(NetworkedApplication&& other) noexcept
|
||||
: m_config(std::move(other.m_config))
|
||||
, m_resources(other.m_resources)
|
||||
, m_owned_host(std::move(other.m_owned_host))
|
||||
, m_host(other.m_host)
|
||||
, m_store(std::move(other.m_store))
|
||||
, m_api(std::move(other.m_api))
|
||||
, m_server(std::move(other.m_server))
|
||||
, m_admin_server(std::move(other.m_admin_server))
|
||||
, m_directory(std::move(other.m_directory))
|
||||
, m_discovery_error(std::move(other.m_discovery_error))
|
||||
, m_state(other.m_state)
|
||||
{
|
||||
other.m_host = nullptr;
|
||||
other.m_state = ApplicationState::Stopped;
|
||||
}
|
||||
|
||||
NetworkedApplication&
|
||||
NetworkedApplication::operator=(NetworkedApplication&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
stop_owned_host();
|
||||
m_config = std::move(other.m_config);
|
||||
m_resources = other.m_resources;
|
||||
m_owned_host = std::move(other.m_owned_host);
|
||||
m_host = other.m_host;
|
||||
m_store = std::move(other.m_store);
|
||||
m_api = std::move(other.m_api);
|
||||
m_server = std::move(other.m_server);
|
||||
m_admin_server = std::move(other.m_admin_server);
|
||||
m_directory = std::move(other.m_directory);
|
||||
m_discovery_error = std::move(other.m_discovery_error);
|
||||
m_state = other.m_state;
|
||||
other.m_host = nullptr;
|
||||
other.m_state = ApplicationState::Stopped;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
NetworkedApplication::~NetworkedApplication()
|
||||
{
|
||||
if (m_server) {
|
||||
m_server->shutdown(m_config.shutdown_grace);
|
||||
m_server.reset();
|
||||
}
|
||||
if (m_admin_server) {
|
||||
m_admin_server->shutdown(m_config.shutdown_grace);
|
||||
m_admin_server.reset();
|
||||
}
|
||||
stop_owned_host();
|
||||
}
|
||||
|
||||
Void::Result::Result<NetworkedApplication>
|
||||
NetworkedApplication::create(ApplicationResources resources,
|
||||
NetworkedConfig config)
|
||||
{
|
||||
if (auto valid = config.validate(); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
if (resources.ownership == ResourceOwnership::Embedded &&
|
||||
(resources.borrowed_host == nullptr ||
|
||||
!resources.borrowed_host->valid())) {
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedApplication: embedded mode requires a valid borrowed "
|
||||
"host")};
|
||||
}
|
||||
NetworkedApplication app;
|
||||
app.m_config = std::move(config);
|
||||
app.m_resources = resources;
|
||||
if (app.m_config.storage_path.empty()) {
|
||||
app.m_store = std::make_unique<MemoryKvStore>();
|
||||
} else {
|
||||
auto durable = SqliteKvStore::open(app.m_config.storage_path);
|
||||
if (!durable) {
|
||||
return std::unexpected{std::move(durable).error()};
|
||||
}
|
||||
app.m_store = std::move(*durable);
|
||||
}
|
||||
app.m_api = std::make_unique<KvApi>(
|
||||
*app.m_store,
|
||||
ApiConfig{.bearer_token = app.m_config.bearer_token,
|
||||
.max_body_bytes = app.m_config.max_request_bytes,
|
||||
.max_scan_limit = app.m_config.max_scan_page});
|
||||
if (app.m_config.discovery_enabled) {
|
||||
app.m_directory = std::make_unique<ServiceDirectory>(
|
||||
ServiceDirectoryConfig{
|
||||
.service_name = app.m_config.discovery_service,
|
||||
.instance_id = app.m_config.discovery_instance,
|
||||
.advertise_host = app.m_config.discovery_host});
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
Void::Result::Result<void> NetworkedApplication::start()
|
||||
{
|
||||
if (m_state == ApplicationState::Running) {
|
||||
return std::unexpected{
|
||||
state_error("NetworkedApplication: already running")};
|
||||
}
|
||||
if (m_resources.ownership == ResourceOwnership::Managed) {
|
||||
if (!m_owned_host) {
|
||||
auto created =
|
||||
Void::Runtime::Host::create(m_resources.runtime_options);
|
||||
if (!created) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return std::unexpected{std::move(created).error()};
|
||||
}
|
||||
m_owned_host =
|
||||
std::make_unique<Void::Runtime::Host>(std::move(*created));
|
||||
m_host = m_owned_host.get();
|
||||
}
|
||||
if (!m_host->is_running()) {
|
||||
if (auto started = m_host->start(); !started) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return started;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m_host = m_resources.borrowed_host;
|
||||
if (m_host == nullptr || !m_host->is_running()) {
|
||||
return std::unexpected{state_error(
|
||||
"NetworkedApplication: embedded mode requires a running "
|
||||
"borrowed host")};
|
||||
}
|
||||
}
|
||||
if (!m_server) {
|
||||
std::string host;
|
||||
std::uint16_t port = 0;
|
||||
if (!parse_address(m_config.listen_address, host, port)) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedApplication: listen_address must be host:port")};
|
||||
}
|
||||
Void::Net::HttpServerOptions options;
|
||||
options.bind_host = std::move(host);
|
||||
options.port = port;
|
||||
options.max_body_bytes = m_config.max_request_bytes;
|
||||
options.max_header_bytes = m_config.max_header_bytes;
|
||||
options.read_timeout = m_config.read_timeout;
|
||||
options.write_timeout = m_config.write_timeout;
|
||||
options.max_concurrent_connections = m_config.max_connections;
|
||||
auto server = std::make_unique<Void::Net::HttpServer>(options);
|
||||
auto add = [&](Void::Net::Method method, const char* pattern) {
|
||||
return server->add_route(
|
||||
method, pattern,
|
||||
[this](const Void::Net::ServerRequest& request)
|
||||
-> Void::Net::RouteResult {
|
||||
return to_server_response(
|
||||
m_api->handle(to_http_request(request)));
|
||||
});
|
||||
};
|
||||
Void::Result::Error route_error{};
|
||||
bool routes_ok = true;
|
||||
auto add_checked = [&](Void::Net::Method method, const char* pattern) {
|
||||
if (!routes_ok) {
|
||||
return;
|
||||
}
|
||||
if (auto added = add(method, pattern); !added) {
|
||||
routes_ok = false;
|
||||
route_error = std::move(added).error();
|
||||
}
|
||||
};
|
||||
add_checked(Void::Net::Method::Get, "/v1/kv/:key");
|
||||
add_checked(Void::Net::Method::Put, "/v1/kv/:key");
|
||||
add_checked(Void::Net::Method::Delete, "/v1/kv/:key");
|
||||
add_checked(Void::Net::Method::Get, "/v1/scan");
|
||||
add_checked(Void::Net::Method::Get, "/v1/operations/:id");
|
||||
if (!routes_ok) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return std::unexpected{std::move(route_error)};
|
||||
}
|
||||
if (auto started = server->start(); !started) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return started;
|
||||
}
|
||||
m_server = std::move(server);
|
||||
if (m_directory) {
|
||||
// Discovery is an observation dependency: a failed registration
|
||||
// is reported, never fatal for the data plane.
|
||||
if (auto registered =
|
||||
m_directory->register_endpoint(m_server->bound_port());
|
||||
!registered) {
|
||||
m_discovery_error = registered.error().message();
|
||||
} else {
|
||||
m_discovery_error.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The administrative listener is separate from the data plane and
|
||||
// only exposes bounded lifecycle and telemetry views.
|
||||
if (!m_admin_server && !m_config.admin_address.empty()) {
|
||||
std::string host;
|
||||
std::uint16_t port = 0;
|
||||
if (!parse_address(m_config.admin_address, host, port)) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return std::unexpected{config_error(
|
||||
"NetworkedApplication: admin_address must be host:port")};
|
||||
}
|
||||
Void::Net::HttpServerOptions options;
|
||||
options.bind_host = std::move(host);
|
||||
options.port = port;
|
||||
options.max_concurrent_connections = 8;
|
||||
auto admin = std::make_unique<Void::Net::HttpServer>(options);
|
||||
auto add_admin = [&](const char* pattern) {
|
||||
return admin->add_route(
|
||||
Void::Net::Method::Get, pattern,
|
||||
[this](const Void::Net::ServerRequest& request)
|
||||
-> Void::Net::RouteResult {
|
||||
return to_server_response(
|
||||
m_api->admin(to_http_request(request)));
|
||||
});
|
||||
};
|
||||
Void::Result::Error admin_error{};
|
||||
bool admin_ok = true;
|
||||
for (const char* pattern : {"/live", "/ready", "/metrics"}) {
|
||||
if (!admin_ok) {
|
||||
break;
|
||||
}
|
||||
if (auto added = add_admin(pattern); !added) {
|
||||
admin_ok = false;
|
||||
admin_error = std::move(added).error();
|
||||
}
|
||||
}
|
||||
if (!admin_ok) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return std::unexpected{std::move(admin_error)};
|
||||
}
|
||||
if (auto started = admin->start(); !started) {
|
||||
m_state = ApplicationState::Failed;
|
||||
return started;
|
||||
}
|
||||
m_admin_server = std::move(admin);
|
||||
}
|
||||
m_state = ApplicationState::Running;
|
||||
++m_generation;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
NetworkedApplication::reload(NetworkedConfig candidate)
|
||||
{
|
||||
if (auto valid = candidate.validate(); !valid) {
|
||||
return valid;
|
||||
}
|
||||
if (m_state != ApplicationState::Running) {
|
||||
return std::unexpected{state_error(
|
||||
"NetworkedApplication: reload requires a running application")};
|
||||
}
|
||||
// Only policy that can change without rebinding listeners or reopening
|
||||
// the backend is applied live. Everything else is a restart decision.
|
||||
if (candidate.listen_address != m_config.listen_address ||
|
||||
candidate.admin_address != m_config.admin_address ||
|
||||
candidate.storage_path != m_config.storage_path ||
|
||||
candidate.max_connections != m_config.max_connections ||
|
||||
candidate.max_request_bytes != m_config.max_request_bytes ||
|
||||
candidate.max_header_bytes != m_config.max_header_bytes ||
|
||||
candidate.read_timeout != m_config.read_timeout ||
|
||||
candidate.write_timeout != m_config.write_timeout ||
|
||||
candidate.max_scan_page != m_config.max_scan_page) {
|
||||
return std::unexpected{state_error(
|
||||
"NetworkedApplication: listener, storage and limit changes "
|
||||
"require a restart")};
|
||||
}
|
||||
|
||||
// Publish the immutable generation only after every step succeeded.
|
||||
// The API token swap is the single live mutation; there is no second
|
||||
// listener to fail after it.
|
||||
m_api->set_bearer_token(candidate.bearer_token);
|
||||
m_config = std::move(candidate);
|
||||
++m_generation;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<Void::Runtime::ShutdownReport>
|
||||
NetworkedApplication::stop()
|
||||
{
|
||||
if (m_state == ApplicationState::Stopped) {
|
||||
return Void::Runtime::ShutdownReport{};
|
||||
}
|
||||
if (m_state != ApplicationState::Running) {
|
||||
m_state = ApplicationState::Stopped;
|
||||
return Void::Runtime::ShutdownReport{};
|
||||
}
|
||||
m_state = ApplicationState::Stopping;
|
||||
if (m_directory) {
|
||||
m_directory->deregister();
|
||||
}
|
||||
if (m_server) {
|
||||
m_server->shutdown(m_config.shutdown_grace);
|
||||
m_server.reset();
|
||||
}
|
||||
if (m_admin_server) {
|
||||
m_admin_server->shutdown(m_config.shutdown_grace);
|
||||
m_admin_server.reset();
|
||||
}
|
||||
if (m_resources.ownership == ResourceOwnership::Managed && m_host) {
|
||||
auto report =
|
||||
m_host->shutdown_blocking(deadline_after(m_config.shutdown_grace));
|
||||
m_state = ApplicationState::Stopped;
|
||||
return report;
|
||||
}
|
||||
// Embedded: the borrowed host belongs to the application, so only
|
||||
// this composition's view stops.
|
||||
m_state = ApplicationState::Stopped;
|
||||
Void::Runtime::ShutdownReport report;
|
||||
report.complete = true;
|
||||
report.state = m_host ? m_host->state()
|
||||
: Void::Runtime::HostState::stopped;
|
||||
return report;
|
||||
}
|
||||
|
||||
HealthSnapshot NetworkedApplication::health() const
|
||||
{
|
||||
HealthSnapshot snapshot;
|
||||
snapshot.state = m_state;
|
||||
snapshot.managed = m_resources.ownership == ResourceOwnership::Managed;
|
||||
if (m_host != nullptr) {
|
||||
snapshot.ready = m_host->is_ready();
|
||||
snapshot.started_workers = m_host->started_worker_count();
|
||||
}
|
||||
snapshot.bound_port = bound_port();
|
||||
snapshot.discovery_registered =
|
||||
m_directory != nullptr && m_directory->registered();
|
||||
snapshot.discovery_error = m_discovery_error;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
std::uint16_t NetworkedApplication::bound_port() const noexcept
|
||||
{
|
||||
return m_server ? m_server->bound_port() : 0;
|
||||
}
|
||||
|
||||
std::uint16_t NetworkedApplication::admin_bound_port() const noexcept
|
||||
{
|
||||
return m_admin_server ? m_admin_server->bound_port() : 0;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
NetworkedApplication::backup_storage(const std::string& destination)
|
||||
{
|
||||
auto* durable = dynamic_cast<SqliteKvStore*>(m_store.get());
|
||||
if (durable == nullptr) {
|
||||
return std::unexpected{state_error(
|
||||
"NetworkedApplication: backup requires the durable profile")};
|
||||
}
|
||||
if (destination.empty()) {
|
||||
return std::unexpected{
|
||||
config_error("NetworkedApplication: backup destination is empty")};
|
||||
}
|
||||
if (auto backed_up = durable->backup_to(destination); !backed_up) {
|
||||
return std::unexpected{std::move(backed_up).error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
NetworkedApplication::restore_storage(const std::string& source)
|
||||
{
|
||||
auto* durable = dynamic_cast<SqliteKvStore*>(m_store.get());
|
||||
if (durable == nullptr) {
|
||||
return std::unexpected{state_error(
|
||||
"NetworkedApplication: restore requires the durable profile")};
|
||||
}
|
||||
if (source.empty()) {
|
||||
return std::unexpected{
|
||||
config_error("NetworkedApplication: restore source is empty")};
|
||||
}
|
||||
if (auto restored = durable->restore_from(source); !restored) {
|
||||
return std::unexpected{std::move(restored).error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void NetworkedApplication::stop_owned_host() noexcept
|
||||
{
|
||||
if (m_resources.ownership != ResourceOwnership::Managed ||
|
||||
!m_owned_host || m_state != ApplicationState::Running) {
|
||||
return;
|
||||
}
|
||||
m_state = ApplicationState::Stopping;
|
||||
(void)m_owned_host->shutdown_blocking(
|
||||
deadline_after(m_config.shutdown_grace));
|
||||
m_state = ApplicationState::Stopped;
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,483 @@
|
||||
#include "networked_kv/http_api.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::string_view kJsonType{"application/json"};
|
||||
constexpr std::string_view kTextType{"text/plain; charset=utf-8"};
|
||||
constexpr std::string_view kKvPrefix{"/v1/kv/"};
|
||||
constexpr std::string_view kOperationsPrefix{"/v1/operations/"};
|
||||
|
||||
[[nodiscard]] bool iequals(std::string_view lhs,
|
||||
std::string_view rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < lhs.size(); ++i) {
|
||||
const char a = lhs[i] >= 'A' && lhs[i] <= 'Z'
|
||||
? static_cast<char>(lhs[i] + 32)
|
||||
: lhs[i];
|
||||
const char b = rhs[i] >= 'A' && rhs[i] <= 'Z'
|
||||
? static_cast<char>(rhs[i] + 32)
|
||||
: rhs[i];
|
||||
if (a != b) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view path_of(std::string_view target) noexcept
|
||||
{
|
||||
const auto query = target.find('?');
|
||||
return target.substr(0, query);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view query_of(std::string_view target) noexcept
|
||||
{
|
||||
const auto query = target.find('?');
|
||||
return query == std::string_view::npos ? std::string_view{}
|
||||
: target.substr(query + 1);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
query_param(std::string_view query, std::string_view name) noexcept
|
||||
{
|
||||
while (!query.empty()) {
|
||||
const auto amp = query.find('&');
|
||||
const auto part = query.substr(0, amp);
|
||||
const auto eq = part.find('=');
|
||||
if (eq != std::string_view::npos &&
|
||||
part.substr(0, eq) == name) {
|
||||
return part.substr(eq + 1);
|
||||
}
|
||||
if (amp == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
query.remove_prefix(amp + 1);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool constant_time_equal(std::string_view lhs,
|
||||
std::string_view rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
unsigned int diff = 0;
|
||||
for (std::size_t i = 0; i < lhs.size(); ++i) {
|
||||
diff |= static_cast<unsigned int>(
|
||||
static_cast<unsigned char>(lhs[i]) ^
|
||||
static_cast<unsigned char>(rhs[i]));
|
||||
}
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string json_escape(std::string_view input,
|
||||
std::size_t max)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(std::min(input.size(), max) + 8);
|
||||
for (const char ch : input) {
|
||||
if (out.size() >= max) {
|
||||
break;
|
||||
}
|
||||
const auto byte = static_cast<unsigned char>(ch);
|
||||
switch (ch) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (byte < 0x20) {
|
||||
out += std::format("\\u{:04x}", byte);
|
||||
} else {
|
||||
out += ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] int status_for(const Void::Result::Error& error) noexcept
|
||||
{
|
||||
using Kind = Void::Result::ErrorKind;
|
||||
switch (error.kind()) {
|
||||
case Kind::invalid_argument: return 400;
|
||||
case Kind::not_found: return 404;
|
||||
case Kind::conflict: return 409;
|
||||
case Kind::exhausted: return 429;
|
||||
case Kind::overloaded: return 503;
|
||||
case Kind::cancelled: return 499;
|
||||
case Kind::timeout: return 504;
|
||||
case Kind::unsupported: return 501;
|
||||
default: return 500;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] HttpResponse error_response(int status,
|
||||
std::string message)
|
||||
{
|
||||
HttpResponse response;
|
||||
response.status = status;
|
||||
response.headers["content-type"] = std::string{kJsonType};
|
||||
response.body = "{\"error\":\"" + json_escape(message, 512) + "\"}";
|
||||
return response;
|
||||
}
|
||||
|
||||
[[nodiscard]] HttpResponse text_response(int status, std::string body)
|
||||
{
|
||||
HttpResponse response;
|
||||
response.status = status;
|
||||
response.headers["content-type"] = std::string{kTextType};
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<Version>
|
||||
parse_etag(std::string_view value) noexcept
|
||||
{
|
||||
if (value.size() >= 2 && value.front() == '"' &&
|
||||
value.back() == '"') {
|
||||
value = value.substr(1, value.size() - 2);
|
||||
}
|
||||
Version version = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
value.data(), value.data() + value.size(), version);
|
||||
if (parsed.ec != std::errc{} ||
|
||||
parsed.ptr != value.data() + value.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string etag(Version version)
|
||||
{
|
||||
return "\"" + std::to_string(version) + "\"";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string_view>
|
||||
HttpRequest::header(std::string_view name) const
|
||||
{
|
||||
for (const auto& [key, value] : headers) {
|
||||
if (iequals(key, name)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
KvApi::KvApi(KvStore& store, ApiConfig config)
|
||||
: m_store(store)
|
||||
, m_config(std::move(config))
|
||||
{
|
||||
}
|
||||
|
||||
bool KvApi::authorized(const HttpRequest& request) const
|
||||
{
|
||||
const auto header = request.header("authorization");
|
||||
if (!header) {
|
||||
return false;
|
||||
}
|
||||
constexpr std::string_view scheme{"bearer "};
|
||||
if (header->size() < scheme.size() ||
|
||||
!iequals(header->substr(0, scheme.size()), scheme)) {
|
||||
return false;
|
||||
}
|
||||
std::lock_guard lock{m_config_mutex};
|
||||
// Fail closed: an empty configured token authorizes nothing.
|
||||
if (m_config.bearer_token.empty()) {
|
||||
return false;
|
||||
}
|
||||
return constant_time_equal(header->substr(scheme.size()),
|
||||
m_config.bearer_token);
|
||||
}
|
||||
|
||||
void KvApi::note(const HttpResponse& response)
|
||||
{
|
||||
m_metrics.bytes_out += response.body.size();
|
||||
if (response.status >= 500) {
|
||||
++m_metrics.server_errors;
|
||||
} else if (response.status >= 400) {
|
||||
++m_metrics.client_errors;
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse KvApi::handle(const HttpRequest& request)
|
||||
{
|
||||
++m_metrics.requests;
|
||||
m_metrics.bytes_in += request.target.size() + request.body.size();
|
||||
|
||||
if (request.body.size() > m_config.max_body_bytes) {
|
||||
HttpResponse response = error_response(413, "request body too large");
|
||||
note(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
const auto path = path_of(request.target);
|
||||
HttpResponse response;
|
||||
if (path.starts_with(kKvPrefix) || path == "/v1/scan" ||
|
||||
path.starts_with(kOperationsPrefix)) {
|
||||
if (!authorized(request)) {
|
||||
++m_metrics.unauthorized;
|
||||
response = error_response(401, "missing or invalid bearer token");
|
||||
} else if (path == "/v1/scan") {
|
||||
response = request.method == "GET"
|
||||
? kv_scan(request)
|
||||
: error_response(405, "method not allowed");
|
||||
} else if (path.starts_with(kOperationsPrefix)) {
|
||||
response = request.method == "GET"
|
||||
? kv_operation(path.substr(kOperationsPrefix.size()))
|
||||
: error_response(405, "method not allowed");
|
||||
} else {
|
||||
|
||||
const auto key = path.substr(kKvPrefix.size());
|
||||
if (key.empty()) {
|
||||
response = error_response(400, "key required");
|
||||
} else if (request.method == "GET") {
|
||||
response = kv_get(key, request);
|
||||
} else if (request.method == "PUT") {
|
||||
response = kv_put(key, request);
|
||||
} else if (request.method == "DELETE") {
|
||||
response = kv_delete(key, request);
|
||||
} else {
|
||||
response = error_response(405, "method not allowed");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
response = error_response(404, "not found");
|
||||
}
|
||||
note(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_get(std::string_view key, const HttpRequest&)
|
||||
{
|
||||
auto got = m_store.get(key);
|
||||
if (!got) {
|
||||
return error_response(status_for(got.error()),
|
||||
got.error().message());
|
||||
}
|
||||
if (!got->has_value()) {
|
||||
return error_response(404, "not found");
|
||||
}
|
||||
HttpResponse response;
|
||||
response.status = 200;
|
||||
response.headers["content-type"] = "application/octet-stream";
|
||||
response.headers["etag"] = etag((*got)->version);
|
||||
response.headers["cache-control"] = "no-store";
|
||||
response.body = (*got)->value;
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_put(std::string_view key, const HttpRequest& request)
|
||||
{
|
||||
const auto request_id = request.header("x-request-id");
|
||||
if (!request_id || request_id->empty()) {
|
||||
return error_response(428, "x-request-id required");
|
||||
}
|
||||
Precondition precondition;
|
||||
if (const auto none = request.header("if-none-match");
|
||||
none && *none == "*") {
|
||||
precondition = Precondition::absent();
|
||||
} else if (const auto match = request.header("if-match")) {
|
||||
const auto version = parse_etag(*match);
|
||||
if (!version) {
|
||||
return error_response(400, "invalid if-match");
|
||||
}
|
||||
precondition = Precondition::at_version(*version);
|
||||
} else {
|
||||
return error_response(428,
|
||||
"if-none-match or if-match required");
|
||||
}
|
||||
|
||||
auto result = m_store.put(key, request.body, precondition,
|
||||
RequestId{std::string{*request_id}});
|
||||
if (!result) {
|
||||
return error_response(status_for(result.error()),
|
||||
result.error().message());
|
||||
}
|
||||
switch (result->outcome) {
|
||||
case WriteOutcome::Applied: {
|
||||
HttpResponse response = text_response(200, "applied");
|
||||
response.headers["etag"] = etag(result->version);
|
||||
return response;
|
||||
}
|
||||
case WriteOutcome::Conflict:
|
||||
return error_response(412, "version precondition failed");
|
||||
case WriteOutcome::NotFound:
|
||||
return error_response(404, "not found");
|
||||
case WriteOutcome::Unknown:
|
||||
return error_response(503, "commit outcome unknown");
|
||||
}
|
||||
return error_response(500, "unreachable");
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_delete(std::string_view key,
|
||||
const HttpRequest& request)
|
||||
{
|
||||
const auto request_id = request.header("x-request-id");
|
||||
if (!request_id || request_id->empty()) {
|
||||
return error_response(428, "x-request-id required");
|
||||
}
|
||||
const auto match = request.header("if-match");
|
||||
if (!match) {
|
||||
return error_response(428, "if-match required");
|
||||
}
|
||||
const auto version = parse_etag(*match);
|
||||
if (!version) {
|
||||
return error_response(400, "invalid if-match");
|
||||
}
|
||||
|
||||
auto result = m_store.erase(key, Precondition::at_version(*version),
|
||||
RequestId{std::string{*request_id}});
|
||||
if (!result) {
|
||||
return error_response(status_for(result.error()),
|
||||
result.error().message());
|
||||
}
|
||||
switch (result->outcome) {
|
||||
case WriteOutcome::Applied: {
|
||||
HttpResponse response;
|
||||
response.status = 204;
|
||||
return response;
|
||||
}
|
||||
case WriteOutcome::Conflict:
|
||||
return error_response(412, "version precondition failed");
|
||||
case WriteOutcome::NotFound:
|
||||
return error_response(404, "not found");
|
||||
case WriteOutcome::Unknown:
|
||||
return error_response(503, "commit outcome unknown");
|
||||
}
|
||||
return error_response(500, "unreachable");
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_scan(const HttpRequest& request)
|
||||
{
|
||||
const auto query = query_of(request.target);
|
||||
const auto cursor = query_param(query, "cursor");
|
||||
std::size_t limit = 0;
|
||||
if (const auto raw = query_param(query, "limit")) {
|
||||
std::size_t parsed = 0;
|
||||
const auto result = std::from_chars(
|
||||
raw->data(), raw->data() + raw->size(), parsed);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != raw->data() + raw->size() || parsed == 0) {
|
||||
return error_response(400, "invalid limit");
|
||||
}
|
||||
limit = std::min(parsed, m_config.max_scan_limit);
|
||||
}
|
||||
|
||||
auto page = m_store.scan(cursor ? std::optional<std::string_view>{*cursor}
|
||||
: std::nullopt,
|
||||
limit);
|
||||
if (!page) {
|
||||
return error_response(status_for(page.error()),
|
||||
page.error().message());
|
||||
}
|
||||
|
||||
std::string body = "{\"items\":[";
|
||||
for (std::size_t i = 0; i < page->items.size(); ++i) {
|
||||
const auto& item = page->items[i];
|
||||
if (i != 0) {
|
||||
body += ',';
|
||||
}
|
||||
body += "{\"key\":\"" + json_escape(item.key, 1024) +
|
||||
"\",\"version\":" + std::to_string(item.entry.version) +
|
||||
",\"value\":\"" + json_escape(item.entry.value, 64 * 1024) +
|
||||
"\"}";
|
||||
}
|
||||
body += "],\"next_cursor\":";
|
||||
if (page->next_cursor) {
|
||||
body += "\"" + json_escape(*page->next_cursor, 1024) + "\"";
|
||||
} else {
|
||||
body += "null";
|
||||
}
|
||||
body += '}';
|
||||
|
||||
HttpResponse response;
|
||||
response.status = 200;
|
||||
response.headers["content-type"] = std::string{kJsonType};
|
||||
response.headers["cache-control"] = "no-store";
|
||||
response.body = std::move(body);
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::kv_operation(std::string_view request_id)
|
||||
{
|
||||
HttpResponse response;
|
||||
response.status = 200;
|
||||
response.headers["content-type"] = std::string{kJsonType};
|
||||
response.headers["cache-control"] = "no-store";
|
||||
|
||||
if (request_id.empty()) {
|
||||
return error_response(400, "operation id required");
|
||||
}
|
||||
auto recorded = m_store.lookup_operation(RequestId{std::string{request_id}});
|
||||
if (!recorded) {
|
||||
return error_response(status_for(recorded.error()),
|
||||
recorded.error().message());
|
||||
}
|
||||
if (!recorded->has_value()) {
|
||||
// Absence or expired retention is explicitly unknown, never proof
|
||||
// that the write did not commit.
|
||||
response.body = "{\"outcome\":\"unknown\"}";
|
||||
return response;
|
||||
}
|
||||
std::string_view outcome;
|
||||
switch ((*recorded)->outcome) {
|
||||
case WriteOutcome::Applied: outcome = "applied"; break;
|
||||
case WriteOutcome::Conflict: outcome = "conflict"; break;
|
||||
case WriteOutcome::NotFound: outcome = "not_found"; break;
|
||||
case WriteOutcome::Unknown: outcome = "unknown"; break;
|
||||
}
|
||||
response.body = "{\"outcome\":\"" + std::string{outcome} +
|
||||
"\",\"version\":" +
|
||||
std::to_string((*recorded)->version) + "}";
|
||||
return response;
|
||||
}
|
||||
|
||||
HttpResponse KvApi::admin(const HttpRequest& request) const
|
||||
{
|
||||
const auto path = path_of(request.target);
|
||||
if (request.method != "GET") {
|
||||
return error_response(405, "method not allowed");
|
||||
}
|
||||
if (path == "/live") {
|
||||
return text_response(200, "ok");
|
||||
}
|
||||
if (path == "/ready") {
|
||||
return m_ready ? text_response(200, "ready")
|
||||
: text_response(503, "not ready");
|
||||
}
|
||||
if (path == "/metrics") {
|
||||
std::string body;
|
||||
body += "# bounded application counters\n";
|
||||
body += "networked_kv_requests_total " +
|
||||
std::to_string(m_metrics.requests) + "\n";
|
||||
body += "networked_kv_unauthorized_total " +
|
||||
std::to_string(m_metrics.unauthorized) + "\n";
|
||||
body += "networked_kv_client_errors_total " +
|
||||
std::to_string(m_metrics.client_errors) + "\n";
|
||||
body += "networked_kv_server_errors_total " +
|
||||
std::to_string(m_metrics.server_errors) + "\n";
|
||||
body += "networked_kv_bytes_in_total " +
|
||||
std::to_string(m_metrics.bytes_in) + "\n";
|
||||
body += "networked_kv_bytes_out_total " +
|
||||
std::to_string(m_metrics.bytes_out) + "\n";
|
||||
return text_response(200, std::move(body));
|
||||
}
|
||||
return error_response(404, "not found");
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,232 @@
|
||||
#include "networked_kv/job_service.hpp"
|
||||
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <exception>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error not_found(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<std::byte> to_bytes(std::string_view text)
|
||||
{
|
||||
const auto raw = std::as_bytes(std::span{text.data(), text.size()});
|
||||
return std::vector<std::byte>{raw.begin(), raw.end()};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string to_string(std::span<const std::byte> bytes)
|
||||
{
|
||||
return std::string{
|
||||
reinterpret_cast<const char*>(bytes.data()), bytes.size()};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string_view job_state_name(JobState state) noexcept
|
||||
{
|
||||
switch (state) {
|
||||
case JobState::Submitted: return "submitted";
|
||||
case JobState::Running: return "running";
|
||||
case JobState::Succeeded: return "succeeded";
|
||||
case JobState::RetryScheduled: return "retry-scheduled";
|
||||
case JobState::DeadLettered: return "dead-lettered";
|
||||
case JobState::Unknown: return "unknown";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
JobService::JobService(Void::Messaging::Queue& queue,
|
||||
JobServiceConfig config)
|
||||
: m_queue(queue), m_config(std::move(config))
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> JobService::initialize()
|
||||
{
|
||||
if (m_initialized) {
|
||||
return {};
|
||||
}
|
||||
Void::Messaging::QueueConfig queue;
|
||||
queue.name = m_config.queue_name;
|
||||
queue.retry = Void::Messaging::RetryPolicy{
|
||||
.max_attempts = m_config.max_attempts,
|
||||
.base_delay = m_config.retry_delay,
|
||||
.max_delay = m_config.retry_delay};
|
||||
if (auto created = m_queue.create_queue(std::move(queue)); !created) {
|
||||
return created;
|
||||
}
|
||||
Void::Messaging::GroupConfig group;
|
||||
group.name = m_config.group_name;
|
||||
group.visibility_timeout = m_config.visibility_timeout;
|
||||
if (auto created =
|
||||
m_queue.create_group(m_config.queue_name, std::move(group));
|
||||
!created) {
|
||||
return created;
|
||||
}
|
||||
m_initialized = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string> JobService::submit(std::string payload)
|
||||
{
|
||||
if (!m_initialized) {
|
||||
return std::unexpected{
|
||||
conflict("JobService: initialize() before submitting")};
|
||||
}
|
||||
Void::Messaging::Message message;
|
||||
message.id = "job-" + std::to_string(m_next_id++);
|
||||
message.payload = to_bytes(payload);
|
||||
auto published = m_queue.publish(
|
||||
m_config.queue_name, std::move(message),
|
||||
m_config.publish_durability);
|
||||
if (!published) {
|
||||
return std::unexpected{std::move(published).error()};
|
||||
}
|
||||
track(JobView{.id = published->message_id,
|
||||
.state = JobState::Submitted});
|
||||
return published->message_id;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<JobView>>
|
||||
JobService::process_one(const JobHandler& handler)
|
||||
{
|
||||
auto received =
|
||||
m_queue.try_receive(m_config.queue_name, m_config.group_name);
|
||||
if (!received) {
|
||||
return std::unexpected{std::move(received).error()};
|
||||
}
|
||||
if (!received->has_value()) {
|
||||
return std::optional<JobView>{};
|
||||
}
|
||||
Void::Messaging::Delivery delivery = std::move(**received);
|
||||
const std::string id = delivery.message.id;
|
||||
|
||||
JobView view;
|
||||
view.id = id;
|
||||
view.attempts = delivery.attempt;
|
||||
view.state = JobState::Running;
|
||||
track(view);
|
||||
|
||||
Void::Result::Result<void> handled;
|
||||
try {
|
||||
handled = handler
|
||||
? handler(to_string(delivery.message.payload),
|
||||
delivery.attempt)
|
||||
: Void::Result::Result<void>{};
|
||||
} catch (const std::exception& error) {
|
||||
handled = std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::internal,
|
||||
std::string{"job handler threw: "} + error.what()}};
|
||||
} catch (...) {
|
||||
handled = std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::internal,
|
||||
"job handler threw an unknown exception"}};
|
||||
}
|
||||
|
||||
if (handled.has_value()) {
|
||||
if (auto acknowledged = m_queue.ack(delivery.receipt);
|
||||
!acknowledged) {
|
||||
return std::unexpected{std::move(acknowledged).error()};
|
||||
}
|
||||
view.state = JobState::Succeeded;
|
||||
track(view);
|
||||
return std::optional<JobView>{view};
|
||||
}
|
||||
|
||||
view.last_error = handled.error().message();
|
||||
// Exhausted attempts are moved to the DLQ by the queue; record the
|
||||
// terminal state now so status does not depend on another receive.
|
||||
view.state = delivery.attempt >= m_config.max_attempts
|
||||
? JobState::DeadLettered
|
||||
: JobState::RetryScheduled;
|
||||
if (auto rejected = m_queue.nack(delivery.receipt,
|
||||
m_config.retry_delay);
|
||||
!rejected) {
|
||||
return std::unexpected{std::move(rejected).error()};
|
||||
}
|
||||
track(view);
|
||||
return std::optional<JobView>{view};
|
||||
}
|
||||
|
||||
Void::Result::Result<JobView>
|
||||
JobService::status(std::string_view id) const
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto found = m_jobs.find(id);
|
||||
if (found == m_jobs.end()) {
|
||||
return std::unexpected{not_found(
|
||||
"JobService: no tracked job for the given id")};
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::size_t> JobService::maintain()
|
||||
{
|
||||
return m_queue.reap_expired_visibility();
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<Void::Messaging::DeadLetterEntry>>
|
||||
JobService::dead_letters(std::size_t limit) const
|
||||
{
|
||||
return m_queue.list_dead_letters(m_config.queue_name,
|
||||
m_config.group_name, limit);
|
||||
}
|
||||
|
||||
Void::Result::Result<std::uint64_t> JobService::schedule_maintenance(
|
||||
Void::Scheduler::Scheduler& scheduler, std::chrono::milliseconds period)
|
||||
{
|
||||
if (!m_maintenance_registered) {
|
||||
auto registered = scheduler.register_handler(
|
||||
"job-maintenance",
|
||||
[this](const Void::Scheduler::OccurrenceContext&,
|
||||
std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Void::Result::Result<void> {
|
||||
auto reaped = maintain();
|
||||
if (!reaped) {
|
||||
return std::unexpected{std::move(reaped).error()};
|
||||
}
|
||||
return {};
|
||||
});
|
||||
if (!registered) {
|
||||
return std::unexpected{std::move(registered).error()};
|
||||
}
|
||||
m_maintenance_registered = true;
|
||||
}
|
||||
Void::Scheduler::JobSpec spec;
|
||||
spec.id = "job-maintenance";
|
||||
spec.handler_id = "job-maintenance";
|
||||
spec.schedule = Void::Scheduler::Schedule::fixed_rate(
|
||||
period, Void::Time::SystemMonotonicClock::instance().now());
|
||||
return scheduler.add_job(std::move(spec));
|
||||
}
|
||||
|
||||
void JobService::track(const JobView& view)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto found = m_jobs.find(view.id);
|
||||
if (found == m_jobs.end()) {
|
||||
if (m_jobs.size() >= m_config.max_tracked_jobs &&
|
||||
!m_order.empty()) {
|
||||
m_jobs.erase(m_order.front());
|
||||
m_order.pop_front();
|
||||
}
|
||||
m_order.push_back(view.id);
|
||||
}
|
||||
m_jobs.insert_or_assign(view.id, view);
|
||||
}
|
||||
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,210 @@
|
||||
#include "networked_kv/domain.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool matches(const std::optional<Entry>& current,
|
||||
const Precondition& precondition) noexcept
|
||||
{
|
||||
if (precondition.kind == PreconditionKind::Absent) {
|
||||
return !current.has_value();
|
||||
}
|
||||
return current.has_value() &&
|
||||
current->version == precondition.version;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
MemoryKvStore::MemoryKvStore(Limits limits)
|
||||
: m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
MemoryKvStore::validate_key(std::string_view key) const
|
||||
{
|
||||
if (key.empty()) {
|
||||
return std::unexpected{invalid("KvStore: key must not be empty")};
|
||||
}
|
||||
if (key.size() > m_limits.max_key_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("KvStore: key exceeds max_key_bytes")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
MemoryKvStore::validate_request(const RequestId& request) const
|
||||
{
|
||||
if (request.value.empty()) {
|
||||
return std::unexpected{
|
||||
invalid("KvStore: request id must not be empty")};
|
||||
}
|
||||
if (request.value.size() > m_limits.max_request_id_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("KvStore: request id exceeds max_request_id_bytes")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<WriteResult>
|
||||
MemoryKvStore::replay(const RequestId& request) const
|
||||
{
|
||||
const auto found = m_operations.find(request.value);
|
||||
if (found == m_operations.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return found->second;
|
||||
}
|
||||
|
||||
void MemoryKvStore::remember(const RequestId& request,
|
||||
const WriteResult& result)
|
||||
{
|
||||
if (m_limits.max_operation_records == 0) {
|
||||
return;
|
||||
}
|
||||
if (m_operations.size() >= m_limits.max_operation_records &&
|
||||
!m_operation_order.empty()) {
|
||||
m_operations.erase(m_operation_order.front());
|
||||
m_operation_order.erase(m_operation_order.begin());
|
||||
}
|
||||
m_operations.emplace(request.value, result);
|
||||
m_operation_order.push_back(request.value);
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<Entry>>
|
||||
MemoryKvStore::get(std::string_view key) const
|
||||
{
|
||||
if (auto valid = validate_key(key); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto found = m_entries.find(key);
|
||||
if (found == m_entries.end()) {
|
||||
return std::optional<Entry>{};
|
||||
}
|
||||
return std::optional<Entry>{found->second};
|
||||
}
|
||||
|
||||
Void::Result::Result<WriteResult>
|
||||
MemoryKvStore::put(std::string_view key, std::string value,
|
||||
Precondition precondition, RequestId request)
|
||||
{
|
||||
if (auto valid = validate_key(key); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
if (auto valid = validate_request(request); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
if (value.size() > m_limits.max_value_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("KvStore: value exceeds max_value_bytes")};
|
||||
}
|
||||
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (const auto replayed = replay(request)) {
|
||||
return *replayed;
|
||||
}
|
||||
|
||||
const auto found = m_entries.find(key);
|
||||
const std::optional<Entry> current =
|
||||
found == m_entries.end() ? std::nullopt
|
||||
: std::optional<Entry>{found->second};
|
||||
if (!matches(current, precondition)) {
|
||||
WriteResult result{WriteOutcome::Conflict,
|
||||
current ? current->version : 0};
|
||||
remember(request, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
const Version version = current ? current->version + 1 : 1;
|
||||
m_entries.insert_or_assign(
|
||||
std::string{key}, Entry{std::move(value), version});
|
||||
WriteResult result{WriteOutcome::Applied, version};
|
||||
remember(request, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
Void::Result::Result<WriteResult>
|
||||
MemoryKvStore::erase(std::string_view key, Precondition precondition,
|
||||
RequestId request)
|
||||
{
|
||||
if (auto valid = validate_key(key); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
if (auto valid = validate_request(request); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
|
||||
std::lock_guard lock{m_mutex};
|
||||
if (const auto replayed = replay(request)) {
|
||||
return *replayed;
|
||||
}
|
||||
|
||||
const auto found = m_entries.find(key);
|
||||
if (found == m_entries.end()) {
|
||||
WriteResult result{WriteOutcome::NotFound, 0};
|
||||
remember(request, result);
|
||||
return result;
|
||||
}
|
||||
const std::optional<Entry> current = found->second;
|
||||
if (!matches(current, precondition)) {
|
||||
WriteResult result{WriteOutcome::Conflict, current->version};
|
||||
remember(request, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
m_entries.erase(found);
|
||||
WriteResult result{WriteOutcome::Applied, 0};
|
||||
remember(request, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
Void::Result::Result<ScanPage>
|
||||
MemoryKvStore::scan(std::optional<std::string_view> cursor,
|
||||
std::size_t limit) const
|
||||
{
|
||||
const std::size_t page =
|
||||
std::min(limit == 0 ? m_limits.max_scan_page : limit,
|
||||
m_limits.max_scan_page);
|
||||
|
||||
std::lock_guard lock{m_mutex};
|
||||
ScanPage out;
|
||||
auto it = cursor ? m_entries.upper_bound(*cursor) : m_entries.begin();
|
||||
while (it != m_entries.end() && out.items.size() < page) {
|
||||
out.items.push_back(ScanItem{it->first, it->second});
|
||||
++it;
|
||||
}
|
||||
if (it != m_entries.end() && !out.items.empty()) {
|
||||
out.next_cursor = out.items.back().key;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
Void::Result::Result<std::optional<WriteResult>>
|
||||
MemoryKvStore::lookup_operation(const RequestId& request) const
|
||||
{
|
||||
if (auto valid = validate_request(request); !valid) {
|
||||
return std::unexpected{std::move(valid).error()};
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
const auto found = m_operations.find(request.value);
|
||||
if (found == m_operations.end()) {
|
||||
return std::optional<WriteResult>{};
|
||||
}
|
||||
return std::optional<WriteResult>{found->second};
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "networked_kv/service_directory.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
ServiceDirectory::ServiceDirectory(ServiceDirectoryConfig config)
|
||||
: m_config(std::move(config))
|
||||
{
|
||||
}
|
||||
|
||||
ServiceDirectory::~ServiceDirectory()
|
||||
{
|
||||
deregister();
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ServiceDirectory::register_endpoint(std::uint16_t port)
|
||||
{
|
||||
if (m_registration.active()) {
|
||||
return {};
|
||||
}
|
||||
if (m_config.instance_id.empty()) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
"ServiceDirectory: instance_id is required"}};
|
||||
}
|
||||
if (port == 0) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::invalid_argument,
|
||||
"ServiceDirectory: a bound port is required"}};
|
||||
}
|
||||
|
||||
Void::Discovery::EndpointRecord record;
|
||||
record.instance = m_config.instance_id;
|
||||
record.service = m_config.service_name;
|
||||
record.endpoint.scheme = m_config.scheme;
|
||||
record.endpoint.host = m_config.advertise_host;
|
||||
record.endpoint.port = port;
|
||||
record.weight = m_config.weight;
|
||||
record.ready = true;
|
||||
|
||||
auto registered = m_catalog.register_local(std::move(record));
|
||||
if (!registered) {
|
||||
return std::unexpected{std::move(registered).error()};
|
||||
}
|
||||
m_registration = std::move(*registered);
|
||||
return {};
|
||||
}
|
||||
|
||||
void ServiceDirectory::deregister() noexcept
|
||||
{
|
||||
if (m_registration.active()) {
|
||||
m_registration.release();
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<Void::Discovery::EndpointRecord>>
|
||||
ServiceDirectory::resolve(std::string_view service,
|
||||
Void::Discovery::ResolvePolicy policy) const
|
||||
{
|
||||
auto snapshot = m_catalog.resolve(service, policy);
|
||||
if (!snapshot) {
|
||||
return std::unexpected{std::move(snapshot).error()};
|
||||
}
|
||||
return std::move(snapshot->records);
|
||||
}
|
||||
|
||||
void ServiceDirectory::set_provider_health(
|
||||
Void::Discovery::Freshness freshness,
|
||||
std::optional<Void::Discovery::Error> provider_error) noexcept
|
||||
{
|
||||
m_catalog.set_provider_health(freshness, std::move(provider_error));
|
||||
}
|
||||
|
||||
std::size_t ServiceDirectory::active_records() const noexcept
|
||||
{
|
||||
return m_catalog.active_record_count();
|
||||
}
|
||||
|
||||
std::uint64_t ServiceDirectory::revision() const noexcept
|
||||
{
|
||||
return m_catalog.revision();
|
||||
}
|
||||
|
||||
bool ServiceDirectory::registered() const noexcept
|
||||
{
|
||||
return m_registration.active();
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,531 @@
|
||||
#include "networked_kv/sqlite_store.hpp"
|
||||
|
||||
#include <Void/Sqlite/Types.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
using Void::Sqlite::BeginMode;
|
||||
using Void::Sqlite::ValueView;
|
||||
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] int outcome_to_int(WriteOutcome outcome) noexcept
|
||||
{
|
||||
return static_cast<int>(outcome);
|
||||
}
|
||||
|
||||
[[nodiscard]] WriteOutcome outcome_from_int(int value) noexcept
|
||||
{
|
||||
switch (value) {
|
||||
case 0: return WriteOutcome::Applied;
|
||||
case 1: return WriteOutcome::Conflict;
|
||||
case 2: return WriteOutcome::NotFound;
|
||||
default: return WriteOutcome::Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool matches(const std::optional<Entry>& current,
|
||||
const Precondition& precondition) noexcept
|
||||
{
|
||||
if (precondition.kind == PreconditionKind::Absent) {
|
||||
return !current.has_value();
|
||||
}
|
||||
return current.has_value() &&
|
||||
current->version == precondition.version;
|
||||
}
|
||||
|
||||
[[nodiscard]] ValueView blob_view(std::string_view value) noexcept
|
||||
{
|
||||
return ValueView{std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(value.data()), value.size()}};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
SqliteKvStore::SqliteKvStore(Void::Sqlite::Database database, Limits limits)
|
||||
: m_db(std::move(database))
|
||||
, m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> SqliteKvStore::ensure_schema()
|
||||
{
|
||||
if (auto wal = m_db.exec("PRAGMA journal_mode=WAL"); !wal) {
|
||||
return std::unexpected{std::move(wal).error()};
|
||||
}
|
||||
if (auto kv = m_db.exec(
|
||||
"CREATE TABLE IF NOT EXISTS kv("
|
||||
"key TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL)");
|
||||
!kv) {
|
||||
return std::unexpected{std::move(kv).error()};
|
||||
}
|
||||
if (auto ops = m_db.exec(
|
||||
"CREATE TABLE IF NOT EXISTS operations("
|
||||
"request_id TEXT PRIMARY KEY, outcome INTEGER NOT NULL, "
|
||||
"version INTEGER NOT NULL)");
|
||||
!ops) {
|
||||
return std::unexpected{std::move(ops).error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<SqliteKvStore>>
|
||||
SqliteKvStore::open(const std::filesystem::path& path, Limits limits)
|
||||
{
|
||||
auto database = Void::Sqlite::Database::open(path);
|
||||
if (!database) {
|
||||
return std::unexpected{std::move(database).error()};
|
||||
}
|
||||
std::unique_ptr<SqliteKvStore> store{
|
||||
new SqliteKvStore{std::move(*database), limits}};
|
||||
if (auto schema = store->ensure_schema(); !schema) {
|
||||
return std::unexpected{std::move(schema).error()};
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<Entry>>
|
||||
SqliteKvStore::get(std::string_view key) const
|
||||
{
|
||||
if (key.empty() || key.size() > m_limits.max_key_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid key")};
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
auto statement = m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
|
||||
if (!statement) {
|
||||
return std::unexpected{std::move(statement).error()};
|
||||
}
|
||||
if (auto bound = statement->bind_checked(1, ValueView{key}); !bound) {
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = statement->step();
|
||||
if (!row) {
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (!*row) {
|
||||
return std::optional<Entry>{};
|
||||
}
|
||||
auto value = statement->try_column_blob(0);
|
||||
auto version = statement->try_column_int(1);
|
||||
if (!value || !version) {
|
||||
return std::unexpected{invalid("KvStore: malformed row")};
|
||||
}
|
||||
Entry entry;
|
||||
entry.value.assign(reinterpret_cast<const char*>(value->data()),
|
||||
value->size());
|
||||
entry.version = static_cast<Version>(*version);
|
||||
return std::optional<Entry>{std::move(entry)};
|
||||
}
|
||||
|
||||
Void::Result::Result<WriteResult>
|
||||
SqliteKvStore::put(std::string_view key, std::string value,
|
||||
Precondition precondition, RequestId request)
|
||||
{
|
||||
if (key.empty() || key.size() > m_limits.max_key_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid key")};
|
||||
}
|
||||
if (request.value.empty() ||
|
||||
request.value.size() > m_limits.max_request_id_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid request id")};
|
||||
}
|
||||
if (value.size() > m_limits.max_value_bytes) {
|
||||
return std::unexpected{invalid("KvStore: value too large")};
|
||||
}
|
||||
|
||||
std::lock_guard lock{m_mutex};
|
||||
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
|
||||
if (!transaction) {
|
||||
return std::unexpected{std::move(transaction).error()};
|
||||
}
|
||||
const auto rollback = [&] { (void)transaction->rollback_checked(); };
|
||||
|
||||
// Idempotent replay.
|
||||
{
|
||||
auto replay = m_db.prepare(
|
||||
"SELECT outcome, version FROM operations WHERE request_id = ?");
|
||||
if (!replay) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(replay).error()};
|
||||
}
|
||||
if (auto bound =
|
||||
replay->bind_checked(1, ValueView{request.value});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = replay->step();
|
||||
if (!row) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (*row) {
|
||||
auto outcome = replay->try_column_int(0);
|
||||
auto version = replay->try_column_int(1);
|
||||
if (!outcome || !version) {
|
||||
rollback();
|
||||
return std::unexpected{invalid("KvStore: malformed operation")};
|
||||
}
|
||||
if (auto committed = transaction->commit(); !committed) {
|
||||
return std::unexpected{std::move(committed).error()};
|
||||
}
|
||||
return WriteResult{outcome_from_int(
|
||||
static_cast<int>(*outcome)),
|
||||
static_cast<Version>(*version)};
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<Entry> current;
|
||||
{
|
||||
auto existing =
|
||||
m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
|
||||
if (!existing) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(existing).error()};
|
||||
}
|
||||
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = existing->step();
|
||||
if (!row) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (*row) {
|
||||
auto version = existing->try_column_int(1);
|
||||
if (!version) {
|
||||
rollback();
|
||||
return std::unexpected{invalid("KvStore: malformed row")};
|
||||
}
|
||||
current = Entry{{}, static_cast<Version>(*version)};
|
||||
}
|
||||
}
|
||||
|
||||
WriteResult result;
|
||||
if (!matches(current, precondition)) {
|
||||
result = WriteResult{WriteOutcome::Conflict,
|
||||
current ? current->version : 0};
|
||||
} else {
|
||||
const Version version = current ? current->version + 1 : 1;
|
||||
auto upsert = m_db.prepare(
|
||||
"INSERT INTO kv(key, value, version) VALUES(?, ?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET "
|
||||
"value = excluded.value, version = excluded.version");
|
||||
if (!upsert) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(upsert).error()};
|
||||
}
|
||||
if (auto bound = upsert->bind_checked(1, ValueView{key}); !bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
if (auto bound = upsert->bind_checked(2, blob_view(value)); !bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
if (auto bound = upsert->bind_checked(
|
||||
3, ValueView{static_cast<std::int64_t>(version)});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto stepped = upsert->step();
|
||||
if (!stepped) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(stepped).error()};
|
||||
}
|
||||
result = WriteResult{WriteOutcome::Applied, version};
|
||||
}
|
||||
|
||||
{
|
||||
auto record = m_db.prepare(
|
||||
"INSERT INTO operations(request_id, outcome, version) "
|
||||
"VALUES(?, ?, ?)");
|
||||
if (!record) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(record).error()};
|
||||
}
|
||||
if (auto bound =
|
||||
record->bind_checked(1, ValueView{request.value});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
if (auto bound = record->bind_checked(
|
||||
2, ValueView{outcome_to_int(result.outcome)});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
if (auto bound = record->bind_checked(
|
||||
3, ValueView{static_cast<std::int64_t>(result.version)});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto stepped = record->step();
|
||||
if (!stepped) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(stepped).error()};
|
||||
}
|
||||
}
|
||||
|
||||
if (auto committed = transaction->commit(); !committed) {
|
||||
return std::unexpected{std::move(committed).error()};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Void::Result::Result<WriteResult>
|
||||
SqliteKvStore::erase(std::string_view key, Precondition precondition,
|
||||
RequestId request)
|
||||
{
|
||||
if (key.empty() || key.size() > m_limits.max_key_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid key")};
|
||||
}
|
||||
if (request.value.empty() ||
|
||||
request.value.size() > m_limits.max_request_id_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid request id")};
|
||||
}
|
||||
|
||||
std::lock_guard lock{m_mutex};
|
||||
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
|
||||
if (!transaction) {
|
||||
return std::unexpected{std::move(transaction).error()};
|
||||
}
|
||||
const auto rollback = [&] { (void)transaction->rollback_checked(); };
|
||||
|
||||
{
|
||||
auto replay = m_db.prepare(
|
||||
"SELECT outcome, version FROM operations WHERE request_id = ?");
|
||||
if (!replay) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(replay).error()};
|
||||
}
|
||||
if (auto bound =
|
||||
replay->bind_checked(1, ValueView{request.value});
|
||||
!bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = replay->step();
|
||||
if (!row) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (*row) {
|
||||
auto outcome = replay->try_column_int(0);
|
||||
auto version = replay->try_column_int(1);
|
||||
if (!outcome || !version) {
|
||||
rollback();
|
||||
return std::unexpected{invalid("KvStore: malformed operation")};
|
||||
}
|
||||
if (auto committed = transaction->commit(); !committed) {
|
||||
return std::unexpected{std::move(committed).error()};
|
||||
}
|
||||
return WriteResult{outcome_from_int(
|
||||
static_cast<int>(*outcome)),
|
||||
static_cast<Version>(*version)};
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<Version> current;
|
||||
{
|
||||
auto existing = m_db.prepare("SELECT version FROM kv WHERE key = ?");
|
||||
if (!existing) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(existing).error()};
|
||||
}
|
||||
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = existing->step();
|
||||
if (!row) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (*row) {
|
||||
auto version = existing->try_column_int(0);
|
||||
if (!version) {
|
||||
rollback();
|
||||
return std::unexpected{invalid("KvStore: malformed row")};
|
||||
}
|
||||
current = static_cast<Version>(*version);
|
||||
}
|
||||
}
|
||||
|
||||
WriteResult result;
|
||||
if (!current) {
|
||||
result = WriteResult{WriteOutcome::NotFound, 0};
|
||||
} else if (precondition.kind == PreconditionKind::Version &&
|
||||
*current != precondition.version) {
|
||||
result = WriteResult{WriteOutcome::Conflict, *current};
|
||||
} else if (precondition.kind == PreconditionKind::Absent) {
|
||||
result = WriteResult{WriteOutcome::Conflict, *current};
|
||||
} else {
|
||||
auto remove = m_db.prepare("DELETE FROM kv WHERE key = ?");
|
||||
if (!remove) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(remove).error()};
|
||||
}
|
||||
if (auto bound = remove->bind_checked(1, ValueView{key}); !bound) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto stepped = remove->step();
|
||||
if (!stepped) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(stepped).error()};
|
||||
}
|
||||
result = WriteResult{WriteOutcome::Applied, 0};
|
||||
}
|
||||
|
||||
{
|
||||
auto record = m_db.prepare(
|
||||
"INSERT INTO operations(request_id, outcome, version) "
|
||||
"VALUES(?, ?, ?)");
|
||||
if (!record) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(record).error()};
|
||||
}
|
||||
(void)record->bind_checked(1, ValueView{request.value});
|
||||
(void)record->bind_checked(
|
||||
2, ValueView{outcome_to_int(result.outcome)});
|
||||
(void)record->bind_checked(
|
||||
3, ValueView{static_cast<std::int64_t>(result.version)});
|
||||
if (auto stepped = record->step(); !stepped) {
|
||||
rollback();
|
||||
return std::unexpected{std::move(stepped).error()};
|
||||
}
|
||||
}
|
||||
|
||||
if (auto committed = transaction->commit(); !committed) {
|
||||
return std::unexpected{std::move(committed).error()};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Void::Result::Result<ScanPage>
|
||||
SqliteKvStore::scan(std::optional<std::string_view> cursor,
|
||||
std::size_t limit) const
|
||||
{
|
||||
const std::size_t page =
|
||||
std::min(limit == 0 ? m_limits.max_scan_page : limit,
|
||||
m_limits.max_scan_page);
|
||||
if (page == 0) {
|
||||
return ScanPage{};
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
auto statement = m_db.prepare(
|
||||
"SELECT key, value, version FROM kv WHERE key > ? "
|
||||
"ORDER BY key LIMIT ?");
|
||||
if (!statement) {
|
||||
return std::unexpected{std::move(statement).error()};
|
||||
}
|
||||
if (auto bound = statement->bind_checked(
|
||||
1, ValueView{cursor.value_or(std::string_view{})});
|
||||
!bound) {
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
if (auto bound = statement->bind_checked(
|
||||
2, ValueView{static_cast<std::int64_t>(page + 1)});
|
||||
!bound) {
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
|
||||
ScanPage out;
|
||||
while (true) {
|
||||
auto row = statement->step();
|
||||
if (!row) {
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (!*row) {
|
||||
break;
|
||||
}
|
||||
auto key = statement->try_column_text(0);
|
||||
auto value = statement->try_column_blob(1);
|
||||
auto version = statement->try_column_int(2);
|
||||
if (!key || !value || !version) {
|
||||
return std::unexpected{invalid("KvStore: malformed scan row")};
|
||||
}
|
||||
if (out.items.size() == page) {
|
||||
out.next_cursor = out.items.back().key;
|
||||
break;
|
||||
}
|
||||
Entry entry;
|
||||
entry.value.assign(reinterpret_cast<const char*>(value->data()),
|
||||
value->size());
|
||||
entry.version = static_cast<Version>(*version);
|
||||
out.items.push_back(
|
||||
ScanItem{std::string{*key}, std::move(entry)});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
Void::Result::Result<Void::Sqlite::BackupReport>
|
||||
SqliteKvStore::backup_to(const std::filesystem::path& destination)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_db.backup_to(destination);
|
||||
}
|
||||
|
||||
Void::Result::Result<Void::Sqlite::BackupReport>
|
||||
SqliteKvStore::restore_from(const std::filesystem::path& source)
|
||||
{
|
||||
std::lock_guard lock{m_mutex};
|
||||
return m_db.restore_from(source);
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
|
||||
namespace NetworkedKv
|
||||
{
|
||||
Void::Result::Result<std::optional<WriteResult>>
|
||||
SqliteKvStore::lookup_operation(const RequestId& request) const
|
||||
{
|
||||
if (request.value.empty() ||
|
||||
request.value.size() > m_limits.max_request_id_bytes) {
|
||||
return std::unexpected{invalid("KvStore: invalid request id")};
|
||||
}
|
||||
std::lock_guard lock{m_mutex};
|
||||
auto statement = m_db.prepare(
|
||||
"SELECT outcome, version FROM operations WHERE request_id = ?");
|
||||
if (!statement) {
|
||||
return std::unexpected{std::move(statement).error()};
|
||||
}
|
||||
if (auto bound = statement->bind_checked(1, ValueView{request.value});
|
||||
!bound) {
|
||||
return std::unexpected{std::move(bound).error()};
|
||||
}
|
||||
auto row = statement->step();
|
||||
if (!row) {
|
||||
return std::unexpected{std::move(row).error()};
|
||||
}
|
||||
if (!*row) {
|
||||
return std::optional<WriteResult>{};
|
||||
}
|
||||
auto outcome = statement->try_column_int(0);
|
||||
auto version = statement->try_column_int(1);
|
||||
if (!outcome || !version) {
|
||||
return std::unexpected{invalid("KvStore: malformed operation")};
|
||||
}
|
||||
return std::optional<WriteResult>{WriteResult{
|
||||
outcome_from_int(static_cast<int>(*outcome)),
|
||||
static_cast<Version>(*version)}};
|
||||
}
|
||||
} // namespace NetworkedKv
|
||||
@@ -0,0 +1,400 @@
|
||||
#include "networked_kv/application.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
void config_validation()
|
||||
{
|
||||
NetworkedConfig bad;
|
||||
bad.listen_address.clear();
|
||||
assert(!bad.validate().has_value());
|
||||
|
||||
NetworkedConfig no_connections;
|
||||
no_connections.max_connections = 0;
|
||||
assert(!no_connections.validate().has_value());
|
||||
|
||||
NetworkedConfig ok;
|
||||
assert(ok.validate().has_value());
|
||||
}
|
||||
|
||||
void managed_mode_owns_the_host()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
|
||||
assert(app.has_value());
|
||||
|
||||
// Construction opens no listener or worker.
|
||||
const auto created = app->health();
|
||||
assert(created.state == ApplicationState::Created);
|
||||
assert(!created.ready);
|
||||
|
||||
assert(app->start().has_value());
|
||||
const auto running = app->health();
|
||||
assert(running.state == ApplicationState::Running);
|
||||
assert(running.managed);
|
||||
|
||||
auto report = app->stop();
|
||||
assert(report.has_value());
|
||||
assert(app->health().state == ApplicationState::Stopped);
|
||||
|
||||
// Idempotent.
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void embedded_mode_borrows_the_host()
|
||||
{
|
||||
auto host = Void::Runtime::Host::create();
|
||||
assert(host.has_value());
|
||||
assert(host->start().has_value());
|
||||
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Embedded;
|
||||
resources.borrowed_host = &*host;
|
||||
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
assert(app->health().state == ApplicationState::Running);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
// The borrowed host is not shut down by the composition.
|
||||
assert(host->is_running());
|
||||
(void)host->shutdown_blocking();
|
||||
}
|
||||
|
||||
void embedded_requires_a_host()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Embedded;
|
||||
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
|
||||
assert(!app.has_value());
|
||||
}
|
||||
|
||||
void http_listener_serves_kv()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
|
||||
const auto port = app->health().bound_port;
|
||||
assert(port != 0);
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(port);
|
||||
Void::Net::HttpClient client;
|
||||
|
||||
auto unauthorized = client.get(base + "/v1/kv/a");
|
||||
assert(unauthorized.has_value());
|
||||
assert(unauthorized->status == 401);
|
||||
|
||||
Void::Net::Request put;
|
||||
put.method = Void::Net::Method::Put;
|
||||
put.url = base + "/v1/kv/a";
|
||||
put.body = std::string{"one"};
|
||||
put.headers.push_back(
|
||||
Void::Net::Header{"authorization", "Bearer secret"});
|
||||
put.headers.push_back(Void::Net::Header{"x-request-id", "r1"});
|
||||
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
|
||||
auto created = client.send(put);
|
||||
assert(created.has_value());
|
||||
assert(created->status == 200);
|
||||
|
||||
auto got = client.get(
|
||||
base + "/v1/kv/a",
|
||||
{Void::Net::Header{"authorization", "Bearer secret"}});
|
||||
assert(got.has_value());
|
||||
assert(got->status == 200);
|
||||
assert(got->body == "one");
|
||||
|
||||
assert(app->stop().has_value());
|
||||
assert(app->health().bound_port == 0);
|
||||
}
|
||||
|
||||
void admin_listener_is_separate()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.admin_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
|
||||
const auto data_port = app->health().bound_port;
|
||||
const auto admin_port = app->admin_bound_port();
|
||||
assert(data_port != 0);
|
||||
assert(admin_port != 0);
|
||||
assert(admin_port != data_port);
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const std::string admin_base =
|
||||
"http://127.0.0.1:" + std::to_string(admin_port);
|
||||
auto live = client.get(admin_base + "/live");
|
||||
assert(live.has_value() && live->status == 200);
|
||||
auto ready = client.get(admin_base + "/ready");
|
||||
assert(ready.has_value() && ready->status == 200);
|
||||
auto metrics = client.get(admin_base + "/metrics");
|
||||
assert(metrics.has_value() && metrics->status == 200);
|
||||
assert(metrics->body.find("networked_kv_requests_total") !=
|
||||
std::string::npos);
|
||||
|
||||
// Administrative routes are not exposed on the data plane.
|
||||
const std::string data_base =
|
||||
"http://127.0.0.1:" + std::to_string(data_port);
|
||||
auto not_admin = client.get(data_base + "/live");
|
||||
assert(not_admin.has_value() && not_admin->status == 404);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
assert(app->admin_bound_port() == 0);
|
||||
}
|
||||
|
||||
void durable_profile_survives_restart()
|
||||
{
|
||||
const auto directory = std::filesystem::temp_directory_path() /
|
||||
("void-netapp-" + std::to_string(::getpid()));
|
||||
std::filesystem::remove_all(directory);
|
||||
std::filesystem::create_directories(directory);
|
||||
const std::string path = (directory / "kv.db").string();
|
||||
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
config.storage_path = path;
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
|
||||
Void::Net::Request put;
|
||||
put.method = Void::Net::Method::Put;
|
||||
put.url = base + "/v1/kv/persist";
|
||||
put.body = std::string{"durable"};
|
||||
put.headers.push_back(
|
||||
Void::Net::Header{"authorization", "Bearer secret"});
|
||||
put.headers.push_back(Void::Net::Header{"x-request-id", "p1"});
|
||||
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
|
||||
auto created = client.send(put);
|
||||
assert(created.has_value());
|
||||
assert(created->status == 200);
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
config.storage_path = path;
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
|
||||
auto got = client.get(
|
||||
base + "/v1/kv/persist",
|
||||
{Void::Net::Header{"authorization", "Bearer secret"}});
|
||||
assert(got.has_value());
|
||||
assert(got->status == 200);
|
||||
assert(got->body == "durable");
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
std::filesystem::remove_all(directory);
|
||||
}
|
||||
|
||||
void config_reload_publishes_a_new_generation()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
|
||||
// Reload before start is rejected and publishes nothing.
|
||||
assert(!app->reload(config).has_value());
|
||||
assert(app->config_generation() == 0);
|
||||
|
||||
assert(app->start().has_value());
|
||||
assert(app->config_generation() == 1);
|
||||
const auto port = app->health().bound_port;
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(port);
|
||||
Void::Net::HttpClient client;
|
||||
|
||||
// A restart-required change is rejected atomically.
|
||||
NetworkedConfig rebound = app->config();
|
||||
rebound.listen_address = "127.0.0.1:1";
|
||||
auto rejected = app->reload(rebound);
|
||||
assert(!rejected.has_value());
|
||||
assert(app->config_generation() == 1);
|
||||
assert(app->config().listen_address == "127.0.0.1:0");
|
||||
assert(app->health().bound_port == port);
|
||||
|
||||
// An invalid candidate is rejected before anything is applied.
|
||||
NetworkedConfig invalid = app->config();
|
||||
invalid.max_scan_page = 0;
|
||||
assert(!app->reload(invalid).has_value());
|
||||
assert(app->config_generation() == 1);
|
||||
|
||||
// The bearer token rotates live without rebinding the listener.
|
||||
NetworkedConfig rotated = app->config();
|
||||
rotated.bearer_token = "rotated";
|
||||
assert(app->reload(std::move(rotated)).has_value());
|
||||
assert(app->config_generation() == 2);
|
||||
assert(app->health().bound_port == port);
|
||||
|
||||
auto old_token = client.get(
|
||||
base + "/v1/kv/a",
|
||||
{Void::Net::Header{"authorization", "Bearer secret"}});
|
||||
assert(old_token.has_value());
|
||||
assert(old_token->status == 401);
|
||||
auto new_token = client.get(
|
||||
base + "/v1/kv/a",
|
||||
{Void::Net::Header{"authorization", "Bearer rotated"}});
|
||||
assert(new_token.has_value());
|
||||
assert(new_token->status == 404);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void durable_backup_and_restore_roundtrip()
|
||||
{
|
||||
const auto directory = std::filesystem::temp_directory_path() /
|
||||
("void-netapp-backup-" + std::to_string(::getpid()));
|
||||
std::filesystem::remove_all(directory);
|
||||
std::filesystem::create_directories(directory);
|
||||
const std::string path = (directory / "kv.db").string();
|
||||
const std::string backup = (directory / "kv.backup.db").string();
|
||||
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
config.storage_path = path;
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
const std::string base =
|
||||
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
|
||||
Void::Net::Request put;
|
||||
put.method = Void::Net::Method::Put;
|
||||
put.url = base + "/v1/kv/backed-up";
|
||||
put.body = std::string{"value"};
|
||||
put.headers.push_back(
|
||||
Void::Net::Header{"authorization", "Bearer secret"});
|
||||
put.headers.push_back(Void::Net::Header{"x-request-id", "b1"});
|
||||
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
|
||||
auto created = client.send(put);
|
||||
assert(created.has_value());
|
||||
assert(created->status == 200);
|
||||
|
||||
assert(app->backup_storage(backup).has_value());
|
||||
assert(std::filesystem::exists(backup));
|
||||
|
||||
// Mutate after the backup so restore is observable.
|
||||
Void::Net::Request overwrite = put;
|
||||
overwrite.body = std::string{"changed"};
|
||||
overwrite.headers[1].value = "b2";
|
||||
overwrite.headers[2] = Void::Net::Header{"if-match", "\"1\""};
|
||||
auto updated = client.send(overwrite);
|
||||
assert(updated.has_value());
|
||||
assert(updated->status == 200);
|
||||
|
||||
assert(app->restore_storage(backup).has_value());
|
||||
auto got = client.get(
|
||||
base + "/v1/kv/backed-up",
|
||||
{Void::Net::Header{"authorization", "Bearer secret"}});
|
||||
assert(got.has_value());
|
||||
assert(got->status == 200);
|
||||
assert(got->body == "value");
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
std::filesystem::remove_all(directory);
|
||||
}
|
||||
void discovery_registers_the_live_endpoint()
|
||||
{
|
||||
// Enabling discovery without an instance identity is rejected.
|
||||
NetworkedConfig missing_identity;
|
||||
missing_identity.discovery_enabled = true;
|
||||
assert(!missing_identity.validate().has_value());
|
||||
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
NetworkedConfig config;
|
||||
config.listen_address = "127.0.0.1:0";
|
||||
config.bearer_token = "secret";
|
||||
config.discovery_enabled = true;
|
||||
config.discovery_instance = "test-node";
|
||||
auto app = NetworkedApplication::create(resources, config);
|
||||
assert(app.has_value());
|
||||
assert(app->directory() != nullptr);
|
||||
assert(app->start().has_value());
|
||||
|
||||
const auto port = app->health().bound_port;
|
||||
assert(app->health().discovery_registered);
|
||||
assert(app->health().discovery_error.empty());
|
||||
auto records = app->directory()->resolve("networked-kv");
|
||||
assert(records.has_value());
|
||||
assert(records->size() == 1);
|
||||
assert((*records)[0].instance == "test-node");
|
||||
assert((*records)[0].endpoint.port == port);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
assert(!app->directory()->registered());
|
||||
auto after = app->directory()->resolve("networked-kv");
|
||||
assert(after.has_value());
|
||||
assert(after->empty());
|
||||
|
||||
// The directory is optional and absent by default.
|
||||
auto plain = NetworkedApplication::create(resources, NetworkedConfig{});
|
||||
assert(plain.has_value());
|
||||
assert(plain->directory() == nullptr);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
config_validation();
|
||||
managed_mode_owns_the_host();
|
||||
embedded_mode_borrows_the_host();
|
||||
embedded_requires_a_host();
|
||||
http_listener_serves_kv();
|
||||
admin_listener_is_separate();
|
||||
durable_profile_survives_restart();
|
||||
config_reload_publishes_a_new_generation();
|
||||
durable_backup_and_restore_roundtrip();
|
||||
discovery_registers_the_live_endpoint();
|
||||
std::puts("networked-kv lifecycle ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
#include "networked_kv/domain.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
void versioned_lifecycle()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
auto created = store.put("a", "one", Precondition::absent(), {"r1"});
|
||||
assert(created.has_value());
|
||||
assert(created->outcome == WriteOutcome::Applied);
|
||||
assert(created->version == 1);
|
||||
|
||||
auto got = store.get("a");
|
||||
assert(got.has_value() && got->has_value());
|
||||
assert((*got)->value == "one");
|
||||
|
||||
// Absent precondition no longer holds.
|
||||
auto conflict = store.put("a", "two", Precondition::absent(), {"r2"});
|
||||
assert(conflict.has_value());
|
||||
assert(conflict->outcome == WriteOutcome::Conflict);
|
||||
|
||||
auto updated =
|
||||
store.put("a", "two", Precondition::at_version(1), {"r3"});
|
||||
assert(updated.has_value());
|
||||
assert(updated->outcome == WriteOutcome::Applied);
|
||||
assert(updated->version == 2);
|
||||
|
||||
// Replaying the same request id returns the recorded outcome without
|
||||
// applying the mutation again.
|
||||
auto replay =
|
||||
store.put("a", "ignored", Precondition::at_version(2), {"r3"});
|
||||
assert(replay.has_value());
|
||||
assert(replay->outcome == WriteOutcome::Applied);
|
||||
assert(replay->version == 2);
|
||||
auto current = store.get("a");
|
||||
assert(current.has_value() && current->has_value());
|
||||
assert((*current)->value == "two");
|
||||
assert((*current)->version == 2);
|
||||
|
||||
auto stale = store.erase("a", Precondition::at_version(1), {"r4"});
|
||||
assert(stale.has_value());
|
||||
assert(stale->outcome == WriteOutcome::Conflict);
|
||||
|
||||
auto erased = store.erase("a", Precondition::at_version(2), {"r5"});
|
||||
assert(erased.has_value());
|
||||
assert(erased->outcome == WriteOutcome::Applied);
|
||||
assert(!store.get("a")->has_value());
|
||||
|
||||
auto missing = store.erase("missing", Precondition::absent(), {"r6"});
|
||||
assert(missing.has_value());
|
||||
assert(missing->outcome == WriteOutcome::NotFound);
|
||||
}
|
||||
|
||||
void input_validation()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
assert(!store.put("", "x", Precondition::absent(), {"r"}).has_value());
|
||||
assert(!store.put("k", "x", Precondition::absent(), {""}).has_value());
|
||||
|
||||
MemoryKvStore small{Limits{.max_key_bytes = 2, .max_value_bytes = 2}};
|
||||
assert(!small.put("key", "x", Precondition::absent(), {"r"}).has_value());
|
||||
assert(!small.put("k", "long", Precondition::absent(), {"r"}).has_value());
|
||||
}
|
||||
|
||||
void bounded_scan()
|
||||
{
|
||||
MemoryKvStore store{Limits{.max_scan_page = 2}};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const std::string key(1, static_cast<char>('a' + i));
|
||||
auto written = store.put(key, "v", Precondition::absent(),
|
||||
{"s" + std::to_string(i)});
|
||||
assert(written.has_value());
|
||||
}
|
||||
|
||||
std::vector<std::string> keys;
|
||||
std::optional<std::string> cursor;
|
||||
for (;;) {
|
||||
auto page = store.scan(
|
||||
cursor ? std::optional<std::string_view>{*cursor} : std::nullopt);
|
||||
assert(page.has_value());
|
||||
assert(page->items.size() <= 2);
|
||||
for (const auto& item : page->items) {
|
||||
keys.push_back(item.key);
|
||||
}
|
||||
if (!page->next_cursor) {
|
||||
break;
|
||||
}
|
||||
cursor = page->next_cursor;
|
||||
}
|
||||
assert(keys.size() == 5);
|
||||
assert(keys.front() == "a");
|
||||
assert(keys.back() == "e");
|
||||
}
|
||||
|
||||
void bounded_operation_records()
|
||||
{
|
||||
MemoryKvStore store{Limits{.max_operation_records = 2}};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const auto precondition = i == 0 ? Precondition::absent()
|
||||
: Precondition::at_version(
|
||||
static_cast<Version>(i));
|
||||
auto written = store.put("k", "v" + std::to_string(i), precondition,
|
||||
{"b" + std::to_string(i)});
|
||||
assert(written.has_value());
|
||||
assert(written->outcome == WriteOutcome::Applied);
|
||||
}
|
||||
// The store keeps working after evicting old operation records.
|
||||
auto got = store.get("k");
|
||||
assert(got.has_value() && got->has_value());
|
||||
assert((*got)->version == 5);
|
||||
}
|
||||
|
||||
void operation_lookup_reports_recorded_outcomes()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
auto applied =
|
||||
store.put("k", "v", Precondition::absent(), {"op-1"});
|
||||
assert(applied.has_value());
|
||||
assert(applied->outcome == WriteOutcome::Applied);
|
||||
|
||||
// A replayed request id resolves to the original outcome.
|
||||
auto replayed = store.put("k", "ignored", Precondition::absent(),
|
||||
{"op-1"});
|
||||
assert(replayed.has_value());
|
||||
assert(replayed->version == applied->version);
|
||||
|
||||
auto known = store.lookup_operation({"op-1"});
|
||||
assert(known.has_value() && known->has_value());
|
||||
assert((*known)->outcome == WriteOutcome::Applied);
|
||||
assert((*known)->version == applied->version);
|
||||
|
||||
// Unknown ids are absent (not an error), and invalid ids are errors.
|
||||
auto absent = store.lookup_operation({"never-used"});
|
||||
assert(absent.has_value() && !absent->has_value());
|
||||
assert(!store.lookup_operation({""}).has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
versioned_lifecycle();
|
||||
input_validation();
|
||||
bounded_scan();
|
||||
bounded_operation_records();
|
||||
operation_lookup_reports_recorded_outcomes();
|
||||
std::puts("networked-kv domain ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
#include "networked_kv/http_api.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
HttpRequest make_request(std::string method, std::string target,
|
||||
std::string body = {})
|
||||
{
|
||||
HttpRequest request;
|
||||
request.method = std::move(method);
|
||||
request.target = std::move(target);
|
||||
request.body = std::move(body);
|
||||
return request;
|
||||
}
|
||||
|
||||
HttpRequest authed(HttpRequest request)
|
||||
{
|
||||
request.headers["authorization"] = "Bearer secret";
|
||||
return request;
|
||||
}
|
||||
|
||||
void bearer_auth_is_required()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
|
||||
assert(api.handle(make_request("GET", "/v1/kv/a")).status == 401);
|
||||
|
||||
auto wrong = make_request("GET", "/v1/kv/a");
|
||||
wrong.headers["authorization"] = "Bearer wrong";
|
||||
assert(api.handle(wrong).status == 401);
|
||||
assert(api.metrics().unauthorized == 2);
|
||||
|
||||
// Fail closed when no token is configured.
|
||||
KvApi unconfigured{store, ApiConfig{}};
|
||||
assert(unconfigured.handle(authed(make_request("GET", "/v1/kv/a")))
|
||||
.status == 401);
|
||||
}
|
||||
|
||||
void kv_lifecycle_over_http()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
|
||||
auto put = authed(make_request("PUT", "/v1/kv/a", "one"));
|
||||
put.headers["x-request-id"] = "r1";
|
||||
put.headers["if-none-match"] = "*";
|
||||
auto created = api.handle(put);
|
||||
assert(created.status == 200);
|
||||
assert(created.headers.at("etag") == "\"1\"");
|
||||
|
||||
auto get = authed(make_request("GET", "/v1/kv/a"));
|
||||
auto got = api.handle(get);
|
||||
assert(got.status == 200);
|
||||
assert(got.body == "one");
|
||||
assert(got.headers.at("etag") == "\"1\"");
|
||||
|
||||
auto stale = authed(make_request("PUT", "/v1/kv/a", "two"));
|
||||
stale.headers["x-request-id"] = "r2";
|
||||
stale.headers["if-match"] = "\"9\"";
|
||||
assert(api.handle(stale).status == 412);
|
||||
|
||||
// Replaying the same request id returns the recorded outcome and does
|
||||
// not apply the mutation again.
|
||||
auto replay = authed(make_request("PUT", "/v1/kv/a", "ignored"));
|
||||
replay.headers["x-request-id"] = "r1";
|
||||
replay.headers["if-none-match"] = "*";
|
||||
auto replayed = api.handle(replay);
|
||||
assert(replayed.status == 200);
|
||||
assert(replayed.headers.at("etag") == "\"1\"");
|
||||
assert(api.handle(get).body == "one");
|
||||
|
||||
auto delete_stale = authed(make_request("DELETE", "/v1/kv/a"));
|
||||
delete_stale.headers["x-request-id"] = "r3";
|
||||
delete_stale.headers["if-match"] = "\"9\"";
|
||||
assert(api.handle(delete_stale).status == 412);
|
||||
|
||||
auto remove = authed(make_request("DELETE", "/v1/kv/a"));
|
||||
remove.headers["x-request-id"] = "r4";
|
||||
remove.headers["if-match"] = "\"1\"";
|
||||
assert(api.handle(remove).status == 204);
|
||||
assert(api.handle(get).status == 404);
|
||||
}
|
||||
|
||||
void request_validation()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret",
|
||||
.max_body_bytes = 4}};
|
||||
|
||||
auto oversized = authed(make_request("PUT", "/v1/kv/a", "12345"));
|
||||
oversized.headers["x-request-id"] = "r";
|
||||
oversized.headers["if-none-match"] = "*";
|
||||
assert(api.handle(oversized).status == 413);
|
||||
|
||||
auto no_id = authed(make_request("PUT", "/v1/kv/a", "x"));
|
||||
no_id.headers["if-none-match"] = "*";
|
||||
assert(api.handle(no_id).status == 428);
|
||||
|
||||
auto no_precondition = authed(make_request("PUT", "/v1/kv/a", "x"));
|
||||
no_precondition.headers["x-request-id"] = "r";
|
||||
assert(api.handle(no_precondition).status == 428);
|
||||
|
||||
assert(api.handle(authed(make_request("POST", "/v1/kv/a")))
|
||||
.status == 405);
|
||||
assert(api.handle(authed(make_request("GET", "/v1/nope"))).status ==
|
||||
404);
|
||||
}
|
||||
|
||||
void operation_status_endpoint()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
|
||||
auto put = authed(make_request("PUT", "/v1/kv/a", "one"));
|
||||
put.headers["x-request-id"] = "op-1";
|
||||
put.headers["if-none-match"] = "*";
|
||||
assert(api.handle(put).status == 200);
|
||||
|
||||
auto known =
|
||||
api.handle(authed(make_request("GET", "/v1/operations/op-1")));
|
||||
assert(known.status == 200);
|
||||
assert(known.body.find("\"outcome\":\"applied\"") != std::string::npos);
|
||||
|
||||
// Absence is explicitly unknown, not a 404 claiming no commit.
|
||||
auto unknown =
|
||||
api.handle(authed(make_request("GET", "/v1/operations/missing")));
|
||||
assert(unknown.status == 200);
|
||||
assert(unknown.body.find("\"outcome\":\"unknown\"") !=
|
||||
std::string::npos);
|
||||
|
||||
// The endpoint requires authentication like the data plane.
|
||||
assert(api.handle(make_request("GET", "/v1/operations/op-1")).status ==
|
||||
401);
|
||||
assert(api.handle(authed(make_request("POST", "/v1/operations/op-1")))
|
||||
.status == 405);
|
||||
}
|
||||
|
||||
void scan_is_bounded()
|
||||
{
|
||||
MemoryKvStore store{Limits{.max_scan_page = 2}};
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret",
|
||||
.max_scan_limit = 2}};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
auto put = authed(make_request(
|
||||
"PUT", "/v1/kv/" + std::string(1, static_cast<char>('a' + i)),
|
||||
"v"));
|
||||
put.headers["x-request-id"] = "s" + std::to_string(i);
|
||||
put.headers["if-none-match"] = "*";
|
||||
assert(api.handle(put).status == 200);
|
||||
}
|
||||
|
||||
auto page = api.handle(authed(make_request("GET", "/v1/scan")));
|
||||
assert(page.status == 200);
|
||||
// Two items retained, and a cursor is offered for the rest.
|
||||
std::size_t keys = 0;
|
||||
for (std::size_t pos = 0;
|
||||
(pos = page.body.find("\"key\":", pos)) != std::string::npos;
|
||||
pos += 6) {
|
||||
++keys;
|
||||
}
|
||||
assert(keys == 2);
|
||||
assert(page.body.find("\"next_cursor\":null") == std::string::npos);
|
||||
|
||||
assert(api.handle(authed(make_request("GET", "/v1/scan?limit=0")))
|
||||
.status == 400);
|
||||
}
|
||||
|
||||
void admin_views_are_bounded()
|
||||
{
|
||||
MemoryKvStore store;
|
||||
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
|
||||
assert(api.admin(make_request("GET", "/live")).status == 200);
|
||||
assert(api.admin(make_request("GET", "/ready")).status == 200);
|
||||
api.set_ready(false);
|
||||
assert(api.admin(make_request("GET", "/ready")).status == 503);
|
||||
|
||||
(void)api.handle(authed(make_request("GET", "/v1/kv/a")));
|
||||
auto metrics = api.admin(make_request("GET", "/metrics"));
|
||||
assert(metrics.status == 200);
|
||||
assert(metrics.body.find("networked_kv_requests_total") !=
|
||||
std::string::npos);
|
||||
// No credential material in the admin output.
|
||||
assert(metrics.body.find("secret") == std::string::npos);
|
||||
assert(api.admin(make_request("POST", "/live")).status == 405);
|
||||
assert(api.admin(make_request("GET", "/unknown")).status == 404);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
bearer_auth_is_required();
|
||||
kv_lifecycle_over_http();
|
||||
request_validation();
|
||||
scan_is_bounded();
|
||||
operation_status_endpoint();
|
||||
admin_views_are_bounded();
|
||||
std::puts("networked-kv http api ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
#include "networked_kv/job_service.hpp"
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
JobServiceConfig config()
|
||||
{
|
||||
JobServiceConfig cfg;
|
||||
cfg.max_attempts = 2;
|
||||
cfg.retry_delay = std::chrono::milliseconds{0};
|
||||
cfg.visibility_timeout = std::chrono::milliseconds{500};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
void submit_requires_initialization()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobService service{queue};
|
||||
assert(!service.submit("payload").has_value());
|
||||
}
|
||||
|
||||
void successful_job_is_acked_and_tracked()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobService service{queue, config()};
|
||||
assert(service.initialize().has_value());
|
||||
|
||||
auto id = service.submit("payload");
|
||||
assert(id.has_value());
|
||||
assert(service.status(*id)->state == JobState::Submitted);
|
||||
|
||||
int calls = 0;
|
||||
auto processed = service.process_one(
|
||||
[&](std::string_view payload, std::uint32_t attempt) {
|
||||
++calls;
|
||||
assert(payload == "payload");
|
||||
assert(attempt == 1);
|
||||
return Void::Result::Result<void>{};
|
||||
});
|
||||
assert(processed.has_value() && processed->has_value());
|
||||
assert((*processed)->state == JobState::Succeeded);
|
||||
assert(calls == 1);
|
||||
|
||||
const auto status = service.status(*id);
|
||||
assert(status.has_value());
|
||||
assert(status->state == JobState::Succeeded);
|
||||
assert(status->attempts == 1);
|
||||
|
||||
// Acked: no redelivery and an empty receive.
|
||||
auto none = service.process_one([](std::string_view,
|
||||
std::uint32_t) {
|
||||
return Void::Result::Result<void>{};
|
||||
});
|
||||
assert(none.has_value() && !none->has_value());
|
||||
|
||||
// Unknown ids are an explicit not-found error.
|
||||
auto missing = service.status("never-submitted");
|
||||
assert(!missing.has_value());
|
||||
assert(missing.error().kind() == Void::Result::ErrorKind::not_found);
|
||||
}
|
||||
|
||||
void failing_job_retries_then_dead_letters()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobServiceConfig cfg = config();
|
||||
cfg.max_attempts = 2;
|
||||
JobService service{queue, cfg};
|
||||
assert(service.initialize().has_value());
|
||||
auto id = service.submit("poison");
|
||||
assert(id.has_value());
|
||||
|
||||
const auto failing = [](std::string_view, std::uint32_t) {
|
||||
return Void::Result::Result<void>{std::unexpected{
|
||||
Void::Result::Error{Void::Result::ErrorKind::internal,
|
||||
"handler exploded"}}};
|
||||
};
|
||||
|
||||
auto first = service.process_one(failing);
|
||||
assert(first.has_value() && first->has_value());
|
||||
assert((*first)->attempts == 1);
|
||||
assert((*first)->state == JobState::RetryScheduled);
|
||||
assert((*first)->last_error == "handler exploded");
|
||||
|
||||
// Retry is immediately available (zero delay) and exhausts attempts.
|
||||
auto second = service.process_one(failing);
|
||||
assert(second.has_value() && second->has_value());
|
||||
assert((*second)->attempts == 2);
|
||||
assert((*second)->state == JobState::DeadLettered);
|
||||
|
||||
auto dead = service.dead_letters();
|
||||
assert(dead.has_value());
|
||||
assert(dead->size() == 1);
|
||||
assert((*dead)[0].message.id == *id);
|
||||
assert((*dead)[0].attempts == 2);
|
||||
}
|
||||
|
||||
void throwing_handler_is_a_recorded_failure()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobService service{queue, config()};
|
||||
assert(service.initialize().has_value());
|
||||
assert(service.submit("boom").has_value());
|
||||
|
||||
auto processed = service.process_one(
|
||||
[](std::string_view, std::uint32_t) -> Void::Result::Result<void> {
|
||||
throw std::runtime_error{"unexpected"};
|
||||
});
|
||||
assert(processed.has_value() && processed->has_value());
|
||||
assert((*processed)->state == JobState::RetryScheduled);
|
||||
assert((*processed)->last_error.find("unexpected") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
void scheduler_driven_maintenance_reclaims_expired_deliveries()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobServiceConfig cfg = config();
|
||||
cfg.visibility_timeout = std::chrono::milliseconds{50};
|
||||
JobService service{queue, cfg};
|
||||
assert(service.initialize().has_value());
|
||||
assert(service.submit("payload").has_value());
|
||||
|
||||
// Take the delivery in flight and let its visibility expire.
|
||||
auto in_flight =
|
||||
queue.try_receive(cfg.queue_name, cfg.group_name);
|
||||
assert(in_flight.has_value() && in_flight->has_value());
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{80});
|
||||
|
||||
auto scheduler = Void::Scheduler::Scheduler::create();
|
||||
assert(scheduler.has_value());
|
||||
auto job = service.schedule_maintenance(*scheduler,
|
||||
std::chrono::seconds{1});
|
||||
assert(job.has_value());
|
||||
|
||||
// The scheduler is pure: the caller drives it. A tick materializes due
|
||||
// occurrences and dispatch_one executes at most one ready occurrence;
|
||||
// its handler reaps the expired delivery.
|
||||
assert(scheduler->tick().has_value());
|
||||
(void)scheduler->dispatch_one();
|
||||
|
||||
auto processed = service.process_one([](std::string_view,
|
||||
std::uint32_t attempt) {
|
||||
assert(attempt == 2);
|
||||
return Void::Result::Result<void>{};
|
||||
});
|
||||
assert(processed.has_value() && processed->has_value());
|
||||
assert((*processed)->state == JobState::Succeeded);
|
||||
assert((*processed)->attempts == 2);
|
||||
|
||||
assert(scheduler->close_and_join().has_value());
|
||||
}
|
||||
|
||||
void tracked_status_is_bounded()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue queue;
|
||||
JobServiceConfig cfg = config();
|
||||
cfg.max_tracked_jobs = 2;
|
||||
JobService service{queue, cfg};
|
||||
assert(service.initialize().has_value());
|
||||
const auto first = service.submit("a");
|
||||
const auto second = service.submit("b");
|
||||
const auto third = service.submit("c");
|
||||
assert(first.has_value() && second.has_value() && third.has_value());
|
||||
// Oldest record evicted; recent ones retained.
|
||||
assert(!service.status(*first).has_value());
|
||||
assert(service.status(*second).has_value());
|
||||
assert(service.status(*third).has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
submit_requires_initialization();
|
||||
successful_job_is_acked_and_tracked();
|
||||
failing_job_retries_then_dead_letters();
|
||||
throwing_handler_is_a_recorded_failure();
|
||||
scheduler_driven_maintenance_reclaims_expired_deliveries();
|
||||
tracked_status_is_bounded();
|
||||
std::puts("networked-kv job service ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
#include "networked_kv/application.hpp"
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
/// Minimal raw HTTP peer so framing/overload behavior is observable
|
||||
/// without the library's own client normalizing it.
|
||||
class RawPeer
|
||||
{
|
||||
public:
|
||||
|
||||
explicit RawPeer(std::uint16_t port)
|
||||
{
|
||||
m_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
assert(m_fd >= 0);
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = htons(port);
|
||||
assert(::connect(m_fd, reinterpret_cast<sockaddr*>(&addr),
|
||||
sizeof(addr)) == 0);
|
||||
}
|
||||
|
||||
~RawPeer()
|
||||
{
|
||||
if (m_fd >= 0) {
|
||||
(void)::close(m_fd);
|
||||
}
|
||||
}
|
||||
|
||||
RawPeer(const RawPeer&) = delete;
|
||||
RawPeer& operator=(const RawPeer&) = delete;
|
||||
|
||||
void send(std::string_view bytes) const
|
||||
{
|
||||
std::size_t offset = 0;
|
||||
while (offset < bytes.size()) {
|
||||
const ssize_t written =
|
||||
::send(m_fd, bytes.data() + offset,
|
||||
bytes.size() - offset, MSG_NOSIGNAL);
|
||||
assert(written > 0);
|
||||
offset += static_cast<std::size_t>(written);
|
||||
}
|
||||
}
|
||||
|
||||
/// Read until the server closes or `timeout` elapses.
|
||||
std::string read_until_closed(
|
||||
std::chrono::milliseconds timeout = std::chrono::seconds{5})
|
||||
{
|
||||
std::string out;
|
||||
const auto deadline =
|
||||
std::chrono::steady_clock::now() + timeout;
|
||||
for (;;) {
|
||||
const auto remaining = deadline - std::chrono::steady_clock::now();
|
||||
if (remaining <= std::chrono::milliseconds::zero()) {
|
||||
break;
|
||||
}
|
||||
pollfd pfd{.fd = m_fd, .events = POLLIN, .revents = 0};
|
||||
const int ready = ::poll(
|
||||
&pfd, 1,
|
||||
static_cast<int>(std::min<long long>(
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
remaining)
|
||||
.count(),
|
||||
1000)));
|
||||
if (ready <= 0) {
|
||||
if (ready == 0) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
char buffer[4096];
|
||||
const ssize_t read = ::recv(m_fd, buffer, sizeof(buffer), 0);
|
||||
if (read <= 0) {
|
||||
break;
|
||||
}
|
||||
out.append(buffer, static_cast<std::size_t>(read));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] int fd() const noexcept { return m_fd; }
|
||||
|
||||
private:
|
||||
|
||||
int m_fd{-1};
|
||||
};
|
||||
|
||||
std::string raw_exchange(std::uint16_t port, std::string_view raw)
|
||||
{
|
||||
RawPeer peer{port};
|
||||
peer.send(raw);
|
||||
(void)::shutdown(peer.fd(), SHUT_WR);
|
||||
return peer.read_until_closed();
|
||||
}
|
||||
|
||||
NetworkedConfig config()
|
||||
{
|
||||
NetworkedConfig cfg;
|
||||
cfg.listen_address = "127.0.0.1:0";
|
||||
cfg.admin_address = "127.0.0.1:0";
|
||||
cfg.bearer_token = "secret";
|
||||
cfg.read_timeout = std::chrono::milliseconds{200};
|
||||
cfg.write_timeout = std::chrono::milliseconds{200};
|
||||
return cfg;
|
||||
}
|
||||
|
||||
ApplicationResources managed()
|
||||
{
|
||||
ApplicationResources resources;
|
||||
resources.ownership = ResourceOwnership::Managed;
|
||||
return resources;
|
||||
}
|
||||
|
||||
void malformed_framing_is_rejected()
|
||||
{
|
||||
auto app = NetworkedApplication::create(managed(), config());
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
const auto port = app->health().bound_port;
|
||||
|
||||
assert(raw_exchange(port, "NOT-HTTP\r\n\r\n")
|
||||
.starts_with("HTTP/1.1 400"));
|
||||
// Conflicting framing (smuggling shape) is rejected before routing.
|
||||
assert(raw_exchange(port,
|
||||
"POST /v1/kv/a HTTP/1.1\r\nHost: x\r\n"
|
||||
"Content-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n"
|
||||
"0\r\n\r\n")
|
||||
.starts_with("HTTP/1.1 400"));
|
||||
// A request line without a version is malformed.
|
||||
assert(raw_exchange(port, "GET /v1/kv/a\r\n\r\n")
|
||||
.starts_with("HTTP/1.1 400"));
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void oversized_header_and_body_are_bounded()
|
||||
{
|
||||
NetworkedConfig cfg = config();
|
||||
cfg.max_header_bytes = 512;
|
||||
cfg.max_request_bytes = 64;
|
||||
auto app = NetworkedApplication::create(managed(), cfg);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
const auto port = app->health().bound_port;
|
||||
|
||||
std::string huge = "GET /v1/kv/a HTTP/1.1\r\nHost: x\r\nX-Huge: ";
|
||||
huge += std::string(2000, 'H');
|
||||
huge += "\r\n\r\n";
|
||||
assert(raw_exchange(port, huge).starts_with("HTTP/1.1 431"));
|
||||
|
||||
std::string body = "PUT /v1/kv/a HTTP/1.1\r\nHost: x\r\n";
|
||||
body += "Authorization: Bearer secret\r\nX-Request-Id: r\r\n";
|
||||
body += "If-None-Match: *\r\nContent-Length: 100\r\n\r\n";
|
||||
body += std::string(100, 'B');
|
||||
assert(raw_exchange(port, body).starts_with("HTTP/1.1 413"));
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void pipelining_and_keep_alive_preserve_order()
|
||||
{
|
||||
auto app = NetworkedApplication::create(managed(), config());
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
const auto port = app->health().bound_port;
|
||||
|
||||
RawPeer peer{port};
|
||||
const std::string first =
|
||||
"GET /v1/kv/missing HTTP/1.1\r\nHost: x\r\n"
|
||||
"Authorization: Bearer secret\r\n\r\n";
|
||||
// Two pipelined requests: the 404 for the missing key, then a 401 for
|
||||
// the unauthenticated one, in that order.
|
||||
peer.send(first +
|
||||
"GET /v1/kv/missing HTTP/1.1\r\nHost: x\r\n\r\n");
|
||||
(void)::shutdown(peer.fd(), SHUT_WR);
|
||||
const std::string responses = peer.read_until_closed();
|
||||
const auto first_response = responses.find("HTTP/1.1 404");
|
||||
const auto second_response = responses.find("HTTP/1.1 401");
|
||||
assert(first_response != std::string::npos);
|
||||
assert(second_response != std::string::npos);
|
||||
assert(first_response < second_response);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void slow_header_is_bounded_by_the_read_timeout()
|
||||
{
|
||||
auto app = NetworkedApplication::create(managed(), config());
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
const auto port = app->health().bound_port;
|
||||
|
||||
RawPeer peer{port};
|
||||
peer.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n");
|
||||
const auto begin = std::chrono::steady_clock::now();
|
||||
const std::string response =
|
||||
peer.read_until_closed(std::chrono::seconds{5});
|
||||
const auto elapsed = std::chrono::steady_clock::now() - begin;
|
||||
// Bounded: the 200 ms read timeout ends the connection well before
|
||||
// the client-side 5 second cap.
|
||||
assert(response.empty());
|
||||
assert(elapsed < std::chrono::seconds{4});
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
|
||||
void overload_returns_503_while_admin_stays_responsive()
|
||||
{
|
||||
NetworkedConfig cfg = config();
|
||||
cfg.max_connections = 1;
|
||||
auto app = NetworkedApplication::create(managed(), cfg);
|
||||
assert(app.has_value());
|
||||
assert(app->start().has_value());
|
||||
const auto port = app->health().bound_port;
|
||||
const auto admin_port = app->admin_bound_port();
|
||||
|
||||
// Occupy the only admitted connection with a partial request.
|
||||
RawPeer held{port};
|
||||
held.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n");
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{50});
|
||||
|
||||
RawPeer second{port};
|
||||
second.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n\r\n");
|
||||
const std::string rejected = second.read_until_closed();
|
||||
assert(rejected.starts_with("HTTP/1.1 503"));
|
||||
|
||||
// The administrative listener has its own admission reserve.
|
||||
Void::Net::HttpClient client;
|
||||
auto live = client.get("http://127.0.0.1:" +
|
||||
std::to_string(admin_port) + "/live");
|
||||
assert(live.has_value());
|
||||
assert(live->status == 200);
|
||||
|
||||
assert(app->stop().has_value());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
malformed_framing_is_rejected();
|
||||
oversized_header_and_body_are_bounded();
|
||||
pipelining_and_keep_alive_preserve_order();
|
||||
slow_header_is_bounded_by_the_read_timeout();
|
||||
overload_returns_503_while_admin_stays_responsive();
|
||||
std::puts("networked-kv protocol matrix ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#include "networked_kv/service_directory.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
ServiceDirectoryConfig config()
|
||||
{
|
||||
ServiceDirectoryConfig cfg;
|
||||
cfg.service_name = "networked-kv";
|
||||
cfg.instance_id = "node-1";
|
||||
return cfg;
|
||||
}
|
||||
|
||||
void registration_resolves_and_deregisters()
|
||||
{
|
||||
ServiceDirectory directory{config()};
|
||||
assert(!directory.registered());
|
||||
assert(directory.register_endpoint(8080).has_value());
|
||||
assert(directory.registered());
|
||||
assert(directory.active_records() == 1);
|
||||
|
||||
// Idempotent while active.
|
||||
assert(directory.register_endpoint(9090).has_value());
|
||||
assert(directory.active_records() == 1);
|
||||
|
||||
auto records = directory.resolve("networked-kv");
|
||||
assert(records.has_value());
|
||||
assert(records->size() == 1);
|
||||
assert((*records)[0].instance == "node-1");
|
||||
assert((*records)[0].endpoint.port == 8080);
|
||||
|
||||
directory.deregister();
|
||||
assert(!directory.registered());
|
||||
assert(directory.active_records() == 0);
|
||||
auto empty = directory.resolve("networked-kv");
|
||||
assert(empty.has_value());
|
||||
assert(empty->empty());
|
||||
// Idempotent.
|
||||
directory.deregister();
|
||||
}
|
||||
|
||||
void registration_requires_identity_and_port()
|
||||
{
|
||||
ServiceDirectory no_id{ServiceDirectoryConfig{}};
|
||||
assert(!no_id.register_endpoint(8080).has_value());
|
||||
ServiceDirectory directory{config()};
|
||||
assert(!directory.register_endpoint(0).has_value());
|
||||
}
|
||||
|
||||
void provider_partition_does_not_break_registration()
|
||||
{
|
||||
ServiceDirectory directory{config()};
|
||||
assert(directory.register_endpoint(8080).has_value());
|
||||
|
||||
// The upstream directory provider becomes unavailable (partition).
|
||||
Void::Discovery::Error error;
|
||||
directory.set_provider_health(Void::Discovery::Freshness::Unavailable,
|
||||
error);
|
||||
|
||||
// Default policy refuses stale data...
|
||||
auto strict = directory.resolve("networked-kv");
|
||||
assert(!strict.has_value());
|
||||
// ...but the explicit stale policy still sees the last known records.
|
||||
Void::Discovery::ResolvePolicy stale;
|
||||
stale.allow_stale = true;
|
||||
auto tolerated = directory.resolve("networked-kv", stale);
|
||||
assert(tolerated.has_value());
|
||||
assert(tolerated->size() == 1);
|
||||
|
||||
// The local registration survives the provider outage.
|
||||
assert(directory.registered());
|
||||
assert(directory.active_records() == 1);
|
||||
|
||||
// Recovery restores fresh resolution.
|
||||
directory.set_provider_health(Void::Discovery::Freshness::Fresh);
|
||||
auto recovered = directory.resolve("networked-kv");
|
||||
assert(recovered.has_value());
|
||||
assert(recovered->size() == 1);
|
||||
}
|
||||
|
||||
void unknown_service_resolves_empty()
|
||||
{
|
||||
ServiceDirectory directory{config()};
|
||||
assert(directory.register_endpoint(8080).has_value());
|
||||
auto records = directory.resolve("other-service");
|
||||
assert(records.has_value());
|
||||
assert(records->empty());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
registration_resolves_and_deregisters();
|
||||
registration_requires_identity_and_port();
|
||||
provider_partition_does_not_break_registration();
|
||||
unknown_service_resolves_empty();
|
||||
std::puts("networked-kv service directory ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#include "networked_kv/sqlite_store.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace NetworkedKv;
|
||||
|
||||
std::filesystem::path temp_database()
|
||||
{
|
||||
const auto directory =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("void-kv-sqlite-" + std::to_string(::getpid()));
|
||||
std::filesystem::create_directories(directory);
|
||||
return directory / "kv.db";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto path = temp_database();
|
||||
std::filesystem::remove_all(path.parent_path());
|
||||
std::filesystem::create_directories(path.parent_path());
|
||||
|
||||
{
|
||||
auto store = SqliteKvStore::open(path);
|
||||
assert(store.has_value());
|
||||
auto& kv = **store;
|
||||
|
||||
auto created = kv.put("a", "one", Precondition::absent(), {"r1"});
|
||||
assert(created.has_value());
|
||||
assert(created->outcome == WriteOutcome::Applied);
|
||||
assert(created->version == 1);
|
||||
|
||||
auto conflict = kv.put("a", "two", Precondition::absent(), {"r2"});
|
||||
assert(conflict.has_value());
|
||||
assert(conflict->outcome == WriteOutcome::Conflict);
|
||||
|
||||
auto updated = kv.put("a", "two", Precondition::at_version(1), {"r3"});
|
||||
assert(updated.has_value());
|
||||
assert(updated->outcome == WriteOutcome::Applied);
|
||||
assert(updated->version == 2);
|
||||
|
||||
// Idempotent replay does not mutate the row.
|
||||
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
|
||||
assert(replay.has_value());
|
||||
assert(replay->version == 2);
|
||||
auto got = kv.get("a");
|
||||
assert(got.has_value() && got->has_value());
|
||||
assert((*got)->value == "two");
|
||||
assert((*got)->version == 2);
|
||||
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
auto written = kv.put("s" + std::to_string(i), "v",
|
||||
Precondition::absent(),
|
||||
{"s" + std::to_string(i)});
|
||||
assert(written.has_value());
|
||||
}
|
||||
|
||||
std::size_t seen = 0;
|
||||
std::optional<std::string> cursor;
|
||||
for (;;) {
|
||||
auto page = kv.scan(cursor ? std::optional<std::string_view>{*cursor}
|
||||
: std::nullopt,
|
||||
2);
|
||||
assert(page.has_value());
|
||||
assert(page->items.size() <= 2);
|
||||
seen += page->items.size();
|
||||
if (!page->next_cursor) {
|
||||
break;
|
||||
}
|
||||
cursor = page->next_cursor;
|
||||
}
|
||||
assert(seen == 6);
|
||||
}
|
||||
|
||||
// Reopen: durable rows and idempotency records survive.
|
||||
{
|
||||
auto store = SqliteKvStore::open(path);
|
||||
assert(store.has_value());
|
||||
auto& kv = **store;
|
||||
auto got = kv.get("a");
|
||||
assert(got.has_value() && got->has_value());
|
||||
assert((*got)->value == "two");
|
||||
|
||||
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
|
||||
assert(replay.has_value());
|
||||
assert(replay->version == 2);
|
||||
|
||||
// Idempotency outcomes survive the reopen and are queryable.
|
||||
auto known = kv.lookup_operation({"r3"});
|
||||
assert(known.has_value() && known->has_value());
|
||||
assert((*known)->outcome == WriteOutcome::Applied);
|
||||
assert((*known)->version == 2);
|
||||
auto absent = kv.lookup_operation({"never-used"});
|
||||
assert(absent.has_value() && !absent->has_value());
|
||||
|
||||
auto removed = kv.erase("a", Precondition::at_version(2), {"r4"});
|
||||
assert(removed.has_value());
|
||||
assert(removed->outcome == WriteOutcome::Applied);
|
||||
assert(!kv.get("a")->has_value());
|
||||
}
|
||||
|
||||
std::filesystem::remove_all(path.parent_path());
|
||||
std::puts("networked-kv sqlite profile ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(ReloadableHost LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Functional System)
|
||||
|
||||
add_library(reloadable_host STATIC
|
||||
src/activation.cpp
|
||||
src/checkpoint.cpp
|
||||
src/control.cpp
|
||||
src/posix_worker.cpp
|
||||
src/release_registry.cpp
|
||||
src/reload_transaction.cpp
|
||||
src/resources.cpp
|
||||
src/supervisor.cpp)
|
||||
target_include_directories(reloadable_host PUBLIC include)
|
||||
target_link_libraries(reloadable_host PUBLIC Void::Functional Void::System)
|
||||
|
||||
add_executable(reloadable_host_test tests/reload_transaction_test.cpp)
|
||||
target_link_libraries(reloadable_host_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_release_test tests/release_registry_test.cpp)
|
||||
target_link_libraries(reloadable_host_release_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_control_test tests/control_test.cpp)
|
||||
target_link_libraries(reloadable_host_control_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_checkpoint_test tests/checkpoint_test.cpp)
|
||||
target_link_libraries(reloadable_host_checkpoint_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_activation_test tests/activation_test.cpp)
|
||||
target_link_libraries(reloadable_host_activation_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_failure_matrix_test tests/reload_failure_matrix_test.cpp)
|
||||
target_link_libraries(reloadable_host_failure_matrix_test PRIVATE reloadable_host)
|
||||
|
||||
add_executable(reloadable_host_supervisor_test tests/supervisor_test.cpp)
|
||||
target_link_libraries(reloadable_host_supervisor_test PRIVATE reloadable_host)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME reloadable_host_transaction COMMAND reloadable_host_test)
|
||||
add_test(NAME reloadable_host_release COMMAND reloadable_host_release_test)
|
||||
add_test(NAME reloadable_host_control COMMAND reloadable_host_control_test)
|
||||
add_test(NAME reloadable_host_checkpoint COMMAND reloadable_host_checkpoint_test)
|
||||
add_test(NAME reloadable_host_activation COMMAND reloadable_host_activation_test)
|
||||
add_test(NAME reloadable_host_failure_matrix COMMAND reloadable_host_failure_matrix_test)
|
||||
add_test(NAME reloadable_host_supervisor COMMAND reloadable_host_supervisor_test)
|
||||
@@ -0,0 +1,256 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
/// Durable phase of one host reload.
|
||||
///
|
||||
/// `Activated` is reversible and uncommitted: a crash here recovers to the
|
||||
/// previous healthy release. `HealthyCommitted` is the single commit
|
||||
/// marker: a crash after it keeps the candidate even when cleanup is
|
||||
/// incomplete. `RolledBack` records an explicit pre-commit rollback.
|
||||
enum class ActivationPhase : std::uint8_t {
|
||||
None,
|
||||
Activated,
|
||||
HealthyCommitted,
|
||||
RolledBack
|
||||
};
|
||||
|
||||
struct ActivationRecord {
|
||||
std::uint64_t transaction_id{0};
|
||||
std::string previous_release;
|
||||
std::string candidate_release;
|
||||
std::uint64_t checkpoint_generation{0};
|
||||
ActivationPhase phase{ActivationPhase::None};
|
||||
};
|
||||
|
||||
struct ActivationLimits {
|
||||
std::size_t max_release_bytes{256};
|
||||
std::size_t max_record_bytes{4096};
|
||||
};
|
||||
|
||||
/// Durable journal storage boundary. `write` must not report success
|
||||
/// before the bytes are durable; a file-backed implementation owns
|
||||
/// fsync and directory sync.
|
||||
class ActivationStorage
|
||||
{
|
||||
public:
|
||||
|
||||
ActivationStorage() = default;
|
||||
ActivationStorage(const ActivationStorage&) = delete;
|
||||
ActivationStorage& operator=(const ActivationStorage&) = delete;
|
||||
virtual ~ActivationStorage() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<std::vector<std::byte>>>
|
||||
read() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
write(std::span<const std::byte> bytes) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> clear() = 0;
|
||||
};
|
||||
|
||||
/// Bounded in-memory journal used by tests and by hosts without durable
|
||||
/// recovery (it never survives a process, so it is not recovery evidence).
|
||||
class MemoryActivationStorage final : public ActivationStorage
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<
|
||||
std::optional<std::vector<std::byte>>>
|
||||
read() override
|
||||
{
|
||||
if (!m_bytes) {
|
||||
return std::optional<std::vector<std::byte>>{};
|
||||
}
|
||||
return std::optional<std::vector<std::byte>>{*m_bytes};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
write(std::span<const std::byte> bytes) override
|
||||
{
|
||||
if (m_fail_write) {
|
||||
m_fail_write = false;
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io,
|
||||
"MemoryActivationStorage: injected write failure"}};
|
||||
}
|
||||
m_bytes = std::vector<std::byte>{bytes.begin(), bytes.end()};
|
||||
if (m_lose_ack) {
|
||||
m_lose_ack = false;
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::io,
|
||||
"MemoryActivationStorage: lost acknowledgement"}};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> clear() override
|
||||
{
|
||||
m_bytes.reset();
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Test hook: simulate a torn/garbage durable record.
|
||||
void corrupt(std::vector<std::byte> bytes)
|
||||
{
|
||||
m_bytes = std::move(bytes);
|
||||
}
|
||||
|
||||
/// Test hook: fail the next write without touching the record.
|
||||
void fail_next_write(bool fail) noexcept { m_fail_write = fail; }
|
||||
|
||||
/// Test hook: make the next write return an error even though the
|
||||
/// bytes were durably stored (lost acknowledgement).
|
||||
void lose_next_acknowledgement(bool lose) noexcept
|
||||
{
|
||||
m_lose_ack = lose;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
std::optional<std::vector<std::byte>> m_bytes{};
|
||||
bool m_fail_write{false};
|
||||
bool m_lose_ack{false};
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_activation(const ActivationRecord& record,
|
||||
ActivationLimits limits = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<ActivationRecord>
|
||||
decode_activation(std::span<const std::byte> bytes,
|
||||
ActivationLimits limits = {});
|
||||
|
||||
enum class RecoveryAction : std::uint8_t {
|
||||
/// No journal: first bootstrap.
|
||||
None,
|
||||
/// Uncommitted activation or explicit rollback: restore the previous
|
||||
/// healthy release.
|
||||
UsePrevious,
|
||||
/// The healthy marker is durable: keep the candidate.
|
||||
UseCandidate,
|
||||
/// Corrupt or unknown journal: start not-ready and never invent a
|
||||
/// release.
|
||||
Diagnostic
|
||||
};
|
||||
|
||||
struct RecoveryDecision {
|
||||
RecoveryAction action{RecoveryAction::None};
|
||||
ActivationRecord record{};
|
||||
/// True when the healthy marker is durable but post-commit
|
||||
/// cleanup did not finish.
|
||||
bool cleanup_pending{false};
|
||||
std::string diagnostic;
|
||||
};
|
||||
|
||||
enum class CommitOutcome : std::uint8_t {
|
||||
Committed,
|
||||
/// The durable acknowledgement was lost. The caller must reconcile;
|
||||
/// it must never assume a rollback.
|
||||
Unknown,
|
||||
/// The transaction is not the active uncommitted activation.
|
||||
Rejected
|
||||
};
|
||||
|
||||
/// One authoritative activation journal.
|
||||
///
|
||||
/// Exactly one record is live. The phase transitions are:
|
||||
/// None -> Activated -> HealthyCommitted (commit marker, irreversible)
|
||||
/// -> RolledBack (explicit pre-commit rollback)
|
||||
/// Committed/rolled-back records are cleared only by `cleanup()`.
|
||||
class ActivationJournal
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ActivationJournal(ActivationStorage& storage,
|
||||
ActivationLimits limits = {});
|
||||
|
||||
/// Durably record a new reversible activation. Requires an empty
|
||||
/// journal (or a cleared one) so two transactions cannot disagree.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
activate(ActivationRecord record);
|
||||
|
||||
/// Durably record the healthy commit marker. A failed write is
|
||||
/// resolved by re-reading: if the marker is durable the outcome is
|
||||
/// Committed, otherwise Unknown.
|
||||
[[nodiscard]] CommitOutcome
|
||||
commit_healthy(std::uint64_t transaction_id) noexcept;
|
||||
|
||||
/// Durably record an explicit rollback of the uncommitted
|
||||
/// activation. Rejected after the healthy marker.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
rollback(std::uint64_t transaction_id);
|
||||
|
||||
/// Remove a committed or rolled-back record after reclaim. Never
|
||||
/// removes an uncommitted activation.
|
||||
[[nodiscard]] Void::Result::Result<void> cleanup();
|
||||
|
||||
/// Read and classify the durable journal on startup.
|
||||
[[nodiscard]] RecoveryDecision reconcile();
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<ActivationRecord>>
|
||||
current();
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<ActivationRecord>>
|
||||
load();
|
||||
|
||||
ActivationStorage& m_storage;
|
||||
ActivationLimits m_limits;
|
||||
};
|
||||
|
||||
/// Reversible read-only health window after publication.
|
||||
///
|
||||
/// During the window snapshot-safe reads are admitted and mutations get a
|
||||
/// retryable not-ready result; writes reopen only after the healthy marker
|
||||
/// is durable. A failed observation rolls back immediately.
|
||||
class HealthWindow
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Decision : std::uint8_t {
|
||||
Pending,
|
||||
Commit,
|
||||
Rollback
|
||||
};
|
||||
|
||||
explicit HealthWindow(
|
||||
std::chrono::milliseconds duration =
|
||||
std::chrono::milliseconds{10000}) noexcept;
|
||||
|
||||
[[nodiscard]] bool admit_read() const noexcept { return m_open; }
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> admit_write() const;
|
||||
|
||||
/// Record one readiness observation. Any unhealthy observation
|
||||
/// closes the window for mutation.
|
||||
void observe(bool healthy) noexcept;
|
||||
|
||||
/// Commit once the window elapsed with no failure, roll back on a
|
||||
/// failed observation, otherwise keep waiting.
|
||||
[[nodiscard]] Decision evaluate(
|
||||
std::chrono::steady_clock::time_point now) const noexcept;
|
||||
|
||||
/// Close the window after the decision was applied.
|
||||
void finish() noexcept { m_open = false; }
|
||||
|
||||
[[nodiscard]] bool open() const noexcept { return m_open; }
|
||||
[[nodiscard]] bool failed() const noexcept { return m_failed; }
|
||||
|
||||
private:
|
||||
|
||||
std::chrono::steady_clock::time_point m_deadline;
|
||||
bool m_open{true};
|
||||
bool m_failed{false};
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
inline constexpr std::uint32_t kCurrentCheckpointVersion{3};
|
||||
|
||||
/// Durable workflow state carried across releases.
|
||||
struct CheckpointState {
|
||||
std::uint64_t counter{0};
|
||||
std::string workflow;
|
||||
std::uint64_t generation{0};
|
||||
};
|
||||
|
||||
struct CheckpointLimits {
|
||||
std::size_t max_bytes{64ULL * 1024ULL};
|
||||
std::size_t max_workflow_bytes{4ULL * 1024ULL};
|
||||
};
|
||||
|
||||
/// Encode the current checkpoint schema (bounded).
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_checkpoint(const CheckpointState& state,
|
||||
CheckpointLimits limits = {});
|
||||
|
||||
/// Decode a supported checkpoint and migrate it to the current schema.
|
||||
///
|
||||
/// v1 (counter) and v2 (counter + workflow) are migrated forward with
|
||||
/// defaults for fields they did not have. Corrupt magic, truncation,
|
||||
/// oversized payloads and unknown newer versions are rejected.
|
||||
[[nodiscard]] Void::Result::Result<CheckpointState>
|
||||
decode_checkpoint(std::span<const std::byte> bytes,
|
||||
CheckpointLimits limits = {});
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
enum class ControlStatus : std::uint16_t {
|
||||
Ok = 0,
|
||||
Unauthenticated = 1,
|
||||
InvalidArgument = 2,
|
||||
NotFound = 3,
|
||||
FailedPrecondition = 4,
|
||||
Overloaded = 5,
|
||||
Timeout = 6,
|
||||
Internal = 7,
|
||||
Unimplemented = 8
|
||||
};
|
||||
|
||||
struct ControlRequest {
|
||||
std::string command;
|
||||
std::string candidate;
|
||||
std::string token;
|
||||
std::chrono::milliseconds deadline{0};
|
||||
std::string payload;
|
||||
};
|
||||
|
||||
struct ControlReply {
|
||||
ControlStatus status{ControlStatus::Ok};
|
||||
std::string body;
|
||||
std::uint64_t transaction_id{0};
|
||||
};
|
||||
|
||||
struct ControlLimits {
|
||||
std::size_t max_request_bytes{64ULL * 1024ULL};
|
||||
std::size_t max_reply_bytes{64ULL * 1024ULL};
|
||||
};
|
||||
|
||||
/// Host operations exposed over the authenticated local control endpoint.
|
||||
class ControlHandler
|
||||
{
|
||||
public:
|
||||
|
||||
ControlHandler() = default;
|
||||
ControlHandler(const ControlHandler&) = delete;
|
||||
ControlHandler& operator=(const ControlHandler&) = delete;
|
||||
virtual ~ControlHandler() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::string> inspect() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<bool> health() const = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
validate_candidate(std::string_view candidate) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<std::uint64_t>
|
||||
reload(std::string_view candidate,
|
||||
std::chrono::milliseconds deadline) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
drain(std::chrono::milliseconds deadline) = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> shutdown() = 0;
|
||||
[[nodiscard]] virtual Void::Result::Result<void> recover() = 0;
|
||||
};
|
||||
|
||||
/// Authenticated, bounded control dispatcher.
|
||||
///
|
||||
/// The transport (local IPC) owns framing; this validates the token in
|
||||
/// constant time, enforces request/reply bounds, and maps host errors to
|
||||
/// stable statuses. An empty configured token authorizes nothing.
|
||||
class ControlEndpoint
|
||||
{
|
||||
public:
|
||||
|
||||
ControlEndpoint(std::string token, ControlHandler& handler,
|
||||
ControlLimits limits = {});
|
||||
|
||||
[[nodiscard]] ControlReply handle(const ControlRequest& request);
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool authorized(std::string_view token) const noexcept;
|
||||
[[nodiscard]] ControlReply dispatch(const ControlRequest& request);
|
||||
|
||||
std::string m_token;
|
||||
ControlHandler& m_handler;
|
||||
ControlLimits m_limits;
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include "reloadable_host/supervisor.hpp"
|
||||
|
||||
#include <Void/System/Process.hpp>
|
||||
|
||||
#include <optional>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
/// Real out-of-process provider port over Void::Process.
|
||||
///
|
||||
/// Commands run through `/bin/sh -c` with inherited stdio (no unconsumed
|
||||
/// pipes), so a noisy worker cannot fill an unread pipe and block.
|
||||
class PosixWorkerPort final : public WorkerProcessPort
|
||||
{
|
||||
public:
|
||||
|
||||
PosixWorkerPort() = default;
|
||||
PosixWorkerPort(const PosixWorkerPort&) = delete;
|
||||
PosixWorkerPort& operator=(const PosixWorkerPort&) = delete;
|
||||
~PosixWorkerPort() override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
spawn(const std::string& command) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<WorkerExit>>
|
||||
try_wait() override;
|
||||
|
||||
void terminate(std::chrono::milliseconds grace) noexcept override;
|
||||
|
||||
[[nodiscard]] bool running() const noexcept override;
|
||||
|
||||
private:
|
||||
|
||||
std::optional<Void::Process::Child> m_child{};
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
struct ReleaseDescriptor {
|
||||
std::string id;
|
||||
std::string path;
|
||||
std::uint64_t generation{0};
|
||||
};
|
||||
|
||||
/// Host-supplied trust/checksum validation for a candidate release.
|
||||
using ReleaseValidator =
|
||||
std::function<Void::Result::Result<void>(const ReleaseDescriptor&)>;
|
||||
|
||||
struct ReleaseLimits {
|
||||
/// Maximum unpinned-reclaimable older generations retained.
|
||||
std::size_t max_retained_generations{2};
|
||||
};
|
||||
|
||||
/// Immutable pinned release handle. Holding it keeps its generation alive
|
||||
/// across reloads, exactly like an old read handle in the reference host.
|
||||
using ReleaseHandle = std::shared_ptr<const ReleaseDescriptor>;
|
||||
|
||||
/// Immutable release generations with pin-based retention.
|
||||
///
|
||||
/// Publishing never invalidates an acquired handle. Older generations are
|
||||
/// retired only after every pin is released, so the retained set stays
|
||||
/// bounded by the pin count and the configured cap.
|
||||
class ReleaseRegistry
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ReleaseRegistry(ReleaseLimits limits = {});
|
||||
|
||||
/// Validate and publish a candidate. Returns its generation.
|
||||
[[nodiscard]] Void::Result::Result<std::uint64_t>
|
||||
publish(ReleaseDescriptor candidate,
|
||||
const ReleaseValidator& validate);
|
||||
|
||||
/// Pin the current generation. Empty when nothing is published.
|
||||
[[nodiscard]] ReleaseHandle acquire() const;
|
||||
|
||||
[[nodiscard]] std::optional<ReleaseDescriptor> current() const;
|
||||
|
||||
/// Retire older generations with no outstanding pins.
|
||||
std::size_t collect() noexcept;
|
||||
|
||||
[[nodiscard]] std::size_t retained() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
std::size_t collect_locked() noexcept;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
ReleaseLimits m_limits;
|
||||
std::uint64_t m_next_generation{1};
|
||||
ReleaseHandle m_current;
|
||||
std::vector<ReleaseHandle> m_retained;
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
using TransactionId = std::uint64_t;
|
||||
|
||||
enum class ReloadPhase : std::uint8_t {
|
||||
Idle,
|
||||
Validating,
|
||||
Preparing,
|
||||
Draining,
|
||||
Publishing,
|
||||
Committing,
|
||||
Completed,
|
||||
RolledBack,
|
||||
Failed,
|
||||
CancelledBeforePublish,
|
||||
UnknownOutcome
|
||||
};
|
||||
|
||||
enum class ReloadOutcome : std::uint8_t {
|
||||
None,
|
||||
Published,
|
||||
RolledBack,
|
||||
Failed,
|
||||
UnknownOutcome
|
||||
};
|
||||
|
||||
struct ReloadReport {
|
||||
TransactionId id{0};
|
||||
ReloadPhase phase{ReloadPhase::Idle};
|
||||
ReloadOutcome outcome{ReloadOutcome::None};
|
||||
std::string candidate;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
/// Immutable candidate release identifier and payload location.
|
||||
struct ReleaseCandidate {
|
||||
std::string id;
|
||||
std::string path;
|
||||
std::uint64_t generation{0};
|
||||
};
|
||||
|
||||
/// Host-supplied trust/checksum validation boundary.
|
||||
using Validator =
|
||||
std::function<Void::Result::Result<void>(const ReleaseCandidate&)>;
|
||||
|
||||
struct ReloadLimits {
|
||||
std::chrono::milliseconds drain_deadline{std::chrono::seconds{30}};
|
||||
std::size_t max_pins{1024};
|
||||
};
|
||||
|
||||
/// Tracks in-flight application calls so a reload drains before publishing.
|
||||
class Quiescence
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Quiescence(ReloadLimits limits = {});
|
||||
|
||||
/// Admit a call. Fails while draining or at the pin cap.
|
||||
[[nodiscard]] Void::Result::Result<void> admit();
|
||||
void release() noexcept;
|
||||
|
||||
/// Stop admissions and wait until pins drain or the deadline
|
||||
/// expires. Returns false on timeout (still draining).
|
||||
[[nodiscard]] bool drain();
|
||||
|
||||
/// Resume admissions after a rollback.
|
||||
void resume() noexcept;
|
||||
|
||||
[[nodiscard]] std::size_t pins() const noexcept;
|
||||
[[nodiscard]] bool draining() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::condition_variable m_cv;
|
||||
ReloadLimits m_limits;
|
||||
std::size_t m_pins{0};
|
||||
bool m_draining{false};
|
||||
};
|
||||
|
||||
/// One authoritative reload transaction.
|
||||
///
|
||||
/// Exactly one outcome wins. Publication is the point of no return:
|
||||
/// cancellation before it rolls back, after it the outcome stays
|
||||
/// published, and a lost durable acknowledgement is UnknownOutcome rather
|
||||
/// than a false rollback.
|
||||
class ReloadTransaction
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ReloadTransaction(TransactionId id);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
prepare(const ReleaseCandidate& candidate,
|
||||
const Validator& validate);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
drain(Quiescence& quiescence);
|
||||
|
||||
/// Publish the prepared candidate. Only valid after a successful
|
||||
/// drain.
|
||||
[[nodiscard]] Void::Result::Result<void> publish();
|
||||
|
||||
/// Record the durable healthy commit. `durable == false` models a
|
||||
/// lost acknowledgement: the outcome is Unknown.
|
||||
void commit(bool durable) noexcept;
|
||||
|
||||
/// Cancel before publication. A no-op once published.
|
||||
void cancel() noexcept;
|
||||
|
||||
[[nodiscard]] ReloadReport report() const;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
TransactionId m_id;
|
||||
ReloadPhase m_phase{ReloadPhase::Idle};
|
||||
ReloadOutcome m_outcome{ReloadOutcome::None};
|
||||
std::optional<ReleaseCandidate> m_candidate;
|
||||
std::string m_error;
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
/// Aggregate retained-resource permits shared by candidate and retired
|
||||
/// generations. These are host-owned budgets, not a total-process RSS
|
||||
/// promise: mapped images, stacks and kernel buffers are accounted
|
||||
/// separately by the platform.
|
||||
struct ResourceLimits {
|
||||
std::size_t max_total_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_generation_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_generations{4};
|
||||
};
|
||||
|
||||
struct ResourceUsage {
|
||||
std::size_t total_bytes{0};
|
||||
std::size_t generations{0};
|
||||
};
|
||||
|
||||
/// Thread-safe byte/generation ledger.
|
||||
///
|
||||
/// `reserve` is admission: it rejects an over-budget generation with
|
||||
/// `exhausted` before any publication happens. A generation stays reserved
|
||||
/// until every pin on it is gone and the host releases it, so budget
|
||||
/// saturation is observable and recoverable rather than silent eviction.
|
||||
class ResourceLedger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ResourceLedger(ResourceLimits limits = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
reserve(std::uint64_t generation, std::size_t bytes);
|
||||
|
||||
/// Release one reserved generation. False when it was not held.
|
||||
bool release(std::uint64_t generation) noexcept;
|
||||
|
||||
[[nodiscard]] bool holds(std::uint64_t generation) const noexcept;
|
||||
|
||||
[[nodiscard]] ResourceUsage usage() const noexcept;
|
||||
/// High-water mark, for retained-resource and RSS reporting.
|
||||
[[nodiscard]] ResourceUsage peak_usage() const noexcept;
|
||||
|
||||
[[nodiscard]] const ResourceLimits& limits() const noexcept
|
||||
{
|
||||
return m_limits;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
ResourceLimits m_limits;
|
||||
std::map<std::uint64_t, std::size_t> m_reserved;
|
||||
std::size_t m_total_bytes{0};
|
||||
ResourceUsage m_peak{};
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
enum class WorkerState : std::uint8_t {
|
||||
Stopped,
|
||||
Running,
|
||||
Restarting,
|
||||
Failed
|
||||
};
|
||||
|
||||
/// Effects already handed to a crashed worker cannot be proven absent.
|
||||
enum class EffectState : std::uint8_t {
|
||||
None,
|
||||
InProgress,
|
||||
/// The worker died (or was terminated) with an effect in progress.
|
||||
/// The host must reconcile with the provider; it must never assume
|
||||
/// the effect was rolled back.
|
||||
Unknown,
|
||||
Completed
|
||||
};
|
||||
|
||||
struct RestartPolicy {
|
||||
std::uint32_t max_restarts{3};
|
||||
std::chrono::milliseconds base_backoff{50};
|
||||
std::chrono::milliseconds max_backoff{1000};
|
||||
};
|
||||
|
||||
struct WorkerExit {
|
||||
bool exited{false};
|
||||
int code{-1};
|
||||
int signal{0};
|
||||
|
||||
[[nodiscard]] bool clean() const noexcept
|
||||
{
|
||||
return exited && code == 0 && signal == 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct SupervisorReport {
|
||||
WorkerState state{WorkerState::Stopped};
|
||||
EffectState effects{EffectState::None};
|
||||
std::uint32_t restarts{0};
|
||||
/// Advisory delay before the next restart attempt; the caller
|
||||
/// owns the clock so supervision stays deterministic.
|
||||
std::chrono::milliseconds next_backoff{0};
|
||||
std::string last_error;
|
||||
};
|
||||
|
||||
/// Spawn/observe/terminate boundary for one out-of-process provider.
|
||||
/// Implementations own exactly one worker at a time.
|
||||
class WorkerProcessPort
|
||||
{
|
||||
public:
|
||||
|
||||
WorkerProcessPort() = default;
|
||||
WorkerProcessPort(const WorkerProcessPort&) = delete;
|
||||
WorkerProcessPort& operator=(const WorkerProcessPort&) = delete;
|
||||
virtual ~WorkerProcessPort() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
spawn(const std::string& command) = 0;
|
||||
|
||||
/// Non-blocking observation. Empty optional while still running.
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<WorkerExit>>
|
||||
try_wait() = 0;
|
||||
|
||||
virtual void terminate(std::chrono::milliseconds grace) noexcept = 0;
|
||||
[[nodiscard]] virtual bool running() const noexcept = 0;
|
||||
};
|
||||
|
||||
/// Supervises one out-of-process provider with an explicit restart policy.
|
||||
///
|
||||
/// Restarts are attempted only by the next `poll()` after a crash, so the
|
||||
/// backoff is reported rather than slept. A crash with an in-progress
|
||||
/// effect reports `EffectState::Unknown`: this composition makes no
|
||||
/// exactly-once or distributed claim.
|
||||
class WorkerSupervisor
|
||||
{
|
||||
public:
|
||||
|
||||
WorkerSupervisor(WorkerProcessPort& port, std::string command,
|
||||
RestartPolicy policy = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
/// Mark one effect as handed to the worker, and its confirmed
|
||||
/// completion.
|
||||
void begin_effect() noexcept;
|
||||
void complete_effect() noexcept;
|
||||
|
||||
/// Observe one exit (non-blocking) and apply the restart policy.
|
||||
/// The next poll after a crash respawns the worker.
|
||||
[[nodiscard]] Void::Result::Result<SupervisorReport> poll();
|
||||
|
||||
/// Terminate a running worker with a bounded grace. Never claims an
|
||||
/// in-progress effect was rolled back.
|
||||
void stop(std::chrono::milliseconds grace = std::chrono::milliseconds{
|
||||
2000}) noexcept;
|
||||
|
||||
[[nodiscard]] SupervisorReport report() const;
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds backoff_for(
|
||||
std::uint32_t restarts) const noexcept;
|
||||
|
||||
WorkerProcessPort& m_port;
|
||||
std::string m_command;
|
||||
RestartPolicy m_policy;
|
||||
SupervisorReport m_report{};
|
||||
};
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,407 @@
|
||||
#include "reloadable_host/activation.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::array<std::byte, 4> kMagic{
|
||||
std::byte{'V'}, std::byte{'A'}, std::byte{'C'}, std::byte{'T'}};
|
||||
constexpr std::uint32_t kVersion{1};
|
||||
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error corrupt(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Error conflict(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::conflict,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
|
||||
{
|
||||
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
|
||||
{
|
||||
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::uint32_t& value) noexcept
|
||||
{
|
||||
if (pos + 4 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint32_t>(in[pos + i]);
|
||||
}
|
||||
pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::uint64_t& value) noexcept
|
||||
{
|
||||
if (pos + 8 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint64_t>(in[pos + i]);
|
||||
}
|
||||
pos += 8;
|
||||
return true;
|
||||
}
|
||||
|
||||
void append_string(std::vector<std::byte>& out, std::string_view text)
|
||||
{
|
||||
append_u32(out, static_cast<std::uint32_t>(text.size()));
|
||||
for (const char c : text) {
|
||||
out.push_back(static_cast<std::byte>(
|
||||
static_cast<unsigned char>(c)));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_string(std::span<const std::byte> in,
|
||||
std::size_t& pos, std::string& out,
|
||||
std::size_t max_bytes) noexcept
|
||||
{
|
||||
std::uint32_t length = 0;
|
||||
if (!read_u32(in, pos, length) || length > max_bytes ||
|
||||
pos + length > in.size()) {
|
||||
return false;
|
||||
}
|
||||
out.clear();
|
||||
out.reserve(length);
|
||||
for (std::uint32_t i = 0; i < length; ++i) {
|
||||
out.push_back(static_cast<char>(
|
||||
std::to_integer<unsigned char>(in[pos + i])));
|
||||
}
|
||||
pos += length;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
|
||||
{
|
||||
std::uint64_t hash = 0xCBF29CE484222325ULL;
|
||||
for (const std::byte byte : bytes) {
|
||||
hash ^= std::to_integer<std::uint64_t>(byte);
|
||||
hash *= 0x100000001B3ULL;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_known_phase(ActivationPhase phase) noexcept
|
||||
{
|
||||
return phase == ActivationPhase::Activated ||
|
||||
phase == ActivationPhase::HealthyCommitted ||
|
||||
phase == ActivationPhase::RolledBack;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<std::byte>>
|
||||
encode_activation(const ActivationRecord& record, ActivationLimits limits)
|
||||
{
|
||||
if (record.previous_release.size() > limits.max_release_bytes ||
|
||||
record.candidate_release.size() > limits.max_release_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("Activation: release id exceeds the size limit")};
|
||||
}
|
||||
if (!is_known_phase(record.phase)) {
|
||||
return std::unexpected{
|
||||
invalid("Activation: cannot encode an unset phase")};
|
||||
}
|
||||
|
||||
std::vector<std::byte> out;
|
||||
out.insert(out.end(), kMagic.begin(), kMagic.end());
|
||||
append_u32(out, kVersion);
|
||||
append_u64(out, record.transaction_id);
|
||||
append_u64(out, record.checkpoint_generation);
|
||||
out.push_back(static_cast<std::byte>(record.phase));
|
||||
append_string(out, record.previous_release);
|
||||
append_string(out, record.candidate_release);
|
||||
append_u64(out, checksum(out));
|
||||
if (out.size() > limits.max_record_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("Activation: record exceeds max_record_bytes")};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<ActivationRecord>
|
||||
decode_activation(std::span<const std::byte> bytes,
|
||||
ActivationLimits limits)
|
||||
{
|
||||
if (bytes.size() > limits.max_record_bytes ||
|
||||
bytes.size() < kMagic.size() + 4 + 8 + 8 + 1 + 4 + 4 + 8) {
|
||||
return std::unexpected{corrupt("Activation: record is truncated")};
|
||||
}
|
||||
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
|
||||
return std::unexpected{corrupt("Activation: bad magic")};
|
||||
}
|
||||
const std::size_t payload = bytes.size() - 8;
|
||||
std::uint64_t stored_checksum = 0;
|
||||
{
|
||||
std::size_t pos = payload;
|
||||
if (!read_u64(bytes, pos, stored_checksum)) {
|
||||
return std::unexpected{
|
||||
corrupt("Activation: missing checksum")};
|
||||
}
|
||||
}
|
||||
if (checksum(bytes.first(payload)) != stored_checksum) {
|
||||
return std::unexpected{
|
||||
corrupt("Activation: checksum mismatch")};
|
||||
}
|
||||
|
||||
std::size_t pos = kMagic.size();
|
||||
std::uint32_t version = 0;
|
||||
if (!read_u32(bytes, pos, version) || version != kVersion) {
|
||||
return std::unexpected{
|
||||
corrupt("Activation: unsupported record version")};
|
||||
}
|
||||
ActivationRecord record;
|
||||
if (!read_u64(bytes, pos, record.transaction_id) ||
|
||||
!read_u64(bytes, pos, record.checkpoint_generation) ||
|
||||
pos >= payload) {
|
||||
return std::unexpected{corrupt("Activation: malformed record")};
|
||||
}
|
||||
record.phase = static_cast<ActivationPhase>(
|
||||
std::to_integer<unsigned char>(bytes[pos++]));
|
||||
if (!is_known_phase(record.phase)) {
|
||||
return std::unexpected{corrupt("Activation: unknown phase")};
|
||||
}
|
||||
if (!read_string(bytes, pos, record.previous_release,
|
||||
limits.max_release_bytes) ||
|
||||
!read_string(bytes, pos, record.candidate_release,
|
||||
limits.max_release_bytes) ||
|
||||
pos != payload) {
|
||||
return std::unexpected{corrupt("Activation: malformed record")};
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
ActivationJournal::ActivationJournal(ActivationStorage& storage,
|
||||
ActivationLimits limits)
|
||||
: m_storage(storage), m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<ActivationRecord>>
|
||||
ActivationJournal::load()
|
||||
{
|
||||
auto bytes = m_storage.read();
|
||||
if (!bytes) {
|
||||
return std::unexpected{std::move(bytes).error()};
|
||||
}
|
||||
if (!bytes->has_value()) {
|
||||
return std::optional<ActivationRecord>{};
|
||||
}
|
||||
auto decoded = decode_activation(**bytes, m_limits);
|
||||
if (!decoded) {
|
||||
return std::unexpected{std::move(decoded).error()};
|
||||
}
|
||||
return std::optional<ActivationRecord>{std::move(*decoded)};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ActivationJournal::activate(ActivationRecord record)
|
||||
{
|
||||
record.phase = ActivationPhase::Activated;
|
||||
auto existing = load();
|
||||
if (!existing) {
|
||||
return std::unexpected{std::move(existing).error()};
|
||||
}
|
||||
if (existing->has_value()) {
|
||||
return std::unexpected{conflict(
|
||||
"Activation: journal already holds a record; cleanup first")};
|
||||
}
|
||||
auto encoded = encode_activation(record, m_limits);
|
||||
if (!encoded) {
|
||||
return std::unexpected{std::move(encoded).error()};
|
||||
}
|
||||
if (auto written = m_storage.write(*encoded); !written) {
|
||||
// The write may still have landed durably; make the caller decide
|
||||
// from the journal rather than assuming nothing happened.
|
||||
return std::unexpected{std::move(written).error()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
CommitOutcome
|
||||
ActivationJournal::commit_healthy(std::uint64_t transaction_id) noexcept
|
||||
{
|
||||
auto existing = load();
|
||||
if (!existing || !existing->has_value() ||
|
||||
(*existing)->transaction_id != transaction_id) {
|
||||
return CommitOutcome::Rejected;
|
||||
}
|
||||
ActivationRecord record = **existing;
|
||||
if (record.phase == ActivationPhase::HealthyCommitted) {
|
||||
return CommitOutcome::Committed;
|
||||
}
|
||||
if (record.phase != ActivationPhase::Activated) {
|
||||
return CommitOutcome::Rejected;
|
||||
}
|
||||
record.phase = ActivationPhase::HealthyCommitted;
|
||||
auto encoded = encode_activation(record, m_limits);
|
||||
if (!encoded) {
|
||||
return CommitOutcome::Unknown;
|
||||
}
|
||||
if (auto written = m_storage.write(*encoded); written) {
|
||||
return CommitOutcome::Committed;
|
||||
}
|
||||
// Lost acknowledgement: re-read the durable record. The marker being
|
||||
// present means committed; its absence is Unknown, never a rollback.
|
||||
auto reread = load();
|
||||
if (reread && reread->has_value() &&
|
||||
(*reread)->phase == ActivationPhase::HealthyCommitted &&
|
||||
(*reread)->transaction_id == transaction_id) {
|
||||
return CommitOutcome::Committed;
|
||||
}
|
||||
return CommitOutcome::Unknown;
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
ActivationJournal::rollback(std::uint64_t transaction_id)
|
||||
{
|
||||
auto existing = load();
|
||||
if (!existing) {
|
||||
return std::unexpected{std::move(existing).error()};
|
||||
}
|
||||
if (!existing->has_value()) {
|
||||
return std::unexpected{
|
||||
conflict("Activation: no activation to roll back")};
|
||||
}
|
||||
ActivationRecord record = **existing;
|
||||
if (record.transaction_id != transaction_id) {
|
||||
return std::unexpected{
|
||||
conflict("Activation: transaction is not the active one")};
|
||||
}
|
||||
if (record.phase == ActivationPhase::HealthyCommitted) {
|
||||
return std::unexpected{conflict(
|
||||
"Activation: healthy marker is durable; rollback is not the "
|
||||
"recovery action")};
|
||||
}
|
||||
if (record.phase == ActivationPhase::RolledBack) {
|
||||
return {};
|
||||
}
|
||||
record.phase = ActivationPhase::RolledBack;
|
||||
auto encoded = encode_activation(record, m_limits);
|
||||
if (!encoded) {
|
||||
return std::unexpected{std::move(encoded).error()};
|
||||
}
|
||||
return m_storage.write(*encoded);
|
||||
}
|
||||
|
||||
Void::Result::Result<void> ActivationJournal::cleanup()
|
||||
{
|
||||
auto existing = load();
|
||||
if (!existing) {
|
||||
return std::unexpected{std::move(existing).error()};
|
||||
}
|
||||
if (existing->has_value() &&
|
||||
(*existing)->phase == ActivationPhase::Activated) {
|
||||
return std::unexpected{conflict(
|
||||
"Activation: cannot clean up an uncommitted activation")};
|
||||
}
|
||||
return m_storage.clear();
|
||||
}
|
||||
|
||||
RecoveryDecision ActivationJournal::reconcile()
|
||||
{
|
||||
RecoveryDecision decision;
|
||||
auto existing = load();
|
||||
if (!existing) {
|
||||
decision.action = RecoveryAction::Diagnostic;
|
||||
decision.diagnostic = existing.error().message();
|
||||
return decision;
|
||||
}
|
||||
if (!existing->has_value()) {
|
||||
decision.action = RecoveryAction::None;
|
||||
return decision;
|
||||
}
|
||||
decision.record = **existing;
|
||||
switch (decision.record.phase) {
|
||||
case ActivationPhase::Activated:
|
||||
// Crash before the healthy marker: the activation is
|
||||
// reversible, so the prior healthy release wins.
|
||||
decision.action = RecoveryAction::UsePrevious;
|
||||
break;
|
||||
case ActivationPhase::HealthyCommitted:
|
||||
// Committed even if reclaim never ran.
|
||||
decision.action = RecoveryAction::UseCandidate;
|
||||
decision.cleanup_pending = true;
|
||||
break;
|
||||
case ActivationPhase::RolledBack:
|
||||
decision.action = RecoveryAction::UsePrevious;
|
||||
break;
|
||||
case ActivationPhase::None:
|
||||
decision.action = RecoveryAction::Diagnostic;
|
||||
decision.diagnostic = "Activation: unset phase";
|
||||
break;
|
||||
}
|
||||
return decision;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<ActivationRecord>>
|
||||
ActivationJournal::current()
|
||||
{
|
||||
return load();
|
||||
}
|
||||
|
||||
HealthWindow::HealthWindow(std::chrono::milliseconds duration) noexcept
|
||||
: m_deadline(std::chrono::steady_clock::now() + duration)
|
||||
{
|
||||
}
|
||||
|
||||
Void::Result::Result<void> HealthWindow::admit_write() const
|
||||
{
|
||||
if (!m_open) {
|
||||
return {};
|
||||
}
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::overloaded,
|
||||
"HealthWindow: mutations are closed during the read-only health "
|
||||
"window"}};
|
||||
}
|
||||
|
||||
void HealthWindow::observe(bool healthy) noexcept
|
||||
{
|
||||
if (!healthy) {
|
||||
m_failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
HealthWindow::Decision HealthWindow::evaluate(
|
||||
std::chrono::steady_clock::time_point now) const noexcept
|
||||
{
|
||||
if (!m_open) {
|
||||
return Decision::Pending;
|
||||
}
|
||||
if (m_failed) {
|
||||
return Decision::Rollback;
|
||||
}
|
||||
return now >= m_deadline ? Decision::Commit : Decision::Pending;
|
||||
}
|
||||
} // namespace ReloadableHost
|
||||
@@ -0,0 +1,143 @@
|
||||
#include "reloadable_host/checkpoint.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace ReloadableHost
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::array<std::byte, 4> kMagic{
|
||||
std::byte{'V'}, std::byte{'C'}, std::byte{'H'}, std::byte{'K'}};
|
||||
|
||||
[[nodiscard]] Void::Result::Error invalid(std::string message)
|
||||
{
|
||||
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
|
||||
std::move(message)};
|
||||
}
|
||||
|
||||
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
|
||||
{
|
||||
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
|
||||
{
|
||||
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
|
||||
std::size_t& pos,
|
||||
std::uint32_t& value) noexcept
|
||||
{
|
||||
if (pos + 4 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint32_t>(in[pos + i]);
|
||||
}
|
||||
pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
|
||||
std::size_t& pos,
|
||||
std::uint64_t& value) noexcept
|
||||
{
|
||||
if (pos + 8 > in.size()) {
|
||||
return false;
|
||||
}
|
||||
value = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
value = (value << 8) |
|
||||
std::to_integer<std::uint64_t>(in[pos + i]);
|
||||
}
|
||||
pos += 8;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<std::byte>>
|
||||
encode_checkpoint(const CheckpointState& state, CheckpointLimits limits)
|
||||
{
|
||||
if (state.workflow.size() > limits.max_workflow_bytes ||
|
||||
state.workflow.size() > 0xFFFFFFFFULL) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: workflow exceeds the size limit")};
|
||||
}
|
||||
std::vector<std::byte> out;
|
||||
out.reserve(4 + 4 + 8 + 4 + state.workflow.size() + 8);
|
||||
out.insert(out.end(), kMagic.begin(), kMagic.end());
|
||||
append_u32(out, kCurrentCheckpointVersion);
|
||||
append_u64(out, state.counter);
|
||||
append_u32(out, static_cast<std::uint32_t>(state.workflow.size()));
|
||||
for (const char ch : state.workflow) {
|
||||
out.push_back(static_cast<std::byte>(ch));
|
||||
}
|
||||
append_u64(out, state.generation);
|
||||
if (out.size() > limits.max_bytes) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: encoded state exceeds the size limit")};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<CheckpointState>
|
||||
decode_checkpoint(std::span<const std::byte> bytes,
|
||||
CheckpointLimits limits)
|
||||
{
|
||||
if (bytes.size() > limits.max_bytes ||
|
||||
bytes.size() < kMagic.size() + 4 + 8) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: truncated or oversized payload")};
|
||||
}
|
||||
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
|
||||
return std::unexpected{invalid("Checkpoint: bad magic")};
|
||||
}
|
||||
|
||||
std::size_t pos = kMagic.size();
|
||||
std::uint32_t version = 0;
|
||||
if (!read_u32(bytes, pos, version)) {
|
||||
return std::unexpected{invalid("Checkpoint: truncated version")};
|
||||
}
|
||||
if (version == 0 || version > kCurrentCheckpointVersion) {
|
||||
return std::unexpected{invalid(
|
||||
"Checkpoint: unsupported schema version")};
|
||||
}
|
||||
|
||||
CheckpointState state;
|
||||
if (!read_u64(bytes, pos, state.counter)) {
|
||||
return std::unexpected{invalid("Checkpoint: truncated counter")};
|
||||
}
|
||||
if (version >= 2) {
|
||||
std::uint32_t workflow_size = 0;
|
||||
if (!read_u32(bytes, pos, workflow_size) ||
|
||||
workflow_size > limits.max_workflow_bytes ||
|
||||
pos + workflow_size > bytes.size()) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: invalid workflow payload")};
|
||||
}
|
||||
state.workflow.assign(
|
||||
reinterpret_cast<const char*>(bytes.data() + pos),
|
||||
workflow_size);
|
||||
pos += workflow_size;
|
||||
}
|
||||
if (version >= 3 && !read_u64(bytes, pos, state.generation)) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: truncated generation")};
|
||||
}
|
||||
if (pos != bytes.size()) {
|
||||
return std::unexpected{
|
||||
invalid("Checkpoint: trailing bytes after payload")};
|
||||
}
|
||||
return state;
|
||||
}
|
||||
} // namespace ReloadableHost
|
||||
Loaded 100 of 376 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user