-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombatStore.lua
More file actions
2574 lines (2342 loc) · 106 KB
/
CombatStore.lua
File metadata and controls
2574 lines (2342 loc) · 106 KB
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
local _, ns = ...
local Constants = ns.Constants
local ApiCompat = ns.ApiCompat
local Helpers = ns.Helpers
local CombatStore = {}
local function buildEmptyDb()
return {
schemaVersion = Constants.SCHEMA_VERSION,
settings = Helpers.CopyTable(Constants.DEFAULT_SETTINGS, true),
matches = {
order = {},
byId = {},
},
combats = {
order = {},
byId = {},
},
aggregates = {
opponents = {},
classes = {},
specs = {},
builds = {},
contexts = {},
daily = {},
weekly = {},
ratingHistory = {},
buildEffectiveness = {},
specDamageSignatures = {},
soloShuffleSpecStats = {},
bgBlitzSpecStats = {},
openerSequenceEffectiveness = {},
comps = {},
matchupArchetypes = {},
openers = {},
matchupMemory = {},
duelSeries = {},
metricBaselines = {},
},
dummyBenchmarks = {},
suggestionCache = {
order = {},
bySessionId = {},
},
maintenance = {
totalRawEvents = 0,
lastRebuildAt = nil,
aggregateVersion = 1,
warnings = {},
traceLog = {},
},
}
end
local function ensureDefaults(db)
db.schemaVersion = db.schemaVersion or Constants.SCHEMA_VERSION
db.settings = db.settings or Helpers.CopyTable(Constants.DEFAULT_SETTINGS, true)
for key, value in pairs(Constants.DEFAULT_SETTINGS) do
if db.settings[key] == nil then
db.settings[key] = value
end
end
db.matches = db.matches or { order = {}, byId = {} }
db.matches.order = db.matches.order or {}
db.matches.byId = db.matches.byId or {}
db.combats = db.combats or { order = {}, byId = {} }
db.combats.order = db.combats.order or {}
db.combats.byId = db.combats.byId or {}
db.aggregates = db.aggregates or {}
db.aggregates.opponents = db.aggregates.opponents or {}
db.aggregates.classes = db.aggregates.classes or {}
db.aggregates.specs = db.aggregates.specs or {}
db.aggregates.builds = db.aggregates.builds or {}
db.aggregates.contexts = db.aggregates.contexts or {}
db.aggregates.daily = db.aggregates.daily or {}
db.aggregates.weekly = db.aggregates.weekly or {}
db.aggregates.ratingHistory = db.aggregates.ratingHistory or {}
db.aggregates.buildEffectiveness = db.aggregates.buildEffectiveness or {}
db.aggregates.specDamageSignatures = db.aggregates.specDamageSignatures or {}
db.aggregates.soloShuffleSpecStats = db.aggregates.soloShuffleSpecStats or {}
db.aggregates.bgBlitzSpecStats = db.aggregates.bgBlitzSpecStats or {}
db.aggregates.openerSequenceEffectiveness = db.aggregates.openerSequenceEffectiveness or {}
db.aggregates.comps = db.aggregates.comps or {}
db.aggregates.soloShuffleHealerStats = db.aggregates.soloShuffleHealerStats or {}
db.aggregates.matchupArchetypes = db.aggregates.matchupArchetypes or {}
db.aggregates.openers = db.aggregates.openers or {}
db.aggregates.matchupMemory = db.aggregates.matchupMemory or {}
db.aggregates.duelSeries = db.aggregates.duelSeries or {}
db.aggregates.metricBaselines = db.aggregates.metricBaselines or {}
db.dummyBenchmarks = db.dummyBenchmarks or {}
-- Build catalog — v7+. Indexed by canonical buildId.
db.buildCatalog = db.buildCatalog or { order = {}, byId = {} }
db.buildCatalog.order = db.buildCatalog.order or {}
db.buildCatalog.byId = db.buildCatalog.byId or {}
-- Per-character preferences (scope persistence, etc.) — v7+.
db.characterPrefs = db.characterPrefs or {}
db.suggestionCache = db.suggestionCache or { order = {}, bySessionId = {} }
db.suggestionCache.order = db.suggestionCache.order or {}
db.suggestionCache.bySessionId = db.suggestionCache.bySessionId or {}
db.maintenance = db.maintenance or {}
db.maintenance.totalRawEvents = db.maintenance.totalRawEvents or 0
db.maintenance.aggregateVersion = db.maintenance.aggregateVersion or 1
db.maintenance.warnings = db.maintenance.warnings or {}
db.maintenance.traceLog = db.maintenance.traceLog or {}
db.maintenance.stabilizationVersion = db.maintenance.stabilizationVersion or 0
end
local function buildAggregateBucket(kind, key, label)
return {
kind = kind,
key = key,
label = label or key,
fights = 0,
wins = 0,
losses = 0,
other = 0,
totalDuration = 0,
totalDamageDone = 0,
totalHealingDone = 0,
totalDamageTaken = 0,
totalDeaths = 0,
totalPressureScore = 0,
totalBurstScore = 0,
totalSurvivabilityScore = 0,
topSpells = {},
lastSessionId = nil,
lastUpdatedAt = nil,
}
end
local function updateTopSpells(bucket, session)
bucket.topSpells = bucket.topSpells or {}
for spellId, aggregate in pairs(session.spells or {}) do
local spellBucket = bucket.topSpells[spellId]
if not spellBucket then
spellBucket = {
spellId = spellId,
totalDamage = 0,
totalHealing = 0,
casts = 0,
hits = 0,
}
bucket.topSpells[spellId] = spellBucket
end
spellBucket.totalDamage = spellBucket.totalDamage + (aggregate.totalDamage or 0)
spellBucket.totalHealing = spellBucket.totalHealing + (aggregate.totalHealing or 0)
spellBucket.casts = spellBucket.casts + (aggregate.castCount or 0)
spellBucket.hits = spellBucket.hits + (aggregate.hitCount or 0)
end
end
local function applySessionToBucket(bucket, session)
bucket.fights = bucket.fights + 1
bucket.totalDuration = bucket.totalDuration + (session.duration or 0)
bucket.totalDamageDone = bucket.totalDamageDone + (session.totals.damageDone or 0)
bucket.totalHealingDone = bucket.totalHealingDone + (session.totals.healingDone or 0)
bucket.totalDamageTaken = bucket.totalDamageTaken + (session.totals.damageTaken or 0)
-- session.totals is always initialised in CreateSession; no 2-level guard needed.
-- session.survival and session.metrics use 2-level guards as a schema-migration
-- safety net for sessions persisted before those fields were guaranteed.
bucket.totalDeaths = bucket.totalDeaths + ((session.survival and session.survival.deaths) or 0)
bucket.totalPressureScore = bucket.totalPressureScore + ((session.metrics and session.metrics.pressureScore) or 0)
bucket.totalBurstScore = bucket.totalBurstScore + ((session.metrics and session.metrics.burstScore) or 0)
bucket.totalSurvivabilityScore = bucket.totalSurvivabilityScore + ((session.metrics and session.metrics.survivabilityScore) or 0)
bucket.lastSessionId = session.id
bucket.lastUpdatedAt = session.timestamp
local resultBucket = Helpers.GetResultBucket(session.result)
bucket[resultBucket] = (bucket[resultBucket] or 0) + 1
updateTopSpells(bucket, session)
end
local function getOrCreateBucket(container, kind, key, label)
-- Arena opponent GUIDs/names are 'secret strings' — WoW marks them so addons
-- can't read their content. tostring() propagates the secret flag rather than
-- stripping it. Concatenation with "" forces a fresh plain-Lua-string
-- allocation; if that also throws, fall back to "unknown".
-- Both key AND label must be sanitized: key is used as a table index (crashes
-- on secret compare), label is stored in bucket.label and used by UI SetText.
local okKey, safeKey = pcall(function() return (key or "") .. "" end)
local okCmp, notEmpty = pcall(function() return safeKey ~= "" end)
key = (okKey and okCmp and notEmpty and safeKey) or "unknown"
if Helpers.IsBlank(key) then
key = "unknown"
end
local okLabel, rawLabel = pcall(function() return (label or "") .. "" end)
local okLabelCmp, labelNotEmpty = pcall(function() return rawLabel ~= "" end)
local safeLabel = (okLabel and okLabelCmp and labelNotEmpty and rawLabel) or key
container[key] = container[key] or buildAggregateBucket(kind, key, safeLabel)
return container[key]
end
local function getPrimaryOpponent(session)
return session.primaryOpponent
end
local function buildCharacterKey(guid, name, realm)
if guid and guid ~= "" then
return guid
end
local resolvedName = name or "unknown"
local resolvedRealm = realm or ""
if resolvedRealm ~= "" then
return string.format("%s@%s", resolvedName, resolvedRealm)
end
return resolvedName
end
local function getSessionCharacterKey(session)
local snapshot = session and session.playerSnapshot or nil
if not snapshot then
return "unknown"
end
return buildCharacterKey(snapshot.guid, snapshot.name, snapshot.realm)
end
local function getSessionCharacterLabel(session)
local snapshot = session and session.playerSnapshot or nil
if not snapshot then
return "Unknown Character"
end
local name = snapshot.name or "Unknown"
local realm = snapshot.realm or ""
if realm ~= "" then
return string.format("%s-%s", name, realm)
end
return name
end
local function buildCharacterRef(guid, name, realm)
return {
key = buildCharacterKey(guid, name, realm),
guid = guid,
name = name,
realm = realm,
}
end
local function matchesCharacter(session, characterRef)
if not characterRef then
return true
end
local snapshot = session and session.playerSnapshot or nil
if not snapshot then
return false
end
local sessionKey = getSessionCharacterKey(session)
if sessionKey == characterRef.key then
return true
end
local sessionName = tostring(snapshot.name or "")
local sessionRealm = tostring(snapshot.realm or "")
local refName = tostring(characterRef.name or "")
local refRealm = tostring(characterRef.realm or "")
if sessionName ~= "" and refName ~= "" and string.lower(sessionName) == string.lower(refName) then
if sessionRealm == "" or refRealm == "" or string.lower(sessionRealm) == string.lower(refRealm) then
return true
end
end
return false
end
local function updateDummyBenchmarkRecord(container, session)
if session.context ~= Constants.CONTEXT.TRAINING_DUMMY then
return
end
local opponent = getPrimaryOpponent(session) or {}
local dummyInfo = opponent.creatureId and ns.StaticPvpData and ns.StaticPvpData.GetDummyInfo and ns.StaticPvpData.GetDummyInfo(opponent.creatureId) or nil
local buildHash = session.playerSnapshot and session.playerSnapshot.buildHash or "unknown"
local specId = session.playerSnapshot and session.playerSnapshot.specId or 0
local key = table.concat({
tostring(getSessionCharacterKey(session)),
tostring(buildHash),
tostring(specId),
tostring(dummyInfo and dummyInfo.benchmarkGroup or opponent.name or "dummy"),
tostring(opponent.level or 0),
}, "#")
local benchmark = container[key]
if not benchmark then
benchmark = {
key = key,
characterKey = getSessionCharacterKey(session),
characterName = getSessionCharacterLabel(session),
buildHash = buildHash,
specId = specId,
dummyName = dummyInfo and dummyInfo.displayName or opponent.name or "Training Dummy",
dummyFamily = dummyInfo and dummyInfo.family or "unknown",
benchmarkGroup = dummyInfo and dummyInfo.benchmarkGroup or (opponent.name or "dummy"),
dummyLevel = opponent.level or 0,
sessions = 0,
totalSustainedDps = 0,
totalBurstDps = 0,
totalOpenerDamage = 0,
totalRotationScore = 0,
lastSessionId = nil,
lastUpdatedAt = nil,
}
container[key] = benchmark
end
benchmark.sessions = benchmark.sessions + 1
benchmark.totalSustainedDps = benchmark.totalSustainedDps + ((session.metrics and session.metrics.sustainedDps) or 0)
benchmark.totalBurstDps = benchmark.totalBurstDps + ((session.metrics and session.metrics.burstDps) or 0)
benchmark.totalOpenerDamage = benchmark.totalOpenerDamage + ((session.metrics and session.metrics.openerDamage) or 0)
benchmark.totalRotationScore = benchmark.totalRotationScore + ((session.metrics and session.metrics.rotationalConsistencyScore) or 0)
benchmark.lastSessionId = session.id
benchmark.lastUpdatedAt = session.timestamp
end
local function updateDummyBenchmark(db, session)
updateDummyBenchmarkRecord(db.dummyBenchmarks, session)
end
local function updateAggregateContainerForSession(aggregates, session, kindFilter)
local opponent = getPrimaryOpponent(session)
if (not kindFilter or kindFilter == Constants.AGGREGATE_KIND.OPPONENT) and opponent then
local opponentKey = opponent.guid or opponent.name or "unknown"
local opponentLabel = opponent.name or opponent.guid or "Unknown Opponent"
applySessionToBucket(getOrCreateBucket(aggregates.opponents, Constants.AGGREGATE_KIND.OPPONENT, opponentKey, opponentLabel), session)
end
if (not kindFilter or kindFilter == Constants.AGGREGATE_KIND.CLASS) and opponent and opponent.classFile then
applySessionToBucket(getOrCreateBucket(aggregates.classes, Constants.AGGREGATE_KIND.CLASS, opponent.classFile, opponent.className or opponent.classFile), session)
end
if (not kindFilter or kindFilter == Constants.AGGREGATE_KIND.SPEC) and opponent and opponent.specId then
local specKey = tostring(opponent.specId)
local specLabel = opponent.specName or specKey
applySessionToBucket(getOrCreateBucket(aggregates.specs, Constants.AGGREGATE_KIND.SPEC, specKey, specLabel), session)
end
local buildHash = session.playerSnapshot and session.playerSnapshot.buildHash or "unknown"
if not kindFilter or kindFilter == Constants.AGGREGATE_KIND.BUILD then
local buildBucket = getOrCreateBucket(aggregates.builds, Constants.AGGREGATE_KIND.BUILD, buildHash, buildHash)
applySessionToBucket(buildBucket, session)
-- Stamp human-readable snapshot metadata once so the UI can show spec
-- name + PvP talents instead of the raw hash. Only written on first
-- encounter; the hash guarantees the build never changes under this key.
local snap = session.playerSnapshot
if snap and not buildBucket.specName then
buildBucket.specId = snap.specId
buildBucket.specName = snap.specName
buildBucket.classFile = snap.classFile
buildBucket.pvpTalents = snap.pvpTalents and Helpers.CopyTable(snap.pvpTalents, false) or {}
buildBucket.heroTalentSpecId = snap.heroTalentSpecId
end
-- Build confidence score: sample-size-corrected win rate.
-- Formula: min(1.0, fights / targetSample) * winRate
-- Prevents small-sample builds from outranking stable high-fight builds.
local thresholds = ns.StaticPvpData and ns.StaticPvpData.METRIC_THRESHOLDS
local targetSample = (thresholds and thresholds.minSamples and thresholds.minSamples.buildFull)
or 30
local winRate = buildBucket.fights > 0 and (buildBucket.wins / buildBucket.fights) or 0
local sampleFactor = math.min(1.0, buildBucket.fights / targetSample)
buildBucket.confidenceScore = sampleFactor * winRate
end
local contextKey = session.context
if session.subcontext then
contextKey = string.format("%s:%s", session.context, session.subcontext)
end
if not kindFilter or kindFilter == Constants.AGGREGATE_KIND.CONTEXT then
applySessionToBucket(getOrCreateBucket(aggregates.contexts, Constants.AGGREGATE_KIND.CONTEXT, contextKey, contextKey), session)
end
local dateKey = Helpers.GetDateKey(session.timestamp)
if not kindFilter or kindFilter == Constants.AGGREGATE_KIND.DAILY then
applySessionToBucket(getOrCreateBucket(aggregates.daily, Constants.AGGREGATE_KIND.DAILY, dateKey, dateKey), session)
end
local weekKey = Helpers.GetWeekKey(session.timestamp)
if not kindFilter or kindFilter == Constants.AGGREGATE_KIND.WEEKLY then
applySessionToBucket(getOrCreateBucket(aggregates.weekly, Constants.AGGREGATE_KIND.WEEKLY, weekKey, weekKey), session)
end
end
function CombatStore:Initialize()
CombatAnalyticsDB = CombatAnalyticsDB or buildEmptyDb()
ensureDefaults(CombatAnalyticsDB)
if (CombatAnalyticsDB.maintenance.stabilizationVersion or 0) < 1 then
CombatAnalyticsDB.settings.showMinimapButton = false
CombatAnalyticsDB.settings.showSummaryAfterCombat = false
CombatAnalyticsDB.maintenance.stabilizationVersion = 1
end
-- A single corrupt legacy session record must not abort CombatStore
-- initialization (which would leave persistence/aggregates dead for the
-- whole play session). Degrade gracefully instead.
local ok, err = pcall(function() self:MigrateSchema(CombatAnalyticsDB) end)
if not ok then
CombatAnalyticsDB.maintenance = CombatAnalyticsDB.maintenance or {}
CombatAnalyticsDB.maintenance.migrationError = tostring(err)
if ns.Addon and ns.Addon.Warn then
ns.Addon:Warn("CombatStore: schema migration failed (%s); continuing with existing data.", tostring(err))
end
end
end
-- MigrateSchema applies incremental upgrades to saved data.
-- Design rules:
-- • Each version gate is a forward-only, idempotent migration.
-- • Never backfill derived fields that require live API data (GUIDs, specs).
-- • Mark legacy sessions with version metadata so analytics can down-grade
-- confidence rather than silently produce wrong results.
-- • Bump Constants.SCHEMA_VERSION whenever a new gate is added.
function CombatStore:MigrateSchema(db)
local version = db.schemaVersion or 0
-- Downgrade guard: if the DB was written by a NEWER addon build, its
-- session/aggregate shapes are unknown to these v<=SCHEMA_VERSION gates.
-- Running old aggregate code over future-schema data silently corrupts
-- it. Refuse to migrate (and flag it) rather than mutate forward data.
local target = (Constants and Constants.SCHEMA_VERSION) or version
if version > target then
db.maintenance = db.maintenance or {}
db.maintenance.downgraded = true
if ns.Addon and ns.Addon.Warn then
ns.Addon:Warn(
"CombatAnalytics: saved data is from a newer version (v%s > v%s). "
.. "Skipping migration to avoid corrupting it; some views may be limited.",
tostring(version), tostring(target))
end
return
end
-- v1 → v2: introduce rawEventVersion field, arena slot metadata, and
-- attribution stub on existing sessions. No data backfill — sessions
-- captured under v1 are marked as legacy raw events so confidence labels
-- reflect actual capture quality.
if version < 2 then
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
-- Tag raw event format; v1 sessions lack absorbed/resisted
-- fields in SWING_DAMAGE and several other subevent fields.
if not session.rawEventVersion then
session.rawEventVersion = 1
end
-- Stub arena block; will be populated by ArenaRoundTracker
-- on sessions created under schema v2+.
if session.arena == nil then
session.arena = false -- false = not an arena session / unknown
end
-- Stub attribution block.
if session.attribution == nil then
session.attribution = false -- false = not yet computed
end
end
end
db.schemaVersion = 2
end
-- v2 → v3: introduce rating, CC, and post-match score fields on sessions,
-- and initialise new aggregate buckets for rating history, build
-- effectiveness, and spec damage signatures.
if version < 3 then
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
if session.ratingSnapshot == nil then
session.ratingSnapshot = false
end
if session.ccReceived == nil then
session.ccReceived = false
end
if session.postMatchScores == nil then
session.postMatchScores = false
end
if session.teamRatingInfo == nil then
session.teamRatingInfo = false
end
if session.isRated == nil then
session.isRated = false
end
end
end
if db.aggregates.ratingHistory == nil then
db.aggregates.ratingHistory = {}
end
if db.aggregates.buildEffectiveness == nil then
db.aggregates.buildEffectiveness = {}
end
if db.aggregates.specDamageSignatures == nil then
db.aggregates.specDamageSignatures = {}
end
db.schemaVersion = 3
end
-- v3 → v4: add fields for loss-of-control tracking, interrupt log,
-- kill timings, comp analysis, streak context, and arena DR/talent data.
-- New aggregate bucket: comps (opponent team composition win rates).
if version < 4 then
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
if session.lossOfControl == nil then
session.lossOfControl = false
end
if session.interruptLog == nil then
session.interruptLog = false
end
if session.killTimings == nil then
session.killTimings = false
end
if session.opponentCompKey == nil then
session.opponentCompKey = false
end
if session.streakContext == nil then
session.streakContext = false
end
end
end
if db.aggregates.comps == nil then
db.aggregates.comps = {}
end
db.schemaVersion = 4
end
-- v4 → v5: greed death / defensive economy / kill window fields
if version < 5 then
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
session.survival = session.survival or {}
session.survival.greedDeaths = session.survival.greedDeaths or 0
session.survival.defensiveOverlapCount = session.survival.defensiveOverlapCount or 0
session.survival.burstWasteCount = session.survival.burstWasteCount or 0
session.killWindows = session.killWindows or {}
session.killWindowConversions = session.killWindowConversions or 0
end
end
db.schemaVersion = 5
end
-- v5 → v6: Midnight compliance overhaul — add timelineEvents, provenance,
-- fieldConfidence on arena slots, new aggregate buckets, and map old
-- ANALYSIS_CONFIDENCE labels to the new SESSION_CONFIDENCE enum.
if version < 6 then
-- Confidence label migration map (old → new)
local confidenceMap = {
full_raw = Constants.SESSION_CONFIDENCE.LEGACY_CLEU_IMPORT,
enriched = Constants.SESSION_CONFIDENCE.LEGACY_CLEU_IMPORT,
restricted_raw = Constants.SESSION_CONFIDENCE.STATE_PLUS_DAMAGE_METER,
degraded = Constants.SESSION_CONFIDENCE.DAMAGE_METER_ONLY,
partial_roster = Constants.SESSION_CONFIDENCE.PARTIAL_ROSTER,
unknown = Constants.SESSION_CONFIDENCE.ESTIMATED,
}
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
-- T006: Add timelineEvents and provenance to all existing sessions
if session.timelineEvents == nil then
session.timelineEvents = {}
end
if session.provenance == nil then
session.provenance = {}
end
-- T007: Map old confidence labels to new SessionConfidence
if session.captureQuality then
local oldConf = session.captureQuality.confidence
if oldConf and confidenceMap[oldConf] then
session.captureQuality.confidence = confidenceMap[oldConf]
end
end
-- T008: Add fieldConfidence to existing arena slot records
if type(session.arena) == "table" then
local rounds = session.arena.rounds
if type(rounds) == "table" then
for _, round in pairs(rounds) do
local slots = round and round.slots
if type(slots) == "table" then
for _, slot in pairs(slots) do
if type(slot) == "table" and not slot.fieldConfidence then
local fc = {}
-- Infer initial confidence from existing data
if slot.prepSpecId then
fc.spec = "prep"
fc.class = "prep"
end
if slot.guid then
fc.guid = "visible"
fc.name = "visible"
if not fc.class then
fc.class = "visible"
end
end
if slot.pvpTalents then
fc.pvpTalents = "inspect"
fc.talentImportString = "inspect"
fc.spec = "inspect" -- upgrade from prep
end
slot.fieldConfidence = fc
end
end
end
end
end
end
end
end
-- T009: Initialize new aggregate buckets
db.aggregates.openers = db.aggregates.openers or {}
db.aggregates.matchupMemory = db.aggregates.matchupMemory or {}
db.aggregates.duelSeries = db.aggregates.duelSeries or {}
db.schemaVersion = 6
end
-- v6 → v7: Build Comparator Overhaul — initialize build catalog, stamp
-- canonical buildId / loadoutId onto every existing session snapshot, upsert
-- build profiles, and merge legacy hash values.
-- T024 / T025 / T026
if version < 7 then
-- (1) Ensure catalog and prefs structures exist (may already exist from
-- ensureDefaults, but be defensive here too).
db.buildCatalog = db.buildCatalog or { order = {}, byId = {} }
db.buildCatalog.order = db.buildCatalog.order or {}
db.buildCatalog.byId = db.buildCatalog.byId or {}
db.characterPrefs = db.characterPrefs or {}
-- T025: Collect legacy hashes per buildId so we can consolidate them
-- after all sessions are stamped (belt-and-suspenders merge).
local legacyHashesMap = {} -- buildId → { hash, ... }
local buildSessionCounts = {} -- buildId → count
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
local snap = session.playerSnapshot
-- T026: Idempotence guard — skip if already stamped.
if snap and snap.buildId then
-- Already migrated; still count for sessionCount accuracy.
local bid = snap.buildId
buildSessionCounts[bid] = (buildSessionCounts[bid] or 0) + 1
local legacyHash = snap.buildHash
if legacyHash then
legacyHashesMap[bid] = legacyHashesMap[bid] or {}
local seen = false
for _, h in ipairs(legacyHashesMap[bid]) do
if h == legacyHash then seen = true; break end
end
if not seen then
legacyHashesMap[bid][#legacyHashesMap[bid] + 1] = legacyHash
end
end
elseif snap and (snap.talentNodes or snap.classId) then
-- T024: Normal session with snapshot data — stamp buildId.
local ok, bid = pcall(function() return ns.BuildHash.ComputeBuildId(snap) end)
if not ok or not bid then
bid = nil
end
local ok2, lid = pcall(function() return ns.BuildHash.ComputeLoadoutId(snap) end)
if not ok2 then lid = nil end
if bid then
snap.buildId = bid
snap.loadoutId = lid
snap.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.FRESH
buildSessionCounts[bid] = (buildSessionCounts[bid] or 0) + 1
-- T025: Collect the old legacy hash for later consolidation.
local legacyHash = snap.buildHash
if legacyHash then
legacyHashesMap[bid] = legacyHashesMap[bid] or {}
local seen = false
for _, h in ipairs(legacyHashesMap[bid]) do
if h == legacyHash then seen = true; break end
end
if not seen then
legacyHashesMap[bid][#legacyHashesMap[bid] + 1] = legacyHash
end
end
else
-- T026: Partial-data session — assign deterministic fallback buildId.
local fallbackSuffix = snap.buildHash or sessionId
bid = "legacy-partial-" .. string.sub(tostring(fallbackSuffix), 1, 8)
snap.buildId = bid
snap.loadoutId = nil
snap.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.DEGRADED
snap.isMigrated = true
snap.isMigratedWithWarnings = true
buildSessionCounts[bid] = (buildSessionCounts[bid] or 0) + 1
-- Record warning
db.maintenance = db.maintenance or {}
db.maintenance.buildMigrationWarnings = db.maintenance.buildMigrationWarnings or {}
local warn = db.maintenance.buildMigrationWarnings
warn[#warn + 1] = {
sessionId = sessionId,
reason = "partial_snapshot_no_talent_data",
fallbackBuildId = bid,
}
end
else
-- T026: Nil snapshot — assign sentinel fallback.
local bid = "legacy-partial-" .. string.sub(tostring(sessionId), 1, 8)
snap = snap or {}
snap.buildId = bid
snap.loadoutId = nil
snap.snapshotFreshness = Constants.SNAPSHOT_FRESHNESS.DEGRADED
snap.isMigrated = true
snap.isMigratedWithWarnings = true
session.playerSnapshot = snap
buildSessionCounts[bid] = (buildSessionCounts[bid] or 0) + 1
db.maintenance = db.maintenance or {}
db.maintenance.buildMigrationWarnings = db.maintenance.buildMigrationWarnings or {}
local warn = db.maintenance.buildMigrationWarnings
warn[#warn + 1] = {
sessionId = sessionId,
reason = "nil_player_snapshot",
fallbackBuildId = bid,
}
end
end
end
-- (2) Upsert one BuildProfile per unique buildId.
for bid, sessionCount in pairs(buildSessionCounts) do
local existing = db.buildCatalog.byId[bid]
if not existing then
-- Collect one representative snapshot for this buildId.
local repSnap = nil
for _, sessionId in ipairs(db.combats.order or {}) do
local s = db.combats.byId[sessionId]
if s and s.playerSnapshot and s.playerSnapshot.buildId == bid then
repSnap = s.playerSnapshot
break
end
end
local charKey = nil
if repSnap and repSnap.name and repSnap.realm then
charKey = repSnap.name .. "-" .. repSnap.realm
end
local profile = {
buildId = bid,
buildIdentityVersion = Constants.BUILD_IDENTITY_VERSION,
classId = repSnap and repSnap.classId,
specId = repSnap and repSnap.specId,
heroTalentSpecId = repSnap and repSnap.heroTalentSpecId,
talentSignature = "",
pvpTalentSignature = "",
displayNames = { "Migrated Build" },
associatedLoadoutIds = {},
legacyBuildHashes = legacyHashesMap[bid] or {},
sessionCount = sessionCount,
characterKey = charKey,
isCurrentBuild = false,
isMigrated = true,
isMigratedWithWarnings = (repSnap and repSnap.isMigratedWithWarnings) or false,
isLowConfidence = sessionCount < Constants.CONFIDENCE_TIER_THRESHOLDS.LOW_MIN,
firstSeenAt = 0,
lastSeenAt = 0,
}
-- Talent and PvP signature from snapshot
if repSnap and repSnap.talentNodes then
local parts = {}
for _, node in ipairs(repSnap.talentNodes) do
parts[#parts + 1] = table.concat({
tostring(node.nodeId or 0),
tostring(node.entryId or 0),
tostring(node.activeRank or 0),
}, ":")
end
table.sort(parts)
profile.talentSignature = table.concat(parts, "|")
end
if repSnap and repSnap.pvpTalents then
local sorted = {}
for _, v in ipairs(repSnap.pvpTalents) do
sorted[#sorted + 1] = tostring(v)
end
table.sort(sorted)
profile.pvpTalentSignature = table.concat(sorted, ",")
end
db.buildCatalog.byId[bid] = profile
db.buildCatalog.order[#db.buildCatalog.order + 1] = bid
else
-- T025: Merge any newly found legacy hashes into the existing profile.
existing.legacyBuildHashes = existing.legacyBuildHashes or {}
for _, h in ipairs(legacyHashesMap[bid] or {}) do
local found = false
for _, eh in ipairs(existing.legacyBuildHashes) do
if eh == h then found = true; break end
end
if not found then
existing.legacyBuildHashes[#existing.legacyBuildHashes + 1] = h
end
end
-- Recalculate session count from actual tally
existing.sessionCount = sessionCount
end
end
db.schemaVersion = 7
ns.Addon:Trace("migration.v7.complete", {
profilesCreated = #db.buildCatalog.order,
})
end
-- v7 → v8: add stat-profile fields to build catalog entries and
-- damage-import-status fields to existing sessions. All additive.
if version < 8 then
-- Extend each build catalog entry with stat-profile fields.
for _, bid in ipairs(db.buildCatalog.order or {}) do
local p = db.buildCatalog.byId[bid]
if p then
if p.latestStatProfile == nil then
p.latestStatProfile = false
end
if p.statProfiles == nil then
p.statProfiles = {}
end
if p.lastCapturedAt == nil then
p.lastCapturedAt = false
end
end
end
-- Extend each session with import-status fields.
local sessionCount = 0
for _, sessionId in ipairs(db.combats.order or {}) do
local s = db.combats.byId[sessionId]
if s then
s.importedTotals = s.importedTotals or {}
if s.importedTotals.importStatus == nil then
s.importedTotals.importStatus = false
end
if s.importedTotals.importDiagnostics == nil then
s.importedTotals.importDiagnostics = false
end
if s.importedTotals.totalAuthority == nil then
s.importedTotals.totalAuthority = false
end
sessionCount = sessionCount + 1
end
end
db.schemaVersion = 8
ns.Addon:Trace("migration.v8.complete", {
buildProfiles = #(db.buildCatalog.order or {}),
sessions = sessionCount,
})
end
-- v8 → v9: PvP Improvements — add metric baselines, comp aggregates,
-- rating history, absorbs, activeTime, effectiveDamageDone, and
-- Solo Shuffle round-level fields.
if version < 9 then
-- Initialize new aggregate buckets
db.aggregates.metricBaselines = db.aggregates.metricBaselines or {}
-- comps bucket may already exist from v4; ensure it does
db.aggregates.comps = db.aggregates.comps or {}
-- ratingHistory may already exist from v3; ensure it does
db.aggregates.ratingHistory = db.aggregates.ratingHistory or {}
-- Stub new session-level fields on existing sessions
for _, sessionId in ipairs(db.combats.order or {}) do
local s = db.combats.byId[sessionId]
if s then
if s.activeTime == nil then
s.activeTime = false
end
if s.effectiveDamageDone == nil then
s.effectiveDamageDone = false
end
if s.absorbs == nil then
s.absorbs = false
end
if s.ratingBefore == nil then
s.ratingBefore = false
end
if s.ratingAfter == nil then
s.ratingAfter = false
end
if s.mmrBefore == nil then
s.mmrBefore = false
end
if s.mmrAfter == nil then
s.mmrAfter = false
end
-- Ensure arena.rounds is available for Solo Shuffle sessions
if type(s.arena) == "table" and s.arena.rounds == nil then
s.arena.rounds = {}
end
end
end
db.schemaVersion = 9
ns.Addon:Trace("migration.v9.complete", {
sessions = #(db.combats.order or {}),
})
end
if version < 10 then
-- v10: per-metric provenance (session.metrics.provenance).
-- No backfill is possible: provenance records where a metric's inputs
-- came from, and that source information is not recoverable from a
-- stored session after the fact. Old sessions simply lack the table;
-- SuggestionEngine.metricConfidence and SuggestionsView.metricConfidenceTag
-- both nil-guard a missing provenance table (falling back to UNKNOWN
-- and the session-wide trust card respectively). Only advance the
-- version so freshly finalized sessions start carrying provenance.
db.schemaVersion = 10
ns.Addon:Trace("migration.v10.complete", {
sessions = #(db.combats.order or {}),
})
end
-- Future migrations go here as additional `if version < N then` blocks.
-- T121: Post-migration validation for mixed-version datasets.
-- Ensures all sessions have required fields regardless of original schema version.
local validationErrors = 0
for _, sessionId in ipairs(db.combats.order or {}) do
local session = db.combats.byId[sessionId]
if session then
-- Ensure timelineEvents is always a table (never nil)
if type(session.timelineEvents) ~= "table" then
session.timelineEvents = {}
validationErrors = validationErrors + 1
end
-- Ensure provenance is always a table
if type(session.provenance) ~= "table" then
session.provenance = {}
validationErrors = validationErrors + 1
end
-- Ensure captureQuality has a confidence field
if not session.captureQuality then
session.captureQuality = { confidence = Constants.SESSION_CONFIDENCE.ESTIMATED }
validationErrors = validationErrors + 1
elseif not session.captureQuality.confidence then
session.captureQuality.confidence = Constants.SESSION_CONFIDENCE.ESTIMATED
validationErrors = validationErrors + 1
end
-- Ensure metrics is a table
if session.metrics == nil then
session.metrics = {}
end
-- Ensure totals is a table. SummaryView and other views deref
-- session.totals.* directly; a nil here aborts the whole render
-- and leaves the dashboard blank.
if session.totals == nil then
session.totals = {}
end
end
end
if validationErrors > 0 then
ns.Addon:Trace("migration.validation_fixes", { count = validationErrors })
end
end
function CombatStore:GetDB()
return CombatAnalyticsDB
end
function CombatStore:CreateMatchRecord(context, subcontext)
local db = self:GetDB()
local id = Helpers.GenerateId("match")
local zoneName, mapId = ns.ApiCompat.GetCurrentZoneName()
local record = {
id = id,
context = context,
subcontext = subcontext,