File size: 24,016 Bytes
f946f56
 
 
8810c94
f946f56
 
 
7a6e037
f946f56
 
 
 
 
 
 
2611958
40186ac
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2611958
 
 
 
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8810c94
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a6e037
 
8810c94
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a6e037
 
8810c94
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a6e037
 
8810c94
ae450ae
f946f56
ae450ae
f946f56
 
 
ae450ae
f946f56
 
 
ae450ae
 
 
 
 
 
 
 
 
 
 
 
 
 
f946f56
ae450ae
 
 
 
 
 
 
 
 
 
 
f946f56
 
 
 
 
 
8810c94
f946f56
 
8810c94
f946f56
 
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
 
8810c94
f946f56
 
 
7a9962a
 
 
f946f56
7a9962a
 
f946f56
7a9962a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f946f56
7a9962a
 
 
 
 
 
 
 
 
 
 
 
 
f946f56
 
7a9962a
 
 
f946f56
 
 
8810c94
f946f56
 
 
 
 
 
8810c94
f946f56
 
8810c94
f946f56
 
 
 
 
 
 
 
 
9a287e3
 
 
f946f56
 
f5c7282
f946f56
 
 
 
 
 
8810c94
f946f56
64f969c
 
f946f56
 
7a9962a
 
9a287e3
f946f56
 
 
 
9a287e3
f946f56
 
9a287e3
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
c8e2847
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
c8e2847
f946f56
 
8810c94
f946f56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
 
8810c94
f946f56
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
 
8810c94
f946f56
 
 
 
8810c94
f946f56
 
 
 
 
 
8810c94
9a287e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f946f56
 
9a287e3
 
 
 
 
 
 
 
 
 
 
 
f946f56
 
9a287e3
 
f946f56
9a287e3
 
 
 
 
 
 
 
 
 
f946f56
9a287e3
f946f56
9a287e3
 
 
 
 
 
 
f946f56
 
9a287e3
 
 
 
f946f56
8810c94
f946f56
 
 
 
8810c94
f946f56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use axum::{
    extract::{Path, Query, State},
    http::StatusCode,
    response::{IntoResponse, Json},
    routing::{get, post},
    Router,
};
use chrono::Utc;
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tokio::process::Command;
use tracing::{error, info};
use uuid::Uuid;
use tower::ServiceBuilder;
use tower_http::limit::RequestBodyLimitLayer;

mod models;
mod utils;

use models::*;
use utils::*;

const MODEL_ID: &str = "english_mfa";
const CLEANUP_INTERVAL: u64 = 5;
const JOB_TTL_SECONDS: i64 = 300;
const AVG_ALIGN_SECONDS: f64 = 15.0;
const MIN_AUDIO_SECONDS: f64 = 0.3;
const MAX_AUDIO_SECONDS: f64 = 180.0;
const ROLLING_AVG_WINDOW: usize = 10;

#[derive(Clone)]
struct AppState {
    jobs: Arc<Mutex<HashMap<String, Job>>>,
    metrics: Arc<Mutex<Metrics>>,
    recent_durations: Arc<Mutex<VecDeque<f64>>>,
    worker_ready: Arc<Mutex<bool>>,
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    info!("Starting MFA Aligner Rust Service v1.5.0");

    let state = AppState {
        jobs: Arc::new(Mutex::new(HashMap::new())),
        metrics: Arc::new(Mutex::new(Metrics::new())),
        recent_durations: Arc::new(Mutex::new(VecDeque::with_capacity(ROLLING_AVG_WINDOW))),
        worker_ready: Arc::new(Mutex::new(false)),
    };

    // Start cleanup task
    let cleanup_state = state.clone();
    tokio::spawn(async move {
        cleanup_loop(cleanup_state).await;
    });

    // Start Python worker monitor
    let worker_state = state.clone();
    tokio::spawn(async move {
        start_python_worker(worker_state).await;
    });

