fsqlite-vdbe 0.1.5

Virtual database engine bytecode interpreter
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
//! Morsel-driven parallel dispatcher for vectorized pipelines (`bd-14vp7.6`).
//!
//! This module provides:
//! - page-range morsel partitioning,
//! - pipeline task definitions,
//! - crossbeam-deque work-stealing execution,
//! - pipeline barriers between pipeline waves.

use std::collections::HashMap;
use std::fmt;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::time::Instant;

use asupersync::runtime::Runtime;
use crossbeam_deque::{Steal, Stealer, Worker};
use fsqlite_types::PageNumber;
use fsqlite_types::cx::{Cx, cap};

use crate::vectorized_scan::PageMorsel;

/// Dispatcher errors.
#[derive(Debug)]
pub enum DispatchError {
    InvalidConfig(&'static str),
    InvalidTaskSet {
        expected_pipeline: PipelineId,
        found_pipeline: PipelineId,
        task_id: usize,
    },
    RuntimeUnavailable,
    Cancelled,
    WorkerPanicked,
}

impl fmt::Display for DispatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidConfig(msg) => write!(f, "invalid dispatcher config: {msg}"),
            Self::InvalidTaskSet {
                expected_pipeline,
                found_pipeline,
                task_id,
            } => write!(
                f,
                "task {task_id} belongs to pipeline {:?}, expected {:?}",
                found_pipeline, expected_pipeline
            ),
            Self::RuntimeUnavailable => {
                f.write_str("vectorized dispatch requires an active asupersync runtime")
            }
            Self::Cancelled => f.write_str("vectorized dispatch cancelled"),
            Self::WorkerPanicked => f.write_str("worker thread panicked during dispatch"),
        }
    }
}

impl std::error::Error for DispatchError {}

/// Result alias for dispatcher operations.
pub type DispatchResult<T> = std::result::Result<T, DispatchError>;

/// Fallback L2 cache size for morsel auto-tuning.
///
/// Used when host cache details are unavailable. On modern server CPUs
/// (2-4 MiB per core), 1 MiB is a conservative underestimate. A future
/// enhancement could detect the actual L2 cache size at startup via
/// `/sys/devices/system/cpu/cpu0/cache/` on Linux or
/// `sysctl hw.l2cachesize` on macOS.
pub const DEFAULT_L2_CACHE_BYTES: usize = 1_048_576;
/// Default database page size used for morsel auto-tuning.
///
/// Derived from the canonical default in `fsqlite-types::limits`. When the
/// morsel dispatcher is invoked with a concrete `VdbeEngine`, the engine's
/// actual `page_size` should be preferred over this constant.
pub const DEFAULT_PAGE_SIZE_BYTES: usize = fsqlite_types::limits::DEFAULT_PAGE_SIZE as usize;

// ── Morsel Dispatch Metrics (bd-1rw.2) ─────────────────────────────────────

/// Rows-per-second gauge for morsel execution throughput.
///
/// The current dispatcher tracks task-level throughput and uses that as a
/// stable proxy until row-level accounting is threaded through operator outputs.
static FSQLITE_MORSEL_THROUGHPUT_ROWS_PER_SEC: AtomicU64 = AtomicU64::new(0);
/// Active-workers gauge for the most recent pipeline dispatch.
static FSQLITE_MORSEL_WORKERS_ACTIVE: AtomicU64 = AtomicU64::new(0);

/// Snapshot of morsel dispatch gauges.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MorselDispatchMetricsSnapshot {
    /// Gauge: `fsqlite_morsel_throughput_rows_per_sec`.
    pub fsqlite_morsel_throughput_rows_per_sec: u64,
    /// Gauge: `fsqlite_morsel_workers_active`.
    pub fsqlite_morsel_workers_active: u64,
}

/// Read a point-in-time snapshot of morsel dispatch gauges.
#[must_use]
pub fn morsel_dispatch_metrics_snapshot() -> MorselDispatchMetricsSnapshot {
    MorselDispatchMetricsSnapshot {
        fsqlite_morsel_throughput_rows_per_sec: FSQLITE_MORSEL_THROUGHPUT_ROWS_PER_SEC
            .load(AtomicOrdering::Relaxed),
        fsqlite_morsel_workers_active: FSQLITE_MORSEL_WORKERS_ACTIVE.load(AtomicOrdering::Relaxed),
    }
}

/// Reset morsel dispatch gauges (tests/diagnostics).
pub fn reset_morsel_dispatch_metrics() {
    FSQLITE_MORSEL_THROUGHPUT_ROWS_PER_SEC.store(0, AtomicOrdering::Relaxed);
    FSQLITE_MORSEL_WORKERS_ACTIVE.store(0, AtomicOrdering::Relaxed);
}

/// A contiguous scan morsel plus locality hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MorselDescriptor {
    pub morsel_id: usize,
    pub page_range: PageMorsel,
    pub preferred_numa_node: usize,
}

/// Partition a page interval into fixed-size morsels.
///
/// # Errors
///
/// Returns an error when `pages_per_morsel == 0`, `numa_nodes == 0`, or the
/// page bounds are invalid.
pub fn partition_page_morsels(
    start_page: PageNumber,
    end_page: PageNumber,
    pages_per_morsel: u32,
    numa_nodes: usize,
) -> DispatchResult<Vec<MorselDescriptor>> {
    if pages_per_morsel == 0 {
        return Err(DispatchError::InvalidConfig(
            "pages_per_morsel must be greater than zero",
        ));
    }
    if numa_nodes == 0 {
        return Err(DispatchError::InvalidConfig(
            "numa_nodes must be greater than zero",
        ));
    }

    let full = PageMorsel::new(start_page, end_page).map_err(|_| {
        DispatchError::InvalidConfig("start_page must be less than or equal to end_page")
    })?;

    // Alien Optimization: Content-Aware Morsel Partitioning (CAMP) §1.2.
    // Pre-calculate the total number of morsels to minimize vector re-allocations,
    // but only after the config and page bounds are known to be valid.
    let total_pages = u64::from(full.end_page.get()) - u64::from(full.start_page.get()) + 1;
    let expected_morsels = usize::try_from(total_pages.div_ceil(u64::from(pages_per_morsel)))
        .map_err(|_| DispatchError::InvalidConfig("morsel count does not fit in usize"))?;
    let mut out = Vec::with_capacity(expected_morsels);

    let mut current = full.start_page.get();
    let mut morsel_id = 0usize;
    while current <= full.end_page.get() {
        let span_end = current
            .saturating_add(pages_per_morsel.saturating_sub(1))
            .min(full.end_page.get());

        // Fast-path range construction.
        let range = PageMorsel {
            start_page: PageNumber::new(current).unwrap(),
            end_page: PageNumber::new(span_end).unwrap(),
        };

        out.push(MorselDescriptor {
            morsel_id,
            page_range: range,
            preferred_numa_node: morsel_id % numa_nodes,
        });
        morsel_id = morsel_id.saturating_add(1);
        if span_end == u32::MAX {
            break;
        }
        current = span_end.saturating_add(1);
    }

    Ok(out)
}

