a3s-lane 0.5.0

Lane-based priority command queue for async task scheduling with reliability, scalability, and observability features
Documentation
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Core queue implementation with lanes and priority scheduling

#[cfg(feature = "distributed")]
use crate::boost::PriorityBooster;
use crate::config::LaneConfig;
use crate::dlq::{DeadLetter, DeadLetterQueue};
use crate::error::{LaneError, Result};
use crate::event::{events, EventEmitter, EventStream, LaneEvent};
#[cfg(feature = "distributed")]
use crate::ratelimit::RateLimiter;
use crate::retry::RetryPolicy;
use crate::storage::{Storage, StoredCommand};
#[cfg(feature = "telemetry")]
use crate::telemetry;
use async_trait::async_trait;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[cfg(feature = "telemetry")]
use std::time::Instant;
use tokio::sync::{Mutex, Semaphore};
use uuid::Uuid;

/// Lane identifier
pub type LaneId = String;

/// Command identifier
pub type CommandId = String;

/// Lane priority (lower number = higher priority)
pub type Priority = u8;

/// Lane priorities
pub mod priorities {
    use super::Priority;

    pub const SYSTEM: Priority = 0;
    pub const CONTROL: Priority = 1;
    pub const QUERY: Priority = 2;
    pub const SESSION: Priority = 3;
    pub const SKILL: Priority = 4;
    pub const PROMPT: Priority = 5;
}

/// Command to be executed
#[async_trait]
pub trait Command: Send + Sync {
    /// Execute the command
    async fn execute(&self) -> Result<serde_json::Value>;

    /// Get command type (for logging/debugging)
    fn command_type(&self) -> &str;
}

/// A simple JSON-based command for data-driven Rust usage.
///
/// Returns the payload as-is when executed. Useful when commands are represented
/// as JSON data but still run through the Rust queue API.
pub struct JsonCommand {
    command_type: String,
    payload: serde_json::Value,
}

impl JsonCommand {
    /// Create a new JSON command.
    pub fn new(command_type: impl Into<String>, payload: serde_json::Value) -> Self {
        Self {
            command_type: command_type.into(),
            payload,
        }
    }
}

#[async_trait]
impl Command for JsonCommand {
    async fn execute(&self) -> Result<serde_json::Value> {
        Ok(self.payload.clone())
    }

    fn command_type(&self) -> &str {
        &self.command_type
    }
}

/// Command wrapper
struct CommandWrapper {
    id: CommandId,
    command: Arc<dyn Command>,
    result_tx: Option<tokio::sync::oneshot::Sender<Result<serde_json::Value>>>,
    timeout: Option<std::time::Duration>,
    retry_policy: RetryPolicy,
    attempt: u32,
    lane_id: LaneId,
    command_type: String,
    /// Submission time used by the priority booster to calculate deadline proximity
    #[cfg(feature = "distributed")]
    enqueue_time: chrono::DateTime<chrono::Utc>,
}

/// Lane state
#[allow(dead_code)]
struct LaneState {
    /// Lane configuration
    config: LaneConfig,

    /// Priority
    priority: Priority,

    /// Pending commands (FIFO queue)
    pending: VecDeque<CommandWrapper>,

    /// Active command count
    active: usize,

    /// Semaphore for concurrency control
    semaphore: Arc<Semaphore>,

    /// True when the lane is currently considered under pressure
    is_pressured: bool,
}

impl LaneState {
    fn new(config: LaneConfig, priority: Priority) -> Self {
        let semaphore = Arc::new(Semaphore::new(config.max_concurrency));
        Self {
            config,
            priority,
            pending: VecDeque::new(),
            active: 0,
            semaphore,
            is_pressured: false,
        }
    }

    fn has_capacity(&self) -> bool {
        self.active < self.config.max_concurrency
    }

    fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }
}

/// Lane
pub struct Lane {
    id: LaneId,
    state: Arc<Mutex<LaneState>>,
    storage: Option<Arc<dyn Storage>>,
    /// Rate limiter instantiated from LaneConfig.rate_limit (None = unlimited)
    #[cfg(feature = "distributed")]
    rate_limiter: RateLimiter,
    /// Priority booster instantiated from LaneConfig.priority_boost
    #[cfg(feature = "distributed")]
    booster: Option<PriorityBooster>,
}

impl Lane {
    /// Create a new lane
    pub fn new(id: impl Into<String>, config: LaneConfig, priority: Priority) -> Self {
        #[cfg(feature = "distributed")]
        let rate_limiter = config
            .rate_limit
            .as_ref()
            .map(RateLimiter::token_bucket)
            .unwrap_or_default();
        #[cfg(feature = "distributed")]
        let booster = config
            .priority_boost
            .as_ref()
            .map(|pb| PriorityBooster::new(pb.clone()));
        Self {
            id: id.into(),
            state: Arc::new(Mutex::new(LaneState::new(config, priority))),
            storage: None,
            #[cfg(feature = "distributed")]
            rate_limiter,
            #[cfg(feature = "distributed")]
            booster,
        }
    }

    /// Create a new lane with storage
    pub fn with_storage(
        id: impl Into<String>,
        config: LaneConfig,
        priority: Priority,
        storage: Arc<dyn Storage>,
    ) -> Self {
        #[cfg(feature = "distributed")]
        let rate_limiter = config
            .rate_limit
            .as_ref()
            .map(RateLimiter::token_bucket)
            .unwrap_or_default();
        #[cfg(feature = "distributed")]
        let booster = config
            .priority_boost
            .as_ref()
            .map(|pb| PriorityBooster::new(pb.clone()));
        Self {
            id: id.into(),
            state: Arc::new(Mutex::new(LaneState::new(config, priority))),
            storage: Some(storage),
            #[cfg(feature = "distributed")]
            rate_limiter,
            #[cfg(feature = "distributed")]
            booster,
        }
    }

    /// Get lane ID
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get lane priority
    pub async fn priority(&self) -> Priority {
        self.state.lock().await.priority
    }

