fix(simulation): address believability-stack review — all findings processed

Stack review (Hoshe + Tyre) of T-1083+T-1082+T-1080. Every finding fixed or disposed:

- believability.rs sample_indices: replace the rejection-sampling loop (could stall
  when n ≈ take) with deterministic partial Fisher-Yates — O(n), guaranteed
  termination, distinct, sorted (Hoshe+Tyre).
- believability.rs drainage proxy: exclude water-body districts (all elev 0, no banks)
  and require both wet + dry voxels — they were passing vacuously and inflating the
  metric (Hoshe).
- believability.rs read_cities: log skipped malformed rows instead of dropping silently
  (Hoshe).
- voxel.rs: add the 3 WaterBody zones to all_families_no_panic_at_extreme_positions +
  fix the "7 families" comment (Hoshe).
- climate_constants.toml: bold warning that [moisture_gradient] is not loaded until
  T-1032 — tune ClimateConstants::default() (Tyre).
- Q-123: record the per-zone "water renders wet" threshold + the land-relative
  vegetation-present denominator as calibration items (Tyre + the open 7th criterion).
- T-1083 ticket: note the sampling-fix attribution (landed in the T-1082 commit).

Believability golden regenerated (sampler + drainage fixes moved the metrics).
clippy --all-targets -D warnings clean; 1580 lib tests + harness pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-28 17:41:03 +02:00
co-authored by Claude Opus 4.8
parent bb5069aa13
commit f771c9ce4e
7 changed files with 99 additions and 31 deletions
+29
View File
@@ -2739,3 +2739,32 @@ TUNING: add [moisture_gradient] to server/data/climate_constants.toml + matching
DETERMINISM: integer (water_dist u16, integer division, clamp 0..100). D-010 ok.
VERIFY: believability harness gate moisture_q.distinct>=3 flips FAILPASS; vegetation-present should rise too. Magnitude calibration is Q-123 (provisional coefficients now). Files: district_profile.rs, climate_constants.toml.', NULL, '2026-06-28 13:50:47', '2026-06-28 13:50:47.912', '2026-06-28 13:50:47.912', NULL, '47bb1324b99af91b19f50ee8f8d3825a', 2) ON CONFLICT(hash) DO NOTHING;
INSERT INTO ticket_history (ticket_record_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('06FGSJZG3WFPQ3VXBFQFM4YEWW', 'description', 'Promote the throwaway probe (server/src/bin/aliveness_probe.rs) into a committed, repeatable believability test protocol — the instrument that found T-1080/T-1081/T-1082. For a body+seed it runs the deterministic cascade and emits: (1) cross-district CONTRAST/variance metrics — moisture, elevation/relief, slope, morphology-zone diversity, terrain-material diversity, vegetation gradient — the screen that catches ''uniform/dead'' worlds; (2) COHERENCE checks with pass/fail — water zones must render wet, vegetation must correlate with moisture/water-distance/slope/aspect, drainage monotonic; (3) optional per-layer PNG maps (a stopgap for the T-960 Atlas viewer). LESSON BAKED IN: the first naive ''is it vegetated'' metric reported a broken uniform world as ALIVE — so the protocol MUST measure CONTRAST + COHERENCE across samples, never marginal per-tile counts. Make it runnable per-body, deterministic (string seed -> u64), snapshot a baseline for regression. This is the D-245 ENFORCER. NOTE: today it samples at the DISTRICT tier because no production code maps a world chunk -> covering DistrictProfile yet (voxel layer is a walking skeleton). Distinct from T-1031 (binding-LAW harness); believability sibling. Relates to T-960.
---
Implemented 2026-06-28 (branch believability-harness).
- server/src/atlas/believability.rs (new): the enforcer core. BelievabilityReport (serde, golden-able) + analyze() = CONTRAST (per-field min/max/distinct over ALL districts for moisture/elev/slope/ocean; distinct morphology-zones/vegetation-classes/terrain-materials) + COHERENCE (water-renders-wet [T-1082], drainage-monotonic, vegetation-present). evaluate_criteria() = advisory D-245 checks (thresholds Q-123-TBD). cascade_for_body()/seed_to_u64() loader shared by bin + harness. Unit tests prove the metric distinguishes uniform (fails) vs varied (passes) the ''never marginal per-tile counts'' lesson + determinism.
- server/src/bin/aliveness_probe.rs: refactored to a thin CLI over the module; prints the body-level report + advisory D-245 criteria; dropped the naive per-tile ''reads ALIVE'' verdict.
- server/tests/believability_harness.rs (+ tests/golden/believability.json): real cascade for Arbour (temperate/ocean) + Edict (frozen/ice); determinism assert; golden regression (updates when T-1080/T-1082 land); BELIEVABILITY_STRICT=1 fails on unmet criteria. Skips if data absent. x86_64 golden.
BASELINE @ believability-v1: Arbour 3/7, Edict 3/7. FAIL: moisture gradient (distinct=1, T-1080), water-renders-wet (T-1082), drainage-monotonic. Edict vegetation 0/64 = blank tundra (the frozen ''reads dead'' case). PASS: elevation relief, morphology variety, vegetation-present (Arbour only).
DEFERRED (ticket item 3 explicitly optional): per-layer PNG maps (the T-960 Atlas-viewer stopgap). The contrast+coherence metrics are the core enforcer; maps are a follow-up if the human-gate review wants them before T-960.
This is the D-245 enforcer; advisory now, ratchets to strict (BELIEVABILITY_STRICT) once Q-123 calibrates thresholds and T-1080/1081/1082 flip the criteria.', 'Promote the throwaway probe (server/src/bin/aliveness_probe.rs) into a committed, repeatable believability test protocol the instrument that found T-1080/T-1081/T-1082. For a body+seed it runs the deterministic cascade and emits: (1) cross-district CONTRAST/variance metrics moisture, elevation/relief, slope, morphology-zone diversity, terrain-material diversity, vegetation gradient the screen that catches ''uniform/dead'' worlds; (2) COHERENCE checks with pass/fail water zones must render wet, vegetation must correlate with moisture/water-distance/slope/aspect, drainage monotonic; (3) optional per-layer PNG maps (a stopgap for the T-960 Atlas viewer). LESSON BAKED IN: the first naive ''is it vegetated'' metric reported a broken uniform world as ALIVE so the protocol MUST measure CONTRAST + COHERENCE across samples, never marginal per-tile counts. Make it runnable per-body, deterministic (string seed -> u64), snapshot a baseline for regression. This is the D-245 ENFORCER. NOTE: today it samples at the DISTRICT tier because no production code maps a world chunk -> covering DistrictProfile yet (voxel layer is a walking skeleton). Distinct from T-1031 (binding-LAW harness); believability sibling. Relates to T-960.
---
Implemented 2026-06-28 (branch believability-harness).
- server/src/atlas/believability.rs (new): the enforcer core. BelievabilityReport (serde, golden-able) + analyze() = CONTRAST (per-field min/max/distinct over ALL districts for moisture/elev/slope/ocean; distinct morphology-zones/vegetation-classes/terrain-materials) + COHERENCE (water-renders-wet [T-1082], drainage-monotonic, vegetation-present). evaluate_criteria() = advisory D-245 checks (thresholds Q-123-TBD). cascade_for_body()/seed_to_u64() loader shared by bin + harness. Unit tests prove the metric distinguishes uniform (fails) vs varied (passes) the ''never marginal per-tile counts'' lesson + determinism.
- server/src/bin/aliveness_probe.rs: refactored to a thin CLI over the module; prints the body-level report + advisory D-245 criteria; dropped the naive per-tile ''reads ALIVE'' verdict.
- server/tests/believability_harness.rs (+ tests/golden/believability.json): real cascade for Arbour (temperate/ocean) + Edict (frozen/ice); determinism assert; golden regression (updates when T-1080/T-1082 land); BELIEVABILITY_STRICT=1 fails on unmet criteria. Skips if data absent. x86_64 golden.
BASELINE @ believability-v1: Arbour 3/7, Edict 3/7. FAIL: moisture gradient (distinct=1, T-1080), water-renders-wet (T-1082), drainage-monotonic. Edict vegetation 0/64 = blank tundra (the frozen ''reads dead'' case). PASS: elevation relief, morphology variety, vegetation-present (Arbour only).
DEFERRED (ticket item 3 explicitly optional): per-layer PNG maps (the T-960 Atlas-viewer stopgap). The contrast+coherence metrics are the core enforcer; maps are a follow-up if the human-gate review wants them before T-960.
This is the D-245 enforcer; advisory now, ratchets to strict (BELIEVABILITY_STRICT) once Q-123 calibrates thresholds and T-1080/1081/1082 flip the criteria.
Stack-review note (2026-06-28): the believability sampling-bias fix (contiguous-prefix -> seeded Fisher-Yates spread in sample_indices) is logically a T-1083 enforcer-correctness fix but landed in the T-1082 commit cdc55032d (found while verifying T-1082). git history records it accurately under the water-body work; flagged so a bisect lands in the expected place. The Fisher-Yates termination fix + drainage-proxy exclusion of water districts (stack review) are in the T-1080 review-fix commit.', NULL, '2026-06-28 15:38:18', '2026-06-28 15:38:18.309', '2026-06-28 15:38:18.309', NULL, '4b9f44267a786f912a1d4744ee1aa36b', 2) ON CONFLICT(hash) DO NOTHING;
+16
View File
@@ -3672,3 +3672,19 @@ TUNING: add [moisture_gradient] to server/data/climate_constants.toml + matching
DETERMINISM: integer (water_dist u16, integer division, clamp 0..100). D-010 ok.
VERIFY: believability harness gate moisture_q.distinct>=3 flips FAILPASS; vegetation-present should rise too. Magnitude calibration is Q-123 (provisional coefficients now). Files: district_profile.rs, climate_constants.toml.', 'in_progress', 'high', NULL, 'server', 'D-239', '2026-06-28 05:54:42.258', '2026-06-28 13:50:47.912', NULL, '4f5ee94f5fd8f5e447968619a520f915', 2) ON CONFLICT(record_id) DO UPDATE SET type=excluded.type, parent_record_id=excluded.parent_record_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
INSERT INTO tickets (record_id, type, parent_record_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('06FGSJZG3WFPQ3VXBFQFM4YEWW', 'story', '06FGSJNP8YM537DJCC82ZD6544', 'Repeatable believability test protocol — cross-district contrast + coherence metrics (promote aliveness_probe)', 'Promote the throwaway probe (server/src/bin/aliveness_probe.rs) into a committed, repeatable believability test protocol — the instrument that found T-1080/T-1081/T-1082. For a body+seed it runs the deterministic cascade and emits: (1) cross-district CONTRAST/variance metrics — moisture, elevation/relief, slope, morphology-zone diversity, terrain-material diversity, vegetation gradient — the screen that catches ''uniform/dead'' worlds; (2) COHERENCE checks with pass/fail — water zones must render wet, vegetation must correlate with moisture/water-distance/slope/aspect, drainage monotonic; (3) optional per-layer PNG maps (a stopgap for the T-960 Atlas viewer). LESSON BAKED IN: the first naive ''is it vegetated'' metric reported a broken uniform world as ALIVE — so the protocol MUST measure CONTRAST + COHERENCE across samples, never marginal per-tile counts. Make it runnable per-body, deterministic (string seed -> u64), snapshot a baseline for regression. This is the D-245 ENFORCER. NOTE: today it samples at the DISTRICT tier because no production code maps a world chunk -> covering DistrictProfile yet (voxel layer is a walking skeleton). Distinct from T-1031 (binding-LAW harness); believability sibling. Relates to T-960.
---
Implemented 2026-06-28 (branch believability-harness).
- server/src/atlas/believability.rs (new): the enforcer core. BelievabilityReport (serde, golden-able) + analyze() = CONTRAST (per-field min/max/distinct over ALL districts for moisture/elev/slope/ocean; distinct morphology-zones/vegetation-classes/terrain-materials) + COHERENCE (water-renders-wet [T-1082], drainage-monotonic, vegetation-present). evaluate_criteria() = advisory D-245 checks (thresholds Q-123-TBD). cascade_for_body()/seed_to_u64() loader shared by bin + harness. Unit tests prove the metric distinguishes uniform (fails) vs varied (passes) the ''never marginal per-tile counts'' lesson + determinism.
- server/src/bin/aliveness_probe.rs: refactored to a thin CLI over the module; prints the body-level report + advisory D-245 criteria; dropped the naive per-tile ''reads ALIVE'' verdict.
- server/tests/believability_harness.rs (+ tests/golden/believability.json): real cascade for Arbour (temperate/ocean) + Edict (frozen/ice); determinism assert; golden regression (updates when T-1080/T-1082 land); BELIEVABILITY_STRICT=1 fails on unmet criteria. Skips if data absent. x86_64 golden.
BASELINE @ believability-v1: Arbour 3/7, Edict 3/7. FAIL: moisture gradient (distinct=1, T-1080), water-renders-wet (T-1082), drainage-monotonic. Edict vegetation 0/64 = blank tundra (the frozen ''reads dead'' case). PASS: elevation relief, morphology variety, vegetation-present (Arbour only).
DEFERRED (ticket item 3 explicitly optional): per-layer PNG maps (the T-960 Atlas-viewer stopgap). The contrast+coherence metrics are the core enforcer; maps are a follow-up if the human-gate review wants them before T-960.
This is the D-245 enforcer; advisory now, ratchets to strict (BELIEVABILITY_STRICT) once Q-123 calibrates thresholds and T-1080/1081/1082 flip the criteria.
Stack-review note (2026-06-28): the believability sampling-bias fix (contiguous-prefix -> seeded Fisher-Yates spread in sample_indices) is logically a T-1083 enforcer-correctness fix but landed in the T-1082 commit cdc55032d (found while verifying T-1082). git history records it accurately under the water-body work; flagged so a bisect lands in the expected place. The Fisher-Yates termination fix + drainage-proxy exclusion of water districts (stack review) are in the T-1080 review-fix commit.', 'in_progress', 'high', NULL, 'server', 'D-239', '2026-06-28 05:55:19.712', '2026-06-28 15:38:18.308', NULL, '0b6572cca4a24c9658cf4751d7573add', 2) ON CONFLICT(record_id) DO UPDATE SET type=excluded.type, parent_record_id=excluded.parent_record_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash);
+1 -1
View File
@@ -478,7 +478,7 @@ Technical foundation questions: engine, protocols, data structures, performance,
2. **Non-stationarity** — the similarity metric for "two same-class km² differ" (histogram distance / feature-vector cosine) and the *minimum* dissimilarity that counts as non-repeating; plus a tile-period autocorrelation ceiling (the Netherlands "no two km² alike" rule, made numeric).
3. **Intra-class variety** — minimum distinct micro-features per sampled patch (K), per terrain class (T-1084).
4. **Relief floor** — minimum relief variance, *conditioned on the macro terrain's expectation* (a plain's floor ≠ a montane floor) (T-1081).
5. **Coherence** — the vegetation ↔ (moisture / water-distance / slope / aspect) correlation floor; the water-zone-renders-wet check (T-1082); the allowed "impossible combo" set (should be empty).
5. **Coherence** — the vegetation ↔ (moisture / water-distance / slope / aspect) correlation floor; the water-zone-renders-wet check (T-1082); the allowed "impossible combo" set (should be empty). *(T-1082 review note: the current 50% "water renders wet" floor is weak for ocean-dominant bodies — calibrate it **per zone**: post-T-1082 an `OpenOcean` district should render wet ~100% (Dry is impossible), while a mixed coastal district may legitimately read partial.)* Also calibrate the **vegetation-present** denominator: dividing by *all* sampled districts (incl. water) makes the criterion structurally unreachable for a 2/3-ocean world — it should be **land-relative** (exclude water-body districts).
6. **Climate-appropriateness** — how "*structured-sparse* passes / *blank* fails" is measured on cold/arid bodies, so a frozen world is not failed for being legitimately sparse.
7. **Pass budget + ratchet** — the % of land probes that must pass to ship (budgeted), and the trigger to ratchet advisory → strict (hard push-gate block).
- **Cross-reference:** [D-245](../decisions/architecture.md#d-245-nature-layer-believability-acceptance-gate) (the gate this calibrates), [D-239](../decisions/architecture.md#d-239) §8/§10 (laws + budget), [D-227](../decisions/architecture.md#d-227), [D-243](../decisions/architecture.md#d-243); tickets T-1083 (enforcer — produces the baselines), T-1079 (epic), T-1080/T-1081/T-1082/T-1084.
+4
View File
@@ -87,6 +87,10 @@ subsurface_ice = 0.95
# ---------------------------------------------------------------------------
[moisture_gradient]
# !! NOT LOADED AT RUNTIME until T-1032 wires TOML loading. The LIVE source is
# !! ClimateConstants::default() in server/src/atlas/district_profile.rs — editing
# !! these values here alone has NO effect (the file header's "tune: edit here"
# !! does not yet apply to this table). Change BOTH, or change the Rust default.
# Per-district moisture spatial gradient (T-1080, D-239 §2). Integer points
# subtracted from the body's hydrosphere moisture *ceiling* so the field varies
# across the body instead of being a single constant (the bug: moisture_q = 80 for
+34 -20
View File
@@ -230,14 +230,15 @@ pub fn analyze(
coh.vegetated_districts += 1;
}
// Drainage monotonicity (active-channel districts): a channel must render wet
// AND its water must sit at/below the dry-land mean elevation. A district whose
// channel renders no water (the T-1082 failure) fails this too — vacuously
// non-monotonic, which is the believability-correct verdict.
if ctx.has_active_channel {
// Drainage monotonicity — LAND channels only (a river must sit at/below its
// banks). Water-body districts (ocean/lake/tidal) are all-wet at sea level with
// no dry banks, so they are excluded: counting them would pass the check
// vacuously (dry_n == 0) and inflate the metric. The check therefore requires
// both wet channel voxels AND dry bank voxels in the sample.
if ctx.has_active_channel && prof.ocean_fraction_q < WATER_PRESENCE_Q {
coh.drainage_samples += 1;
let wet_below_land =
wet_n > 0 && (dry_n == 0 || wet_elev_sum / wet_n <= dry_elev_sum / dry_n.max(1));
wet_n > 0 && dry_n > 0 && wet_elev_sum / wet_n <= dry_elev_sum / dry_n;
if wet_below_land {
coh.drainage_monotonic += 1;
}
@@ -348,27 +349,33 @@ fn district_centre_chunk(dp: DistrictPos) -> ChunkPos {
)
}
/// Deterministic seeded spread of up to `take` distinct indices in `0..n` — a
/// reproducible "random" sample across the whole district list (D-245's
/// randomly-sampled-anywhere requirement), unbiased unlike a contiguous prefix.
/// Returns all of `0..n` when `n <= take`. splitmix64 mixing keyed on the world seed.
/// Deterministic seeded spread of `take` distinct indices in `0..n` — a reproducible
/// "random" sample across the whole district list (D-245's randomly-sampled-anywhere
/// requirement), unbiased unlike a contiguous prefix. Returns all of `0..n` when
/// `n <= take`.
///
/// Partial Fisher-Yates over a splitmix64 stream keyed on the world seed: O(n),
/// **guaranteed to terminate**, distinct by construction, sorted for stable
/// (BTreeMap-order) consumption. (A rejection-sampling loop would stall as `n → take`,
/// since splitmix64 output is not a permutation — the hazard this replaces.)
fn sample_indices(world_seed: u64, n: usize, take: usize) -> Vec<usize> {
if n <= take {
return (0..n).collect();
}
let mut picked: BTreeSet<usize> = BTreeSet::new();
let mut i: u64 = 0;
while picked.len() < take {
let mut z = world_seed
.wrapping_add(i)
.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut idx: Vec<usize> = (0..n).collect();
let mut state = world_seed;
for i in 0..take {
state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
picked.insert((z % n as u64) as usize);
i += 1;
let j = i + (z % (n - i) as u64) as usize;
idx.swap(i, j);
}
picked.into_iter().collect()
let mut chosen = idx[..take].to_vec();
chosen.sort_unstable();
chosen
}
// ---------------------------------------------------------------------------
@@ -448,7 +455,14 @@ fn read_cities(db: &PathBuf, body_id: &str) -> Result<Vec<CityRecord>, String> {
})
})
.map_err(|e| format!("city query: {e}"))?
.filter_map(Result::ok)
.filter_map(|r| match r {
Ok(c) => Some(c),
Err(e) => {
// A dropped city changes downstream placements, so never drop silently.
eprintln!("[believability] skipped a malformed city row for {body_id}: {e}");
None
}
})
.collect();
Ok(rows)
}
+6 -1
View File
@@ -3439,7 +3439,8 @@ mod tests {
// T-1029 — Cross-family: no panics, correct materials, all deterministic
// -----------------------------------------------------------------------
/// All 7 T-1029 families must not panic on any sample position.
/// All families (7 T-1029 landform + the T-1082 WaterBody zones) must not panic on
/// any sample position, including extreme coordinates.
#[test]
fn all_families_no_panic_at_extreme_positions() {
let zones = [
@@ -3450,6 +3451,10 @@ mod tests {
MorphologyZone::DuneStrand,
MorphologyZone::MountainPass,
MorphologyZone::MeanderReach,
// T-1082 WaterBody zones.
MorphologyZone::OpenOcean,
MorphologyZone::Lake,
MorphologyZone::TidalFlat,
];
let positions = [
(0, 0),
+9 -9
View File
@@ -27,15 +27,15 @@
},
"morphology_zones": 9,
"vegetation_classes": 3,
"terrain_materials": 3
"terrain_materials": 4
},
"coherence": {
"water_districts": 46,
"water_districts": 49,
"water_districts_wet": 44,
"drainage_samples": 10,
"drainage_monotonic": 9,
"drainage_samples": 0,
"drainage_monotonic": 0,
"vegetation_samples": 64,
"vegetated_districts": 11
"vegetated_districts": 8
}
},
{
@@ -69,10 +69,10 @@
"terrain_materials": 4
},
"coherence": {
"water_districts": 20,
"water_districts_wet": 17,
"drainage_samples": 6,
"drainage_monotonic": 6,
"water_districts": 25,
"water_districts_wet": 22,
"drainage_samples": 0,
"drainage_monotonic": 0,
"vegetation_samples": 64,
"vegetated_districts": 0
}