    let app = Router::new()
        .route("/", get(root))
        .route("/health", get(health))
        .route("/metrics", get(metrics))
        .route("/queue/status", get(queue_status))
        .route("/align", post(align_audio))
        .route("/job/:job_id", get(get_job))
        .route("/result/:job_id", get(get_result))
        .route("/cancel/:job_id", post(cancel_job))
        .layer(
            ServiceBuilder::new()
                .layer(RequestBodyLimitLayer::new(25 * 1024 * 1024)) // 25 MB limit
        )
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:7860").await.unwrap();
    info!("Server listening on http://0.0.0.0:7860");
    axum::serve(listener, app).await.unwrap();
}

async fn cleanup_loop(state: AppState) {
    loop {
        tokio::time::sleep(Duration::from_secs(CLEANUP_INTERVAL)).await;
        
        let now = Utc::now();
        let ttl_cutoff = now - chrono::Duration::seconds(JOB_TTL_SECONDS);
        
        let mut jobs = state.jobs.lock();
        let terminal_statuses = [
            JobStatus::Completed.as_str(),
            JobStatus::Failed.as_str(),
            JobStatus::Abandoned.as_str(),
        ];
        
        jobs.retain(|_, job| {
            if terminal_statuses.contains(&job.status.as_str()) {
                if let Some(terminal_at) = job.terminal_at {
                    return terminal_at >= ttl_cutoff;
                }
            }
            true
        });
        
        promote_queued(&mut jobs);
    }
}

async fn start_python_worker(state: AppState) {
    info!("Starting Python MFA worker process...");
    
    // Give worker time to initialize and warm up
    tokio::time::sleep(Duration::from_secs(15)).await;
    
    let mut worker_ready = state.worker_ready.lock();
    *worker_ready = true;
    info!("Python MFA worker ready");
}

fn promote_queued(jobs: &mut HashMap<String, Job>) -> Option<String> {
    // Check if any running job exists
    if jobs.values().any(|job| job.status.as_str() == JobStatus::Running.as_str()) {
        return None;
    }
    
    // Find oldest queued job
    let mut queued: Vec<_> = jobs
        .iter()
        .filter(|(_, job)| job.status.as_str() == JobStatus::Queued.as_str())
        .collect();
    
    queued.sort_by_key(|(_, job)| job.created_at);
    
    if let Some((job_id, _)) = queued.first() {
        let job_id = (*job_id).clone();
        let job_mut = jobs.get_mut(&job_id).unwrap();
        job_mut.status = JobStatus::Running;
        job_mut.started_at = Some(Utc::now());
        info!("Promoted queued job {} β†’ RUNNING", job_id);
        Some(job_id)
    } else {
        None
    }
}

fn avg_align_s(state: &AppState) -> f64 {
    let recent = state.recent_durations.lock();
    if recent.is_empty() {
        AVG_ALIGN_SECONDS
    } else {
        (recent.iter().sum::<f64>() / recent.len() as f64 * 10.0).round() / 10.0
    }
}

async fn root() -> impl IntoResponse {
    Json(serde_json::json!({
        "name": "MFA Aligner Rust Service",
        "version": "1.5.0",
        "status": "ready",
        "model": MODEL_ID,
        "endpoints": {
            "POST /align": "Submit alignment job",
            "GET /job/{id}": "Unified status + result [preferred]",
            "GET /job/{id}?slim=true": "Status only β€” omits word_timestamps (use while polling)",
            "GET /result/{id}": "Legacy result poll [compat]",
            "GET /queue/status": "Queue availability",
            "POST /cancel/{id}": "Explicit job cancellation",
            "GET /health": "Service health + job counts",
            "GET /metrics": "Aggregate metrics",
        }
    }))
}

