nopaldb 0.4.35

High-performance graph database with ACID transactions, MVCC time-travel, and Arrow analytics
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
// src/query/sack.rs
//
// Acumulador por traverser ("sack") para traversals fluidos.
//
// Cada traverser carga un valor que se pliega con la arista en cada paso,
// preservando multiplicidad por camino: el mismo nodo alcanzado por dos
// ramas distintas aparece dos veces, con acumuladores distintos.

//! Acumulador por traverser para traversals.
//!
//! Permite acarrear un valor a lo largo del recorrido, transformándolo en
//! cada arista — por ejemplo, la explosión de materiales de un BOM donde la
//! cantidad se multiplica al bajar por cada componente:
//!
//! ```no_run
//! # async fn demo() -> nopaldb::Result<()> {
//! # use nopaldb::{Graph, Node};
//! # let graph = Graph::in_memory().await?;
//! # let raiz = graph.add_node(Node::new("Material")).await?;
//! let r = graph.traverse(raiz)
//!     .sack(10.0)
//!     .repeat(|b| b.out_e("ContieneComponente").sack_mul_by("cantidad"))
//!     .emit()
//!     .await?;
//! for item in &r.items {
//!     println!("{} necesita {}", item.node, item.sack);
//! }
//! assert!(r.is_complete());
//! # Ok(()) }
//! ```
//!
//! A diferencia de [`Graph::bfs`](crate::Graph::bfs)/[`Graph::dfs`](crate::Graph::dfs),
//! aquí no hay deduplicación por nodo: la multiplicidad por camino es parte
//! del resultado. Los ciclos se detectan sobre la línea de ancestros de cada
//! traverser (un diamante no es un ciclo) y el truncamiento por
//! `max_depth`/`max_nodes` se reporta en [`SackResult::truncated`] en vez de
//! cortar en silencio.
//!
//! Cada [`SackItem`] enlaza a su padre por índice ([`SackItem::parent`]), así
//! que el árbol anidado se reconstruye en un solo paso — el `NodeId` del
//! padre no bastaría, porque bajo multiplicidad el mismo nodo puede aparecer
//! varias veces:
//!
//! ```no_run
//! # fn demo(r: nopaldb::SackResult<f64>) {
//! let mut children: Vec<Vec<usize>> = vec![Vec::new(); r.items.len()];
//! let mut roots = Vec::new();
//! for (i, item) in r.items.iter().enumerate() {
//!     match item.parent {
//!         Some(p) => children[p].push(i),
//!         None => roots.push(i), // hijos directos del nodo de inicio
//!     }
//! }
//! # }
//! ```

use std::fmt;
use std::sync::Arc;

use crate::error::{NopalError, Result};
use crate::graph::{Direction, Graph};
use crate::query::filter::NodePredicate;
use crate::query::step::TraversalStep;
use crate::types::{Edge, EdgeId, Node, NodeId};

/// Pliegue del acumulador: recibe la arista recién seguida y el valor actual.
pub type SackFold<T> = Arc<dyn Fn(&Edge, &T) -> Result<T> + Send + Sync>;

/// Predicado sobre la última arista seguida.
pub type EdgePredicate = Arc<dyn Fn(&Edge) -> bool + Send + Sync>;

/// Qué hacer al detectar un ciclo (un traverser que vuelve a un nodo de su
/// propia línea de ancestros) dentro de `repeat`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CycleMode {
    /// Abortar con un error que nombra el camino del ciclo (default).
    Error,
    /// Descartar el traverser y contarlo en [`SackResult::cycles_skipped`].
    Skip,
}

/// Por qué se detuvo el recorrido antes de agotar el frontier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Truncation {
    /// Se descartaron traversers que excedían `max_depth`.
    MaxDepth,
    /// Se alcanzó el tope de traversers creados (`max_nodes`).
    MaxNodes,
}