    /// Get effective priority, applying boost based on the front command's age
    pub async fn effective_priority(&self) -> Priority {
        let state = self.state.lock().await;
        let base = state.priority;
        #[cfg(feature = "distributed")]
        if let Some(booster) = &self.booster {
            if let Some(front) = state.pending.front() {
                return booster.calculate_priority(base, front.enqueue_time);
            }
        }
        base
    }

    /// Enqueue a command
    pub async fn enqueue(
        &self,
        command: Box<dyn Command>,
    ) -> tokio::sync::oneshot::Receiver<Result<serde_json::Value>> {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let state = self.state.lock().await;
        let timeout = state.config.default_timeout;
        let retry_policy = state.config.retry_policy.clone();
        drop(state);

        let command_id = Uuid::new_v4().to_string();
        let command_type = command.command_type().to_string();
        let wrapper = CommandWrapper {
            id: command_id.clone(),
            command: Arc::from(command),
            result_tx: Some(tx),
            timeout,
            retry_policy,
            attempt: 0,
            lane_id: self.id.clone(),
            command_type: command_type.clone(),
            #[cfg(feature = "distributed")]
            enqueue_time: Utc::now(),
        };

        // Persist to storage if available
        if let Some(storage) = &self.storage {
            let stored_cmd = StoredCommand {
                id: command_id,
                command_type,
                lane_id: self.id.clone(),
                payload: serde_json::json!({}), // Empty payload for now
                retry_count: 0,
                created_at: Utc::now(),
                last_attempt_at: None,
            };
            // Ignore storage errors to not block command execution
            let _ = storage.save_command(stored_cmd).await;
        }

        let mut state = self.state.lock().await;
        state.pending.push_back(wrapper);

        rx
    }

    /// Re-enqueue a command for retry (internal use)
    async fn retry_command(&self, mut wrapper: CommandWrapper, delay: std::time::Duration) {
        wrapper.attempt += 1;

        // Spawn a task to re-enqueue after delay
        let state_clone = Arc::clone(&self.state);
        tokio::spawn(async move {
            tokio::time::sleep(delay).await;
            let mut state = state_clone.lock().await;
            state.pending.push_back(wrapper);
        });
    }

    /// Try to dequeue a command for execution
    async fn try_dequeue(&self) -> Option<CommandWrapper> {
        // Check rate limiter before acquiring the state lock
        #[cfg(feature = "distributed")]
        if !self.rate_limiter.try_acquire().await {
            return None;
        }
        let mut state = self.state.lock().await;
        if state.has_capacity() && state.has_pending() {
            state.active += 1;
            state.pending.pop_front()
        } else {
            None
        }
    }

    /// Mark a command as completed
    async fn mark_completed(&self) {
        let mut state = self.state.lock().await;
        state.active = state.active.saturating_sub(1);
    }

    /// Get lane status
    pub async fn status(&self) -> LaneStatus {
        let state = self.state.lock().await;
        LaneStatus {
            pending: state.pending.len(),
            active: state.active,
            min: state.config.min_concurrency,
            max: state.config.max_concurrency,
        }
    }

    /// Check for pressure state transitions.
    ///
    /// Returns the event key to emit if a transition occurred, or `None` if no change.
    /// - Transitions to pressured when `pending >= threshold` and was not already pressured.
    /// - Transitions to idle when `pending == 0` and was previously pressured.
    async fn check_pressure(&self) -> Option<&'static str> {
        let mut state = self.state.lock().await;
        let threshold = match state.config.pressure_threshold {
            Some(t) => t,
            None => return None,
        };
        let pending = state.pending.len();
        let was_pressured = state.is_pressured;
        if pending >= threshold && !was_pressured {
            state.is_pressured = true;
            Some(events::QUEUE_LANE_PRESSURE)
        } else if pending == 0 && was_pressured {
            state.is_pressured = false;
            Some(events::QUEUE_LANE_IDLE)
        } else {
            None
        }
    }
}

/// Lane status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaneStatus {
    pub pending: usize,
    pub active: usize,
    pub min: usize,
    pub max: usize,
}

/// Command queue
#[allow(dead_code)]
pub struct CommandQueue {
    lanes: Arc<Mutex<HashMap<LaneId, Arc<Lane>>>>,
    event_emitter: EventEmitter,
    dlq: Option<DeadLetterQueue>,
    storage: Option<Arc<dyn Storage>>,
    is_shutting_down: Arc<AtomicBool>,
    shutdown_notify: Arc<tokio::sync::Notify>,
}

impl CommandQueue {
    /// Create a new command queue
    pub fn new(event_emitter: EventEmitter) -> Self {
        Self {
            lanes: Arc::new(Mutex::new(HashMap::new())),
            event_emitter,
            dlq: None,
            storage: None,
            is_shutting_down: Arc::new(AtomicBool::new(false)),
            shutdown_notify: Arc::new(tokio::sync::Notify::new()),
        }
    }

    /// Create a new command queue with a dead letter queue
    pub fn with_dlq(event_emitter: EventEmitter, dlq_size: usize) -> Self {
        Self {
            lanes: Arc::new(Mutex::new(HashMap::new())),
            event_emitter,
            dlq: Some(DeadLetterQueue::new(dlq_size)),
            storage: None,
            is_shutting_down: Arc::new(AtomicBool::new(false)),
            shutdown_notify: Arc::new(tokio::sync::Notify::new()),
        }
    }

    /// Create a new command queue with storage
    pub fn with_storage(event_emitter: EventEmitter, storage: Arc<dyn Storage>) -> Self {
        Self {
            lanes: Arc::new(Mutex::new(HashMap::new())),
            event_emitter,
            dlq: None,
            storage: Some(storage),
            is_shutting_down: Arc::new(AtomicBool::new(false)),
            shutdown_notify: Arc::new(tokio::sync::Notify::new()),
        }
    }