async fn health(
    State(state): State<AppState>,
) -> impl IntoResponse {
    let jobs = state.jobs.lock();
    let worker_ready = *state.worker_ready.lock();
    
    let mut counts = serde_json::Map::new();
    for status in ["queued", "running", "completed", "failed", "abandoned"] {
        let count = jobs.values()
            .filter(|job| job.status.as_str() == status)
            .count();
        counts.insert(status.to_string(), count.into());
    }
    
    let tmp_free = get_tmp_free_mb();
    let shm_ok = tmp_free.map_or(true, |free| free >= 500.0);
    
    let overall = if worker_ready && shm_ok { "healthy" } else { "degraded" };
    
    Json(serde_json::json!({
        "status": overall,
        "worker_alive": worker_ready,
        "worker_ready": worker_ready,
        "worker_restarting": false,
        "model": MODEL_ID,
        "shm_free_mb": tmp_free,
        "shm_ok": shm_ok,
        "avg_align_s": avg_align_s(&state),
        "job_counts": counts,
        "total_jobs": jobs.len(),
    }))
}

async fn metrics(
    State(state): State<AppState>,
) -> impl IntoResponse {
    let metrics = state.metrics.lock();
    let total = metrics.total_completed + metrics.total_failed + metrics.total_abandoned;
    let success_rate = if total > 0 {
        Some((metrics.total_completed as f64 / total as f64 * 1000.0).round() / 1000.0)
    } else {
        None
    };
    
    let recent: Vec<f64> = state.recent_durations.lock().iter().copied().collect();
    
    Json(serde_json::json!({
        "uptime_s": metrics.start_time.map(|t| (Utc::now() - t).num_seconds()),
        "total_submitted": metrics.total_submitted,
        "total_completed": metrics.total_completed,
        "total_failed": metrics.total_failed,
        "total_abandoned": metrics.total_abandoned,
        "total_cancelled": metrics.total_cancelled,
        "success_rate": success_rate,
        "worker_restarts": 0,
        "avg_align_s": avg_align_s(&state),
        "recent_durations": recent,
    }))
}

async fn queue_status(
    State(state): State<AppState>,
) -> impl IntoResponse {
    let jobs         = state.jobs.lock();
    let worker_ready = *state.worker_ready.lock();
 
    let running_job = jobs.values()
        .find(|job| job.status.as_str() == JobStatus::Running.as_str())
        .map(|job| job.id.clone());
 
    let queued_job = jobs.values()
        .find(|job| job.status.as_str() == JobStatus::Queued.as_str())
        .map(|job| job.id.clone());
 
    let running_count: u32 = if running_job.is_some() { 1 } else { 0 };
    let waiting_count: u32 = if queued_job.is_some()  { 1 } else { 0 };
 
    let can_submit = running_count == 0 && waiting_count == 0;
    let slot_free  = running_count == 0;
    let queue_full = running_count == 1 && waiting_count == 1;
 
    let estimated_wait: f64 = if running_job.is_some() {
        avg_align_s(&state)
    } else {
        0.0
    };
 
    Json(serde_json::json!({
        // NEW: integer counts the controller reads
        "running":          running_count,
        "waiting":          waiting_count,
        // Existing fields kept for backwards compat
        "can_submit":       can_submit,
        "slot_available":   slot_free,
        "queue_full":       queue_full,
        "running_job_id":   running_job,
        "queued_job_id":    queued_job,
        "worker_ready":     worker_ready,
        "estimated_wait_s": estimated_wait,
    }))
}