/// Un nodo emitido junto con su acumulador y profundidad.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SackItem<T> {
    pub node: NodeId,
    pub sack: T,
    pub depth: usize,
    /// Índice en [`SackResult::items`] del ítem padre (el ancestro emitido
    /// más cercano). `None` = hijo directo de un nodo de inicio. Bajo
    /// multiplicidad por camino el `NodeId` del padre sería ambiguo; el
    /// índice identifica al traverser exacto y permite reconstruir el árbol
    /// en un solo paso (ver el ejemplo del módulo).
    pub parent: Option<usize>,
    /// Arista por la que se llegó a este nodo. Desambigua aristas paralelas
    /// y da acceso a sus propiedades vía [`Graph::get_edge`](crate::Graph::get_edge).
    pub via_edge: Option<EdgeId>,
}

/// Resultado de un traversal con acumulador.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SackResult<T> {
    /// Pares (nodo, acumulador) en orden de visita.
    pub items: Vec<SackItem<T>>,
    /// `None` = el recorrido terminó; `Some` = se detuvo por un tope.
    pub truncated: Option<Truncation>,
    /// Traversers descartados por ciclo bajo [`CycleMode::Skip`].
    pub cycles_skipped: usize,
}

impl<T> SackResult<T> {
    /// `true` si el recorrido terminó sin toparse con `max_depth`/`max_nodes`.
    pub fn is_complete(&self) -> bool {
        self.truncated.is_none()
    }
}

/// Un paso del pipeline sack. Guarda closures directamente.
enum SackStep<T> {
    FollowEdge {
        edge_type: Option<String>,
        direction: Direction,
    },
    Fold(SackFold<T>),
    FilterNode(NodePredicate),
    FilterEdge(EdgePredicate),
    Limit(usize),
    Skip(usize),
}

impl<T> fmt::Debug for SackStep<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SackStep::FollowEdge { edge_type, direction } => f
                .debug_struct("FollowEdge")
                .field("edge_type", edge_type)
                .field("direction", direction)
                .finish(),
            SackStep::Fold(_) => write!(f, "Fold(<closure>)"),
            SackStep::FilterNode(_) => write!(f, "FilterNode(<closure>)"),
            SackStep::FilterEdge(_) => write!(f, "FilterEdge(<closure>)"),
            SackStep::Limit(n) => write!(f, "Limit({n})"),
            SackStep::Skip(n) => write!(f, "Skip({n})"),
        }
    }
}

/// Eslabón inmutable de la cadena de ancestros de un traverser.
struct PathLink {
    node: NodeId,
    parent: Option<Arc<PathLink>>,
}

/// Un traverser: posición actual + acumulador + contexto del camino.
struct Traverser<T> {
    node: NodeId,
    sack: T,
    depth: usize,
    last_edge: Option<Arc<Edge>>,
    path: Arc<PathLink>,
    /// Índice en `items` del ancestro emitido más cercano (incluido este
    /// mismo traverser una vez emitido); lo heredan sus hijos.
    last_emitted_ancestor: Option<usize>,
}

impl<T: Clone> Clone for Traverser<T> {
    fn clone(&self) -> Self {
        Self {
            node: self.node,
            sack: self.sack.clone(),
            depth: self.depth,
            last_edge: self.last_edge.clone(),
            path: self.path.clone(),
            last_emitted_ancestor: self.last_emitted_ancestor,
        }
    }
}

impl<T> Traverser<T> {
    fn ancestry_contains(&self, node: NodeId) -> bool {
        let mut cur = Some(&self.path);
        while let Some(link) = cur {
            if link.node == node {
                return true;
            }
            cur = link.parent.as_ref();
        }
        false
    }
}

/// Grabador de pasos para el bloque de `repeat`.
pub struct SackBlock<T> {
    steps: Vec<SackStep<T>>,
    has_follow: bool,
    error: Option<String>,
}

/// Builder de un traversal con acumulador. Se obtiene con
/// [`TraverseBuilder::sack`](crate::TraverseBuilder::sack).
pub struct SackBuilder<T> {
    graph: Arc<Graph>,
    start: Vec<NodeId>,
    init: T,
    prefix: Vec<SackStep<T>>,
    repeat_block: Option<Vec<SackStep<T>>>,
    has_follow: bool,
    max_depth: usize,
    max_nodes: usize,
    on_cycle: CycleMode,
    config_error: Option<String>,
}