    /// Create a new command queue with both DLQ and storage
    pub fn with_dlq_and_storage(
        event_emitter: EventEmitter,
        dlq_size: usize,
        storage: Arc<dyn Storage>,
    ) -> Self {
        Self {
            lanes: Arc::new(Mutex::new(HashMap::new())),
            event_emitter,
            dlq: Some(DeadLetterQueue::new(dlq_size)),
            storage: Some(storage),
            is_shutting_down: Arc::new(AtomicBool::new(false)),
            shutdown_notify: Arc::new(tokio::sync::Notify::new()),
        }
    }

    /// Get the storage backend
    pub fn storage(&self) -> Option<&Arc<dyn Storage>> {
        self.storage.as_ref()
    }

    /// Get the dead letter queue
    pub fn dlq(&self) -> Option<&DeadLetterQueue> {
        self.dlq.as_ref()
    }

    /// Check if shutdown is in progress
    pub fn is_shutting_down(&self) -> bool {
        self.is_shutting_down.load(Ordering::SeqCst)
    }

    /// Initiate graceful shutdown - stop accepting new commands
    pub async fn shutdown(&self) {
        self.is_shutting_down.store(true, Ordering::SeqCst);
        self.event_emitter
            .emit(LaneEvent::empty(events::QUEUE_SHUTDOWN_STARTED));
    }

    /// Wait for all pending commands to complete (with timeout)
    pub async fn drain(&self, timeout: std::time::Duration) -> Result<()> {
        let start = std::time::Instant::now();

        loop {
            // Check if all lanes are empty and idle
            let lanes = self.lanes.lock().await;
            let mut all_idle = true;

            for lane in lanes.values() {
                let status = lane.status().await;
                if status.pending > 0 || status.active > 0 {
                    all_idle = false;
                    break;
                }
            }
            drop(lanes);

            if all_idle {
                return Ok(());
            }

            // Check timeout
            if start.elapsed() >= timeout {
                return Err(LaneError::Timeout(timeout));
            }

            // Wait a bit before checking again
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }

    /// Register a lane
    pub async fn register_lane(&self, lane: Arc<Lane>) {
        let mut lanes = self.lanes.lock().await;
        lanes.insert(lane.id().to_string(), lane);
    }

    /// Submit a command to a lane
    pub async fn submit(
        &self,
        lane_id: &str,
        command: Box<dyn Command>,
    ) -> Result<tokio::sync::oneshot::Receiver<Result<serde_json::Value>>> {
        // Reject new commands during shutdown
        if self.is_shutting_down() {
            return Err(LaneError::ShutdownInProgress);
        }

        let lanes = self.lanes.lock().await;
        let lane = lanes
            .get(lane_id)
            .ok_or_else(|| LaneError::LaneNotFound(lane_id.to_string()))?;
        let rx = lane.enqueue(command).await;

        self.event_emitter.emit(LaneEvent::with_map(
            events::QUEUE_COMMAND_SUBMITTED,
            HashMap::from([("lane_id".to_string(), serde_json::json!(lane_id))]),
        ));

        Ok(rx)
    }

    /// Start the scheduler
    pub async fn start_scheduler(self: Arc<Self>) {
        tokio::spawn(async move {
            loop {
                self.schedule_next().await;
                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            }
        });
    }

    /// Schedule the next command
    async fn schedule_next(&self) {
        // Find the highest-priority lane with pending commands.
        // effective_priority applies any deadline-based boost configured on the lane.
        let lanes = self.lanes.lock().await;

        // Check pressure transitions for all lanes and emit events
        for (lane_id, lane) in lanes.iter() {
            if let Some(event_key) = lane.check_pressure().await {
                self.event_emitter.emit(LaneEvent::with_map(
                    event_key,
                    HashMap::from([("lane_id".to_string(), serde_json::json!(lane_id))]),
                ));
            }
        }

        let mut lane_priorities = Vec::new();
        for lane in lanes.values() {
            let priority = lane.effective_priority().await;
            lane_priorities.push((priority, Arc::clone(lane)));
        }

        // Sort by priority (lower number = higher priority)
        lane_priorities.sort_by_key(|(priority, _)| *priority);

        for (_, lane) in lane_priorities {
            if let Some(mut wrapper) = lane.try_dequeue().await {
                let lane_clone = Arc::clone(&lane);
                let timeout = wrapper.timeout;
                let retry_policy = wrapper.retry_policy.clone();
                let attempt = wrapper.attempt;
                let dlq = self.dlq.clone();
                let command_id = wrapper.id.clone();
                let command_type = wrapper.command_type.clone();
                let lane_id = wrapper.lane_id.clone();
                let storage = lane.storage.clone();
                let event_emitter = self.event_emitter.clone();

                event_emitter.emit(LaneEvent::with_map(
                    events::QUEUE_COMMAND_STARTED,
                    HashMap::from([
                        ("lane_id".to_string(), serde_json::json!(lane_id)),
                        ("command_id".to_string(), serde_json::json!(command_id)),
                        ("command_type".to_string(), serde_json::json!(command_type)),
                    ]),
                ));

                tokio::spawn(async move {
                    #[cfg(feature = "telemetry")]
                    let exec_start = Instant::now();

                    let result = match timeout {
                        Some(dur) => {
                            match tokio::time::timeout(dur, wrapper.command.execute()).await {
                                Ok(r) => r,
                                Err(_) => Err(LaneError::Timeout(dur)),
                            }
                        }
                        None => wrapper.command.execute().await,
                    };

                    match result {
                        Ok(value) => {
                            if let Some(storage) = &storage {
                                let _ = storage.remove_command(&command_id).await;
                            }

                            #[cfg(feature = "telemetry")]
                            telemetry::record_complete(
                                &lane_id,
                                exec_start.elapsed().as_secs_f64(),
                            );

                            event_emitter.emit(LaneEvent::with_map(
                                events::QUEUE_COMMAND_COMPLETED,
                                HashMap::from([
                                    ("lane_id".to_string(), serde_json::json!(lane_id)),
                                    ("command_id".to_string(), serde_json::json!(command_id)),
                                ]),
                            ));

                            if let Some(tx) = wrapper.result_tx.take() {
                                let _ = tx.send(Ok(value));
                            }
                            lane_clone.mark_completed().await;
                        }
                        Err(err) => {
                            if retry_policy.should_retry(attempt) {
                                let delay = retry_policy.delay_for_attempt(attempt + 1);

                                tracing::info!(
                                    command_id = %command_id,
                                    retry_attempt = attempt + 1,
                                    "a3s.lane.retry: retrying command"
                                );

                                event_emitter.emit(LaneEvent::with_map(
                                    events::QUEUE_COMMAND_RETRY,
                                    HashMap::from([
                                        ("lane_id".to_string(), serde_json::json!(lane_id)),
                                        ("command_id".to_string(), serde_json::json!(command_id)),
                                        ("attempt".to_string(), serde_json::json!(attempt + 1)),
                                    ]),
                                ));

                                lane_clone.retry_command(wrapper, delay).await;
                                lane_clone.mark_completed().await;
                            } else {
                                #[cfg(feature = "telemetry")]
                                telemetry::record_failure(&lane_id);

                                if let Some(storage) = &storage {
                                    let _ = storage.remove_command(&command_id).await;
                                }

                                let error_msg = err.to_string();
                                let is_timeout = matches!(err, LaneError::Timeout(_));

                                if let Some(dlq) = dlq {
                                    let dead_letter = DeadLetter {
                                        command_id: command_id.clone(),
                                        command_type: command_type.clone(),
                                        lane_id: lane_id.clone(),
                                        error: error_msg.clone(),
                                        attempts: attempt + 1,
                                        failed_at: Utc::now(),
                                    };
                                    dlq.push(dead_letter).await;

                                    event_emitter.emit(LaneEvent::with_map(
                                        events::QUEUE_COMMAND_DEAD_LETTERED,
                                        HashMap::from([
                                            ("lane_id".to_string(), serde_json::json!(lane_id)),
                                            (
                                                "command_id".to_string(),
                                                serde_json::json!(command_id),
                                            ),
                                            (
                                                "command_type".to_string(),
                                                serde_json::json!(command_type),
                                            ),
                                        ]),
                                    ));
                                }

                                event_emitter.emit(LaneEvent::with_map(
                                    if is_timeout {
                                        events::QUEUE_COMMAND_TIMEOUT
                                    } else {
                                        events::QUEUE_COMMAND_FAILED
                                    },
                                    HashMap::from([
                                        ("lane_id".to_string(), serde_json::json!(lane_id)),
                                        ("command_id".to_string(), serde_json::json!(command_id)),
                                        ("error".to_string(), serde_json::json!(error_msg)),
                                    ]),
                                ));

                                if let Some(tx) = wrapper.result_tx.take() {
                                    let _ = tx.send(Err(err));
                                }
                                lane_clone.mark_completed().await;
                            }
                        }
                    }
                });
                break;
            }
        }
    }

    /// Subscribe to all queue lifecycle events as an `EventStream` (implements `Stream`)
    pub fn subscribe_stream(&self) -> EventStream {
        self.event_emitter.subscribe_stream()
    }

    /// Subscribe to filtered queue lifecycle events as an `EventStream`
    pub fn subscribe_filtered(
        &self,
        filter: impl Fn(&LaneEvent) -> bool + Send + Sync + 'static,
    ) -> EventStream {
        self.event_emitter.subscribe_filtered(filter)
    }

    /// Get queue status for all lanes
    pub async fn status(&self) -> HashMap<LaneId, LaneStatus> {
        let lanes = self.lanes.lock().await;
        let mut status = HashMap::new();

        for (id, lane) in lanes.iter() {
            status.insert(id.clone(), lane.status().await);
        }

        status
    }
}

/// Built-in lane IDs
pub mod lane_ids {
    pub const SYSTEM: &str = "system";
    pub const CONTROL: &str = "control";
    pub const QUERY: &str = "query";
    pub const SESSION: &str = "session";
    pub const SKILL: &str = "skill";
    pub const PROMPT: &str = "prompt";
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Test command implementation
    struct TestCommand {
        result: serde_json::Value,
        delay_ms: Option<u64>,
    }

