diff --git a/app/lan_session.hpp b/app/lan_session.hpp index cfcc08b..e9357e9 100644 --- a/app/lan_session.hpp +++ b/app/lan_session.hpp @@ -3,6 +3,7 @@ #include "settlement/core/world.hpp" #include +#include #include #include #include @@ -31,9 +32,16 @@ struct LanCommandResult { AgentId resident; }; +struct LanSessionOptions { + // Runs on the polling thread after a guest command's snapshot checks and + // before owner admission. May block or throw for diagnostics/tests. + std::function before_command_admission; +}; + class LanSession { public: LanSession(); + explicit LanSession(LanSessionOptions options); ~LanSession(); LanSession(const LanSession&) = delete; LanSession& operator=(const LanSession&) = delete; diff --git a/app/lan_session_win32.cpp b/app/lan_session_win32.cpp index ba5c55e..e711410 100644 --- a/app/lan_session_win32.cpp +++ b/app/lan_session_win32.cpp @@ -196,8 +196,9 @@ struct LanSession::Impl { std::optional runtime_session; std::optional compatibility_rules; std::optional pending_command; + LanSessionOptions options; - Impl() { + explicit Impl(LanSessionOptions settings) : options(std::move(settings)) { WSADATA data{}; winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0; } @@ -280,8 +281,9 @@ struct LanSession::Impl { peer.queue(Message::Receipt, std::string_view(bytes)); } - void handle_runtime_host(SimulationRuntime& runtime, const PublishedSnapshot& snapshot, + void handle_runtime_host(SimulationRuntime& runtime, const std::shared_ptr& checked, Message message, std::string_view payload) { + const auto& snapshot = *checked; if (!authenticated) { authenticate(message, payload); return; @@ -300,11 +302,17 @@ struct LanSession::Impl { snapshot.next_requests[guest_player - 1], CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident} }; - auto submitted = runtime.try_submit({guest_player}, envelope); + if (options.before_command_admission) options.before_command_admission(); + auto submitted = runtime.try_submit_if_current({guest_player}, envelope, checked); if (submitted.admission == RuntimeAdmission::Accepted) { pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation); - } else if (submitted.admission == RuntimeAdmission::Busy) { - reply(CommandStatus::Busy, *snapshot.world); + } else if (submitted.admission == RuntimeAdmission::Busy || + submitted.admission == RuntimeAdmission::StaleSnapshot) { + // Contention/capacity does not certify the old publication either. + // Fail closed on incompatible/faulted/replaced state; an ordinary + // compatible revision leaves the legacy sequence available to retry. + const auto current = current_runtime_snapshot(runtime); + reply(CommandStatus::Busy, *current->world); } else { throw std::runtime_error("The authoritative owner cannot accept guest commands."); } @@ -461,7 +469,8 @@ struct LanSession::Impl { } }; -LanSession::LanSession() : impl_(std::make_unique()) {} +LanSession::LanSession() : LanSession(LanSessionOptions{}) {} +LanSession::LanSession(LanSessionOptions options) : impl_(std::make_unique(std::move(options))) {} LanSession::~LanSession() = default; void LanSession::host(std::uint16_t port, bool loopback_only) { @@ -593,7 +602,7 @@ void LanSession::poll_host(SimulationRuntime& runtime) { connection.bind_runtime(view); connection.poll_network([&](Message message, std::string_view payload) { const auto snapshot = connection.current_runtime_snapshot(runtime); - connection.handle_runtime_host(runtime, *snapshot, message, payload); + connection.handle_runtime_host(runtime, snapshot, message, payload); }, [&](Clock::time_point now) { const auto snapshot = connection.current_runtime_snapshot(runtime); if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now); diff --git a/docs/agent-workflow/tasks/S16-04.md b/docs/agent-workflow/tasks/S16-04.md new file mode 100644 index 0000000..6204245 --- /dev/null +++ b/docs/agent-workflow/tasks/S16-04.md @@ -0,0 +1,47 @@ +# Linearize legacy guest command admission with authoritative publication + +Task ID: S16-04 +Role: sol_implementer +Status: READY + +## 1. Context and baseline +Independent review M01-V15 found a real race in S16-03 at c183de1 in s16 worktree. app/lan_session_win32.cpp current_runtime_snapshot takes a healthy compatible immutable snapshot, then handle_runtime_host later calls unconditional SimulationRuntime::try_submit. Runtime::enqueue under its mutex only checks closing/capacity; a host cancellation can publish an unrepresentable world in the same epoch between those operations. Work already queued before cutoff must still settle. Earlier old/current compatibility and partial buffered data tests unrelated to this gap passed. + +## 2. Objective and deliverables +Enforce atomic conditional admission against the exact compatible publication already inspected by protocol11; verify a deterministically forced check→concurrent publish→enqueue race using the real owner/host/socket. Keep old clients functional on compatible newer snapshots, and no secret fallback to the legacy path. + +## 3. Scope and non-goals +Limited change to S16 adapter, smallest general runtime admission seam and targeted regression/doc. No protocol layout change, global gameplay trust/authority changes, or duplicate compatibility logic under network ownership. + +## 4. Files to inspect +Inspect engine/include/settlement/core/simulation_runtime.hpp, engine/src/simulation_runtime.cpp enqueue/publish/fault/try_submit, app/lan_session_win32.cpp + lan_session.hpp poll/handle_runtime_host/reply/drop, tests/lan_tests.cpp plus tests/runtime_tests.cpp existing gates, docs/plan/systems/{S01,S16}.md. Read M01-V15 and S16-03 and actual earlier logs in temp. + +## 5. Write ownership and coordination +Write scope: engine/include/settlement/core/simulation_runtime.hpp; engine/src/simulation_runtime.cpp; app/lan_session_win32.cpp; app/lan_session.hpp if essential for a small test seam; tests/lan_tests.cpp; docs/plan/systems/S16.md. S21 owns runtime_tests.cpp in a sibling; keep your specific regression in lan_tests. No shared changes/remote, Git writes, children or shared Serena switching. + +## 6. Implementation or investigation approach +Add narrowly named conditional admission to normal runtime queue (suggest try_submit_if_current, explicit checked snapshot). Under exactly the mutex serializing published/state and queue insertion, before effects, require RuntimeState::Running and match non-null expected retained shared publication (identity pointer or version+incarnation with equal semantics). Leave existing unconditional local API unchanged. Ensure lock contention/capacity Busy is distinct in outcome/handling from a changed publication, e.g. explicit mismatch result or documented guard outcome; no read outside mutex can certify admission. Do not recompute/copy the whole World in the lock. Never revalidate/revoke work already admitted before publication. + +## 7. Interfaces and data contracts +LAN adapter passes checked published snapshot capability with outgoing command. On mismatch re-evaluate latest state: incompatible/faulted/session replacement clears peer/buffers and never enqueues stale envelope; healthy same-session changed revision must retain old protocol sequence/ack, e.g. legitimate Busy and old-client retry or bounded retry with current snapshot, not disconnect all guests every tick. Invalid/fault/capacity must not emit receipt for an unadmitted command as Accepted. Distinguish handshakes/queue flush; prior external bytes already sent cannot be recalled. + +## 8. Dependencies and integration +Real S04 cancel from host and custody S06/S15 already in s16. Root also integrating S21/S18 tests. Use test hook at narrow point after checking snapshot and before runtime enqueue, or equivalent genuine scheduling barrier. Avoid new permanent per-frame overhead unrelated to this path. If testing hook is needed, prefer existing configured seams or narrow optional sterile observer rather than global test-only code in normal library that changes semantics. + +## 9. Edge cases security and performance +Protect repeated remote sessions/idempotency and stale same-epoch publication across canonical cancellation. Guards must not coerce nullptr into unconditional admission, ABA impossible with retained shared_ptr and immutable identity. Publication faults and shutdown must obey existing semantics. Do not busy-loop when current world is advancing. Old/queued command with exact accepted availability must complete on healthy owner even if the state changes afterwards. + +## 10. Acceptance criteria +1. Deterministic two-thread/real-loopback test holds remote operation after capturing representable S, publishes same-epoch unrepresentable S+1 via real typed cancellation, releases, proves zero new guest ledger entry/sequence/stock/command effect and correct peer drop (works on old code as counterexample). 2. Positive same-session compatible revision interleaving maintains coherent old-client progress/sequence and earlier admitted request still settles. 3. Existing 13 LAN and target viewer, actual compiled original/new host+guest both ways pass. 4. No change to PC11 bytes/ordinary local auth or installed snapshots. + +## 11. Verification commands and evidence +Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s16-custody-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build --parallel 6, run ctest --test-dir --output-on-failure and your targeted tests. Evidence required. Run new focused LAN tests and full CTest -V, old/new interop harnesses from your S16-03 context, use logs s16-published-admission-*.log and git diff --check. Native Windows unavailable. Before fixed build, show exact reproducer outcome if feasible. + +## 12. Constraints and stop conditions +If inability to atomically compare protected publication and enqueue, report actual contract and fail closed within scope. After two failed same-cause attempts root escalates; no other agents, external writes, retrying commands outside the appropriate session or full scans under runtime lock. + +## 13. Authorization and decisions +User requested end-to-end software and protocol compatibility. Fresh V15 correction belongs to S16; bounded change to existing owner seam is authorized. Root exclusively owns commits/remote operations and post-fix re-review. + +## 14. Return format +Return S16-04 READY or PARTIAL, frozen paths, observed pre-fix failure/post-fix controlled interleaving and old/new compatibility, actual logs and residual limits. diff --git a/docs/plan/systems/S16.md b/docs/plan/systems/S16.md index b327fe9..f664cf5 100644 --- a/docs/plan/systems/S16.md +++ b/docs/plan/systems/S16.md @@ -55,6 +55,14 @@ Общий `ViewerSession::can_host_legacy()` разрешает создание слушателя только для опубликованной представимой активной колонии 32×32 с точными встроенными правилами, вне гостевого режима и смены партии. Это ограничение совместимости не блокирует современные команды и контрольные точки. Историческая активная колония с простым рецептом кровати и встроенным манифестом остаётся допустимой. [Контракт S16-03](../../agent-workflow/tasks/S16-03.md) +Проверка представимости снимка сама по себе не разрешает позднейший допуск команды. `SimulationRuntime::try_submit_if_current` сравнивает удержанную проверенную публикацию с текущей и проверяет рабочее состояние под тем же mutex, который защищает публикацию и постановку в очередь. Пустая ссылка получает `InvalidRequest`, нерабочий владелец — `Closed`, сменившаяся публикация — `StaleSnapshot`; конкуренция за mutex и заполненная очередь возвращают `Busy`. Сравнение публикаций предшествует проверке вместимости очереди. Внутри блокировки нет сканирования мира или сериализации. Обычный `try_submit` сохраняет прежний контракт. Уже допущенные операции не отзываются последующей публикацией. + +Адаптер передаёт точную проверенную ссылку. При `StaleSnapshot` или `Busy` он заново проверяет текущую публикацию: несовместимое имущество, отказ владельца или другая инкарнация закрывают гостя и очищают буферы. Совместимое новое состояние возвращает честный `Busy` с актуальным прежним номером команды, чтобы гость мог повторить намерение. Цикла повторных допусков в сетевом опросе нет. Необязательный диагностический `LanSessionOptions::before_command_admission` позволяет остановить поток опроса ровно между проверкой и допуском, не удерживая блокировку владельца. [Контракт S16-04](../../agent-workflow/tasks/S16-04.md) + +Общий контракт условного допуска отслеживается отдельно от публикации и журнала результатов в [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16). Закреплённый `FuturePool::try_submit` проверяет лимит и остановку исполнителя, но не игровую публикацию. Условие замены локального допуска — сохранить точное сравнение удержанного снимка и постановку в ограниченную очередь одной критической секцией и повторить управляемую гонку: после проверки представимого S реальный владелец публикует несовместимое S+1 в той же инкарнации, затем гость пытается войти в очередь. До исправления регрессия реально продвинула номер запроса гостя с 1 до 2. Она также проверяет совместимую новую публикацию с повтором прежнего сетевого номера, отсутствие эффектов отказа, завершение ранее допущенной работы и отказ после сбоя владельца. + +Проверка S16-04 на базе `c183de1`: Windows x64 Release GCC 16.2 под Wine 11, 4/4 новых `lan-admission`; полный CTest — 168/168 core, 17/17 LAN, 15/15 клиента и 6/6 управления заказами. После исправления управляемая гонка сохраняет точную публикацию отмены, прежние сетевой номер и номер запроса гостя, профессию жителя и отсутствие квитанции в журнале. Старый скомпилированный клиент и заново собранный адаптер успешно обменялись приказами в обеих ролях. `git diff --check` прошёл. Нативная Windows, MSVC и физические машины этим прогоном не проверялись. + Для этого адаптера повторно проверены публичный `Void/Net/Socket.hpp`, Windows-ветка `src/Net/Socket.cpp` и `tests/standalone/Net/Socket.cpp` закреплённого `7b0fea6095f603f9e1904f66dfdc7752f4be4792`: UDP не реализован для Windows и не предоставляет игровую проверку представимости. Существующий TCP-транспорт остаётся прежним. Имущество и условие отказа принадлежат игровому адаптеру поверх операций [Void/Library #8](https://git.faumaray.com/Void/Library/issues/8); новое универсальное сетевое средство не вводится. Проверка S16-03 на интеграционной базе `5c309b2`: Windows x64 Release GCC 16.2 под Wine 11, 13/13 LAN и 15/15 клиента. Четыре новых LAN-сценария проверяют настоящий отменённый смешанный груз при полном складе, отказ входа, сохранение современного мира, завершение ранее допущенного приказа и отсечение следующего приказа в той же инкарнации, а также удаление недосланного снимка размером больше 64 КиБ на обоих путях хоста. Отдельно проходят 3/3 `wire` и 9/9 `lan-owner`. Старый скомпилированный клиент и новый адаптер обменялись приказами в обеих ролях. Оба старых корпуса формата 13 (738 386 и 393 857 байтов) совпали полностью на 1/2/6/12 исполнителях. Полный CTest этой базы выявил два отказа `production-command` и четыре отказа `production-controls` в параллельном срезе S04; их исправление и повторная общая проверка относятся к интеграции. Нативная Windows, MSVC и две физические машины этим прогоном не проверялись. diff --git a/engine/include/settlement/core/simulation_runtime.hpp b/engine/include/settlement/core/simulation_runtime.hpp index 4e85ea7..aac817a 100644 --- a/engine/include/settlement/core/simulation_runtime.hpp +++ b/engine/include/settlement/core/simulation_runtime.hpp @@ -15,7 +15,7 @@ namespace settlement { enum class RuntimeState { Running, Faulted, Closed }; -enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted }; +enum class RuntimeAdmission { Accepted, Busy, Closed, InvalidRequest, IdExhausted, StaleSnapshot }; enum class RuntimeOutcome { Completed, Faulted, Closed, Superseded, InvalidCandidate }; enum class RuntimePhase { BeforeTick, BeforeCapture, BeforeInstallCapture }; @@ -77,6 +77,14 @@ public: [[nodiscard]] std::optional lookup( TrustedClient client, const CommandEnvelope& command) const; [[nodiscard]] RuntimeSubmission try_submit(TrustedClient client, const CommandEnvelope& command); + // Atomically admit against the exact retained publication inspected by the + // caller. Null returns InvalidRequest; a nonrunning owner returns Closed; + // a different publication returns StaleSnapshot, before checking capacity. + // Mutex contention or full capacity returns Busy. Refusals have no future. + // Later publications never revoke work that was already admitted. + [[nodiscard]] RuntimeSubmission try_submit_if_current( + TrustedClient client, const CommandEnvelope& command, + const std::shared_ptr& expected); [[nodiscard]] RuntimeSubmission set_ticking(bool enabled); // Fences earlier queued operations and all eligible clock debt through the // admission time. Advancing a ManualClock should be followed by this or notify_clock(). diff --git a/engine/src/simulation_runtime.cpp b/engine/src/simulation_runtime.cpp index 2bbcd2c..2f7820e 100644 --- a/engine/src/simulation_runtime.cpp +++ b/engine/src/simulation_runtime.cpp @@ -107,11 +107,17 @@ struct SimulationRuntime::Impl { return published->revision + 1; } - RuntimeSubmission enqueue(std::unique_ptr work, WorldCheckpoint* candidate = nullptr) { + RuntimeSubmission enqueue(std::unique_ptr work, WorldCheckpoint* candidate = nullptr, + const std::shared_ptr* expected = nullptr) { auto completion = work->promise.get_future(); std::unique_lock lock(mutex, std::try_to_lock); if (!lock.owns_lock()) return {RuntimeAdmission::Busy, {}}; if (stopping.load()) return {RuntimeAdmission::Closed, {}}; + if (expected) { + if (!*expected) return {RuntimeAdmission::InvalidRequest, {}}; + if (state != RuntimeState::Running) return {RuntimeAdmission::Closed, {}}; + if (published != *expected) return {RuntimeAdmission::StaleSnapshot, {}}; + } if (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}}; queue.push_back(std::move(work)); if (candidate) { @@ -333,6 +339,16 @@ RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const Comm return impl_->enqueue(std::move(work)); } +RuntimeSubmission SimulationRuntime::try_submit_if_current( + TrustedClient client, const CommandEnvelope& command, + const std::shared_ptr& expected) { + if (!expected) return {RuntimeAdmission::InvalidRequest, {}}; + auto work = std::make_unique(Impl::Kind::Command); + work->client = client; + work->command = command; + return impl_->enqueue(std::move(work), nullptr, &expected); +} + RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) { auto work = std::make_unique(Impl::Kind::Ticking); work->enabled = enabled; diff --git a/tests/lan_tests.cpp b/tests/lan_tests.cpp index a471e73..d781261 100644 --- a/tests/lan_tests.cpp +++ b/tests/lan_tests.cpp @@ -89,8 +89,7 @@ struct CaptureGate { bool entered = false; bool released = false; - void capture(RuntimePhase phase) { - if (phase != RuntimePhase::BeforeCapture) return; + void block() { std::unique_lock lock(mutex); if (!armed) return; entered = true; @@ -100,6 +99,10 @@ struct CaptureGate { } } + void capture(RuntimePhase phase) { + if (phase == RuntimePhase::BeforeCapture) block(); + } + void arm() { std::lock_guard lock(mutex); armed = true; } bool waiting() { std::lock_guard lock(mutex); return entered; } void release() { @@ -191,6 +194,10 @@ struct LanTests : Void::Testing::Suite { [[= Void::Testing::tag("lan-owner")]] Test test_standalone_custody_discards_queued_snapshot_and_command(); [[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_cuts_off_queued_guest_but_settles_admitted_work(); [[= Void::Testing::tag("lan-owner")]] Test test_runtime_custody_discards_queued_snapshot_before_admission(); + [[= Void::Testing::tag("lan-admission")]] Test test_guest_admission_cannot_cross_incompatible_publication(); + [[= Void::Testing::tag("lan-admission")]] Test test_guest_retries_same_sequence_after_compatible_publication(); + [[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_preserves_accepted_work_and_reports_refusals(); + [[= Void::Testing::tag("lan-admission")]] Test test_conditional_admission_rejects_faulted_owner_with_retained_publication(); }; Test LanTests::test_protocol_11_fixed_messages() { @@ -810,4 +817,168 @@ Test LanTests::test_runtime_custody_discards_queued_snapshot_before_admission() require(runtime.latest()->next_requests[1] == 1 && runtime.latest()->world->next_command_sequence(2) == 1); } +Test LanTests::test_guest_admission_cannot_cross_incompatible_publication() { + CaptureGate admission; + auto initial = colony_checkpoint(); + initial.world = mixed_delivery(); + const auto production = initial.world->production_orders().front().id; + const auto resident = initial.world->agents().front().id; + SimulationRuntime runtime(std::move(initial), {.ticking = false}); + LanSession host({.before_command_admission = [&] { admission.block(); }}); + host.host(0, true); + RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16)); + pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.snapshot != nullptr; }, + "Admission-race guest did not join."); + const auto checked = runtime.latest(); + const auto id = checked->identity; + const auto old_profession = checked->world->agents().front().profession; + const CommandPayload intent{CommandKind::AssignProfession, {}, + static_cast(Profession::Miner), {}, resident}; + const CommandEnvelope envelope{command_envelope_version, id.world, id.session, id.city, + checked->next_requests[1], intent}; + admission.arm(); + guest.command(1, intent.kind, {}, intent.value, resident); + guest.poll(); + auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); }); + auto release = Void::Scope::on_exit([&] { admission.release(); }); + pump_until([] {}, [&] { return admission.waiting(); }, "Guest did not reach pre-admission barrier."); + // This is a genuine owner publication between the adapter's compatibility + // check of S and admission of the remote command, without an epoch change. + RuntimeSubmission canceled{RuntimeAdmission::Busy, {}}; + pump_until([&] { + canceled = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, + checked->next_requests[0], CancelProductionPayload{production}}); + }, [&] { return canceled.admission != RuntimeAdmission::Busy; }, "Cancel could not obtain owner admission."); + require(canceled.admission == RuntimeAdmission::Accepted && canceled.completion.wait_for(3s) == std::future_status::ready); + require(canceled.completion.get().receipt->command_status == CommandStatus::Accepted); + const auto cutoff = runtime.latest(); + require(cutoff != checked && cutoff->identity.session == id.session && !cutoff->world->legacy_representable()); + admission.release(); + require(polling.wait_for(3s) == std::future_status::ready); + polling.get(); + RuntimeSubmission fence{RuntimeAdmission::Busy, {}}; + pump_until([&] { fence = runtime.synchronize(); }, [&] { return fence.admission != RuntimeAdmission::Busy; }, + "Owner fence could not be admitted."); + require(fence.admission == RuntimeAdmission::Accepted && fence.completion.wait_for(3s) == std::future_status::ready); + require(fence.completion.get().outcome == RuntimeOutcome::Completed); + const auto after = runtime.latest(); + const auto evidence = "Guest command crossed incompatible publication: next_request=" + + std::to_string(after->next_requests[1]); + if (after->next_requests[1] != checked->next_requests[1]) throw std::runtime_error(evidence); + require(after->world->next_command_sequence(2) == checked->world->next_command_sequence(2)); + require(after->world->agents().front().profession == old_profession && !runtime.lookup({2}, envelope)); + require(after == cutoff && runtime.view().state == RuntimeState::Running); + pump_until([&] { host.poll_host(runtime); guest.poll(); }, [&] { return guest.closed; }, + "Race-cutoff peer was not disconnected."); + require(host.state() == LanState::Hosting && guest.receipts.empty()); + require(encode_checkpoint(*after->world, id.world, id.city, *after->rules).has_value()); +} + +Test LanTests::test_guest_retries_same_sequence_after_compatible_publication() { + CaptureGate admission; + SimulationRuntime runtime(colony_checkpoint(), {.ticking = false}); + LanSession host({.before_command_admission = [&] { admission.block(); }}); + host.host(0, true); + RawGuest guest(host.port(), std::stoull(host.join_code(), nullptr, 16)); + const auto pump = [&] { host.poll_host(runtime); guest.poll(); }; + pump_until(pump, [&] { return guest.snapshot != nullptr; }, "Compatible-race guest did not join."); + const auto checked = runtime.latest(); + const auto id = checked->identity; + const auto resident = checked->world->agents().back().id; + admission.arm(); + guest.command(1, CommandKind::AssignProfession, {}, static_cast(Profession::Miner), resident); + guest.poll(); + auto polling = std::async(std::launch::async, [&] { host.poll_host(runtime); }); + auto release = Void::Scope::on_exit([&] { admission.release(); }); + pump_until([] {}, [&] { return admission.waiting(); }, "Compatible command did not reach admission barrier."); + RuntimeSubmission local{RuntimeAdmission::Busy, {}}; + pump_until([&] { + local = runtime.try_submit({1}, {command_envelope_version, id.world, id.session, id.city, + checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}}); + }, [&] { return local.admission != RuntimeAdmission::Busy; }, "Compatible local change could not be admitted."); + require(local.admission == RuntimeAdmission::Accepted && local.completion.wait_for(3s) == std::future_status::ready); + require(local.completion.get().receipt->command_status == CommandStatus::Accepted); + const auto changed = runtime.latest(); + require(changed != checked && changed->identity.session == id.session && changed->world->legacy_representable()); + admission.release(); + require(polling.wait_for(3s) == std::future_status::ready); + polling.get(); + pump_until(pump, [&] { return guest.receipts.size() == 1; }, "Compatible revision did not report retryable Busy."); + require(guest.receipts.front().status == CommandStatus::Busy && guest.receipts.front().next_sequence == 1); + require(runtime.latest() == changed && changed->next_requests[1] == 1 && host.state() == LanState::HostConnected); + guest.command(1, CommandKind::AssignProfession, {}, static_cast(Profession::Miner), resident); + pump_until(pump, [&] { return guest.receipts.size() == 2; }, "Same-sequence guest retry did not settle."); + require(guest.receipts.back().status == CommandStatus::Accepted && guest.receipts.back().next_sequence == 2); + require(runtime.latest()->next_requests[1] == 2 && runtime.latest()->world->agents().back().profession == Profession::Miner); +} + +Test LanTests::test_conditional_admission_preserves_accepted_work_and_reports_refusals() { + CaptureGate owner; + RuntimeOptions options{.capacity = 2, .ticking = false}; + options.observer = [&](RuntimePhase phase) { owner.capture(phase); }; + SimulationRuntime runtime(colony_checkpoint(), options); + auto release = Void::Scope::on_exit([&] { owner.release(); }); + const auto checked = runtime.latest(); + const auto id = checked->identity; + const CommandEnvelope local_command{command_envelope_version, id.world, id.session, id.city, + checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}}; + const CommandEnvelope guest_command{command_envelope_version, id.world, id.session, id.city, + checked->next_requests[1], CommandPayload{CommandKind::AssignProfession, {}, + static_cast(Profession::Miner), {}, checked->world->agents().back().id}}; + const auto invalid = runtime.try_submit_if_current({2}, guest_command, {}); + require(invalid.admission == RuntimeAdmission::InvalidRequest && !invalid.completion.valid()); + owner.arm(); + RuntimeSubmission local{RuntimeAdmission::Busy, {}}; + pump_until([&] { local = runtime.try_submit({1}, local_command); }, + [&] { return local.admission != RuntimeAdmission::Busy; }, "Local work did not enter owner queue."); + require(local.admission == RuntimeAdmission::Accepted); + pump_until([] {}, [&] { return owner.waiting(); }, "Owner did not reach capture barrier."); + RuntimeSubmission accepted{RuntimeAdmission::Busy, {}}; + pump_until([&] { accepted = runtime.try_submit_if_current({2}, guest_command, checked); }, + [&] { return accepted.admission != RuntimeAdmission::Busy; }, "Conditional work did not enter remaining slot."); + require(accepted.admission == RuntimeAdmission::Accepted); + const auto full = runtime.try_submit_if_current({2}, guest_command, checked); + require(full.admission == RuntimeAdmission::Busy && !full.completion.valid()); + // Both operations were admitted while S was current. Publishing the local + // result must not revoke the already queued guarded guest operation. + owner.release(); + require(local.completion.wait_for(3s) == std::future_status::ready && + local.completion.get().receipt->command_status == CommandStatus::Accepted); + require(accepted.completion.wait_for(3s) == std::future_status::ready && + accepted.completion.get().receipt->command_status == CommandStatus::Accepted); + const auto current = runtime.latest(); + require(current != checked && current->next_requests[1] == 2); + RuntimeSubmission stale{RuntimeAdmission::Busy, {}}; + pump_until([&] { stale = runtime.try_submit_if_current({2}, guest_command, checked); }, + [&] { return stale.admission != RuntimeAdmission::Busy; }, "Stale snapshot refusal remained contended."); + require(stale.admission == RuntimeAdmission::StaleSnapshot && !stale.completion.valid()); + require(runtime.latest() == current); + runtime.shutdown(); + const auto closed = runtime.try_submit_if_current({2}, guest_command, current); + require(closed.admission == RuntimeAdmission::Closed && !closed.completion.valid()); +} + +Test LanTests::test_conditional_admission_rejects_faulted_owner_with_retained_publication() { + RuntimeOptions options{.ticking = false}; + options.observer = [](RuntimePhase phase) { + if (phase == RuntimePhase::BeforeCapture) throw std::runtime_error("Injected guarded-admission fault."); + }; + SimulationRuntime runtime(colony_checkpoint(), options); + const auto checked = runtime.latest(); + const auto id = checked->identity; + const CommandEnvelope command{command_envelope_version, id.world, id.session, id.city, + checked->next_requests[0], CommandPayload{CommandKind::SetPaused, {}, 1}}; + RuntimeSubmission fault{RuntimeAdmission::Busy, {}}; + pump_until([&] { fault = runtime.try_submit({1}, command); }, + [&] { return fault.admission != RuntimeAdmission::Busy; }, "Fault trigger remained contended."); + require(fault.admission == RuntimeAdmission::Accepted && fault.completion.wait_for(3s) == std::future_status::ready); + require(fault.completion.get().outcome == RuntimeOutcome::Faulted); + require(runtime.latest() == checked && runtime.view().state == RuntimeState::Faulted); + RuntimeSubmission denied{RuntimeAdmission::Busy, {}}; + pump_until([&] { denied = runtime.try_submit_if_current({1}, command, checked); }, + [&] { return denied.admission != RuntimeAdmission::Busy; }, "Faulted owner refusal remained contended."); + require(denied.admission == RuntimeAdmission::Closed && !denied.completion.valid()); + require(runtime.latest() == checked && !runtime.lookup({1}, command)); +} + } // namespace