Files
dingoandClaude Opus 5.5 46c106409e
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 4m33s
Foundation / postgres-tools (push) Successful in 2m14s
Foundation / server-image (push) Successful in 5m21s
Foundation / image (push) Successful in 6m18s
feat(admin): session windows in SQL, opened from the admin portal (schema 62)
The dev session window moves from Git to SQL (ADR-0087 amendment): the admin
portal opens, extends (30 min to 4 h from now) and closes it, and the cellular
region re-reads it every 5 s with --session-window-source db. No push, sync or
restart per window; a closed window keeps the region running instead of
crash-looping.

- Schema 62: append-only session_windows (4 h cap, no rewrites),
  load_session_window_v1 for the runtime group, admin_set_session_window_v1
  and admin_session_windows_v1 for a dedicated admin group role, granted and
  audited each migration run when EVO_PG_ADMIN_ROLE is set (aevolution_admin in
  DEV). Schema 61's views are revoked from the runtime group.
- RegionSessions admission switch: while closed every Hello is refused before
  signature work and closing closes open sessions (new sessions were still
  admitted after expiry before).
- Admin API: GET/POST /api/regions/<n>/session-window, window state in the
  regions list; the portal's session-window card with history.
- Git: REGION_SESSION_WINDOW and the pre-push refresh rule are removed; the
  policy check requires the database source and refuses a committed window.

Needs the new image and the aevolution_admin role (with the portal's login in
aevolution-admin-pg) before a sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:13:02 -04:00

227 lines
14 KiB
C++

