feat: reduce independent rulings against an epoch baseline
This commit is contained in:
parent
1ebba7b75b
commit
fa6996e6fe
|
|
@ -276,7 +276,7 @@ and [`docs/presentation-design.md`](docs/presentation-design.md).
|
|||
sequential worldgen RNG, and platform-sized arithmetic need dedicated work.
|
||||
- Validation: formatting, all-target/all-feature locked workspace tests, and
|
||||
strict Clippy passed; this change documents rules without changing runtime behavior.
|
||||
- [ ] Implement a versioned serial batch reference and proposal/receipt schema
|
||||
- [x] Implement a versioned serial batch reference and proposal/receipt schema
|
||||
with compatibility fixtures before introducing a worker pool.
|
||||
- [ ] Convert mental checks into executable permutation, retry, stale-state,
|
||||
arithmetic, RNG golden-vector, and recovery tests.
|
||||
|
|
|
|||
|
|
@ -17,11 +17,11 @@ round lifecycle and explicit diffusion arrival bookkeeping remain ordered.
|
|||
|
||||
- [x] Create `feat/deterministic-epoch-resolution`; revise the execution contract
|
||||
and record this assessment and task list.
|
||||
- [ ] Add versioned persisted epoch baseline/record membership with old-data
|
||||
- [x] Add versioned persisted epoch baseline/record membership with old-data
|
||||
defaults and compatibility fixtures before activating the new schema.
|
||||
- [ ] Implement pure baseline preview and exact reduction of clamped ruling
|
||||
- [x] Implement pure baseline preview and exact reduction of clamped ruling
|
||||
contributions; merge source potency by minimum and destruction by OR.
|
||||
- [ ] Test permutations, bounds, overlapping targets, duplicates, stale edits,
|
||||
- [x] Test permutations, bounds, overlapping targets, duplicates, stale edits,
|
||||
source state, malformed persisted accumulators, and cross-epoch compounding.
|
||||
- [ ] Integrate all three CLI resolution paths and show epoch aggregate results
|
||||
separately from independent ruling outcomes.
|
||||
|
|
@ -52,3 +52,7 @@ round lifecycle and explicit diffusion arrival bookkeeping remain ordered.
|
|||
preserve earlier baselines and audit history.
|
||||
- Event-local RNG is a foundation API; worldgen's existing sequential stream is
|
||||
a separate versioned generator and remains unchanged in this feature.
|
||||
|
||||
Checkpoint 1: pure reducer and six library tests pass. The schema defaults to
|
||||
absent on legacy data; ordinary format-1.0 saves explicitly refuse accumulator
|
||||
state until transactional format publication is integrated in checkpoint 2.
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ pub enum AdjudicationDisposition {
|
|||
}
|
||||
|
||||
/// Supported editable statistic names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum StatName {
|
||||
/// Population count or modifier.
|
||||
|
|
@ -490,12 +490,17 @@ pub fn preview_at_potency(
|
|||
let stat = effect.stat.list_stat();
|
||||
let before = **projected.get_stats().get_field(&stat);
|
||||
let applied_delta = scale(effect.delta, attenuation);
|
||||
let local_after = crate::epoch_resolution::normalize(
|
||||
effect.stat,
|
||||
target.entity_type,
|
||||
before as i128 + applied_delta as i128,
|
||||
)?;
|
||||
projected.change_stat_strict(
|
||||
StatPair {
|
||||
stat,
|
||||
value: applied_delta.into(),
|
||||
value: local_after.into(),
|
||||
},
|
||||
Modification::Delta,
|
||||
Modification::Replace,
|
||||
);
|
||||
projected.update_metastats();
|
||||
let after = **projected.get_stats().get_field(&stat);
|
||||
|
|
@ -716,13 +721,13 @@ fn validate_effects(effects: &[ChosenEffect], max_effects: usize) -> Result<(),
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a basis-point multiplier with saturating multiplication.
|
||||
/// Scale in widened arithmetic; validated multipliers cannot increase magnitude.
|
||||
fn scale(value: isize, basis_points: isize) -> isize {
|
||||
value.saturating_mul(basis_points) / 10_000
|
||||
((value as i128 * basis_points as i128) / 10_000) as isize
|
||||
}
|
||||
|
||||
/// Generate a stable UUID from canonical serialized content.
|
||||
fn content_id(bytes: &[u8]) -> Uuid {
|
||||
pub(crate) fn content_id(bytes: &[u8]) -> Uuid {
|
||||
let mut high = 0xcbf2_9ce4_8422_2325_u64;
|
||||
let mut low = 0x8422_2325_cbf2_9ce4_u64;
|
||||
for byte in bytes {
|
||||
|
|
|
|||
|
|
@ -110,6 +110,10 @@ pub struct EpochInfo {
|
|||
#[serde(default)]
|
||||
#[table(skip)]
|
||||
pub conflicts: BTreeMap<Uuid, ConflictState>,
|
||||
/// Frozen inputs and enrolled records for simultaneous epoch resolution.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[table(skip)]
|
||||
pub epoch_resolution: Option<Box<crate::epoch_resolution::EpochResolution>>,
|
||||
}
|
||||
|
||||
impl Prettiable for EpochInfo {}
|
||||
|
|
@ -135,6 +139,7 @@ impl Default for EpochInfo {
|
|||
adjudications: BTreeMap::new(),
|
||||
event_adjudications: BTreeMap::new(),
|
||||
conflicts: BTreeMap::new(),
|
||||
epoch_resolution: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,387 @@
|
|||
//! Simultaneous, independently clamped rulings sharing a durable epoch baseline.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
adjudication::{
|
||||
AdjudicationConfig, AdjudicationDisposition, AdjudicationError, AdjudicationReport,
|
||||
AdjudicationSpec, EventAdjudicationState, StatName, preview_at_potency,
|
||||
},
|
||||
epoch::EpochInfo,
|
||||
stats::{EntityType, Modification, StatPair},
|
||||
};
|
||||
|
||||
/// Persisted interpretation of independently clamped epoch contributions.
|
||||
pub const RULESET: &str = "epoch-forge/epoch-resolution-1";
|
||||
|
||||
/// One accumulation interval. Committing changes the epoch ID and closes it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EpochResolution {
|
||||
/// Explicit ruleset; unknown interpretations are rejected.
|
||||
pub ruleset: String,
|
||||
/// Frozen inputs, without recursively embedded resolution state.
|
||||
pub baseline: Box<EpochInfo>,
|
||||
/// Only these new records contribute; historical records are not replayed.
|
||||
pub records: BTreeSet<Uuid>,
|
||||
}
|
||||
|
||||
/// One aggregate result, distinct from an individual ruling's clamped outcome.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AggregateChange {
|
||||
/// Entity receiving the contributions.
|
||||
pub target: Uuid,
|
||||
/// Primitive stat, never a derived summary.
|
||||
pub stat: StatName,
|
||||
/// Common epoch starting value.
|
||||
pub before: isize,
|
||||
/// Exact total of independently clamped contributions.
|
||||
pub contribution: i128,
|
||||
/// Aggregate normalized value.
|
||||
pub after: isize,
|
||||
}
|
||||
|
||||
/// Inputs for all independent rulings in the current epoch.
|
||||
pub fn inputs(world: &EpochInfo) -> &EpochInfo {
|
||||
match &world.epoch_resolution {
|
||||
Some(state) if state.baseline.epoch_id == world.epoch_id => &state.baseline,
|
||||
_ => world,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview a ruling against the common baseline with an epoch-scoped record ID.
|
||||
pub fn preview(
|
||||
world: &EpochInfo,
|
||||
config: &AdjudicationConfig,
|
||||
spec: &AdjudicationSpec,
|
||||
target: Uuid,
|
||||
tick_or_round: u64,
|
||||
) -> Result<AdjudicationReport, AdjudicationError> {
|
||||
validate(world)?;
|
||||
let baseline = inputs(world);
|
||||
let target = baseline.find_entity_strict(target, None).map_err(|_| {
|
||||
invalid(format!("target @{target} is absent from the epoch baseline; commit before resolving newly created entities"))
|
||||
})?;
|
||||
let source_is_event = baseline
|
||||
.find_entity_strict(spec.source, Some(EntityType::Event))
|
||||
.is_ok();
|
||||
if !source_is_event && !world.conflicts.contains_key(&spec.source) {
|
||||
return Err(invalid(format!(
|
||||
"source @{} is absent from the epoch baseline or conflicts",
|
||||
spec.source
|
||||
)));
|
||||
}
|
||||
let source_state = baseline.event_adjudications.get(&spec.source);
|
||||
if source_is_event && source_state.is_some_and(|state| state.destroyed) {
|
||||
return Err(invalid(format!(
|
||||
"source @{} was destroyed before this epoch; restore or select another event",
|
||||
spec.source
|
||||
)));
|
||||
}
|
||||
// Effects are a keyed set; input vector order must not change record identity.
|
||||
let mut spec = spec.clone();
|
||||
spec.effects.sort_by_key(|effect| effect.stat);
|
||||
let mut report = preview_at_potency(
|
||||
config,
|
||||
&spec,
|
||||
target,
|
||||
tick_or_round,
|
||||
source_state.map_or(10_000, |state| state.potency_basis_points),
|
||||
)?;
|
||||
report.id = crate::adjudication::content_id(
|
||||
&serde_json::to_vec(&(RULESET, world.epoch_id, report.id))
|
||||
.map_err(|error| invalid(format!("cannot identify epoch ruling: {error}")))?,
|
||||
);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Apply a complete set of independent reports without mutating the input.
|
||||
/// All reports must have been previewed against this epoch's common baseline.
|
||||
pub fn apply(
|
||||
world: &EpochInfo,
|
||||
config: &AdjudicationConfig,
|
||||
reports: &[(EntityType, AdjudicationReport)],
|
||||
) -> Result<EpochInfo, AdjudicationError> {
|
||||
config.validate()?;
|
||||
validate(world)?;
|
||||
if reports.is_empty() {
|
||||
return Err(invalid("cannot apply an empty epoch resolution"));
|
||||
}
|
||||
if world
|
||||
.adjudications
|
||||
.len()
|
||||
.checked_add(reports.len())
|
||||
.is_none_or(|count| count > config.max_records)
|
||||
{
|
||||
return Err(AdjudicationError::RecordLimit {
|
||||
limit: config.max_records,
|
||||
});
|
||||
}
|
||||
let baseline = inputs(world);
|
||||
let previous = aggregate(world)?;
|
||||
let mut updated = world.clone();
|
||||
if baseline.epoch_resolution.is_some() || world.epoch_resolution.is_none() {
|
||||
let mut frozen = baseline.clone();
|
||||
frozen.epoch_resolution = None;
|
||||
canonicalize(&mut frozen);
|
||||
updated.epoch_resolution = Some(Box::new(EpochResolution {
|
||||
ruleset: RULESET.into(),
|
||||
baseline: Box::new(frozen),
|
||||
records: BTreeSet::new(),
|
||||
}));
|
||||
}
|
||||
// When an active state exists, inputs() returned its nonrecursive baseline.
|
||||
for (kind, report) in reports {
|
||||
if updated.adjudications.contains_key(&report.id) {
|
||||
return Err(AdjudicationError::Duplicate { record: report.id });
|
||||
}
|
||||
if report.policy_id != config.policy_id {
|
||||
return Err(invalid(format!(
|
||||
"record @{} uses a different policy",
|
||||
report.id
|
||||
)));
|
||||
}
|
||||
let target = baseline.find_entity_strict(report.target, Some(*kind))?;
|
||||
let current = world.find_entity_strict(report.target, Some(*kind))?;
|
||||
for change in &report.changes {
|
||||
let expected = previous
|
||||
.iter()
|
||||
.find(|entry| entry.target == report.target && entry.stat == change.stat)
|
||||
.map_or(change.before, |entry| entry.after);
|
||||
if **target.get_stats().get_field(&change.stat.list_stat()) != change.before
|
||||
|| **current.get_stats().get_field(&change.stat.list_stat()) != expected
|
||||
{
|
||||
return Err(AdjudicationError::Stale {
|
||||
target: report.target,
|
||||
});
|
||||
}
|
||||
}
|
||||
updated.adjudications.insert(report.id, report.clone());
|
||||
let state = updated
|
||||
.epoch_resolution
|
||||
.as_mut()
|
||||
.ok_or_else(|| invalid("missing epoch baseline"))?;
|
||||
state.records.insert(report.id);
|
||||
}
|
||||
for change in aggregate(&updated)? {
|
||||
let entity = updated.find_entity_strict_as_mut(change.target, None)?;
|
||||
entity.change_stat_strict(
|
||||
StatPair {
|
||||
stat: change.stat.list_stat(),
|
||||
value: change.after.into(),
|
||||
},
|
||||
Modification::Replace,
|
||||
);
|
||||
entity.update_metastats();
|
||||
}
|
||||
reduce_sources(&mut updated)?;
|
||||
canonicalize(&mut updated);
|
||||
validate(&updated)?;
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
/// Compute the exact reduction, in canonical target/stat order.
|
||||
pub fn aggregate(world: &EpochInfo) -> Result<Vec<AggregateChange>, AdjudicationError> {
|
||||
let Some(state) = &world.epoch_resolution else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
if state.baseline.epoch_id != world.epoch_id {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
aggregate_state(world, state)
|
||||
}
|
||||
|
||||
/// Reduce the specified accumulator, including when auditing a closed epoch.
|
||||
fn aggregate_state(
|
||||
world: &EpochInfo,
|
||||
state: &EpochResolution,
|
||||
) -> Result<Vec<AggregateChange>, AdjudicationError> {
|
||||
let mut totals = BTreeMap::<(Uuid, StatName), i128>::new();
|
||||
for id in &state.records {
|
||||
let report = world
|
||||
.adjudications
|
||||
.get(id)
|
||||
.ok_or_else(|| invalid(format!("epoch resolution refers to missing record @{id}")))?;
|
||||
let target = state.baseline.find_entity_strict(report.target, None)?;
|
||||
for change in &report.changes {
|
||||
if **target.get_stats().get_field(&change.stat.list_stat()) != change.before
|
||||
|| normalize(
|
||||
change.stat,
|
||||
target.entity_type,
|
||||
change.before as i128 + change.applied_delta as i128,
|
||||
)? != change.after
|
||||
{
|
||||
return Err(invalid(format!(
|
||||
"record @{id} does not match its epoch baseline or local clamp"
|
||||
)));
|
||||
}
|
||||
let total = totals.entry((report.target, change.stat)).or_default();
|
||||
*total = total
|
||||
.checked_add(change.after as i128 - change.before as i128)
|
||||
.ok_or_else(|| invalid("epoch contribution total exceeds i128"))?;
|
||||
}
|
||||
}
|
||||
totals
|
||||
.into_iter()
|
||||
.map(|((target, stat), contribution)| {
|
||||
let entity = state.baseline.find_entity_strict(target, None)?;
|
||||
let before = **entity.get_stats().get_field(&stat.list_stat());
|
||||
let raw = (before as i128)
|
||||
.checked_add(contribution)
|
||||
.ok_or_else(|| invalid("epoch total exceeds i128"))?;
|
||||
Ok(AggregateChange {
|
||||
target,
|
||||
stat,
|
||||
before,
|
||||
contribution,
|
||||
after: normalize(stat, entity.entity_type, raw)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Clamp before narrowing; population has no gameplay upper bound.
|
||||
pub(crate) fn normalize(
|
||||
stat: StatName,
|
||||
kind: EntityType,
|
||||
value: i128,
|
||||
) -> Result<isize, AdjudicationError> {
|
||||
let minimum = if matches!(kind, EntityType::Event | EntityType::Blocker) {
|
||||
-120
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let value = match stat {
|
||||
StatName::Population => value.max(minimum),
|
||||
StatName::GrowthRate => value.clamp(-120, 120),
|
||||
_ => value.clamp(minimum, 120),
|
||||
};
|
||||
isize::try_from(value).map_err(|_| {
|
||||
invalid(format!(
|
||||
"{stat:?} result {value} exceeds this platform's supported range"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Merge source state by minimum/OR rather than report arrival order.
|
||||
fn reduce_sources(world: &mut EpochInfo) -> Result<(), AdjudicationError> {
|
||||
let state = world
|
||||
.epoch_resolution
|
||||
.as_ref()
|
||||
.ok_or_else(|| invalid("missing epoch baseline"))?;
|
||||
let mut sources = BTreeMap::<Uuid, EventAdjudicationState>::new();
|
||||
for id in &state.records {
|
||||
let report = world
|
||||
.adjudications
|
||||
.get(id)
|
||||
.ok_or_else(|| invalid(format!("missing record @{id}")))?;
|
||||
if state
|
||||
.baseline
|
||||
.find_entity_strict(report.source, Some(EntityType::Event))
|
||||
.is_err()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let original = state.baseline.event_adjudications.get(&report.source);
|
||||
let source = sources
|
||||
.entry(report.source)
|
||||
.or_insert_with(|| EventAdjudicationState {
|
||||
potency_basis_points: original.map_or(10_000, |entry| entry.potency_basis_points),
|
||||
destroyed: original.is_some_and(|entry| entry.destroyed),
|
||||
last_record: *id,
|
||||
});
|
||||
source.potency_basis_points = source.potency_basis_points.min(report.source_potency_after);
|
||||
source.destroyed |= report.disposition == AdjudicationDisposition::Destroyed;
|
||||
source.last_record = *id;
|
||||
if source.destroyed {
|
||||
source.potency_basis_points = 0;
|
||||
}
|
||||
}
|
||||
for (id, source) in sources {
|
||||
if source.destroyed
|
||||
&& let Some(diffusion) = world.diffusions.get_mut(&id)
|
||||
{
|
||||
diffusion.expired = true;
|
||||
}
|
||||
world.event_adjudications.insert(id, source);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check persisted accumulator structure and its audit references.
|
||||
pub fn validate(world: &EpochInfo) -> Result<(), AdjudicationError> {
|
||||
let Some(state) = &world.epoch_resolution else {
|
||||
return Ok(());
|
||||
};
|
||||
crate::adjudication::validate_adjudications(world)?;
|
||||
if state.ruleset != RULESET
|
||||
|| state.baseline.epoch_resolution.is_some()
|
||||
|| state.baseline.epoch_id > world.epoch_id
|
||||
|| state.records.is_empty()
|
||||
{
|
||||
return Err(invalid(
|
||||
"invalid epoch resolution ruleset, baseline, or record membership",
|
||||
));
|
||||
}
|
||||
crate::adjudication::validate_adjudications(&state.baseline)?;
|
||||
for id in &state.records {
|
||||
if state.baseline.adjudications.contains_key(id) {
|
||||
return Err(invalid(format!(
|
||||
"record @{id} already belongs to the epoch baseline"
|
||||
)));
|
||||
}
|
||||
let report = world
|
||||
.adjudications
|
||||
.get(id)
|
||||
.ok_or_else(|| invalid(format!("missing epoch resolution record @{id}")))?;
|
||||
let potency = state
|
||||
.baseline
|
||||
.event_adjudications
|
||||
.get(&report.source)
|
||||
.map_or(10_000, |entry| entry.potency_basis_points);
|
||||
if report.source_potency_before != potency
|
||||
|| !(0..=potency).contains(&report.source_potency_after)
|
||||
{
|
||||
return Err(invalid(format!(
|
||||
"record @{id} has inconsistent epoch source potency"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let changes = aggregate_state(world, state)?;
|
||||
if state.baseline.epoch_id == world.epoch_id {
|
||||
for change in changes {
|
||||
let target = world.find_entity_strict(change.target, None)?;
|
||||
if **target.get_stats().get_field(&change.stat.list_stat()) != change.after {
|
||||
return Err(invalid(format!(
|
||||
"target @{} {:?} differs from its epoch resolution; restore the worktree or commit before editing resolved statistics",
|
||||
change.target, change.stat
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stable collection order for frozen inputs and published worlds.
|
||||
fn canonicalize(world: &mut EpochInfo) {
|
||||
for kind in [
|
||||
EntityType::Character,
|
||||
EntityType::Town,
|
||||
EntityType::Event,
|
||||
EntityType::Calamity,
|
||||
EntityType::Organization,
|
||||
EntityType::Blocker,
|
||||
] {
|
||||
world
|
||||
.vec_entities_mut(&kind)
|
||||
.sort_by_key(|entity| entity.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a domain validation error with caller-provided context.
|
||||
fn invalid(message: impl Into<String>) -> AdjudicationError {
|
||||
AdjudicationError::Invalid(message.into())
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ pub mod conflict;
|
|||
pub mod diff;
|
||||
pub mod entity;
|
||||
pub mod epoch;
|
||||
pub mod epoch_resolution;
|
||||
pub mod naming;
|
||||
pub mod output;
|
||||
pub mod repository_format;
|
||||
|
|
|
|||
|
|
@ -352,7 +352,10 @@ impl OverallStats {
|
|||
// TODO: Force the use of this ?
|
||||
pub fn update(&mut self) {
|
||||
self.demographics =
|
||||
(*(self.population + self.growth_rate + self.happiness - self.crime) / 4).into();
|
||||
(((*self.population as i128 + *self.growth_rate as i128 + *self.happiness as i128
|
||||
- *self.crime as i128)
|
||||
/ 4) as isize)
|
||||
.into();
|
||||
self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into();
|
||||
self.military =
|
||||
(*(self.army + self.strength + self.fortification + self.threat) / 4).into();
|
||||
|
|
|
|||
|
|
@ -283,6 +283,12 @@ impl Workspace {
|
|||
|
||||
/// Persist a caller-modified worktree through the transaction layer.
|
||||
pub fn save_worktree(&self, command: &str) -> Result<(), WorkspaceError> {
|
||||
if self.worktree.world.epoch_resolution.is_some() && self.manifest.format_version.minor == 0
|
||||
{
|
||||
return Err(WorkspaceError::Inconsistent(
|
||||
"epoch resolution requires format 1.1 publication".into(),
|
||||
));
|
||||
}
|
||||
save(&self.root, ".efo/worktree.json", &self.worktree, command)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,235 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"epoch_id":{"id":0},"rng_seed":0,"tags":{"inner":[]},"summary":"legacy epoch without resolution state","events":[],"characters":[],"towns":[],"calamities":[],"blockers":[]}
|
||||
Loading…
Reference in New Issue