1109 lines
31 KiB
C++
1109 lines
31 KiB
C++
#include <Void/Async/Executor.hpp>
|
|
#include <Void/Async/Task.hpp>
|
|
#include <Void/Data/Reflect.hpp>
|
|
#include <Void/Fsm/Fsm.hpp>
|
|
#include <Void/Fsm/Orchestrator.hpp>
|
|
#include <Void/Service/Registry.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <stdexcept>
|
|
#include <stop_token>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
namespace void_fsm_hardening_test
|
|
{
|
|
using Void::Coro::Task;
|
|
using Void::Fsm::Checkpoint;
|
|
using Void::Fsm::ExecutionBinding;
|
|
using Void::Fsm::FsmError;
|
|
using Void::Fsm::FsmErrorCode;
|
|
using Void::Fsm::FsmLimits;
|
|
using Void::Fsm::Machine;
|
|
using Void::Fsm::MachineOptions;
|
|
using Void::Fsm::Orchestrator;
|
|
using Void::Fsm::OrchestratorLimits;
|
|
using Void::Fsm::State;
|
|
using Void::Fsm::StateId;
|
|
using Void::Fsm::StateKey;
|
|
using Void::Fsm::Status;
|
|
using Void::Fsm::SupervisionEvent;
|
|
using Void::Fsm::SupervisionMode;
|
|
using Void::Fsm::SupervisionPolicy;
|
|
using Void::Fsm::TerminationReason;
|
|
using Void::Fsm::Transition;
|
|
using namespace std::chrono_literals;
|
|
|
|
template <typename T>
|
|
Task<void> assign_task_result(Task<T> task, std::optional<T>* out)
|
|
{
|
|
*out = co_await task;
|
|
}
|
|
|
|
template <typename T>
|
|
T drive_task(Void::Async::ManualExecutor& exec, Task<T> task)
|
|
{
|
|
std::optional<T> out;
|
|
Void::Async::spawn(exec, assign_task_result(std::move(task), &out));
|
|
(void)exec.drain();
|
|
return std::move(*out);
|
|
}
|
|
|
|
struct Ping {
|
|
int value{0};
|
|
};
|
|
|
|
struct NeverEvent {
|
|
};
|
|
|
|
struct SizedEvent {
|
|
std::size_t bytes{0};
|
|
[[nodiscard]] std::size_t payload_bytes() const noexcept
|
|
{
|
|
return bytes;
|
|
}
|
|
};
|
|
|
|
// ── Supervision test machines ────────────────────────────────────────
|
|
class FaultingWorker : public Machine<FaultingWorker>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Boom : State {
|
|
Task<StateKey> run()
|
|
{
|
|
throw std::runtime_error("worker fault");
|
|
co_return succeed(0);
|
|
}
|
|
};
|
|
};
|
|
|
|
explicit FaultingWorker(std::atomic<int>* runs = nullptr)
|
|
: m_runs(runs)
|
|
{
|
|
}
|
|
|
|
protected:
|
|
|
|
void on_machine_enter() override
|
|
{
|
|
if (m_runs != nullptr) {
|
|
m_runs->fetch_add(1, std::memory_order_acq_rel);
|
|
}
|
|
}
|
|
|
|
private:
|
|
|
|
std::atomic<int>* m_runs;
|
|
};
|
|
|
|
class ParkedWorker : public Machine<ParkedWorker>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Wait : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto r =
|
|
co_await await_event_cancellable<Ping>();
|
|
if (!r) {
|
|
co_return succeed(0);
|
|
}
|
|
co_return succeed(r->value);
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
template <typename HandleT> bool wait_handle_finished(const HandleT& h)
|
|
{
|
|
for (int i = 0; i < 500; ++i) {
|
|
if (h.finished()) {
|
|
return true;
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
|
}
|
|
return h.finished();
|
|
}
|
|
|
|
// ── Scope, timer purge, exit fault, observer isolation ───────────────
|
|
class CancellableWaitFsm : public Machine<CancellableWaitFsm>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Wait : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto r =
|
|
co_await await_event_cancellable<Ping>();
|
|
if (!r) {
|
|
co_return succeed(-1);
|
|
}
|
|
co_return succeed(r->value);
|
|
}
|
|
};
|
|
};
|
|
|
|
CancellableWaitFsm() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class TimerPurgeFsm : public Machine<TimerPurgeFsm>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
std::atomic<bool>* orphaned_timer_fired{nullptr};
|
|
bool* limit_hit{nullptr};
|
|
const Void::Time::MonotonicClock* clock{nullptr};
|
|
|
|
struct States {
|
|
struct First : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto* ctx = machine().execution_context();
|
|
const auto scope = machine().active_scope();
|
|
const auto now = self().clock->now();
|
|
auto t1 = ctx->try_add_timer(
|
|
now + 20ms,
|
|
[flag = self().orphaned_timer_fired] {
|
|
if (flag != nullptr) {
|
|
flag->store(
|
|
true, std::memory_order_release);
|
|
}
|
|
},
|
|
scope);
|
|
Void::Testing::require(t1.has_value());
|
|
|
|
auto t2 = ctx->try_add_timer(
|
|
now + 30ms, [] {}, scope);
|
|
Void::Testing::require(t2.has_value());
|
|
|
|
auto t3 = ctx->try_add_timer(
|
|
now + 40ms, [] {}, scope);
|
|
if (self().limit_hit != nullptr) {
|
|
*self().limit_hit =
|
|
(!t3.has_value() &&
|
|
t3.error().code().value ==
|
|
static_cast<std::int32_t>(
|
|
FsmErrorCode::limit_exceeded));
|
|
}
|
|
co_return next<Second>();
|
|
}
|
|
};
|
|
|
|
struct Second : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await await_event_cancellable<Ping>();
|
|
co_return succeed(7);
|
|
}
|
|
};
|
|
};
|
|
|
|
TimerPurgeFsm() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class ExitThrowFsm : public Machine<ExitThrowFsm>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct S1 : State {
|
|
Task<StateKey> run() { co_return succeed(1); }
|
|
Task<void> on_exit() override
|
|
{
|
|
throw std::runtime_error("exit cleanup error");
|
|
co_return;
|
|
}
|
|
};
|
|
};
|
|
|
|
ExitThrowFsm() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class BoundedHistoryFsm : public Machine<BoundedHistoryFsm>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
int steps{0};
|
|
|
|
struct States {
|
|
struct Step : State {
|
|
Task<StateKey> run()
|
|
{
|
|
if (++self().steps >= 8) {
|
|
co_return succeed(self().steps);
|
|
}
|
|
co_return next<Step>();
|
|
}
|
|
};
|
|
};
|
|
|
|
BoundedHistoryFsm() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
// ── Structured parallel & race machines ──────────────────────────────
|
|
struct SharedRaceFlags {
|
|
std::atomic<bool> loser_exited{false};
|
|
std::atomic<bool> co_child_exited{false};
|
|
};
|
|
|
|
inline SharedRaceFlags* g_flags = nullptr;
|
|
|
|
class FastFailChild : public Machine<FastFailChild>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
using Failure = FsmError;
|
|
|
|
struct States {
|
|
struct Run : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await delay_cancellable(1ms);
|
|
co_return fail(FsmError{"winner_fail"});
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
class ForeverLoserChild : public Machine<ForeverLoserChild>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Park : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await await_event_cancellable<
|
|
NeverEvent>();
|
|
co_return succeed(0);
|
|
}
|
|
Task<void> on_exit() override
|
|
{
|
|
if (g_flags != nullptr) {
|
|
g_flags->loser_exited.store(
|
|
true, std::memory_order_release);
|
|
}
|
|
co_return;
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
class RaceParent : public Machine<RaceParent>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
using Failure = FsmError;
|
|
|
|
struct States {
|
|
struct Race : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto r = co_await run_parallel_any_structured<
|
|
FastFailChild, ForeverLoserChild>();
|
|
if (!r) {
|
|
co_return fail(
|
|
FsmError{r.error().message()});
|
|
}
|
|
if (r->index() == 0) {
|
|
auto& winner = std::get<0>(*r);
|
|
if (!winner.has_value()) {
|
|
co_return fail(winner.error());
|
|
}
|
|
}
|
|
co_return succeed(99);
|
|
}
|
|
};
|
|
};
|
|
|
|
RaceParent() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class TieChildA : public Machine<TieChildA>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Wait : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await delay_cancellable(10ms);
|
|
co_return succeed(1);
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
class TieChildB : public Machine<TieChildB>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Wait : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await delay_cancellable(5ms);
|
|
co_return succeed(2);
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
class TieRaceParent : public Machine<TieRaceParent>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Race : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto r = co_await run_parallel_any_structured<
|
|
TieChildA, TieChildB>();
|
|
if (!r) {
|
|
co_return succeed(-1);
|
|
}
|
|
co_return succeed(static_cast<int>(r->index()));
|
|
}
|
|
};
|
|
};
|
|
|
|
TieRaceParent() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class FaultParent : public Machine<FaultParent>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
std::string observed_error{};
|
|
|
|
class CoopSibling : public Machine<CoopSibling>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Park : State {
|
|
Task<StateKey> run()
|
|
{
|
|
(void)co_await await_event_cancellable<
|
|
NeverEvent>();
|
|
co_return succeed(1);
|
|
}
|
|
Task<void> on_exit() override
|
|
{
|
|
if (g_flags != nullptr) {
|
|
g_flags->co_child_exited.store(
|
|
true,
|
|
std::memory_order_release);
|
|
}
|
|
co_return;
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
class BoomSibling : public Machine<BoomSibling>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct States {
|
|
struct Boom : State {
|
|
Task<StateKey> run()
|
|
{
|
|
throw std::runtime_error(
|
|
"sibling fault");
|
|
co_return succeed(0);
|
|
}
|
|
};
|
|
};
|
|
};
|
|
|
|
struct States {
|
|
struct JoinAll : State {
|
|
Task<StateKey> run()
|
|
{
|
|
auto r = co_await run_parallel_structured<
|
|
CoopSibling, BoomSibling>();
|
|
if (!r) {
|
|
self().observed_error =
|
|
r.error().message();
|
|
co_return succeed(-1);
|
|
}
|
|
co_return succeed(1);
|
|
}
|
|
};
|
|
};
|
|
|
|
FaultParent() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
class MailboxMachine : public Machine<MailboxMachine>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
int drained{0};
|
|
|
|
struct States {
|
|
struct Drain : State {
|
|
Task<StateKey> run()
|
|
{
|
|
for (;;) {
|
|
auto ev =
|
|
co_await await_event_cancellable<
|
|
SizedEvent>();
|
|
if (!ev) {
|
|
co_return succeed(self().drained);
|
|
}
|
|
if (ev->bytes == 0) {
|
|
co_return succeed(self().drained);
|
|
}
|
|
++self().drained;
|
|
}
|
|
}
|
|
};
|
|
};
|
|
|
|
MailboxMachine() : Machine(MachineOptions{.own_worker = false}) {}
|
|
};
|
|
|
|
// ── Checkpoints, migration & service lease machines ──────────────────
|
|
struct ICounterSvc : Void::Service::IService {
|
|
virtual int version() const = 0;
|
|
};
|
|
|
|
struct CounterSvcImpl final : ICounterSvc {
|
|
int ver{1};
|
|
explicit CounterSvcImpl(int v) : ver(v) {}
|
|
std::string_view service_name() const override
|
|
{
|
|
return "CounterSvc";
|
|
}
|
|
int version() const override { return ver; }
|
|
};
|
|
|
|
class WorkflowMachine : public Machine<WorkflowMachine>
|
|
{
|
|
public:
|
|
|
|
using Success = int;
|
|
|
|
struct Data {
|
|
int count{0};
|
|
std::string note{"init"};
|
|
};
|
|
Data data;
|
|
bool fail_validation{false};
|
|
int first_handle_ver{0};
|
|
std::uint64_t first_handle_gen{0};
|
|
int second_handle_ver{0};
|
|
std::uint64_t second_handle_gen{0};
|
|
std::string seen_resume_label;
|
|
|
|
struct States {
|
|
struct [[= StateId{"v2.ingest"}]] Ingest : State {
|
|
Task<StateKey> run()
|
|
{
|
|
self().data.count += 1;
|
|
co_await safe_point("after_step1");
|
|
auto h1 = acquire_service<ICounterSvc>();
|
|
if (h1) {
|
|
self().first_handle_ver = (*h1)->version();
|
|
self().first_handle_gen = h1->generation();
|
|
}
|
|
(void)co_await await_event_cancellable<Ping>();
|
|
if (h1) {
|
|
self().first_handle_ver = (*h1)->version();
|
|
}
|
|
auto h2 = acquire_service<ICounterSvc>();
|
|
if (h2) {
|
|
self().second_handle_ver =
|
|
(*h2)->version();
|
|
self().second_handle_gen = h2->generation();
|
|
}
|
|
co_return next<Process>();
|
|
}
|
|
};
|
|
|
|
struct [[= StateId{"v2.process"}]] Process : State {
|
|
Task<StateKey> run()
|
|
{
|
|
self().seen_resume_label =
|
|
std::string{restored_resume_label()};
|
|
self().data.count += 10;
|
|
co_return succeed(self().data.count);
|
|
}
|
|
};
|
|
};
|
|
|
|
WorkflowMachine() : Machine(MachineOptions{.own_worker = false})
|
|
{
|
|
set_machine_identity("Workflow", 2);
|
|
}
|
|
|
|
protected:
|
|
|
|
void on_serialize(Void::Json::Value& out) const override
|
|
{
|
|
out = Void::Json::to_json(data);
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
on_validate_restore(const Void::Json::Value& in) const override
|
|
{
|
|
if (fail_validation) {
|
|
return Void::Result::fail(Void::Fsm::make_fsm_error(
|
|
FsmErrorCode::migration_failed,
|
|
"rejected by validator"));
|
|
}
|
|
const auto* c = in.find("count");
|
|
if (c == nullptr || !c->is_int() || c->as_int() < 0) {
|
|
return Void::Result::fail(Void::Fsm::make_fsm_error(
|
|
FsmErrorCode::migration_failed, "negative count"));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
void on_restore(const Void::Json::Value& in) override
|
|
{
|
|
auto parsed = Void::Json::from_json<Data>(in);
|
|
if (parsed.has_value()) {
|
|
data = std::move(*parsed);
|
|
}
|
|
}
|
|
};
|
|
|
|
} // namespace void_fsm_hardening_test
|
|
|
|
using namespace void_fsm_hardening_test;
|
|
|
|
// @tag reflection
|
|
Void::Testing::Test fsm_faulted_terminal_handle_and_supervision_bounds()
|
|
{
|
|
Void::Testing::expect(Void::Fsm::terminal(Status::Succeeded));
|
|
Void::Testing::expect(Void::Fsm::terminal(Status::Failed));
|
|
Void::Testing::expect(Void::Fsm::terminal(Status::Faulted));
|
|
Void::Testing::expect(!Void::Fsm::terminal(Status::Idle));
|
|
Void::Testing::expect(!Void::Fsm::terminal(Status::Running));
|
|
|
|
Void::Time::ManualClock clock;
|
|
Orchestrator orch{&clock, OrchestratorLimits{.max_supervised = 2}};
|
|
|
|
std::vector<SupervisionEvent::Kind> seen_kinds;
|
|
std::size_t inside_running_count = 999;
|
|
orch.observe_supervision([&](const SupervisionEvent& ev) {
|
|
seen_kinds.push_back(ev.kind);
|
|
// Must execute outside Orchestrator's m_mutex without deadlock.
|
|
inside_running_count = orch.running_count();
|
|
});
|
|
orch.observe_supervision([](const SupervisionEvent&) {
|
|
throw std::runtime_error("supervision observer threw");
|
|
});
|
|
|
|
// StopOnFault: FsmHandle::finished() treats Faulted as terminal, and
|
|
// handle retains immutable evidence after reap_finished().
|
|
auto h_fault = orch.try_launch<FaultingWorker>(SupervisionPolicy{});
|
|
Void::Testing::require(h_fault.has_value());
|
|
Void::Testing::require(wait_handle_finished(*h_fault));
|
|
Void::Testing::expect(h_fault->finished());
|
|
Void::Testing::expect_eq(h_fault->status(), Status::Faulted);
|
|
Void::Testing::expect_eq(h_fault->termination_reason(),
|
|
TerminationReason::faulted);
|
|
Void::Testing::require(h_fault->system_error().has_value());
|
|
|
|
Void::Testing::expect_eq(orch.reap_finished(), std::size_t{1});
|
|
Void::Testing::expect_eq(orch.running_count(), std::size_t{0});
|
|
Void::Testing::expect(h_fault->finished());
|
|
Void::Testing::expect_eq(h_fault->status(), Status::Faulted);
|
|
Void::Testing::expect(inside_running_count <= 2);
|
|
Void::Testing::expect(!orch.observer_errors().empty());
|
|
|
|
// Enforce max_supervised = 2.
|
|
auto p1 = orch.try_launch<ParkedWorker>(SupervisionPolicy{});
|
|
auto p2 = orch.try_launch<ParkedWorker>(SupervisionPolicy{});
|
|
Void::Testing::require(p1.has_value() && p2.has_value());
|
|
auto p3 = orch.try_launch<ParkedWorker>(SupervisionPolicy{});
|
|
Void::Testing::expect(!p3.has_value());
|
|
Void::Testing::expect_eq(
|
|
p3.error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::limit_exceeded));
|
|
orch.stop_all();
|
|
|
|
// BoundedRestart: 3 restarts within 60s on injected ManualClock with
|
|
// exponential backoff (10ms, 20ms, 40ms), then budget exhausted.
|
|
std::atomic<int> runs{0};
|
|
SupervisionPolicy br_policy{
|
|
.mode = SupervisionMode::BoundedRestart,
|
|
.max_restarts = 3,
|
|
.restart_window = 60s,
|
|
.initial_backoff = 10ms,
|
|
};
|
|
auto br = orch.try_launch<FaultingWorker>(br_policy, &runs);
|
|
Void::Testing::require(br.has_value());
|
|
Void::Testing::require(wait_handle_finished(*br));
|
|
|
|
const std::chrono::milliseconds backoffs[] = {10ms, 20ms, 40ms};
|
|
for (std::size_t i = 0; i < 3; ++i) {
|
|
Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1});
|
|
// Halfway through backoff: must not restart prematurely.
|
|
(void)clock.advance(backoffs[i] / 2);
|
|
Void::Testing::expect_eq(orch.supervise_step(), std::size_t{0});
|
|
Void::Testing::expect_eq(br->restart_count(), i);
|
|
|
|
(void)clock.advance(backoffs[i] - backoffs[i] / 2);
|
|
Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1});
|
|
Void::Testing::expect_eq(br->restart_count(), i + 1);
|
|
Void::Testing::require(wait_handle_finished(*br));
|
|
}
|
|
|
|
// 4th fault within 60s exhausts restart budget and releases active slot.
|
|
Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1});
|
|
Void::Testing::expect_eq(orch.running_count(), std::size_t{0});
|
|
Void::Testing::expect_eq(br->restart_count(), std::size_t{3});
|
|
Void::Testing::expect_eq(br->status(), Status::Faulted);
|
|
Void::Testing::expect_eq(runs.load(), 4);
|
|
Void::Testing::expect(!seen_kinds.empty());
|
|
}
|
|
|
|
// @tag reflection
|
|
Void::Testing::Test fsm_structured_scopes_cancellation_timers_and_exit_fault()
|
|
{
|
|
Void::Async::ManualExecutor exec;
|
|
Void::Time::ManualClock clock;
|
|
|
|
// Deadline timeout + external stop token cancellation via ExecutionBinding.
|
|
{
|
|
CancellableWaitFsm fsm;
|
|
std::optional<Void::Result::Result<CancellableWaitFsm::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock},
|
|
{.deadline = clock.now() + 50ms}),
|
|
&out));
|
|
(void)exec.drain();
|
|
Void::Testing::expect(!out.has_value());
|
|
(void)clock.advance(50ms);
|
|
(void)fsm.pump();
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value());
|
|
Void::Testing::expect(!out->has_value());
|
|
Void::Testing::expect_eq(
|
|
out->error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::timeout));
|
|
Void::Testing::expect_eq(fsm.status(), Status::Faulted);
|
|
Void::Testing::expect_eq(fsm.termination_reason(),
|
|
TerminationReason::timed_out);
|
|
}
|
|
{
|
|
CancellableWaitFsm fsm;
|
|
std::stop_source ss;
|
|
std::optional<Void::Result::Result<CancellableWaitFsm::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock},
|
|
{.stop = ss.get_token()}),
|
|
&out));
|
|
(void)exec.drain();
|
|
Void::Testing::expect(!out.has_value());
|
|
ss.request_stop();
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value());
|
|
Void::Testing::expect(!out->has_value());
|
|
Void::Testing::expect_eq(
|
|
out->error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::cancelled));
|
|
Void::Testing::expect_eq(fsm.status(), Status::Faulted);
|
|
Void::Testing::expect_eq(fsm.termination_reason(),
|
|
TerminationReason::cancelled);
|
|
}
|
|
|
|
// Queued timer after state exit must never fire + max_timers enforced.
|
|
{
|
|
std::atomic<bool> orphan_fired{false};
|
|
bool limit_hit{false};
|
|
TimerPurgeFsm fsm;
|
|
fsm.orphaned_timer_fired = &orphan_fired;
|
|
fsm.limit_hit = &limit_hit;
|
|
fsm.clock = &clock;
|
|
|
|
std::optional<Void::Result::Result<TimerPurgeFsm::Outcome<>>> out;
|
|
FsmLimits limits;
|
|
limits.max_timers = 2;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock, .limits = limits}),
|
|
&out));
|
|
(void)exec.drain();
|
|
Void::Testing::expect(limit_hit);
|
|
|
|
(void)clock.advance(100ms);
|
|
(void)fsm.pump();
|
|
(void)exec.drain();
|
|
Void::Testing::expect(!orphan_fired.load(std::memory_order_acquire));
|
|
|
|
Void::Testing::require(fsm.try_post(Ping{1}).has_value());
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value() && out->has_value() &&
|
|
out->value().has_value());
|
|
Void::Testing::expect_eq(out->value().value(), 7);
|
|
}
|
|
|
|
// on_exit exception faults the machine cleanly.
|
|
{
|
|
ExitThrowFsm fsm;
|
|
auto res = drive_task(
|
|
exec, fsm.run({.executor = &exec, .clock = &clock}));
|
|
Void::Testing::expect(!res.has_value());
|
|
Void::Testing::expect_eq(fsm.status(), Status::Faulted);
|
|
Void::Testing::expect_eq(fsm.termination_reason(),
|
|
TerminationReason::faulted);
|
|
Void::Testing::require(fsm.system_error().has_value());
|
|
}
|
|
|
|
// Observer throws isolated + bounded transition history (max 4).
|
|
{
|
|
BoundedHistoryFsm fsm;
|
|
fsm.observe([](const Transition&) {
|
|
throw std::runtime_error("observer failed");
|
|
});
|
|
fsm.add_interceptor({
|
|
.before = [](const Transition&) {
|
|
throw std::runtime_error("interceptor before failed");
|
|
},
|
|
.after = [](std::string_view) {
|
|
throw std::runtime_error("interceptor after failed");
|
|
},
|
|
});
|
|
FsmLimits limits;
|
|
limits.max_retained_transitions = 4;
|
|
auto res = drive_task(
|
|
exec,
|
|
fsm.run({.executor = &exec, .clock = &clock, .limits = limits}));
|
|
Void::Testing::require(res.has_value() && res->has_value());
|
|
Void::Testing::expect_eq(res->value(), 8);
|
|
Void::Testing::expect_eq(fsm.transition_history().size(),
|
|
std::size_t{4});
|
|
Void::Testing::expect_eq(fsm.observer_errors().size(), std::size_t{24});
|
|
}
|
|
}
|
|
|
|
// @tag reflection
|
|
Void::Testing::Test fsm_parallel_structured_loser_join_tiebreak_and_mailbox_bounds()
|
|
{
|
|
Void::Async::ManualExecutor exec;
|
|
Void::Time::ManualClock clock;
|
|
SharedRaceFlags flags;
|
|
g_flags = &flags;
|
|
|
|
// Race-any: typed Failure wins and forever-waiting loser is stopped and
|
|
// joined BEFORE run_parallel_any_structured returns.
|
|
{
|
|
RaceParent fsm;
|
|
std::optional<Void::Result::Result<RaceParent::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock}), &out));
|
|
(void)exec.drain();
|
|
Void::Testing::expect(!out.has_value());
|
|
(void)clock.advance(1ms);
|
|
(void)fsm.pump();
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value() && out->has_value());
|
|
Void::Testing::expect(!(*out)->has_value());
|
|
Void::Testing::expect_eq((*out)->error().message,
|
|
std::string{"winner_fail"});
|
|
Void::Testing::expect(flags.loser_exited.load(std::memory_order_acquire));
|
|
}
|
|
|
|
// Same-turn completion tie-break uses child declaration order (index 0).
|
|
{
|
|
TieRaceParent fsm;
|
|
std::optional<Void::Result::Result<TieRaceParent::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock}), &out));
|
|
(void)exec.drain();
|
|
// Advance clock past BOTH 5ms and 10ms in one step so both timers fire
|
|
// in the same dispatch turn -> TieChildA (index 0) must win!
|
|
(void)clock.advance(20ms);
|
|
(void)fsm.pump();
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value() && out->has_value() &&
|
|
out->value().has_value());
|
|
Void::Testing::expect_eq(out->value().value(), 0);
|
|
}
|
|
|
|
// Structured parallel-all: sibling Fault triggers cooperative stop and join.
|
|
{
|
|
FaultParent fsm;
|
|
auto res = drive_task(
|
|
exec, fsm.run({.executor = &exec, .clock = &clock}));
|
|
Void::Testing::require(res.has_value() && res->has_value());
|
|
Void::Testing::expect_eq(res->value(), -1);
|
|
Void::Testing::expect(
|
|
flags.co_child_exited.load(std::memory_order_acquire));
|
|
Void::Testing::expect(fsm.observed_error.find("sibling fault") !=
|
|
std::string::npos);
|
|
}
|
|
|
|
g_flags = nullptr;
|
|
|
|
// Mailbox event/byte caps + reserved control lane + 64-event turn budget.
|
|
{
|
|
MailboxMachine fsm;
|
|
FsmLimits limits;
|
|
limits.max_mailbox_events = 3;
|
|
limits.max_mailbox_bytes = 64;
|
|
limits.max_events_per_turn = 64;
|
|
|
|
std::optional<Void::Result::Result<MailboxMachine::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock, .limits = limits}),
|
|
&out));
|
|
(void)exec.drain();
|
|
|
|
// Byte limit check.
|
|
auto over_bytes = fsm.try_post(SizedEvent{128});
|
|
Void::Testing::expect(!over_bytes.has_value());
|
|
Void::Testing::expect_eq(
|
|
over_bytes.error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::overloaded));
|
|
|
|
// Fill 3 events.
|
|
Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value());
|
|
Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value());
|
|
Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value());
|
|
auto over_cnt = fsm.try_post(SizedEvent{8});
|
|
Void::Testing::expect(!over_cnt.has_value());
|
|
Void::Testing::expect_eq(
|
|
over_cnt.error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::overloaded));
|
|
|
|
// Reserved control lane still accepts checkpoint request under user
|
|
// mailbox saturation (timed out once clock advances).
|
|
std::optional<Void::Result::Result<Checkpoint>> cp_out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.request_checkpoint({.deadline = clock.now() + 5ms}),
|
|
&cp_out));
|
|
(void)clock.advance(5ms);
|
|
(void)fsm.pump();
|
|
(void)exec.drain();
|
|
Void::Testing::require(cp_out.has_value());
|
|
Void::Testing::expect(!cp_out->has_value());
|
|
|
|
Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value());
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value() && out->has_value() &&
|
|
out->value().has_value());
|
|
Void::Testing::expect_eq(out->value().value(), 3);
|
|
}
|
|
|
|
// 64-event turn budget on pump().
|
|
{
|
|
MailboxMachine fsm;
|
|
FsmLimits limits;
|
|
limits.max_mailbox_events = 256;
|
|
limits.max_events_per_turn = 64;
|
|
std::optional<Void::Result::Result<MailboxMachine::Outcome<>>> out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock, .limits = limits}),
|
|
&out));
|
|
(void)exec.drain();
|
|
|
|
for (int i = 0; i < 100; ++i) {
|
|
Void::Testing::require(fsm.try_post(SizedEvent{4}).has_value());
|
|
}
|
|
// One pump processes at most 64 user events before yielding.
|
|
(void)fsm.pump();
|
|
Void::Testing::expect_eq(fsm.execution_context()->last_turn_events(),
|
|
std::size_t{64});
|
|
(void)exec.drain();
|
|
Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value());
|
|
(void)exec.drain();
|
|
Void::Testing::require(out.has_value() && out->has_value() &&
|
|
out->value().has_value());
|
|
Void::Testing::expect_eq(out->value().value(), 100);
|
|
}
|
|
}
|
|
|
|
// @tag reflection
|
|
Void::Testing::Test fsm_boundary_checkpoint_migration_and_owning_service_handle()
|
|
{
|
|
Void::Async::ManualExecutor exec;
|
|
Void::Time::ManualClock clock;
|
|
|
|
// Duplicate durable StateId rejected; checkpoint at safe_point succeeds and
|
|
// survives provider swap across await via acquire_service<I>().
|
|
Void::Service::ServiceRegistry registry;
|
|
Void::Service::ProviderSet pset1;
|
|
pset1.add<ICounterSvc>("c1", std::make_shared<CounterSvcImpl>(1));
|
|
Void::Testing::require(registry.start_and_publish(std::move(pset1)).has_value());
|
|
|
|
Checkpoint captured_cp;
|
|
{
|
|
WorkflowMachine fsm;
|
|
fsm.set_services(registry);
|
|
auto dup = fsm.register_state_id<WorkflowMachine::States::Process>(
|
|
"v2.ingest");
|
|
Void::Testing::expect(!dup.has_value());
|
|
|
|
std::optional<Void::Result::Result<WorkflowMachine::Outcome<>>> out;
|
|
std::optional<Void::Result::Result<Checkpoint>> cp_out;
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.run({.executor = &exec, .clock = &clock}), &out));
|
|
Void::Async::spawn(
|
|
exec,
|
|
assign_task_result(
|
|
fsm.request_checkpoint({.deadline = clock.now() + 100ms}),
|
|
&cp_out));
|
|
(void)exec.drain();
|
|
|
|
Void::Testing::require(cp_out.has_value() && cp_out->has_value());
|
|
captured_cp = std::move(**cp_out);
|
|
Void::Testing::expect_eq(captured_cp.state_id,
|
|
std::string{"v2.ingest"});
|
|
Void::Testing::expect_eq(captured_cp.resume_label,
|
|
std::string{"after_step1"});
|
|
Void::Testing::expect_eq(captured_cp.application_schema,
|
|
std::uint32_t{2});
|
|
|
|
// Hot-swap service from v1 -> v2 while Ingest is suspended waiting for
|
|
// Ping; Ingest's held ServiceHandle<ICounterSvc> must keep v1 alive.
|
|
Void::Service::ProviderSet pset2;
|
|
pset2.add<ICounterSvc>("c2", std::make_shared<CounterSvcImpl>(2));
|
|
Void::Testing::require(
|
|
registry.start_and_publish(std::move(pset2)).has_value());
|
|
|
|
Void::Testing::require(fsm.try_post(Ping{1}).has_value());
|
|
(void)exec.drain();
|
|
|
|
Void::Testing::require(out.has_value() && out->has_value() &&
|
|
out->value().has_value());
|
|
Void::Testing::expect_eq(out->value().value(), 11);
|
|
Void::Testing::expect_eq(fsm.first_handle_ver, 1);
|
|
Void::Testing::expect_eq(fsm.first_handle_gen, std::uint64_t{1});
|
|
Void::Testing::expect_eq(fsm.second_handle_ver, 2);
|
|
Void::Testing::expect_eq(fsm.second_handle_gen, std::uint64_t{2});
|
|
}
|
|
|
|
// Validate-then-commit restore: migration failure leaves Idle machine
|
|
// unchanged; valid migration + legacy restore succeed atomically.
|
|
{
|
|
WorkflowMachine fsm;
|
|
fsm.data.count = 42;
|
|
fsm.data.note = "untouched";
|
|
|
|
Checkpoint bad_schema = captured_cp;
|
|
bad_schema.application_schema = 1;
|
|
auto r1 = fsm.restore_checkpoint(bad_schema); // no migrator
|
|
Void::Testing::expect(!r1.has_value());
|
|
Void::Testing::expect_eq(
|
|
r1.error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::schema_mismatch));
|
|
Void::Testing::expect_eq(fsm.data.count, 42);
|
|
|
|
auto r2 = fsm.restore_checkpoint(
|
|
bad_schema, [](std::uint32_t, std::uint32_t, Void::Json::Value&,
|
|
std::string&) -> Void::Result::Result<void> {
|
|
throw std::runtime_error("migrator boom");
|
|
});
|
|
Void::Testing::expect(!r2.has_value());
|
|
Void::Testing::expect_eq(
|
|
r2.error().code().value,
|
|
static_cast<std::int32_t>(FsmErrorCode::migration_failed));
|
|
Void::Testing::expect_eq(fsm.data.count, 42);
|
|
Void::Testing::expect_eq(fsm.data.note, std::string{"untouched"});
|
|
|
|
// Schema 1 -> Schema 2 valid migration onto Process with resume label.
|
|
auto r3 = fsm.restore_checkpoint(
|
|
bad_schema,
|
|
[](std::uint32_t, std::uint32_t, Void::Json::Value& data,
|
|
std::string& sid) -> Void::Result::Result<void> {
|
|
sid = "v2.process";
|
|
data = Void::Json::object();
|
|
data.as_object().emplace_back(
|
|
"count", Void::Json::Value{std::int64_t{20}});
|
|
data.as_object().emplace_back("note",
|
|
Void::Json::Value{"migrated"});
|
|
return {};
|
|
});
|
|
Void::Testing::require(r3.has_value());
|
|
auto res = drive_task(
|
|
exec, fsm.run({.executor = &exec, .clock = &clock}));
|
|
Void::Testing::require(res.has_value() && res->has_value());
|
|
Void::Testing::expect_eq(res->value(), 30);
|
|
Void::Testing::expect_eq(fsm.seen_resume_label,
|
|
std::string{"after_step1"});
|
|
}
|
|
|
|
// Explicit legacy {state, data} reader with old->durable state map.
|
|
{
|
|
WorkflowMachine fsm;
|
|
const auto legacy = Void::Json::parse(
|
|
R"({"state":"OldProcess","data":{"count":5,"note":"legacy"}})");
|
|
Void::Testing::require(legacy.has_value());
|
|
const std::unordered_map<std::string, std::string> id_map{
|
|
{"OldProcess", "v2.process"}};
|
|
auto lr = fsm.restore_legacy_checkpoint(
|
|
*legacy, id_map,
|
|
[](std::uint32_t, std::uint32_t, Void::Json::Value&,
|
|
std::string&) -> Void::Result::Result<void> { return {}; });
|
|
Void::Testing::require(lr.has_value());
|
|
auto res = drive_task(
|
|
exec, fsm.run({.executor = &exec, .clock = &clock}));
|
|
Void::Testing::require(res.has_value() && res->has_value());
|
|
Void::Testing::expect_eq(res->value(), 15);
|
|
}
|
|
}
|