caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
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
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! Hot Reload Manager
//!
//! Manages hot reloading of agent WASM modules with zero downtime,
//! supporting graceful, immediate, parallel, and traffic-splitting strategies.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::{Mutex, RwLock};
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

use crate::agent_lifecycle_manager::HotReloadManager;
use crate::domain::hot_reload::ResourceUsageSnapshot;
#[allow(unused_imports)]
use crate::domain::{
    AgentVersion, HotReloadConfig, HotReloadError, HotReloadId, HotReloadRequest, HotReloadResult,
    HotReloadStatus, HotReloadStrategy, ReloadMetrics, TrafficSplitPercentage, VersionNumber,
    VersionSnapshot,
};
use crate::domain_types::AgentId;
use crate::time_provider::{SharedTimeProvider, production_time_provider};

/// Hot reload execution context
#[derive(Debug, Clone)]
struct HotReloadContext {
    pub request: HotReloadRequest,
    pub started_at: SystemTime,
    pub status: HotReloadStatus,
    pub metrics: ReloadMetrics,
    pub current_traffic_split: TrafficSplitPercentage,
    pub version_snapshots: Vec<VersionSnapshot>,
    pub warmup_completed: bool,
}

/// Agent instance for hot reload operations
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct AgentInstance {
    pub agent_id: AgentId,
    pub version: AgentVersion,
    pub is_active: bool,
    pub memory_usage: usize,
    pub fuel_consumed: u64,
    pub requests_handled: u64,
    pub created_at: SystemTime,
}

/// State preservation data during hot reload
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct PreservedState {
    pub agent_id: AgentId,
    pub state_data: Vec<u8>,
    pub preserved_at: SystemTime,
}

/// Traffic routing decision
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct TrafficDecision {
    pub route_to_new_version: bool,
    pub old_version_weight: u8,
    pub new_version_weight: u8,
}

/// Agent runtime manager interface
#[async_trait::async_trait]
pub trait RuntimeManager {
    /// Create a new agent instance with WASM module
    async fn create_instance(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
        wasm_bytes: &[u8],
    ) -> Result<(), HotReloadError>;

    /// Stop an agent instance
    async fn stop_instance(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
    ) -> Result<(), HotReloadError>;

    /// Get instance metrics
    async fn get_instance_metrics(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
    ) -> Result<(usize, u64, u64), HotReloadError>; // (memory, fuel, requests)

    /// Preserve agent state
    async fn preserve_state(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
    ) -> Result<Vec<u8>, HotReloadError>;

    /// Restore agent state
    async fn restore_state(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
        state_data: &[u8],
    ) -> Result<(), HotReloadError>;

    /// Check if instance is healthy
    async fn health_check(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
    ) -> Result<bool, HotReloadError>;
}

/// Traffic routing manager interface
#[async_trait::async_trait]
pub trait TrafficRouter {
    /// Route traffic between agent versions
    async fn set_traffic_split(
        &self,
        agent_id: AgentId,
        old_version: AgentVersion,
        new_version: AgentVersion,
        split_percentage: TrafficSplitPercentage,
    ) -> Result<(), HotReloadError>;

    /// Get current traffic distribution
    async fn get_traffic_split(
        &self,
        agent_id: AgentId,
    ) -> Result<TrafficSplitPercentage, HotReloadError>;

    /// Switch all traffic to new version
    async fn switch_traffic(
        &self,
        agent_id: AgentId,
        target_version: AgentVersion,
    ) -> Result<(), HotReloadError>;
}

/// Core hot reload manager implementation
pub struct CaxtonHotReloadManager {
    /// Active hot reload operations
    active_reloads: Arc<RwLock<HashMap<HotReloadId, HotReloadContext>>>,
    /// Version snapshots for rollback
    version_snapshots: Arc<RwLock<HashMap<AgentId, Vec<VersionSnapshot>>>>,
    /// Preserved state data
    preserved_states: Arc<Mutex<HashMap<AgentId, PreservedState>>>,
    /// Runtime manager for agent instances
    runtime_manager: Arc<dyn RuntimeManager + Send + Sync>,
    /// Traffic router for managing traffic splits
    traffic_router: Arc<dyn TrafficRouter + Send + Sync>,
    /// Time provider for testable time operations
    time_provider: SharedTimeProvider,
    /// Maximum concurrent hot reloads
    max_concurrent_reloads: usize,
    /// Default operation timeout
    default_timeout: Duration,
}