macro_rules! sack_step_methods {
    () => {
        /// Sigue aristas salientes de cualquier tipo.
        pub fn out(self) -> Self {
            self.push_step(SackStep::FollowEdge {
                edge_type: None,
                direction: Direction::Outgoing,
            })
        }

        /// Sigue aristas salientes de un tipo específico.
        pub fn out_e(self, edge_type: impl Into<String>) -> Self {
            self.push_step(SackStep::FollowEdge {
                edge_type: Some(edge_type.into()),
                direction: Direction::Outgoing,
            })
        }

        /// Sigue aristas entrantes de cualquier tipo.
        pub fn in_(self) -> Self {
            self.push_step(SackStep::FollowEdge {
                edge_type: None,
                direction: Direction::Incoming,
            })
        }

        /// Sigue aristas entrantes de un tipo específico.
        pub fn in_e(self, edge_type: impl Into<String>) -> Self {
            self.push_step(SackStep::FollowEdge {
                edge_type: Some(edge_type.into()),
                direction: Direction::Incoming,
            })
        }

        /// Sigue aristas en ambas direcciones.
        pub fn both(self) -> Self {
            self.push_step(SackStep::FollowEdge {
                edge_type: None,
                direction: Direction::Both,
            })
        }

        /// Filtra traversers por predicado sobre el nodo actual.
        pub fn filter<F>(self, predicate: F) -> Self
        where
            F: Fn(&Node) -> bool + Send + Sync + 'static,
        {
            self.push_step(SackStep::FilterNode(Arc::new(predicate)))
        }

        /// Filtra traversers por predicado sobre la última arista seguida.
        pub fn filter_edge<F>(self, predicate: F) -> Self
        where
            F: Fn(&Edge) -> bool + Send + Sync + 'static,
        {
            self.push_edge_dependent(SackStep::FilterEdge(Arc::new(predicate)), "filter_edge")
        }

        /// Pliega la última arista seguida dentro del acumulador.
        pub fn sack_by<F>(self, f: F) -> Self
        where
            F: Fn(&Edge, &T) -> T + Send + Sync + 'static,
        {
            self.push_edge_dependent(SackStep::Fold(Arc::new(move |e, s| Ok(f(e, s)))), "sack_by")
        }

        /// Como [`Self::sack_by`], pero el pliegue puede fallar.
        pub fn try_sack_by<F>(self, f: F) -> Self
        where
            F: Fn(&Edge, &T) -> Result<T> + Send + Sync + 'static,
        {
            self.push_edge_dependent(SackStep::Fold(Arc::new(f)), "try_sack_by")
        }

        fn push_edge_dependent(mut self, step: SackStep<T>, name: &str) -> Self {
            if !self.has_follow {
                self.note_error(format!(
                    "{name} requiere un paso de arista previo (out/out_e/in_/in_e/both)"
                ));
                return self;
            }
            self.push_step(step)
        }
    };
}

/// Pliegue numérico sobre una propiedad de arista. Propiedad faltante o no
/// numérica es un error duro: tratarla como identidad produciría un número
/// silenciosamente equivocado.
fn numeric_fold(prop: String, op: &'static str, apply: fn(f64, f64) -> f64) -> SackFold<f64> {
    Arc::new(move |edge, acc| {
        let v = edge
            .properties
            .get(&prop)
            .and_then(|v| v.as_number())
            .ok_or_else(|| {
                NopalError::query_error(format!(
                    "{op}: la arista {} ({}) no tiene propiedad numérica '{}'",
                    edge.id, edge.edge_type, prop
                ))
            })?;
        Ok(apply(*acc, v))
    })
}

macro_rules! sack_numeric_methods {
    () => {
        /// Multiplica el acumulador por la propiedad numérica de la arista.
        /// Propiedad faltante o no numérica → error en `emit()`.
        pub fn sack_mul_by(self, prop: impl Into<String>) -> Self {
            let fold = numeric_fold(prop.into(), "sack_mul_by", |acc, v| acc * v);
            self.push_edge_dependent(SackStep::Fold(fold), "sack_mul_by")
        }

        /// Suma la propiedad numérica de la arista al acumulador.
        /// Propiedad faltante o no numérica → error en `emit()`.
        pub fn sack_sum_by(self, prop: impl Into<String>) -> Self {
            let fold = numeric_fold(prop.into(), "sack_sum_by", |acc, v| acc + v);
            self.push_edge_dependent(SackStep::Fold(fold), "sack_sum_by")
        }
    };
}

