Skip to main content

feagi_brain_development/
mapping_rule_schema.rs

1// Copyright 2025 Neuraville Inc.
2// Licensed under the Apache License, Version 2.0
3
4//! Single source of truth for the fields of a dict-format cortical mapping rule: type, range,
5//! default, allowed values, and whether the field only configures plasticity.
6//!
7//! `ConnectomeManager` validation reads the ranges from here, and
8//! `GET /v1/cortical_mapping/rule_schema` serves this table, so clients and the validator
9//! cannot disagree.
10
11use serde_json::{json, Map, Value};
12
13/// JSON type of a rule field.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum RuleFieldType {
16    Boolean,
17    Integer,
18    Number,
19    String,
20    Array,
21    Object,
22}
23
24impl RuleFieldType {
25    /// Name used in the schema reply.
26    pub fn as_str(self) -> &'static str {
27        match self {
28            Self::Boolean => "boolean",
29            Self::Integer => "integer",
30            Self::Number => "number",
31            Self::String => "string",
32            Self::Array => "array",
33            Self::Object => "object",
34        }
35    }
36}
37
38/// Default a field resolves to when the rule omits it (or sets null).
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub enum RuleDefault {
41    /// No default: the field is optional with no effect, or required.
42    None,
43    Bool(bool),
44    Int(i64),
45    Num(f64),
46    Str(&'static str),
47}
48
49/// One mapping-rule field.
50#[derive(Debug, Clone, Copy)]
51pub struct MappingRuleField {
52    pub key: &'static str,
53    pub kind: RuleFieldType,
54    /// Lower bound, if any.
55    pub min: Option<f64>,
56    /// When true the lower bound itself is excluded (`value > min`).
57    pub min_exclusive: bool,
58    /// Upper bound (inclusive), if any.
59    pub max: Option<f64>,
60    pub default: RuleDefault,
61    /// Allowed string values (case-insensitive), for enumerated fields.
62    pub allowed: &'static [&'static str],
63    /// True when changing the field never changes which synapses exist or their stored weights.
64    pub plasticity_only: bool,
65}
66
67impl MappingRuleField {
68    /// True when `value` is a finite-or-infinite non-NaN number inside the field's range.
69    pub fn accepts_number(&self, value: f64) -> bool {
70        if value.is_nan() {
71            return false;
72        }
73        if let Some(min) = self.min {
74            if value < min || (self.min_exclusive && value <= min) {
75                return false;
76            }
77        }
78        if let Some(max) = self.max {
79            if value > max {
80                return false;
81            }
82        }
83        true
84    }
85
86    /// JSON entry served by the schema endpoint.
87    pub fn to_schema_json(&self) -> Value {
88        let default = match self.default {
89            RuleDefault::None => Value::Null,
90            RuleDefault::Bool(b) => json!(b),
91            RuleDefault::Int(i) => json!(i),
92            RuleDefault::Num(f) => json!(f),
93            RuleDefault::Str(s) => json!(s),
94        };
95        let mut entry = Map::new();
96        entry.insert("type".into(), json!(self.kind.as_str()));
97        entry.insert("min".into(), self.min.map_or(Value::Null, |v| json!(v)));
98        entry.insert("max".into(), self.max.map_or(Value::Null, |v| json!(v)));
99        entry.insert("default".into(), default);
100        if self.min_exclusive {
101            entry.insert("exclusive_min".into(), json!(true));
102        }
103        if !self.allowed.is_empty() {
104            entry.insert("enum".into(), json!(self.allowed));
105        }
106        entry.insert("plasticity_only".into(), json!(self.plasticity_only));
107        Value::Object(entry)
108    }
109}
110
111const fn field(key: &'static str, kind: RuleFieldType, plasticity_only: bool) -> MappingRuleField {
112    MappingRuleField {
113        key,
114        kind,
115        min: None,
116        min_exclusive: false,
117        max: None,
118        default: RuleDefault::None,
119        allowed: &[],
120        plasticity_only,
121    }
122}
123
124pub const PLASTICITY_FLAG: MappingRuleField = MappingRuleField {
125    default: RuleDefault::Bool(false),
126    ..field("plasticity_flag", RuleFieldType::Boolean, true)
127};
128pub const PLASTICITY_MODE: MappingRuleField = MappingRuleField {
129    default: RuleDefault::Str("stdp"),
130    allowed: &["off", "stdp", "rstdp"],
131    ..field("plasticity_mode", RuleFieldType::String, true)
132};
133pub const PLASTICITY_WINDOW: MappingRuleField = MappingRuleField {
134    min: Some(0.0),
135    ..field("plasticity_window", RuleFieldType::Integer, true)
136};
137pub const PLASTICITY_CONSTANT: MappingRuleField =
138    field("plasticity_constant", RuleFieldType::Integer, true);
139/// LTP / LTD multipliers are stored in the NPU as `i8`.
140pub const LTP_MULTIPLIER: MappingRuleField = MappingRuleField {
141    min: Some(i8::MIN as f64),
142    max: Some(i8::MAX as f64),
143    ..field("ltp_multiplier", RuleFieldType::Integer, true)
144};
145pub const LTD_MULTIPLIER: MappingRuleField = MappingRuleField {
146    min: Some(i8::MIN as f64),
147    max: Some(i8::MAX as f64),
148    ..field("ltd_multiplier", RuleFieldType::Integer, true)
149};
150pub const ELIGIBILITY_DECAY_BURSTS: MappingRuleField = MappingRuleField {
151    min: Some(0.0),
152    max: Some(u32::MAX as f64),
153    default: RuleDefault::Int(0),
154    ..field("eligibility_decay_bursts", RuleFieldType::Integer, true)
155};
156/// Learning-rate scale on the end-of-burst weight commit: finite and strictly positive.
157pub const PLASTICITY_ETA: MappingRuleField = MappingRuleField {
158    min: Some(0.0),
159    min_exclusive: true,
160    max: Some(f32::MAX as f64),
161    default: RuleDefault::Num(1.0),
162    ..field("plasticity_eta", RuleFieldType::Number, true)
163};
164/// Upper clamp on plastic weights: strictly positive; absent means no clamp.
165pub const MAX_WEIGHT: MappingRuleField = MappingRuleField {
166    min: Some(0.0),
167    min_exclusive: true,
168    ..field("max_weight", RuleFieldType::Number, true)
169};
170pub const ONE_SIDED_FIRING: MappingRuleField = MappingRuleField {
171    default: RuleDefault::Str("decrement"),
172    allowed: &["decrement", "ignore"],
173    ..field("one_sided_firing", RuleFieldType::String, true)
174};
175pub const MODULATORS: MappingRuleField = field("modulators", RuleFieldType::Array, true);
176pub const CLASSIFIER_INSTANCE_REWARD: MappingRuleField =
177    field("classifier_instance_reward", RuleFieldType::String, true);
178pub const REWARD_SOURCE_AREA: MappingRuleField =
179    field("reward_source_area", RuleFieldType::String, true);
180pub const PUNISHMENT_SOURCE_AREA: MappingRuleField =
181    field("punishment_source_area", RuleFieldType::String, true);
182
183/// Structural fields: they decide which synapses exist, so changing them rebuilds the mapping.
184pub const MORPHOLOGY_ID: MappingRuleField = field("morphology_id", RuleFieldType::String, false);
185pub const MORPHOLOGY_SCALAR: MappingRuleField =
186    field("morphology_scalar", RuleFieldType::Array, false);
187pub const POST_SYNAPTIC_CURRENT_MULTIPLIER: MappingRuleField = field(
188    "postSynapticCurrent_multiplier",
189    RuleFieldType::Number,
190    false,
191);
192pub const SYNAPTIC_DELAY_BURSTS: MappingRuleField = MappingRuleField {
193    min: Some(1.0),
194    default: RuleDefault::Int(1),
195    ..field("synaptic_delay_bursts", RuleFieldType::Integer, false)
196};
197
198/// Every field of a dict-format mapping rule.
199pub const MAPPING_RULE_FIELDS: [MappingRuleField; 18] = [
200    MORPHOLOGY_ID,
201    MORPHOLOGY_SCALAR,
202    POST_SYNAPTIC_CURRENT_MULTIPLIER,
203    SYNAPTIC_DELAY_BURSTS,
204    PLASTICITY_FLAG,
205    PLASTICITY_MODE,
206    PLASTICITY_WINDOW,
207    PLASTICITY_CONSTANT,
208    LTP_MULTIPLIER,
209    LTD_MULTIPLIER,
210    ELIGIBILITY_DECAY_BURSTS,
211    PLASTICITY_ETA,
212    MAX_WEIGHT,
213    ONE_SIDED_FIRING,
214    MODULATORS,
215    CLASSIFIER_INSTANCE_REWARD,
216    REWARD_SOURCE_AREA,
217    PUNISHMENT_SOURCE_AREA,
218];
219
220/// True when `key` only configures plasticity (see [`MappingRuleField::plasticity_only`]).
221pub fn is_plasticity_only_key(key: &str) -> bool {
222    MAPPING_RULE_FIELDS
223        .iter()
224        .any(|f| f.plasticity_only && f.key == key)
225}
226
227/// The schema body: `{"fields": {<key>: {type, min, max, default, enum?, plasticity_only}}}`.
228pub fn mapping_rule_schema_json() -> Value {
229    let fields: Map<String, Value> = MAPPING_RULE_FIELDS
230        .iter()
231        .map(|f| (f.key.to_string(), f.to_schema_json()))
232        .collect();
233    json!({ "fields": fields })
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn every_plasticity_only_key_is_flagged_in_the_schema() {
242        let schema = mapping_rule_schema_json();
243        let fields = schema["fields"].as_object().unwrap();
244        // The keys that configure plasticity only (changing them never rebuilds synapses).
245        const EXPECTED: [&str; 14] = [
246            "plasticity_flag",
247            "plasticity_mode",
248            "plasticity_window",
249            "plasticity_constant",
250            "ltp_multiplier",
251            "ltd_multiplier",
252            "eligibility_decay_bursts",
253            "plasticity_eta",
254            "max_weight",
255            "one_sided_firing",
256            "modulators",
257            "classifier_instance_reward",
258            "reward_source_area",
259            "punishment_source_area",
260        ];
261        let flagged = MAPPING_RULE_FIELDS
262            .iter()
263            .filter(|f| f.plasticity_only)
264            .count();
265        assert_eq!(flagged, EXPECTED.len());
266        for key in EXPECTED {
267            assert!(is_plasticity_only_key(key));
268            assert_eq!(
269                fields[key]["plasticity_only"],
270                json!(true),
271                "{key} must be plasticity_only in the schema"
272            );
273        }
274        // Structural keys are not flagged.
275        assert_eq!(fields["morphology_id"]["plasticity_only"], json!(false));
276        assert_eq!(
277            fields["postSynapticCurrent_multiplier"]["plasticity_only"],
278            json!(false)
279        );
280    }
281
282    #[test]
283    fn schema_ranges_match_the_validator() {
284        // The validator rejects a non-positive eta and max_weight; the schema excludes them too.
285        let mut rule = serde_json::Map::new();
286        rule.insert("plasticity_mode".into(), json!("stdp"));
287        for (field, bad) in [(&PLASTICITY_ETA, 0.0), (&MAX_WEIGHT, -1.0)] {
288            let entry = field.to_schema_json();
289            assert_eq!(entry["min"], json!(0.0));
290            assert_eq!(entry["exclusive_min"], json!(true));
291            assert!(!field.accepts_number(bad));
292            let mut r = rule.clone();
293            r.insert(field.key.into(), json!(bad));
294            let err = crate::connectome_manager::ConnectomeManager::validate_plastic_rule_options(
295                &r, "src", "dst",
296            )
297            .unwrap_err();
298            assert!(err.contains(field.key), "{err}");
299            // An in-range value passes both.
300            assert!(field.accepts_number(0.5));
301            r.insert(field.key.into(), json!(0.5));
302            assert!(
303                crate::connectome_manager::ConnectomeManager::validate_plastic_rule_options(
304                    &r, "src", "dst"
305                )
306                .is_ok()
307            );
308        }
309        // i8 multipliers.
310        assert!(!LTP_MULTIPLIER.accepts_number(128.0));
311        assert!(LTP_MULTIPLIER.accepts_number(-128.0));
312    }
313
314    #[test]
315    fn enum_values_are_accepted_by_the_runtime_parsers() {
316        for v in ONE_SIDED_FIRING.allowed {
317            assert!(feagi_npu_burst_engine::npu::OneSidedFiring::parse(v).is_some());
318        }
319        assert!(feagi_npu_burst_engine::npu::OneSidedFiring::parse("bogus").is_none());
320    }
321}