Files
aevolution/src/client/session/region_session.cpp
T
dingoandClaude Opus 5.5 d2f603b582
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m25s
Foundation / postgres-tools (push) Successful in 1m12s
Foundation / server-image (push) Successful in 4m20s
Foundation / image (push) Successful in 4m54s
feat: durable liquid regions (bundle 14, schema 58), cellular-v9 and session v13
ADR-0178. Bundle 14 (rules 12 on owner format 10) is admitted by schema 58
through parser-local normalization to bundle 13, with an exact fenced 13 -> 14
upgrade whose only input, the liquid rules, recovery reads from the target.
Schema 58 also widens the canonical action input: byte 13 bit 0 is brake.

evo-world-clone gains the cellular-v9 opening: cellular-v8 followed by the liquid
upgrade from --tuning FILE (region size must match) and an optional
--current-seed; resumable and idempotent at bundle 14.

Session v13 adds the owner's velocity, heading and the region's current
configuration to its perception, each deposit's world velocity, and a brake on
cellular actions; older sessions keep their layouts. A rules-12 server lists every
pool and the nearest 256 moving bubbles. The client speaks v13, brakes on Space
(rebindable; older controls files take the default), draws currents as drifting
streaks and carries bubbles along their velocities between perceptions.

Tests: protocol v13 round trips and refusals, action-input brake, controls files,
and a PostgreSQL cellular-v9 provisioning test whose player is born, swims and
brakes through the live host. Full local PostgreSQL qualification, the Linux debug
suite and the Windows client suite pass. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 18:08:59 -04:00

476 lines
22 KiB
C++

