Skip to content

New PSG Autopilot rewrite - #2776

Merged
lamont-granquist merged 7 commits into
devfrom
lcg/psg-new-state-machine
Nov 19, 2026
Merged

lamont-granquist merged 7 commits into
devfrom
lcg/psg-new-state-machine

Conversation

@lamont-granquist

Copy link
Copy Markdown
Collaborator

replaces #2746
replaces #2747

This is almost certainly going to need more cleanup. I haven't done an actual human pass on it.

This look good enough to start with and passes some basic flame
tests.

MechJebModuleAscentPSGAutopilot + MechJebModuleGuidanceController become
the MechJebModulePSGAutopilot which is responsible for the whole launch
including PSG active guidance.
- trying to better isolate the guidance code from throttle code from
  updating display items
- fixing a problem with boosters that need to stop and be staged off
  from not being staged off because the next stage is a fairing or
  LES or something and not the decoupler for the boosters.
The _inertial field does need to be updated every tick and always
updates if _inertial is V3.zero
Adds some comments around JETTISON
I want those to reflect the moment the main engines were cut.

Major discrepancies in the Tgo line usually indicates root part
issues or some other deviation between the rocket in the stage stats
and what is actually flying, so is important in diagnosis.

Alternatively some ~15 burnout TWR rocket with Abs(Tgo) < 0.02 and
some fairly large Vgo just indicates inherent inaccuracy in shutting
down engines on 0.02 discrete ticks, and proper operation.

The Tgo/Vgo values read from the Solution after TERMINAL_RCS is
done are meaningless.
@lamont-granquist
lamont-granquist force-pushed the lcg/psg-new-state-machine branch from cf26786 to deb96d5 Compare November 19, 2026 04:26
@github-actions

Copy link
Copy Markdown
Contributor

✅ Build Artifact 🚀

MechJeb2-2062af1.zip (built from deb96d5)

@lamont-granquist
lamont-granquist merged commit 4ae25bf into dev Nov 19, 2026
3 checks passed
@lamont-granquist
lamont-granquist deleted the lcg/psg-new-state-machine branch November 19, 2026 04:32
@sarbian

