vectorless 0.1.24

Hierarchical, reasoning-native document intelligence engine
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0

//! Retrieval pipeline orchestrator.
//!
//! Manages stage execution with support for:
//! - Dependency-based ordering
//! - Parallel execution of independent stages
//! - Backtracking for incremental retrieval
//! - Failure policies
//! - Pilot integration for navigation guidance

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tracing::{debug, error, info, warn};

use crate::document::DocumentTree;
use crate::document::ReasoningIndex;
use crate::error::Result;
use crate::retrieval::pilot::{Pilot, SearchState};
// FailurePolicy is re-exported for stages
use crate::retrieval::stream::{
    DEFAULT_STREAM_BOUND, RetrieveEvent, RetrieveEventReceiver, RetrieveEventSender,
};
use crate::retrieval::types::{RetrieveOptions, RetrieveResponse};

use super::context::{CandidateNode, PipelineContext};
use super::outcome::StageOutcome;
use super::stage::RetrievalStage;

/// Stage entry with metadata.
struct StageEntry {
    stage: Box<dyn RetrievalStage>,
    priority: i32,
    depends_on: Vec<String>,
}

impl std::fmt::Debug for StageEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StageEntry")
            .field("name", &self.stage.name())
            .field("priority", &self.priority)
            .field("depends_on", &self.depends_on)
            .finish()
    }
}

/// Group of stages at the same dependency level (can run in parallel).
#[derive(Debug, Clone)]
pub struct ExecutionGroup {
    /// Indices of stages in this group.
    pub stage_indices: Vec<usize>,
    /// Whether this group has multiple stages (parallelizable).
    pub parallel: bool,
}

/// Retrieval pipeline orchestrator.
///
/// Coordinates stage execution with:
/// - Dependency resolution via topological sort
/// - Parallel execution of independent stages
/// - Backtracking support for incremental retrieval
/// - Configurable failure policies
/// - Pilot integration for intelligent navigation
///
/// # Example
///
/// ```rust,ignore
/// let orchestrator = RetrievalOrchestrator::new()
///     .stage(AnalyzeStage::new())
///     .stage(PlanStage::new())
///     .stage(SearchStage::new())
///     .stage(EvaluateStage::new())
///     .with_pilot(pilot)
///     .with_max_backtracks(3);
///
/// let response = orchestrator.execute(tree, query, options).await?;
/// ```
pub struct RetrievalOrchestrator {
    stages: Vec<StageEntry>,
    pilot: Option<Arc<dyn Pilot>>,
    max_backtracks: usize,
    max_total_iterations: usize,
}

impl Default for RetrievalOrchestrator {
    fn default() -> Self {
        Self::new()
    }
}

impl RetrievalOrchestrator {
    /// Create a new empty orchestrator.
    pub fn new() -> Self {
        Self {
            stages: Vec::new(),
            pilot: None,
            max_backtracks: 5,
            max_total_iterations: 10,
        }
    }

    /// Add a stage to the pipeline.
    ///
    /// Dependencies are read from the stage's `depends_on()` method.
    pub fn stage<S>(mut self, stage: S) -> Self
    where
        S: RetrievalStage + 'static,
    {
        let deps = stage.depends_on();
        let priority = stage.priority();
        self.stages.push(StageEntry {
            stage: Box::new(stage),
            priority,
            depends_on: deps.into_iter().map(|s| s.to_string()).collect(),
        });
        self
    }

    /// Add Pilot for navigation guidance during backtracking.
    ///
    /// When set, the Pilot will be consulted during backtracking
    /// to provide intelligent guidance on alternative search paths.
    pub fn with_pilot(mut self, pilot: Arc<dyn Pilot>) -> Self {
        self.pilot = Some(pilot);
        self
    }

    /// Set maximum number of backtracks allowed.
    pub fn with_max_backtracks(mut self, n: usize) -> Self {
        self.max_backtracks = n;
        self
    }

