Skip to main content

hypergraph_rs/raster/ingest/
mod.rs

1//! Attribute contract + typed ingest errors for real-`Hypergraph` topology
2//! ingest (Phase I, Task 1). This module doc is the **canonical, normative**
3//! home of the attribute contract; `plans/phase-I-topology-ingest.md` is its
4//! rationale, not its spec.
5//!
6//! `ATTR_CONTRACT_VERSION` is bumped whenever a key's *meaning*, default, or
7//! error disposition changes — never for adding a new optional key (D-I3).
8//!
9//! ## Node attrs (one node per agent)
10//!
11//! | Contract field | Default key | Type | Missing ⇒ | Rationale |
12//! |---|---|---|---|---|
13//! | `identity` | *(the node id itself)* | `String` | n/a | The `Hypergraph` node id **is** the agent identity (D7 stringly-typed boundary). Never read from attrs. |
14//! | `wealth` | `"wealth"` | finite `f64` | [`IngestError::MissingNodeAttr`] | Feeds `agent_tension` and `psa`. No honest default exists. |
15//! | `subsistence` | `"subsistence"` | finite `f64` | [`IngestError::MissingNodeAttr`] | Same. |
16//! | `bloc` | `"bloc"` | `u8` in `0..=2` | [`DEFAULT_BLOC`] | Bloc selects a marker colour and the periphery filter. `1` is the neutral unclassified middle bloc. With ≥2 communities, at least one node must carry `bloc == PERIPHERY_BLOC (2)` or ingest errors. |
17//! | `tension` | `"tension"` | finite `f64 ≥ 0` | absent ⇒ derive | Optional override. When present, used verbatim as the terrain's per-agent scalar (via a `subsistence` inversion); when absent the frozen `agent_tension(a, repression)` formula applies. Recorded in [`IngestReport::tension_source`]. |
18//! | `h3_cell` | `"h3_cell"` | `u64` or decimal `String` | absent ⇒ `None` | Optional, carried not consumed. Stored in [`IngestReport::h3_cells`]; no instrument reads it. A decimal string is accepted because JSON numbers lose precision above 2^53 and H3 ids exceed it. |
19//!
20//! ## Edge attrs (edge `kind` dispatches the shape)
21//!
22//! `kind` default key `"kind"`. An edge whose `kind` is missing or
23//! unrecognised is **skipped** and counted in [`IngestReport::skipped_edges`]
24//! — never a silent success, never an error.
25//!
26//! | `kind` | Extra keys | Missing ⇒ | Maps to |
27//! |---|---|---|---|
28//! | `"community"` | `name` (default [`DEFAULT_COMMUNITY_NAME`] + edge id), `links` (array of 2-element id arrays, default `[]`) | name defaults; `links` defaults to empty | `Community { name, members = edge members, links }`. Any link id not among this edge's own members ⇒ [`IngestError::LinkOutsideCommunity`]. |
29//! | `"extraction"` | `head` (node id, **required**), `mass` (default [`DEFAULT_MASS`]) | missing `head` ⇒ [`IngestError::MissingEdgeAttr`] | `Extraction { tails = members minus head, head, mass }`. `head` not among members ⇒ [`IngestError::HeadNotMember`]. `mass` defaults because no instrument reads it. |
30//! | `"industry"` | `name` (default = edge id), `c`, `v`, `e` (finite `f64`, **all required**), `lane` (`u8` in `0..=3`) | `c`/`v`/`e` missing ⇒ [`IngestError::MissingEdgeAttr`]; `lane` missing ⇒ [`DEFAULT_LANE`] and [`IngestReport::lane_defaulted`] set | `Industry { name, lane, c, v, e }`. `v == 0.0` ⇒ [`IngestError::DegenerateIndustry`]. |
31//!
32//! ## Graph attrs
33//!
34//! | Contract field | Default key | Missing ⇒ | Notes |
35//! |---|---|---|---|
36//! | `repression` | `"repression"` | [`DEFAULT_REPRESSION`] | Scales `agent_tension` and appears in `psr`'s denominator. Must be finite and `> 0.0`, else [`IngestError::BadGraphAttr`]. |
37//! | `zoom` | `"zoom"` | [`DEFAULT_ZOOM`] (fine) | `instruments::build` maps `zoom == 1` → coarse, else fine. |
38//!
39//! `seed` and `tick` are **not** in the contract: they are set to `0` on the
40//! produced `DeckWorld` (documented sentinels, never read by any
41//! instrument); real provenance lives on [`IngestReport`].
42
43use serde::{Deserialize, Serialize};
44use serde_json::Value;
45
46use crate::raster::deck::DeckWorld;
47#[cfg(feature = "cells3d")]
48use crate::raster::instruments::{self, Instrument, InstrumentOpts};
49#[cfg(feature = "cells3d")]
50use crate::raster::SceneGraph3D;
51use crate::Hypergraph;
52
53mod edges;
54mod nodes;
55
56pub use edges::{ingest_edges, IngestedEdges};
57pub(crate) use nodes::index_of;
58pub use nodes::{ingest_nodes, IngestedNodes};
59
60/// Version of the attribute contract's key spellings, defaults, and error
61/// dispositions. Bumped only on a meaning-changing edit (D-I3).
62pub const ATTR_CONTRACT_VERSION: u32 = 1;
63
64pub const K_WEALTH: &str = "wealth";
65pub const K_SUBSISTENCE: &str = "subsistence";
66pub const K_BLOC: &str = "bloc";
67pub const K_TENSION: &str = "tension";
68pub const K_H3_CELL: &str = "h3_cell";
69pub const K_KIND: &str = "kind";
70pub const K_NAME: &str = "name";
71pub const K_LINKS: &str = "links";
72pub const K_HEAD: &str = "head";
73pub const K_MASS: &str = "mass";
74pub const K_LANE: &str = "lane";
75pub const K_C: &str = "c";
76pub const K_V: &str = "v";
77pub const K_E: &str = "e";
78pub const K_REPRESSION: &str = "repression";
79pub const K_ZOOM: &str = "zoom";
80
81pub const KIND_COMMUNITY: &str = "community";
82pub const KIND_EXTRACTION: &str = "extraction";
83pub const KIND_INDUSTRY: &str = "industry";
84
85/// Default bloc for a node with no `bloc` attr: the neutral, unclassified
86/// middle bloc — never "core" (0) or "periphery" (2).
87pub const DEFAULT_BLOC: u8 = 1;
88/// The bloc read by `periphery_mean_wealth` (`deck.rs:416-419`).
89pub const PERIPHERY_BLOC: u8 = 2;
90/// Default lane for an industry edge with no `lane` attr. Babylon has no
91/// per-sector lane classification (see module doc); every unlabelled
92/// industry lands here and [`IngestReport::lane_defaulted`] is raised.
93pub const DEFAULT_LANE: u8 = 0;
94/// Default `mass` for an extraction edge: safe because no instrument reads
95/// `mass` (only `do_tick` does, which Phase I never calls).
96pub const DEFAULT_MASS: f64 = 1.0;
97/// Default `repression`: the identity scaling, the one value that adds no
98/// information.
99pub const DEFAULT_REPRESSION: f64 = 1.0;
100/// Default `zoom`: fine (un-aggregated).
101pub const DEFAULT_ZOOM: u8 = 0;
102/// Prefix used to synthesize a community name when `name` is absent; the
103/// edge id is appended.
104pub const DEFAULT_COMMUNITY_NAME: &str = "community-";
105
106/// Named spellings for every contract-governed attribute key, plus the
107/// contract version. Owned `String`s so a caller may rename any key
108/// (e.g. to match babylon's own vocabulary) without forking the crate.
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110pub struct AttrContract {
111    pub version: u32,
112    pub wealth: String,
113    pub subsistence: String,
114    pub bloc: String,
115    pub tension: String,
116    pub h3_cell: String,
117    pub kind: String,
118    pub name: String,
119    pub links: String,
120    pub head: String,
121    pub mass: String,
122    pub lane: String,
123    pub c: String,
124    pub v: String,
125    pub e: String,
126    pub repression: String,
127    pub zoom: String,
128}
129
130impl Default for AttrContract {
131    fn default() -> Self {
132        Self {
133            version: ATTR_CONTRACT_VERSION,
134            wealth: K_WEALTH.to_string(),
135            subsistence: K_SUBSISTENCE.to_string(),
136            bloc: K_BLOC.to_string(),
137            tension: K_TENSION.to_string(),
138            h3_cell: K_H3_CELL.to_string(),
139            kind: K_KIND.to_string(),
140            name: K_NAME.to_string(),
141            links: K_LINKS.to_string(),
142            head: K_HEAD.to_string(),
143            mass: K_MASS.to_string(),
144            lane: K_LANE.to_string(),
145            c: K_C.to_string(),
146            v: K_V.to_string(),
147            e: K_E.to_string(),
148            repression: K_REPRESSION.to_string(),
149            zoom: K_ZOOM.to_string(),
150        }
151    }
152}
153
154/// Which formula produced a `DeckWorld`'s per-agent tension: the frozen
155/// `agent_tension` derivation, or a caller-supplied `tension` attr (inverted
156/// into a synthetic `subsistence` — see [`crate::raster::ingest`] module
157/// doc, D-I1).
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum TensionSource {
160    Derived,
161    Attr,
162}
163
164/// Provenance and every default applied while ingesting one `Hypergraph`:
165/// what was read, what was defaulted, and how a rendered node maps back to
166/// the caller's own string id.
167#[derive(Debug, Clone, PartialEq)]
168pub struct IngestReport {
169    pub contract_version: u32,
170    /// Dense render-space index -> original `Hypergraph` node id.
171    pub node_ids: Vec<String>,
172    pub agent_count: usize,
173    pub community_count: usize,
174    pub extraction_count: usize,
175    pub industry_count: usize,
176    /// Edge ids whose `kind` was missing or unrecognised.
177    pub skipped_edges: Vec<String>,
178    pub bloc_defaulted: usize,
179    pub lane_defaulted: bool,
180    pub repression_defaulted: bool,
181    pub tension_source: TensionSource,
182    /// Parallel to `node_ids`.
183    pub h3_cells: Vec<Option<u64>>,
184}
185
186/// Every way ingest can fail. Each variant carries the offending node/edge
187/// id and key so a caller can find the exact place their graph disagrees
188/// with the contract (Power-of-10 rule 4: no catch-all).
189#[derive(Debug, thiserror::Error, PartialEq)]
190pub enum IngestError {
191    #[error("node `{node}` is missing required attribute `{key}`")]
192    MissingNodeAttr { node: String, key: String },
193    #[error("edge `{edge}` (kind `{kind}`) is missing required attribute `{key}`")]
194    MissingEdgeAttr {
195        edge: String,
196        kind: String,
197        key: String,
198    },
199    #[error("attribute `{key}` on `{owner}` has the wrong shape or is not finite")]
200    BadAttrType { owner: String, key: String },
201    #[error("graph attribute `{key}` is invalid: {reason}")]
202    BadGraphAttr { key: String, reason: String },
203    #[error("community edge `{edge}` links node `{node}`, which is not one of its members")]
204    LinkOutsideCommunity { edge: String, node: String },
205    #[error("extraction edge `{edge}` names head `{node}`, which is not one of its members")]
206    HeadNotMember { edge: String, node: String },
207    #[error("industry edge `{edge}` has v == 0 (rate of exploitation would divide by zero)")]
208    DegenerateIndustry { edge: String },
209    #[error("edge `{edge}` references node `{node}`, which is not in the hypergraph")]
210    UnknownNode { edge: String, node: String },
211    #[error("at least 2 agent nodes are required for a spectral embedding, found {found}")]
212    TooFewAgents { found: usize },
213    #[error(
214        "a world with {communities} communities computes psa over the periphery bloc ({bloc}), but no node carries it"
215    )]
216    NoPeripheryBloc { communities: usize, bloc: u8 },
217}
218
219/// Read the `repression` graph attr: absent ⇒ [`DEFAULT_REPRESSION`] (and
220/// `defaulted` is set); present ⇒ must be a finite `f64` (its `> 0.0`
221/// requirement is checked by the caller, since the message differs from a
222/// bad-shape message). Bad shape ⇒ [`IngestError::BadGraphAttr`].
223fn read_repression(
224    h: &Hypergraph<Value, Value, Value>,
225    key: &str,
226    defaulted: &mut bool,
227) -> Result<f64, IngestError> {
228    match h.graph_attr(key) {
229        None => {
230            *defaulted = true;
231            Ok(DEFAULT_REPRESSION)
232        }
233        Some(v) => v.as_f64().ok_or_else(|| IngestError::BadGraphAttr {
234            key: key.to_string(),
235            reason: "must be a finite number".to_string(),
236        }),
237    }
238}
239
240/// Read the `zoom` graph attr: absent ⇒ [`DEFAULT_ZOOM`]; present ⇒ must be
241/// a `u8`, else [`IngestError::BadGraphAttr`].
242fn read_zoom(h: &Hypergraph<Value, Value, Value>, key: &str) -> Result<u8, IngestError> {
243    match h.graph_attr(key) {
244        None => Ok(DEFAULT_ZOOM),
245        Some(v) => {
246            let n = v.as_u64().ok_or_else(|| IngestError::BadGraphAttr {
247                key: key.to_string(),
248                reason: "must be an unsigned integer".to_string(),
249            })?;
250            u8::try_from(n).map_err(|_| IngestError::BadGraphAttr {
251                key: key.to_string(),
252                reason: "must fit in a u8".to_string(),
253            })
254        }
255    }
256}
257
258/// Ingest a real `Hypergraph` into a `DeckWorld` the frozen render path
259/// (`instruments::build` → `rasterize` / `render_pixels`) can consume
260/// unchanged, per `c`'s attribute contract. Pure and deterministic: two
261/// calls on the same `(h, c)` produce equal outputs (Global Constraints —
262/// determinism).
263///
264/// Validates the three CRITICAL PRECONDITIONS (module doc, "Global
265/// Constraints" / plan's "CRITICAL PRECONDITION FINDING") before returning,
266/// as a straight-line sequence of explicit checks — no combined
267/// "invalid world" catch-all (Power-of-10 rule 4):
268///
269/// 1. `agents.len() >= 2`, else [`IngestError::TooFewAgents`] (the spectral
270///    embedding's `smallest_k_eigenvectors` requirement).
271/// 2. If `communities.len() >= 2` and no agent carries [`PERIPHERY_BLOC`],
272///    [`IngestError::NoPeripheryBloc`] — the `0.0/0.0` route in
273///    `periphery_mean_wealth` (`deck.rs:416-419`).
274/// 3. `repression` finite and `> 0.0`, else [`IngestError::BadGraphAttr`]
275///    (it divides in `psr`, `deck.rs:445`).
276pub fn to_world(
277    h: &Hypergraph<Value, Value, Value>,
278    c: &AttrContract,
279) -> Result<(DeckWorld, IngestReport), IngestError> {
280    let mut repression_defaulted = false;
281    let repression = read_repression(h, &c.repression, &mut repression_defaulted)?;
282    if !repression.is_finite() || repression <= 0.0 {
283        return Err(IngestError::BadGraphAttr {
284            key: c.repression.clone(),
285            reason: "must be finite and > 0.0".to_string(),
286        });
287    }
288    let zoom = read_zoom(h, &c.zoom)?;
289
290    let IngestedNodes {
291        agents,
292        node_ids,
293        h3_cells,
294        bloc_defaulted,
295        tension_source,
296    } = ingest_nodes(h, c, repression)?;
297
298    if agents.len() < 2 {
299        return Err(IngestError::TooFewAgents {
300            found: agents.len(),
301        });
302    }
303
304    let index = index_of(&node_ids);
305    let edges = ingest_edges(h, c, &index)?;
306
307    if edges.communities.len() >= 2 && !agents.iter().any(|a| a.bloc == PERIPHERY_BLOC) {
308        return Err(IngestError::NoPeripheryBloc {
309            communities: edges.communities.len(),
310            bloc: PERIPHERY_BLOC,
311        });
312    }
313
314    let world = DeckWorld {
315        seed: 0,
316        agents,
317        communities: edges.communities,
318        extraction: edges.extraction,
319        industries: edges.industries,
320        repression,
321        tick: 0,
322        zoom,
323    };
324
325    let report = IngestReport {
326        contract_version: c.version,
327        agent_count: world.agents.len(),
328        community_count: world.communities.len(),
329        extraction_count: world.extraction.len(),
330        industry_count: world.industries.len(),
331        skipped_edges: edges.skipped,
332        bloc_defaulted,
333        lane_defaulted: edges.lane_defaulted,
334        repression_defaulted,
335        tension_source,
336        node_ids,
337        h3_cells,
338    };
339
340    Ok((world, report))
341}
342
343/// Ingest `h` per `c`, then dispatch to the **untouched**
344/// `instruments::build` (Task 5, graceful degradation). This is a thin
345/// wrapper: it never edits, wraps, or reimplements a builder — a change
346/// here can never be the reason a builder's byte-identity guarantee (Task
347/// 6) breaks.
348///
349/// Degradation policy (exhaustive, no case left to judgement):
350///
351/// - Any [`IngestError`] from `to_world` ⇒ `Err` — the caller learns which
352///   node/edge and which key.
353/// - [`Instrument::Sankey`] with zero industry edges ⇒
354///   `Ok((SceneGraph3D::empty(), report))`. `algebra::transform(&[])`
355///   computes `0.0/0.0 = NaN`, which would otherwise reach the glyph
356///   banner; an empty scene is the honest rendering of "no industries".
357/// - Every other `(instrument, world)` pair ⇒ `Ok((instruments::build(..),
358///   report))` — including zero-community `Cylinder`/`Terrain`, which is a
359///   legitimate degraded-but-real scene handled by the builders themselves.
360#[cfg(feature = "cells3d")]
361pub fn build_scene(
362    h: &Hypergraph<Value, Value, Value>,
363    c: &AttrContract,
364    inst: Instrument,
365    opts: &InstrumentOpts,
366) -> Result<(SceneGraph3D, IngestReport), IngestError> {
367    let (world, report) = to_world(h, c)?;
368
369    if inst == Instrument::Sankey && world.industries.is_empty() {
370        return Ok((SceneGraph3D::empty(), report));
371    }
372
373    let scene = instruments::build(inst, &world, opts);
374    Ok((scene, report))
375}