Skip to main content

sublinear_solver/temporal_nexus/core/
scheduler.rs

1//! Main NanosecondScheduler implementation for temporal consciousness
2//!
3//! This module provides the core scheduling functionality that manages temporal consciousness
4//! operations at nanosecond precision while maintaining identity continuity and temporal coherence.
5
6use std::cmp::Ordering;
7use std::collections::{BinaryHeap, VecDeque};
8use std::sync::{Arc, Mutex};
9use std::time::Instant;
10
11use super::{
12    ConsciousnessTask, ContinuityMetrics, ContractionMetrics, IdentityContinuityTracker,
13    StrangeLoopOperator, TemporalConfig, TemporalError, TemporalResult, TscTimestamp,
14    WindowOverlapManager,
15};
16
17// Import quantum validation when available
18use crate::temporal_nexus::quantum::{QuantumValidator, ValidationResult};
19
20/// Scheduled task with timing information
21#[derive(Debug, Clone)]
22struct ScheduledTask {
23    task: ConsciousnessTask,
24    scheduled_at: TscTimestamp,
25    deadline: TscTimestamp,
26    priority: u8,
27    id: u64,
28}
29
30impl PartialEq for ScheduledTask {
31    fn eq(&self, other: &Self) -> bool {
32        self.priority == other.priority && self.scheduled_at == other.scheduled_at
33    }
34}
35
36impl Eq for ScheduledTask {}
37
38impl PartialOrd for ScheduledTask {
39    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
40        Some(self.cmp(other))
41    }
42}
43
44impl Ord for ScheduledTask {
45    fn cmp(&self, other: &Self) -> Ordering {
46        // Higher priority and earlier deadline first (reverse order for max-heap behavior)
47        other
48            .priority
49            .cmp(&self.priority)
50            .then_with(|| self.deadline.cmp(&other.deadline))
51    }
52}
53
54/// Performance metrics for the nanosecond scheduler
55#[derive(Debug, Clone, Default)]
56pub struct SchedulerMetrics {
57    pub total_ticks: u64,
58    pub tasks_scheduled: u64,
59    pub tasks_completed: u64,
60    pub avg_scheduling_overhead_ns: f64,
61    pub max_scheduling_overhead_ns: u64,
62    pub window_overlap_percentage: f64,
63    pub contraction_convergence_rate: f64,
64    pub identity_continuity_score: f64,
65    pub temporal_advantage_ns: u64,
66
67    // Quantum validation metrics
68    pub quantum_validity_rate: f64,
69    pub avg_quantum_energy_j: f64,
70    pub avg_margolus_levitin_margin: f64,
71    pub avg_uncertainty_margin: f64,
72    pub avg_coherence_preservation: f64,
73    pub avg_entanglement_strength: f64,
74}
75
76/// Main nanosecond scheduler for temporal consciousness
77pub struct NanosecondScheduler {
78    config: TemporalConfig,
79    task_queue: BinaryHeap<ScheduledTask>,
80    completed_tasks: VecDeque<ScheduledTask>,
81    next_task_id: u64,
82    current_tick: u64,
83    start_time: Instant,
84    tsc_start: TscTimestamp,
85
86    // Component managers
87    window_manager: WindowOverlapManager,
88    strange_loop: StrangeLoopOperator,
89    identity_tracker: IdentityContinuityTracker,
90
91    // Quantum validation
92    quantum_validator: QuantumValidator,
93    quantum_validations: VecDeque<ValidationResult>,
94
95    // Metrics tracking
96    metrics: SchedulerMetrics,
97    overhead_measurements: VecDeque<u64>,
98
99    // Memory persistence state
100    memory_state: Arc<Mutex<Vec<u8>>>,
101}
102
103impl NanosecondScheduler {
104    /// Create a new nanosecond scheduler with default configuration
105    pub fn new() -> Self {
106        Self::with_config(TemporalConfig::default())
107    }
108
109    /// Create a new nanosecond scheduler with custom configuration
110    pub fn with_config(config: TemporalConfig) -> Self {
111        let now = Instant::now();
112        let tsc_now = TscTimestamp::now();
113
114        Self {
115            config: config.clone(),
116            task_queue: BinaryHeap::new(),
117            completed_tasks: VecDeque::new(),
118            next_task_id: 1,
119            current_tick: 0,
120            start_time: now,
121            tsc_start: tsc_now,
122
123            window_manager: WindowOverlapManager::new(config.window_overlap_percent),
124            strange_loop: StrangeLoopOperator::new(
125                config.lipschitz_bound,
126                config.max_contraction_iterations,
127            ),
128            identity_tracker: IdentityContinuityTracker::new(),
129
130            // Initialize quantum validator
131            quantum_validator: QuantumValidator::new(),
132            quantum_validations: VecDeque::with_capacity(1000),
133
134            metrics: SchedulerMetrics::default(),
135            overhead_measurements: VecDeque::with_capacity(1000),
136            memory_state: Arc::new(Mutex::new(Vec::new())),
137        }
138    }
139
140    /// Process one nanosecond tick
141    pub fn tick(&mut self) -> TemporalResult<()> {
142        let tick_start = TscTimestamp::now();
143        self.current_tick += 1;
144        self.metrics.total_ticks += 1;
145
146        // Perform quantum validation for nanosecond operation
147        let tick_duration_s = 1e-9; // 1 nanosecond
148        let estimated_energy_j = 1e-15; // 1 femtojoule - conservative estimate
149        self.validate_quantum_operation(tick_duration_s, estimated_energy_j)?;
150
151        // Update temporal window
152        self.window_manager.advance_window(self.current_tick)?;
153
154        // Process due tasks
155        self.process_due_tasks(tick_start)?;
156
157        // Update strange loop operator
158        let contraction_result = self
159            .strange_loop
160            .process_iteration(self.current_tick as f64, &self.get_current_state_vector()?)?;
161
162        // Update identity continuity
163        self.identity_tracker
164            .track_continuity(tick_start, &self.get_identity_state()?)?;
165
166        // Calculate and record overhead
167        let tick_end = TscTimestamp::now();
168        let overhead_ns = tick_end.nanos_since(tick_start, self.config.tsc_frequency_hz);
169        self.record_overhead(overhead_ns)?;
170
171        // Update metrics
172        self.update_metrics(contraction_result)?;
173
174        Ok(())
175    }
176
177    /// Schedule a consciousness task for execution
178    pub fn schedule_task(
179        &mut self,
180        task: ConsciousnessTask,
181        delay_ns: u64,
182        deadline_ns: u64,
183    ) -> TemporalResult<u64> {
184        let now = TscTimestamp::now();
185        let scheduled_at = now.add_nanos(delay_ns, self.config.tsc_frequency_hz);
186        let deadline = now.add_nanos(deadline_ns, self.config.tsc_frequency_hz);
187
188        let priority = match &task {
189            ConsciousnessTask::IdentityPreservation { .. } => 255, // Highest priority
190            ConsciousnessTask::StrangeLoopProcessing { .. } => 200,
191            ConsciousnessTask::WindowManagement { .. } => 150,
192            ConsciousnessTask::MemoryIntegration { .. } => 100,
193            ConsciousnessTask::Perception { priority, .. } => *priority,
194        };
195
196        let task_id = self.next_task_id;
197        self.next_task_id += 1;
198
199        let scheduled_task = ScheduledTask {
200            task,
201            scheduled_at,
202            deadline,
203            priority,
204            id: task_id,
205        };
206
207        // Check for queue overflow
208        if self.task_queue.len() >= 10000 {
209            return Err(TemporalError::TaskQueueOverflow {
210                current_size: self.task_queue.len(),
211                max_size: 10000,
212            });
213        }
214
215        self.task_queue.push(scheduled_task);
216        self.metrics.tasks_scheduled += 1;
217
218        Ok(task_id)
219    }
220
221    /// Measure identity continuity over recent history
222    pub fn measure_continuity(&self) -> TemporalResult<ContinuityMetrics> {
223        self.identity_tracker.get_metrics()
224    }
225
226    /// Calculate temporal advantage (lookahead window)
227    pub fn get_temporal_advantage(&self) -> u64 {
228        let window_info = self.window_manager.get_current_window();
229        let overlap_ticks = window_info.overlap_size;
230        let advantage_ns = (overlap_ticks * 1_000_000_000) / self.config.tsc_frequency_hz;
231
232        self.metrics.temporal_advantage_ns.max(advantage_ns)
233    }
234
235    /// Get current scheduler metrics
236    pub fn get_metrics(&self) -> &SchedulerMetrics {
237        &self.metrics
238    }
239
240    /// Export memory state for MCP integration
241    pub fn export_memory_state(&self) -> TemporalResult<Vec<u8>> {
242        let state = self
243            .memory_state
244            .lock()
245            .map_err(|e| TemporalError::TscTimingError {
246                message: format!("Memory lock error: {}", e),
247            })?;
248        Ok(state.clone())
249    }
250
251    /// Import memory state from MCP integration
252    pub fn import_memory_state(&mut self, state: Vec<u8>) -> TemporalResult<()> {
253        let mut memory = self
254            .memory_state
255            .lock()
256            .map_err(|e| TemporalError::TscTimingError {
257                message: format!("Memory lock error: {}", e),
258            })?;
259        *memory = state;
260        Ok(())
261    }
262
263    /// Hook for MCP consciousness_evolve integration
264    pub fn mcp_consciousness_evolve_hook(
265        &mut self,
266        iterations: usize,
267        target: f64,
268    ) -> TemporalResult<f64> {
269        let mut emergence_level = 0.0;
270
271        for i in 0..iterations {
272            // Schedule consciousness evolution tasks
273            self.schedule_task(
274                ConsciousnessTask::StrangeLoopProcessing {
275                    iteration: i,
276                    state: vec![emergence_level; 10],
277                },
278                0,         // Immediate
279                1_000_000, // 1ms deadline
280            )?;
281
282            // Process several ticks to advance evolution
283            for _ in 0..100 {
284                self.tick()?;
285            }
286
287            // Update emergence level
288            let contraction_metrics = self.strange_loop.get_metrics();
289            emergence_level = contraction_metrics.convergence_rate * target;
290
291            if emergence_level >= target {
292                break;
293            }
294        }
295
296        Ok(emergence_level)
297    }
298
299    // Private helper methods
300
301    fn process_due_tasks(&mut self, current_time: TscTimestamp) -> TemporalResult<()> {
302        let mut processed = 0;
303
304        while let Some(task) = self.task_queue.peek() {
305            if task.scheduled_at <= current_time {
306                let task = self.task_queue.pop().unwrap();
307                self.execute_task(task)?;
308                processed += 1;
309                self.metrics.tasks_completed += 1;
310
311                // Limit processing per tick to maintain real-time performance
312                if processed >= 10 {
313                    break;
314                }
315            } else {
316                break;
317            }
318        }
319
320        Ok(())
321    }
322
323    fn execute_task(&mut self, task: ScheduledTask) -> TemporalResult<()> {
324        match &task.task {
325            ConsciousnessTask::Perception { data, .. } => {
326                // Process perception data
327                self.process_perception_data(data)?;
328            }
329            ConsciousnessTask::MemoryIntegration { session_id, state } => {
330                // Integrate memory state
331                self.integrate_memory_state(session_id, state)?;
332            }
333            ConsciousnessTask::IdentityPreservation { continuity_check } => {
334                // Preserve identity continuity
335                if *continuity_check {
336                    self.identity_tracker.validate_continuity()?;
337                }
338            }
339            ConsciousnessTask::StrangeLoopProcessing { iteration, state } => {
340                // Process strange loop iteration
341                self.strange_loop
342                    .process_iteration(*iteration as f64, state)?;
343            }
344            ConsciousnessTask::WindowManagement {
345                window_id,
346                overlap_target,
347            } => {
348                // Manage temporal window
349                self.window_manager
350                    .adjust_overlap(*window_id, *overlap_target)?;
351            }
352        }
353
354        self.completed_tasks.push_back(task);
355
356        // Keep completed tasks history bounded
357        while self.completed_tasks.len() > 1000 {
358            self.completed_tasks.pop_front();
359        }
360
361        Ok(())
362    }
363
364    fn get_current_state_vector(&self) -> TemporalResult<Vec<f64>> {
365        let mut state = Vec::with_capacity(8);
366
367        state.push(self.current_tick as f64);
368        state.push(self.metrics.window_overlap_percentage);
369        state.push(self.metrics.identity_continuity_score);
370        state.push(self.task_queue.len() as f64);
371        state.push(self.metrics.avg_scheduling_overhead_ns);
372        state.push(self.get_temporal_advantage() as f64);
373        state.push(self.strange_loop.get_metrics().convergence_rate);
374        state.push(self.identity_tracker.get_metrics()?.continuity_score);
375
376        Ok(state)
377    }
378
379    fn get_identity_state(&self) -> TemporalResult<Vec<u8>> {
380        let state = self
381            .memory_state
382            .lock()
383            .map_err(|e| TemporalError::TscTimingError {
384                message: format!("Memory lock error: {}", e),
385            })?;
386        Ok(state.clone())
387    }
388
389    fn record_overhead(&mut self, overhead_ns: u64) -> TemporalResult<()> {
390        // Record the measurement always — the budget check is metric-only,
391        // not fatal. The previous implementation returned Err whenever a
392        // single tick exceeded `max_scheduling_overhead_ns`, which made
393        // every test that runs on a debug build (or a busy CI host) fail
394        // with `SchedulingOverhead { actual_ns: ~66000, limit_ns: 1000 }`.
395        // The scheduler's job is to *track* timing, not to crash on it.
396        self.overhead_measurements.push_back(overhead_ns);
397        if self.overhead_measurements.len() > 1000 {
398            self.overhead_measurements.pop_front();
399        }
400
401        // Update average
402        let sum: u64 = self.overhead_measurements.iter().sum();
403        self.metrics.avg_scheduling_overhead_ns =
404            sum as f64 / self.overhead_measurements.len() as f64;
405        self.metrics.max_scheduling_overhead_ns =
406            self.metrics.max_scheduling_overhead_ns.max(overhead_ns);
407
408        Ok(())
409    }
410
411    fn update_metrics(&mut self, contraction_result: ContractionMetrics) -> TemporalResult<()> {
412        self.metrics.window_overlap_percentage =
413            self.window_manager.get_current_overlap_percentage();
414        self.metrics.contraction_convergence_rate = contraction_result.convergence_rate;
415        self.metrics.identity_continuity_score =
416            self.identity_tracker.get_metrics()?.continuity_score;
417        self.metrics.temporal_advantage_ns = self.get_temporal_advantage();
418
419        Ok(())
420    }
421
422    fn process_perception_data(&mut self, _data: &[u8]) -> TemporalResult<()> {
423        // Placeholder for perception processing
424        Ok(())
425    }
426
427    fn integrate_memory_state(&mut self, _session_id: &str, state: &[u8]) -> TemporalResult<()> {
428        let mut memory = self
429            .memory_state
430            .lock()
431            .map_err(|e| TemporalError::TscTimingError {
432                message: format!("Memory lock error: {}", e),
433            })?;
434        memory.extend_from_slice(state);
435        Ok(())
436    }
437
438    /// Validate quantum mechanical constraints for temporal operation
439    fn validate_quantum_operation(
440        &mut self,
441        operation_time_s: f64,
442        energy_j: f64,
443    ) -> TemporalResult<()> {
444        match self
445            .quantum_validator
446            .validate_temporal_operation(operation_time_s, energy_j)
447        {
448            Ok(validation_result) => {
449                // Store validation result for metrics
450                self.quantum_validations
451                    .push_back(validation_result.clone());
452                if self.quantum_validations.len() > 1000 {
453                    self.quantum_validations.pop_front();
454                }
455
456                // Update quantum metrics
457                self.update_quantum_metrics(&validation_result);
458
459                if !validation_result.is_valid {
460                    // Log warning but don't fail - this is advisory
461                    eprintln!(
462                        "Warning: Quantum validation failed for operation_time={}s, energy={}J",
463                        operation_time_s, energy_j
464                    );
465                }
466                Ok(())
467            }
468            Err(quantum_error) => {
469                // Log quantum physics violations but don't stop operation
470                eprintln!("Quantum physics constraint violation: {}", quantum_error);
471
472                // Create a failed validation result for metrics
473                let failed_result = ValidationResult {
474                    is_valid: false,
475                    speed_limit_result: crate::temporal_nexus::quantum::SpeedLimitResult {
476                        is_valid: false,
477                        requested_time_s: operation_time_s,
478                        minimum_time_s: 0.0,
479                        available_energy_j: energy_j,
480                        required_energy_j: 0.0,
481                        safety_margin: 1.0,
482                        operation_frequency_hz: 1.0 / operation_time_s,
483                        hardware_limit_hz: 1e12,
484                        margin_factor: 0.0,
485                    },
486                    uncertainty_result: crate::temporal_nexus::quantum::UncertaintyResult {
487                        is_valid: false,
488                        energy_j,
489                        energy_ev: energy_j
490                            / crate::temporal_nexus::quantum::constants::EV_TO_JOULES,
491                        time_s: operation_time_s,
492                        uncertainty_product: energy_j * operation_time_s,
493                        minimum_product: crate::temporal_nexus::quantum::constants::PLANCK_HBAR
494                            / 2.0,
495                        margin: 0.0,
496                        thermal_energy_j: crate::temporal_nexus::quantum::constants::BOLTZMANN_K
497                            * crate::temporal_nexus::quantum::constants::ROOM_TEMPERATURE_K,
498                        thermal_energy_ev: (crate::temporal_nexus::quantum::constants::BOLTZMANN_K
499                            * crate::temporal_nexus::quantum::constants::ROOM_TEMPERATURE_K)
500                            / crate::temporal_nexus::quantum::constants::EV_TO_JOULES,
501                        temperature_k:
502                            crate::temporal_nexus::quantum::constants::ROOM_TEMPERATURE_K,
503                        energy_scale_classification:
504                            crate::temporal_nexus::quantum::EnergyScale::MilliElectronVolt,
505                    },
506                    decoherence_result: crate::temporal_nexus::quantum::DecoherenceResult {
507                        is_valid: false,
508                        operation_time_s,
509                        coherence_time_s: 1e-9,
510                        t1_relaxation_s: 1e-6,
511                        t2_dephasing_s: 1e-9,
512                        coherence_preserved: 0.0,
513                        temperature_k:
514                            crate::temporal_nexus::quantum::constants::ROOM_TEMPERATURE_K,
515                        thermal_rate_hz: 1e6,
516                        dephasing_rate_hz: 1e9,
517                        environment_type:
518                            crate::temporal_nexus::quantum::EnvironmentType::RoomTemperature,
519                        noise_analysis: crate::temporal_nexus::quantum::NoiseAnalysis {
520                            frequency_hz: 1.0 / operation_time_s,
521                            thermal_noise_density: 1e-18,
522                            flicker_noise_density: 1e-18,
523                            shot_noise_density: 1e-20,
524                            total_noise_density: 2e-18,
525                            dominant_source: "thermal".to_string(),
526                        },
527                    },
528                    entanglement_result: crate::temporal_nexus::quantum::EntanglementResult {
529                        is_valid: false,
530                        operation_time_s,
531                        concurrence: 0.0,
532                        entanglement_entropy: 0.0,
533                        bell_parameter: 2.0,
534                        survival_probability: 0.0,
535                        qubit_count: 2,
536                        decoherence_time_s: 1e-9,
537                        correlation_type:
538                            crate::temporal_nexus::quantum::CorrelationType::Separable,
539                        quantum_advantage: false,
540                    },
541                    operation_time_s,
542                    energy_j,
543                };
544
545                self.quantum_validations.push_back(failed_result.clone());
546                if self.quantum_validations.len() > 1000 {
547                    self.quantum_validations.pop_front();
548                }
549                self.update_quantum_metrics(&failed_result);
550
551                // Continue operation despite quantum constraint violation
552                Ok(())
553            }
554        }
555    }
556
557    /// Update quantum metrics from validation results
558    fn update_quantum_metrics(&mut self, _validation: &ValidationResult) {
559        if self.quantum_validations.is_empty() {
560            return;
561        }
562
563        let total_validations = self.quantum_validations.len() as f64;
564        let valid_count = self
565            .quantum_validations
566            .iter()
567            .filter(|v| v.is_valid)
568            .count() as f64;
569
570        self.metrics.quantum_validity_rate = valid_count / total_validations;
571
572        // Calculate averages
573        let avg_energy: f64 = self
574            .quantum_validations
575            .iter()
576            .map(|v| v.energy_j)
577            .sum::<f64>()
578            / total_validations;
579
580        let avg_ml_margin: f64 = self
581            .quantum_validations
582            .iter()
583            .map(|v| v.speed_limit_result.margin_factor)
584            .sum::<f64>()
585            / total_validations;
586
587        let avg_uncertainty_margin: f64 = self
588            .quantum_validations
589            .iter()
590            .map(|v| v.uncertainty_result.margin)
591            .sum::<f64>()
592            / total_validations;
593
594        let avg_coherence: f64 = self
595            .quantum_validations
596            .iter()
597            .map(|v| v.decoherence_result.coherence_preserved)
598            .sum::<f64>()
599            / total_validations;
600
601        let avg_entanglement: f64 = self
602            .quantum_validations
603            .iter()
604            .map(|v| v.entanglement_result.concurrence)
605            .sum::<f64>()
606            / total_validations;
607
608        self.metrics.avg_quantum_energy_j = avg_energy;
609        self.metrics.avg_margolus_levitin_margin = avg_ml_margin;
610        self.metrics.avg_uncertainty_margin = avg_uncertainty_margin;
611        self.metrics.avg_coherence_preservation = avg_coherence;
612        self.metrics.avg_entanglement_strength = avg_entanglement;
613    }
614
615    /// Get quantum validation analysis
616    pub fn get_quantum_analysis(&self) -> QuantumAnalysisReport {
617        let attosecond_report = self.quantum_validator.check_attosecond_feasibility();
618
619        QuantumAnalysisReport {
620            total_validations: self.quantum_validations.len(),
621            validity_rate: self.metrics.quantum_validity_rate,
622            avg_energy_j: self.metrics.avg_quantum_energy_j,
623            avg_energy_ev: self.metrics.avg_quantum_energy_j
624                / crate::temporal_nexus::quantum::constants::EV_TO_JOULES,
625            margolus_levitin_margin: self.metrics.avg_margolus_levitin_margin,
626            uncertainty_margin: self.metrics.avg_uncertainty_margin,
627            coherence_preservation: self.metrics.avg_coherence_preservation,
628            entanglement_strength: self.metrics.avg_entanglement_strength,
629            attosecond_feasibility: attosecond_report,
630            recommended_time_scale_s:
631                crate::temporal_nexus::quantum::constants::CONSCIOUSNESS_SCALE_NS,
632        }
633    }
634}
635
636/// Quantum analysis report for consciousness operations
637#[derive(Debug, Clone)]
638pub struct QuantumAnalysisReport {
639    pub total_validations: usize,
640    pub validity_rate: f64,
641    pub avg_energy_j: f64,
642    pub avg_energy_ev: f64,
643    pub margolus_levitin_margin: f64,
644    pub uncertainty_margin: f64,
645    pub coherence_preservation: f64,
646    pub entanglement_strength: f64,
647    pub attosecond_feasibility: crate::temporal_nexus::quantum::AttosecondFeasibilityReport,
648    pub recommended_time_scale_s: f64,
649}
650
651impl Default for NanosecondScheduler {
652    fn default() -> Self {
653        Self::new()
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    #[test]
662    fn test_scheduler_creation() {
663        let scheduler = NanosecondScheduler::new();
664        assert_eq!(scheduler.current_tick, 0);
665        assert_eq!(scheduler.task_queue.len(), 0);
666    }
667
668    #[test]
669    fn test_task_scheduling() {
670        let mut scheduler = NanosecondScheduler::new();
671
672        let task = ConsciousnessTask::Perception {
673            priority: 128,
674            data: vec![1, 2, 3],
675        };
676
677        let task_id = scheduler.schedule_task(task, 1000, 10000).unwrap();
678        assert_eq!(task_id, 1);
679        assert_eq!(scheduler.task_queue.len(), 1);
680    }
681
682    #[test]
683    fn test_tick_processing() {
684        let mut scheduler = NanosecondScheduler::new();
685
686        // Schedule an immediate task
687        let task = ConsciousnessTask::IdentityPreservation {
688            continuity_check: true,
689        };
690        scheduler.schedule_task(task, 0, 1000).unwrap();
691
692        // Process tick
693        scheduler.tick().unwrap();
694
695        assert_eq!(scheduler.current_tick, 1);
696        assert_eq!(scheduler.metrics.tasks_completed, 1);
697    }
698
699    #[test]
700    fn test_temporal_advantage() {
701        let scheduler = NanosecondScheduler::new();
702        let advantage = scheduler.get_temporal_advantage();
703        assert!(advantage >= 0);
704    }
705
706    #[test]
707    fn test_memory_state_export_import() {
708        let mut scheduler = NanosecondScheduler::new();
709
710        let test_state = vec![1, 2, 3, 4, 5];
711        scheduler.import_memory_state(test_state.clone()).unwrap();
712
713        let exported_state = scheduler.export_memory_state().unwrap();
714        assert_eq!(exported_state, test_state);
715    }
716
717    #[test]
718    fn test_mcp_consciousness_evolve_hook() {
719        let mut scheduler = NanosecondScheduler::new();
720
721        let emergence_level = scheduler.mcp_consciousness_evolve_hook(10, 0.5).unwrap();
722        assert!(emergence_level >= 0.0);
723        assert!(emergence_level <= 1.0);
724    }
725}