organizational-intelligence-plugin 0.3.4

Organizational Intelligence Plugin - Defect pattern analysis for GitHub organizations
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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
# GPU-Accelerated Correlation & Pattern Prediction System
## Technical Specification

**Version:** 1.0.0
**Status:** Draft
**Last Updated:** 2025-11-24
**Project:** Organizational Intelligence Plugin - GPU Extension

---

## Table of Contents

### [1. Executive Summary]#1-executive-summary
- [1.1 Purpose]#11-purpose
- [1.2 Design Philosophy]#12-design-philosophy
- [1.3 Core Capabilities]#13-core-capabilities
- [1.4 Technology Stack]#14-technology-stack

### [2. Introduction & Research Foundation]#2-introduction--research-foundation
- [2.1 Problem Statement]#21-problem-statement
- [2.2 Research Motivation]#22-research-motivation
- [2.3 Peer-Reviewed Foundations]#23-peer-reviewed-foundations
- [2.4 GPU Acceleration Rationale]#24-gpu-acceleration-rationale

### [3. Architecture Overview]#3-architecture-overview
- [3.1 System Architecture]#31-system-architecture
- [3.2 Component Interaction]#32-component-interaction
- [3.3 Technology Stack Integration]#33-technology-stack-integration
- [3.4 Data Flow Pipeline]#34-data-flow-pipeline

### [4. Data Ingestion & Preprocessing]#4-data-ingestion--preprocessing
- [4.1 GitHub Repository Acquisition]#41-github-repository-acquisition
- [4.2 Git History Mining]#42-git-history-mining
- [4.3 Feature Extraction]#43-feature-extraction
- [4.4 Trueno-DB Storage Layer]#44-trueno-db-storage-layer

### [5. GPU Processing Pipeline]#5-gpu-processing-pipeline
- [5.1 Trueno Compute Kernels]#51-trueno-compute-kernels
- [5.2 Correlation Matrix Computation]#52-correlation-matrix-computation
- [5.3 Similarity Metrics]#53-similarity-metrics
- [5.4 Performance Optimization]#54-performance-optimization

### [6. Graph Analytics with Trueno-Graph]#6-graph-analytics-with-trueno-graph
- [6.1 Dependency Graph Construction]#61-dependency-graph-construction
- [6.2 GPU-Accelerated Graph Algorithms]#62-gpu-accelerated-graph-algorithms
- [6.3 Defect Propagation Analysis]#63-defect-propagation-analysis
- [6.4 Impact Radius Computation]#64-impact-radius-computation

### [7. Machine Learning with Aprender]#7-machine-learning-with-aprender
- [7.1 Feature Engineering]#71-feature-engineering
- [7.2 Supervised Learning Models]#72-supervised-learning-models
- [7.3 Clustering & Pattern Discovery]#73-clustering--pattern-discovery
- [7.4 Anomaly Detection]#74-anomaly-detection
- [7.5 Model Training Pipeline]#75-model-training-pipeline

### [8. Statistical Analysis & Correlation]#8-statistical-analysis--correlation
- [8.1 Pearson/Spearman Correlation]#81-pearsonspearman-correlation
- [8.2 Time Series Analysis]#82-time-series-analysis
- [8.3 Causal Inference]#83-causal-inference
- [8.4 Predictive Modeling]#84-predictive-modeling

### [9. CLI Interface Specification]#9-cli-interface-specification
- [9.1 Command Structure]#91-command-structure
- [9.2 GPU Analysis Commands]#92-gpu-analysis-commands
- [9.3 Query Interface]#93-query-interface
- [9.4 Output Formats]#94-output-formats

### [10. Query System & Natural Language Interface]#10-query-system--natural-language-interface
- [10.1 Query Language Design]#101-query-language-design
- [10.2 Example Queries]#102-example-queries
- [10.3 Query Optimization]#103-query-optimization
- [10.4 Result Visualization]#104-result-visualization

### [11. Performance & Scalability]#11-performance--scalability
- [11.1 Throughput Targets]#111-throughput-targets
- [11.2 Memory Management]#112-memory-management
- [11.3 Batch Processing]#113-batch-processing
- [11.4 Distributed Processing]#114-distributed-processing

### [12. Integration with Renacer]#12-integration-with-renacer
- [12.1 Runtime Profiling Integration]#121-runtime-profiling-integration
- [12.2 Anomaly Correlation]#122-anomaly-correlation
- [12.3 Performance Baseline Learning]#123-performance-baseline-learning

### [13. Testing Strategy]#13-testing-strategy
- [13.1 Unit Testing]#131-unit-testing
- [13.2 Integration Testing]#132-integration-testing
- [13.3 Performance Benchmarking]#133-performance-benchmarking
- [13.4 Quality Gates]#134-quality-gates

### [14. Deployment & Operations]#14-deployment--operations
- [14.1 Installation]#141-installation
- [14.2 Configuration]#142-configuration
- [14.3 Hardware Requirements]#143-hardware-requirements
- [14.4 Monitoring & Observability]#144-monitoring--observability

### [15. Roadmap & Validation Gates]#15-roadmap--validation-gates
- [15.1 Phase 1: Foundation]#151-phase-1-foundation
- [15.2 Phase 2: GPU Acceleration]#152-phase-2-gpu-acceleration
- [15.3 Phase 3: Advanced ML]#153-phase-3-advanced-ml
- [15.4 Phase 4: Production Hardening]#154-phase-4-production-hardening

### [16. Academic References]#16-academic-references
- [16.1 GPU Computing for ML]#161-gpu-computing-for-ml
- [16.2 Software Defect Prediction]#162-software-defect-prediction
- [16.3 Graph Neural Networks]#163-graph-neural-networks
- [16.4 Time Series & Causality]#164-time-series--causality
- [16.5 Complete Bibliography]#165-complete-bibliography

### [17. Appendices]#17-appendices
- [17.1 API Reference]#171-api-reference
- [17.2 Configuration Examples]#172-configuration-examples
- [17.3 Performance Tuning Guide]#173-performance-tuning-guide
- [17.4 Glossary]#174-glossary

---

## 1. Executive Summary

### 1.1 Purpose

The GPU-Accelerated Correlation & Pattern Prediction System extends the Organizational Intelligence Plugin (OIP) with massively parallel processing capabilities to identify defect patterns, predict bug occurrences, and analyze software quality at unprecedented scale and speed. By leveraging GPU acceleration through the trueno ecosystem, this system can analyze entire GitHub organizations (1000+ repositories) in minutes rather than hours, enabling real-time quality insights and predictive defect prevention.

**Key Innovation**: Treating repository analysis as a tensor computation problem, transforming git history into high-dimensional feature spaces suitable for GPU-accelerated correlation analysis, graph analytics, and machine learning inference.

### 1.2 Design Philosophy

This specification follows **Toyota Way principles** with GPU-specific adaptations:

- **Genchi Genbutsu (Go and See)**: Profile CPU bottlenecks before adding GPU complexity. Every GPU optimization includes CPU baseline benchmarks.
- **Kaizen (Continuous Improvement)**: Start with SIMD (via trueno), add GPU only when profiling justifies it.
- **Jidoka (Quality Built-In)**: Equivalence testing ensures GPU results match CPU/SIMD within floating-point tolerance.
- **Muda Elimination**: Minimize PCIe transfers through intelligent batching and kernel fusion.

**Data-First Approach**: Leverage existing OIP defect classifications and labels to train predictive models rather than starting from scratch.

### 1.3 Core Capabilities

1. **GPU-Accelerated Correlation Analysis**
   - Compute correlation matrices for all defect patterns across repositories (O(n²) operations parallelized)
   - Identify co-occurrence patterns: "Concurrency bugs often followed by Memory Safety issues"
   - Time-lagged correlations for causal inference

2. **Graph-Based Impact Analysis**
   - Build dependency graphs from import/call relationships
   - GPU-accelerated PageRank for identifying critical components
   - Defect propagation likelihood along dependency edges
   - Impact radius computation: "If X has a bug, probability Y is affected"

3. **Predictive Defect Modeling**
   - Train classifiers on historical data: "Given these features, predict defect category"
   - Temporal forecasting: "This repository will likely have N defects in next sprint"
   - Anomaly detection: "This commit deviates from organizational patterns"

4. **Natural Language Query Interface**
   - `oip-gpu query "show me most common defect in rust-lang/rust"`
   - `oip-gpu predict "probability of concurrency bug in PR #1234"`
   - `oip-gpu correlate "security vulnerabilities" with "test coverage < 70%"`

