Skip to main content

trustformers_mobile/
android_work_manager.rs

1//! Android Work Manager Integration for TrustformeRS Mobile
2//!
3//! This module provides comprehensive Android WorkManager integration, enabling
4//! TrustformeRS to schedule and execute background tasks, deferred inference,
5//! model updates, and federated learning operations that survive app restarts
6//! and device reboots.
7
8use crate::{
9    device_info::{MobileDeviceDetector, MobileDeviceInfo},
10    inference::MobileInferenceEngine,
11    model_management::ModelManager,
12    MemoryOptimization, MobileConfig,
13};
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16use std::sync::{Arc, Mutex};
17use trustformers_core::errors::Result;
18use trustformers_core::{Tensor, TrustformersError};
19
20/// Android Work Manager configuration
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct AndroidWorkManagerConfig {
23    /// Enable periodic work scheduling
24    pub enable_periodic_work: bool,
25    /// Enable one-time work requests
26    pub enable_one_time_work: bool,
27    /// Enable expedited work for urgent tasks
28    pub enable_expedited_work: bool,
29    /// Work constraints configuration
30    pub constraints: WorkConstraintsConfig,
31    /// Retry policy configuration
32    pub retry_policy: WorkRetryPolicyConfig,
33    /// Background execution configuration
34    pub background_execution: BackgroundExecutionConfig,
35    /// Data synchronization configuration
36    pub data_sync: DataSyncConfig,
37}
38
39/// Work constraints configuration
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct WorkConstraintsConfig {
42    /// Require unmetered network (WiFi)
43    pub require_unmetered_network: bool,
44    /// Require charging
45    pub require_charging: bool,
46    /// Require device idle
47    pub require_device_idle: bool,
48    /// Require battery not low
49    pub require_battery_not_low: bool,
50    /// Required network type
51    pub required_network_type: WorkNetworkType,
52    /// Storage constraints
53    pub storage_constraints: StorageConstraints,
54}
55
56/// Required network types for work
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub enum WorkNetworkType {
59    /// No network required
60    NotRequired,
61    /// Any network connection
62    Connected,
63    /// Unmetered network only (WiFi)
64    Unmetered,
65    /// Not roaming
66    NotRoaming,
67    /// Metered network allowed
68    Metered,
69}
70
71/// Storage constraints for work
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct StorageConstraints {
74    /// Minimum free storage in MB
75    pub min_free_storage_mb: usize,
76    /// Maximum storage usage for cache in MB
77    pub max_cache_storage_mb: usize,
78    /// Enable storage cleanup
79    pub enable_storage_cleanup: bool,
80}
81
82/// Work retry policy configuration
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct WorkRetryPolicyConfig {
85    /// Retry policy type
86    pub retry_policy: WorkRetryPolicy,
87    /// Maximum retry attempts
88    pub max_retry_attempts: usize,
89    /// Initial retry delay in milliseconds
90    pub initial_retry_delay_ms: f64,
91    /// Maximum retry delay in milliseconds
92    pub max_retry_delay_ms: f64,
93    /// Backoff multiplier
94    pub backoff_multiplier: f64,
95}
96
97/// Work retry policies
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99pub enum WorkRetryPolicy {
100    /// Linear backoff
101    Linear,
102    /// Exponential backoff
103    Exponential,
104    /// No retry
105    None,
106}
107
108/// Background execution configuration
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct BackgroundExecutionConfig {
111    /// Maximum execution time in seconds
112    pub max_execution_time_seconds: f64,
113    /// Enable foreground service for long-running tasks
114    pub enable_foreground_service: bool,
115    /// Foreground service notification configuration
116    pub foreground_notification: ForegroundNotificationConfig,
117    /// Background task prioritization
118    pub task_prioritization: TaskPrioritizationConfig,
119}
120
121/// Foreground notification configuration
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct ForegroundNotificationConfig {
124    /// Notification channel ID
125    pub channel_id: String,
126    /// Notification title
127    pub title: String,
128    /// Notification content text
129    pub content_text: String,
130    /// Enable progress indicator
131    pub show_progress: bool,
132    /// Enable cancel action
133    pub enable_cancel_action: bool,
134}
135
136/// Task prioritization configuration
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct TaskPrioritizationConfig {
139    /// High priority task types
140    pub high_priority_tasks: Vec<WorkTaskType>,
141    /// Enable adaptive prioritization
142    pub enable_adaptive_prioritization: bool,
143    /// Priority adjustment based on device state
144    pub device_state_priority_adjustment: bool,
145    /// Task execution order strategy
146    pub execution_order: TaskExecutionOrder,
147}
148
149/// Task execution order strategies
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
151pub enum TaskExecutionOrder {
152    /// First In, First Out
153    FIFO,
154    /// Last In, First Out
155    LIFO,
156    /// Priority-based
157    Priority,
158    /// Deadline-based
159    Deadline,
160    /// Resource-aware
161    ResourceAware,
162}
163
164/// Data synchronization configuration
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct DataSyncConfig {
167    /// Enable automatic model updates
168    pub enable_model_updates: bool,
169    /// Enable federated learning sync
170    pub enable_federated_sync: bool,
171    /// Sync frequency for periodic tasks
172    pub sync_frequency: WorkFrequency,
173    /// Conflict resolution strategy
174    pub conflict_resolution: ConflictResolutionStrategy,
175    /// Data compression settings
176    pub compression_settings: DataCompressionConfig,
177}
178
179/// Work frequency settings
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct WorkFrequency {
182    /// Interval in minutes
183    pub interval_minutes: usize,
184    /// Flex interval in minutes
185    pub flex_interval_minutes: usize,
186    /// Initial delay in minutes
187    pub initial_delay_minutes: usize,
188}
189
190/// Conflict resolution strategies
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192pub enum ConflictResolutionStrategy {
193    /// Server wins
194    ServerWins,
195    /// Client wins
196    ClientWins,
197    /// Last modified wins
198    LastModifiedWins,
199    /// Merge conflicts
200    Merge,
201    /// Manual resolution required
202    Manual,
203}
204
205/// Data compression configuration
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct DataCompressionConfig {
208    /// Enable compression
209    pub enable_compression: bool,
210    /// Compression algorithm
211    pub algorithm: CompressionAlgorithm,
212    /// Compression level (1-9)
213    pub compression_level: u8,
214    /// Minimum size threshold for compression (bytes)
215    pub min_size_threshold_bytes: usize,
216}
217
218/// Compression algorithms
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220pub enum CompressionAlgorithm {
221    /// GZIP compression
222    Gzip,
223    /// LZ4 compression
224    LZ4,
225    /// Brotli compression
226    Brotli,
227    /// Snappy compression
228    Snappy,
229}
230
231/// Work task types
232// Not `Copy`: the `Custom(String)` variant holds a `String`.
233#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
234pub enum WorkTaskType {
235    /// Model inference task
236    Inference,
237    /// Model download task
238    ModelDownload,
239    /// Model update task
240    ModelUpdate,
241    /// Federated learning task
242    FederatedLearning,
243    /// Data preprocessing task
244    DataPreprocessing,
245    /// Cache cleanup task
246    CacheCleanup,
247    /// Performance profiling task
248    PerformanceProfiling,
249    /// Health check task
250    HealthCheck,
251    /// Custom task
252    Custom(String),
253}
254
255/// Work request specification
256#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct WorkRequest {
258    /// Unique work ID
259    pub work_id: String,
260    /// Work type
261    pub work_type: WorkRequestType,
262    /// Task type
263    pub task_type: WorkTaskType,
264    /// Work priority
265    pub priority: WorkPriority,
266    /// Input data
267    pub input_data: WorkInputData,
268    /// Work constraints
269    pub constraints: Option<WorkConstraintsConfig>,
270    /// Custom tags
271    pub tags: Vec<String>,
272    /// Work deadline
273    pub deadline: Option<std::time::SystemTime>,
274}
275
276/// Work request types
277#[derive(Debug, Clone, Serialize, Deserialize)]
278pub enum WorkRequestType {
279    /// One-time work
280    OneTime {
281        /// Initial delay in minutes
282        initial_delay_minutes: usize,
283        /// Enable expedited execution
284        expedited: bool,
285    },
286    /// Periodic work
287    Periodic {
288        /// Repeat interval
289        frequency: WorkFrequency,
290        /// Keep existing work policy
291        existing_work_policy: ExistingWorkPolicy,
292    },
293}
294
295/// Existing work policies
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
297pub enum ExistingWorkPolicy {
298    /// Replace existing work
299    Replace,
300    /// Keep existing work
301    Keep,
302    /// Append to existing work
303    Append,
304    /// Replace if running
305    ReplaceIfRunning,
306}
307
308/// Work priority levels
309#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
310pub enum WorkPriority {
311    /// Minimum priority
312    Min = 0,
313    /// Low priority
314    Low = 1,
315    /// Default priority
316    Default = 2,
317    /// High priority
318    High = 3,
319    /// Maximum priority
320    Max = 4,
321}
322
323/// Work input data
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct WorkInputData {
326    /// Model ID (if applicable)
327    pub model_id: Option<String>,
328    /// Input tensor data
329    pub tensor_data: Option<Vec<f32>>,
330    /// Input shape
331    pub tensor_shape: Option<Vec<usize>>,
332    /// Configuration overrides
333    pub config_overrides: Option<HashMap<String, serde_json::Value>>,
334    /// Custom parameters
335    pub custom_params: HashMap<String, serde_json::Value>,
336}
337
338/// Work execution result
339#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct WorkResult {
341    /// Work ID
342    pub work_id: String,
343    /// Success flag
344    pub success: bool,
345    /// Result data
346    pub result_data: Option<WorkResultData>,
347    /// Error information
348    pub error: Option<WorkError>,
349    /// Execution metrics
350    pub metrics: WorkExecutionMetrics,
351    /// Retry information
352    pub retry_info: WorkRetryInfo,
353}
354
355/// Work result data
356#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct WorkResultData {
358    /// Output tensor data
359    pub output_data: Option<Vec<f32>>,
360    /// Output shape
361    pub output_shape: Option<Vec<usize>>,
362    /// Status message
363    pub status_message: String,
364    /// Additional result metadata
365    pub metadata: HashMap<String, serde_json::Value>,
366}
367
368/// Work error information
369#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct WorkError {
371    /// Error code
372    pub code: String,
373    /// Error message
374    pub message: String,
375    /// Error category
376    pub category: WorkErrorCategory,
377    /// Is recoverable
378    pub recoverable: bool,
379    /// Suggested retry delay
380    pub suggested_retry_delay_ms: Option<f64>,
381}
382
383/// Work error categories
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub enum WorkErrorCategory {
386    /// Network error
387    Network,
388    /// Storage error
389    Storage,
390    /// Memory error
391    Memory,
392    /// Model error
393    Model,
394    /// Configuration error
395    Configuration,
396    /// Timeout error
397    Timeout,
398    /// Permission error
399    Permission,
400    /// System error
401    System,
402    /// Unknown error
403    Unknown,
404}
405
406/// Work execution metrics
407#[derive(Debug, Clone, Serialize, Deserialize)]
408pub struct WorkExecutionMetrics {
409    /// Start time
410    pub start_time: std::time::SystemTime,
411    /// End time
412    pub end_time: std::time::SystemTime,
413    /// Execution duration in milliseconds
414    pub duration_ms: f64,
415    /// Memory used in MB
416    pub memory_used_mb: usize,
417    /// CPU usage percentage
418    pub cpu_usage_percent: f64,
419    /// Network bytes transferred
420    pub network_bytes: usize,
421    /// Storage bytes used
422    pub storage_bytes: usize,
423}
424
425/// Work retry information
426#[derive(Debug, Clone, Serialize, Deserialize)]
427pub struct WorkRetryInfo {
428    /// Current retry attempt
429    pub attempt_count: usize,
430    /// Maximum retry attempts
431    pub max_attempts: usize,
432    /// Next retry time
433    pub next_retry_time: Option<std::time::SystemTime>,
434    /// Backoff delay in milliseconds
435    pub backoff_delay_ms: f64,
436}
437
438/// Android Work Manager
439pub struct AndroidWorkManager {
440    config: AndroidWorkManagerConfig,
441    inference_engine: Arc<Mutex<MobileInferenceEngine>>,
442    // `tokio::sync::Mutex`, not `std::sync::Mutex`: `execute_model_download_work` /
443    // `execute_model_update_work` hold this guard across an `.await` (the download/update
444    // call itself is async), which makes the enclosing future non-`Send` under a
445    // `std::sync::MutexGuard` and fails to compile under `tokio::spawn`'s `Send` bound.
446    // `tokio::sync::MutexGuard` is `Send`, so it does not have that restriction.
447    model_manager: Arc<tokio::sync::Mutex<ModelManager>>,
448    work_queue: Arc<Mutex<WorkQueue>>,
449    work_executor: Arc<Mutex<WorkExecutor>>,
450    work_statistics: Arc<Mutex<WorkStatistics>>,
451}
452
453/// Work queue management
454#[derive(Debug)]
455struct WorkQueue {
456    pending_work: HashMap<String, WorkRequest>,
457    running_work: HashMap<String, WorkExecution>,
458    completed_work: HashMap<String, WorkResult>,
459    work_priorities: std::collections::BinaryHeap<PriorityWorkItem>,
460}
461
462/// Priority work item for queue ordering
463#[derive(Debug, Clone, PartialEq, Eq)]
464struct PriorityWorkItem {
465    work_id: String,
466    priority: WorkPriority,
467    deadline: Option<std::time::SystemTime>,
468    created_at: std::time::SystemTime,
469}
470
471impl Ord for PriorityWorkItem {
472    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
473        // Higher priority first, then by deadline, then by creation time
474        self.priority
475            .cmp(&other.priority)
476            .then_with(|| match (&self.deadline, &other.deadline) {
477                (Some(a), Some(b)) => a.cmp(b),
478                (Some(_), None) => std::cmp::Ordering::Greater,
479                (None, Some(_)) => std::cmp::Ordering::Less,
480                (None, None) => std::cmp::Ordering::Equal,
481            })
482            .then_with(|| self.created_at.cmp(&other.created_at))
483    }
484}
485
486impl PartialOrd for PriorityWorkItem {
487    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
488        Some(self.cmp(other))
489    }
490}
491
492/// Work execution tracking
493#[derive(Debug, Clone)]
494struct WorkExecution {
495    work_request: WorkRequest,
496    start_time: std::time::SystemTime,
497    executor_thread: Option<String>,
498    progress: f64,
499    can_cancel: bool,
500}
501
502/// Work executor
503#[derive(Debug)]
504struct WorkExecutor {
505    max_concurrent_workers: usize,
506    active_workers: usize,
507    worker_threads: HashMap<String, WorkerThread>,
508    execution_context: ExecutionContext,
509}
510
511/// Worker thread information
512#[derive(Debug, Clone)]
513struct WorkerThread {
514    thread_id: String,
515    current_work_id: Option<String>,
516    start_time: std::time::SystemTime,
517    cpu_affinity: Option<Vec<usize>>,
518}
519
520/// Execution context
521#[derive(Debug, Clone)]
522struct ExecutionContext {
523    device_info: MobileDeviceInfo,
524    available_memory_mb: usize,
525    battery_level: f64,
526    is_charging: bool,
527    network_type: WorkNetworkType,
528    thermal_state: f64,
529}
530
531/// Work statistics
532#[derive(Debug, Clone)]
533struct WorkStatistics {
534    total_work_requests: usize,
535    completed_work_requests: usize,
536    failed_work_requests: usize,
537    retried_work_requests: usize,
538    average_execution_time_ms: f64,
539    success_rate_by_type: HashMap<WorkTaskType, f64>,
540    resource_usage_stats: ResourceUsageStats,
541}
542
543/// Resource usage statistics
544#[derive(Debug, Clone)]
545struct ResourceUsageStats {
546    average_memory_usage_mb: f64,
547    peak_memory_usage_mb: usize,
548    average_cpu_usage_percent: f64,
549    total_network_bytes: usize,
550    total_storage_bytes: usize,
551}
552
553impl AndroidWorkManager {
554    /// Create new Android Work Manager
555    pub fn new(config: AndroidWorkManagerConfig, mobile_config: MobileConfig) -> Result<Self> {
556        config.validate()?;
557
558        let inference_engine = Arc::new(Mutex::new(MobileInferenceEngine::new(mobile_config)?));
559        let model_manager = Arc::new(tokio::sync::Mutex::new(ModelManager::new_default()?));
560        let work_queue = Arc::new(Mutex::new(WorkQueue::new()));
561        let work_executor = Arc::new(Mutex::new(WorkExecutor::new(&config)));
562        let work_statistics = Arc::new(Mutex::new(WorkStatistics::new()));
563
564        Ok(Self {
565            config,
566            inference_engine,
567            model_manager,
568            work_queue,
569            work_executor,
570            work_statistics,
571        })
572    }
573
574    /// Enqueue work request
575    pub async fn enqueue_work(&self, work_request: WorkRequest) -> Result<String> {
576        tracing::info!(
577            "Enqueuing work: {} (type: {:?})",
578            work_request.work_id,
579            work_request.task_type
580        );
581
582        // Validate work request
583        self.validate_work_request(&work_request)?;
584
585        // Check constraints
586        if !self.check_work_constraints(&work_request).await? {
587            return Err(TrustformersError::runtime_error(
588                "Work constraints not met".to_string(),
589            ));
590        }
591
592        // Add to queue
593        {
594            let mut queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
595            queue.enqueue_work(work_request.clone());
596        }
597
598        // Update statistics
599        {
600            let mut stats = self.work_statistics.lock().unwrap_or_else(|p| p.into_inner());
601            stats.total_work_requests += 1;
602        }
603
604        // Try to schedule immediate execution if possible
605        self.try_schedule_work()?;
606
607        Ok(work_request.work_id)
608    }
609
610    /// Cancel work by ID
611    pub async fn cancel_work(&self, work_id: &str) -> Result<bool> {
612        tracing::info!("Cancelling work: {}", work_id);
613
614        let mut queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
615
616        // Remove from pending queue
617        if queue.pending_work.remove(work_id).is_some() {
618            return Ok(true);
619        }
620
621        // Try to cancel running work
622        if let Some(execution) = queue.running_work.get(work_id) {
623            if execution.can_cancel {
624                // Signal cancellation to executor
625                let mut executor = self.work_executor.lock().unwrap_or_else(|p| p.into_inner());
626                executor.cancel_work(work_id);
627                queue.running_work.remove(work_id);
628                return Ok(true);
629            }
630        }
631
632        Ok(false)
633    }
634
635    /// Get work status
636    pub fn get_work_status(&self, work_id: &str) -> Result<WorkStatus> {
637        let queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
638
639        if queue.pending_work.contains_key(work_id) {
640            Ok(WorkStatus::Pending)
641        } else if queue.running_work.contains_key(work_id) {
642            Ok(WorkStatus::Running)
643        } else if let Some(result) = queue.completed_work.get(work_id) {
644            if result.success {
645                Ok(WorkStatus::Succeeded)
646            } else {
647                Ok(WorkStatus::Failed)
648            }
649        } else {
650            Ok(WorkStatus::Unknown)
651        }
652    }
653
654    /// Get work result
655    pub fn get_work_result(&self, work_id: &str) -> Result<Option<WorkResult>> {
656        let queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
657        Ok(queue.completed_work.get(work_id).cloned())
658    }
659
660    /// Get work statistics
661    pub fn get_work_statistics(&self) -> Result<String> {
662        let stats = self.work_statistics.lock().unwrap_or_else(|p| p.into_inner());
663
664        let stats_json = serde_json::json!({
665            "total_work_requests": stats.total_work_requests,
666            "completed_work_requests": stats.completed_work_requests,
667            "failed_work_requests": stats.failed_work_requests,
668            "retried_work_requests": stats.retried_work_requests,
669            "success_rate": if stats.total_work_requests > 0 {
670                stats.completed_work_requests as f64 / stats.total_work_requests as f64
671            } else { 0.0 },
672            "average_execution_time_ms": stats.average_execution_time_ms,
673            "success_rate_by_type": stats.success_rate_by_type,
674            "resource_usage": {
675                "average_memory_usage_mb": stats.resource_usage_stats.average_memory_usage_mb,
676                "peak_memory_usage_mb": stats.resource_usage_stats.peak_memory_usage_mb,
677                "average_cpu_usage_percent": stats.resource_usage_stats.average_cpu_usage_percent,
678                "total_network_bytes": stats.resource_usage_stats.total_network_bytes,
679                "total_storage_bytes": stats.resource_usage_stats.total_storage_bytes
680            }
681        });
682
683        Ok(stats_json.to_string())
684    }
685
686    /// List all pending work
687    pub fn list_pending_work(&self) -> Result<Vec<String>> {
688        let queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
689        Ok(queue.pending_work.keys().cloned().collect())
690    }
691
692    /// List all running work
693    pub fn list_running_work(&self) -> Result<Vec<String>> {
694        let queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
695        Ok(queue.running_work.keys().cloned().collect())
696    }
697
698    /// Clean up completed work older than specified duration
699    pub fn cleanup_completed_work(&self, older_than_hours: f64) -> Result<usize> {
700        let mut queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
701        let cutoff_time = std::time::SystemTime::now()
702            - std::time::Duration::from_secs_f64(older_than_hours * 3600.0);
703
704        let initial_count = queue.completed_work.len();
705        queue.completed_work.retain(|_, result| result.metrics.end_time > cutoff_time);
706
707        let cleaned_count = initial_count - queue.completed_work.len();
708        Ok(cleaned_count)
709    }
710
711    // Private helper methods
712
713    // Deliberately NOT `async fn`: its body has no `.await` of its own -- it only
714    // *constructs* a future and hands it to `tokio::spawn` without polling it inline.
715    // Declaring it `async fn` anyway made its opaque return-position-`impl Future` type
716    // mutually recursive with `complete_work`'s (this fn spawns a task that awaits
717    // `complete_work`, which itself `.await`s this fn), which rustc's Send auto-trait
718    // solver cannot resolve through a `tokio::spawn` boundary -- "future cannot be sent
719    // between threads safely" even though no `MutexGuard` is ever actually held across a
720    // real suspension point. Keeping this synchronous removes the opaque `Future` type
721    // (and the cycle) entirely rather than papering over it with a `Box::pin` erasure.
722    fn try_schedule_work(&self) -> Result<()> {
723        let executor = self.work_executor.lock().unwrap_or_else(|p| p.into_inner());
724        let mut queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
725
726        // Check if we can schedule more work
727        if executor.can_accept_more_work() {
728            if let Some(work_item) = queue.get_next_work() {
729                if let Some(work_request) = queue.pending_work.remove(&work_item.work_id) {
730                    let execution = WorkExecution {
731                        work_request: work_request.clone(),
732                        start_time: std::time::SystemTime::now(),
733                        executor_thread: None,
734                        progress: 0.0,
735                        can_cancel: true,
736                    };
737
738                    queue.running_work.insert(work_request.work_id.clone(), execution);
739
740                    // Execute work asynchronously
741                    let work_manager = self.clone_for_execution();
742                    let work_id = work_request.work_id.clone();
743
744                    tokio::spawn(async move {
745                        let result = work_manager.execute_work(work_request).await;
746                        work_manager.complete_work(&work_id, result).await;
747                    });
748                }
749            }
750        }
751
752        Ok(())
753    }
754
755    async fn execute_work(&self, work_request: WorkRequest) -> WorkResult {
756        let start_time = std::time::SystemTime::now();
757
758        let result = match work_request.task_type {
759            WorkTaskType::Inference => self.execute_inference_work(&work_request).await,
760            WorkTaskType::ModelDownload => self.execute_model_download_work(&work_request).await,
761            WorkTaskType::ModelUpdate => self.execute_model_update_work(&work_request).await,
762            WorkTaskType::FederatedLearning => {
763                self.execute_federated_learning_work(&work_request).await
764            },
765            WorkTaskType::DataPreprocessing => {
766                self.execute_data_preprocessing_work(&work_request).await
767            },
768            WorkTaskType::CacheCleanup => self.execute_cache_cleanup_work(&work_request).await,
769            WorkTaskType::PerformanceProfiling => {
770                self.execute_performance_profiling_work(&work_request).await
771            },
772            WorkTaskType::HealthCheck => self.execute_health_check_work(&work_request).await,
773            WorkTaskType::Custom(_) => self.execute_custom_work(&work_request).await,
774        };
775
776        let end_time = std::time::SystemTime::now();
777        let duration = end_time.duration_since(start_time).unwrap_or_default();
778
779        let metrics = WorkExecutionMetrics {
780            start_time,
781            end_time,
782            duration_ms: duration.as_millis() as f64,
783            memory_used_mb: self.get_current_memory_usage(),
784            cpu_usage_percent: self.get_current_cpu_usage(),
785            network_bytes: 0, // Would be tracked during execution
786            storage_bytes: 0, // Would be tracked during execution
787        };
788
789        match result {
790            Ok(result_data) => WorkResult {
791                work_id: work_request.work_id,
792                success: true,
793                result_data: Some(result_data),
794                error: None,
795                metrics,
796                retry_info: WorkRetryInfo {
797                    attempt_count: 1,
798                    max_attempts: self.config.retry_policy.max_retry_attempts,
799                    next_retry_time: None,
800                    backoff_delay_ms: 0.0,
801                },
802            },
803            Err(error) => WorkResult {
804                work_id: work_request.work_id,
805                success: false,
806                result_data: None,
807                error: Some(WorkError {
808                    code: "EXECUTION_ERROR".to_string(),
809                    message: error.to_string(),
810                    category: WorkErrorCategory::System,
811                    recoverable: true,
812                    suggested_retry_delay_ms: Some(self.config.retry_policy.initial_retry_delay_ms),
813                }),
814                metrics,
815                retry_info: WorkRetryInfo {
816                    attempt_count: 1,
817                    max_attempts: self.config.retry_policy.max_retry_attempts,
818                    next_retry_time: Some(
819                        std::time::SystemTime::now()
820                            + std::time::Duration::from_millis(
821                                self.config.retry_policy.initial_retry_delay_ms as u64,
822                            ),
823                    ),
824                    backoff_delay_ms: self.config.retry_policy.initial_retry_delay_ms,
825                },
826            },
827        }
828    }
829
830    async fn complete_work(&self, work_id: &str, result: WorkResult) {
831        // Move work from running to completed
832        {
833            let mut queue = self.work_queue.lock().unwrap_or_else(|p| p.into_inner());
834            queue.running_work.remove(work_id);
835            queue.completed_work.insert(work_id.to_string(), result.clone());
836        }
837
838        // Update statistics
839        {
840            let mut stats = self.work_statistics.lock().unwrap_or_else(|p| p.into_inner());
841            if result.success {
842                stats.completed_work_requests += 1;
843            } else {
844                stats.failed_work_requests += 1;
845            }
846
847            // Update running average execution time
848            let alpha = 0.1;
849            if stats.completed_work_requests + stats.failed_work_requests == 1 {
850                stats.average_execution_time_ms = result.metrics.duration_ms;
851            } else {
852                stats.average_execution_time_ms = alpha * result.metrics.duration_ms
853                    + (1.0 - alpha) * stats.average_execution_time_ms;
854            }
855        }
856
857        // Try to schedule next work
858        let _ = self.try_schedule_work();
859    }
860
861    fn clone_for_execution(&self) -> Self {
862        Self {
863            config: self.config.clone(),
864            inference_engine: self.inference_engine.clone(),
865            model_manager: self.model_manager.clone(),
866            work_queue: self.work_queue.clone(),
867            work_executor: self.work_executor.clone(),
868            work_statistics: self.work_statistics.clone(),
869        }
870    }
871
872    // Work execution implementations for different task types
873    async fn execute_inference_work(&self, work_request: &WorkRequest) -> Result<WorkResultData> {
874        if let Some(ref model_id) = work_request.input_data.model_id {
875            if let (Some(ref tensor_data), Some(ref tensor_shape)) = (
876                &work_request.input_data.tensor_data,
877                &work_request.input_data.tensor_shape,
878            ) {
879                let input_tensor = Tensor::from_vec(tensor_data.clone(), tensor_shape)?;
880
881                let result = {
882                    let mut engine =
883                        self.inference_engine.lock().unwrap_or_else(|p| p.into_inner());
884                    // `MobileInferenceEngine` holds one loaded model at a
885                    // time and has no per-`model_id` dispatch (see its own
886                    // doc comment in `inference.rs`) -- it runs whichever
887                    // checkpoint was most recently loaded into this
888                    // `AndroidWorkManager`'s shared engine, regardless of
889                    // which `model_id` this work item names. This is an
890                    // existing single-model-engine limitation of
891                    // `AndroidWorkManager`, not something this fix
892                    // introduces; the previous call here
893                    // (`engine.inference(model_id, &input_tensor)`) did not
894                    // even match `MobileInferenceEngine::inference`'s real
895                    // one-argument signature and could not have compiled.
896                    if !engine.has_loaded_model() {
897                        return Err(TrustformersError::runtime_error(format!(
898                            "no model is loaded in the shared inference engine (requested \
899                             model_id '{model_id}')"
900                        )));
901                    }
902                    engine.inference(&input_tensor)?
903                };
904
905                let output_data = result.data_f32()?.to_vec();
906                let output_shape = result.shape().to_vec();
907
908                Ok(WorkResultData {
909                    output_data: Some(output_data),
910                    output_shape: Some(output_shape),
911                    status_message: "Inference completed successfully".to_string(),
912                    metadata: HashMap::new(),
913                })
914            } else {
915                Err(TrustformersError::runtime_error(
916                    "Missing tensor data for inference".into(),
917                ))
918            }
919        } else {
920            Err(TrustformersError::runtime_error(
921                "Missing model ID for inference".into(),
922            ))
923        }
924    }
925
926    async fn execute_model_download_work(
927        &self,
928        work_request: &WorkRequest,
929    ) -> Result<WorkResultData> {
930        if let Some(ref model_id) = work_request.input_data.model_id {
931            let mut model_manager = self.model_manager.lock().await;
932            // Simulate model download
933            model_manager.download_model(model_id, None).await?;
934
935            Ok(WorkResultData {
936                output_data: None,
937                output_shape: None,
938                status_message: format!("Model {} downloaded successfully", model_id),
939                metadata: HashMap::new(),
940            })
941        } else {
942            Err(TrustformersError::runtime_error(
943                "Missing model ID for download".into(),
944            ))
945        }
946    }
947
948    async fn execute_model_update_work(
949        &self,
950        work_request: &WorkRequest,
951    ) -> Result<WorkResultData> {
952        if let Some(ref model_id) = work_request.input_data.model_id {
953            let mut model_manager = self.model_manager.lock().await;
954            // Simulate model update
955            model_manager.update_model(model_id).await?;
956
957            Ok(WorkResultData {
958                output_data: None,
959                output_shape: None,
960                status_message: format!("Model {} updated successfully", model_id),
961                metadata: HashMap::new(),
962            })
963        } else {
964            Err(TrustformersError::runtime_error(
965                "Missing model ID for update".into(),
966            ))
967        }
968    }
969
970    async fn execute_federated_learning_work(
971        &self,
972        _work_request: &WorkRequest,
973    ) -> Result<WorkResultData> {
974        // Federated learning implementation would go here
975        Ok(WorkResultData {
976            output_data: None,
977            output_shape: None,
978            status_message: "Federated learning round completed".to_string(),
979            metadata: HashMap::new(),
980        })
981    }
982
983    async fn execute_data_preprocessing_work(
984        &self,
985        _work_request: &WorkRequest,
986    ) -> Result<WorkResultData> {
987        // Data preprocessing implementation would go here
988        Ok(WorkResultData {
989            output_data: None,
990            output_shape: None,
991            status_message: "Data preprocessing completed".to_string(),
992            metadata: HashMap::new(),
993        })
994    }
995
996    async fn execute_cache_cleanup_work(
997        &self,
998        _work_request: &WorkRequest,
999    ) -> Result<WorkResultData> {
1000        // Cache cleanup implementation would go here
1001        Ok(WorkResultData {
1002            output_data: None,
1003            output_shape: None,
1004            status_message: "Cache cleanup completed".to_string(),
1005            metadata: HashMap::new(),
1006        })
1007    }
1008
1009    async fn execute_performance_profiling_work(
1010        &self,
1011        _work_request: &WorkRequest,
1012    ) -> Result<WorkResultData> {
1013        // Performance profiling implementation would go here
1014        Ok(WorkResultData {
1015            output_data: None,
1016            output_shape: None,
1017            status_message: "Performance profiling completed".to_string(),
1018            metadata: HashMap::new(),
1019        })
1020    }
1021
1022    async fn execute_health_check_work(
1023        &self,
1024        _work_request: &WorkRequest,
1025    ) -> Result<WorkResultData> {
1026        // Health check implementation would go here
1027        Ok(WorkResultData {
1028            output_data: None,
1029            output_shape: None,
1030            status_message: "Health check completed - all systems operational".to_string(),
1031            metadata: HashMap::new(),
1032        })
1033    }
1034
1035    async fn execute_custom_work(&self, _work_request: &WorkRequest) -> Result<WorkResultData> {
1036        // Custom work implementation would go here
1037        Ok(WorkResultData {
1038            output_data: None,
1039            output_shape: None,
1040            status_message: "Custom work completed".to_string(),
1041            metadata: HashMap::new(),
1042        })
1043    }
1044
1045    fn validate_work_request(&self, work_request: &WorkRequest) -> Result<()> {
1046        if work_request.work_id.is_empty() {
1047            return Err(TrustformersError::config_error(
1048                "Work ID cannot be empty",
1049                "validate_work_request",
1050            ));
1051        }
1052
1053        // Validate input data based on task type
1054        match work_request.task_type {
1055            WorkTaskType::Inference => {
1056                if work_request.input_data.model_id.is_none() {
1057                    return Err(TrustformersError::config_error(
1058                        "Model ID required for inference task",
1059                        "validate_work_request",
1060                    ));
1061                }
1062                if work_request.input_data.tensor_data.is_none() {
1063                    return Err(TrustformersError::config_error(
1064                        "Tensor data required for inference task",
1065                        "validate_work_request",
1066                    ));
1067                }
1068            },
1069            WorkTaskType::ModelDownload | WorkTaskType::ModelUpdate
1070                if work_request.input_data.model_id.is_none() =>
1071            {
1072                return Err(TrustformersError::config_error(
1073                    "Model ID required for model task",
1074                    "validate_work_request",
1075                ));
1076            },
1077            _ => {
1078                // Other task types may have different validation requirements
1079            },
1080        }
1081
1082        Ok(())
1083    }
1084
1085    async fn check_work_constraints(&self, work_request: &WorkRequest) -> Result<bool> {
1086        let constraints = work_request.constraints.as_ref().unwrap_or(&self.config.constraints);
1087
1088        // Check network constraints
1089        if constraints.require_unmetered_network && !self.is_unmetered_network_available() {
1090            return Ok(false);
1091        }
1092
1093        // Check battery constraints
1094        if constraints.require_charging && !self.is_device_charging() {
1095            return Ok(false);
1096        }
1097
1098        if constraints.require_battery_not_low && self.is_battery_low() {
1099            return Ok(false);
1100        }
1101
1102        // Check device idle constraint
1103        if constraints.require_device_idle && !self.is_device_idle() {
1104            return Ok(false);
1105        }
1106
1107        // Check storage constraints
1108        if !self.check_storage_constraints(&constraints.storage_constraints) {
1109            return Ok(false);
1110        }
1111
1112        Ok(true)
1113    }
1114
1115    /// Real resident-memory usage of this process, in MB, via `sysinfo`
1116    /// (the same crate/pattern `crash_reporter::collect_memory_usage`
1117    /// already uses). Previously a hardcoded `64`, regardless of actual
1118    /// memory pressure.
1119    fn get_current_memory_usage(&self) -> usize {
1120        use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
1121
1122        let pid = Pid::from_u32(std::process::id());
1123        let mut system = System::new();
1124        system.refresh_processes_specifics(
1125            ProcessesToUpdate::Some(&[pid]),
1126            true,
1127            ProcessRefreshKind::nothing().with_memory(),
1128        );
1129        system.process(pid).map(|p| (p.memory() / (1024 * 1024)) as usize).unwrap_or(0)
1130    }
1131
1132    /// Real global CPU usage percentage via `sysinfo`. `sysinfo` requires
1133    /// two samples separated by `MINIMUM_CPU_UPDATE_INTERVAL` for an
1134    /// accurate reading (the same pattern `crash_reporter::collect_cpu_info`
1135    /// uses); this method is called from constraint checks ahead of
1136    /// scheduling a work item, not in a per-frame hot path, so the short
1137    /// blocking sleep is acceptable. Previously a hardcoded `25.0`,
1138    /// regardless of actual load.
1139    fn get_current_cpu_usage(&self) -> f64 {
1140        use sysinfo::System;
1141
1142        let mut system = System::new();
1143        system.refresh_cpu_usage();
1144        std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
1145        system.refresh_cpu_usage();
1146        system.global_cpu_usage() as f64
1147    }
1148
1149    // Real per-platform detection of network metering, charging state,
1150    // battery level and device-idle state requires querying Android's
1151    // `ConnectivityManager`/`BatteryManager`/`PowerManager` system services
1152    // through JNI, which in turn requires a `Context` (or at minimum a
1153    // `JavaVM`, as `crate::android::engine::AndroidInferenceEngine::init_jvm`
1154    // is given). `AndroidWorkManager` is never handed one -- its
1155    // constructor takes only `AndroidWorkManagerConfig` and `MobileConfig` --
1156    // so there is nothing to honestly query from any of the four methods
1157    // below. This is the same class of gap already documented on
1158    // `AndroidInferenceEngine::nnapi_inference`/`gpu_inference`: real,
1159    // substantial work (threading a `Context`/`JavaVM` through this
1160    // manager's construction and every caller) that this pass does not
1161    // fabricate a shortcut for.
1162    //
1163    // What changes here is the *direction* of the fallback. The previous
1164    // constants were each wrong in the specific way that made constraints
1165    // easiest to (incorrectly) satisfy: unmetered network "available"
1166    // (`true`), battery "not low" (`is_battery_low` => `false`), and device
1167    // "idle" (`true`) were all assumed by default, so a job declared
1168    // "requires charging + unmetered network + battery not low" could run
1169    // on a low battery over metered cellular the moment `require_charging`
1170    // (the one constraint that *was* conservative) happened not to be set.
1171    // Every fallback below now fails *closed* instead: a condition is
1172    // reported satisfied only when it has actually been verified, so an
1173    // unverifiable precondition blocks the work that declared it required
1174    // rather than silently waving it through.
1175
1176    /// Conservative fallback: never assume an unmetered connection that has
1177    /// not been verified. Previously `true` unconditionally.
1178    fn is_unmetered_network_available(&self) -> bool {
1179        false
1180    }
1181
1182    /// Conservative fallback: never assume charging that has not been
1183    /// verified. Unchanged in *value* from the previous constant (already
1184    /// `false`) but now documented as a deliberate fail-closed default
1185    /// rather than an unexplained placeholder.
1186    fn is_device_charging(&self) -> bool {
1187        false
1188    }
1189
1190    /// Conservative fallback: assume the battery *may* be low until
1191    /// verified otherwise. Previously `false` unconditionally -- the
1192    /// direction that let a `require_battery_not_low` job run on a real
1193    /// low battery.
1194    fn is_battery_low(&self) -> bool {
1195        true
1196    }
1197
1198    /// Conservative fallback: never assume the device is idle without
1199    /// verification. Previously `true` unconditionally -- the direction
1200    /// that let a `require_device_idle` job run while the device was
1201    /// actively in use.
1202    fn is_device_idle(&self) -> bool {
1203        false
1204    }
1205
1206    /// Real, cross-platform available-storage check via `sysinfo::Disks`
1207    /// (no JNI/Context needed -- disk space is exposed the same way on
1208    /// every desktop/mobile OS `sysinfo` supports). Compares against the
1209    /// disk backing the current working directory when that can be
1210    /// determined (the longest matching mount-point prefix, the standard
1211    /// "which filesystem owns this path" rule), falling back to the
1212    /// largest available-space figure across all detected disks otherwise.
1213    /// Previously a hardcoded `true`, regardless of real free space --
1214    /// `enable_storage_cleanup`/`min_free_storage_mb` were configurable but
1215    /// never actually enforced.
1216    fn check_storage_constraints(&self, constraints: &StorageConstraints) -> bool {
1217        use sysinfo::Disks;
1218
1219        let disks = Disks::new_with_refreshed_list();
1220        let cwd = std::env::current_dir().ok();
1221
1222        let available_bytes = cwd
1223            .as_deref()
1224            .and_then(|cwd| {
1225                disks
1226                    .list()
1227                    .iter()
1228                    .filter(|d| cwd.starts_with(d.mount_point()))
1229                    .max_by_key(|d| d.mount_point().as_os_str().len())
1230                    .map(|d| d.available_space())
1231            })
1232            .or_else(|| disks.list().iter().map(|d| d.available_space()).max())
1233            .unwrap_or(0);
1234
1235        let available_mb = available_bytes / (1024 * 1024);
1236        available_mb >= constraints.min_free_storage_mb as u64
1237    }
1238}
1239
1240/// Work status enumeration
1241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1242pub enum WorkStatus {
1243    /// Work is pending execution
1244    Pending,
1245    /// Work is currently running
1246    Running,
1247    /// Work completed successfully
1248    Succeeded,
1249    /// Work failed
1250    Failed,
1251    /// Work was cancelled
1252    Cancelled,
1253    /// Work status is unknown
1254    Unknown,
1255}
1256
1257// Implementation details for helper structs
1258
1259impl WorkQueue {
1260    fn new() -> Self {
1261        Self {
1262            pending_work: HashMap::new(),
1263            running_work: HashMap::new(),
1264            completed_work: HashMap::new(),
1265            work_priorities: std::collections::BinaryHeap::new(),
1266        }
1267    }
1268
1269    fn enqueue_work(&mut self, work_request: WorkRequest) {
1270        let priority_item = PriorityWorkItem {
1271            work_id: work_request.work_id.clone(),
1272            priority: work_request.priority,
1273            deadline: work_request.deadline,
1274            created_at: std::time::SystemTime::now(),
1275        };
1276
1277        self.pending_work.insert(work_request.work_id.clone(), work_request);
1278        self.work_priorities.push(priority_item);
1279    }
1280
1281    fn get_next_work(&mut self) -> Option<PriorityWorkItem> {
1282        self.work_priorities.pop()
1283    }
1284}
1285
1286impl WorkExecutor {
1287    fn new(config: &AndroidWorkManagerConfig) -> Self {
1288        Self {
1289            max_concurrent_workers: 4, // Default
1290            active_workers: 0,
1291            worker_threads: HashMap::new(),
1292            execution_context: ExecutionContext {
1293                // Real detection, falling back to `MobileDeviceInfo::default()`
1294                // (not a panic) if it fails -- this constructor is
1295                // infallible (`WorkExecutor::new` returns `Self`, not
1296                // `Result<Self>`), so a detection error cannot propagate.
1297                device_info: MobileDeviceDetector::detect().unwrap_or_default(),
1298                available_memory_mb: 512,
1299                battery_level: 100.0,
1300                is_charging: false,
1301                network_type: WorkNetworkType::Connected,
1302                thermal_state: 0.0,
1303            },
1304        }
1305    }
1306
1307    fn can_accept_more_work(&self) -> bool {
1308        self.active_workers < self.max_concurrent_workers
1309    }
1310
1311    fn cancel_work(&mut self, _work_id: &str) {
1312        // Implementation for cancelling work
1313    }
1314}
1315
1316impl WorkStatistics {
1317    fn new() -> Self {
1318        Self {
1319            total_work_requests: 0,
1320            completed_work_requests: 0,
1321            failed_work_requests: 0,
1322            retried_work_requests: 0,
1323            average_execution_time_ms: 0.0,
1324            success_rate_by_type: HashMap::new(),
1325            resource_usage_stats: ResourceUsageStats {
1326                average_memory_usage_mb: 0.0,
1327                peak_memory_usage_mb: 0,
1328                average_cpu_usage_percent: 0.0,
1329                total_network_bytes: 0,
1330                total_storage_bytes: 0,
1331            },
1332        }
1333    }
1334}
1335
1336impl Default for AndroidWorkManagerConfig {
1337    fn default() -> Self {
1338        Self {
1339            enable_periodic_work: true,
1340            enable_one_time_work: true,
1341            enable_expedited_work: true,
1342            constraints: WorkConstraintsConfig {
1343                require_unmetered_network: false,
1344                require_charging: false,
1345                require_device_idle: false,
1346                require_battery_not_low: true,
1347                required_network_type: WorkNetworkType::Connected,
1348                storage_constraints: StorageConstraints {
1349                    min_free_storage_mb: 100,
1350                    max_cache_storage_mb: 500,
1351                    enable_storage_cleanup: true,
1352                },
1353            },
1354            retry_policy: WorkRetryPolicyConfig {
1355                retry_policy: WorkRetryPolicy::Exponential,
1356                max_retry_attempts: 3,
1357                initial_retry_delay_ms: 1000.0,
1358                max_retry_delay_ms: 300000.0, // 5 minutes
1359                backoff_multiplier: 2.0,
1360            },
1361            background_execution: BackgroundExecutionConfig {
1362                max_execution_time_seconds: 600.0, // 10 minutes
1363                enable_foreground_service: true,
1364                foreground_notification: ForegroundNotificationConfig {
1365                    channel_id: "trustformers_work".to_string(),
1366                    title: "TrustformeRS Background Processing".to_string(),
1367                    content_text: "Processing machine learning tasks".to_string(),
1368                    show_progress: true,
1369                    enable_cancel_action: true,
1370                },
1371                task_prioritization: TaskPrioritizationConfig {
1372                    high_priority_tasks: vec![
1373                        WorkTaskType::Inference,
1374                        WorkTaskType::FederatedLearning,
1375                    ],
1376                    enable_adaptive_prioritization: true,
1377                    device_state_priority_adjustment: true,
1378                    execution_order: TaskExecutionOrder::Priority,
1379                },
1380            },
1381            data_sync: DataSyncConfig {
1382                enable_model_updates: true,
1383                enable_federated_sync: true,
1384                sync_frequency: WorkFrequency {
1385                    interval_minutes: 60,
1386                    flex_interval_minutes: 15,
1387                    initial_delay_minutes: 5,
1388                },
1389                conflict_resolution: ConflictResolutionStrategy::LastModifiedWins,
1390                compression_settings: DataCompressionConfig {
1391                    enable_compression: true,
1392                    algorithm: CompressionAlgorithm::Gzip,
1393                    compression_level: 6,
1394                    min_size_threshold_bytes: 1024,
1395                },
1396            },
1397        }
1398    }
1399}
1400
1401impl AndroidWorkManagerConfig {
1402    /// Validate configuration
1403    pub fn validate(&self) -> Result<()> {
1404        if self.retry_policy.max_retry_attempts > 10 {
1405            return Err(TrustformersError::config_error(
1406                "Too many retry attempts",
1407                "validate",
1408            ));
1409        }
1410
1411        if self.background_execution.max_execution_time_seconds > 3600.0 {
1412            return Err(TrustformersError::config_error(
1413                "Execution time too long",
1414                "validate",
1415            ));
1416        }
1417
1418        if self.constraints.storage_constraints.min_free_storage_mb < 50 {
1419            return Err(TrustformersError::config_error(
1420                "Minimum storage too low",
1421                "validate",
1422            ));
1423        }
1424
1425        Ok(())
1426    }
1427}
1428
1429// Mock implementations for ModelManager methods
1430impl ModelManager {
1431    fn new_default() -> Result<Self> {
1432        // Default model manager creation
1433        Ok(Self::new(
1434            crate::model_management::ModelManagerConfig::default(),
1435        )?)
1436    }
1437
1438    async fn update_model(&mut self, _model_id: &str) -> Result<()> {
1439        // Model update implementation
1440        Ok(())
1441    }
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446    use super::*;
1447
1448    #[test]
1449    fn test_work_manager_config_default() {
1450        let config = AndroidWorkManagerConfig::default();
1451        assert!(config.enable_periodic_work);
1452        assert!(config.enable_one_time_work);
1453        assert_eq!(
1454            config.retry_policy.retry_policy,
1455            WorkRetryPolicy::Exponential
1456        );
1457    }
1458
1459    #[test]
1460    fn test_work_manager_config_validation() {
1461        let mut config = AndroidWorkManagerConfig::default();
1462        assert!(config.validate().is_ok());
1463
1464        config.retry_policy.max_retry_attempts = 15;
1465        assert!(config.validate().is_err());
1466    }
1467
1468    #[test]
1469    fn test_work_priority_ordering() {
1470        assert!(WorkPriority::Max > WorkPriority::High);
1471        assert!(WorkPriority::High > WorkPriority::Default);
1472        assert!(WorkPriority::Default > WorkPriority::Low);
1473        assert!(WorkPriority::Low > WorkPriority::Min);
1474    }
1475
1476    #[tokio::test]
1477    async fn test_work_manager_creation() {
1478        let work_config = AndroidWorkManagerConfig::default();
1479        let mobile_config = MobileConfig::android_optimized();
1480
1481        let result = AndroidWorkManager::new(work_config, mobile_config);
1482        assert!(result.is_ok());
1483    }
1484
1485    #[test]
1486    fn test_work_request_validation() {
1487        let work_config = AndroidWorkManagerConfig::default();
1488        let mobile_config = MobileConfig::android_optimized();
1489        let manager =
1490            AndroidWorkManager::new(work_config, mobile_config).expect("Operation failed");
1491
1492        let valid_request = WorkRequest {
1493            work_id: "test_inference".to_string(),
1494            work_type: WorkRequestType::OneTime {
1495                initial_delay_minutes: 0,
1496                expedited: false,
1497            },
1498            task_type: WorkTaskType::Inference,
1499            priority: WorkPriority::Default,
1500            input_data: WorkInputData {
1501                model_id: Some("test_model".to_string()),
1502                tensor_data: Some(vec![1.0, 2.0, 3.0]),
1503                tensor_shape: Some(vec![1, 3]),
1504                config_overrides: None,
1505                custom_params: HashMap::new(),
1506            },
1507            constraints: None,
1508            tags: vec!["test".to_string()],
1509            deadline: None,
1510        };
1511
1512        assert!(manager.validate_work_request(&valid_request).is_ok());
1513
1514        let invalid_request = WorkRequest {
1515            work_id: "".to_string(), // Invalid: empty work ID
1516            ..valid_request
1517        };
1518
1519        assert!(manager.validate_work_request(&invalid_request).is_err());
1520    }
1521}