impl<T: Clone + Send + Sync + 'static> SackBlock<T> {
    fn new(has_follow: bool) -> Self {
        Self {
            steps: Vec::new(),
            has_follow,
            error: None,
        }
    }

    fn push_step(mut self, step: SackStep<T>) -> Self {
        if matches!(step, SackStep::FollowEdge { .. }) {
            self.has_follow = true;
        }
        self.steps.push(step);
        self
    }

    fn note_error(&mut self, msg: String) {
        self.error.get_or_insert(msg);
    }

    sack_step_methods!();
}

impl SackBlock<f64> {
    sack_numeric_methods!();
}

impl<T: Clone + Send + Sync + 'static> SackBuilder<T> {
    /// Construye desde las partes de un `TraverseBuilder`: los pasos ya
    /// grabados se convierten al pipeline sack y corren como prefijo.
    pub(crate) fn from_traverse(
        graph: Arc<Graph>,
        start: Vec<NodeId>,
        init: T,
        steps: Vec<TraversalStep>,
        predicates: Vec<NodePredicate>,
    ) -> Self {
        let mut prefix = Vec::with_capacity(steps.len());
        let mut has_follow = false;
        let mut pred_idx = 0;

        for step in steps {
            match step {
                TraversalStep::FollowEdge { edge_type, direction } => {
                    has_follow = true;
                    prefix.push(SackStep::FollowEdge { edge_type, direction });
                }
                TraversalStep::Filter { .. } => {
                    if pred_idx < predicates.len() {
                        prefix.push(SackStep::FilterNode(predicates[pred_idx].clone()));
                        pred_idx += 1;
                    }
                }
                TraversalStep::Limit { count } => prefix.push(SackStep::Limit(count)),
                TraversalStep::Skip { count } => prefix.push(SackStep::Skip(count)),
            }
        }

        Self {
            graph,
            start,
            init,
            prefix,
            repeat_block: None,
            has_follow,
            max_depth: 32,
            max_nodes: 10_000,
            on_cycle: CycleMode::Error,
            config_error: None,
        }
    }

    fn push_step(mut self, step: SackStep<T>) -> Self {
        if self.repeat_block.is_some() {
            self.note_error("no se admiten pasos después de repeat()".to_string());
            return self;
        }
        if matches!(step, SackStep::FollowEdge { .. }) {
            self.has_follow = true;
        }
        self.prefix.push(step);
        self
    }

    fn note_error(&mut self, msg: String) {
        self.config_error.get_or_insert(msg);
    }

    sack_step_methods!();

    /// Repite el bloque de pasos hasta que el frontier quede vacío. El
    /// recorrido siempre está acotado por [`Self::max_depth`] y
    /// [`Self::max_nodes`]; los ciclos se manejan según [`Self::on_cycle`].
    pub fn repeat(mut self, f: impl FnOnce(SackBlock<T>) -> SackBlock<T>) -> Self {
        if self.repeat_block.is_some() {
            self.note_error("repeat() solo puede llamarse una vez".to_string());
            return self;
        }
        let block = f(SackBlock::new(false));
        if let Some(err) = block.error {
            self.note_error(err);
        }
        self.repeat_block = Some(block.steps);
        self
    }

    /// Profundidad máxima (default 32). La guarda es obligatoria: no puede
    /// desactivarse, solo ajustarse.
    pub fn max_depth(mut self, depth: usize) -> Self {
        self.max_depth = depth;
        self
    }

    /// Tope de traversers creados (default 10 000, paridad con
    /// [`TraversalConfig`](crate::TraversalConfig)).
    pub fn max_nodes(mut self, max: usize) -> Self {
        self.max_nodes = max;
        self
    }

    /// Manejo de ciclos dentro de `repeat` (default [`CycleMode::Error`]).
    pub fn on_cycle(mut self, mode: CycleMode) -> Self {
        self.on_cycle = mode;
        self
    }

    /// Ejecuta y emite cada nodo alcanzado al cierre de cada bloque: el
    /// frontier tras el prefijo y el de cada iteración de `repeat`. Los
    /// nodos de inicio no se emiten (nada se ha plegado aún).
    ///
    /// [`SackItem::parent`] enlaza cada ítem con el ancestro emitido más
    /// cercano. Con bloques de un salto (el caso típico) eso es el padre
    /// directo (`items[parent].depth == depth - 1`); con bloques multi-salto,
    /// es el nodo del cierre de bloque anterior — los saltos intermedios no
    /// se emiten.
    pub async fn emit(self) -> Result<SackResult<T>> {
        self.run(false).await
    }

    /// Ejecuta y emite solo las hojas: traversers que no producen sucesores
    /// en una iteración de `repeat` (o el frontier final si no hay `repeat`).
    ///
    /// Es un reporte plano, no un árbol: como ningún intermedio se emite,
    /// [`SackItem::parent`] es siempre `None` aquí. Para reconstruir el
    /// árbol usar [`Self::emit`].
    pub async fn emit_leaves(self) -> Result<SackResult<T>> {
        self.run(true).await
    }

    async fn run(self, leaves_only: bool) -> Result<SackResult<T>> {
        if let Some(msg) = self.config_error {
            return Err(NopalError::query_error(msg));
        }

        let mut ctx = RunCtx {
            max_depth: self.max_depth,
            max_nodes: self.max_nodes,
            on_cycle: self.on_cycle,
            created: 0,
            cycles_skipped: 0,
            truncated: None,
            stop: false,
        };
        let mut items: Vec<SackItem<T>> = Vec::new();

        let mut frontier: Vec<Traverser<T>> = self
            .start
            .iter()
            .map(|&node| Traverser {
                node,
                sack: self.init.clone(),
                depth: 0,
                last_edge: None,
                path: Arc::new(PathLink { node, parent: None }),
                last_emitted_ancestor: None,
            })
            .collect();

        // Prefijo: los ciclos no se vigilan aquí (una secuencia fija de
        // pasos siempre termina, y p.ej. both().both() revisita el origen
        // legítimamente).
        frontier = apply_block(&self.graph, &self.prefix, frontier, &mut ctx, false).await?;

        if !leaves_only {
            emit_frontier(&mut frontier, &mut items);
        }

        match self.repeat_block {
            None => {
                if leaves_only {
                    for t in &frontier {
                        items.push(SackItem {
                            node: t.node,
                            sack: t.sack.clone(),
                            depth: t.depth,
                            parent: t.last_emitted_ancestor,
                            via_edge: t.last_edge.as_ref().map(|e| e.id),
                        });
                    }
                }
            }
            Some(block) => {
                while !frontier.is_empty() && !ctx.stop {
                    let mut next = Vec::new();
                    for t in frontier {
                        if ctx.stop {
                            break;
                        }
                        let children =
                            apply_block(&self.graph, &block, vec![t.clone()], &mut ctx, true)
                                .await?;
                        if leaves_only && children.is_empty() {
                            items.push(SackItem {
                                node: t.node,
                                sack: t.sack,
                                depth: t.depth,
                                parent: t.last_emitted_ancestor,
                                via_edge: t.last_edge.as_ref().map(|e| e.id),
                            });
                        }
                        next.extend(children);
                    }
                    if !leaves_only {
                        emit_frontier(&mut next, &mut items);
                    }
                    frontier = next;
                }
            }
        }

        Ok(SackResult {
            items,
            truncated: ctx.truncated,
            cycles_skipped: ctx.cycles_skipped,
        })
    }
}