### 1.4 Technology Stack

| Component | Technology | Purpose |
|-----------|-----------|---------|
| **Compute Engine** | `trueno` v0.4.1+ | SIMD/GPU vector/matrix operations, auto-backend selection |
| **Storage Layer** | `trueno-db` | GPU-first embedded analytics with Arrow/Parquet |
| **Graph Analytics** | `trueno-graph` | GPU-accelerated graph algorithms (PageRank, BFS, betweenness) |
| **Machine Learning** | `aprender` | Pure Rust ML (Random Forest, Gradient Boosting, K-Means, PCA) |
| **Runtime Profiling** | `renacer` | Anomaly detection integration for live systems |
| **CLI Framework** | `clap` v4 | Command-line interface |
| **Data Ingestion** | `octocrab`, `git2` | GitHub API and git operations |

**Hardware Targets**: NVIDIA GPUs (CUDA via Vulkan), AMD GPUs (ROCm via Vulkan), Apple Silicon (Metal), CPU fallback (AVX-512/AVX2/NEON)

---

## 2. Introduction & Research Foundation

### 2.1 Problem Statement

**Challenge**: Traditional software defect analysis tools process repositories sequentially, limiting scalability. Analyzing 1000+ repository organizations with millions of commits requires hours of CPU-bound computation, making real-time quality insights infeasible.

**Opportunity**: Modern defect analysis involves embarrassingly parallel operations:
- Computing pairwise correlations between defect categories (N×M matrix operations)
- Aggregating statistics across millions of commits (reductions)
- Graph traversals over dependency networks (BFS/PageRank)
- Training ML models on high-dimensional feature spaces

These operations map naturally to GPU architectures with thousands of parallel cores.

**Gap in Existing Solutions**:
- Academic tools (CPatMiner, CodeBERT): Research prototypes, not production-ready
- Commercial tools (SonarQube, CodeClimate): CPU-bound, no GPU acceleration
- ML Platforms (H2O, XGBoost-GPU): General-purpose, not code-aware

**Our Contribution**: Purpose-built GPU acceleration for **software quality analytics**, leveraging domain-specific optimizations (AST-aware features, git history structure, defect taxonomies).

### 2.2 Research Motivation

**Empirical Evidence from Literature**:

1. **Defect Prediction is Computationally Expensive** [[1]]#ref-1
   - Feature extraction from AST diffs: O(n×m) where n=commits, m=features
   - Correlation analysis across repositories: O(r²×d) where r=repos, d=defects
   - Graph algorithms on call graphs: O(V²) for all-pairs shortest paths

2. **GPU Acceleration Effective for Similar Domains** [[2]]#ref-2
   - Bioinformatics: 100-250× speedup for sequence alignment (GPU vs CPU)
   - Financial analytics: 50-100× speedup for Monte Carlo simulations
   - Scientific computing: 10-50× speedup for matrix operations (cuBLAS)

3. **Software Defect Patterns Exhibit Spatial-Temporal Structure** [[3]]#ref-3
   - Defects cluster in files ("defect-prone modules")
   - Temporal autocorrelation: Past defects predict future defects
   - Suitable for tensor-based representations and GPU processing

### 2.3 Peer-Reviewed Foundations

This specification synthesizes research from three domains: **GPU computing**, **defect prediction**, and **graph neural networks**.

#### GPU Computing for Machine Learning

<a name="ref-1"></a>
**[1] Steinkraus et al., "Using GPUs for Machine Learning Algorithms"**, *ICDAR 2005*
- **Key Finding**: Convolutional neural networks achieve 4× speedup on GPU vs optimized CPU
- **Application**: Feature extraction from code ASTs can be parallelized similarly to image convolutions
- **Citation**: https://ieeexplore.ieee.org/document/1227828

<a name="ref-2"></a>
**[2] Cano, "A Survey on Graphic Processing Unit Computing for Large-Scale Data Mining"**, *WIREs Data Mining & Knowledge Discovery, 2018*
- **Key Finding**: GPU-accelerated data mining achieves 10-100× speedup for distance computations, clustering
- **Application**: Repository similarity metrics, K-means clustering of defect patterns
- **Citation**: https://doi.org/10.1002/widm.1232

#### Software Defect Prediction

<a name="ref-3"></a>
**[3] D'Ambros et al., "Evaluating Defect Prediction Approaches: A Benchmark and An Extensive Comparison"**, *Empirical Software Engineering, 2012*
- **Key Finding**: Historical defect data is the strongest predictor of future defects (AUC 0.7-0.8)
- **Application**: Justifies data-driven ML approach over rule-based heuristics
- **Citation**: https://doi.org/10.1007/s10664-011-9173-9

<a name="ref-4"></a>
**[4] Qin et al., "DeMuVGN: Effective Software Defect Prediction via Multi-view Graph Neural Networks"**, *arXiv:2410.19550, 2024*
- **Key Finding**: Multi-view GNNs achieve 92.3% F1-score on defect prediction (SOTA)
- **Application**: Graph-based representation for dependency + AST + commit history
- **Citation**: https://arxiv.org/abs/2410.19550

#### Graph Analytics for Code

<a name="ref-5"></a>
**[5] Nguyen et al., "Graph-based Mining of In-the-Wild, Fine-grained, Semantic Code Change Patterns"**, *ICSE 2019*
- **Key Finding**: Code changes form graph structures; graph mining identifies 85% of common patterns
- **Application**: trueno-graph for change pattern detection via PageRank, betweenness centrality
- **Citation**: https://doi.org/10.1109/ICSE.2019.00089

<a name="ref-6"></a>
**[6] Wang et al., "Code Revert Prediction with Graph Neural Networks: J.P. Morgan Case Study"**, *arXiv:2403.09507, 2024*
- **Key Finding**: GNN on call graphs achieves 78% precision for revert prediction (production system)
- **Application**: Real-world validation that graph + ML works at scale
- **Citation**: https://arxiv.org/abs/2403.09507

#### Time Series & Causality

<a name="ref-7"></a>
**[7] Khomh et al., "Do Faster Releases Improve Software Quality? An Empirical Case Study"**, *MSR 2012*
- **Key Finding**: Temporal patterns in defects; release velocity correlates with post-release defects
- **Application**: Time-lagged correlation analysis for causal inference
- **Citation**: https://doi.org/10.1109/MSR.2012.6224279

<a name="ref-8"></a>
**[8] Granger, "Investigating Causal Relations by Econometric Models and Cross-Spectral Methods"**, *Econometrica, 1969* (Nobel Prize)
- **Key Finding**: Granger causality tests whether X(t-k) predicts Y(t)
- **Application**: Does "code churn" at t-1 Granger-cause "defects" at t?
- **Citation**: https://doi.org/10.2307/1912791

#### AST-Based Analysis

<a name="ref-9"></a>
**[9] Sun et al., "Abstract Syntax Tree for Programming Language Understanding: How Far Are We?"**, *arXiv:2312.00413, 2023*
- **Key Finding**: AST representations outperform token-based for code classification (87% vs 79% F1)
- **Application**: Feature extraction from AST diffs using tree-sitter
- **Citation**: https://arxiv.org/abs/2312.00413

#### Rust-Specific Safety

<a name="ref-10"></a>
**[10] Xu et al., "Understanding and Detecting Real-World Safety Issues in Rust"**, *IEEE TSE, 2024*
- **Key Finding**: 70% of Rust CVEs involve unsafe code; 30% are concurrency bugs
- **Application**: Defect taxonomy design for Rust-specific patterns
- **Citation**: https://doi.org/10.1109/TSE.2024.3380393

### 2.4 GPU Acceleration Rationale

**When to Use GPU** (data-driven decision framework):

| Operation | CPU Time (1M commits) | GPU Speedup | Justification |
|-----------|----------------------|-------------|---------------|
| **Correlation matrix (100×100 categories)** | 15 seconds | 20-50× | O(n×m²) embarrassingly parallel |
| **K-means clustering (10 clusters, 1000 iter)** | 8 seconds | 10-30× | Distance computations vectorize well |
| **PageRank (10K node graph, 100 iter)** | 3 seconds | 5-15× | Sparse matrix-vector multiply |
| **Random Forest training (100 trees)** | 25 seconds | 3-8× | Tree construction parallelizes poorly |
| **Feature extraction (AST parsing)** | 40 seconds | 1-2× | I/O bound, irregular memory access |

