sim-lib-scene 0.2.0

Scene value model and codec:scene for SIM Web.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Scene value model: builders, accessors, and fail-closed validation.
//!
//! A Scene is a SIM value (an `Expr` tree) built from open maps tagged with a
//! `kind` symbol. This module never introduces a parallel data model; it only
//! provides ergonomic constructors over `Expr` and a validator that turns a
//! malformed scene into a structured [`SceneError`] (a path plus a message)
//! rather than a panic.

use std::sync::Arc;

use sim_kernel::{Cx, DefaultFactory, Expr, NoopEvalPolicy, ShapeMatch, Symbol};

use crate::kinds::{KIND_KEY, is_known_kind};

const HEATMAP_KIND: &str = "heatmap";

/// Palette names accepted by the domain-neutral `scene/heatmap` contract.
///
/// These names are data, not a Rust enum, so a browser renderer can implement
/// them without introducing a closed device or domain vocabulary.
pub const HEATMAP_PALETTES: &[&str] = &["viridis", "blue-red", "cyclic-phase"];

/// Scalar payload bytes represented by one heatmap cell (`f64` plus mask bit
/// stored as a Rust `bool`).
pub const HEATMAP_BYTES_PER_CELL: u64 =
    core::mem::size_of::<f64>() as u64 + core::mem::size_of::<bool>() as u64;

/// Calculate the checked scalar-and-metadata payload footprint recorded in a
/// `scene/heatmap` node.
///
/// The footprint intentionally describes the caller-prepared scalar payload,
/// not a codec-specific serialized size. Surface projections use it as the
/// stable byte budget across Scene codecs.
pub fn heatmap_payload_bytes(
    cells: u64,
    label: &str,
    detector: &str,
    advisory: Option<&str>,
) -> Option<u64> {
    let cell_bytes = cells.checked_mul(HEATMAP_BYTES_PER_CELL)?;
    [Some(label), Some(detector), advisory]
        .into_iter()
        .flatten()
        .try_fold(cell_bytes, |total, text| {
            total.checked_add(u64::try_from(text.len()).ok()?)
        })
}

/// One total budget for producing or rendering a Scene.
///
/// `nodes` and `depth` bound structural growth. `encoded_bytes` bounds the
/// whole scene value as encoded data. `face_bytes` bounds any single rendered
/// face such as a label, text run, title, or field value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SceneBudget {
    /// Maximum number of scene nodes.
    pub nodes: usize,
    /// Maximum nesting depth, with the root at depth 0.
    pub depth: usize,
    /// Maximum encoded bytes for the scene value.
    pub encoded_bytes: usize,
    /// Maximum bytes for one visible face.
    pub face_bytes: usize,
}

impl SceneBudget {
    /// Create a budget from explicit limits.
    pub const fn new(nodes: usize, depth: usize, encoded_bytes: usize, face_bytes: usize) -> Self {
        Self {
            nodes,
            depth,
            encoded_bytes,
            face_bytes,
        }
    }

    /// Default browser-safe budget for generic views.
    pub const fn interactive() -> Self {
        Self::new(512, 32, 256 * 1024, 8 * 1024)
    }

    /// Smaller budget used by tests and compact previews.
    pub const fn compact() -> Self {
        Self::new(64, 12, 32 * 1024, 1024)
    }
}

/// Mutable receipt for a [`SceneBudget`] as scene producers spend it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SceneBudgetState {
    budget: SceneBudget,
    nodes_used: usize,
    encoded_bytes_used: usize,
}

impl SceneBudgetState {
    /// Start spending `budget`.
    pub fn new(budget: SceneBudget) -> Self {
        Self {
            budget,
            nodes_used: 0,
            encoded_bytes_used: 0,
        }
    }

    /// The immutable limits this state enforces.
    pub fn budget(&self) -> &SceneBudget {
        &self.budget
    }

    /// Number of scene nodes admitted so far.
    pub fn nodes_used(&self) -> usize {
        self.nodes_used
    }

    /// Number of approximate encoded bytes admitted so far.
    pub fn encoded_bytes_used(&self) -> usize {
        self.encoded_bytes_used
    }

