polaris_graph 0.2.2

Graph execution primitives for Polaris (Layer 2).
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
//! Tests for Graph validation.
//!
//! These tests verify the `Graph::validate()` functionality:
//! - Entry point validation
//! - Node reference validation
//! - Decision node requirements
//! - Parallel node requirements
//! - Loop node requirements
//! - Scope node validation (empty graph, resource access rules)
//! - Error display formatting

mod test_utils;

use polaris_graph::CaughtError;
use polaris_graph::executor::{GraphExecutor, ResourceValidationError};
use polaris_graph::graph::{Graph, ValidationError, ValidationWarning};
use polaris_graph::hooks::HooksAPI;
use polaris_graph::hooks::schedule::OnGraphStart;
use polaris_graph::node::{ContextPolicy, NodeId};
use polaris_system::param::{
    Access, AccessMode, ERROR_CONTEXT, ErrOut, SystemAccess, SystemContext, SystemParam,
};
use polaris_system::resource::LocalResource;
use polaris_system::system::{BoxFuture, System, SystemError};
use std::any::TypeId;
use test_utils::{ReadConfigSystem, SuccessSystem, TestConfig, WriteConfigSystem};

// ─────────────────────────────────────────────────────────────────────────────
// Test Systems
// ─────────────────────────────────────────────────────────────────────────────

async fn first_step() -> i32 {
    1
}

async fn second_step() -> i32 {
    2
}

async fn true_path_system() -> String {
    "true".to_string()
}

async fn false_path_system() -> String {
    "false".to_string()
}

async fn branch_a() -> i32 {
    1
}

async fn branch_b() -> i32 {
    2
}

async fn loop_body() -> i32 {
    42
}

