-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPositionSort.lua
More file actions
3723 lines (3500 loc) · 137 KB
/
Copy pathPositionSort.lua
File metadata and controls
3723 lines (3500 loc) · 137 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
---------------------------------------------------------------------------
-- PugzRaidTools - Exact Position Sort
--
-- Supported force-position path used by Shift + Left Click and the Raid
-- Groups "Force Positions" option. Membership and exact within-group
-- positions are planned together, issued in safe batches, and verified
-- against authoritative roster fingerprints after every dependent stage.
---------------------------------------------------------------------------
local _, PRT = ...
local RR_NAME = PRT.RR_NAME
local RR_SUBGROUP = PRT.RR_SUBGROUP
local RR_INDEX = PRT.RR_INDEX
local RR_LOCKED = PRT.RR_LOCKED
local RR_START = PRT.RR_START
-- Position cycles are pipelined into identity-disjoint stages. This is the
-- maximum number of independent calls sent in one acknowledged stage.
local MAX_CYCLES_PER_WAVE = 8
local MAX_POSITION_CYCLES = 40
local MAX_POSITION_WAVES = 40
local MAX_POSITION_STAGES = 240
local MAX_GROUP_PASSES = 3
local GROUP_SETTLE_DELAY = 0.50
local POSITION_SETTLE_DELAY = 0.50
local ACK_POLL_INTERVAL = 0.10
-- Once the expected fingerprint is visible, yield to the next frame before
-- resolving fresh indices. C_Timer.After(0) preserves the event boundary
-- without imposing a fixed delay.
local NEXT_STAGE_DELAY = 0
-- Live Classic tests have shown authoritative roster changes arriving more
-- than four seconds after a SwapRaidSubgroup burst. A longer watchdog does
-- not slow successful stages: events and polling still acknowledge them as
-- soon as they appear.
local WAIT_TIMEOUT = 8.00
-- Classic accepted 50 group actions and rejected the 51st in live testing.
-- Use the full observed allowance, while still aging calls over a
-- conservative rolling window before starting a whole stage.
local GROUP_ACTION_LIMIT = 50
local GROUP_ACTION_WINDOW = 10.50
local GROUP_ACTION_GUARD = 0.20
-- Candidate ranking predicts wall time with a deliberately middling
-- acknowledgement latency. The exact value is less important than modelling
-- the rolling-window pause that a sequence of burst sizes will cause.
local PREDICTED_ACK_SECONDS = 1.50
local PREDICTED_HANDOFF_SECONDS = 0.03
-- Candidate evaluation gets a very small exact-scheduler budget; the selected
-- live route gets a larger final attempt before execution. Both fall back to
-- the proven greedy schedule on timeout or infeasibility.
local POSITION_CANDIDATE_EXACT_BUDGET_MS = 8
local POSITION_FINAL_EXACT_BUDGET_MS = 75
-- Joint membership/position route search. Generation uses cheap analytical
-- scoring and reserves the remainder of the roughly one-second budget for
-- fully simulated finalists.
local MEMBERSHIP_SEARCH_BUDGET_MS = 900
local MEMBERSHIP_GENERATION_BUDGET_MS = 800
-- Live validation showed that dependency-staged 48-call routes took longer
-- than the proven one-batch MRT route (10 acknowledgement stages versus 7).
-- Keep the research implementation available, but do not spend click-time
-- generating or executing it until a route can match MRT's stage count.
local ENABLE_DEEP_ROUTE_RESEARCH = false
local MAX_MEMBERSHIP_CANDIDATES = 4096
local MAX_MEMBERSHIP_FINALISTS = 64
local MAX_MRT_PERMUTATION_CANDIDATES = 512
local UNIFIED_BEAM_WIDTH = 128
local UNIFIED_BEAM_PIVOT_CHOICES = 4
local UNIFIED_BEAM_EXTRA_CALLS = 4
local UNIFIED_BEAM_LOWER_BOUND_SLACK = 8
local MAX_UNIFIED_SHADOW_FINALISTS = 512
local MAX_LOG_LINES = 2000
local function Now()
if GetTime then return GetTime() end
return 0
end
local function PlanningNowMs()
if debugprofilestop then return debugprofilestop() end
return Now() * 1000
end
local function CopyArray(source)
local result = {}
for i = 1, #(source or {}) do result[i] = source[i] end
return result
end
local function CopyGroups(groups)
local result = {}
for group = 1, 8 do
result[group] = CopyArray(groups and groups[group] or {})
end
return result
end
local function GroupFingerprint(groups)
local parts = {}
for group = 1, 8 do
parts[group] = table.concat(groups[group] or {}, ",")
end
return table.concat(parts, "|")
end
local function GroupSummary(groups)
local parts = {}
for group = 1, 8 do
parts[#parts + 1] = ("G%d=[%s]"):format(
group,
table.concat(groups[group] or {}, ", "))
end
return table.concat(parts, "\n")
end
---------------------------------------------------------------------------
-- Per-run logger
---------------------------------------------------------------------------
function PRT:ResetPositionSortLog(label)
self._positionSortLog = {
startedAt = Now(),
label = label or "Position sort",
lines = {},
truncated = false,
stats = {
status = "running",
apiCalls = 0,
setCalls = 0,
swapCalls = 0,
groupApiCalls = 0,
positionApiCalls = 0,
groupPasses = 0,
membershipStages = 0,
positionWaves = 0,
positionStages = 0,
positionCycles = 0,
rosterEvents = 0,
replans = 0,
stageRetries = 0,
},
}
self:PositionSortLog("BEGIN %s", label or "Position sort")
end
function PRT:PositionSortLog(formatText, ...)
local log = self._positionSortLog
if not log then
self:ResetPositionSortLog("Manual log")
log = self._positionSortLog
end
if #log.lines >= MAX_LOG_LINES then
if not log.truncated then
log.truncated = true
log.lines[#log.lines + 1] = "... log truncated ..."
end
return
end
local ok, message = pcall(string.format, tostring(formatText or ""), ...)
if not ok then message = tostring(formatText or "") end
local elapsed = math.max(
0, (log.endedAt or Now()) - (log.startedAt or Now()))
log.lines[#log.lines + 1] = ("%08.3f %s"):format(elapsed, message)
end
function PRT:GetPositionSortLogText()
local log = self._positionSortLog
if not log then
return "No position sort log has been recorded yet."
end
local stats = log.stats or {}
local lines = CopyArray(log.lines)
lines[#lines + 1] = ""
lines[#lines + 1] = "----- Summary -----"
lines[#lines + 1] = "Run: " .. tostring(log.label or "")
lines[#lines + 1] = "Status: " .. tostring(stats.status or "unknown")
lines[#lines + 1] = ("Elapsed: %.3fs"):format(
math.max(0, (log.endedAt or Now()) - (log.startedAt or Now())))
lines[#lines + 1] =
("API calls: %d total (%d SetRaidSubgroup, %d SwapRaidSubgroup)"):format(
stats.apiCalls or 0,
stats.setCalls or 0,
stats.swapCalls or 0)
lines[#lines + 1] =
("API calls by phase: %d membership, %d position"):format(
stats.groupApiCalls or 0,
stats.positionApiCalls or 0)
lines[#lines + 1] =
("Planning: %d group passes, %d membership stages, %d position pipelines, %d position stages, %d position cycles, %d replans, %d safe retries"):format(
stats.groupPasses or 0,
stats.membershipStages or 0,
stats.positionWaves or 0,
stats.positionStages or 0,
stats.positionCycles or 0,
stats.replans or 0,
stats.stageRetries or 0)
lines[#lines + 1] = ("GROUP_ROSTER_UPDATE events: %d"):format(
stats.rosterEvents or 0)
return table.concat(lines, "\n")
end
function PRT:ClearPositionSortLog()
if self._positionSortSession
and not self._positionSortSession.finished then
self:CancelPositionSort("the event log was cleared")
end
self:ResetPositionSortLog("Cleared")
self._positionSortLog.stats.status = "cleared"
self._positionSortLog.endedAt = Now()
end
function PRT:ShowPositionSortLog()
local W = self.UI
if not W or not W.CreateTextTransferPopup then
PRT.Print("The sort log window is not available yet.")
return
end
if not self._positionSortLogPopup then
self._positionSortLogPopup = W.CreateTextTransferPopup(
"PRT_PositionSortLogPopup",
{
title = "Position Sort Event Log",
instruction = "Select all with Ctrl+A, then copy with Ctrl+C.",
width = 720,
height = 560,
boxWidth = 696,
boxHeight = 470,
actionText = "Close",
})
end
self._positionSortLogPopup:Open({
title = "Position Sort Event Log",
text = self:GetPositionSortLogText(),
actionText = "Close",
})
end
local function LogApiCall(self, apiName, phase, details)
local log = self._positionSortLog
if not log then return end
local stats = log.stats
stats.apiCalls = stats.apiCalls + 1
if apiName == "SetRaidSubgroup" then
stats.setCalls = stats.setCalls + 1
else
stats.swapCalls = stats.swapCalls + 1
end
if phase == "membership" then
stats.groupApiCalls = stats.groupApiCalls + 1
elseif phase == "position" then
stats.positionApiCalls = stats.positionApiCalls + 1
end
self:PositionSortLog("API %03d %s %s %s",
stats.apiCalls, phase, apiName, details or "")
local history = self._groupActionTimes or {}
self._groupActionTimes = history
local now = Now()
local cutoff = now - GROUP_ACTION_WINDOW
while history[1] and history[1] <= cutoff do
table.remove(history, 1)
end
history[#history + 1] = now
end
function PRT:_PositionSortSetRaidSubgroup(raidIndex, subgroup, phase)
local name = GetRaidRosterInfo(raidIndex)
LogApiCall(self, "SetRaidSubgroup", phase,
("index=%s player=%s group=%s"):format(
tostring(raidIndex), tostring(name or "?"), tostring(subgroup)))
SetRaidSubgroup(raidIndex, subgroup)
end
function PRT:_PositionSortSwapRaidSubgroup(
firstIndex, secondIndex, phase, detail)
local firstName = GetRaidRosterInfo(firstIndex)
local secondName = GetRaidRosterInfo(secondIndex)
LogApiCall(self, "SwapRaidSubgroup", phase,
("index1=%s player1=%s index2=%s player2=%s%s"):format(
tostring(firstIndex), tostring(firstName or "?"),
tostring(secondIndex), tostring(secondName or "?"),
detail and (" " .. detail) or ""))
SwapRaidSubgroup(firstIndex, secondIndex)
end
---------------------------------------------------------------------------
-- Authoritative roster snapshots
---------------------------------------------------------------------------
function PRT:ReadPositionRosterSnapshot()
local snapshot = {
count = GetNumGroupMembers(),
members = {},
groups = {},
indexByKey = {},
groupByKey = {},
rankByKey = {},
keyByIndex = {},
leaderKey = nil,
}
for group = 1, 8 do snapshot.groups[group] = {} end
for raidIndex = 1, snapshot.count do
local name, rank, subgroup = GetRaidRosterInfo(raidIndex)
if name and subgroup and subgroup >= 1 and subgroup <= 8 then
local key = self:GetRaidMemberIdentityKey(raidIndex, name)
local entry = {
key = key,
name = name,
index = raidIndex,
rank = rank or 0,
group = subgroup,
}
snapshot.members[#snapshot.members + 1] = entry
snapshot.groups[subgroup][#snapshot.groups[subgroup] + 1] = key
snapshot.indexByKey[key] = raidIndex
snapshot.groupByKey[key] = subgroup
snapshot.rankByKey[key] = rank or 0
snapshot.keyByIndex[raidIndex] = key
if rank == 2 then snapshot.leaderKey = key end
end
end
-- Classic normally exposes the raid leader at index 1. Keep that
-- compatibility fallback if rank data is unavailable.
if not snapshot.leaderKey then
snapshot.leaderKey = snapshot.keyByIndex[1]
end
snapshot.fingerprint = GroupFingerprint(snapshot.groups)
return snapshot
end
local function BuildTargetGroupMap(target)
local result = {}
for group = 1, 8 do
for slot = 1, 5 do
local key = target[group][slot]
and target[group][slot][RR_NAME] or ""
if key ~= "" then result[key] = group end
end
end
return result
end
local function MembershipMatchesTarget(snapshot, target)
local targetGroups = BuildTargetGroupMap(target)
for key, desiredGroup in pairs(targetGroups) do
local currentGroup = snapshot.groupByKey[key]
if currentGroup and currentGroup ~= desiredGroup then
return false, ("%s is in G%d, expected G%d"):format(
key, currentGroup, desiredGroup)
end
end
return true
end
---------------------------------------------------------------------------
-- Position precomputation
---------------------------------------------------------------------------
local function BuildDesiredOrders(snapshot, target)
local desiredGroups = {}
local leaderAdjustment
for group = 1, 8 do
local desired = {}
local included = {}
-- Present composition members in saved slot order.
for slot = 1, 5 do
local key = target[group][slot]
and target[group][slot][RR_NAME] or ""
if key ~= ""
and snapshot.groupByKey[key] == group
and not included[key] then
desired[#desired + 1] = key
included[key] = true
end
end
-- Preserve non-composition players, but place them after target members.
for _, key in ipairs(snapshot.groups[group]) do
if not included[key] then
desired[#desired + 1] = key
included[key] = true
end
end
-- The game permits a raid leader to change subgroup, but always forces
-- them to the first occupied position of that subgroup. Membership is
-- handled before this phase; normalize the destination order to that
-- live rule instead of attempting an impossible position swap.
local leaderKey = snapshot.leaderKey
if leaderKey and snapshot.groupByKey[leaderKey] == group then
local desiredLeaderPosition
for position, key in ipairs(desired) do
if key == leaderKey then
desiredLeaderPosition = position
break
end
end
if desiredLeaderPosition
and desiredLeaderPosition ~= 1 then
table.remove(desired, desiredLeaderPosition)
table.insert(desired, 1, leaderKey)
leaderAdjustment = {
key = leaderKey,
group = group,
requested = desiredLeaderPosition,
forced = 1,
}
end
end
desiredGroups[group] = desired
end
return desiredGroups, leaderAdjustment
end
local function GroupsMatch(left, right)
for group = 1, 8 do
local a = left[group] or {}
local b = right[group] or {}
if #a ~= #b then return false end
for position = 1, #a do
if a[position] ~= b[position] then return false end
end
end
return true
end
local function SwapIdentityPositions(groups, firstKey, secondKey)
local firstGroup, firstPosition
local secondGroup, secondPosition
for group = 1, 8 do
for position, key in ipairs(groups[group] or {}) do
if key == firstKey then
firstGroup, firstPosition = group, position
elseif key == secondKey then
secondGroup, secondPosition = group, position
end
end
end
if not firstGroup or not secondGroup then return false end
groups[firstGroup][firstPosition], groups[secondGroup][secondPosition] =
groups[secondGroup][secondPosition], groups[firstGroup][firstPosition]
return true
end
local function GetCycleResources(cycle)
local resources = {}
for _, key in ipairs(cycle.memberKeys or {}) do
resources[key] = true
end
if cycle.bridgeKey then resources[cycle.bridgeKey] = true end
return resources
end
local function ResourcesOverlap(left, right)
for key in pairs(left or {}) do
if right and right[key] then return true end
end
return false
end
local function AssignCycleBridge(cycle, bridgeKey)
cycle.bridgeKey = bridgeKey
if cycle.steps and #cycle.steps >= 2 then
cycle.steps[1].secondKey = bridgeKey
cycle.steps[#cycle.steps].secondKey = bridgeKey
end
cycle.resources = GetCycleResources(cycle)
end
local function BuildBridgeCandidates(
cycle, snapshot, allCycleMembers)
local idle = {}
local participating = {}
for _, member in ipairs(snapshot.members or {}) do
local key = member.key
if key ~= snapshot.leaderKey
and member.group ~= cycle.group
and not cycle.memberKeySet[key] then
local list = allCycleMembers[key]
and participating or idle
list[#list + 1] = key
end
end
for _, key in ipairs(participating) do
idle[#idle + 1] = key
end
return idle
end
-- Assign longer cycles first so a late long cycle cannot create a mostly
-- empty tail. Bridge identities are selected globally: idle players are
-- preferred, while a member of another cycle is allowed only when the
-- resulting cycle lifetimes do not overlap.
local function BuildPipelinedStages(
cycles, maxCallsPerStage, snapshot)
local stages = {}
local stageUsedKeys = {}
local allCycleMembers = {}
for originalIndex, cycle in ipairs(cycles) do
cycle.originalIndex = originalIndex
cycle.memberKeySet = {}
for _, key in ipairs(cycle.memberKeys or {}) do
cycle.memberKeySet[key] = true
allCycleMembers[key] = true
end
end
table.sort(cycles, function(left, right)
local leftLength = #(left.steps or {})
local rightLength = #(right.steps or {})
if leftLength ~= rightLength then
return leftLength > rightLength
end
return (left.originalIndex or 0)
< (right.originalIndex or 0)
end)
for cycleIndex, cycle in ipairs(cycles) do
local bestBridge
local bestStartStage
local candidates = BuildBridgeCandidates(
cycle, snapshot, allCycleMembers)
for _, bridgeKey in ipairs(candidates) do
AssignCycleBridge(cycle, bridgeKey)
local earliestStage = 1
for priorIndex = 1, cycleIndex - 1 do
local prior = cycles[priorIndex]
if ResourcesOverlap(cycle.resources, prior.resources) then
earliestStage = math.max(
earliestStage, (prior.endStage or 0) + 1)
end
end
local startStage = earliestStage
while startStage <= MAX_POSITION_STAGES do
local fits = true
for localStage, step in ipairs(cycle.steps or {}) do
local stageIndex = startStage + localStage - 1
local entries = stages[stageIndex] or {}
local used = stageUsedKeys[stageIndex] or {}
if #entries >= maxCallsPerStage
or used[step.firstKey]
or used[step.secondKey] then
fits = false
break
end
end
if fits then
if not bestStartStage
or startStage < bestStartStage then
bestBridge = bridgeKey
bestStartStage = startStage
end
break
end
startStage = startStage + 1
end
end
if not bestBridge then
return nil,
"Pipelined position plan exceeded the 240-stage safety limit."
end
AssignCycleBridge(cycle, bestBridge)
cycle.startStage = bestStartStage
cycle.endStage =
bestStartStage + #(cycle.steps or {}) - 1
for localStage, step in ipairs(cycle.steps or {}) do
local stageIndex = bestStartStage + localStage - 1
stages[stageIndex] = stages[stageIndex] or {}
stageUsedKeys[stageIndex] =
stageUsedKeys[stageIndex] or {}
stages[stageIndex][#stages[stageIndex] + 1] = {
cycle = cycle,
cycleIndex = cycleIndex,
cycleStage = localStage,
firstKey = step.firstKey,
secondKey = step.secondKey,
}
stageUsedKeys[stageIndex][step.firstKey] = true
stageUsedKeys[stageIndex][step.secondKey] = true
end
end
return stages
end
local function PositionStageLowerBound(cycles, maxCallsPerStage)
local calls = 0
local longest = 0
for _, cycle in ipairs(cycles or {}) do
local length = #(cycle.steps or {})
calls = calls + length
longest = math.max(longest, length)
end
return math.max(
longest,
math.ceil(calls / math.max(1, maxCallsPerStage)))
end
local function ExactCycleStepPair(cycle, bridgeKey, localStage)
local steps = cycle.steps or {}
local step = steps[localStage]
if not step then return nil, nil end
if localStage == 1 or localStage == #steps then
return step.firstKey, bridgeKey
end
return step.firstKey, step.secondKey
end
local function IntervalsOverlap(
leftStart, leftEnd, rightStart, rightEnd)
return leftStart <= rightEnd and rightStart <= leftEnd
end
-- Find a schedule with a proven fixed stage count. Calls belonging to one
-- bridge cycle remain ordered but may leave gaps, while cycles sharing any
-- identity may not overlap in time. Those constraints preserve the already
-- validated bridge semantics while independent cycles fill empty slots.
local function BuildExactPipelinedStages(
cycles, maxCallsPerStage, snapshot, targetStageCount, deadlineMs)
local allCycleMembers = {}
local stageCounts = {}
local stageAssignments = {}
local bridgeAssignments = {}
local expanded = 0
local timedOut = false
local totalCalls = 0
for stage = 1, targetStageCount do
stageCounts[stage] = 0
end
for originalIndex, cycle in ipairs(cycles or {}) do
cycle.originalIndex = cycle.originalIndex or originalIndex
cycle.memberKeySet = cycle.memberKeySet or {}
for _, key in ipairs(cycle.memberKeys or {}) do
cycle.memberKeySet[key] = true
allCycleMembers[key] = true
end
totalCalls = totalCalls + #(cycle.steps or {})
end
local ordered = CopyArray(cycles)
local candidateCache = {}
local sequenceCache = {}
for _, cycle in ipairs(ordered) do
candidateCache[cycle] =
BuildBridgeCandidates(cycle, snapshot, allCycleMembers)
end
table.sort(ordered, function(left, right)
local leftLength = #(left.steps or {})
local rightLength = #(right.steps or {})
if leftLength ~= rightLength then
return leftLength > rightLength
end
local leftCandidates = #(candidateCache[left] or {})
local rightCandidates = #(candidateCache[right] or {})
if leftCandidates ~= rightCandidates then
return leftCandidates < rightCandidates
end
return (left.originalIndex or 0)
< (right.originalIndex or 0)
end)
local function BuildStageSequences(length)
local sequences = {}
local current = {}
local function Add(nextStage, remaining)
if remaining == 0 then
sequences[#sequences + 1] = CopyArray(current)
return
end
local lastStage =
targetStageCount - remaining + 1
for stage = nextStage, lastStage do
current[#current + 1] = stage
Add(stage + 1, remaining - 1)
current[#current] = nil
end
end
Add(1, length)
return sequences
end
for _, cycle in ipairs(ordered) do
local length = #(cycle.steps or {})
sequenceCache[cycle] =
BuildStageSequences(length)
end
local remainingCalls = {}
remainingCalls[#ordered + 1] = 0
for index = #ordered, 1, -1 do
remainingCalls[index] =
remainingCalls[index + 1]
+ #(ordered[index].steps or {})
end
local function HasCapacity(index)
local available = 0
for stage = 1, targetStageCount do
available = available
+ maxCallsPerStage - stageCounts[stage]
end
return available >= (remainingCalls[index] or 0)
end
local function CheckDeadline()
expanded = expanded + 1
if expanded % 64 == 0
and PlanningNowMs() >= deadlineMs then
timedOut = true
return true
end
return false
end
-- Once call slots have been assigned, solve bridge identities separately.
-- This avoids exploring equivalent bridge permutations for a temporal
-- packing that is already impossible.
local function AssignBridges()
local stageUsedKeys = {}
local assignedCycles = {}
for stage = 1, targetStageCount do
stageUsedKeys[stage] = {}
end
for _, cycle in ipairs(ordered) do
local assignment = stageAssignments[cycle]
for localStage, stage in ipairs(
assignment.stageSequence) do
local step = cycle.steps[localStage]
stageUsedKeys[stage][step.firstKey] = true
if localStage ~= 1
and localStage ~= #(cycle.steps or {}) then
stageUsedKeys[stage][step.secondKey] = true
end
end
end
local bridgeOrder = CopyArray(ordered)
table.sort(bridgeOrder, function(left, right)
local leftCandidates =
#(candidateCache[left] or {})
local rightCandidates =
#(candidateCache[right] or {})
if leftCandidates ~= rightCandidates then
return leftCandidates < rightCandidates
end
local leftAssignment = stageAssignments[left]
local rightAssignment = stageAssignments[right]
local leftSpan = leftAssignment.endStage
- leftAssignment.startStage
local rightSpan = rightAssignment.endStage
- rightAssignment.startStage
if leftSpan ~= rightSpan then
return leftSpan > rightSpan
end
return (left.originalIndex or 0)
< (right.originalIndex or 0)
end)
local function SearchBridge(index)
if CheckDeadline() then return false end
if index > #bridgeOrder then return true end
local cycle = bridgeOrder[index]
local assignment = stageAssignments[cycle]
local sequence = assignment.stageSequence
local firstStage = sequence[1]
local lastStage = sequence[#sequence]
for _, bridgeKey in ipairs(
candidateCache[cycle] or {}) do
local resources = {}
for _, key in ipairs(cycle.memberKeys or {}) do
resources[key] = true
end
resources[bridgeKey] = true
local fits =
not stageUsedKeys[firstStage][bridgeKey]
and not stageUsedKeys[lastStage][bridgeKey]
if fits then
for _, prior in ipairs(assignedCycles) do
if ResourcesOverlap(
resources, prior.resources)
and IntervalsOverlap(
assignment.startStage,
assignment.endStage,
prior.startStage,
prior.endStage) then
fits = false
break
end
end
end
if fits then
local bridgeAssignment = {
bridgeKey = bridgeKey,
resources = resources,
startStage = assignment.startStage,
endStage = assignment.endStage,
}
bridgeAssignments[cycle] =
bridgeAssignment
assignedCycles[#assignedCycles + 1] =
bridgeAssignment
stageUsedKeys[firstStage][bridgeKey] = true
stageUsedKeys[lastStage][bridgeKey] = true
if SearchBridge(index + 1) then
return true
end
stageUsedKeys[firstStage][bridgeKey] = nil
stageUsedKeys[lastStage][bridgeKey] = nil
assignedCycles[#assignedCycles] = nil
bridgeAssignments[cycle] = nil
end
if timedOut then return false end
end
return false
end
return SearchBridge(1)
end
local function SearchStages(index)
if CheckDeadline() then return false end
if index > #ordered then
return AssignBridges()
end
if not HasCapacity(index) then return false end
local cycle = ordered[index]
local sequenceOptions =
CopyArray(sequenceCache[cycle] or {})
local function SequenceScore(sequence)
local added = {}
for _, stage in ipairs(sequence) do
added[stage] = true
end
local maximum = 0
local squares = 0
local frontLoad = 0
for stage = 1, targetStageCount do
local count = stageCounts[stage]
+ (added[stage] and 1 or 0)
maximum = math.max(maximum, count)
squares = squares + count * count
frontLoad = frontLoad
+ count * (targetStageCount - stage + 1)
end
return maximum, squares, frontLoad,
table.concat(sequence, ",")
end
table.sort(sequenceOptions, function(left, right)
local leftMaximum, leftSquares,
leftFrontLoad, leftSignature =
SequenceScore(left)
local rightMaximum, rightSquares,
rightFrontLoad, rightSignature =
SequenceScore(right)
if leftMaximum ~= rightMaximum then
return leftMaximum < rightMaximum
end
if leftSquares ~= rightSquares then
return leftSquares < rightSquares
end
-- With equal balance, defer calls slightly so a rolling action
-- window is more likely to age out before the larger tail.
if leftFrontLoad ~= rightFrontLoad then
return leftFrontLoad < rightFrontLoad
end
return leftSignature < rightSignature
end)
for _, sequence in ipairs(sequenceOptions) do
local fits = true
for _, stage in ipairs(sequence) do
if stageCounts[stage] >= maxCallsPerStage then
fits = false
break
end
end
if fits then
stageAssignments[cycle] = {
stageSequence = sequence,
startStage = sequence[1],
endStage = sequence[#sequence],
}
for _, stage in ipairs(sequence) do
stageCounts[stage] = stageCounts[stage] + 1
end
if SearchStages(index + 1) then return true end
for _, stage in ipairs(sequence) do
stageCounts[stage] = stageCounts[stage] - 1
end
stageAssignments[cycle] = nil
end
if timedOut then return false end
end
return false
end
if totalCalls > targetStageCount * maxCallsPerStage
or not SearchStages(1) then
return nil, {
expanded = expanded,
timedOut = timedOut,
}
end
local stages = {}
for stage = 1, targetStageCount do stages[stage] = {} end
for cycleIndex, cycle in ipairs(cycles) do
local assignment = stageAssignments[cycle]
local bridgeAssignment = bridgeAssignments[cycle]
if not assignment or not bridgeAssignment then
return nil, {
expanded = expanded,
timedOut = timedOut,
}
end
AssignCycleBridge(cycle, bridgeAssignment.bridgeKey)
cycle.startStage = assignment.startStage
cycle.endStage = assignment.endStage
cycle.stageSequence =
CopyArray(assignment.stageSequence)
for localStage, stage in ipairs(
assignment.stageSequence) do
local firstKey, secondKey =
ExactCycleStepPair(
cycle,
bridgeAssignment.bridgeKey,
localStage)
stages[stage][#stages[stage] + 1] = {
cycle = cycle,
cycleIndex = cycleIndex,
cycleStage = localStage,
firstKey = firstKey,
secondKey = secondKey,
}
end
end
return stages, {
expanded = expanded,
timedOut = false,
}
end
local function BuildStagedEntryFingerprints(beforeGroups, stages)
local stagedGroups = CopyGroups(beforeGroups)
local fingerprints = {}
for stageIndex, entries in ipairs(stages or {}) do
for _, entry in ipairs(entries) do
if not SwapIdentityPositions(
stagedGroups, entry.firstKey, entry.secondKey) then
return nil, nil
end
end
fingerprints[stageIndex] = GroupFingerprint(stagedGroups)
end
return fingerprints, stagedGroups
end
local function FindBridge(groups, targetGroup, reserved, leaderKey)
for group = 1, 8 do
if group ~= targetGroup then
for _, key in ipairs(groups[group] or {}) do
if key ~= leaderKey and not reserved[key] then
return key
end
end
end
end
end
local function BuildPositionWave(
groups, desiredGroups, snapshot, maxCycles)
local working = CopyGroups(groups)
local reserved = {}
local cycles = {}
for group = 1, 8 do
local members = working[group]
local desired = desiredGroups[group]
local desiredPositionByKey = {}
for position, key in ipairs(desired) do
desiredPositionByKey[key] = position
end
local visited = {}
for startPosition = 1, math.min(#members, #desired) do
if not visited[startPosition]
and members[startPosition] ~= desired[startPosition] then
local positions = {}
local position = startPosition