impl CaxtonHotReloadManager {
    /// Creates a new hot reload manager
    pub fn new(
        runtime_manager: Arc<dyn RuntimeManager + Send + Sync>,
        traffic_router: Arc<dyn TrafficRouter + Send + Sync>,
    ) -> Self {
        Self::with_time_provider(runtime_manager, traffic_router, production_time_provider())
    }

    /// Creates a new hot reload manager with custom time provider
    pub fn with_time_provider(
        runtime_manager: Arc<dyn RuntimeManager + Send + Sync>,
        traffic_router: Arc<dyn TrafficRouter + Send + Sync>,
        time_provider: SharedTimeProvider,
    ) -> Self {
        Self {
            active_reloads: Arc::new(RwLock::new(HashMap::new())),
            version_snapshots: Arc::new(RwLock::new(HashMap::new())),
            preserved_states: Arc::new(Mutex::new(HashMap::new())),
            runtime_manager,
            traffic_router,
            time_provider,
            max_concurrent_reloads: 5,
            default_timeout: Duration::from_secs(300), // 5 minutes
        }
    }

    /// Creates hot reload manager with custom settings
    pub fn with_limits(
        runtime_manager: Arc<dyn RuntimeManager + Send + Sync>,
        traffic_router: Arc<dyn TrafficRouter + Send + Sync>,
        max_concurrent: usize,
        timeout: Duration,
    ) -> Self {
        Self::with_limits_and_time_provider(
            runtime_manager,
            traffic_router,
            max_concurrent,
            timeout,
            production_time_provider(),
        )
    }

    /// Creates hot reload manager with custom settings and time provider
    pub fn with_limits_and_time_provider(
        runtime_manager: Arc<dyn RuntimeManager + Send + Sync>,
        traffic_router: Arc<dyn TrafficRouter + Send + Sync>,
        max_concurrent: usize,
        timeout: Duration,
        time_provider: SharedTimeProvider,
    ) -> Self {
        Self {
            active_reloads: Arc::new(RwLock::new(HashMap::new())),
            version_snapshots: Arc::new(RwLock::new(HashMap::new())),
            preserved_states: Arc::new(Mutex::new(HashMap::new())),
            runtime_manager,
            traffic_router,
            time_provider,
            max_concurrent_reloads: max_concurrent,
            default_timeout: timeout,
        }
    }

    /// Check if hot reload limit is reached
    async fn check_reload_limit(&self) -> Result<(), HotReloadError> {
        let active = self.active_reloads.read().await;
        if active.len() >= self.max_concurrent_reloads {
            return Err(HotReloadError::InsufficientResources);
        }
        Ok(())
    }

    /// Execute hot reload based on strategy
    async fn execute_hot_reload_strategy(
        &self,
        mut context: HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        match context.request.config.strategy {
            HotReloadStrategy::Graceful => self.execute_graceful_reload(&mut context).await,
            HotReloadStrategy::Immediate => self.execute_immediate_reload(&mut context).await,
            HotReloadStrategy::Parallel => self.execute_parallel_reload(&mut context).await,
            HotReloadStrategy::TrafficSplitting => {
                self.execute_traffic_splitting_reload(&mut context).await
            }
        }
    }

    /// Execute graceful hot reload (drain requests then switch)
    async fn execute_graceful_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        info!(
            "Executing graceful hot reload for agent {}",
            context.request.agent_id
        );

        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        // Step 1: Create snapshot of current version
        context.status = HotReloadStatus::Preparing;
        self.create_version_snapshot(agent_id, old_version, context)
            .await?;

        // Step 2: Preserve state if requested
        if context.request.preserve_state {
            let state_data = self
                .runtime_manager
                .preserve_state(agent_id, old_version)
                .await?;

            let preserved_state = PreservedState {
                agent_id,
                state_data,
                preserved_at: SystemTime::now(),
            };

            let mut states = self.preserved_states.lock().await;
            states.insert(agent_id, preserved_state);
        }