    /// Set maximum total iterations.
    pub fn with_max_iterations(mut self, n: usize) -> Self {
        self.max_total_iterations = n;
        self
    }

    /// Resolve dependencies and return stage indices in execution order.
    fn resolve_order(&self) -> Result<Vec<usize>> {
        // Build name -> index map
        let name_to_idx: HashMap<&str, usize> = self
            .stages
            .iter()
            .enumerate()
            .map(|(i, entry)| (entry.stage.name(), i))
            .collect();

        // Validate dependencies
        for entry in &self.stages {
            for dep in &entry.depends_on {
                if !name_to_idx.contains_key(dep.as_str()) {
                    return Err(crate::Error::Config(format!(
                        "Stage '{}' depends on non-existent stage '{}'",
                        entry.stage.name(),
                        dep
                    )));
                }
            }
        }

        // Topological sort (Kahn's algorithm)
        let n = self.stages.len();
        let mut in_degree: Vec<usize> = vec![0; n];
        let mut adjacency: HashMap<usize, Vec<usize>> = HashMap::new();

        for (i, entry) in self.stages.iter().enumerate() {
            for dep in &entry.depends_on {
                if let Some(&dep_idx) = name_to_idx.get(dep.as_str()) {
                    adjacency.entry(dep_idx).or_default().push(i);
                    in_degree[i] += 1;
                }
            }
        }

        // Collect stages with no dependencies, sorted by priority
        let mut ready: Vec<usize> = (0..n)
            .filter(|&i| in_degree[i] == 0) // 0 means no dependencies
            .collect();
        ready.sort_by_key(|&i| (self.stages[i].priority, i));

        let mut result: Vec<usize> = Vec::new();

        while let Some(idx) = ready.first().cloned() {
            ready.remove(0);
            result.push(idx);

            if let Some(neighbors) = adjacency.get(&idx) {
                for &neighbor in neighbors {
                    in_degree[neighbor] -= 1;
                    if in_degree[neighbor] == 0 {
                        let entry = &self.stages[neighbor];
                        let pos = ready
                            .binary_search_by_key(&(entry.priority, neighbor), |&i| {
                                (self.stages[i].priority, i)
                            })
                            .unwrap_or_else(|e| e);
                        ready.insert(pos, neighbor);
                    }
                }
            }
        }

        // Check for cycles
        if result.len() != n {
            let remaining: Vec<&str> = (0..n)
                .filter(|i| !result.contains(i))
                .map(|i| self.stages[i].stage.name())
                .collect();
            return Err(crate::Error::Config(format!(
                "Circular dependency detected involving stages: {:?}",
                remaining
            )));
        }

        Ok(result)
    }

    /// Compute execution groups from resolved order.
    fn compute_execution_groups(&self, order: &[usize]) -> Vec<ExecutionGroup> {
        if order.is_empty() {
            return Vec::new();
        }

        // Build name -> index map
        let name_to_idx: HashMap<&str, usize> = self
            .stages
            .iter()
            .enumerate()
            .map(|(i, entry)| (entry.stage.name(), i))
            .collect();

        // Calculate level for each stage based on dependencies
        let mut levels: HashMap<usize, usize> = HashMap::new();

        for &idx in order {
            let entry = &self.stages[idx];
            let level = if entry.depends_on.is_empty() {
                0
            } else {
                entry
                    .depends_on
                    .iter()
                    .filter_map(|dep| {
                        name_to_idx
                            .get(dep.as_str())
                            .and_then(|&dep_idx| levels.get(&dep_idx))
                    })
                    .max()
                    .map(|&l| l + 1)
                    .unwrap_or(0)
            };
            levels.insert(idx, level);
        }

        // Group stages by level
        let mut level_groups: HashMap<usize, Vec<usize>> = HashMap::new();
        for &idx in order {
            let level = levels[&idx];
            level_groups.entry(level).or_default().push(idx);
        }

        // Convert to execution groups
        let max_level = *levels.values().max().unwrap_or(&0);
        (0..=max_level)
            .filter_map(|level| {
                level_groups.get(&level).map(|indices| ExecutionGroup {
                    stage_indices: indices.clone(),
                    parallel: indices.len() > 1,
                })
            })
            .collect()
    }