    impl TestCommand {
        fn new(result: serde_json::Value) -> Self {
            Self {
                result,
                delay_ms: None,
            }
        }

        fn with_delay(result: serde_json::Value, delay_ms: u64) -> Self {
            Self {
                result,
                delay_ms: Some(delay_ms),
            }
        }
    }

    #[async_trait]
    impl Command for TestCommand {
        async fn execute(&self) -> Result<serde_json::Value> {
            if let Some(delay) = self.delay_ms {
                tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
            }
            Ok(self.result.clone())
        }

        fn command_type(&self) -> &str {
            "test"
        }
    }

    /// Failing test command
    struct FailingCommand {
        message: String,
    }

    #[async_trait]
    impl Command for FailingCommand {
        async fn execute(&self) -> Result<serde_json::Value> {
            Err(LaneError::Other(self.message.clone()))
        }

        fn command_type(&self) -> &str {
            "failing"
        }
    }

    #[test]
    fn test_priorities() {
        assert_eq!(priorities::SYSTEM, 0);
        assert_eq!(priorities::CONTROL, 1);
        assert_eq!(priorities::QUERY, 2);
        assert_eq!(priorities::SESSION, 3);
        assert_eq!(priorities::SKILL, 4);
        assert_eq!(priorities::PROMPT, 5);

        // Verify priority ordering: system has highest priority (lowest number)
        // Using const block to satisfy clippy assertions_on_constants
        const _: () = {
            assert!(priorities::SYSTEM < priorities::CONTROL);
            assert!(priorities::CONTROL < priorities::QUERY);
            assert!(priorities::QUERY < priorities::SESSION);
            assert!(priorities::SESSION < priorities::SKILL);
            assert!(priorities::SKILL < priorities::PROMPT);
        };
    }