sarbian commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Review notes on #2776 and #2777 (dev ef54081). Method:

  • The new AscentStateMachine and MechJebModulePSGAutopilot were checked against a list of the PSG/PVG guidance failures seen so far: from the in-game test runs, the audits and the issues.
  • Each suspect was confirmed with an AscentFlight test.
  • In-game flights: Kerbal X at 3.2x (coast before and during the last stage, short of Δv, a thrust loss late in the core's burn, a jettison before a fixed upper stage), the RP-1 Juno I, and one comparison flight on the code before the rewrite (aea5836).

What the rewrite fixes

  • The booster hang in TERMINAL. This is the RP-1 Juno I case that PSG: go on to the coast or the next stages when the optimized booster runs dry in terminal guidance #2724 and PSG guidance: a segment state machine in MechJebLib (no terminal guidance for boosters) #2746 were about. A booster before a coast no longer goes through terminal guidance. The Juno was re-flown: the A-7 burned out, the coast started, the solids fired and guidance finished, with no hang.
  • The last stage running dry short of the target. The autopilot turns itself off 0.6 s after the flame-out (Kerbal X with its Poodle tank at 5 %).
  • Edge cases fixed before are still handled:
    • the RCS rounding noise in ThrustAvailable is not counted as thrust;
    • an engine waiting for its propellant to settle is not counted as spent;
    • a zero-length coast-during is flown as one burn.
  • Coast before and coast during the last stage both reach 145 × 145 km at 30.00°.
  • kOS: the GUIDANCESTATUS names are unchanged (JETTISON reports TERMINAL_STAGING).
  • Settings: they move over to the new module through FormerName.
  • The 41 AscentStateMachine tests and the rest of MechJebLibTest pass in Release and Debug.

1. A burn is cut on the clock, not on the energy it has reached

AscentStateMachine.JettisonDue (:1026) is Reached(EndTime(p)), and the cut for a coast in CoastDue (:920) is Reached(StartTime(coast)). Both are pure MET tests.

When it matters: a burn that falls behind its plan, through an engine short of thrust (TestFlight's thrust loss on the Juno's A-7) or a late ignition:

  • the booster before a fixed upper stack is dropped at its planned end with propellant left;
  • the burn before a coast is cut there too, short of the apoapsis the plan meant it to reach.

Why a re-solve doesn't help: PSGSimulation stops solving once CurrentPhaseTgo < PreStageTime (10 s). Solution.Tgo(t, n) clamps to 0 once the phase's planned end has passed, so the pause lasts until the stage is gone. A thrust loss in the last 10 s of a burn, or any lateness, is flown on the plan made before it.

Before:

  • The old controller cut the precise-shutdown booster before a fixed stack in TERMINAL, on |r×v| reaching the target's (TerminalGuidanceSatisfied). For that case this is a regression.
  • The coast cut was already on the clock (Solution.Coast(MET)).
  • The closed PSG guidance: cut a booster at the later of its planned end and its planned angular momentum #2747 changed both to the later of the planned end and the tick the angular momentum reaches the plan's at that end, within 1e-5. Without the margin, a coast-during's first burn exactly on its plan was cut 34 s late.

Seen in game:

  • Kerbal X, coast before the Poodle; the core's thrust halved 8 s before its planned end.
  • The core was cut at MET 144.36, the same tick as in the healthy flight. It still had 218 m/s, and the apoapsis was 124 km instead of 145.
  • The re-solve in the coast and the Poodle's margin still made 144.7 × 145.2 km. A rocket with less margin would not.

Tests: F6_JettisonCutWaitsForThePlannedAngularMomentum and F6_CoastCutWaitsForThePlannedAngularMomentum. With the booster 5 s behind, both cut at plan MET 45 of 50.

2. A late fixed booster eats the cut stage above it

Plan: a fixed booster, then a stage the optimizer cuts with propellant left (JETTISON before a fixed stack), then the last stage.

What happens when the booster burns past its planned end:

  1. The booster's phase isn't done until the stage stats show it gone. All that time the solver is paused (Tgo 0) and the steering is held, as in item 1.
  2. When the booster is gone, the middle stage's JettisonDue is already true or nearly so. JettisonDue has no OnStageOf(p) check.
  3. TickJettison then stages IMMEDIATE from wherever the vessel is: through the middle stage's ignition and on past it.

Results:

  • Booster 3 s late: the middle stage burns 7 s of its 10, and leaves with 33 s of 40 s of propellant.
  • Booster 12 s late: the middle stage is staged off unlit, with all its propellant.

Before: the old controller cut that stage in TERMINAL on |r×v|, so it burned until it had the plan's energy. BoosterOverburnIsNotStagedOffByTheCoast asserts the coast version of the same thing (the stage after an overburning booster is staged off without lighting) as intended.

Test: F6_LateBoosterDoesNotEatTheCutStageAboveIt(3) and (12).

3. A Solution that lands during JETTISON relights the cut booster

A solve is cancelled only at the coast's start and end, at TERMINAL_STARTED and at FINISHED. Nothing cancels it at a jettison cut.

  1. A solve started more than PreStageTime before the cut can land while JETTISON waits for KSP's staging cooldown.
  2. If the vessel was behind when that solve started, its booster ends later than now. JettisonDue turns false and JettisonIndex() returns -1 (:506).
  3. The state goes back to BURNING, and ThrottleGuided throttles the cut booster up again.
  4. Then the cut comes again: BURNING > JETTISON > BURNING > JETTISON, with the booster lit twice. A RealFuels engine with no relights left is dead from then on.

Before: the old TERMINAL_STAGING held until currentStage changed, so a new Solution couldn't bring the booster back.

Test: StaleSolutionInJettisonDoesNotRelightTheCutBooster.

4. A coast skipped by #2777 can come back ahead of the burning upper stage

The setup: a COAST_BEFORE coast the optimizer leaves under SKIP_TIME (about 0.4 to 0.8 s at these scales; MinCoast is 0 by default).

  • Guidance never enters COASTING, so HasCoasted stays false.
  • PSGSimulation marks the coast's flight plan stage done only on COAST_ENDED (MarkCoastDone).
  • After the booster, FlightPlan.ReconcileStages keeps that coast stage, since it matches the upper stage's engine signature. FindStartingIndex (PSGSimulation.cs:827) returns its index, so every re-solve starts with a free coast ahead of the upper burn.

What happens once a re-solve gives that coast SKIP_TIME or more:

  1. CoastIndex() is 0.
  2. CurrentPhase(false) uses last = coast - 1 = -1 and returns -1.
  3. CoastDue treats p < 0 as "the burns before the coast are gone" and returns true.
  4. The burning upper stage is cut, coasts, and relights. That is the stage the coast was put before, usually because it can't relight.

Before: the old code had the same gap. But a coast shrunk to nothing used to be flown as a short coast, which set hasCoasted. With #2777 it is never flown, so this path is now open.

Test: SkippedCoastBeforeComingBackDoesNotCutTheBurningStage.

Smaller

  • Ullage against warp. TickCoasting asks for the RCS ullage UllageLeadTime (20 s) before the burn, but CutNear only drops warp CUT_WARP_TIME (10 s) before it. RCS doesn't fire on rails, so the ullage gets 10 s at most, and one tick of high warp can jump the whole window.
  • RCSOn writes Vessel.ctrlState.Z from OnFixedUpdate. FlightInputHandler.FixedUpdate copies the player's input over ctrlState (vessel.SetControlState). Whether the ullage and the TERMINAL_RCS trim fire then depends on the script order. This is unchanged from the old controller.
  • A skipped burn can be one the vessel still has to get rid of. AnalyzeStages skips any burn before the last stage shorter than SKIP_TIME, including one the optimizer cuts with propellant left. CurrentPhase passes over it, and guidance flies the next burn's steering and throttle on it. Nothing cuts it or stages it off, since autostaging won't drop an engine with propellant. Unlikely for the burn being flown (the 10 s pause), possible for a later cut stage. Test: SkippedCutBoosterIsNotBurnedOut.
  • Steering held past a phase's end. The steering lock (Tgo(p) <= 2) lasts as long as a booster burns past its planned end, since Tgo clamps to 0. This is unchanged from the old controller.
  • PSG engaged in flight still restarts the pitch program at 90° and steers north first. This is unchanged from the old controller.

The tests

Each item above has an AscentFlight test, 7 cases in all, and every one fails on dev:
MechJebLibTest/PSGTests/ReviewRegressionTests.cs (below; it needs only AscentFlight and SolutionTests from dev).

To make a booster fall behind its plan, the tests light it late (Engine.LightAt). AscentFlight only moves the vessel along the trajectory while it thrusts, so it reaches each planned |r×v| late.

#2733, #2731 and #2732 look fine. For #2733 specifically: T is still its own variable, and dropping the norm row on continuity-tied points avoids the LICQ problem #2316 fixed.

ReviewRegressionTests.cs
/*
 * Copyright Lamont Granquist, Sebastien Gaggini and the MechJeb contributors
 * SPDX-License-Identifier: LicenseRef-PD-hp OR Unlicense OR CC0-1.0 OR 0BSD OR MIT-0 OR MIT OR LGPL-2.1+
 */

using System.Linq;
using MechJebLib.PSG;
using Xunit;
using static MechJebLibTest.PSGTests.AscentFlight;

namespace MechJebLibTest.PSGTests
{
    /// <summary>
    ///     Review of #2776 / #2777: known past failure states of PSG guidance, flown through the AscentStateMachine.  A test that
    ///     fails on dev ef540816 shows a defect.  "Behind the plan" is modelled as an engine that lights late (Engine.LightAt): the
    ///     vessel only moves along the synthetic trajectory while it thrusts, so it reaches each planned angular momentum late.
    /// </summary>
    public class ReviewRegressionTests
    {
        private const PlanEditor.CoastKind BEFORE = PlanEditor.CoastKind.BEFORE;

        private static AscentFlight ThreeStages(double booster = 60, double middle = 40, double last = 30)
        {
            var flight = new AscentFlight(2);
            flight.AddEngine(1, 0, -1, last);
            flight.AddEngine(2, 1, 0, middle);
            flight.AddEngine(3, 2, 1, booster);
            return flight;
        }

        /*
         * F6: a burn cut on the clock with the vessel behind the plan.  #2747 cut at the later of the planned end and the
         * planned end's |r x v|; the old controller cut the precise-shutdown booster in TERMINAL on |r x v|.
         */

        // a booster cut before a fixed upper stack, 5 s behind its plan, with no new Solution (the re-solves are paused for the
        // last PreStageTime = 10 s of a phase anyway)
        [Fact]
        public void F6_JettisonCutWaitsForThePlannedAngularMomentum()
        {
            AscentFlight flight = ThreeStages();
            flight.EngineOf(3).LightAt = MET0 + 5;
            flight.Engage(Solve(flight.Plan(), MET0, Cut(50), Fixed(40), Fixed(30)));

            Assert.True(flight.RunUntil(PSGState.JETTISON, 100));

            // the vessel is where the plan is at its cut, or the booster leaves with 5 s of propellant more than planned
            Assert.True(flight.TrajectoryT >= MET0 + 50 - DT,
                $"cut at MET {flight.Met - MET0:F2} with the vessel at plan MET {flight.TrajectoryT - MET0:F2}, booster fuel left {flight.EngineOf(3).Fuel:F2} s");
        }

        // the same booster cut by the coast before the last stages
        [Fact]
        public void F6_CoastCutWaitsForThePlannedAngularMomentum()
        {
            AscentFlight flight = ThreeStages();
            flight.EngineOf(3).LightAt = MET0 + 5;
            flight.Engage(Solve(flight.Plan(BEFORE, 1), MET0, Cut(50), Coast(30), Fixed(40), Fixed(30)));

            Assert.True(flight.RunUntil(PSGState.COASTING, 100));

            Assert.True(flight.TrajectoryT >= MET0 + 50 - DT,
                $"coast at MET {flight.Met - MET0:F2} with the vessel at plan MET {flight.TrajectoryT - MET0:F2}, booster fuel left {flight.EngineOf(3).Fuel:F2} s");
        }

        // A fixed booster behind its plan burns past the planned end of the short cut stage above it.  The re-solves are paused
        // all that time (CurrentPhaseTgo is 0, under PreStageTime), and the cut stage is jettisoned on the clock as soon as the
        // stage stats show the booster gone: lateness comes straight off the cut stage, and here all of it.
        [Theory]
        [InlineData(3)]  // the middle stage burns 7 s of its 10
        [InlineData(12)] // the middle stage past its planned end before it lights: staged off unlit, full
        public void F6_LateBoosterDoesNotEatTheCutStageAboveIt(double late)
        {
            AscentFlight flight = ThreeStages(60, 40, 30);
            flight.EngineOf(3).LightAt = MET0 + late;
            flight.Engage(Solve(flight.Plan(), MET0, Fixed(60), Cut(10), Fixed(30)));

            Assert.True(flight.RunUntil(PSGState.JETTISON, 200), flight.Sequence());
            double planAtCut = flight.TrajectoryT - MET0;
            double middleFuel = flight.EngineOf(2).Fuel;
            int middleBurns = flight.EngineOf(2).Burns;

            Assert.True(middleBurns == 1 && planAtCut >= 70 - DT,
                $"middle stage cut at MET {flight.Met - MET0:F2}, vessel at plan MET {planAtCut:F2} (planned cut 70), " +
                $"middle burns {middleBurns}, fuel left {middleFuel:F2} s of 40 (planned 30)");
        }

        /*
         * JETTISON and a Solution that lands in it
         */

        // A solve started before the cut (more than PreStageTime before it) lands while JETTISON waits for KSP to stage.  Its
        // booster ends 3 s later than the one being cut (the vessel was behind when it started).  Nothing cancels a solve at a
        // jettison (only at the coast, terminal guidance and the end), so it is flown: the cut booster is throttled up again.
        [Fact]
        public void StaleSolutionInJettisonDoesNotRelightTheCutBooster()
        {
            AscentFlight flight = ThreeStages();
            flight.RefuseStagingUntil = MET0 + 51;
            flight.Engage(Solve(flight.Plan(), MET0, Cut(50), Fixed(40), Fixed(30)));

            Assert.True(flight.RunUntil(PSGState.JETTISON, 100));
            flight.Run(0.4);
            Assert.Equal(PSGState.JETTISON, flight.Machine.State);

            Assert.True(flight.Machine.SetSolution(Solve(flight.FlownPlan, MET0 + 39, Cut(14), Fixed(40), Fixed(30))));
            flight.Fly();

            Assert.True(flight.EngineOf(3).Burns == 1,
                $"the cut booster lit {flight.EngineOf(3).Burns} times: {flight.Sequence()}, {flight.StagingLog()}");
        }

        /*
         * Skipped phases (#2777)
         */

        // A coast-before that a Solution skips (shorter than SKIP_TIME): the booster is cut and jettisoned, and the coast's stage
        // lights.  PSGSimulation never marks the coast done (MarkCoastDone runs only on COAST_ENDED) and FindStartingIndex
        // starts the next solve at it, so the next Solution starts with the coast, which the optimizer (MinCoast 0) may now
        // make longer than SKIP_TIME.  CurrentPhase(false) is then -1 and CoastDue fires: the burning upper stage is cut for a
        // coast before itself and relit (a no-relight engine, F23; the throttle cut, F56).
        [Fact]
        public void SkippedCoastBeforeComingBackDoesNotCutTheBurningStage()
        {
            AscentFlight flight = ThreeStages();
            flight.Engage(Solve(flight.Plan(BEFORE, 1), MET0, Cut(50), Coast(0), Fixed(40), Fixed(30)));

            Assert.True(flight.RunUntil(f => f.Met >= MET0 + 55, 100));
            Assert.Equal(PSGState.BURNING, flight.Machine.State);
            Assert.Equal(1, flight.Stage);
            Assert.Equal(1, flight.EngineOf(2).Burns);

            // flight plan stages: 0 BURN row 0, 1 BURN row 1, 2 COAST_BEFORE row 1, 3 BURN row 2 (gone)
            double now = flight.Met;
            Assert.True(flight.Machine.SetSolution(Solve(flight.FlownPlan, now, 2, Coast(1), Fixed(35), Fixed(30))));
            flight.Fly();

            Assert.True(flight.Count(AscentEvents.COAST_STARTED) == 0 && flight.EngineOf(2).Burns == 1,
                $"{flight.Sequence()}; upper stage lit {flight.EngineOf(2).Burns} times");
        }

        // A booster the optimizer cuts with propellant left, whose remaining burn a Solution shrinks under SKIP_TIME (0.128 s in these tests) while the
        // vessel is in it: guidance skips it and flies the next burn's steering and throttle on the booster, which nothing cuts
        // or stages (autostaging won't drop an engine with propellant): it burns out.
        [Fact]
        public void SkippedCutBoosterIsNotBurnedOut()
        {
            AscentFlight flight = ThreeStages();
            flight.Engage(Solve(flight.Plan(), MET0, Cut(0.1), Fixed(40), Fixed(30)));

            flight.Run(10);

            Assert.True(flight.EngineOf(3).Fuel > 59,
                $"{flight.Sequence()}; booster fuel left {flight.EngineOf(3).Fuel:F2} s of 60 after 10 s, stage {flight.Stage}");
        }
    }
}

@lamont-granquist

Copy link
Copy Markdown
Collaborator Author

Yeah, I deliberately avoided addressing 1 to keep the state machine simpler at "BECO", which is already getting complicated enough. I want to do stabilization before fixing everything else. This is largely about managing my own context window. If you get a thrust fault during the prestage cooldown you're also not going to get an updated optimizer solve, and you might hit the energy target, but you won't follow the actual right path, so this is about making a fault better, but you can't ever fix it.

2 is also very weird. This is a fixed burntime stack before a coast before a fixed burntime upper ending in a fully guided unfixed stage? If I'm understanding it correctly that is an incredibly low concern use case.

3 means that the PSGSImulation manager should flush a new Solution that comes in during JETTISON? That would be fine.

4 i'm guessing this edge conditions suggests that HasCoasted is the wrong API to use and that WillCoast combined with IsCoasting is the right way to query what we're doing.

@sarbian

sarbian commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

I pushed the PR fix it proposed as draft. About 2 it has this following comment.

Still sick, so no better analysis on my side, sorry.

On 2: there is no coast in it. The shape is a fixed booster, then a middle stage the optimizer cuts with propellant left, then a fixed upper stage (the test's plan is Fixed(60), Cut(10), Fixed(30)).

Stock Kerbal X with a fixed Poodle and no coast has that shape:

the last asparagus pair (stage 5) burns to depletion;
the core (stage 4) is cut at 43 km with about 1,470 m/s left;
the Poodle is fixed.
What sets it off is the fault in 1, a booster running late. The difference is what is lost. In 1 it is the last seconds of the booster. In 2 the middle stage's planned end has already passed when it lights, so JettisonDue is true right away. With the booster 12 s late, the whole middle stage is staged off unlit.

A guard that leaves the BECO logic alone: hold a clock cut until a Solution solved after that stage lit has arrived. PSGSimulation already solves after staging (AFTER_STAGING), and that solve re-plans the cut from where the vessel actually is. The middle stage has propellant to spare in the meantime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants