MZ Help Figuring Out TPB Acceleration

I'm trying to make a plugin that speeds up the pace at which the action bars fill up in MZ's TPB ("ATB") battle systems. Since this is meant to just be a convenience that cuts out unnecessary waiting, it's important that the turn order stays exactly the same.

I took the following method from the core scripts:
JavaScript:
Game_Battler.prototype.tpbAcceleration = function() {
    const speed = this.tpbRelativeSpeed();
    const referenceTime = $gameParty.tpbReferenceTime();
    return speed / referenceTime;
};

...and I aliased it as such:
JavaScript:
Game_Battler.prototype.tpbAcceleration_lapse = Game_Battler.prototype.tpbAcceleration;
Game_Battler.prototype.tpbAcceleration = function() {
    // Run the old version of this method to get what the TPB Gain would be without any further modifications
    var orig_accel = this.tpbAcceleration_lapse.call(this);
    // Multiply the TPB Gain by the Normal Multiplier specified in this plugin's parameters
    var final_accel = orig_accel * wave_lapse.normal_mult;
    // Now that all calculations have been done, return the amount of TPB Gain calculated
    return final_accel;
};

For now, this is the only method in the plugin.

In order to test the plugin, I assigned each Actor a considerably different AGI, and tested a battle against a troop (using the same Troop each time). In order to prevent the randomization of the starting TPB gauge fill value, and start it at 0 instead for all battlers, I added a troop event that paralyzes all Actors and all Enemies for 1 turn, on "turn 0" (the start of battle).

First, I tested without the plugin (in TPB Wait Mode). The faster battlers lost their Paralyze states first and then their TPBs started to fill. As expected, Actor 2 (the highest-AGI battler) went first, then Actor 1, then 3, then 4. Then 2 again, and so on; Actor 2 eventually lapped 4, and the TPB behaved as I would expect.

Then, I tested with the plugin, and with the Speed Multiplier parameter (wave_lapse.normal_mult) set to 10. It looked like this time Actor 1 lost his Paralyze status first (though it was very close), and even more strangely, Actor 1 received the first turn! Then Actor 2, then 3, then 4. Repeated tests with 10x speed showed the same exact thing happening.

Thinking that maybe I did something wrong with my code, I tried a third test with the plugin but with the Speed Multiplier parameter set to 1. Behavior was exactly the same as what happened when the plugin was not installed, so I don't think I made any kind of coding/logic error.

Throwing some debug messages to the console (pasting the code I used to do this below, but it's only relevant if you want to try it yourself), it looks like actors' TPBs are moving up the correct amount with each tick - for example, with the Parameter set to 1, Actor 2's TPB charge increases by 0.01666 each frame, whereas when it's set to 10, Actor 2's TPB charge increases by 0.16666 each frame (exactly 10x the amount). Actors seem to correctly gain a turn whenever their TPB increases to 1.000 or above, although there is likely a 1 frame delay (probably because of the way battle flow is handled in the core scripts).
Spoiler: Code I used to log battlers' TPB fill values
JavaScript:
Game_Battler.prototype.updateTpbChargeTime = function() {
    if (this._tpbState === "charging") {
        this._tpbChargeTime += this.tpbAcceleration();
        console.log(this.name() + "'s Charge is " + String(this._tpbChargeTime));
        if (this._tpbChargeTime >= 1) {
            this._tpbChargeTime = 1;
            this.onTpbCharged();
        }
    }
};

I played around with a bunch of different numbers for the Parameter: When using 1 through 9, Actor 2 (correctly) received the first turn, and all numbers 10 and above (including a really high multiplier like 38) caused Actor 1 to go first instead.

I have been looking through the code for hours now and I can't figure out why this is happening!!

Can anyone help me figure out what is causing Actor #1 to get their turn faster than Actor #2 whenever the multiplier is high enough? Is there something in the base code that would cause only the first Actor to lose a state during a tick in the TPB when two Actors are due to lose a state during that tick? Is there something else in the code base that could cause this slightly different turn order when the TPB meters are set to fill at many times their normal rates?

Thanks so much for any help or thoughts you can offer. This one's really been vexing me!
...looks like it's just a simple rounding "error". 😊

When the gauge fills (in either mode, action or idle) it is capped at 1 = 100%. When a battler's turn ends, their TPB resets to 0: any excess is lost. This excess will tend to be proportional to the magnitude of tpbAcceleration.

To get around this, I believe you'd need to retain the excess (in both charging modes) from one turn to the next. 😴

Edit: since, in retrospect, I should probably have explained more...this is the plugin I used for testing, very similar to what you describe~
Spoiler: Plugin stuff
JavaScript:
// Adjust TPB rate via reference time
(alias => {
    Game_Unit.prototype.tpbReferenceTime = function() {
        return alias.apply(this, arguments) / 10;
    };
})(Game_Unit.prototype.tpbReferenceTime);

// Test!
(alias => {
    Game_Battler.prototype.updateTpb = function() {
        console.log(this.name() + ' updateTpb:\n--active: ' + this.tpbChargeTime() + '\n--idle: ' + this._tpbIdleTime);
        alias.apply(this, arguments);
    };
})(Game_Battler.prototype.updateTpb);
Like you said, the fastest battler gains 0.016 TPB gauge per frame (in wait mode). However, this hits 0.9999999999999999 the frame before it caps out (thanks, JavaScript!). This means that any battler who is within one frame's acceleration of filling their TPB gauge will fill it in the same frame as the fastest one. When it comes to selecting actions, actors are checked in order of index. Thus if the actors' agility values are sufficiently similar and the fastest one is not the leader, the order of actions is prone to change.

If the excess were retained, you could use that to determine the order of same-frame actor actions, as well as carrying it over to the battler's next turn gauge. 👋
@caethyril Thank you kindly for your thoughts on this! You have come through for me a lot recently! The "rounding error" makes a lot of sense in light of the fact that 10x the speed means 10x the chance of actors reaching the ready-to-act threshold at the same time (even if the faster Actor #2 reached it by "more" than the slower Actor #1). It does seem to be a significant part of the issue. However, I think there must be something additional going on here (and I can't figure out what!).

However, when I added console.log lines to all methods that call tpbAcceleration(), to see if maybe it was kind of Idle timing issue, I got some unexpected results. Here's what came up on my console as of Actor #1 (Reid) receiving his first turn. The test was done using the same setup as in my first post - 10x speed multiplier, and a Paralysis state applied to all actors and enemies on Turn 0 to ensure Charge Times would start at 0.
Spoiler: Console Output
Reid's Idle Time is 0.15380552155668353
Michelle's Idle Time is 0.16666666666666666
Kasey's Idle Time is 0.13957967860943965
Eliot's Idle Time is 0.12343262143659894
Gnome A's Idle Time is 0.1410769195636468
Gnome B's Idle Time is 0.1410769195636468
Gnome C's Idle Time is 0.1410769195636468
Gnome D's Idle Time is 0.1410769195636468
Gnome E's Idle Time is 0.1410769195636468
Reid's Idle Time is 0.30761104311336707
Michelle's Idle Time is 0.3333333333333333
Kasey's Idle Time is 0.2791593572188793
Eliot's Idle Time is 0.2468652428731979
Gnome A's Idle Time is 0.2821538391272936
Gnome B's Idle Time is 0.2821538391272936
Gnome C's Idle Time is 0.2821538391272936
Gnome D's Idle Time is 0.2821538391272936
Gnome E's Idle Time is 0.2821538391272936
Reid's Idle Time is 0.4614165646700506
Michelle's Idle Time is 0.5
Kasey's Idle Time is 0.41873903582831895
Eliot's Idle Time is 0.37029786430979683
Gnome A's Idle Time is 0.4232307586909404
Gnome B's Idle Time is 0.4232307586909404
Gnome C's Idle Time is 0.4232307586909404
Gnome D's Idle Time is 0.4232307586909404
Gnome E's Idle Time is 0.4232307586909404
Reid's Idle Time is 0.6152220862267341
Michelle's Idle Time is 0.6666666666666666
Kasey's Idle Time is 0.5583187144377586
Eliot's Idle Time is 0.4937304857463958
Gnome A's Idle Time is 0.5643076782545872
Gnome B's Idle Time is 0.5643076782545872
Gnome C's Idle Time is 0.5643076782545872
Gnome D's Idle Time is 0.5643076782545872
Gnome E's Idle Time is 0.5643076782545872
Reid's Idle Time is 0.7690276077834177
Michelle's Idle Time is 0.8333333333333333
Kasey's Idle Time is 0.6978983930471983
Eliot's Idle Time is 0.6171631071829947
Gnome A's Idle Time is 0.7053845978182339
Gnome B's Idle Time is 0.7053845978182339
Gnome C's Idle Time is 0.7053845978182339
Gnome D's Idle Time is 0.7053845978182339
Gnome E's Idle Time is 0.7053845978182339
Reid's Idle Time is 0.9228331293401013
Michelle's Idle Time is 0.9999999999999999
Kasey's Idle Time is 0.8374780716566379
Eliot's Idle Time is 0.7405957286195937
Gnome A's Idle Time is 0.8464615173818807
Gnome B's Idle Time is 0.8464615173818807
Gnome C's Idle Time is 0.8464615173818807
Gnome D's Idle Time is 0.8464615173818807
Gnome E's Idle Time is 0.8464615173818807
Reid's Idle Time is 1.076638650896785
Michelle's Idle Time is 1.1666666666666665
Kasey's Idle Time is 0.9770577502660776
Eliot's Idle Time is 0.8640283500561926
Gnome A's Idle Time is 0.9875384369455275
Gnome B's Idle Time is 0.9875384369455275
Gnome C's Idle Time is 0.9875384369455275
Gnome D's Idle Time is 0.9875384369455275
Gnome E's Idle Time is 0.9875384369455275
Reid's Idle Time is 0.15380552155668353
Michelle's Idle Time is 0.16666666666666666
Kasey's Idle Time is 1.1166374288755172
Eliot's Idle Time is 0.9874609714927916
Gnome A's Idle Time is 1.1286153565091743
Gnome B's Idle Time is 1.1286153565091743
Gnome C's Idle Time is 1.1286153565091743
Gnome D's Idle Time is 1.1286153565091743
Gnome E's Idle Time is 1.1286153565091743
Reid's Cast Time is 0.15380552155668353
Michelle's Cast Time is 0.16666666666666666
Kasey's Idle Time is 0.13957967860943965
Eliot's Idle Time is 1.1108935929293904
Gnome A's Idle Time is 0.1410769195636468
Gnome B's Idle Time is 0.1410769195636468
Gnome C's Idle Time is 0.1410769195636468
Gnome D's Idle Time is 0.1410769195636468
Gnome E's Idle Time is 0.1410769195636468
Kasey's Cast Time is 0.13957967860943965
Eliot's Idle Time is 0.12343262143659894
Gnome A's Cast Time is 0.1410769195636468
Gnome B's Cast Time is 0.1410769195636468
Gnome C's Cast Time is 0.1410769195636468
Gnome D's Cast Time is 0.1410769195636468
Gnome E's Cast Time is 0.1410769195636468
Reid's Charge Time is 0.15380552155668353
Eliot's Cast Time is 0.12343262143659894
Reid's Charge Time is 0.30761104311336707
Reid's Charge Time is 0.4614165646700506

Michelle's Charge Time is 0.16666666666666666
Reid's Charge Time is 0.6152220862267341
Michelle's Charge Time is 0.3333333333333333
Reid's Charge Time is 0.7690276077834177
Michelle's Charge Time is 0.5
Kasey's Charge Time is 0.13957967860943965
Reid's Charge Time is 0.9228331293401013
Michelle's Charge Time is 0.6666666666666666
Kasey's Charge Time is 0.2791593572188793
Gnome A's Charge Time is 0.1410769195636468
Reid's Charge Time is 1.076638650896785
Reid's Idle Time is 0.15380552155668353
Michelle's Charge Time is 0.8333333333333333
Kasey's Charge Time is 0.41873903582831895
Gnome A's Charge Time is 0.2821538391272936
Gnome B's Charge Time is 0.1410769195636468

I find it very strange that Cast Times are being logged for actors before they even receive their first action, but that's probably irrelevant. What I can't figure out here is why Reid (the slower Actor #1) is sometimes receiving multiple increases to his Charge Time in a row without Michelle (the faster Actor #2) receiving any. I think this is at the root of the issue!

My instinct is that something is happening when States are removed from a battler that causes this - maybe because of the writing of the message to the battle log, a frame or two have to pass before another actor can have their state removed (and therefore Reid can start earning Charge Time first)? I followed several chains of methods in the core scripts to try and figure out whether only one actor could lose a state at a time, but didn't see anything that stuck out to me to suggest this, and when I added another console printout to indicate the Graphics.frameCount where each battler was losing the state, it was the same for Reid and Michelle (Frame #97 of the battle test).

One more oddity that might be worth mentioning: I tried a different approach where instead of any of the code I used in the first post, I instead used this modification to the Game_Battler.prototype.updateTpb method, iterating through it a number of times equal to the Multiplier:
Code:
Game_Battler.prototype.updateTpb = function() {
    for (var mult = 0; mult < wave_lapse.normal_mult; mult++) {
        if (this.canMove()) {
            this.updateTpbChargeTime();
            this.updateTpbCastTime();
            this.updateTpbAutoBattle();
        }
        if (this.isAlive()) {
            this.updateTpbIdleTime();
        }
    }
};
I thought that might automatically handle the granularity of "each step" of charge where a step of 10x the magnitude might not. This time, with the same 10x Multiplier, Actor #2 (Michelle) did go first but she lapped Actor #4, which was different behavior from the default RPG Maker behavior without my plugin. Found this especially weird.

I know this is getting incredibly far into the weeds, and normally I wouldn't worry much about an uncommon discrepancy in battler order - but I feel like a plugin designed to speed things up while not touching anything gameplay-wise would be doing a disservice to its users if it actually affects the way that battles play out.
All battlers get one TPB update per frame, always in the same order (actors first, then enemies, each in ascending order by index).

You are only logging from cast, charge, and idle updates, but _tpbState can take values that do not involve calling tpbAcceleration, e.g.
  • "ready" - after "casting" completes, checked by BattleManager to perform action;
  • "acting" - busy performing, basically deactivates other TPB state responses.
Maybe include _tpbState in your logs to see if there is a pattern. Relevant snippets (comments mine):
Spoiler: BattleManager > updateTurn, updateTpb, updateTpbBattler (rmmz_managers.js)
JavaScript:
BattleManager.updateTurn = function(timeActive) {
    $gameParty.requestMotionRefresh();
    if (this.isTpb() && timeActive) {
        this.updateTpb();   // update!
    }
    if (!this._subject) {
        this._subject = this.getNextSubject();
    }
    if (this._subject) {
        this.processTurn();   // process one subject per frame
    } else if (!this.isTpb()) {
        this.endTurn();
    }
};

BattleManager.updateTpb = function() {
    $gameParty.updateTpb();        // updateTpb, the method you cited
    $gameTroop.updateTpb();
    this.updateAllTpbBattlers();   // perform relevant actions
    this.checkTpbTurnEnd();        // TPB <-> troop turn equivalence
};

BattleManager.updateAllTpbBattlers = function() {
    for (const battler of this.allBattleMembers()) {
        this.updateTpbBattler(battler);
    }
};

BattleManager.updateTpbBattler = function(battler) {
    if (battler.isTpbTurnEnd()) {
        battler.onTurnEnd();
        battler.startTpbTurn();
        this.displayBattlerStatus(battler, false);
    } else if (battler.isTpbReady()) {
        battler.startTpbAction();
        this._actionBattlers.push(battler);
    } else if (battler.isTpbTimeout()) {
        battler.onTpbTimeout();
        this.displayBattlerStatus(battler, true);
    }
};
Cast times are showing up because a battler's state is set to "casting" when they have no actions available...I'm not sure why, but I assume there's a good reason. 😅 Relevant snips (comments mine):
Spoiler: Game_Battler > startTpbTurn, makeTpbActions (rmmz_objects.js)
JavaScript:
Game_Battler.prototype.startTpbTurn = function() {
    this._tpbTurnEnd = false;
    this._tpbTurnCount++;
    this._tpbIdleTime = 0;
    if (this.numActions() === 0) {   // no actions, e.g. due to restriction
        this.makeTpbActions();
    }
};

Game_Battler.prototype.makeTpbActions = function() {
    this.makeActions();
    if (this.canInput()) {
        this.setActionState("undecided");
    } else {   // no input available
        this.startTpbCasting();   // start casting
        this.setActionState("waiting");
    }
};
updateTpb only affects a battler's internal TPB values; the related action(s) are performed via the BattleManager according to the resultant TPB state (cf BattleManager spoiler above). With this in mind, the only major difference in outcome that I think would result from implementing your "speed up" effect as a loop rather than a simple multiplier is that the TPB state can charge part-way through, sending the remainder to idle time. Not sure how that might connect to what you're seeing, though... 😴
@caethyril Wow!! Thanks for that clear explanation of the code; I can see you took a lot of time to write that up and I appreciate it. Following from the updateTpbBattler method you pasted, it looks like while multiple battlers can enter into _actionBattlers at the same time (I believe), only one will actually be pulled as the "_subject" of BattleManager:
JavaScript:
BattleManager.getNextSubject = function() {
    for (;;) {
        const battler = this._actionBattlers.shift();
        if (!battler) {
            return null;
        }
        if (battler.isBattleMember() && battler.isAlive()) {
            return battler;
        }
    }
};
With that in mind, I think I see the weakness of my brute-force multiplier approach. Maybe I need to "look ahead" and calculate whether any battlers will become the subject this tick, and if so, run the ticks one-by-one until it happens.

If you don't mind, I've got one question for now I'd really appreciate guidance with - is it the fact that only one battler is becoming the subject each tick, that explains why the slower actor #1's States are being removed before the faster actor #2's (and subsequently can get multiple Charge Time increases before actor #2 does)? Or is it something else entirely? I searched the codebase for instances of _subject, followed it to processTurn() and then its sub-methods, but couldn't find anything about removing states for the subject specifically.
@Wavelength: the end turn stuff is invoked through the onTurnEnd method of Game_Battler, which gets called in BattleManager.updateTpbBattler:
Spoiler: Relevant methods, comments mine
JavaScript:
// rmmz_managers.js
BattleManager.updateTpbBattler = function(battler) {
    if (battler.isTpbTurnEnd()) {
        battler.onTurnEnd();   // <- here ^-^
        battler.startTpbTurn();
        this.displayBattlerStatus(battler, false);
//...etc
}

// rmmz_objects.js
Game_Battler.prototype.onTurnEnd = function() {
    this.clearResult();
    this.regenerateAll();
    this.updateStateTurns();    // tick states down by 1 turn
    this.updateBuffTurns();
    this.removeStatesAuto(2);   // remove expired states
};
I'm not sure why the states would be being removed faster, though if the "rounding" thing I mentioned originally is at play then, like you mention, that may cause 1+ frames of delay due to the 1-subject-per-frame thing. 😅

(Quick note: this is the first time I'm really exploring the TPB system code, so I might be missing stuff. You're not the only one learning things from this! 🙏)
Actually, I'm afraid to say that, almost none of what both of you covered so far matters to the core issue OP faced 🙁
Spoiler: Actor 1 having a turn before actor 2 despite actor 1 being slower
It's because of BattleManager.updateTpb:
JavaScript:
BattleManager.updateTpb = function() {
    $gameParty.updateTpb();
    $gameTroop.updateTpb();
    this.updateAllTpbBattlers();
    this.checkTpbTurnEnd();
};
Which calls Game_Unit.prototype.updateTpb:
JavaScript:
Game_Unit.prototype.updateTpb = function() {
    for (const member of this.members()) {
        member.updateTpb();
    }
};
Which calls Game_Party.prototype.members in the case of $gameParty:
JavaScript:
Game_Party.prototype.members = function() {
    return this.inBattle() ? this.battleMembers() : this.allMembers();
};

Game_Party.prototype.allMembers = function() {
    return this._actors.map(id => $gameActors.actor(id));
};

Game_Party.prototype.battleMembers = function() {
    return this.allMembers()
        .slice(0, this.maxBattleMembers())
        .filter(actor => actor.isAppeared());
};
So Game_Party.prototype.members always returns the list of members in battle sorted ascendingly by their ids.

Now, back to Game_Battler.prototype.updateTpb:
JavaScript:
Game_Battler.prototype.updateTpb = function() {
    if (this.canMove()) {
        this.updateTpbChargeTime();
        this.updateTpbCastTime();
        this.updateTpbAutoBattle();
    }
    if (this.isAlive()) {
        this.updateTpbIdleTime();
    }
};

Game_Battler.prototype.updateTpbChargeTime = function() {
    if (this._tpbState === "charging") {
        this._tpbChargeTime += this.tpbAcceleration();
        if (this._tpbChargeTime >= 1) {
            this._tpbChargeTime = 1;
            this.onTpbCharged();
        }
    }
};
Which calls Game_Battler.prototype.onTpbCharged:
JavaScript:
Game_Battler.prototype.onTpbCharged = function() {
    if (!this.shouldDelayTpbCharge()) {
        this.finishTpbCharge();
    }
};

Game_Battler.prototype.shouldDelayTpbCharge = function() {
    return !BattleManager.isActiveTpb() && $gameParty.canInput();
};

Game_Battler.prototype.finishTpbCharge = function() {
    this._tpbState = "charged";
    this._tpbTurnEnd = true;
    this._tpbIdleTime = 0;
};
This means that, when multiple battlers can become having their TPB charged at the exact same frame(which can happen when the TPB acceleration becomes too large), they'll also become inputable at that frame:
JavaScript:
Game_Battler.prototype.canInput = function() {
    if (BattleManager.isTpb() && !this.isTpbCharged()) {
        return false;
    }
    return Game_BattlerBase.prototype.canInput.call(this);
};
Which causes Game_Party.prototype.canInput to return true as well:
JavaScript:
Game_Party.prototype.canInput = function() {
    return this.members().some(actor => actor.canInput());
};
This causes BattleManager.checkTpbInputOpen to setup an inputable actor:
JavaScript:
BattleManager.checkTpbInputOpen = function() {
    if (this.isPartyTpbInputtable()) {
        if (this._tpbNeedsPartyCommand) {
            this._inputting = true;
            this._tpbNeedsPartyCommand = false;
        } else {
            this.selectNextCommand();
        }
    }
};
By BattleManager.selectNextCommand:
JavaScript:
BattleManager.selectNextCommand = function() {
    if (this._currentActor) {
        if (this._currentActor.selectNextCommand()) {
            return;
        }
        this.finishActorInput();
    }
    this.selectNextActor();
};

BattleManager.selectNextActor = function() {
    this.changeCurrentActor(true);
    if (!this._currentActor) {
        if (this.isTpb()) {
            this.changeCurrentActor(true);
        } else {
            this.startTurn();
        }
    }
};
Because BattleManager._currentActor doesn't exist when no inputable actor's already selected, BattleManager.changeCurrentActor will be called with its argument forward being true:
JavaScript:
BattleManager.changeCurrentActor = function(forward) {
    const members = $gameParty.battleMembers();
    let actor = this._currentActor;
    for (;;) {
        const currentIndex = members.indexOf(actor);
        actor = members[currentIndex + (forward ? 1 : -1)];
        if (!actor || actor.canInput()) {
            break;
        }
    }
    this._currentActor = actor ? actor : null;
    this.startActorInput();
};
Because Game_Party.prototype.battleMembers also returns the list of members in battle sorted ascendingly by their ids, the 1st actor, having a smaller actor id than that of the 2nd one, is selected for inputting actions, even when the 2nd one's faster.

To solve this, you can simply change BattleManager.changeCurrentActor into this:
JavaScript:
BattleManager.changeCurrentActor = function(forward) {
    const members = $gameParty.battleMembers();
    if (this.isTpb()) {
        members.sort((a, b) => b.tpbAcceleration() - a.tpbAcceleration());
    }
    let actor = this._currentActor;
    for (;;) {
        const currentIndex = members.indexOf(actor);
        actor = members[currentIndex + (forward ? 1 : -1)];
        if (!actor || actor.canInput()) {
            break;
        }
    }
    this._currentActor = actor ? actor : null;
    this.startActorInput();
};
It basically sorts all battle members descendingly by their TPB acceleration, thus ensuring the fastest battlers to always removing their states first 😀
Bear in mind that the BattleManager.isTpb check is needed, because the default turn based battle system also uses BattleManager.changeCurrentActor, meaning that the above change would break that system if the aforementioned check's isn't in place 😛

Spoiler: Actor 1 removing state before actor 2 despite actor 1 being slower
It's because of this:
JavaScript:
BattleManager.updateAllTpbBattlers = function() {
    for (const battler of this.allBattleMembers()) {
        this.updateTpbBattler(battler);
    }
};
Where BattleManager.allBattleMembers is this:
JavaScript:
BattleManager.allBattleMembers = function() {
    return $gameParty.battleMembers().concat($gameTroop.members());
};
And Game_Party.prototype.battleMembers always returns the list of members in battle sorted ascendingly by their ids:
JavaScript:
Game_Party.prototype.allMembers = function() {
    return this._actors.map(id => $gameActors.actor(id));
};

Game_Party.prototype.battleMembers = function() {
    return this.allMembers()
        .slice(0, this.maxBattleMembers())
        .filter(actor => actor.isAppeared());
};

It means that, when the battlers are too fast in TPB, Game_Battler.prototype.isTpbTurnEnd will return true at the same time for both faster and slower battlers:
JavaScript:
Game_Battler.prototype.finishTpbCharge = function() {
    this._tpbState = "charged";
    this._tpbTurnEnd = true;
    this._tpbIdleTime = 0;
};

Game_Battler.prototype.isTpbTurnEnd = function() {
    return this._tpbTurnEnd;
};

Then BattleManager.displayBattlerStatus, which displays the fact that the battler involved has the involved state removed:
JavaScript:
BattleManager.displayBattlerStatus = function(battler, current) {
    this._logWindow.displayAutoAffectedStatus(battler);
    if (current) {
        this._logWindow.displayCurrentState(battler);
    }
    this._logWindow.displayRegeneration(battler);
};
Bear in mind that, all those battlers involved have already called Game_Battler.prototype.onTurnEnd at the exact same frame, which is the actual method really removing states, just that it's not responsible for displaying the state removal as well:
JavaScript:
Game_Battler.prototype.onTurnEnd = function() {
    this.clearResult();
    this.regenerateAll();
    this.updateStateTurns();
    this.updateBuffTurns();
    this.removeStatesAuto(2);
};

Now, back to Window_BattleLog.prototype.displayAutoAffectedStatus:
JavaScript:
Window_BattleLog.prototype.displayAffectedStatus = function(target) {
    if (target.result().isStatusAffected()) {
        this.push("pushBaseLine");
        this.displayChangedStates(target);
        this.displayChangedBuffs(target);
        this.push("waitForNewLine");
        this.push("popBaseLine");
    }
};

Window_BattleLog.prototype.displayAutoAffectedStatus = function(target) {
    if (target.result().isStatusAffected()) {
        this.displayAffectedStatus(target, null);
        this.push("clear");
    }
};

Bear in mind that the real battle log window display follows this sequence:
1. Window_BattleLog.prototype.pushBaseLine
2. Messages pushed by Window_BattleLog.prototype.displayChangedStates
3. Those pushed by Window_BattleLog.prototype.displayChangedBuffs
4. Window_BattleLog.prototype.waitForNewLine
5. Window_BattleLog.prototype.popBaseLine
6. Window.BattleLog.prototype.clear
And when there are multiple battlers end their turns at the exact same frame, the one with the smallest id will run the sequence first, then the next will be the one with the next smallest id, then so on.
That's why, in your case, despite the fact that actor 2 has higher agi than actor 1, when they both end their turns at the exact same frame, the real sequence will be this:
1. Window_BattleLog.prototype.pushBaseLine
2. Messages pushed by Window_BattleLog.prototype.displayChangedStates FOR ACTOR 1
3. Those pushed by Window_BattleLog.prototype.displayChangedBuffs FOR ACTOR 1
4. Window_BattleLog.prototype.waitForNewLine
5. Window_BattleLog.prototype.popBaseLine
6. Window.BattleLog.prototype.clear
7. Window_BattleLog.prototype.pushBaseLine
8. Messages pushed by Window_BattleLog.prototype.displayChangedStates FOR ACTOR 2
9. Those pushed by Window_BattleLog.prototype.displayChangedBuffs FOR ACTOR 2
10. Window_BattleLog.prototype.waitForNewLine
11. Window_BattleLog.prototype.popBaseLine
12. Window.BattleLog.prototype.clear

To solve this, you can simply change BattleManager.updateAllTpbBattlers into this:
JavaScript:
BattleManager.updateAllTpbBattlers = function() {
    for (const battler of this.allBattleMembers().sort((a, b) => b.tpbAcceleration() - a.tpbAcceleration())) {
        this.updateTpbBattler(battler);
    }
};
It basically sorts all battle members descendingly by their TPB acceleration, thus ensuring the fastest battlers to always removing their states first 🙂

P.S.: This solves the issue of the slower battlers being able to execute actions first, assuming that both them and the faster ones finish casting at the exact same frame, because of BattleManager.updateTpbBattler with Game_Battler.prototype.isTpbReady returning true 🤣
@DoubleX in my initial response I stated that actors reaching full TPB charge on the same frame are processed in order of index:
This means that any battler who is within one frame's acceleration of filling their TPB gauge will fill it in the same frame as the fastest one. When it comes to selecting actions, actors are checked in order of index. Thus if the actors' agility values are sufficiently similar and the fastest one is not the leader, the order of actions is prone to change.
Your first spoiler seems to be exactly what I mentioned: only one battler can process per turn, so if multiple battlers reach full charge in the same frame, the order of action will be from lowest index to highest index. 😴

I also mentioned a fix similar, logically, to what you suggest:
If the excess were retained, you could use that to determine the order of same-frame actor actions, as well as carrying it over to the battler's next turn gauge.
I personally prefer this approach, since it also addresses the loss of excess charge when the gauge resets, but that's mostly a matter of preference. Thank you for the detailed explanation, though~ 🙏

Your second spoiler I agree with! 😂 States get removed for everyone with frame-perfect timing in order of index, through updateAllTpbBattlers, i.e. I was wrong here, since all battlers get updated, not just the subject:
I'm not sure why the states would be being removed faster, though if the "rounding" thing I mentioned originally is at play then, like you mention, that may cause 1+ frames of delay due to the 1-subject-per-frame thing.
The associated messages each frame, e.g. "X is no longer poisoned!", are queued in order of party index, thus will be displayed one after the other with short pauses between, in order of index. Your fix changes the order in which the battlers are updated, which also affects the order of these messages. By default I think this would only be a visual change (order of messages), though I see that if you have a plugin to do stuff when a state is removed then it could have mechanical relevance as well.
I personally prefer this approach, since it also addresses the loss of excess charge when the gauge resets, but that's mostly a matter of preference. Thank you for the detailed explanation, though~ 🙏
I personally consider this approach very, very dangerous, especially in the case of OP, where the TPB acceleration can return large values relative to the maximum, 1, because the excess charge can also be large relative to that maximum.
For instance, if the fastest battler has the TPB acceleration being 0.24, then that battler will have its charge hitting 1.2 before being capped, now the excess will be 0.2, which is 20% of 1.
While it only seems to be a 1 frame difference for that battler, it's assuming that the TPB acceleration of that battler won't be reduced later on, so if, say, that original 0.24 TPB acceleration is due to a level 2 agi buff, netting a 50% of the agi increase, then if that battler later becomes to have a level 2 agi debuff, netting a 50% of the agi decrease, the new TPB acceleration will be (0.24 / (1.5 ^ 0.5)) * (0.5 ^ 0.5) = Around 0.138, which is much smaller than 0.2, and is now a 2 frame difference instead of just 1(which is enough to confuse some players in some cases even though a 2 frame difference is still small).
Of course, this approach can still work, it's just that one really has to know what he/she's truly doing, or his/her players can end up being confused sometimes by the TPB charge reset with previous carry-overs for apparently no reasons 😛
P.S.: If it's ever possible that the excess can still be greater than the maximum(i.e., the TPB acceleration is more than 2), then the whole carry-over will become pointless, even though I know it's an extreme case(which demands TPB acceleration to be multiplied by an insanely large number) 😀

The associated messages each frame, e.g. "X is no longer poisoned!", are queued in order of party index, thus will be displayed one after the other with short pauses between, in order of index. Your fix changes the order in which the battlers are updated, which also affects the order of these messages. By default I think this would only be a visual change (order of messages), though I see that if you have a plugin to do stuff when a state is removed then it could have mechanical relevance as well.
Actually, the battle log window does MUCH, MUCH MORE than just showing logs in battle, because it's actually the sole coordinator of all visual changes in the battle(meaning that it's the highest level of view in MVC), including state change(add/remove/etc) animations, damage popup displays, battler poses upon taking damage/having recovery/being collapsed/etc, skill/item execution animations, etc.
Even just in the case of state changes, the display ordering also matters, because when multiple battlers have state changes at the exact same frame, only the 1st one having such changes displayed will have the display timing being the same as that of actual internal state changes, while all the other battlers will first receive actual internal state changes, then have such changes displayed only after all the previous ones have their counterparts displayed.
It means that, on the eyes of players, the displayed ordering will seem to be the actual ordering, because the internal state changes are invisible, so to ensure the fastest battlers always have their state changes displayed first, the display ordering must be changed descendingly according to the TPB speed of the battlers 🙂
I personally consider this approach very, very dangerous, especially in the case of OP, where the TPB acceleration can return large values relative to the maximum, 1, because the excess charge can also be large relative to that maximum.
For instance, if the fastest battler has the TPB acceleration being 0.24...
I see nothing you have mentioned here as a problem, let alone "very, very dangerous"! Like I said, it's just a matter of preference~

In the extreme case you can, like you say, cap the excess charge at 100%, since there's no point carrying over more than that anyway. If a battler is getting more than 1 turn per frame of charging, I think there are deeper issues to consider there... 😅

Also, I feel like 0.24 is already a fairly extreme example, being 15x the fastest actor's default, unbuffed acceleration in "fast TPB" (wait) mode. 😴

And yes, I recognise that the battle log queues the initialisation of visual effects in battle: messages, animations, and motions. However, I thought state icons (hovering and in the battle status window) update immediately? I assume that was what Wavelength used to determine who lost the state first, but maybe not.
@caethyril @DoubleX Thank you both so much!! (And wow, DoubleX, that is a detailed code chain! Thanks for that great explanation) I need to keep reading through this as I go back to the code, but what I think I understand now from the combination of your responses, is that the main issue is being caused by multiple battlers hitting the 1.00 threshold at the same time (and the order that they're checked to "break" the check and take the battler as the subject is sorted by Actor ID). It sounds as if there were other places where actor order can get messed up that I wasn't tracking in my debug, too?

Thinking to how to most accurately give faster Actors more turns in all situations, I'm starting to believe I should implement both of your solutions - choose the actor who has the highest current TPB score via the sort (this would be especially important for the first action in an accelerated TPB ), and then hold the fraction of excess and then return it to the Actor's TPB after they take their action. The issue, of course, is that this would not mirror current MZ behavior, but the more you guys explain how it's working on the back end, the more I'm thinking that this new approach would be strictly better than MZ behavior. So if I can get everything working smoothly, the new plan is to make my plugin a TPB "Enhancement" rather than a mere Speed-Up, which will use this new Sort and Holdover functionality even when the speed chosen is completely normal at 1.00x. Then, the only thing I will need to ensure is that the turn order with my plugin when the speed is accelerated to 5x or 15x, is still the same as the turn order when it's 1x.

Original thread: https://forums.rpgmakerweb.com/threads/help-figuring-out-tpb-acceleration.131076/