epoch_forge/lib_efo/tests/epoch_resolution.rs

507 lines
18 KiB
Rust

use lib_efo::{
adjudication::{
AdjudicationConfig, AdjudicationDisposition as Disposition, AdjudicationLevel as Level,
AdjudicationSpec, ChosenEffect, StatName,
},
entity::Entity,
epoch::{EpochId, EpochInfo},
epoch_resolution::{self as resolution, apply, preview},
stats::{EntityType, ListStats, Modification, StatPair},
};
use uuid::Uuid;
fn world(health: isize) -> EpochInfo {
let mut world = EpochInfo::default();
for id in [1, 2] {
let mut event = Entity::default();
event.id = Uuid::from_u128(id);
event.name = format!("event {id}");
event.entity_type = EntityType::Event;
world.events.push(event);
}
let mut target = Entity::default();
target.id = Uuid::from_u128(3);
target.name = "town".into();
target.entity_type = EntityType::Town;
target.change_stat_strict(
StatPair {
stat: ListStats::Health,
value: health.into(),
},
Modification::Replace,
);
target.update_metastats();
world.towns.push(target);
world
}
fn spec(source: u128, delta: isize) -> AdjudicationSpec {
AdjudicationSpec {
level: Level::Apocalypse,
disposition: Disposition::Applied,
source: Uuid::from_u128(source),
external_result: "GM ruling".into(),
note: String::new(),
effects: vec![ChosenEffect {
stat: StatName::Health,
delta,
}],
policy_id: AdjudicationConfig::embedded().expect("config").policy_id,
}
}
fn health(world: &EpochInfo) -> isize {
**world.towns[0].get_stats().get_field(&ListStats::Health)
}
#[test]
fn independent_clamps_are_order_independent_in_batches_and_separate_invocations() {
let config = AdjudicationConfig::embedded().expect("config");
for (base, plus, minus, expected) in [
(110, 20, -20, 100),
(5, 10, -10, 10),
(100, 10, 10, 120),
(100, 100, 100, 120),
] {
let initial = world(base);
let a = preview(&initial, &config, &spec(1, plus), Uuid::from_u128(3), 0).expect("a");
let b = preview(&initial, &config, &spec(2, minus), Uuid::from_u128(3), 0).expect("b");
let first = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("first");
// Simulate another process opening persisted state before previewing b.
let first: EpochInfo =
serde_json::from_slice(&serde_json::to_vec(&first).expect("encode")).expect("decode");
assert_eq!(
preview(&first, &config, &spec(2, minus), Uuid::from_u128(3), 0)
.expect("same baseline"),
b
);
let ab = apply(&first, &config, &[(EntityType::Town, b.clone())]).expect("second");
let ba = apply(
&initial,
&config,
&[(EntityType::Town, b), (EntityType::Town, a)],
)
.expect("reversed batch");
assert_eq!(health(&ab), expected);
assert_eq!(
serde_json::to_value(&ab).expect("ab"),
serde_json::to_value(&ba).expect("ba")
);
}
}
#[test]
fn next_epoch_compounds_and_identical_ruling_has_new_identity() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
let mut next = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("apply");
next.epoch_id = EpochId::new(1);
let b = preview(&next, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("next");
assert_ne!(a.id, b.id);
assert_eq!(b.changes[0].before, 90);
let next = apply(&next, &config, &[(EntityType::Town, b)]).expect("compound");
assert_eq!(health(&next), 80);
assert!(
next.epoch_resolution
.as_ref()
.expect("state")
.baseline
.epoch_resolution
.is_none()
);
}
#[test]
fn duplicate_and_stale_reports_are_atomic_and_do_not_overwrite_edits() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
assert!(
apply(
&initial,
&config,
&[(EntityType::Town, a.clone()), (EntityType::Town, a.clone())]
)
.is_err()
);
assert_eq!(health(&initial), 100);
let mut updated = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("apply");
assert!(apply(&updated, &config, &[(EntityType::Town, a)]).is_err());
updated.towns[0].change_stat_strict(
StatPair {
stat: ListStats::Health,
value: 40.into(),
},
Modification::Replace,
);
assert!(preview(&updated, &config, &spec(2, -10), Uuid::from_u128(3), 0).is_err());
assert_eq!(health(&updated), 40);
}
#[test]
fn source_state_reduces_by_minimum_and_destruction_dominates() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let mut destroy = spec(1, -10);
destroy.disposition = Disposition::Destroyed;
let a = preview(&initial, &config, &destroy, Uuid::from_u128(3), 0).expect("destroy");
let mut defaults = spec(1, 0);
defaults.effects.clear();
defaults.level = Level::Bad;
let b = preview(&initial, &config, &defaults, Uuid::from_u128(3), 1).expect("defaults");
let first = apply(&initial, &config, &[(EntityType::Town, a.clone())]).expect("destroy first");
assert_eq!(
preview(&first, &config, &defaults, Uuid::from_u128(3), 1).expect("same-epoch default"),
b
);
let ab = apply(&first, &config, &[(EntityType::Town, b.clone())]).expect("default next");
let ba = apply(
&initial,
&config,
&[(EntityType::Town, b), (EntityType::Town, a)],
)
.expect("batch");
assert_eq!(
serde_json::to_value(&ab).expect("ab"),
serde_json::to_value(&ba).expect("ba")
);
assert_eq!(health(&ab), 85);
assert_eq!(
ab.event_adjudications[&Uuid::from_u128(1)].potency_basis_points,
0
);
assert!(ab.event_adjudications[&Uuid::from_u128(1)].destroyed);
let mut next = ab;
next.epoch_id = EpochId::new(1);
assert!(preview(&next, &config, &defaults, Uuid::from_u128(3), 1).is_err());
}
#[test]
fn legacy_fixture_and_corrupt_state_are_handled_explicitly() {
let legacy: EpochInfo =
serde_json::from_str(include_str!("fixtures/epoch-resolution/legacy.json"))
.expect("old epoch");
assert!(legacy.epoch_resolution.is_none());
resolution::validate(&legacy).expect("legacy validation");
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("a");
let updated = apply(&initial, &config, &[(EntityType::Town, a)]).expect("apply");
let mut bad = updated.clone();
bad.epoch_resolution.as_mut().expect("state").ruleset = "future".into();
assert!(resolution::validate(&bad).is_err());
let mut bad = updated.clone();
bad.adjudications.clear();
assert!(resolution::validate(&bad).is_err());
let mut bad = updated.clone();
bad.epoch_resolution
.as_mut()
.expect("state")
.baseline
.epoch_resolution = updated.epoch_resolution;
assert!(resolution::validate(&bad).is_err());
}
#[test]
fn extreme_deltas_clamp_without_intermediate_overflow() {
let initial = world(100);
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&initial,
&config,
&spec(1, isize::MAX),
Uuid::from_u128(3),
0,
)
.expect("positive");
let b = preview(
&initial,
&config,
&spec(2, isize::MIN),
Uuid::from_u128(3),
0,
)
.expect("negative");
assert_eq!(a.changes[0].applied_delta, isize::MAX);
assert_eq!(b.changes[0].applied_delta, isize::MIN);
let updated = apply(
&initial,
&config,
&[(EntityType::Town, a), (EntityType::Town, b)],
)
.expect("exact sum");
assert_eq!(health(&updated), 20);
}
#[test]
fn repository_publication_upgrades_legacy_format_and_rejects_stale_snapshots() {
use lib_efo::workspace::Workspace;
let dir = tempfile::tempdir().expect("dir");
let mut workspace = Workspace::initialize(dir.path(), "test").expect("init");
workspace.worktree.world = world(110);
workspace.save_worktree("setup").expect("setup");
workspace.stage_all().expect("stage");
workspace.commit("initial".into()).expect("commit");
// Compatibility fixture: all pre-existing state layers use 1.0 and no baseline.
for path in [".epoch", ".efo/index.json", ".efo/worktree.json"] {
let path = dir.path().join(path);
let mut value: serde_json::Value =
serde_json::from_slice(&std::fs::read(&path).expect("read")).expect("json");
value["format_version"]["minor"] = 0.into();
std::fs::write(path, serde_json::to_vec(&value).expect("encode")).expect("write fixture");
}
let mut workspace = Workspace::open(dir.path()).expect("legacy reader");
let mut stale = workspace.clone();
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&workspace.worktree.world,
&config,
&spec(1, 20),
Uuid::from_u128(3),
0,
)
.expect("a");
let projected =
apply(&workspace.worktree.world, &config, &[(EntityType::Town, a)]).expect("project");
workspace
.apply_resolution(projected.clone())
.expect("publish");
assert_eq!(workspace.manifest.format_version.minor, 1);
assert_eq!(workspace.worktree.format_version.minor, 1);
let bytes = std::fs::read(dir.path().join(".efo/worktree.json")).expect("bytes");
assert!(stale.apply_resolution(projected).is_err());
assert_eq!(
std::fs::read(dir.path().join(".efo/worktree.json")).expect("bytes"),
bytes
);
// A reload recovers the baseline, and partial staging cannot orphan its audit.
let mut workspace = Workspace::open(dir.path()).expect("reload");
assert!(workspace.stage_world().is_err());
workspace.stage_all().expect("stage complete");
workspace.commit("resolution".into()).expect("commit");
let next = preview(
&workspace.worktree.world,
&config,
&spec(2, -20),
Uuid::from_u128(3),
0,
)
.expect("next epoch");
assert_eq!(next.changes[0].before, 120);
workspace
.check_epoch(workspace.head.epoch_id)
.expect("historical validation");
workspace
.revert_to_worktree(workspace.head.epoch_id)
.expect("revert complete resolution");
assert_eq!(
health(
&Workspace::open(dir.path())
.expect("reverted")
.worktree
.world
),
110
);
}
#[test]
fn writer_lock_and_interrupted_transaction_leave_resolution_unpublished() {
use lib_efo::{transaction::RepositoryLock, workspace::Workspace};
let dir = tempfile::tempdir().expect("dir");
let mut workspace = Workspace::initialize(dir.path(), "test").expect("init");
workspace.worktree.world = world(100);
workspace.save_worktree("setup").expect("save");
let config = AdjudicationConfig::embedded().expect("config");
let a = preview(
&workspace.worktree.world,
&config,
&spec(1, -10),
Uuid::from_u128(3),
0,
)
.expect("a");
let projected =
apply(&workspace.worktree.world, &config, &[(EntityType::Town, a)]).expect("project");
let before = std::fs::read(dir.path().join(".efo/worktree.json")).expect("before");
let lock = RepositoryLock::acquire(dir.path(), "other writer").expect("lock");
assert!(workspace.apply_resolution(projected.clone()).is_err());
drop(lock);
std::fs::write(dir.path().join(".efo/transaction.json"), "{}").expect("journal");
assert!(workspace.apply_resolution(projected).is_err());
assert_eq!(
std::fs::read(dir.path().join(".efo/worktree.json")).expect("after"),
before
);
assert_eq!(health(&workspace.worktree.world), 100);
}
#[test]
fn stale_epoch_identity_and_population_overflow_are_rejected() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let report = preview(&initial, &config, &spec(1, -10), Uuid::from_u128(3), 0).expect("report");
let mut next = initial.clone();
next.epoch_id = EpochId::new(1);
assert!(apply(&next, &config, &[(EntityType::Town, report)]).is_err());
let mut initial = initial;
initial.towns[0].change_stat_strict(
StatPair {
stat: ListStats::Population,
value: isize::MAX.into(),
},
Modification::Replace,
);
initial.towns[0].update_metastats();
let mut population = spec(1, 1);
population.effects[0].stat = StatName::Population;
assert!(preview(&initial, &config, &population, Uuid::from_u128(3), 0).is_err());
}
#[test]
fn event_rng_reads_frozen_inputs_and_compounds_its_identity_only_next_epoch() {
use lib_efo::event_rng::EventRandom;
let mut initial = world(100);
initial.rng_seed = 42;
let config = AdjudicationConfig::embedded().expect("config");
let original = EventRandom::for_event(&initial, Uuid::from_u128(1), 0, &config).expect("rng");
let mut unrelated = initial.clone();
let mut town = unrelated.towns[0].clone();
town.id = Uuid::from_u128(9);
unrelated.towns.push(town);
assert_eq!(
EventRandom::for_event(&unrelated, Uuid::from_u128(1), 0, &config).expect("rng"),
original
);
let ruling =
preview(&initial, &config, &spec(2, 30), Uuid::from_u128(1), 0).expect("event as target");
let mut updated = apply(&initial, &config, &[(EntityType::Event, ruling)]).expect("apply");
updated.rng_seed = 77; // A metadata edit must not alter already-frozen draws.
assert_eq!(
EventRandom::for_event(&updated, Uuid::from_u128(1), 0, &config).expect("frozen rng"),
original
);
updated.epoch_id = EpochId::new(1);
assert_ne!(
EventRandom::for_event(&updated, Uuid::from_u128(1), 0, &config).expect("next rng"),
original
);
}
#[test]
fn three_way_reduction_never_clamps_partial_sums() {
let initial = world(100);
let config = AdjudicationConfig::embedded().expect("config");
let reports = [100, -200, 10]
.into_iter()
.enumerate()
.map(|(occurrence, delta)| {
(
EntityType::Town,
preview(
&initial,
&config,
&spec(1, delta),
Uuid::from_u128(3),
occurrence as u64,
)
.expect("report"),
)
})
.collect::<Vec<_>>();
let expected = apply(&initial, &config, &reports).expect("batch");
assert_eq!(health(&expected), 30);
for order in [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
] {
let mut updated = initial.clone();
for index in order {
updated = apply(&updated, &config, &[reports[index].clone()]).expect("incremental");
}
assert_eq!(
serde_json::to_value(updated).expect("updated"),
serde_json::to_value(&expected).expect("expected")
);
}
}
#[test]
fn legacy_rulings_are_baseline_history_and_never_reenrolled() {
let config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let old = lib_efo::adjudication::preview(&config, &spec(1, -10), &initial.towns[0], 0)
.expect("legacy report");
let old_world =
lib_efo::adjudication::apply_to_world(&initial, &config, &old, EntityType::Town)
.expect("legacy apply");
let old_bytes = serde_json::to_vec(&old_world).expect("legacy representation");
let old_world: EpochInfo = serde_json::from_slice(&old_bytes).expect("read legacy record");
let next =
preview(&old_world, &config, &spec(2, -10), Uuid::from_u128(3), 0).expect("new ruling");
let next_id = next.id;
let updated = apply(&old_world, &config, &[(EntityType::Town, next)]).expect("apply");
assert_eq!(health(&updated), 80);
assert_eq!(updated.adjudications[&old.id], old);
assert_eq!(
updated.epoch_resolution.as_ref().expect("state").records,
[next_id].into_iter().collect()
);
let mut corrupt = updated.clone();
corrupt.epoch_resolution = None;
assert!(resolution::validate(&corrupt).is_err());
let mut corrupt = updated.clone();
corrupt
.event_adjudications
.get_mut(&Uuid::from_u128(2))
.expect("source")
.potency_basis_points = 1;
assert!(resolution::validate(&corrupt).is_err());
let mut corrupt = updated;
corrupt
.epoch_resolution
.as_mut()
.expect("state")
.records
.clear();
assert!(resolution::validate(&corrupt).is_err());
}
#[test]
fn record_limits_and_population_aggregate_overflow_leave_inputs_untouched() {
let mut config = AdjudicationConfig::embedded().expect("config");
let initial = world(100);
let a = preview(&initial, &config, &spec(1, 5), Uuid::from_u128(3), 0).expect("a");
let b = preview(&initial, &config, &spec(2, 5), Uuid::from_u128(3), 0).expect("b");
config.max_records = 1;
assert!(
apply(
&initial,
&config,
&[(EntityType::Town, a), (EntityType::Town, b)]
)
.is_err()
);
assert_eq!(health(&initial), 100);
config.max_records = 10;
let reports = [1, 2]
.into_iter()
.map(|source| {
let mut ruling = spec(source, isize::MAX);
ruling.effects[0].stat = StatName::Population;
(
EntityType::Town,
preview(&initial, &config, &ruling, Uuid::from_u128(3), 0)
.expect("local population"),
)
})
.collect::<Vec<_>>();
assert!(apply(&initial, &config, &reports).is_err());
assert!(initial.epoch_resolution.is_none());
}