        // Step 3: Create new instance
        context.status = HotReloadStatus::Starting;
        self.runtime_manager
            .create_instance(agent_id, new_version, &context.request.new_wasm_module)
            .await?;

        // Step 4: Warmup period
        if context.request.config.warmup_duration > Duration::from_secs(0) {
            info!(
                "Warming up new version for {:?}",
                context.request.config.warmup_duration
            );
            self.time_provider
                .sleep(context.request.config.warmup_duration)
                .await;
        }
        context.warmup_completed = true;

        // Step 5: Health check new version
        if !self
            .runtime_manager
            .health_check(agent_id, new_version)
            .await?
        {
            return Err(HotReloadError::StatePreservationFailed {
                reason: "New version failed health check".to_string(),
            });
        }

        // Step 6: Restore state if preserved
        if context.request.preserve_state {
            let states = self.preserved_states.lock().await;
            if let Some(preserved) = states.get(&agent_id) {
                self.runtime_manager
                    .restore_state(agent_id, new_version, &preserved.state_data)
                    .await?;
            }
        }

        // Step 7: Drain old version
        context.status = HotReloadStatus::InProgress;

        if self.time_provider.should_skip_delays() {
            debug!("Skipping drain wait in test mode");
        } else {
            info!(
                "Draining old version for {:?}",
                context.request.config.drain_timeout.as_duration()
            );
            let drain_start = self.time_provider.instant();
            let drain_duration = context.request.config.drain_timeout.as_duration();

            // Wait for drain to complete or timeout
            while drain_start.elapsed() < drain_duration {
                // In a real implementation, we'd check if there are pending requests
                // For now, we'll just wait with small increments
                self.time_provider.sleep(Duration::from_millis(100)).await;

                // Check if drain is complete (placeholder for real implementation)
                // if self.is_drain_complete(agent_id, old_version).await { break; }
            }
        }

        // Step 8: Switch traffic to new version
        self.traffic_router
            .switch_traffic(agent_id, new_version)
            .await?;

        // Step 9: Stop old version
        self.runtime_manager
            .stop_instance(agent_id, old_version)
            .await?;

        context.status = HotReloadStatus::Completed;

        // Collect final metrics
        self.update_metrics(context).await?;

