Skip to main content

sublinear_solver/temporal_nexus/core/
mod.rs

1//! Temporal Nexus Core - Nanosecond Scheduler for Temporal Consciousness
2//!
3//! This module implements the core nanosecond scheduler that enables temporal consciousness
4//! by managing high-precision timing, temporal windows, and identity continuity.
5//!
6//! The scheduler operates at nanosecond precision using hardware Time Stamp Counter (TSC)
7//! and maintains temporal windows with 50-100 tick overlap to ensure consciousness continuity.
8
9pub mod scheduler;
10pub mod temporal_window;
11pub mod strange_loop;
12pub mod identity;
13
14pub use scheduler::NanosecondScheduler;
15pub use temporal_window::{TemporalWindow, WindowOverlapManager};
16pub use strange_loop::{StrangeLoopOperator, ContractionMetrics};
17pub use identity::{IdentityContinuityTracker, ContinuityMetrics};
18
19/// Core temporal consciousness configuration
20#[derive(Debug, Clone)]
21pub struct TemporalConfig {
22    /// Target temporal window overlap percentage (50-100%)
23    pub window_overlap_percent: f64,
24    /// Maximum scheduling overhead in nanoseconds
25    pub max_scheduling_overhead_ns: u64,
26    /// Lipschitz constant upper bound for contraction (< 1.0)
27    pub lipschitz_bound: f64,
28    /// Maximum iterations for contraction convergence
29    pub max_contraction_iterations: usize,
30    /// TSC frequency for high-precision timing
31    pub tsc_frequency_hz: u64,
32}
33
34impl Default for TemporalConfig {
35    fn default() -> Self {
36        Self {
37            window_overlap_percent: 75.0,
38            max_scheduling_overhead_ns: 1_000, // 1 microsecond
39            lipschitz_bound: 0.95,
40            max_contraction_iterations: 10,
41            tsc_frequency_hz: 3_000_000_000, // 3 GHz default
42        }
43    }
44}
45
46/// Temporal consciousness task types
47#[derive(Debug, Clone, PartialEq)]
48pub enum ConsciousnessTask {
49    /// Perception processing task
50    Perception { priority: u8, data: Vec<u8> },
51    /// Memory integration task
52    MemoryIntegration { session_id: String, state: Vec<u8> },
53    /// Identity preservation task
54    IdentityPreservation { continuity_check: bool },
55    /// Strange loop processing task
56    StrangeLoopProcessing { iteration: usize, state: Vec<f64> },
57    /// Temporal window management task
58    WindowManagement { window_id: u64, overlap_target: f64 },
59}
60
61/// Error types for temporal consciousness operations
62#[derive(Debug, thiserror::Error)]
63pub enum TemporalError {
64    #[error("Scheduling overhead exceeded limit: {actual_ns}ns > {limit_ns}ns")]
65    SchedulingOverhead { actual_ns: u64, limit_ns: u64 },
66    
67    #[error("Window overlap below threshold: {actual}% < {required}%")]
68    WindowOverlapTooLow { actual: f64, required: f64 },
69    
70    #[error("Contraction failed to converge in {iterations} iterations")]
71    ContractionNoConvergence { iterations: usize },
72    
73    #[error("Identity continuity broken: gap = {gap_ns}ns")]
74    IdentityContinuityBreak { gap_ns: u64 },
75    
76    #[error("TSC timing error: {message}")]
77    TscTimingError { message: String },
78    
79    #[error("Task queue overflow: {current_size}/{max_size}")]
80    TaskQueueOverflow { current_size: usize, max_size: usize },
81}
82
83pub type TemporalResult<T> = Result<T, TemporalError>;
84
85/// Fallback timestamp source for non-x86/non-arm64 targets. Returns
86/// nanoseconds since a fixed reference point (the static `START`).
87/// Not as fast as RDTSC but portable.
88#[cfg(any(
89    not(any(target_arch = "x86_64", target_arch = "aarch64")),
90    all(target_arch = "aarch64", not(target_feature = "neon")),
91))]
92fn generic_now_ns() -> u64 {
93    use std::sync::OnceLock;
94    use std::time::Instant;
95    static START: OnceLock<Instant> = OnceLock::new();
96    let start = START.get_or_init(Instant::now);
97    start.elapsed().as_nanos() as u64
98}
99
100/// High-precision timestamp using TSC
101#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
102pub struct TscTimestamp(pub u64);
103
104impl TscTimestamp {
105    /// Read current TSC timestamp.
106    ///
107    /// - **x86_64**: `RDTSC` — bias 0, latency a few cycles.
108    /// - **aarch64**: `CNTVCT_EL0` (the virtual count register) — same
109    ///   wall-clock semantics as RDTSC but at the system counter
110    ///   frequency (typically 24 MHz on Apple Silicon, exposed via
111    ///   `CNTFRQ_EL0`). Callers must pass the right `tsc_freq_hz` to
112    ///   `nanos_since` for portability.
113    /// - **other**: fall back to `Instant::now()` so the crate still
114    ///   compiles on wasm32 / riscv64 / etc. The returned u64 is
115    ///   nanoseconds since program start, and `nanos_since` should be
116    ///   called with `tsc_freq_hz = 1_000_000_000` on these targets.
117    #[inline]
118    pub fn now() -> Self {
119        #[cfg(target_arch = "x86_64")]
120        unsafe {
121            Self(core::arch::x86_64::_rdtsc())
122        }
123        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
124        unsafe {
125            let val: u64;
126            core::arch::asm!("mrs {0}, cntvct_el0", out(reg) val);
127            Self(val)
128        }
129        #[cfg(all(target_arch = "aarch64", not(target_feature = "neon")))]
130        unsafe {
131            // No `target_feature = "neon"` (rare on stable arm64 toolchains
132            // but possible on some embedded triples) — fall through to the
133            // generic path.
134            Self(generic_now_ns())
135        }
136        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
137        {
138            Self(generic_now_ns())
139        }
140    }
141    
142    /// Calculate nanoseconds since another timestamp
143    pub fn nanos_since(&self, other: TscTimestamp, tsc_freq_hz: u64) -> u64 {
144        let tsc_diff = self.0.saturating_sub(other.0);
145        (tsc_diff * 1_000_000_000) / tsc_freq_hz
146    }
147    
148    /// Add nanoseconds to timestamp
149    pub fn add_nanos(&self, nanos: u64, tsc_freq_hz: u64) -> Self {
150        let tsc_increment = (nanos * tsc_freq_hz) / 1_000_000_000;
151        Self(self.0 + tsc_increment)
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    
159    #[test]
160    fn test_temporal_config_default() {
161        let config = TemporalConfig::default();
162        assert!(config.window_overlap_percent >= 50.0);
163        assert!(config.window_overlap_percent <= 100.0);
164        assert!(config.lipschitz_bound < 1.0);
165        assert!(config.max_scheduling_overhead_ns <= 1_000);
166    }
167    
168    #[test]
169    fn test_tsc_timestamp() {
170        let ts1 = TscTimestamp::now();
171        std::thread::sleep(std::time::Duration::from_nanos(1000));
172        let ts2 = TscTimestamp::now();
173        assert!(ts2 > ts1);
174        
175        let nanos = ts2.nanos_since(ts1, 3_000_000_000);
176        assert!(nanos > 0);
177    }
178}