Files
aevolution/apps/evo-session-probe/main.cpp
T
dingoandClaude Opus 5.5 dabeee8e8b
Foundation / checks (deploy) (push) Successful in 3m20s
Foundation / checks (ecs) (push) Successful in 2m0s
Foundation / checks (client) (push) Failing after 12m9s
Foundation / checks (network) (push) Successful in 13m2s
Foundation / checks (tsan) (push) Successful in 8m7s
Foundation / checks (checks) (push) Successful in 32m1s
Foundation / checks (postgres) (push) Successful in 42m43s
Foundation / postgres-tools (push) Skipped
Foundation / server-image (push) Skipped
Foundation / image (push) Skipped
Add M10.8c-2 client handoff switch and evo-server handoff configuration
ADR-0096. The engineering client follows a HandoffOffer into the next region
with its ticket (no grant, no pause, the view kept) and a Redirect to the
probe's owner, picking grants by region claim in rising serial order.
evo-server gains --m10-area, --m10-handoff-key and --m10-neighbour (dev
only), wiring the PostgreSQL probe and handoff ledgers; the probe tool writes
multi-region bundles and reports handoffs and redirects.

Refreshes the dev session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:56:42 -04:00

480 lines
21 KiB
C++

// M10.4c headless session client (ADR-0091, ADR-0092). Development and test only.
//
// evo-session-probe keys --out DIR
// Writes a fresh dev issuer key pair: DIR/issuer.key (32-byte P-256 scalar, owner-only)
// and DIR/issuer.pub (65-byte public key for evo-server --m10-issuer).
// evo-session-probe grants --issuer-key FILE --world N --frame N --region N
// --account HEX32 --out FILE [--serial N] [--count 1..64] [--lifetime 60..3600]
// M10.5c (ADR-0093): writes COUNT 160-byte grants for one account (the engineering
// client's grant bundle), serials SERIAL..SERIAL+COUNT-1, all issued now. Without
// --serial the first is 64 x the issue time in seconds, so a later bundle for the same
// account supersedes an earlier one without bookkeeping. The file is created new and
// owner-only (a credential: never commit or share it); the issuer key stays here.
// The region refuses grants longer than its --m10-max-grant-lifetime (default 300).
// M10.8c (ADR-0096): --region may repeat; COUNT grants are written per region,
// interleaved in serial order, so a client crossing between regions always has a newer
// serial for the next one (serials must rise world-wide). A handoff key is a key pair
// from `keys` (issuer.key for --m10-handoff-key, issuer.pub for --m10-neighbour).
// evo-session-probe run --connect HOST:PORT --server-name NAME --ca FILE --issuer-key FILE
// --world N --frame N --region N --account HEX32 --serial N [--lifetime S]
// [--intents N] [--actions N --action-base ID] [--query ID]... [--timeout-ms N]
// [--interest X,Y,Z,R] [--snapshots N]
// Signs a dev grant for the account and serial, logs in over QUIC, sends N intentions
// (one per tick, two ticks ahead) and N probe actions (three ticks ahead), queries the
// given action ids, and prints one line per answer:
// welcome SESSION EPOCH TICK | intention SEQ STATUS | simulated SEQ TICK
// receipt ID STATUS TICK | outcome ID RESULT TICK COMMIT | done
// resolved HOST ADDRESS (a host name was looked up; IPv4)
// snapshot TICK CELLS ORGANISMS MINX MINY MAXX MAXY Z (each newly applied snapshot;
// --snapshots N waits for N; --interest asks for another focus than the default)
// marker TICK X Y APPLIED (the session's own probe marker in each new snapshot: um
// position after TICK and the newest applied intention sequence; ADR-0094)
// handoff REGION ENDPOINT | redirect REGION ENDPOINT (v4, ADR-0096; then closed)
// closed REASON TRANSPORT (TRANSPORT names why QUIC ended: untrusted means the server
// answered but failed the pinned CA/name check; idle means nothing answered)
// Statuses, results and reasons are the session-v1 wire values. Exits 0 once every
// action is final and every query answered, 1 on timeout, 3 when the server closes.
// The issuer key is a development credential: the probe refuses any environment but dev.
#include "evo/client/region_session.hpp"
#include "evo/network/session_grant.hpp"
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace {
using namespace evo;
using namespace evo::network;
using Clock = std::chrono::steady_clock;
std::optional<std::uint64_t> number(std::string_view v) {
std::uint64_t n = 0;
const auto [end, ec] = std::from_chars(v.data(), v.data() + v.size(), n);
if (ec != std::errc{} || end != v.data() + v.size())
return std::nullopt;
return n;
}
std::string read(const std::filesystem::path& path) {
std::ifstream file{path, std::ios::binary};
return {std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
}
bool write(const std::filesystem::path& path, std::span<const std::uint8_t> bytes) {
std::ofstream file{path, std::ios::binary | std::ios::trunc};
file.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(bytes.size()));
return file.good();
}
std::optional<AccountId> account_of(std::string_view hex) {
if (hex.size() != 32)
return std::nullopt;
AccountId id;
for (std::size_t i = 0; i < 16; ++i) {
unsigned value = 0;
const auto [end, ec] =
std::from_chars(hex.data() + (2 * i), hex.data() + (2 * i) + 2, value, 16);
if (ec != std::errc{} || end != hex.data() + (2 * i) + 2)
return std::nullopt;
id.bytes.at(i) = static_cast<std::uint8_t>(value);
}
return id.valid() ? std::optional{id} : std::nullopt;
}
const char* cause_name(std::optional<quic::CloseCause> c) {
if (!c)
return "none";
switch (*c) {
case quic::CloseCause::local:
return "local";
case quic::CloseCause::peer:
return "peer";
case quic::CloseCause::idle:
return "idle";
case quic::CloseCause::untrusted:
return "untrusted";
case quic::CloseCause::overloaded:
return "overloaded";
case quic::CloseCause::protocol:
return "protocol";
default:
return "transport";
}
}
std::uint64_t now_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
std::optional<GrantSigningKey> issuer(const std::string& path) {
const auto scalar = read(path);
auto key = GrantSigningKey::import(
DeploymentEnvironment::dev, 1,
std::span{reinterpret_cast<const std::uint8_t*>(scalar.data()), scalar.size()});
if (!key)
return std::nullopt;
return std::move(*key);
}
std::optional<SessionGrant> sign(const GrantSigningKey& key, GrantClaims claims) {
std::array<std::uint8_t, 8> id{};
if (!random_bytes(id))
return std::nullopt;
for (std::size_t i = 0; i < id.size(); ++i)
claims.grant_id |= static_cast<std::uint64_t>(id.at(i)) << (8U * i);
claims.grant_id = std::max<std::uint64_t>(claims.grant_id, 1);
const auto grant = key.sign(claims);
if (!grant)
return std::nullopt;
return *grant;
}
int keys(const std::filesystem::path& out) {
std::filesystem::create_directories(out);
for (int attempt = 0; attempt < 8; ++attempt) {
std::array<std::uint8_t, grant_private_key_bytes> scalar{};
if (!random_bytes(scalar))
return 1;
auto key = GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar);
if (!key)
continue; // Out of the curve's range: draw again.
const auto pub = key->public_key();
if (!pub || !write(out / "issuer.key", scalar) || !write(out / "issuer.pub", *pub))
return 1;
std::filesystem::permissions(out / "issuer.key",
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace);
std::puts("keys written");
return 0;
}
return 1;
}
struct RunOptions {
std::string host, server_name, ca, issuer_key;
std::uint16_t port{};
std::uint64_t world{}, frame{}, region{}, serial{}, lifetime{60}, intents{}, actions{},
action_base{1}, timeout_ms{20000};
std::optional<AccountId> account;
std::vector<std::uint64_t> queries;
std::vector<std::uint64_t> more_regions; // grants: further --region values.
std::optional<SessionInterest> interest;
std::uint64_t snapshots{};
};
std::optional<SessionInterest> interest_of(std::string_view v) {
std::array<std::int64_t, 4> parts{};
for (std::size_t i = 0; i < parts.size(); ++i) {
const auto comma = v.find(',');
const auto part = v.substr(0, comma);
const auto [end, ec] = std::from_chars(part.data(), part.data() + part.size(), parts.at(i));
if (ec != std::errc{} || end != part.data() + part.size() ||
(comma == std::string_view::npos) != (i + 1 == parts.size()))
return std::nullopt;
v.remove_prefix(comma == std::string_view::npos ? v.size() : comma + 1);
}
if (parts[3] < 0 || parts[3] > 65535)
return std::nullopt;
return SessionInterest{parts[0], parts[1], parts[2], static_cast<std::uint16_t>(parts[3])};
}
// Exclusive create, owner-only on POSIX: a bundle is a credential.
bool write_new(const std::filesystem::path& path, std::span<const std::uint8_t> bytes) {
if (std::filesystem::exists(path))
return false;
if (!write(path, bytes))
return false;
std::filesystem::permissions(
path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace);
return true;
}
int grants(const RunOptions& o, const std::string& out, std::uint64_t count) {
const auto key = issuer(o.issuer_key);
if (!key || !o.account) {
std::puts("error issuer-key");
return 2;
}
GrantClaims claims;
claims.account = *o.account;
claims.world = {o.world, o.frame};
claims.issued_at = now_seconds();
claims.expires_at = claims.issued_at + o.lifetime;
const auto first = o.serial != 0 ? o.serial : claims.issued_at * 64;
std::vector<std::uint64_t> regions{o.region};
regions.insert(regions.end(), o.more_regions.begin(), o.more_regions.end());
if (count * regions.size() > 64) {
std::puts("error count (at most 64 grants in all)");
return 2;
}
std::vector<std::uint8_t> bundle;
std::uint64_t serial = first;
for (std::uint64_t i = 0; i < count; ++i)
for (const auto region : regions) {
claims.region = region;
claims.serial = serial++;
const auto grant = sign(*key, claims);
if (!grant) {
std::puts("error grant");
return 2;
}
bundle.insert(bundle.end(), grant->begin(), grant->end());
}
count *= regions.size();
if (!write_new(out, bundle)) {
std::puts("error out (exists or unwritable)");
return 1;
}
std::printf("wrote %llu grants serial %llu..%llu valid %llu s\n",
static_cast<unsigned long long>(count), static_cast<unsigned long long>(first),
static_cast<unsigned long long>(first + count - 1),
static_cast<unsigned long long>(o.lifetime));
return 0;
}
int run(const RunOptions& o) {
const auto key = issuer(o.issuer_key);
if (!key) {
std::puts("error issuer-key");
return 2;
}
if (!o.account)
return 2; // Required at parse time.
GrantClaims claims;
claims.account = *o.account;
claims.serial = o.serial;
claims.world = {o.world, o.frame};
claims.region = o.region;
claims.issued_at = now_seconds();
claims.expires_at = claims.issued_at + o.lifetime;
const auto grant = sign(*key, claims);
if (!grant) {
std::puts("error grant");
return 2;
}
client::RegionSessionClientConfig config;
const auto address = quic::resolve_ipv4(o.host);
if (!address) {
std::puts("error resolve");
return 2;
}
if (*address != o.host)
std::printf("resolved %s %s\n", o.host.c_str(), address->c_str());
config.transport.server_address = *address;
config.transport.port = o.port;
config.transport.server_name = o.server_name;
config.transport.authority_pem = read(o.ca);
config.transport.authority_pem_file = o.ca;
config.grant = *grant;
auto made = client::RegionSessionClient::connect(std::move(config), Clock::now());
if (!made) {
std::puts("error connect");
return 2;
}
auto& c = **made;
const auto deadline = Clock::now() + std::chrono::milliseconds{o.timeout_ms};
bool welcomed = false, queried = false;
std::uint64_t sent_intents = 0, sent_actions = 0, last_tick = 0, simulated = 0;
std::uint64_t seen_snapshot = 0, snapshots = 0;
std::set<std::uint64_t> pending_actions, pending_queries(o.queries.begin(), o.queries.end());
for (std::uint64_t i = 0; i < o.actions; ++i)
pending_actions.insert(o.action_base + i);
while (Clock::now() < deadline) {
c.poll(Clock::now());
if (c.state() == client::RegionSessionState::closed) {
if (const auto offer = c.take_handoff())
std::printf("handoff %llu %s\n",
static_cast<unsigned long long>(offer->destination.region),
offer->destination.endpoint.c_str());
if (const auto& to = c.redirect())
std::printf("redirect %llu %s\n", static_cast<unsigned long long>(to->region),
to->endpoint.c_str());
std::printf("closed %u %s\n",
static_cast<unsigned>(
c.close_reason().value_or(SessionCloseReason::connection_lost)),
cause_name(c.transport_cause()));
return 3;
}
if (c.state() != client::RegionSessionState::established) {
std::this_thread::sleep_for(std::chrono::milliseconds{2});
continue;
}
if (!welcomed) {
welcomed = true;
const auto& w = *c.welcome();
std::printf("welcome %llu %llu %llu\n", static_cast<unsigned long long>(w.session),
static_cast<unsigned long long>(w.epoch),
static_cast<unsigned long long>(w.server_tick));
}
const auto tick = c.server_tick();
if (tick != last_tick) {
last_tick = tick;
if (sent_intents < o.intents && c.send_intention(tick + 2, 100, 0))
++sent_intents;
if (sent_actions < o.actions &&
c.send_action(o.action_base + sent_actions, ActionKind::probe, tick + 3))
++sent_actions;
}
if (!queried) {
queried = true;
if (o.interest && !c.set_interest(*o.interest))
std::puts("error interest");
for (const auto query : o.queries)
(void)c.query_action(query);
}
for (const auto& r : c.take_intention_receipts())
std::printf("intention %llu %u\n", static_cast<unsigned long long>(r.sequence),
static_cast<unsigned>(r.status));
if (const auto s = c.simulated(); s && s->sequence != simulated) {
simulated = s->sequence;
std::printf("simulated %llu %llu\n", static_cast<unsigned long long>(s->sequence),
static_cast<unsigned long long>(s->tick));
}
if (const auto* v = c.view(); v && v->tick != seen_snapshot) {
seen_snapshot = v->tick;
++snapshots;
std::int64_t min_x = 0, min_y = 0, max_x = 0, max_y = 0;
for (std::size_t i = 0; i < v->environment.size(); ++i) {
const auto& voxel = v->environment[i].voxel;
min_x = i == 0 ? voxel.x : std::min(min_x, voxel.x);
min_y = i == 0 ? voxel.y : std::min(min_y, voxel.y);
max_x = i == 0 ? voxel.x : std::max(max_x, voxel.x);
max_y = i == 0 ? voxel.y : std::max(max_y, voxel.y);
}
std::printf("snapshot %llu %zu %zu %lld %lld %lld %lld %lld\n",
static_cast<unsigned long long>(v->tick), v->environment.size(),
v->organisms.size(), static_cast<long long>(min_x),
static_cast<long long>(min_y), static_cast<long long>(max_x),
static_cast<long long>(max_y), static_cast<long long>(v->slice_z));
for (const auto& m : v->markers)
if (m.own)
std::printf(
"marker %llu %lld %lld %llu\n", static_cast<unsigned long long>(v->tick),
static_cast<long long>(m.state.x), static_cast<long long>(m.state.y),
static_cast<unsigned long long>(m.applied_sequence));
}
for (const auto& r : c.take_action_receipts())
std::printf("receipt %llu %u %llu\n", static_cast<unsigned long long>(r.action_id),
static_cast<unsigned>(r.status), static_cast<unsigned long long>(r.tick));
for (const auto& out : c.take_action_outcomes()) {
std::printf(
"outcome %llu %u %llu %llu\n", static_cast<unsigned long long>(out.action_id),
static_cast<unsigned>(out.result), static_cast<unsigned long long>(out.tick),
static_cast<unsigned long long>(out.commit_sequence));
pending_queries.erase(out.action_id);
if (out.result == ActionResult::committed_no_effect ||
out.result == ActionResult::not_committed)
pending_actions.erase(out.action_id);
}
std::fflush(stdout);
if (sent_actions == o.actions && pending_actions.empty() && pending_queries.empty() &&
sent_intents == o.intents && simulated >= std::min<std::uint64_t>(o.intents, 1) &&
snapshots >= o.snapshots) {
std::printf("snapshot-bytes %llu chunks %llu\n",
static_cast<unsigned long long>(c.snapshot_bytes()),
static_cast<unsigned long long>(c.snapshot_chunks()));
std::puts("done");
c.close();
return 0;
}
std::this_thread::sleep_for(std::chrono::milliseconds{2});
}
std::puts("timeout");
return 1;
}
} // namespace
int main(int argc, char** argv) {
const std::vector<std::string_view> args(argv + 1, argv + argc);
if (args.size() == 3 && args[0] == "keys" && args[1] == "--out")
return keys(std::filesystem::path{std::string{args[2]}});
RunOptions o;
const bool bundle = !args.empty() && args[0] == "grants";
std::string out;
std::uint64_t count = 1;
if (bundle)
o.lifetime = 300; // The region's default maximum.
bool ok = !args.empty() && (args[0] == "run" || bundle) && args.size() % 2 == 1;
for (std::size_t i = 1; ok && i + 1 < args.size(); i += 2) {
const auto flag = args[i];
const auto value = args[i + 1];
const auto n = number(value);
if (flag == "--connect") {
const auto colon = value.rfind(':');
const auto port =
colon == std::string_view::npos ? std::nullopt : number(value.substr(colon + 1));
ok = port && *port > 0 && *port <= 65535;
if (ok) {
o.host = std::string{value.substr(0, colon)};
o.port = static_cast<std::uint16_t>(*port);
}
} else if (flag == "--server-name")
o.server_name = value;
else if (flag == "--ca")
o.ca = value;
else if (flag == "--issuer-key")
o.issuer_key = value;
else if (flag == "--account")
ok = (o.account = account_of(value)).has_value();
else if (flag == "--query" && n)
o.queries.push_back(*n);
else if (n && flag == "--world")
o.world = *n;
else if (n && flag == "--frame")
o.frame = *n;
else if (n && *n != 0 && flag == "--region" && bundle && o.region != 0)
o.more_regions.push_back(*n);
else if (n && flag == "--region")
o.region = *n;
else if (n && flag == "--serial")
o.serial = *n;
else if (n && flag == "--lifetime" && *n > 0 && *n <= 3600)
o.lifetime = *n;
else if (n && flag == "--intents" && *n <= 1000)
o.intents = *n;
else if (n && flag == "--actions" && *n <= 1000)
o.actions = *n;
else if (n && flag == "--action-base" && *n > 0)
o.action_base = *n;
else if (n && flag == "--timeout-ms" && *n > 0)
o.timeout_ms = *n;
else if (n && flag == "--snapshots" && *n <= 100000)
o.snapshots = *n;
else if (flag == "--interest")
ok = (o.interest = interest_of(value)).has_value();
else if (bundle && flag == "--out")
out = value;
else if (bundle && n && flag == "--count" && *n >= 1 && *n <= 64)
count = *n;
else
ok = false;
}
if (bundle && ok && !o.issuer_key.empty() && o.account && o.world != 0 && o.frame != 0 &&
o.region != 0 && !out.empty() && o.lifetime >= 60 && o.host.empty())
return grants(o, out, count);
if (bundle || !ok || o.host.empty() || o.server_name.empty() || o.ca.empty() ||
o.issuer_key.empty() || !o.account || o.world == 0 || o.frame == 0 || o.region == 0 ||
o.serial == 0) {
std::fputs("usage: evo-session-probe keys --out DIR | grants --issuer-key FILE "
"--world N --frame N --region N --account HEX32 --out FILE [--serial N] "
"[--count 1..64] [--lifetime 60..3600] | run --connect HOST:PORT "
"--server-name NAME --ca FILE --issuer-key FILE --world N --frame N "
"--region N --account HEX32 --serial N [--lifetime S] [--intents N] "
"[--actions N --action-base ID] [--query ID]... [--timeout-ms N] "
"[--interest X,Y,Z,R] [--snapshots N]\n",
stderr);
return 2;
}
return run(o);
}