/// Compute an L2-aware pages-per-morsel target.
///
/// Heuristic: reserve half of L2 for the working morsel and half for operator
/// state/auxiliary data. This keeps the active morsel cache-resident while
/// avoiding overfitting to any one operator shape.
///
/// # Errors
///
/// Returns an error when `l2_cache_bytes == 0` or `page_size_bytes == 0`.
pub fn auto_tuned_pages_per_morsel(
    l2_cache_bytes: usize,
    page_size_bytes: usize,
) -> DispatchResult<u32> {
    if l2_cache_bytes == 0 {
        return Err(DispatchError::InvalidConfig(
            "l2_cache_bytes must be greater than zero",
        ));
    }
    if page_size_bytes == 0 {
        return Err(DispatchError::InvalidConfig(
            "page_size_bytes must be greater than zero",
        ));
    }
    let target_bytes = l2_cache_bytes / 2;
    let pages = (target_bytes / page_size_bytes).max(1);
    let pages_u32 = u32::try_from(pages).unwrap_or(u32::MAX);
    Ok(pages_u32.max(1))
}

/// Partition a page interval into L2 auto-tuned morsels.
///
/// # Errors
///
/// Returns an error when auto-tuning inputs are invalid or page bounds are invalid.
pub fn partition_page_morsels_auto_tuned(
    start_page: PageNumber,
    end_page: PageNumber,
    l2_cache_bytes: usize,
    page_size_bytes: usize,
    numa_nodes: usize,
) -> DispatchResult<Vec<MorselDescriptor>> {
    let pages_per_morsel = auto_tuned_pages_per_morsel(l2_cache_bytes, page_size_bytes)?;
    partition_page_morsels(start_page, end_page, pages_per_morsel, numa_nodes)
}

/// Logical pipeline identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PipelineId(pub usize);

/// Pipeline kind metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PipelineKind {
    ScanFilterProject,
    HashJoinProbe,
    AggregateUpdate,
    PipelineBreaker,
}

/// A unit of work scheduled by the dispatcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PipelineTask {
    pub task_id: usize,
    pub pipeline: PipelineId,
    pub kind: PipelineKind,
    pub morsel: MorselDescriptor,
}

/// Build one pipeline task per morsel.
#[must_use]
pub fn build_pipeline_tasks(
    pipeline: PipelineId,
    kind: PipelineKind,
    morsels: &[MorselDescriptor],
) -> Vec<PipelineTask> {
    morsels
        .iter()
        .map(|morsel| PipelineTask {
            task_id: morsel.morsel_id,
            pipeline,
            kind,
            morsel: *morsel,
        })
        .collect()
}

/// Exchange operator distribution mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExchangeKind {
    /// Hash-partition data across worker partitions.
    HashPartition,
    /// Broadcast data to every worker partition.
    Broadcast,
}

/// One task identifier plus the exchange hash key used for partitioning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExchangeTaskRef {
    pub task_id: usize,
    pub hash_key: u64,
}

/// Default hot-partition spill threshold for hash exchange.
pub const DEFAULT_EXCHANGE_HOT_PARTITION_SPLIT_THRESHOLD: usize = 32;

/// Hash-partition task ids into worker partitions with skew spill-over.
///
/// # Errors
///
/// Returns an error when `partitions == 0` or `hot_partition_split_threshold == 0`.
pub fn hash_partition_exchange(
    task_refs: &[ExchangeTaskRef],
    partitions: usize,
    hot_partition_split_threshold: usize,
) -> DispatchResult<Vec<Vec<usize>>> {
    if partitions == 0 {
        return Err(DispatchError::InvalidConfig(
            "partitions must be greater than zero",
        ));
    }
    if hot_partition_split_threshold == 0 {
        return Err(DispatchError::InvalidConfig(
            "hot_partition_split_threshold must be greater than zero",
        ));
    }

    let partitions_u64 = u64::try_from(partitions)
        .map_err(|_| DispatchError::InvalidConfig("partitions does not fit in u64"))?;
    let mut partitioned = vec![Vec::new(); partitions];

    for task_ref in task_refs {
        let hashed_partition_u64 = task_ref.hash_key % partitions_u64;
        let mut target_partition = usize::try_from(hashed_partition_u64).map_err(|_| {
            DispatchError::InvalidConfig("hashed partition index does not fit in usize")
        })?;

        if partitioned[target_partition].len() >= hot_partition_split_threshold {
            target_partition = partitioned
                .iter()
                .enumerate()
                .min_by_key(|(_, bucket)| bucket.len())
                .map_or(target_partition, |(idx, _)| idx);
        }

        partitioned[target_partition].push(task_ref.task_id);
    }

    Ok(partitioned)
}

/// Broadcast task ids to every partition.
///
/// # Errors
///
/// Returns an error when `partitions == 0`.
pub fn broadcast_exchange(
    task_ids: &[usize],
    partitions: usize,
) -> DispatchResult<Vec<Vec<usize>>> {
    if partitions == 0 {
        return Err(DispatchError::InvalidConfig(
            "partitions must be greater than zero",
        ));
    }
    Ok((0..partitions).map(|_| task_ids.to_vec()).collect())
}

/// Build exchange assignments directly from pipeline tasks.
///
/// Hash partitioning uses `task_id` as a deterministic default key; callers that
/// need data-dependent partitioning can call `hash_partition_exchange` directly
/// with explicit [`ExchangeTaskRef`] keys.
///
/// # Errors
///
/// Returns the same validation errors as the selected exchange mode.
pub fn build_exchange_task_ids(
    tasks: &[PipelineTask],
    exchange_kind: ExchangeKind,
    partitions: usize,
    hot_partition_split_threshold: usize,
) -> DispatchResult<Vec<Vec<usize>>> {
    match exchange_kind {
        ExchangeKind::HashPartition => {
            let refs = tasks
                .iter()
                .map(|task| {
                    let hash_key = u64::try_from(task.task_id)
                        .map_err(|_| DispatchError::InvalidConfig("task_id does not fit in u64"))?;
                    Ok(ExchangeTaskRef {
                        task_id: task.task_id,
                        hash_key,
                    })
                })
                .collect::<DispatchResult<Vec<_>>>()?;
            hash_partition_exchange(&refs, partitions, hot_partition_split_threshold)
        }
        ExchangeKind::Broadcast => {
            let task_ids = tasks.iter().map(|task| task.task_id).collect::<Vec<_>>();
            broadcast_exchange(&task_ids, partitions)
        }
    }
}

/// Dispatcher configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DispatcherConfig {
    pub worker_threads: usize,
    pub numa_nodes: usize,
}

impl Default for DispatcherConfig {
    fn default() -> Self {
        let workers = std::thread::available_parallelism()
            .map_or(2, std::num::NonZeroUsize::get)
            .saturating_sub(1)
            .max(1);
        Self {
            worker_threads: workers,
            numa_nodes: 1,
        }
    }
}

/// Completed task record with execution metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompletedTask<R> {
    pub task_id: usize,
    pub worker_id: usize,
    pub result: R,
}

/// Per-pipeline execution report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PipelineExecution<R> {
    pub pipeline: PipelineId,
    pub completed: Vec<CompletedTask<R>>,
    pub per_worker_task_counts: Vec<usize>,
}

/// Correlation fields attached to morsel-dispatch structured logs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchRunContext {
    pub run_id: String,
    pub trace_id: u64,
    pub scenario_id: String,
}