    /// Try to admit one node at `depth` with a visible face and encoded-size
    /// estimate. Returns a truncation reason when the budget is exhausted.
    pub fn admit(
        &mut self,
        depth: usize,
        face: Option<&str>,
        encoded_bytes: usize,
    ) -> Result<(), SceneBudgetExhausted> {
        if self.nodes_used >= self.budget.nodes {
            return Err(SceneBudgetExhausted::Nodes {
                limit: self.budget.nodes,
            });
        }
        if depth > self.budget.depth {
            return Err(SceneBudgetExhausted::Depth {
                limit: self.budget.depth,
            });
        }
        if let Some(face) = face
            && face.len() > self.budget.face_bytes
        {
            return Err(SceneBudgetExhausted::FaceBytes {
                limit: self.budget.face_bytes,
            });
        }
        if self.encoded_bytes_used.saturating_add(encoded_bytes) > self.budget.encoded_bytes {
            return Err(SceneBudgetExhausted::EncodedBytes {
                limit: self.budget.encoded_bytes,
            });
        }
        self.nodes_used += 1;
        self.encoded_bytes_used = self.encoded_bytes_used.saturating_add(encoded_bytes);
        Ok(())
    }
}

/// Reason a Scene budget refused another node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SceneBudgetExhausted {
    /// The node count was exhausted.
    Nodes {
        /// Configured node limit.
        limit: usize,
    },
    /// The depth limit was exhausted.
    Depth {
        /// Configured depth limit.
        limit: usize,
    },
    /// The total encoded-byte limit was exhausted.
    EncodedBytes {
        /// Configured encoded-byte limit.
        limit: usize,
    },
    /// A single visible face exceeded the per-face limit.
    FaceBytes {
        /// Configured per-face byte limit.
        limit: usize,
    },
}

impl SceneBudgetExhausted {
    /// Stable reason token for scene truncation metadata.
    pub fn reason(&self) -> &'static str {
        match self {
            Self::Nodes { .. } => "nodes",
            Self::Depth { .. } => "depth",
            Self::EncodedBytes { .. } => "encoded-bytes",
            Self::FaceBytes { .. } => "face-bytes",
        }
    }

    /// Configured limit that was exceeded.
    pub fn limit(&self) -> usize {
        match self {
            Self::Nodes { limit }
            | Self::Depth { limit }
            | Self::EncodedBytes { limit }
            | Self::FaceBytes { limit } => *limit,
        }
    }
}

/// A structured scene validation diagnostic: where the problem is and what it
/// is. `path` is a human-readable address into the scene tree (for example
/// `nodes[0].kind`); `message` describes the violation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SceneError {
    /// Address into the scene tree, outermost segment first.
    pub path: Vec<String>,
    /// Human-readable description of the violation.
    pub message: String,
}

impl SceneError {
    fn at(path: &[String], message: impl Into<String>) -> Self {
        Self {
            path: path.to_vec(),
            message: message.into(),
        }
    }

    /// Render the path as a dotted/indexed address, or `<root>` when empty.
    pub fn path_string(&self) -> String {
        if self.path.is_empty() {
            "<root>".to_owned()
        } else {
            self.path.join("")
        }
    }
}

impl core::fmt::Display for SceneError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}: {}", self.path_string(), self.message)
    }
}

/// Build a plain data map from string-keyed entries (keys become `core`-less
/// symbols). Use [`node`] to build a tagged scene node.
pub use sim_value::build::map;

/// Build a scene node: an `Expr::Map` whose first entry is `kind: scene/<name>`
/// followed by `entries`.
pub fn node(kind_name: &str, entries: Vec<(&str, Expr)>) -> Expr {
    let mut pairs = Vec::with_capacity(entries.len() + 1);
    pairs.push((
        Expr::Symbol(Symbol::new(KIND_KEY)),
        Expr::Symbol(Symbol::qualified(crate::kinds::SCENE_NAMESPACE, kind_name)),
    ));
    for (key, value) in entries {
        pairs.push((Expr::Symbol(Symbol::new(key)), value));
    }
    Expr::Map(pairs)
}

/// If `expr` is a map tagged with a symbol `kind`, return that kind symbol.
pub fn node_kind(expr: &Expr) -> Option<Symbol> {
    sim_value::access::field_sym(expr, KIND_KEY)
}

fn kind_entry(map: &Expr) -> Option<&Expr> {
    sim_value::access::field(map, KIND_KEY)
}

fn has_kind_key(map: &Expr) -> bool {
    kind_entry(map).is_some()
}