#include "evo/client/region_session.hpp"
#include <algorithm>
#include <cstdio>
#include <utility>
namespace evo::client {
namespace {
using network::SessionCloseReason;
using Clock = std::chrono::steady_clock;
} // namespace
struct RegionSessionClient::Impl {
std::unique_ptr<network::quic::Endpoint> endpoint;
network::WireGrant grant{};
std::uint16_t protocol_version{network::session_protocol_version};
Clock::time_point deadline;
RegionSessionState state{RegionSessionState::connecting};
network::quic::ConnectionId connection{};
std::optional<network::SessionWelcome> welcome;
std::optional<SessionCloseReason> reason;
std::optional<network::quic::CloseCause> transport_cause;
std::optional<network::SessionRefreshResult> refresh_result;
std::uint64_t next_sequence{1}, server_tick{};
std::optional<network::SimulatedThrough> simulated;
std::vector<network::IntentionReceipt> intention_receipts;
std::vector<network::ActionReceipt> action_receipts;
std::vector<network::ActionOutcome> action_outcomes;
std::vector<network::PrimitiveLifeReceipt> primitive_life_receipts;
std::vector<network::PrimitiveLifeOutcome> primitive_life_outcomes;
std::optional<network::SnapshotAssembler> snapshots;
std::optional<network::CellularPerception> cellular_perception;
// First tick of a run of empty views while a cell was shown (0: none). See message().
std::uint64_t empty_since{};
std::optional<network::CellularMutationOffer> mutation_offer;
std::optional<network::CellularLifeEnded> life_ended;
std::uint64_t snapshot_chunks{}, snapshot_bytes{};
std::optional<network::HandoffOffer> handoff; // v4: continue at another region.
std::optional<network::RegionAddress> redirect; // v4: the probe is owned elsewhere.
static constexpr std::size_t max_kept = 1024; // Per kind, until taken; oldest dropped.
template <typename T> static void keep(std::vector<T>& list, const T& item) {
if (list.size() >= max_kept)
list.erase(list.begin());
list.push_back(item);
}
void seen_tick(std::uint64_t tick) {
server_tick = std::max(server_tick, tick);
}
// A protocol close names its cause on stderr: which channel, the codec or assembly
// error, or the message alternative and version that was not expected here.
void protocol_close(const char* where, int detail, std::size_t bytes) {
std::fprintf(stderr, "session protocol close: %s detail=%d bytes=%zu state=%d\n", where,
detail, bytes, static_cast<int>(state));
end(SessionCloseReason::protocol, true);
}
// Datagrams: receipts and watermarks only, after Welcome.
void datagram(std::span<const std::uint8_t> bytes) {
if (state != RegionSessionState::established)
return;
const auto decoded = network::decode_session(bytes);
if (!decoded)
return protocol_close("datagram decode", static_cast<int>(decoded.error()),
bytes.size());
if (const auto* m = std::get_if<network::IntentionReceipt>(&*decoded)) {
seen_tick(m->server_tick);
return keep(intention_receipts, *m);
}
if (const auto* m = std::get_if<network::SnapshotChunk>(&*decoded)) {
++snapshot_chunks;
snapshot_bytes += bytes.size();
seen_tick(m->tick);
if (!snapshots)
return; // Before Welcome (channels are not ordered): the next tick resends.
const auto accepted = snapshots->accept(*m);
if (!accepted) // Malformed snapshot.
return protocol_close("snapshot", static_cast<int>(accepted.error()), bytes.size());
if (const auto ack = accepted.value_or(std::nullopt); ack && connection != 0)
// A lost ack only means the next delta is against an older baseline.
(void)endpoint
->send_datagram(connection, network::encode_session(*ack, protocol_version))
.has_value();
return;
}
if (const auto* m = std::get_if<network::SimulatedThrough>(&*decoded)) {
if (!welcome || m->epoch != welcome->epoch)
return; // Another epoch's watermark says nothing about this session.
seen_tick(m->tick);
if (!simulated || m->sequence >= simulated->sequence)
simulated = *m;
return;
}
protocol_close("datagram unexpected", static_cast<int>(decoded->index()), bytes.size());
}
// An encoding refused for this session's version (empty) is never sent as success.
bool send(const network::SessionMessage& m) {
const auto bytes = network::encode_session(m, protocol_version);
return connection != 0 && !bytes.empty() &&
endpoint->send_message(connection, bytes).has_value();
}
// Ends the session locally; `tell` sends a Close first (best effort).
void end(SessionCloseReason why, bool tell) {
if (state == RegionSessionState::closed)
return;
if (tell)
(void)send(network::SessionClose{why});
state = RegionSessionState::closed;
reason = why;
grant.fill(0);
if (connection != 0)
endpoint->close(connection);
}
void message(std::span<const std::uint8_t> bytes) {
std::uint16_t wire_version{};
const auto decoded = network::decode_session(bytes, &wire_version);
if (!decoded)
return protocol_close("message decode", static_cast<int>(decoded.error()),
bytes.size());
if (wire_version != protocol_version)
return end(SessionCloseReason::unsupported_version, true);
if (const auto* m = std::get_if<network::SessionClose>(&*decoded))
return end(m->reason, false);
if (state == RegionSessionState::awaiting_welcome) {
if (const auto* m = std::get_if<network::SessionRedirect>(&*decoded)) {
redirect = m->owner; // A Close (moved) follows.
return;
}
if (const auto* m = std::get_if<network::SessionWelcome>(&*decoded)) {
welcome = *m;
snapshots.emplace(world::WorldIdentity{m->world, m->frame}, m->epoch);
seen_tick(m->server_tick);
state = RegionSessionState::established;
return;
}
} else if (state == RegionSessionState::established) {
if (const auto* m = std::get_if<network::SessionRefreshResult>(&*decoded)) {
if (m->status == 0)
welcome->expires_at = m->expires_at;
refresh_result = *m;
return;
}
if (const auto* m = std::get_if<network::ActionReceipt>(&*decoded)) {
seen_tick(m->server_tick);
return keep(action_receipts, *m);
}
if (const auto* m = std::get_if<network::ActionOutcome>(&*decoded))
return keep(action_outcomes, *m);
if (const auto* m = std::get_if<network::CellularPerception>(&*decoded)) {
seen_tick(m->tick);
// Older servers send every session an empty view each tick around the real
// one, in either order, so a lone empty view made the cell vanish for a frame
// (input stopped, the no-cell panel blinked). While a cell is shown, empty
// views count only after a second of ticks with no real view; a death still
// arrives at once as CellularLifeEnded.
constexpr std::uint64_t empty_grace_ticks = 20;
if (m->life_identity == 0 && cellular_perception &&
cellular_perception->life_identity != 0) {
if (empty_since == 0)
empty_since = m->tick;
if (m->tick < empty_since + empty_grace_ticks)
return;
}
empty_since = 0;
cellular_perception = *m;
return;
}
if (const auto* m = std::get_if<network::CellularLifeEnded>(&*decoded)) {
seen_tick(m->tick);
life_ended = *m;
mutation_offer.reset(); // A dead life has no offer.
return;
}
if (const auto* m = std::get_if<network::CellularMutationOffer>(&*decoded)) {
seen_tick(m->tick);
if (m->candidates.empty())
mutation_offer.reset();
else
mutation_offer = *m;
return;
}
if (const auto* m = std::get_if<network::PrimitiveLifeReceipt>(&*decoded)) {
seen_tick(m->server_tick);
return keep(primitive_life_receipts, *m);
}
if (const auto* m = std::get_if<network::PrimitiveLifeOutcome>(&*decoded))
return keep(primitive_life_outcomes, *m);
if (const auto* m = std::get_if<network::HandoffOffer>(&*decoded)) {
handoff = *m; // A Close (handed_off) follows.
return;
}
}
protocol_close("message unexpected",
static_cast<int>(decoded->index()) * 100 + wire_version, bytes.size());
}
};
RegionSessionClient::RegionSessionClient(std::unique_ptr<Impl> impl) : impl_{std::move(impl)} {}
RegionSessionClient::~RegionSessionClient() = default;
std::expected<std::unique_ptr<RegionSessionClient>, network::quic::EndpointError>
RegionSessionClient::connect(RegionSessionClientConfig config, Clock::time_point now) {
if (config.protocol_version != network::session_protocol_version &&
config.protocol_version != network::session_protocol_v5 &&
config.protocol_version != network::session_protocol_v6 &&
config.protocol_version != network::session_protocol_v7 &&
config.protocol_version != network::session_protocol_v8 &&
config.protocol_version != network::session_protocol_v9 &&
!network::cellular_v10_family(config.protocol_version))
return std::unexpected(network::quic::EndpointError::configuration);
auto endpoint = network::quic::Endpoint::connect(config.transport);
if (!endpoint)
return std::unexpected(endpoint.error());
auto impl = std::make_unique<Impl>();
impl->endpoint = std::move(*endpoint);
impl->protocol_version = config.protocol_version;
impl->grant = config.grant;
config.grant.fill(0);
impl->deadline = now + config.welcome_deadline;
return std::unique_ptr<RegionSessionClient>{new RegionSessionClient{std::move(impl)}};
}
void RegionSessionClient::poll(Clock::time_point now) {
auto& m = *impl_;
for (auto& e : m.endpoint->poll()) {
using network::quic::EventKind;
if (m.state == RegionSessionState::closed)
continue;
if (e.kind == EventKind::connected && m.state == RegionSessionState::connecting) {
m.connection = e.connection;
m.state = RegionSessionState::awaiting_welcome;
network::SessionHello hello;
hello.grant = m.grant;
m.grant.fill(0); // The grant is a credential: keep it no longer than needed.
if (!m.send(hello))
m.end(SessionCloseReason::connection_lost, false);
} else if (e.kind == EventKind::message) {
m.message(e.bytes);
} else if (e.kind == EventKind::datagram) {
m.datagram(e.bytes);
} else if (e.kind == EventKind::closed) {
m.transport_cause = e.cause;
m.connection = 0; // Already gone; nothing to close or send.
m.end(SessionCloseReason::connection_lost, false);
}
}
if ((m.state == RegionSessionState::connecting ||
m.state == RegionSessionState::awaiting_welcome) &&
now >= m.deadline)
m.end(SessionCloseReason::timeout, false);
}
bool RegionSessionClient::refresh(const network::WireGrant& grant) {
return impl_->state == RegionSessionState::established &&
impl_->send(network::SessionRefresh{grant});
}
std::optional<network::SessionRefreshResult> RegionSessionClient::take_refresh_result() {
return std::exchange(impl_->refresh_result, std::nullopt);
}
void RegionSessionClient::close() {
impl_->end(SessionCloseReason::client_closed, true);
}
std::optional<std::uint64_t>
RegionSessionClient::send_intention(std::uint64_t tick, std::int16_t move_x, std::int16_t move_y) {
auto& m = *impl_;
if (m.protocol_version != network::session_protocol_version ||
m.state != RegionSessionState::established || m.connection == 0 || !m.welcome)
return std::nullopt;
const network::SessionIntention intention{
m.welcome->session, m.welcome->epoch, m.next_sequence, tick, move_x, move_y};
if (!m.endpoint->send_datagram(m.connection, network::encode_session(intention)))
return std::nullopt;
return m.next_sequence++;
}
std::optional<std::uint64_t> RegionSessionClient::send_cellular_intention(
std::uint64_t tick, std::int16_t move_x, std::int16_t move_y,
std::optional<std::pair<std::uint32_t, std::uint32_t>> intake_target) {
auto& m = *impl_;
if (m.protocol_version != network::session_protocol_v6 ||
m.state != RegionSessionState::established || m.connection == 0 || !m.welcome)
return std::nullopt;
const network::CellularIntention intention{m.welcome->session,
m.welcome->epoch,
m.next_sequence,
tick,
move_x,
move_y,
intake_target.has_value(),
intake_target ? intake_target->first : 0,
intake_target ? intake_target->second : 0};
if (!m.endpoint->send_datagram(m.connection,
network::encode_session(intention, m.protocol_version)))
return std::nullopt;
return m.next_sequence++;
}
bool RegionSessionClient::send_action(std::uint64_t action_id, network::ActionKind kind,
std::uint64_t tick) {
auto& m = *impl_;
return m.protocol_version == network::session_protocol_version &&
m.state == RegionSessionState::established && m.welcome &&
m.send(network::SessionAction{m.welcome->session, m.welcome->epoch, action_id,
static_cast<std::uint16_t>(kind), tick});
}
bool RegionSessionClient::send_cellular_action(
std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y,
std::optional<std::pair<std::uint32_t, std::uint32_t>> intake_target, bool engulf, bool bud,
bool brake) {
auto& m = *impl_;
return (m.protocol_version == network::session_protocol_v7 ||
m.protocol_version == network::session_protocol_v8 ||
m.protocol_version == network::session_protocol_v9 ||
network::cellular_v10_family(m.protocol_version)) &&
m.state == RegionSessionState::established && m.welcome && action_id != 0 && tick != 0 &&
m.send(network::CellularAction{
m.welcome->session, m.welcome->epoch, action_id, tick, move_x, move_y,
intake_target.has_value(), intake_target ? intake_target->first : 0,
intake_target ? intake_target->second : 0, engulf, bud,
// A brake needs v13; older sessions never send one.
brake && m.protocol_version == network::session_protocol_v13});
}
bool RegionSessionClient::send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick,
std::uint64_t life_identity,
std::uint64_t event_index,
std::uint64_t offer_tick,
std::uint16_t operator_id) {
auto& m = *impl_;
return network::cellular_v10_family(m.protocol_version) &&
m.state == RegionSessionState::established && m.welcome && action_id != 0 &&
offer_tick != 0 && tick > offer_tick &&
m.send(network::CellularMutationAction{m.welcome->session, m.welcome->epoch, action_id,
tick, life_identity, event_index, offer_tick,
operator_id});
}
bool RegionSessionClient::query_action(std::uint64_t action_id) {
auto& m = *impl_;
return (m.protocol_version == network::session_protocol_version ||
m.protocol_version == network::session_protocol_v7 ||
m.protocol_version == network::session_protocol_v8 ||
m.protocol_version == network::session_protocol_v9 ||
network::cellular_v10_family(m.protocol_version)) &&
m.state == RegionSessionState::established && m.send(network::ActionQuery{action_id});
}
bool RegionSessionClient::request_primitive_life(std::uint64_t request_id) {
auto& m = *impl_;
return (m.protocol_version == network::session_protocol_v5 ||
m.protocol_version == network::session_protocol_v8 ||
m.protocol_version == network::session_protocol_v9 ||
network::cellular_v10_family(m.protocol_version)) &&
m.state == RegionSessionState::established && m.welcome && request_id != 0 &&
m.send(network::PrimitiveLifeRequest{m.welcome->session, m.welcome->epoch, request_id});
}
bool RegionSessionClient::query_primitive_life(std::uint64_t request_id) {
auto& m = *impl_;
return (m.protocol_version == network::session_protocol_v5 ||
m.protocol_version == network::session_protocol_v8 ||
m.protocol_version == network::session_protocol_v9 ||
network::cellular_v10_family(m.protocol_version)) &&
m.state == RegionSessionState::established && request_id != 0 &&
m.send(network::PrimitiveLifeQuery{request_id});
}
std::vector<network::PrimitiveLifeReceipt> RegionSessionClient::take_primitive_life_receipts() {
return std::exchange(impl_->primitive_life_receipts, {});
}
std::vector<network::PrimitiveLifeOutcome> RegionSessionClient::take_primitive_life_outcomes() {
return std::exchange(impl_->primitive_life_outcomes, {});
}
std::vector<network::IntentionReceipt> RegionSessionClient::take_intention_receipts() {
return std::exchange(impl_->intention_receipts, {});
}
std::vector<network::ActionReceipt> RegionSessionClient::take_action_receipts() {
return std::exchange(impl_->action_receipts, {});
}
std::vector<network::ActionOutcome> RegionSessionClient::take_action_outcomes() {
return std::exchange(impl_->action_outcomes, {});
}
std::optional<network::SimulatedThrough> RegionSessionClient::simulated() const noexcept {
return impl_->simulated;
}
std::uint64_t RegionSessionClient::server_tick() const noexcept {
return impl_->server_tick;
}
bool RegionSessionClient::set_interest(const network::SessionInterest& interest) {
auto& m = *impl_;
return (m.protocol_version == network::session_protocol_version ||
m.protocol_version == network::session_protocol_v7 ||
m.protocol_version == network::session_protocol_v8 ||
m.protocol_version == network::session_protocol_v9 ||
network::cellular_v10_family(m.protocol_version)) &&
m.state == RegionSessionState::established && m.send(interest);
}
const network::ReplicatedView* RegionSessionClient::view() const noexcept {
const auto& snapshots = impl_->snapshots;
return snapshots ? snapshots->latest() : nullptr;
}
const std::optional<network::CellularPerception>&
RegionSessionClient::cellular_perception() const noexcept {
return impl_->cellular_perception;
}
const std::optional<network::CellularMutationOffer>&
RegionSessionClient::mutation_offer() const noexcept {
return impl_->mutation_offer;
}
const std::optional<network::CellularLifeEnded>& RegionSessionClient::life_ended() const noexcept {
return impl_->life_ended;
}
std::expected<client::EnvironmentPresentation, client::ViewError>
RegionSessionClient::environment() const {
const auto& snapshots = impl_->snapshots;
if (!snapshots)
return std::unexpected(client::ViewError::empty_slice);
return snapshots->environment();
}
std::expected<client::OrganismPresentation, client::ViewError>
RegionSessionClient::organisms() const {
const auto& snapshots = impl_->snapshots;
if (!snapshots)
return std::unexpected(client::ViewError::empty_slice);
return snapshots->organisms();
}
std::uint64_t RegionSessionClient::snapshot_chunks() const noexcept {
return impl_->snapshot_chunks;
}
std::uint64_t RegionSessionClient::snapshot_bytes() const noexcept {
return impl_->snapshot_bytes;
}
std::optional<network::HandoffOffer> RegionSessionClient::take_handoff() {
return std::exchange(impl_->handoff, std::nullopt);
}
const std::optional<network::RegionAddress>& RegionSessionClient::redirect() const noexcept {
return impl_->redirect;
}
RegionSessionState RegionSessionClient::state() const noexcept {
return impl_->state;
}
const std::optional<network::SessionWelcome>& RegionSessionClient::welcome() const noexcept {
return impl_->welcome;
}
std::optional<network::quic::CloseCause> RegionSessionClient::transport_cause() const noexcept {
return impl_->transport_cause;
}
std::optional<SessionCloseReason> RegionSessionClient::close_reason() const noexcept {
return impl_->reason;
}
} // namespace evo::client