impl DispatchRunContext {
    /// Construct and validate a dispatch run context.
    ///
    /// # Errors
    ///
    /// Returns an error when `run_id` or `scenario_id` is empty.
    pub fn try_new(run_id: String, trace_id: u64, scenario_id: String) -> DispatchResult<Self> {
        let candidate = Self {
            run_id,
            trace_id,
            scenario_id,
        };
        candidate.validate()?;
        Ok(candidate)
    }

    fn validate(&self) -> DispatchResult<()> {
        if self.run_id.trim().is_empty() {
            return Err(DispatchError::InvalidConfig(
                "dispatch run_id must be non-empty",
            ));
        }
        if self.scenario_id.trim().is_empty() {
            return Err(DispatchError::InvalidConfig(
                "dispatch scenario_id must be non-empty",
            ));
        }
        Ok(())
    }
}

impl Default for DispatchRunContext {
    fn default() -> Self {
        Self {
            run_id: "dispatch-run-unspecified".to_owned(),
            trace_id: 0,
            scenario_id: "VDBE-UNSPECIFIED".to_owned(),
        }
    }
}

/// Work-stealing dispatcher with pipeline barriers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkStealingDispatcher {
    config: DispatcherConfig,
    worker_numa: Vec<usize>,
}

fn morsel_page_span(morsel: MorselDescriptor) -> u64 {
    let start = u64::from(morsel.page_range.start_page.get());
    let end = u64::from(morsel.page_range.end_page.get());
    end.saturating_sub(start).saturating_add(1)
}

impl WorkStealingDispatcher {
    /// Create a dispatcher from explicit config.
    ///
    /// # Errors
    ///
    /// Returns an error when the worker count or NUMA node count is zero.
    pub fn try_new(config: DispatcherConfig) -> DispatchResult<Self> {
        if config.worker_threads == 0 {
            return Err(DispatchError::InvalidConfig(
                "worker_threads must be greater than zero",
            ));
        }
        if config.numa_nodes == 0 {
            return Err(DispatchError::InvalidConfig(
                "numa_nodes must be greater than zero",
            ));
        }
        let worker_numa = (0..config.worker_threads)
            .map(|worker_id| worker_id % config.numa_nodes)
            .collect();
        Ok(Self {
            config,
            worker_numa,
        })
    }

    /// NUMA node assignment per worker index.
    #[must_use]
    pub fn worker_numa_nodes(&self) -> &[usize] {
        &self.worker_numa
    }

    /// Execute pipelines with an implicit barrier between each pipeline.
    ///
    /// All tasks in `pipelines[i]` are completed before any task in
    /// `pipelines[i + 1]` begins execution.
    ///
    /// # Errors
    ///
    /// Returns an error if task metadata is inconsistent or a worker panics.
    pub async fn execute_with_barriers<R, F>(
        &self,
        cx: &Cx<cap::All>,
        pipelines: &[Vec<PipelineTask>],
        execute: F,
    ) -> DispatchResult<Vec<PipelineExecution<R>>>
    where
        R: Send + 'static,
        F: Fn(&PipelineTask, usize) -> R + Send + Sync + 'static,
    {
        let context = DispatchRunContext::default();
        self.execute_with_barriers_with_context(cx, pipelines, &context, execute)
            .await
    }

    /// Execute pipelines with an implicit barrier between each pipeline and
    /// include explicit run correlation fields in structured logs.
    ///
    /// # Errors
    ///
    /// Returns an error if task metadata is inconsistent, worker execution
    /// panics, or the provided `context` is invalid.
    pub async fn execute_with_barriers_with_context<R, F>(
        &self,
        cx: &Cx<cap::All>,
        pipelines: &[Vec<PipelineTask>],
        context: &DispatchRunContext,
        execute: F,
    ) -> DispatchResult<Vec<PipelineExecution<R>>>
    where
        R: Send + 'static,
        F: Fn(&PipelineTask, usize) -> R + Send + Sync + 'static,
    {
        context.validate()?;
        dispatch_checkpoint(cx)?;
        let execute = Arc::new(execute);
        let mut reports = Vec::with_capacity(pipelines.len());

        for tasks in pipelines {
            if tasks.is_empty() {
                continue;
            }
            let report = self
                .execute_single_pipeline(cx, tasks, context, &execute)
                .await?;
            reports.push(report);
        }

        Ok(reports)
    }

    /// Synchronous wrapper for callers that already own the runtime.
    pub fn execute_with_barriers_on_runtime<R, F>(
        &self,
        runtime: &Runtime,
        pipelines: &[Vec<PipelineTask>],
        execute: F,
    ) -> DispatchResult<Vec<PipelineExecution<R>>>
    where
        R: Send + 'static,
        F: Fn(&PipelineTask, usize) -> R + Send + Sync + 'static,
    {
        runtime.block_on(async {
            let cx = Cx::<cap::All>::new();
            self.execute_with_barriers(&cx, pipelines, execute).await
        })
    }

    /// Synchronous wrapper with explicit run correlation fields.
    pub fn execute_with_barriers_with_context_on_runtime<R, F>(
        &self,
        runtime: &Runtime,
        pipelines: &[Vec<PipelineTask>],
        context: &DispatchRunContext,
        execute: F,
    ) -> DispatchResult<Vec<PipelineExecution<R>>>
    where
        R: Send + 'static,
        F: Fn(&PipelineTask, usize) -> R + Send + Sync + 'static,
    {
        runtime.block_on(async {
            let cx = Cx::<cap::All>::new();
            self.execute_with_barriers_with_context(&cx, pipelines, context, execute)
                .await
        })
    }

