Skip to main content

graphrefly_graph/
describe.rs

1//! `Graph::describe()` — JSON form of canonical spec §3.6 + Appendix B.
2//!
3//! D246: describe logic is a free fn [`describe_of`] over
4//! `(&dyn CoreFull, &Rc<RefCell<GraphInner>>)` so the one [`Graph`]
5//! (`crate::Graph`) reuses it, AND so the in-wave reactive-describe
6//! `MailboxOp::Defer` closure (D246 rule 6) can run it through the
7//! `&dyn CoreFull` it is handed (the one facade carries read-only
8//! inspection). `ReactiveDescribeHandle` holds ids only (Core-free,
9//! `Send`); there is **no RAII `Drop`** (D246 rule 3) — teardown is the
10//! owner-invoked [`ReactiveDescribeHandle::detach`].
11//!
12//! # Value rendering — raw vs. binding-rendered
13//!
14//! Canonical TS surfaces `value: T` directly. The Rust port preserves
15//! the handle-protocol cleaving plane (`value: DescribeValue`):
16//! `Handle(HandleId)` raw u64 (default) or `Rendered(serde_json::Value)`
17//! via [`DebugBindingBoundary`].
18
19use std::cell::RefCell;
20use std::rc::{Rc, Weak};
21
22use graphrefly_core::{
23    Core, CoreFull, HandleId, NodeId, NodeKind, OperatorOp, TerminalKind, TopologyEvent,
24    TopologySubscriptionId, NO_HANDLE,
25};
26use indexmap::IndexMap;
27use serde::{Serialize, Serializer};
28
29use crate::debug::DebugBindingBoundary;
30use crate::graph::{register_ns_sink, unregister_ns_sink, GraphInner};
31
32/// Top-level `describe()` output (canonical Appendix B JSON schema).
33///
34/// # `factory` + `factoryArgs` (R3.1.2, D285)
35///
36/// `factory` / `factory_args` are populated from
37/// [`crate::graph::GraphInner::factory`] / `factory_args` (set via
38/// [`crate::Graph::tag_factory`]). Both use `skip_serializing_if =
39/// "Option::is_none"` to match the pure-ts spread-conditional shape at
40/// `packages/pure-ts/src/graph/graph.ts:3508-3509` — a cold `describe()`
41/// before any `tag_factory` call OMITS the `factory` / `factoryArgs`
42/// keys entirely (not serializes them as `null`). The pure-ts arm
43/// pins this via the `"factoryArgs" in desc` assertion in
44/// `scenarios/graph/tag-factory.test.ts:70` (QA-A2 invariant); the
45/// Rust JSON shape converges via `skip_serializing_if` + `rename =
46/// "factoryArgs"` for the camelCase key parity.
47#[derive(Debug, Clone, Serialize)]
48pub struct GraphDescribeOutput {
49    /// Graph name as set at construction / mount.
50    pub name: String,
51    /// Local nodes by name.
52    pub nodes: IndexMap<String, NodeDescribe>,
53    /// Local edges (dep → consumer).
54    pub edges: Vec<EdgeDescribe>,
55    /// Mounted child names.
56    pub subgraphs: Vec<String>,
57    /// R3.1.2 factory provenance — name set via
58    /// [`crate::Graph::tag_factory`]. Omitted from JSON when `None`
59    /// (matches pure-ts spread-conditional shape).
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub factory: Option<String>,
62    /// R3.1.2 factory args — paired with [`Self::factory`]. Omitted
63    /// from JSON when `None`. Serialized as the `factoryArgs` camelCase
64    /// key to match pure-ts output byte-for-byte.
65    #[serde(
66        default,
67        skip_serializing_if = "Option::is_none",
68        rename = "factoryArgs"
69    )]
70    pub factory_args: Option<serde_json::Value>,
71}
72
73/// Per-node descriptor.
74///
75/// # JSON-shape disambiguation (D279, 2026-05-22, E-ii.3 — Rust ↔ TS parity)
76///
77/// Sentinel-vs-JSON-null disambiguation matches the TS `describeNode`
78/// shape (`packages/pure-ts/src/core/meta.ts`
79/// `DescribeNodeOutput { value?: unknown, sentinel?: boolean }`):
80///
81/// - Sentinel cache (`cache == NO_HANDLE` AND `status ==
82///   NodeStatus::Sentinel`) → `value` key omitted from JSON;
83///   `sentinel: true` present.
84/// - Legitimate JSON-null user value (`DescribeValue::Rendered(Value::Null)`
85///   under [`crate::Graph::describe_with_debug`]) → `"value": null`
86///   present; `sentinel` key omitted.
87/// - Any other value → `"value": <v>` present; `sentinel` key omitted.
88///
89/// Pre-D279 the Rust shape diverged: `value: None` (sentinel) and
90/// `value: Some(DescribeValue::Rendered(Value::Null))` (rendered null)
91/// both serialized to `"value": null` — JSON-indistinguishable.
92/// `#[serde(skip_serializing_if = "Option::is_none")]` on both `value`
93/// and `sentinel` enforces the converged TS-shape. Rust additionally
94/// always emits `status` (TS makes it optional via `includeFields`);
95/// the `sentinel` flag is redundant for Rust consumers that check
96/// `status == "sentinel"`, but its presence preserves cross-impl
97/// shape parity (cross-track-ledger §2 row 2026-05-22).
98#[derive(Debug, Clone, Serialize)]
99pub struct NodeDescribe {
100    /// `"state"` / `"derived"` / `"dynamic"` / `"producer"`.
101    #[serde(rename = "type")]
102    pub r#type: NodeTypeStr,
103    /// Lifecycle status (canonical Appendix B enum).
104    pub status: NodeStatus,
105    /// Current cache value. `None` when sentinel (`NO_HANDLE`);
106    /// omitted from serialized JSON via `skip_serializing_if` (D279).
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub value: Option<DescribeValue>,
109    /// D279 (2026-05-22): explicit sentinel discriminator matching
110    /// TS's `sentinel?: boolean` field. `Some(true)` when `status ==
111    /// NodeStatus::Sentinel`; `None` otherwise (omitted from JSON via
112    /// `skip_serializing_if`).
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub sentinel: Option<bool>,
115    /// Dep names in declaration order (`_anon_<NodeId>` for unnamed).
116    pub deps: Vec<String>,
117    /// Operator discriminant (e.g. `"map"`); `None` for non-operators.
118    #[serde(default, skip_serializing_if = "Option::is_none", rename = "operator")]
119    pub operator_kind: Option<String>,
120    /// Free-form metadata per canonical Appendix B. Always `None` in
121    /// this slice (metadata-storage primitive not yet shipped).
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub meta: Option<serde_json::Value>,
124}
125
126/// Per-node cache value in `describe` output. Serialized uniformly
127/// without an enum tag.
128#[derive(Debug, Clone, PartialEq)]
129pub enum DescribeValue {
130    /// Raw handle view (default for [`crate::Graph::describe`]).
131    Handle(HandleId),
132    /// Binding-rendered view (from [`crate::Graph::describe_with_debug`]).
133    Rendered(serde_json::Value),
134}
135
136impl Serialize for DescribeValue {
137    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
138        match self {
139            DescribeValue::Handle(h) => ser.serialize_u64(h.raw()),
140            DescribeValue::Rendered(v) => v.serialize(ser),
141        }
142    }
143}
144
145/// Edge between two named nodes (or a named node and `_anon_<NodeId>`).
146#[derive(Debug, Clone, Serialize)]
147pub struct EdgeDescribe {
148    pub from: String,
149    pub to: String,
150}
151
152/// Canonical Appendix B `type` enum.
153#[derive(Debug, Clone, Copy, Serialize)]
154#[serde(rename_all = "lowercase")]
155pub enum NodeTypeStr {
156    State,
157    Derived,
158    Dynamic,
159    Producer,
160    Effect,
161    Operator,
162}
163
164/// Canonical Appendix B `status` enum.
165#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
166#[serde(rename_all = "lowercase")]
167pub enum NodeStatus {
168    Sentinel,
169    Pending,
170    Dirty,
171    Settled,
172    Resolved,
173    Completed,
174    Errored,
175}
176
177/// β/D243: describe over the read-only-inspection `&dyn CoreFull` (so
178/// the in-wave `MailboxOp::Defer` reactive-describe closure can run it)
179/// + the namespace handle. Pure read; no `Core`-mutation.
180pub(crate) fn describe_of(
181    core: &dyn CoreFull,
182    inner_arc: &Rc<RefCell<GraphInner>>,
183    debug: Option<&dyn DebugBindingBoundary>,
184) -> GraphDescribeOutput {
185    let (graph_name, local_names, subgraphs, names_iter, factory, factory_args) = {
186        let inner = inner_arc.borrow_mut();
187        let graph_name = inner.name.clone();
188        let local_names: IndexMap<NodeId, String> = inner
189            .names
190            .iter()
191            .map(|(name, id)| (*id, name.clone()))
192            .collect();
193        let subgraphs: Vec<String> = inner.children.keys().cloned().collect();
194        let names_iter: Vec<(String, NodeId)> =
195            inner.names.iter().map(|(n, id)| (n.clone(), *id)).collect();
196        // R3.1.2 (D285): read fresh on every describe call so a
197        // subsequent topology event observes the latest tag without
198        // needing a `_topologyVersion`-equivalent cache invalidation
199        // field. Parity test `tag-factory.test.ts:96-140` covers this.
200        let factory = inner.factory.clone();
201        let factory_args = inner.factory_args.clone();
202        (
203            graph_name,
204            local_names,
205            subgraphs,
206            names_iter,
207            factory,
208            factory_args,
209        )
210    };
211
212    let mut nodes: IndexMap<String, NodeDescribe> = IndexMap::new();
213    let mut edges: Vec<EdgeDescribe> = Vec::new();
214
215    for (name, id) in &names_iter {
216        let kind = core.kind_of(*id).unwrap_or(NodeKind::State);
217        let cache = core.cache_of(*id);
218        let terminal = core.is_terminal(*id);
219        let dirty = core.is_dirty(*id);
220        let fired = core.has_fired_once(*id);
221
222        let dep_ids = core.deps_of(*id);
223        let dep_names: Vec<String> = dep_ids
224            .iter()
225            .map(|d| {
226                local_names
227                    .get(d)
228                    .cloned()
229                    .unwrap_or_else(|| format!("_anon_{}", d.raw()))
230            })
231            .collect();
232        for dep_name in &dep_names {
233            edges.push(EdgeDescribe {
234                from: dep_name.clone(),
235                to: name.clone(),
236            });
237        }
238
239        let value = if cache == NO_HANDLE {
240            None
241        } else if let Some(debug) = debug {
242            Some(DescribeValue::Rendered(debug.handle_to_debug(cache)))
243        } else {
244            Some(DescribeValue::Handle(cache))
245        };
246
247        let operator_kind = match kind {
248            NodeKind::Operator(op) => Some(operator_op_name(op)),
249            _ => None,
250        };
251        let status = status_of(kind, cache, terminal, dirty, fired);
252        // D279 (2026-05-22, E-ii.3): explicit sentinel discriminator to
253        // match TS's `sentinel?: boolean` shape. Only set when status is
254        // `Sentinel`; `None` otherwise (omitted from JSON).
255        let sentinel = if status == NodeStatus::Sentinel {
256            Some(true)
257        } else {
258            None
259        };
260        nodes.insert(
261            name.clone(),
262            NodeDescribe {
263                r#type: type_str_of(kind),
264                status,
265                value,
266                sentinel,
267                deps: dep_names,
268                operator_kind,
269                meta: None,
270            },
271        );
272    }
273
274    GraphDescribeOutput {
275        name: graph_name,
276        nodes,
277        edges,
278        subgraphs,
279        factory,
280        factory_args,
281    }
282}
283
284fn type_str_of(kind: NodeKind) -> NodeTypeStr {
285    match kind {
286        NodeKind::State => NodeTypeStr::State,
287        NodeKind::Producer => NodeTypeStr::Producer,
288        NodeKind::Derived => NodeTypeStr::Derived,
289        NodeKind::Dynamic => NodeTypeStr::Dynamic,
290        NodeKind::Operator(_) => NodeTypeStr::Operator,
291    }
292}
293
294fn operator_op_name(op: OperatorOp) -> String {
295    match op {
296        OperatorOp::Map { .. } => "map",
297        OperatorOp::Filter { .. } => "filter",
298        OperatorOp::Scan { .. } => "scan",
299        OperatorOp::Reduce { .. } => "reduce",
300        OperatorOp::DistinctUntilChanged { .. } => "distinctUntilChanged",
301        OperatorOp::Pairwise { .. } => "pairwise",
302        OperatorOp::Combine { .. } => "combine",
303        OperatorOp::WithLatestFrom { .. } => "withLatestFrom",
304        OperatorOp::Merge => "merge",
305        OperatorOp::Take { .. } => "take",
306        OperatorOp::Skip { .. } => "skip",
307        OperatorOp::TakeWhile { .. } => "takeWhile",
308        OperatorOp::Last { .. } => "last",
309        OperatorOp::Tap { .. } => "tap",
310        OperatorOp::TapFirst { .. } => "tapFirst",
311        OperatorOp::Valve => "valve",
312        OperatorOp::Settle { .. } => "settle",
313    }
314    .to_owned()
315}
316
317/// Canonical-spec §3.6.1 status mapping. Precedence: errored >
318/// completed > dirty > (cache-cleared) > settled > pending > sentinel.
319/// R1.3.7.b: `cache == NO_HANDLE` discriminates Sentinel-vs-Settled
320/// BEFORE the `fired` check (post-INVALIDATE fired compute → Sentinel).
321fn status_of(
322    kind: NodeKind,
323    cache: HandleId,
324    terminal: Option<TerminalKind>,
325    dirty: bool,
326    fired: bool,
327) -> NodeStatus {
328    match terminal {
329        Some(TerminalKind::Error(_)) => return NodeStatus::Errored,
330        Some(TerminalKind::Complete) => return NodeStatus::Completed,
331        None => {}
332    }
333    if dirty {
334        return NodeStatus::Dirty;
335    }
336    if cache == NO_HANDLE {
337        return match kind {
338            NodeKind::State => NodeStatus::Sentinel,
339            NodeKind::Producer | NodeKind::Derived | NodeKind::Dynamic | NodeKind::Operator(_) => {
340                if fired {
341                    NodeStatus::Sentinel
342                } else {
343                    NodeStatus::Pending
344                }
345            }
346        };
347    }
348    NodeStatus::Settled
349}
350
351// -------------------------------------------------------------------
352// Reactive describe (canonical §3.6.1 `reactive: true` mode)
353// -------------------------------------------------------------------
354
355/// Sink type for reactive describe. D272 (2026-05-21): single-owner-
356/// thread shape — `Rc<dyn Fn>` matches D248's `!Send + !Sync` Core. The
357/// `assert_not_impl_any!` below locks D248 intent at the type system.
358pub type DescribeSink = Rc<dyn Fn(&GraphDescribeOutput)>;
359
360static_assertions::assert_not_impl_any!(DescribeSink: Send, Sync);
361
362/// Id-bearing handle for a reactive describe subscription.
363///
364/// D246 rule 3: Core-free (`Send`), **no RAII `Drop`** — teardown is
365/// the owner-invoked synchronous [`Self::detach`]. This eliminates the
366/// "unsubscribe in `Drop`" deadlock class. The embedder's
367/// Teardown is the owner-invoked [`Self::detach`]`(core)` — REQUIRED.
368/// The ns-sink is also collected by `graph.destroy(core)`; the Core
369/// topology sub is opened via raw `core.subscribe_topology` and is NOT
370/// `OwnedCore`-tracked, so only `detach(core)` collects it.
371#[must_use = "ReactiveDescribeHandle holds a Core topology sub NOT tracked by OwnedCore; you MUST call detach(core) or it leaks"]
372pub struct ReactiveDescribeHandle {
373    inner: Rc<RefCell<GraphInner>>,
374    ns_sink_id: u64,
375    /// Slice V3 D5: Core topology sub for `DepsChanged` (edges change
376    /// without a namespace change). D246 r6: re-snapshot is in-wave
377    /// `MailboxOp::Defer`'d (the topology event fires inside a Core
378    /// wave; `describe_of` runs via the handed `&dyn CoreFull`).
379    topo_sub_id: TopologySubscriptionId,
380}
381
382impl ReactiveDescribeHandle {
383    /// Owner-invoked, synchronous detach (D246 rule 3). Topology sub
384    /// first (so a topo fire mid-detach can't re-snapshot through a
385    /// half-removed namespace sink), then the namespace sink.
386    pub fn detach(&self, core: &Core) {
387        core.unsubscribe_topology(self.topo_sub_id);
388        unregister_ns_sink(&self.inner, self.ns_sink_id);
389    }
390}
391
392/// Build a reactive-describe subscription. Push-on-subscribe fires
393/// the current snapshot once, then re-fires on every namespace change
394/// (owner-side `&Core`, D246 r2) and on `set_deps` `DepsChanged`
395/// (in-wave `MailboxOp::Defer` → `&dyn CoreFull`, D246 r6).
396pub(crate) fn describe_reactive_in(
397    core: &Core,
398    inner: &Rc<RefCell<GraphInner>>,
399    sink: &DescribeSink,
400) -> ReactiveDescribeHandle {
401    // Push-on-subscribe (no lock held).
402    sink(&describe_of(core, inner, None));
403
404    // Namespace-change path (owner-side `&Core`, β/D231).
405    let weak_inner: Weak<RefCell<GraphInner>> = Rc::downgrade(inner);
406    let sink_ns = sink.clone();
407    let ns_sink: crate::graph::NamespaceChangeSink = Rc::new(move |c: &Core| {
408        let Some(arc_inner) = weak_inner.upgrade() else {
409            return;
410        };
411        sink_ns(&describe_of(c, &arc_inner, None));
412    });
413    let ns_sink_id = register_ns_sink(inner, ns_sink);
414
415    // Topology path (set_deps → `DepsChanged`, fired inside a Core
416    // wave): re-snapshot via an in-wave `MailboxOp::Defer` so it runs
417    // owner-side with a real `&dyn CoreFull` (D243/D233).
418    let weak_inner_topo: Weak<RefCell<GraphInner>> = Rc::downgrade(inner);
419    // D249/S2c: owner-side `!Send` `DeferQueue` (the closure captures a
420    // `Weak<RefCell<GraphInner>>`, `!Send`). Owner-thread-only `Rc` —
421    // fine: this topo sink is `!Send` (D248) and fires owner-side.
422    let deferred = core.defer_queue();
423    let sink_topo = sink.clone();
424    // D246 rule 8 (S4): reusable coalescing slot. Re-snapshot is
425    // idempotent at drain time (`describe_of` reads current state), so
426    // N `DepsChanged` in one wave need only ONE deferred re-snapshot,
427    // not N boxed closures. `scheduled` (owner-thread-only `Cell`) gates
428    // a single `Box` post per drain; the closure clears it so the next
429    // wave re-arms. Behaviour-equivalent (deferred-snapshot acceptable,
430    // D243/D244) — one alloc + one snapshot per wave, not per emission.
431    let scheduled = Rc::new(std::cell::Cell::new(false));
432    let topo_sink: Rc<dyn Fn(&TopologyEvent)> = Rc::new(move |event: &TopologyEvent| {
433        if matches!(event, TopologyEvent::DepsChanged { .. }) {
434            if scheduled.get() {
435                return; // already armed for this drain — coalesce.
436            }
437            // INVARIANT (QA, 2026-05-19): the `upgrade()` check runs
438            // BEFORE `scheduled.set(true)`, so a graph-gone fire never
439            // poisons the slot (`scheduled` stays `false`; a later
440            // fire on the next wave re-tries the upgrade fresh).
441            let Some(arc_inner) = weak_inner_topo.upgrade() else {
442                return;
443            };
444            let s = sink_topo.clone();
445            let sched = Rc::clone(&scheduled);
446            sched.set(true);
447            // The Defer closure captures no `HandleId` (only an
448            // `Arc<sink>` + a `Weak`-upgraded inner) — if the Core
449            // is gone (`false`) the snapshot simply won't fire;
450            // nothing to release (D235 P8 pattern).
451            let _ = deferred.post(Box::new(move |cf: &dyn CoreFull| {
452                sched.set(false);
453                s(&describe_of(cf, &arc_inner, None));
454            }));
455        }
456    });
457    let topo_sub_id = core.subscribe_topology(topo_sink);
458
459    ReactiveDescribeHandle {
460        inner: inner.clone(),
461        ns_sink_id,
462        topo_sub_id,
463    }
464}