async fn align_audio(
    State(state): State<AppState>,
    Json(req): Json<AlignRequest>,
) -> impl IntoResponse {
    // 1. Model check
    if !*state.worker_ready.lock() {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(serde_json::json!({
                "error": "Worker unavailable",
                "error_code": "WORKER_DOWN",
                "detail": "Model is still loading. Retry in a few seconds.",
            })),
        ).into_response();
    }

    // 2. Text validation (MFA strips digits)
    let cleaned_text = clean_text_mfa(&req.text);
    if cleaned_text.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({
                "error": "Invalid text",
                "error_code": "TEXT_EMPTY",
                "detail": "Text is empty after normalisation.",
            })),
        ).into_response();
    }

    // 3. Audio validation
    let (wav_normalised, audio_duration) = match validate_audio(&req.audio_base64) {
        Ok(result) => result,
        Err(response) => return response.into_response(),
    };

    // 4. SHM space check
    if let Some(free_mb) = get_tmp_free_mb() {
        if free_mb < 500.0 {
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({
                    "error": "Insufficient RAM",
                    "error_code": "SHM_FULL",
                    "detail": format!("Only {} MB free in /dev/shm (minimum 500 MB).", free_mb),
                })),
            ).into_response();
        }
    }

    // Phase 1: check queue state and duplicate β€” lock held, no .await
    let (running_exists, queued_exists, duplicate_warning) = {
        let jobs = state.jobs.lock();

        let running_exists = jobs.values().any(|job| job.status.as_str() == JobStatus::Running.as_str());
        let queued_exists = jobs.values().any(|job| job.status.as_str() == JobStatus::Queued.as_str());

        // 5. Queue full check
        if running_exists && queued_exists {
            let wait = avg_align_s(&state);
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({
                    "error": "Service busy",
                    "error_code": "QUEUE_FULL",
                    "detail": "One job running, one already queued. Retry after current jobs finish.",
                    "retry_after": wait,
                })),
            ).into_response();
        }

        // 6. Duplicate client check
        let client_id_ref = req.client_id.as_ref();
        let duplicate_warning = if let Some(client_id) = client_id_ref {
            jobs.values()
                .find(|job| {
                    job.client_id.as_ref() == Some(client_id) &&
                    (job.status.as_str() == JobStatus::Running.as_str() ||
                     job.status.as_str() == JobStatus::Queued.as_str())
                })
                .map(|existing| {
                    serde_json::json!({
                        "message": "You already have an active job.",
                        "existing_job_id": existing.id.clone(),
                        "existing_status": existing.status.as_str(),
                    })
                })
        } else {
            None
        };

        (running_exists, queued_exists, duplicate_warning)
        // lock released here β€” BEFORE the .await below
    };

    let client_id = req.client_id.clone();

    // 7. Write audio to temp file (.await β€” lock is NOT held)
    let job_id = Uuid::new_v4().to_string()[..12].to_string();
    let temp_path = format!("/dev/shm/tmp_{}.wav", job_id);
    if let Err(e) = tokio::fs::write(&temp_path, wav_normalised).await {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(serde_json::json!({
                "error": "Storage error",
                "error_code": "SHM_WRITE_ERROR",
                "detail": format!("Could not write audio to /dev/shm: {}", e),
            })),
        ).into_response();
    }

    // 8. Create job
    let status = if running_exists { 
        JobStatus::Queued 
    } else { 
        JobStatus::Running 
    };
    
    let queue_position = if status == JobStatus::Queued { 1 } else { 0 };
    let now = Utc::now();

    // FIX 1: Extract client_id before constructing Job so we can log it after the move.
    let job_client_id_for_log = client_id.clone();

    let job = Job {
        id: job_id.clone(),
        request: req.clone(),
        status: status.clone(),
        created_at: now,
        started_at: if status == JobStatus::Running { Some(now) } else { None },
        terminal_at: None,
        result: None,
        error: None,
        client_id,
        audio_duration: (audio_duration * 100.0).round() / 100.0,
        wav_path: temp_path,
        cleaned_text,
    };

    // Phase 2: re-acquire lock to insert job (after the .await is done)
    let mut jobs = state.jobs.lock();
    jobs.insert(job_id.clone(), job);  // job is moved here β€” do NOT use `job` after this line
    
    let mut metrics = state.metrics.lock();
    metrics.total_submitted += 1;
    
    // FIX 1 (continued): Use the pre-extracted copy instead of `job.client_id`
    info!(
        "Job {} created β€” status={}, duration={:.1}s, client={:?}",
        job_id, status.as_str(), audio_duration, job_client_id_for_log
    );

    drop(metrics);
    drop(jobs);

    // If running, start alignment
    if status == JobStatus::Running {
        let state_clone = state.clone();
        let job_id_clone = job_id.clone();
        tokio::spawn(async move {
            run_alignment(state_clone, job_id_clone).await;
        });
    }

    let mut response = serde_json::json!({
        "job_id": job_id,
        "status": status.as_str(),
        "queue_position": queue_position,
        "poll_url": format!("/job/{}", job_id),
        "estimated_wait_s": if status == JobStatus::Running { 0.0 } else { avg_align_s(&state) },
        "audio_duration_s": (audio_duration * 100.0).round() / 100.0,
        "message": if status == JobStatus::Running {
            format!("Job started. Poll GET /job/{}.", job_id)
        } else {
            format!("Job queued at position 1. Poll GET /job/{} every 2 s.", job_id)
        },
    });

    if let Some(warning) = duplicate_warning {
        response["duplicate_warning"] = warning;
    }

    (StatusCode::OK, Json(response)).into_response()
}

