Add deterministic transactional lifecycle command scheduler
This commit is contained in:
+1
-1
@@ -27,7 +27,7 @@ set(EVO_SANITIZER "none" CACHE STRING "none, address (ASan/UBSan), or thread")
|
|||||||
set_property(CACHE EVO_SANITIZER PROPERTY STRINGS none address thread)
|
set_property(CACHE EVO_SANITIZER PROPERTY STRINGS none address thread)
|
||||||
include(cmake/ProjectOptions.cmake)
|
include(cmake/ProjectOptions.cmake)
|
||||||
|
|
||||||
set(evo_simulation_sources src/simulation/world.cpp src/simulation/snapshot.cpp)
|
set(evo_simulation_sources src/simulation/world.cpp src/simulation/snapshot.cpp src/simulation/scheduler.cpp)
|
||||||
add_library(evo_simulation STATIC ${evo_simulation_sources})
|
add_library(evo_simulation STATIC ${evo_simulation_sources})
|
||||||
add_library(evo::simulation ALIAS evo_simulation)
|
add_library(evo::simulation ALIAS evo_simulation)
|
||||||
target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ network service. Dev verification manifests are separate from the simulation.
|
|||||||
- [Actual validation results](docs/engineering/VALIDATION.md)
|
- [Actual validation results](docs/engineering/VALIDATION.md)
|
||||||
- [Current delivery status and next steps](docs/STATUS.md)
|
- [Current delivery status and next steps](docs/STATUS.md)
|
||||||
- [Opt-in ECS evaluation and measurements](docs/engineering/ECS_EVALUATION.md)
|
- [Opt-in ECS evaluation and measurements](docs/engineering/ECS_EVALUATION.md)
|
||||||
|
- [Sequential command scheduling and recovery](docs/architecture/SCHEDULER_CONTRACT.md)
|
||||||
|
|
||||||
Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are
|
Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are
|
||||||
authoritative over implementation. No external runtime library is needed for
|
authoritative over implementation. No external runtime library is needed for
|
||||||
|
|||||||
+4
-3
@@ -28,13 +28,14 @@ independent reviews; dependent tasks begin after their contracts are settled.
|
|||||||
| 1.3 Canonical local snapshot and restore | simulation/snapshot.cpp, schemas/proof-snapshot.md | 1.2, ADR-0008 | Bounded versioned byte format; validate before publish | Round trip, corruption, overflow, truncation, version rejection | Unsafe parsing, native padding |
|
| 1.3 Canonical local snapshot and restore | simulation/snapshot.cpp, schemas/proof-snapshot.md | 1.2, ADR-0008 | Bounded versioned byte format; validate before publish | Round trip, corruption, overflow, truncation, version rejection | Unsafe parsing, native padding |
|
||||||
| 1.4 Freeze deterministic reference result | tests/simulation_tests.cpp | 1.3 | Continuous and restored runs match agreed fingerprint | Golden fingerprint and seeded property ensembles | Test only comparing same broken implementation |
|
| 1.4 Freeze deterministic reference result | tests/simulation_tests.cpp | 1.3 | Continuous and restored runs match agreed fingerprint | Golden fingerprint and seeded property ensembles | Test only comparing same broken implementation |
|
||||||
| 1.5 Evaluate mature ECS adoption | experiments/ecs/, ADR-0005, ADR-0021 | 1.2, biological component workload sketch | Measured iteration/lifecycle/serialization cost and scoped choice | Opt-in row/EnTT sparse/dense/churn comparison with canonical equality; production decision needs richer biology | Premature general framework |
|
| 1.5 Evaluate mature ECS adoption | experiments/ecs/, ADR-0005, ADR-0021 | 1.2, biological component workload sketch | Measured iteration/lifecycle/serialization cost and scoped choice | Opt-in row/EnTT sparse/dense/churn comparison with canonical equality; production decision needs richer biology | Premature general framework |
|
||||||
| 1.6 Establish scheduler and input phases | simulation/scheduler/, core/time/ | 1.4–1.5 | Explicit phase DAG, one writer, immutable jobs and stable merge | Reordered completion gives equal state; command ordering tests | Hidden concurrency nondeterminism |
|
| 1.6 Establish scheduler and input phases | simulation/scheduler.*, ADR-0022 | 1.4–1.5 | Sequential phase DAG, one writer, immutable bounded commands and atomic commit; parallel jobs deferred | Permuted delivery gives equal state; admission, rollback and recovery tests | Hidden ordering and partial mutation |
|
||||||
| 1.7 Add spatial contract | simulation/spatial/, units ADR | 1.5–1.6 | Local coordinates and bounded neighborhood queries | Boundary/wrap/precision properties and brute-force comparison | Planet precision leaking into local physics |
|
| 1.7 Add spatial contract | simulation/spatial/, units ADR | 1.5–1.6 | Local coordinates and bounded neighborhood queries | Boundary/wrap/precision properties and brute-force comparison | Planet precision leaking into local physics |
|
||||||
|
|
||||||
The first increment implements 1.1–1.4 as a proof. M1.5 now has an isolated
|
The first increment implements 1.1–1.4 as a proof. M1.5 now has an isolated
|
||||||
comparison and scoped recommendation; see engineering/ECS_EVALUATION.md for
|
comparison and scoped recommendation; see engineering/ECS_EVALUATION.md for
|
||||||
measured versus still-unmeasured coverage. M1.6–1.7 remain separate work; no
|
measured versus still-unmeasured coverage. M1.6 implements the sequential command
|
||||||
scheduler or generic ECS placeholder is counted as completion.
|
boundary in ADR-0022; no parallel job execution is claimed. M1.7 spatial queries
|
||||||
|
are next. A generic ECS or job framework is not required to complete this proof.
|
||||||
|
|
||||||
## M2 — Minimal energy ecosystem
|
## M2 — Minimal energy ecosystem
|
||||||
|
|
||||||
|
|||||||
+18
-8
@@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged.
|
|||||||
## Completed implementation
|
## Completed implementation
|
||||||
|
|
||||||
- Vision, architectural pillars, risks, open-question register, architecture
|
- Vision, architectural pillars, risks, open-question register, architecture
|
||||||
diagrams, biological contracts, engineering constitution and 21 ADRs.
|
diagrams, biological contracts, engineering constitution and 22 ADRs.
|
||||||
Proposed/deferred choices remain distinct from accepted proof decisions.
|
Proposed/deferred choices remain distinct from accepted proof decisions.
|
||||||
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
|
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
|
||||||
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
|
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
|
||||||
@@ -37,8 +37,9 @@ Windows checks also pass; full commands and intermediate CI failures are recorde
|
|||||||
in the validation report. M0's engineering proof is verified; dev cluster
|
in the validation report. M0's engineering proof is verified; dev cluster
|
||||||
execution is the remaining delivery check, not a claim of persistent-world readiness.
|
execution is the remaining delivery check, not a claim of persistent-world readiness.
|
||||||
|
|
||||||
The maintainer reports Argo is configured. This workspace has no kubeconfig;
|
The maintainer confirms Argo is configured and deployment additions will sync
|
||||||
the app/source mapping and completed dev Job are not yet independently verified.
|
when a pod workload is ready. This workspace has no kubeconfig, so completed dev
|
||||||
|
Job execution is not independently verified. This is not a blocker for M1.
|
||||||
The repository supplies a restricted dev Job and bootstrap examples; image
|
The repository supplies a restricted dev Job and bootstrap examples; image
|
||||||
publication does not demonstrate a Kubernetes rollout or world recovery.
|
publication does not demonstrate a Kubernetes rollout or world recovery.
|
||||||
|
|
||||||
@@ -58,11 +59,20 @@ for the bounded proof; the general production ECS remains a later measured choic
|
|||||||
|
|
||||||
| Priority | Work | Completion evidence |
|
| Priority | Work | Completion evidence |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 | Verify the existing dev Argo mapping and sync the pinned, validated image | Dev Job Complete with replay_verified=true; no World0 changes |
|
| 1 | M1.7 local spatial contract | Neighborhood queries checked against brute force, wrap/boundary/unit tests and measured workload |
|
||||||
| 2 | M1.6 scheduler/input contract: ratify phase order and command admission before implementing a sequential scheduler | Stable input order, one writer, deterministic merges and replay equivalence |
|
| 2 | M2.1 energy/matter ledger | Agreed units/ranges, atomic transfers, nonnegative balances and conservation tests before organisms |
|
||||||
| 3 | M1.7 local spatial contract | Neighborhood queries checked against brute force, wrap/boundary/unit tests and measured workload |
|
| 3 | M2.2–2.6 first headless energy cycle | Explicit source → producer → consumer → death → decomposition → nutrients; seeded million-tick ledger evidence |
|
||||||
| 4 | M2.1 energy/matter ledger | Agreed units/ranges, atomic transfers, nonnegative balances and conservation tests before organisms |
|
| Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes |
|
||||||
| 5 | M2.2–2.6 first headless energy cycle | Explicit source → producer → consumer → death → decomposition → nutrients; seeded million-tick ledger evidence |
|
|
||||||
|
M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md):
|
||||||
|
exact-tick admission, bounded ordered lifecycle commands, receipts and atomic
|
||||||
|
rollback on rejection. Windows Release, clang-tidy, ASan and formatting checks
|
||||||
|
pass. Permutations across 32 seeds, restored continuation, duplicate/late/future
|
||||||
|
inputs, limits and exhaustion are covered. The no-input golden and snapshot v1
|
||||||
|
are unchanged. Linux CI evidence is recorded in the validation report after push.
|
||||||
|
Nonempty batches copy world state; this favors a clear transaction boundary for
|
||||||
|
the proof, not a measured realtime performance claim. No thread pool or gameplay
|
||||||
|
input protocol is introduced.
|
||||||
|
|
||||||
Before biology, resolve the relevant heredity and energetic contracts rather
|
Before biology, resolve the relevant heredity and energetic contracts rather
|
||||||
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
|
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# ADR-0022: Transactional sequential command scheduling
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Adopted for the synthetic M1.6 proof only. No gameplay input or concurrency policy
|
||||||
|
is selected by this decision.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
M1.5 retains the bounded row store. Before adding systems, replay needs an explicit
|
||||||
|
input cutoff, total order and failure boundary. The kernel cannot depend on packet
|
||||||
|
arrival order, clocks, threads or authenticated session state.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Add `advance(world, target_tick, commands)` in a scheduler module. The target is
|
||||||
|
the next completed tick (`current_tick + 1`). Admit at most 1,024 immutable
|
||||||
|
commands, each with a nonzero host-assigned sequence unique within that tick.
|
||||||
|
Sort by sequence; reject duplicate sequences even if payloads match. Reject past
|
||||||
|
and future targets rather than queueing, retiming or rolling back. Sequences may
|
||||||
|
restart in a later tick; the pair (target tick, sequence) is the identity.
|
||||||
|
|
||||||
|
The phase DAG is admission → ordered lifecycle commands → synthetic movement →
|
||||||
|
tick commit → returned receipts. Commands wrap the existing create/remove API;
|
||||||
|
they are trusted host lifecycle operations, not player permissions or movement.
|
||||||
|
Receipts are sorted by sequence and contain the resulting affected entity ID.
|
||||||
|
|
||||||
|
Execute nonempty batches against a private copy; publish by noexcept move only
|
||||||
|
after every command, receipt allocation and tick succeeds. Any recoverable error
|
||||||
|
rejects the entire batch. Empty batches call the existing allocation-free tick.
|
||||||
|
No queue, callbacks, threads or job system are introduced. One owner calls the
|
||||||
|
kernel; direct lifecycle methods remain available for setup and existing callers.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
|
||||||
|
Arrival-order mutation cannot replay reordered delivery. Per-command partial
|
||||||
|
success complicates recovery. Undo logs or staged component writes may eventually
|
||||||
|
reduce copy cost but require broader contracts. An extensible phase executor or
|
||||||
|
parallel task graph has no measured workload yet.
|
||||||
|
|
||||||
|
## Benefits
|
||||||
|
|
||||||
|
Stable ordering, atomic rejection, bounded admission and an explicit recovery
|
||||||
|
boundary without changes to the existing snapshot or no-input golden.
|
||||||
|
|
||||||
|
## Costs
|
||||||
|
|
||||||
|
Nonempty ticks copy all current rows and allocate receipts. The host must retain
|
||||||
|
the admitted command stream externally if it needs replay. Copy performance must
|
||||||
|
be measured before adopting this approach for a realtime server.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
These operations are not safe to expose directly to clients. A host must validate
|
||||||
|
authorization, assign ordering keys and bound ingress. A malformed batch can
|
||||||
|
reject otherwise valid work; host admission must isolate untrusted requests.
|
||||||
|
Synthetic tests do not validate parallel execution or crash durability.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
Snapshots remain format/rules v1: no new persistent state or changed movement
|
||||||
|
laws. Scheduler contract v1 is identified separately; future command journals
|
||||||
|
must store it with admitted inputs. Checkpoint only at completed ticks, then
|
||||||
|
replay subsequent admitted batches. There is no pending input inside snapshots.
|
||||||
|
Future jobs must return immutable, stably keyed results and have explicit merge
|
||||||
|
conflict rules; implementing that executor remains deferred until actual work
|
||||||
|
exists. Test permutations, duplicate/late/future admission, lifecycle conflicts,
|
||||||
|
limits, exhaustion, rollback and restored continuation under NDEBUG.
|
||||||
@@ -14,6 +14,7 @@ messaging and metrics. 0016–0019 cover durability/ownership, networking/securi
|
|||||||
infrastructure and voxels. 0020 scopes Gitea delivery and the stateless dev Job.
|
infrastructure and voxels. 0020 scopes Gitea delivery and the stateless dev Job.
|
||||||
Each record has the eight required sections.
|
Each record has the eight required sections.
|
||||||
0021 authorizes the opt-in ECS comparison only, not a production dependency.
|
0021 authorizes the opt-in ECS comparison only, not a production dependency.
|
||||||
|
0022 adopts the bounded sequential lifecycle-command scheduler for the proof.
|
||||||
|
|
||||||
Every dependency adoption records exact version/commit and integrity hash,
|
Every dependency adoption records exact version/commit and integrity hash,
|
||||||
transitive license obligations, maintenance/security review, owner and removal
|
transitive license obligations, maintenance/security review, owner and removal
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Sequential scheduler contract v1
|
||||||
|
|
||||||
|
This implements the scoped decision in [ADR-0022](../adr/0022-sequential-command-scheduler.md).
|
||||||
|
It is a synthetic lifecycle proof, not a player input protocol.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
H[Host: validate and assign sequence] --> A[Admit exact next tick / bounded batch]
|
||||||
|
A --> O[Sort unique sequences]
|
||||||
|
O --> C[Private candidate: ordered create/remove]
|
||||||
|
C --> S[Stable entity-order synthetic movement]
|
||||||
|
S --> P[Commit world and return ordered receipts]
|
||||||
|
A -->|invalid| R[Reject without changing world]
|
||||||
|
C -->|invalid| R
|
||||||
|
```
|
||||||
|
|
||||||
|
`advance(SimulationWorld&, Tick target, span<const Command>)` returns
|
||||||
|
`expected<vector<CommandReceipt>, ScheduleError>`. Errors distinguish admission
|
||||||
|
failures from command/tick failures; the latter include the existing `Error` cause
|
||||||
|
and command sequence (zero for the tick itself). No references to input survive
|
||||||
|
the call. The owner must not mutate world or input concurrently.
|
||||||
|
|
||||||
|
| Boundary | Invariant |
|
||||||
|
|---|---|
|
||||||
|
| Admission | Next completed tick only; at most 1,024 commands; nonzero unique sequence per tick |
|
||||||
|
| Ordering | Sequence alone defines execution; input span order cannot change results |
|
||||||
|
| Lifecycle | Create starts participating in movement this tick; removed entities do not move; IDs are never reused |
|
||||||
|
| Conflict | A second removal of the same entity rejects the entire batch, including earlier creations |
|
||||||
|
| Commit | Errors and allocation exceptions leave original world unchanged; successful call increments tick exactly once |
|
||||||
|
| Receipt | One affected entity ID per command, in sequence order, published only on success |
|
||||||
|
| Recovery | Snapshot after tick T plus admitted batches T+1 onward equals uninterrupted execution |
|
||||||
|
| Retry | Retrying a committed target is rejected; no durable exactly-once acknowledgment is claimed |
|
||||||
|
|
||||||
|
The host assigns sequences before dispatching any future immutable work. Completion
|
||||||
|
order must not assign them. Permutation tests model reordered delivery, not
|
||||||
|
concurrent execution. A host journals validated batches and durable outcomes at
|
||||||
|
its later persistence boundary; it must never assume a returned receipt is durable.
|
||||||
|
Future-target buffering, session deduplication, authorization and pacing remain
|
||||||
|
outside this library. There is no player/NPC behavior or offline progression here.
|
||||||
|
|
||||||
|
Existing `tick()` means an empty input tick and preserves the frozen v1 golden.
|
||||||
|
Existing direct create/remove are setup/tool APIs; a replaying host must use a
|
||||||
|
single recorded mutation path. This phase chain is deliberately concrete; no
|
||||||
|
generic registration API or speculative thread pool is part of M1.6.
|
||||||
@@ -67,6 +67,10 @@ simulation rules change.
|
|||||||
|
|
||||||
## Scheduling and pacing
|
## Scheduling and pacing
|
||||||
|
|
||||||
|
The sequential lifecycle scheduler and atomic input boundary are specified in
|
||||||
|
[SCHEDULER_CONTRACT.md](SCHEDULER_CONTRACT.md) and ADR-0022. The input-free tick
|
||||||
|
remains unchanged; lifecycle commands are synthetic host operations only.
|
||||||
|
|
||||||
The kernel accepts no `deltaTime` argument. The executable advances an exact
|
The kernel accepts no `deltaTime` argument. The executable advances an exact
|
||||||
requested number of ticks. A future realtime host converts monotonic wall time
|
requested number of ticks. A future realtime host converts monotonic wall time
|
||||||
into tick debt; it must cap catch-up work, emit overload metrics and shed region
|
into tick debt; it must cap catch-up work, emit overload metrics and shed region
|
||||||
|
|||||||
@@ -130,3 +130,20 @@ results/ecs-gcc142.jsonl; all 56 fingerprints match corresponding Windows sample
|
|||||||
No production rule or snapshot-format change occurred. This supersedes the
|
No production rule or snapshot-format change occurred. This supersedes the
|
||||||
pending Linux experiment note above. The final follow-up edits only record
|
pending Linux experiment note above. The final follow-up edits only record
|
||||||
results and decision scope; production ECS adoption remains deferred.
|
results and decision scope; production ECS adoption remains deferred.
|
||||||
|
|
||||||
|
## M1.6 sequential scheduler (2026-09-19)
|
||||||
|
|
||||||
|
Native commands: `tools/windows-check.ps1 -Preset release -Action configure`,
|
||||||
|
clang-format on changed C++ files, `cmake --build --preset release`,
|
||||||
|
`ctest --preset release`; then `tools/windows-check.ps1 -Preset analysis -Action check`,
|
||||||
|
`tools/windows-check.ps1 -Preset asan -Action check` and Release `-Action format`.
|
||||||
|
All three configurations passed 5/5 CTests; clang-tidy and format-check passed.
|
||||||
|
Tests execute under NDEBUG and cover six batch permutations across 32 seeds,
|
||||||
|
an independent direct-lifecycle reference, ordered receipts, restore continuation,
|
||||||
|
rejected conflicts and malformed admission, the 1,024-command boundary, full entity
|
||||||
|
capacity and tick/ID exhaustion. Golden `d61ad5bf0c928c76` remains unchanged.
|
||||||
|
|
||||||
|
The copy-and-commit implementation allocates before publishing world state and
|
||||||
|
statically checks noexcept publication/receipt moves. Allocation-failure injection
|
||||||
|
was not run. No scheduler throughput claim, concurrency validation, durable input
|
||||||
|
journal or Kubernetes execution is implied. Linux CI is pending this source push.
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "evo/simulation/world.hpp"
|
||||||
|
|
||||||
|
#include <optional>
|
||||||
|
#include <variant>
|
||||||
|
|
||||||
|
namespace evo {
|
||||||
|
inline constexpr std::uint32_t scheduler_version = 1;
|
||||||
|
inline constexpr std::size_t max_commands_per_tick = 1'024;
|
||||||
|
|
||||||
|
struct CreateEntity {
|
||||||
|
Position2 position{};
|
||||||
|
};
|
||||||
|
struct RemoveEntity {
|
||||||
|
EntityId id;
|
||||||
|
};
|
||||||
|
struct Command {
|
||||||
|
std::uint64_t sequence;
|
||||||
|
std::variant<CreateEntity, RemoveEntity> operation;
|
||||||
|
};
|
||||||
|
struct CommandReceipt {
|
||||||
|
std::uint64_t sequence;
|
||||||
|
EntityId entity;
|
||||||
|
auto operator<=>(const CommandReceipt&) const = default;
|
||||||
|
};
|
||||||
|
enum class ScheduleErrorCode : std::uint8_t {
|
||||||
|
wrong_tick,
|
||||||
|
batch_limit,
|
||||||
|
invalid_sequence,
|
||||||
|
duplicate_sequence,
|
||||||
|
simulation_failure
|
||||||
|
};
|
||||||
|
struct ScheduleError {
|
||||||
|
ScheduleErrorCode code;
|
||||||
|
std::uint64_t sequence{};
|
||||||
|
std::optional<Error> cause{};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Single-owner call. No input is retained. Rejection leaves world unchanged.
|
||||||
|
// target is the next completed tick; receipts follow ascending sequence.
|
||||||
|
[[nodiscard]] std::expected<std::vector<CommandReceipt>, ScheduleError>
|
||||||
|
advance(SimulationWorld& world, Tick target, std::span<const Command> commands = {});
|
||||||
|
} // namespace evo
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
#include "evo/simulation/scheduler.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <limits>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace evo {
|
||||||
|
std::expected<std::vector<CommandReceipt>, ScheduleError>
|
||||||
|
advance(SimulationWorld& world, Tick target, std::span<const Command> commands) {
|
||||||
|
if (world.current_tick().value == std::numeric_limits<std::uint64_t>::max()) {
|
||||||
|
return std::unexpected{
|
||||||
|
ScheduleError{ScheduleErrorCode::simulation_failure, 0, Error::tick_exhausted}};
|
||||||
|
}
|
||||||
|
if (target.value != world.current_tick().value + 1) {
|
||||||
|
return std::unexpected{ScheduleError{ScheduleErrorCode::wrong_tick}};
|
||||||
|
}
|
||||||
|
if (commands.size() > max_commands_per_tick) {
|
||||||
|
return std::unexpected{ScheduleError{ScheduleErrorCode::batch_limit}};
|
||||||
|
}
|
||||||
|
if (commands.empty()) {
|
||||||
|
const auto result = world.tick();
|
||||||
|
if (!result) {
|
||||||
|
return std::unexpected{
|
||||||
|
ScheduleError{ScheduleErrorCode::simulation_failure, 0, result.error()}};
|
||||||
|
}
|
||||||
|
return std::vector<CommandReceipt>{};
|
||||||
|
}
|
||||||
|
std::vector<Command> ordered{commands.begin(), commands.end()};
|
||||||
|
std::ranges::sort(ordered, {}, &Command::sequence);
|
||||||
|
std::uint64_t previous{};
|
||||||
|
for (const auto& command : ordered) {
|
||||||
|
if (command.sequence == 0) {
|
||||||
|
return std::unexpected{ScheduleError{ScheduleErrorCode::invalid_sequence}};
|
||||||
|
}
|
||||||
|
if (command.sequence == previous) {
|
||||||
|
return std::unexpected{
|
||||||
|
ScheduleError{ScheduleErrorCode::duplicate_sequence, command.sequence}};
|
||||||
|
}
|
||||||
|
previous = command.sequence;
|
||||||
|
}
|
||||||
|
auto candidate = world;
|
||||||
|
std::vector<CommandReceipt> receipts;
|
||||||
|
receipts.reserve(ordered.size());
|
||||||
|
for (const auto& command : ordered) {
|
||||||
|
EntityId affected{};
|
||||||
|
if (const auto* create = std::get_if<CreateEntity>(&command.operation)) {
|
||||||
|
const auto result = candidate.create_entity(create->position);
|
||||||
|
if (!result) {
|
||||||
|
return std::unexpected{ScheduleError{ScheduleErrorCode::simulation_failure,
|
||||||
|
command.sequence, result.error()}};
|
||||||
|
}
|
||||||
|
affected = *result;
|
||||||
|
} else {
|
||||||
|
affected = std::get<RemoveEntity>(command.operation).id;
|
||||||
|
const auto result = candidate.remove_entity(affected);
|
||||||
|
if (!result) {
|
||||||
|
return std::unexpected{ScheduleError{ScheduleErrorCode::simulation_failure,
|
||||||
|
command.sequence, result.error()}};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
receipts.push_back({command.sequence, affected});
|
||||||
|
}
|
||||||
|
const auto result = candidate.tick();
|
||||||
|
if (!result) {
|
||||||
|
return std::unexpected{
|
||||||
|
ScheduleError{ScheduleErrorCode::simulation_failure, 0, result.error()}};
|
||||||
|
}
|
||||||
|
static_assert(std::is_nothrow_move_assignable_v<SimulationWorld>);
|
||||||
|
static_assert(std::is_nothrow_move_constructible_v<std::vector<CommandReceipt>>);
|
||||||
|
world = std::move(candidate);
|
||||||
|
return receipts;
|
||||||
|
}
|
||||||
|
} // namespace evo
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
|
#include "evo/simulation/scheduler.hpp"
|
||||||
#include "evo/simulation/world.hpp"
|
#include "evo/simulation/world.hpp"
|
||||||
#include "evo/telemetry/sinks.hpp"
|
#include "evo/telemetry/sinks.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <exception>
|
#include <exception>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
@@ -217,6 +219,100 @@ void telemetry_is_host_owned() {
|
|||||||
evo::log_error(log, evo::Error::invalid_snapshot);
|
evo::log_error(log, evo::Error::invalid_snapshot);
|
||||||
CHECK(log.str() == "{\"level\":\"error\",\"event\":\"invalid_snapshot\"}\n");
|
CHECK(log.str() == "{\"level\":\"error\",\"event\":\"invalid_snapshot\"}\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void scheduled_order_and_recovery() {
|
||||||
|
for (std::uint64_t seed = 0; seed < 32; ++seed) {
|
||||||
|
auto expected = fixture(seed, 2);
|
||||||
|
CHECK(expected.remove_entity(evo::EntityId{1}));
|
||||||
|
CHECK(expected.create_entity({evo::Millimetres{1023}, evo::Millimetres{0}}));
|
||||||
|
CHECK(expected.create_entity());
|
||||||
|
CHECK(expected.tick());
|
||||||
|
std::array commands{
|
||||||
|
evo::Command{10, evo::RemoveEntity{evo::EntityId{1}}},
|
||||||
|
evo::Command{20, evo::CreateEntity{{evo::Millimetres{1023}, evo::Millimetres{0}}}},
|
||||||
|
evo::Command{30, evo::CreateEntity{}}};
|
||||||
|
do {
|
||||||
|
auto world = fixture(seed, 2);
|
||||||
|
const auto receipts = evo::advance(world, evo::Tick{1}, commands);
|
||||||
|
CHECK(receipts && receipts->size() == 3);
|
||||||
|
CHECK((*receipts)[0] == (evo::CommandReceipt{10, evo::EntityId{1}}));
|
||||||
|
CHECK((*receipts)[1] == (evo::CommandReceipt{20, evo::EntityId{3}}));
|
||||||
|
CHECK((*receipts)[2] == (evo::CommandReceipt{30, evo::EntityId{4}}));
|
||||||
|
CHECK(world.serialize() == expected.serialize());
|
||||||
|
auto restored = evo::SimulationWorld::restore(world.serialize());
|
||||||
|
CHECK(restored);
|
||||||
|
for (std::uint64_t tick = 2; tick < 20; ++tick) {
|
||||||
|
const std::array next{evo::Command{1, evo::CreateEntity{}}};
|
||||||
|
CHECK(evo::advance(world, evo::Tick{tick}, next));
|
||||||
|
CHECK(evo::advance(*restored, evo::Tick{tick}, next));
|
||||||
|
}
|
||||||
|
CHECK(restored->serialize() == world.serialize());
|
||||||
|
} while (std::ranges::next_permutation(commands, {}, &evo::Command::sequence).found);
|
||||||
|
}
|
||||||
|
auto scheduled = fixture(123456, 8);
|
||||||
|
for (std::uint64_t tick = 1; tick <= 1000; ++tick) {
|
||||||
|
CHECK(evo::advance(scheduled, evo::Tick{tick}));
|
||||||
|
}
|
||||||
|
CHECK(scheduled.state_hash() == 0xd61ad5bf0c928c76ULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void scheduled_rejection() {
|
||||||
|
auto world = fixture(17, 2);
|
||||||
|
const auto before = world.serialize();
|
||||||
|
const auto reject = [&](evo::Tick tick, std::span<const evo::Command> commands,
|
||||||
|
evo::ScheduleErrorCode code) {
|
||||||
|
const auto result = evo::advance(world, tick, commands);
|
||||||
|
CHECK(!result && result.error().code == code);
|
||||||
|
CHECK(world.serialize() == before);
|
||||||
|
return result.error();
|
||||||
|
};
|
||||||
|
reject(evo::Tick{0}, {}, evo::ScheduleErrorCode::wrong_tick);
|
||||||
|
reject(evo::Tick{2}, {}, evo::ScheduleErrorCode::wrong_tick);
|
||||||
|
std::array commands{evo::Command{1, evo::CreateEntity{}},
|
||||||
|
evo::Command{1, evo::RemoveEntity{evo::EntityId{1}}}};
|
||||||
|
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::duplicate_sequence);
|
||||||
|
commands[1].sequence = 0;
|
||||||
|
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::invalid_sequence);
|
||||||
|
commands[1] = evo::Command{2, evo::RemoveEntity{evo::EntityId{99}}};
|
||||||
|
auto error = reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
|
||||||
|
CHECK(error.sequence == 2 && error.cause == evo::Error::entity_not_found);
|
||||||
|
commands[1] = evo::Command{2, evo::CreateEntity{{evo::Millimetres{1024}, {}}}};
|
||||||
|
error = reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
|
||||||
|
CHECK(error.cause == evo::Error::invalid_position);
|
||||||
|
commands = {evo::Command{1, evo::RemoveEntity{evo::EntityId{1}}},
|
||||||
|
evo::Command{2, evo::RemoveEntity{evo::EntityId{1}}}};
|
||||||
|
reject(evo::Tick{1}, commands, evo::ScheduleErrorCode::simulation_failure);
|
||||||
|
std::vector<evo::Command> large(evo::max_commands_per_tick + 1,
|
||||||
|
evo::Command{1, evo::CreateEntity{}});
|
||||||
|
reject(evo::Tick{1}, large, evo::ScheduleErrorCode::batch_limit);
|
||||||
|
large.pop_back();
|
||||||
|
for (std::size_t index = 0; index < large.size(); ++index) {
|
||||||
|
large[index].sequence = index + 1;
|
||||||
|
}
|
||||||
|
CHECK(evo::advance(world, evo::Tick{1}, large));
|
||||||
|
const auto committed = world.serialize();
|
||||||
|
const auto retry = evo::advance(world, evo::Tick{1}, large);
|
||||||
|
CHECK(!retry && retry.error().code == evo::ScheduleErrorCode::wrong_tick);
|
||||||
|
CHECK(world.serialize() == committed);
|
||||||
|
|
||||||
|
auto full = fixture(1, evo::max_entities);
|
||||||
|
const auto full_before = full.serialize();
|
||||||
|
const std::array create{evo::Command{1, evo::CreateEntity{}}};
|
||||||
|
const auto capacity = evo::advance(full, evo::Tick{1}, create);
|
||||||
|
CHECK(!capacity && capacity.error().cause == evo::Error::entity_limit);
|
||||||
|
CHECK(full.serialize() == full_before);
|
||||||
|
for (const auto offset : {32U, 40U}) {
|
||||||
|
auto bytes = before;
|
||||||
|
put(bytes, offset, std::numeric_limits<std::uint64_t>::max(), 8);
|
||||||
|
resign(bytes);
|
||||||
|
auto exhausted = evo::SimulationWorld::restore(bytes);
|
||||||
|
CHECK(exhausted);
|
||||||
|
const auto result = evo::advance(*exhausted, evo::Tick{1}, create);
|
||||||
|
CHECK(!result && result.error().cause == (offset == 32 ? evo::Error::tick_exhausted
|
||||||
|
: evo::Error::id_exhausted));
|
||||||
|
CHECK(exhausted->serialize() == bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
int main(int argc, char**) try {
|
int main(int argc, char**) try {
|
||||||
@@ -242,7 +338,9 @@ int main(int argc, char**) try {
|
|||||||
Test{"atomic exhaustion", exhaustion_is_atomic},
|
Test{"atomic exhaustion", exhaustion_is_atomic},
|
||||||
Test{"capacity", capacity_boundary},
|
Test{"capacity", capacity_boundary},
|
||||||
Test{"canonical empty state", wire_layout_and_empty_state},
|
Test{"canonical empty state", wire_layout_and_empty_state},
|
||||||
Test{"host telemetry", telemetry_is_host_owned}};
|
Test{"host telemetry", telemetry_is_host_owned},
|
||||||
|
Test{"scheduled order and recovery", scheduled_order_and_recovery},
|
||||||
|
Test{"atomic scheduler rejection", scheduled_rejection}};
|
||||||
int failures = 0;
|
int failures = 0;
|
||||||
for (const auto& test : tests) {
|
for (const auto& test : tests) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
Reference in New Issue
Block a user