        Ok(HotReloadResult::success(
            context.request.reload_id,
            agent_id,
            old_version,
            new_version,
            context.started_at,
            Some(context.metrics.clone()),
            context.version_snapshots.clone(),
        ))
    }

    /// Execute immediate hot reload (terminate old, start new)
    async fn execute_immediate_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        info!(
            "Executing immediate hot reload for agent {}",
            context.request.agent_id
        );

        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        // Step 1: Create version snapshot
        context.status = HotReloadStatus::Preparing;
        self.create_version_snapshot(agent_id, old_version, context)
            .await?;

        // Step 2: Create new instance first (before stopping old one)
        context.status = HotReloadStatus::Starting;
        self.runtime_manager
            .create_instance(agent_id, new_version, &context.request.new_wasm_module)
            .await?;

        // Step 3: Switch traffic to new version
        context.status = HotReloadStatus::InProgress;
        self.traffic_router
            .switch_traffic(agent_id, new_version)
            .await?;

        // Step 4: Stop old version (only after new one is running)
        self.runtime_manager
            .stop_instance(agent_id, old_version)
            .await?;

        // Step 5: Health check
        if !self
            .runtime_manager
            .health_check(agent_id, new_version)
            .await?
        {
            warn!("New version failed health check, but immediate reload cannot rollback");
        }

        context.status = HotReloadStatus::Completed;

        // Collect metrics
        self.update_metrics(context).await?;

        Ok(HotReloadResult::success(
            context.request.reload_id,
            agent_id,
            old_version,
            new_version,
            context.started_at,
            Some(context.metrics.clone()),
            context.version_snapshots.clone(),
        ))
    }

    /// Execute parallel hot reload (run both versions simultaneously)
    async fn execute_parallel_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        info!(
            "Executing parallel hot reload for agent {}",
            context.request.agent_id
        );

        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        // Step 1: Create version snapshot
        context.status = HotReloadStatus::Preparing;
        self.create_version_snapshot(agent_id, old_version, context)
            .await?;

        // Step 2: Create new instance alongside old one
        context.status = HotReloadStatus::Starting;
        self.runtime_manager
            .create_instance(agent_id, new_version, &context.request.new_wasm_module)
            .await?;

        // Step 3: Warmup new version
        if context.request.config.warmup_duration > Duration::from_secs(0) {
            self.time_provider
                .sleep(context.request.config.warmup_duration)
                .await;
        }
        context.warmup_completed = true;

        // Step 4: Health check new version
        if !self
            .runtime_manager
            .health_check(agent_id, new_version)
            .await?
        {
            // Rollback by stopping new version
            self.runtime_manager
                .stop_instance(agent_id, new_version)
                .await?;
            return Err(HotReloadError::AutomaticRollback {
                reason: "New version failed health check".to_string(),
            });
        }

        // Step 5: Run both versions in parallel for monitoring
        context.status = HotReloadStatus::InProgress;

        // Monitor both versions for a period
        let monitoring_duration = if self.time_provider.should_skip_delays() {
            Duration::from_millis(1) // Skip monitoring in tests
        } else {
            Duration::from_secs(60) // 1 minute monitoring in production
        };
        let monitor_start = SystemTime::now();

        while monitor_start.elapsed().unwrap_or_default() < monitoring_duration {
            // Collect metrics from both versions
            self.update_metrics(context).await?;

            // Check if rollback is needed
            if context
                .request
                .config
                .rollback_capability
                .should_trigger_rollback(&context.metrics)
            {
                warn!("Automatic rollback triggered during parallel execution");
                self.runtime_manager
                    .stop_instance(agent_id, new_version)
                    .await?;
                return Err(HotReloadError::AutomaticRollback {
                    reason: "Metrics triggered automatic rollback".to_string(),
                });
            }

            let check_interval = if self.time_provider.should_skip_delays() {
                Duration::from_millis(1)
            } else {
                Duration::from_secs(5)
            };
            self.time_provider.sleep(check_interval).await;
        }

        // Step 6: Switch traffic to new version
        self.traffic_router
            .switch_traffic(agent_id, new_version)
            .await?;

        // Step 7: Stop old version
        self.runtime_manager
            .stop_instance(agent_id, old_version)
            .await?;

        context.status = HotReloadStatus::Completed;

        Ok(HotReloadResult::success(
            context.request.reload_id,
            agent_id,
            old_version,
            new_version,
            context.started_at,
            Some(context.metrics.clone()),
            context.version_snapshots.clone(),
        ))
    }

    /// Execute traffic splitting hot reload (gradual traffic shift)
    async fn execute_traffic_splitting_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        self.prepare_traffic_splitting_reload(context).await?;
        self.execute_gradual_traffic_split(context).await?;
        self.finalize_traffic_splitting_reload(context).await
    }

    /// Prepare new version for traffic splitting
    async fn prepare_traffic_splitting_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<(), HotReloadError> {
        info!(
            "Executing traffic splitting hot reload for agent {}",
            context.request.agent_id
        );

        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        // Step 1: Create version snapshot
        context.status = HotReloadStatus::Preparing;
        self.create_version_snapshot(agent_id, old_version, context)
            .await?;

        // Step 2: Create new instance
        context.status = HotReloadStatus::Starting;
        self.runtime_manager
            .create_instance(agent_id, new_version, &context.request.new_wasm_module)
            .await?;

        // Step 3: Warmup
        if context.request.config.warmup_duration > Duration::from_secs(0) {
            self.time_provider
                .sleep(context.request.config.warmup_duration)
                .await;
        }
        context.warmup_completed = true;

        // Step 4: Health check
        if !self
            .runtime_manager
            .health_check(agent_id, new_version)
            .await?
        {
            self.runtime_manager
                .stop_instance(agent_id, new_version)
                .await?;
            return Err(HotReloadError::AutomaticRollback {
                reason: "New version failed initial health check".to_string(),
            });
        }

        context.status = HotReloadStatus::InProgress;
        Ok(())
    }

    /// Execute gradual traffic split with monitoring
    async fn execute_gradual_traffic_split(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<(), HotReloadError> {
        let traffic_steps = if context.request.config.progressive_rollout {
            vec![5, 10, 25, 50, 75, 100]
        } else {
            vec![context.request.config.traffic_split.as_percentage()]
        };

        for (i, percentage) in traffic_steps.iter().enumerate() {
            self.execute_traffic_split_step(context, *percentage, i, traffic_steps.len())
                .await?;
        }
        Ok(())
    }

    /// Execute a single traffic split step
    async fn execute_traffic_split_step(
        &self,
        context: &mut HotReloadContext,
        percentage: u8,
        step_index: usize,
        total_steps: usize,
    ) -> Result<(), HotReloadError> {
        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        let split_percentage = TrafficSplitPercentage::try_new(percentage).map_err(|_| {
            HotReloadError::TrafficSplittingFailed {
                reason: "Invalid traffic percentage".to_string(),
            }
        })?;

        info!("Setting traffic split to {}% for new version", percentage);

        self.traffic_router
            .set_traffic_split(agent_id, old_version, new_version, split_percentage)
            .await?;

        context.current_traffic_split = split_percentage;

        self.monitor_traffic_split_step(context, percentage).await?;

        if step_index < total_steps - 1 {
            info!(
                "Traffic split at {}% successful, proceeding to next step",
                percentage
            );
        }
        Ok(())
    }

    /// Monitor a traffic split step for rollback conditions
    async fn monitor_traffic_split_step(
        &self,
        context: &mut HotReloadContext,
        percentage: u8,
    ) -> Result<(), HotReloadError> {
        let monitor_duration = if self.time_provider.should_skip_delays() {
            Duration::from_millis(1)
        } else {
            Duration::from_secs(30)
        };
        let step_start = SystemTime::now();

        while step_start.elapsed().unwrap_or_default() < monitor_duration {
            self.update_metrics(context).await?;

            if context
                .request
                .config
                .rollback_capability
                .should_trigger_rollback(&context.metrics)
            {
                self.handle_automatic_rollback(context, percentage).await?;
            }

            let check_interval = if self.time_provider.should_skip_delays() {
                Duration::from_millis(1)
            } else {
                Duration::from_secs(5)
            };
            self.time_provider.sleep(check_interval).await;
        }
        Ok(())
    }

    /// Handle automatic rollback during traffic splitting
    async fn handle_automatic_rollback(
        &self,
        context: &mut HotReloadContext,
        percentage: u8,
    ) -> Result<(), HotReloadError> {
        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        warn!("Automatic rollback triggered at {}% traffic", percentage);

        let zero_split = TrafficSplitPercentage::try_new(0).unwrap();
        self.traffic_router
            .set_traffic_split(agent_id, old_version, new_version, zero_split)
            .await?;

        self.runtime_manager
            .stop_instance(agent_id, new_version)
            .await?;

        Err(HotReloadError::AutomaticRollback {
            reason: format!("Rollback triggered at {percentage}% traffic"),
        })
    }

    /// Finalize traffic splitting reload by switching remaining traffic and cleanup
    async fn finalize_traffic_splitting_reload(
        &self,
        context: &mut HotReloadContext,
    ) -> Result<HotReloadResult, HotReloadError> {
        let agent_id = context.request.agent_id;
        let old_version = context.request.from_version;
        let new_version = context.request.to_version;

        // Complete rollout - switch traffic and stop old version
        self.traffic_router
            .switch_traffic(agent_id, new_version)
            .await?;

        self.runtime_manager
            .stop_instance(agent_id, old_version)
            .await?;

        context.status = HotReloadStatus::Completed;

        Ok(HotReloadResult::success(
            context.request.reload_id,
            agent_id,
            old_version,
            new_version,
            context.started_at,
            Some(context.metrics.clone()),
            context.version_snapshots.clone(),
        ))
    }

    /// Create version snapshot for rollback capability
    async fn create_version_snapshot(
        &self,
        agent_id: AgentId,
        version: AgentVersion,
        context: &mut HotReloadContext,
    ) -> Result<(), HotReloadError> {
        debug!(
            "Creating version snapshot for agent {} version {}",
            agent_id, version
        );

        // Get current metrics
        let (memory, fuel, requests) = self
            .runtime_manager
            .get_instance_metrics(agent_id, version)
            .await?;

        let snapshot = VersionSnapshot {
            version,
            version_number: context.request.to_version_number,
            wasm_module: context.request.new_wasm_module.clone(),
            created_at: SystemTime::now(),
            resource_usage: ResourceUsageSnapshot {
                memory_allocated: memory,
                fuel_consumed: fuel,
                requests_handled: requests,
                average_response_time_ms: 100, // Would be calculated from actual metrics
            },
        };

        context.version_snapshots.push(snapshot.clone());

        // Store in global snapshots
        let mut snapshots = self.version_snapshots.write().await;
        let agent_snapshots = snapshots.entry(agent_id).or_insert_with(Vec::new);
        agent_snapshots.push(snapshot);

        // Keep only the configured number of snapshots
        let max_snapshots = context
            .request
            .config
            .rollback_capability
            .preserve_previous_versions as usize;
        if agent_snapshots.len() > max_snapshots {
            agent_snapshots.drain(0..agent_snapshots.len() - max_snapshots);
        }

        Ok(())
    }

    /// Update metrics during hot reload
    async fn update_metrics(&self, context: &mut HotReloadContext) -> Result<(), HotReloadError> {
        let agent_id = context.request.agent_id;
        let new_version = context.request.to_version;

        // Get metrics from new version
        if let Ok((memory, _fuel, requests)) = self
            .runtime_manager
            .get_instance_metrics(agent_id, new_version)
            .await
        {
            // Update context metrics (simplified)
            context.metrics.memory_usage_peak = context.metrics.memory_usage_peak.max(memory);
            context.metrics.requests_processed = requests;

            // Health check
            if let Ok(healthy) = self
                .runtime_manager
                .health_check(agent_id, new_version)
                .await
            {
                context.metrics.health_check_success_rate = if healthy { 100.0 } else { 0.0 };
            }

            context.metrics.collected_at = SystemTime::now();
        }

        Ok(())
    }
}

