Complete M7.5 durable batch outcomes and commit resolution

ADR-0063: manifest v2 (360 bytes) binds a per-tick validation trace
object and a canonical decision block by SHA-256. Publication replays the
trace from the committed predecessor's verified payload and requires
every report and the candidate bytes, derives deaths deterministically,
uploads payload and trace with verified read-back, then sends manifest
and decisions to one fenced statement. RegionBatch seals at a terminal
transition or 64 ticks and refuses ticks until durable confirmation.

Schema v5 records the checkpoint, its decisions and outbox rows
atomically; a unique index keeps one terminal outcome per actor
(EVL08), triggers make commits/decisions immutable (EVL09), an exact
retry of a committed ID returns the original receipt, changed bytes
conflict, and read-only resolve_region_commit answers committed/absent/
conflict. Outbox pending/acknowledge give idempotent at-least-once
delivery. Recovery reconciles durable deaths with restored lifecycle
(and archive deaths for the lineage profile).

Validated: Windows CTest 58/58; Linux GCC Debug/Release, clang-tidy and
ASan/UBSan CTest 58/58 each; PostgreSQL suites Release, analysis, ASan
(lost response, committed-after-timeout, terminated orphan retry,
changed bytes, repeated/partial/reordered decisions, gap, outbox
redelivery, history quarantine); five mutations each caught. No
Docker/Gitea CI, process kill, broker or deployment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-28 17:30:30 -04:00
co-authored by Claude Opus 5.5
parent a2c4543df2
commit dd7e8028b0
27 changed files with 2075 additions and 216 deletions
+325 -62
View File
@@ -7,10 +7,12 @@
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <optional>
#include <source_location>
#include <stdexcept>
#include <string>
#include <sys/stat.h>
#include <thread>
#include <unistd.h>
void run_region_checkpoint_store_tests();
@@ -172,6 +174,15 @@ std::size_t count_objects(const fs::path& dir) {
return n;
}
using EnvBatch = RegionBatch<evo::processes::EnvironmentalCommunity>;
using LineageBatch = RegionBatch<evo::processes::LineageRegion>;
// Runs up to `ticks` more ticks (stopping early if an outcome seals it), then flushes.
template <typename Batch> void run_batch(Batch& b, std::uint64_t ticks, bool deaths = false) {
for (std::uint64_t i = 0; i < ticks && !b.sealed(); ++i)
CHECK(b.advance(evo::test::region_input(b.end_tick() + 1, deaths)));
b.seal();
}
void publish_recover_and_continue() {
auto r = provisioned("publish", 3, 0xC0);
const std::array<Sha256Digest, 1> retained{build};
@@ -180,7 +191,7 @@ void publish_recover_and_continue() {
// Genesis recovers to the exact opening state.
auto recovered =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s);
CHECK(recovered && recovered->state->progress().tick == 0);
CHECK(recovered && recovered->state->progress().tick == 0 && recovered->decisions.empty());
auto head = recovered->committed;
// Genesis cannot be re-provisioned or published over.
@@ -189,31 +200,55 @@ void publish_recover_and_continue() {
filled<16>(0xC9), build, budget, 5s));
auto original = evo::test::region_community();
EnvBatch batch{*original};
// An unsealed batch is still being simulated: refused before any upload.
CHECK(batch.advance(evo::test::region_input(1)));
const auto before = count_objects(r.objects->directory());
auto open = publish_environmental_batch(*r.runtime, *r.objects, *lease, head, batch,
filled<16>(0xCA), build, budget, 5s);
CHECK(!open && open.error().kind == PublicationError::candidate);
CHECK(count_objects(r.objects->directory()) == before);
std::uint8_t seed = 0xC1;
for (int batch = 0; batch < 3; ++batch) {
evo::test::advance_region(*original, batch == 1 ? 64 : 16);
for (int n = 0; n < 3; ++n) {
run_batch(batch, n == 1 ? 64 : 15);
const auto started = std::chrono::steady_clock::now();
auto published = publish_environmental_checkpoint(
*r.runtime, *r.objects, *lease, head, *original, filled<16>(seed++), build, budget, 5s);
auto published = publish_environmental_batch(*r.runtime, *r.objects, *lease, head, batch,
filled<16>(seed++), build, budget, 5s);
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - started)
.count();
CHECK(published && published->head.sequence == head.head.sequence + 1);
CHECK(published->head.end_tick == original->progress().tick);
std::printf(
"checkpoint_publish_us batch=%d ticks=%llu payload_bytes=%llu us=%lld\n", batch,
static_cast<unsigned long long>(published->head.end_tick - head.head.end_tick),
static_cast<unsigned long long>(decode_manifest(published->manifest)->payload_bytes),
static_cast<long long>(us));
head = std::move(*published);
CHECK(published && published->committed.head.sequence == head.head.sequence + 1);
CHECK(published->committed.head.end_tick == original->progress().tick);
CHECK(published->decisions.empty());
const auto m = *decode_manifest(published->committed.manifest);
CHECK(m.manifest_version == 2 &&
m.batch.trace_bytes == trace_bytes_for(m.end_tick - m.begin_tick));
std::printf("batch_publish_us batch=%d ticks=%llu payload_bytes=%llu us=%lld\n", n,
static_cast<unsigned long long>(m.end_tick - m.begin_tick),
static_cast<unsigned long long>(m.payload_bytes), static_cast<long long>(us));
CHECK(batch.confirm(m.end_tick));
head = std::move(published->committed);
// The trace object is retained, bound to this link of the chain.
auto trace = r.objects->get({m.batch.trace_sha256, m.batch.trace_bytes});
auto decoded = trace ? decode_trace(*trace) : std::unexpected{BatchError::format};
CHECK(decoded && decoded->header.begin_tick == m.begin_tick &&
decoded->header.predecessor_digest == m.predecessor_digest);
}
// 65 ticks is more than one batch: refused before upload.
const auto before = count_objects(r.objects->directory());
evo::test::advance_region(*original, 65);
auto oversized = publish_environmental_checkpoint(
*r.runtime, *r.objects, *lease, head, *original, filled<16>(0xCA), build, budget, 5s);
CHECK(!oversized && oversized.error().kind == PublicationError::candidate);
CHECK(count_objects(r.objects->directory()) == before);
// State advanced outside the recorded batch cannot be published: the replay of
// the recorded inputs no longer reproduces it.
auto drifted = evo::test::region_community();
EnvBatch drift{*drifted};
run_batch(drift, 3);
CHECK(drifted->advance(4, evo::test::region_input(4)));
auto diverged =
publish_environmental_batch(*r.runtime, *r.objects, *lease, recovered->committed, drift,
filled<16>(0xCD), build, budget, 5s);
CHECK(!diverged && diverged.error().kind == PublicationError::candidate);
// A batch replayed from the wrong predecessor cannot reproduce its state.
run_batch(batch, 4);
auto stale = publish_environmental_batch(*r.runtime, *r.objects, *lease, recovered->committed,
batch, filled<16>(0xCB), build, budget, 5s);
CHECK(!stale && stale.error().kind == PublicationError::candidate);
// A new process recovers the committed head; its trajectory matches the original's.
auto second = FilesystemObjectStore::open(r.objects->directory().parent_path().parent_path(),
@@ -222,11 +257,11 @@ void publish_recover_and_continue() {
auto restored =
recover_environmental_checkpoint(*r.runtime, **second, r.key, retained, budget, 5s);
CHECK(restored && restored->committed.head == head.head);
CHECK(restored->state->progress().tick == 96);
CHECK(restored->state->progress().tick == 95);
auto reference = evo::test::region_community();
evo::test::advance_region(*reference, 96);
evo::test::advance_region(*reference, 95);
CHECK(reference->snapshot() == restored->state->snapshot());
for (std::uint64_t tick = 97; tick <= 140; ++tick) {
for (std::uint64_t tick = 96; tick <= 140; ++tick) {
auto a = reference->advance(tick, evo::test::region_input(tick, true));
auto b = restored->state->advance(tick, evo::test::region_input(tick, true));
CHECK(a && b && *a == *b);
@@ -238,11 +273,9 @@ void publish_recover_and_continue() {
auto foreign =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, other, budget, 5s);
CHECK(!foreign && foreign.error().kind == RecoveryError::unsupported);
// Unretained build is refused by the database; the upload stays an orphan.
auto next = evo::test::region_community();
evo::test::advance_region(*next, 100);
auto refused = publish_environmental_checkpoint(*r.runtime, *r.objects, *lease, head, *next,
filled<16>(0xCB), filled<32>(0xB2), budget, 5s);
// Unretained build is refused by the database; the uploads stay orphans.
auto refused = publish_environmental_batch(*r.runtime, *r.objects, *lease, head, batch,
filled<16>(0xCC), filled<32>(0xB2), budget, 5s);
CHECK(!refused && refused.error().kind == PublicationError::rejected &&
refused.error().store.kind == LeaseStoreError::unsupported);
CHECK(release_region_lease(*r.runtime, r.key, *lease, 5s));
@@ -256,32 +289,34 @@ void failures_leave_the_previous_head() {
auto head = load_region_checkpoint(*r.runtime, r.key, 5s);
CHECK(head);
auto state = evo::test::region_community();
evo::test::advance_region(*state, 8);
auto first = publish_environmental_checkpoint(*r.runtime, *r.objects, *lease, *head, *state,
filled<16>(0xD1), build, budget, 5s);
CHECK(first);
const auto manifest = *decode_manifest(first->manifest);
EnvBatch batch{*state};
run_batch(batch, 8);
auto first = publish_environmental_batch(*r.runtime, *r.objects, *lease, *head, batch,
filled<16>(0xD1), build, budget, 5s);
CHECK(first && batch.confirm(8));
const auto manifest = *decode_manifest(first->committed.manifest);
const auto object = r.objects->directory() / hex(manifest.payload_sha256);
// Upload failure: no manifest is sent; the head does not move.
evo::test::advance_region(*state, 8);
run_batch(batch, 8);
if (::geteuid() != 0) {
fs::permissions(r.objects->directory(), fs::perms::owner_read | fs::perms::owner_exec,
fs::perm_options::replace);
auto upload = publish_environmental_checkpoint(*r.runtime, *r.objects, *lease, *first,
*state, filled<16>(0xD2), build, budget, 5s);
auto upload = publish_environmental_batch(*r.runtime, *r.objects, *lease, first->committed,
batch, filled<16>(0xD2), build, budget, 5s);
fs::permissions(r.objects->directory(), fs::perms::owner_all, fs::perm_options::replace);
CHECK(!upload && upload.error().kind == PublicationError::upload);
CHECK(load_region_head(*r.runtime, r.key, 5s)->sequence == 1);
}
// Manifest transaction failure after a verified upload: fenced writer, orphan retained.
// Manifest transaction failure after verified uploads: fenced writer, orphans retained.
auto stale = *lease;
stale.holder[0] ^= 1U;
auto fenced = publish_environmental_checkpoint(*r.runtime, *r.objects, stale, *first, *state,
filled<16>(0xD3), build, budget, 5s);
auto fenced = publish_environmental_batch(*r.runtime, *r.objects, stale, first->committed,
batch, filled<16>(0xD3), build, budget, 5s);
CHECK(!fenced && fenced.error().kind == PublicationError::rejected &&
fenced.error().store.kind == LeaseStoreError::fenced);
CHECK(fenced.error().prepared.commit == filled<16>(0xD3));
auto orphan_bytes = state->snapshot();
auto orphan = r.objects->get({*sha256(*orphan_bytes), orphan_bytes->size()});
CHECK(orphan && *orphan == *orphan_bytes); // Uploaded, verified, unreferenced.
@@ -296,6 +331,11 @@ void failures_leave_the_previous_head() {
auto missing =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s);
CHECK(!missing && missing.error().kind == RecoveryError::missing_payload);
// Staging replays from the committed predecessor bytes; without them it stops.
auto no_base = publish_environmental_batch(*r.runtime, *r.objects, *lease, first->committed,
batch, filled<16>(0xD4), build, budget, 5s);
CHECK(!no_base && no_base.error().kind == PublicationError::predecessor &&
no_base.error().object == ObjectError::missing);
CHECK(r.objects->put(*saved));
fs::permissions(object, fs::perms::owner_all, fs::perm_options::replace);
{
@@ -310,18 +350,26 @@ void failures_leave_the_previous_head() {
CHECK(r.objects->put(*saved));
CHECK(recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s));
// The database refuses tampering with committed manifests even by the owner.
// Committed history is immutable even to the owner (trigger), and the head
// cannot be repointed (composite foreign key).
auto tamper = r.owner->query("UPDATE evolution.region_commits SET manifest = "
"overlay(manifest placing '\\x02'::bytea from 121 for 1) "
"WHERE world_id = 7 AND region_id = 4 AND commit_sequence = 1",
{}, 5s);
CHECK(!tamper && std::string(tamper.error().sqlstate.data()) == "23514");
CHECK(!tamper && std::string(tamper.error().sqlstate.data()) == "EVL09");
auto erase = r.owner->query("DELETE FROM evolution.region_commits WHERE world_id = 7 AND "
"region_id = 4 AND commit_sequence = 1",
{}, 5s);
CHECK(!erase && std::string(erase.error().sqlstate.data()) == "EVL09");
auto repoint = r.owner->query("UPDATE evolution.region_heads SET digest = sha256('\\x00') "
"WHERE world_id = 7 AND region_id = 4",
{}, 5s);
CHECK(!repoint && std::string(repoint.error().sqlstate.data()) == "23503");
// Defense in depth: even if that constraint were lost, recovery re-digests the
// manifest and quarantines. Restores the constraint before continuing.
// Defense in depth: even with the trigger and digest constraint removed, recovery
// re-digests the manifest and quarantines. Both guards are restored afterwards.
CHECK(r.owner->query("ALTER TABLE evolution.region_commits DISABLE TRIGGER "
"region_commits_immutable",
{}, 5s));
CHECK(r.owner->query("ALTER TABLE evolution.region_commits DROP CONSTRAINT "
"region_commits_manifest_digest",
{}, 5s));
@@ -333,13 +381,16 @@ void failures_leave_the_previous_head() {
auto tampered =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s);
CHECK(!tampered && tampered.error().kind == RecoveryError::manifest);
const std::array<std::string, 1> original{"\\x" + hex(first->manifest)};
const std::array<std::string, 1> original{"\\x" + hex(first->committed.manifest)};
CHECK(r.owner->query("UPDATE evolution.region_commits SET manifest = $1::bytea "
"WHERE world_id = 7 AND region_id = 4 AND commit_sequence = 1",
original, 5s));
CHECK(r.owner->query("ALTER TABLE evolution.region_commits ADD CONSTRAINT "
"region_commits_manifest_digest CHECK (commit_digest = sha256(manifest))",
{}, 5s));
CHECK(r.owner->query("ALTER TABLE evolution.region_commits ENABLE TRIGGER "
"region_commits_immutable",
{}, 5s));
CHECK(recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s));
// Recovery does not create genesis for an unknown region.
@@ -347,6 +398,7 @@ void failures_leave_the_previous_head() {
recover_environmental_checkpoint(*r.runtime, *r.objects, {7, 99}, retained, budget, 5s);
CHECK(!none && none.error().kind == RecoveryError::not_provisioned);
}
// History-capable profile: deaths commit with the state that caused them, the
// archive survives recovery, and a region never switches profile.
void lineage_publish_and_recover() {
@@ -369,50 +421,260 @@ void lineage_publish_and_recover() {
CHECK(lease);
auto region = evo::test::lineage_region();
evo::test::advance_lineage(*region, 24, true); // Consumer dies at tick 20.
auto first = publish_lineage_checkpoint(*runtime, **objects, *lease, *genesis, *region,
filled<16>(0xE1), build, budget, 5s);
CHECK(first && first->head.end_tick == 24);
LineageBatch batch{*region};
run_batch(batch, 64, true); // The consumer's death at tick 20 seals the batch there.
CHECK(batch.end_tick() == 20);
auto first = publish_lineage_batch(*runtime, **objects, *lease, *genesis, batch,
filled<16>(0xE1), build, budget, 5s);
CHECK(first && first->committed.head.end_tick == 20);
CHECK(first->decisions.size() == 1 &&
first->decisions[0] == BatchDecision{20, Actor::consumer, Outcome::death, 11});
CHECK(batch.confirm(20));
// The environmental path refuses a lineage predecessor before uploading.
auto plain = evo::test::region_community();
evo::test::advance_region(*plain, 30);
auto crossed = publish_environmental_checkpoint(*runtime, **objects, *lease, *first, *plain,
filled<16>(0xE2), build, budget, 5s);
EnvBatch plain_batch{*plain};
run_batch(plain_batch, 30);
auto crossed = publish_environmental_batch(*runtime, **objects, *lease, first->committed,
plain_batch, filled<16>(0xE2), build, budget, 5s);
CHECK(!crossed && crossed.error().kind == PublicationError::candidate);
// The database refuses a profile switch even when the manifest is well formed.
auto switched = *decode_manifest(first->manifest);
auto next = successor_manifest(switched, first->head.digest, filled<16>(0xE3), *lease, 30,
build, 100, filled<32>(0xA2));
auto switched = *decode_manifest(first->committed.manifest);
auto next = successor_manifest(switched, first->committed.head.digest, filled<16>(0xE3), *lease,
30, build, 100, filled<32>(0xA2),
{trace_bytes_for(10), filled<32>(0x7C), 0, {}});
CHECK(next);
next->profile = CheckpointProfile::environmental_v1;
next->history_profile = 0;
auto switched_bytes = encode_manifest(*next);
CHECK(switched_bytes);
auto refused = publish_region_checkpoint(*runtime, *switched_bytes, 5s);
auto refused = publish_region_checkpoint(*runtime, *switched_bytes, {}, 5s);
CHECK(!refused && refused.error().kind == LeaseStoreError::unsupported);
const std::array<Sha256Digest, 1> retained{build};
auto recovered = recover_lineage_checkpoint(*runtime, **objects, key, retained, budget, 5s);
CHECK(recovered && recovered->committed.head == first->head);
CHECK(recovered && recovered->committed.head == first->committed.head);
CHECK(recovered->decisions.size() == 1 && recovered->decisions[0].commit_sequence == 1);
const auto consumer = recovered->state->archive().organism(11);
CHECK(consumer && !consumer->alive && consumer->died.value == 20);
CHECK(recovered->state->archive().ancestry(2)->size() == 2); // Retained ancestry.
CHECK(recovered->state->snapshot() == region->snapshot());
for (std::uint64_t tick = 25; tick <= 60; ++tick) {
LineageBatch resumed{*recovered->state};
for (std::uint64_t tick = 21; tick <= 60; ++tick) {
auto a = region->advance(tick, evo::test::region_input(tick));
auto b = recovered->state->advance(tick, evo::test::region_input(tick));
auto b = resumed.advance(evo::test::region_input(tick));
CHECK(a && b && *a == *b);
}
CHECK(recovered->state->snapshot() == region->snapshot());
auto second =
publish_lineage_checkpoint(*runtime, **objects, *lease, recovered->committed,
*recovered->state, filled<16>(0xE4), build, budget, 5s);
CHECK(second && second->head.sequence == 2 && second->head.end_tick == 60);
resumed.seal();
auto second = publish_lineage_batch(*runtime, **objects, *lease, recovered->committed, resumed,
filled<16>(0xE4), build, budget, 5s);
CHECK(second && second->committed.head.sequence == 2 && second->committed.head.end_tick == 60 &&
second->decisions.empty());
// A host restoring the other profile refuses rather than misreading the payload.
auto wrong = recover_environmental_checkpoint(*runtime, **objects, key, retained, budget, 5s);
CHECK(!wrong && wrong.error().kind == RecoveryError::unsupported);
CHECK(release_region_lease(*runtime, key, *lease, 5s));
}
std::string runtime_user() {
return env("EVO_PG_RUNTIME_USER");
}
// Polls resolution on a fresh connection until the prepared commit is committed.
ResolvedCommit await_resolution(const PreparedCommit& prepared, Resolution wanted) {
auto db = connect_as(runtime_user());
for (int attempt = 0; attempt < 200; ++attempt) {
auto resolved = resolve_prepared(*db, prepared, 5s);
CHECK(resolved);
if (resolved->status == wanted)
return *resolved;
std::this_thread::sleep_for(25ms);
}
CHECK(false);
return {};
}
// Holds the lease row lock so a publication's outcome becomes ambiguous to its client.
struct LeaseRowLock {
std::unique_ptr<Postgres> db;
LeaseRowLock(RegionKey key) : db(connect_as(env("PGUSER"))) {
const std::array<std::string, 2> p{std::to_string(key.world), std::to_string(key.region)};
CHECK(db->query("BEGIN", {}, 5s));
CHECK(db->query("SELECT 1 FROM evolution.region_leases WHERE world_id = $1::evolution.u64 "
"AND region_id = $2::evolution.u64 FOR UPDATE",
p, 5s));
}
// Terminates backends of the runtime login queued behind this lock.
void kill_waiters() {
const std::array<std::string, 1> p{runtime_user()};
CHECK(db->query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE "
"usename = $1 AND wait_event_type = 'Lock'",
p, 5s));
}
void release() {
CHECK(db->query("ROLLBACK", {}, 5s));
}
};
// M7.5 durability: permanent outcomes commit atomically with their checkpoint,
// ambiguity is resolved by exact bytes, and nothing is ever applied twice.
void durable_outcomes_and_ambiguity() {
auto r = provisioned("outcomes", 7, 0xF0);
const std::array<Sha256Digest, 1> retained{build};
auto lease = acquire_region_lease(*r.runtime, r.key, 20000ms, 5s);
CHECK(lease);
auto genesis = load_region_checkpoint(*r.runtime, r.key, 5s);
CHECK(genesis);
auto state = evo::test::region_community();
EnvBatch batch{*state};
run_batch(batch, 64, true); // Sealed by the consumer's death at tick 20.
CHECK(batch.end_tick() == 20);
auto died = publish_environmental_batch(*r.runtime, *r.objects, *lease, *genesis, batch,
filled<16>(0xF1), build, budget, 5s);
CHECK(died && died->decisions.size() == 1 &&
died->decisions[0] == BatchDecision{20, Actor::consumer, Outcome::death, 0});
CHECK(batch.confirm(20));
const CommittedDecision final_death{1, died->decisions[0]};
auto decisions = load_region_decisions(*r.runtime, r.key, 5s);
CHECK(decisions && decisions->size() == 1 && (*decisions)[0] == final_death);
// Outbox: at-least-once delivery, idempotent acknowledgement, no simulation effect.
auto pending = pending_region_outbox(*r.runtime, r.key, 64, 5s);
CHECK(pending && pending->size() == 1 && (*pending)[0] == final_death);
CHECK(pending_region_outbox(*r.runtime, r.key, 64, 5s)->size() == 1); // Redelivered.
auto ack = acknowledge_region_outbox(*r.runtime, r.key, died->decisions[0], 5s);
CHECK(ack && *ack);
ack = acknowledge_region_outbox(*r.runtime, r.key, died->decisions[0], 5s);
CHECK(ack && !*ack);
CHECK(pending_region_outbox(*r.runtime, r.key, 64, 5s)->empty());
CHECK(!pending_region_outbox(*r.runtime, r.key, 65, 5s));
const BatchDecision never{21, Actor::producer, Outcome::death, 0};
CHECK(!acknowledge_region_outbox(*r.runtime, r.key, never, 5s));
// Commit succeeded but the response was lost: the exact retry returns the same
// receipt and records nothing twice; resolution confirms it under any epoch.
auto death_block = encode_decisions(died->decisions, 0, 20);
CHECK(death_block);
const PreparedCommit lost{r.key, filled<16>(0xF1), died->committed.manifest, *death_block};
auto retried = retry_prepared(*r.runtime, lost, 5s);
CHECK(retried && *retried == died->committed.head);
auto resolved = resolve_prepared(*r.runtime, lost, 5s);
CHECK(resolved && resolved->status == Resolution::committed &&
resolved->receipt == died->committed.head);
CHECK(load_region_decisions(*r.runtime, r.key, 5s)->size() == 1);
// Changed bytes under the same ID conflict, whether manifest or decisions differ.
auto changed = lost;
changed.manifest[288] ^= 1U; // Trace digest.
CHECK(retry_prepared(*r.runtime, changed, 5s).error().kind == LeaseStoreError::commit_conflict);
CHECK(resolve_prepared(*r.runtime, changed, 5s)->status == Resolution::conflict);
auto undecided = lost;
undecided.decisions.clear(); // No longer what the manifest digests.
CHECK(retry_prepared(*r.runtime, undecided, 5s).error().kind == LeaseStoreError::invalid);
CHECK(resolve_prepared(*r.runtime, undecided, 5s)->status == Resolution::conflict);
auto elsewhere = lost;
elsewhere.key.region = 3;
CHECK(resolve_prepared(*r.runtime, elsewhere, 5s)->status == Resolution::conflict);
auto unknown_id = lost;
unknown_id.commit = filled<16>(0xFE);
CHECK(resolve_prepared(*r.runtime, unknown_id, 5s)->status == Resolution::absent);
// The committed dead stay dead: a later batch cannot finalize the death again.
const auto head = died->committed;
const std::array again{BatchDecision{25, Actor::consumer, Outcome::death, 0}};
auto again_bytes = encode_decisions(again, 20, 30);
CHECK(again_bytes);
auto relapse = successor_manifest(
*decode_manifest(head.manifest), head.head.digest, filled<16>(0xF2), *lease, 30, build, 100,
filled<32>(0xA2), {trace_bytes_for(10), filled<32>(0x7C), 1, *sha256(*again_bytes)});
CHECK(relapse);
auto relapse_bytes = encode_manifest(*relapse);
auto repeated = publish_region_checkpoint(*r.runtime, *relapse_bytes, *again_bytes, 5s);
CHECK(!repeated && repeated.error().kind == LeaseStoreError::outcome_final);
// A block of the right size that is not the one the manifest digests is refused.
auto forged_block = *again_bytes;
forged_block[0] ^= 1U; // Tick 25 -> 24: still well formed, different bytes.
CHECK(publish_region_checkpoint(*r.runtime, *relapse_bytes, forged_block, 5s).error().kind ==
LeaseStoreError::invalid);
// Partial or reordered decision blocks are refused whole; nothing is recorded.
CHECK(publish_region_checkpoint(*r.runtime, *relapse_bytes, {}, 5s).error().kind ==
LeaseStoreError::invalid);
const std::array two{BatchDecision{25, Actor::producer, Outcome::death, 0},
BatchDecision{24, Actor::consumer, Outcome::death, 0}};
std::vector<std::uint8_t> reordered(two.size() * decision_bytes);
auto ordered = encode_decisions(std::array{two[1], two[0]}, 20, 30);
CHECK(ordered);
std::copy_n(ordered->begin() + 24, 24, reordered.begin());
std::copy_n(ordered->begin(), 24, reordered.begin() + 24);
auto reorder = *relapse;
reorder.batch = {trace_bytes_for(10), filled<32>(0x7C), 2, *sha256(reordered)};
CHECK(publish_region_checkpoint(*r.runtime, *encode_manifest(reorder), reordered, 5s)
.error()
.kind == LeaseStoreError::invalid);
// A gap: a link from an older predecessor is not the committed head's successor.
auto gap = successor_manifest(*decode_manifest(genesis->manifest), genesis->head.digest,
filled<16>(0xF3), *lease, 30, build, 100, filled<32>(0xA2),
{trace_bytes_for(30), filled<32>(0x7C), 0, {}});
CHECK(publish_region_checkpoint(*r.runtime, *encode_manifest(*gap), {}, 5s).error().kind ==
LeaseStoreError::head_mismatch);
CHECK(load_region_head(*r.runtime, r.key, 5s)->sequence == 1);
CHECK(load_region_decisions(*r.runtime, r.key, 5s)->size() == 1);
// Keep authority comfortably valid for the ambiguity cases (sanitizer builds are slow).
CHECK(renew_region_lease(*r.runtime, r.key, *lease, 20000ms, 5s));
// Ambiguous outcome that did commit: the client times out while queued, the
// server finishes after the lock is released. Resolution adopts the receipt.
run_batch(batch, 10);
std::optional<LeaseRowLock> lock{std::in_place, r.key};
auto ambiguous_db = connect_as(runtime_user());
auto ambiguous = publish_environmental_batch(*ambiguous_db, *r.objects, *lease, head, batch,
filled<16>(0xF4), build, budget, 300ms);
CHECK(!ambiguous && ambiguous.error().kind == PublicationError::unknown);
CHECK(batch.sealed()); // Still paused: never assume rollback.
lock->release();
lock.reset();
const auto committed = await_resolution(ambiguous.error().prepared, Resolution::committed);
CHECK(committed.receipt.sequence == 2 && committed.receipt.end_tick == 30);
auto adopted = retry_prepared(*r.runtime, ambiguous.error().prepared, 5s);
CHECK(adopted && *adopted == committed.receipt);
CHECK(batch.confirm(30));
// Ambiguous outcome that did not commit: the orphaned request is terminated
// before it reaches the row. Absent, so the same bytes are retried while authorized.
auto after = load_region_checkpoint(*r.runtime, r.key, 5s);
CHECK(after);
run_batch(batch, 5);
lock.emplace(r.key);
auto orphan_db = connect_as(runtime_user());
auto orphaned = publish_environmental_batch(*orphan_db, *r.objects, *lease, *after, batch,
filled<16>(0xF5), build, budget, 300ms);
CHECK(!orphaned && orphaned.error().kind == PublicationError::unknown);
lock->kill_waiters();
lock->release();
lock.reset();
std::this_thread::sleep_for(200ms);
CHECK(resolve_prepared(*r.runtime, orphaned.error().prepared, 5s)->status ==
Resolution::absent);
auto recommitted = retry_prepared(*r.runtime, orphaned.error().prepared, 5s);
CHECK(recommitted && recommitted->sequence == 3 && recommitted->end_tick == 35);
CHECK(batch.confirm(35));
// Recovery reconciles durable outcomes with the restored lifecycle.
auto recovered =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s);
CHECK(recovered && recovered->decisions.size() == 1 && recovered->decisions[0] == final_death &&
recovered->state->progress().consumer_terminal == 1);
CHECK(recovered->state->snapshot() == state->snapshot());
// A durable death the state does not show is a history disagreement: quarantine.
CHECK(r.owner->query("INSERT INTO evolution.region_decisions(world_id, region_id, outcome, "
"actor, tick, organism, commit_sequence) VALUES (7, 7, 1, 0, 30, 0, 2)",
{}, 5s));
auto disagreed =
recover_environmental_checkpoint(*r.runtime, *r.objects, r.key, retained, budget, 5s);
CHECK(!disagreed && disagreed.error().kind == RecoveryError::history);
auto undo = r.owner->query("DELETE FROM evolution.region_decisions WHERE world_id = 7 AND "
"region_id = 7 AND actor = 0",
{}, 5s);
CHECK(!undo && std::string(undo.error().sqlstate.data()) == "EVL09"); // Stays quarantined.
CHECK(release_region_lease(*r.runtime, r.key, *lease, 5s));
}
} // namespace
void run_region_checkpoint_store_tests() {
@@ -421,4 +683,5 @@ void run_region_checkpoint_store_tests() {
publish_recover_and_continue();
failures_leave_the_previous_head();
lineage_publish_and_recover();
durable_outcomes_and_ambiguity();
}