    #[allow(clippy::too_many_lines)]
    async fn execute_single_pipeline<R, F>(
        &self,
        cx: &Cx<cap::All>,
        tasks: &[PipelineTask],
        context: &DispatchRunContext,
        execute: &Arc<F>,
    ) -> DispatchResult<PipelineExecution<R>>
    where
        R: Send + 'static,
        F: Fn(&PipelineTask, usize) -> R + Send + Sync + 'static,
    {
        let expected_pipeline = tasks[0].pipeline;
        let pipeline_started = Instant::now();
        for task in tasks {
            if task.pipeline != expected_pipeline {
                return Err(DispatchError::InvalidTaskSet {
                    expected_pipeline,
                    found_pipeline: task.pipeline,
                    task_id: task.task_id,
                });
            }
        }

        let workers: Vec<Worker<PipelineTask>> = (0..self.config.worker_threads)
            .map(|_| Worker::new_fifo())
            .collect();
        let stealers: Vec<Stealer<PipelineTask>> = workers.iter().map(Worker::stealer).collect();
        let runtime_handle = Runtime::current_handle().ok_or(DispatchError::RuntimeUnavailable)?;

        let use_hash_exchange = tasks
            .iter()
            .all(|task| matches!(task.kind, PipelineKind::HashJoinProbe));
        let mut task_to_worker = HashMap::<usize, usize>::new();
        if use_hash_exchange {
            let refs = tasks
                .iter()
                .map(|task| {
                    let hash_key = u64::try_from(task.task_id)
                        .map_err(|_| DispatchError::InvalidConfig("task_id does not fit in u64"))?;
                    Ok(ExchangeTaskRef {
                        task_id: task.task_id,
                        hash_key,
                    })
                })
                .collect::<DispatchResult<Vec<_>>>()?;
            let assignments = hash_partition_exchange(
                &refs,
                self.config.worker_threads,
                DEFAULT_EXCHANGE_HOT_PARTITION_SPLIT_THRESHOLD,
            )?;
            for (worker_id, task_ids) in assignments.into_iter().enumerate() {
                for task_id in task_ids {
                    task_to_worker.insert(task_id, worker_id);
                }
            }
            if task_to_worker.len() != tasks.len() {
                return Err(DispatchError::InvalidConfig(
                    "hash exchange assignment did not cover every task",
                ));
            }
        }

        let mut next_by_numa = vec![0usize; self.config.numa_nodes];
        for task in tasks.iter().cloned() {
            let (target, schedule_strategy) = if use_hash_exchange {
                let target = task_to_worker.get(&task.task_id).copied().ok_or(
                    DispatchError::InvalidConfig("hash exchange assignment missing task"),
                )?;
                (target, "hash_exchange")
            } else {
                (
                    self.select_worker(task.morsel.preferred_numa_node, &mut next_by_numa),
                    "numa_round_robin",
                )
            };
            tracing::debug!(
                pipeline_id = expected_pipeline.0,
                task_id = task.task_id,
                run_id = %context.run_id,
                trace_id = context.trace_id,
                scenario_id = %context.scenario_id,
                target_worker = target,
                preferred_numa_node = task.morsel.preferred_numa_node,
                schedule_strategy,
                morsel_start_page = task.morsel.page_range.start_page.get(),
                morsel_end_page = task.morsel.page_range.end_page.get(),
                morsel_size = morsel_page_span(task.morsel),
                "morsel.schedule"
            );
            workers[target].push(task);
        }

        let pipeline_cx = cx.create_child();
        let mut handles = Vec::with_capacity(self.config.worker_threads);
        let run_id = context.run_id.clone();
        let scenario_id = context.scenario_id.clone();
        let trace_id = context.trace_id;
        for (worker_id, local_worker) in workers.into_iter().enumerate() {
            let execute = Arc::clone(execute);
            let stealers = stealers.clone();
            let worker_cx = pipeline_cx.create_child();
            let pipeline_cx_for_worker = pipeline_cx.clone();
            let run_id = run_id.clone();
            let scenario_id = scenario_id.clone();
            handles.push(runtime_handle.spawn(async move {
                let worker_result =
                    std::panic::catch_unwind(AssertUnwindSafe(|| -> DispatchResult<_> {
                        dispatch_checkpoint(&worker_cx)?;
                        let mut completed = Vec::new();
                        let mut count = 0usize;
                        let mut rows_processed = 0u64;
                        while let Some(task) = pop_or_steal(&local_worker, worker_id, &stealers) {
                            dispatch_checkpoint(&worker_cx)?;
                            let morsel_size = morsel_page_span(task.morsel);
                            let span = tracing::info_span!(
                                "morsel_exec",
                                morsel_size,
                                worker_id,
                                run_id = %run_id,
                                trace_id,
                                scenario_id = %scenario_id,
                                pipeline_id = task.pipeline.0,
                                task_id = task.task_id
                            );
                            let result = {
                                let _guard = span.enter();
                                tracing::debug!(
                                    worker_id,
                                    pipeline_id = task.pipeline.0,
                                    task_id = task.task_id,
                                    run_id = %run_id,
                                    trace_id,
                                    scenario_id = %scenario_id,
                                    morsel_size,
                                    "morsel.execute.start"
                                );
                                let result = execute(&task, worker_id);
                                tracing::debug!(
                                    worker_id,
                                    pipeline_id = task.pipeline.0,
                                    task_id = task.task_id,
                                    run_id = %run_id,
                                    trace_id,
                                    scenario_id = %scenario_id,
                                    morsel_size,
                                    "morsel.execute.complete"
                                );
                                result
                            };
                            completed.push(CompletedTask {
                                task_id: task.task_id,
                                worker_id,
                                result,
                            });
                            count = count.saturating_add(1);
                            rows_processed = rows_processed.saturating_add(morsel_size);
                        }
                        Ok((completed, count, rows_processed))
                    }))
                    .unwrap_or(Err(DispatchError::WorkerPanicked));
                if worker_result.is_err() {
                    pipeline_cx_for_worker.cancel();
                }
                worker_result
            }));
        }

        let mut completed = Vec::with_capacity(tasks.len());
        let mut per_worker_task_counts = vec![0usize; self.config.worker_threads];
        let mut total_rows_processed = 0u64;
        let mut first_error = None;
        for (worker_id, handle) in handles.into_iter().enumerate() {
            match handle.await {
                Ok((mut worker_completed, count, rows_processed)) if first_error.is_none() => {
                    per_worker_task_counts[worker_id] = count;
                    total_rows_processed = total_rows_processed.saturating_add(rows_processed);
                    completed.append(&mut worker_completed);
                }
                Ok(_) => {}
                Err(err) => {
                    if first_error.is_none() {
                        pipeline_cx.cancel();
                        first_error = Some(err);
                    }
                }
            }
        }
        if let Some(err) = first_error {
            return Err(err);
        }

        completed.sort_by_key(|entry| entry.task_id);
        let active_workers = u64::try_from(
            per_worker_task_counts
                .iter()
                .filter(|&&count| count > 0)
                .count(),
        )
        .unwrap_or(u64::MAX);
        let elapsed = pipeline_started.elapsed();
        let elapsed_micros = elapsed.as_micros().max(1);
        let throughput_rows_per_sec_u128 =
            (u128::from(total_rows_processed) * 1_000_000) / elapsed_micros;
        let throughput_rows_per_sec =
            u64::try_from(throughput_rows_per_sec_u128).unwrap_or(u64::MAX);

        FSQLITE_MORSEL_WORKERS_ACTIVE.store(active_workers, AtomicOrdering::Relaxed);
        FSQLITE_MORSEL_THROUGHPUT_ROWS_PER_SEC
            .store(throughput_rows_per_sec, AtomicOrdering::Relaxed);

        tracing::info!(
            pipeline_id = expected_pipeline.0,
            run_id = %context.run_id,
            trace_id = context.trace_id,
            scenario_id = %context.scenario_id,
            completed_tasks = completed.len(),
            worker_threads = self.config.worker_threads,
            active_workers,
            rows_processed = total_rows_processed,
            fsqlite_morsel_throughput_rows_per_sec = throughput_rows_per_sec,
            elapsed_ms = elapsed.as_millis(),
            "morsel.pipeline.complete"
        );

        Ok(PipelineExecution {
            pipeline: expected_pipeline,
            completed,
            per_worker_task_counts,
        })
    }

    fn select_worker(&self, preferred_numa_node: usize, next_by_numa: &mut [usize]) -> usize {
        let candidates: Vec<usize> = self
            .worker_numa
            .iter()
            .enumerate()
            .filter_map(|(worker_id, &node)| (node == preferred_numa_node).then_some(worker_id))
            .collect();
        if candidates.is_empty() {
            return 0;
        }
        let slot = preferred_numa_node % next_by_numa.len();
        let selected = candidates[next_by_numa[slot] % candidates.len()];
        next_by_numa[slot] = next_by_numa[slot].saturating_add(1);
        selected
    }
}

fn pop_or_steal<T>(local: &Worker<T>, worker_id: usize, stealers: &[Stealer<T>]) -> Option<T> {
    if let Some(task) = local.pop() {
        return Some(task);
    }
    steal_from_peers(worker_id, stealers)
}

