Add M10.4a intentions, actions and admission
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 1m45s
Foundation / checks (network) (push) Successful in 9m37s
Foundation / checks (client) (push) Successful in 12m14s
Foundation / checks (tsan) (push) Successful in 7m39s
Foundation / checks (checks) (push) Successful in 31m15s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 32m59s

Session protocol v1 (not yet deployed, amended in place) gains realtime intentions on
datagrams with receipts and a cumulative simulated watermark, and account-scoped
actions with stable ids, receipts, final outcomes and queries. IntentAdmission
enforces session binding, rate, authority, epoch, vector, sequence, tick window,
duplicates and the unresolved bound; RegionSessions and the client carry it over
QUIC. Intentions and actions have no biological effect yet. ADR-0092.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-03 22:09:06 -04:00
co-authored by Claude Opus 5.5
parent 890c57a77f
commit e2f6208433
18 changed files with 1155 additions and 48 deletions
+1 -1
View File
@@ -32,7 +32,7 @@ add_subdirectory("${mbedtls_source}" "${PROJECT_BINARY_DIR}/mbedtls" EXCLUDE_FRO
# Dependency-free protocol: framing, envelopes, admission. No Mbed TLS types.
add_library(evo_network_protocol STATIC src/network/protocol/codec.cpp
src/network/protocol/admission.cpp src/network/protocol/session_control.cpp
src/network/protocol/session_protocol.cpp)
src/network/protocol/session_protocol.cpp src/network/protocol/intent_admission.cpp)
target_link_libraries(evo_network_protocol PUBLIC evo_client_views evo_client_controls)
evo_owned_target(evo_network_protocol)
# Mbed TLS adapters: dev grants (HMAC-SHA256 via PSA) and the TLS 1.3 channel.
+3 -2
View File
@@ -521,8 +521,9 @@ hardware (10.9). 10.2 split: 10.2a selection, pins and build of msquic/OpenSSL d
10.2c loss/head-of-line measurements done (networking/M10_TRANSPORT_MEASUREMENTS.md).
10.3 split (ADR-0091): 10.3a account ids, ECDSA grants, identity adapter and region
session control done; 10.3b QUIC session login (schemas/network/session-v1.md) done;
10.3c durable per-world account control (schema v10) done. Process wiring into
evo-server and the client comes with 10.4. 10.4-10.9 planned.
10.3c durable per-world account control (schema v10) done. 10.4 split (ADR-0092):
10.4a intention/action protocol and admission done; 10.4b durable action records and
10.4c evo-server wiring with a headless client follow. 10.5-10.9 planned.
**Entry:** M9 client/session evidence and M7/M8 dev/stage durability. Read
NETWORK_ARCHITECTURE, PERSISTENCE_ARCHITECTURE and ADR-0017. The M9 transport is
+6 -2
View File
@@ -24,8 +24,12 @@ session login over QUIC (session-v1: Hello, Welcome, Refresh, Close with reasons
the region and client side, tested end to end on loopback. M10.3c adds durable per-world
account control (schema v10): grant serials survive restarts and apply across regions,
cross-region takeover waits out the previous holder, and sessions close when their
control is fenced or cannot be renewed. Next: M10.4 intentions and durable outcomes,
including wiring M10 sessions into evo-server and the client.
control is fenced or cannot be renewed. M10.4a (ADR-0092) adds
intentions (datagram receipts and a cumulative simulated watermark) and account-scoped
actions with stable ids, receipts and final outcomes to session-v1, with admission
(window, rate, sequence, duplicates, unresolved bound) and client support; intentions and
actions have no biological effect yet. Next: M10.4b durable action records (migration
v11) and M10.4c evo-server wiring.
## Previous gate - 2026-10-02
@@ -0,0 +1,61 @@
# ADR-0092: M10 intentions, actions and durable outcomes
## Status
Accepted for M10.4 (2026-10-03). Decisions confirmed with the maintainer on 2026-10-03:
intentions and actions have no biological effect yet (durable no-effect); stable action
ids and final outcomes are made durable in PostgreSQL in the same transaction as the
checkpoint; 10.4 wires M10 sessions into evo-server with a headless client (the GUI
client switches later). Delivery: 10.4a protocol and admission (this text), 10.4b durable
action records (migration v11) and host integration, 10.4c evo-server listener, headless
client and process kill tests. Each segment amends this ADR.
## Context
ADR-0089 fixed the scheduling window (server_tick + 1 ..= + 8), one intention per tick,
per-session u64 sequences, at most 256 unresolved intentions and 1.5 s final outcomes.
ADR-0090 put superseding intentions on QUIC DATAGRAMs and reliable actions on the stream.
ADR-0091 binds sessions to accounts. No controllable organism or movement rule exists
(10.6 movement experiment, M11 organisms), so nothing an intention names can change
authoritative state yet. Committed batch traces record host inputs only, not request ids.
## Decision (10.4a)
**Two kinds of client input, three distinct answers.**
- *Intentions* (datagram): session, epoch, sequence, tick, bounded move vector; never any
state claim (position, energy): the message has no such fields and any extra bytes make
it invalid. Answers: an `IntentionReceipt` (admitted = scheduled for its tick, or a
refusal) and a cumulative `SimulatedThrough` watermark (every admitted intention up to a
sequence whose tick has been simulated in the epoch), repeated every 20 ticks so a lost
datagram is covered. Intentions are superseding: there is no per-intention durable record.
- *Actions* (stream): a client-chosen action id, unique per account and stable across
retries and reconnects, a kind and a tick. Answers: an `ActionReceipt` (scheduled, or a
refusal) and a final `ActionOutcome`: `committed_no_effect` with its commit sequence once
the commit covering its tick is durable, or `not_committed`. `ActionQuery` resolves an id
at any time (`pending`, `unknown`, or the final outcome). The only kind is `probe`.
- A receipt is never a final outcome, and the watermark is never durability.
**Admission** (`IntentAdmission`, transport-neutral, single owner), in order: the message
must name the connection's own session; rate (every attempt counts: 8 intentions and 4
actions per 8-tick window); authority ready; epoch; vector norm <= 1000 or a known action
kind and nonzero id; strictly increasing sequence; tick inside the window and, for
intentions, after the previous admitted intention's tick; duplicates (an action id already
pending or final for the account is never admitted again: `duplicate`, followed by its
outcome when final); at most 256 unresolved intentions plus actions per session.
Actions belong to the account: a takeover or reconnect sees the same pending and final
actions. The host takes scheduled actions with `carry(tick)` for the batch that simulates
that tick and reports durable commits with `committed(end_tick, sequence)`. When the epoch
advances, actions never carried are final `not_committed`; carried ones stay pending until
their durable record decides them (10.4b). Recent final outcomes (2,048) are kept for
duplicates and queries; older ones are resolved from the durable record (10.4b).
**Protocol.** Session protocol v1 gains message types 6-12 and Welcome gains the server
tick (schemas/network/session-v1.md). v1 has never been deployed, so it is amended in
place, as ADR-0083 did for M9 v1; after its first deployment, changes need a new version.
The action kind is a raw u16 on the wire and validated by admission (an enum narrower than
the wire field must never be cast from it).
## Consequences and limits (10.4a)
- Durable resolution of carried actions after a crash, and of final outcomes evicted from
memory, needs the v11 records (10.4b). Until then a carried action of a lost epoch
answers `pending`.
- The simulated watermark says the targeted tick ran while the intention was scheduled;
with no movement rule it changed nothing. 10.6 gives intentions an effect.
- Nothing is wired into evo-server yet (10.4c); nothing deploys M10 sessions.
+1
View File
@@ -98,6 +98,7 @@ design. No unadopted candidate is a link dependency of the proof.
- [ADR-0084: Engineering UI toolkit](0084-engineering-ui-toolkit.md) - Dear ImGui 1.92.9b pinned (M9.8a) and integrated as the engineering client overlay with toolkit-first input routing (M9.8c).
- [ADR-0090: M10 QUIC transport](0090-m10-quic-transport.md) - msquic 2.6.2 with OpenSSL 3.5.9 LTS (TLS 1.3 only) from pinned sources on Windows and Linux; DATAGRAM frames for superseding state, streams for reliable actions; M9 TLS/TCP kept as dev fallback; owned impairment relay; exact CA pinning due in 10.2b.
- [ADR-0092: M10 intentions and durable outcomes](0092-m10-intentions-and-durable-outcomes.md) - realtime intentions (datagram receipts and a cumulative simulated watermark) and account-scoped actions with stable ids, receipts and final outcomes (committed_no_effect / not_committed); no biological effect until organisms exist; durable action records in the commit transaction (10.4b).
- [ADR-0091: M10 session identity and control](0091-m10-session-identity-and-control.md) - provider-independent 128-bit AccountIds, ECDSA P-256 session grants (regions hold public keys only, signed environment byte), per-account serials where the newest grant wins, takeover of an existing session, in-session refresh, bounded attempt rates; identity adapter and issuer as a library; durable control lease follows (10.3c).
- [ADR-0089: M10 timing and budgets](0089-m10-timing-and-budgets.md) - ratified 50 ms tick, 1 s flush with final outcomes p95 <= 1.5 s, responsiveness LAN p95 <= 150 ms / 100 ms RTT <= 250 ms, reference hardware; derived scheduling, sequence, baseline, queue/byte/work budgets and the exact/tolerant determinism contract; records the per-tick biology coupling.
- [ADR-0088: Rendered deployment policy](0088-rendered-deployment-policy.md) - the deploy policy check renders every overlay with pinned kustomize v5.8.1 (checksum-verified, explicit preparation) and validates effective objects; unsupported kustomize features refused.
+2 -1
View File
@@ -9,7 +9,8 @@ pinning (`evo_network_quic`, M10.2b); loss/head-of-line measurements (M10.2c,
superseding state on DATAGRAMs and reliable actions on the ordered stream. Session
identity and control (ADR-0091, M10.3): ECDSA-signed account-scoped grants
([session-grant-v1](../../schemas/network/session-grant-v1.md)), newest grant wins; login over
QUIC per [session-v1](../../schemas/network/session-v1.md). The scoped M9 dev session (TLS 1.3, protocol v1, dev-only grants)
QUIC per [session-v1](../../schemas/network/session-v1.md). Intentions and actions
(ADR-0092): receipt, simulated watermark and final outcome are distinct answers. The scoped M9 dev session (TLS 1.3, protocol v1, dev-only grants)
is specified in [DEV_SESSION_PROTOCOL](../networking/DEV_SESSION_PROTOCOL.md) and
ADR-0082. M0 has no networking. Steam distribution follows later through
an identity-provider adapter; core account IDs are independent of Steam IDs.
+34
View File
@@ -4203,3 +4203,37 @@ repeated; Clang 19 ASan/UBSan session and network tests; Windows MSVC 19.44 pres
build and CTest 4/4 (binary timestamp checked).
Not done: evo-server and client integration (10.4), ASan of the PostgreSQL suite,
a real two-process cross-region takeover with QUIC clients, cluster migration (no deploy).
## 2026-10-03 — M10.4a intentions, actions and admission (ADR-0092)
Implemented session-v1 types 6-12 and Welcome server_tick (codec), `IntentAdmission`
(evo_network_protocol), RegionSessions host facts, datagram intentions, actions, queries,
carry/committed and outcome delivery, and the client API (intentions, actions, queries,
receipts, watermark, outcomes).
Unit tests (`evo-network-tests`): round trips of every new message, every truncation and
extension refused, an intention with appended state claims refused, invalid statuses and
results refused; admission refusals in order (other session, unknown session, stale epoch,
vector, replayed sequence, tick in the past, beyond 8 ticks, same tick, rate after 8
attempts, not ready); cumulative watermark and its 20-tick repeat; action receipt,
pending query, zero id, unknown kind, wire kind 257 (no truncation), duplicate retry keeping
the original tick, action rate, carry once, commit to `committed_no_effect`, other
account's query, outcome visible to a reconnected session, never admitted twice, unresolved
bound across intentions and actions, abandon finalizing only uncarried actions, bounded
final outcomes.
Loopback QUIC (`evo-quic-session-tests`) with a simulated host: Welcome server tick;
intention receipt, outside window, watermark after the tick runs, not ready; action receipt,
pending query, carry, durable outcome, duplicate receipt then the same outcome, the outcome
from a reconnected session, an uncarried action finalized `not_committed` by an epoch
change, intentions in the new epoch; a raw peer appending state claims to an intention
datagram is closed with `protocol`.
Found and fixed during development: an 8-bit `ActionKind` decoded from the u16 wire field
would have truncated unknown kinds to known ones (now raw u16 validated by admission);
unchecked optional accesses in the client (tidy).
Executed: Linux GCC 14 preset `quic` CTest 4/4; session tests 10/10 repeated; Clang 19
ASan/UBSan session and network tests; clang-tidy 19 on the new and changed sources and
tests; format check; Windows MSVC 19.44 preset `quic` build and CTest 4/4 (binaries rebuilt,
timestamps checked).
Not done: durable action records and crash resolution (10.4b), evo-server wiring and
process kill tests (10.4c).
+20 -1
View File
@@ -6,13 +6,16 @@
#include <expected>
#include <memory>
#include <optional>
#include <vector>
// M10.3b client-side session login over QUIC (ADR-0091, schemas/network/session-v1.md).
// Owned by one thread, which calls poll(). Sends Hello with the grant once the pinned
// connection is up (then forgets the grant), waits for Welcome or Close, and can renew
// the session in place with a newer grant. A Close from the server, a malformed message,
// the Welcome deadline or a lost transport ends the session; reconnecting needs a new
// client and a fresh grant (ADR-0089). Intentions and views are later segments.
// client and a fresh grant (ADR-0089). M10.4 (ADR-0092): intentions as datagrams with
// receipts and a simulated watermark; actions with stable ids, receipts and final outcomes.
// The client never treats a receipt or the watermark as a final outcome. Views are 10.5.
namespace evo::client {
struct RegionSessionClientConfig {
network::quic::ClientConfig transport;
@@ -36,6 +39,22 @@ class RegionSessionClient {
[[nodiscard]] std::optional<network::SessionRefreshResult> take_refresh_result();
// Sends Close{client_closed} and closes the connection.
void close();
// Realtime intention for `tick` (server_tick + 1 ..= + 8); returns its sequence, or
// nothing unless established and sent. Datagrams may be lost: no receipt is not a refusal.
[[nodiscard]] std::optional<std::uint64_t>
send_intention(std::uint64_t tick, std::int16_t move_x, std::int16_t move_y);
// A discrete action with a caller-chosen id, unique for the account (stable across
// retries and reconnects). False unless established and sent.
[[nodiscard]] bool send_action(std::uint64_t action_id, network::ActionKind kind,
std::uint64_t tick);
[[nodiscard]] bool query_action(std::uint64_t action_id);
[[nodiscard]] std::vector<network::IntentionReceipt> take_intention_receipts();
[[nodiscard]] std::vector<network::ActionReceipt> take_action_receipts();
[[nodiscard]] std::vector<network::ActionOutcome> take_action_outcomes();
// Newest simulated watermark of this session's epoch.
[[nodiscard]] std::optional<network::SimulatedThrough> simulated() const noexcept;
// Latest server tick seen (Welcome, receipts, watermarks); 0 before Welcome.
[[nodiscard]] std::uint64_t server_tick() const noexcept;
[[nodiscard]] RegionSessionState state() const noexcept;
[[nodiscard]] const std::optional<network::SessionWelcome>& welcome() const noexcept;
[[nodiscard]] std::optional<network::SessionCloseReason> close_reason() const noexcept;
+107
View File
@@ -0,0 +1,107 @@
#pragma once
#include "evo/network/session_control.hpp"
#include "evo/network/session_protocol.hpp"
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <optional>
#include <utility>
#include <vector>
// M10.4 admission of realtime intentions and discrete actions for one region (ADR-0092).
// Transport-neutral and single-owner; the host serializes calls. Three distinct answers:
// - receipt: admitted (scheduled for a tick) or a refusal, never more than that;
// - simulated: the cumulative watermark of admitted intentions whose tick has run;
// - final (actions only): committed_no_effect with its commit, or not_committed.
// Intentions are per session (sequence strictly increasing, superseded by later ones).
// Actions are per account, with client-chosen ids that are never admitted twice, so a
// retry or a reconnect resolves to the same outcome. Neither changes biology in M10.4.
namespace evo::network {
struct IntentLimits {
std::uint32_t intent_window{8}; // Ticks ahead of the server tick (ADR-0089).
std::uint32_t window_ticks{8}; // Rate window.
std::uint32_t max_intents_per_window{8}; // Every attempt counts.
std::uint32_t max_actions_per_window{4}; // Every attempt counts.
std::size_t max_unresolved{256}; // Intentions plus actions per session.
std::size_t max_sessions{32};
std::size_t max_finals{2048}; // Recent final outcomes kept for duplicates and queries.
std::uint64_t watermark_every{20}; // Ticks between repeats of an unchanged watermark.
};
// The host's authority as admission must see it.
struct AdmissionFacts {
bool ready{};
std::uint64_t epoch{}, server_tick{};
};
// An action the host must record durably with the batch that covers its tick.
struct CarriedAction {
AccountId account;
std::uint64_t action_id{}, tick{};
ActionKind kind{};
friend bool operator==(const CarriedAction&, const CarriedAction&) = default;
};
struct AccountOutcome {
AccountId account;
ActionOutcome outcome;
};
enum class IntentConfigError : std::uint8_t { invalid };
class IntentAdmission {
public:
[[nodiscard]] static std::expected<IntentAdmission, IntentConfigError>
create(IntentLimits limits);
// Session lifecycle, driven by session control (after Welcome, on any close).
[[nodiscard]] bool open(std::uint64_t session, const AccountId& account);
void close(std::uint64_t session);
// `session` is the connection's authenticated session; a message naming another is
// refused. Every attempt by a known session counts toward its rate.
[[nodiscard]] IntentionReceipt intention(std::uint64_t session, const SessionIntention& m,
const AdmissionFacts& facts);
[[nodiscard]] ActionReceipt action(std::uint64_t session, const SessionAction& m,
const AdmissionFacts& facts);
// What this process knows about an action of the session's account.
[[nodiscard]] ActionOutcome query(std::uint64_t session, const ActionQuery& m) const;
// Watermarks to send after the host simulated through facts.server_tick.
[[nodiscard]] std::vector<std::pair<std::uint64_t, SimulatedThrough>>
simulated(const AdmissionFacts& facts);
// Scheduled actions whose tick is <= `tick`: they ride that tick's batch from now on.
[[nodiscard]] std::vector<CarriedAction> carry(std::uint64_t tick);
// A commit covering ticks up to `end_tick` is durable: its carried actions are final.
[[nodiscard]] std::vector<AccountOutcome> committed(std::uint64_t end_tick,
std::uint64_t commit_sequence);
// Authority lost or epoch advanced: actions never carried are final (not_committed);
// carried ones stay unresolved until a durable record decides them (10.4b).
[[nodiscard]] std::vector<AccountOutcome> abandon();
// The current session of an account, for delivering outcomes.
[[nodiscard]] std::optional<std::uint64_t> session_of(const AccountId& account) const;
[[nodiscard]] std::size_t unresolved(std::uint64_t session) const;
private:
struct Pending {
std::uint64_t sequence{}, tick{};
};
struct Session {
std::uint64_t id{};
AccountId account;
std::uint64_t last_sequence{}, window_start{};
std::uint32_t intent_attempts{}, action_attempts{};
std::deque<Pending> pending;
std::uint64_t watermark{}, sent_watermark{}, sent_at_tick{};
};
enum class Stage : std::uint8_t { scheduled, carried };
struct Action {
CarriedAction carried;
Stage stage{};
};
explicit IntentAdmission(IntentLimits limits) : limits_{limits} {}
Session* find(std::uint64_t session);
const Session* find(std::uint64_t session) const;
void count_window(Session& s, std::uint64_t server_tick) const;
[[nodiscard]] std::size_t unresolved_of(const Session& s) const;
void remember(const AccountId& account, const ActionOutcome& outcome);
IntentLimits limits_;
std::vector<Session> sessions_;
std::vector<Action> actions_;
std::deque<AccountOutcome> finals_;
};
} // namespace evo::network
+86 -8
View File
@@ -7,8 +7,10 @@
#include <variant>
#include <vector>
// M10 session protocol v1, session part (ADR-0091, schemas/network/session-v1.md).
// Messages travel on the QUIC reliable stream (one message per framed QUIC message).
// M10 session protocol v1 (ADR-0091 session, ADR-0092 intentions and actions;
// schemas/network/session-v1.md). Session, action and outcome messages travel on the QUIC
// reliable stream (one message per framed QUIC message); intentions, their receipts and the
// simulated watermark travel as QUIC DATAGRAMs.
// Each starts with an 8-byte header: magic "EVSN", version u16, type u8, flags u8 (0);
// every payload has a fixed size and explicit little-endian fields. Grants are opaque
// 160-byte credentials here. Later M10 segments add message types under a new version.
@@ -19,11 +21,42 @@ inline constexpr std::size_t session_header_bytes = 8;
inline constexpr std::size_t session_grant_wire_bytes = 160;
enum class SessionMessageType : std::uint8_t {
hello = 1, // Client -> server: grant.
welcome, // Server -> client.
refresh, // Client -> server: newer grant for the open session.
refresh_result, // Server -> client.
close // Either way, then the sender closes the connection.
hello = 1, // Client -> server: grant.
welcome, // Server -> client.
refresh, // Client -> server: newer grant for the open session.
refresh_result, // Server -> client.
close, // Either way, then the sender closes the connection.
intention, // Client -> server, datagram: realtime movement intention.
intention_receipt, // Server -> client, datagram.
simulated_through, // Server -> client, datagram: cumulative simulated watermark.
action, // Client -> server, stream: discrete action with a stable id.
action_receipt, // Server -> client, stream.
action_outcome, // Server -> client, stream: final.
action_query // Client -> server, stream: resolve an action by id.
};
// Admission answers for intentions and actions (wire 0..10).
enum class AdmitStatus : std::uint8_t {
admitted = 0,
unknown_session, // Not this connection's session.
stale_epoch,
outside_window, // Tick not in server_tick + 1 ..= server_tick + window.
rate_limited, // Every attempt counts toward the window budget.
replayed, // Intention sequence not above the last admitted one.
invalid_vector,
too_many_unresolved,
invalid_action, // Unknown kind or zero action id.
duplicate, // Action id already known for this account: its state follows.
not_ready // The region has no current authority (starting, recovering, draining).
};
// Wire u16 (SessionAction::kind carries the raw value; admission validates it).
enum class ActionKind : std::uint8_t {
probe = 1 // No effect on biology: proves admission, scheduling and durability (M10.4).
};
enum class ActionResult : std::uint8_t {
committed_no_effect = 1, // Durable in commit `commit_sequence`; changed nothing.
not_committed, // Final: never part of a committed batch.
pending, // Query answer only: admitted, not yet final.
unknown // Query answer only: no record of this action id.
};
// Wire values 1..13. `connection_lost` is local only (the transport ended without a Close).
enum class SessionCloseReason : std::uint8_t {
@@ -60,6 +93,7 @@ struct SessionHello {
struct SessionWelcome {
std::uint64_t session{}, epoch{}, world{}, frame{}, region{}, expires_at{};
std::uint64_t server_seconds{}; // Server wall clock at Welcome, for refresh timing.
std::uint64_t server_tick{}; // Simulated tick at Welcome, for scheduling.
friend bool operator==(const SessionWelcome&, const SessionWelcome&) = default;
};
struct SessionRefresh {
@@ -75,8 +109,52 @@ struct SessionRefreshResult {
struct SessionClose {
SessionCloseReason reason{};
};
// A movement intention carries only what the player wants: never position, energy or any
// other state claim. Vector components within the M9 bound (norm <= 1000).
struct SessionIntention {
std::uint64_t session{}, epoch{}, sequence{}, tick{};
std::int16_t move_x{}, move_y{};
friend bool operator==(const SessionIntention&, const SessionIntention&) = default;
};
struct IntentionReceipt {
std::uint64_t sequence{};
AdmitStatus status{};
std::uint64_t server_tick{};
friend bool operator==(const IntentionReceipt&, const IntentionReceipt&) = default;
};
// Every admitted intention up to `sequence` whose tick is <= `tick` has been simulated in
// `epoch` (cumulative, so a lost datagram is covered by the next).
struct SimulatedThrough {
std::uint64_t epoch{}, sequence{}, tick{};
friend bool operator==(const SimulatedThrough&, const SimulatedThrough&) = default;
};
struct SessionAction {
std::uint64_t session{}, epoch{}, action_id{};
std::uint16_t kind{}; // Raw wire value: an unknown kind is refused by admission.
std::uint64_t tick{};
friend bool operator==(const SessionAction&, const SessionAction&) = default;
};
// Receipt only: admitted means scheduled for `tick`, never simulated or durable.
struct ActionReceipt {
std::uint64_t action_id{};
AdmitStatus status{};
std::uint64_t server_tick{}, tick{};
friend bool operator==(const ActionReceipt&, const ActionReceipt&) = default;
};
struct ActionOutcome {
std::uint64_t action_id{};
ActionResult result{};
std::uint64_t tick{}, commit_sequence{}; // Zero unless committed_no_effect.
friend bool operator==(const ActionOutcome&, const ActionOutcome&) = default;
};
struct ActionQuery {
std::uint64_t action_id{};
friend bool operator==(const ActionQuery&, const ActionQuery&) = default;
};
using SessionMessage =
std::variant<SessionHello, SessionWelcome, SessionRefresh, SessionRefreshResult, SessionClose>;
std::variant<SessionHello, SessionWelcome, SessionRefresh, SessionRefreshResult, SessionClose,
SessionIntention, IntentionReceipt, SimulatedThrough, SessionAction, ActionReceipt,
ActionOutcome, ActionQuery>;
[[nodiscard]] std::vector<std::uint8_t> encode_session(const SessionMessage& message);
// Exactly one message; any other length for its type rejects.
+22 -4
View File
@@ -1,4 +1,5 @@
#pragma once
#include "evo/network/intent_admission.hpp"
#include "evo/network/quic_transport.hpp"
#include "evo/network/session_control.hpp"
#include "evo/network/session_grant.hpp"
@@ -18,7 +19,11 @@
// public keys and admitted by SessionControl. A newer grant for an account closes the
// account's previous connection with `superseded`. Refusals and closes send Close with a
// reason, then the connection is closed after a short flush. Intentions and views are
// later segments (10.4, 10.5). Events carry account log labels only, never grants.
// later segments (10.5). Events carry account log labels only, never grants.
// M10.4 (ADR-0092): established sessions send intentions (datagrams) and actions (stream);
// IntentAdmission answers with receipts, simulated watermarks and final action outcomes.
// The host reports its authority each poll, takes carried actions for its batches and
// reports durable commits.
// With a ControlLedger, control is durable and unique per world: a session that loses its
// durable control (another region accepted a newer grant) closes with `superseded`, and
// one whose control cannot be renewed in time closes with `shutdown`.
@@ -39,6 +44,13 @@ struct RegionSessionsConfig {
// `renew_interval` and closes before its control can lapse (`safety_margin`).
network::ControlLedger* ledger{};
std::chrono::milliseconds renew_interval{5000}, safety_margin{2000};
network::IntentLimits intents{}; // max_sessions follows control.max_sessions.
};
// The region host's authority, read once per poll.
struct HostFacts {
bool ready{}; // Current authority, recovered, not draining.
std::uint64_t epoch{}; // Ownership epoch; a newer one closes every session.
std::uint64_t simulated_tick{};
};
enum class RegionSessionsError : std::uint8_t { configuration, keys, transport };
struct RegionSessionEvent {
@@ -55,10 +67,16 @@ class RegionSessions {
RegionSessions(const RegionSessions&) = delete;
RegionSessions& operator=(const RegionSessions&) = delete;
~RegionSessions();
// `epoch` is the region's current ownership epoch: a newer one closes every session
// (stale_epoch). `now_seconds` is wall time for grants, `now` monotonic for deadlines.
void poll(std::uint64_t epoch, std::uint64_t now_seconds,
// A newer epoch closes every session (stale_epoch) and abandons unscheduled actions.
// `now_seconds` is wall time for grants, `now` monotonic for deadlines.
void poll(const HostFacts& facts, std::uint64_t now_seconds,
std::chrono::steady_clock::time_point now);
// Actions scheduled for ticks <= `tick`, to be recorded durably with the batch that
// simulates that tick (10.4b). Each action is returned once.
[[nodiscard]] std::vector<network::CarriedAction> carry(std::uint64_t tick);
// A commit covering ticks up to `end_tick` is durable: carried actions become final and
// their outcomes are sent to each account's current session.
void committed(std::uint64_t end_tick, std::uint64_t commit_sequence);
// Closes every connection with `shutdown` (flushed by later polls).
void shutdown(std::chrono::steady_clock::time_point now);
[[nodiscard]] std::vector<RegionSessionEvent> take_events();
+31 -7
View File
@@ -1,30 +1,47 @@
# M10 session protocol, version 1 (session messages)
# M10 session protocol, version 1
Login and session control over the QUIC reliable stream (ADR-0090 transport, ADR-0091
identity). Implemented by `encode_session`/`decode_session`
Login, session control, intentions and actions over QUIC (ADR-0090 transport, ADR-0091
identity, ADR-0092 intentions and actions). Implemented by `encode_session`/`decode_session`
(include/evo/network/session_protocol.hpp), `RegionSessions` (server) and
`RegionSessionClient` (client). Each message is one framed QUIC reliable message.
`RegionSessionClient` (client). Stream messages are one framed QUIC reliable message
each; types 6-8 travel as one QUIC DATAGRAM each, and only after Welcome.
Integers little-endian. Every message has a fixed length for its type; any other length,
magic, version, nonzero flags, unknown type or out-of-range value is refused, and the
server then sends Close (`unsupported_version` for another version, otherwise
`protocol`) and closes the connection. Later M10 segments add types in a new version.
`protocol`) and closes the connection. v1 has not been deployed; it was amended in place
by M10.4 (types 6-12, Welcome server_tick). After its first deployment, changes need a
new version.
## Header (8 bytes)
| Offset | Size | Field | Rule |
|---|---|---|---|
| 0 | 4 | magic | bytes `EVSN` |
| 4 | 2 | version | 1 |
| 6 | 1 | type | 1..5 below |
| 6 | 1 | type | 1..12 below |
| 7 | 1 | flags | 0 |
## Messages
| Type | Direction | Payload | Size |
|---|---|---|---|
| 1 Hello | client -> server | required_features u32 (0), grant (session-grant-v1, 160 bytes) | 164 |
| 2 Welcome | server -> client | session, epoch, world, frame, region, expires_at, server_seconds (u64 each; session and epoch nonzero) | 56 |
| 2 Welcome | server -> client | session, epoch, world, frame, region, expires_at, server_seconds, server_tick (u64 each; session and epoch nonzero) | 64 |
| 3 Refresh | client -> server | newer grant for the same account (160 bytes) | 160 |
| 4 RefreshResult | server -> client | status u8 (0 accepted, else a close reason value), expires_at u64 | 9 |
| 5 Close | either | reason u8 | 1 |
| 6 Intention | client -> server, datagram | session, epoch, sequence, tick (u64), move_x, move_y (i16) | 36 |
| 7 IntentionReceipt | server -> client, datagram | sequence u64, status u8, server_tick u64 | 17 |
| 8 SimulatedThrough | server -> client, datagram | epoch, sequence, tick (u64) | 24 |
| 9 Action | client -> server | session, epoch, action_id (u64), kind u16, tick u64 | 34 |
| 10 ActionReceipt | server -> client | action_id u64, status u8, server_tick u64, tick u64 | 25 |
| 11 ActionOutcome | server -> client | action_id u64, result u8 (1..4), tick u64, commit_sequence u64 | 25 |
| 12 ActionQuery | client -> server | action_id u64 | 8 |
Admission status (wire 0..10): 0 admitted, 1 unknown_session, 2 stale_epoch,
3 outside_window, 4 rate_limited, 5 replayed, 6 invalid_vector, 7 too_many_unresolved,
8 invalid_action, 9 duplicate, 10 not_ready. Action kinds: 1 probe (no effect). Action
results: 1 committed_no_effect, 2 not_committed (both final), 3 pending, 4 unknown (query
answers only). Intentions carry no state claims; their vector ranges and every action
field are checked by admission, which answers with a status rather than closing.
Close reasons (wire 1..13): 1 client_closed, 2 superseded, 3 expired, 4 stale_epoch,
5 unauthenticated, 6 wrong_scope, 7 stale_grant, 8 rate_limited, 9 capacity,
@@ -47,3 +64,10 @@ Close reasons (wire 1..13): 1 client_closed, 2 superseded, 3 expired, 4 stale_ep
- Close is followed by closing the connection (the server waits up to 1 s for delivery).
A client that closes its connection without Close is treated as `client_closed`.
- Reconnecting needs a new connection and a newer grant (ADR-0089).
- Intentions (ADR-0092): one per tick, ticks and sequences increasing, tick within
server_tick + 1 ..= + 8. A receipt only says admitted or refused; `SimulatedThrough`
says which admitted intentions' ticks have run (cumulative, resent every 20 ticks).
Any datagram other than an Intention, or before Welcome, closes with `protocol`.
- Actions (ADR-0092): ids unique per account and never admitted twice. A receipt only
says scheduled or refused; `ActionOutcome` is sent once the action is final, again
after a duplicate of a final action, and in answer to `ActionQuery`.
+91
View File
@@ -1,4 +1,5 @@
#include "evo/client/region_session.hpp"
#include <algorithm>
#include <utility>
namespace evo::client {
@@ -16,6 +17,42 @@ struct RegionSessionClient::Impl {
std::optional<network::SessionWelcome> welcome;
std::optional<SessionCloseReason> reason;
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;
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);
}
// 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 end(SessionCloseReason::protocol, true);
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::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;
}
end(SessionCloseReason::protocol, true);
}
bool send(const network::SessionMessage& m) {
return connection != 0 &&
@@ -42,6 +79,7 @@ struct RegionSessionClient::Impl {
if (state == RegionSessionState::awaiting_welcome) {
if (const auto* m = std::get_if<network::SessionWelcome>(&*decoded)) {
welcome = *m;
seen_tick(m->server_tick);
state = RegionSessionState::established;
return;
}
@@ -52,6 +90,12 @@ struct RegionSessionClient::Impl {
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);
}
end(SessionCloseReason::protocol, true);
}
@@ -89,6 +133,8 @@ void RegionSessionClient::poll(Clock::time_point now) {
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.connection = 0; // Already gone; nothing to close or send.
m.end(SessionCloseReason::connection_lost, false);
@@ -113,6 +159,51 @@ 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.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++;
}
bool RegionSessionClient::send_action(std::uint64_t action_id, network::ActionKind kind,
std::uint64_t tick) {
auto& m = *impl_;
return 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::query_action(std::uint64_t action_id) {
auto& m = *impl_;
return m.state == RegionSessionState::established && m.send(network::ActionQuery{action_id});
}
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;
}
RegionSessionState RegionSessionClient::state() const noexcept {
return impl_->state;
}
+246
View File
@@ -0,0 +1,246 @@
#include "evo/network/intent_admission.hpp"
#include <algorithm>
namespace evo::network {
namespace {
constexpr std::int32_t max_component = 1000;
bool valid_vector(std::int16_t x, std::int16_t y) {
const std::int32_t ix = x, iy = y;
return ix * ix + iy * iy <= max_component * max_component;
}
bool in_window(std::uint64_t tick, std::uint64_t server_tick, std::uint32_t window) {
return tick > server_tick && tick - server_tick <= window;
}
} // namespace
std::expected<IntentAdmission, IntentConfigError> IntentAdmission::create(IntentLimits limits) {
if (limits.intent_window == 0 || limits.intent_window > 64 || limits.window_ticks == 0 ||
limits.max_intents_per_window == 0 || limits.max_actions_per_window == 0 ||
limits.max_unresolved == 0 || limits.max_unresolved > 4096 || limits.max_sessions == 0 ||
limits.max_sessions > 1024 || limits.max_finals == 0 || limits.watermark_every == 0)
return std::unexpected(IntentConfigError::invalid);
IntentAdmission admission{limits};
admission.sessions_.reserve(limits.max_sessions);
return admission;
}
IntentAdmission::Session* IntentAdmission::find(std::uint64_t session) {
const auto it =
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == session; });
return it == sessions_.end() ? nullptr : &*it;
}
const IntentAdmission::Session* IntentAdmission::find(std::uint64_t session) const {
const auto it =
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == session; });
return it == sessions_.end() ? nullptr : &*it;
}
bool IntentAdmission::open(std::uint64_t session, const AccountId& account) {
if (session == 0 || find(session) || sessions_.size() >= limits_.max_sessions)
return false;
Session s;
s.id = session;
s.account = account;
sessions_.push_back(std::move(s));
return true;
}
void IntentAdmission::close(std::uint64_t session) {
// Unsimulated intentions die with the session; actions belong to the account and stay.
std::erase_if(sessions_, [&](const Session& s) { return s.id == session; });
}
void IntentAdmission::count_window(Session& s, std::uint64_t server_tick) const {
if (server_tick < s.window_start || server_tick - s.window_start >= limits_.window_ticks) {
s.window_start = server_tick;
s.intent_attempts = 0;
s.action_attempts = 0;
}
}
std::size_t IntentAdmission::unresolved_of(const Session& s) const {
return s.pending.size() +
static_cast<std::size_t>(std::ranges::count_if(
actions_, [&](const Action& a) { return a.carried.account == s.account; }));
}
std::size_t IntentAdmission::unresolved(std::uint64_t session) const {
const auto* s = find(session);
return s ? unresolved_of(*s) : 0;
}
IntentionReceipt IntentAdmission::intention(std::uint64_t session, const SessionIntention& m,
const AdmissionFacts& facts) {
IntentionReceipt r{m.sequence, AdmitStatus::admitted, facts.server_tick};
auto* s = find(session);
if (!s) {
r.status = AdmitStatus::unknown_session;
return r;
}
count_window(*s, facts.server_tick);
const bool over = s->intent_attempts >= limits_.max_intents_per_window;
if (!over)
++s->intent_attempts;
const std::uint64_t last_tick = s->pending.empty() ? 0 : s->pending.back().tick;
if (over)
r.status = AdmitStatus::rate_limited;
else if (m.session != session)
r.status = AdmitStatus::unknown_session;
else if (!facts.ready)
r.status = AdmitStatus::not_ready;
else if (m.epoch != facts.epoch)
r.status = AdmitStatus::stale_epoch;
else if (!valid_vector(m.move_x, m.move_y))
r.status = AdmitStatus::invalid_vector;
else if (m.sequence <= s->last_sequence)
r.status = AdmitStatus::replayed;
// One intention per tick (ADR-0089): ticks advance with the sequence.
else if (!in_window(m.tick, facts.server_tick, limits_.intent_window) || m.tick <= last_tick)
r.status = AdmitStatus::outside_window;
else if (unresolved_of(*s) >= limits_.max_unresolved)
r.status = AdmitStatus::too_many_unresolved;
if (r.status == AdmitStatus::admitted) {
s->last_sequence = m.sequence;
s->pending.push_back({m.sequence, m.tick});
}
return r;
}
ActionReceipt IntentAdmission::action(std::uint64_t session, const SessionAction& m,
const AdmissionFacts& facts) {
ActionReceipt r{m.action_id, AdmitStatus::admitted, facts.server_tick, m.tick};
auto* s = find(session);
if (!s) {
r.status = AdmitStatus::unknown_session;
return r;
}
count_window(*s, facts.server_tick);
const bool over = s->action_attempts >= limits_.max_actions_per_window;
if (!over)
++s->action_attempts;
const auto& account = s->account;
const auto known_action = std::ranges::find_if(actions_, [&](const Action& a) {
return a.carried.account == account && a.carried.action_id == m.action_id;
});
const auto known_final = std::ranges::find_if(finals_, [&](const AccountOutcome& f) {
return f.account == account && f.outcome.action_id == m.action_id;
});
if (over)
r.status = AdmitStatus::rate_limited;
else if (m.session != session)
r.status = AdmitStatus::unknown_session;
else if (!facts.ready)
r.status = AdmitStatus::not_ready;
else if (m.epoch != facts.epoch)
r.status = AdmitStatus::stale_epoch;
else if (m.kind != static_cast<std::uint16_t>(ActionKind::probe) || m.action_id == 0)
r.status = AdmitStatus::invalid_action;
else if (known_action != actions_.end() || known_final != finals_.end()) {
// Never admitted twice; the receipt names the tick it was scheduled for.
r.status = AdmitStatus::duplicate;
r.tick =
known_action != actions_.end() ? known_action->carried.tick : known_final->outcome.tick;
} else if (!in_window(m.tick, facts.server_tick, limits_.intent_window))
r.status = AdmitStatus::outside_window;
else if (unresolved_of(*s) >= limits_.max_unresolved)
r.status = AdmitStatus::too_many_unresolved;
if (r.status == AdmitStatus::admitted)
actions_.push_back({{account, m.action_id, m.tick, ActionKind::probe}, Stage::scheduled});
return r;
}
ActionOutcome IntentAdmission::query(std::uint64_t session, const ActionQuery& m) const {
ActionOutcome o{m.action_id, ActionResult::unknown, 0, 0};
const auto* s = find(session);
if (!s)
return o;
const auto pending = std::ranges::find_if(actions_, [&](const Action& a) {
return a.carried.account == s->account && a.carried.action_id == m.action_id;
});
if (pending != actions_.end()) {
o.result = ActionResult::pending;
o.tick = pending->carried.tick;
return o;
}
const auto final = std::ranges::find_if(finals_, [&](const AccountOutcome& f) {
return f.account == s->account && f.outcome.action_id == m.action_id;
});
return final != finals_.end() ? final->outcome : o;
}
std::vector<std::pair<std::uint64_t, SimulatedThrough>>
IntentAdmission::simulated(const AdmissionFacts& facts) {
std::vector<std::pair<std::uint64_t, SimulatedThrough>> out;
for (auto& s : sessions_) {
while (!s.pending.empty() && s.pending.front().tick <= facts.server_tick) {
s.watermark = s.pending.front().sequence;
s.pending.pop_front();
}
const bool changed = s.watermark != s.sent_watermark;
const bool repeat =
s.watermark != 0 && (facts.server_tick < s.sent_at_tick ||
facts.server_tick - s.sent_at_tick >= limits_.watermark_every);
if (changed || repeat) {
s.sent_watermark = s.watermark;
s.sent_at_tick = facts.server_tick;
out.emplace_back(s.id, SimulatedThrough{facts.epoch, s.watermark, facts.server_tick});
}
}
return out;
}
std::vector<CarriedAction> IntentAdmission::carry(std::uint64_t tick) {
std::vector<CarriedAction> out;
for (auto& a : actions_)
if (a.stage == Stage::scheduled && a.carried.tick <= tick) {
a.stage = Stage::carried;
out.push_back(a.carried);
}
return out;
}
void IntentAdmission::remember(const AccountId& account, const ActionOutcome& outcome) {
finals_.push_back({account, outcome});
while (finals_.size() > limits_.max_finals)
finals_.pop_front();
}
std::vector<AccountOutcome> IntentAdmission::committed(std::uint64_t end_tick,
std::uint64_t commit_sequence) {
std::vector<AccountOutcome> out;
std::erase_if(actions_, [&](const Action& a) {
if (a.stage != Stage::carried || a.carried.tick > end_tick)
return false;
const ActionOutcome o{a.carried.action_id, ActionResult::committed_no_effect,
a.carried.tick, commit_sequence};
out.push_back({a.carried.account, o});
remember(a.carried.account, o);
return true;
});
return out;
}
std::vector<AccountOutcome> IntentAdmission::abandon() {
std::vector<AccountOutcome> out;
std::erase_if(actions_, [&](const Action& a) {
if (a.stage != Stage::scheduled)
return false;
const ActionOutcome o{a.carried.action_id, ActionResult::not_committed, 0, 0};
out.push_back({a.carried.account, o});
remember(a.carried.account, o);
return true;
});
for (auto& s : sessions_)
s.pending.clear(); // Superseding intentions of a lost epoch are simply dropped.
return out;
}
std::optional<std::uint64_t> IntentAdmission::session_of(const AccountId& account) const {
const auto it =
std::ranges::find_if(sessions_, [&](const Session& s) { return s.account == account; });
if (it == sessions_.end())
return std::nullopt;
return it->id;
}
} // namespace evo::network
+121 -5
View File
@@ -4,10 +4,18 @@
namespace evo::network {
namespace {
constexpr std::size_t hello_bytes = 4 + session_grant_wire_bytes;
constexpr std::size_t welcome_bytes = std::size_t{7} * 8;
constexpr std::size_t welcome_bytes = std::size_t{8} * 8;
constexpr std::size_t refresh_bytes = session_grant_wire_bytes;
constexpr std::size_t refresh_result_bytes = 1 + 8;
constexpr std::size_t close_bytes = 1;
constexpr std::size_t intention_bytes = (std::size_t{4} * 8) + 4;
constexpr std::size_t intention_receipt_bytes = 8 + 1 + 8;
constexpr std::size_t simulated_bytes = std::size_t{3} * 8;
constexpr std::size_t action_bytes = (std::size_t{3} * 8) + 2 + 8;
constexpr std::size_t action_receipt_bytes = 8 + 1 + 8 + 8;
constexpr std::size_t action_outcome_bytes = 8 + 1 + 8 + 8;
constexpr std::size_t action_query_bytes = 8;
constexpr std::uint8_t max_admit_status = static_cast<std::uint8_t>(AdmitStatus::not_ready);
void put(std::vector<std::uint8_t>& out, std::uint64_t v, std::size_t count) {
for (std::size_t i = 0; i < count; ++i)
@@ -49,8 +57,8 @@ std::vector<std::uint8_t> encode_session(const SessionMessage& message) {
}
std::vector<std::uint8_t> operator()(const SessionWelcome& m) const {
auto out = header(SessionMessageType::welcome, welcome_bytes);
for (const auto v :
{m.session, m.epoch, m.world, m.frame, m.region, m.expires_at, m.server_seconds})
for (const auto v : {m.session, m.epoch, m.world, m.frame, m.region, m.expires_at,
m.server_seconds, m.server_tick})
put(out, v, 8);
return out;
}
@@ -70,6 +78,56 @@ std::vector<std::uint8_t> encode_session(const SessionMessage& message) {
out.push_back(static_cast<std::uint8_t>(m.reason));
return out;
}
std::vector<std::uint8_t> operator()(const SessionIntention& m) const {
auto out = header(SessionMessageType::intention, intention_bytes);
for (const auto v : {m.session, m.epoch, m.sequence, m.tick})
put(out, v, 8);
put(out, static_cast<std::uint16_t>(m.move_x), 2);
put(out, static_cast<std::uint16_t>(m.move_y), 2);
return out;
}
std::vector<std::uint8_t> operator()(const IntentionReceipt& m) const {
auto out = header(SessionMessageType::intention_receipt, intention_receipt_bytes);
put(out, m.sequence, 8);
out.push_back(static_cast<std::uint8_t>(m.status));
put(out, m.server_tick, 8);
return out;
}
std::vector<std::uint8_t> operator()(const SimulatedThrough& m) const {
auto out = header(SessionMessageType::simulated_through, simulated_bytes);
for (const auto v : {m.epoch, m.sequence, m.tick})
put(out, v, 8);
return out;
}
std::vector<std::uint8_t> operator()(const SessionAction& m) const {
auto out = header(SessionMessageType::action, action_bytes);
for (const auto v : {m.session, m.epoch, m.action_id})
put(out, v, 8);
put(out, m.kind, 2);
put(out, m.tick, 8);
return out;
}
std::vector<std::uint8_t> operator()(const ActionReceipt& m) const {
auto out = header(SessionMessageType::action_receipt, action_receipt_bytes);
put(out, m.action_id, 8);
out.push_back(static_cast<std::uint8_t>(m.status));
put(out, m.server_tick, 8);
put(out, m.tick, 8);
return out;
}
std::vector<std::uint8_t> operator()(const ActionOutcome& m) const {
auto out = header(SessionMessageType::action_outcome, action_outcome_bytes);
put(out, m.action_id, 8);
out.push_back(static_cast<std::uint8_t>(m.result));
put(out, m.tick, 8);
put(out, m.commit_sequence, 8);
return out;
}
std::vector<std::uint8_t> operator()(const ActionQuery& m) const {
auto out = header(SessionMessageType::action_query, action_query_bytes);
put(out, m.action_id, 8);
return out;
}
};
return std::visit(Encoder{}, message);
}
@@ -99,8 +157,8 @@ decode_session(std::span<const std::uint8_t> bytes) {
if (!expect(welcome_bytes))
return std::unexpected(SessionCodecError::wrong_length);
SessionWelcome m;
std::uint64_t* fields[] = {&m.session, &m.epoch, &m.world, &m.frame,
&m.region, &m.expires_at, &m.server_seconds};
std::uint64_t* fields[] = {&m.session, &m.epoch, &m.world, &m.frame,
&m.region, &m.expires_at, &m.server_seconds, &m.server_tick};
for (std::size_t i = 0; i < std::size(fields); ++i)
*fields[i] = get(payload, 8 * i, 8);
if (m.session == 0 || m.epoch == 0)
@@ -127,6 +185,64 @@ decode_session(std::span<const std::uint8_t> bytes) {
return std::unexpected(SessionCodecError::invalid_value);
return SessionClose{static_cast<SessionCloseReason>(payload[0])};
}
case static_cast<std::uint8_t>(SessionMessageType::intention): {
if (!expect(intention_bytes))
return std::unexpected(SessionCodecError::wrong_length);
SessionIntention m;
m.session = get(payload, 0, 8);
m.epoch = get(payload, 8, 8);
m.sequence = get(payload, 16, 8);
m.tick = get(payload, 24, 8);
m.move_x = static_cast<std::int16_t>(static_cast<std::uint16_t>(get(payload, 32, 2)));
m.move_y = static_cast<std::int16_t>(static_cast<std::uint16_t>(get(payload, 34, 2)));
return m; // Ranges belong to admission, which answers with a status.
}
case static_cast<std::uint8_t>(SessionMessageType::intention_receipt): {
if (!expect(intention_receipt_bytes))
return std::unexpected(SessionCodecError::wrong_length);
if (payload[8] > max_admit_status)
return std::unexpected(SessionCodecError::invalid_value);
return IntentionReceipt{get(payload, 0, 8), static_cast<AdmitStatus>(payload[8]),
get(payload, 9, 8)};
}
case static_cast<std::uint8_t>(SessionMessageType::simulated_through): {
if (!expect(simulated_bytes))
return std::unexpected(SessionCodecError::wrong_length);
return SimulatedThrough{get(payload, 0, 8), get(payload, 8, 8), get(payload, 16, 8)};
}
case static_cast<std::uint8_t>(SessionMessageType::action): {
if (!expect(action_bytes))
return std::unexpected(SessionCodecError::wrong_length);
SessionAction m;
m.session = get(payload, 0, 8);
m.epoch = get(payload, 8, 8);
m.action_id = get(payload, 16, 8);
m.kind = static_cast<std::uint16_t>(get(payload, 24, 2)); // Admission checks it.
m.tick = get(payload, 26, 8);
return m;
}
case static_cast<std::uint8_t>(SessionMessageType::action_receipt): {
if (!expect(action_receipt_bytes))
return std::unexpected(SessionCodecError::wrong_length);
if (payload[8] > max_admit_status)
return std::unexpected(SessionCodecError::invalid_value);
return ActionReceipt{get(payload, 0, 8), static_cast<AdmitStatus>(payload[8]),
get(payload, 9, 8), get(payload, 17, 8)};
}
case static_cast<std::uint8_t>(SessionMessageType::action_outcome): {
if (!expect(action_outcome_bytes))
return std::unexpected(SessionCodecError::wrong_length);
if (payload[8] < static_cast<std::uint8_t>(ActionResult::committed_no_effect) ||
payload[8] > static_cast<std::uint8_t>(ActionResult::unknown))
return std::unexpected(SessionCodecError::invalid_value);
return ActionOutcome{get(payload, 0, 8), static_cast<ActionResult>(payload[8]),
get(payload, 9, 8), get(payload, 17, 8)};
}
case static_cast<std::uint8_t>(SessionMessageType::action_query): {
if (!expect(action_query_bytes))
return std::unexpected(SessionCodecError::wrong_length);
return ActionQuery{get(payload, 0, 8)};
}
default:
return std::unexpected(SessionCodecError::unknown_type);
}
+82 -12
View File
@@ -62,14 +62,16 @@ struct RegionSessions::Impl {
};
Impl(RegionSessionsConfig c, std::unique_ptr<network::quic::Endpoint> e,
network::GrantVerifier v, network::SessionControl s)
network::GrantVerifier v, network::SessionControl s, network::IntentAdmission i)
: config{std::move(c)}, endpoint{std::move(e)}, verifier{std::move(v)},
control{std::move(s)} {}
control{std::move(s)}, intents{std::move(i)} {}
RegionSessionsConfig config;
std::unique_ptr<network::quic::Endpoint> endpoint;
network::GrantVerifier verifier;
network::SessionControl control;
network::IntentAdmission intents;
HostFacts facts;
std::vector<Connection> connections;
std::vector<RegionSessionEvent> events;
@@ -89,6 +91,13 @@ struct RegionSessions::Impl {
// A refused send (budget) leaves the peer to observe the transport close instead.
(void)endpoint->send_message(c.id, network::encode_session(m)).has_value();
}
// Realtime answers: a refused datagram is dropped; cumulative watermarks cover it.
void send_datagram(const Connection& c, const network::SessionMessage& m) {
(void)endpoint->send_datagram(c.id, network::encode_session(m)).has_value();
}
[[nodiscard]] network::AdmissionFacts admission() const {
return {facts.ready, control.epoch(), facts.simulated_tick};
}
// Sends Close, releases control, reports, and closes after the flush deadline.
void close(Connection& c, SessionCloseReason reason, Clock::time_point now) {
if (c.state == State::closing)
@@ -101,6 +110,8 @@ struct RegionSessions::Impl {
event.account = c.account;
event.reason = reason;
events.push_back(std::move(event));
if (c.state == State::established)
intents.close(c.session);
if (c.session != 0) // May already be released (superseded, expired, epoch).
(void)control.close(c.session).has_value();
// A superseded session's durable control already moved to its successor.
@@ -166,11 +177,14 @@ struct RegionSessions::Impl {
return;
}
}
welcome(c);
welcome(c, now);
}
void welcome(Connection& c) {
void welcome(Connection& c, Clock::time_point now) {
if (!intents.open(c.session, c.account_id))
return close(c, SessionCloseReason::capacity, now);
c.state = State::established;
c.welcome.server_tick = facts.simulated_tick;
send(c, c.welcome);
events.push_back({RegionSessionEvent::Kind::opened, c.session, c.account, {}});
}
@@ -225,6 +239,24 @@ struct RegionSessions::Impl {
send(c, result);
}
// Only established sessions may send datagrams, and only intentions.
void datagram(Connection& c, std::span<const std::uint8_t> bytes, Clock::time_point now) {
if (c.state == State::closing)
return;
const auto decoded = network::decode_session(bytes);
const auto* m = decoded ? std::get_if<network::SessionIntention>(&*decoded) : nullptr;
if (c.state != State::established || !m)
return close(c, SessionCloseReason::protocol, now);
send_datagram(c, intents.intention(c.session, *m, admission()));
}
void deliver(const std::vector<network::AccountOutcome>& outcomes) {
for (const auto& o : outcomes)
if (const auto session = intents.session_of(o.account))
if (auto* c = by_session(*session); c && c->state == State::established)
send(*c, o.outcome);
}
void message(Connection& c, std::span<const std::uint8_t> bytes, std::uint64_t now_seconds,
Clock::time_point now) {
if (c.state == State::closing)
@@ -245,6 +277,19 @@ struct RegionSessions::Impl {
}
if (const auto* m = std::get_if<network::SessionRefresh>(&*decoded))
return refresh(c, *m, now_seconds, now);
if (const auto* m = std::get_if<network::SessionAction>(&*decoded)) {
const auto receipt = intents.action(c.session, *m, admission());
send(c, receipt);
// A duplicate of a final action: answer with the outcome as well.
if (receipt.status == network::AdmitStatus::duplicate)
if (const auto o = intents.query(c.session, {m->action_id});
o.result == network::ActionResult::committed_no_effect ||
o.result == network::ActionResult::not_committed)
send(c, o);
return;
}
if (const auto* m = std::get_if<network::ActionQuery>(&*decoded))
return send(c, intents.query(c.session, *m));
if (const auto* m = std::get_if<network::SessionClose>(&*decoded);
m && m->reason == SessionCloseReason::client_closed) {
close(c, SessionCloseReason::client_closed, now);
@@ -275,22 +320,31 @@ RegionSessions::create(RegionSessionsConfig config) {
for (const auto& k : config.issuer_keys)
if (!verifier->add_key(k.key_id, k.public_key))
return std::unexpected(RegionSessionsError::keys);
config.intents.max_sessions = config.control.max_sessions;
auto intents = network::IntentAdmission::create(config.intents);
if (!intents)
return std::unexpected(RegionSessionsError::configuration);
auto endpoint = network::quic::Endpoint::serve(config.transport);
if (!endpoint)
return std::unexpected(RegionSessionsError::transport);
return std::unique_ptr<RegionSessions>{new RegionSessions{std::make_unique<Impl>(
std::move(config), std::move(*endpoint), std::move(*verifier), std::move(*control))}};
return std::unique_ptr<RegionSessions>{new RegionSessions{
std::make_unique<Impl>(std::move(config), std::move(*endpoint), std::move(*verifier),
std::move(*control), std::move(*intents))}};
}
void RegionSessions::poll(std::uint64_t epoch, std::uint64_t now_seconds, Clock::time_point now) {
void RegionSessions::poll(const HostFacts& facts, std::uint64_t now_seconds,
Clock::time_point now) {
auto& m = *impl_;
if (epoch > m.control.epoch()) {
// Every session ends with the epoch (ADR-0089); control has released them.
const auto closed = m.control.advance_epoch(epoch);
m.facts = facts;
if (facts.epoch > m.control.epoch()) {
// Every session ends with the epoch (ADR-0089); control has released them. Actions
// never carried are final; carried ones await their durable record.
const auto closed = m.control.advance_epoch(facts.epoch);
if (closed)
for (const auto session : *closed)
if (auto* c = m.by_session(session))
m.close(*c, SessionCloseReason::stale_epoch, now);
(void)m.intents.abandon(); // Kept for queries; no session is left to tell.
}
for (auto& e : m.endpoint->poll()) {
using network::quic::EventKind;
@@ -307,6 +361,8 @@ void RegionSessions::poll(std::uint64_t epoch, std::uint64_t now_seconds, Clock:
m.connections, [&](const Impl::Connection& c) { return c.id == e.connection; });
if (it == m.connections.end())
continue;
if (it->state == Impl::State::established)
m.intents.close(it->session);
if (it->state == Impl::State::pending) {
(void)m.control.close(it->session).has_value();
if (m.config.ledger && it->generation != 0)
@@ -323,15 +379,21 @@ void RegionSessions::poll(std::uint64_t epoch, std::uint64_t now_seconds, Clock:
: SessionCloseReason::connection_lost});
}
m.connections.erase(it);
} // Datagrams carry nothing before 10.4.
} else if (e.kind == EventKind::datagram) {
if (auto* c = m.find(e.connection))
m.datagram(*c, e.bytes, now);
}
}
for (const auto& [session, watermark] : m.intents.simulated(m.admission()))
if (auto* c = m.by_session(session); c && c->state == Impl::State::established)
m.send_datagram(*c, watermark);
for (const auto session : m.control.expire(now_seconds))
if (auto* c = m.by_session(session))
m.close(*c, SessionCloseReason::expired, now);
for (auto& c : m.connections) {
m.renew(c, now);
if (c.state == Impl::State::pending && now >= c.deadline)
m.welcome(c);
m.welcome(c, now);
if (c.state == Impl::State::hello && now >= c.deadline)
m.close(c, SessionCloseReason::timeout, now);
if (c.state == Impl::State::closing && now >= c.deadline && !c.close_requested) {
@@ -341,6 +403,14 @@ void RegionSessions::poll(std::uint64_t epoch, std::uint64_t now_seconds, Clock:
}
}
std::vector<network::CarriedAction> RegionSessions::carry(std::uint64_t tick) {
return impl_->intents.carry(tick);
}
void RegionSessions::committed(std::uint64_t end_tick, std::uint64_t commit_sequence) {
impl_->deliver(impl_->intents.committed(end_tick, commit_sequence));
}
void RegionSessions::shutdown(Clock::time_point now) {
for (auto& c : impl_->connections)
impl_->close(c, SessionCloseReason::shutdown, now);
+140 -3
View File
@@ -1,5 +1,6 @@
#include "evo/identity/identity.hpp"
#include "evo/network/dev_grant.hpp"
#include "evo/network/intent_admission.hpp"
#include "evo/network/session_control.hpp"
#include "evo/network/session_grant.hpp"
#include "evo/network/session_protocol.hpp"
@@ -326,7 +327,7 @@ void session_codec() {
WireGrant grant{};
for (std::size_t i = 0; i < grant.size(); ++i)
grant.at(i) = static_cast<std::uint8_t>(i * 7);
SessionWelcome welcome{1, 2, 3, 4, 5, 6, 7};
SessionWelcome welcome{1, 2, 3, 4, 5, 6, 7, 8};
const std::vector<SessionMessage> messages{
SessionHello{0, grant},
welcome,
@@ -334,7 +335,14 @@ void session_codec() {
SessionRefreshResult{0, 99},
SessionRefreshResult{static_cast<std::uint8_t>(SessionCloseReason::stale_grant), 0},
SessionClose{SessionCloseReason::superseded},
SessionClose{SessionCloseReason::shutdown}};
SessionClose{SessionCloseReason::shutdown},
SessionIntention{1, 2, 3, 4, -1000, 7},
IntentionReceipt{3, AdmitStatus::not_ready, 9},
SimulatedThrough{2, 3, 4},
SessionAction{1, 2, 77, 1, 5},
ActionReceipt{77, AdmitStatus::duplicate, 4, 5},
ActionOutcome{77, ActionResult::committed_no_effect, 5, 12},
ActionQuery{77}};
for (const auto& m : messages) {
const auto bytes = encode_session(m);
CHECK(bytes.at(0) == 'E' && bytes.at(1) == 'V' && bytes.at(2) == 'S' && bytes.at(3) == 'N');
@@ -359,7 +367,7 @@ void session_codec() {
mutated = bytes;
mutated.at(7) = 1;
CHECK(refused(decode_session(mutated), SessionCodecError::reserved_flags));
for (const auto type : std::array<std::uint8_t, 3>{0, 6, 255}) {
for (const auto type : std::array<std::uint8_t, 3>{0, 13, 255}) {
mutated = bytes;
mutated.at(6) = type;
CHECK(refused(decode_session(mutated), SessionCodecError::unknown_type));
@@ -378,12 +386,140 @@ void session_codec() {
CHECK(refused(decode_session(result), SessionCodecError::invalid_value));
}
}
// Decoded values survive exactly (signed vectors, every field).
const SessionIntention intent{9, 8, 7, 6, -1000, 999};
CHECK(std::get<SessionIntention>(*decode_session(encode_session(intent))) == intent);
const ActionOutcome outcome{5, ActionResult::not_committed, 0, 0};
CHECK(std::get<ActionOutcome>(*decode_session(encode_session(outcome))) == outcome);
// A state claim appended to an intention (position, energy) is not a valid message.
auto claimed = encode_session(intent);
for (int i = 0; i < 16; ++i)
claimed.push_back(0x7F);
CHECK(refused(decode_session(claimed), SessionCodecError::wrong_length));
for (const auto bad : std::array<std::uint8_t, 3>{11, 200, 255}) {
auto receipt = encode_session(IntentionReceipt{1, AdmitStatus::admitted, 1});
receipt.at(session_header_bytes + 8) = bad;
CHECK(refused(decode_session(receipt), SessionCodecError::invalid_value));
}
for (const auto bad : std::array<std::uint8_t, 3>{0, 5, 255}) {
auto o = encode_session(outcome);
o.at(session_header_bytes + 8) = bad;
CHECK(refused(decode_session(o), SessionCodecError::invalid_value));
}
for (const auto zero : {0, 1}) {
auto w = welcome;
(zero == 0 ? w.session : w.epoch) = 0;
CHECK(refused(decode_session(encode_session(w)), SessionCodecError::invalid_value));
}
}
void intent_admission() {
IntentLimits limits;
limits.max_unresolved = 6;
limits.max_finals = 4;
CHECK(refused(IntentAdmission::create(IntentLimits{0}), IntentConfigError::invalid));
auto a = *IntentAdmission::create(limits);
const auto alice = account(1), bob = account(2);
CHECK(a.open(1, alice) && a.open(2, bob) && !a.open(1, alice) && !a.open(0, alice));
AdmissionFacts f{true, 5, 100};
const auto intention = [&](std::uint64_t session, std::uint64_t seq, std::uint64_t tick,
std::int16_t x = 0, std::uint64_t epoch = 5) {
return a.intention(session, SessionIntention{session, epoch, seq, tick, x, 0}, f).status;
};
// Every refusal, in the order admission applies them.
CHECK(intention(1, 1, 101) == AdmitStatus::admitted);
CHECK(a.intention(1, SessionIntention{2, 5, 2, 102, 0, 0}, f).status ==
AdmitStatus::unknown_session); // Names another session.
CHECK(a.intention(9, SessionIntention{9, 5, 2, 102, 0, 0}, f).status ==
AdmitStatus::unknown_session); // No such session.
CHECK(intention(1, 2, 102, 0, 4) == AdmitStatus::stale_epoch);
CHECK(intention(1, 2, 102, 1001) == AdmitStatus::invalid_vector);
CHECK(intention(1, 1, 102) == AdmitStatus::replayed);
CHECK(intention(1, 2, 100) == AdmitStatus::outside_window); // Not in the future.
CHECK(intention(1, 2, 109) == AdmitStatus::outside_window); // Beyond 8 ticks.
CHECK(intention(1, 2, 101) == AdmitStatus::outside_window); // Same tick as before.
CHECK(intention(1, 2, 102) == AdmitStatus::rate_limited); // 8 attempts this window.
f.server_tick = 108; // New window.
f.ready = false;
CHECK(intention(1, 2, 109) == AdmitStatus::not_ready);
f.ready = true;
CHECK(intention(1, 2, 109) == AdmitStatus::admitted);
CHECK(intention(1, 3, 110) == AdmitStatus::admitted);
// Simulated watermark: only intentions whose tick ran, cumulatively.
f.server_tick = 109;
auto marks = a.simulated(f);
CHECK(marks.size() == 1 && marks[0].first == 1 &&
marks[0].second == SimulatedThrough{5, 2, 109});
CHECK(a.simulated(f).empty()); // Unchanged: not repeated yet.
f.server_tick = 110;
marks = a.simulated(f);
CHECK(marks.size() == 1 && marks[0].second.sequence == 3);
f.server_tick = 130;
marks = a.simulated(f); // Repeated after 20 ticks so a lost datagram is covered.
CHECK(marks.size() == 1 && marks[0].second == SimulatedThrough{5, 3, 130});
// Actions: receipt, carried with its tick's batch, final after the commit.
const auto action = [&](std::uint64_t session, std::uint64_t id, std::uint64_t tick,
std::uint16_t kind = 1) {
return a.action(session, SessionAction{session, 5, id, kind, tick}, f);
};
f.server_tick = 200;
auto r = action(1, 10, 203);
CHECK(r.status == AdmitStatus::admitted && r.tick == 203 && r.server_tick == 200);
CHECK(a.query(1, {10}).result == ActionResult::pending);
CHECK(action(1, 0, 203).status == AdmitStatus::invalid_action);
CHECK(action(1, 11, 203, 9).status == AdmitStatus::invalid_action);
{ // Wire kind 257 must not truncate to a known kind.
auto other = *IntentAdmission::create(IntentLimits{});
CHECK(other.open(1, alice));
CHECK(other.action(1, SessionAction{1, 5, 1, 257, 101}, AdmissionFacts{true, 5, 100})
.status == AdmitStatus::invalid_action);
}
r = action(1, 10, 204); // Retry with another tick: the original stands.
CHECK(r.status == AdmitStatus::duplicate && r.tick == 203);
CHECK(action(1, 12, 203).status == AdmitStatus::rate_limited); // 4 action attempts.
CHECK(a.carry(202).empty());
const auto carried = a.carry(203);
CHECK(carried.size() == 1 && carried[0] == CarriedAction{alice, 10, 203, ActionKind::probe});
CHECK(a.carry(203).empty()); // Each action is carried once.
CHECK(a.committed(202, 7).empty());
auto outcomes = a.committed(203, 8);
CHECK(outcomes.size() == 1 && outcomes[0].account == alice &&
outcomes[0].outcome == ActionOutcome{10, ActionResult::committed_no_effect, 203, 8});
CHECK(a.query(1, {10}) == outcomes[0].outcome);
CHECK(a.query(2, {10}).result == ActionResult::unknown); // Bob's account has no action 10.
// A reconnect of the same account (new session) sees the same outcome.
a.close(1);
CHECK(a.query(1, {10}).result == ActionResult::unknown); // Closed session asks nothing.
CHECK(a.open(3, alice) && a.session_of(alice) == 3u);
CHECK(a.query(3, {10}) == outcomes[0].outcome);
f.server_tick = 300;
CHECK(action(3, 10, 301).status == AdmitStatus::duplicate); // Never admitted twice.
// Unresolved cap counts intentions and actions; abandon finalizes only uncarried actions.
CHECK(action(3, 20, 301).status == AdmitStatus::admitted);
CHECK(action(3, 21, 308).status == AdmitStatus::admitted);
(void)a.carry(301);
for (std::uint64_t i = 0; i < 4; ++i)
CHECK(a.intention(3, SessionIntention{3, 5, i + 1, 302 + i, 0, 0}, f).status ==
AdmitStatus::admitted);
CHECK(a.unresolved(3) == 6);
CHECK(a.intention(3, SessionIntention{3, 5, 9, 307, 0, 0}, f).status ==
AdmitStatus::too_many_unresolved);
outcomes = a.abandon();
CHECK(outcomes.size() == 1 &&
outcomes[0].outcome == ActionOutcome{21, ActionResult::not_committed, 0, 0});
CHECK(a.query(3, {20}).result == ActionResult::pending); // Carried: awaits its record.
CHECK(a.unresolved(3) == 1);
CHECK(a.committed(301, 9).size() == 1); // Its batch turned out durable.
// Final outcomes are kept within a bound; older ones become unknown here.
for (std::uint64_t id = 30; id < 34; ++id) {
f.server_tick += 8;
CHECK(action(3, id, f.server_tick + 1).status == AdmitStatus::admitted);
(void)a.carry(f.server_tick + 1);
CHECK(a.committed(f.server_tick + 1, id).size() == 1);
}
CHECK(a.query(3, {10}).result == ActionResult::unknown);
CHECK(a.query(3, {33}).result == ActionResult::committed_no_effect);
}
} // namespace
void control_tests() {
@@ -391,5 +527,6 @@ void control_tests() {
identity_adapter();
control_rules();
session_codec();
intent_admission();
}
} // namespace evo::network_test
+101 -2
View File
@@ -150,7 +150,7 @@ struct Harness {
return std::move(*made);
}
void pump() {
server->poll(epoch, now_seconds, Clock::now());
server->poll({ready, epoch, tick}, now_seconds, Clock::now());
for (auto& e : server->take_events())
events.push_back(std::move(e));
for (auto* c : clients)
@@ -189,7 +189,8 @@ struct Harness {
std::unique_ptr<RegionSessions> server;
std::vector<RegionSessionClient*> clients;
std::vector<RegionSessionEvent> events;
std::uint64_t epoch{5}, now_seconds{start};
std::uint64_t epoch{5}, now_seconds{start}, tick{100};
bool ready{true};
};
bool refused_with(Harness& h, const WireGrant& grant, Reason reason) {
@@ -370,6 +371,103 @@ struct FakeLedger final : ControlLedger {
std::vector<std::uint64_t> renewed, released;
};
// M10.4: intentions, actions and their distinct answers against a simulated host.
void intentions_and_actions(const Files& f) {
Harness h{f};
const auto alice = account(1);
auto a = h.connect(h.issuer.grant(alice, 1));
CHECK(h.settled(*a) && must(a->welcome()).server_tick == 100 && a->server_tick() == 100);
// Intention: a receipt, then the simulated watermark once its tick runs.
CHECK(a->send_intention(101, 10, -10) == 1u);
std::vector<IntentionReceipt> receipts;
CHECK(h.until([&] { return !(receipts = a->take_intention_receipts()).empty(); }));
CHECK(receipts[0] == IntentionReceipt{1, AdmitStatus::admitted, 100});
CHECK(!a->simulated());
CHECK(a->send_intention(150, 0, 0) == 2u);
CHECK(h.until([&] { return !(receipts = a->take_intention_receipts()).empty(); }));
CHECK(receipts[0].status == AdmitStatus::outside_window);
h.tick = 101;
CHECK(h.until([&] { return a->simulated() && a->simulated()->sequence == 1; }));
CHECK(must(a->simulated()) == SimulatedThrough{5, 1, 101} && a->server_tick() == 101);
h.ready = false;
CHECK(a->send_intention(103, 0, 0) == 3u);
CHECK(h.until([&] { return !(receipts = a->take_intention_receipts()).empty(); }));
CHECK(receipts[0].status == AdmitStatus::not_ready);
h.ready = true;
// Action: receipt (scheduled), carried with its tick's batch, final after the commit.
CHECK(a->send_action(7, ActionKind::probe, 103));
std::vector<ActionReceipt> action_receipts;
CHECK(h.until([&] { return !(action_receipts = a->take_action_receipts()).empty(); }));
CHECK(action_receipts[0] == ActionReceipt{7, AdmitStatus::admitted, 101, 103});
CHECK(a->query_action(7));
std::vector<ActionOutcome> outcomes;
CHECK(h.until([&] { return !(outcomes = a->take_action_outcomes()).empty(); }));
CHECK(outcomes[0].result == ActionResult::pending);
CHECK(h.server->carry(102).empty());
const auto carried = h.server->carry(103);
CHECK(carried.size() == 1 && carried[0] == CarriedAction{alice, 7, 103, ActionKind::probe});
h.server->committed(103, 4);
CHECK(h.until([&] { return !(outcomes = a->take_action_outcomes()).empty(); }));
CHECK(outcomes[0] == ActionOutcome{7, ActionResult::committed_no_effect, 103, 4});
// A retry gets a duplicate receipt and the same final outcome.
CHECK(a->send_action(7, ActionKind::probe, 104));
CHECK(h.until([&] { return !(outcomes = a->take_action_outcomes()).empty(); }));
CHECK(outcomes[0] == ActionOutcome{7, ActionResult::committed_no_effect, 103, 4});
// The stream is ordered: the duplicate receipt arrived before the repeated outcome.
const auto duplicates = a->take_action_receipts();
CHECK(duplicates.size() == 1 &&
duplicates[0] == ActionReceipt{7, AdmitStatus::duplicate, 101, 103});
// Reconnect (lost connection, new grant): the account's action resolves the same way.
auto b = h.connect(h.issuer.grant(alice, 2));
CHECK(h.settled(*b) && b->state() == RegionSessionState::established);
CHECK(b->query_action(7));
CHECK(h.until([&] { return !(outcomes = b->take_action_outcomes()).empty(); }));
CHECK(outcomes[0] == ActionOutcome{7, ActionResult::committed_no_effect, 103, 4});
// An action scheduled but never carried when the epoch moves on is final: not committed.
CHECK(b->send_action(8, ActionKind::probe, 108));
CHECK(h.until([&] { return !b->take_action_receipts().empty(); }));
h.epoch = 6;
CHECK(h.until([&] { return b->state() == RegionSessionState::closed; }));
auto c = h.connect(h.issuer.grant(alice, 3));
CHECK(h.settled(*c) && c->state() == RegionSessionState::established);
CHECK(c->query_action(8));
CHECK(h.until([&] { return !(outcomes = c->take_action_outcomes()).empty(); }));
CHECK(outcomes[0].result == ActionResult::not_committed);
// Intentions of an old epoch are refused.
CHECK(c->send_intention(h.tick + 1, 0, 0));
CHECK(h.until([&] { return !(receipts = c->take_intention_receipts()).empty(); }));
CHECK(receipts[0].status == AdmitStatus::admitted); // c is in epoch 6.
// A peer that appends state claims (position, energy) to an intention is closed.
auto peer = h.raw();
quic::ConnectionId id = 0;
std::optional<SessionWelcome> welcome;
std::optional<Reason> reason;
CHECK(h.until([&] {
for (auto& e : peer->poll()) {
if (e.kind == quic::EventKind::connected) {
id = e.connection;
CHECK(peer->send_message(
id, encode_session(SessionHello{0, h.issuer.grant(account(4), 1)})));
} else if (e.kind == quic::EventKind::message) {
const auto m = decode_session(e.bytes);
if (m && std::holds_alternative<SessionWelcome>(*m)) {
welcome = std::get<SessionWelcome>(*m);
auto claim = encode_session(
SessionIntention{welcome->session, welcome->epoch, 1, h.tick + 1, 0, 0});
for (int i = 0; i < 16; ++i)
claim.push_back(0x7F); // "position" and "energy"
CHECK(peer->send_datagram(id, claim));
} else if (m && std::holds_alternative<SessionClose>(*m)) {
reason = std::get<SessionClose>(*m).reason;
}
}
}
return reason.has_value();
}));
CHECK(welcome && reason == Reason::protocol);
}
void durable_control(const Files& f) {
FakeLedger ledger;
Harness h{f, 4, 64, &ledger};
@@ -444,6 +542,7 @@ int main() try {
login_rules(files);
limits(files);
durable_control(files);
intentions_and_actions(files);
std::filesystem::remove_all(files.dir);
std::puts("quic session tests passed");
return 0;