/// Validate that `expr` is a well-formed scene, failing closed with a
/// [`SceneError`] otherwise.
///
/// The root must be a scene node (a map tagged with a recognized `scene/<kind>`
/// symbol). Nested maps that carry a `kind` key are validated as scene nodes
/// too; maps without a `kind` key are treated as plain data and only recursed
/// into. This keeps the metadata open (arbitrary data may ride along) while
/// still rejecting a map that claims to be a scene node but is not one.
pub fn validate_scene(expr: &Expr) -> Result<(), SceneError> {
    let mut path = Vec::new();
    validate_node(expr, &mut path)
}

fn validate_node(expr: &Expr, path: &mut Vec<String>) -> Result<(), SceneError> {
    let shape_error = check_scene_shape(expr, path)?;
    let Expr::Map(entries) = expr else {
        return Err(SceneError::at(
            path,
            "expected a scene node map (an Expr::Map tagged with a kind)",
        ));
    };
    match kind_entry(expr) {
        None => {
            return Err(SceneError::at(path, "scene node is missing a 'kind' tag"));
        }
        Some(Expr::Symbol(kind)) => {
            if !is_known_kind(kind) {
                return Err(SceneError::at(
                    path,
                    format!(
                        "unrecognized scene kind '{kind}' -- if this is a plain data map, \
                         rename its 'kind' field (scene node maps reserve 'kind')"
                    ),
                ));
            }
        }
        Some(_) => {
            return Err(SceneError::at(path, "scene node 'kind' must be a symbol"));
        }
    }
    if let Some(message) = shape_error {
        return Err(SceneError::at(path, message));
    }
    if matches!(
        node_kind(expr),
        Some(kind)
            if kind.namespace.as_deref() == Some(crate::kinds::SCENE_NAMESPACE)
                && &*kind.name == HEATMAP_KIND
    ) {
        validate_heatmap(expr, path)?;
    }
    validate_children(entries, path)
}

fn validate_heatmap(expr: &Expr, path: &[String]) -> Result<(), SceneError> {
    let rows = heatmap_u64(expr, "rows", path)?;
    let cols = heatmap_u64(expr, "cols", path)?;
    if rows == 0 || cols == 0 {
        return Err(SceneError::at(
            path,
            "scene/heatmap rows and cols must be non-zero",
        ));
    }
    let cells = rows.checked_mul(cols).ok_or_else(|| {
        SceneError::at(path, "scene/heatmap rows * cols overflows the cell count")
    })?;
    let cell_count = usize::try_from(cells).map_err(|_| {
        SceneError::at(
            path,
            "scene/heatmap cell count cannot be represented on this host",
        )
    })?;

    let values = heatmap_list(expr, "values", path)?;
    let valid = heatmap_list(expr, "valid", path)?;
    if values.len() != cell_count {
        return Err(SceneError::at(
            path,
            format!(
                "scene/heatmap rows * cols is {cells}, but values has {} entries",
                values.len()
            ),
        ));
    }
    if valid.len() != cell_count {
        return Err(SceneError::at(
            path,
            format!(
                "scene/heatmap rows * cols is {cells}, but valid has {} entries",
                valid.len()
            ),
        ));
    }
    for (index, value) in values.iter().enumerate() {
        let Some(value) = sim_value::access::as_f64(value) else {
            return Err(SceneError::at(
                path,
                format!("scene/heatmap values[{index}] must be a number"),
            ));
        };
        if !value.is_finite() {
            return Err(SceneError::at(
                path,
                format!("scene/heatmap values[{index}] must be finite"),
            ));
        }
    }
    if let Some(index) = valid
        .iter()
        .position(|value| !matches!(value, Expr::Bool(_)))
    {
        return Err(SceneError::at(
            path,
            format!("scene/heatmap valid[{index}] must be a bool"),
        ));
    }

    let min = heatmap_f64(expr, "min", path)?;
    let max = heatmap_f64(expr, "max", path)?;
    if !min.is_finite() || !max.is_finite() || min > max {
        return Err(SceneError::at(
            path,
            "scene/heatmap range must be finite with min <= max",
        ));
    }

    let palette = sim_value::access::field_sym(expr, "palette")
        .filter(|palette| palette.namespace.is_none())
        .ok_or_else(|| {
            SceneError::at(path, "scene/heatmap palette must be an unqualified symbol")
        })?;
    if !HEATMAP_PALETTES.contains(&palette.name.as_ref()) {
        return Err(SceneError::at(
            path,
            format!("scene/heatmap palette '{}' is not recognized", palette.name),
        ));
    }

    let label = heatmap_nonempty_text(expr, "label", path)?;
    let detector = heatmap_nonempty_text(expr, "detector", path)?;
    let advisory = sim_value::access::field(expr, "advisory")
        .map(|_| heatmap_nonempty_text(expr, "advisory", path))
        .transpose()?;

    let footprint = sim_value::access::field(expr, "footprint")
        .ok_or_else(|| SceneError::at(path, "scene/heatmap footprint is required"))?;
    let footprint_cells = heatmap_u64(footprint, "cells", path)?;
    if footprint_cells != cells {
        return Err(SceneError::at(
            path,
            format!("scene/heatmap footprint cells is {footprint_cells}, expected {cells}"),
        ));
    }
    let payload_bytes = heatmap_payload_bytes(cells, label, detector, advisory)
        .ok_or_else(|| SceneError::at(path, "scene/heatmap byte footprint overflowed"))?;
    let footprint_bytes = heatmap_u64(footprint, "bytes", path)?;
    if footprint_bytes != payload_bytes {
        return Err(SceneError::at(
            path,
            format!("scene/heatmap footprint bytes is {footprint_bytes}, expected {payload_bytes}"),
        ));
    }
    Ok(())
}

