Compare commits

..
Author SHA1 Message Date
faumaray 15887d5613 Record M01 software acceptance and trace the new VoidLibrary contract 2026-12-02 23:48:11 +03:00
faumaray 51311ca104 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 69ce32c2b6 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray cd75eab191 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray f60375a9f3 Include the validated system branch and its shared base 2026-12-02 23:47:40 +03:00
faumaray 5dd0e35093 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 519e4e72a7 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 22420e9fe2 Include the tested viewer fault-recovery admission fence 2026-12-02 23:46:59 +03:00
faumaray 89bbb81317 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray c812df8c0b Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray ba00651b45 Include the verified shared checkpoint and transfer implementation 2026-12-02 23:46:38 +03:00
faumaray 4bac17df83 Integrate atomic publication-conditioned admission for legacy peers 2026-12-02 23:39:19 +03:00
faumaray e60dc355f0 Include the final checkpoint migration evidence 2026-12-02 23:37:52 +03:00
faumaray 74aadb27b2 Record the observed LAN count and verified fence recovery 2026-12-02 23:35:46 +03:00
faumaray 2ba4b3ffc4 Record order-control verification against the actual Windows run 2026-12-02 23:35:46 +03:00
faumaray 86b5fb35f1 Integrate reviewed terminal receipts, phase checks and authenticated mutants 2026-12-02 23:35:46 +03:00
faumaray f6402eb80f Check all inventory and transfer state in the held-frame test 2026-12-02 23:31:44 +03:00
faumaray d13a232f29 Run the frame test with full checkpoint state alongside the new controls 2026-12-02 23:31:44 +03:00
faumaray 070db7864e Track complete custody state in presentation smoke tests 2026-12-02 23:31:44 +03:00
faumaray a34733797b Compare stack, reservation and transfer state in every authoritative replay 2026-12-02 23:27:36 +03:00
faumaray 431ee602c7 Exercise full-state replay alongside order controls and protocol 11 2026-12-02 23:27:36 +03:00
faumaray 9bc52ea5c9 Stabilize fault-recovery verification in the integrated client 2026-12-02 23:26:10 +03:00
faumaray 8522f910b3 Exercise full-state replay with validated idle and generic job phases 2026-12-02 23:25:54 +03:00
faumaray 22111440c9 Integrate item custody, checkpoint migration, order controls and legacy peers 2026-12-02 23:24:03 +03:00
faumaray e26b9c2936 Replay complete custody receipts and historical migration state 2026-12-02 23:19:32 +03:00
faumaray a47e850bb4 Record the verified camera, checkpoint and title-screen integration 2026-12-02 23:19:32 +03:00
faumaray 3c7cc3ce2c Exercise replay against the modern custody state and migration 2026-12-02 23:17:10 +03:00
faumaray 1cf8bd08fc Present immutable camera frames independently of colony progress 2026-12-02 23:12:05 +03:00
faumaray 455630fb39 Integrate presentation frames with the current title screen and session rules 2026-12-02 23:12:05 +03:00
faumaray e9e7e8276e Record integrated replay results under opposite worker schedules 2026-12-02 23:10:35 +03:00
faumaray ef980af125 Verify canonical replay under opposing worker completion orders 2026-12-02 23:02:14 +03:00
faumaray 048268a27e Integrate replay diagnostics and adversarial completion-order checks 2026-12-02 23:02:14 +03:00
22 changed files with 1827 additions and 139 deletions

No files matched your search

