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 identity;
10pub mod scheduler;
11pub mod strange_loop;
12pub mod temporal_window;
13
14pub use identity::{ContinuityMetrics, IdentityContinuityTracker};
15pub use scheduler::NanosecondScheduler;
16pub use strange_loop::{ContractionMetrics, StrangeLoopOperator};
17pub use temporal_window::{TemporalWindow, WindowOverlapManager};
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 {
81        current_size: usize,
82        max_size: usize,
83    },
84}
85
86pub type TemporalResult<T> = Result<T, TemporalError>;
87
88/// Fallback timestamp source for non-x86/non-arm64 targets. Returns
89/// nanoseconds since a fixed reference point (the static `START`).
90/// Not as fast as RDTSC but portable.
91#[cfg(any(
92    not(any(target_arch = "x86_64", target_arch = "aarch64")),
93    all(target_arch = "aarch64", not(target_feature = "neon")),
94))]
95fn generic_now_ns() -> u64 {
96    use std::sync::OnceLock;
97    use std::time::Instant;
98    static START: OnceLock<Instant> = OnceLock::new();
99    let start = START.get_or_init(Instant::now);
100    start.elapsed().as_nanos() as u64
101}
102
103/// High-precision timestamp using TSC
104#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
105pub struct TscTimestamp(pub u64);
106
107impl TscTimestamp {
108    /// Read current TSC timestamp.
109    ///
110    /// - **x86_64**: `RDTSC` — bias 0, latency a few cycles.
111    /// - **aarch64**: `CNTVCT_EL0` (the virtual count register) — same
112    ///   wall-clock semantics as RDTSC but at the system counter
113    ///   frequency (typically 24 MHz on Apple Silicon, exposed via
114    ///   `CNTFRQ_EL0`). Callers must pass the right `tsc_freq_hz` to
115    ///   `nanos_since` for portability.
116    /// - **other**: fall back to `Instant::now()` so the crate still
117    ///   compiles on wasm32 / riscv64 / etc. The returned u64 is
118    ///   nanoseconds since program start, and `nanos_since` should be
119    ///   called with `tsc_freq_hz = 1_000_000_000` on these targets.
120    #[inline]
121    pub fn now() -> Self {
122        #[cfg(target_arch = "x86_64")]
123        unsafe {
124            Self(core::arch::x86_64::_rdtsc())
125        }
126        #[cfg(all(target_arch = "aarch64", target_feature = "neon"))]
127        unsafe {
128            let val: u64;
129            core::arch::asm!("mrs {0}, cntvct_el0", out(reg) val);
130            Self(val)
131        }
132        #[cfg(all(target_arch = "aarch64", not(target_feature = "neon")))]
133        unsafe {
134            // No `target_feature = "neon"` (rare on stable arm64 toolchains
135            // but possible on some embedded triples) — fall through to the
136            // generic path.
137            Self(generic_now_ns())
138        }
139        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
140        {
141            Self(generic_now_ns())
142        }
143    }
144
145    /// Calculate nanoseconds since another timestamp
146    pub fn nanos_since(&self, other: TscTimestamp, tsc_freq_hz: u64) -> u64 {
147        let tsc_diff = self.0.saturating_sub(other.0);
148        (tsc_diff * 1_000_000_000) / tsc_freq_hz
149    }
150
151    /// Add nanoseconds to timestamp
152    pub fn add_nanos(&self, nanos: u64, tsc_freq_hz: u64) -> Self {
153        let tsc_increment = (nanos * tsc_freq_hz) / 1_000_000_000;
154        Self(self.0 + tsc_increment)
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn test_temporal_config_default() {
164        let config = TemporalConfig::default();
165        assert!(config.window_overlap_percent >= 50.0);
166        assert!(config.window_overlap_percent <= 100.0);
167        assert!(config.lipschitz_bound < 1.0);
168        assert!(config.max_scheduling_overhead_ns <= 1_000);
169    }
170
171    #[test]
172    fn test_tsc_timestamp() {
173        let ts1 = TscTimestamp::now();
174        std::thread::sleep(std::time::Duration::from_nanos(1000));
175        let ts2 = TscTimestamp::now();
176        assert!(ts2 > ts1);
177
178        let nanos = ts2.nanos_since(ts1, 3_000_000_000);
179        assert!(nanos > 0);
180    }
181}