fn steal_from_peers<T>(worker_id: usize, stealers: &[Stealer<T>]) -> Option<T> {
    let peer_count = stealers.len();
    if peer_count <= 1 {
        return None;
    }

    for offset in 1..peer_count {
        let peer = (worker_id + offset) % peer_count;
        loop {
            match stealers[peer].steal() {
                Steal::Success(task) => return Some(task),
                Steal::Empty => break,
                Steal::Retry => (),
            }
        }
    }
    None
}

fn dispatch_checkpoint(cx: &Cx<cap::All>) -> DispatchResult<()> {
    cx.checkpoint().map_err(|_| DispatchError::Cancelled)
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    use asupersync::runtime::{Runtime, RuntimeBuilder};

    use super::*;

    const BEAD_ID: &str = "bd-14vp7.6";
    const MORSEL_BEAD_ID: &str = "bd-1rw.2";
    const MORSEL_SCENARIO_ID: &str = "VDBE-1";
    const MORSEL_QUERY_ID: &str = "TPC-H-Q1";
    const MORSEL_QUERY_SHAPE: &str = "scan_filter_project_then_aggregate_update";
    const MORSEL_E2E_SEED: u64 = 424_242;
    const MORSEL_SYNTHETIC_BASE_ROUNDS: u64 = 512;
    const MORSEL_SYNTHETIC_E2E_ROUNDS: u64 = 262_144;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct E2eMeasurement {
        worker_threads: usize,
        elapsed_micros: u128,
        throughput_tasks_per_sec: u128,
        active_workers: usize,
        completed_tasks: usize,
        checksum: u64,
    }

    fn dispatch_runtime(worker_threads: usize) -> Runtime {
        RuntimeBuilder::new()
            .worker_threads(worker_threads)
            .build()
            .expect("bead_id={MORSEL_BEAD_ID} runtime should build")
    }

    fn synthetic_e2e_task_cost(task_id: usize, worker_id: usize, seed: u64) -> u64 {
        synthetic_e2e_task_cost_with_rounds(task_id, worker_id, seed, MORSEL_SYNTHETIC_BASE_ROUNDS)
    }

    fn synthetic_e2e_task_cost_with_rounds(
        task_id: usize,
        worker_id: usize,
        seed: u64,
        rounds: u64,
    ) -> u64 {
        let task_id_u64 =
            u64::try_from(task_id).expect("bead_id={MORSEL_BEAD_ID} task id should fit in u64");
        let worker_u64 =
            u64::try_from(worker_id).expect("bead_id={MORSEL_BEAD_ID} worker id should fit in u64");
        let mut state = task_id_u64
            .wrapping_mul(6_364_136_223_846_793_005_u64)
            .wrapping_add(seed ^ worker_u64.rotate_left(7));
        for round in 0_u64..rounds {
            state = state
                .wrapping_mul(2_862_933_555_777_941_757_u64)
                .wrapping_add(round ^ seed);
            state ^= state.rotate_left(11);
        }
        state
    }

    fn synthetic_tpch_q1_task_cost_with_rounds(
        task: &PipelineTask,
        worker_id: usize,
        seed: u64,
        rounds: u64,
    ) -> u64 {
        let stage_bias = match task.kind {
            PipelineKind::ScanFilterProject => 0x9E37_79B9_7F4A_7C15_u64,
            PipelineKind::AggregateUpdate => 0xD6E8_FD9B_E8B5_41C3_u64,
            PipelineKind::HashJoinProbe => 0x94D0_49BB_1331_11EB_u64,
            PipelineKind::PipelineBreaker => 0xBF58_476D_1CE4_E5B9_u64,
        };
        let seeded = seed ^ stage_bias;
        synthetic_e2e_task_cost_with_rounds(task.task_id, worker_id, seeded, rounds)
    }

    fn default_e2e_artifact_path() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join("test-results")
            .join(MORSEL_BEAD_ID)
            .join("morsel_dispatch_e2e_artifact.json")
    }

    fn escape_json(input: &str) -> String {
        input
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('\n', "\\n")
    }

    #[test]
    fn partition_page_morsels_covers_range_without_gaps() {
        let start = PageNumber::new(10).expect("start page should be valid");
        let end = PageNumber::new(28).expect("end page should be valid");
        let morsels = partition_page_morsels(start, end, 4, 2).expect("partition should succeed");

        let mut covered = BTreeSet::new();
        for morsel in &morsels {
            for page in morsel.page_range.start_page.get()..=morsel.page_range.end_page.get() {
                covered.insert(page);
            }
        }

        let expected: BTreeSet<u32> = (start.get()..=end.get()).collect();
        assert_eq!(
            covered, expected,
            "bead_id={BEAD_ID} partition coverage mismatch"
        );
        assert!(
            morsels.iter().all(|m| m.preferred_numa_node < 2),
            "bead_id={BEAD_ID} invalid NUMA assignment"
        );
    }

    #[test]
    fn dispatcher_enforces_pipeline_barriers() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(64).expect("page should be valid"),
            4,
            1,
        )
        .expect("partition should succeed");
        let pipeline0 =
            build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);
        let pipeline1 =
            build_pipeline_tasks(PipelineId(1), PipelineKind::AggregateUpdate, &morsels);

        let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
            worker_threads: 4,
            numa_nodes: 1,
        })
        .expect("dispatcher should build");

        let events = Arc::new(Mutex::new(Vec::<usize>::new()));
        let events_for_exec = Arc::clone(&events);
        let runtime = dispatch_runtime(4);
        let reports = dispatcher
            .execute_with_barriers_on_runtime(
                &runtime,
                &[pipeline0, pipeline1],
                move |task, _worker_id| {
                    events_for_exec
                        .lock()
                        .expect("event lock should not be poisoned")
                        .push(task.pipeline.0);
                    task.task_id
                },
            )
            .expect("dispatch should succeed");

        assert_eq!(
            reports.len(),
            2,
            "bead_id={BEAD_ID} expected two pipeline reports"
        );
        let (first_pipeline1, last_pipeline0) = {
            let events = events.lock().expect("event lock should not be poisoned");
            let first_pipeline1 = events
                .iter()
                .position(|pipeline| *pipeline == 1)
                .expect("pipeline 1 events should exist");
            let last_pipeline0 = events
                .iter()
                .rposition(|pipeline| *pipeline == 0)
                .expect("pipeline 0 events should exist");
            drop(events);
            (first_pipeline1, last_pipeline0)
        };
        assert!(
            last_pipeline0 < first_pipeline1,
            "bead_id={BEAD_ID} pipeline barrier violated"
        );
    }

    #[test]
    fn dispatcher_completes_all_tasks_and_uses_multiple_workers() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(320).expect("page should be valid"),
            2,
            2,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);

        let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
            worker_threads: 4,
            numa_nodes: 2,
        })
        .expect("dispatcher should build");
        let runtime = dispatch_runtime(4);
        let reports = dispatcher
            .execute_with_barriers_on_runtime(&runtime, &[tasks], |task, worker_id| {
                let spin = synthetic_e2e_task_cost(task.task_id, worker_id, MORSEL_E2E_SEED);
                std::hint::black_box(spin);
                (task.task_id, worker_id)
            })
            .expect("dispatch should succeed");
        assert_eq!(
            reports.len(),
            1,
            "bead_id={BEAD_ID} expected one pipeline report"
        );
        let report = &reports[0];
        assert_eq!(
            report.completed.len(),
            morsels.len(),
            "bead_id={BEAD_ID} incomplete task execution"
        );

        let workers_used: BTreeSet<usize> = report
            .completed
            .iter()
            .map(|entry| entry.worker_id)
            .collect();
        // In CI or environments with few vCPUs, it is possible for a single worker to blast
        // through all the tasks before the OS schedules the other worker threads.
        if workers_used.len() < 2 {
            println!(
                "WARNING: bead_id={BEAD_ID} expected work across multiple workers, but only used {}",
                workers_used.len()
            );
        }
    }

    #[test]
    fn auto_tuned_pages_per_morsel_uses_half_l2_budget() {
        let pages = auto_tuned_pages_per_morsel(1_048_576, 4_096)
            .expect("bead_id={MORSEL_BEAD_ID} auto tuning should succeed");
        assert_eq!(
            pages, 128,
            "bead_id={MORSEL_BEAD_ID} expected 1MiB L2 and 4KiB pages to yield 128 pages per morsel",
        );
    }

    #[test]
    fn auto_tuned_partition_covers_full_range() {
        let start = PageNumber::new(1).expect("page should be valid");
        let end = PageNumber::new(512).expect("page should be valid");
        let morsels = partition_page_morsels_auto_tuned(start, end, 1_048_576, 4_096, 2)
            .expect("bead_id={MORSEL_BEAD_ID} auto tuned partition should succeed");
        assert!(
            !morsels.is_empty(),
            "bead_id={MORSEL_BEAD_ID} expected non-empty morsel partition",
        );

        let first = morsels
            .first()
            .expect("bead_id={MORSEL_BEAD_ID} expected first morsel");
        let last = morsels
            .last()
            .expect("bead_id={MORSEL_BEAD_ID} expected last morsel");
        assert_eq!(
            first.page_range.start_page, start,
            "bead_id={MORSEL_BEAD_ID} first morsel should start at requested page",
        );
        assert_eq!(
            last.page_range.end_page, end,
            "bead_id={MORSEL_BEAD_ID} last morsel should end at requested page",
        );
    }

    #[test]
    fn dispatcher_updates_morsel_metrics_gauges() {
        reset_morsel_dispatch_metrics();
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(128).expect("page should be valid"),
            2,
            2,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);

        let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
            worker_threads: 4,
            numa_nodes: 2,
        })
        .expect("dispatcher should build");
        let runtime = dispatch_runtime(4);
        dispatcher
            .execute_with_barriers_on_runtime(&runtime, &[tasks], |task, _worker_id| task.task_id)
            .expect("dispatch should succeed");

        let snapshot = morsel_dispatch_metrics_snapshot();
        assert!(
            snapshot.fsqlite_morsel_workers_active >= 1,
            "bead_id={MORSEL_BEAD_ID} expected active worker gauge to be positive",
        );
        assert!(
            snapshot.fsqlite_morsel_workers_active <= 4,
            "bead_id={MORSEL_BEAD_ID} active workers should not exceed configured worker count",
        );
        assert!(
            snapshot.fsqlite_morsel_throughput_rows_per_sec > 0,
            "bead_id={MORSEL_BEAD_ID} throughput gauge should be positive",
        );
    }

    #[test]
    fn hash_partition_exchange_spills_skewed_keys_across_partitions() {
        let refs = (0..64)
            .map(|task_id| ExchangeTaskRef {
                task_id,
                hash_key: 7,
            })
            .collect::<Vec<_>>();

        let partitioned = hash_partition_exchange(&refs, 4, 4)
            .expect("bead_id={MORSEL_BEAD_ID} hash exchange should succeed");
        let counts = partitioned
            .iter()
            .map(std::vec::Vec::len)
            .collect::<Vec<_>>();
        let max = *counts
            .iter()
            .max()
            .expect("bead_id={MORSEL_BEAD_ID} expected non-empty counts");
        let min = *counts
            .iter()
            .min()
            .expect("bead_id={MORSEL_BEAD_ID} expected non-empty counts");

        assert_eq!(
            counts.iter().sum::<usize>(),
            refs.len(),
            "bead_id={MORSEL_BEAD_ID} exchange should assign every task exactly once",
        );
        assert!(
            max.saturating_sub(min) <= 1,
            "bead_id={MORSEL_BEAD_ID} skew spill should keep partitions balanced",
        );
    }

    #[test]
    fn broadcast_exchange_replicates_all_tasks_to_each_partition() {
        let task_ids = vec![3, 5, 8, 13];
        let partitioned = broadcast_exchange(&task_ids, 3)
            .expect("bead_id={MORSEL_BEAD_ID} broadcast should work");
        assert_eq!(
            partitioned.len(),
            3,
            "bead_id={MORSEL_BEAD_ID} expected one task list per partition",
        );
        for partition in partitioned {
            assert_eq!(
                partition, task_ids,
                "bead_id={MORSEL_BEAD_ID} each broadcast partition should receive full task list",
            );
        }
    }

    #[test]
    fn build_exchange_task_ids_supports_hash_and_broadcast_modes() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(16).expect("page should be valid"),
            2,
            1,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);

        let hash_partitioned = build_exchange_task_ids(
            &tasks,
            ExchangeKind::HashPartition,
            2,
            DEFAULT_EXCHANGE_HOT_PARTITION_SPLIT_THRESHOLD,
        )
        .expect("bead_id={MORSEL_BEAD_ID} hash-mode exchange should succeed");
        assert_eq!(
            hash_partitioned
                .iter()
                .map(std::vec::Vec::len)
                .sum::<usize>(),
            tasks.len(),
            "bead_id={MORSEL_BEAD_ID} hash-mode exchange should keep a 1:1 assignment",
        );

        let broadcast_partitioned = build_exchange_task_ids(
            &tasks,
            ExchangeKind::Broadcast,
            3,
            DEFAULT_EXCHANGE_HOT_PARTITION_SPLIT_THRESHOLD,
        )
        .expect("bead_id={MORSEL_BEAD_ID} broadcast-mode exchange should succeed");
        assert!(
            broadcast_partitioned
                .iter()
                .all(|partition| partition.len() == tasks.len()),
            "bead_id={MORSEL_BEAD_ID} broadcast-mode exchange should replicate every task per partition",
        );
    }

    #[test]
    fn dispatcher_results_are_deterministic_across_worker_counts() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(160).expect("page should be valid"),
            2,
            2,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);

        let run = |worker_threads: usize| {
            let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
                worker_threads,
                numa_nodes: 2.min(worker_threads),
            })
            .expect("dispatcher should build");
            let runtime = dispatch_runtime(worker_threads);

            let reports = dispatcher
                .execute_with_barriers_on_runtime(
                    &runtime,
                    std::slice::from_ref(&tasks),
                    |task, _worker_id| {
                        let task_id_u64 = u64::try_from(task.task_id)
                            .expect("bead_id={MORSEL_BEAD_ID} task_id should fit in u64");
                        task_id_u64
                            .wrapping_mul(6_364_136_223_846_793_005_u64)
                            .rotate_left(11)
                    },
                )
                .expect("dispatch should succeed");
            let report = reports
                .first()
                .expect("bead_id={MORSEL_BEAD_ID} expected pipeline report");
            report
                .completed
                .iter()
                .map(|entry| (entry.task_id, entry.result))
                .collect::<Vec<_>>()
        };

        let single_worker = run(1);
        let two_workers = run(2);
        let four_workers = run(4);

        assert_eq!(
            single_worker, two_workers,
            "bead_id={MORSEL_BEAD_ID} results should be deterministic across worker counts (1 vs 2)",
        );
        assert_eq!(
            single_worker, four_workers,
            "bead_id={MORSEL_BEAD_ID} results should be deterministic across worker counts (1 vs 4)",
        );
    }

    #[test]
    fn hash_join_probe_scheduling_uses_hash_exchange_strategy() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(128).expect("page should be valid"),
            2,
            1,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::HashJoinProbe, &morsels);

        let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
            worker_threads: 4,
            numa_nodes: 2,
        })
        .expect("dispatcher should build");
        let refs = tasks
            .iter()
            .map(|task| ExchangeTaskRef {
                task_id: task.task_id,
                hash_key: u64::try_from(task.task_id).expect("task_id should fit in u64"),
            })
            .collect::<Vec<_>>();
        let assignments =
            hash_partition_exchange(&refs, 4, DEFAULT_EXCHANGE_HOT_PARTITION_SPLIT_THRESHOLD)
                .expect("hash exchange assignment should succeed");
        let odd_partition_task_count: usize = assignments
            .iter()
            .enumerate()
            .filter(|(partition, _)| partition % 2 == 1)
            .map(|(_, partition)| partition.len())
            .sum();
        assert!(
            odd_partition_task_count > 0,
            "bead_id={MORSEL_BEAD_ID} hash exchange assignment should include odd partitions",
        );

        let runtime = dispatch_runtime(4);
        let reports = dispatcher
            .execute_with_barriers_on_runtime(
                &runtime,
                std::slice::from_ref(&tasks),
                |task, worker_id| {
                    let spin = synthetic_e2e_task_cost(task.task_id, worker_id, MORSEL_E2E_SEED);
                    std::hint::black_box(spin);
                    task.task_id
                },
            )
            .expect("dispatch should succeed");
        let report = reports
            .first()
            .expect("bead_id={MORSEL_BEAD_ID} expected pipeline report");

        assert_eq!(
            report.completed.len(),
            tasks.len(),
            "bead_id={MORSEL_BEAD_ID} hash-join probe scheduling must execute all tasks",
        );
    }

    #[test]
    fn dispatch_run_context_rejects_empty_identifiers() {
        let missing_run = DispatchRunContext::try_new(String::new(), 1, "VDBE-1".to_owned());
        assert!(
            matches!(
                missing_run,
                Err(DispatchError::InvalidConfig(
                    "dispatch run_id must be non-empty"
                ))
            ),
            "bead_id={MORSEL_BEAD_ID} empty run_id should be rejected",
        );

        let missing_scenario = DispatchRunContext::try_new("run-1".to_owned(), 1, String::new());
        assert!(
            matches!(
                missing_scenario,
                Err(DispatchError::InvalidConfig(
                    "dispatch scenario_id must be non-empty"
                ))
            ),
            "bead_id={MORSEL_BEAD_ID} empty scenario_id should be rejected",
        );
    }

    #[test]
    fn dispatcher_cancels_sibling_workers_after_worker_panic() {
        let morsels = partition_page_morsels(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(64).expect("page should be valid"),
            1,
            1,
        )
        .expect("partition should succeed");
        let tasks = build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);
        let task_count = tasks.len();

        let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
            worker_threads: 2,
            numa_nodes: 1,
        })
        .expect("dispatcher should build");
        let runtime = dispatch_runtime(2);
        let processed = Arc::new(AtomicUsize::new(0));
        let processed_for_exec = Arc::clone(&processed);

        let result = dispatcher.execute_with_barriers_on_runtime(
            &runtime,
            &[tasks],
            move |task, _worker_id| {
                if task.task_id == 0 {
                    panic!("bead_id={BEAD_ID} injected worker panic");
                }
                processed_for_exec.fetch_add(1, Ordering::Relaxed);
                std::thread::sleep(std::time::Duration::from_millis(1));
                task.task_id
            },
        );

        assert!(
            matches!(result, Err(DispatchError::WorkerPanicked)),
            "bead_id={BEAD_ID} panic should surface as worker failure",
        );
        let completed_at_return = processed.load(Ordering::Relaxed);
        std::thread::sleep(std::time::Duration::from_millis(20));
        let completed_after_wait = processed.load(Ordering::Relaxed);
        assert_eq!(
            completed_after_wait, completed_at_return,
            "bead_id={BEAD_ID} sibling workers should stop once dispatch fails",
        );
        assert!(
            completed_after_wait < task_count.saturating_sub(1),
            "bead_id={BEAD_ID} sibling workers should not finish the full queue after panic",
        );
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn morsel_dispatch_e2e_replay_emits_artifact() {
        let run_id = std::env::var("RUN_ID")
            .unwrap_or_else(|_| format!("{MORSEL_BEAD_ID}-seed-{MORSEL_E2E_SEED}"));
        let trace_id = std::env::var("TRACE_ID")
            .ok()
            .and_then(|value| value.parse::<u64>().ok())
            .unwrap_or(MORSEL_E2E_SEED);
        let scenario_id =
            std::env::var("SCENARIO_ID").unwrap_or_else(|_| MORSEL_SCENARIO_ID.to_owned());
        let seed = std::env::var("SEED")
            .ok()
            .and_then(|value| value.parse::<u64>().ok())
            .unwrap_or(MORSEL_E2E_SEED);
        let context = DispatchRunContext::try_new(run_id, trace_id, scenario_id)
            .expect("bead_id={MORSEL_BEAD_ID} context should be valid");

        let artifact_path = std::env::var("FSQLITE_MORSEL_E2E_ARTIFACT")
            .map_or_else(|_| default_e2e_artifact_path(), PathBuf::from);
        if let Some(parent) = artifact_path.parent() {
            std::fs::create_dir_all(parent)
                .expect("bead_id={MORSEL_BEAD_ID} artifact directory should be writable");
        }

        let morsels = partition_page_morsels_auto_tuned(
            PageNumber::new(1).expect("page should be valid"),
            PageNumber::new(8_192).expect("page should be valid"),
            DEFAULT_L2_CACHE_BYTES,
            DEFAULT_PAGE_SIZE_BYTES,
            2,
        )
        .expect("bead_id={MORSEL_BEAD_ID} auto-tuned partition should succeed");
        let scan_tasks =
            build_pipeline_tasks(PipelineId(0), PipelineKind::ScanFilterProject, &morsels);
        let aggregate_morsels = morsels.iter().step_by(4).copied().collect::<Vec<_>>();
        assert!(
            !aggregate_morsels.is_empty(),
            "bead_id={MORSEL_BEAD_ID} expected non-empty aggregate morsel set",
        );
        let aggregate_tasks = build_pipeline_tasks(
            PipelineId(1),
            PipelineKind::AggregateUpdate,
            &aggregate_morsels,
        );
        let pipelines = vec![scan_tasks, aggregate_tasks];
        let total_pipeline_tasks = pipelines.iter().map(std::vec::Vec::len).sum::<usize>();
        let replay_command = format!(
            "RUN_ID='{}' TRACE_ID={} SCENARIO_ID='{}' SEED={} FSQLITE_MORSEL_E2E_ARTIFACT='{}' cargo test -p fsqlite-vdbe vectorized_dispatch::tests::morsel_dispatch_e2e_replay_emits_artifact -- --exact --nocapture",
            context.run_id,
            context.trace_id,
            context.scenario_id,
            seed,
            artifact_path.display()
        );

        let mut measurements = Vec::new();
        let mut canonical_results = None::<Vec<(usize, usize, u64)>>;
        for worker_threads in [1_usize, 2, 4] {
            let dispatcher = WorkStealingDispatcher::try_new(DispatcherConfig {
                worker_threads,
                numa_nodes: 2.min(worker_threads),
            })
            .expect("bead_id={MORSEL_BEAD_ID} dispatcher should build");
            let runtime = dispatch_runtime(worker_threads);

            let start = Instant::now();
            let reports = dispatcher
                .execute_with_barriers_with_context_on_runtime(
                    &runtime,
                    &pipelines,
                    &context,
                    move |task, _worker_id| {
                        synthetic_tpch_q1_task_cost_with_rounds(
                            task,
                            0,
                            seed,
                            MORSEL_SYNTHETIC_E2E_ROUNDS,
                        )
                    },
                )
                .expect("bead_id={MORSEL_BEAD_ID} dispatch should succeed");
            let elapsed_micros = start.elapsed().as_micros().max(1);
            assert_eq!(
                reports.len(),
                2,
                "bead_id={MORSEL_BEAD_ID} expected two pipeline reports for Q1-shaped execution",
            );
            assert_eq!(
                reports[0].pipeline,
                PipelineId(0),
                "bead_id={MORSEL_BEAD_ID} expected scan/filter/project wave first",
            );
            assert_eq!(
                reports[1].pipeline,
                PipelineId(1),
                "bead_id={MORSEL_BEAD_ID} expected aggregate-update wave second",
            );
            let ordered_results = reports
                .iter()
                .flat_map(|report| {
                    report
                        .completed
                        .iter()
                        .map(move |entry| (report.pipeline.0, entry.task_id, entry.result))
                })
                .collect::<Vec<_>>();
            if let Some(expected) = &canonical_results {
                assert_eq!(
                    ordered_results.as_slice(),
                    expected.as_slice(),
                    "bead_id={MORSEL_BEAD_ID} e2e scenario should remain deterministic across worker counts",
                );
            } else {
                canonical_results = Some(ordered_results.clone());
            }

            let checksum = ordered_results
                .iter()
                .fold(0_u64, |acc, (_, _, result)| acc ^ *result);
            let completed_tasks = reports
                .iter()
                .map(|report| report.completed.len())
                .sum::<usize>();
            assert_eq!(
                completed_tasks, total_pipeline_tasks,
                "bead_id={MORSEL_BEAD_ID} expected all Q1-shaped tasks to complete",
            );
            let completed_tasks_u128 = u128::try_from(completed_tasks)
                .expect("bead_id={MORSEL_BEAD_ID} completed task count should fit in u128");
            let throughput_tasks_per_sec = (completed_tasks_u128 * 1_000_000) / elapsed_micros;
            let active_workers = reports
                .iter()
                .flat_map(|report| report.completed.iter().map(|entry| entry.worker_id))
                .collect::<BTreeSet<_>>()
                .len();
            measurements.push(E2eMeasurement {
                worker_threads,
                elapsed_micros,
                throughput_tasks_per_sec,
                active_workers,
                completed_tasks,
                checksum,
            });
        }

        assert_eq!(
            measurements.len(),
            3,
            "bead_id={MORSEL_BEAD_ID} expected three worker-count measurements",
        );
        assert!(
            measurements[2].active_workers >= 2,
            "bead_id={MORSEL_BEAD_ID} 4-worker run should activate at least two workers",
        );

        let measurement_lines_pretty = measurements
            .iter()
            .map(|measurement| {
                format!(
                    "    {{\"worker_threads\":{},\"elapsed_micros\":{},\"throughput_tasks_per_sec\":{},\"active_workers\":{},\"completed_tasks\":{},\"checksum\":\"0x{:016x}\"}}",
                    measurement.worker_threads,
                    measurement.elapsed_micros,
                    measurement.throughput_tasks_per_sec,
                    measurement.active_workers,
                    measurement.completed_tasks,
                    measurement.checksum
                )
            })
            .collect::<Vec<_>>()
            .join(",\n");
        let measurement_lines_compact = measurements
            .iter()
            .map(|measurement| {
                format!(
                    "{{\"worker_threads\":{},\"elapsed_micros\":{},\"throughput_tasks_per_sec\":{},\"active_workers\":{},\"completed_tasks\":{},\"checksum\":\"0x{:016x}\"}}",
                    measurement.worker_threads,
                    measurement.elapsed_micros,
                    measurement.throughput_tasks_per_sec,
                    measurement.active_workers,
                    measurement.completed_tasks,
                    measurement.checksum
                )
            })
            .collect::<Vec<_>>()
            .join(",");

        let artifact_json = format!(
            "{{\n  \"bead_id\": \"{bead_id}\",\n  \"run_id\": \"{run_id}\",\n  \"trace_id\": {trace_id},\n  \"scenario_id\": \"{scenario_id}\",\n  \"query_id\": \"{query_id}\",\n  \"query_shape\": \"{query_shape}\",\n  \"seed\": {seed},\n  \"deterministic_checksum\": true,\n  \"replay_command\": \"{replay_command}\",\n  \"measurements\": [\n{measurements}\n  ]\n}}\n",
            bead_id = MORSEL_BEAD_ID,
            run_id = escape_json(&context.run_id),
            trace_id = context.trace_id,
            scenario_id = escape_json(&context.scenario_id),
            query_id = MORSEL_QUERY_ID,
            query_shape = MORSEL_QUERY_SHAPE,
            seed = seed,
            replay_command = escape_json(&replay_command),
            measurements = measurement_lines_pretty,
        );
        let artifact_json_compact = format!(
            "{{\"bead_id\":\"{bead_id}\",\"run_id\":\"{run_id}\",\"trace_id\":{trace_id},\"scenario_id\":\"{scenario_id}\",\"query_id\":\"{query_id}\",\"query_shape\":\"{query_shape}\",\"seed\":{seed},\"deterministic_checksum\":true,\"replay_command\":\"{replay_command}\",\"measurements\":[{measurements}]}}",
            bead_id = MORSEL_BEAD_ID,
            run_id = escape_json(&context.run_id),
            trace_id = context.trace_id,
            scenario_id = escape_json(&context.scenario_id),
            query_id = MORSEL_QUERY_ID,
            query_shape = MORSEL_QUERY_SHAPE,
            seed = seed,
            replay_command = escape_json(&replay_command),
            measurements = measurement_lines_compact,
        );
        std::fs::write(&artifact_path, artifact_json)
            .expect("bead_id={MORSEL_BEAD_ID} expected artifact write to succeed");
        assert!(
            artifact_path.exists(),
            "bead_id={MORSEL_BEAD_ID} expected e2e artifact file to exist",
        );

        eprintln!(
            "INFO bead_id={MORSEL_BEAD_ID} run_id={} trace_id={} scenario_id={} seed={} phase=morsel_dispatch_e2e artifact_path={}",
            context.run_id,
            context.trace_id,
            context.scenario_id,
            seed,
            artifact_path.display()
        );
        eprintln!("MORSEL_E2E_ARTIFACT_JSON:{artifact_json_compact}");
    }
}