#[async_trait::async_trait]
impl HotReloadManager for CaxtonHotReloadManager {
    /// Perform hot reload of agent WASM module
    async fn hot_reload_agent(
        &self,
        request: HotReloadRequest,
    ) -> std::result::Result<HotReloadResult, HotReloadError> {
        info!(
            "Starting hot reload for agent {} with strategy {:?}",
            request.agent_id, request.config.strategy
        );

        // Check reload limits
        self.check_reload_limit().await?;

        // Validate request
        request.validate()?;

        // Create hot reload context
        let context = HotReloadContext {
            request: request.clone(),
            started_at: SystemTime::now(),
            status: HotReloadStatus::Pending,
            metrics: ReloadMetrics::new(),
            current_traffic_split: request.config.traffic_split,
            version_snapshots: Vec::new(),
            warmup_completed: false,
        };

        // Track active reload
        {
            let mut active = self.active_reloads.write().await;
            active.insert(request.reload_id, context.clone());
        }

        // Execute hot reload strategy
        let result = timeout(
            self.default_timeout,
            self.execute_hot_reload_strategy(context),
        )
        .await
        .map_err(|_| HotReloadError::TimeoutExceeded {
            timeout: u64::try_from(self.default_timeout.as_millis()).unwrap_or(u64::MAX),
        })?;

        // Remove from active reloads
        {
            let mut active = self.active_reloads.write().await;
            active.remove(&request.reload_id);
        }

        match &result {
            Ok(reload_result) => {
                info!(
                    "Hot reload completed successfully for agent {} in {:?}",
                    request.agent_id,
                    reload_result.duration().unwrap_or_default()
                );
            }
            Err(e) => {
                error!("Hot reload failed for agent {}: {}", request.agent_id, e);
            }
        }

        result
    }