async fn run_alignment(state: AppState, job_id: String) {
    info!("[{}] Starting MFA alignment", job_id);
    
    // Get job data
    let (wav_path, cleaned_text, req) = {
        let jobs = state.jobs.lock();
        let job = jobs.get(&job_id).unwrap();
        (job.wav_path.clone(), job.cleaned_text.clone(), job.request.clone())
    };

    let start = std::time::Instant::now();
    
    // Call Python MFA worker
    let output = Command::new("python3")
        .arg("worker_mfa.py")
        .arg(&wav_path)
        .arg(&cleaned_text)
        .arg(&req.language)
        .output()
        .await;

    // Clean up temp file
    let _ = tokio::fs::remove_file(&wav_path).await;
    
    let duration = start.elapsed().as_secs_f64();

    match output {
        Ok(output) if output.status.success() => {
            match serde_json::from_slice::<Vec<WordTimestamp>>(&output.stdout) {
                Ok(word_timestamps) => {
                    info!("[{}] Done β€” {} words in {:.2}s", job_id, word_timestamps.len(), duration);
                    
                    let mut jobs = state.jobs.lock();
                    if let Some(job) = jobs.get_mut(&job_id) {
                        if job.status.as_str() == JobStatus::Running.as_str() {
                            job.status = JobStatus::Completed;
                            job.result = Some(word_timestamps);
                            job.terminal_at = Some(Utc::now());
                            
                            let mut metrics = state.metrics.lock();
                            metrics.total_completed += 1;
                            
                            let mut recent = state.recent_durations.lock();
                            recent.push_back(duration);
                            if recent.len() > ROLLING_AVG_WINDOW {
                                recent.pop_front();
                            }
                        }
                    }
                }
                Err(e) => {
                    error!("[{}] Failed to parse worker output: {}", job_id, e);
                    let mut jobs = state.jobs.lock();
                    if let Some(job) = jobs.get_mut(&job_id) {
                        if job.status.as_str() == JobStatus::Running.as_str() {
                            job.status = JobStatus::Failed;
                            job.error = Some(format!("Failed to parse alignment result: {}", e));
                            job.terminal_at = Some(Utc::now());
                            
                            let mut metrics = state.metrics.lock();
                            metrics.total_failed += 1;
                        }
                    }
                }
            }
        }
        Ok(output) => {
            let error = String::from_utf8_lossy(&output.stderr);
            error!("[{}] Alignment failed: {}", job_id, error);
            
            let mut jobs = state.jobs.lock();
            if let Some(job) = jobs.get_mut(&job_id) {
                if job.status.as_str() == JobStatus::Running.as_str() {
                    job.status = JobStatus::Failed;
                    job.error = Some(format!("Alignment failed: {}", error));
                    job.terminal_at = Some(Utc::now());
                    
                    let mut metrics = state.metrics.lock();
                    metrics.total_failed += 1;
                }
            }
        }
        Err(e) => {
            error!("[{}] Failed to execute worker: {}", job_id, e);
            
            let mut jobs = state.jobs.lock();
            if let Some(job) = jobs.get_mut(&job_id) {
                if job.status.as_str() == JobStatus::Running.as_str() {
                    job.status = JobStatus::Failed;
                    job.error = Some(format!("Failed to execute worker: {}", e));
                    job.terminal_at = Some(Utc::now());
                    
                    let mut metrics = state.metrics.lock();
                    metrics.total_failed += 1;
                }
            }
        }
    }

    // Promote next queued job
    let mut jobs = state.jobs.lock();
    promote_queued(&mut jobs);
}

