mocra-core 0.4.0

The mocra crawler framework runtime: errors, cache, utilities, domain models, downloader, data-plane queue, coordination, scheduler and 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
//! Queue-backed DAG processor.
//!
//! Design principles:
//! - Node routing uses `ExecutionMark.node_id` carried by Request/Response.
//! - Topology (successors map) is built from `ModuleDagDefinition` at init time.
//! - Fallback traces prior request via `prefix_request`; requests are persisted by `request.id`.
//! - Generate failure allows at most one fallback per `(node_id, prefix_uuid)` gate.
//! - Parser failure emits `TaskErrorEvent` tagged with same-node retry context.
//! - If parser succeeds but yields no `TaskParserEvent` while successors exist,
//!   a per-successor one-shot advance gate synthesizes a placeholder task.
//! - Multi-branch support: when a node has N successors and parser returns one unrouted task,
//!   it is fanned out to all N successors automatically.

use crate::cacheable::{CacheAble, CacheService};
use crate::common::interface::module::{ModuleNodeTrait, SyncBoxStream};
use crate::common::model::chain_key;
use crate::common::model::login_info::LoginInfo;
use crate::common::model::message::{TaskErrorEvent, TaskEvent, TaskOutputEvent, TaskParserEvent};
use crate::common::model::module_dag::ModuleDagDefinition;
use crate::common::model::{ExecutionMark, ModuleConfig, Request, Response};
use crate::errors::Result;
use futures::StreamExt;
use indexmap::IndexMap;
use log::{debug, info, warn};
use serde::{Deserialize, Serialize};
use serde_json::Map;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use uuid::Uuid;

// ── Distributed gate types ──────────────────────────────────────────────────

#[derive(Serialize, Deserialize)]
pub struct DagNodeAdvanceGate(pub bool);

impl CacheAble for DagNodeAdvanceGate {
    fn field() -> impl AsRef<str> {
        "dag_advance"
    }
}

#[derive(Serialize, Deserialize)]
pub struct DagStopSignal(pub bool);

impl CacheAble for DagStopSignal {
    fn field() -> impl AsRef<str> {
        "dag_stop"
    }
}

// ── Processor ───────────────────────────────────────────────────────────────

/// Queue-backed DAG processor that routes execution by `ExecutionMark.node_id`.
///
/// Nodes and topology are populated once from a `ModuleDagDefinition`, then used
/// immutably for the lifetime of a task run.
#[derive(Clone)]
pub struct ModuleDagProcessor {
    module_id: String,
    run_id: Uuid,
    cache: Arc<CacheService>,
    #[allow(dead_code)]
    ttl: u64,
    /// Node registry: preserves definition order so index-based backward-compat lookup works.
    nodes: Arc<RwLock<IndexMap<String, Arc<dyn ModuleNodeTrait>>>>,
    /// Adjacency list: node_id → ordered list of successor node_ids.
    successors: Arc<RwLock<HashMap<String, Vec<String>>>>,
    /// Entry nodes (no predecessors). Used when `pending_ctx.node_id` is not set.
    entry_nodes: Arc<RwLock<Vec<String>>>,
    stop: Arc<RwLock<bool>>,
    last_stop_check: Arc<AtomicU64>,
}