impl SackBuilder<f64> {
    sack_numeric_methods!();
}

struct RunCtx {
    max_depth: usize,
    max_nodes: usize,
    on_cycle: CycleMode,
    created: usize,
    cycles_skipped: usize,
    truncated: Option<Truncation>,
    stop: bool,
}

fn emit_frontier<T: Clone>(frontier: &mut [Traverser<T>], items: &mut Vec<SackItem<T>>) {
    for t in frontier.iter_mut() {
        if t.depth > 0 {
            let idx = items.len();
            items.push(SackItem {
                node: t.node,
                sack: t.sack.clone(),
                depth: t.depth,
                // El valor heredado ANTES de estamparse a sí mismo: el padre.
                parent: t.last_emitted_ancestor,
                via_edge: t.last_edge.as_ref().map(|e| e.id),
            });
            t.last_emitted_ancestor = Some(idx);
        }
    }
}

async fn apply_block<T: Clone + Send + Sync + 'static>(
    graph: &Graph,
    steps: &[SackStep<T>],
    mut frontier: Vec<Traverser<T>>,
    ctx: &mut RunCtx,
    check_cycles: bool,
) -> Result<Vec<Traverser<T>>> {
    for step in steps {
        match step {
            SackStep::FollowEdge { edge_type, direction } => {
                let mut next = Vec::new();
                for t in &frontier {
                    if ctx.stop {
                        break;
                    }
                    let edges = graph.edges_of(t.node, *direction).await?;
                    for edge in edges {
                        if let Some(et) = edge_type
                            && edge.edge_type != *et
                        {
                            continue;
                        }

                        let target = match direction {
                            Direction::Outgoing => edge.target,
                            Direction::Incoming => edge.source,
                            Direction::Both => {
                                if edge.source == t.node {
                                    edge.target
                                } else {
                                    edge.source
                                }
                            }
                        };

                        let child_depth = t.depth + 1;
                        if child_depth > ctx.max_depth {
                            ctx.truncated.get_or_insert(Truncation::MaxDepth);
                            continue;
                        }

                        if check_cycles && t.ancestry_contains(target) {
                            match ctx.on_cycle {
                                CycleMode::Error => {
                                    return Err(cycle_error(graph, t, target).await);
                                }
                                CycleMode::Skip => {
                                    ctx.cycles_skipped += 1;
                                    continue;
                                }
                            }
                        }

                        if ctx.created >= ctx.max_nodes {
                            ctx.truncated = Some(Truncation::MaxNodes);
                            ctx.stop = true;
                            break;
                        }
                        ctx.created += 1;

                        next.push(Traverser {
                            node: target,
                            sack: t.sack.clone(),
                            depth: child_depth,
                            last_edge: Some(Arc::new(edge)),
                            path: Arc::new(PathLink {
                                node: target,
                                parent: Some(t.path.clone()),
                            }),
                            last_emitted_ancestor: t.last_emitted_ancestor,
                        });
                    }
                }
                frontier = next;
            }

            SackStep::Fold(fold) => {
                for t in &mut frontier {
                    let edge = t.last_edge.as_ref().ok_or_else(|| {
                        NopalError::query_error(
                            "el pliegue del sack requiere un paso de arista previo",
                        )
                    })?;
                    t.sack = fold(edge, &t.sack)?;
                }
            }

            SackStep::FilterNode(predicate) => {
                let mut kept = Vec::with_capacity(frontier.len());
                for t in frontier {
                    let node = graph.get_node(t.node).await?;
                    if predicate(&node) {
                        kept.push(t);
                    }
                }
                frontier = kept;
            }

            SackStep::FilterEdge(predicate) => {
                let mut kept = Vec::with_capacity(frontier.len());
                for t in frontier {
                    let edge = t.last_edge.as_ref().ok_or_else(|| {
                        NopalError::query_error(
                            "filter_edge requiere un paso de arista previo",
                        )
                    })?;
                    if predicate(edge) {
                        kept.push(t);
                    }
                }
                frontier = kept;
            }

            SackStep::Limit(count) => frontier.truncate(*count),

            SackStep::Skip(count) => {
                if *count < frontier.len() {
                    frontier.drain(..*count);
                } else {
                    frontier.clear();
                }
            }
        }

        if frontier.is_empty() {
            break;
        }
    }

    Ok(frontier)
}

