Files
aevolution/tests/client_remote_session.cpp
T
dingo 817a830a8a
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 2m23s
Foundation / checks (tsan) (push) Successful in 10m11s
Foundation / checks (client) (push) Failing after 14m26s
Foundation / checks (network) (push) Successful in 18m54s
Foundation / checks (checks) (push) Successful in 42m9s
Foundation / checks (postgres) (push) Successful in 43m51s
Foundation / postgres-tools (push) Skipped
Foundation / server-image (push) Skipped
Foundation / image (push) Skipped
ADR 0127
2026-10-15 09:32:51 -04:00

723 lines
34 KiB
C++

// M10.5c: the engineering client's remote session (apps/evo-client/remote_session.hpp)
// against a loopback region (ADR-0093): the launcher's connect flow, snapshot-fed views,
// the camera recentre and interest, intention outcomes (simulated, unknown), reconnects
// with the next grant of the bundle, and refusals (scope, superseded, exhausted).
#include "evo/client/session_host.hpp"
#include "evo/network/dev_credentials.hpp"
#include "evo/network/session_grant.hpp"
#include "evo/server/region_sessions.hpp"
#include "fixtures/fake_handoff_world.hpp"
#include "remote_session.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <functional>
#include <memory>
#include <source_location>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace {
using namespace evo;
using namespace evo::network;
using client::LaunchError;
using client::LaunchPhase;
using client::OutcomeState;
using client_app::RemoteSession;
using Clock = std::chrono::steady_clock;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("client remote session line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
template <class T> const T& required(const std::optional<T>& value) {
if (!value)
throw std::runtime_error("missing remote client test value");
return *value;
}
constexpr std::string_view name = "dev-region.evolution.test";
constexpr world::WorldIdentity world_id{7, 3};
constexpr std::uint64_t region = 12;
constexpr std::uint64_t start = 1'800'000'000;
struct Files {
std::filesystem::path dir, ca, certificate, key;
std::string ca_pem;
};
Files credentials() {
const auto made = generate_dev_credentials(DeploymentEnvironment::dev, name, 1,
std::chrono::system_clock::now());
CHECK(made.has_value());
Files f;
f.dir = std::filesystem::temp_directory_path() / "evo-client-remote-session";
std::filesystem::remove_all(f.dir);
std::filesystem::create_directories(f.dir);
f.ca_pem = made->authority_pem;
f.ca = f.dir / "ca.pem";
f.certificate = f.dir / "server.pem";
f.key = f.dir / "server.key";
for (const auto& [path, text] : {std::pair{f.ca, made->authority_pem},
std::pair{f.certificate, made->server_certificate_pem},
std::pair{f.key, made->server_key_pem}}) {
std::ofstream out{path, std::ios::binary | std::ios::trunc};
out << text;
CHECK(out.good());
}
return f;
}
AccountId account(std::uint8_t tag) {
AccountId a;
a.bytes.fill(tag);
return a;
}
std::array<std::uint8_t, grant_private_key_bytes> scalar() {
std::array<std::uint8_t, grant_private_key_bytes> s{};
s.back() = 0x2B;
return s;
}
client::EnvironmentCell cell(std::int64_t x, std::int64_t y, std::uint64_t quantity) {
client::EnvironmentCell c;
c.voxel = {x, y, -7};
c.chunk_revision = 40;
c.habitat = {{100}, {200}, {0}, {1000}, {500}, {10}};
c.volume = {1000ULL * 500 * 10};
c.substrate = {1};
c.terrain_material = {2};
c.terrain_fill = 1000;
c.presence[0] = client::FieldPresence::present;
c.quantity[0] = quantity;
c.presence[1] = client::FieldPresence::missing;
c.presence[7] = client::FieldPresence::present;
c.quantity[7] = 5;
c.moisture_status = world::MoistureStatus::available; // Water is requested.
c.moisture = {3, 50};
return c;
}
// A region on loopback with a 21 x 21 slice (x, y in -10..10 at z -7), one snapshot per tick.
struct Region {
explicit Region(const Files& f,
const std::function<void(server::RegionSessionsConfig&)>& configure = {})
: files{f} {
server::RegionSessionsConfig c;
c.transport.certificate_pem_file = f.certificate.string();
c.transport.key_pem_file = f.key.string();
c.control.environment = DeploymentEnvironment::dev;
c.control.world = world_id;
c.control.region = region;
c.control.epoch = epoch;
c.control.max_account_attempts = 16;
c.issuer_keys.push_back({1, *key.public_key()});
if (configure)
configure(c);
const bool cellular = c.accept_cellular_actions;
auto made = server::RegionSessions::create(std::move(c));
CHECK(made.has_value());
sessions = std::move(*made);
sessions->set_default_interest({3, 3, -7, 7});
// Probe markers (ADR-0094) over the slice's cells, spawning in the middle of (3, 3).
if (!cellular)
CHECK(sessions->set_motion_area({-10'000'000, -10'000'000, 10'999'999, 10'999'999, -7},
3'500'000, 3'500'000));
}
WireGrant grant(const AccountId& who, std::uint64_t serial,
std::uint64_t in_region = region) const {
GrantClaims c;
c.grant_id = 900 + serial;
c.account = who;
c.serial = serial;
c.world = world_id;
c.region = in_region;
c.issued_at = start;
c.expires_at = start + 120;
const auto g = key.sign(c);
CHECK(g.has_value());
return *g;
}
// The launcher's material: the endpoint by host name, as a tester types it.
client::ConnectMaterial material(std::vector<WireGrant> grants) const {
return {{"localhost", sessions->port()},
std::string{name},
files.ca_pem,
files.ca.string(),
std::move(grants)};
}
void pump() {
sessions->poll({true, epoch, tick}, start + 1, Clock::now());
if (tick != replicated) {
replicated = tick;
sessions->replicate(tick, [&](const SessionInterest&) {
ReplicationSource s;
s.identity = world_id;
s.field_revision = tick;
s.mask = (1U << 0) | (1U << 1) | (1U << 7);
for (std::int64_t x = -10; x <= 10; ++x)
for (std::int64_t y = -10; y <= 10; ++y)
s.environment.push_back(cell(x, y, 30));
return s;
});
}
static_cast<void>(sessions->take_events());
if (after_poll)
after_poll();
}
const Files& files;
GrantSigningKey key = *GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar());
std::unique_ptr<server::RegionSessions> sessions;
std::uint64_t epoch{3}, tick{100}, replicated{};
std::function<void()> after_poll;
};
struct Client {
client::SessionHost<RemoteSession> host;
client::UiState ui;
client::Intention intention;
// Steps the region and the client together (one region tick every `tick_every`
// iterations, 0: none) until `done` or the limit.
bool until(Region& r, const std::function<bool()>& done, int tick_every = 0,
std::chrono::milliseconds limit = std::chrono::milliseconds{15000}) {
const auto end = Clock::now() + limit;
for (int i = 1; Clock::now() < end; ++i) {
r.pump();
if (tick_every != 0 && i % tick_every == 0)
++r.tick;
host.step(Clock::now(), intention, ui);
if (done())
return true;
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
return done();
}
[[nodiscard]] LaunchPhase phase() const {
return host.launcher().phase();
}
[[nodiscard]] std::size_t cells() const {
const auto* s = host.session();
const auto* e = s ? s->environment().current() : nullptr;
return e ? e->cells().size() : 0;
}
[[nodiscard]] bool has(OutcomeState state) const {
const auto* s = host.session();
return s && std::ranges::any_of(s->outcomes().entries(),
[&](const auto& e) { return e.state == state; });
}
};
void views_interest_and_intentions(Region& r) {
Client c;
CHECK(c.host.connect(
RemoteSession::open(r.material({r.grant(account(1), 1), r.grant(account(1), 2)}))));
CHECK(c.until(r, [&] { return c.phase() == LaunchPhase::connected; }));
// The default interest (3, 3, radius 7) arrives as the copied view.
CHECK(c.until(r, [&] { return c.cells() == 225; }, 20));
auto& s = *c.host.session();
const auto* view = s.environment().current();
CHECK(view != nullptr && view->slice_z() == -7 &&
std::ranges::all_of(view->cells(), [](const auto& e) {
return e.voxel.x >= -4 && e.voxel.x <= 10 && e.voxel.y >= -4 && e.voxel.y <= 10;
}));
CHECK(s.environment().freshness() == client::Freshness::current);
// The session's probe marker, predicted at its spawn; the camera follows it, and so does
// the interest (its cell is the default's centre: the same view).
CHECK(c.until(r, [&] { return s.status().marker; }, 20));
CHECK(s.markers().size() == 1 && s.markers()[0].own && s.status().marker_x_mm == 3500);
const auto centre = s.take_recentre().value_or(client::WorldPoint{-1, -1});
CHECK(centre.x_mm == 3500 && centre.y_mm == 3500 && !s.take_recentre());
s.focus(centre); // Where the session put it: still following.
static_cast<void>(c.until(r, [] { return false; }, 20, std::chrono::milliseconds{300}));
CHECK(s.status().focused && s.status().focus_x == 3 && s.status().focus_y == 3 &&
c.cells() == 225); // 300 ms of ticks: the same view.
// The user moves the camera: its centre's voxel becomes the interest (clipped).
s.focus({-5500, -5200});
CHECK(c.until(r, [&] { return c.cells() == 144; }, 20)); // x, y in -10..1.
const auto status = s.status();
CHECK(status.focused && status.focus_x == -6 && status.focus_y == -6 && status.focus_z == -7 &&
status.phase == "connected" && status.grants_left == 1 && status.snapshot_bytes > 0);
// An intention: sent once per change, admitted, then simulated (never durable).
c.intention.move_x = 700;
CHECK(c.until(r, [&] { return c.has(OutcomeState::admitted); }));
CHECK(c.until(r, [&] { return c.has(OutcomeState::simulated); }, 20));
const auto& first = s.outcomes().entries().front();
CHECK(first.sequence == 1 && first.tick != 0 && s.status().simulated_tick >= first.tick);
// The marker moves +x at 70 mm per tick, predicted ahead of the authority, and the
// authority confirms the prediction (loopback: no correction needed).
CHECK(c.until(r, [&] { return s.status().marker_x_mm > 4000; }, 20));
CHECK(s.status().marker_y_mm == 3500 && s.status().max_error_um == 0 &&
s.status().inputs_pending == 0);
// A new epoch closes the session: the open intention is unknown, the views are stale,
// and the session reconnects with the bundle's next grant after its pause.
const auto old_session = s.status().session;
c.intention.move_x = -700;
CHECK(c.until(r, [&] { return c.has(OutcomeState::admitted) || c.has(OutcomeState::sent); }));
r.epoch = 4;
CHECK(c.until(r, [&] { return c.has(OutcomeState::unknown); }));
CHECK(s.environment().freshness() == client::Freshness::stale);
CHECK(s.outcomes().entries().size() == 2 && s.outcomes().entries()[1].sequence == 2 &&
s.outcomes().entries()[1].state == OutcomeState::unknown);
// The lost session's view stays frozen and stale (ADR-0095): the own marker at its last
// authoritative position, nothing moving while reconnecting.
const auto frozen = s.status();
CHECK(frozen.stale_view && frozen.marker && frozen.stale_markers == s.markers().size() &&
std::ranges::all_of(s.markers(), [](const auto& m) { return m.stale; }));
CHECK(c.until(r, [&] { return s.status().phase == "connected"; }, 20));
CHECK(!s.status().stale_view);
CHECK(s.status().epoch == 4 && s.status().session != old_session &&
s.status().grants_left == 0 && c.phase() == LaunchPhase::connected);
// Views restart for the new epoch, at the camera's interest (sent again).
CHECK(c.until(r, [&] { return c.cells() == 144 && s.status().snapshot_tick > 0; }, 20));
// The current intention is sent again in the new session; the record numbers it on
// (session sequences restart) and keeps the earlier entries.
CHECK(c.until(r, [&] { return s.outcomes().entries().size() == 3; }));
CHECK(s.outcomes().entries()[0].state == OutcomeState::simulated &&
s.outcomes().entries()[2].sequence == 3);
// Another client with a newer grant for the account supersedes this one: no fight back.
Client other;
CHECK(other.host.connect(RemoteSession::open(r.material({r.grant(account(1), 9)}))));
CHECK(other.until(r, [&] {
c.host.step(Clock::now(), c.intention, c.ui);
return c.phase() == LaunchPhase::failed && other.phase() == LaunchPhase::connected;
}));
CHECK(c.host.launcher().error() == LaunchError::grant_refused && !c.host.session());
}
// Two sessions: each sees the other's marker interpolated a few ticks behind its
// authoritative path; a session that leaves takes its marker with it (ADR-0095).
void remote_markers(Region& r) {
Client a, b;
CHECK(a.host.connect(RemoteSession::open(r.material({r.grant(account(7), 1)}))));
CHECK(b.host.connect(RemoteSession::open(r.material({r.grant(account(8), 1)}))));
const auto both = [&] {
a.host.step(Clock::now(), a.intention, a.ui);
return a.phase() == LaunchPhase::connected && b.phase() == LaunchPhase::connected &&
a.host.session()->status().marker && b.host.session()->status().other_markers == 1;
};
CHECK(b.until(r, both, 20));
auto& sa = *a.host.session();
auto& sb = *b.host.session();
a.intention.move_y = 1000; // A walks +y at 100 mm per tick.
const auto drive = [&](auto done) {
return b.until(
r,
[&] {
a.host.step(Clock::now(), a.intention, a.ui);
return done();
},
20);
};
const auto remote = [&] {
const auto it = std::ranges::find_if(sb.markers(), [](const auto& m) { return !m.own; });
CHECK(it != sb.markers().end());
return *it;
};
CHECK(drive([&] { return remote().y_mm > 4500; }));
// B shows A in the recent past: behind A's own (predicted) view, never ahead of it.
const auto seen = remote();
CHECK(!seen.stale && seen.x_mm == 3500 && seen.y_mm < sa.status().marker_y_mm &&
sb.status().interpolation_delay >= 2 && sb.status().interpolation_delay <= 6);
// A leaves: its marker disappears from B's view.
a.host.cancel();
CHECK(drive([&] { return sb.status().other_markers == 0; }));
}
void refusals(Region& r) {
// A grant for another region: refused before any Welcome; the launcher stops.
Client wrong;
CHECK(wrong.host.connect(RemoteSession::open(r.material({r.grant(account(2), 1, 99)}))));
CHECK(wrong.until(r, [&] { return wrong.phase() == LaunchPhase::failed; }));
CHECK(wrong.host.launcher().error() == LaunchError::grant_refused);
// One grant: once its session ends there is nothing to reconnect with.
Client one;
CHECK(one.host.connect(RemoteSession::open(r.material({r.grant(account(3), 1)}))));
CHECK(one.until(r, [&] { return one.phase() == LaunchPhase::connected; }));
r.epoch = 5;
CHECK(one.until(r, [&] { return one.phase() == LaunchPhase::failed; }));
CHECK(one.host.launcher().error() == LaunchError::grants_exhausted);
// A used grant spends only itself: the next grant in the bundle connects, and a bundle
// of used grants ends as exhausted rather than refused.
Client first;
CHECK(first.host.connect(RemoteSession::open(r.material({r.grant(account(5), 2)}))));
CHECK(first.until(r, [&] { return first.phase() == LaunchPhase::connected; }));
first.host.cancel();
Client next;
CHECK(next.host.connect(RemoteSession::open(
r.material({r.grant(account(5), 1), r.grant(account(5), 2), r.grant(account(5), 3)}))));
CHECK(next.until(r, [&] { return next.phase() == LaunchPhase::connected; }, 20));
next.host.cancel();
Client used;
CHECK(used.host.connect(
RemoteSession::open(r.material({r.grant(account(5), 2), r.grant(account(5), 3)}))));
CHECK(used.until(r, [&] { return used.phase() == LaunchPhase::failed; }, 20));
CHECK(used.host.launcher().error() == LaunchError::grants_exhausted);
// Nothing to open: an unresolvable endpoint or an empty bundle.
auto bad = r.material({r.grant(account(4), 1)});
bad.endpoint.host = "no-such-host.invalid";
CHECK(!RemoteSession::open(bad));
CHECK(!RemoteSession::open(r.material({})));
auto cellular = RemoteSession::open(r.material({r.grant(account(6), 1)}), true);
CHECK(cellular && cellular->cellular_trial() && cellular->status().cellular_trial &&
cellular->cellular_perception() == nullptr);
}
// M10.8c-2 (ADR-0096): the client follows a crossing into the next region with the offer's
// ticket (no grant, no pause, the view kept) and follows a redirect at login, picking grants
// by region from a two-region bundle in rising serial order.
void crossing_regions(const Files& f) {
using evo::test::RegionDb;
using evo::test::WorldDb;
constexpr std::int64_t m = 1'000'000;
const auto area = [](std::int64_t x0) {
return network::motion::Area{x0, 0, x0 + (10 * m) - 1, (10 * m) - 1, 0};
};
WorldDb world;
RegionDb db1{world, 1}, db2{world, 2};
auto key1 = std::make_shared<const HandoffSigningKey>(
*HandoffSigningKey::generate(DeploymentEnvironment::dev, 41));
auto key2 = std::make_shared<const HandoffSigningKey>(
*HandoffSigningKey::generate(DeploymentEnvironment::dev, 42));
auto imported = GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar());
CHECK(imported.has_value());
const auto& issuer = *imported;
const auto make = [&](std::uint64_t id, RegionDb& db,
std::shared_ptr<const HandoffSigningKey> own,
const HandoffSigningKey& neighbour_key, std::uint64_t neighbour,
std::uint16_t neighbour_port, std::uint16_t port) {
server::RegionSessionsConfig c;
c.transport.certificate_pem_file = f.certificate.string();
c.transport.key_pem_file = f.key.string();
c.transport.port = port;
c.control.environment = DeploymentEnvironment::dev;
c.control.world = world_id;
c.control.region = id;
c.control.epoch = 3;
c.control.max_account_attempts = 16;
c.issuer_keys.push_back({1, *issuer.public_key()});
c.ledger = &db;
c.handoff = &db;
c.probes = &db;
c.handoff_key = std::move(own);
c.handoff_keys.push_back(
{neighbour, static_cast<std::uint32_t>(neighbour + 40), *neighbour_key.public_key()});
c.neighbours.push_back(
{{neighbour, "localhost:" + std::to_string(neighbour_port), std::string{name}},
area(neighbour == 1 ? 0 : 10 * m)});
c.life_owner_routes = {
server::LifeOwnerRoute{
RegionAddress{id, "localhost:" + std::to_string(port), std::string{name}}},
server::LifeOwnerRoute{RegionAddress{
neighbour, "localhost:" + std::to_string(neighbour_port), std::string{name}}}};
c.ghost_poll = std::chrono::milliseconds{20};
auto made = server::RegionSessions::create(std::move(c));
CHECK(made.has_value());
const auto x0 = id == 1 ? 0 : 10 * m;
CHECK((*made)->set_motion_area(area(x0), x0 + (5 * m), 5 * m));
(*made)->set_default_interest({(x0 / m) + 5, 5, 0, 7});
return std::move(*made);
};
// Reserve both ports using throwaway listeners so each world route is complete.
std::uint16_t port1 = 0, port2 = 0;
{
auto probe = make(1, db1, key1, *key2, 2, 1, 0);
port1 = probe->port();
}
{
auto probe = make(2, db2, key2, *key1, 1, port1, 0);
port2 = probe->port();
}
auto r1 = make(1, db1, key1, *key2, 2, port2, port1);
auto r2 = make(2, db2, key2, *key1, 1, port1, port2);
std::uint64_t tick = 100;
const auto grants = [&](const AccountId& who, std::uint64_t first) {
std::vector<WireGrant> out;
for (std::uint64_t i = 0; i < 4; ++i) {
GrantClaims c;
c.grant_id = 5000 + first + i;
c.account = who;
c.serial = first + i;
c.world = world_id;
c.region = (i % 2) + 1; // Interleaved: region 1, 2, 1, 2.
c.issued_at = start;
c.expires_at = start + 120;
out.push_back(*issuer.sign(c));
}
return out;
};
const auto material = [&](std::vector<WireGrant> g) {
return client::ConnectMaterial{
{"localhost", r1->port()}, std::string{name}, f.ca_pem, f.ca.string(), std::move(g)};
};
const auto pump = [&](const std::vector<Client*>& clients, const std::function<bool()>& done) {
const auto end = Clock::now() + std::chrono::seconds{20};
for (int i = 1; Clock::now() < end; ++i) {
if (i % 5 == 0)
++tick;
for (auto* r : {r1.get(), r2.get()}) {
r->poll({true, 3, tick}, start + 1, Clock::now());
r->replicate(tick, [](const SessionInterest&) {
ReplicationSource s;
s.identity = world_id;
return s;
});
static_cast<void>(r->take_events());
}
for (auto* c : clients)
c->host.step(Clock::now(), c->intention, c->ui);
if (done())
return true;
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
return done();
};
const auto dana = account(31);
Client a;
CHECK(a.host.connect(RemoteSession::open(material(grants(dana, 10)))));
auto& s = *a.host.session();
CHECK(pump({&a}, [&] { return s.status().phase == "connected" && s.status().marker; }));
CHECK(s.status().region == 1 && s.status().marker_x_mm == 5000);
// Walking east: the crossing is followed into region 2 with the ticket, no grant used.
a.intention.move_x = 1000;
const auto left = s.status().grants_left;
CHECK(pump({&a}, [&] {
const auto st = s.status();
return st.region == 2 && st.phase == "connected" && st.handoffs == 1 && st.marker;
}));
CHECK(s.status().grants_left == left && a.phase() == LaunchPhase::connected &&
world.probes.at(dana).owner == 2 && s.status().marker_x_mm >= 10'000);
a.intention.move_x = 0;
// A second client with a newer bundle logs in at region 1 and is redirected to region 2,
// where it takes over (the first is superseded). The active life owner lookup must
// redirect before region 1's durable control claim.
world.life_owners[dana] = 2;
const auto region1_claims = db1.claims;
const auto region2_claims = db2.claims;
Client b;
CHECK(b.host.connect(RemoteSession::open(material(grants(dana, 20)))));
auto& t = *b.host.session();
CHECK(
pump({&a, &b}, [&] { return t.status().region == 2 && t.status().phase == "connected"; }));
CHECK(a.phase() == LaunchPhase::failed && world.probes.at(dana).owner == 2);
CHECK(db1.claims == region1_claims && db2.claims == region2_claims + 1);
}
void cellular_birth_without_view(const Files& files) {
test::WorldDb world;
test::RegionDb control{world, region};
const auto owner = account(0xD1);
std::vector<std::uint64_t> requests;
auto answer = PrimitiveLifeResult::pending;
Region r{files, [&](server::RegionSessionsConfig& config) {
config.ledger = &control;
config.accept_cellular_actions = true;
config.create_primitive_life = [&](const AccountId& a, std::uint64_t generation,
std::uint64_t id) {
CHECK(a == owner && generation != 0);
requests.push_back(id);
return PrimitiveLifeOutcome{id, answer, 901, 0};
};
config.query_primitive_life = config.create_primitive_life;
}};
Client c;
CHECK(c.host.connect(RemoteSession::open(r.material({r.grant(owner, 1)}), true)));
CHECK(c.until(r, [&] { return requests.size() >= 2; }));
auto& remote = *c.host.session();
CHECK(requests[0] == requests[1] && !remote.cellular_play().can_restart() &&
!remote.cellular_perception());
answer = PrimitiveLifeResult::insufficient_funding;
CHECK(c.until(r, [&] { return remote.cellular_play().can_restart(); }));
CHECK(!remote.cellular_play().fresh() &&
remote.status().cellular_action.find("nursery lacks resources") != std::string::npos);
CHECK(remote.restart_cellular() && !remote.restart_cellular());
answer = PrimitiveLifeResult::no_placement;
CHECK(c.until(r, [&] { return remote.cellular_play().can_restart(); }));
CHECK(requests.back() != requests.front() && !remote.cellular_perception());
}
// Real RemoteSession over QUIC; the fixture records authority answers without simulating biology.
void cellular_v10(const Files& files) {
using namespace evo::client_app;
struct Ledger final : ActionLedger {
std::map<std::uint64_t, DurableActionRecord> records;
std::expected<std::optional<ActionOutcome>, ActionLedgerError>
find(const AccountId&, std::uint64_t id) override {
return records.contains(id) ? std::optional{records.at(id).outcome} : std::nullopt;
}
std::expected<std::optional<DurableActionRecord>, ActionLedgerError>
find_record(const AccountId&, std::uint64_t id) override {
return records.contains(id) ? std::optional{records.at(id)} : std::nullopt;
}
} ledger;
test::WorldDb world;
test::RegionDb control{world, region};
std::vector<CellularMutationAction> mutations;
std::vector<std::uint64_t> births;
std::uint64_t life = 0, next_life = 901;
bool resolve_mutation = false;
const auto owner = account(0xD0);
Region r{files, [&](server::RegionSessionsConfig& config) {
config.ledger = &control;
config.actions = &ledger;
config.accept_cellular_actions = true;
config.create_primitive_life = [&](const AccountId& a, std::uint64_t generation,
std::uint64_t id) {
CHECK(a == owner && generation != 0);
births.push_back(id);
life = next_life;
return PrimitiveLifeOutcome{id, PrimitiveLifeResult::born, life, 1};
};
config.query_primitive_life = config.create_primitive_life;
config.select_cellular_mutation = [&](const AccountId& a, std::uint64_t generation,
const CellularMutationAction& m) {
CHECK(a == owner && generation != 0);
mutations.push_back(m);
return server::CellularMutationAnswer{
resolve_mutation ? AdmitStatus::duplicate : AdmitStatus::admitted, 102,
resolve_mutation ? std::optional{ActionOutcome{
m.action_id, ActionResult::committed, 102, 3}}
: std::nullopt};
};
}};
std::uint64_t sent_view{}, view_session{}, sent_life{};
bool offer = true;
r.after_poll = [&] {
const auto session = r.sessions->holder(owner);
if (!session || (sent_view == r.tick && view_session == *session && sent_life == life))
return;
sent_view = r.tick;
view_session = *session;
sent_life = life;
CHECK(r.sessions->send_cellular_perception(
owner,
{r.tick, life, {}, life ? std::optional{CellularLifeDiagnostics{}} : std::nullopt}));
if (offer && life != 0)
CHECK(r.sessions->send_mutation_offer(owner,
{r.tick, life, 1, 99, {{3, 2, 0, 50, 20, 30}}}));
};
Client c;
CHECK(c.host.connect(
RemoteSession::open(r.material({r.grant(owner, 1), r.grant(owner, 2)}), true)));
CHECK(c.until(r, [&] { return c.host.session()->cellular_play().offer().has_value(); }));
auto& remote = *c.host.session();
CHECK(!births.empty() && remote.cellular_play().life() == 901);
CHECK(remote.request_cellular(CellAction::mutation, {901, 1, 99, 3}));
CHECK(!remote.request_cellular(CellAction::mutation, {901, 1, 99, 3}));
CHECK(c.until(r, [&] {
return !mutations.empty() &&
required(remote.cellular_play().pending()).state == CellActionState::admitted;
}));
const auto original = mutations.front();
r.sessions->shutdown(Clock::now());
CHECK(c.until(r, [&] { return remote.status().phase == "reconnecting"; }));
CHECK(!remote.request_cellular(CellAction::bud));
resolve_mutation = true;
CHECK(c.until(r, [&] { return !remote.cellular_play().history().empty(); }, 20));
CHECK(mutations.size() >= 2 && mutations.back().action_id == original.action_id &&
mutations.back().life_identity == original.life_identity &&
mutations.back().tick == original.tick &&
mutations.back().operator_id == original.operator_id && births.size() == 1);
CHECK(remote.cellular_play().history().back().state == CellActionState::committed);
// No patch coordinates or intake accompany a bud; one request creates one carried action.
remote.set_cellular_feed_target({{1000, 2000}});
CHECK(remote.request_cellular(CellAction::bud));
CHECK(!remote.cellular_feed_target());
const auto bud_id = required(remote.cellular_play().pending()).id;
std::optional<CarriedAction> bud;
CHECK(c.until(
r,
[&] {
for (const auto& carried : r.sessions->carry(r.tick + 1))
if (carried.action_id == bud_id)
bud = carried;
return bud.has_value();
},
20));
CHECK(required(bud).cellular_input);
const auto input = decode_cellular_action_input(required(required(bud).cellular_input));
CHECK(input && input->bud && !input->engulf && !input->has_intake_target);
ledger.records.emplace(
bud_id, DurableActionRecord{{bud_id, ActionResult::committed, required(bud).tick, 4},
required(bud).cellular_input});
r.sessions->committed(std::span{&required(bud), 1}, 4);
CHECK(c.until(r, [&] { return !remote.cellular_play().pending(); }));
CHECK(remote.cellular_play().history().back().id == bud_id);
CHECK(remote.request_cellular(CellAction::engulf));
const auto engulf_id = required(remote.cellular_play().pending()).id;
std::optional<CarriedAction> engulf;
CHECK(c.until(
r,
[&] {
for (const auto& carried : r.sessions->carry(r.tick + 1))
if (carried.action_id == engulf_id)
engulf = carried;
return engulf.has_value();
},
20));
CHECK(required(engulf).cellular_input);
const auto engulf_input =
decode_cellular_action_input(required(required(engulf).cellular_input));
CHECK(engulf_input && engulf_input->engulf && !engulf_input->bud &&
!engulf_input->has_intake_target);
r.sessions->dropped(std::span{&required(engulf), 1}, true);
CHECK(c.until(r, [&] { return !remote.cellular_play().pending(); }));
// Death and a fresh request on the same connection. Repeated UI clicks issue only one.
offer = false;
life = 0;
++r.tick;
CHECK(r.sessions->send_life_ended(owner, {r.tick, 901, CellularDeathReason::starved}));
CHECK(c.until(r, [&] { return remote.cellular_play().can_restart(); }));
CHECK(required(remote.cellular_play().ended()).cause == CellularDeathReason::starved);
CHECK(remote.restart_cellular() && !remote.restart_cellular());
next_life = 902;
++r.tick;
CHECK(c.until(r, [&] { return births.size() == 2 && remote.cellular_play().life() == 902; }));
CHECK(births[0] != births[1] && !remote.cellular_play().ended());
}
} // namespace
int main() try {
using namespace std::string_view_literals;
using evo::client_app::cellular_admission_message;
using evo::client_app::cellular_outcome_message;
using evo::network::ActionResult;
using evo::network::AdmitStatus;
const std::array admissions{std::pair{AdmitStatus::admitted, "accepted"sv},
std::pair{AdmitStatus::unknown_session, "no longer active"sv},
std::pair{AdmitStatus::stale_epoch, "session changed"sv},
std::pair{AdmitStatus::outside_window, "tick"sv},
std::pair{AdmitStatus::rate_limited, "too many"sv},
std::pair{AdmitStatus::replayed, "already used"sv},
std::pair{AdmitStatus::invalid_vector, "vector is invalid"sv},
std::pair{AdmitStatus::too_many_unresolved, "unresolved"sv},
std::pair{AdmitStatus::invalid_action, "invalid action"sv},
std::pair{AdmitStatus::duplicate, "Duplicate action"sv},
std::pair{AdmitStatus::not_ready, "recovering"sv}};
for (const auto& [status, phrase] : admissions)
CHECK(cellular_admission_message(status).find(phrase) != std::string_view::npos);
const std::array outcomes{
std::pair{ActionResult::committed_no_effect, "without a state change"sv},
std::pair{ActionResult::not_committed, "no change"sv},
std::pair{ActionResult::pending, "waiting"sv},
std::pair{ActionResult::unknown, "no durable result"sv},
std::pair{ActionResult::committed, "patch stock"sv}};
for (const auto& [result, phrase] : outcomes)
CHECK(cellular_outcome_message(result, 23).find(phrase) != std::string::npos);
const auto files = credentials();
{
Region r{files};
views_interest_and_intentions(r);
remote_markers(r);
refusals(r);
}
crossing_regions(files);
cellular_v10(files);
cellular_birth_without_view(files);
std::filesystem::remove_all(files.dir);
std::puts("client remote session tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}