impl ModuleDagProcessor {
    /// Creates an empty processor. Call `init_from_definition` before use.
    pub fn new(module_id: String, cache: Arc<CacheService>, run_id: Uuid, ttl: u64) -> Self {
        Self {
            module_id,
            run_id,
            cache,
            ttl,
            nodes: Arc::new(RwLock::new(IndexMap::new())),
            successors: Arc::new(RwLock::new(HashMap::new())),
            entry_nodes: Arc::new(RwLock::new(Vec::new())),
            stop: Arc::new(RwLock::new(false)),
            last_stop_check: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Populates nodes and topology from a compiled DAG definition.
    pub async fn init_from_definition(&self, definition: &ModuleDagDefinition) {
        let mut nodes: tokio::sync::RwLockWriteGuard<IndexMap<String, Arc<dyn ModuleNodeTrait>>> =
            self.nodes.write().await;
        let mut successors = self.successors.write().await;
        let mut entry_nodes = self.entry_nodes.write().await;

        nodes.clear();
        successors.clear();

        // Register nodes in definition order.
        for node_def in &definition.nodes {
            nodes.insert(node_def.node_id.clone(), node_def.node.clone());
            successors.entry(node_def.node_id.clone()).or_default();
        }

        // Build successor adjacency list.
        for edge in &definition.edges {
            successors
                .entry(edge.from.clone())
                .or_default()
                .push(edge.to.clone());
        }

        // Derive entry nodes: nodes present in definition.entry_nodes, or nodes with no predecessors.
        if !definition.entry_nodes.is_empty() {
            *entry_nodes = definition.entry_nodes.clone();
        } else {
            let all_targets: std::collections::HashSet<&str> =
                definition.edges.iter().map(|e| e.to.as_str()).collect();
            *entry_nodes = definition
                .nodes
                .iter()
                .filter(|n| !all_targets.contains(n.node_id.as_str()))
                .map(|n| n.node_id.clone())
                .collect();
        }

        debug!(
            "[dag] module={} run={} init: nodes={} edges={} entries={:?}",
            self.module_id,
            self.run_id,
            nodes.len(),
            definition.edges.len(),
            *entry_nodes
        );
    }

    /// Total registered nodes (used for legacy compatibility checks).
    pub async fn get_total_nodes(&self) -> usize {
        let nodes: tokio::sync::RwLockReadGuard<IndexMap<String, Arc<dyn ModuleNodeTrait>>> =
            self.nodes.read().await;
        nodes.len()
    }

    // ── Internal helpers ─────────────────────────────────────────────────────

    /// Resolves the target `node_id` from an optional `ExecutionMark`.
    ///
    /// Priority:
    /// 1. `ctx.node_id` if set
    /// 2. `ctx.step_idx` → index into `nodes` (backward compat for in-flight queue messages)
    /// 3. First entry node (initial call with no context)
    async fn resolve_node_id(&self, ctx: &Option<ExecutionMark>) -> Option<String> {
        if let Some(mark) = ctx {
            if let Some(ref nid) = mark.node_id {
                if !nid.is_empty() {
                    return Some(nid.clone());
                }
            }
            // Backward compat: step_idx → positional lookup.
            if let Some(idx) = mark.step_idx {
                let nodes: tokio::sync::RwLockReadGuard<
                    IndexMap<String, Arc<dyn ModuleNodeTrait>>,
                > = self.nodes.read().await;
                if let Some((id, _)) = nodes.get_index(idx as usize) {
                    return Some(id.clone());
                }
            }
        }
        // Default: first entry node.
        let entry = self.entry_nodes.read().await;
        entry.first().cloned()
    }

    async fn get_node(&self, node_id: &str) -> Option<Arc<dyn ModuleNodeTrait>> {
        let nodes: tokio::sync::RwLockReadGuard<IndexMap<String, Arc<dyn ModuleNodeTrait>>> =
            self.nodes.read().await;
        nodes.get(node_id).cloned()
    }

    async fn get_successors(&self, node_id: &str) -> Vec<String> {
        let succ = self.successors.read().await;
        succ.get(node_id).cloned().unwrap_or_default()
    }

    async fn try_mark_node_advanced_once(&self, node_id: &str, successor_id: &str) -> Result<bool> {
        let key = chain_key::dag_node_advance_gate_key(
            self.run_id,
            &self.module_id,
            node_id,
            successor_id,
        );
        if DagNodeAdvanceGate::sync(&key, &self.cache)
            .await
            .map_err(Into::<crate::errors::Error>::into)?
            .is_some()
        {
            return Ok(false);
        }
        let gate = DagNodeAdvanceGate(true);
        // No TTL — the advance gate is a permanent per-run fact (keyed by UUID run_id).
        // Using a short TTL (e.g. cache.ttl=60s) would allow the gate to expire mid-run,
        // letting a pending login retry re-win the gate and restart the entire DAG fan-out.
        gate.send_nx(&key, &self.cache, None)
            .await
            .map_err(Into::into)
    }

    async fn set_stopped(&self) -> Result<()> {
        let mut stop = self.stop.write().await;
        *stop = true;
        let key = chain_key::dag_stop_key(self.run_id, &self.module_id);
        let signal = DagStopSignal(true);
        // Use send_persistent (no TTL) so the stop signal outlives cache.ttl.
        // The gate-key cleanup below deletes all gate keys; if the stop signal
        // were to expire (e.g. TTL=60s), queued error tasks could re-win the
        // already-deleted gate and restart the entire DAG fan-out.
        signal.send_persistent(&key, &self.cache).await.ok();

        // Clean up all advance gate keys for this run.
        // Successors are already in memory — enumerate every edge and delete its gate key
        // without needing a Redis SCAN.
        let gate_keys: Vec<String> = {
            let succ = self.successors.read().await;
            succ.iter()
                .flat_map(|(from, tos)| {
                    tos.iter().map(move |to| {
                        chain_key::dag_node_advance_gate_key(self.run_id, &self.module_id, from, to)
                    })
                })
                .collect()
        };
        if !gate_keys.is_empty() {
            let refs: Vec<&str> = gate_keys.iter().map(String::as_str).collect();
            if let Err(e) = self.cache.del_batch(&refs).await {
                debug!(
                    "[dag] module={} run={} set_stopped: failed to delete {} gate keys: {}",
                    self.module_id,
                    self.run_id,
                    refs.len(),
                    e
                );
            } else {
                debug!(
                    "[dag] module={} run={} set_stopped: deleted {} advance gate keys",
                    self.module_id,
                    self.run_id,
                    refs.len()
                );
            }
        }

        Ok(())
    }

    /// Deletes the persistent session state for the given run.
    /// Called by Module::parser() with the correctly-patched Module.run_id,
    /// since self.run_id (processor) may be stale when the task was loaded from factory cache.
    pub async fn delete_session_for_run(&self, run_id: Uuid) {
        // Key format mirrors CacheAble::cache_id: "{namespace}:session_state:{module_id}:{run_id}"
        let session_key = format!(
            "{}:session_state:{}:{}",
            self.cache.namespace(),
            self.module_id,
            run_id
        );
        if let Err(e) = self.cache.del(&session_key).await {
            warn!(
                "Failed to delete session state: module={} run={} error={:?}",
                self.module_id, run_id, e
            );
        }
    }

    /// Rate-limited stop signal check (at most once per second).
    async fn check_stop(&self) -> Result<bool> {
        {
            let stop = self.stop.read().await;
            if *stop {
                return Ok(true);
            }
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let last = self.last_stop_check.load(Ordering::Relaxed);
        if now.saturating_sub(last) < 1 {
            return Ok(false);
        }
        self.last_stop_check.store(now, Ordering::Relaxed);
        let key = chain_key::dag_stop_key(self.run_id, &self.module_id);
        if let Ok(Some(DagStopSignal(true))) = DagStopSignal::sync(&key, &self.cache).await {
            let mut stop = self.stop.write().await;
            *stop = true;
            return Ok(true);
        }
        Ok(false)
    }

    /// Returns true when a `TaskParserEvent` targets this processor's module.
    fn is_task_for_current_module(&self, ctx: &ExecutionMark, task_modules: &[String]) -> bool {
        if let Some(ref mid) = ctx.module_id {
            if !mid.is_empty() {
                return mid == &self.module_id;
            }
        }
        if task_modules.is_empty() {
            return true;
        }
        task_modules
            .iter()
            .any(|m| self.module_id.ends_with(m.as_str()) || m == &self.module_id)
    }

    // ── Public execution API ─────────────────────────────────────────────────

    /// Generates a request stream for the resolved DAG node.
    ///
    /// On generate failure the error is returned directly so the caller's retry
    /// policy can re-schedule the same node.
    pub async fn execute_generate(
        &self,
        config: Arc<ModuleConfig>,
        meta: Map<String, serde_json::Value>,
        login_info: Option<LoginInfo>,
        ctx: Option<ExecutionMark>,
        prefix_request: Option<Uuid>,
    ) -> Result<SyncBoxStream<'static, Request>> {
        let prefix = prefix_request.unwrap_or_default();

        // Guard: if this run has already been stopped, skip generation entirely.
        // This prevents queued error tasks from restarting a completed run even
        // when no pending_ctx carries an explicit node_id (they would default to
        // the entry node and re-trigger the full DAG fan-out).
        if self.check_stop().await? {
            debug!(
                "[dag] module={} run={} execute_generate: run is stopped, skipping",
                self.module_id, self.run_id
            );
            return Ok(Box::pin(futures::stream::empty()));
        }

        let Some(node_id) = self.resolve_node_id(&ctx).await else {
            debug!(
                "[dag] module={} run={} execute_generate: no nodes registered",
                self.module_id, self.run_id
            );
            return Ok(Box::pin(futures::stream::empty()));
        };

        debug!(
            "[dag] module={} run={} execute_generate: node={} prefix={}",
            self.module_id, self.run_id, node_id, prefix
        );

        let Some(node) = self.get_node(&node_id).await else {
            warn!(
                "[dag] module={} run={} execute_generate: node '{}' not found",
                self.module_id, self.run_id, node_id
            );
            return Ok(Box::pin(futures::stream::empty()));
        };

        let gen_ctx = {
            let mut mark = ctx.clone().unwrap_or_default();
            mark.node_id = Some(node_id.clone());
            if mark.module_id.is_none() {
                mark.module_id = Some(self.module_id.clone());
            }
            mark
        };

        match node.generate(config, meta, login_info).await {
            Ok(stream) => {
                let run_id = self.run_id;
                let module_id = self.module_id.clone();
                let gen_ctx_clone = gen_ctx.clone();

                let stream = stream.map(move |mut req| {
                    req.context = gen_ctx_clone.clone();
                    req.run_id = run_id;
                    req.prefix_request = prefix;
                    if req.id.is_nil() {
                        req.id = Uuid::now_v7();
                    }

                    info!(
                        "[dag] module={} run={} execute_generate: produced request id={} node={} url={}",
                        module_id, run_id, req.id, req.context.node_id.as_deref().unwrap_or("?"), req.url
                    );
                    req
                });

                Ok(Box::pin(stream))
            }
            Err(e) => {
                warn!(
                    "[dag] module={} run={} execute_generate: generate error at node '{}', will retry current node: {}",
                    self.module_id, self.run_id, node_id, e
                );
                Err(e)
            }
        }
    }

    /// Parses a response at the routed DAG node and determines next-node progression.
    ///
    /// - Parser success with tasks: advance each task to its successor node(s).
    /// - Parser success without tasks: synthesize one placeholder per successor via advance gate.
    /// - Parser failure: emit `TaskErrorEvent` for same-node retry.
    pub async fn execute_parse(
        &self,
        response: Response,
        config: Option<Arc<ModuleConfig>>,
    ) -> Result<TaskOutputEvent> {
        // Resolve node_id + its current index in the processor's IndexMap.
        //
        // Priority:
        //   1. response.context.node_id  (exact string lookup)
        //   2. If (1) misses (stale UUID after DAG rebuild), try step_idx from context
        //   3. step_idx-only path (no node_id set)
        //
        // `node_idx` is also captured so error tasks carry the CORRECT step_idx for
        // reliable index-based fallback on the next retry, regardless of UUID staleness.
        let (node_id, node_idx) = match response.context.node_id.as_deref() {
            Some(id) if !id.is_empty() => {
                let nodes = self.nodes.read().await;
                if let Some(idx) = nodes.get_index_of(id) {
                    (id.to_string(), idx)
                } else {
                    // Node id not found — likely a stale UUID from a prior DAG build.
                    // Fall back to step_idx carried in the context.
                    let fallback_idx = response.context.step_idx.unwrap_or(0) as usize;
                    match nodes.get_index(fallback_idx) {
                        Some((fallback_id, _)) => {
                            warn!(
                                "[dag] module={} run={} execute_parse: node '{}' stale, falling back to index {} ('{}')",
                                self.module_id, self.run_id, id, fallback_idx, fallback_id
                            );
                            (fallback_id.clone(), fallback_idx)
                        }
                        None => {
                            warn!(
                                "[dag] module={} run={} execute_parse: node '{}' not found and step_idx {} out of range, returning empty",
                                self.module_id, self.run_id, id, fallback_idx
                            );
                            return Ok(TaskOutputEvent::default());
                        }
                    }
                }
            }
            _ => {
                let idx = response.context.step_idx.unwrap_or(0) as usize;
                let nodes = self.nodes.read().await;
                match nodes.get_index(idx) {
                    Some((id, _)) => (id.clone(), idx),
                    None => {
                        debug!(
                            "[dag] module={} run={} execute_parse: no node at index {}, returning empty",
                            self.module_id, self.run_id, idx
                        );
                        return Ok(TaskOutputEvent::default());
                    }
                }
            }
        };

        debug!(
            "[dag] module={} run={} execute_parse: node={} idx={} prefix={}",
            self.module_id, self.run_id, node_id, node_idx, response.prefix_request
        );

        if self.check_stop().await? {
            return Ok(TaskOutputEvent::default());
        }

        let Some(node) = self.get_node(&node_id).await else {
            // Unreachable: node existence was verified during resolution above.
            warn!(
                "[dag] module={} run={} execute_parse: node '{}' not found (guard)",
                self.module_id, self.run_id, node_id
            );
            return Ok(TaskOutputEvent::default());
        };

        let node_successors = self.get_successors(&node_id).await;

        match node.parser(response.clone(), config).await {
            Ok(mut data) => {
                if data.stop.unwrap_or(false) {
                    self.set_stopped().await?;
                }

                if !data.parser_task.is_empty() {
                    // ── Route explicit parser tasks ──────────────────────────────
                    let mut routed: Vec<TaskParserEvent> =
                        Vec::with_capacity(data.parser_task.len());

                    for mut task in data.parser_task.drain(..) {
                        task.prefix_request = response.prefix_request;

                        let task_modules = task.account_task.module.clone().unwrap_or_default();

                        let same_module =
                            self.is_task_for_current_module(&task.context, &task_modules);

                        if same_module {
                            let mut next_ctx = task.context.clone();
                            if next_ctx.module_id.is_none() {
                                next_ctx.module_id = Some(self.module_id.clone());
                            }

                            if next_ctx.stay_current_step {
                                // Explicit retry on same node.
                                next_ctx.node_id = Some(node_id.clone());
                                task.context = next_ctx;
                                routed.push(task);
                                continue;
                            }

                            if next_ctx.node_id.is_none()
                                || next_ctx.node_id.as_deref() == Some(node_id.as_str())
                            {
                                // Parser didn't specify a different target (node_id is
                                // absent or still points at the current node): auto-route
                                // to successors.
                                if node_successors.is_empty() {
                                    // Leaf node — DAG execution complete for this path.
                                    debug!(
                                        "[dag] module={} run={} execute_parse: leaf node '{}', discarding unrouted task",
                                        self.module_id, self.run_id, node_id
                                    );
                                    continue;
                                }
                                if node_successors.len() == 1 {
                                    next_ctx.node_id = Some(node_successors[0].clone());
                                    task.context = next_ctx;
                                    routed.push(task);
                                } else {
                                    // Fan-out: replicate task for each successor.
                                    for succ in &node_successors {
                                        let mut t = task.clone();
                                        let mut ctx = next_ctx.clone();
                                        ctx.node_id = Some(succ.clone());
                                        t.context = ctx;
                                        routed.push(t);
                                    }
                                }
                                continue;
                            }

                            // Parser set an explicit node_id — use it verbatim.
                            task.context = next_ctx;
                        }
                        // Cross-module task: pass through unchanged.
                        routed.push(task);
                    }

                    data.parser_task = routed;
                } else {
                    // ── No tasks: synthesize placeholder per successor ────────────
                    for succ in &node_successors {
                        if self.try_mark_node_advanced_once(&node_id, succ).await? {
                            let base: TaskParserEvent = (&response).into();
                            let next_ctx = ExecutionMark::default()
                                .with_module_id(self.module_id.clone())
                                .with_node_id(succ.clone());
                            let mut next_task = base.with_context(next_ctx);
                            next_task.prefix_request = response.prefix_request;
                            data = data.with_task(next_task);
                            debug!(
                                "[dag] module={} run={} execute_parse: advance gate won for '{}' -> synthesized task to '{}'",
                                self.module_id, self.run_id, node_id, succ
                            );
                        } else {
                            debug!(
                                "[dag] module={} run={} execute_parse: advance gate lost for '{}' -> '{}'",
                                self.module_id, self.run_id, node_id, succ
                            );
                        }
                    }
                }

                Ok(data)
            }
            Err(e) => {
                // Parser failure: emit error for same-node retry.
                // Use `node_idx` (the node's current position in this processor's IndexMap)
                // so that on the next retry the index-based fallback routes correctly even
                // if the DAG is rebuilt and the UUID changes.
                warn!(
                    "[dag] module={} run={} execute_parse: parser error at node='{}' account={} platform={} request_id={} error={}",
                    self.module_id,
                    self.run_id,
                    node_id,
                    response.account,
                    response.platform,
                    response.id,
                    e
                );
                let step_idx_u32 = node_idx as u32;
                let meta = response
                    .metadata
                    .task
                    .as_object()
                    .cloned()
                    .unwrap_or_default();
                let error_task = TaskErrorEvent {
                    id: response.id,
                    account_task: TaskEvent {
                        account: response.account.clone(),
                        platform: response.platform.clone(),
                        module: Some(vec![response.module.clone()]),
                        run_id: response.run_id,
                        priority: crate::common::model::Priority::default(),
                    },
                    error_msg: e.to_string(),
                    timestamp: SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs(),
                    metadata: meta,
                    context: ExecutionMark {
                        module_id: Some(self.module_id.clone()),
                        node_id: Some(node_id.clone()),
                        step_idx: Some(step_idx_u32),
                        stay_current_step: true,
                        ..Default::default()
                    },
                    run_id: response.run_id,
                    prefix_request: response.prefix_request,
                };
                Ok(TaskOutputEvent::default().with_error(error_task))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::interface::{SyncBoxStream, ToSyncBoxStream};
    use crate::common::model::message::TaskOutputEvent;
    use crate::common::model::module_dag::{
        ModuleDagDefinition, ModuleDagEdgeDef, ModuleDagNodeDef,
    };
    use crate::common::model::{ModuleConfig, Request, Response};
    use crate::errors::Result as CResult;
    use async_trait::async_trait;
    use serde_json::Map;
    use std::sync::Arc;

    struct DummyNode {
        pub name: &'static str,
    }

    #[async_trait]
    impl ModuleNodeTrait for DummyNode {
        async fn generate(
            &self,
            _config: Arc<ModuleConfig>,
            _params: Map<String, serde_json::Value>,
            _login_info: Option<LoginInfo>,
        ) -> CResult<SyncBoxStream<'static, Request>> {
            Ok(Vec::<Request>::new().to_stream())
        }

        async fn parser(
            &self,
            _response: Response,
            _config: Option<Arc<ModuleConfig>>,
        ) -> CResult<TaskOutputEvent> {
            Ok(TaskOutputEvent::default())
        }
    }

    fn make_definition(edges: &[(&str, &str)]) -> ModuleDagDefinition {
        let node_ids: std::collections::BTreeSet<String> = edges
            .iter()
            .flat_map(|(a, b)| [a.to_string(), b.to_string()])
            .collect();
        let mut nodes: Vec<ModuleDagNodeDef> = node_ids
            .iter()
            .map(|id| ModuleDagNodeDef {
                node_id: id.clone(),
                node: Arc::new(DummyNode {
                    name: Box::leak(id.clone().into_boxed_str()),
                }),
                placement_override: None,
                policy_override: None,
                tags: vec![],
            })
            .collect();
        // Stable node order for tests
        nodes.sort_by(|a, b| a.node_id.cmp(&b.node_id));

        let edge_defs = edges
            .iter()
            .map(|(a, b)| ModuleDagEdgeDef {
                from: a.to_string(),
                to: b.to_string(),
            })
            .collect();

        // entry_nodes: nodes that are not targets of any edge
        let targets: std::collections::HashSet<&str> = edges.iter().map(|(_, b)| *b).collect();
        let entry_nodes = node_ids
            .iter()
            .filter(|id| !targets.contains(id.as_str()))
            .map(|id| id.clone())
            .collect();

        ModuleDagDefinition {
            nodes,
            edges: edge_defs,
            entry_nodes,
            default_policy: None,
            metadata: std::collections::HashMap::new(),
        }
    }

    fn make_cache() -> Arc<CacheService> {
        Arc::new(CacheService::new(None, "test".to_string(), None, None))
    }

    #[tokio::test]
    async fn resolve_node_id_by_node_id_field() {
        let def = make_definition(&[("node_a", "node_b")]);
        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let ctx = Some(ExecutionMark::default().with_node_id("node_b"));
        let resolved = proc.resolve_node_id(&ctx).await;
        assert_eq!(resolved.as_deref(), Some("node_b"));
    }

    #[tokio::test]
    async fn resolve_node_id_defaults_to_entry() {
        let def = make_definition(&[("node_a", "node_b")]);
        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let resolved = proc.resolve_node_id(&None).await;
        assert_eq!(resolved.as_deref(), Some("node_a"));
    }

    #[tokio::test]
    async fn get_successors_linear() {
        let def = make_definition(&[("node_a", "node_b"), ("node_b", "node_c")]);
        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let succ_a = proc.get_successors("node_a").await;
        assert_eq!(succ_a, vec!["node_b"]);
        let succ_b = proc.get_successors("node_b").await;
        assert_eq!(succ_b, vec!["node_c"]);
        let succ_c = proc.get_successors("node_c").await;
        assert!(succ_c.is_empty());
    }

    #[tokio::test]
    async fn get_successors_branch() {
        let def = make_definition(&[("node_a", "node_b"), ("node_a", "node_c")]);
        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let mut succ = proc.get_successors("node_a").await;
        succ.sort();
        assert_eq!(succ, vec!["node_b", "node_c"]);
    }

    // ── Metadata propagation tests ──────────────────────────────────────

    use crate::common::model::meta::MetaData;
    use std::sync::Mutex as StdMutex;

    /// Node that captures the params it receives in generate() and returns
    /// a configurable parser output.
    struct CapturingNode {
        captured_params: Arc<StdMutex<Vec<Map<String, serde_json::Value>>>>,
        parser_output: StdMutex<TaskOutputEvent>,
    }

    impl CapturingNode {
        fn new(parser_output: TaskOutputEvent) -> Self {
            CapturingNode {
                captured_params: Arc::new(StdMutex::new(Vec::new())),
                parser_output: StdMutex::new(parser_output),
            }
        }
        fn captured(&self) -> Vec<Map<String, serde_json::Value>> {
            self.captured_params.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl ModuleNodeTrait for CapturingNode {
        async fn generate(
            &self,
            _config: Arc<ModuleConfig>,
            params: Map<String, serde_json::Value>,
            _login_info: Option<LoginInfo>,
        ) -> CResult<SyncBoxStream<'static, Request>> {
            self.captured_params.lock().unwrap().push(params);
            Ok(Vec::<Request>::new().to_stream())
        }

        async fn parser(
            &self,
            _response: Response,
            _config: Option<Arc<ModuleConfig>>,
        ) -> CResult<TaskOutputEvent> {
            Ok(self.parser_output.lock().unwrap().clone())
        }
    }

    fn make_response(
        node_id: &str,
        task_meta: serde_json::Map<String, serde_json::Value>,
    ) -> Response {
        Response {
            id: Uuid::now_v7(),
            platform: "pf".to_string(),
            account: "acc".to_string(),
            module: "mod".to_string(),
            status_code: 200,
            cookies: Default::default(),
            content: vec![],
            storage_path: None,
            headers: vec![],
            task_retry_times: 0,
            metadata: MetaData::default().add_task_config(task_meta),
            download_middleware: vec![],
            data_middleware: vec![],
            task_finished: false,
            context: ExecutionMark::default()
                .with_node_id(node_id)
                .with_module_id("mod"),
            run_id: Uuid::now_v7(),
            prefix_request: Uuid::now_v7(),
            request_hash: None,
            priority: Default::default(),
        }
    }

    /// Explicit parser_task: metadata set via add_meta() should be preserved
    /// through routing and available for the next node's generate.
    #[tokio::test]
    async fn explicit_parser_task_metadata_preserved_through_routing() {
        let mut meta = Map::new();
        meta.insert("user_id".into(), serde_json::Value::String("abc".into()));
        let task = TaskParserEvent::from(&make_response("node_a", Map::new()))
            .add_meta("user_id", "abc")
            .add_meta("page", 42);

        // node_a parser returns a task with metadata
        let node_a = Arc::new(CapturingNode::new(
            TaskOutputEvent::default().with_task(task),
        ));
        let node_b = Arc::new(CapturingNode::new(TaskOutputEvent::default()));

        let def = ModuleDagDefinition {
            nodes: vec![
                ModuleDagNodeDef {
                    node_id: "node_a".into(),
                    node: node_a.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
                ModuleDagNodeDef {
                    node_id: "node_b".into(),
                    node: node_b.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
            ],
            edges: vec![ModuleDagEdgeDef {
                from: "node_a".into(),
                to: "node_b".into(),
            }],
            entry_nodes: vec!["node_a".into()],
            default_policy: None,
            metadata: Default::default(),
        };

        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let response = make_response("node_a", Map::new());
        let result = proc.execute_parse(response, None).await.unwrap();

        // The routed task should have metadata preserved and be targeted at node_b
        assert_eq!(result.parser_task.len(), 1);
        let routed = &result.parser_task[0];
        assert_eq!(routed.context.node_id.as_deref(), Some("node_b"));
        assert_eq!(
            routed.metadata.get("user_id").and_then(|v| v.as_str()),
            Some("abc")
        );
        assert_eq!(
            routed.metadata.get("page").and_then(|v| v.as_i64()),
            Some(42)
        );

        // Now feed metadata into execute_generate to verify it reaches node_b
        let ctx = Some(routed.context.clone());
        let _ = proc
            .execute_generate(
                Arc::new(ModuleConfig::default()),
                routed.metadata.clone(),
                None,
                ctx,
                None,
            )
            .await
            .unwrap();

        let captured = node_b.captured();
        assert_eq!(captured.len(), 1);
        assert_eq!(
            captured[0].get("user_id").and_then(|v| v.as_str()),
            Some("abc")
        );
        assert_eq!(captured[0].get("page").and_then(|v| v.as_i64()), Some(42));
    }

    /// Advance-gate path: when parser returns empty parser_task, synthesized
    /// tasks should carry forward the response's task metadata.
    #[tokio::test]
    async fn advance_gate_forwards_response_task_metadata() {
        // node_a parser returns empty parser_task (advance gate triggers)
        let node_a = Arc::new(CapturingNode::new(TaskOutputEvent::default()));
        let node_b = Arc::new(CapturingNode::new(TaskOutputEvent::default()));

        let def = ModuleDagDefinition {
            nodes: vec![
                ModuleDagNodeDef {
                    node_id: "node_a".into(),
                    node: node_a.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
                ModuleDagNodeDef {
                    node_id: "node_b".into(),
                    node: node_b.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
            ],
            edges: vec![ModuleDagEdgeDef {
                from: "node_a".into(),
                to: "node_b".into(),
            }],
            entry_nodes: vec!["node_a".into()],
            default_policy: None,
            metadata: Default::default(),
        };

        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        // Response carries task metadata from node_a's generate
        let mut task_meta = Map::new();
        task_meta.insert("session_id".into(), serde_json::Value::String("s1".into()));
        let response = make_response("node_a", task_meta);

        let result = proc.execute_parse(response, None).await.unwrap();

        // Advance gate should synthesize a task with the forwarded metadata
        assert_eq!(result.parser_task.len(), 1);
        let synthesized = &result.parser_task[0];
        assert_eq!(synthesized.context.node_id.as_deref(), Some("node_b"));
        assert_eq!(
            synthesized
                .metadata
                .get("session_id")
                .and_then(|v| v.as_str()),
            Some("s1"),
            "advance-gate synthesized task should carry response.metadata.task"
        );

        // Verify it reaches node_b's generate
        let _ = proc
            .execute_generate(
                Arc::new(ModuleConfig::default()),
                synthesized.metadata.clone(),
                None,
                Some(synthesized.context.clone()),
                None,
            )
            .await
            .unwrap();

        let captured = node_b.captured();
        assert_eq!(captured.len(), 1);
        assert_eq!(
            captured[0].get("session_id").and_then(|v| v.as_str()),
            Some("s1")
        );
    }

    /// Fan-out: metadata should be replicated to each successor.
    #[tokio::test]
    async fn fanout_replicates_metadata_to_all_successors() {
        let task = TaskParserEvent::from(&make_response("node_a", Map::new()))
            .add_meta("key", "shared_value");

        let node_a = Arc::new(CapturingNode::new(
            TaskOutputEvent::default().with_task(task),
        ));
        let node_b = Arc::new(CapturingNode::new(TaskOutputEvent::default()));
        let node_c = Arc::new(CapturingNode::new(TaskOutputEvent::default()));

        let def = ModuleDagDefinition {
            nodes: vec![
                ModuleDagNodeDef {
                    node_id: "node_a".into(),
                    node: node_a.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
                ModuleDagNodeDef {
                    node_id: "node_b".into(),
                    node: node_b.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
                ModuleDagNodeDef {
                    node_id: "node_c".into(),
                    node: node_c.clone(),
                    placement_override: None,
                    policy_override: None,
                    tags: vec![],
                },
            ],
            edges: vec![
                ModuleDagEdgeDef {
                    from: "node_a".into(),
                    to: "node_b".into(),
                },
                ModuleDagEdgeDef {
                    from: "node_a".into(),
                    to: "node_c".into(),
                },
            ],
            entry_nodes: vec!["node_a".into()],
            default_policy: None,
            metadata: Default::default(),
        };

        let proc = ModuleDagProcessor::new("mod".into(), make_cache(), Uuid::now_v7(), 60);
        proc.init_from_definition(&def).await;

        let response = make_response("node_a", Map::new());
        let result = proc.execute_parse(response, None).await.unwrap();

        // Fan-out should produce 2 tasks, each with the same metadata
        assert_eq!(result.parser_task.len(), 2);
        for task in &result.parser_task {
            assert_eq!(
                task.metadata.get("key").and_then(|v| v.as_str()),
                Some("shared_value")
            );
        }
        let mut targets: Vec<_> = result
            .parser_task
            .iter()
            .map(|t| t.context.node_id.clone().unwrap())
            .collect();
        targets.sort();
        assert_eq!(targets, vec!["node_b", "node_c"]);
    }

    /// with_meta replaces all metadata; add_meta appends.
    #[tokio::test]
    async fn add_meta_appends_with_meta_replaces() {
        let response = make_response("node_a", Map::new());
        let task = TaskParserEvent::from(&response)
            .add_meta("a", 1)
            .add_meta("b", 2);
        assert_eq!(task.metadata.len(), 2);

        let mut new_map = Map::new();
        new_map.insert("c".into(), serde_json::Value::from(3));
        let task2 = task.with_meta(new_map);
        assert_eq!(task2.metadata.len(), 1);
        assert_eq!(task2.metadata.get("c").and_then(|v| v.as_i64()), Some(3));
    }

    /// From<&Response> for TaskParserEvent forwards task metadata from
    /// the response's MetaData.task slot.
    #[tokio::test]
    async fn from_response_forwards_task_metadata() {
        let mut task_meta = Map::new();
        task_meta.insert("forwarded".into(), serde_json::Value::Bool(true));
        let response = make_response("node_a", task_meta);

        let parsed: TaskParserEvent = (&response).into();
        assert_eq!(
            parsed.metadata.get("forwarded").and_then(|v| v.as_bool()),
            Some(true),
            "From<&Response> should forward metadata.task into TaskParserEvent.metadata"
        );
    }

    /// From<&Response> with empty metadata still produces empty map.
    #[tokio::test]
    async fn from_response_empty_metadata_stays_empty() {
        let response = make_response("node_a", Map::new());
        let parsed: TaskParserEvent = (&response).into();
        assert!(parsed.metadata.is_empty());
    }
}