+7
View File
@@ -146,6 +146,13 @@ if(BUILD_TESTING)
target_link_libraries(settlement_lan_tests PRIVATE settlement_lan Void::Testing)
add_test(NAME settlement_lan_tests COMMAND settlement_lan_tests)
add_executable(settlement_viewer_frame_smoke
tests/viewer_frame_smoke.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
add_executable(settlement_viewer_tests tests/viewer_session_tests.cpp tests/test_main.cpp)
target_link_libraries(settlement_viewer_tests PRIVATE settlement_client Void::Testing)
add_test(NAME settlement_viewer_tests COMMAND settlement_viewer_tests)
+44 -19
View File
@@ -486,6 +486,11 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
} // namespace
class PreparedGeometry {
public:
Mesh mesh;
};
struct D3DScene::Backend {
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
@@ -501,10 +506,11 @@ struct D3DScene::Backend {
ComPtr<ID3D11Buffer> geometry;
UINT buffer_bytes = 0;
int width = 0, height = 0;
Mesh mesh;
std::shared_ptr<const PreparedGeometry> uploaded;
bool resize(int w, int h) {
if (w == width && h == height && target_view && depth_view) return true;
uploaded.reset();
context->OMSetRenderTargets(0, nullptr, nullptr);
target_texture.Reset();
target_view.Reset();
@@ -532,7 +538,7 @@ struct D3DScene::Backend {
return true;
}
bool upload_geometry() {
bool upload_geometry(const Mesh& mesh) {
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
if (bytes > std::numeric_limits<UINT>::max()) return false;
if (bytes > buffer_bytes) {
@@ -578,7 +584,7 @@ D3DScene::D3DScene() = default;
D3DScene::~D3DScene() = default;
bool D3DScene::initialize(HWND target, bool software) {
auto graphics = std::make_unique<Backend>();
auto graphics = std::make_shared<Backend>();
const auto driver = software ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0};
constexpr UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
@@ -628,24 +634,41 @@ bool D3DScene::initialize(HWND target, bool software) {
bool D3DScene::ready() const noexcept { return backend_ != nullptr; }
void D3DScene::reset() noexcept { backend_.reset(); }
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *backend_;
if (!graphics.resize(view.width, view.height)) return false;
graphics.mesh.vertices.clear();
terrain(graphics.mesh, world, view);
resources(graphics.mesh, world);
construction(graphics.mesh, world, view.building_view);
std::shared_ptr<const PreparedGeometry> D3DScene::prepare(const World& world, const SceneView& view) {
auto prepared = std::make_shared<PreparedGeometry>();
terrain(prepared->mesh, world, view);
resources(prepared->mesh, world);
construction(prepared->mesh, world, view.building_view);
for (std::size_t index = 0; index < view.room_blueprints.size(); ++index) {
if (view.moving_room == index) continue;
const auto& plan = view.room_blueprints[index];
draw_room_plan(graphics.mesh, plan, false, world.can_place_room(plan));
draw_room_plan(prepared->mesh, plan, false, world.can_place_room(plan));
}
if (view.room_preview) draw_room_plan(prepared->mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(prepared->mesh, part, false);
if (view.preview) draw_blueprint(prepared->mesh, *view.preview, true);
residents(prepared->mesh, world, view);
return prepared;
}
bool D3DScene::render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture) {
if (!backend_ || view.width <= 0 || view.height <= 0) return false;
return render(prepare(world, view), view, capture);
}
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
std::vector<std::uint32_t>* capture) {
// Present may dispatch window messages, including destruction. Keep this
// backend alive until the current submission has returned.
const auto held_backend = backend_;
if (!held_backend || !geometry || view.width <= 0 || view.height <= 0) return false;
auto& graphics = *held_backend;
if (!graphics.resize(view.width, view.height)) return false;
if (graphics.uploaded != geometry) {
if (!graphics.upload_geometry(geometry->mesh)) return false;
graphics.uploaded = geometry;
++uploads_;
}
if (view.room_preview) draw_room_plan(graphics.mesh, *view.room_preview, true, view.valid_cursor);
for (const auto& part : view.blueprint) draw_blueprint(graphics.mesh, part, false);
if (view.preview) draw_blueprint(graphics.mesh, *view.preview, true);
residents(graphics.mesh, world, view);
if (!graphics.upload_geometry()) return false;
auto* ctx = graphics.context.Get();
constexpr float clear[] = {.83f, .87f, .79f, 1.f};
@@ -666,9 +689,11 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
ctx->VSSetShader(graphics.vertex_shader.Get(), nullptr, 0);
ctx->VSSetConstantBuffers(0, 1, graphics.camera.GetAddressOf());
ctx->PSSetShader(graphics.pixel_shader.Get(), nullptr, 0);
ctx->Draw(static_cast<UINT>(graphics.mesh.vertices.size()), 0);
ctx->Draw(static_cast<UINT>(geometry->mesh.vertices.size()), 0);
if (capture && !graphics.read_frame(*capture)) return false;
return !graphics.swap_chain || SUCCEEDED(graphics.swap_chain->Present(0, 0));
if (graphics.swap_chain && FAILED(graphics.swap_chain->Present(0, 0))) return false;
++frames_;
return true;
}
} // namespace settlement::viewer
+12 -1
View File
@@ -40,18 +40,29 @@ struct SceneView {
std::optional<std::size_t> moving_room;
};
// Immutable CPU geometry can outlive the latest frame and any GPU backend.
class PreparedGeometry;
class D3DScene {
public:
D3DScene();
~D3DScene();
D3DScene(const D3DScene&) = delete;
D3DScene& operator=(const D3DScene&) = delete;
bool initialize(HWND target, bool software = false);
[[nodiscard]] bool ready() const noexcept;
bool render(const World& world, const SceneView& view, std::vector<std::uint32_t>* capture = nullptr);
[[nodiscard]] static std::shared_ptr<const PreparedGeometry> prepare(const World& world, const SceneView& view);
bool render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
std::vector<std::uint32_t>* capture = nullptr);
[[nodiscard]] std::uint64_t uploads() const noexcept { return uploads_; }
[[nodiscard]] std::uint64_t frames() const noexcept { return frames_; }
void reset() noexcept;
private:
std::uint64_t uploads_ = 0, frames_ = 0;
struct Backend;
std::unique_ptr<Backend> backend_;
std::shared_ptr<Backend> backend_;
};
} // namespace settlement::viewer
+268 -89
View File
@@ -91,6 +91,7 @@ constexpr int min_interface_scale = 50;
constexpr int max_interface_scale = 250;
constexpr int default_interface_scale = 125;
constexpr int timer_id = 1;
constexpr int frame_timer_id = 2;
constexpr int map_size = settlement::first_colony_map_size;
constexpr int tile_width = 24;
constexpr int tile_height = 14;
@@ -295,6 +296,63 @@ std::optional<settlement::GridPosition> hover_cell;
std::optional<settlement::AgentId> selected_resident;
std::wstring placement_message;
// Publication stays on the UI thread. Readers pin the complete packet before
// calling Win32 (which can dispatch nested messages). Upstream publication:
// https://git.faumaray.com/Void/Library/issues/5
struct StatusText { std::wstring status, production, priority; };
struct FrameContent {
std::shared_ptr<const settlement::World> world;
std::vector<settlement::viewer::BlueprintPart> blueprint;
std::vector<settlement::RoomPlan> rooms;
settlement::viewer::SceneView view{};
std::shared_ptr<const settlement::viewer::PreparedGeometry> geometry;
std::wstring hint, details;
StatusText status;
};
struct PreparedFrame {
std::shared_ptr<const FrameContent> content;
settlement::viewer::SceneView view{};
DockLayout dock;
int width = 0, height = 0;
bool backend_ready = false;
std::shared_ptr<void> font;
};
std::shared_ptr<const PreparedFrame> prepared_frame;
std::uint64_t frame_requests = 1, sampled_request = 0;
bool pumping_session = false, preparing_frame = false, painting_scene = false, painting_main = false;
bool viewer_destroyed = false, repaint_pending = false;
void sample_frame(HWND window);
#ifdef SETTLEMENT_FRAME_TEST
std::function<void()> frame_test_after_poll, frame_test_during_paint;
#endif
struct PaintScope {
HWND window;
PAINTSTRUCT paint{};
HDC dc;
explicit PaintScope(HWND target) : window(target), dc(BeginPaint(target, &paint)) {}
~PaintScope() { EndPaint(window, &paint); }
};
struct PaintBuffer {
HDC dc;
HBITMAP bitmap;
HGDIOBJ previous;
PaintBuffer(HDC target, int width, int height) : dc(CreateCompatibleDC(target)),
bitmap(CreateCompatibleBitmap(target, width, height)),
previous(dc && bitmap ? SelectObject(dc, bitmap) : nullptr) {}
~PaintBuffer() {
if (previous) SelectObject(dc, previous);
if (bitmap) DeleteObject(bitmap);
if (dc) DeleteDC(dc);
}
explicit operator bool() const { return dc && bitmap && previous; }
};
struct FlagScope {
bool& flag;
explicit FlagScope(bool& value) : flag(value) { flag = true; }
~FlagScope() { flag = false; }
};
void pump_session(HWND window);
void reconcile_ticking();
@@ -470,13 +528,9 @@ POINT client_point(LPARAM coordinates) {
}
void invalidate_scene(HWND window) {
RECT scene{};
GetClientRect(window, &scene);
scene.top = map_top;
if (scene.bottom > scene.top) InvalidateRect(window, &scene, FALSE);
if (!showing_title && graphics.ready() && scene_window) {
InvalidateRect(scene_window, nullptr, FALSE);
}
++frame_requests;
if (painting_main || painting_scene) repaint_pending = true;
if (showing_title && !viewer_destroyed) InvalidateRect(window, nullptr, FALSE);
}
void layout_scene(HWND window) {
@@ -903,8 +957,8 @@ void sync_resident_roster(bool update_selection = false) {
update_roster_details();
}
void update_status() {
if (status_label == nullptr || !world) return;
StatusText prepare_status() {
StatusText result;
const auto busy = std::count_if(world->agents().begin(), world->agents().end(),
[](const settlement::Agent& agent) { return agent.state != settlement::AgentState::Idle; });
std::uint64_t wood = 0;
@@ -931,21 +985,13 @@ void update_status() {
L" Дерево: " + std::to_wstring(wood) + L" Камень: " + std::to_wstring(stone) +
L" Двери: " + std::to_wstring(doors) +
L" Ход: " + std::to_wstring(world->tick());
SetWindowTextW(status_label, text.c_str());
result.status = text;
const bool scenario = world->scenario_active();
const bool can_play = can_give_orders();
if (work_panel != WorkPanel::None && !can_play) {
set_work_panel(GetParent(residents_button), WorkPanel::None);
}
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, can_play);
EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move);
const wchar_t* priority = L"Равный приоритет";
if (world->work_priority() == settlement::WorkPriority::FoodFirst) priority = L"Сначала еда";
else if (world->work_priority() == settlement::WorkPriority::BuildingFirst) priority = L"Сначала стройка";
SetWindowTextW(priority_button, priority);
if (scenario && production_label != nullptr) {
result.priority = priority;
if (scenario) {
const auto progress = world->scenario_progress();
const auto sleeping = std::count_if(world->agents().begin(), world->agents().end(),
[](const auto& agent) { return agent.state == settlement::AgentState::Sleeping; });
@@ -954,10 +1000,10 @@ void update_status() {
std::to_wstring(progress.residents) + L" Еда " + std::to_wstring(progress.available_food) +
L"/" + std::to_wstring(progress.food_goal) + L" Ткань " + std::to_wstring(cloth) +
L" Лён " + std::to_wstring(flax) + L" Спят " + std::to_wstring(sleeping);
SetWindowTextW(production_label, goal.c_str());
return;
result.production = goal;
return result;
}
if (production_label != nullptr) {
{
unsigned waiting = 0;
unsigned carrying = 0;
unsigned building = 0;
@@ -977,8 +1023,22 @@ void update_status() {
L" Ткань: " + std::to_wstring(cloth) + L" Домики В очереди: " + std::to_wstring(waiting) +
L" Доставка: " + std::to_wstring(carrying) + L" Строятся: " + std::to_wstring(building) +
L" Готовы: " + std::to_wstring(built);
SetWindowTextW(production_label, production.c_str());
result.production = production;
}
return result;
}
void update_status() {
if (!world) return;
const bool scenario = world->scenario_active();
const bool can_play = can_give_orders();
if (work_panel != WorkPanel::None && !can_play) {
set_work_panel(GetParent(residents_button), WorkPanel::None);
}
for (const HWND button : dock_section_buttons) EnableWindow(button, can_play);
EnableWindow(priority_button, scenario && can_play);
EnableWindow(work_list_button, can_play);
EnableWindow(build_blueprint_button, has_blueprint() && can_play && !room_draft_move);
}
void update_bed_choices() {
@@ -1323,7 +1383,7 @@ void handle_lan_menu(HWND window, int command) {
guest_intents.clear();
if (was_guest) {
clear_blueprints();
world = session->world();
if (!session->changing_world()) world = session->world();
}
enter_game_on_snapshot = false;
set_work_panel(window, WorkPanel::None);
@@ -1726,12 +1786,13 @@ void reconcile_ticking() {
}
void pump_session(HWND window) {
static bool pumping = false;
if (!session || pumping) return;
pumping = true;
struct Finish { ~Finish() { pumping = false; } } finish;
if (!session || pumping_session || preparing_frame || viewer_destroyed) return;
FlagScope pumping(pumping_session);
reconcile_ticking();
auto events = session->poll();
#ifdef SETTLEMENT_FRAME_TEST
if (frame_test_after_poll) frame_test_after_poll();
#endif
if (lan->is_guest()) {
if (auto incoming = lan->poll_guest()) {
session->receive_guest(std::move(incoming));
@@ -1740,13 +1801,21 @@ void pump_session(HWND window) {
} else if (lan->state() != LanState::Offline) {
lan->poll_host(session->runtime());
}
world = session->world();
// A runtime install may publish after poll_changes observed an unready
// future. Never read that candidate until Replaced has reset client state.
const bool replacing = std::any_of(events.begin(), events.end(), [](const auto& event) {
return event.kind == settlement::viewer::ViewerEventKind::Replaced;
});
if (!session->changing_world() && !replacing) world = session->world();
for (const auto& event : events) {
switch (event.kind) {
case settlement::viewer::ViewerEventKind::Replaced:
clear_blueprints();
camera = {};
selected_resident.reset();
hover_cell.reset();
move_source.reset();
world = session->world();
has_session = true;
set_work_panel(window, WorkPanel::None);
set_placement_mode(window, PlacementMode::None, L"Поселение готово.");
@@ -2297,31 +2366,7 @@ std::wstring blueprint_details() {
return text;
}
void draw_world(HDC dc, int width, int height) {
RECT bounds{0, 0, width, height};
HBRUSH background = CreateSolidBrush(color(239, 235, 222));
FillRect(dc, &bounds, background);
DeleteObject(background);
if (!world) return;
if (!graphics.ready() && height > map_top + dock_layout.height) {
RECT scene{16, map_top + 24, width - 16, height - dock_layout.height};
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(55, 68, 59));
DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.",
-1, &scene, DT_CENTER | DT_WORDBREAK);
}
const RECT dock{0, height - dock_layout.height, width, height};
const auto dock_brush = CreateSolidBrush(color(34, 46, 40));
FillRect(dc, &dock, dock_brush);
DeleteObject(dock_brush);
const RECT dock_edge{0, dock.top, width, dock.top + 2};
const auto edge_brush = CreateSolidBrush(color(142, 132, 92));
FillRect(dc, &dock_edge, edge_brush);
DeleteObject(edge_brush);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(231, 227, 205));
std::pair<std::wstring, std::wstring> prepare_hud() {
const wchar_t* hint = world->scenario_active() ?
L"Колесо — масштаб Перетаскивание — сдвиг карты Home — общий план Esc — меню" :
L"Голубой — очередь Бирюзовый — доставка Янтарный — строительство";
@@ -2363,10 +2408,6 @@ void draw_world(HDC dc, int width, int height) {
} else if (work_panel == WorkPanel::Carpenter) {
hint = L"Дверь и станок требуют по 2 дерева, шкаф — 1 дерево, стойка — по 1 дереву и камню.";
}
const auto previous_font = dock_font ? SelectObject(dc, dock_font) : nullptr;
const int margin = dock_pixels(12);
RECT legend{margin, dock_layout.hint_top, width - margin, dock_layout.hint_top + dock_layout.line_height};
DrawTextW(dc, hint, -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
auto details = has_blueprint() ? blueprint_details() :
selected_room_template != settlement::RoomTemplate::Empty
? std::wstring((world->staged_beds() ? house_contents : simple_house_contents)
@@ -2390,9 +2431,43 @@ void draw_world(HDC dc, int width, int height) {
details += L" Назначьте плотника в списке «Жители».";
}
}
return {hint, std::move(details)};
}
void draw_world(HDC dc, const PreparedFrame& frame) {
const int width = frame.width, height = frame.height;
const auto& frame_dock = frame.dock;
RECT bounds{0, 0, width, height};
HBRUSH background = CreateSolidBrush(color(239, 235, 222));
FillRect(dc, &bounds, background);
DeleteObject(background);
if (!frame.content) return;
if (!frame.backend_ready && height > map_top + frame_dock.height) {
RECT scene{16, map_top + 24, width - 16, height - frame_dock.height};
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(55, 68, 59));
DrawTextW(dc, L"Не удалось запустить Direct3D 11. Откройте главное меню и войдите в колонию снова.",
-1, &scene, DT_CENTER | DT_WORDBREAK);
}
const RECT dock{0, height - frame_dock.height, width, height};
const auto dock_brush = CreateSolidBrush(color(34, 46, 40));
FillRect(dc, &dock, dock_brush);
DeleteObject(dock_brush);
const RECT dock_edge{0, dock.top, width, dock.top + 2};
const auto edge_brush = CreateSolidBrush(color(142, 132, 92));
FillRect(dc, &dock_edge, edge_brush);
DeleteObject(edge_brush);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, color(231, 227, 205));
const auto previous_font = frame.font ? SelectObject(dc, frame.font.get()) : nullptr;
const int margin = MulDiv(12, frame_dock.scale, 100);
RECT legend{margin, frame_dock.hint_top, width - margin, frame_dock.hint_top + frame_dock.line_height};
DrawTextW(dc, frame.content->hint.c_str(), -1, &legend, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
SetTextColor(dc, color(190, 201, 178));
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + dock_layout.line_height};
DrawTextW(dc, details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
RECT inspector{margin, legend.bottom, width - margin, legend.bottom + frame_dock.line_height};
DrawTextW(dc, frame.content->details.c_str(), -1, &inspector, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
if (previous_font) SelectObject(dc, previous_font);
}
@@ -2421,23 +2496,117 @@ settlement::viewer::SceneView scene_view(int width, int height) {
building_view, room_draft_move ? std::optional(room_draft_move->index) : std::nullopt};
}
bool same_part(const settlement::viewer::BlueprintPart& a, const settlement::viewer::BlueprintPart& b) {
return a.cell == b.cell && a.recipe == b.recipe && a.base == b.base;
}
bool same_room(const settlement::RoomPlan& a, const settlement::RoomPlan& b) {
return a.first == b.first && a.last == b.last && a.entrance == b.entrance && a.layout == b.layout;
}
template<class T, class Equal>
bool same_optional(const std::optional<T>& a, const std::optional<T>& b, Equal equal) {
return a.has_value() == b.has_value() && (!a || equal(*a, *b));
}
bool same_geometry(const FrameContent& a, const FrameContent& b) {
const auto& x = a.view; const auto& y = b.view;
return a.world == b.world && x.cursor == y.cursor && x.valid_cursor == y.valid_cursor &&
x.move_source == y.move_source && x.selected == y.selected && x.building_view == y.building_view &&
x.moving_room == y.moving_room && same_optional(x.preview, y.preview, same_part) &&
same_optional(x.room_preview, y.room_preview, same_room) &&
std::equal(a.blueprint.begin(), a.blueprint.end(), b.blueprint.begin(), b.blueprint.end(), same_part) &&
std::equal(a.rooms.begin(), a.rooms.end(), b.rooms.begin(), b.rooms.end(), same_room);
}
bool frame_visible(HWND window) {
if (viewer_destroyed || showing_title || !IsWindowVisible(window) || IsIconic(window)) return false;
RECT client{}; GetClientRect(window, &client);
return client.right > 0 && client.bottom > map_top + dock_layout.height;
}
void sample_frame(HWND window) {
if (!frame_visible(window) || preparing_frame || pumping_session || painting_main || painting_scene) return;
FlagScope preparing(preparing_frame);
// changing_world is UI-owned: the worker cannot clear this gate. This also
// holds an absent initial world while a first install is in flight.
if (session && !session->changing_world()) {
auto latest = session->world();
if (world != latest) { world = std::move(latest); ++frame_requests; }
}
if (prepared_frame && !repaint_pending && sampled_request == frame_requests &&
prepared_frame->backend_ready == graphics.ready()) return;
const auto request = frame_requests;
const bool repaint = std::exchange(repaint_pending, false);
RECT client{}; GetClientRect(window, &client);
auto frame = std::make_shared<PreparedFrame>();
frame->width = client.right; frame->height = client.bottom;
frame->dock = dock_layout; frame->backend_ready = graphics.ready();
const auto previous = prepared_frame;
if (previous && previous->dock.scale == dock_layout.scale) frame->font = previous->font;
else if (dock_font) {
LOGFONTW font{};
if (GetObjectW(dock_font, sizeof(font), &font)) {
frame->font = std::shared_ptr<void>(CreateFontIndirectW(&font), [](void* value) { if (value) DeleteObject(value); });
}
}
if (session && session->changing_world()) {
if (previous) frame->content = previous->content;
} else if (world) {
auto content = std::make_shared<FrameContent>();
content->world = world;
content->blueprint = blueprint; content->rooms = room_blueprints;
content->view = scene_view(client.right, client.bottom - map_top - dock_layout.height);
content->view.blueprint = content->blueprint; content->view.room_blueprints = content->rooms;
content->status = prepare_status();
auto hud = prepare_hud();
content->hint = std::move(hud.first); content->details = std::move(hud.second);
if (previous && previous->content && same_geometry(*content, *previous->content)) {
content->geometry = previous->content->geometry;
} else content->geometry = settlement::viewer::D3DScene::prepare(*content->world, content->view);
frame->content = std::move(content);
}
if (frame->content) frame->view = frame->content->view;
const auto pan = camera.offset(); const auto scale = camera.scale();
frame->view.width = client.right; frame->view.height = client.bottom - map_top - dock_layout.height;
frame->view.origin_x = static_cast<float>(client.right / 2 * scale + pan.x);
frame->view.origin_y = static_cast<float>(map_origin_y * scale + pan.y - map_top);
frame->view.scale = static_cast<float>(scale);
sampled_request = request;
if (!repaint && previous && previous->content && frame->content &&
previous->content->geometry == frame->content->geometry &&
previous->content->hint == frame->content->hint && previous->content->details == frame->content->details &&
previous->width == frame->width && previous->height == frame->height &&
previous->dock.scale == frame->dock.scale && previous->dock.height == frame->dock.height &&
previous->dock.hint_top == frame->dock.hint_top && previous->dock.line_height == frame->dock.line_height &&
previous->backend_ready == frame->backend_ready && previous->view.origin_x == frame->view.origin_x &&
previous->view.origin_y == frame->view.origin_y && previous->view.scale == frame->view.scale) return;
prepared_frame = std::move(frame);
// Publish before notifying child controls: their synchronous paints may nest.
if (prepared_frame->content) {
const auto content = prepared_frame->content;
SetWindowTextW(status_label, content->status.status.c_str());
SetWindowTextW(production_label, content->status.production.c_str());
SetWindowTextW(priority_button, content->status.priority.c_str());
}
InvalidateRect(window, nullptr, FALSE);
if (scene_window && IsWindowVisible(scene_window)) InvalidateRect(scene_window, nullptr, FALSE);
}
LRESULT CALLBACK scene_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
const auto held_world = world;
try {
if (message == WM_NCHITTEST) return HTTRANSPARENT;
if (message == WM_ERASEBKGND) return 1;
if (message == WM_PAINT) {
PAINTSTRUCT paint{};
BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const bool drawn = !world || !graphics.ready() ||
client.right <= 0 || client.bottom <= 0 ||
graphics.render(*world, scene_view(client.right, client.bottom));
EndPaint(window, &paint);
const auto frame = prepared_frame;
if (painting_scene) { ++frame_requests; repaint_pending = true; ValidateRect(window, nullptr); return 0; }
FlagScope painting(painting_scene);
PaintScope paint(window);
#ifdef SETTLEMENT_FRAME_TEST
if (frame_test_during_paint) frame_test_during_paint();
#endif
const auto parent = GetParent(window);
RECT viewport{}; GetClientRect(window, &viewport);
if (viewport.right <= 0 || viewport.bottom <= 0) return 0;
if (!frame_visible(parent) || !IsWindowVisible(window) || !frame || !frame->content) return 0;
const bool drawn = !graphics.ready() || graphics.render(frame->content->geometry, frame->view);
if (!drawn) {
graphics.reset();
const auto parent = GetParent(window);
layout_scene(parent);
invalidate_scene(parent);
}
@@ -2740,7 +2909,9 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
apply_interface_scale(window, read_interface_scale());
show_title_screen(window, true);
refresh_lan_controls(window);
viewer_destroyed = false;
SetTimer(window, timer_id, 60, nullptr);
SetTimer(window, frame_timer_id, 16, nullptr);
return 0;
}
case WM_DRAWITEM:
@@ -3090,6 +3261,8 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
}
break;
case WM_TIMER:
if (viewer_destroyed) return 0;
if (wparam == frame_timer_id) { sample_frame(window); return 0; }
if (wparam == timer_id) {
pump_session(window);
return 0;
@@ -3097,7 +3270,12 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
break;
case WM_ERASEBKGND:
return 1;
case WM_SHOWWINDOW:
repaint_pending = true;
invalidate_scene(window);
break;
case WM_SIZE:
invalidate_scene(window);
if (showing_title) {
RECT client{};
GetClientRect(window, &client);
@@ -3108,28 +3286,29 @@ LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lp
InvalidateRect(window, nullptr, FALSE);
break;
case WM_PAINT: {
PAINTSTRUCT paint{};
HDC target = BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const int width = client.right - client.left;
const int height = client.bottom - client.top;
HDC buffer = CreateCompatibleDC(target);
HBITMAP bitmap = CreateCompatibleBitmap(target, width, height);
HGDIOBJ old_bitmap = SelectObject(buffer, bitmap);
if (showing_title) title_screen.draw(buffer, width, height, placement_message);
else draw_world(buffer, width, height);
const RECT& dirty = paint.rcPaint;
BitBlt(target, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top,
buffer, dirty.left, dirty.top, SRCCOPY);
SelectObject(buffer, old_bitmap);
DeleteObject(bitmap);
DeleteDC(buffer);
EndPaint(window, &paint);
sample_frame(window);
const auto frame = prepared_frame;
if (painting_main) { ++frame_requests; repaint_pending = true; ValidateRect(window, nullptr); return 0; }
FlagScope painting(painting_main);
PaintScope paint(window);
RECT client{}; GetClientRect(window, &client);
const int width = client.right, height = client.bottom;
if (viewer_destroyed || !IsWindowVisible(window) || IsIconic(window) || width <= 0 || height <= 0) return 0;
PaintBuffer buffer(paint.dc, width, height);
if (!buffer) { ++frame_requests; repaint_pending = true; return 0; }
if (showing_title) title_screen.draw(buffer.dc, width, height, placement_message);
else if (frame) draw_world(buffer.dc, *frame);
else FillRect(buffer.dc, &client, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
const RECT& dirty = paint.paint.rcPaint;
BitBlt(paint.dc, dirty.left, dirty.top, dirty.right - dirty.left, dirty.bottom - dirty.top,
buffer.dc, dirty.left, dirty.top, SRCCOPY);
return 0;
}
case WM_DESTROY:
viewer_destroyed = true;
KillTimer(window, frame_timer_id);
KillTimer(window, timer_id);
prepared_frame.reset();
lan->leave();
graphics.reset();
if (dock_font) DeleteObject(std::exchange(dock_font, nullptr));
+6
View File
@@ -2,6 +2,8 @@
Текущий план разработки расположен в [PLAN.md](../../PLAN.md). Ниже сохранена история предыдущего этапа интеграции.
Программная приёмка M01 завершена на `4bac17d` для Windows x64 под Wine. Проверены потактное воспроизведение, перенос и возврат имущества, исторические сохранения, управление заказами, оба профиля правил, совместимость с прежним клиентом в обеих ролях и кадры во время ожидания. Пять исполняемых наборов прошли полностью. Для M02 доступны подтверждённые границы мира, сеанса, команд, сохранений и отображения. [Результаты M01](../plan/milestones/M01.md#приёмка-реализации-m01) · [Экономика и кодек](tasks/M01-V14.md) · [Сеть и клиент](tasks/M01-V15.md)
As of 2026-12-02, the baseline is `74b89ae` on `chore/integrate-void-library`. The tracked checkout was clean at discovery. The project targets Windows x64, MSYS2 UCRT64 and Direct3D 11.
The user approved pinning Void to `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, adopting Binary and Core for saves and LAN, and migrating the reflection suites to Void Testing. The Windows build uses CMake 4+ and GCC 16. Use a configurable agent with Astra 6.2 XHigh for planning and independent review and Sol 6.2 XHigh for implementation, as approved by the user.
@@ -95,3 +97,7 @@ wine /tmp/stoneheart-milestones.xprJ2SVp/windows/settlement_core_tests.exe --tag
Клиент Windows в `db0a872` обрабатывает действия игрока по квитанциям владельца и рисует из неизменяемого снимка. Три отдельных процесса под Wine проверили создание партии, паузу в меню и окне выбора файла, запись, современное и прежнее сохранения и отказ при повреждении файла. Отдельно проверены подтверждение разбора при смене партии, сохранение гостевой колонии после неудачного переподключения и возобновление тактов после восстановления. В общей сборке прошли 122 теста ядра, 9 LAN и 10 клиента. [Клиент S18](../plan/systems/S18.md) · [Проверка с обеими родительскими ветками](tasks/M01-V10.md)
В `37fb6a8` объединены проверяемая передача всего груза одной остановки и выбор правил на титульном экране. Игрок может создать поселение с поэтапной сборкой кровати либо с рецептом из одной доски. При открытии сохранения восстанавливается его собственный набор правил. Испытание настоящего окна проверило оба выбора мышью и клавиатурой, файл и продолжение из нового процесса. В общей сборке под Wine прошли 136 тестов ядра, 9 LAN и 14 клиента. [Загрузка и инвентарь S06](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/11) · [Клиент S18](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/13) · [Совместная проверка](tasks/M01-V12.md)
В `048268a` две настоящие рабочие задачи завершаются в противоположном порядке. Во всех 24 воспроизведениях победитель спорной заявки и байты состояния совпали с последовательной партией. При загрузке более старого мира запоздалый результат не изменил новую партию. Windows x64 под Wine прошла 141 тест ядра, 9 LAN и 14 клиента. [Проверки S21](../plan/systems/S21.md) · [Интеграционная проверка](tasks/M01-V13.md) · [Управляемый порядок завершения в VoidLibrary](https://git.faumaray.com/Void/Library/issues/15)
В `455630f` камера отвечает на колесо мыши и перетаскивание, пока симуляция или запись файла задержана. Проверка настоящего окна сравнила пиксели и байты контрольной точки, воспроизвела замену мира между опросом и рисованием и проверила сохранение прежнего кадра. Под Wine прошли 141 тест ядра, 9 LAN, 14 клиента и отдельное испытание кадра с видимой цепочкой D3D11 и WARP. Проверка в нескольких процессах также подтвердила выбор и загрузку обоих рецептов кровати. Частота кадров на физическом Windows-ПК ещё не измерена. [Рендерер S17](../plan/systems/S17.md) · [Совместная проверка](tasks/M01-V13.md)
+52
View File
@@ -0,0 +1,52 @@
# Audit deterministic completion evidence and immutable presentation frames
Task ID: M01-V13
Role: astra_reviewer
Status: READY
## 1. Context and baseline
S21-01 sibling s21 at 66af7c5 with new optional success hook and actual replay/fault barrier tests; branch final pass imminent. S17-01 sibling s17 same base with immutable packet/render caching and test target in progress. Original contracts S21-01/S17-01 and preflight F9/P6. Root cumulative currently 5a64a27 includes S18-02 profile chooser.
## 2. Objective and deliverables
Review CPU observer/real replay/diagnostics and independent GUI presentation as separate completed components and later combined integration. Send all actual blocking findings immediately.
## 3. Scope and non-goals
S21 worker adapter and tests/diagnostics/docs; S17 frame packet creation, D3D mesh/upload, lifetime/timer and actual test path. S06 custody15 beyond scope except future compatibility noted.
## 4. Files to inspect
Inspect actual tracked/untracked files and exact contracts in siblings. S21 world.hpp/world.cpp stage layout, WorkerPool submit/admit, tests/executor/replay/runtime, new diagnostics, end-to-end old corpora and logs. S17 actual Win32 handlers, scene packet and D3D, tests/viewer_frame_smoke.cpp, CMake, involved S18 session/GUI, Win32 smoke and docs.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/remote posts/other agents or Serena switch; siblings outside root graph require direct source. Check diff --check and new source separately.
## 6. Implementation or investigation approach
S21 success-only invocation (void/value/reference/move-only, throws, overload and before_submit/before_execute failure), original no-hook semantics and capacity. Validate opposing actual completions (two real candidate calculations, separate driver/hook release), lower ID winner, serial berry claim vs parallel advancement, no flakiness/deadlocks, stale load barrier and modern Current14, domain mismatch reports and tests incl byte fallback; inspect fixture/scoped source and actual logs.
## 7. Interfaces and data contracts
S17 after ready marker verify one immutable prepared packet held across nested callbacks even during release/install, candidate not sampled while changing before consumed Replaced, owned overlays and HUD, true camera-only reuse of prepared physical geometry and GPU upload keyed over all visuals incl reset, no extra work hidden/resized/destroyed; original camera input, GUI titles/profile and normal LAN/events still work. Check actual settled tests including two real windows, blocked file/owner, saved content, offscreen/native fallback and helper includes.
## 8. Dependencies and integration
Stage A S21 ready first; stage B only on finished status, separate integrated approvals requested later. No sign-off until actual cross-component evidence and fixes are available.
## 9. Edge cases security and performance
Pay particular attention to return category/dangling references, accidentally recording pre-completion, capacity1 coordinator deadlock, exceptions in optional hook, tests changing data outside owner. For S17 camera/cursor geometry keys, offscreen rendering and clipping/nested frames, pending parent/child window messages, backend recreation and save/peer replacement while rendering. Do not equate Wine with native Windows.
## 10. Acceptance criteria
1. Separate READY/CHANGES_REQUIRED per component. 2. State source/trigger/severity and corrective acceptance per defect. 3. Verify actual logs with issue #15 link and stable old corpora, new frame target and prior GUI smoke. No unsupported physical 60fps claim.
## 11. Verification commands and evidence
Use git -C <wt> rev-parse/status/diff --check; read new files and surrounding actual consumers. In /tmp/stoneheart-milestones.xprJ2SVp inspect s21-replay-* and s17-frame-* logs and harnesses once supplied. Eventual merged refs and logs will be appended.
## 12. Constraints and stop conditions
Check actual completed source, no early approval of another component. No source/branch/Gitea changes/children. After corrective commit re-audit relevant behavior per root instructions.
## 13. Authorization and decisions
User authorizes all milestone/system development and Gitea, root owns all external operations; published reusable missing completion test support upstream #15 and existing publication issue #5.
## 14. Return format
Return M01-V13 S21/S17 independent findings, inspected source/logs/limits, then integrated recheck when supplied.
S21 branch `ef980af` passed component review. Integrated root commit `048268a` has parents `5a64a27` and `ef980af`; inspect `m01-replay-{build,ctest}.log` and check its actual merged adapter, registered suites and unchanged core/GUI. S17 code and docs have also frozen in the sibling worktree at the original base plus working source. Read the actual committed-path smoke source, all tracked edits, and `s17-frame-*` logs. Verify the corrected pre-Replaced fence and stable rendering/cache/lifecycle conditions before branch approval.
Final S17 integration `455630f` joins reviewed `1cf8bd0` and `e9e7e82`. Cross-check S18 title/profile/host eligibility and S17 packet replacement, timer, GPU and cleanup against both parents. The build, verbose four-target CTest and separate multi-process real profile smoke are in `m01-frame-build.log`, `m01-frame-ctest.log` and `m01-frame-profiles.log`.
+50
View File
@@ -0,0 +1,50 @@
# Audit live item ownership and checkpoint migration across real game actions
Task ID: M01-V14
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Independent review on root M01 at 2211144 vs a47e850. S06+S15 share ccd50ec plus validated phase/ID changes 4f4c038. Contracts M01-P5/F8, S06-03, S15-04 and docs/plan/custody.md. Real saved old v1/raw<=13, v2/raw14 historical f6493e2 world fixtures, new v3/raw15. One pending correction deduplicates consumed effects when one site input merges pooled supplies and rejects invalid duplicate result rows (root supplies refs later). User requested real upstream gaps, #7 and #8 exist. S04/S16/UI are independently reviewed.
## 2. Objective and deliverables
Review full ownership/ID/transaction/replay invariants and raw15/checkpoint3 encoding, real migration + strict malformed input behavior. Send source/trigger/scope for high-confidence defects early. Recheck repaired areas and eventual integrated evidence prior to publication.
## 3. Scope and non-goals
Only M01 S06 physical stock/reservation/transfer logic, receipt lifecycle, balances, migration/projection, bounds/format and validation. Cross S04/S16 entry when determining effect/reservations but leave UI/transport review to peer. No code, tests, performance redesign or external effects.
## 4. Files to inspect
Inspect real 2211144 vs a47e850 delta in engine/include/settlement/core/{world,custody,inventory_transaction,checkpoint}.hpp, engine/src/{world,custody,inventory_transaction,world_save,checkpoint}.cpp, tests/{custody_tests,custody_migration_tests,checkpoint_tests,snapshot_tests}.cpp and tests/fixtures/custody_v14/{capture.cpp,fixtures.hpp,README.md}; M01-P5,F8,S06-03/S15-04. Look at unchanged scheduler/job/cache and replay owners as needed. S06/S15 sibling and stable historical f6493e2 source in /tmp/stoneheart-milestones.xprJ2SVp/fixture-v14. Actual logs in same temp directory.
## 5. Write ownership and coordination
Write scope: none
No mutations, builds (root/implementers run builds), Git/Gitea changes/shared project switches or children. Review real sources, not worker summaries. Root M01 graph identity matches main worktree, check freshness/file coverage; direct source for parsed gaps and all siblings.
## 6. Implementation or investigation approach
Trace actual grant, depletion, admission, meal, cancel while fetching/working/partial, split/merge/delivery, final generated material, retired stacks IDs and replay. Verify preflight of count/capacity/exhaustion incl multi-actor effects plus before allocating memory, no state changes after late failure, no duplicate issue on retries. Audit request key shape/cache/misses/highwaters for exactly-once and ring wrap despite losing prior receipt after retirement; differentiated source/dest refs across ops. Clarify caller-owned scheduler advance vs recoverable repeat endpoint; look for actual repeated/public invocations causing duplicate effects. Validate balance equation and max 5 material/8 claims/11 effects vs true recipes and multiple stores.
## 7. Interfaces and data contracts
Check current/legacy save schema pairs, bounded typed extensions/no trailing bytes/digest, active vs retired references, ID allocator ordering, source/sink balances, strict phase/live ownership/claims/cache and backed capacity, genuine historical Working & routes & generic jobs, mixed/canceled blocked/suspended/unrepresentable legacy error before writing. Distinguish representable historical migration with Opening from true current state. Confirm 4096 fixed retained results and canonical order despite physical wrap. Normal file/guest/corrupt loads preserve old world. Verify resource-limited loops/allocations/drift and that doc performance describes actual configurations.
## 8. Dependencies and integration
Component baseline 4f4c038 and root 2211144 are stable snapshots; sibling latest duplicate-row/consumption adjustments are ongoing and not pre-approved. Report first pass immediately, wait for frozen fixes and final root acceptance. S21-02 will incorporate Current15 authoritative replay separately; original raw13 corpora remain.
## 9. Edge cases security and performance
Watch valid images silently rejected at supported count/phase, malformed modern input creating economic value/alias, algorithmic overrun from untrusted huge small-on-wire counts, pre-commit partial effects, underflow on pending timer0, MAX issuance and persisted retired ID lookup. Only high-confidence findings with source & concrete realistic reproduction/impact. Native Windows limits noted.
## 10. Acceptance criteria
1. READY or changes required for both core and format, with precise counterexample and verification. 2. State source evidence and inspected logs of authentic schema tests, exact old outputs across modes and actual scoped benchmark/limits. 3. Audit zero-byte legacy refusal and current persistence consistency. 4. Final verdict on supplied frozen fixing ref and integrated root evidence only.
## 11. Verification commands and evidence
Use git diff --check and git show/diff a47e850..2211144 for relevant paths; git log for history. Probe logs /tmp/stoneheart-milestones.xprJ2SVp/s06-custody-*-final.log, *compare.log, s15-custody-{strict*,*migration*,*ctest*}.log, m01-custody-*.log. Read actual fixtures/capture.cpp and origin 2 corpora + metadata if needed, note no tests run yourself. Follow root graph coverage skill and direct reads for sibling files.
## 12. Constraints and stop conditions
No additional models/tests or reproduction that mutates checkout. If same defect already under repair, mention coverage and wait for actual new source. Do not equate reported passing tests with independent correctness or native Windows. Report unresolved exposure rather than accepting a moving target.
## 13. Authorization and decisions
User authorizes all milestones, normal pushes and filing real library gaps; only root owns all external operations. Grants/receipts business contract in docs/plan/custody.md, retain functional old projection for normal worlds.
## 14. Return format
Return M01-V14 staged defect-oriented findings with citeable file/line/domain, correction and verifiable example; state final actual refs/outcome only after recheck.
Final economic and codec candidate `e348a42` incorporates S06 `120db6c` and S15 `d613b73`/ `67fba6e`. It is merged into M01 `86b5fb3`, followed by documentation-only `2ba4b3f`. Inspect the actual canonicalization and issuer verification, live/terminal disjointness and operation-specific terminal states, acquisition/hauling/working/tending/meal/return phase and source/capacity rules, validated historical retained routes and ring. The final migration logs `s15-custody-final-{build,migration,ctest}.log` contain the 14 authentic and re-signed test cases. The root will attach the final combined game/transport evidence.
+50
View File
@@ -0,0 +1,50 @@
# Audit live order controls, peer cutoff and integrated viewer recovery
Task ID: M01-V15
Role: astra_reviewer
Status: READY
## 1. Context and baseline
Independent review at M01 merged 2211144 parents a47e850 + c183de1, plus 9bc52ea that includes root test fix 596b491. S04 control branch 13b4665, S16 final 6cc59b4 plus integrated data c183de1. S17 was independently accepted at 455630f. New S04 typed SessionPayload, UI and real Win32 menus; S16 gates raw13/protocol11 hosting on stable represented state and handles queued bytes/outstanding receipts; V14 peer owns core/codec details. S21-02 modern replay will be added to final source.
## 2. Objective and deliverables
Read the complete actual cross-branch changes from both parent sides. Check authenticated command idempotency, exact target and presentation generation, all legacy host/rules/wire and old-binary handling across same-epoch cancellation, and S17 snapshot HUD/frame lockstep. Later issue final integrated verdict when all repaired sources and logs provided.
## 3. Scope and non-goals
Review modern cancel/resume session/GUI, S16 legacy compatibility admission/drop, S18 test fence, integration boundaries including S17. Do not duplicate exhaustive core/format inside V14; identify cross-boundary contract flaws and relay either owner.
## 4. Files to inspect
Inspect engine/include/settlement/core/{command_dispatcher,world,simulation_runtime}.hpp, engine/src/{command_dispatcher,simulation_runtime,custody}.cpp, app/{lan_session_win32,viewer_session,viewer_win32,d3d_scene_win32}.cpp, lan_session.hpp and lan_wire.cpp, tests/{production_commands_tests,production_controls_tests,lan_tests,viewer_session_tests,viewer_frame_smoke}.cpp, S04-02/S16-03 and M01-V13, CMake and actual logs; preserve exact S18 profile/held world behavior. At final recheck inspect S21-02, actual current-canonical comparisons and instructions.
## 5. Write ownership and coordination
Write scope: none
No mutations/builds/commits/Gitea/children or shared Serena switching. Use root graph verified identity plus direct actual sources/missed lines; branch specific source via read-only git show/diff.
## 6. Implementation or investigation approach
Inspect complete command admission and dispatch sequencing through trust gates, ledger conflict/replay, stale world/incarnation/city, refusal revision and pending local async UI. Follow open modal/quick selections, exact durable ProductionId, all orders/same cell after paging and generation/connection replacement, guest hide/synthetic action, actual game handler uses active frame. Trace protocol11 hello/auth/input/partial or queued output and completion from both standalone World and Runtime; active default 32×32 exact profile, actual legacy-representable predicate with nonprojectable mixed returns/suspended, ability to continue locally, earlier admitted results retained, later queued command refused. Question race windows at message receive/send/completion vs changing latest() when cancellation occurs in same epoch.
## 7. Interfaces and data contracts
Old protocol unchanged, authentication maps to authoritative context. No leaked stale/partial snapshot or receipt or reapplication after disconnect; host still healthy, rejoin when eligible. User displays precise refusal/return/wait and preserves old title/profile choices, S17 immutable frame synchronization, null replacement fencing and nested modal. Test helper new bounded flush_owner retries documented RuntimeAdmission::Busy but must still assert Faulted, not mask regressions. Consider classic tests that assert immediate admission despite try_to_lock.
## 8. Dependencies and integration
At a47e850 S17 + S21 accepted. Actual 2211144 integrated core&UI+protocol. Root fresh CTest prior to helper has 5/5 targets. 9bc52ea includes helper with 24 successive viewer-suite executions in S18. Stage final includes newest core duplicate-row fixes and S21 modern replay; root appends exact ref/evidence before final verdict.
## 9. Edge cases security and performance
Pay attention to outstanding owner completion survives peer drop, replacing/reconnection with distinct session & same player ID, partially drained FIFO bytes vs disconnect handling, state sampled before committed result, race between readiness and send, actual old binary cross-play both ways. Aggregate genuine observables rather than promising TCP can recall bytes already sent. Prior flaky test must be protected by legitimate Busy handling and bounded wait.
## 10. Acceptance criteria
1. READY or changes required for S04,S16 and their S17/S18 integration independently, reproducible trigger and correction for defect. 2. Verify evidence for six real normal window controls, stale modal, real guest, old compiled two-way interop, held frame+file, prior variant profiles, actual previous signs. 3. Final merged source/CTest consistency, no unsupported native Windows performance/real LAN claim. 4. Review last S21 replay data when new ref provided.
## 11. Verification commands and evidence
Use git diff --check <relevant range>, git show --stat, actual files and surrounding calls. Logs in /tmp/stoneheart-milestones.xprJ2SVp/ s04-cancel-ctest-complete.log, s16-custody-{interop,target-ctest,legacy-corpus}.log, m01-custody-{build,ctest}.log, s18-fault-fence-repeat.log, m01-frame-profiles.log. Look at real harness/fixtures, not summaries. After appending final ref inspect corresponding logs; never require additional physical PCs to certify a Wine run.
## 12. Constraints and stop conditions
No external operations or peer implementation, tests maintained by root/workers. Report actionable actual defects early; if correction only pending on one surface, report other subsystem separately. Never approve unseen final changes.
## 13. Authorization and decisions
User authorized all milestones, branches and Gitea, root owns remote side effects. Existing product P5/F8 authorize cancel/resume and old-peer fence; full contract in docs/plan/custody.md and S04/S16 work orders.
## 14. Return format
Return M01-V15 separate source-anchored component verdicts and after final root recheck combined verdict; identify code/evidence refs and limitations.
Final M01 combined candidate `4bac17d` includes the S16 conditional-admission repair `447a1cf`, S17 full-custody frame assertion `f6402eb`, S21 current-canonical replay `a347337`, S18 bounded fence `596b491` and V14-reviewed economics `e348a42`. Read `s16-published-admission-{before-test,after-test,ctest,interop}.log` for the deterministic real-peer race, successful compatible retry, already admitted work and original binary exchange. Review the publication mutex and stale/Busy/null/fault paths in the actual changes. Combined build and five-target CTest are in `m01-exit-{build,ctest}.log`; independent latest executable GUI/profile, original/current interop and both old byte corpora are recorded in `m01-exit-*.log`. [Library proposal](https://git.faumaray.com/Void/Library/issues/16)
+48
View File
@@ -0,0 +1,48 @@
# Prepare immutable client frames and present camera changes independently
Task ID: S17-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated system/s17-rendering at 66af7c5 includes reviewed S18-01 client. app/viewer_win32.cpp has a 60 ms session/network timer, parent+child paints retain an old pointer but still dereference changing globals and SceneView spans live blueprint vectors. D3DScene::render presently regenerates flat geometry even on camera-only paints. S18-02 alters title/host gates and bed text in another worktree. M01-P6/F9 advise independent dirty-only 16ms frame sampling and strict install boundary.
## 2. Objective and deliverables
Implement S17-W01 normal Windows entry: scene and HUD consume one immutable prepared client packet including owned overlays, camera and pinned snapshot; camera frames can render while 20 Hz world step or file/load busy. Coalesce invalidation and reuse geometry on view-only changes.
## 3. Scope and non-goals
Existing flat game map, hardware Direct3D/WARP and error HUD only. No M02 chunk meshes, new camera settings, render thread, input/protocol changes or 60fps hardware claim. Preserve current viewer/rooms/blueprints/colony UX and all baseline harnesses.
## 4. Files to inspect
Inspect app/viewer_win32.cpp scene_window and main WndProc, WM_TIMER/PAINT/DESTROY, camera wheel/drags, pump_session, draft/room render, title/minimize/resize, D3DScene in app/d3d_scene_win32.hpp/.cpp, map_camera, actual /tmp/stoneheart-milestones.xprJ2SVp/client_handlers_smoke.cpp. CMake/tests WARP/capture availability, app/viewer_session member changing_world/poll_changes.
## 5. Write ownership and coordination
Write scope: app/viewer_win32.cpp (drawing, camera invalidation, timer/pump sequencing only); app/d3d_scene_win32.{hpp,cpp}; NEW app/viewer_frame.hpp/.cpp if useful; NEW tests/viewer_frame_smoke.cpp; CMakeLists.txt limited to registering frame test/owned sources; docs/plan/systems/S17.md
Other branches own title/profile and stock; do not revert others' changes or switch Serena. Exclusive isolated s17 checkout. No Git/remote operations, further agents or unrelated app changes.
## 6. Implementation or investigation approach
Prepare owned immutable presentation data on UI thread, derive HUD/selection/cursor/room validity and existing geometry from exactly one accepted world and copied relevant overlay state. Avoid borrowed spans into mutable UI across nested WM_PAINT or an overwritten single scratch buffer. Main and child paint each pin packet locally; no global world deref to render. Frame timer and camera/window invalidation independently drive dirty visible frames; keep existing 60ms LAN/control pump. While session->changing_world() keep prior presented world/frame including null, even if runtime.latest has already installed newer; release new world only after pump consumes Replaced, resets overlays/camera and updates identity. Guest/epoch transitions likewise cannot mix old work and new overlays. Sample ordinary healthy revisions with stable client identity.
## 7. Interfaces and data contracts
Keep one current flat geometry version keyed by world identity/snapshot and all overlay/selected/cursor/BuildingView inputs. Camera-only or size-only change regenerates only camera/projection constants; account for resize/device/backend reset invalidating GPU upload. Explicit immutable geometry ownership shared by packets retained by readers; stale packets can render consistently even after newer packet then reuse correct upload. No work on hidden/title/minimized/zero sizes. On restoration or failed/recreated backend request fresh frame. No busy loop or full mesh rebuild/upload for unchanged view. Preserve existing D3DScene::render callers or update only within ownership. RAII for paint/DC and timers/shutdown.
## 8. Dependencies and integration
Integration root will merge separately from S18 title+host. Avoid code dependencies on S06 custody changes, S21 hooks. Reuse Void owner snapshot (#5) and current D3D facilities; GPU resource ownership remains in renderer. Do not copy fixture include paths from other worktrees into repo. There is no GDI world renderer to invent in this scope.
## 9. Edge cases security and performance
Check nested dialog/WM_PAINT while replacements happen, applied room/draft vector lifetime, same-world rollback or new UUID taking same tick, mouse cursor remains coherent re camera zoom and changes may legitimately affect preview geometry, no blocked owner/file calls on presentation thread. Render failure presents current HUD error and recoverable state. Graphics-test availability must be explicit, tests need bounded cleanup and skip/report only genuine backend unavailability.
## 10. Acceptance criteria
1. Durable actual regression target (repo-relative source paths) observes fresh render and actual input camera/zoom/drag while owner worker and file writer blocked; original tick/canonical snapshot preserved. 2. Frame timer alone advances camera frame without event timer. 3. Held old packet remains renderable with old overlays across nested install; new packet resets correctly; exact saved snapshot content. 4. Geometry/upload reuse on pure camera/unchanged, title/hide/minimize/0-size/restore/destruct, device reset semantics; WARP/offscreen capture/real UI as available. 5. All original UI, core and LAN checks still pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-frame-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. CTest -V, git diff --check; source actual Wine GUI/D3D environment from env.sh. Add/verify focused new real frame smoke and existing UI regressions (three-process/temp harness with isolated LOCALAPPDATA, no user data). Use s17-frame-* logs and report observed device/driver.
## 12. Constraints and stop conditions
Stop if independent-frame scheduling would require replacing app/renderer architecture or mutating unrelated title/guest controls. Ask root on genuine scope change; after two failed same-cause fixes escalate with evidence. No M02 feature additions, Git/remote or children.
## 13. Authorization and decisions
User authorizes complete roadmap on system/milestone branches. Root approved independent dirty-only 16ms sampling, immutable packet, one flat geometry generation and no unsourced performance claims. F9 requires explicit pre-Replaced candidate fence.
## 14. Return format
Return S17-01 READY or PARTIAL, actual owned changes/normal paths, packet/geometry lifetime, render/repaint file/worker evidence, exact logs/native limits. Send frozen smoke seam early.
+48
View File
@@ -0,0 +1,48 @@
# Prove deterministic arbitration under opposing worker completion orders
Task ID: S21-01
Role: astra_implementer
Status: READY
## 1. Context and baseline
Isolated system/s21-verification at 66af7c5. World assign_idle_agents calculates independent candidates for idle residents then assigns competing jobs in stable order. Meal claim is serial before parallel movement. Existing replay compares Current14 state for 1/2/6/12, last meal and mid-delivery plus capacity1; scheduler hooks currently before_submit/before_execute only. M01-P6/F9 request an observer of actual returns and readable divergence reports.
## 2. Objective and deliverables
Implement a minimal optional success observer in the real WorkerPool adapter, prove opposite actual calculation completions and deterministic arbitration, and report first divergence through domain facts tied to canonical bytes. Verify runtime install waits for outstanding work and fresh session fences stale results.
## 3. Scope and non-goals
WorkerPool instrumentation, tests and S21 verification docs only. No World scheduling/codec/receipt semantic changes, no synthetic exploit inputs or unrelated rendering/milestone changes. Native Windows hardware separate.
## 4. Files to inspect
Read engine/include/settlement/core/worker_pool.hpp, engine/src/worker_pool.cpp/world.cpp (actual partitions and meal selection), runtime source, tests/{executor,replay,runtime}_tests.cpp, M01-P6/F9 and S21. Void FuturePool/Testing at pinned clone and issue #15.
## 5. Write ownership and coordination
Write scope: engine/include/settlement/core/worker_pool.hpp; tests/executor_tests.cpp; tests/replay_tests.cpp; tests/runtime_tests.cpp; NEW tests/replay_diagnostics.hpp only if useful; docs/plan/systems/S21.md
Isolated s21 only. Other agents own sibling source. No CMake mutations, shared project switch, children/Git/remote changes. Root integrates.
## 6. Implementation or investigation approach
NEW optional WorkerPoolOptions::after_execute(index), success-only after callable returns before result future ready. Account for optional observer alone in submission indexing. Preserve original no-hook path and hook/call behavior for void, values, lvalue refs, move-only closures/results and exceptions on worker + inline fallback. Observer exceptions reach corresponding future; no throwing destructor. Test using separate driver and bounded CV gate for two known submissions; release on all exit paths. Only block task B until A has actually returned (post hook), then reverse. Never wait for all tasks/lanes or rely on sleeps/scheduling chance.
## 7. Interfaces and data contracts
Fresh two-resident/one real reachable WorkJob scenario, opposite completion traces must be observed even with max_admitted1 on a separate driver, 2/6/12. Verify deterministic winner and each future state equal serial canonical Current14. Last berry serial claim test/cargo/movement preserve independent one-winner evidence, do not claim parallel meal arbitration. Add old worker held, queue same-world earlier load, verify old view remains readable/install pending until drained, replacement identity fresh, old request rejected, current state intact after further fence.
## 8. Dependencies and integration
Test-local semantic reporting only when canonical byte comparison differs (existing Current14 encoder remains oracle). Include seed/scenario, attempt/tick, concurrency/schedule, load, stable first differing entity/property and expected/actual, command/receipt player/number/status/revision or byte-offset fallback. Actor/job/storage stack as owner plus type for current14; support absent/extra records. Test at least stock/job/command divergences individually and equal-case. Later body15 will extend this; don't introduce alternate persistence schema. Reuse existing helpers/tests.
## 9. Edge cases security and performance
Bound waits even on CI; each branch releases gates before destroying/joining pool; no assertion library calls from worker threads. Keep hook captures alive; no mutex while running user callbacks. When no selector installed, no new allocations/counters per job. Tested genuine Submit paths including inline. No simulated full native performance claim.
## 10. Acceptance criteria
1. Tests fail when completion acknowledgement incorrectly moves to start, schedules traces must be opposite and canonical states match. 2. Observer sees returned value/reference/void, exceptions incl hook and overload, callable ownership preserved. 3. Reload barrier stale work/commands and snapshot fencing checked. 4. Domain diagnostics exercised with expected entity ID/field/receipt context. 5. All CTest, corpus, focused tags and docs checks pass.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run CTest -V and --tag executor, --tag replay and --tag runtime under Wine; record s21-replay-* logs and commands. Old normal corpus should remain unchanged, use available trajectory probes as appropriate. Actual checks rather than latency claims.
## 12. Constraints and stop conditions
Stop if index pair cannot be tied to real first job-choice partition: identify actual code and adjust fixture, no pretend success. No global installation or unrelated changes. Two failed same-cause fixes escalate. No children/Git/remote writes.
## 13. Authorization and decisions
User authorizes complete M01 and separate S21 system branch; root approved test-only success observer and strict canonical oracle. [Void/Library completion test facility](https://git.faumaray.com/Void/Library/issues/15) documents the replacement test. Root publishes.
## 14. Return format
Return S21-01 READY/PARTIAL, bounded integration/worker semantics, branch files, tests with actual opposing traces/diagnostic cases/corpus, native limits.
+50
View File
@@ -0,0 +1,50 @@
# Compare authoritative custody state in journal and runtime replay
Task ID: S21-02
Role: sol_implementer
Status: READY
## 1. Context and baseline
S21 sibling at 3c7cc3c merges approved replay ef980af with provisional live World/codec 539cea0, later partner fixes will be included. tests/replay_diagnostics.hpp canonical and tests/replay_tests.cpp saved_state still choose Current14, tests/runtime_tests.cpp bytes currently defaults to Legacy13. Both projections drop custody15. S15 owns tests/snapshot_tests.cpp. Released S21 real opposite-order tests and prior hashes must still pass.
## 2. Objective and deliverables
Use current complete raw15 state for replay/owner snapshots and identify divergent item owner, stack/reservation/transfer/receipt/balance when those facts change. Exercise retained cancel/retry and continuation on 1/2/6/12. Keep intentional legacy13/14 compatibility fixtures and golden outputs as separate existing coverage.
## 3. Scope and non-goals
Only test replay/diagnostics and their S21 explanation. No changes to application World, protocol/codec, CMake unless unavoidable for existing registered suites, generator/M02 or unrelated tests. This is a contracted validation extension of S21-01 (M01-F8/F9).
## 4. Files to inspect
Inspect tests/replay_tests.cpp, replay_diagnostics.hpp, runtime_tests.cpp, tests/custody_tests.cpp and custody_migration_tests.cpp, engine/include/settlement/core/{world,custody,simulation_runtime}.hpp, custody.cpp, world_save.cpp, S06-03/S15-04/docs/plan/custody.md and S21. Read surrounding domain projections and fallback.
## 5. Write ownership and coordination
Write scope: tests/replay_tests.cpp; tests/replay_diagnostics.hpp; tests/runtime_tests.cpp; docs/plan/systems/S21.md
Isolated s21 only. You share checkout state with others in separate working directories; do not revert others or change other WTs/branches, shared Serena or any Git/Gitea state. Parent handles schema source seals.
## 6. Implementation or investigation approach
Centralize canonical save selection in the test helper to Current15 and apply it to current replay & runtime owner world equality paths, preserving any explicit legacy compatibility expectations. Extend first-difference report from real public immutable facts with stable entity/owner IDs: resident/storage/order input stack quantities/IDs, execution and active claims, admission/operation receipt keys and result outcome, material balance. Compare canonical bytes first and retain unknown/opaque byte fallback. Organize human-readable distinctions so stock change still reports stock, before a secondary balance if relevant. Do not construct huge diagnostic maps on equality.
## 7. Interfaces and data contracts
Consume Inventory::stack_id, Agent.execution and next_admission, ProductionOrder.input and suspended, World::item_balances(), custody_receipts() and public receipt/request/result. A public vector is a ring backing store; use key and true order only when authoritative, avoid exposing physical ring layout as game identity. No modifying private counters nor pointers into mutable shared data for assertions. Use a valid game action/migrated world with same historical projection but differing modern owner/receipts if possible (old projected world loaded vs originating modern).
## 8. Dependencies and integration
Real source base includes custody and codec; parent will furnish final stricter validation and zero-count terminal semantics as local commits. S06 owns normal domain fixtures S15 authenticated raw15/history; S21 owns comparison and divergent-entity diagnostics, runtime stale/reload, not another codec test. External library support references existing issue #15 real execution, #7 ids/#8 transfer only if relevant. No request creation.
## 9. Edge cases security and performance
Only derive proof from real accepted actions with invariant-valid states. Catch first divergence when original legacy projection matches despite changed durable facts; do not falsely flag a different ring backing index as a logical change. Preserve old positive-negative receipt/stale owner and reproducible opposing completion trace. Keep replay test runtime bounded (first compare bytes and build facts on mismatch only). Notify root early of genuine production defects.
## 10. Acceptance criteria
1. Current canonical captures include all custody state on real replay and after load; regression makes prior projection blind yet new one finds named entity/step. 2. Existing identity/stock/job/context and byte fallback still work. 3. Continue canceled in-flight durable cargo through checkpoint on serial/2/6/12, retained replay/conflict without physical duplicate. 4. Root can integrate while all registered tests, 24 actual completion traces and historical golden checks remain intact.
## 11. Verification commands and evidence
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s21-replay-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 <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Focus --tag replay and --tag runtime after build, full CTest -V, named /tmp/stoneheart-milestones.xprJ2SVp/s21-custody-*.log and git diff --check. Authentic raw13 corpora old-trajectory.bin + identity-compat-old.bin independently validated by S06; compare if behavior or underlying partner revisions change.
## 12. Constraints and stop conditions
No application edits, publishing, shared source checkout switch, new helper API into World or script internals just for diagnostics. If blocked by partner fix, obtain it through root while implementing independent diagnostics; report exact evidence. Review independent via root.
## 13. Authorization and decisions
Approved milestone/system work plus explicit exact-state replay and ID diagnostics from M01. Root keeps transient cross-branch commits local pending package acceptance.
## 14. Return format
Return S21-02 READY or PARTIAL with real base, owned diff, command results, source domain/id and regression observations, test runtime and external dependencies.
Worktree now at `e26b9c2` includes the stricter S06 validator and S15 zero-count terminal effects, count budgets and authentic migration/ring tests from `ccd50ec`. Begin on this combined source.
+8
View File
@@ -13,6 +13,14 @@
5. Ввести выбор совместимых модулей при создании мира и сохранить их версии и контрольные суммы. Определить контракт явного состояния скрипта и атомарного применения его предложений в [S19](../systems/S19.md). Внутренний сценарий с двумя клиентами проверяет общую поверхность команд до публичного кооператива M09.
6. Для механизмов потоков, бинарной записи и тестов проверить существующие возможности VoidLibrary по [матрице](../void-library.md). Для отсутствующей возможности найти или создать issue в Void/Library и привязать к локальной реализации. Конкретный API выбирать по проверенной версии библиотеки.
## Приёмка реализации M01
В Windows x64 Release `4bac17d` под Wine 11 прошли все пять исполняемых наборов. Они охватили 182 теста ядра, 17 LAN, 15 клиентского сеанса, 6 проверок управления заказами и отдельный тест окна Direct3D. В последовательном режиме и на 2, 6 и 12 исполнителях два контрольных файла прежнего прототипа совпали побайтово. Потактный тест современной партии также сравнивает владельцев стеков, резервы, идентификаторы передач, квитанции и балансы. В 24 запусках с перестановкой завершений результат совпал с эталоном. [Испытания воспроизведения](../../../tests/replay_tests.cpp) · [Независимая проверка](../../agent-workflow/tasks/M01-V15.md)
Сохранение в пути, отмена заказа и возврат части груза прошли через рабочее меню и авторитетный диспетчер. Формат контрольной точки 3 восстанавливает имущество и незавершённые работы. Для 13 подлинных сохранений формата 2 проверены следующие 80 тактов на каждой из четырёх конфигураций исполнения. В отдельном опыте остановили гостевой приказ между чтением снимка и постановкой в очередь. После несовместимой отмены на хосте номер приказа гостя и состояние мира сохранились. При обратном порядке ранее принятый приказ завершился. Первоначальная и новая сборки сыграли по протоколу 11 в обеих ролях. [Фикстуры прежних сохранений](../../../tests/fixtures/custody_v14/README.md) · [Проверка имущества и кодека](../../agent-workflow/tasks/M01-V14.md) · [Условный допуск в VoidLibrary](https://git.faumaray.com/Void/Library/issues/16)
Два профиля рецепта кровати проверены через настоящие элементы управления в отдельных процессах. Камера работала во время задержанной записи и незаконченного такта. Воспроизведены загрузка предыдущего состояния и отказ при повреждённом файле. Эти результаты подтверждают программные условия выхода в M02. Нативный прогон Windows, физическая сеть и измерение частоты кадров на целевом ПК ещё предстоят. [Кадр и пользовательский интерфейс](../../agent-workflow/tasks/M01-V13.md) · [Ветка этапа](https://git.faumaray.com/Lagg1ng/stoneheart_at_home/pulls/6)
## Первый переход с текущего клиента
### Потактный эталон прототипа
+1 -1
View File
@@ -32,7 +32,7 @@
Проверки с реальным ядром: [production_commands_tests.cpp](../../../tests/production_commands_tests.cpp) — повтор принятых/отклонённых результатов, конфликты вариантов и ID, границы контекста и прав, отмена до получения/в пути/на площадке, ожидание полного склада и возврат всех материалов, продолжение частичной кровати и установленного станка, публикация runtime. [production_controls_tests.cpp](../../../tests/production_controls_tests.cpp) создаёт настоящее Win32-окно с Direct3D, выбирает клетку обычными сообщениями мыши, проходит меню клавиатурным вводом через `WM_TIMER`, проверяет квитанции обоих действий, выбор точного ID и доступ ко всем 35 заказам на одной клетке, смену мира во время меню, подключённого гостя LAN 11 и причину ожидания возвращающегося жителя. Каждый запуск окна использует отдельный временный каталог пользовательских данных.
На объединённом ядре S06 и кодеке S15 выполнена сборка Windows x64 GCC 16.2; полный `ctest -V` под Wine 11 прошёл 4 исполняемых набора: 160 core, 4 LAN, 14 viewer-session и 6 Win32 controls. В предыдущем полном прогоне один существовавший тест восстановления после сбоя (`viewer_session_tests.cpp:363`) однократно не получил ожидаемый допуск синхронизации; отдельный повтор и итоговый полный прогон прошли. Нативные Windows и MSVC не проверялись.
Полный `ctest -V` для Windows x64 GCC 16.2 под Wine 11 выполнил 160 тестов ядра, 9 LAN, 14 клиентских сеансов и 6 проверок управления в настоящем окне. В одном предыдущем прогоне тест восстановления после сбоя получил временный отказ при попытке синхронизации. Ветка S18 добавила ограниченное ожидание допуска. После этой правки клиентский набор прошёл 24 раза подряд. На физической Windows и под MSVC эти проверки ещё предстоят.
## Данные и владение
+26 -3
View File
@@ -1,10 +1,33 @@
# S17. D3D11-рендеринг, камера и визуальное состояние
Статус — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
Статус — S17-W01 реализован и проверен в Windows x64/Wine; ожидает независимой приёмки. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
## Исходное состояние
`D3DScene::render` принимает `const World&`, заново собирает геометрию карты, ресурсов, построек и жителей, загружает её и вызывает D3D11. `SceneView` хранит положение камеры, выбор и предпросмотр. Вызов происходит из `WM_PAINT`, а симуляция — из `WM_TIMER` того же окна. Основой нового клиента остаётся имеющийся Win32/D3D11-путь. [Интерфейс сцены](../../../app/d3d_scene_win32.hpp) · [Текущий рендер](../../../app/d3d_scene_win32.cpp)
S17-W01 сохраняет существующую плоскую карту и Win32/D3D11. `PreparedFrame` удерживает один принятый `World`, параметры камеры и области, копии чертежей/комнат, выбор и предпросмотр, готовую CPU-геометрию, строки HUD и собственный шрифт. Главная и дочерняя `WM_PAINT` сначала удерживают весь пакет, затем рисуют без обращения к живому миру или векторам редактирования. [Подготовка кадров](../../../app/viewer_win32.cpp) · [Интерфейс сцены](../../../app/d3d_scene_win32.hpp)
Отдельный таймер 16 мс выбирает актуальный кадр только для видимой ненулевой игровой области и при изменениях. Таймер управления/LAN остаётся 60 мс, владелец симуляции — 50 мс. Это частоты обслуживания, а не утверждение о физической частоте экрана. Камера и размеры не пересобирают плоскую CPU-геометрию; неизменённая геометрия повторно не загружается на GPU. Размер render target, пересоздание устройства или возврат к удержанному старому пакету требуют соответствующей загрузки.
Ключ геометрии учитывает удержанный снимок мира, курсор и его допустимость, переносимый объект, жителя, все поля чертежей/комнат и предпросмотра, режим крыши/стен и переносимую комнату. Сравнение удерживаемых объектов снимков различает новые публикации даже при одинаковом такте. Пакеты владеют CPU-геометрией совместно; у renderer остаётся только текущая GPU-загрузка. Старый пакет можно отрисовать после нового или после сброса backend.
Пока `ViewerSession::changing_world()` истинно, прежнее представление сохраняется, включая отсутствие мира. Фоновая публикация между проверкой future и чтением мира не выпускает кандидата в UI. Только обработанный `Replaced` сбрасывает чертежи, выбор и камеру перед подготовкой замены. Подготовка приостанавливается внутри обработки событий и отрисовки; вложенная инвалидизация остаётся запросом следующего кадра. `BeginPaint` и временные DC/bitmap имеют RAII, backend удерживается до возврата из `Present`. При отказе остаётся HUD ошибки с восстановлением через повторный вход из меню; резервного GDI-рендера карты нет.
### Проверка S17-W01
Постоянная CMake/CTest-цель `settlement_viewer_frame_smoke` использует относительный include реального обработчика и настоящие главное/дочернее окна. [Тест](../../../tests/viewer_frame_smoke.cpp) проверяет:
- колесо и оба перетаскивания с изменением кадра/пикселей, когда настоящий рабочий `World` и запись файла `WriteStage` удерживаются барьерами; таймер событий в этой части не вызывается;
- неизменность полного канонического снимка и такта, повторное использование CPU/GPU-геометрии, побайтовое равенство сохранённого checkpoint исходному `World` и метаданным;
- отдельный удержанный файловый reader, старые комнаты/чертежи после редактирования, вложенные paint и незатерянную инвалидизацию;
- публикацию установки после `poll()` до чтения мира, вложенные paint в этом промежутке, сохранение прежнего/нулевого представления до `Replaced`;
- скрытие, минимизацию, меню, восстановление последней публикации, изменение размера, нулевую область, ошибку и повторный запуск renderer, отрисовку старого пакета после сброса backend;
- разрушение окна внутри paint и игнорирование оставшихся таймерных сообщений.
Сборка: GCC 16.2 MinGW, Release, закреплённая VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792`, `BUILD_TESTING=ON`. Проверка: `cmake --build <build> --parallel 6`, `ctest --test-dir <build> -V`, `git diff --check`. В Wine 11 с доступным DISPLAY работают видимый swap chain и offscreen WARP; проба DXGI сообщает «ATI Radeon HD 5600 Series» для обоих типов устройств. Это имя адаптера Wine, а не подтверждение физического GPU. Если устройства отсутствуют, smoke возвращает CTest skip 77; отказ renderer при доступном устройстве считается ошибкой.
Дополнительно прошли прежние UI-прогоны: blueprint/room handlers, отказ команд и сохранность чертежей, загрузка/выход из гостя, rollback LAN-диалогов, три настоящих процесса viewer с изолированным `LOCALAPPDATA`, меню, реальный file picker, современное и прежнее сохранение. Нативная Windows, физическая потеря устройства, 1080p60/p95 и будущая воксельная геометрия здесь не проверялись. Тест отказа renderer намеренно подаёт неподходящий viewport и проверяет штатный HUD/повторный вход.
Общий примитив публикации остаётся связан с [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5). При его появлении заменить локальное владение только после тех же проверок старого пакета, вложенной установки и срока жизни геометрии. `PreparedFrame` и игровые правила формирования HUD остаются клиентскими данными.
## Границы данных и потоков
@@ -16,7 +39,7 @@
## Последовательность реализации
1. **S17-W01, M01.** Ввести публикацию снимков и самостоятельный цикл кадров. Перенести обращения к миру из обработчиков отрисовки в подготовку снимка. Проверить работу камеры при искусственно долгом такте.
1. **S17-W01, M01 — реализовано, ожидает приёмки.** Неизменяемый пакет, отдельный таймер кадра и проверки камеры при удержанном рабочем/файловом вводе-выводе описаны выше.
2. **S17-W02, M02.** Построить геометрию изменившихся чанков и обработку общих граней. Добавить отсечение невидимых областей и приоритет ближних участков. В тесте редактировать грань между двумя чанками и проверять отсутствие щели и дублирующей поверхности.
3. **S17-W03, M02–M03.** Добавить вращение, масштабирование вокруг указателя, выбор по лучу и срез высоты. Выбор возвращает регион, клетку, грань и ревизию, по которым интерфейс формирует намерение. При подтверждении симуляция проверяет действие на актуальной геометрии.
4. **S17-W04, M03–M07.** Разделить статическую геометрию, жителей, предметы и эффекты. Интерполировать визуальные позы между подтверждёнными тактами. Подключить оригинальные модели, анимацию, освещение, время суток и читаемую индикацию работы.
+113
View File
@@ -73,3 +73,116 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\build.ps1
Текущие тесты используют `Void::Testing`. Перед собственным runner, профилировщиком, таймером, журналом и форматом отчёта проверить существующие возможности VoidLibrary. Использовать подходящую реализацию. Для отсутствующей возможности найти или создать issue в `Void/Library`, приложить воспроизводимый пример нужного поведения и связать локальную реализацию с issue. [Матрица VoidLibrary](../void-library.md)
Система принята, когда каждый обязательный сценарий имеет команду запуска либо точную ручную процедуру, исходный мир, фактический результат и границы среды. Финальный отчёт различает кросс-сборку, Wine, нативную Windows, физические ПК и измерения GPU. Готовность пакета подтверждается запуском из поставки с её библиотеками и материалами. [Сохранения](S15.md) · [Сеть](S16.md) · [Происхождение материалов](S20.md)
## M01: наблюдаемый порядок завершения (S21-01)
Проверка подготовлена поверх `66af7c5` в `system/s21-verification`. Закреплённый
Void `7b0fea6095f603f9e1904f66dfdc7752f4be4792` предоставляет `FuturePool::try_submit`
с сохранением отклонённого callable и доставкой исключений через future. Его
`Testing::DeterministicRun` управляет тестовыми действиями; он не наблюдает возврат
реального `World` callable. Поэтому локальный `WorkerPoolOptions::after_execute(index)`
вызывается после успешного возврата callable, перед готовностью future. Исключение
наблюдателя попадает в тот же future; ошибка до исполнения или внутри callable
не вызывает наблюдателя. Без хуков остаётся прежняя ветка без счётчика отправок.
[Реализация](../../../engine/include/settlement/core/worker_pool.hpp) ·
[Контракт замены Void/Library#15](https://git.faumaray.com/Void/Library/issues/15).
Условие замены локального наблюдателя библиотечным — сохранить проверяемые возврат
`void`, значения, lvalue-ссылки, move-only результата и callable, ровно одно
успешное уведомление, исключения и исполнение при переполнении на координаторе.
[ExecutorTests](../../../tests/executor_tests.cpp) дополнительно удерживает сам
наблюдатель и проверяет, что future ещё не готов. Перенос уведомления к началу
вызова нарушает проверку завершённого действия.
[ReplayTests](../../../tests/replay_tests.cpp) использует два отдельных сценария:
- Seed 101, два жителя в `(5,1)`, одно достижимое общее задание в `(1,1)`.
При 2/6/12 потоках первые отправки 0 и 1 — реальные независимые вычисления
`choose_jobs` для жителей 0 и 1. Контроллер разрешает первый расчёт, ждёт его
`after_execute`, затем разрешает второй. Получены обе последовательности
`A->B` и `B->A`; владельцем задания остаётся житель с меньшим стабильным ID.
- Seed 97, два голодных жителя и одна ягода. Здесь общих заданий нет, поэтому
отправки 0 и 1 — стадии продвижения жителей. Захват еды выполняется
последовательно в `assign_meals` до этих стадий. Проверяются противоположные
завершения продвижения, один владелец, сохранность ягоды и ровно одно потребление;
параллельный арбитраж еды этим сценарием не заявляется.
Оба сценария проверены с `max_admitted=4096` и `1`. Контроллер находится вне
координатора, который при переполнении сам может ждать в inline callable.
Ожидания ограничены пятью секундами; scope guard всегда открывает ворота до
ожидания координатора или разрушения пула. Каждая из 24 конфигураций сравнивает
все 40 тактов с последовательным эталоном через настоящий `Current15` writer.
Лог содержит фактическую последовательность завершений каждой конфигурации.
[RuntimeTests](../../../tests/runtime_tests.cpp) удерживает старую задачу во время
постановки загрузки того же сохранения в очередь. Пока задача удержана, доступны
старый неизменяемый снимок и захват сохранения, а установка и старая команда ещё
не завершены. Перед захватом кандидата проверяется равенство числа начатых и
вернувшихся задач. После установки меняется session, старая команда получает
`StaleSession`; дополнительный барьер и следующий такт подтверждают неизменность
старого снимка и соответствие нового мира эталону.
[Test-local диагностика](../../../tests/replay_diagnostics.hpp) сначала сравнивает
канонические байты. Только при несовпадении она показывает первый различающийся
публичный факт с ID жителя, задания или производства, именем поля и значениями
expected/actual. Для запасов указываются владелец, тип предмета и ID стека,
для команд — игрок и следующий номер.
Сравнение квитанций содержит игрока, номер команды, статус, tick и revision.
Контекст включает первый обнаруженный tick/attempt, seed мира, число потоков,
расписание, состояние загрузки и предел допуска. Непокрытое публичной проекцией
поле получает смещение и значения байта. Это диагностическая проекция, а не
второй кодек или альтернативный критерий равенства. Отдельно проверены равенство,
ошибки запаса/задания/команды/квитанции, лишний ID и байтовый fallback.
Проверка 2 декабря 2026 года: Windows x64 Release кросс-сборка GCC 16.2.0,
выполнение Wine 11.0. CTest `-V`: 3/3 цели, 141 core + 9 LAN + 10 viewer тестов.
Отдельные теги: executor 10/10, replay 8/8, runtime 11/11. Логи:
`/tmp/stoneheart-milestones.xprJ2SVp/s21-replay-{configure,build,ctest,executor,replay,runtime}.log`.
Повторная окончательная сборка/CTest: `s21-replay-final-build.log`, `s21-replay-final-ctest.log` (3/3, 18,35 с).
Два внешних probe собраны заново против этой библиотеки; при 1/2/6/12 потоках
`cmp` подтвердил совпадение обоих исторических корпусов:
- `trajectory.cpp`: 361 такт, 5 приёмов пищи; SHA-256
`d50ce3f5cd339e2c87c83cb599075813caf86c6384e5caaab776d57e4b727cc7`.
- `identity-compat.cpp`: доставка и строительство после удаления других объектов;
SHA-256 `05972620f0ce29b1f6a3ebdd0315eb2e9faebc6629dfe38d0e804b19d86b7b0f`.
Логи probe: `s21-replay-probe-build.log`, `s21-replay-golden.log` в том же каталоге.
Физическая Windows, длительная нагрузка и производительность GPU здесь не проверялись.
Serena/граф были связаны с основным checkout; для изолированного worktree использована
прямая проверка исходников без переключения общего проекта и без заявления о покрытии графом.
## Полное состояние владения грузом
Потактный эталон и сравнение публикаций владельца используют `Current15`.
Сравнение включает имущество у производства, приостановку заказа, следующий
номер назначения, действующее исполнение и его резервы, результаты передач
и баланс каждого предмета. При расхождении диагностика показывает сначала
видимое изменение запасов или задания, затем постоянные ID и шаги исполнения,
сохранённые результаты и счётчики баланса. Ключ квитанции состоит из вида,
ID и номера операции. Положение квитанции в кольцевом буфере не служит её ID.
Если публичные факты совпали, сравнение сообщает первое различие байтов.
Проверка загрузки прежнего формата создаёт корректные миры с одинаковыми
байтами `Current14` и разными данными `Current15`. Она выявляет восстановленный
ID стека, различие начального остатка и начисления и отсутствие квитанции
назначения в историческом сохранении. Диагностический пример сообщает
`stock owner=storage:1 item=3 field=stack_id expected=2 actual=1`.
Отдельный сценарий отменяет настоящую стройку после доставки, заполняет
исходный склад и возвращает одну доску в склад вместимостью один предмет.
Оставшиеся две доски и два каменных блока ждут места у того же исполнителя
с тем же ID передачи. Контрольная точка восстанавливается на 1/2/6/12
исполнителях. После появления свободного склада каждый такт совпадает
с непрерывной партией. Точные и конфликтующие повторы квитанций назначения
и отмены проверяются до и после загрузки и после возврата груза.
Windows x64 Release GCC 16.2 под Wine 11 выполнил 10 проверок `replay` за 2,71 с
и 11 проверок `runtime` за 30 мс на рабочем срезе `e26b9c2` с этой проверкой.
Все 24 расписания завершения настоящих задач сохранились. Сценарий частичного
возврата занял 19,1 мс. Логи находятся в
`/tmp/stoneheart-milestones.xprJ2SVp/s21-custody-{configure,build-final,replay,runtime}.log`.
После объединения с исправлением проверки времени и ссылок S06 в `8522f91`
повторная сборка и CTest завершились с кодом 0. Все три цели прошли за 26,91 с,
включая 169 проверок ядра, 9 LAN и 10 клиента. Журналы этой сборки и запуска —
`s21-custody-build-validated.log` и `s21-custody-ctest-validated.log`.
+4
View File
@@ -49,6 +49,10 @@
У текущего `settlement::WorkerPool` есть отправка функции, получение future, число потоков и ожидание принятых работ при завершении. Сверить эти четыре операции с `ThreadExecutor + FuturePool`. Начать перенос с эталонной партии, затем испытать переполнение, частичный запуск и остановку. При переполнении симуляция должна выполнить тот же набор логических работ с тем же результатом. Выбранный вариант измерить на малой партии и на нагруженном городе. Существующие тесты Void проверяют поведение утилит, игровые тесты должны дополнительно сравнить хеши мира. [Текущий пул](../../engine/src/worker_pool.cpp) · [Проверки FuturePool](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/FuturePool.cpp) · [Проверки запуска потоков](https://git.faumaray.com/Void/Library/src/commit/7b0fea6095f603f9e1904f66dfdc7752f4be4792/tests/standalone/Async/ThreadExecutor.cpp)
## Публикация мира и приём команд
Клиент протокола 11 проверяет, можно ли передать ему текущее состояние. Пока он готовит приказ, владелец может опубликовать несовместимое состояние в той же партии. Проверка актуальности снимка и помещение приказа в очередь должны выполняться под одной блокировкой владельца. Тест задерживает клиента после получения старого снимка, отменяет заказ на хосте и проверяет, что номер гостевого приказа и состояние колонии сохранились. При обратном порядке уже принятый приказ должен завершиться. Публичный `FuturePool::try_submit` проверяет ёмкость своего исполнителя. Предложение связать допуск с публикацией передано сопровождающим. [Void/Library #16](https://git.faumaray.com/Void/Library/issues/16) · [Владелец симуляции](../../engine/src/simulation_runtime.cpp) · [Сетевой адаптер](../../app/lan_session_win32.cpp)
## Подготовка воксельного мира M02
Для проверки порядка завершения реальных вычислений [S21](systems/S21.md) использует работающий `FuturePool`. У `Testing::DeterministicRun` есть очередь управляемых тестовых действий. Для потактного теста игры требуется отдельно зарегистрировать возврат конкретной функции исполнителя, переставить две такие операции и проверить тот же результат мира на 2/6/12 потоках и при заполненной очереди. Предложение относится к тестовому адаптеру реальных задач. [Void/Library #15](https://git.faumaray.com/Void/Library/issues/15) · [Адаптер исполнения игры](../../engine/include/settlement/core/worker_pool.hpp)
+16 -3
View File
@@ -21,6 +21,9 @@ struct WorkerPoolOptions {
std::function<void(std::size_t)> before_worker_start;
std::function<void(std::size_t)> before_submit;
std::function<void(std::size_t)> before_execute;
// Success-only observation after invocation returns, before future readiness.
// A throwing observer fails that future. Replacement contract: Void/Library#15.
std::function<void(std::size_t)> after_execute;
};
class WorkerPool {
@@ -38,12 +41,22 @@ public:
if (executor_->is_executor_thread()) {
throw std::logic_error("cannot submit nested work to the same worker pool");
}
if (options_.before_submit || options_.before_execute) {
if (options_.before_submit || options_.before_execute || options_.after_execute) {
const auto index = submission_index_.fetch_add(1, std::memory_order_relaxed);
if (options_.before_submit) options_.before_submit(index);
return admit([this, index, function = std::forward<Function>(function)]() mutable -> decltype(auto) {
return admit([this, index, function = std::forward<Function>(function)]() mutable
-> std::invoke_result_t<Function> {
if (options_.before_execute) options_.before_execute(index);
return std::invoke(function);
if (!options_.after_execute) return std::invoke(function);
using Result = std::invoke_result_t<Function>;
if constexpr (std::is_void_v<Result>) {
std::invoke(function);
options_.after_execute(index);
} else {
Result result = std::invoke(function);
options_.after_execute(index);
return result;
}
});
}
return admit(std::forward<Function>(function));
+102 -1
View File
@@ -6,6 +6,9 @@
#include <atomic>
#include <chrono>
#include <array>
#include <condition_variable>
#include <mutex>
#include <future>
#include <memory>
#include <sstream>
@@ -82,6 +85,8 @@ void check_world_unwind(std::size_t phase, bool submit_failure) {
}
struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing::Suite<ExecutorTests> {
[[= Void::Testing::tag("executor")]] Test test_completion_observer_results_and_failures();
[[= Void::Testing::tag("executor")]] Test test_completion_observer_precedes_future_readiness();
[[= Void::Testing::tag("executor")]] Test test_limits_and_nested_submission();
[[= Void::Testing::tag("executor")]] Test test_capacity_retains_move_only_work_and_exceptions();
[[= Void::Testing::tag("executor")]] Test test_failed_callable_transfer_releases_capacity();
@@ -92,6 +97,102 @@ struct [[= Void::Testing::name("ExecutorTests")]] ExecutorTests : Void::Testing:
[[= Void::Testing::tag("executor")]] Test test_world_capacity_one_matches_reference();
};
// Exercise the same wrapper on a worker and on the submitting thread. Keeping
// index zero admitted forces every other submission through inline overload.
Test ExecutorTests::test_completion_observer_results_and_failures() {
for (bool inline_work : {false, true}) {
std::promise<void> release;
auto permit = release.get_future().share();
std::promise<void> entered;
auto running = entered.get_future();
std::array<std::atomic<int>, 8> observed{};
std::array<std::atomic<bool>, 8> returned{};
std::atomic<bool> observed_too_early{false};
WorkerPoolOptions options{.max_admitted = inline_work ? 1U : 4096U};
options.before_submit = [](std::size_t index) {
if (index == 8) throw std::bad_alloc();
};
options.before_execute = [](std::size_t index) {
if (index == 6) throw std::runtime_error("before invocation");
};
options.after_execute = [&](std::size_t index) {
if (index >= observed.size()) throw std::logic_error("observer on failed submission");
if (!returned[index].load()) observed_too_early.store(true);
++observed[index];
if (index == 7) throw std::runtime_error("after invocation");
};
WorkerPool pool(2, std::move(options));
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
auto held = pool.submit([&] {
entered.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
returned[0] = true;
});
require(running.wait_for(5s) == std::future_status::ready);
const auto caller = std::this_thread::get_id();
auto value = pool.submit([&] {
returned[1] = true;
return std::pair{17, std::this_thread::get_id() == caller};
});
require(value.get() == std::pair{17, inline_work});
int referent = 23;
auto reference = pool.submit([&]() -> int& { returned[2] = true; return referent; });
require(&reference.get() == &referent);
auto nothing = pool.submit([&] { returned[3] = true; });
nothing.get();
auto owned = pool.submit([&, value = std::make_unique<int>(31)]() mutable {
returned[4] = true;
return std::move(value);
});
require(*owned.get() == 31);
auto failure = pool.submit([]() -> int { throw std::runtime_error("invocation failed"); });
expect_throw<std::runtime_error>([&] { static_cast<void>(failure.get()); });
auto before = pool.submit([&] { returned[6] = true; });
expect_throw<std::runtime_error>([&] { before.get(); });
auto after = pool.submit([&] { returned[7] = true; });
expect_throw<std::runtime_error>([&] { after.get(); });
bool submitted_failure_ran = false;
expect_throw<std::bad_alloc>([&] {
static_cast<void>(pool.submit([&] { submitted_failure_ran = true; }));
});
require(!submitted_failure_ran);
release_task.release();
release.set_value();
held.get();
for (std::size_t i = 0; i < observed.size(); ++i) {
require(observed[i] == ((i == 5 || i == 6) ? 0 : 1));
}
require(!returned[6] && !observed_too_early);
}
}
Test ExecutorTests::test_completion_observer_precedes_future_readiness() {
std::promise<void> observed;
auto entered = observed.get_future();
std::promise<void> release;
auto permit = release.get_future().share();
std::atomic<int> calls{0};
WorkerPoolOptions options;
// Observer alone must enable monotonically increasing submission indices.
options.after_execute = [&](std::size_t index) {
if (index != static_cast<std::size_t>(calls.fetch_add(1))) throw std::runtime_error("bad index");
if (index == 0) {
observed.set_value();
if (permit.wait_for(5s) != std::future_status::ready) throw std::runtime_error("release timeout");
}
};
WorkerPool pool(2, std::move(options));
auto release_task = Void::Scope::on_exit([&] { release.set_value(); });
auto result = pool.submit([] { return 11; });
require(entered.wait_for(5s) == std::future_status::ready);
require(result.wait_for(0s) == std::future_status::timeout);
release_task.release();
release.set_value();
require(result.get() == 11);
pool.submit([] {}).get();
require(calls == 2);
}
Test ExecutorTests::test_limits_and_nested_submission() {
expect_throw<std::invalid_argument>([] { WorkerPool pool(1); });
expect_throw<std::invalid_argument>([] { WorkerPool pool(2, {.max_admitted = 0}); });
@@ -118,7 +219,7 @@ Test ExecutorTests::test_capacity_retains_move_only_work_and_exceptions() {
const auto coordinator = std::this_thread::get_id();
std::atomic<int> executions{0};
auto answer = pool.submit([value = std::make_unique<int>(17), coordinator, &executions] {
require(std::this_thread::get_id() == coordinator);
if (std::this_thread::get_id() != coordinator) throw std::runtime_error("expected inline work");
++executions;
return *value;
});
+218
View File
@@ -0,0 +1,218 @@
#pragma once
#include "settlement/core/world.hpp"
#include <algorithm>
#include <map>
#include <sstream>
#include <string>
#include <type_traits>
namespace replay_diagnostics {
using namespace settlement;
struct Context {
std::uint64_t attempt = 0;
std::size_t workers = 1;
std::string schedule = "uncontrolled";
std::string load = "uninterrupted";
std::size_t capacity = 4096;
};
inline std::string canonical(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current15);
return stream.str();
}
template<class T> std::string value(T item) {
if constexpr (std::is_enum_v<T>) return std::to_string(static_cast<unsigned>(item));
else return std::to_string(item);
}
inline std::string value(GridPosition p) { return "(" + value(p.x) + "," + value(p.y) + ")"; }
inline std::string value(StockOwner owner) { return value(owner.kind) + ":" + value(owner.id); }
inline std::string value(const std::vector<GridPosition>& route) {
std::string text = "[";
for (auto p : route) text += value(p) + ",";
return text + "]";
}
// Diagnostic projection of public domain objects, never a save parser or an
// alternate equality oracle. Unknown/private fields retain the byte fallback.
// Prefer visible stock/job changes, then durable identities, retained results
// and accounting. A secondary balance change must not hide the changed stock.
using Facts = std::map<std::pair<unsigned, std::string>, std::string>;
inline Facts facts(const World& world) {
Facts out;
const auto put = [&](const std::string& owner, const char* field, const auto& item, unsigned priority = 0) {
out[{priority, owner + " field=" + field}] = value(item);
};
for (const auto& a : world.agents()) {
const auto key = "agent id=" + value(a.id);
#define AGENT_FIELD(field) put(key, #field, a.field)
AGENT_FIELD(position); AGENT_FIELD(state); AGENT_FIELD(current_job);
AGENT_FIELD(route); AGENT_FIELD(route_cursor); AGENT_FIELD(work_remaining);
AGENT_FIELD(resource_node_id); AGENT_FIELD(storage_id); AGENT_FIELD(haul_route);
AGENT_FIELD(production_id); AGENT_FIELD(hunger); AGENT_FIELD(fatigue);
AGENT_FIELD(resting_on_ground); AGENT_FIELD(profession);
#undef AGENT_FIELD
put(key, "next_admission", a.next_admission, 1);
put(key, "transfer_id", a.execution ? a.execution->id : 0, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto stock = "stock owner=agent:" + value(a.id) + " item=" + value(item);
put(stock, "count",
a.inventory.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", a.inventory.stack_id(static_cast<ItemType>(item)), 1);
}
if (a.execution) {
const auto& transfer = *a.execution;
const auto transfer_key = "transfer id=" + value(transfer.id) + " owner=agent:" + value(a.id);
put(transfer_key, "kind", transfer.kind, 1);
put(transfer_key, "production", transfer.production, 1);
put(transfer_key, "source", transfer.source, 1);
put(transfer_key, "destination", transfer.destination, 1);
put(transfer_key, "next_operation", transfer.next_operation, 1);
put(transfer_key, "blocked", transfer.blocked, 1);
put(transfer_key, "reservation_count", transfer.reservation_count, 1);
for (const auto& claim : transfer.reservations) {
if (!claim.id) continue;
const auto claim_key = "reservation id=" + value(claim.id) + " transfer=" + value(transfer.id);
put(claim_key, "kind", claim.kind, 1);
put(claim_key, "owner", claim.owner, 1);
put(claim_key, "stack_id", claim.stack, 1);
put(claim_key, "item", claim.item, 1);
put(claim_key, "count", claim.count, 1);
put(claim_key, "backing", claim.backing, 1);
put(claim_key, "origin_storage", claim.origin_storage, 1);
}
}
}
for (const auto& j : world.jobs()) {
const auto key = "job id=" + value(j.id);
put(key, "position", j.position); put(key, "state", j.state);
put(key, "work_required", j.work_required); put(key, "work_remaining", j.work_remaining);
}
for (const auto& p : world.production_orders()) {
const auto key = "production id=" + value(p.id);
put(key, "position", p.position); put(key, "recipe", p.recipe); put(key, "state", p.state);
put(key, "collected_stops", p.collected_stops); put(key, "bed_owner", p.bed_owner);
put(key, "bed_base", p.bed_base); put(key, "bed_stage", p.bed_stage);
put(key, "suspended", p.suspended, 1);
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto stock = "stock owner=production:" + value(p.id) + " item=" + value(item);
put(stock, "count", p.input.item_count(static_cast<ItemType>(item)));
put(stock, "stack_id", p.input.stack_id(static_cast<ItemType>(item)), 1);
}
for (const auto& m : p.materials) {
put(key + " material owner=storage:" + value(m.storage_id) + " item=" + value(m.type),
"count", m.count);
}
for (std::size_t i = 0; i < p.delivery_stops.size(); ++i) {
const auto stop = key + " stop=" + value(i);
put(stop, "storage_id", p.delivery_stops[i].storage_id);
put(stop, "route_to_next", p.delivery_stops[i].route_to_next);
}
}
for (const auto& s : world.storages()) {
const auto key = "storage id=" + value(s.id);
put(key, "position", s.position); put(key, "capacity", s.capacity);
put(key, "reserved_slots", s.reserved_slots); put(key, "kind", s.kind);
for (const auto& stack : s.items) {
const auto stock = "stock owner=storage:" + value(s.id) + " item=" + value(stack.type);
put(stock, "count", stack.count); put(stock, "reserved", stack.reserved);
put(stock, "stack_id", stack.id, 1);
}
}
// Keys identify logical results independently of the ring's backing slots.
for (const auto& receipt : world.custody_receipts()) {
const auto& request = receipt->request;
const auto& result = receipt->result;
const auto key = "custody receipt kind=" + value(request.key.kind) + " id=" + value(request.key.id) +
" ordinal=" + value(request.key.ordinal);
put(key, "operation", request.operation, 2);
put(key, "kind", request.kind, 2);
put(key, "production", request.production, 2);
put(key, "source", request.source, 2);
put(key, "destination", request.destination, 2);
put(key, "line_count", request.line_count, 2);
for (std::size_t i = 0; i < request.line_count; ++i) {
const auto line_key = key + " line=" + value(i);
put(line_key, "storage", request.lines[i].storage, 2);
put(line_key, "item", request.lines[i].item, 2);
put(line_key, "count", request.lines[i].count, 2);
}
put(key, "status", result.status, 2);
put(key, "transfer_id", result.transfer, 2);
put(key, "terminal", result.terminal, 2);
put(key, "reservation_count", result.reservation_count, 2);
put(key, "effect_count", result.effect_count, 2);
for (std::size_t i = 0; i < result.reservation_count; ++i) {
put(key + " reservation=" + value(i), "id", result.reservations[i], 2);
}
for (std::size_t i = 0; i < result.effect_count; ++i) {
const auto effect_key = key + " effect=" + value(i);
const auto& effect = result.effects[i];
put(effect_key, "owner", effect.owner, 2);
put(effect_key, "stack_id", effect.stack, 2);
put(effect_key, "item", effect.item, 2);
put(effect_key, "count", effect.count, 2);
}
}
for (std::size_t item = 1; item <= item_type_count; ++item) {
const auto key = "balance item=" + value(item);
const auto& balance = world.item_balances()[item - 1];
put(key, "opening", balance.opening, 3);
put(key, "grant", balance.grant, 3);
put(key, "harvest", balance.harvest, 3);
put(key, "recipe_output", balance.recipe_output, 3);
put(key, "recipe_input", balance.recipe_input, 3);
put(key, "meal", balance.meal, 3);
put(key, "installation", balance.installation, 3);
put(key, "demolition", balance.demolition, 3);
}
for (std::uint8_t player = 1; player <= colony_player_slots; ++player) {
put("command player=" + value(player), "next_sequence", world.next_command_sequence(player));
}
return out;
}
inline std::string context(const World& world, const Context& c) {
return "replay divergence tick=" + value(world.tick()) + " attempt=" + value(c.attempt) +
" seed=" + value(world.seed()) + " workers=" + value(c.workers) + " schedule=" + c.schedule +
" load=" + c.load + " capacity=" + value(c.capacity) + " ";
}
inline std::string difference(const World& expected, const World& actual, const Context& c = {}) {
const auto left = canonical(expected), right = canonical(actual);
if (left == right) return {};
const auto a = facts(expected), b = facts(actual);
auto ai = a.begin(), bi = b.begin();
while (ai != a.end() || bi != b.end()) {
if (bi == b.end() || (ai != a.end() && ai->first < bi->first)) {
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=<absent>";
}
if (ai == a.end() || bi->first < ai->first) {
return context(expected, c) + bi->first.second + " expected=<absent> actual=" + bi->second;
}
if (ai->second != bi->second) {
return context(expected, c) + ai->first.second + " expected=" + ai->second + " actual=" + bi->second;
}
++ai; ++bi;
}
const auto mismatch = std::mismatch(left.begin(), left.end(), right.begin(), right.end());
const auto offset = static_cast<std::size_t>(mismatch.first - left.begin());
const auto byte = [offset](const std::string& bytes) {
return offset < bytes.size() ? value(static_cast<unsigned char>(bytes[offset])) : "<end>";
};
return context(expected, c) + "byte=" + value(offset) + " expected=" + byte(left) + " actual=" + byte(right);
}
inline std::string receipt_difference(const World& world, const PlayerCommand& command,
CommandReceipt expected, CommandReceipt actual, const Context& c) {
if (expected.status == actual.status && expected.tick == actual.tick && expected.revision == actual.revision) return {};
const auto receipt = [](CommandReceipt r) {
return "{status=" + value(r.status) + ",tick=" + value(r.tick) + ",revision=" + value(r.revision) + "}";
};
return context(world, c) + "command player=" + value(command.player) + " sequence=" + value(command.sequence) +
" field=receipt expected=" + receipt(expected) + " actual=" + receipt(actual);
}
} // namespace replay_diagnostics
+313 -19
View File
@@ -1,10 +1,18 @@
#include "settlement/core/world.hpp"
#include "settlement/core/checkpoint.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <condition_variable>
#include <future>
#include <iostream>
#include <mutex>
#include <cstddef>
#include <cstdint>
#include <memory>
@@ -37,9 +45,7 @@ void require(bool condition, std::string_view message) {
}
std::string saved_state(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
return replay_diagnostics::canonical(world);
}
std::unique_ptr<World> load_state(const std::string& bytes, ExecutionConfig config,
@@ -66,6 +72,7 @@ public:
}
void step() {
++attempt_;
reference->step();
for (auto& run : runs_) run.world->step();
compare();
@@ -75,9 +82,10 @@ public:
std::uint64_t expected_tick, std::uint64_t expected_revision) {
const auto check = [&](World& world) {
const auto result = world.apply_command(command);
require(result.status == expected_status && result.tick == expected_tick &&
result.revision == expected_revision,
"command receipt differs from the recorded status, tick or revision");
const auto diagnostic = replay_diagnostics::receipt_difference(world, command,
{expected_status, expected_tick, expected_revision}, result,
{attempt_, world.worker_count(), "journal", "command", options_.max_admitted});
require(diagnostic.empty(), diagnostic);
};
check(*reference);
for (auto& run : runs_) check(*run.world);
@@ -102,28 +110,25 @@ private:
};
void compare() const {
const auto expected = saved_state(*reference);
for (const auto& run : runs_) {
const auto actual = saved_state(*run.world);
if (actual == expected) continue;
const auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin(), actual.end());
const auto offset = static_cast<std::size_t>(mismatch.first - expected.begin());
throw std::runtime_error("replay diverged at tick " + std::to_string(reference->tick()) +
", workers " + std::to_string(run.config.workers) +
(run.reloaded ? ", reloaded" : ", uninterrupted") +
", byte " + std::to_string(offset) +
", path searches " + std::to_string(reference->path_searches()) + "/" +
std::to_string(run.world->path_searches()) + ", path nodes " +
std::to_string(reference->path_nodes_visited()) + "/" +
std::to_string(run.world->path_nodes_visited()));
const auto diagnostic = replay_diagnostics::difference(*reference, *run.world,
{attempt_, run.config.workers, "uncontrolled", run.reloaded ? "reloaded" : "uninterrupted",
options_.max_admitted});
require(diagnostic.empty(), diagnostic);
}
}
std::uint64_t attempt_ = 0;
WorkerPoolOptions options_;
std::vector<Run> runs_;
};
struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Suite<ReplayTests> {
[[= Void::Testing::tag("replay")]] Test test_opposite_real_completion_orders();
[[= Void::Testing::tag("replay")]] Test test_semantic_divergence_diagnostics();
[[= Void::Testing::tag("replay")]] Test test_modern_custody_exposes_legacy_projection_blindness();
[[= Void::Testing::tag("replay")]] Test test_cancelled_partial_cargo_checkpoint_replay();
[[= Void::Testing::tag("replay")]] Test test_execution_configuration_and_empty_world();
[[= Void::Testing::tag("replay")]] Test test_one_resident_completes_work();
[[= Void::Testing::tag("replay")]] Test test_competing_jobs_retry_unreachable_routes();
@@ -132,6 +137,295 @@ struct [[= Void::Testing::name("ReplayTests")]] ReplayTests : Void::Testing::Sui
[[= Void::Testing::tag("replay")]] Test test_last_meal_has_one_winner_and_one_consumer();
};
// The driver is the test thread, separate from World::step's coordinator:
// capacity one can run submission 1 inline while submission 0 is held.
struct CompletionGate {
std::mutex mutex;
std::condition_variable changed;
std::array<bool, 2> entered{}, permitted{};
std::vector<std::size_t> completed;
bool released = false;
void before(std::size_t index) {
if (index > 1) return;
std::unique_lock lock(mutex);
entered[index] = true;
changed.notify_all();
if (!changed.wait_for(lock, std::chrono::seconds(5), [&] { return released || permitted[index]; })) {
throw std::runtime_error("completion gate release timeout");
}
}
void after(std::size_t index) {
if (index > 1) return;
std::lock_guard lock(mutex);
completed.push_back(index);
changed.notify_all();
}
void drive(std::size_t first) {
std::unique_lock lock(mutex);
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return entered[0] && entered[1]; }),
"both real calculations did not enter");
require(completed.empty(), "a calculation completed before its gate was released");
permitted[first] = true;
changed.notify_all();
require(changed.wait_for(lock, std::chrono::seconds(5), [&] { return !completed.empty(); }),
"first real calculation did not return");
require(completed == std::vector<std::size_t>{first}, "completion order was not forced");
permitted[1 - first] = true;
changed.notify_all();
}
void release() {
std::lock_guard lock(mutex);
released = true;
changed.notify_all();
}
};
Test ReplayTests::test_opposite_real_completion_orders() {
for (bool meal : {false, true}) {
World initial(meal ? 97 : 101, 8, 8, 1, ExecutionMode::SerialReference);
const auto winner = initial.spawn_agent({5, 1});
static_cast<void>(initial.spawn_agent({5, 1}));
JobId job = 0;
if (meal) {
const auto pantry = initial.add_storage({1, 1}, 1, StorageKind::Pantry);
initial.enable_hunger();
for (std::uint16_t tick = 0; tick < hunger_threshold; ++tick) initial.step();
initial.stock_storage(pantry, ItemType::Berries, 1);
} else {
job = initial.add_job({1, 1}, 3);
}
const auto fixture = saved_state(initial);
for (auto workers : {2U, 6U, 12U}) for (auto capacity : {4096U, 1U}) for (auto first : {0U, 1U}) {
CompletionGate gate;
WorkerPoolOptions options{.max_admitted = capacity};
options.before_execute = [&](std::size_t index) { gate.before(index); };
options.after_execute = [&](std::size_t index) { gate.after(index); };
auto reference = load_state(fixture, execution_configs.front());
auto candidate = load_state(fixture, {workers, ExecutionMode::Parallel}, std::move(options));
auto step = std::async(std::launch::async, [&] { candidate->step(); });
// Always release before joining the coordinator, including assertion failure.
auto release = Void::Scope::on_exit([&] { gate.release(); });
gate.drive(first);
gate.release();
require(step.wait_for(std::chrono::seconds(5)) == std::future_status::ready, "world step did not drain");
step.get();
require(gate.completed == std::vector<std::size_t>{first, 1 - first}, "wrong actual return trace");
const std::string schedule = first == 0 ? "A->B" : "B->A";
std::cout << "actual " << (meal ? "meal movement" : "job choices") << " workers=" << workers
<< " capacity=" << capacity << " completions=" << schedule << '\n';
for (std::uint64_t attempt = 1; attempt <= 40; ++attempt) {
reference->step();
const auto diagnostic = replay_diagnostics::difference(*reference, *candidate,
{attempt, workers, schedule, "fixture", capacity});
require(diagnostic.empty(), diagnostic);
if (attempt == 1) {
require(candidate->agents()[0].id == winner, "fixture IDs changed");
if (meal) {
require(candidate->agents()[0].state == AgentState::GoingToEat &&
candidate->agents()[1].state == AgentState::Idle,
"serial meal claim lost its stable winner");
} else {
require(candidate->agents()[0].current_job == job && candidate->agents()[1].current_job == 0,
"competing real calculations changed the lower-ID winner");
}
}
if (meal) {
const auto& agents = candidate->agents();
require(candidate->storages()[0].item_count(ItemType::Berries) +
agents[0].inventory.item_count(ItemType::Berries) + agents[1].inventory.item_count(ItemType::Berries) +
candidate->meals_eaten() == 1, "meal duplicated or lost");
require(agents[1].inventory.empty() && agents[1].state != AgentState::GoingToEat &&
agents[1].state != AgentState::Eating, "second resident consumed reserved meal");
}
if (attempt != 40) candidate->step();
}
require(meal ? candidate->meals_eaten() == 1 : candidate->jobs_completed() == 1,
"the sole job or meal did not finish exactly once");
}
}
}
Test ReplayTests::test_semantic_divergence_diagnostics() {
const replay_diagnostics::Context context{7, 6, "B->A", "checkpoint", 1};
World expected(103, 8, 8, 1, ExecutionMode::SerialReference);
const auto storage = expected.add_storage({1, 1}, 20);
expected.stock_storage(storage, ItemType::Wood, 2);
const auto job = expected.add_job({4, 4}, 2);
const auto fixture = saved_state(expected);
auto actual = load_state(fixture, execution_configs.front());
require(replay_diagnostics::difference(expected, *actual, context).empty(), "equal worlds reported divergence");
actual->stock_storage(storage, ItemType::Wood, 1);
auto report = replay_diagnostics::difference(expected, *actual, context);
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
report.find("item=1 field=count expected=2 actual=3") != std::string::npos &&
report.find("attempt=7 seed=103 workers=6 schedule=B->A load=checkpoint capacity=1") != std::string::npos,
"stock diagnostic omitted context or identity: " + report);
actual = load_state(fixture, execution_configs.front());
// These are deliberate diagnostic inputs built by public domain operations.
World changed_job(103, 8, 8, 1, ExecutionMode::SerialReference);
const auto matching = changed_job.add_storage({1, 1}, 20);
changed_job.stock_storage(matching, ItemType::Wood, 2);
static_cast<void>(changed_job.add_job({4, 4}, 3));
report = replay_diagnostics::difference(expected, changed_job, context);
require(report.find("job id=" + std::to_string(job)) != std::string::npos &&
report.find("field=work_remaining expected=2 actual=3") != std::string::npos,
"job diagnostic omitted identity: " + report);
auto command_world = make_first_colony(2);
auto command_copy = load_state(saved_state(*command_world), execution_configs.front());
const PlayerCommand command{1, 1, CommandKind::SetPaused, {}, 1};
const auto receipt = command_copy->apply_command(command);
report = replay_diagnostics::difference(*command_world, *command_copy, context);
require(report.find("command player=1 field=next_sequence expected=1 actual=2") != std::string::npos,
"command diagnostic omitted player and sequence: " + report);
report = replay_diagnostics::receipt_difference(*command_copy, command,
{CommandStatus::Accepted, 0, 0}, receipt, context);
require(report.find("command player=1 sequence=1 field=receipt") != std::string::npos &&
report.find("revision=0") != std::string::npos && report.find("revision=1") != std::string::npos,
"receipt diagnostic omitted revision: " + report);
require(replay_diagnostics::receipt_difference(*command_copy, command, receipt, receipt, context).empty(),
"equal receipts reported divergence");
// An absent entity and a private field exercise identity and byte fallbacks.
static_cast<void>(actual->add_job({6, 6}, 1));
require(replay_diagnostics::difference(expected, *actual).find("job id=2") != std::string::npos,
"extra entity lost stable identity");
actual = load_state(fixture, execution_configs.front());
actual->set_blocked({7, 7});
require(replay_diagnostics::difference(expected, *actual).find("byte=") != std::string::npos,
"unprojected canonical field lost byte fallback");
}
Test ReplayTests::test_modern_custody_exposes_legacy_projection_blindness() {
const auto legacy = [](const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream, WorldSaveFormat::Current14);
return stream.str();
};
const replay_diagnostics::Context context{2, 1, "custody", "legacy-import", 4096};
World stock(107, 12, 12, 1, ExecutionMode::SerialReference);
const auto storage = stock.add_storage({2, 2}, 10);
// Issued identities follow grants, while historical migration reconstructs
// them from the canonically sorted item rows.
stock.stock_storage(storage, ItemType::StoneBlock, 2);
stock.stock_storage(storage, ItemType::Plank, 3);
auto imported = load_state(legacy(stock), execution_configs.front());
require(legacy(stock) == legacy(*imported), "legacy stock projection changed on import");
auto report = replay_diagnostics::difference(stock, *imported, context);
require(report.find("stock owner=storage:" + std::to_string(storage)) != std::string::npos &&
report.find("field=stack_id expected=2 actual=1") != std::string::npos,
"modern comparison missed reconstructed stack identity: " + report);
std::cout << report << '\n';
World accounting(108, 12, 12, 1, ExecutionMode::SerialReference);
const auto store = accounting.add_storage({2, 2}, 10);
accounting.stock_storage(store, ItemType::Wood, 2);
imported = load_state(legacy(accounting), execution_configs.front());
require(legacy(accounting) == legacy(*imported), "legacy accounting projection changed on import");
report = replay_diagnostics::difference(accounting, *imported, context);
require(report.find("balance item=1 field=grant expected=2 actual=0") != std::string::npos,
"modern comparison missed opening/grant distinction: " + report);
World active(109, 32, 32, 1, ExecutionMode::SerialReference);
const auto materials = active.add_storage({3, 3}, 5);
active.stock_storage(materials, ItemType::Plank, 3);
active.stock_storage(materials, ItemType::StoneBlock, 2);
static_cast<void>(active.spawn_agent({1, 3}));
active.queue_production({16, 3}, RecipeId::BuildCabin);
active.step();
imported = load_state(legacy(active), execution_configs.front());
require(legacy(active) == legacy(*imported), "legacy active projection changed on import");
require(!active.custody_receipts().empty() && imported->custody_receipts().empty(),
"fixture did not distinguish real and reconstructed history");
report = replay_diagnostics::difference(active, *imported, context);
require(report.find("custody receipt kind=0 id=1 ordinal=1") != std::string::npos &&
report.find("actual=<absent>") != std::string::npos,
"modern comparison missed retained admission result: " + report);
std::cout << report << '\n';
const auto facts = replay_diagnostics::facts(active);
const auto& transfer = *active.agents().front().execution;
const auto& reservation = transfer.reservations.front();
require(facts.at({1, "transfer id=" + std::to_string(transfer.id) + " owner=agent:1 field=next_operation"}) == "1" &&
facts.at({1, "reservation id=" + std::to_string(reservation.id) + " transfer=" +
std::to_string(transfer.id) + " field=stack_id"}) == std::to_string(reservation.stack),
"active transfer/reservation diagnostics lost durable identities");
}
Test ReplayTests::test_cancelled_partial_cargo_checkpoint_replay() {
World reference(113, 32, 32, 1, ExecutionMode::SerialReference);
const auto source = reference.add_storage({3, 3}, 5);
reference.stock_storage(source, ItemType::Plank, 3);
reference.stock_storage(source, ItemType::StoneBlock, 2);
static_cast<void>(reference.spawn_agent({1, 3}));
reference.queue_production({16, 3}, RecipeId::BuildCabin);
const auto order = reference.production_orders().front().id;
for (int tick = 0; tick < 30 && reference.agents().front().state != AgentState::Working; ++tick) reference.step();
require(reference.agents().front().state == AgentState::Working, "cabin delivery did not reach the site");
const auto transfer = reference.agents().front().execution->id;
require(reference.cancel_production(order) == CommandStatus::Accepted, "live construction cancellation failed");
reference.stock_storage(source, ItemType::Wood, 5);
const auto partial = reference.add_storage({4, 3}, 1);
for (int tick = 0; tick < 40; ++tick) reference.step();
const auto& actor = reference.agents().front();
require(actor.state == AgentState::Returning && actor.execution && actor.execution->id == transfer &&
actor.execution->blocked == CustodyStatus::NoDestination &&
actor.inventory.item_count(ItemType::Plank) == 2 && actor.inventory.item_count(ItemType::StoneBlock) == 2 &&
reference.find_storage(partial)->item_count(ItemType::Plank) == 1,
"partial return did not retain the same transfer and remaining cargo");
const auto admission = *reference.custody_receipts().front();
const auto cancelled = std::find_if(reference.custody_receipts().begin(), reference.custody_receipts().end(),
[](const auto& receipt) { return receipt->request.operation == CustodyOperation::Cancel; });
require(cancelled != reference.custody_receipts().end(), "cancel result was not retained");
const std::array retained{admission, **cancelled};
Void::Uuid::Uuid world_id;
world_id.bytes.back() = 113;
const auto rules = default_rules_manifest();
const auto catalog = builtin_rule_packages();
require(rules.has_value() && catalog.has_value(), "default rules unavailable");
const auto checkpoint = encode_checkpoint(reference, world_id, 7, *rules);
require(checkpoint.has_value(), "partial cargo checkpoint failed");
std::vector<std::unique_ptr<World>> candidates;
for (const auto config : execution_configs) {
auto loaded = decode_checkpoint(*checkpoint, *catalog, config.workers, config.mode);
require(loaded.has_value(), "partial cargo checkpoint was not decoded");
require(loaded->world_id == world_id && loaded->city == 7, "checkpoint identity changed");
const auto repeated = encode_checkpoint(*loaded->world, loaded->world_id, loaded->city, loaded->rules);
require(repeated.has_value() && *repeated == *checkpoint, "partial checkpoint roundtrip changed bytes");
candidates.push_back(std::move(loaded->world));
}
const auto repeat_without_effect = [&](World& world) {
const auto before = saved_state(world);
for (const auto& receipt : retained) {
require(world.custody_request(receipt.request) == receipt.result, "retained result changed after reload");
auto conflict = receipt.request;
++conflict.destination;
require(world.custody_request(conflict).status == CustodyStatus::Conflict,
"changed payload reused an accepted transfer step");
}
require(saved_state(world) == before, "retry repeated a physical transfer or consumed an ordinal");
};
repeat_without_effect(reference);
for (auto& world : candidates) repeat_without_effect(*world);
for (std::uint64_t attempt = 0; attempt < 40; ++attempt) {
if (attempt == 5) {
static_cast<void>(reference.add_storage({6, 3}, 20));
for (auto& world : candidates) static_cast<void>(world->add_storage({6, 3}, 20));
}
reference.step();
for (std::size_t i = 0; i < candidates.size(); ++i) {
candidates[i]->step();
const auto report = replay_diagnostics::difference(reference, *candidates[i],
{attempt, execution_configs[i].workers, "cancel-return", "checkpoint", 4096});
require(report.empty(), report);
repeat_without_effect(*candidates[i]);
}
}
require(reference.agents().front().inventory.empty() && !reference.agents().front().execution &&
reference.item_balances()[2].installation == 0 && reference.item_balances()[3].installation == 0,
"return duplicated consumption or retained finished cargo");
repeat_without_effect(reference);
}
Test ReplayTests::test_execution_configuration_and_empty_world() {
World initial(20261202, 5, 5);
const auto bytes = saved_state(initial);
+66 -3
View File
@@ -1,4 +1,5 @@
#include "settlement/core/simulation_runtime.hpp"
#include "replay_diagnostics.hpp"
#include <Void/Core/Scope.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
@@ -20,9 +21,7 @@ constexpr TrustedClient host{1};
constexpr TrustedClient guest{2};
std::string bytes(const World& world) {
std::ostringstream stream(std::ios::binary);
world.write_save(stream);
return stream.str();
return replay_diagnostics::canonical(world);
}
WorldCheckpoint colony(std::size_t workers = 2, WorkerPoolOptions options = {}) {
@@ -98,6 +97,7 @@ void command_observer(CommandMutationPhase phase) {
}
struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::Suite<RuntimeTests> {
[[= Void::Testing::tag("runtime")]] Test test_queued_same_save_install_drains_old_world();
[[= Void::Testing::tag("runtime")]] Test test_fixed_clock_matches_reference_and_suspend_discards_idle_time();
[[= Void::Testing::tag("runtime")]] Test test_paused_commands_publish_and_two_clients_replay_exact_results();
[[= Void::Testing::tag("runtime")]] Test test_readers_and_save_capture_progress_during_real_worker_tick();
@@ -110,6 +110,69 @@ struct [[= Void::Testing::name("RuntimeTests")]] RuntimeTests : Void::Testing::S
[[= Void::Testing::tag("runtime")]] Test test_exhausted_clock_faults_without_spinning();
};
Test RuntimeTests::test_queued_same_save_install_drains_old_world() {
auto gate = std::make_shared<Gate>();
auto clock = std::make_shared<Void::Time::ManualClock>();
std::atomic<std::size_t> started{0}, completed{0};
std::atomic<bool> install_saw_drained{false};
WorkerPoolOptions workers;
workers.before_execute = [&](std::size_t index) {
++started;
if (index == 0) gate->block();
};
workers.after_execute = [&](std::size_t) { ++completed; };
RuntimeOptions options{.clock = clock};
options.observer = [&](RuntimePhase phase) {
if (phase == RuntimePhase::BeforeInstallCapture) {
install_saw_drained = started.load() >= 2 && started.load() == completed.load();
}
};
auto replacement = colony();
const auto replacement_bytes = replay_diagnostics::canonical(*replacement.world);
SimulationRuntime runtime(colony(2, std::move(workers)), std::move(options));
auto release = Void::Scope::on_exit([&] { gate->release(); });
const auto old_view = runtime.latest();
const auto old_bytes = replay_diagnostics::canonical(*old_view->world);
const auto stale_command = envelope(*old_view, 1, CommandKind::SetPaused, 1);
require(clock->advance(50ms).has_value());
runtime.notify_clock();
gate->wait();
const auto ticket = runtime.begin_load();
require(ticket.has_value());
auto installing = admitted([&] { return runtime.try_install(*ticket, replacement); });
require(installing.admission == RuntimeAdmission::Accepted && !replacement.world);
auto stale = admitted([&] { return runtime.try_submit(host, stale_command); });
require(stale.admission == RuntimeAdmission::Accepted);
require(installing.completion.wait_for(0s) == std::future_status::timeout);
require(stale.completion.wait_for(0s) == std::future_status::timeout);
require(!install_saw_drained && started.load() > completed.load());
require(runtime.latest() == old_view);
require(runtime.snapshot_for_save().value() == old_view);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
gate->release();
const auto installed = finished(std::move(installing));
require(installed.outcome == RuntimeOutcome::Completed && install_saw_drained);
require(installed.snapshot->identity.world == old_view->identity.world);
require(installed.snapshot->identity.session != old_view->identity.session);
require(installed.snapshot->world->tick() == 0);
const auto rejected = finished(std::move(stale));
require(rejected.receipt && rejected.receipt->status == DispatchStatus::StaleSession);
const auto drained_count = completed.load();
require(fence(runtime).outcome == RuntimeOutcome::Completed);
require(runtime.latest() == installed.snapshot);
require(replay_diagnostics::canonical(*runtime.latest()->world) == replacement_bytes);
require(replay_diagnostics::canonical(*old_view->world) == old_bytes);
require(completed.load() == drained_count && started.load() == completed.load());
auto serial = colony(1);
serial.world->step();
require(clock->advance(50ms).has_value());
require(fence(runtime).outcome == RuntimeOutcome::Completed);
const auto diagnostic = replay_diagnostics::difference(*serial.world, *runtime.latest()->world,
{1, 2, "old-worker-held", "same-save-replacement", 4096});
if (!diagnostic.empty()) throw std::runtime_error(diagnostic);
require(completed.load() == drained_count);
}
Test RuntimeTests::test_fixed_clock_matches_reference_and_suspend_discards_idle_time() {
for (const auto workers : {1U, 2U, 6U, 12U}) {
auto clock = std::make_shared<Void::Time::ManualClock>();
+325
View File
@@ -0,0 +1,325 @@
// Exercise the real two-window handlers without an alternate rendering path.
#define SETTLEMENT_FRAME_TEST
#include "../app/viewer_win32.cpp"
#include <d3d11.h>
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <sstream>
using namespace std::chrono_literals;
namespace {
bool probe_device(D3D_DRIVER_TYPE driver) {
ID3D11Device* device = nullptr;
if (FAILED(D3D11CreateDevice(nullptr, driver, nullptr, 0, nullptr, 0,
D3D11_SDK_VERSION, &device, nullptr, nullptr))) return false;
IDXGIDevice* dxgi = nullptr;
if (SUCCEEDED(device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgi)))) {
IDXGIAdapter* adapter = nullptr;
if (SUCCEEDED(dxgi->GetAdapter(&adapter))) {
DXGI_ADAPTER_DESC desc{};
if (SUCCEEDED(adapter->GetDesc(&desc))) std::printf("DEVICE %s: %ls\n",
driver == D3D_DRIVER_TYPE_WARP ? "WARP" : "hardware", desc.Description);
adapter->Release();
}
dxgi->Release();
}
device->Release(); return true;
}
void require_frame(bool value, const char* message) {
if (!value) throw std::runtime_error(message);
}
struct Gate {
std::mutex mutex;
std::condition_variable changed;
bool entered = false, released = false;
void block() {
std::unique_lock lock(mutex);
entered = true; changed.notify_all();
if (!changed.wait_for(lock, 30s, [&] { return released; })) throw std::runtime_error("gate deadline");
}
void wait() {
std::unique_lock lock(mutex);
require_frame(changed.wait_for(lock, 10s, [&] { return entered; }), "gate did not enter");
}
void release() { std::lock_guard lock(mutex); released = true; changed.notify_all(); }
};
template<class Predicate> void wait_for_frame(Predicate done) {
const auto deadline = std::chrono::steady_clock::now() + 10s;
while (!done()) {
require_frame(std::chrono::steady_clock::now() < deadline, "frame wait deadline");
std::this_thread::yield();
}
}
std::string canonical(const settlement::World& value) {
std::ostringstream stream(std::ios::binary);
value.write_save(stream, settlement::WorldSaveFormat::Current15);
return stream.str();
}
void frame_only(HWND window) {
SendMessageW(window, WM_TIMER, frame_timer_id, 0);
UpdateWindow(window);
if (scene_window) UpdateWindow(scene_window);
}
void event_and_frame(HWND window) {
SendMessageW(window, WM_TIMER, timer_id, 0);
frame_only(window);
}
std::vector<std::uint32_t> capture_frame(settlement::viewer::D3DScene& renderer,
const std::shared_ptr<const PreparedFrame>& frame) {
std::vector<std::uint32_t> pixels;
require_frame(frame && frame->content && renderer.render(frame->content->geometry, frame->view, &pixels), "capture frame");
return pixels;
}
void drag(HWND window, bool left, int dx, int dy) {
const auto start = MAKELPARAM(420, 220), finish = MAKELPARAM(420 + dx, 220 + dy);
SendMessageW(window, left ? WM_LBUTTONDOWN : WM_MBUTTONDOWN, 0, start);
SendMessageW(window, WM_MOUSEMOVE, left ? MK_LBUTTON : MK_MBUTTON, finish);
SendMessageW(window, left ? WM_LBUTTONUP : WM_MBUTTONUP, 0, finish);
}
}
int main() {
auto clock = std::make_shared<Void::Time::ManualClock>();
auto worker = std::make_shared<Gate>(), writer = std::make_shared<Gate>(), installer = std::make_shared<Gate>();
auto reader = std::make_shared<Gate>();
std::atomic<bool> block_worker{false}, block_install{false}, block_reader{false};
std::atomic<DWORD> worker_thread{0};
HWND window = nullptr;
std::unique_ptr<settlement::SaveService> saves;
wchar_t temporary[MAX_PATH]{}; GetTempPathW(MAX_PATH, temporary);
const auto folder = std::filesystem::path(temporary) / (L"settlement-frames-" + std::to_wstring(GetCurrentProcessId()));
std::filesystem::create_directories(folder);
SetEnvironmentVariableW(L"LOCALAPPDATA", folder.c_str());
try {
auto colony = settlement::make_first_colony(2);
std::istringstream input(canonical(*colony), std::ios::binary);
settlement::WorkerPoolOptions workers;
workers.before_execute = [&](std::size_t) {
if (block_worker.exchange(false)) { worker_thread = GetCurrentThreadId(); worker->block(); }
};
auto owned = settlement::World::read_save(input, 2, settlement::ExecutionMode::Parallel, std::move(workers));
auto id = Void::Uuid::try_v4(); auto rules = settlement::default_rules_manifest();
require_frame(id.has_value() && rules.has_value(), "fixture identity/rules");
settlement::viewer::ViewerSessionOptions options;
options.runtime.clock = clock;
options.runtime.observer = [&](settlement::RuntimePhase phase) {
if (phase == settlement::RuntimePhase::BeforeInstallCapture && block_install.exchange(false)) installer->block();
};
options.files.read_observer = [&](settlement::CheckpointReadPhase phase) {
if (phase == settlement::CheckpointReadPhase::BeforeRead && block_reader.exchange(false)) reader->block();
};
session = std::make_unique<settlement::viewer::ViewerSession>(
settlement::WorldCheckpoint{std::move(owned), *id, 1, *rules}, 2, std::move(options));
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES}; InitCommonControlsEx(&controls);
WNDCLASSEXW klass{}; klass.cbSize = sizeof(klass); klass.hInstance = GetModuleHandleW(nullptr);
klass.lpfnWndProc = window_proc; klass.lpszClassName = window_class;
require_frame(RegisterClassExW(&klass) != 0, "register viewer");
window = CreateWindowExW(0, window_class, L"Prepared frame regression", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
0, 0, 1120, 752, nullptr, nullptr, klass.hInstance, nullptr);
require_frame(window != nullptr && scene_window != nullptr, "real main and scene windows");
ShowWindow(window, SW_SHOW);
KillTimer(window, timer_id); KillTimer(window, frame_timer_id); // Test drives each timer explicitly.
world = session->world(); has_session = true; show_title_screen(window, false);
const bool warp_device = probe_device(D3D_DRIVER_TYPE_WARP);
const bool hardware_device = probe_device(D3D_DRIVER_TYPE_HARDWARE);
if (!graphics.ready()) {
require_frame(!warp_device && !hardware_device, "renderer failed despite available D3D device");
std::puts("SKIP D3D11 hardware and WARP unavailable; real frame assertions require a backend");
DestroyWindow(window); session.reset(); std::filesystem::remove_all(folder); return 77;
}
event_and_frame(window);
require_frame(prepared_frame && prepared_frame->content && graphics.frames() > 0, "first real child render");
settlement::viewer::D3DScene offscreen;
const bool warp = offscreen.initialize(nullptr, true);
if (!warp) {
require_frame(!warp_device, "WARP renderer failed despite available device");
require_frame(offscreen.initialize(nullptr), "offscreen hardware fallback");
}
std::printf("BACKEND offscreen %s; visible D3D11 swap chain\n", warp ? "WARP" : "hardware");
// Ensure ticking has been admitted before holding an actual World worker.
event_and_frame(window);
auto sync = session->runtime().synchronize();
require_frame(sync.admission == settlement::RuntimeAdmission::Accepted && sync.completion.wait_for(10s) == std::future_status::ready, "owner synchronized");
event_and_frame(window);
block_worker = true; require_frame(clock->advance(50ms).has_value(), "clock advance");
session->runtime().notify_clock(); worker->wait();
require_frame(worker_thread != GetCurrentThreadId(), "worker is not UI thread");
const auto original = session->runtime().latest();
const auto original_bytes = canonical(*original->world);
auto encoded = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
require_frame(encoded.has_value(), "encode full snapshot");
settlement::SaveServiceOptions save_options;
save_options.fault_hook = [&](settlement::SavePhase phase) -> std::uint32_t {
if (phase == settlement::SavePhase::WriteStage) writer->block();
return 0;
};
saves = std::make_unique<settlement::SaveService>(std::move(save_options));
const auto path = folder / L"held.settlement";
auto saved = saves->try_submit({path, original->world->tick(), original->identity.session, [original] {
auto bytes = settlement::encode_checkpoint(*original->world, original->identity.world, original->identity.city, *original->rules);
if (!bytes) throw std::runtime_error("encode save");
return *bytes;
}});
require_frame(saved.admission == settlement::SaveAdmission::Accepted, "writer admitted"); writer->wait();
const auto initial = prepared_frame;
const auto pixels = capture_frame(offscreen, initial);
const auto uploads = graphics.uploads(), frames = graphics.frames();
POINT anchor{420, 220}; ClientToScreen(window, &anchor);
SendMessageW(window, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), MAKELPARAM(anchor.x, anchor.y));
frame_only(window);
require_frame(prepared_frame->view.scale != initial->view.scale && graphics.frames() > frames, "frame timer alone presents wheel");
require_frame(prepared_frame->content->geometry == initial->content->geometry && graphics.uploads() == uploads, "zoom reuses CPU/GPU geometry");
require_frame(capture_frame(offscreen, prepared_frame) != pixels, "zoom changes rendered pixels");
const auto before_drag = prepared_frame;
drag(window, false, 35, 18); frame_only(window);
require_frame(prepared_frame->view.origin_x != before_drag->view.origin_x, "middle drag changes frame");
const auto before_left = prepared_frame;
drag(window, true, -24, 16); frame_only(window);
require_frame(prepared_frame->view.origin_y != before_left->view.origin_y, "left drag changes frame");
require_frame(graphics.uploads() == uploads && prepared_frame->content->geometry == initial->content->geometry, "both drags reuse upload");
const auto prior_building_view = prepared_frame->content->geometry;
SendMessageW(window, WM_COMMAND, building_view_id, 0); frame_only(window);
require_frame(prepared_frame->content->geometry != prior_building_view, "building visibility invalidates geometry");
const auto stable_frames = graphics.frames();
frame_only(window); frame_only(window);
require_frame(graphics.frames() == stable_frames, "unchanged frame timer does no rendering");
require_frame(session->runtime().latest() == original && canonical(*original->world) == original_bytes, "blocked world snapshot/tick unchanged");
std::puts("PASS wheel and both real drags/rendered pixels while World worker and WriteStage held; frame timer independent; geometry/upload reused");
// Dirty work arriving inside a nested paint must survive the outer paint.
bool nested = false;
frame_test_during_paint = [&] {
if (nested) return; nested = true;
camera.pan(9, 0); invalidate_scene(window);
SendMessageW(scene_window, WM_PAINT, 0, 0);
};
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
require_frame(frame_requests != sampled_request, "nested paint leaves dirty request pending");
frame_only(window); require_frame(frame_requests == sampled_request, "next frame consumes nested dirty request");
// An exposure paint can nest without changing camera or world content.
frame_test_during_paint = [&] { SendMessageW(scene_window, WM_PAINT, 0, 0); };
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
const auto exposed_frames = graphics.frames();
frame_only(window);
require_frame(graphics.frames() > exposed_frames, "nested unchanged exposure is repainted");
// Owned overlay data and old geometry survive later edits/publications.
blueprint.push_back({{6, 10}, settlement::RecipeId::BuildBed});
room_blueprints.push_back({{20, 20}, {23, 23}, settlement::RoomSide::North});
selected_resident = world->agents().front().id;
invalidate_scene(window); frame_only(window);
const auto overlay = prepared_frame;
const auto old_pixels = capture_frame(offscreen, overlay);
blueprint.clear(); room_blueprints.clear(); selected_resident.reset();
invalidate_scene(window); frame_only(window);
require_frame(prepared_frame->content->geometry != overlay->content->geometry, "overlay invalidates geometry");
capture_frame(offscreen, prepared_frame);
require_frame(capture_frame(offscreen, overlay) == old_pixels && overlay->view.blueprint.size() == 1 && overlay->view.room_blueprints.size() == 1,
"retained old packet owns overlays and reuploads correct mesh");
worker->release(); writer->release();
require_frame(saved.completion.wait_for(10s) == std::future_status::ready && saved.completion.get().succeeded(), "held save completes");
saves.reset();
std::ifstream saved_file(path, std::ios::binary);
const std::string saved_bytes{std::istreambuf_iterator<char>(saved_file), {}}; saved_file.close();
require_frame(saved_bytes == *encoded, "saved bytes match full captured World and metadata");
std::puts("PASS nested paints retain pending dirt; retained packet/overlays; saved full canonical World and checkpoint metadata");
// A real file reader can remain blocked while the old presentation moves.
block_reader = true; handle_save_menu(window, false, path); reader->wait();
const auto before_read = prepared_frame;
drag(window, false, 12, 8); frame_only(window);
require_frame(session->changing_world() && prepared_frame->content == before_read->content &&
prepared_frame->view.origin_x != before_read->view.origin_x, "camera while file reader held");
reader->release();
std::puts("PASS real asynchronous file reader held while camera presents the prior packet");
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
// Deterministically publish between poll_changes' not-ready check and
// pump_session's world fetch, including nested paints in that interval.
auto install_race = [&](bool absent) {
installer = std::make_shared<Gate>(); block_install = true;
if (absent) { world.reset(); prepared_frame.reset(); }
const auto prior_world = world;
const auto prior_frame = prepared_frame;
session->new_colony();
event_and_frame(window); installer->wait();
const auto prior_session = session->runtime().latest()->identity.session;
bool injected = false;
frame_test_after_poll = [&] {
if (injected) return; injected = true;
require_frame(session->changing_world(), "poll still changing before install completion");
installer->release();
wait_for_frame([&] { return session->runtime().latest()->identity.session != prior_session; });
SendMessageW(window, WM_PAINT, 0, 0);
SendMessageW(scene_window, WM_PAINT, 0, 0);
};
SendMessageW(window, WM_TIMER, timer_id, 0);
frame_test_after_poll = {};
frame_only(window);
require_frame(world == prior_world, "pre-Replaced published candidate must not escape, including null");
require_frame(!prepared_frame->content || (prior_frame && prepared_frame->content == prior_frame->content), "old presentation content remains pinned");
wait_for_frame([&] { event_and_frame(window); return !session->changing_world(); });
require_frame(world == session->world() && prepared_frame->content->world == world &&
blueprint.empty() && room_blueprints.empty() && !selected_resident && camera.scale() == 1.0, "Replaced clears overlays/selection/camera before release");
};
install_race(false); install_race(true);
std::puts("PASS real publication race after poll/not-ready, nested main/child paints, old/null fence and Replaced reset");
const auto visible = prepared_frame;
const auto visible_frames = graphics.frames();
ShowWindow(window, SW_HIDE); drag(window, false, 10, 10); frame_only(window);
require_frame(prepared_frame == visible && graphics.frames() == visible_frames, "hidden suppresses preparation/render");
const auto hidden_command = session->submit(settlement::CommandPayload{settlement::CommandKind::SetPriority, {}, 2});
require_frame(hidden_command.has_value(), "hidden command admitted");
wait_for_frame([&] { event_and_frame(window); return !session->pending(*hidden_command); });
require_frame(prepared_frame == visible && world != visible->content->world, "hidden retains packet while world publishes");
ShowWindow(window, SW_SHOW); frame_only(window);
require_frame(prepared_frame->content->world == world, "restore presents latest accepted snapshot");
ShowWindow(window, SW_MINIMIZE); const auto minimized = prepared_frame;
invalidate_scene(window); frame_only(window);
require_frame(prepared_frame == minimized, "minimized suppresses preparation");
ShowWindow(window, SW_RESTORE); frame_only(window);
show_title_screen(window, true); const auto title_frame = prepared_frame;
invalidate_scene(window); frame_only(window); require_frame(prepared_frame == title_frame, "title suppresses preparation");
show_title_screen(window, false); frame_only(window);
const auto restore = prepared_frame;
const auto size_uploads = graphics.uploads();
SetWindowPos(window, nullptr, 0, 0, 1200, 800, SWP_NOMOVE | SWP_NOZORDER); frame_only(window);
require_frame(prepared_frame->content->geometry == restore->content->geometry && graphics.uploads() > size_uploads, "resize reuses CPU mesh and invalidates upload");
const auto zero_frames = graphics.frames();
SetWindowPos(scene_window, nullptr, 0, map_top, 0, 0, SWP_NOZORDER);
InvalidateRect(scene_window, nullptr, FALSE); SendMessageW(scene_window, WM_PAINT, 0, 0);
require_frame(graphics.frames() == zero_frames, "zero-sized real viewport suppresses render");
layout_scene(window); frame_only(window);
auto zero_view = prepared_frame->view; zero_view.height = 0;
require_frame(!offscreen.render(prepared_frame->content->geometry, zero_view), "zero viewport rejected");
auto bad_frame = std::make_shared<PreparedFrame>(*prepared_frame); bad_frame->view.height = 0;
prepared_frame = bad_frame;
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_only(window);
require_frame(!graphics.ready() && !prepared_frame->backend_ready, "render failure reaches current error HUD");
show_title_screen(window, true); show_title_screen(window, false); frame_only(window);
require_frame(graphics.ready() && prepared_frame->backend_ready, "menu retry recovers backend");
const auto reset_uploads = offscreen.uploads();
offscreen.reset(); require_frame(offscreen.initialize(nullptr, warp), "recreate offscreen backend");
require_frame(capture_frame(offscreen, overlay) == old_pixels && offscreen.uploads() > reset_uploads, "backend reset reuploads retained packet");
std::puts("PASS hidden/minimized/title/restore, resize, zero viewport, error HUD/recovery and backend reset");
const auto final_frames = graphics.frames();
frame_test_during_paint = [&] { DestroyWindow(window); };
InvalidateRect(scene_window, nullptr, FALSE); UpdateWindow(scene_window);
frame_test_during_paint = {};
window_proc(window, WM_TIMER, frame_timer_id, 0); window_proc(window, WM_TIMER, timer_id, 0);
require_frame(viewer_destroyed && !prepared_frame && !graphics.ready() && graphics.frames() == final_frames, "queued timers after destruction ignored");
window = nullptr; session.reset(); std::filesystem::remove_all(folder);
std::puts("PASS destruction and queued timers; no physical refresh-rate claim");
return 0;
} catch (const std::exception& error) {
frame_test_after_poll = {}; frame_test_during_paint = {};
worker->release(); writer->release(); installer->release(); reader->release();
saves.reset(); if (window) DestroyWindow(window); session.reset();
std::fprintf(stderr, "FAIL %s\n", error.what()); return 1;
}
}