    /// Get hot reload status
    async fn get_hot_reload_status(
        &self,
        reload_id: HotReloadId,
    ) -> std::result::Result<HotReloadStatus, HotReloadError> {
        let active = self.active_reloads.read().await;
        if let Some(context) = active.get(&reload_id) {
            Ok(context.status)
        } else {
            // Not in active reloads, assume completed
            Ok(HotReloadStatus::Completed)
        }
    }

    /// Cancel active hot reload
    async fn cancel_hot_reload(
        &self,
        reload_id: HotReloadId,
    ) -> std::result::Result<(), HotReloadError> {
        let mut active = self.active_reloads.write().await;

        if let Some(context) = active.remove(&reload_id) {
            info!("Cancelling hot reload {}", reload_id);

            // Stop new instance if it was created
            if let Err(e) = self
                .runtime_manager
                .stop_instance(context.request.agent_id, context.request.to_version)
                .await
            {
                warn!("Failed to stop new instance during cancellation: {}", e);
            }

            // Reset traffic to old version
            if let Err(e) = self
                .traffic_router
                .switch_traffic(context.request.agent_id, context.request.from_version)
                .await
            {
                warn!("Failed to reset traffic during cancellation: {}", e);
            }

            Ok(())
        } else {
            Err(HotReloadError::AlreadyInProgress { reload_id })
        }
    }