**Decision Rule** (from trueno-db's 5× rule):
- **Use GPU if**: Expected speedup ≥ 5× AND dataset > 100K elements AND operation is compute-bound
- **Use SIMD if**: Dataset 10K-100K elements OR mixed compute/memory bound
- **Use Scalar if**: Dataset < 10K elements OR I/O bound

**Cost Model** (PCIe transfer overhead):
```rust
total_time = transfer_to_gpu + gpu_compute + transfer_from_gpu
gpu_speedup_factor = cpu_compute_time / gpu_compute_time

// Only use GPU if:
gpu_speedup_factor > (transfer_to_gpu + transfer_from_gpu) / gpu_compute_time + 5.0
```

**Example Calculation** (correlation matrix):
- CPU compute: 15s
- GPU compute: 0.5s (30× faster)
- PCIe transfer: 100ms each way (200ms total)
- Effective speedup: 15 / (0.5 + 0.2) = **21.4×** ✅ Use GPU

---


## 3. Architecture Overview

### 3.1 System Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                          CLI Interface Layer                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐              │
│  │ oip-gpu      │  │ oip-gpu      │  │ oip-gpu      │              │
│  │ analyze      │  │ correlate    │  │ predict      │              │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘              │
└─────────┼──────────────────┼──────────────────┼─────────────────────┘
          │                  │                  │
┌─────────┴──────────────────┴──────────────────┴─────────────────────┐
│                    Query Orchestration Layer                         │
│  ┌─────────────────────────────────────────────────────────────┐    │
│  │  Natural Language Query Parser & Planner                    │    │
│  │  - Parse user queries into execution plans                  │    │
│  │  - Determine GPU/CPU backend selection                      │    │
│  │  - Optimize query execution order                           │    │
│  └─────────────────────────────────────────────────────────────┘    │
└──────────────────────────────┬───────────────────────────────────────┘
┌──────────────────────────────┴───────────────────────────────────────┐
│                     Processing Engine Layer                          │
│                                                                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐  │
│  │ Trueno Compute   │  │ Trueno-Graph     │  │ Aprender ML      │  │
│  │ - Correlation    │  │ - PageRank       │  │ - Classification │  │
│  │ - Statistics     │  │ - Betweenness    │  │ - Clustering     │  │
│  │ - Linear Algebra │  │ - BFS/DFS        │  │ - Anomaly Det.   │  │
│  └──────────────────┘  └──────────────────┘  └──────────────────┘  │
│         │                       │                       │            │
│         └───────────┬───────────┴──────────┬────────────┘            │
│                     │                      │                         │
│         ┌───────────▼──────────┐  ┌────────▼─────────┐              │
│         │ GPU Backend (wgpu)   │  │ SIMD Backend     │              │
│         │ Vulkan/Metal/DX12    │  │ AVX-512/AVX2     │              │
│         └──────────────────────┘  └──────────────────┘              │
└──────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────┴───────────────────────────────────────┐
│                       Storage & Data Layer                           │
│                                                                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐  │
│  │ Trueno-DB        │  │ Feature Store    │  │ Graph Storage    │  │
│  │ - Arrow/Parquet  │  │ - Commit vectors │  │ - CSR format     │  │
│  │ - Morsel paging  │  │ - AST features   │  │ - Edge lists     │  │
│  │ - SQL interface  │  │ - Metadata cache │  │ - Node attrs     │  │
│  └──────────────────┘  └──────────────────┘  └──────────────────┘  │
└──────────────────────────────────────────────────────────────────────┘
┌──────────────────────────────┴───────────────────────────────────────┐
│                      Data Ingestion Layer                            │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐  │
│  │ GitHub API       │  │ Git History      │  │ AST Extractor    │  │
│  │ (octocrab)       │  │ (git2)           │  │ (tree-sitter)    │  │
│  └──────────────────┘  └──────────────────┘  └──────────────────┘  │
└──────────────────────────────────────────────────────────────────────┘
```

**[↑ Back to TOC](#table-of-contents)**

### 3.2 Component Interaction

**Data Flow Example**: "Show me correlation between concurrency bugs and memory safety issues"

1. **CLI Parsing** (`oip-gpu correlate "concurrency bugs" "memory safety"`)
   - Parse command into query AST
   - Identify required data: defect categories, timestamps

2. **Query Planning**
   - Check if data exists in trueno-db cache
   - Plan GPU execution: correlation matrix computation
   - Estimate cost: 100K commits × 2 categories = GPU-worthy

3. **Data Retrieval**
   - Load defect vectors from trueno-db (Arrow format)
   - Filter to relevant categories: [ConcurrencyBugs, MemorySafety]

4. **GPU Computation** (via trueno)
   - Transfer vectors to GPU memory
   - Compute Pearson correlation: `r = cov(X,Y) / (std(X) * std(Y))`
   - Return scalar correlation coefficient

5. **Result Formatting**
   - Format output: "Correlation: 0.68 (strong positive, p<0.001)"
   - Generate visualization if requested

**[↑ Back to TOC](#table-of-contents)**

### 3.3 Technology Stack Integration

| Layer | Primary Tech | Secondary Tech | Responsibility |
|-------|-------------|----------------|----------------|
| **CLI** | `clap` v4 | `colored`, `indicatif` | User interface, progress bars |
| **Query** | Custom parser | `pest` (optional) | Natural language → execution plan |
| **Compute** | `trueno` v0.4.1+ | `wgpu`, `rayon` | SIMD/GPU vector operations |
| **Graph** | `trueno-graph` | `petgraph` fallback | Graph algorithms, CSR storage |
| **ML** | `aprender` | `ndarray` | Supervised/unsupervised learning |
| **Storage** | `trueno-db` | `arrow`, `parquet` | Columnar storage, SQL queries |
| **Profiling** | `renacer` | - | Runtime anomaly detection |
| **Ingestion** | `octocrab`, `git2` | `tree-sitter` | GitHub API, git ops, AST parsing |

**Dependency Management** (per CLAUDE.md):
- **CRITICAL**: Always use latest `trueno` from crates.io (not git dependency)
- Verify: `cargo search trueno` before each development session
- Update: `cargo update trueno` and run full test suite

**[↑ Back to TOC](#table-of-contents)**

### 3.4 Data Flow Pipeline

**Pipeline Stages**:

```rust
// Conceptual data flow
pub struct AnalysisPipeline {
    ingestion: IngestionStage,      // GitHub → Raw commits
    extraction: FeatureStage,        // Commits → Feature vectors
    storage: StorageStage,           // Vectors → trueno-db
    compute: ComputeStage,           // GPU/SIMD analytics
    ml: MachineLearningStage,        // Model training/inference
    output: OutputStage,             // Results → User
}

impl AnalysisPipeline {
    pub async fn analyze_org(&self, org: &str) -> Result<AnalysisReport> {
        // Stage 1: Ingest all repos
        let repos = self.ingestion.fetch_repos(org).await?;
        
        // Stage 2: Extract features (parallel)
        let features = self.extraction.extract_parallel(repos).await?;
        
        // Stage 3: Store in trueno-db
        self.storage.bulk_insert(&features).await?;
        
        // Stage 4: GPU-accelerated analytics
        let correlations = self.compute.correlation_matrix_gpu(&features)?;
        let clusters = self.compute.kmeans_gpu(&features, k=10)?;
        
        // Stage 5: ML predictions
        let predictions = self.ml.predict_defects(&features)?;
        
        // Stage 6: Generate report
        self.output.generate_report(correlations, clusters, predictions)
    }
}
```

**Throughput Optimization**:
- **Batching**: Process 1000 commits per GPU kernel launch (amortize transfer cost)
- **Pipelining**: Overlap CPU feature extraction with GPU computation
- **Caching**: trueno-db stores computed features (avoid recomputation)
- **Lazy Loading**: Load only required columns from Parquet (columnar advantage)

**[↑ Back to TOC](#table-of-contents)**

---


## 4. Data Ingestion & Preprocessing

### 4.1 GitHub Repository Acquisition

**Approach**: Reuse existing OIP infrastructure with GPU-aware extensions.

```rust
use octocrab::Octocrab;

pub struct GitHubIngestion {
    client: Octocrab,
    rate_limiter: RateLimiter,
    cache: Arc<trueno_db::Database>,
}

impl GitHubIngestion {
    /// Fetch all repos for organization or specific repos
    pub async fn fetch_repos(&self, target: &AnalysisTarget) -> Result<Vec<Repository>> {
        match target {
            AnalysisTarget::Organization(org) => {
                self.fetch_org_repos(org).await
            }
            AnalysisTarget::Repositories(repos) => {
                self.fetch_specific_repos(repos).await
            }
            AnalysisTarget::SingleRepo(owner, repo) => {
                Ok(vec![self.fetch_repo(owner, repo).await?])
            }
        }
    }
}

pub enum AnalysisTarget {
    Organization(String),           // "rust-lang"
    Repositories(Vec<String>),      // ["rust-lang/rust", "rust-lang/cargo"]
    SingleRepo(String, String),     // ("rust-lang", "rust")
}
```

**Rate Limiting**: 5000 req/hour with GitHub token, intelligent backoff.

**[↑ Back to TOC](#table-of-contents)**

### 4.2 Git History Mining

**Integration with OIP's Git Module**:

```rust
use git2::Repository;

pub struct CommitMiner {
    repo_path: PathBuf,
    classifier: DefectClassifier,  // From OIP
}

impl CommitMiner {
    /// Mine all defect-fix commits
    pub fn mine_defects(&self) -> Result<Vec<DefectCommit>> {
        let repo = Repository::open(&self.repo_path)?;
        let mut commits = Vec::new();
        
        for commit in repo.log()? {
            // Filter: Only defect-related commits
            if self.is_defect_fix(&commit)? {
                let features = self.extract_features(&commit)?;
                let category = self.classifier.classify(&commit)?;
                
                commits.push(DefectCommit {
                    sha: commit.id(),
                    timestamp: commit.time(),
                    category,
                    features,
                });
            }
        }
        
        Ok(commits)
    }
    
    fn is_defect_fix(&self, commit: &Commit) -> Result<bool> {
        // Use OIP's heuristics: commit message patterns, labels
        let msg = commit.message().unwrap_or("");
        let patterns = ["fix", "bug", "defect", "issue", "error", "crash"];
        Ok(patterns.iter().any(|p| msg.to_lowercase().contains(p)))
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 4.3 Feature Extraction

**GPU-Friendly Feature Encoding**:

```rust
pub struct FeatureExtractor {
    ast_parser: tree_sitter::Parser,
}

pub struct CommitFeatures {
    // Categorical (one-hot encoded for GPU)
    defect_category: u8,           // 0-9 (10 categories)
    language: u8,                  // 0-N languages
    
    // Numerical (GPU-native)
    files_changed: f32,
    lines_added: f32,
    lines_deleted: f32,
    complexity_delta: f32,         // Cyclomatic complexity change
    
    // Temporal
    timestamp: f64,                // Unix epoch (for time-series)
    hour_of_day: u8,              // 0-23 (circadian patterns)
    day_of_week: u8,              // 0-6
    
    // AST-derived (high-dimensional)
    ast_node_changes: Vec<f32>,    // 128-dim embedding
    
    // Graph-derived
    files_coupling: f32,           // Co-change frequency
    author_expertise: f32,         // Prior commits in this module
}

impl FeatureExtractor {
    /// Extract features suitable for GPU processing
    pub fn extract(&self, commit: &Commit) -> Result<CommitFeatures> {
        let diff = commit.diff()?;
        
        Ok(CommitFeatures {
            files_changed: diff.files.len() as f32,
            lines_added: diff.insertions as f32,
            lines_deleted: diff.deletions as f32,
            complexity_delta: self.compute_complexity_delta(&diff)?,
            ast_node_changes: self.extract_ast_features(&diff)?,
            // ... other features
        })
    }
    
    /// Convert to flat vector for GPU
    pub fn to_vector(&self, features: &CommitFeatures) -> Vec<f32> {
        let mut vec = Vec::with_capacity(150);  // Fixed size
        vec.push(features.defect_category as f32);
        vec.push(features.files_changed);
        vec.push(features.lines_added);
        // ... flatten all features
        vec.extend_from_slice(&features.ast_node_changes);
        vec
    }
}
```

**Feature Normalization** (critical for GPU numerics):
```rust
pub fn normalize_features(features: &mut [f32]) {
    // Z-score normalization: (x - μ) / σ
    let mean = features.iter().sum::<f32>() / features.len() as f32;
    let std = (features.iter()
        .map(|x| (x - mean).powi(2))
        .sum::<f32>() / features.len() as f32).sqrt();
    
    for x in features.iter_mut() {
        *x = (*x - mean) / std;
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 4.4 Trueno-DB Storage Layer

**Schema Design**:

```sql
-- Defects table (columnar Parquet storage)
CREATE TABLE defects (
    id BIGINT PRIMARY KEY,
    repo_id INT,
    commit_sha TEXT,
    timestamp TIMESTAMP,
    category INT,  -- 0-9 for 10 defect types
    features BLOB  -- Serialized Vec<f32> for GPU
);

-- Feature table (wide format for GPU)
CREATE TABLE commit_features (
    commit_id BIGINT PRIMARY KEY,
    -- Numerical features (150 columns)
    f0 REAL, f1 REAL, ..., f149 REAL
);

-- Graph edges table
CREATE TABLE dependency_edges (
    source_file TEXT,
    target_file TEXT,
    weight REAL  -- Co-change frequency
);
```

**Bulk Insert** (optimize for Parquet):

```rust
use trueno_db::{Database, Table};

pub async fn bulk_insert_features(
    db: &Database,
    features: Vec<CommitFeatures>
) -> Result<()> {
    // Convert to Arrow RecordBatch (columnar)
    let batch = features_to_arrow(&features)?;
    
    // Write to Parquet (GPU-friendly format)
    db.write_parquet("commit_features", batch).await?;
    
    Ok(())
}

fn features_to_arrow(features: &[CommitFeatures]) -> arrow::RecordBatch {
    // Columnar layout: all f0 values, then all f1 values, ...
    // Optimized for GPU column-wise access
    arrow::RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(Float32Array::from_iter(features.iter().map(|f| f.files_changed))),
            Arc::new(Float32Array::from_iter(features.iter().map(|f| f.lines_added))),
            // ... all features
        ]
    )
}
```

**Query Interface**:

```rust
// SQL queries leverage trueno-db's GPU aggregations
let result = db.query("
    SELECT category, COUNT(*) as count
    FROM defects
    WHERE timestamp > '2024-01-01'
    GROUP BY category
    ORDER BY count DESC
").await?;
```

**[↑ Back to TOC](#table-of-contents)**

---


## 5. GPU Processing Pipeline

### 5.1 Trueno Compute Kernels

**Auto-Backend Selection** (trueno's killer feature):

```rust
use trueno::{Vector, Matrix, Backend};

pub struct GPUCorrelationEngine {
    backend: Backend,  // Auto-selected: GPU, SIMD, or Scalar
}

impl GPUCorrelationEngine {
    pub fn new() -> Self {
        // Trueno automatically selects best backend
        Self {
            backend: Backend::auto_detect()  // GPU if available, else SIMD
        }
    }
    
    /// Compute correlation matrix on GPU
    pub fn correlation_matrix(&self, data: &Matrix) -> Result<Matrix> {
        // Trueno handles GPU transfer, kernel launch, and result retrieval
        let result = data.correlation()?;  // Automatic GPU dispatch
        Ok(result)
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 5.2 Correlation Matrix Computation

**Pearson Correlation** (parallelized on GPU):

```rust
pub fn compute_defect_correlations(
    defects: &[DefectRecord]
) -> Result<CorrelationMatrix> {
    // Shape: (n_commits, n_categories)
    let matrix = defects_to_matrix(defects)?;  // e.g., 1M × 10
    
    // GPU-accelerated correlation (trueno)
    // Computes all pairs: O(n_categories^2) in parallel
    let corr = matrix.transpose()?.matmul(&matrix)?;  // 10×10 result
    
    // Normalize to correlation coefficients
    let corr_matrix = normalize_correlation(corr)?;
    
    Ok(CorrelationMatrix {
        categories: 10,
        values: corr_matrix,
        p_values: compute_significance(&matrix, &corr_matrix)?,
    })
}

// Example output:
// Concurrency ↔ Memory Safety: r=0.68, p<0.001 (strong correlation)
// Security ↔ Type Errors: r=0.32, p<0.05 (weak correlation)
```

**[↑ Back to TOC](#table-of-contents)**

### 5.3 Similarity Metrics

**Cosine Similarity** (GPU-accelerated):

```rust
use trueno::Vector;

pub fn repository_similarity(
    repo1_features: &Vector,
    repo2_features: &Vector
) -> Result<f32> {
    // Cosine similarity: dot(A,B) / (norm(A) * norm(B))
    let dot_product = repo1_features.dot(repo2_features)?;
    let norm1 = repo1_features.norm()?;
    let norm2 = repo2_features.norm()?;
    
    Ok(dot_product / (norm1 * norm2))
}

// Use case: "Find repositories similar to rust-lang/rust"
// Computes 1M pairwise similarities in <1 second on GPU
```

**[↑ Back to TOC](#table-of-contents)**

### 5.4 Performance Optimization

**Kernel Fusion** (via trueno-db's JIT compiler):

```rust
// Instead of: mean(filter(data, predicate))
// Fuse into single kernel to avoid intermediate GPU memory

let result = db.query_gpu("
    SELECT AVG(complexity_delta)
    FROM defects
    WHERE category = 2 AND timestamp > '2024-01-01'
")?;

// Trueno-db JIT compiles to WGSL:
// - Single GPU kernel: filter + reduction
// - No intermediate memory allocation
// - 10-20x faster than multi-pass
```

**Memory Management**:

```rust
pub struct GPUMemoryPool {
    device: wgpu::Device,
    buffers: Vec<wgpu::Buffer>,
    capacity: usize,
}

impl GPUMemoryPool {
    /// Pre-allocate GPU buffers to avoid allocation overhead
    pub fn new(device: wgpu::Device, capacity: usize) -> Self {
        let buffers = (0..8).map(|_| {
            device.create_buffer(&wgpu::BufferDescriptor {
                size: capacity as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
                label: Some("gpu_pool_buffer"),
            })
        }).collect();
        
        Self { device, buffers, capacity }
    }
    
    /// Reuse buffer instead of allocating
    pub fn get_buffer(&mut self) -> &mut wgpu::Buffer {
        self.buffers.pop().expect("Pool exhausted")
    }
}
```

**Batch Processing** (amortize PCIe transfer):

```rust
pub async fn process_batches<T>(
    items: Vec<T>,
    batch_size: usize,
    gpu_fn: impl Fn(&[T]) -> Result<Vec<f32>>
) -> Result<Vec<f32>> {
    let mut results = Vec::new();
    
    for chunk in items.chunks(batch_size) {
        // Transfer batch to GPU once
        // Process all items in parallel
        // Transfer results back once
        results.extend(gpu_fn(chunk)?);
    }
    
    Ok(results)
}

// Example: Process 1M commits in batches of 10K
// Transfer overhead: 100 transfers vs 1M individual transfers
// Speedup: 50-100x
```

**[↑ Back to TOC](#table-of-contents)**

---

## 9. CLI Interface Specification

### 9.1 Command Structure

```bash
oip-gpu [GLOBAL_OPTIONS] <COMMAND> [COMMAND_OPTIONS]

GLOBAL OPTIONS:
    --backend <gpu|simd|cpu>    Force specific compute backend
    --verbose, -v               Verbose logging
    --config <FILE>             Configuration file path

COMMANDS:
    analyze      Analyze GitHub organization or repositories
    correlate    Compute correlations between defect patterns
    predict      Predict defect likelihood for PR/commit
    query        Natural language query interface
    cluster      Cluster repositories by defect patterns
    graph        Graph analytics (PageRank, betweenness)
    export       Export data to various formats
    benchmark    Run performance benchmarks
```

**[↑ Back to TOC](#table-of-contents)**

### 9.2 GPU Analysis Commands

**Analyze Command**:

```bash
# Analyze entire organization
oip-gpu analyze --org rust-lang --output rust-analysis.db

# Analyze specific repositories
oip-gpu analyze --repos rust-lang/rust,rust-lang/cargo --output analysis.db

# Single repository analysis
oip-gpu analyze --repo rust-lang/rust --output rust-defects.db

# Force GPU backend
oip-gpu analyze --org nodejs --backend gpu --output nodejs.db

OPTIONS:
    --org <ORG>              GitHub organization name
    --repos <REPO1,REPO2>    Comma-separated repository list
    --repo <OWNER/REPO>      Single repository
    --output <FILE>          Output database file (trueno-db format)
    --backend <gpu|simd>     Force compute backend
    --since <DATE>           Only analyze commits after date
    --workers <N>            Parallel worker count (default: auto)
```

**Correlate Command**:

```bash
# Compute all defect category correlations
oip-gpu correlate --input analysis.db --output correlations.json

# Specific category pairs
oip-gpu correlate --input analysis.db \
    --categories "concurrency,memory_safety" \
    --output corr.json

# Time-lagged correlation (causal inference)
oip-gpu correlate --input analysis.db --lag 7 --output lagged.json

OPTIONS:
    --input <FILE>           Input database (from analyze command)
    --output <FILE>          Output file (JSON/YAML/CSV)
    --categories <CATS>      Specific categories to correlate
    --lag <DAYS>             Time lag for Granger causality
    --format <json|yaml|csv> Output format
    --threshold <FLOAT>      Only show correlations > threshold
```

**Predict Command**:

```bash
# Predict defect likelihood for PR
oip-gpu predict --pr https://github.com/rust-lang/rust/pull/12345

# Predict for local uncommitted changes
oip-gpu predict --files src/main.rs,src/lib.rs

# Batch prediction for all open PRs
oip-gpu predict --org rust-lang --open-prs

OPTIONS:
    --pr <URL>               GitHub PR URL
    --files <FILES>          Local files to analyze
    --org <ORG>              Predict for all open PRs in org
    --model <FILE>           Custom trained model
    --explain                Show feature importance (SHAP values)
```

**[↑ Back to TOC](#table-of-contents)**

### 9.3 Query Interface

**Natural Language Queries**:

```bash
# Show most common defect in repository
oip-gpu query "show me most common defect in rust-lang/rust"

# Correlation queries
oip-gpu query "correlate security vulnerabilities with test coverage"

# Temporal queries
oip-gpu query "defect trend in last 6 months for nodejs"

# Comparison queries
oip-gpu query "compare rust-lang/rust vs golang/go defect patterns"

# Prediction queries
oip-gpu query "probability of concurrency bug in PR #12345"

# Graph queries
oip-gpu query "which files are most likely to cause cascading defects"

OPTIONS:
    --input <FILE>           Database file (default: ./oip-gpu.db)
    --format <table|json>    Output format
    --limit <N>              Limit results to N entries
    --export <FILE>          Export results to file
```

**Example Outputs**:

```
$ oip-gpu query "show me most common defect in rust-lang/rust"

┌─────────────────────┬───────┬────────────┐
│ Defect Category     │ Count │ Percentage │
├─────────────────────┼───────┼────────────┤
│ Type Errors         │ 1234  │ 24.1%      │
│ Logic Errors        │ 987   │ 19.3%      │
│ Concurrency Bugs    │ 765   │ 15.0%      │
│ Memory Safety       │ 543   │ 10.6%      │
│ API Misuse          │ 432   │ 8.5%       │
└─────────────────────┴───────┴────────────┘

Top insight: Type errors are 2.5x more common than memory safety issues
Recommendation: Focus on stricter type checking in PR reviews

$ oip-gpu query "correlate concurrency bugs with memory safety"

Correlation Analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Pearson correlation: 0.68 (strong positive)
P-value: p < 0.001 (statistically significant)
Interpretation: Repositories with more concurrency bugs 
                tend to have more memory safety issues

Time-lagged analysis:
  Lag -7 days:  r=0.45 (concurrency → memory safety)
  Lag +7 days:  r=0.23 (memory safety → concurrency)

Granger causality: Concurrency bugs predict memory safety 
                   issues (F-stat: 23.4, p<0.001)
```

**[↑ Back to TOC](#table-of-contents)**

### 9.4 Output Formats

**JSON Output**:

```json
{
  "query": "most common defect in rust-lang/rust",
  "results": [
    {
      "category": "Type Errors",
      "count": 1234,
      "percentage": 24.1,
      "examples": [
        {
          "commit": "abc123",
          "file": "src/type_checker.rs",
          "line": 456
        }
      ]
    }
  ],
  "metadata": {
    "execution_time_ms": 234,
    "backend": "GPU",
    "commits_analyzed": 125000
  }
}
```

**CSV Output**:

```csv
category,count,percentage,mean_time_to_fix_hours
Type Errors,1234,24.1,12.4
Logic Errors,987,19.3,8.7
Concurrency Bugs,765,15.0,24.6
```

**YAML Output** (compatible with OIP):

```yaml
organization: rust-lang
repository: rust
analysis_date: 2025-11-24T00:00:00Z
defect_patterns:
  - category: Type Errors
    frequency: 1234
    percentage: 24.1
    gpu_compute_time_ms: 45
```

**[↑ Back to TOC](#table-of-contents)**

---


## 7. Machine Learning with Aprender

### 7.1 Feature Engineering

```rust
use aprender::{DataFrame, Vector};

pub struct MLFeatureEngine {
    scaler: StandardScaler,
}

impl MLFeatureEngine {
    pub fn engineer_features(&self, defects: &[DefectRecord]) -> DataFrame {
        // Use aprender's DataFrame for feature preparation
        let mut df = DataFrame::new();
        df.add_column("files_changed", defects.iter().map(|d| d.files_changed).collect());
        df.add_column("complexity_delta", defects.iter().map(|d| d.complexity_delta).collect());
        // Normalize via aprender
        self.scaler.fit_transform(&mut df).unwrap();
        df
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 7.2 Supervised Learning Models

```rust
use aprender::{RandomForestClassifier, GradientBoostingClassifier};

pub struct DefectPredictor {
    rf_model: RandomForestClassifier,
    gb_model: GradientBoostingClassifier,
}

impl DefectPredictor {
    pub fn train(&mut self, X: &DataFrame, y: &Vector) -> Result<()> {
        // Random Forest (100 trees, aprender uses trueno for speed)
        self.rf_model.fit(X, y)?;
        
        // Gradient Boosting
        self.gb_model.fit(X, y)?;
        
        Ok(())
    }
    
    pub fn predict(&self, features: &DataFrame) -> Result<Vector> {
        // Ensemble: average both models
        let rf_pred = self.rf_model.predict(features)?;
        let gb_pred = self.gb_model.predict(features)?;
        Ok(rf_pred.add(&gb_pred)?.scale(0.5)?)
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 7.3 Clustering & Pattern Discovery

```rust
use aprender::KMeans;

pub fn cluster_repositories(features: &Matrix, k: usize) -> Result<Vec<usize>> {
    // K-means clustering (aprender uses trueno's SIMD/GPU backend)
    let kmeans = KMeans::new(k);
    let labels = kmeans.fit_predict(features)?;
    Ok(labels)
}

// Use case: "Group 1000 repos into 10 clusters by defect patterns"
// GPU-accelerated distance computations: 10-30x faster than CPU
```

**[↑ Back to TOC](#table-of-contents)**

### 7.4 Anomaly Detection

```rust
use aprender::IsolationForest;

pub fn detect_anomalous_commits(features: &DataFrame) -> Result<Vec<bool>> {
    let iforest = IsolationForest::new(100, 256);
    let anomaly_scores = iforest.fit_predict(features)?;
    Ok(anomaly_scores.iter().map(|&s| s < -0.5).collect())
}
```

**[↑ Back to TOC](#table-of-contents)**

---

## 6. Graph Analytics with Trueno-Graph

### 6.1 Dependency Graph Construction

```rust
use trueno_graph::{CsrGraph, NodeId};

pub fn build_dependency_graph(repos: &[Repository]) -> Result<CsrGraph> {
    let mut graph = CsrGraph::new();
    
    for repo in repos {
        for file in repo.files() {
            // Add edges for imports/dependencies
            for import in file.imports() {
                graph.add_edge(
                    NodeId::from_file(file.path()),
                    NodeId::from_file(import.path()),
                    1.0
                )?;
            }
        }
    }
    
    Ok(graph)
}
```

**[↑ Back to TOC](#table-of-contents)**

### 6.2 GPU-Accelerated Graph Algorithms

```rust
use trueno_graph::pagerank;

pub fn identify_critical_files(graph: &CsrGraph) -> Result<Vec<(NodeId, f32)>> {
    // GPU-accelerated PageRank (5-15x faster than CPU)
    let scores = pagerank(graph, 20, 1e-6)?;
    
    let mut ranked: Vec<_> = scores.iter().enumerate()
        .map(|(id, &score)| (NodeId(id as u32), score))
        .collect();
    ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
    
    Ok(ranked)
}
```

**[↑ Back to TOC](#table-of-contents)**

### 6.3 Defect Propagation Analysis

```rust
pub fn defect_propagation_probability(
    graph: &CsrGraph,
    defect_file: NodeId,
    radius: usize
) -> Result<HashMap<NodeId, f32>> {
    // BFS to find files within radius
    let reachable = trueno_graph::bfs(graph, defect_file)?;
    
    // Compute propagation probability (distance decay)
    let mut probs = HashMap::new();
    for (node, distance) in reachable {
        if distance <= radius {
            probs.insert(node, 1.0 / (1.0 + distance as f32));
        }
    }
    
    Ok(probs)
}
```

**[↑ Back to TOC](#table-of-contents)**

---

## 13. Testing Strategy

### 13.1 Unit Testing

```rust
#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_correlation_computation() {
        let data = Matrix::from_vec(3, 2, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
        let corr = compute_correlation(&data).unwrap();
        assert!((corr - 1.0).abs() < 1e-6);  // Perfect correlation
    }
    
    #[test]
    fn test_gpu_cpu_equivalence() {
        let data = generate_test_data(1000, 10);
        
        let gpu_result = compute_gpu(&data).unwrap();
        let cpu_result = compute_cpu(&data).unwrap();
        
        assert_vectors_close(&gpu_result, &cpu_result, 1e-4);
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

### 13.2 Integration Testing

```bash
# Test full pipeline: GitHub → GPU → Results
cargo test --test integration_gpu --features gpu -- --nocapture
```

**[↑ Back to TOC](#table-of-contents)**

### 13.3 Performance Benchmarking

```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn bench_correlation_matrix(c: &mut Criterion) {
    let data = generate_data(100000, 10);
    
    c.bench_function("correlation_gpu", |b| {
        b.iter(|| correlation_gpu(black_box(&data)))
    });
    
    c.bench_function("correlation_cpu", |b| {
        b.iter(|| correlation_cpu(black_box(&data)))
    });
}

criterion_group!(benches, bench_correlation_matrix);
criterion_main!(benches);
```

**[↑ Back to TOC](#table-of-contents)**

---

## 15. Roadmap & Validation Gates

### 15.1 Phase 1: Foundation (Weeks 1-4)

**Deliverables**:
- CLI interface with `analyze`, `query` commands
- Integration with OIP defect classification
- Trueno-db storage layer
- SIMD-accelerated correlation (no GPU yet)

**Validation Gate**:
- Analyze 100-repo org in <10 minutes (SIMD)
- 90%+ test coverage
- Zero GPU code (CPU baseline established)

**[↑ Back to TOC](#table-of-contents)**

### 15.2 Phase 2: GPU Acceleration (Weeks 5-8)

**Deliverables**:
- GPU correlation matrix computation
- Trueno-graph PageRank integration
- GPU/CPU equivalence tests
- Performance benchmarks

**Validation Gate**:
- 10-20x speedup vs SIMD for correlation
- GPU results match CPU within 1e-4 tolerance
- Analyze 1000-repo org in <30 minutes

**[↑ Back to TOC](#table-of-contents)**

### 15.3 Phase 3: Advanced ML (Weeks 9-12)

**Deliverables**:
- Aprender ML models (RF, GBM, K-means)
- Predictive defect modeling
- Natural language query interface

**Validation Gate**:
- >75% F1-score on defect prediction
- Query response time <2 seconds

**[↑ Back to TOC](#table-of-contents)**

---

## 16. Academic References

### 16.5 Complete Bibliography

**[1]** Steinkraus et al. "Using GPUs for Machine Learning Algorithms." ICDAR 2005.

**[2]** Cano. "A Survey on GPU Computing for Large-Scale Data Mining." WIREs 2018.

**[3]** D'Ambros et al. "Evaluating Defect Prediction Approaches." Empirical SE 2012.

**[4]** Qin et al. "DeMuVGN: Software Defect Prediction via GNNs." arXiv:2410.19550, 2024.

**[5]** Nguyen et al. "Graph-based Mining of Code Change Patterns." ICSE 2019.

**[6]** Wang et al. "Code Revert Prediction with GNNs." arXiv:2403.09507, 2024.

**[7]** Khomh et al. "Do Faster Releases Improve Quality?" MSR 2012.

**[8]** Granger. "Investigating Causal Relations." Econometrica 1969.

**[9]** Sun et al. "AST for Programming Language Understanding." arXiv:2312.00413, 2023.

**[10]** Xu et al. "Detecting Real-World Safety Issues in Rust." IEEE TSE 2024.

**[↑ Back to TOC](#table-of-contents)**

---

## 17. Appendices

### 17.4 Glossary

- **AST**: Abstract Syntax Tree
- **GPU**: Graphics Processing Unit
- **SIMD**: Single Instruction Multiple Data
- **PCIe**: Peripheral Component Interconnect Express
- **CSR**: Compressed Sparse Row (graph format)
- **Trueno**: Multi-target compute library (CPU/GPU/WASM)
- **Aprender**: Pure Rust ML library
- **Renacer**: System call tracer with anomaly detection
- **OIP**: Organizational Intelligence Plugin

**[↑ Back to TOC](#table-of-contents)**

---

**Document Status**: Draft Complete
**Total Sections**: 17
**Peer-Reviewed Citations**: 10
**Target Completion**: Ready for review


---

## Technical Addendum: Production-Critical Optimizations

**Added:** 2025-11-24 (Post-Review)
**Reviewer Feedback:** Addresses PCIe bottleneck, class imbalance, thread divergence, concept drift, validation gaps

### A.1 GPU Memory Persistence Strategy

**Problem**: Section 4.3 transfers feature vectors per operation → 30-50% execution time wasted [[A1]](#addendum-ref-1).

**Solution**: GPU-resident feature store with pinned memory.

```rust
pub struct GPUHotStore {
    device: wgpu::Device,
    // Persistent GPU buffers for active repositories
    commit_features: wgpu::Buffer,      // Pre-loaded features
    dependency_graph: wgpu::Buffer,     // CSR format on GPU
    correlation_cache: wgpu::Buffer,    // Pre-computed matrices
}

impl GPUHotStore {
    /// Load entire repository context to GPU once
    pub fn load_repository(&mut self, repo: &Repository) -> Result<()> {
        // Extract ALL features upfront
        let features = extract_all_features(repo)?;
        
        // Transfer once, reuse for all queries
        self.commit_features = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            contents: bytemuck::cast_slice(&features),
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            label: Some("persistent_features"),
        });
        
        Ok(())
    }
    
    /// Zero-copy query (data already on GPU)
    pub fn query_gpu(&self, query: &str) -> Result<QueryResult> {
        // Execute entirely on GPU - no PCIe transfer
        self.execute_shader(query)
    }
}
```

**Impact**: 2.1x speedup for graph operations [[A2]](#addendum-ref-2).

**[↑ Back to TOC](#table-of-contents)**

---

### A.2 Class Imbalance Handling

**Problem**: Defects are <1% of commits. Standard models predict "no defect" → high accuracy, zero value [[A3]](#addendum-ref-3).

**Solution**: Focal Loss + SMOTE in training pipeline.

```rust
use aprender::{FocalLoss, SMOTE};

pub struct ImbalanceAwareTrainer {
    focal_loss: FocalLoss,
    smote: SMOTE,
}

impl ImbalanceAwareTrainer {
    pub fn train(&self, X: &DataFrame, y: &Vector) -> Result<Model> {
        // Check class distribution
        let defect_ratio = y.sum() / y.len() as f32;
        
        if defect_ratio < 0.05 {
            // Severe imbalance: use SMOTE
            let (X_resampled, y_resampled) = self.smote.fit_resample(X, y)?;
            
            // Train with Focal Loss (emphasizes hard examples)
            let model = GradientBoostingClassifier::new()
                .with_loss(self.focal_loss)  // alpha=0.25, gamma=2.0
                .fit(&X_resampled, &y_resampled)?;
            
            Ok(model)
        } else {
            // Mild imbalance: weighted sampling sufficient
            self.train_weighted(X, y)
        }
    }
}
```

**Validation Metric**: Use AUPRC (Area Under Precision-Recall Curve), NOT accuracy [[A3]](#addendum-ref-3).

```rust
pub fn evaluate_model(predictions: &Vector, ground_truth: &Vector) -> Metrics {
    Metrics {
        auprc: compute_auprc(predictions, ground_truth),  // Primary metric
        f1_score: compute_f1(predictions, ground_truth),
        // Accuracy is misleading for imbalanced data
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

---

### A.3 Bucketed Dynamic Batching

**Problem**: Fixed batch sizes cause thread divergence (40% slowdown on irregular workloads [[A5]](#addendum-ref-5)).

**Solution**: Sort by complexity before batching.

```rust
pub fn bucketed_batching(commits: Vec<Commit>, batch_size: usize) -> Vec<Vec<Commit>> {
    // Sort by AST node count (proxy for processing time)
    let mut sorted = commits;
    sorted.sort_by_key(|c| c.ast_node_count);
    
    // Create uniform-complexity batches
    sorted.chunks(batch_size)
        .map(|chunk| chunk.to_vec())
        .collect()
}

// GPU warps finish simultaneously → no thread waiting
```

**Alternative**: Adaptive batch sizing based on GPU occupancy.

```rust
pub fn adaptive_batch_size(commit_complexity: usize) -> usize {
    match commit_complexity {
        0..=100 => 1024,      // Small commits: large batches
        101..=500 => 256,     // Medium commits
        _ => 64,              // Large commits: small batches
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

---

### A.4 Sliding Window Correlation (Concept Drift)

**Problem**: Codebases evolve. Correlation matrix over 5 years mixes obsolete patterns with current ones [[A6]](#addendum-ref-6).

**Solution**: Time-windowed correlation matrices.

```rust
pub struct TemporalCorrelationAnalyzer {
    window_size: Duration,  // e.g., 6 months
}

impl TemporalCorrelationAnalyzer {
    pub fn analyze(&self, defects: &[DefectRecord]) -> Vec<CorrelationMatrix> {
        let mut windows = Vec::new();
        
        // Sliding window: compute correlation per time period
        for window_start in defects.timestamps().step_by(self.window_size) {
            let window_end = window_start + self.window_size;
            let window_data = defects.filter(|d| 
                d.timestamp >= window_start && d.timestamp < window_end
            );
            
            let corr_matrix = compute_correlation(&window_data)?;
            windows.push(CorrelationMatrix {
                timestamp: window_start,
                values: corr_matrix,
            });
        }
        
        windows
    }
    
    /// Detect changing patterns over time
    pub fn detect_drift(&self, matrices: &[CorrelationMatrix]) -> DriftReport {
        // Compare consecutive windows
        let mut drifts = Vec::new();
        for window in matrices.windows(2) {
            let delta = window[1].values.sub(&window[0].values)?;
            if delta.norm() > 0.5 {  // Significant change
                drifts.push(ConceptDrift {
                    timestamp: window[1].timestamp,
                    magnitude: delta.norm(),
                });
            }
        }
        DriftReport { drifts }
    }
}
```

**Validation**: Use chronological splits, NOT k-fold [[A7]](#addendum-ref-7).

```rust
// WRONG: K-fold (leaks future into past)
// let folds = k_fold_split(data, k=5);

// CORRECT: Chronological split
let train_data = data.filter(|d| d.timestamp < cutoff);
let test_data = data.filter(|d| d.timestamp >= cutoff);
```

**[↑ Back to TOC](#table-of-contents)**

---

### A.5 Value-Based Validation Gates

**Problem**: Section 15.1 validates speed, not accuracy. Fast garbage is still garbage [[A10]](#addendum-ref-10).

**Solution**: Add baseline comparison gates.

```rust
pub struct ValidationGate {
    baseline_model: LogisticRegression,  // Simple CPU model
    gpu_model: Model,
}

impl ValidationGate {
    pub fn validate(&self, test_data: &DataFrame) -> GateResult {
        let baseline_f1 = self.baseline_model.evaluate(test_data).f1_score;
        let gpu_f1 = self.gpu_model.evaluate(test_data).f1_score;
        let speedup = self.measure_speedup();
        
        GateResult {
            pass: gpu_f1 >= baseline_f1 && speedup >= 5.0,
            message: format!(
                "GPU F1: {:.3}, Baseline F1: {:.3}, Speedup: {:.1}x",
                gpu_f1, baseline_f1, speedup
            ),
        }
    }
}
```

**Updated Phase 1 Validation Gate**:

```yaml
success_criteria:
  functional:
    - GPU model F1-score >= Logistic Regression F1-score (no accuracy regression)
    - Analyze 100-repo org in <10 minutes
    - AUPRC > 0.6 on imbalanced test set
  
  technical:
    - GPU speedup >= 5x vs SIMD (after PCIe transfer)
    - Thread divergence <10% (bucketed batching)
    - Cache hit rate >80% (GPU-resident features)
  
  quality:
    - Concept drift detection operational (sliding windows)
    - Chronological validation (no temporal leakage)
```

**[↑ Back to TOC](#table-of-contents)**

---

### A.6 Control Flow Graph Features

**Problem**: Section 4.3 uses AST features. CFG features are more predictive (r=0.7 vs r=0.5 [[A8]](#addendum-ref-8)).

**Solution**: Add CFG-based complexity metrics.

```rust
pub struct CFGFeatureExtractor {
    parser: tree_sitter::Parser,
}

pub struct CFGFeatures {
    // Structural metrics (CFG-derived)
    cyclomatic_complexity: f32,
    loop_depth: f32,
    branch_density: f32,
    
    // Social metrics (often better than code metrics [[A9]](#addendum-ref-9))
    author_expertise: f32,    // Prior commits in module
    bus_factor: f32,          // # developers who touched file
    ownership_turnover: f32,  // Change in primary maintainer
}

impl CFGFeatureExtractor {
    pub fn extract(&self, commit: &Commit) -> Result<CFGFeatures> {
        let ast = self.parser.parse(commit.diff())?;
        let cfg = ast.to_control_flow_graph()?;
        
        Ok(CFGFeatures {
            cyclomatic_complexity: cfg.cyclomatic_complexity(),
            loop_depth: cfg.max_nesting_depth(),
            branch_density: cfg.branches() as f32 / cfg.nodes() as f32,
            // Extract social metrics from git blame
            author_expertise: self.compute_expertise(commit)?,
            bus_factor: self.compute_bus_factor(commit)?,
            ownership_turnover: self.compute_turnover(commit)?,
        })
    }
}
```

**[↑ Back to TOC](#table-of-contents)**

---

## Addendum References

<a name="addendum-ref-1"></a>
**[A1]** Gregg, C., & Hazelwood, K. (2011). "Where is the data? Why you cannot debate CPU vs. GPU performance without the answer." *ISPASS*.

<a name="addendum-ref-2"></a>
**[A2]** Che, S., et al. (2011). "Pannotia: Understanding irregular GPGPU graph applications." *IEEE IISWC*.

<a name="addendum-ref-3"></a>
**[A3]** Tantithamthavorn, C., et al. (2018). "The Impact of Class Rebalancing Techniques on the Performance of Defect Prediction Models." *IEEE TSE*.

<a name="addendum-ref-4"></a>
**[A4]** Nam, J., et al. (2018). "Heterogeneous Defect Prediction." *IEEE TSE*.

<a name="addendum-ref-5"></a>
**[A5]** Yu, G., et al. (2022). "Orca: A Distributed Serving System for Transformer-Based Generative Models." *OSDI*.

<a name="addendum-ref-6"></a>
**[A6]** McIntosh, S., et al. (2017). "The Evolution of Software Defect Prediction Models." *MSR*.

<a name="addendum-ref-7"></a>
**[A7]** Tan, M., et al. (2015). "Online Defect Prediction for Software Projects." *ICSE*.

<a name="addendum-ref-8"></a>
**[A8]** Zimmermann, T., et al. (2007). "Predicting Defects using Network Analysis on Dependency Graphs." *ICSE*.

<a name="addendum-ref-9"></a>
**[A9]** Bird, C., et al. (2011). "Don't Touch My Code! Examining the Effects of Ownership on Software Quality." *ESEC/FSE*.

<a name="addendum-ref-10"></a>
**[A10]** Mende, T., & Koschke, R. (2010). "Effort-Aware Defect Prediction Models." *CSMR*.

---

**Addendum Status**: Complete
**Additional Citations**: 10 peer-reviewed papers
**Critical Gaps Addressed**: 6 (PCIe, imbalance, batching, drift, validation, features)


---

## A.7 Future: WASM GPU Visualization Integration

**Assumed**: Future WASM-based GPU visualization system will consume this project's output.

**Architecture**:

```
┌─────────────────────────────────────────────────────┐
│   Browser (WASM + WebGPU)                           │
│  ┌─────────────────────────────────────────────┐    │
│  │  GPU Visualization System (Pure WASM)       │    │
│  │  - Heatmaps (correlation matrices)          │    │
│  │  - Force-directed graphs (dependencies)     │    │
│  │  - Time series (defect trends)              │    │
│  │  - 3D tensor viz (feature spaces)           │    │
│  └─────────────┬───────────────────────────────┘    │
└────────────────┼────────────────────────────────────┘
                 │ WebGPU API
                 │ (zero-copy GPU buffers)
┌────────────────▼────────────────────────────────────┐
│   OIP-GPU Analysis System (Native or WASM)          │
│  ┌──────────────────────────────────────────────┐   │
│  │ GPU Hot Store (Section A.1)                  │   │
│  │ - Correlation matrices (GPU buffers)         │   │
│  │ - Graph data (CSR format, GPU-resident)      │   │
│  │ - Time series tensors                        │   │
│  └──────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────┘
```

**Integration Points**:

1. **Shared GPU Context** (wgpu supports native + WASM):

```rust
// This spec's compute system
pub struct AnalysisEngine {
    device: wgpu::Device,
    gpu_store: GPUHotStore,
}

// Future visualization system (same device)
pub struct WASMVisualizer {
    device: wgpu::Device,  // Same GPU context
    canvas: web_sys::HtmlCanvasElement,
}

// Zero-copy data sharing
impl AnalysisEngine {
    pub fn export_for_viz(&self) -> VizBuffers {
        VizBuffers {
            correlation_matrix: self.gpu_store.correlation_cache.clone(),  // GPU buffer handle
            graph_edges: self.gpu_store.dependency_graph.clone(),
            // No CPU roundtrip - direct GPU→GPU
        }
    }
}
```

2. **Data Formats** (GPU-native, no serialization):

| Visualization | Data Source | GPU Format |
|---------------|-------------|------------|
| **Heatmap** | Correlation matrix (Section 5.2) | `f32` 2D texture |
| **Graph** | Dependency graph (Section 6.1) | CSR buffers (trueno-graph) |
| **Time series** | Sliding windows (Section A.4) | `f32` 1D buffer |
| **Scatter plot** | PCA projections (aprender) | `f32` 2D buffer |

3. **WASM Compilation** (trueno already supports WASM SIMD128):

```toml
[target.wasm32-unknown-unknown.dependencies]
trueno = { version = "0.4.1", features = ["wasm-simd"] }
wgpu = { version = "0.19", features = ["webgpu"] }
```

4. **API Contract** (visualization consumes):

```rust
// OIP-GPU exports this interface
#[wasm_bindgen]
pub struct GPUAnalysisExport {
    // Pre-computed on GPU, ready for rendering
    correlation_heatmap: js_sys::Float32Array,  // Backed by GPU buffer
    graph_nodes: js_sys::Uint32Array,
    graph_edges: js_sys::Uint32Array,
    time_series: js_sys::Float32Array,
}

#[wasm_bindgen]
impl GPUAnalysisExport {
    /// Zero-copy: returns GPU buffer handle for WebGPU
    pub fn get_gpu_buffer(&self, buffer_name: &str) -> web_sys::GpuBuffer {
        match buffer_name {
            "correlation" => self.correlation_heatmap.buffer(),
            "graph" => self.graph_edges.buffer(),
            _ => panic!("Unknown buffer"),
        }
    }
}
```

5. **Performance Characteristics**:

- **Zero CPU marshaling**: GPU compute → GPU render pipeline
- **Streaming updates**: Sliding window correlations (Section A.4) → real-time heatmap animation
- **Interactive**: User selects time range → re-query GPU store → instant viz update
- **Portable**: Same WASM binary runs native (via wasmtime) or browser

**Example Use Case**: Real-time defect correlation dashboard

```javascript
// Browser-side JavaScript
const analysis = await init_wasm_analysis();
const viz = await init_wasm_visualizer();

// Compute on GPU (WASM + WebGPU)
const correlations = await analysis.compute_correlations("rust-lang");

// Render on GPU (zero-copy)
const gpuBuffer = correlations.get_gpu_buffer("correlation");
viz.render_heatmap(gpuBuffer);  // Direct GPU buffer → shader

// User interaction: drill down
canvas.onclick = async (event) => {
    const category = viz.pick_category(event);
    const timeseries = await analysis.get_timeseries(category);
    viz.render_timeseries(timeseries.get_gpu_buffer("timeseries"));
};
```

**Validation**: Future viz system must:
- Consume GPU buffers without CPU conversion
- Support trueno's WASM SIMD backend
- Handle sparse graphs (CSR format from trueno-graph)
- Render at 60fps for interactive exploration

**[↑ Back to TOC](#table-of-contents)**