test: harden epoch resolution compatibility and reduction boundaries

This commit is contained in:
Dandaedre 2026-09-24 19:35:42 +02:00
parent 4124e9c61d
commit b8df3cc142
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
10 changed files with 154 additions and 14 deletions

View File

@ -268,6 +268,9 @@ and [`docs/presentation-design.md`](docs/presentation-design.md).
complete-resolution stage/restore, historical validation, and CLI permutation tests.
- [x] Add pinned event-local ChaCha12 named draws; keep GM rolls external and
preserve the existing worldgen algorithm. Actual worker pools remain future work.
- Final validation: 167 all-feature workspace tests, formatting, and strict
Clippy pass. Coverage includes all six three-ruling permutations, three mixed
CLI orders, format upgrades, legacy records, stale snapshots, and overflow.
- [x] Document immutable batch inputs, event/occurrence RNG identities, exact
delta reduction, normalization, retries, phase barriers, and atomic publication

View File

@ -10,7 +10,7 @@ future timeline when needed.
The current release manages organisations, characters, towns, events,
calamities, and blockers with statistics and relationships. Repository format
1.0 provides worktree/index staging, immutable commits, restore, conflict-safe
1.1 provides worktree/index staging, immutable commits, restore, conflict-safe
revert, switching, and recoverable future pruning from initialisation. A separate
TUI searches entities across HEAD, staged, and working state, and offers
previewed entity creation/editing with one-step undo. Custom fields and TUI
@ -71,7 +71,7 @@ Run `efo --help`, `efo <command> --help`, or see the
| Area | Available now | Not available yet |
|---|---|---|
| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
| Repository | Initialise format 1.1; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
| Timeline | Commit, advance, switch, log, tag, summarise, diff, reviewable/committed revert, backed-up pruning, and explicit hard reset | Branching and merging |
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
| Generation and simulation | Generate deterministic seeded worlds; roads, travel, event diffusion/arrival resolution; record external rolls and adjudications; run multi-side fights and wars | Setting template packs and interpolated in-transit positions |

View File

@ -24,9 +24,9 @@ metadata as the model becomes organisation-agnostic.
Phase 4's approved persistence boundary is specified in the
[staging, history, and recovery design](staging-design.md). It separates HEAD,
the index, and the editable worktree, and defines the atomic transaction rules
that implementation must preserve. The sole pre-release repository format is
version 1.0; its structured major/minor discriminator leaves room for explicit
1.x migrations without retaining an unreleased prototype reader.
that implementation must preserve. Repository format 1.1 adds a persisted epoch-resolution baseline; 1.0 remains
readable and upgrades atomically on resolution publication or new history.
The structured version rejects readers that cannot preserve the new state.
The [TUI contract](tui-design.md) covers browsing and previewed entity editing.
`EntityDraft` validates forms in the library; `Workspace::apply_entity_change`
checks the editor snapshot and writes the worktree under one transaction lock.
@ -39,3 +39,10 @@ ptrace backend cannot reliably attribute child-process execution. Routine CI
should run formatting, all-target workspace tests, strict Clippy, and a release
build. Tarpaulin and `rust_autobadges` remain local significant-release-only
tools. See [AGENTS.md](../AGENTS.md) for contributor rules.
`epoch_resolution` owns independent baseline previews and exact contribution
reduction for adjudication, diffusion arrivals, and conflict rounds. CLI handlers
render local and aggregate outcomes and call `Workspace::apply_resolution` for
locked stale-snapshot validation and publication. `event_rng` provides immutable
named ChaCha12 draws from frozen event inputs; adjudication remains externally
rolled. See [the execution contract](deterministic-execution-design.md).

View File

@ -68,3 +68,6 @@ versions are pinned; golden vectors were cross-checked with an independent
Python FNV/ChaCha12 reference calculation. GM rulings and existing worldgen do
not call this API. No worker pool, transfer allocation, or automatic event
scheduling is introduced by this feature.
Final validation: formatting, 167 locked all-feature workspace tests, and strict
Clippy pass. All implementation increments are committed on the feature branch.

View File

@ -73,7 +73,7 @@ The optional `epoch_resolution` field stores ruleset
set of enrolled adjudication IDs. The baseline has no nested resolution state.
Each new adjudication identifies its `epoch_baseline`; absent fields on 1.0
records mean historical sequential semantics. Old records are never enrolled
implicitly. Committed snapshots retain the interval's audit inputs; a new
implicitly; their already-applied effects become part of the first new baseline. Committed snapshots retain the interval's audit inputs; a new
interval replaces the worktree's baseline rather than nesting previous ones.
Existing 1.0 repositories open without writes. Applying a resolution upgrades

View File

@ -23,7 +23,7 @@ Nerd Font output has a portable build option, relationships are type-validated,
and every mutation has documented and tested recovery guidance.
The [Phase 4 format contract](staging-design.md) is implemented. Native format
1.0 initialization, locking, recovery, staging, immutable commits, revert, and
1.1 initialization, locking, recovery, staging, immutable commits, revert, and
recoverable pruning are implemented. The unreleased prototype reader and its
temporary migration were removed before the first release. Future compatible
changes use 1.x versions and regain explicit migration tooling when needed.
@ -59,3 +59,9 @@ direct terminal printing. PNG map rendering follows those tracker issues.
Completions and structured output are the best first stretch investments. A TUI
and branching should wait until staging, revert, and locking are reliable.
Epoch-wide independent ruling reduction is implemented across adjudication,
diffusion resolution, and conflict rounds, with format-1.0 compatibility reads.
Named event-local RNG is available as a library foundation. Worker pools,
automatic event scheduling, and transfer allocation remain future work; see
[the completed implementation checklist](epoch-resolution-tasks.md).

View File

@ -158,13 +158,17 @@ pub fn apply(
.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
{
if **target.get_stats().get_field(&change.stat.list_stat()) != change.before {
return Err(AdjudicationError::Stale {
target: report.target,
});
}
if **current.get_stats().get_field(&change.stat.list_stat()) != expected {
return Err(invalid(format!(
"target @{} {:?} was edited since the epoch baseline; commit or restore the worktree before resolving this field",
report.target, change.stat
)));
}
}
updated.adjudications.insert(report.id, report.clone());
let state = updated

View File

@ -22,10 +22,10 @@ impl std::fmt::Display for FormatVersion {
}
}
/// The only repository format supported by this pre-release build.
/// Latest writable repository format; older minors in this major remain readable.
pub const CURRENT_FORMAT_VERSION: FormatVersion = FormatVersion { major: 1, minor: 1 };
/// The version-2 repository manifest.
/// The versioned repository manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryManifest {
/// On-disk format discriminator.
@ -63,7 +63,7 @@ impl RepositoryManifest {
}
}
/// A complete version-2 index or worktree snapshot.
/// A complete versioned index or worktree snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositorySnapshot {
/// Snapshot format discriminator.

View File

@ -1,4 +1,4 @@
//! Format-2 HEAD, index, and worktree access.
//! Format-1.x HEAD, index, and worktree access.
use std::{
collections::{BTreeMap, HashMap},
@ -231,6 +231,7 @@ impl Workspace {
/// Copy the complete worktree into the index.
pub fn stage_all(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.worktree.world.clone();
self.index.format_version = self.worktree.format_version;
self.save_index("stage --all")
}

View File

@ -388,3 +388,119 @@ fn event_rng_reads_frozen_inputs_and_compounds_its_identity_only_next_epoch() {
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());
}