    /// Rollback hot reload to previous version
    async fn rollback_hot_reload(
        &self,
        reload_id: HotReloadId,
        target_version: AgentVersion,
    ) -> std::result::Result<HotReloadResult, HotReloadError> {
        info!(
            "Rolling back hot reload {} to version {}",
            reload_id, target_version
        );

        let active = self.active_reloads.read().await;

        if let Some(context) = active.get(&reload_id) {
            let agent_id = context.request.agent_id;

            // Find the target version snapshot
            let snapshots = self.version_snapshots.read().await;
            let agent_snapshots =
                snapshots
                    .get(&agent_id)
                    .ok_or(HotReloadError::VersionNotFound {
                        version: target_version,
                    })?;

            let target_snapshot = agent_snapshots
                .iter()
                .find(|s| s.version == target_version)
                .ok_or(HotReloadError::VersionNotFound {
                    version: target_version,
                })?;

            // Stop current version
            self.runtime_manager
                .stop_instance(agent_id, context.request.to_version)
                .await
                .map_err(|e| HotReloadError::RollbackFailed {
                    reason: format!("Failed to stop current version: {e}"),
                })?;

            // Deploy target version
            self.runtime_manager
                .create_instance(agent_id, target_version, &target_snapshot.wasm_module)
                .await
                .map_err(|e| HotReloadError::RollbackFailed {
                    reason: format!("Failed to create target version instance: {e}"),
                })?;

            // Switch traffic
            self.traffic_router
                .switch_traffic(agent_id, target_version)
                .await
                .map_err(|e| HotReloadError::RollbackFailed {
                    reason: format!("Failed to switch traffic: {e}"),
                })?;

            Ok(HotReloadResult::rollback(
                reload_id,
                agent_id,
                context.request.from_version,
                context.request.to_version,
                Some(context.started_at),
                format!("Rolled back to version {target_version}"),
                Some(context.metrics.clone()),
            ))
        } else {
            Err(HotReloadError::AlreadyInProgress { reload_id })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::TrafficSplitPercentage;
    use std::sync::atomic::{AtomicBool, Ordering};

    // Mock implementations for testing
    struct MockRuntimeManager {
        should_succeed: Arc<AtomicBool>,
    }

    #[async_trait::async_trait]
    impl RuntimeManager for MockRuntimeManager {
        async fn create_instance(
            &self,
            _: AgentId,
            _: AgentVersion,
            _: &[u8],
        ) -> Result<(), HotReloadError> {
            if self.should_succeed.load(Ordering::SeqCst) {
                Ok(())
            } else {
                Err(HotReloadError::StatePreservationFailed {
                    reason: "Mock creation failure".to_string(),
                })
            }
        }

        async fn stop_instance(&self, _: AgentId, _: AgentVersion) -> Result<(), HotReloadError> {
            Ok(())
        }

        async fn get_instance_metrics(
            &self,
            _: AgentId,
            _: AgentVersion,
        ) -> Result<(usize, u64, u64), HotReloadError> {
            Ok((1024, 1000, 100))
        }

        async fn preserve_state(
            &self,
            _: AgentId,
            _: AgentVersion,
        ) -> Result<Vec<u8>, HotReloadError> {
            Ok(vec![1, 2, 3, 4])
        }

        async fn restore_state(
            &self,
            _: AgentId,
            _: AgentVersion,
            _: &[u8],
        ) -> Result<(), HotReloadError> {
            Ok(())
        }

        async fn health_check(&self, _: AgentId, _: AgentVersion) -> Result<bool, HotReloadError> {
            Ok(self.should_succeed.load(Ordering::SeqCst))
        }
    }

    struct MockTrafficRouter;

    #[async_trait::async_trait]
    impl TrafficRouter for MockTrafficRouter {
        async fn set_traffic_split(
            &self,
            _: AgentId,
            _: AgentVersion,
            _: AgentVersion,
            _: TrafficSplitPercentage,
        ) -> Result<(), HotReloadError> {
            Ok(())
        }

        async fn get_traffic_split(
            &self,
            _: AgentId,
        ) -> Result<TrafficSplitPercentage, HotReloadError> {
            Ok(TrafficSplitPercentage::half())
        }

        async fn switch_traffic(&self, _: AgentId, _: AgentVersion) -> Result<(), HotReloadError> {
            Ok(())
        }
    }

    fn create_test_hot_reload_manager() -> CaxtonHotReloadManager {
        let runtime_manager = Arc::new(MockRuntimeManager {
            should_succeed: Arc::new(AtomicBool::new(true)),
        });
        let traffic_router = Arc::new(MockTrafficRouter);

        CaxtonHotReloadManager::new(runtime_manager, traffic_router)
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "Slow test - involves sleep operations"]
    async fn test_graceful_hot_reload() {
        let manager = create_test_hot_reload_manager();

        let mut config = HotReloadConfig::graceful();
        // Reduce timeouts for testing
        config.warmup_duration = Duration::from_millis(1);

        let request = HotReloadRequest::new(
            AgentId::generate(),
            None,
            AgentVersion::generate(),
            AgentVersion::generate(),
            VersionNumber::first().next().unwrap(),
            config,
            vec![5, 6, 7, 8],
        );

        let result =
            tokio::time::timeout(Duration::from_secs(1), manager.hot_reload_agent(request)).await;
        assert!(result.is_ok());
        let inner_result = result.unwrap();
        assert!(inner_result.is_ok());
    }

    #[tokio::test]
    async fn test_immediate_hot_reload() {
        let manager = create_test_hot_reload_manager();

        let mut config = HotReloadConfig::immediate();
        // Reduce warmup for testing
        config.warmup_duration = Duration::from_millis(1);

        let request = HotReloadRequest::new(
            AgentId::generate(),
            None,
            AgentVersion::generate(),
            AgentVersion::generate(),
            VersionNumber::first().next().unwrap(),
            config,
            vec![5, 6, 7, 8],
        );

        let result = manager.hot_reload_agent(request).await;
        assert!(result.is_ok());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "Slow test - involves sleep operations"]
    async fn test_traffic_splitting_hot_reload() {
        let manager = create_test_hot_reload_manager();

        let traffic_split = TrafficSplitPercentage::try_new(25).unwrap();
        let mut config = HotReloadConfig::traffic_splitting(traffic_split);
        // Reduce timeouts for testing
        config.warmup_duration = Duration::from_millis(1);

        let request = HotReloadRequest::new(
            AgentId::generate(),
            None,
            AgentVersion::generate(),
            AgentVersion::generate(),
            VersionNumber::first().next().unwrap(),
            config,
            vec![5, 6, 7, 8],
        );

        let result =
            tokio::time::timeout(Duration::from_secs(1), manager.hot_reload_agent(request)).await;
        assert!(result.is_ok());
        let inner_result = result.unwrap();
        assert!(inner_result.is_ok());
    }

    #[tokio::test]
    async fn test_hot_reload_status() {
        let manager = create_test_hot_reload_manager();
        let reload_id = HotReloadId::generate();

        // Non-existent reload should return completed
        let status = manager.get_hot_reload_status(reload_id).await;
        assert!(status.is_ok());
        assert_eq!(status.unwrap(), HotReloadStatus::Completed);
    }

    #[tokio::test]
    async fn test_hot_reload_cancellation() {
        let manager = create_test_hot_reload_manager();
        let reload_id = HotReloadId::generate();

        // Cancelling non-existent reload should return error
        let result = manager.cancel_hot_reload(reload_id).await;
        assert!(result.is_err());
    }
}