    #[test]
    fn test_lane_ids() {
        assert_eq!(lane_ids::SYSTEM, "system");
        assert_eq!(lane_ids::CONTROL, "control");
        assert_eq!(lane_ids::QUERY, "query");
        assert_eq!(lane_ids::SESSION, "session");
        assert_eq!(lane_ids::SKILL, "skill");
        assert_eq!(lane_ids::PROMPT, "prompt");
    }

    #[test]
    fn test_lane_new() {
        let config = LaneConfig::new(1, 4);
        let lane = Lane::new("test-lane", config, priorities::QUERY);

        assert_eq!(lane.id(), "test-lane");
    }

    #[tokio::test]
    async fn test_lane_priority() {
        let config = LaneConfig::new(1, 4);
        let lane = Lane::new("test", config, priorities::SESSION);

        assert_eq!(lane.priority().await, priorities::SESSION);
    }

    #[tokio::test]
    async fn test_lane_status_initial() {
        let config = LaneConfig::new(2, 8);
        let lane = Lane::new("test", config, priorities::QUERY);

        let status = lane.status().await;
        assert_eq!(status.pending, 0);
        assert_eq!(status.active, 0);
        assert_eq!(status.min, 2);
        assert_eq!(status.max, 8);
    }

    #[tokio::test]
    async fn test_lane_enqueue() {
        let config = LaneConfig::new(1, 4);
        let lane = Lane::new("test", config, priorities::QUERY);

        let cmd = Box::new(TestCommand::new(serde_json::json!({"result": "ok"})));
        let _rx = lane.enqueue(cmd).await;

        let status = lane.status().await;
        assert_eq!(status.pending, 1);
    }

    #[tokio::test]
    async fn test_lane_status_serialization() {
        let status = LaneStatus {
            pending: 5,
            active: 2,
            min: 1,
            max: 8,
        };

        let json = serde_json::to_string(&status).unwrap();
        assert!(json.contains("\"pending\":5"));
        assert!(json.contains("\"active\":2"));
        assert!(json.contains("\"min\":1"));
        assert!(json.contains("\"max\":8"));

        let parsed: LaneStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.pending, 5);
        assert_eq!(parsed.active, 2);
    }