// ─────────────────────────────────────────────────────────────────────────────
// Entry Point Validation
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_empty_graph_fails() {
    let graph = Graph::new();
    let result = graph.validate();

    assert!(result.is_err());
    assert!(
        result
            .errors
            .iter()
            .any(|err| matches!(err, ValidationError::NoEntryPoint))
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Valid Graph Structures
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_simple_graph_succeeds() {
    let mut graph = Graph::new();
    graph.add_system(first_step).add_system(second_step);

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

#[test]
fn validate_graph_with_conditional_branch_succeeds() {
    #[derive(Debug)]
    struct DecisionOutput {
        should_branch: bool,
    }

    async fn decision_system() -> DecisionOutput {
        DecisionOutput {
            should_branch: true,
        }
    }

    let mut graph = Graph::new();
    graph
        .add_system(decision_system)
        .add_conditional_branch::<DecisionOutput, _, _, _>(
            "branch",
            |output| output.should_branch,
            |g| {
                g.add_system(true_path_system);
            },
            |g| {
                g.add_system(false_path_system);
            },
        );

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

#[test]
fn validate_graph_with_parallel_succeeds() {
    let mut graph = Graph::new();
    graph.add_parallel(
        "parallel",
        vec![
            |g: &mut Graph| {
                g.add_system(branch_a);
            },
            |g: &mut Graph| {
                g.add_system(branch_b);
            },
        ],
    );

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

#[test]
fn validate_graph_with_loop_succeeds() {
    let mut graph = Graph::new();
    graph.add_loop_n("loop", 5, |g| {
        g.add_system(loop_body);
    });

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

// ─────────────────────────────────────────────────────────────────────────────
// Error Display Formatting
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validation_error_no_entry_point_display() {
    let err = ValidationError::NoEntryPoint;
    assert_eq!(format!("{err}"), "graph has no entry point");
}

#[test]
fn validation_error_invalid_entry_point_display() {
    let err = ValidationError::InvalidEntryPoint(NodeId::from_string("5"));
    let msg = format!("{err}");
    assert!(msg.contains("invalid node"));
    assert!(msg.contains("node_5"));
}

#[test]
fn validation_error_missing_predicate_display() {
    let err = ValidationError::MissingPredicate {
        node: NodeId::from_string("3"),
        name: "decision",
    };
    let msg = format!("{err}");
    assert!(msg.contains("decision"));
    assert!(msg.contains("missing predicate"));
}

#[test]
fn validation_error_missing_branch_display() {
    let err = ValidationError::MissingBranch {
        node: NodeId::from_string("2"),
        name: "choice",
        branch: "true",
    };
    let msg = format!("{err}");
    assert!(msg.contains("choice"));
    assert!(msg.contains("true branch"));
}

#[test]
fn validation_error_no_termination_condition_display() {
    let err = ValidationError::NoTerminationCondition {
        node: NodeId::from_string("1"),
        name: "infinite_loop",
    };
    let msg = format!("{err}");
    assert!(msg.contains("termination condition"));
    assert!(msg.contains("infinite_loop"));
}

// ─────────────────────────────────────────────────────────────────────────────
// Error Trait Implementation
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validation_error_implements_error_trait() {
    fn assert_error<E: std::error::Error>() {}
    assert_error::<ValidationError>();
}

// ─────────────────────────────────────────────────────────────────────────────
// Parallel Output Conflict Detection
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_parallel_conflicting_outputs_warns() {
    // Both branches produce the same output type (i32)
    let mut graph = Graph::new();
    graph.add_parallel(
        "conflict",
        vec![
            |g: &mut Graph| {
                g.add_system(branch_a);
            },
            |g: &mut Graph| {
                g.add_system(branch_b);
            },
        ],
    );

    let result = graph.validate();
    assert!(result.is_ok(), "graph should be structurally valid");
    assert!(
        result
            .warnings
            .iter()
            .any(|w| matches!(w, ValidationWarning::ConflictingParallelOutputs { .. })),
        "expected ConflictingParallelOutputs warning, got: {:?}",
        result.warnings
    );
}

#[test]
fn validate_parallel_different_outputs_no_warning() {
    // Branches produce different output types (i32 vs String)
    async fn string_branch() -> String {
        "hello".to_string()
    }

    let mut graph = Graph::new();
    graph.add_parallel(
        "no_conflict",
        vec![
            |g: &mut Graph| {
                g.add_system(branch_a);
            },
            |g: &mut Graph| {
                g.add_system(string_branch);
            },
        ],
    );

    let result = graph.validate();
    assert!(result.is_ok(), "graph should be structurally valid");
    assert!(
        result.warnings.is_empty(),
        "expected no warnings, got: {:?}",
        result.warnings
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Loop Predicate Output Validation
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_loop_predicate_output_not_produced() {
    #[derive(Debug)]
    struct LoopState {
        done: bool,
    }

    // Loop predicate reads LoopState, but body only produces i32
    let mut graph = Graph::new();
    graph.add_loop::<LoopState, _, _>(
        "bad_loop",
        |state| state.done,
        |g| {
            g.add_system(loop_body); // produces i32, not LoopState
        },
    );

    let result = graph.validate();
    assert!(result.is_err());
    assert!(
        result
            .errors
            .iter()
            .any(|err| matches!(err, ValidationError::LoopPredicateOutputNotProduced { .. })),
        "expected LoopPredicateOutputNotProduced error, got: {:?}",
        result.errors
    );
}

#[test]
fn validate_loop_predicate_output_produced() {
    #[derive(Debug)]
    struct LoopState {
        done: bool,
    }

    async fn produce_loop_state() -> LoopState {
        LoopState { done: true }
    }

    // Loop predicate reads LoopState, body produces LoopState
    let mut graph = Graph::new();
    graph.add_loop::<LoopState, _, _>(
        "good_loop",
        |state| state.done,
        |g| {
            g.add_system(produce_loop_state);
        },
    );

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

// ─────────────────────────────────────────────────────────────────────────────
// Edge Requirement Validation
// ─────────────────────────────────────────────────────────────────────────────

/// A system that declares it requires an error edge (like one using `CaughtError`).
struct ErrorHandlerSystem;

impl System for ErrorHandlerSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "error_handler_system"
    }

    fn access(&self) -> SystemAccess {
        let mut access = SystemAccess::default();
        access.require_context(ERROR_CONTEXT);
        access
    }
}

#[test]
fn validate_missing_error_edge_for_caught_error_system() {
    let mut graph = Graph::new();
    // Place the error-requiring system on a normal sequential path
    graph.add_boxed_system(Box::new(ErrorHandlerSystem));

    let result = graph.validate();
    assert!(result.is_err());
    assert!(
        result.errors.iter().any(|err| matches!(
            err,
            ValidationError::MissingEdgeRequirement {
                requirement: ERROR_CONTEXT,
                ..
            }
        )),
        "expected MissingEdgeRequirement error, got: {:?}",
        result.errors
    );
}

#[test]
fn validate_error_edge_satisfies_requirement() {
    let mut graph = Graph::new();

    // Add a normal system first, then attach an error handler that requires error edge
    let source_id = graph.add_system_node(first_step);
    graph.add_error_handler_for(source_id, |g| {
        g.add_boxed_system(Box::new(ErrorHandlerSystem));
    });

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

#[test]
fn context_requirements_affect_is_empty() {
    let access = SystemAccess::default();
    assert!(access.is_empty());

    let mut access = SystemAccess::default();
    access.require_context(ERROR_CONTEXT);
    assert!(!access.is_empty());
}

#[test]
fn context_requirements_merge() {
    let mut a = SystemAccess::default();
    a.require_context(ERROR_CONTEXT);

    let mut b = SystemAccess::default();
    b.require_context("timeout");

    a.merge(&b);
    assert!(a.context_requirements.contains(&ERROR_CONTEXT));
    assert!(a.context_requirements.contains(&"timeout"));
}

#[test]
fn context_requirements_no_duplicates() {
    let mut access = SystemAccess::default();
    access.require_context(ERROR_CONTEXT);
    access.require_context(ERROR_CONTEXT);
    assert_eq!(access.context_requirements.len(), 1);
}

// ─────────────────────────────────────────────────────────────────────────────
// ErrOut<CaughtError> Validation
// ─────────────────────────────────────────────────────────────────────────────

/// System that delegates its access to `ErrOut<CaughtError>`.
struct ErrOutHandlerSystem;

impl System for ErrOutHandlerSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "err_out_handler_system"
    }

    fn access(&self) -> SystemAccess {
        <ErrOut<CaughtError>>::access()
    }
}

#[test]
fn err_out_param_declares_error_context_requirement() {
    let access = <ErrOut<CaughtError>>::access();
    assert!(
        access.context_requirements.contains(&ERROR_CONTEXT),
        "ErrOut<CaughtError> should declare error context requirement"
    );
}

#[test]
fn err_out_param_rejected_without_error_edge() {
    let mut graph = Graph::new();
    graph.add_boxed_system(Box::new(ErrOutHandlerSystem));

    let result = graph.validate();
    assert!(result.is_err());
    assert!(
        result.errors.iter().any(|err| matches!(
            err,
            ValidationError::MissingEdgeRequirement {
                requirement: ERROR_CONTEXT,
                ..
            }
        )),
        "expected MissingEdgeRequirement, got: {:?}",
        result.errors
    );
}

#[test]
fn err_out_param_accepted_behind_error_edge() {
    let mut graph = Graph::new();

    let source_id = graph.add_system_node(first_step);
    graph.add_error_handler_for(source_id, |g| {
        g.add_boxed_system(Box::new(ErrOutHandlerSystem));
    });

    let result = graph.validate();
    assert!(result.is_ok(), "Validation failed: {:?}", result.errors);
}

// ─────────────────────────────────────────────────────────────────────────────
// ValidationResult API
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validation_result_warnings_preserved_with_errors() {
    // Build a graph that has both a warning (parallel output conflict)
    // and an error (error-handler system without error edge).
    let mut graph = Graph::new();
    graph.add_parallel(
        "conflict",
        vec![
            |g: &mut Graph| {
                g.add_system(branch_a);
            },
            |g: &mut Graph| {
                g.add_system(branch_b);
            },
        ],
    );

    // This system requires an error edge but is on a sequential path → error
    graph.add_boxed_system(Box::new(ErrorHandlerSystem));

    let result = graph.validate();
    assert!(result.is_err(), "should have errors");
    assert!(
        result.has_warnings(),
        "warnings should be preserved even when errors exist"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Scope Validation
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn scope_with_empty_inner_graph_reports_error() {
    let inner = Graph::new();
    let mut graph = Graph::new();
    graph.add_scope("empty_scope", inner, ContextPolicy::shared());

    let result = graph.validate();
    assert!(
        result
            .errors
            .iter()
            .any(|err| { matches!(err, ValidationError::EmptyScopeGraph { .. }) }),
        "should report EmptyScopeGraph error, got: {:?}",
        result.errors
    );
}

#[test]
fn scope_with_valid_inner_graph_passes_validation() {
    let mut inner = Graph::new();
    inner.add_boxed_system(Box::new(SuccessSystem));

    let mut graph = Graph::new();
    graph.add_scope("valid_scope", inner, ContextPolicy::shared());

    let result = graph.validate();
    assert!(
        result.errors.is_empty(),
        "valid scope should pass validation, got: {:?}",
        result.errors
    );
}

#[test]
fn scope_isolated_forward_allows_write_access() {
    let mut inner = Graph::new();
    inner.add_boxed_system(Box::new(WriteConfigSystem));

    let policy = ContextPolicy::isolated().forward::<TestConfig>();

    let mut graph = Graph::new();
    graph.add_scope("isolated_rw", inner, policy);

    let ctx = SystemContext::new().with(TestConfig { value: 1 });

    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, None);

    assert!(
        result.is_ok(),
        "write access to forwarded resource should pass validation, got: {:?}",
        result.unwrap_err()
    );
}

#[test]
fn scope_isolated_forward_allows_read_access() {
    let mut inner = Graph::new();
    inner.add_boxed_system(Box::new(ReadConfigSystem));

    let policy = ContextPolicy::isolated().forward::<TestConfig>();

    let mut graph = Graph::new();
    graph.add_scope("isolated_ro_read", inner, policy);

    let ctx = SystemContext::new().with(TestConfig { value: 1 });

    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, None);

    assert!(
        result.is_ok(),
        "read access to forwarded resource should pass validation, got: {:?}",
        result.unwrap_err()
    );
}

#[test]
fn scope_inner_graph_invalid_propagates_errors() {
    // A scope graph with a structural error should produce ScopeGraphInvalid
    // wrapping the inner error. Here we use a loop whose predicate reads
    // LoopState but whose body only produces i32.
    #[derive(Debug)]
    struct LoopState {
        done: bool,
    }

    let mut inner = Graph::new();
    inner.add_loop::<LoopState, _, _>(
        "bad_loop",
        |state| state.done,
        |g| {
            g.add_system(loop_body); // produces i32, not LoopState
        },
    );

    let mut graph = Graph::new();
    graph.add_scope("invalid_inner_scope", inner, ContextPolicy::shared());

    let result = graph.validate();
    assert!(
        result
            .errors
            .iter()
            .any(|err| matches!(err, ValidationError::ScopeGraphInvalid { .. })),
        "should report ScopeGraphInvalid wrapping inner error, got: {:?}",
        result.errors
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Scope Resource Validation — Negative Tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn scope_isolated_without_forward_rejects_required_resource() {
    // An isolated scope whose inner system requires TestConfig (via read)
    // but the policy does not forward it — validation should fail.
    let mut inner = Graph::new();
    inner.add_boxed_system(Box::new(ReadConfigSystem));

    let policy = ContextPolicy::isolated(); // no forward
    let mut graph = Graph::new();
    graph.add_scope("iso_no_fwd", inner, policy);

    let ctx = SystemContext::new().with(TestConfig { value: 1 });
    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, None);

    assert!(
        result.is_err(),
        "isolated scope without forwarding should fail resource validation"
    );
    let errors = result.unwrap_err();
    assert!(
        errors
            .iter()
            .any(|err| { matches!(err, ResourceValidationError::MissingResource { .. }) }),
        "should report MissingResource, got: {errors:?}"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Scope Warning Propagation
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn scope_propagates_inner_graph_warnings() {
    // A scope containing a parallel node with duplicate output types
    // should produce a ScopeGraphWarning wrapping ConflictingParallelOutputs.
    let mut inner = Graph::new();
    inner.add_parallel(
        "inner_conflict",
        vec![
            |g: &mut Graph| {
                g.add_system(branch_a);
            },
            |g: &mut Graph| {
                g.add_system(branch_b);
            },
        ],
    );

    let mut graph = Graph::new();
    graph.add_scope("warn_scope", inner, ContextPolicy::shared());

    let result = graph.validate();
    assert!(
        result.is_ok(),
        "scope with inner warnings should still pass validation, got errors: {:?}",
        result.errors
    );
    assert!(
        result
            .warnings
            .iter()
            .any(|w| matches!(w, ValidationWarning::ScopeGraphWarning { .. })),
        "expected ScopeGraphWarning wrapping inner ConflictingParallelOutputs, got: {:?}",
        result.warnings
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// Output Reachability Validation
// ─────────────────────────────────────────────────────────────────────────────

/// System that produces `i32` output.
struct ProducesI32;

impl System for ProducesI32 {
    type Output = i32;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(42) })
    }

    fn name(&self) -> &'static str {
        "produces_i32"
    }
}

/// System that declares an `Out<i32>` dependency in its access.
struct ConsumesI32Output;

impl System for ConsumesI32Output {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "consumes_i32_output"
    }

    fn access(&self) -> SystemAccess {
        let mut access = SystemAccess::default();
        access.outputs.push(Access {
            type_id: TypeId::of::<i32>(),
            type_name: std::any::type_name::<i32>(),
            mode: AccessMode::Write,
            is_global: false,
        });
        access
    }
}

/// System that declares an `Out<String>` dependency in its access.
struct ConsumesStringOutput;

impl System for ConsumesStringOutput {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "consumes_string_output"
    }

    fn access(&self) -> SystemAccess {
        let mut access = SystemAccess::default();
        access.outputs.push(Access {
            type_id: TypeId::of::<String>(),
            type_name: std::any::type_name::<String>(),
            mode: AccessMode::Write,
            is_global: false,
        });
        access
    }
}

#[test]
fn validate_output_reachability_succeeds_for_linear_chain() {
    let mut graph = Graph::new();
    graph.add_boxed_system(Box::new(ProducesI32));
    graph.add_boxed_system(Box::new(ConsumesI32Output));

    let ctx = SystemContext::new();
    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, None);

    assert!(
        result.is_ok(),
        "linear chain with matching output should pass validation, got: {:?}",
        result.unwrap_err()
    );
}

#[test]
fn validate_output_reachability_fails_for_missing_output() {
    let mut graph = Graph::new();
    graph.add_boxed_system(Box::new(ProducesI32));
    graph.add_boxed_system(Box::new(ConsumesStringOutput));

    let ctx = SystemContext::new();
    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, None);

    assert!(result.is_err(), "should fail when output is not produced");
    let errors = result.unwrap_err();
    assert!(
        errors.iter().any(|err| matches!(
            err,
            ResourceValidationError::MissingOutput {
                system_name: "consumes_string_output",
                ..
            }
        )),
        "expected MissingOutput error for consumes_string_output, got: {errors:?}"
    );
}

/// A resource type used for testing hook-provided outputs.
#[derive(Clone)]
struct HookProvidedOutput;
impl LocalResource for HookProvidedOutput {}

/// System that declares an `Out<HookProvidedOutput>` dependency.
struct ConsumesHookOutput;

impl System for ConsumesHookOutput {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "consumes_hook_output"
    }

    fn access(&self) -> SystemAccess {
        let mut access = SystemAccess::default();
        access.outputs.push(Access {
            type_id: TypeId::of::<HookProvidedOutput>(),
            type_name: std::any::type_name::<HookProvidedOutput>(),
            mode: AccessMode::Write,
            is_global: false,
        });
        access
    }
}

#[test]
fn validate_output_reachability_hook_provided_outputs_pass() {
    let mut graph = Graph::new();
    graph.add_boxed_system(Box::new(ConsumesHookOutput));

    let hooks = HooksAPI::new();
    hooks
        .register_provider::<OnGraphStart, HookProvidedOutput, _>("provide_hook_output", |_event| {
            Some(HookProvidedOutput)
        })
        .expect("hook registration should succeed");

    let ctx = SystemContext::new();
    let executor = GraphExecutor::new();
    let result = executor.validate_resources(&graph, &ctx, Some(&hooks));

    assert!(
        result.is_ok(),
        "hook-provided output should pass validation, got: {:?}",
        result.unwrap_err()
    );
}