async fn get_job(
    State(state): State<AppState>,
    Path(job_id): Path<String>,
    Query(params): Query<JobQuery>,
) -> impl IntoResponse {
    let jobs = state.jobs.lock();
    
    let job = match jobs.get(&job_id) {
        Some(job) => job,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": "Job not found",
                    "error_code": "JOB_NOT_FOUND",
                    "detail": "Job may have been purged (TTL=5 min) or never existed.",
                })),
            ).into_response();
        }
    };

    let response = job_view(job, params.slim.unwrap_or(false), avg_align_s(&state));
    (StatusCode::OK, Json(response)).into_response()
}

async fn get_result(
    State(state): State<AppState>,
    Path(job_id): Path<String>,
) -> impl IntoResponse {
    let jobs = state.jobs.lock();
    
    let job = match jobs.get(&job_id) {
        Some(job) => job,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "error": "Job not found",
                    "error_code": "JOB_NOT_FOUND",
                })),
            ).into_response();
        }
    };

    let response = job_view(job, false, avg_align_s(&state));
    (StatusCode::OK, Json(response)).into_response()
}

async fn cancel_job(
    State(state): State<AppState>,
    Path(job_id): Path<String>,
    Json(body): Json<CancelRequest>,
) -> impl IntoResponse {
    // FIX 2 & 3: Extract everything we need from the locked map BEFORE any .await,
    // then release the lock, do the async work, and re-acquire to mutate.
    // parking_lot::MutexGuard is !Send, so holding it across an .await point
    // prevents the future from being Send, which breaks the axum Handler bound.

    // --- Phase 1: validate & extract (no .await, lock held briefly) ---
    let (was_running, wav_path) = {
        let mut jobs = state.jobs.lock();

        let job = match jobs.get_mut(&job_id) {
            Some(job) => job,
            None => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(serde_json::json!({
                        "error": "Job not found",
                        "error_code": "JOB_NOT_FOUND",
                    })),
                ).into_response();
            }
        };

        // Client ID check
        if let Some(stored) = &job.client_id {
            if body.client_id.is_none() || body.client_id.as_ref() != Some(stored) {
                return (
                    StatusCode::FORBIDDEN,
                    Json(serde_json::json!({
                        "error": "Client ID mismatch",
                        "error_code": "FORBIDDEN",
                        "detail": "You are not the owner of this job.",
                    })),
                ).into_response();
            }
        }

        let terminal_statuses = [
            JobStatus::Completed.as_str(),
            JobStatus::Failed.as_str(),
            JobStatus::Abandoned.as_str(),
        ];

        if terminal_statuses.contains(&job.status.as_str()) {
            return Json(serde_json::json!({
                "cancelled": false,
                "status": job.status.as_str(),
                "message": format!("Job was already {} β€” nothing to cancel.", job.status.as_str()),
            })).into_response();
        }

        let was_running = job.status.as_str() == JobStatus::Running.as_str();
        let wav_path = job.wav_path.clone();

        // Mark cancelled while we still hold the lock (no .await needed here)
        job.status = JobStatus::Abandoned;
        job.error = Some("Cancelled by client".to_string());
        job.terminal_at = Some(Utc::now());

        (was_running, wav_path)
        // lock is released here (end of block)
    };

    // --- Phase 2: async I/O β€” lock is NOT held ---
    if was_running {
        let _ = tokio::fs::remove_file(&wav_path).await;
    }

    // --- Phase 3: update metrics & promote (no .await, lock held briefly) ---
    {
        let mut metrics = state.metrics.lock();
        metrics.total_cancelled += 1;
    }

    info!("Job {} cancelled ({})", job_id, if was_running { "RUNNING" } else { "QUEUED" });

    {
        let mut jobs = state.jobs.lock();
        promote_queued(&mut jobs);
    }

    Json(serde_json::json!({
        "cancelled": true,
        "job_id": job_id,
        "restarting": false,
        "message": "Job cancelled.",
    })).into_response()
}