Skip to main content

nmbrs_runtime/wrappers/
gutter.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Gutter wrapper — publishes the phase's contextual left-gutter
5//! cell from workload-declared polydat templates.
6//!
7//! Distinct from the `memo` wrapper: memo owns the `[[ ... ]]`
8//! header line above the phase status; the gutter owns the compact
9//! cell to the LEFT of the phase's detail row, where the display
10//! otherwise auto-derives a completion bar (metered phases) or a
11//! latency trend (daemons). This wrapper lets the workload take
12//! that cell over with its own computed value.
13//!
14//! Declaration forms:
15//!
16//! - `gutter: "<layout template>"` — printf-style polydat layout
17//!   string; the rendered text fills the cell verbatim.
18//! - `gutter: { bar: "<template>" }` — template renders to an
19//!   `f64` fraction in `0..=1`; displayed as the house braille
20//!   completion bar.
21//! - `gutter: { spark: "<template>" }` — template renders to an
22//!   `f64` sample; each publication appends to a per-phase trend
23//!   ring displayed as a sparkline with the current value.
24//! - `gutter: { …, final: <string | {bar|spark|text}> }` — the
25//!   COMPLETION form: evaluated once at phase end and rendered as
26//!   the left-gutter cell of the phase's ✓ outcome DETAIL line
27//!   (the header line's timing triad is never touched). Final
28//!   templates may also reference status-metric names (`{recall}`,
29//!   `{latency_p50}`, …) — resolved from the phase's aggregates
30//!   when no wire matches. Phases with a during-form but no
31//!   `final:` still get ONE final update: the during template
32//!   re-evaluated at phase end.
33//!
34//! Inside a `poll:` drain, the during form is additionally
35//! re-published per poll iteration by the poll wrapper (against
36//! that iteration's captures, like the poll memo) — this wrapper
37//! alone fires only when the drain op completes.
38
39use std::sync::Arc;
40
41use crate::adapter::WrappingDispenser;
42use crate::adapter::{ExecutionError, OpDispenser, OpResult};
43use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
44
45pub const NAME: WrapperName = WrapperName::new("gutter");
46
47/// One published gutter-cell value. The display consumes this via
48/// the phase render handle; `None` in the activity's slot means
49/// "derive automatically".
50#[derive(Debug, Clone, PartialEq)]
51pub enum GutterSpec {
52    /// Pre-rendered layout text, placed in the cell verbatim
53    /// (truncated to the cell width by the display).
54    Text(String),
55    /// Completion fraction `0..=1` → house braille bar.
56    Bar(f64),
57    /// One trend sample → sparkline ring + current-value label.
58    Spark(f64),
59    /// A key metric: label and value rendered on opposite sides of the cell.
60    /// Declared as `gutter: { final: { name: "recall", value: "{recall}" } }`.
61    /// The pair is explicit rather than split out of one string because the two
62    /// orders both occur in practice (`recall 96%` vs `≈900/s units`), so no
63    /// splitting rule can infer which token is the value.
64    Labeled { name: String, value: String },
65}
66
67/// Trigger: `gutter:` is a string (layout template) or a map with
68/// a `bar:` or `spark:` key.
69fn triggers(s: WrapperSubject) -> bool {
70    let Some(template) = s.op() else {
71        return false;
72    };
73    template
74        .params
75        .get("gutter")
76        .map(|v| v.is_string() || v.is_object())
77        .unwrap_or(false)
78}
79
80fn describe_assignment(s: WrapperSubject) -> Option<String> {
81    let template = s.op()?;
82    let v = template.params.get("gutter")?;
83    if let Some(s) = v.as_str() {
84        if s.is_empty() {
85            return None;
86        }
87        Some(format!("gutter: \"{s}\" (layout)"))
88    } else if let Some(obj) = v.as_object() {
89        let mut parts: Vec<String> = Vec::new();
90        for key in ["bar", "spark", "text"] {
91            if let Some(t) = obj.get(key).and_then(|x| x.as_str()) {
92                parts.push(format!("{key} \"{t}\""));
93            }
94        }
95        match obj.get("final") {
96            Some(f) if f.is_string() => {
97                parts.push(format!("final \"{}\"", f.as_str().unwrap_or("")))
98            }
99            Some(f) if f.is_object() => parts.push("final {…}".to_string()),
100            _ => {}
101        }
102        if parts.is_empty() {
103            None
104        } else {
105            Some(format!("gutter: {}", parts.join(" / ")))
106        }
107    } else {
108        None
109    }
110}
111
112inventory::submit! {
113    WrapperRegistration {
114        name: NAME,
115        // `gutter:` is the sole discriminant — layout string or
116        // `{bar}` / `{spark}` map. Like memo, publication is
117        // independent of every other wrapper's behaviour: it sees
118        // the same wires and writes to its own atomic slot.
119        owned_fields: &["gutter"],
120        triggers,
121        requires_inner: &[super::traverse::NAME],
122        forbids_outer: &[],
123        mutually_exclusive_with: &[],
124        describe_assignment,
125        levels: &[crate::wrapper_registry::WrapperLevel::Op],
126    }
127}
128
129/// The parsed declaration — which cell shape the template feeds.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum GutterKind {
132    Text,
133    Bar,
134    Spark,
135    /// Key metric: label and value, carried through the template pipeline as a
136    /// single string joined by US (unit separator) so interpolation of both
137    /// halves happens in one pass, then split at render time.
138    Labeled,
139}
140
141/// A declared gutter cell: the shape it renders as and the template
142/// that feeds it. A `Labeled` template carries its label and value
143/// joined by US (`\u{1f}`).
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct GutterTemplate {
146    pub kind: GutterKind,
147    pub template: String,
148}
149
150impl GutterTemplate {
151    pub fn new(kind: GutterKind, template: impl Into<String>) -> Self {
152        Self {
153            kind,
154            template: template.into(),
155        }
156    }
157}
158
159/// An op's parsed `gutter:` param: the form rendered while the op runs
160/// and the `final:` form rendered once at phase end.
161#[derive(Debug, Clone, Default, PartialEq, Eq)]
162pub struct GutterTemplates {
163    pub during: Option<GutterTemplate>,
164    pub finish: Option<GutterTemplate>,
165}
166
167/// Parse an op's `gutter:` param value into its during and final
168/// template forms. Shared by the wrapper-cascade arm (which builds
169/// the [`GutterDispenser`] and stores the templates on the activity) and
170/// the poll wrapper (which re-publishes the during form per poll
171/// iteration so a single long drain op keeps a live cell).
172pub fn parse_templates(v: Option<&serde_json::Value>) -> GutterTemplates {
173    let parse_forms = |obj: &serde_json::Map<String, serde_json::Value>| -> Option<GutterTemplate> {
174        if let Some(m) = obj.get("labeled").and_then(|x| x.as_object()) {
175            let name = m.get("name").and_then(|x| x.as_str()).unwrap_or("");
176            let value = m.get("value").and_then(|x| x.as_str()).unwrap_or("");
177            return Some(GutterTemplate::new(
178                GutterKind::Labeled,
179                format!("{name}{}{value}", '\u{1f}'),
180            ));
181        }
182        if let Some(t) = obj.get("bar").and_then(|x| x.as_str()) {
183            Some(GutterTemplate::new(GutterKind::Bar, t))
184        } else if let Some(t) = obj.get("spark").and_then(|x| x.as_str()) {
185            Some(GutterTemplate::new(GutterKind::Spark, t))
186        } else {
187            obj.get("text")
188                .and_then(|x| x.as_str())
189                .map(|t| GutterTemplate::new(GutterKind::Text, t))
190        }
191    };
192    match v {
193        Some(serde_json::Value::String(s)) if !s.is_empty() => GutterTemplates {
194            during: Some(GutterTemplate::new(GutterKind::Text, s.as_str())),
195            finish: None,
196        },
197        Some(serde_json::Value::Object(obj)) => GutterTemplates {
198            during: parse_forms(obj),
199            finish: match obj.get("final") {
200                Some(serde_json::Value::String(s)) if !s.is_empty() => {
201                    Some(GutterTemplate::new(GutterKind::Text, s.as_str()))
202                }
203                Some(serde_json::Value::Object(fobj)) => parse_forms(fobj),
204                _ => None,
205            },
206        },
207        _ => GutterTemplates::default(),
208    }
209}
210
211/// Render one gutter template against the wires into its publishable
212/// spec. `None` on substitution failure or (for the numeric kinds) a
213/// non-numeric render — callers leave the last good value in place.
214pub(crate) fn render_spec(
215    declared: &GutterTemplate,
216    wires: &dyn crate::wires::WireSource,
217) -> Option<GutterSpec> {
218    let (kind, template) = (declared.kind, declared.template.as_str());
219    let rendered = match crate::wires::substitute_via_wires(template, wires) {
220        Ok(s) => s,
221        Err(e) => {
222            crate::diag!(
223                crate::observer::LogLevel::Debug,
224                "gutter: substitution failed for '{template}': {e}"
225            );
226            return None;
227        }
228    };
229    match kind {
230        GutterKind::Labeled => {
231            let (name, value) = rendered
232                .split_once('\u{1f}')
233                .unwrap_or(("", rendered.as_str()));
234            Some(GutterSpec::Labeled {
235                name: name.to_string(),
236                value: value.to_string(),
237            })
238        }
239        GutterKind::Text => Some(GutterSpec::Text(rendered)),
240        GutterKind::Bar | GutterKind::Spark => match rendered.trim().parse::<f64>() {
241            Ok(v) if kind == GutterKind::Bar => Some(GutterSpec::Bar(v.clamp(0.0, 1.0))),
242            Ok(v) => Some(GutterSpec::Spark(v)),
243            Err(_) => {
244                crate::diag!(
245                    crate::observer::LogLevel::Debug,
246                    "gutter: '{template}' rendered to non-numeric '{rendered}'"
247                );
248                None
249            }
250        },
251    }
252}
253
254/// Op-wrapper publishing the phase's gutter-cell spec after each
255/// successful inner op (post-op, so captures from THIS execution
256/// are on the wires — the cell reflects measured state).
257///
258/// No-op on inner errors; substitution or parse failures degrade
259/// to a debug log — the gutter must never fail an otherwise-good
260/// op. Numeric kinds (`bar` / `spark`) additionally require the
261/// rendered string to parse as `f64`.
262pub struct GutterDispenser {
263    inner: Arc<dyn OpDispenser>,
264    template: GutterTemplate,
265    /// Shared slot owned by the activity (see `Activity::gutter`).
266    /// Writes here are visible to the display fold without a
267    /// separate channel.
268    gutter_state: Arc<arc_swap::ArcSwapOption<GutterSpec>>,
269}
270
271impl GutterDispenser {
272    pub fn wrap(
273        inner: Arc<dyn OpDispenser>,
274        template: GutterTemplate,
275        gutter_state: Arc<arc_swap::ArcSwapOption<GutterSpec>>,
276    ) -> Arc<dyn OpDispenser> {
277        Arc::new(Self {
278            inner,
279            template,
280            gutter_state,
281        })
282    }
283
284    fn publish(&self, wires: &dyn crate::wires::WireSource) {
285        if let Some(spec) = render_spec(&self.template, wires) {
286            self.gutter_state.store(Some(Arc::new(spec)));
287        }
288    }
289}
290
291impl WrappingDispenser for GutterDispenser {}
292
293impl OpDispenser for GutterDispenser {
294    fn execute<'a>(
295        &'a self,
296        cycle: u64,
297        ctx: &'a crate::fixture::ExecCtx<'a>,
298    ) -> std::pin::Pin<
299        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
300    > {
301        Box::pin(async move {
302            let result = self.inner.execute(cycle, ctx).await?;
303            self.publish(ctx.wires);
304            Ok(result)
305        })
306    }
307
308    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
309        Some(self.inner.as_ref())
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use crate::adapter::{AdapterError, ExecutionError, OpResult};
317    use crate::fixture::{ExecCtx, ResolvedPulls};
318
319    struct FakeInner {
320        error: Option<&'static str>,
321    }
322
323    impl OpDispenser for FakeInner {
324        fn execute<'a>(
325            &'a self,
326            _cycle: u64,
327            _ctx: &'a ExecCtx<'a>,
328        ) -> std::pin::Pin<
329            Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
330        > {
331            Box::pin(async move {
332                if let Some(msg) = self.error {
333                    return Err(ExecutionError::Op(AdapterError {
334                        error_name: "test".into(),
335                        message: msg.into(),
336                        retryable: false,
337                    }));
338                }
339                Ok(OpResult {
340                    body: None,
341                    skipped: false,
342                })
343            })
344        }
345    }
346
347    fn empty_ctx() -> (crate::adapter::ResolvedFields, ResolvedPulls) {
348        let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
349        let pulls = ResolvedPulls::empty();
350        (fields, pulls)
351    }
352
353    #[tokio::test]
354    async fn text_form_publishes_rendered_layout() {
355        let state = Arc::new(arc_swap::ArcSwapOption::empty());
356        let inner = Arc::new(FakeInner { error: None });
357        let d = GutterDispenser::wrap(
358            inner,
359            GutterTemplate::new(GutterKind::Text, "queue depth ok"),
360            state.clone(),
361        );
362        let (fields, pulls) = empty_ctx();
363        let ctx = ExecCtx::new(&fields, &pulls);
364        let _ = d.execute(0, &ctx).await.expect("inner ok");
365        assert_eq!(
366            state.load().as_deref(),
367            Some(&GutterSpec::Text("queue depth ok".into()))
368        );
369    }
370
371    #[tokio::test]
372    async fn bar_form_parses_and_clamps_fraction() {
373        let state = Arc::new(arc_swap::ArcSwapOption::empty());
374        let inner = Arc::new(FakeInner { error: None });
375        let d = GutterDispenser::wrap(
376            inner,
377            GutterTemplate::new(GutterKind::Bar, "1.7"),
378            state.clone(),
379        );
380        let (fields, pulls) = empty_ctx();
381        let ctx = ExecCtx::new(&fields, &pulls);
382        let _ = d.execute(0, &ctx).await.expect("inner ok");
383        assert_eq!(
384            state.load().as_deref(),
385            Some(&GutterSpec::Bar(1.0)),
386            "fraction must clamp to 0..=1"
387        );
388    }
389
390    #[tokio::test]
391    async fn numeric_parse_failure_leaves_slot_untouched() {
392        let state: Arc<arc_swap::ArcSwapOption<GutterSpec>> =
393            Arc::new(arc_swap::ArcSwapOption::empty());
394        state.store(Some(Arc::new(GutterSpec::Spark(3.0))));
395        let inner = Arc::new(FakeInner { error: None });
396        let d = GutterDispenser::wrap(
397            inner,
398            GutterTemplate::new(GutterKind::Spark, "not-a-number"),
399            state.clone(),
400        );
401        let (fields, pulls) = empty_ctx();
402        let ctx = ExecCtx::new(&fields, &pulls);
403        let _ = d.execute(0, &ctx).await.expect("inner ok");
404        assert_eq!(
405            state.load().as_deref(),
406            Some(&GutterSpec::Spark(3.0)),
407            "unparseable render must not clobber the last good value"
408        );
409    }
410
411    #[tokio::test]
412    async fn does_not_publish_on_inner_error() {
413        let state: Arc<arc_swap::ArcSwapOption<GutterSpec>> =
414            Arc::new(arc_swap::ArcSwapOption::empty());
415        let inner = Arc::new(FakeInner {
416            error: Some("boom"),
417        });
418        let d = GutterDispenser::wrap(
419            inner,
420            GutterTemplate::new(GutterKind::Text, "never"),
421            state.clone(),
422        );
423        let (fields, pulls) = empty_ctx();
424        let ctx = ExecCtx::new(&fields, &pulls);
425        assert!(d.execute(0, &ctx).await.is_err());
426        assert!(
427            state.load().is_none(),
428            "gutter must not publish on inner error"
429        );
430    }
431}