Skip to main content

hypergraph_rs/raster/ingest/
nodes.rs

1//! Node ingest: agent extraction, dense-index assignment, contract defaults
2//! and typed errors (Phase I, Task 2). See the [`super`] module doc for the
3//! normative attribute contract this file implements.
4
5use std::collections::HashMap;
6
7use serde_json::Value;
8
9use crate::raster::deck::Agent;
10use crate::Hypergraph;
11
12use super::{AttrContract, IngestError, TensionSource, DEFAULT_BLOC};
13
14/// Build a `key -> dense index` lookup over `ids`, for `edges.rs` (Task 3)
15/// to resolve edge members without re-scanning `node_ids()`. Internal only:
16/// its `HashMap` iteration order must never reach an output `Vec` (Global
17/// Constraints — determinism).
18///
19/// Live: called from `to_world` (`ingest/mod.rs`) to build the index handed
20/// to `ingest_edges`.
21pub(crate) fn index_of(ids: &[String]) -> HashMap<&str, usize> {
22    let mut out = HashMap::with_capacity(ids.len());
23    // Bounded: one pass over `ids` (node count).
24    for (i, id) in ids.iter().enumerate() {
25        out.insert(id.as_str(), i);
26    }
27    out
28}
29
30/// Read a required, finite `f64` attribute. `key` absent ⇒
31/// [`IngestError::MissingNodeAttr`]; present but not a finite number ⇒
32/// [`IngestError::BadAttrType`].
33fn read_required_f64(attrs: &Value, key: &str, owner: &str) -> Result<f64, IngestError> {
34    let v = attrs.get(key).ok_or_else(|| IngestError::MissingNodeAttr {
35        node: owner.to_string(),
36        key: key.to_string(),
37    })?;
38    let f = v.as_f64().ok_or_else(|| IngestError::BadAttrType {
39        owner: owner.to_string(),
40        key: key.to_string(),
41    })?;
42    if !f.is_finite() {
43        return Err(IngestError::BadAttrType {
44            owner: owner.to_string(),
45            key: key.to_string(),
46        });
47    }
48    Ok(f)
49}
50
51/// Read `bloc`: absent ⇒ [`DEFAULT_BLOC`] (and the caller counts it);
52/// present ⇒ must be a `u8` in `0..=2`, else [`IngestError::BadAttrType`].
53fn read_bloc(
54    attrs: &Value,
55    key: &str,
56    owner: &str,
57    defaulted: &mut usize,
58) -> Result<u8, IngestError> {
59    match attrs.get(key) {
60        None => {
61            *defaulted += 1;
62            Ok(DEFAULT_BLOC)
63        }
64        Some(v) => {
65            let n = v.as_u64().ok_or_else(|| IngestError::BadAttrType {
66                owner: owner.to_string(),
67                key: key.to_string(),
68            })?;
69            if n > 2 {
70                return Err(IngestError::BadAttrType {
71                    owner: owner.to_string(),
72                    key: key.to_string(),
73                });
74            }
75            Ok(n as u8)
76        }
77    }
78}
79
80/// Read the optional `h3_cell`: absent ⇒ `None`; a `u64`-shaped JSON number
81/// or a decimal string ⇒ `Some(u64)` (a decimal string is required because
82/// JSON numbers lose precision above 2^53 and H3 indices exceed it); any
83/// other shape ⇒ [`IngestError::BadAttrType`].
84fn read_h3_cell(attrs: &Value, key: &str, owner: &str) -> Result<Option<u64>, IngestError> {
85    match attrs.get(key) {
86        None => Ok(None),
87        Some(Value::Number(n)) => n
88            .as_u64()
89            .map(Some)
90            .ok_or_else(|| IngestError::BadAttrType {
91                owner: owner.to_string(),
92                key: key.to_string(),
93            }),
94        Some(Value::String(s)) => {
95            s.parse::<u64>()
96                .map(Some)
97                .map_err(|_| IngestError::BadAttrType {
98                    owner: owner.to_string(),
99                    key: key.to_string(),
100                })
101        }
102        Some(_) => Err(IngestError::BadAttrType {
103            owner: owner.to_string(),
104            key: key.to_string(),
105        }),
106    }
107}
108
109/// Result of [`ingest_nodes`]: agents in `node_ids()` order; the parallel
110/// original-id vector; the parallel optional H3 cells; the count of nodes
111/// whose `bloc` defaulted; and which formula produced `subsistence`.
112///
113/// A named struct rather than a 5-tuple — the Task 9 clippy leg's preferred
114/// fix for `clippy::type_complexity` over an `#[allow]` (the `IngestedEdges`
115/// precedent in `edges.rs` follows the same shape).
116#[derive(Debug, Clone, PartialEq)]
117pub struct IngestedNodes {
118    pub agents: Vec<Agent>,
119    pub node_ids: Vec<String>,
120    pub h3_cells: Vec<Option<u64>>,
121    pub bloc_defaulted: usize,
122    pub tension_source: TensionSource,
123}
124
125/// Ingest one node per agent, in [`Hypergraph::node_ids`] order.
126///
127/// `repression` is the graph-level repression scalar (read from graph attrs
128/// by `to_world`, Task 4) — needed here only to invert a supplied `tension`
129/// attr into a synthetic `subsistence` per the D-I1 algebra (module doc,
130/// "tension" row). **Deviation from the plan's abbreviated interface
131/// sketch**, which omitted this parameter: the inversion `subsistence' =
132/// wealth + t/repression` is not computable without it, and no other
133/// signature lets `to_world` supply it before agents exist. Recorded in the
134/// executor's deviations, not invented silently.
135///
136/// Bounded: two passes over `h.node_ids()` (node count) — pass 1 detects
137/// whether *any* node carries the tension key (which puts every node under
138/// the same, stricter, obligation), pass 2 builds the agents.
139pub fn ingest_nodes(
140    h: &Hypergraph<Value, Value, Value>,
141    c: &AttrContract,
142    repression: f64,
143) -> Result<IngestedNodes, IngestError> {
144    let ids = h.node_ids();
145    static EMPTY: Value = Value::Null;
146
147    // Pass 1: does any node carry the tension key? If so every node must
148    // (a half-populated field is the silent-mixing failure the contract
149    // forbids).
150    let mut any_tension = false;
151    for id in &ids {
152        let attrs = h.node_attrs(id).unwrap_or(&EMPTY);
153        if attrs.get(&c.tension).is_some() {
154            any_tension = true;
155            break;
156        }
157    }
158    let tension_source = if any_tension {
159        TensionSource::Attr
160    } else {
161        TensionSource::Derived
162    };
163
164    let mut agents = Vec::with_capacity(ids.len());
165    let mut h3_cells = Vec::with_capacity(ids.len());
166    let mut bloc_defaulted = 0usize;
167
168    // Pass 2: build each agent.
169    for (idx, id) in ids.iter().enumerate() {
170        let attrs = h.node_attrs(id).unwrap_or(&EMPTY);
171
172        let wealth = read_required_f64(attrs, &c.wealth, id)?;
173
174        let subsistence = if any_tension {
175            let t = read_required_f64(attrs, &c.tension, id)?;
176            if t < 0.0 {
177                return Err(IngestError::BadAttrType {
178                    owner: id.clone(),
179                    key: c.tension.clone(),
180                });
181            }
182            if repression.is_finite() && repression > 0.0 {
183                wealth + t / repression
184            } else {
185                // `repression` is invalid; `to_world`'s own precondition
186                // check rejects this graph before the value below is ever
187                // observed. Fall back to a finite, non-fabricated value
188                // rather than dividing by a non-positive number.
189                wealth
190            }
191        } else {
192            read_required_f64(attrs, &c.subsistence, id)?
193        };
194
195        let bloc = read_bloc(attrs, &c.bloc, id, &mut bloc_defaulted)?;
196        let h3 = read_h3_cell(attrs, &c.h3_cell, id)?;
197
198        agents.push(Agent {
199            id: idx,
200            bloc,
201            wealth,
202            subsistence,
203        });
204        h3_cells.push(h3);
205    }
206
207    Ok(IngestedNodes {
208        agents,
209        node_ids: ids,
210        h3_cells,
211        bloc_defaulted,
212        tension_source,
213    })
214}