/// Construye el error de ciclo nombrando el camino (`A → B → A`).
async fn cycle_error<T>(graph: &Graph, traverser: &Traverser<T>, repeated: NodeId) -> NopalError {
    let mut chain = Vec::new();
    let mut cur = Some(&traverser.path);
    while let Some(link) = cur {
        chain.push(link.node);
        if link.node == repeated {
            break;
        }
        cur = link.parent.as_ref();
    }
    chain.reverse();
    chain.push(repeated);

    let mut names = Vec::with_capacity(chain.len());
    for id in chain {
        let name = match graph.get_node(id).await {
            Ok(node) => node
                .properties
                .get("name")
                .and_then(|v| v.as_str().map(String::from))
                .unwrap_or(node.label),
            Err(_) => id.to_string(),
        };
        names.push(name);
    }

    NopalError::query_error(format!("cycle detected: {}", names.join("")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::PropertyValue;

    async fn graph_with_edge(cantidad: PropertyValue) -> (Graph, NodeId, NodeId) {
        let graph = Graph::in_memory().await.unwrap();
        let a = graph
            .add_node(Node::new("Material").with_property("name", PropertyValue::String("A".into())))
            .await
            .unwrap();
        let b = graph
            .add_node(Node::new("Material").with_property("name", PropertyValue::String("B".into())))
            .await
            .unwrap();
        graph
            .add_edge(Edge::new(a, b, "ContieneComponente").with_property("cantidad", cantidad))
            .await
            .unwrap();
        (graph, a, b)
    }

    #[tokio::test]
    async fn test_one_hop_multiply() {
        let (graph, a, b) = graph_with_edge(PropertyValue::Float(18.0)).await;

        let r = graph
            .traverse(a)
            .sack(10.0)
            .out_e("ContieneComponente")
            .sack_mul_by("cantidad")
            .emit()
            .await
            .unwrap();

        assert_eq!(r.items.len(), 1);
        assert_eq!(r.items[0].node, b);
        assert_eq!(r.items[0].sack, 180.0);
        assert_eq!(r.items[0].depth, 1);
        // Hijo directo del nodo de inicio, llegado por la arista seguida
        assert_eq!(r.items[0].parent, None);
        let edge_id = r.items[0].via_edge.expect("via_edge debe estar presente");
        let edge = graph.get_edge(edge_id).await.unwrap();
        assert_eq!(edge.edge_type, "ContieneComponente");
        assert!(r.is_complete());
        assert_eq!(r.cycles_skipped, 0);
    }

    #[tokio::test]
    async fn test_int_property_coercion() {
        let (graph, a, _) = graph_with_edge(PropertyValue::Int(18)).await;

        let r = graph
            .traverse(a)
            .sack(1.0)
            .out_e("ContieneComponente")
            .sack_mul_by("cantidad")
            .emit()
            .await
            .unwrap();

        assert_eq!(r.items[0].sack, 18.0);
    }

    #[tokio::test]
    async fn test_missing_property_is_hard_error() {
        let (graph, a, _) = graph_with_edge(PropertyValue::Float(18.0)).await;

        let err = graph
            .traverse(a)
            .sack(1.0)
            .out_e("ContieneComponente")
            .sack_mul_by("merma")
            .emit()
            .await
            .unwrap_err();

        let msg = err.to_string();
        assert!(msg.contains("sack_mul_by"), "mensaje: {msg}");
        assert!(msg.contains("'merma'"), "mensaje: {msg}");
        assert!(msg.contains("ContieneComponente"), "mensaje: {msg}");
    }

    #[tokio::test]
    async fn test_fold_without_edge_step_is_config_error() {
        let (graph, a, _) = graph_with_edge(PropertyValue::Float(18.0)).await;

        let err = graph
            .traverse(a)
            .sack(1.0)
            .sack_mul_by("cantidad")
            .emit()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("sack_mul_by"));
    }

    #[tokio::test]
    async fn test_prefix_steps_convert_before_sack() {
        // Los pasos grabados antes de .sack() corren como prefijo, y el
        // pliegue posterior ve la arista que ellos siguieron.
        let (graph, a, b) = graph_with_edge(PropertyValue::Float(18.0)).await;

        let r = graph
            .traverse(a)
            .out_e("ContieneComponente")
            .sack(10.0)
            .sack_mul_by("cantidad")
            .emit()
            .await
            .unwrap();

        assert_eq!(r.items.len(), 1);
        assert_eq!(r.items[0].node, b);
        assert_eq!(r.items[0].sack, 180.0);
    }
}