feat(admin): live admin commands in trace 5 (schema 63)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 4m44s
Foundation / image (push) Successful in 5m33s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 4m44s
Foundation / image (push) Successful in 5m33s
The admin portal can now spawn wildlife, add bubbles, add to or release the spent pool, remove a cell and grant a cell's reserve on a running rules-13 region (ADR-0182 section 10). No new owner format or region opening. - Trace 5: trace 4 plus 64-byte command records counted in the tick header's last word; a batch without commands stays trace 4 (older builds replay it). Bundle 15 admits trace 5. - CellularLives::admin_candidate applies a tick's commands after its births, each on a copy kept only when it applies and closes: imports through the boundary ledger, removals into the spent pool with a new `removed` corpse cause, spawned roots via the ADR-0180 seed (now a shared helper) funded by an exact import. Refused commands change nothing. - Schema 63: the immutable admin_commands queue (spawn identities from the life allocator), pending/history reads, and binding of every recorded command exactly once inside both cellular publishers; the SQL trace parsers read trace 5 through its trace-4 normal form. - The region polls pending commands every 2 s and appends up to 16 per tick; the admin API and portal gain region actions, per-cell Remove/Grant and the command history. - Fixes an existing test that did not advance its head after a tick commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -149,7 +149,7 @@ bool prepared_is_canonical(const CellularPreparedCommit& prepared,
|
||||
const auto encoded_trace = server::encode_cellular_batch(trace);
|
||||
const auto digest = sha256(prepared.trace);
|
||||
const bool trace_version_matches =
|
||||
trace.format_version == cellular_checkpoint_trace_format(manifest.cellular_versions);
|
||||
cellular_checkpoint_trace_admits(manifest.cellular_versions, trace.format_version);
|
||||
return manifest.profile == CheckpointProfile::cellular_lives_v1 && trace_version_matches &&
|
||||
manifest.key == prepared.key && manifest.commit == prepared.commit &&
|
||||
manifest.sequence > 0 && manifest.batch.trace_bytes == prepared.trace.size() && digest &&
|
||||
@@ -561,7 +561,9 @@ publish_cellular_batch(Postgres& db, const FilesystemObjectStore& objects, const
|
||||
const auto previous = decode_manifest(predecessor.manifest);
|
||||
const auto predecessor_digest = sha256(predecessor.manifest);
|
||||
auto committed_batch = batch;
|
||||
if (previous)
|
||||
if (previous && !(committed_batch.format_version == server::cellular_batch_admin_format &&
|
||||
cellular_checkpoint_trace_admits(previous->cellular_versions,
|
||||
committed_batch.format_version)))
|
||||
committed_batch.format_version =
|
||||
cellular_checkpoint_trace_format(previous->cellular_versions);
|
||||
const auto trace = server::encode_cellular_batch(committed_batch);
|
||||
@@ -834,7 +836,7 @@ recover_cellular_loaded(Postgres& db, const FilesystemObjectStore& objects, Regi
|
||||
auto trace = server::decode_cellular_batch(*trace_bytes);
|
||||
if (!trace)
|
||||
return fail_with(RecoveryError::tail);
|
||||
if (trace->format_version != cellular_checkpoint_trace_format(manifest->cellular_versions))
|
||||
if (!cellular_checkpoint_trace_admits(manifest->cellular_versions, trace->format_version))
|
||||
return fail_with(RecoveryError::tail);
|
||||
if (trace->header.world != key.world || trace->header.region != key.region ||
|
||||
trace->header.frame != manifest->frame ||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "evo/server/admin/admin_api.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <netdb.h>
|
||||
@@ -263,10 +264,10 @@ OpsResponse AdminApi::handle(const ApiRequest& request, std::uint64_t now_second
|
||||
auto path = request.path.substr(0, mark);
|
||||
const auto query =
|
||||
mark == std::string_view::npos ? std::string_view{} : request.path.substr(mark + 1);
|
||||
// Only the session window accepts POST; everything else is read-only.
|
||||
// Only session windows and commands accept POST; everything else is read-only.
|
||||
if (request.method != "GET" &&
|
||||
!(request.method == "POST" && path.starts_with("/api/regions/") &&
|
||||
path.ends_with("/session-window")))
|
||||
(path.ends_with("/session-window") || path.ends_with("/commands"))))
|
||||
return {405, "method not allowed\n"};
|
||||
if (path == "/healthz")
|
||||
return {200, "ok\n"};
|
||||
@@ -330,6 +331,15 @@ OpsResponse AdminApi::api(std::string_view method, std::string_view path, std::s
|
||||
return error(404, "not_found");
|
||||
return method == "POST" ? set_window(*region, query, admin) : window(*region);
|
||||
}
|
||||
constexpr std::string_view commands_suffix = "/commands";
|
||||
if (path.starts_with(region_prefix) && path.ends_with(commands_suffix) &&
|
||||
path.size() > region_prefix.size() + commands_suffix.size()) {
|
||||
const auto region = number(path.substr(
|
||||
region_prefix.size(), path.size() - region_prefix.size() - commands_suffix.size()));
|
||||
if (!region)
|
||||
return error(404, "not_found");
|
||||
return method == "POST" ? enqueue(*region, query, admin) : commands(*region);
|
||||
}
|
||||
return error(404, "not_found");
|
||||
}
|
||||
|
||||
@@ -464,6 +474,92 @@ OpsResponse AdminApi::set_window(std::uint64_t region, std::string_view query_te
|
||||
",\"expires_at\":" + seconds_value(at(rows->front(), 1)) + "}\n");
|
||||
}
|
||||
|
||||
namespace {
|
||||
constexpr std::array<std::string_view, 7> command_kinds{
|
||||
"", "remove_cell", "grant_reserve", "add_bubbles",
|
||||
"add_pool", "release_pool", "spawn_wildlife"};
|
||||
} // namespace
|
||||
|
||||
OpsResponse AdminApi::commands(std::uint64_t region) {
|
||||
const auto rows =
|
||||
query("SELECT command_id, kind, cell_count, target, energy, carbon, nitrogen, phosphorus, "
|
||||
"other, author_subject, reason, floor(extract(epoch FROM created_at))::bigint, "
|
||||
"applied_tick FROM evolution.admin_commands_v1($1, $2)",
|
||||
{std::to_string(config_.world), std::to_string(region)});
|
||||
if (!rows)
|
||||
return error(503, "unavailable");
|
||||
std::string out = "{\"region\":\"" + std::to_string(region) + "\",\"commands\":[";
|
||||
for (std::size_t i = 0; i < rows->size(); ++i) {
|
||||
const auto& row = (*rows)[i];
|
||||
const auto kind = number(at(row, 1).value_or("0")).value_or(0);
|
||||
out +=
|
||||
std::string(i == 0 ? "" : ",") + "{\"id\":" + text_value(at(row, 0)) + ",\"kind\":\"" +
|
||||
std::string(kind < command_kinds.size() ? command_kinds[kind] : "") +
|
||||
"\",\"count\":" + count_value(at(row, 2)) + ",\"target\":" + text_value(at(row, 3)) +
|
||||
",\"amount\":[" + text_value(at(row, 4)) + "," + text_value(at(row, 5)) + "," +
|
||||
text_value(at(row, 6)) + "," + text_value(at(row, 7)) + "," + text_value(at(row, 8)) +
|
||||
"],\"author\":" + text_value(at(row, 9)) + ",\"reason\":" + text_value(at(row, 10)) +
|
||||
",\"created_at\":" + seconds_value(at(row, 11)) +
|
||||
",\"applied_tick\":" + text_value(at(row, 12)) + "}";
|
||||
}
|
||||
return json(200, out + "]}\n");
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::enqueue(std::uint64_t region, std::string_view query_text,
|
||||
const broker::AccessTokenClaims& admin) {
|
||||
const auto kind_text = query_value(query_text, "kind", 20);
|
||||
const auto kind =
|
||||
kind_text ? std::ranges::find(command_kinds, *kind_text) : command_kinds.end();
|
||||
if (!kind_text || kind_text->empty() || kind == command_kinds.end())
|
||||
return error(400, "bad_kind");
|
||||
// Absent numbers are zero; present ones must be plain u64 decimals.
|
||||
const auto value = [&](std::string_view name) -> std::optional<std::uint64_t> {
|
||||
const auto text = query_value(query_text, name, 20);
|
||||
if (!text)
|
||||
return query_text.find(std::string(name) + "=") == std::string_view::npos
|
||||
? std::optional<std::uint64_t>{0}
|
||||
: std::nullopt;
|
||||
return number(*text);
|
||||
};
|
||||
std::array<std::optional<std::uint64_t>, 7> v{
|
||||
value("count"), value("target"), value("energy"), value("carbon"),
|
||||
value("nitrogen"), value("phosphorus"), value("other")};
|
||||
if (std::ranges::any_of(v, [](const auto& x) { return !x; }))
|
||||
return error(400, "bad_number");
|
||||
const auto reason = query_value(query_text, "reason");
|
||||
if (!reason && query_text.find("reason=") != std::string_view::npos)
|
||||
return error(400, "bad_reason");
|
||||
auto author = admin.email.empty() ? admin.subject : admin.email + " (" + admin.subject + ")";
|
||||
if (author.size() > 255)
|
||||
author = admin.subject;
|
||||
std::vector<std::string> parameters{std::to_string(config_.world), std::to_string(region),
|
||||
std::to_string(kind - command_kinds.begin())};
|
||||
for (const auto& x : v)
|
||||
parameters.push_back(std::to_string(x.value_or(0))); // All present: checked above.
|
||||
parameters.push_back(author);
|
||||
parameters.push_back(reason.value_or(""));
|
||||
if (!db_ && connect_)
|
||||
db_ = connect_();
|
||||
if (!db_)
|
||||
return error(503, "unavailable");
|
||||
const auto rows =
|
||||
db_->query("SELECT command_id, target FROM evolution.admin_enqueue_command_v1("
|
||||
"$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
|
||||
parameters, config_.db_timeout);
|
||||
if (!rows) {
|
||||
// An invalid command is refused by the database (SQLSTATE 22023); keep the connection.
|
||||
const bool invalid = rows.error().kind == persistence::PgError::sql &&
|
||||
std::string_view{rows.error().sqlstate.data(), 5} == "22023";
|
||||
if (!invalid)
|
||||
db_.reset();
|
||||
return error(invalid ? 400 : 503, invalid ? "invalid_command" : "unavailable");
|
||||
}
|
||||
if (rows->empty())
|
||||
return error(503, "unavailable");
|
||||
return json(200, "{\"id\":" + text_value(at(rows->front(), 0)) +
|
||||
",\"target\":" + text_value(at(rows->front(), 1)) + "}\n");
|
||||
}
|
||||
|
||||
OpsResponse AdminApi::view(std::uint64_t region, std::chrono::steady_clock::time_point now) {
|
||||
if (!std::ranges::contains(config_.view_regions, region))
|
||||
return error(404, "not_viewable");
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <thread>
|
||||
@@ -448,6 +449,9 @@ void CellularRegionHost::resolve() {
|
||||
finalized_actions_.push_back({action, committed_->head.sequence});
|
||||
finalize_births(pending_->births);
|
||||
finalize_mutations(pending_->mutation_actions, pending_->prepared.results);
|
||||
// The store knows which admin commands this commit bound: read the queue again.
|
||||
queued_admin_.clear();
|
||||
next_admin_reload_ = {};
|
||||
pending_.reset();
|
||||
++status_.commits;
|
||||
status_.committed_sequence = committed_->head.sequence;
|
||||
@@ -738,6 +742,8 @@ const HostStatus& CellularRegionHost::step() {
|
||||
reconcile_interval();
|
||||
if (!pending_ && state_ && mutations_uncertain_ && status_.phase == HostPhase::running)
|
||||
reload_mutations();
|
||||
if (!pending_ && state_ && status_.phase == HostPhase::running)
|
||||
reload_admin_commands();
|
||||
if (!pending_ && state_ && status_.phase == HostPhase::running)
|
||||
flush_endings();
|
||||
refresh();
|
||||
@@ -928,6 +934,64 @@ CellularRegionHost::select_mutation(const persistence::Uuid& account, std::uint6
|
||||
return {admitted, tick, {}};
|
||||
}
|
||||
|
||||
std::vector<CellularAdminCommand> CellularRegionHost::unbound_admin_commands() const {
|
||||
std::vector<CellularAdminCommand> unbound;
|
||||
for (const auto& queued : queued_admin_) {
|
||||
if (unbound.size() >= max_cellular_tick_admin_commands)
|
||||
break;
|
||||
const bool flying =
|
||||
in_flight_ && std::ranges::any_of(in_flight_->batch.ticks, [&](const auto& tick) {
|
||||
return std::ranges::find(tick.admin, queued.id, &CellularAdminCommand::id) !=
|
||||
tick.admin.end();
|
||||
});
|
||||
if (!flying)
|
||||
unbound.push_back(queued);
|
||||
}
|
||||
return unbound;
|
||||
}
|
||||
|
||||
// ADR-0182: the region's unpublished admin commands, every 2 s (rules 13 only).
|
||||
void CellularRegionHost::reload_admin_commands() {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now < next_admin_reload_ || !committed_ ||
|
||||
state_->rules_version() < cellular_lives_revamp_rules || !database())
|
||||
return;
|
||||
next_admin_reload_ = now + std::chrono::seconds{2};
|
||||
const std::array<std::string, 2> parameters{std::to_string(config_.key.world),
|
||||
std::to_string(config_.key.region)};
|
||||
const auto rows = db_->query(
|
||||
"SELECT command_id, kind, cell_count, target, energy, carbon, nitrogen, phosphorus, other "
|
||||
"FROM evolution.load_pending_admin_commands_v1($1::evolution.u64, $2::evolution.u64)",
|
||||
parameters, config_.lease.commit_timeout);
|
||||
if (!rows) {
|
||||
db_.reset();
|
||||
++status_.store_failures;
|
||||
return;
|
||||
}
|
||||
std::vector<CellularAdminCommand> loaded;
|
||||
for (const auto& row : *rows) {
|
||||
std::array<std::uint64_t, 9> v{};
|
||||
bool ok = row.size() == v.size();
|
||||
for (std::size_t i = 0; ok && i < v.size(); ++i) {
|
||||
const auto& text = row[i];
|
||||
ok = text.has_value() &&
|
||||
std::from_chars(text->data(), text->data() + text->size(), v[i]).ec == std::errc{};
|
||||
}
|
||||
if (!ok || v[1] > 0xFF || v[2] > 0xFFFF)
|
||||
continue;
|
||||
CellularAdminCommand command{v[0],
|
||||
static_cast<CellularAdminKind>(v[1]),
|
||||
static_cast<std::uint16_t>(v[2]),
|
||||
v[3],
|
||||
{{v[4]}, {}}};
|
||||
for (std::size_t c = 0; c < command.amount.matter.size(); ++c)
|
||||
command.amount.matter[c].value = v[5 + c];
|
||||
if (cellular_admin_command_valid(command))
|
||||
loaded.push_back(command);
|
||||
}
|
||||
queued_admin_ = std::move(loaded);
|
||||
}
|
||||
|
||||
std::vector<persistence::CellularMutationReservation>
|
||||
CellularRegionHost::unbound_mutations() const {
|
||||
std::vector<persistence::CellularMutationReservation> unbound;
|
||||
@@ -1091,6 +1155,10 @@ CellularRegionHost::finish_publication(
|
||||
for (const auto result : published->mutation_results)
|
||||
results.push_back(static_cast<std::uint8_t>(result));
|
||||
finalize_mutations(mutation_actions, results);
|
||||
for (const auto& tick : batch.ticks)
|
||||
for (const auto& command : tick.admin)
|
||||
std::erase_if(queued_admin_,
|
||||
[&](const auto& queued) { return queued.id == command.id; });
|
||||
++status_.commits;
|
||||
status_.committed_sequence = committed_->head.sequence;
|
||||
status_.committed_tick = committed_->head.end_tick;
|
||||
|
||||
@@ -34,20 +34,29 @@ bool valid_header(const CellularBatchHeader& h, std::size_t ticks) {
|
||||
}
|
||||
bool known_format(std::uint32_t format) {
|
||||
return format == cellular_batch_legacy_format || format == cellular_batch_v2_format ||
|
||||
format == cellular_batch_format || format == cellular_batch_inheritance_format;
|
||||
format == cellular_batch_format || format == cellular_batch_inheritance_format ||
|
||||
format == cellular_batch_admin_format;
|
||||
}
|
||||
bool owner_version_matches(const CellularLives& owner, const CellularBatch& batch) {
|
||||
if (!known_format(batch.format_version))
|
||||
return false;
|
||||
if (batch.format_version == cellular_batch_admin_format)
|
||||
return owner.format_version() == cellular_lives_revamp_format &&
|
||||
owner.rules_version() >= cellular_lives_revamp_rules;
|
||||
if (batch.format_version == cellular_batch_inheritance_format)
|
||||
return owner.format_version() >= cellular_lives_inheritance_format &&
|
||||
cellular_retained_plans(owner.rules_version());
|
||||
return owner.format_version() < cellular_lives_inheritance_format;
|
||||
}
|
||||
bool payload_version_matches(const CellularBatch& batch) {
|
||||
// ADR-0182: trace 5 only with a command; a batch without one is trace 4.
|
||||
if (batch.format_version == cellular_batch_admin_format &&
|
||||
std::ranges::none_of(batch.ticks, [](const auto& tick) { return !tick.admin.empty(); }))
|
||||
return false;
|
||||
return std::ranges::all_of(batch.ticks, [&](const auto& tick) {
|
||||
return (batch.format_version >= cellular_batch_v2_format || tick.births.empty()) &&
|
||||
(batch.format_version >= cellular_batch_format || tick.mutations.empty());
|
||||
(batch.format_version >= cellular_batch_format || tick.mutations.empty()) &&
|
||||
(batch.format_version == cellular_batch_admin_format || tick.admin.empty());
|
||||
});
|
||||
}
|
||||
bool valid_intent(const CellularLifeIntent& life) {
|
||||
@@ -84,6 +93,12 @@ bool valid_ticks(std::span<const CellularTickIntents> ticks) {
|
||||
if (!identities.insert(birth.identity).second || !accounts.insert(birth.account).second)
|
||||
return false;
|
||||
}
|
||||
if (tick.admin.size() > max_cellular_tick_admin_commands)
|
||||
return false;
|
||||
for (std::size_t i = 0; i < tick.admin.size(); ++i)
|
||||
if (!cellular_admin_command_valid(tick.admin[i]) ||
|
||||
(i > 0 && tick.admin[i - 1].id >= tick.admin[i].id))
|
||||
return false;
|
||||
for (std::size_t i = 0; i < tick.mutations.size(); ++i) {
|
||||
const auto& mutation = tick.mutations[i];
|
||||
if (mutation.life_id == 0 || mutation.event_index == 0 || mutation.offer_tick == 0 ||
|
||||
@@ -198,7 +213,8 @@ encode_cellular_batch(const CellularBatch& batch) {
|
||||
: 0) +
|
||||
(batch.format_version >= cellular_batch_format
|
||||
? tick.mutations.size() * cellular_batch_mutation_bytes
|
||||
: 0);
|
||||
: 0) +
|
||||
tick.admin.size() * cellular_batch_admin_bytes;
|
||||
if (records > max_cellular_batch_bytes - size - tick_header_bytes)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
size += tick_header_bytes + records;
|
||||
@@ -224,7 +240,7 @@ encode_cellular_batch(const CellularBatch& batch) {
|
||||
put(out, tick.births.size(), 4);
|
||||
if (batch.format_version >= cellular_batch_format) {
|
||||
put(out, tick.mutations.size(), 4);
|
||||
put(out, 0, 4);
|
||||
put(out, tick.admin.size(), 4); // Zero before format 5.
|
||||
}
|
||||
for (const auto& life : tick.lives)
|
||||
put_intent(out, life);
|
||||
@@ -247,6 +263,16 @@ encode_cellular_batch(const CellularBatch& batch) {
|
||||
put(out, mutation.become ? 1 : 0, 1); // Byte 34 (rules 13).
|
||||
put(out, 0, 5);
|
||||
}
|
||||
for (const auto& command : tick.admin) {
|
||||
put(out, command.id, 8);
|
||||
put(out, static_cast<std::uint16_t>(command.kind), 2);
|
||||
put(out, command.count, 2);
|
||||
put(out, 0, 4);
|
||||
put(out, command.target, 8);
|
||||
put(out, command.amount.energy.value, 8);
|
||||
for (const auto& channel : command.amount.matter)
|
||||
put(out, channel.value, 8);
|
||||
}
|
||||
}
|
||||
if (out.size() != size)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
@@ -259,8 +285,8 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
||||
!std::ranges::equal(bytes.first(magic.size()), magic))
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
const auto format = get(bytes, 8, 4);
|
||||
if (format > cellular_batch_inheritance_format ||
|
||||
!known_format(static_cast<std::uint32_t>(format)) || get(bytes, 12, 4) != 4)
|
||||
if (format > cellular_batch_admin_format || !known_format(static_cast<std::uint32_t>(format)) ||
|
||||
get(bytes, 12, 4) != 4)
|
||||
return std::unexpected{CellularBatchError::version};
|
||||
if (get(bytes, 108, 4) != 0)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
@@ -298,13 +324,16 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
||||
birth_count = get(bytes, offset, 4);
|
||||
offset += 4;
|
||||
}
|
||||
std::uint64_t mutation_count{};
|
||||
std::uint64_t mutation_count{}, admin_count{};
|
||||
if (format >= cellular_batch_format) {
|
||||
mutation_count = get(bytes, offset, 4);
|
||||
if (get(bytes, offset + 4, 4) != 0)
|
||||
admin_count = get(bytes, offset + 4, 4);
|
||||
if (format != cellular_batch_admin_format && admin_count != 0)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
offset += 8;
|
||||
}
|
||||
if (admin_count > max_cellular_tick_admin_commands)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
if (count > biology::max_cellular_tick_lives ||
|
||||
count > (bytes.size() - offset) / cellular_batch_intent_bytes ||
|
||||
birth_count > biology::max_cellular_tick_lives ||
|
||||
@@ -381,9 +410,29 @@ decode_cellular_batch(std::span<const std::uint8_t> bytes) {
|
||||
step.mutations.push_back(mutation);
|
||||
offset += cellular_batch_mutation_bytes;
|
||||
}
|
||||
if (admin_count > (bytes.size() - offset) / cellular_batch_admin_bytes)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
for (std::uint64_t i = 0; i < admin_count; ++i) {
|
||||
const auto record = bytes.subspan(offset, cellular_batch_admin_bytes);
|
||||
CellularAdminCommand command;
|
||||
command.id = get(record, 0, 8);
|
||||
const auto kind = get(record, 8, 2);
|
||||
if (kind > 0xFF)
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
command.kind = static_cast<CellularAdminKind>(kind);
|
||||
command.count = static_cast<std::uint16_t>(get(record, 10, 2));
|
||||
command.target = get(record, 16, 8);
|
||||
command.amount.energy.value = get(record, 24, 8);
|
||||
for (std::size_t c = 0; c < command.amount.matter.size(); ++c)
|
||||
command.amount.matter[c].value = get(record, 32 + 8 * c, 8);
|
||||
if (!all_zero(record.subspan(12, 4)))
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
step.admin.push_back(command);
|
||||
offset += cellular_batch_admin_bytes;
|
||||
}
|
||||
out.ticks.push_back(std::move(step));
|
||||
}
|
||||
if (offset != bytes.size() || !valid_ticks(out.ticks))
|
||||
if (offset != bytes.size() || !valid_ticks(out.ticks) || !payload_version_matches(out))
|
||||
return std::unexpected{CellularBatchError::format};
|
||||
return out;
|
||||
}
|
||||
@@ -433,7 +482,16 @@ decode_cellular_mutation_input(const std::array<std::uint8_t, 16>& account, std:
|
||||
std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||
std::vector<CellularMutationOutcome>& mutation_outcomes) {
|
||||
std::vector<CellularAdminResult> ignored;
|
||||
return replay_cellular_batch(base, batch, mutation_outcomes, ignored);
|
||||
}
|
||||
|
||||
std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
|
||||
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||
std::vector<CellularMutationOutcome>& mutation_outcomes,
|
||||
std::vector<CellularAdminResult>& admin_results) {
|
||||
mutation_outcomes.clear();
|
||||
admin_results.clear();
|
||||
if (!owner_version_matches(base, batch))
|
||||
return std::unexpected{CellularBatchError::version};
|
||||
const auto& h = batch.header;
|
||||
@@ -448,6 +506,7 @@ replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||
if (!replay)
|
||||
return std::unexpected{CellularBatchError::state};
|
||||
std::vector<CellularMutationOutcome> complete_outcomes;
|
||||
std::vector<CellularAdminResult> complete_admin;
|
||||
for (const auto& tick : batch.ticks) {
|
||||
const auto executed = (*replay)->advance_tick_with_mutations(tick.lives, tick.mutations);
|
||||
if (!executed)
|
||||
@@ -467,8 +526,17 @@ replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
|
||||
return std::unexpected{CellularBatchError::state};
|
||||
*replay = std::move(*born);
|
||||
}
|
||||
if (!tick.admin.empty()) {
|
||||
std::vector<CellularAdminResult> results;
|
||||
auto applied = (*replay)->admin_candidate(tick.admin, &results);
|
||||
if (!applied)
|
||||
return std::unexpected{CellularBatchError::state};
|
||||
*replay = std::move(*applied);
|
||||
complete_admin.insert(complete_admin.end(), results.begin(), results.end());
|
||||
}
|
||||
}
|
||||
mutation_outcomes = std::move(complete_outcomes);
|
||||
admin_results = std::move(complete_admin);
|
||||
return std::move(*replay);
|
||||
}
|
||||
|
||||
|
||||
@@ -1344,103 +1344,268 @@ CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules, std::u
|
||||
next.archive.archived() != 0 || count >= rules.organism_cap || count > 255 || first == 0 ||
|
||||
first > cellular_bud_namespace - count)
|
||||
return std::unexpected{CellularLivesError::invalid_config};
|
||||
for (std::uint32_t index = 0; index < count; ++index) {
|
||||
const auto id = first + index;
|
||||
const auto founder = biology::primitive_founder(id, id, biology::primitive_founder_v6);
|
||||
if (!founder)
|
||||
return std::unexpected{CellularLivesError::biology};
|
||||
biology::GenomeDraft draft{
|
||||
.id = id,
|
||||
.origin_event = id,
|
||||
.development_version = 7,
|
||||
.parents = {},
|
||||
.capabilities = {founder->capabilities().begin(), founder->capabilities().end()},
|
||||
.schema_version = biology::genome_schema_v7,
|
||||
.movement_arrangement = biology::founder_movement_arrangement,
|
||||
.cellular_traits = biology::founder_cellular_traits};
|
||||
Random random{mutation_seed(world(), region(), id, 0x57494C44U)};
|
||||
const auto points = [&] { return static_cast<std::uint16_t>(75 + random.next() % 51); };
|
||||
auto& traits = *draft.cellular_traits;
|
||||
traits.density = points();
|
||||
traits.upkeep_efficiency = points();
|
||||
traits.growth_speed = points();
|
||||
for (auto& channel : traits.collection)
|
||||
channel = points();
|
||||
for (auto& channel : traits.burn)
|
||||
channel = points();
|
||||
traits.engulf_capacity = points();
|
||||
traits.kill_absorption = points();
|
||||
auto& movement = *draft.movement_arrangement;
|
||||
movement.output = points();
|
||||
movement.efficiency = points();
|
||||
movement.steering = points();
|
||||
movement.streamlining = points();
|
||||
movement.braking = points();
|
||||
movement.coasting = points();
|
||||
const auto genome = biology::Genome::create(draft);
|
||||
const auto budget =
|
||||
genome ? biology::metabolic_budget(*genome, {1000, 0},
|
||||
{next.config.ambient_temperature_millikelvin, {}},
|
||||
1000, rules.body)
|
||||
: std::unexpected{biology::DevelopmentError::overflow};
|
||||
if (!budget)
|
||||
return std::unexpected{CellularLivesError::biology};
|
||||
// A normal founder's starting provision, evaluated for its randomized genome.
|
||||
const accounting::Inventory reserve{
|
||||
{budget->demand.value * biology::founder_reserve_seconds}, {}};
|
||||
auto empty_body = accounting::Inventory{};
|
||||
auto nursery = next.nursery;
|
||||
auto heat = next.heat;
|
||||
const auto development = biology::rules_for(genome->development_version());
|
||||
if (!development || !subtract_inventory(nursery, reserve) ||
|
||||
!rebody(empty_body, nursery, heat, budget->body,
|
||||
development->construction_per_kilogram))
|
||||
return std::unexpected{CellularLivesError::insufficient_funding};
|
||||
const auto extent = budget->phenotype.extent;
|
||||
if (next.config.area.width_um <= extent + 2000 ||
|
||||
next.config.area.height_um <= extent + 2000)
|
||||
return std::unexpected{CellularLivesError::no_placement};
|
||||
std::optional<biology::CellularPosition> position;
|
||||
for (int attempt = 0; attempt < 1024 && !position; ++attempt) {
|
||||
const biology::CellularPosition spot{
|
||||
1000 + random.next() % (next.config.area.width_um - extent - 2000),
|
||||
1000 + random.next() % (next.config.area.height_um - extent - 2000)};
|
||||
bool occupied = false;
|
||||
for (const auto& other : next.lives) {
|
||||
const auto body = budget_for(
|
||||
next.archive, other, next.config.ambient_temperature_millikelvin, rules.body);
|
||||
if (!body)
|
||||
return std::unexpected{CellularLivesError::biology};
|
||||
const auto side = body->phenotype.extent;
|
||||
occupied = occupied || (spot.x_um < other.position.x_um + side &&
|
||||
other.position.x_um < spot.x_um + extent &&
|
||||
spot.y_um < other.position.y_um + side &&
|
||||
other.position.y_um < spot.y_um + extent);
|
||||
}
|
||||
if (!occupied)
|
||||
position = spot;
|
||||
}
|
||||
if (!position)
|
||||
return std::unexpected{CellularLivesError::no_placement};
|
||||
if (!next.archive.admit(*genome) || !next.archive.record_birth(id, id, {tick()}))
|
||||
return std::unexpected{CellularLivesError::archive};
|
||||
CellularOwnedLife life{};
|
||||
life.identity = {id, id, id, id, {tick()}};
|
||||
life.source = next.nursery_config.source;
|
||||
life.growth = {1000, 0};
|
||||
life.position = *position;
|
||||
life.body = budget->body;
|
||||
life.reserve = reserve;
|
||||
life.offspring_genome = id;
|
||||
next.lives.push_back(life);
|
||||
next.nursery = nursery;
|
||||
next.nursery_config.funding = nursery;
|
||||
next.heat = heat;
|
||||
}
|
||||
for (std::uint32_t index = 0; index < count; ++index)
|
||||
if (const auto error =
|
||||
seed_wildlife_root(next, world(), region(), tick(), first + index, nullptr))
|
||||
return std::unexpected{*error};
|
||||
// Restore validates bodies, identities, history and channel-by-channel closure.
|
||||
return restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
||||
}
|
||||
|
||||
std::optional<CellularLivesError>
|
||||
CellularLives::seed_wildlife_root(State& next, std::uint64_t world, std::uint64_t region,
|
||||
std::uint64_t tick, std::uint64_t id,
|
||||
accounting::Inventory* imported) {
|
||||
const auto& rules = next.revamp;
|
||||
const auto founder = biology::primitive_founder(id, id, biology::primitive_founder_v6);
|
||||
if (!founder)
|
||||
return CellularLivesError::biology;
|
||||
biology::GenomeDraft draft{
|
||||
.id = id,
|
||||
.origin_event = id,
|
||||
.development_version = 7,
|
||||
.parents = {},
|
||||
.capabilities = {founder->capabilities().begin(), founder->capabilities().end()},
|
||||
.schema_version = biology::genome_schema_v7,
|
||||
.movement_arrangement = biology::founder_movement_arrangement,
|
||||
.cellular_traits = biology::founder_cellular_traits};
|
||||
Random random{mutation_seed(world, region, id, 0x57494C44U)};
|
||||
const auto points = [&] { return static_cast<std::uint16_t>(75 + random.next() % 51); };
|
||||
auto& traits = *draft.cellular_traits;
|
||||
traits.density = points();
|
||||
traits.upkeep_efficiency = points();
|
||||
traits.growth_speed = points();
|
||||
for (auto& channel : traits.collection)
|
||||
channel = points();
|
||||
for (auto& channel : traits.burn)
|
||||
channel = points();
|
||||
traits.engulf_capacity = points();
|
||||
traits.kill_absorption = points();
|
||||
auto& movement = *draft.movement_arrangement;
|
||||
movement.output = points();
|
||||
movement.efficiency = points();
|
||||
movement.steering = points();
|
||||
movement.streamlining = points();
|
||||
movement.braking = points();
|
||||
movement.coasting = points();
|
||||
const auto genome = biology::Genome::create(draft);
|
||||
const auto budget =
|
||||
genome ? biology::metabolic_budget(*genome, {1000, 0},
|
||||
{next.config.ambient_temperature_millikelvin, {}}, 1000,
|
||||
rules.body)
|
||||
: std::unexpected{biology::DevelopmentError::overflow};
|
||||
if (!budget)
|
||||
return CellularLivesError::biology;
|
||||
// A normal founder's starting provision, evaluated for its randomized genome.
|
||||
const accounting::Inventory reserve{{budget->demand.value * biology::founder_reserve_seconds},
|
||||
{}};
|
||||
auto empty_body = accounting::Inventory{};
|
||||
const auto development = biology::rules_for(genome->development_version());
|
||||
if (!development)
|
||||
return CellularLivesError::insufficient_funding;
|
||||
// ADR-0182: an import pays exactly the reserve, the body's matter and its construction.
|
||||
auto funding = next.nursery;
|
||||
if (imported) {
|
||||
std::uint64_t added{};
|
||||
funding = reserve;
|
||||
for (std::size_t c = 0; c < funding.matter.size(); ++c) {
|
||||
funding.matter[c] = budget->body.matter[c];
|
||||
added += budget->body.matter[c].value;
|
||||
}
|
||||
const auto price = development->construction_per_kilogram;
|
||||
funding.energy.value += added / 1'000 * price + added % 1'000 * price / 1'000;
|
||||
}
|
||||
const auto paid = funding;
|
||||
auto heat = next.heat;
|
||||
if (!subtract_inventory(funding, reserve) ||
|
||||
!rebody(empty_body, funding, heat, budget->body, development->construction_per_kilogram))
|
||||
return CellularLivesError::insufficient_funding;
|
||||
const auto extent = budget->phenotype.extent;
|
||||
if (next.config.area.width_um <= extent + 2000 || next.config.area.height_um <= extent + 2000)
|
||||
return CellularLivesError::no_placement;
|
||||
std::optional<biology::CellularPosition> position;
|
||||
for (int attempt = 0; attempt < 1024 && !position; ++attempt) {
|
||||
const biology::CellularPosition spot{
|
||||
1000 + random.next() % (next.config.area.width_um - extent - 2000),
|
||||
1000 + random.next() % (next.config.area.height_um - extent - 2000)};
|
||||
bool occupied = false;
|
||||
for (const auto& other : next.lives) {
|
||||
const auto body = budget_for(next.archive, other,
|
||||
next.config.ambient_temperature_millikelvin, rules.body);
|
||||
if (!body)
|
||||
return CellularLivesError::biology;
|
||||
const auto side = body->phenotype.extent;
|
||||
occupied = occupied || (spot.x_um < other.position.x_um + side &&
|
||||
other.position.x_um < spot.x_um + extent &&
|
||||
spot.y_um < other.position.y_um + side &&
|
||||
other.position.y_um < spot.y_um + extent);
|
||||
}
|
||||
if (!occupied)
|
||||
position = spot;
|
||||
}
|
||||
if (!position)
|
||||
return CellularLivesError::no_placement;
|
||||
if (!next.archive.admit(*genome) || !next.archive.record_birth(id, id, {tick}))
|
||||
return CellularLivesError::archive;
|
||||
CellularOwnedLife life{};
|
||||
life.identity = {id, id, id, id, {tick}};
|
||||
life.source = next.nursery_config.source;
|
||||
life.growth = {1000, 0};
|
||||
life.position = *position;
|
||||
life.body = budget->body;
|
||||
life.reserve = reserve;
|
||||
life.offspring_genome = id;
|
||||
const auto at = std::ranges::lower_bound(next.lives, id, {},
|
||||
[](const auto& value) { return value.identity.life; });
|
||||
next.lives.insert(at, life);
|
||||
if (imported) {
|
||||
if (funding != accounting::Inventory{} || !add_inventory(*imported, paid))
|
||||
return CellularLivesError::conservation;
|
||||
} else {
|
||||
next.nursery = funding;
|
||||
next.nursery_config.funding = funding;
|
||||
}
|
||||
next.heat = heat;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool cellular_admin_command_valid(const CellularAdminCommand& c) noexcept {
|
||||
const bool some = c.amount != accounting::Inventory{};
|
||||
switch (c.kind) {
|
||||
case CellularAdminKind::remove_cell:
|
||||
return c.id != 0 && c.target != 0 && c.count == 0 && !some;
|
||||
case CellularAdminKind::grant_reserve:
|
||||
return c.id != 0 && c.target != 0 && c.count == 0 && some;
|
||||
case CellularAdminKind::add_bubbles:
|
||||
case CellularAdminKind::release_pool:
|
||||
return c.id != 0 && c.target == 0 && c.count >= 1 && c.count <= 256 && some;
|
||||
case CellularAdminKind::add_pool:
|
||||
return c.id != 0 && c.target == 0 && c.count == 0 && some;
|
||||
case CellularAdminKind::spawn_wildlife:
|
||||
return c.id != 0 && c.count >= 1 && c.count <= 64 && !some && c.target != 0 &&
|
||||
c.target <= cellular_bud_namespace - c.count;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
||||
CellularLives::admin_candidate(std::span<const CellularAdminCommand> commands,
|
||||
std::vector<CellularAdminResult>* results) const {
|
||||
if (state_->format_version != cellular_lives_revamp_format ||
|
||||
state_->rules_version < cellular_lives_revamp_rules)
|
||||
return std::unexpected{CellularLivesError::version};
|
||||
for (std::size_t i = 0; i < commands.size(); ++i)
|
||||
if (!cellular_admin_command_valid(commands[i]) ||
|
||||
(i != 0 && commands[i - 1].id >= commands[i].id))
|
||||
return std::unexpected{CellularLivesError::invalid_config};
|
||||
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
||||
if (!candidate)
|
||||
return std::unexpected(candidate.error());
|
||||
std::vector<CellularAdminResult> report;
|
||||
for (const auto& command : commands) {
|
||||
// Each command works on a copy, kept only when it applies and still closes.
|
||||
auto attempt = restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
||||
if (!attempt)
|
||||
return std::unexpected(attempt.error());
|
||||
auto& next = *(*attempt)->state_;
|
||||
bool applied = false;
|
||||
const auto life = std::ranges::lower_bound(next.lives, command.target, {},
|
||||
[](const auto& v) { return v.identity.life; });
|
||||
const bool found = life != next.lives.end() && life->identity.life == command.target;
|
||||
switch (command.kind) {
|
||||
case CellularAdminKind::remove_cell:
|
||||
if (found && next.archive.record_death(life->identity.organism, {tick()})) {
|
||||
auto single = *life;
|
||||
single.revamp.members = 1; // A corpse records the single-cell extent.
|
||||
const auto extent =
|
||||
budget_for(next.archive, single, next.config.ambient_temperature_millikelvin,
|
||||
next.revamp.body);
|
||||
if (extent && add_inventory(next.spent, life->body) &&
|
||||
add_inventory(next.spent, life->reserve)) {
|
||||
CellularOwnedCorpse corpse{life->identity.life,
|
||||
life->identity.organism,
|
||||
life->source,
|
||||
tick(),
|
||||
life->position,
|
||||
life->growth,
|
||||
extent->phenotype.extent,
|
||||
{},
|
||||
biology::CellularDeathCause::removed,
|
||||
0,
|
||||
life->parent_life,
|
||||
life->offspring_genome};
|
||||
const auto at = std::ranges::lower_bound(next.corpses, corpse.organism, {},
|
||||
&CellularOwnedCorpse::organism);
|
||||
next.corpses.insert(at, corpse);
|
||||
next.lives.erase(life);
|
||||
applied = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CellularAdminKind::grant_reserve:
|
||||
applied = found && add_inventory(life->reserve, command.amount) &&
|
||||
add_inventory(next.boundary.incoming, command.amount);
|
||||
break;
|
||||
case CellularAdminKind::add_pool:
|
||||
applied = add_inventory(next.spent, command.amount) &&
|
||||
add_inventory(next.boundary.incoming, command.amount);
|
||||
break;
|
||||
case CellularAdminKind::add_bubbles:
|
||||
case CellularAdminKind::release_pool: {
|
||||
const bool release = command.kind == CellularAdminKind::release_pool;
|
||||
auto amount = command.amount;
|
||||
if (release) // Never more than the pool holds.
|
||||
for (std::size_t c = 0; c < 5; ++c) {
|
||||
auto& want = c == 0 ? amount.energy.value : amount.matter[c - 1].value;
|
||||
const auto have =
|
||||
c == 0 ? next.spent.energy.value : next.spent.matter[c - 1].value;
|
||||
want = std::min(want, have);
|
||||
}
|
||||
auto config = next.habitat->config();
|
||||
if (amount != accounting::Inventory{} &&
|
||||
(release ? subtract_inventory(next.spent, amount)
|
||||
: add_inventory(next.boundary.incoming, amount)) &&
|
||||
cellular_scatter_bubbles(config, amount, command.count,
|
||||
mutation_seed(world(), region(), command.id, tick()),
|
||||
next.nursery_config.source)) {
|
||||
if (auto habitat = biology::CellularHabitat::create(std::move(config))) {
|
||||
next.habitat = std::move(*habitat);
|
||||
applied = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CellularAdminKind::spawn_wildlife: {
|
||||
if (next.lives.size() + command.count >= next.revamp.organism_cap)
|
||||
break;
|
||||
accounting::Inventory imported{};
|
||||
bool ok = true;
|
||||
for (std::uint16_t i = 0; ok && i < command.count; ++i) {
|
||||
const auto id = command.target + i;
|
||||
ok = !std::ranges::binary_search(next.lives, id, {},
|
||||
[](const auto& v) { return v.identity.life; }) &&
|
||||
!next.archive.find(id) &&
|
||||
!seed_wildlife_root(next, world(), region(), tick(), id, &imported);
|
||||
}
|
||||
applied = ok && add_inventory(next.boundary.incoming, imported);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (applied) {
|
||||
// Restore checks bodies, identities, history and channel-by-channel closure.
|
||||
auto checked = restore((*attempt)->snapshot(), world(), region(), frame(), tick());
|
||||
if (checked)
|
||||
candidate = std::move(checked);
|
||||
else
|
||||
applied = false;
|
||||
}
|
||||
report.push_back({command.id, applied});
|
||||
}
|
||||
if (results)
|
||||
*results = std::move(report);
|
||||
return std::move(*candidate);
|
||||
}
|
||||
|
||||
std::optional<accounting::Inventory> CellularLives::budding_cost(std::uint64_t id) const {
|
||||
const auto life =
|
||||
std::ranges::find(state_->lives, id, [](const auto& value) { return value.identity.life; });
|
||||
@@ -2354,7 +2519,8 @@ CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
|
||||
const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed;
|
||||
const bool revamp_cause =
|
||||
revamp_version && (corpse.cause == biology::CellularDeathCause::merged ||
|
||||
corpse.cause == biology::CellularDeathCause::emerged);
|
||||
corpse.cause == biology::CellularDeathCause::emerged ||
|
||||
corpse.cause == biology::CellularDeathCause::removed);
|
||||
if (padding != 0 ||
|
||||
(corpse.cause != biology::CellularDeathCause::starved && !engulfed &&
|
||||
!revamp_cause) ||
|
||||
|
||||
@@ -48,6 +48,7 @@ summarize_cellular_play(const CellularLives& state) {
|
||||
++summary.engulfed;
|
||||
break;
|
||||
case biology::CellularDeathCause::unrecorded:
|
||||
case biology::CellularDeathCause::removed: // ADR-0182: an operator's, not biology's.
|
||||
++summary.unrecorded;
|
||||
break;
|
||||
case biology::CellularDeathCause::merged:
|
||||
|
||||
@@ -59,8 +59,9 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept {
|
||||
rules.split_share_per_thousand < 1'000 && rules.split_min_growth != 0 &&
|
||||
rules.split_min_growth <= 1'000 && rules.bud_fee_scale_percent <= 100 &&
|
||||
rules.bud_fee.energy.value <= most &&
|
||||
std::ranges::all_of(rules.bud_fee.matter,
|
||||
[](const accounting::Femtograms& f) { return f.value <= most; }) &&
|
||||
std::ranges::all_of(
|
||||
rules.bud_fee.matter,
|
||||
[](const accounting::Femtograms& f) { return f.value <= most; }) &&
|
||||
rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives &&
|
||||
rules.organism_load_per_thousand <= 10'000 && rules.emerge_members >= 2 &&
|
||||
rules.emerge_members <= 10'000 && rules.emerge_mass_fg <= most &&
|
||||
@@ -133,6 +134,44 @@ bool cellular_drip_spent(biology::CellularHabitatConfig& config, accounting::Inv
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cellular_scatter_bubbles(biology::CellularHabitatConfig& config,
|
||||
const accounting::Inventory& amount, std::uint16_t count,
|
||||
std::uint64_t seed, std::uint64_t source) {
|
||||
if (count == 0 || config.patches.size() + count > biology::max_cellular_liquid_deposits ||
|
||||
config.next_deposit > std::numeric_limits<std::uint32_t>::max() - count ||
|
||||
config.width_um == 0 || config.height_um == 0)
|
||||
return false;
|
||||
Random random{seed};
|
||||
const auto by_address = [](const biology::CellularPatch& patch) { return patch.address; };
|
||||
for (std::uint16_t i = 0; i < count; ++i) {
|
||||
biology::CellularPatchAddress address{
|
||||
static_cast<std::uint32_t>(random.next() % config.width_um),
|
||||
static_cast<std::uint32_t>(random.next() % config.height_um)};
|
||||
auto at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||
while (at != config.patches.end() && at->address == address) {
|
||||
address.x_um = address.x_um + 1 < config.width_um ? address.x_um + 1 : 0;
|
||||
at = std::ranges::lower_bound(config.patches, address, {}, by_address);
|
||||
}
|
||||
const bool last = i + 1 == count;
|
||||
const auto share = [&](std::uint64_t total) {
|
||||
return total / count + (last ? total % count : 0);
|
||||
};
|
||||
biology::CellularPatch bubble{address,
|
||||
source,
|
||||
{},
|
||||
config.next_deposit++,
|
||||
biology::cellular_mote_radius_um,
|
||||
biology::CellularDepositKind::mote};
|
||||
bubble.merged = 1;
|
||||
bubble.stock.energy.value = share(amount.energy.value);
|
||||
for (std::size_t c = 0; c < amount.matter.size(); ++c)
|
||||
bubble.stock.matter[c].value = share(amount.matter[c].value);
|
||||
if (bubble.stock != accounting::Inventory{})
|
||||
config.patches.insert(at, bubble);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<CellularRevampOffer> cellular_draw_offer(const biology::Genome& plan,
|
||||
const CellularRevampLife& life,
|
||||
const CellularRevampRules& rules,
|
||||
|
||||
@@ -201,24 +201,33 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||
std::span<const network::CarriedAction> actions,
|
||||
std::span<const CellularTickIntents::Birth> births,
|
||||
std::span<const persistence::CellularMutationReservation> mutations) {
|
||||
return append_impl(tick, baseline, actions, births, mutations, false);
|
||||
std::span<const persistence::CellularMutationReservation> mutations,
|
||||
std::span<const CellularAdminCommand> admin) {
|
||||
return append_impl(tick, baseline, actions, births, mutations, admin, false);
|
||||
}
|
||||
std::expected<void, CellularSessionBatchError>
|
||||
CellularSessionBatchBuilder::append_with_birth_refusals(
|
||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||
std::span<const network::CarriedAction> actions,
|
||||
std::span<const CellularTickIntents::Birth> births,
|
||||
std::span<const persistence::CellularMutationReservation> mutations) {
|
||||
return append_impl(tick, baseline, actions, births, mutations, true);
|
||||
std::span<const persistence::CellularMutationReservation> mutations,
|
||||
std::span<const CellularAdminCommand> admin) {
|
||||
return append_impl(tick, baseline, actions, births, mutations, admin, true);
|
||||
}
|
||||
std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::append_impl(
|
||||
std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
|
||||
std::span<const network::CarriedAction> actions,
|
||||
std::span<const CellularTickIntents::Birth> births,
|
||||
std::span<const persistence::CellularMutationReservation> mutations, bool allow_refusals) {
|
||||
std::span<const persistence::CellularMutationReservation> mutations,
|
||||
std::span<const CellularAdminCommand> admin, bool allow_refusals) {
|
||||
if (batch_.ticks.size() >= max_cellular_batch_ticks)
|
||||
return std::unexpected{CellularSessionBatchError::batch_full};
|
||||
// ADR-0182: a command appears once in a publication.
|
||||
for (const auto& command : admin)
|
||||
for (const auto& previous_tick : batch_.ticks)
|
||||
if (std::ranges::find(previous_tick.admin, command.id, &CellularAdminCommand::id) !=
|
||||
previous_tick.admin.end())
|
||||
return std::unexpected{CellularSessionBatchError::duplicate_action};
|
||||
if (actions_.size() + actions.size() > max_cellular_action_records)
|
||||
return std::unexpected{CellularSessionBatchError::action_limit};
|
||||
if (mutation_actions_.size() + mutations.size() > max_cellular_action_records)
|
||||
@@ -267,7 +276,7 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
||||
// it byte-for-byte unchanged: check the encodings first, then advance in place. A full
|
||||
// copy per tick costs a restore of the whole region (rules-12 regions hold thousands of
|
||||
// deposits).
|
||||
if (prepared->intents.births.empty()) {
|
||||
if (prepared->intents.births.empty() && admin.empty()) {
|
||||
auto next_batch = batch_;
|
||||
next_batch.ticks.push_back(prepared->intents);
|
||||
next_batch.header.end_tick = tick;
|
||||
@@ -325,8 +334,20 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
||||
accepted_births.push_back(birth);
|
||||
}
|
||||
prepared->intents.births = std::move(accepted_births);
|
||||
std::vector<CellularAdminResult> admin_results;
|
||||
if (!admin.empty()) {
|
||||
auto applied = (*next)->admin_candidate(admin, &admin_results);
|
||||
if (!applied) {
|
||||
last_lives_error_ = applied.error();
|
||||
return std::unexpected{CellularSessionBatchError::biology};
|
||||
}
|
||||
*next = std::move(*applied);
|
||||
prepared->intents.admin.assign(admin.begin(), admin.end());
|
||||
}
|
||||
|
||||
auto next_batch = batch_;
|
||||
if (!admin.empty())
|
||||
next_batch.format_version = cellular_batch_admin_format;
|
||||
next_batch.ticks.push_back(std::move(prepared->intents));
|
||||
next_batch.header.end_tick = tick;
|
||||
if (!encode_cellular_batch(next_batch))
|
||||
@@ -345,6 +366,7 @@ std::expected<void, CellularSessionBatchError> CellularSessionBatchBuilder::appe
|
||||
actions_.insert(actions_.end(), prepared->actions.begin(), prepared->actions.end());
|
||||
mutation_actions_ = next_mutation_actions;
|
||||
refused_births_.insert(refused_births_.end(), refused_births.begin(), refused_births.end());
|
||||
admin_results_.insert(admin_results_.end(), admin_results.begin(), admin_results.end());
|
||||
return {};
|
||||
}
|
||||
} // namespace evo::server
|
||||
|
||||
Reference in New Issue
Block a user