fn heatmap_list<'a>(expr: &'a Expr, name: &str, path: &[String]) -> Result<&'a [Expr], SceneError> {
    match sim_value::access::field(expr, name) {
        Some(Expr::List(items)) => Ok(items),
        _ => Err(SceneError::at(
            path,
            format!("scene/heatmap {name} must be a list"),
        )),
    }
}

fn heatmap_u64(expr: &Expr, name: &str, path: &[String]) -> Result<u64, SceneError> {
    sim_value::access::field(expr, name)
        .and_then(|value| match value {
            Expr::Number(number)
                if matches!(number.domain.name.as_ref(), "i64" | "u64")
                    && number.domain.namespace.is_none() =>
            {
                number.canonical.parse::<u64>().ok()
            }
            _ => None,
        })
        .ok_or_else(|| {
            SceneError::at(
                path,
                format!("scene/heatmap {name} must be a non-negative integer number"),
            )
        })
}

fn heatmap_f64(expr: &Expr, name: &str, path: &[String]) -> Result<f64, SceneError> {
    sim_value::access::field(expr, name)
        .and_then(sim_value::access::as_f64)
        .ok_or_else(|| SceneError::at(path, format!("scene/heatmap {name} must be a number")))
}

fn heatmap_nonempty_text<'a>(
    expr: &'a Expr,
    name: &str,
    path: &[String],
) -> Result<&'a str, SceneError> {
    let text = sim_value::access::field_str(expr, name)
        .ok_or_else(|| SceneError::at(path, format!("scene/heatmap {name} must be a string")))?;
    if text.trim().is_empty() {
        return Err(SceneError::at(
            path,
            format!("scene/heatmap {name} must not be empty"),
        ));
    }
    Ok(text)
}

fn check_scene_shape(expr: &Expr, path: &[String]) -> Result<Option<String>, SceneError> {
    let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
    let matched = crate::shapes::scene_shape()
        .check_expr(&mut cx, expr)
        .map_err(|error| SceneError::at(path, format!("scene shape check failed: {error}")))?;
    Ok((!matched.accepted)
        .then(|| rejection_message(&matched, "value is not a recognized scene node")))
}

fn rejection_message(matched: &ShapeMatch, fallback: &str) -> String {
    matched
        .diagnostics
        .first()
        .map(|diagnostic| diagnostic.message.clone())
        .unwrap_or_else(|| fallback.to_owned())
}

fn validate_children(entries: &[(Expr, Expr)], path: &mut Vec<String>) -> Result<(), SceneError> {
    for (key, value) in entries {
        let label = match key {
            Expr::Symbol(symbol) => format!(".{}", symbol.as_qualified_str()),
            other => format!(".{other:?}"),
        };
        path.push(label);
        validate_data(value, path)?;
        path.pop();
    }
    Ok(())
}

fn validate_data(expr: &Expr, path: &mut Vec<String>) -> Result<(), SceneError> {
    match expr {
        Expr::Map(_) if has_kind_key(expr) => validate_node(expr, path),
        Expr::Map(entries) => validate_children(entries, path),
        Expr::List(items) | Expr::Vector(items) | Expr::Set(items) => {
            for (index, item) in items.iter().enumerate() {
                path.push(format!("[{index}]"));
                validate_data(item, path)?;
                path.pop();
            }
            Ok(())
        }
        _ => Ok(()),
    }
}