diff --git a/ml/src/inference.rs b/ml/src/inference.rs index 3aa994e7e..1dd865906 100644 --- a/ml/src/inference.rs +++ b/ml/src/inference.rs @@ -934,7 +934,7 @@ pub fn load_tft_optimized( /// /// * `Ok(())` - Quantization successful /// * `Err(MLSafetyError)` - Quantization failure -fn apply_int8_quantization(model: &mut TemporalFusionTransformer) -> SafetyResult<()> { +fn apply_int8_quantization(_model: &mut TemporalFusionTransformer) -> SafetyResult<()> { let device = Device::cuda_if_available(0).unwrap_or(Device::Cpu); // Create INT8 quantizer @@ -945,7 +945,7 @@ fn apply_int8_quantization(model: &mut TemporalFusionTransformer) -> SafetyResul calibration_samples: Some(1000), }; - let mut quantizer = Quantizer::new(quant_config, device); + let quantizer = Quantizer::new(quant_config, device); // Note: Actual weight quantization requires access to model's VarMap // For Wave 9.12, we've validated the quantization infrastructure diff --git a/ml/src/model_registry/checkpoint_loader.rs b/ml/src/model_registry/checkpoint_loader.rs index ab26a6d88..a2efa13c0 100644 --- a/ml/src/model_registry/checkpoint_loader.rs +++ b/ml/src/model_registry/checkpoint_loader.rs @@ -7,7 +7,6 @@ use crate::model_registry::{ModelRegistry, ModelVersionMetadata}; use crate::{MLError, MLResult, ModelType}; use std::fs; use std::path::{Path, PathBuf}; -use chrono::Utc; use serde_json; /// Checkpoint metadata extracted from filesystem @@ -22,6 +21,7 @@ pub struct CheckpointMetadata { } /// Checkpoint scanner for discovering trained models +#[derive(Debug)] pub struct CheckpointScanner { base_path: PathBuf, } @@ -46,7 +46,7 @@ impl CheckpointScanner { // Find actor checkpoints let actor_checkpoints = self.scan_checkpoints_in_dir(&ppo_path, ModelType::PPO, "ppo_actor_epoch_")?; - let critic_checkpoints = self.scan_checkpoints_in_dir(&ppo_path, ModelType::PPO, "ppo_critic_epoch_")?; + let _critic_checkpoints = self.scan_checkpoints_in_dir(&ppo_path, ModelType::PPO, "ppo_critic_epoch_")?; // For PPO, we return actor checkpoints with metadata pointing to both // (The registration logic will handle the critic checkpoint separately) @@ -149,6 +149,7 @@ impl CheckpointScanner { } /// Checkpoint registrar for registering discovered checkpoints +#[derive(Debug)] pub struct CheckpointRegistrar { registry: ModelRegistry, } diff --git a/ml/src/ppo/ppo.rs b/ml/src/ppo/ppo.rs index 4eb5b7046..da266b71e 100644 --- a/ml/src/ppo/ppo.rs +++ b/ml/src/ppo/ppo.rs @@ -8,6 +8,8 @@ //! - Mini-batch SGD training with multiple epochs //! - NO productions, todo!(), or unimplemented!() macros +#![allow(unsafe_code)] // Required for memory-mapped checkpoint loading + use candle_core::{DType, Device, Tensor}; use candle_nn::Module; use candle_nn::{linear, Linear, Optimizer, VarBuilder, VarMap}; diff --git a/ml/src/tft/lstm_encoder.rs b/ml/src/tft/lstm_encoder.rs index db0960796..c691dbf6c 100644 --- a/ml/src/tft/lstm_encoder.rs +++ b/ml/src/tft/lstm_encoder.rs @@ -351,7 +351,7 @@ impl LSTMEncoder { input: &Tensor, states: Option<(Tensor, Tensor)>, ) -> Result<(Tensor, Tensor, Tensor), MLError> { - let (batch_size, _seq_len, _input_size) = input.dims3().map_err(|e| { + let (_batch_size, _seq_len, _input_size) = input.dims3().map_err(|e| { MLError::TensorCreationError { operation: "lstm_encoder forward: get input dims".to_string(), reason: e.to_string(), diff --git a/ml/src/tft/mod.rs b/ml/src/tft/mod.rs index 91fb6d6f2..a61b1ca83 100644 --- a/ml/src/tft/mod.rs +++ b/ml/src/tft/mod.rs @@ -746,7 +746,7 @@ impl Checkpointable for TemporalFusionTransformer { // Save VarMap to temporary file, then read as bytes // VarMap.save() requires a Path, not a writer let temp_dir = std::env::temp_dir(); - let temp_path = temp_dir.join(format!("tft_checkpoint_{}.safetensors", uuid::Uuid::new_v4())); + let temp_path = temp_dir.join(format!("tft_checkpoint_{}.safetensors", Uuid::new_v4())); // Convert temp_path to string for VarMap::save() let temp_path_str = temp_path.to_str() diff --git a/ml/src/tft/quantized_lstm.rs b/ml/src/tft/quantized_lstm.rs index 40138daed..789a61cb0 100644 --- a/ml/src/tft/quantized_lstm.rs +++ b/ml/src/tft/quantized_lstm.rs @@ -107,7 +107,7 @@ impl QuantizedLSTMEncoder { states: Option<(Tensor, Tensor)>, _quantizer: &Quantizer, ) -> Result { - let (batch_size, _seq_len, _input_size) = input.dims3().map_err(|e| { + let (_batch_size, _seq_len, _input_size) = input.dims3().map_err(|e| { MLError::TensorCreationError { operation: "quantized_lstm forward: get input dims".to_string(), reason: e.to_string(), diff --git a/ml/src/tlob/mbp10_feature_extractor.rs b/ml/src/tlob/mbp10_feature_extractor.rs index e7d8841cb..8dc5bb10e 100644 --- a/ml/src/tlob/mbp10_feature_extractor.rs +++ b/ml/src/tlob/mbp10_feature_extractor.rs @@ -4,7 +4,7 @@ //! for transformer-based limit order book prediction. use anyhow::Result; -use data::providers::databento::mbp10::{BidAskPair, Mbp10Snapshot}; +use data::providers::databento::mbp10::Mbp10Snapshot; use crate::tlob::features::{TLOBFeatures, TLOBFeatureExtractor, FeatureVector}; use crate::MLError; use tracing::{debug, instrument}; diff --git a/ml/tests/common/mod.rs b/ml/tests/common/mod.rs index 58f2a8248..33b0cb924 100644 --- a/ml/tests/common/mod.rs +++ b/ml/tests/common/mod.rs @@ -6,4 +6,4 @@ //! //! - `validation_helpers`: Helpers for data validation pipeline tests -pub mod validation_helpers; +pub(crate) mod validation_helpers; diff --git a/ml/tests/common/validation_helpers.rs b/ml/tests/common/validation_helpers.rs index c9d00cc96..02465af4e 100644 --- a/ml/tests/common/validation_helpers.rs +++ b/ml/tests/common/validation_helpers.rs @@ -53,7 +53,7 @@ use ml::real_data_loader::{Indicators, OHLCVBar}; /// // Create validator with only integrity checks /// let validator = create_test_validator_config(true, false, false); /// ``` -pub fn create_test_validator_config( +pub(crate) fn create_test_validator_config( with_integrity: bool, with_continuity: bool, with_indicators: bool, @@ -89,7 +89,7 @@ pub fn create_test_validator_config( /// // Create validator that allows 30% spikes /// let validator = create_test_validator_with_threshold(0.30); /// ``` -pub fn create_test_validator_with_threshold(spike_threshold: f64) -> DataValidator { +pub(crate) fn create_test_validator_with_threshold(spike_threshold: f64) -> DataValidator { DataValidator::new() .with_rule(Box::new(IntegrityRule::new())) .with_rule(Box::new(ContinuityRule::new(spike_threshold))) @@ -108,7 +108,7 @@ pub fn create_test_validator_with_threshold(spike_threshold: f64) -> DataValidat /// // Create validator for 5-minute bars /// let validator = create_test_validator_with_timestamps(300); /// ``` -pub fn create_test_validator_with_timestamps(bar_interval_secs: i64) -> DataValidator { +pub(crate) fn create_test_validator_with_timestamps(bar_interval_secs: i64) -> DataValidator { DataValidator::new() .with_rule(Box::new(IntegrityRule::new())) .with_rule(Box::new(TimestampRule::new(bar_interval_secs))) @@ -128,7 +128,7 @@ pub fn create_test_validator_with_timestamps(bar_interval_secs: i64) -> DataVali /// // Require 99% data completeness for 1-minute bars /// let validator = create_test_validator_with_completeness(60, 0.99); /// ``` -pub fn create_test_validator_with_completeness( +pub(crate) fn create_test_validator_with_completeness( bar_interval_secs: i64, min_completeness: f64, ) -> DataValidator { @@ -149,7 +149,7 @@ pub fn create_test_validator_with_completeness( /// let corrector = create_test_corrector(); /// let corrected_bars = corrector.correct_price_spikes(&bars, 0.20)?; /// ``` -pub fn create_test_corrector() -> DataCorrector { +pub(crate) fn create_test_corrector() -> DataCorrector { DataCorrector::new() } @@ -159,7 +159,7 @@ pub fn create_test_corrector() -> DataCorrector { /// Type of anomaly to inject into test data #[derive(Debug, Clone, Copy)] -pub enum AnomalyType { +pub(crate) enum AnomalyType { /// Price spikes >20% between bars PriceSpikes, /// Invalid OHLCV relationships (high < low, etc.) @@ -196,7 +196,7 @@ pub enum AnomalyType { /// let result = validator.validate(&bars)?; /// assert!(!result.is_valid()); /// ``` -pub fn generate_anomalous_data(bar_count: usize, anomaly_type: AnomalyType) -> Vec { +pub(crate) fn generate_anomalous_data(bar_count: usize, anomaly_type: AnomalyType) -> Vec { let mut bars = generate_clean_data(bar_count); match anomaly_type { @@ -236,7 +236,7 @@ pub fn generate_anomalous_data(bar_count: usize, anomaly_type: AnomalyType) -> V /// let result = validator.validate(&bars)?; /// assert!(result.is_valid()); /// ``` -pub fn generate_clean_data(bar_count: usize) -> Vec { +pub(crate) fn generate_clean_data(bar_count: usize) -> Vec { let mut bars = Vec::with_capacity(bar_count); let mut base_price = 100.0; let base_timestamp = chrono::Utc::now(); @@ -390,7 +390,7 @@ fn generate_bars_with_gaps(bar_count: usize) -> Vec { /// let result = validator.validate_indicators(&indicators)?; /// assert!(result.is_valid()); /// ``` -pub fn generate_clean_indicators(bar_count: usize) -> Indicators { +pub(crate) fn generate_clean_indicators(bar_count: usize) -> Indicators { Indicators { rsi: (0..bar_count).map(|i| 30.0 + (i % 40) as f32).collect(), // Oscillates 30-70 macd: (0..bar_count).map(|i| (i as f32 % 10.0) - 5.0).collect(), // -5 to +5 @@ -425,7 +425,7 @@ pub fn generate_clean_indicators(bar_count: usize) -> Indicators { /// let result = validator.validate_indicators(&indicators)?; /// assert!(!result.is_valid()); /// ``` -pub fn generate_anomalous_indicators( +pub(crate) fn generate_anomalous_indicators( bar_count: usize, anomaly_type: IndicatorAnomalyType, ) -> Indicators { @@ -457,7 +457,7 @@ pub fn generate_anomalous_indicators( /// Type of indicator anomaly #[derive(Debug, Clone, Copy)] -pub enum IndicatorAnomalyType { +pub(crate) enum IndicatorAnomalyType { /// RSI values outside 0-100 range RsiOutOfRange, /// NaN values in indicators @@ -495,7 +495,7 @@ pub enum IndicatorAnomalyType { /// // Assert validation failed with 5 errors and 2 warnings /// assert_validation_result(&result, false, 5, 2); /// ``` -pub fn assert_validation_result( +pub(crate) fn assert_validation_result( result: &ValidationResult, should_be_valid: bool, expected_errors: usize, @@ -543,7 +543,7 @@ pub fn assert_validation_result( /// assert_has_error_category(&result, "integrity"); /// assert_has_error_category(&result, "continuity"); /// ``` -pub fn assert_has_error_category(result: &ValidationResult, error_category: &str) { +pub(crate) fn assert_has_error_category(result: &ValidationResult, error_category: &str) { assert!( result.error_summary().contains(error_category), "Expected error category '{}' not found in errors: {}", @@ -561,7 +561,7 @@ pub fn assert_has_error_category(result: &ValidationResult, error_category: &str /// let result = validator.validate(&clean_bars)?; /// assert_validation_passed(&result); /// ``` -pub fn assert_validation_passed(result: &ValidationResult) { +pub(crate) fn assert_validation_passed(result: &ValidationResult) { assert!( result.is_valid(), "Validation should pass but failed. Errors: {}", @@ -584,7 +584,7 @@ pub fn assert_validation_passed(result: &ValidationResult) { /// let result = validator.validate(&bad_bars)?; /// assert_validation_failed(&result); /// ``` -pub fn assert_validation_failed(result: &ValidationResult) { +pub(crate) fn assert_validation_failed(result: &ValidationResult) { assert!( !result.is_valid(), "Validation should fail but passed" @@ -614,7 +614,7 @@ pub fn assert_validation_failed(result: &ValidationResult) { /// .trend(0.001) // 0.1% uptrend per bar /// .build(); /// ``` -pub struct TestBarBuilder { +pub(crate) struct TestBarBuilder { count: usize, base_price: f64, volatility: f64, @@ -625,7 +625,7 @@ pub struct TestBarBuilder { impl TestBarBuilder { /// Create new builder with defaults - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { count: 100, base_price: 100.0, @@ -637,43 +637,43 @@ impl TestBarBuilder { } /// Set number of bars to generate - pub fn count(mut self, count: usize) -> Self { + pub(crate) fn count(mut self, count: usize) -> Self { self.count = count; self } /// Set starting price - pub fn base_price(mut self, price: f64) -> Self { + pub(crate) fn base_price(mut self, price: f64) -> Self { self.base_price = price; self } /// Set price volatility (e.g., 0.02 = ±2% per bar) - pub fn volatility(mut self, volatility: f64) -> Self { + pub(crate) fn volatility(mut self, volatility: f64) -> Self { self.volatility = volatility; self } /// Set price trend (e.g., 0.001 = +0.1% per bar) - pub fn trend(mut self, trend: f64) -> Self { + pub(crate) fn trend(mut self, trend: f64) -> Self { self.trend = trend; self } /// Set starting timestamp - pub fn base_timestamp(mut self, timestamp: chrono::DateTime) -> Self { + pub(crate) fn base_timestamp(mut self, timestamp: chrono::DateTime) -> Self { self.base_timestamp = timestamp; self } /// Set interval between bars in seconds - pub fn interval_secs(mut self, interval: i64) -> Self { + pub(crate) fn interval_secs(mut self, interval: i64) -> Self { self.interval_secs = interval; self } /// Build the bars - pub fn build(self) -> Vec { + pub(crate) fn build(self) -> Vec { let mut bars = Vec::with_capacity(self.count); let mut price = self.base_price; diff --git a/ml/tests/dqn_tests.rs b/ml/tests/dqn_tests.rs index 6082264e9..6136bcf81 100644 --- a/ml/tests/dqn_tests.rs +++ b/ml/tests/dqn_tests.rs @@ -18,7 +18,7 @@ use ml::dqn::{ use ml::dqn::noisy_layers::{NoisyLinear, NoisyNetworkConfig, NoisyNetworkManager}; mod real_data_helpers; -use real_data_helpers::{load_dqn_states, real_data_available}; +use real_data_helpers::load_dqn_states; // ============================================================================ // DQN Core Algorithm Tests - Bellman Equation & Q-value Updates diff --git a/ml/tests/e2e_mamba2_training.rs b/ml/tests/e2e_mamba2_training.rs index 297dabbae..c0852731d 100644 --- a/ml/tests/e2e_mamba2_training.rs +++ b/ml/tests/e2e_mamba2_training.rs @@ -20,7 +20,7 @@ //! ``` use anyhow::Result; -use candle_core::{Device, DType, Tensor}; +use candle_core::{Device, Tensor}; use ml::mamba::{Mamba2Config, Mamba2SSM}; /// Helper to create default MAMBA-2 config for testing diff --git a/ml/tests/ensemble_hot_swap_test.rs b/ml/tests/ensemble_hot_swap_test.rs index eab0eb04e..ab704bfb9 100644 --- a/ml/tests/ensemble_hot_swap_test.rs +++ b/ml/tests/ensemble_hot_swap_test.rs @@ -9,8 +9,7 @@ //! 6. Test rollback mechanism use ml::ensemble::{ - CheckpointModel, CheckpointValidator, HotSwapManager, RollbackPolicy, - ValidationResult, CanaryResult, EnsembleMetrics, + CheckpointModel, CheckpointValidator, HotSwapManager, RollbackPolicy, EnsembleMetrics, }; use ml::{Features, ModelPrediction, MLResult}; use std::sync::Arc; diff --git a/ml/tests/liquid_ensemble_risk_tests.rs b/ml/tests/liquid_ensemble_risk_tests.rs index 5b1c8c39c..a36c21ce5 100644 --- a/ml/tests/liquid_ensemble_risk_tests.rs +++ b/ml/tests/liquid_ensemble_risk_tests.rs @@ -13,10 +13,9 @@ use ml::ensemble::voting::{EnsembleVoter, VotingConfig, VotingStrategy}; use ml::liquid::activation::ActivationType; use ml::liquid::cells::{CfCCell, CfCConfig, LTCCell, LTCConfig}; use ml::liquid::ode_solvers::{ - EulerSolver, LiquidDynamics, ODESolver, RK4Solver, SolverType, VolatilityAwareTimeConstants, + EulerSolver, ODESolver, RK4Solver, SolverType, VolatilityAwareTimeConstants, }; use ml::liquid::{FixedPoint, LiquidError, Result as LiquidResult, PRECISION}; -use ml::MarketRegime; use ml::risk::kelly_optimizer::{KellyCriterionOptimizer, KellyOptimizerConfig}; use ml::risk::var_models::{MarketTick, NeuralVarConfig, NeuralVarModel, VarFeatures}; use ml::MLError; diff --git a/ml/tests/liquid_nn_training_tests.rs b/ml/tests/liquid_nn_training_tests.rs index 61c65bb48..191c40850 100644 --- a/ml/tests/liquid_nn_training_tests.rs +++ b/ml/tests/liquid_nn_training_tests.rs @@ -528,7 +528,7 @@ fn test_memory_usage() -> anyhow::Result<()> { // Calculate memory footprint let param_count = network.parameter_count(); - let bytes_per_param = std::mem::size_of::(); // 8 bytes (i64) + let bytes_per_param = size_of::(); // 8 bytes (i64) let total_bytes = param_count * bytes_per_param; let kb = total_bytes as f64 / 1024.0; let mb = kb / 1024.0; @@ -585,7 +585,7 @@ fn test_memory_usage() -> anyhow::Result<()> { }); } - let sample_memory = samples.len() * (16 + 3) * std::mem::size_of::(); + let sample_memory = samples.len() * (16 + 3) * size_of::(); let sample_mb = sample_memory as f64 / 1024.0 / 1024.0; println!(" Sample dataset memory: {:.3} MB", sample_mb); diff --git a/ml/tests/model_registry_checkpoint_test.rs b/ml/tests/model_registry_checkpoint_test.rs index df165232f..2faf5bbb8 100644 --- a/ml/tests/model_registry_checkpoint_test.rs +++ b/ml/tests/model_registry_checkpoint_test.rs @@ -345,7 +345,7 @@ async fn test_multi_model_registry_query() -> MLResult<()> { async fn test_production_promotion_workflow() -> MLResult<()> { let registry = ModelRegistry::new(TEST_DB_URL, TEST_S3_PATH).await?; - let mut metadata = ModelVersionMetadata::new( + let metadata = ModelVersionMetadata::new( "dqn-promotion-test".to_string(), ModelType::DQN, "1.0.0".to_string(), diff --git a/ml/tests/multi_day_training_simulation.rs b/ml/tests/multi_day_training_simulation.rs index f8c270b82..b18907cb6 100644 --- a/ml/tests/multi_day_training_simulation.rs +++ b/ml/tests/multi_day_training_simulation.rs @@ -42,11 +42,10 @@ //! - Batch timing analysis use anyhow::Result; -use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; -use tracing::{info, warn}; +use tracing::info; // ============================================================================ // Test Fixtures diff --git a/ml/tests/real_data_helpers.rs b/ml/tests/real_data_helpers.rs index aa0883894..6e092b40f 100644 --- a/ml/tests/real_data_helpers.rs +++ b/ml/tests/real_data_helpers.rs @@ -31,13 +31,13 @@ const BTC_FILE: &str = "BTC-USD_30day_2024-09.parquet"; const ETH_FILE: &str = "ETH-USD_30day_2024-09.parquet"; /// Real market data loader for ML tests -pub struct RealDataLoader { +pub(crate) struct RealDataLoader { base_path: String, } impl RealDataLoader { /// Create new loader with workspace-relative path - pub fn new() -> Self { + pub(crate) fn new() -> Self { let manifest_dir = env!("CARGO_MANIFEST_DIR"); let base_path = PathBuf::from(manifest_dir) .parent() @@ -50,19 +50,19 @@ impl RealDataLoader { } /// Check if real data files exist - pub fn files_exist(&self) -> bool { + pub(crate) fn files_exist(&self) -> bool { let btc_path = PathBuf::from(&self.base_path).join(BTC_FILE); let eth_path = PathBuf::from(&self.base_path).join(ETH_FILE); btc_path.exists() && eth_path.exists() } /// Load raw market events from BTC data - pub async fn load_btc_events(&self, count: usize) -> Result> { + pub(crate) async fn load_btc_events(&self, count: usize) -> Result> { self.load_events(BTC_FILE, count).await } /// Load raw market events from ETH data - pub async fn load_eth_events(&self, count: usize) -> Result> { + pub(crate) async fn load_eth_events(&self, count: usize) -> Result> { self.load_events(ETH_FILE, count).await } @@ -89,7 +89,7 @@ impl Default for RealDataLoader { /// Convert market events to DQN/PPO state vectors /// /// Each state vector contains [price, volume, bid_ask_spread, momentum, volatility] -pub fn events_to_dqn_states(events: &[MarketDataEvent], state_dim: usize) -> Vec> { +pub(crate) fn events_to_dqn_states(events: &[MarketDataEvent], state_dim: usize) -> Vec> { if events.is_empty() { return vec![]; } @@ -134,7 +134,7 @@ pub fn events_to_dqn_states(events: &[MarketDataEvent], state_dim: usize) -> Vec /// Returns (sequences, targets) where: /// - sequences: [batch, seq_len, features] /// - targets: [batch, prediction_horizon] -pub fn events_to_time_series( +pub(crate) fn events_to_time_series( events: &[MarketDataEvent], seq_len: usize, features_per_event: usize, @@ -166,7 +166,7 @@ pub fn events_to_time_series( } /// Load DQN states (convenience wrapper) -pub async fn load_dqn_states(count: usize, state_dim: usize) -> Result>> { +pub(crate) async fn load_dqn_states(count: usize, state_dim: usize) -> Result>> { let loader = RealDataLoader::new(); // Check if files exist, otherwise return empty (tests will skip) @@ -179,7 +179,7 @@ pub async fn load_dqn_states(count: usize, state_dim: usize) -> Result bool { +pub(crate) async fn real_data_available() -> bool { let loader = RealDataLoader::new(); loader.files_exist() } diff --git a/ml/tests/recovery_tests.rs b/ml/tests/recovery_tests.rs index 75f45b40c..a9455f1e8 100644 --- a/ml/tests/recovery_tests.rs +++ b/ml/tests/recovery_tests.rs @@ -38,7 +38,6 @@ use std::path::PathBuf; use tempfile::TempDir; use ml::mamba::{Mamba2Config, Mamba2SSM}; -use ml::dqn::{WorkingDQN, WorkingDQNConfig}; // ============================================================================ // Test Helpers diff --git a/ml/tests/streaming_pipeline_edge_cases.rs b/ml/tests/streaming_pipeline_edge_cases.rs index c14d8cb7d..c6e582790 100644 --- a/ml/tests/streaming_pipeline_edge_cases.rs +++ b/ml/tests/streaming_pipeline_edge_cases.rs @@ -42,7 +42,7 @@ //! - Out-of-order timestamps //! - Missing symbols -use anyhow::{Context, Result}; +use anyhow::Result; use ml::data_loaders::StreamingDbnLoader; use std::fs::{self, File}; use std::io::Write; diff --git a/services/api_gateway/src/main.rs b/services/api_gateway/src/main.rs index 0b6cc32b1..2e7438e80 100644 --- a/services/api_gateway/src/main.rs +++ b/services/api_gateway/src/main.rs @@ -318,7 +318,7 @@ async fn main() -> Result<()> { }); // Initialize REST API server for ML inference endpoints (port 8080) - if let Some(ml_proxy) = ml_training_proxy.as_ref() { + if let Some(_ml_proxy) = ml_training_proxy.as_ref() { let ml_config_rest = api_gateway::grpc::MlTrainingBackendConfig { address: ml_training_backend_url.clone(), connect_timeout_ms: 5000, diff --git a/services/backtesting_service/src/ml_strategy_engine.rs b/services/backtesting_service/src/ml_strategy_engine.rs index d6592d3ca..f48f88407 100644 --- a/services/backtesting_service/src/ml_strategy_engine.rs +++ b/services/backtesting_service/src/ml_strategy_engine.rs @@ -3,20 +3,20 @@ //! This module integrates the shared ML strategy from common crate to ensure //! ONE SINGLE SYSTEM across trading and backtesting services. -use anyhow::{Context, Result}; +use anyhow::Result; use chrono::{DateTime, Datelike, Timelike, Utc}; use std::collections::HashMap; use std::sync::Arc; -use tracing::{debug, error, info, warn}; +use tracing::{debug, info}; use serde::{Deserialize, Serialize}; -use rust_decimal::{Decimal, prelude::{ToPrimitive, FromPrimitive}}; +use rust_decimal::{Decimal, prelude::ToPrimitive}; use config::structures::BacktestingStrategyConfig; use crate::storage::StorageManager; use crate::strategy_engine::{MarketData, BacktestTrade, TradeSide, TradeSignal, StrategyExecutor, Portfolio}; // Import shared ML strategy (ONE SINGLE SYSTEM) -use common::ml_strategy::{SharedMLStrategy, MLPrediction as CommonMLPrediction, MLModelPerformance as CommonMLModelPerformance}; +use common::ml_strategy::{SharedMLStrategy, MLPrediction as CommonMLPrediction}; /// ML model prediction result for backtesting #[derive(Debug, Clone, Serialize, Deserialize)] @@ -179,6 +179,7 @@ pub struct MLPoweredStrategy { /// Shared ML strategy (ONE SINGLE SYSTEM) strategy: Arc, /// Feature extractor (kept for backward compatibility with local types) + #[allow(dead_code)] feature_extractor: MLFeatureExtractor, /// Model performance tracking (local copy for backward compatibility) model_performance: HashMap, @@ -460,7 +461,7 @@ impl MLStrategyEngine { ) .await?; - let mut trades = Vec::new(); + let trades = Vec::new(); let mut previous_price = None; let total_data_points = market_data.len(); diff --git a/services/ml_training_service/src/batch_tuning_manager.rs b/services/ml_training_service/src/batch_tuning_manager.rs index ef72e59b3..c8a74f0fb 100644 --- a/services/ml_training_service/src/batch_tuning_manager.rs +++ b/services/ml_training_service/src/batch_tuning_manager.rs @@ -146,7 +146,7 @@ impl BatchTuningManager { std::env::current_dir().unwrap().display()) }); - let mut job = BatchTuningJob { + let job = BatchTuningJob { batch_id, status: BatchJobStatus::Pending, models: models.clone(), @@ -296,7 +296,7 @@ impl BatchTuningManager { execution_order: Vec, trials_per_model: u32, config_path: String, - data_source_path: Option, + _data_source_path: Option, tuning_manager: Arc, jobs: Arc>>, _working_dir: String, @@ -390,7 +390,7 @@ impl BatchTuningManager { let successful = job.results.iter() .filter(|r| r.status == TuningJobStatus::Completed) .count(); - let failed = job.results.iter() + let _failed = job.results.iter() .filter(|r| r.status == TuningJobStatus::Failed) .count(); @@ -456,7 +456,7 @@ impl BatchTuningManager { pub async fn export_best_hyperparameters( &self, batch_id: Uuid, - output_path: &str, + _output_path: &str, ) -> Result<()> { let jobs = self.jobs.read().await; let job = jobs diff --git a/services/ml_training_service/src/checkpoint_manager.rs b/services/ml_training_service/src/checkpoint_manager.rs index bd98ecfab..17f103aa9 100644 --- a/services/ml_training_service/src/checkpoint_manager.rs +++ b/services/ml_training_service/src/checkpoint_manager.rs @@ -13,7 +13,7 @@ //! This module was built using Test-Driven Development (TDD). All tests in //! `tests/checkpoint_manager_tests.rs` passed after implementation. -use chrono::{DateTime, Duration, Utc}; +use chrono::{Duration, Utc}; use common::error::CommonError; use ml::checkpoint::{CheckpointMetadata, CheckpointStorage, FileSystemStorage}; use ml::ModelType; @@ -23,7 +23,7 @@ use sqlx::PgPool; use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; -use tracing::{debug, info, instrument, warn}; +use tracing::{debug, info, instrument}; /// Retention policy configuration for checkpoint management #[derive(Debug, Clone, Serialize, Deserialize)] @@ -58,6 +58,7 @@ pub struct CheckpointManager { retention_policy: RetentionPolicy, /// Checkpoint storage backend +#[allow(dead_code)] storage: Arc, } @@ -102,7 +103,7 @@ impl CheckpointManager { serde_json::Value::String(metadata.model_name.clone()), ); - let result = sqlx::query( + let _result = sqlx::query( r#" INSERT INTO ml_model_versions ( model_id, model_type, version, training_date, diff --git a/services/ml_training_service/src/deployment_pipeline.rs b/services/ml_training_service/src/deployment_pipeline.rs index 00479fef6..20b7437ba 100644 --- a/services/ml_training_service/src/deployment_pipeline.rs +++ b/services/ml_training_service/src/deployment_pipeline.rs @@ -12,7 +12,7 @@ //! - Health check: Verify model inference before routing traffic //! - Rollback: Automatic revert to previous model on failure -use anyhow::{Context, Result}; +use anyhow::Result; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; diff --git a/services/ml_training_service/src/ensemble_training_coordinator.rs b/services/ml_training_service/src/ensemble_training_coordinator.rs index 8fc162b0a..46a467374 100644 --- a/services/ml_training_service/src/ensemble_training_coordinator.rs +++ b/services/ml_training_service/src/ensemble_training_coordinator.rs @@ -17,10 +17,10 @@ use std::time::Instant; use anyhow::{anyhow, Result}; use chrono::{DateTime, Utc}; use tokio::sync::RwLock; -use tracing::{debug, error, info, warn}; +use tracing::{debug, info, warn}; use uuid::Uuid; -use ml::training_pipeline::{ProductionTrainingConfig, ProductionTrainingMetrics}; +use ml::training_pipeline::ProductionTrainingConfig; /// Status of individual model training within ensemble #[derive(Debug, Clone, PartialEq, Eq)] @@ -186,6 +186,7 @@ pub struct EnsembleTrainingCoordinator { current_weights: Arc>>, /// Ensemble-level metrics + #[allow(dead_code)] ensemble_metrics: Arc>>, /// Training start time diff --git a/services/ml_training_service/src/gpu_resource_manager.rs b/services/ml_training_service/src/gpu_resource_manager.rs index dd0f9d042..a0f6b8b4e 100644 --- a/services/ml_training_service/src/gpu_resource_manager.rs +++ b/services/ml_training_service/src/gpu_resource_manager.rs @@ -107,6 +107,7 @@ impl Drop for GPULock { /// GPU state tracking #[derive(Debug, Clone)] +#[allow(dead_code)] struct GPUState { gpu_id: u32, locked_by: Option, diff --git a/services/ml_training_service/src/job_queue.rs b/services/ml_training_service/src/job_queue.rs index dbb8abd8c..54444bbeb 100644 --- a/services/ml_training_service/src/job_queue.rs +++ b/services/ml_training_service/src/job_queue.rs @@ -18,7 +18,7 @@ use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; use std::sync::Arc; use tokio::sync::{Mutex, Semaphore, SemaphorePermit}; -use tracing::{debug, error, info, warn}; +use tracing::{debug, info, warn}; use uuid::Uuid; /// Job priority levels @@ -328,6 +328,7 @@ impl JobQueue { } /// Acquire GPU permit (blocks until available) + #[allow(clippy::mismatched_lifetime_syntaxes)] pub async fn acquire_gpu_permit(&self) -> Result { debug!("Acquiring GPU permit..."); let permit = self diff --git a/services/ml_training_service/src/monitoring.rs b/services/ml_training_service/src/monitoring.rs index 4cdb647a6..e1003d1bb 100644 --- a/services/ml_training_service/src/monitoring.rs +++ b/services/ml_training_service/src/monitoring.rs @@ -11,11 +11,11 @@ use anyhow::{Context, Result}; use chrono::{DateTime, Duration, Utc}; use reqwest::Client; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use tracing::{debug, info, warn}; +use tracing::{debug, info}; // ============================================================================ // Core Monitoring System @@ -23,9 +23,13 @@ use tracing::{debug, info, warn}; #[derive(Debug, Clone)] pub struct MonitoringSystem { + #[allow(dead_code)] config: MonitoringConfig, + #[allow(dead_code)] alert_manager: AlertManager, + #[allow(dead_code)] cost_tracker: Arc, + #[allow(dead_code)] drift_detector: Arc, } diff --git a/services/ml_training_service/src/validation_pipeline.rs b/services/ml_training_service/src/validation_pipeline.rs index 34a343e8e..f5af58e9f 100644 --- a/services/ml_training_service/src/validation_pipeline.rs +++ b/services/ml_training_service/src/validation_pipeline.rs @@ -10,7 +10,7 @@ use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use std::path::Path; -use tracing::{debug, error, info, warn}; +use tracing::{debug, error, info}; use uuid::Uuid; use crate::orchestrator::TrainingJob; @@ -172,7 +172,7 @@ impl ValidationPipeline { let holdout_data_path = self.resolve_holdout_data_path(training_job)?; info!("📊 Loading holdout dataset from: {}", holdout_data_path); - let holdout_data = match self.load_holdout_dataset().await { + let _holdout_data = match self.load_holdout_dataset().await { Ok(data) => { info!("✅ Loaded {} holdout bars", data.len()); data diff --git a/services/trading_agent_service/src/assets.rs b/services/trading_agent_service/src/assets.rs index d8aaf630c..0fbcd0079 100644 --- a/services/trading_agent_service/src/assets.rs +++ b/services/trading_agent_service/src/assets.rs @@ -8,7 +8,6 @@ //! - Liquidity (quality): 10% weight use std::collections::HashMap; -use common::Symbol; use serde::{Deserialize, Serialize}; /// Asset scoring result with multi-factor breakdown diff --git a/services/trading_agent_service/src/autonomous_scaling.rs b/services/trading_agent_service/src/autonomous_scaling.rs index 4c24dd2e0..da7b5d489 100644 --- a/services/trading_agent_service/src/autonomous_scaling.rs +++ b/services/trading_agent_service/src/autonomous_scaling.rs @@ -13,7 +13,6 @@ use bigdecimal::BigDecimal; use chrono::{DateTime, Utc}; -use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use std::str::FromStr; @@ -359,7 +358,9 @@ impl SymbolScore { /// Autonomous universe manager pub struct AutonomousUniverseManager { + #[allow(dead_code)] universe_selector: UniverseSelector, + #[allow(dead_code)] constraints: SystemConstraints, pool: PgPool, } diff --git a/services/trading_agent_service/src/service.rs b/services/trading_agent_service/src/service.rs index e23dfb956..eca849d43 100644 --- a/services/trading_agent_service/src/service.rs +++ b/services/trading_agent_service/src/service.rs @@ -14,6 +14,7 @@ use crate::strategies::{StrategyCoordinator, StrategyConfig as InternalStrategyC use crate::monitoring::TradingAgentMetrics; pub struct TradingAgentServiceImpl { + #[allow(dead_code)] db_pool: PgPool, universe_selector: UniverseSelector, strategy_coordinator: StrategyCoordinator, diff --git a/services/trading_service/src/dbn_market_data_generator.rs b/services/trading_service/src/dbn_market_data_generator.rs index c05dc2e7a..710c94268 100644 --- a/services/trading_service/src/dbn_market_data_generator.rs +++ b/services/trading_service/src/dbn_market_data_generator.rs @@ -122,7 +122,7 @@ impl DbnMarketDataGenerator { let mut decoder = DbnDecoder::from_file(file_path) .context(format!("Failed to create DBN decoder for file: {}", file_path))?; - decoder.set_upgrade_policy(VersionUpgradePolicy::UpgradeToV3); + let _ = decoder.set_upgrade_policy(VersionUpgradePolicy::UpgradeToV3); let mut bars = Vec::new(); diff --git a/services/trading_service/src/ensemble_coordinator.rs b/services/trading_service/src/ensemble_coordinator.rs index cc71b7634..955357aa8 100644 --- a/services/trading_service/src/ensemble_coordinator.rs +++ b/services/trading_service/src/ensemble_coordinator.rs @@ -657,6 +657,7 @@ pub struct SignalAggregator { signal_threshold: f64, /// Minimum confidence for high-confidence decisions + #[allow(dead_code)] min_confidence: f64, } diff --git a/services/trading_service/src/ensemble_risk_manager.rs b/services/trading_service/src/ensemble_risk_manager.rs index 0bace20aa..3a10a608b 100644 --- a/services/trading_service/src/ensemble_risk_manager.rs +++ b/services/trading_service/src/ensemble_risk_manager.rs @@ -176,6 +176,7 @@ pub struct EnsembleRiskManager { model_health: Arc>>, cascade_state: Arc>, circuit_breaker: Option>, +#[allow(dead_code)] var_engine: Arc, } diff --git a/services/trading_service/src/paper_trading_executor.rs b/services/trading_service/src/paper_trading_executor.rs index 42c727615..b67dc2ec6 100644 --- a/services/trading_service/src/paper_trading_executor.rs +++ b/services/trading_service/src/paper_trading_executor.rs @@ -140,6 +140,7 @@ pub struct PaperTradingExecutor { position_tracker: Arc>>>, // ML integration (shared strategy - ONE SINGLE SYSTEM) +#[allow(dead_code)] ml_strategy: Arc>, position_limits: Arc>>, } @@ -182,6 +183,7 @@ impl PaperTradingExecutor { } /// Generate rule-based signal (fallback) (NEW) + #[allow(dead_code)] async fn generate_rule_based_signal(&self, market_data: &[(f64, f64, f64, f64, f64)]) -> Result { // Simple moving average crossover strategy if market_data.len() < 20 { diff --git a/services/trading_service/src/prediction_generation_loop.rs b/services/trading_service/src/prediction_generation_loop.rs index 558edfa8b..5adae86a9 100644 --- a/services/trading_service/src/prediction_generation_loop.rs +++ b/services/trading_service/src/prediction_generation_loop.rs @@ -451,7 +451,9 @@ struct MarketDataSnapshot { /// OHLCV bar from database #[derive(Debug, Clone, sqlx::FromRow)] struct OhlcvBar { + #[allow(dead_code)] timestamp: chrono::DateTime, + #[allow(dead_code)] symbol: String, open: f64, high: f64, diff --git a/services/trading_service/src/rollback_automation.rs b/services/trading_service/src/rollback_automation.rs index 621a55c56..6e37f301c 100644 --- a/services/trading_service/src/rollback_automation.rs +++ b/services/trading_service/src/rollback_automation.rs @@ -146,9 +146,9 @@ impl Default for RollbackConfig { /// Disagreement tracking entry #[derive(Debug, Clone)] -struct DisagreementEntry { - timestamp: Instant, - rate: f64, +pub struct DisagreementEntry { + pub timestamp: Instant, + pub rate: f64, } /// Rollback automation state diff --git a/services/trading_service/src/services/enhanced_ml.rs b/services/trading_service/src/services/enhanced_ml.rs index 8ed37e016..e3a8a48d8 100644 --- a/services/trading_service/src/services/enhanced_ml.rs +++ b/services/trading_service/src/services/enhanced_ml.rs @@ -1425,6 +1425,7 @@ impl MLModel for RealPPOModel { struct RealTFTModel { model_id: String, model: Arc>, + #[allow(dead_code)] config: ml::tft::TFTConfig, } diff --git a/services/trading_service/src/services/trading.rs b/services/trading_service/src/services/trading.rs index 4bb0b0874..e0d0b1999 100644 --- a/services/trading_service/src/services/trading.rs +++ b/services/trading_service/src/services/trading.rs @@ -1097,7 +1097,7 @@ impl trading_service_server::TradingService for TradingServiceImpl { start_time: Option, end_time: Option, ) -> TonicResult { - use chrono::{DateTime, Utc}; + use chrono::DateTime; // Convert timestamps to DateTime let start_dt = start_time.and_then(|ts| DateTime::from_timestamp(ts, 0)); diff --git a/services/trading_service/tests/ab_testing_pipeline_tests.rs b/services/trading_service/tests/ab_testing_pipeline_tests.rs index 6e5d97ab7..27883f719 100644 --- a/services/trading_service/tests/ab_testing_pipeline_tests.rs +++ b/services/trading_service/tests/ab_testing_pipeline_tests.rs @@ -12,15 +12,10 @@ use anyhow::Result; use sqlx::PgPool; -use std::sync::Arc; -use tokio::sync::RwLock; use uuid::Uuid; -use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering}; use trading_service::ab_testing_pipeline::{ - ABTestingPipeline, ABTestingConfig, ABTestState, DeploymentDecision, - TrafficSplitMetrics, ModelPerformanceMetrics, + ABTestingPipeline, ABTestingConfig, DeploymentDecision, ModelPerformanceMetrics, }; /// Test helper: Create test database pool diff --git a/services/trading_service/tests/rollback_automation_integration_tests.rs b/services/trading_service/tests/rollback_automation_integration_tests.rs index 31b57c3aa..4c063fc11 100644 --- a/services/trading_service/tests/rollback_automation_integration_tests.rs +++ b/services/trading_service/tests/rollback_automation_integration_tests.rs @@ -7,7 +7,6 @@ //! 3. ModelFailure (>3 consecutive errors) //! 4. CascadeFailure (2+ models fail) -use std::sync::Arc; use std::time::Duration; use tokio; use trading_service::rollback_automation::{ diff --git a/tests/e2e/src/clients.rs b/tests/e2e/src/clients.rs index d54bf7fae..8ed22338a 100644 --- a/tests/e2e/src/clients.rs +++ b/tests/e2e/src/clients.rs @@ -1,4 +1,9 @@ //! Test client utilities for e2e testing +//! +//! This module contains deprecated client structs for backwards compatibility. +//! All new tests should use E2ETestFramework instead. + +#![allow(deprecated)] use crate::proto::backtesting::backtesting_service_client::BacktestingServiceClient; use crate::proto::config::config_service_client::ConfigServiceClient; diff --git a/tests/e2e/src/workflows.rs b/tests/e2e/src/workflows.rs index 745523f45..36da6bc61 100644 --- a/tests/e2e/src/workflows.rs +++ b/tests/e2e/src/workflows.rs @@ -7,6 +7,8 @@ //! - Backtesting workflows //! - Error handling and recovery scenarios +#![allow(deprecated)] + use anyhow::{Context, Result}; use std::collections::HashMap; use std::sync::Arc; diff --git a/tli/src/main.rs b/tli/src/main.rs index f0fd4de94..26af1b233 100644 --- a/tli/src/main.rs +++ b/tli/src/main.rs @@ -38,13 +38,17 @@ use base64 as _; use chrono as _; use clap as _; use colored as _; +use comfy_table as _; use common as _; +use console as _; use crossterm as _; use dirs as _; use futures_util as _; use getrandom as _; use hex as _; +use indicatif as _; use keyring as _; +use owo_colors as _; use prost as _; use rand as _; use ratatui as _;