    /// Find the index of a stage by name.
    fn find_stage_index(&self, name: &str) -> usize {
        self.stages
            .iter()
            .enumerate()
            .find(|(_, entry)| entry.stage.name() == name)
            .map(|(i, _)| i)
            .unwrap_or(0)
    }

    /// Find which group contains a stage index.
    fn find_group_for_stage(&self, groups: &[ExecutionGroup], stage_idx: usize) -> Option<usize> {
        groups
            .iter()
            .enumerate()
            .find(|(_, g)| g.stage_indices.contains(&stage_idx))
            .map(|(i, _)| i)
    }

    /// Execute the retrieval pipeline.
    pub async fn execute(
        &mut self,
        tree: Arc<DocumentTree>,
        query: &str,
        options: RetrieveOptions,
    ) -> Result<RetrieveResponse> {
        let total_start = Instant::now();
        info!(
            "Starting retrieval pipeline for query: '{}' ({} stages)",
            query,
            self.stages.len()
        );

        // Resolve execution order
        let order = self.resolve_order()?;
        let stage_names: Vec<&str> = order.iter().map(|&i| self.stages[i].stage.name()).collect();
        info!("Execution order: {:?}", stage_names);

        // Compute execution groups
        let groups = self.compute_execution_groups(&order);
        info!(
            "Execution groups: {} ({} parallelizable)",
            groups.len(),
            groups.iter().filter(|g| g.parallel).count()
        );

        // Create context with Pilot
        let document_graph = options.document_graph.clone();
        let mut ctx = PipelineContext::with_pilot(tree, query, options, self.pilot.clone());
        if let Some(graph) = document_graph {
            ctx = ctx.with_document_graph(graph);
        }

        // Track execution state
        let mut backtrack_count = 0;
        let mut total_iterations = 0;
        let mut group_idx = 0;

        // Execute pipeline with backtracking support
        while group_idx < groups.len() {
            if backtrack_count >= self.max_backtracks {
                warn!("Max backtracks reached, completing with current results");
                break;
            }

            if total_iterations >= self.max_total_iterations {
                warn!("Max total iterations reached, completing");
                break;
            }

            let group = &groups[group_idx];

            // Execute stages in this group
            for &stage_idx in &group.stage_indices {
                let entry = &self.stages[stage_idx];
                let stage_name = entry.stage.name();
                let policy = entry.stage.failure_policy();

                ctx.start_stage();
                info!("Executing stage: {}", stage_name);

                match entry.stage.execute(&mut ctx).await {
                    Ok(outcome) => {
                        ctx.end_stage(stage_name, true, None);
                        total_iterations += 1;

                        match outcome {
                            StageOutcome::Continue => {
                                // Continue to next stage
                            }
                            StageOutcome::Complete => {
                                // Retrieval complete
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                info!("Retrieval completed by stage: {}", stage_name);
                                return Ok(ctx.finalize());
                            }
                            StageOutcome::NeedMoreData {
                                additional_beam,
                                go_deeper,
                            } => {
                                // Backtrack to search stage
                                if let Some(search_idx) =
                                    self.stages.iter().position(|e| e.stage.name() == "search")
                                {
                                    info!(
                                        "Need more data, backtracking to search (beam +{}, deeper: {})",
                                        additional_beam, go_deeper
                                    );

                                    // Consult Pilot for backtrack guidance
                                    if let Some(ref pilot) = self.pilot {
                                        if pilot.config().guide_at_backtrack {
                                            // Build search state for Pilot
                                            let visited: std::collections::HashSet<_> = ctx
                                                .search_paths
                                                .iter()
                                                .flat_map(|p| p.nodes.iter().copied())
                                                .collect();
                                            let candidates: Vec<_> =
                                                ctx.candidates.iter().map(|c| c.node_id).collect();

                                            let state = SearchState::new(
                                                &ctx.tree,
                                                &ctx.query,
                                                &[],
                                                &candidates,
                                                &visited,
                                            );

                                            match pilot.guide_backtrack(&state).await {
                                                Some(guidance) => {
                                                    debug!(
                                                        "Pilot backtrack guidance: confidence={}, candidates={}",
                                                        guidance.confidence,
                                                        guidance.ranked_candidates.len()
                                                    );
                                                    // Update candidates with Pilot's suggestions
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                                None => {
                                                    debug!("Pilot provided no backtrack guidance");
                                                }
                                            }
                                        }
                                    }

                                    // Update search config
                                    if let Some(ref mut config) = ctx.search_config {
                                        config.beam_width += additional_beam;
                                        if go_deeper {
                                            config.max_depth += 1;
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    // Find group containing search stage
                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, search_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Backtrack {
                                target_stage,
                                reason,
                            } => {
                                info!("Backtracking to {}: {}", target_stage, reason);

                                if let Some(target_idx) = self
                                    .stages
                                    .iter()
                                    .position(|e| e.stage.name() == target_stage)
                                {
                                    // Consult Pilot for backtrack guidance if going to search
                                    if target_stage == "search" {
                                        if let Some(ref pilot) = self.pilot {
                                            if pilot.config().guide_at_backtrack {
                                                let visited: std::collections::HashSet<_> = ctx
                                                    .search_paths
                                                    .iter()
                                                    .flat_map(|p| p.nodes.iter().copied())
                                                    .collect();
                                                let candidates: Vec<_> = ctx
                                                    .candidates
                                                    .iter()
                                                    .map(|c| c.node_id)
                                                    .collect();

                                                let state = SearchState::new(
                                                    &ctx.tree,
                                                    &ctx.query,
                                                    &[],
                                                    &candidates,
                                                    &visited,
                                                );

                                                if let Some(guidance) =
                                                    pilot.guide_backtrack(&state).await
                                                {
                                                    debug!(
                                                        "Pilot backtrack guidance for explicit backtrack: confidence={}",
                                                        guidance.confidence
                                                    );
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, target_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Skip { reason } => {
                                info!("Skipping remaining stages: {}", reason);
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                return Ok(ctx.finalize());
                            }
                        }
                    }
                    Err(e) => {
                        ctx.end_stage(stage_name, false, Some(e.to_string()));

                        if policy.allows_continuation() {
                            warn!(
                                "Stage {} failed but policy allows continuation: {}",
                                stage_name, e
                            );
                        } else {
                            error!("Stage {} failed: {}", stage_name, e);
                            return Err(e);
                        }
                    }
                }
            }

            group_idx += 1;
        }

        ctx.metrics.total_time_ms = total_start.elapsed().as_millis() as u64;
        info!(
            "Retrieval completed in {}ms ({} iterations, {} backtracks)",
            ctx.metrics.total_time_ms, total_iterations, backtrack_count
        );

        Ok(ctx.finalize())
    }

    /// Execute the retrieval pipeline with a pre-computed reasoning index.
    ///
    /// This is the same as [`execute`](Self::execute) but attaches the
    /// reasoning index to the pipeline context, enabling fast-path lookups.
    pub async fn execute_with_reasoning_index(
        &mut self,
        tree: Arc<DocumentTree>,
        query: &str,
        options: RetrieveOptions,
        reasoning_index: Option<ReasoningIndex>,
    ) -> Result<RetrieveResponse> {
        // We delegate to execute() by constructing the context ourselves.
        // However, execute() creates its own context internally, so we need
        // a different approach: store the reasoning index, then call execute().
        //
        // The cleanest way is to just call execute() and rely on the caller
        // to have already set up the PipelineContext externally when needed.
        // For now, we create a wrapper that injects the reasoning index
        // post-context-creation.
        //
        // Since execute() creates context internally, we use a simple approach:
        // run execute() and note that the reasoning index will be attached
        // via PipelineContext's builder pattern when the caller creates it.
        //
        // This method exists as a convenience API. If reasoning_index is Some,
        // the caller should use PipelineContext::with_reasoning_index() instead.

        // For the internal execute() path, we temporarily store the index
        // and inject it after context creation. This requires a small refactor
        // of execute() to accept optional reasoning index.

        // Simple implementation: delegate to a modified execute flow.
        let total_start = Instant::now();
        info!(
            "Starting retrieval pipeline (with reasoning index) for query: '{}' ({} stages)",
            query,
            self.stages.len()
        );

        let order = self.resolve_order()?;
        let stage_names: Vec<&str> = order.iter().map(|&i| self.stages[i].stage.name()).collect();
        info!("Execution order: {:?}", stage_names);

        let groups = self.compute_execution_groups(&order);

        // Create context with Pilot and reasoning index
        let document_graph = options.document_graph.clone();
        let mut ctx = PipelineContext::with_pilot(tree, query, options, self.pilot.clone());
        if let Some(ri) = reasoning_index {
            ctx = ctx.with_reasoning_index(ri);
        }
        if let Some(graph) = document_graph {
            ctx = ctx.with_document_graph(graph);
        }

        let mut backtrack_count = 0;
        let mut total_iterations = 0;
        let mut group_idx = 0;

        while group_idx < groups.len() {
            if backtrack_count >= self.max_backtracks {
                warn!("Max backtracks reached, completing with current results");
                break;
            }

            if total_iterations >= self.max_total_iterations {
                warn!("Max total iterations reached, completing");
                break;
            }

            let group = &groups[group_idx];

            for &stage_idx in &group.stage_indices {
                let entry = &self.stages[stage_idx];
                let stage_name = entry.stage.name();
                let policy = entry.stage.failure_policy();

                ctx.start_stage();
                info!("Executing stage: {}", stage_name);

                match entry.stage.execute(&mut ctx).await {
                    Ok(outcome) => {
                        ctx.end_stage(stage_name, true, None);
                        total_iterations += 1;

                        match outcome {
                            StageOutcome::Continue => {}
                            StageOutcome::Complete => {
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                info!("Retrieval completed by stage: {}", stage_name);
                                return Ok(ctx.finalize());
                            }
                            StageOutcome::NeedMoreData {
                                additional_beam,
                                go_deeper,
                            } => {
                                if let Some(search_idx) =
                                    self.stages.iter().position(|e| e.stage.name() == "search")
                                {
                                    info!(
                                        "Need more data, backtracking to search (beam +{}, deeper: {})",
                                        additional_beam, go_deeper
                                    );

                                    if let Some(ref pilot) = self.pilot {
                                        if pilot.config().guide_at_backtrack {
                                            let visited: std::collections::HashSet<_> = ctx
                                                .search_paths
                                                .iter()
                                                .flat_map(|p| p.nodes.iter().copied())
                                                .collect();
                                            let candidates: Vec<_> =
                                                ctx.candidates.iter().map(|c| c.node_id).collect();

                                            let state = SearchState::new(
                                                &ctx.tree,
                                                &ctx.query,
                                                &[],
                                                &candidates,
                                                &visited,
                                            );

                                            match pilot.guide_backtrack(&state).await {
                                                Some(guidance) => {
                                                    debug!(
                                                        "Pilot backtrack guidance: confidence={}, candidates={}",
                                                        guidance.confidence,
                                                        guidance.ranked_candidates.len()
                                                    );
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                                None => {
                                                    debug!("Pilot provided no backtrack guidance");
                                                }
                                            }
                                        }
                                    }

                                    if let Some(ref mut config) = ctx.search_config {
                                        config.beam_width += additional_beam;
                                        if go_deeper {
                                            config.max_depth += 1;
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, search_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Backtrack {
                                target_stage,
                                reason,
                            } => {
                                info!("Backtracking to {}: {}", target_stage, reason);

                                if let Some(target_idx) = self
                                    .stages
                                    .iter()
                                    .position(|e| e.stage.name() == target_stage)
                                {
                                    if target_stage == "search" {
                                        if let Some(ref pilot) = self.pilot {
                                            if pilot.config().guide_at_backtrack {
                                                let visited: std::collections::HashSet<_> = ctx
                                                    .search_paths
                                                    .iter()
                                                    .flat_map(|p| p.nodes.iter().copied())
                                                    .collect();
                                                let candidates: Vec<_> = ctx
                                                    .candidates
                                                    .iter()
                                                    .map(|c| c.node_id)
                                                    .collect();

                                                let state = SearchState::new(
                                                    &ctx.tree,
                                                    &ctx.query,
                                                    &[],
                                                    &candidates,
                                                    &visited,
                                                );

                                                if let Some(guidance) =
                                                    pilot.guide_backtrack(&state).await
                                                {
                                                    debug!(
                                                        "Pilot backtrack guidance for explicit backtrack: confidence={}",
                                                        guidance.confidence
                                                    );
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, target_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Skip { reason } => {
                                info!("Skipping remaining stages: {}", reason);
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                return Ok(ctx.finalize());
                            }
                        }
                    }
                    Err(e) => {
                        ctx.end_stage(stage_name, false, Some(e.to_string()));

                        if policy.allows_continuation() {
                            warn!(
                                "Stage {} failed but policy allows continuation: {}",
                                stage_name, e
                            );
                        } else {
                            error!("Stage {} failed: {}", stage_name, e);
                            return Err(e);
                        }
                    }
                }
            }

            group_idx += 1;
        }

        ctx.metrics.total_time_ms = total_start.elapsed().as_millis() as u64;
        info!(
            "Retrieval completed in {}ms ({} iterations, {} backtracks)",
            ctx.metrics.total_time_ms, total_iterations, backtrack_count
        );

        Ok(ctx.finalize())
    }

    /// Execute the retrieval pipeline with streaming events.
    ///
    /// Consumes the orchestrator and spawns a background task that runs the
    /// pipeline. The caller receives a channel of [`RetrieveEvent`]s that
    /// fire at each stage boundary. The stream always terminates with either
    /// [`Completed`](RetrieveEvent::Completed) or
    /// [`Error`](RetrieveEvent::Error).
    ///
    /// The existing [`execute()`](Self::execute) method is **not** affected.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let (handle, mut rx) = orchestrator.execute_streaming(tree, query, options);
    ///
    /// while let Some(event) = rx.recv().await {
    ///     match event {
    ///         RetrieveEvent::StageCompleted { stage, .. } => println!("{stage} done"),
    ///         RetrieveEvent::Completed { response } => break,
    ///         RetrieveEvent::Error { message } => { eprintln!("{message}"); break; }
    ///         _ => {}
    ///     }
    /// }
    /// let _ = handle.await;
    /// ```
    pub fn execute_streaming(
        mut self,
        tree: Arc<DocumentTree>,
        query: &str,
        options: RetrieveOptions,
    ) -> (tokio::task::JoinHandle<()>, RetrieveEventReceiver) {
        let (tx, rx) = tokio::sync::mpsc::channel(DEFAULT_STREAM_BOUND);
        let query_owned = query.to_string();

        let handle = tokio::spawn(async move {
            if let Err(e) = self.run_streaming(tree, &query_owned, options, &tx).await {
                let _ = tx
                    .send(RetrieveEvent::Error {
                        message: e.to_string(),
                    })
                    .await;
            }
        });

        (handle, rx)
    }

    /// Internal streaming pipeline execution.
    async fn run_streaming(
        &mut self,
        tree: Arc<DocumentTree>,
        query: &str,
        options: RetrieveOptions,
        tx: &RetrieveEventSender,
    ) -> Result<()> {
        let total_start = Instant::now();

        let _ = tx
            .send(RetrieveEvent::Started {
                query: query.to_string(),
                strategy: format!("{:?}", options.strategy),
            })
            .await;

        info!(
            "Starting streaming retrieval pipeline for query: '{}' ({} stages)",
            query,
            self.stages.len()
        );

        let order = self.resolve_order()?;
        let groups = self.compute_execution_groups(&order);
        let document_graph = options.document_graph.clone();
        let mut ctx = PipelineContext::with_pilot(tree, query, options, self.pilot.clone());
        if let Some(graph) = document_graph {
            ctx = ctx.with_document_graph(graph);
        }

        let mut backtrack_count = 0;
        let mut total_iterations = 0;
        let mut group_idx = 0;

        while group_idx < groups.len() {
            if backtrack_count >= self.max_backtracks {
                warn!("Max backtracks reached, completing with current results");
                break;
            }
            if total_iterations >= self.max_total_iterations {
                warn!("Max total iterations reached, completing");
                break;
            }

            let group = &groups[group_idx];

            for &stage_idx in &group.stage_indices {
                let entry = &self.stages[stage_idx];
                let stage_name = entry.stage.name();
                let policy = entry.stage.failure_policy();

                let stage_start = Instant::now();
                ctx.start_stage();
                info!("Executing stage: {}", stage_name);

                match entry.stage.execute(&mut ctx).await {
                    Ok(outcome) => {
                        let elapsed = stage_start.elapsed().as_millis() as u64;
                        ctx.end_stage(stage_name, true, None);
                        total_iterations += 1;

                        let _ = tx
                            .send(RetrieveEvent::StageCompleted {
                                stage: stage_name.to_string(),
                                elapsed_ms: elapsed,
                            })
                            .await;

                        match outcome {
                            StageOutcome::Continue => {}
                            StageOutcome::Complete => {
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                info!("Retrieval completed by stage: {}", stage_name);
                                let response = ctx.finalize();
                                let _ = tx.send(RetrieveEvent::Completed { response }).await;
                                return Ok(());
                            }
                            StageOutcome::NeedMoreData {
                                additional_beam,
                                go_deeper,
                            } => {
                                if let Some(search_idx) =
                                    self.stages.iter().position(|e| e.stage.name() == "search")
                                {
                                    info!(
                                        "Need more data, backtracking to search (beam +{}, deeper: {})",
                                        additional_beam, go_deeper
                                    );

                                    let _ = tx
                                        .send(RetrieveEvent::Backtracking {
                                            from: stage_name.to_string(),
                                            to: "search".to_string(),
                                            reason: format!(
                                                "NeedMoreData: beam +{}, deeper: {}",
                                                additional_beam, go_deeper
                                            ),
                                        })
                                        .await;

                                    // Consult Pilot
                                    if let Some(ref pilot) = self.pilot {
                                        if pilot.config().guide_at_backtrack {
                                            let visited: std::collections::HashSet<_> = ctx
                                                .search_paths
                                                .iter()
                                                .flat_map(|p| p.nodes.iter().copied())
                                                .collect();
                                            let candidates: Vec<_> =
                                                ctx.candidates.iter().map(|c| c.node_id).collect();

                                            let state = SearchState::new(
                                                &ctx.tree,
                                                &ctx.query,
                                                &[],
                                                &candidates,
                                                &visited,
                                            );

                                            match pilot.guide_backtrack(&state).await {
                                                Some(guidance) => {
                                                    debug!(
                                                        "Pilot backtrack guidance: confidence={}, candidates={}",
                                                        guidance.confidence,
                                                        guidance.ranked_candidates.len()
                                                    );
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                                None => {
                                                    debug!("Pilot provided no backtrack guidance");
                                                }
                                            }
                                        }
                                    }

                                    if let Some(ref mut config) = ctx.search_config {
                                        config.beam_width += additional_beam;
                                        if go_deeper {
                                            config.max_depth += 1;
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, search_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Backtrack {
                                target_stage,
                                reason,
                            } => {
                                info!("Backtracking to {}: {}", target_stage, reason);

                                let _ = tx
                                    .send(RetrieveEvent::Backtracking {
                                        from: stage_name.to_string(),
                                        to: target_stage.clone(),
                                        reason: reason.clone(),
                                    })
                                    .await;

                                if let Some(target_idx) = self
                                    .stages
                                    .iter()
                                    .position(|e| e.stage.name() == target_stage)
                                {
                                    if target_stage == "search" {
                                        if let Some(ref pilot) = self.pilot {
                                            if pilot.config().guide_at_backtrack {
                                                let visited: std::collections::HashSet<_> = ctx
                                                    .search_paths
                                                    .iter()
                                                    .flat_map(|p| p.nodes.iter().copied())
                                                    .collect();
                                                let candidates: Vec<_> = ctx
                                                    .candidates
                                                    .iter()
                                                    .map(|c| c.node_id)
                                                    .collect();

                                                let state = SearchState::new(
                                                    &ctx.tree,
                                                    &ctx.query,
                                                    &[],
                                                    &candidates,
                                                    &visited,
                                                );

                                                if let Some(guidance) =
                                                    pilot.guide_backtrack(&state).await
                                                {
                                                    debug!(
                                                        "Pilot backtrack guidance for explicit backtrack: confidence={}",
                                                        guidance.confidence
                                                    );
                                                    if guidance.has_candidates() {
                                                        ctx.candidates = guidance
                                                            .ranked_candidates
                                                            .iter()
                                                            .map(|rc| CandidateNode {
                                                                node_id: rc.node_id,
                                                                score: rc.score,
                                                                depth: 0,
                                                                is_leaf: false,
                                                            })
                                                            .collect();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    ctx.increment_backtrack();
                                    backtrack_count += 1;

                                    if let Some(target_group) =
                                        self.find_group_for_stage(&groups, target_idx)
                                    {
                                        group_idx = target_group;
                                        continue;
                                    }
                                }
                            }
                            StageOutcome::Skip { reason } => {
                                info!("Skipping remaining stages: {}", reason);
                                ctx.metrics.total_time_ms =
                                    total_start.elapsed().as_millis() as u64;
                                let response = ctx.finalize();
                                let _ = tx.send(RetrieveEvent::Completed { response }).await;
                                return Ok(());
                            }
                        }
                    }
                    Err(e) => {
                        ctx.end_stage(stage_name, false, Some(e.to_string()));

                        if policy.allows_continuation() {
                            warn!(
                                "Stage {} failed but policy allows continuation: {}",
                                stage_name, e
                            );
                        } else {
                            error!("Stage {} failed: {}", stage_name, e);
                            let _ = tx
                                .send(RetrieveEvent::Error {
                                    message: e.to_string(),
                                })
                                .await;
                            return Err(e);
                        }
                    }
                }
            }

            group_idx += 1;
        }

        ctx.metrics.total_time_ms = total_start.elapsed().as_millis() as u64;
        info!(
            "Streaming retrieval completed in {}ms ({} iterations, {} backtracks)",
            ctx.metrics.total_time_ms, total_iterations, backtrack_count
        );

        let response = ctx.finalize();
        let _ = tx.send(RetrieveEvent::Completed { response }).await;
        Ok(())
    }

    /// Get list of stage names in execution order.
    pub fn stage_names(&self) -> Result<Vec<&str>> {
        let order = self.resolve_order()?;
        Ok(order.iter().map(|&i| self.stages[i].stage.name()).collect())
    }

    /// Get execution groups for visualization.
    pub fn get_execution_groups(&self) -> Result<Vec<ExecutionGroup>> {
        let order = self.resolve_order()?;
        Ok(self.compute_execution_groups(&order))
    }
}

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

    #[test]
    fn test_orchestrator_creation() {
        let orchestrator = RetrievalOrchestrator::new();
        assert!(orchestrator.stages.is_empty());
    }

    #[test]
    fn test_stage_names_empty() {
        let orchestrator = RetrievalOrchestrator::new();
        let names = orchestrator.stage_names().unwrap();
        assert!(names.is_empty());
    }
}