feat(simulation): dispatch RegionProfile layer in production (T-1032)

The D-239 carrier layer (T-1023/1024/1026) only ran in tests because every
production AnalyzeBody enqueue passed body_params: None. Wire the real path:

- New BodyParamsReader (server/src/atlas/body_params_reader.rs): read-only
  systems.db reader, joins bodies -> star_systems (LEFT JOIN) for the climate/
  tectonic inputs. SQL verified against systems-schema.sql. All fields Option,
  NULLs handled; tectonic_activity absent from schema -> None (derives from
  planet_class). 5 unit tests.
- layer_proxy.rs: on cache miss, read the body's params and pass
  Some(Box::new(..)). On read error, warn + fall back to None (cascade stops at
  Settlement, no panic) — graceful degradation.
- plugin.rs / main.rs: register BodyParamsReaderResource (CityContextReader
  pattern) and thread it through serve_atlas_requests.

BodyWorldState.regions now populates for real bodies in the D-206 background
pass. End-to-end tests cover wired (regions populated) + unwired (empty) paths.

cargo test 1504 pass, clippy -D warnings clean, fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-08 12:28:01 +02:00
co-authored by Claude Opus 4.8
parent a516b06de9
commit 1887c886ef
5 changed files with 581 additions and 7 deletions
+196 -4
View File
@@ -13,6 +13,7 @@
use serde::{Deserialize, Serialize};
use crate::atlas::body_params_reader::BodyParamsReader;
use crate::atlas::body_world_state::{BodyWorldStateCache, SimTick};
use crate::atlas::cascade::CascadeLayer;
use crate::atlas::city_context_reader::CityContextReader;
@@ -64,12 +65,20 @@ pub struct AtlasLayerResponse {
/// `city_reader` supplies the body's settlements for Layer-3 placement (#955),
/// read on a cache miss. `None` (or a read failure) places no cities — the
/// cascade still runs Layer 1; the body just gets no settlement placements.
///
/// `body_params_reader` supplies the body's physical parameters for the
/// RegionProfile carrier layer (T-1032, D-239 §1), read on a cache miss.
/// `None` (or a read failure) passes `body_params: None` to the work item,
/// causing the cascade to stop at `CascadeLayer::Settlement` (pre-T-1032
/// behaviour). A successful read passes `Some(Box::new(params))`, enabling
/// the full `CascadeLayer::RegionProfile` path.
pub fn handle_atlas_request(
req: &AtlasLayerRequest,
cache: &mut BodyWorldStateCache,
queue: &GenerationQueue,
resolver: &BodySourceResolver,
city_reader: Option<&CityContextReader>,
body_params_reader: Option<&BodyParamsReader>,
world_seed: u64,
current_tick: SimTick,
) -> AtlasLayerResponse {
@@ -124,6 +133,24 @@ pub fn handle_atlas_request(
}
None => (Vec::new(), None),
};
// Pre-resolve body physical params so the Rayon work item stays
// DB-free (D-225 pattern). Read failures are non-fatal: log and
// fall back to None (cascade stops at Settlement, pre-T-1032
// behaviour, rather than aborting the entire analysis).
let body_params = match body_params_reader {
Some(reader) => reader
.read_body_params(&req.body_id)
.map(|p| Some(Box::new(p)))
.unwrap_or_else(|e| {
tracing::warn!(
body_id = %req.body_id,
error = %e,
"body_params read failed; region layer skipped"
);
None
}),
None => None,
};
queue.submit(
GenWorkItem::AnalyzeBody {
body_id: req.body_id.clone(),
@@ -132,7 +159,7 @@ pub fn handle_atlas_request(
body_seed: SeedChain::for_body(world_seed, &req.body_id),
cities,
dominant_faction,
body_params: None, // T-1023: body_params wired when DB reader is extended
body_params,
},
GenPriority::Immediate,
);
@@ -250,7 +277,16 @@ mod tests {
let (_db, resolver) = empty_resolver();
let queue = GenerationQueue::with_threads(1);
let resp = handle_atlas_request(&req("GJ1c"), &mut cache, &queue, &resolver, None, 42, 1);
let resp = handle_atlas_request(
&req("GJ1c"),
&mut cache,
&queue,
&resolver,
None,
None,
42,
1,
);
assert_eq!(resp.status, AtlasLayerStatus::Ready);
assert_eq!(resp.layer1.expect("layer1").body_id, "GJ1c");
}
@@ -261,7 +297,16 @@ mod tests {
let (_db, resolver) = resolver_with_body("GJ1c");
let queue = GenerationQueue::with_threads(1);
let resp = handle_atlas_request(&req("GJ1c"), &mut cache, &queue, &resolver, None, 42, 1);
let resp = handle_atlas_request(
&req("GJ1c"),
&mut cache,
&queue,
&resolver,
None,
None,
42,
1,
);
assert_eq!(resp.status, AtlasLayerStatus::Pending);
assert!(resp.layer1.is_none());
@@ -282,7 +327,154 @@ mod tests {
let (_db, resolver) = empty_resolver();
let queue = GenerationQueue::with_threads(1);
let resp = handle_atlas_request(&req("ghost"), &mut cache, &queue, &resolver, None, 42, 1);
let resp = handle_atlas_request(
&req("ghost"),
&mut cache,
&queue,
&resolver,
None,
None,
42,
1,
);
assert_eq!(resp.status, AtlasLayerStatus::NotFound);
}
/// Build a DB with the columns needed by both `BodySourceResolver` and
/// `BodyParamsReader` for the same body, plus a tiny heightmap root.
///
/// Returns (db_path, resolver, body_params_reader, _root_kept_alive).
fn resolver_and_params_reader(
body_id: &str,
) -> (
PathBuf,
BodySourceResolver,
crate::atlas::body_params_reader::BodyParamsReader,
PathBuf, // root dir — must stay alive for the test duration
) {
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let db = std::env::temp_dir().join(format!("sr_proxybp_{}_{n}.db", std::process::id()));
let _ = std::fs::remove_file(&db);
let conn = Connection::open(&db).unwrap();
conn.execute_batch(
"CREATE TABLE star_systems (
system_id TEXT PRIMARY KEY,
spectral_class TEXT,
star_type TEXT
);
CREATE TABLE bodies (
body_id TEXT PRIMARY KEY,
system_id TEXT,
terrain_reference TEXT,
hydrosphere TEXT,
atmosphere TEXT,
planet_class TEXT,
orbital_period_days REAL,
axial_tilt_deg REAL
);",
)
.unwrap();
conn.execute(
"INSERT INTO star_systems (system_id, spectral_class, star_type) VALUES ('GJ-1', 'G', 'main_sequence')",
[],
)
.unwrap();
conn.execute(
"INSERT INTO bodies (body_id, system_id, terrain_reference, hydrosphere, atmosphere, planet_class, orbital_period_days, axial_tilt_deg)
VALUES (?1, 'GJ-1', ?2, 'ocean', 'breathable', 'temperate', 365.25, 23.5)",
rusqlite::params![body_id, REL],
)
.unwrap();
drop(conn);
let root = std::env::temp_dir().join(format!("sr_proxybproot_{}_{n}", std::process::id()));
write_tiny_heightmap(&root.join(REL));
let resolver = BodySourceResolver::open(&db, vec![root.clone()]).unwrap();
let params_reader = crate::atlas::body_params_reader::BodyParamsReader::open(&db).unwrap();
(db, resolver, params_reader, root)
}
/// With body_params_reader wired, a cache miss enqueues an AnalyzeBody that
/// completes with populated `regions` (RegionProfile layer ran).
#[test]
fn body_params_reader_wired_produces_populated_regions() {
let mut cache = BodyWorldStateCache::new(CACHE_CAPACITY);
let (_db, resolver, params_reader, _root) = resolver_and_params_reader("GJ1c");
let queue = GenerationQueue::with_threads(1);
let resp = handle_atlas_request(
&req("GJ1c"),
&mut cache,
&queue,
&resolver,
None,
Some(&params_reader),
42,
1,
);
assert_eq!(resp.status, AtlasLayerStatus::Pending);
// Wait for the Rayon work item to complete.
std::thread::sleep(Duration::from_millis(300));
let completions = queue.drain_completions();
let body_state = completions
.into_iter()
.find_map(|c| {
if let GenCompletion::BodyAnalyzed { body_id, state } = c {
if body_id == "GJ1c" {
return Some(state);
}
}
None
})
.expect("AnalyzeBody must complete for GJ1c");
assert!(
!body_state.regions.is_empty(),
"regions must be populated when body_params_reader is wired (T-1032 dispatch path)"
);
}
/// Without body_params_reader (None), regions is empty — pre-T-1032 behaviour.
#[test]
fn no_body_params_reader_leaves_regions_empty() {
let mut cache = BodyWorldStateCache::new(CACHE_CAPACITY);
let (_db, resolver) = resolver_with_body("GJ1c");
let queue = GenerationQueue::with_threads(1);
let resp = handle_atlas_request(
&req("GJ1c"),
&mut cache,
&queue,
&resolver,
None,
None, // no body_params_reader
42,
1,
);
assert_eq!(resp.status, AtlasLayerStatus::Pending);
std::thread::sleep(Duration::from_millis(300));
let completions = queue.drain_completions();
let body_state = completions
.into_iter()
.find_map(|c| {
if let GenCompletion::BodyAnalyzed { body_id, state } = c {
if body_id == "GJ1c" {
return Some(state);
}
}
None
})
.expect("AnalyzeBody must complete for GJ1c");
assert!(
body_state.regions.is_empty(),
"regions must remain empty when no body_params_reader is wired"
);
}
}