#pragma once
#include "evo/network/handoff_ticket.hpp"
#include "evo/network/intent_admission.hpp"
#include "evo/network/probe_motion.hpp"
#include "evo/network/quic_transport.hpp"
#include "evo/network/replication.hpp"
#include "evo/network/session_control.hpp"
#include "evo/network/session_grant.hpp"
#include "evo/network/session_protocol.hpp"
#include "evo/server/probe_ledger.hpp"
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <vector>
// M10.3b region-side session login over QUIC (ADR-0091, schemas/network/session-v1.md).
// Owned by the region host's thread, which calls poll(). A connection must send Hello
// with a grant before the deadline; the grant is verified with the region's issuer
// 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.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.
// M10.5 (ADR-0093): every established session has a spatial interest (the default set by
// the host until the client sends its own); the host calls replicate() once per simulated
// tick and each session receives its snapshot chunks as datagrams sized to its path.
// M10.6 (ADR-0094, EXPERIMENT): once the host sets a motion area, every established session
// has a probe marker; admitted intentions schedule its movement, each poll advances markers
// to the simulated tick, and snapshots carry them. A new epoch starts without markers.
// M10.8b (ADR-0096): a Hello may carry a handoff ticket instead of a grant (same slot,
// another marker). A ticket verified against a neighbour's key for this region opens a
// session for its account after the HandoffLedger durably staged and committed its transfer
// and moved the account's control here.
// 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`.
namespace evo::server {
struct IssuerKey {
std::uint32_t key_id{};
network::GrantPublicKey public_key{};
};
// A region whose area adjoins this one: where its clients dial and the area it owns.
struct Neighbour {
network::RegionAddress address;
network::motion::Area area; // Micrometres, same slice as this region's.
};
// A neighbouring region's handoff public key (ADR-0096): tickets it signs are accepted here.
struct HandoffKey {
std::uint64_t source_region{};
std::uint32_t key_id{};
network::GrantPublicKey public_key{};
};
// Operator-provisioned destination for a durable primitive life. This world catalog is
// independent of physical neighbours and is consulted only before a grant claims control.
struct LifeOwnerRoute {
network::RegionAddress address;
};
// A host's answer to one v10 choice: the receipt status and target tick, plus the final
// outcome when the same action already published.
struct CellularMutationAnswer {
network::AdmitStatus status{};
std::uint64_t tick{};
std::optional<network::ActionOutcome> outcome;
};
struct RegionSessionsConfig {
network::quic::ServerConfig transport;
network::ControlConfig control; // `epoch` is the initial ownership epoch.
std::vector<IssuerKey> issuer_keys;
std::chrono::milliseconds hello_deadline{5000}; // Connected to Hello (ADR-0089).
std::chrono::milliseconds close_flush{1000}; // Close sent to connection closed.
// Durable per-world control (10.3c), owned by the host; null keeps control in memory
// only (tests, tools). With a ledger, a session is admitted only after its durable
// claim, waits out another region's control before Welcome, renews every
// `renew_interval` and closes before its control can lapse (`safety_margin`).
network::ControlLedger* ledger{};
// When present, every entry must be supplied by the operator, including this region.
// A life in another region is redirected before durable control can move here.
std::vector<LifeOwnerRoute> life_owner_routes;
std::chrono::milliseconds renew_interval{5000}, safety_margin{2000};
network::IntentLimits intents{}; // max_sessions follows control.max_sessions.
// Durable action records (10.4b), owned by the host; null keeps outcomes in memory only.
network::ActionLedger* actions{};
network::ReplicationLimits replication{}; // max_sessions follows control.max_sessions.
// M10.8b handoff tickets (ADR-0096): neighbours' keys, and the durable side owned by the
// host. Without keys every ticket is refused (unauthenticated). With a ControlLedger a
// ticket also needs a HandoffLedger (control must move durably with the transfer).
std::vector<HandoffKey> handoff_keys;
network::HandoffLedger* handoff{};
// M10.8c: with probe records, a session's marker is the account's durable probe (it opens
// where it was saved, a login whose probe lives elsewhere is redirected). With this
// region's handoff key and neighbours as well, a marker crossing into a neighbour's area
// is frozen, prepared and handed over with a ticket.
ProbeLedger* probes{};
std::shared_ptr<const network::HandoffSigningKey> handoff_key;
std::vector<Neighbour> neighbours;
std::uint64_t ticket_lifetime{30}; // Seconds a handoff ticket is valid.
std::chrono::milliseconds ghost_poll{1000}; // Incoming transfers read this often.
// M10.8d recovery: this often, open outgoing transfers prepared more than ticket_lifetime
// + 10 s ago (by the store's clock, e.g. by a process that died) are aborted.
std::chrono::milliseconds overdue_poll{5000};
// v5/v8/v9 are accepted only when both primitive-life handlers are supplied. Callbacks
// receive the authenticated account and durable control generation for this session.
// A cellular host may enable v5 together with the v7 cellular action path; each
// connection remains fixed to its negotiated protocol.
std::function<network::PrimitiveLifeOutcome(const network::AccountId&, std::uint64_t,
std::uint64_t)>
create_primitive_life;
std::function<network::PrimitiveLifeOutcome(const network::AccountId&, std::uint64_t,
std::uint64_t)>
query_primitive_life;
// M11.3 v6 cellular intentions. Opt-in until a cellular state owner consumes them.
bool accept_cellular_intentions{};
// M11.3 v7 durable cellular actions and v8/v9 owner-filtered perception. Requires durable
// control and action ledgers; the caller forwards carried inputs to profile 4.
bool accept_cellular_actions{};
// M11.4c v10 mutation choices (ADR-0121), answered with an ActionReceipt and, once
// published, an ActionOutcome. Without a handler a v10 choice closes as a protocol error.
std::function<CellularMutationAnswer(const network::AccountId&, std::uint64_t,
const network::CellularMutationAction&)>
select_cellular_mutation;
};
// 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 {
enum class Kind : std::uint8_t { opened, closed, refused } kind{};
std::uint64_t session{}; // 0 for refusals.
std::string account; // log_label, empty when unauthenticated.
network::SessionCloseReason reason{};
};
class RegionSessions {
public:
[[nodiscard]] static std::expected<std::unique_ptr<RegionSessions>, RegionSessionsError>
create(RegionSessionsConfig config);
RegionSessions(const RegionSessions&) = delete;
RegionSessions& operator=(const RegionSessions&) = delete;
~RegionSessions();
// 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);
// Read-only admitted v6 inputs for a tick. The host must inspect them before advancing
// HostFacts::simulated_tick past that tick; poll then publishes the cumulative watermark.
[[nodiscard]] std::vector<network::ScheduledCellularIntention>
cellular_intentions(std::uint64_t tick) const;
// These carried actions are durable in `commit_sequence` (each with the tick it rode):
// their outcomes go to each account's current session.
void committed(std::span<const network::CarriedAction> actions, std::uint64_t commit_sequence);
// The host dropped these carried actions: final ones are reported not_committed; the
// others await their durable record (their batch outcome was unknown).
void dropped(std::span<const network::CarriedAction> actions, bool final);
// Interest given to each new session until it sends its own (none: no snapshots until it
// does). Sessions already open without an interest receive it too.
void set_default_interest(network::SessionInterest interest);
// Sends every interested session its snapshot for `tick` (call once per simulated tick).
// `source` reads the host's state for one interest; `perceives` hides organisms.
void replicate(
std::uint64_t tick,
const std::function<network::ReplicationSource(const network::SessionInterest&)>& source,
const network::Perceives& perceives = {});
// V8 reliable cellular perception is unicast to the current established session
// for the supplied authenticated account. Empty views clear that owner's stale view.
[[nodiscard]] bool send_cellular_perception(const network::AccountId& account,
const network::CellularPerception& perception);
void clear_cellular_perceptions(std::uint64_t tick);
// A published v10 choice's outcome, to the account's current v10 session if any.
[[nodiscard]] bool send_mutation_outcome(const network::AccountId& account,
const network::ActionOutcome& outcome);
// The owner's outstanding offer (11.4d), to the account's current v10 session if any. A
// rules-13 catalog offer (`named`) goes only to a v14 session, an operator offer only to
// v10-v13.
[[nodiscard]] bool send_mutation_offer(const network::AccountId& account,
const network::CellularMutationOffer& offer,
bool named = false);
// 11.8 (ADR-0129): the owner's life ended, with its cause, to its v10 session if any.
[[nodiscard]] bool send_life_ended(const network::AccountId& account,
const network::CellularLifeEnded& ended);
[[nodiscard]] network::ReplicationStats replication_stats() const;
// M10.9a (ADR-0097): the host's load governor output. While `refuse_logins`, a Hello
// carrying a grant is closed with `capacity` before signature work (handoff tickets are
// still admitted); `shed` (0-3) limits replication (ReplicationServer::set_shed).
void set_load(bool refuse_logins, std::uint8_t shed);
// Grant logins refused for load since creation.
[[nodiscard]] std::uint64_t refused_for_load() const noexcept;
// Where probe markers live and spawn (ADR-0094); sessions already established receive a
// marker. False for an invalid area. With neighbours (ADR-0096), markers move within the
// bounding box of this area and the neighbours' areas, and leaving this area hands off.
[[nodiscard]] bool set_motion_area(const network::motion::Area& area, std::int64_t spawn_x,
std::int64_t spawn_y);
[[nodiscard]] const network::motion::ProbeMarkers& markers() const noexcept;
// Closes every connection with `shutdown` (flushed by later polls).
void shutdown(std::chrono::steady_clock::time_point now);
// ADR-0087 session window: while closed, every Hello (grant or handoff ticket) is closed
// with `shutdown` before signature work. Open by default; closing does not close the
// connections already open (call shutdown for that).
void set_admission(bool open) noexcept;
[[nodiscard]] bool admitting() const noexcept;
[[nodiscard]] std::vector<RegionSessionEvent> take_events();
[[nodiscard]] std::optional<std::uint64_t> holder(const network::AccountId& account) const;
[[nodiscard]] std::size_t sessions() const noexcept;
[[nodiscard]] std::size_t connections() const noexcept;
[[nodiscard]] std::uint16_t port() const noexcept;
private:
struct Impl;
explicit RegionSessions(std::unique_ptr<Impl> impl);
std::unique_ptr<Impl> impl_;
};
} // namespace evo::server