    #[tokio::test]
    async fn test_command_queue_new() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        let status = queue.status().await;
        assert!(status.is_empty());
    }

    #[tokio::test]
    async fn test_command_queue_register_lane() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));

        queue.register_lane(lane).await;

        let status = queue.status().await;
        assert!(status.contains_key("test-lane"));
    }

    #[tokio::test]
    async fn test_command_queue_submit() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        let cmd = Box::new(TestCommand::new(serde_json::json!({"status": "ok"})));
        let result = queue.submit("test-lane", cmd).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_command_queue_submit_unknown_lane() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        let cmd = Box::new(TestCommand::new(serde_json::json!({})));
        let result = queue.submit("nonexistent", cmd).await;

        assert!(result.is_err());
        if let Err(LaneError::LaneNotFound(id)) = result {
            assert_eq!(id, "nonexistent");
        } else {
            panic!("Expected LaneNotFound error");
        }
    }

    #[tokio::test]
    async fn test_command_queue_multiple_lanes() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        // Register multiple lanes
        let configs = vec![
            ("system", priorities::SYSTEM, 1),
            ("control", priorities::CONTROL, 8),
            ("query", priorities::QUERY, 4),
        ];

        for (id, priority, max) in configs {
            let config = LaneConfig::new(1, max);
            let lane = Arc::new(Lane::new(id, config, priority));
            queue.register_lane(lane).await;
        }

        let status = queue.status().await;
        assert_eq!(status.len(), 3);
        assert!(status.contains_key("system"));
        assert!(status.contains_key("control"));
        assert!(status.contains_key("query"));
    }

    #[tokio::test]
    async fn test_command_queue_status() {
        let emitter = EventEmitter::new(100);
        let queue = CommandQueue::new(emitter);

        let config = LaneConfig::new(2, 16);
        let lane = Arc::new(Lane::new("query", config, priorities::QUERY));
        queue.register_lane(lane).await;

        let status = queue.status().await;
        let lane_status = status.get("query").unwrap();

        assert_eq!(lane_status.min, 2);
        assert_eq!(lane_status.max, 16);
        assert_eq!(lane_status.pending, 0);
        assert_eq!(lane_status.active, 0);
    }

    #[test]
    fn test_lane_state_has_capacity() {
        let config = LaneConfig::new(1, 2);
        let mut state = LaneState::new(config, priorities::QUERY);

        assert!(state.has_capacity());
        state.active = 1;
        assert!(state.has_capacity());
        state.active = 2;
        assert!(!state.has_capacity());
    }

    #[tokio::test]
    async fn test_lane_state_has_pending() {
        let config = LaneConfig::new(1, 4);
        let state = LaneState::new(config, priorities::QUERY);

        assert!(!state.has_pending());
        assert_eq!(state.pending.len(), 0);
    }

    #[test]
    fn test_lane_status_debug() {
        let status = LaneStatus {
            pending: 3,
            active: 1,
            min: 1,
            max: 4,
        };

        let debug_str = format!("{:?}", status);
        assert!(debug_str.contains("LaneStatus"));
        assert!(debug_str.contains("pending"));
        assert!(debug_str.contains("active"));
    }

    #[test]
    fn test_lane_status_clone() {
        let status = LaneStatus {
            pending: 5,
            active: 2,
            min: 1,
            max: 8,
        };

        let cloned = status.clone();
        assert_eq!(cloned.pending, 5);
        assert_eq!(cloned.active, 2);
        assert_eq!(cloned.min, 1);
        assert_eq!(cloned.max, 8);
    }

    #[tokio::test]
    async fn test_command_execution() {
        let cmd = TestCommand::new(serde_json::json!({"value": 42}));
        let result = cmd.execute().await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), serde_json::json!({"value": 42}));
    }

    #[tokio::test]
    async fn test_command_type() {
        let cmd = TestCommand::new(serde_json::json!({}));
        assert_eq!(cmd.command_type(), "test");

        let failing = FailingCommand {
            message: "error".to_string(),
        };
        assert_eq!(failing.command_type(), "failing");
    }

    #[tokio::test]
    async fn test_failing_command() {
        let cmd = FailingCommand {
            message: "Something went wrong".to_string(),
        };

        let result = cmd.execute().await;
        assert!(result.is_err());

        if let Err(LaneError::Other(msg)) = result {
            assert_eq!(msg, "Something went wrong");
        } else {
            panic!("Expected Other error");
        }
    }

    #[tokio::test]
    async fn test_command_with_delay() {
        let cmd = TestCommand::with_delay(serde_json::json!({"delayed": true}), 10);

        let start = std::time::Instant::now();
        let result = cmd.execute().await;
        let elapsed = start.elapsed();

        assert!(result.is_ok());
        assert!(elapsed.as_millis() >= 10);
    }

    #[test]
    fn test_priority_type() {
        let p: Priority = 5;
        assert_eq!(p, 5u8);
    }

    #[test]
    fn test_lane_id_type() {
        let id: LaneId = "test-lane".to_string();
        assert_eq!(id, "test-lane");
    }

    #[test]
    fn test_command_id_type() {
        let id: CommandId = "cmd-123".to_string();
        assert_eq!(id, "cmd-123");
    }

    #[tokio::test]
    async fn test_command_timeout() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4).with_timeout(std::time::Duration::from_millis(50));
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        // Start scheduler
        Arc::clone(&queue).start_scheduler().await;

        // Submit a command that takes longer than timeout
        let cmd = Box::new(TestCommand::with_delay(
            serde_json::json!({"result": "ok"}),
            200,
        ));
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Wait for result
        let result = tokio::time::timeout(std::time::Duration::from_secs(1), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        // Should be a timeout error
        assert!(result.is_err());
        if let Err(LaneError::Timeout(dur)) = result {
            assert_eq!(dur, std::time::Duration::from_millis(50));
        } else {
            panic!("Expected Timeout error");
        }
    }

    #[tokio::test]
    async fn test_command_no_timeout() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        // Submit a command with delay but no timeout configured
        let cmd = Box::new(TestCommand::with_delay(
            serde_json::json!({"result": "ok"}),
            50,
        ));
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        let result = tokio::time::timeout(std::time::Duration::from_secs(1), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        // Should succeed
        assert!(result.is_ok());
        assert_eq!(result.unwrap()["result"], "ok");
    }

    #[tokio::test]
    async fn test_command_completes_before_timeout() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4).with_timeout(std::time::Duration::from_secs(5));
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        // Submit a fast command with long timeout
        let cmd = Box::new(TestCommand::with_delay(
            serde_json::json!({"result": "fast"}),
            10,
        ));
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        let result = tokio::time::timeout(std::time::Duration::from_secs(1), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        // Should succeed
        assert!(result.is_ok());
        assert_eq!(result.unwrap()["result"], "fast");
    }

    #[tokio::test]
    async fn test_command_retry_on_failure() {
        use std::sync::atomic::{AtomicU32, Ordering};

        // Command that fails first 2 times, then succeeds
        struct RetryableCommand {
            attempts: Arc<AtomicU32>,
        }

        #[async_trait]
        impl Command for RetryableCommand {
            async fn execute(&self) -> Result<serde_json::Value> {
                let attempt = self.attempts.fetch_add(1, Ordering::SeqCst);
                if attempt < 2 {
                    Err(LaneError::Other(format!("Attempt {} failed", attempt)))
                } else {
                    Ok(serde_json::json!({"success": true, "attempts": attempt + 1}))
                }
            }

            fn command_type(&self) -> &str {
                "retryable"
            }
        }

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let retry_policy = RetryPolicy::fixed(3, std::time::Duration::from_millis(10));
        let config = LaneConfig::new(1, 4).with_retry_policy(retry_policy);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        let attempts = Arc::new(AtomicU32::new(0));
        let cmd = Box::new(RetryableCommand {
            attempts: Arc::clone(&attempts),
        });
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Wait for result (should succeed after retries)
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        assert!(result.is_ok());
        let value = result.unwrap();
        assert_eq!(value["success"], true);
        assert_eq!(value["attempts"], 3); // Failed twice, succeeded on 3rd attempt
    }

    #[tokio::test]
    async fn test_command_retry_exhausted() {
        // Command that always fails
        struct AlwaysFailCommand;

        #[async_trait]
        impl Command for AlwaysFailCommand {
            async fn execute(&self) -> Result<serde_json::Value> {
                Err(LaneError::Other("Always fails".to_string()))
            }

            fn command_type(&self) -> &str {
                "always_fail"
            }
        }

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let retry_policy = RetryPolicy::fixed(2, std::time::Duration::from_millis(10));
        let config = LaneConfig::new(1, 4).with_retry_policy(retry_policy);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        let cmd = Box::new(AlwaysFailCommand);
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Wait for result (should fail after exhausting retries)
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        assert!(result.is_err());
        if let Err(LaneError::Other(msg)) = result {
            assert_eq!(msg, "Always fails");
        } else {
            panic!("Expected Other error");
        }
    }

    #[tokio::test]
    async fn test_command_no_retry_on_success() {
        use std::sync::atomic::{AtomicU32, Ordering};

        struct CountingCommand {
            counter: Arc<AtomicU32>,
        }

        #[async_trait]
        impl Command for CountingCommand {
            async fn execute(&self) -> Result<serde_json::Value> {
                let count = self.counter.fetch_add(1, Ordering::SeqCst);
                Ok(serde_json::json!({"count": count + 1}))
            }

            fn command_type(&self) -> &str {
                "counting"
            }
        }

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let retry_policy = RetryPolicy::exponential(3);
        let config = LaneConfig::new(1, 4).with_retry_policy(retry_policy);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        let counter = Arc::new(AtomicU32::new(0));
        let cmd = Box::new(CountingCommand {
            counter: Arc::clone(&counter),
        });
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        let result = tokio::time::timeout(std::time::Duration::from_secs(1), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        assert!(result.is_ok());
        assert_eq!(result.unwrap()["count"], 1);

        // Verify command was only executed once (no retries on success)
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_dlq_integration() {
        // Command that always fails
        struct FailCommand;

        #[async_trait]
        impl Command for FailCommand {
            async fn execute(&self) -> Result<serde_json::Value> {
                Err(LaneError::Other("Permanent failure".to_string()))
            }

            fn command_type(&self) -> &str {
                "fail_command"
            }
        }

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::with_dlq(emitter, 100));

        let retry_policy = RetryPolicy::fixed(2, std::time::Duration::from_millis(10));
        let config = LaneConfig::new(1, 4).with_retry_policy(retry_policy);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        // Submit a failing command
        let cmd = Box::new(FailCommand);
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Wait for result
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx)
            .await
            .expect("Timeout waiting for result")
            .expect("Channel closed");

        assert!(result.is_err());

        // Check DLQ
        let dlq = queue.dlq().expect("DLQ should exist");
        tokio::time::sleep(std::time::Duration::from_millis(50)).await; // Give time for DLQ push

        assert_eq!(dlq.len().await, 1);

        let letters = dlq.list().await;
        assert_eq!(letters[0].command_type, "fail_command");
        assert_eq!(letters[0].lane_id, "test-lane");
        assert_eq!(letters[0].attempts, 3); // Initial + 2 retries
        assert!(letters[0].error.contains("Permanent failure"));
    }

    #[tokio::test]
    async fn test_no_dlq_without_configuration() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        assert!(queue.dlq().is_none());
    }

    #[tokio::test]
    async fn test_shutdown_rejects_new_commands() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        // Initiate shutdown
        queue.shutdown().await;
        assert!(queue.is_shutting_down());

        // Try to submit a command - should be rejected
        let cmd = Box::new(TestCommand::new(serde_json::json!({"test": "data"})));
        let result = queue.submit("test-lane", cmd).await;

        assert!(result.is_err());
        if let Err(LaneError::ShutdownInProgress) = result {
            // Expected
        } else {
            panic!("Expected ShutdownInProgress error");
        }
    }

    #[tokio::test]
    async fn test_drain_waits_for_completion() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        // Submit a slow command
        let cmd = Box::new(TestCommand::with_delay(
            serde_json::json!({"result": "ok"}),
            100,
        ));
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Initiate shutdown
        queue.shutdown().await;

        // Drain should wait for the command to complete
        let drain_result = queue.drain(std::time::Duration::from_secs(2)).await;
        assert!(drain_result.is_ok());

        // Command should have completed
        let result = tokio::time::timeout(std::time::Duration::from_millis(100), rx)
            .await
            .expect("Timeout")
            .expect("Channel closed");
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_drain_timeout() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        Arc::clone(&queue).start_scheduler().await;

        // Submit a very slow command
        let cmd = Box::new(TestCommand::with_delay(
            serde_json::json!({"result": "ok"}),
            5000,
        ));
        let _rx = queue.submit("test-lane", cmd).await.unwrap();

        // Initiate shutdown
        queue.shutdown().await;

        // Drain with short timeout should fail
        let drain_result = queue.drain(std::time::Duration::from_millis(50)).await;
        assert!(drain_result.is_err());
        if let Err(LaneError::Timeout(_)) = drain_result {
            // Expected
        } else {
            panic!("Expected Timeout error");
        }
    }

    #[tokio::test]
    async fn test_is_shutting_down() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        assert!(!queue.is_shutting_down());

        queue.shutdown().await;
        assert!(queue.is_shutting_down());
    }

    // ── Pressure event tests ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_lane_pressure_emits_on_threshold() {
        use crate::event::events;

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter.clone()));

        let config = LaneConfig::new(1, 4).with_pressure_threshold(2);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        // Subscribe before enqueuing to capture all events
        let mut stream = emitter.subscribe_filtered(|e| e.key == events::QUEUE_LANE_PRESSURE);

        // Enqueue 2 commands (meets threshold=2)
        for _ in 0..2 {
            let cmd = Box::new(TestCommand::new(serde_json::json!({})));
            std::mem::drop(queue.submit("test-lane", cmd).await.unwrap());
        }

        // Start scheduler — first tick calls check_pressure → pending=2 >= 2 → emit PRESSURE
        Arc::clone(&queue).start_scheduler().await;

        let event = tokio::time::timeout(std::time::Duration::from_secs(1), stream.recv())
            .await
            .expect("No pressure event received within timeout")
            .expect("Stream ended");

        assert_eq!(event.key, events::QUEUE_LANE_PRESSURE);
    }

    #[tokio::test]
    async fn test_lane_idle_emits_when_drained() {
        use crate::event::events;

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter.clone()));

        let config = LaneConfig::new(1, 4).with_pressure_threshold(1);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        // Subscribe to both pressure and idle events
        let mut stream = emitter.subscribe_filtered(|e| {
            e.key == events::QUEUE_LANE_PRESSURE || e.key == events::QUEUE_LANE_IDLE
        });

        // Enqueue 1 command (meets threshold=1)
        let cmd = Box::new(TestCommand::new(serde_json::json!({})));
        std::mem::drop(queue.submit("test-lane", cmd).await.unwrap());

        // Start scheduler
        Arc::clone(&queue).start_scheduler().await;

        // First event must be pressure
        let pressure = tokio::time::timeout(std::time::Duration::from_secs(1), stream.recv())
            .await
            .expect("No pressure event")
            .expect("Stream ended");
        assert_eq!(pressure.key, events::QUEUE_LANE_PRESSURE);

        // After dequeue, pending=0 → idle event on the next scheduler tick
        let idle = tokio::time::timeout(std::time::Duration::from_secs(1), stream.recv())
            .await
            .expect("No idle event")
            .expect("Stream ended");
        assert_eq!(idle.key, events::QUEUE_LANE_IDLE);
    }

    #[tokio::test]
    async fn test_lane_no_pressure_without_threshold() {
        use crate::event::events;

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter.clone()));

        // No pressure threshold
        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        let mut stream = emitter.subscribe_filtered(|e| {
            e.key == events::QUEUE_LANE_PRESSURE || e.key == events::QUEUE_LANE_IDLE
        });

        // Enqueue several commands
        for _ in 0..5 {
            let cmd = Box::new(TestCommand::new(serde_json::json!({})));
            std::mem::drop(queue.submit("test-lane", cmd).await.unwrap());
        }

        Arc::clone(&queue).start_scheduler().await;

        // Allow time for scheduler ticks to run
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // No pressure/idle events should have been emitted
        let result =
            tokio::time::timeout(std::time::Duration::from_millis(50), stream.recv()).await;

        assert!(
            result.is_err(),
            "Should not receive pressure/idle events without threshold"
        );
    }

    // ── Bug-fix tests ──────────────────────────────────────────────────────────

    /// Bug fix: EventEmitter.emit() is now called on submit, start, complete, retry,
    /// dead-letter, fail, and shutdown.
    #[tokio::test]
    async fn test_event_emitted_on_submit() {
        use crate::event::events;

        let emitter = EventEmitter::new(100);
        let mut rx = emitter.subscribe();
        let queue = CommandQueue::new(emitter);

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;

        let cmd = Box::new(TestCommand::new(serde_json::json!({"result": "ok"})));
        std::mem::drop(queue.submit("test-lane", cmd).await.unwrap());

        let event = tokio::time::timeout(std::time::Duration::from_millis(200), async {
            rx.recv().await.unwrap()
        })
        .await
        .expect("QUEUE_COMMAND_SUBMITTED event not received");

        assert_eq!(event.key, events::QUEUE_COMMAND_SUBMITTED);
    }

    #[tokio::test]
    async fn test_event_emitted_on_complete() {
        use crate::event::{events, EventStream};

        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter.clone()));

        let config = LaneConfig::new(1, 4);
        let lane = Arc::new(Lane::new("test-lane", config, priorities::QUERY));
        queue.register_lane(lane).await;
        Arc::clone(&queue).start_scheduler().await;

        let mut stream: EventStream =
            emitter.subscribe_filtered(|e| e.key == events::QUEUE_COMMAND_COMPLETED);

        let cmd = Box::new(TestCommand::new(serde_json::json!({"result": "ok"})));
        let rx = queue.submit("test-lane", cmd).await.unwrap();

        // Wait for command to complete
        let _ = tokio::time::timeout(std::time::Duration::from_secs(1), rx).await;

        let event = tokio::time::timeout(std::time::Duration::from_millis(200), stream.recv())
            .await
            .expect("QUEUE_COMMAND_COMPLETED event not received")
            .expect("stream closed");

        assert_eq!(event.key, events::QUEUE_COMMAND_COMPLETED);
    }

    #[tokio::test]
    async fn test_event_emitted_on_shutdown() {
        use crate::event::events;

        let emitter = EventEmitter::new(100);
        let mut rx = emitter.subscribe();
        let queue = CommandQueue::new(emitter);

        queue.shutdown().await;

        let event = tokio::time::timeout(std::time::Duration::from_millis(100), async {
            rx.recv().await.unwrap()
        })
        .await
        .expect("QUEUE_SHUTDOWN_STARTED event not received");

        assert_eq!(event.key, events::QUEUE_SHUTDOWN_STARTED);
    }

    #[cfg(feature = "distributed")]
    #[tokio::test]
    async fn test_rate_limit_blocks_dequeue() {
        use crate::ratelimit::RateLimitConfig;

        // Token bucket starts full (1 token for per_second(1))
        let config = LaneConfig::new(1, 10).with_rate_limit(RateLimitConfig::per_second(1));
        let lane = Lane::new("test", config, priorities::QUERY);

        let _rx1 = lane
            .enqueue(Box::new(TestCommand::new(serde_json::json!(1))))
            .await;
        let _rx2 = lane
            .enqueue(Box::new(TestCommand::new(serde_json::json!(2))))
            .await;

        // First dequeue consumes the single available token
        let first = lane.try_dequeue().await;
        assert!(first.is_some(), "first dequeue should succeed");
        // Return the slot so capacity isn't the limiting factor
        lane.mark_completed().await;

        // No tokens left — rate limiter should block the second dequeue
        let second = lane.try_dequeue().await;
        assert!(second.is_none(), "second dequeue should be rate-limited");
    }

    #[cfg(feature = "distributed")]
    #[tokio::test]
    async fn test_effective_priority_no_boost_when_fresh() {
        use crate::boost::PriorityBoostConfig;

        // Boost activates with 9 s remaining on a 10 s deadline.
        // A freshly-enqueued command has ~10 s left, so no boost yet.
        let config = LaneConfig::new(1, 4).with_priority_boost(
            PriorityBoostConfig::new(std::time::Duration::from_secs(10))
                .with_boost(std::time::Duration::from_secs(9), 2),
        );
        let lane = Lane::new("test", config, priorities::QUERY);

        // Without any pending command the lane returns its base priority
        assert_eq!(lane.effective_priority().await, priorities::QUERY);

        // A just-enqueued command has ~10 s left — no boost
        let _rx = lane
            .enqueue(Box::new(TestCommand::new(serde_json::json!(1))))
            .await;
        assert_eq!(lane.effective_priority().await, priorities::QUERY);
    }

    #[cfg(feature = "distributed")]
    #[tokio::test]
    async fn test_effective_priority_boosted_when_past_deadline() {
        use crate::boost::PriorityBoostConfig;

        // Deadline already passed — effective priority should reach 0 (maximum)
        let config = LaneConfig::new(1, 4).with_priority_boost(PriorityBoostConfig::standard(
            std::time::Duration::from_millis(1), // 1 ms deadline
        ));
        let lane = Lane::new("test", config, priorities::PROMPT); // base = 5

        let _rx = lane
            .enqueue(Box::new(TestCommand::new(serde_json::json!(1))))
            .await;

        // Sleep past the deadline so the booster gives priority 0
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        assert_eq!(lane.effective_priority().await, 0);
    }
}