Repository navigation
Description
Description
On osx-arm64, a NativeAOT-published program reads a wrong value from a double local after a loop: the local mac is computed before a foreach whose body runs a floating-point while loop and calls a helper that can throw. After the loop, mac reads back as 1 instead of about 4,300, so the final check fails. The same program gives the correct result under the JIT (Release) and under linux-x64 NativeAOT. Marking the lambda [MethodImpl(MethodImplOptions.NoOptimization)] avoids it.
The repro was minimized by statement-level delta debugging from a numerical test in a larger suite. That suite has 25 tests that fail only under osx-arm64 NativeAOT, with the same pattern: values read back changed after loops with throwing calls.
Reproduction Steps
Save the two files below in an empty folder, then:
dotnet publish -c Release -r osx-arm64 --self-contained true -p:PublishAot=true -o out
./out/Repro # prints: REPRO FAIL: Mac state not impossible (exit 1)
dotnet run -c Release # JIT: prints REPRO PASSRepro.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><InvariantGlobalization>true</InvariantGlobalization></PropertyGroup>
</Project>Program.cs:
using System;
internal static class EarthPilotReadout
{
public enum RecoveryVerdict
{
/// <summary>No propellant can be burned.</summary>
NoFuel,
/// <summary>The upper bound on available impulse is below the lower bound on need: no burns from here or higher can restore the floor.</summary>
Impossible,
/// <summary>The ideal burn time for the bound impulse exceeds the coast estimate of the time to the air: entry should
/// come first. A heuristic, not a proof: a burn changes the descent, so the cue says "likely".</summary>
TooLate,
/// <summary>Available impulse covers the bound by less than 15 %, in time: losses may eat the margin.</summary>
Marginal,
/// <summary>Available impulse covers the bound with at least 15 % spare, in time; still an estimate, not a promise.</summary>
Feasible
}
public static double RecoveryDeltaVLowerBound(double radiusMeters, double speedMetersPerSecond, double floorRadiusMeters,
double airRadiusMeters, double gravitationalParameter)
{
if (!double.IsFinite(radiusMeters) || radiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(radiusMeters));
if (!double.IsFinite(speedMetersPerSecond) || speedMetersPerSecond < 0) throw new ArgumentOutOfRangeException(nameof(speedMetersPerSecond));
if (!double.IsFinite(floorRadiusMeters) || floorRadiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(floorRadiusMeters));
if (!double.IsFinite(airRadiusMeters) || airRadiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(airRadiusMeters));
if (!double.IsFinite(gravitationalParameter) || gravitationalParameter <= 0) throw new ArgumentOutOfRangeException(nameof(gravitationalParameter));
double reference = Math.Min(radiusMeters, airRadiusMeters);
double energy = speedMetersPerSecond * speedMetersPerSecond / 2 - gravitationalParameter / radiusMeters;
double fastest = Math.Sqrt(Math.Max(0, 2 * (energy + gravitationalParameter / reference)));
double least = -gravitationalParameter / (floorRadiusMeters + Math.Max(reference, floorRadiusMeters));
if (energy >= least) return 0;
return Math.Max(0, Math.Sqrt(2 * (least + gravitationalParameter / reference)) - fastest);
}
public static double AvailableDeltaV(double massKilograms, double propellantKilograms, double specificImpulseSeconds)
{
if (!double.IsFinite(massKilograms) || massKilograms <= 0) throw new ArgumentOutOfRangeException(nameof(massKilograms));
if (!double.IsFinite(propellantKilograms) || propellantKilograms < 0 || propellantKilograms >= massKilograms) throw new ArgumentOutOfRangeException(nameof(propellantKilograms));
if (!double.IsFinite(specificImpulseSeconds) || specificImpulseSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(specificImpulseSeconds));
return specificImpulseSeconds * 9.80665 * Math.Log(massKilograms / (massKilograms - propellantKilograms));
}
public static double BurnSeconds(double deltaV, double thrustNewtons, double massFlowKilogramsPerSecond, double massKilograms)
{
if (!double.IsFinite(deltaV) || deltaV < 0) throw new ArgumentOutOfRangeException(nameof(deltaV));
if (!double.IsFinite(thrustNewtons) || thrustNewtons <= 0) throw new ArgumentOutOfRangeException(nameof(thrustNewtons));
if (!double.IsFinite(massFlowKilogramsPerSecond) || massFlowKilogramsPerSecond < 0)
throw new ArgumentOutOfRangeException(nameof(massFlowKilogramsPerSecond));
if (!double.IsFinite(massKilograms) || massKilograms <= 0) throw new ArgumentOutOfRangeException(nameof(massKilograms));
if (massFlowKilogramsPerSecond == 0) return deltaV * massKilograms / thrustNewtons;
double fraction = 1 - Math.Exp(-deltaV * massFlowKilogramsPerSecond / thrustNewtons);
return massKilograms / massFlowKilogramsPerSecond * fraction;
}
public static RecoveryVerdict Recovery(double availableDeltaV, double neededDeltaV, double burnSeconds, double secondsToAir)
{
if (!double.IsFinite(availableDeltaV) || availableDeltaV < 0) throw new ArgumentOutOfRangeException(nameof(availableDeltaV));
if (!double.IsFinite(neededDeltaV) || neededDeltaV < 0) throw new ArgumentOutOfRangeException(nameof(neededDeltaV));
if (!double.IsFinite(burnSeconds) || burnSeconds < 0) throw new ArgumentOutOfRangeException(nameof(burnSeconds));
if (!double.IsFinite(secondsToAir) || secondsToAir < 0) throw new ArgumentOutOfRangeException(nameof(secondsToAir));
return availableDeltaV <= 0 ? RecoveryVerdict.NoFuel
: availableDeltaV < neededDeltaV ? RecoveryVerdict.Impossible
: burnSeconds > secondsToAir ? RecoveryVerdict.TooLate
: availableDeltaV < 1.15 * neededDeltaV ? RecoveryVerdict.Marginal : RecoveryVerdict.Feasible;
}
}
internal static class Program
{
private static void Require(bool condition, string message)
{ if (!condition) throw new Exception(message); }
private static void Reject<T>(Action action, string message) where T : Exception
{
try { action(); } catch (T) { return; }
throw new Exception(message);
}
private static int Main()
{
Action fixture = () =>
{
const double mu = 3.986004418e14, air = 6_378_137 + 100_000, floor = 6_378_137 + 150_000;
// 41 % fuel gives at most about 1.9 km/s, so the fall-back stays impossible under the rigorous bound.
double mac = EarthPilotReadout.RecoveryDeltaVLowerBound(6_378_137 + 144_570, 3500, floor, air, mu);
double available = EarthPilotReadout.AvailableDeltaV(400_000, 160_000, 380);
// Burn time is the ideal finite-mass time, checked independently of the production formula: Codex's
// counterexample (ALL SIX thrust and flow, 400 t, 1000 m/s) is 21.966176 s, below the former Δv·m/F of 25.27 s.
const double allSixThrust = 15_827_933.1, allSixFlow = 4546.411483;
// Brute-force integration of dv/dt = F / (m0 - ṁ t) until the impulse is reached, 1 ms steps (midpoint mass).
foreach (double impulse in new[] { 250.0, 1000.0, 4000.0 })
{
double v = 0, t = 0; const double step = .001;
while (v < impulse) { v += allSixThrust / (400_000 - allSixFlow * (t + step / 2)) * step; t += step; }
double ideal = EarthPilotReadout.BurnSeconds(impulse, allSixThrust, allSixFlow, 400_000);
Require(Math.Abs(ideal - t) < 2 * step, $"integrated {t:F3} s vs ideal {ideal:F3} s for {impulse} m/s");
Require(ideal < impulse * 400_000 / allSixThrust && ideal > impulse * (400_000 - allSixFlow * ideal) / allSixThrust,
$"ideal time outside the constant-mass bounds for {impulse} m/s");
}
Require(EarthPilotReadout.BurnSeconds(0, allSixThrust, allSixFlow, 400_000) == 0, "zero impulse takes time");
Reject<ArgumentOutOfRangeException>(() => EarthPilotReadout.BurnSeconds(1, 0, 1, 1), "zero thrust");
Require(EarthPilotReadout.Recovery(available, mac, 1, 100) == EarthPilotReadout.RecoveryVerdict.Impossible, "Mac state not impossible");
};
try { fixture(); Console.WriteLine("REPRO PASS"); return 0; }
catch (Exception e) { Console.WriteLine("REPRO FAIL: " + e.Message); return 1; }
}
}Expected behavior
REPRO PASS: mac keeps the value computed before the loop, so Recovery(available, mac, 1, 100) returns Impossible.
Actual behavior
REPRO FAIL: Mac state not impossible. Instrumenting the original test showed mac == 1 at the final check, while the same local had passed 4000 < mac < 4600 twelve lines earlier.
Regression?
Unknown. Observed with .NET 10.0.11 and 10.0.12.
Known Workarounds
[MethodImpl(MethodImplOptions.NoOptimization)] on the affected lambda or method. OptimizationPreference=Size does not help.
Configuration
| Configuration | Result |
|---|---|
| osx-arm64 NativeAOT, SDK 10.0.400 / ILCompiler 10.0.11 | FAIL |
| osx-arm64 NativeAOT, Microsoft.DotNet.ILCompiler 10.0.12 + runtime 10.0.12 | FAIL |
osx-arm64 NativeAOT, -p:OptimizationPreference=Size |
FAIL |
osx-arm64 NativeAOT, NoOptimization on the lambda |
PASS |
osx-arm64 JIT (Release), default and with TieredCompilation=0 |
PASS |
| linux-x64 NativeAOT (the original 1,630-test suite) | PASS |
Hardware and OS: Apple M3 Pro, macOS 27.0.1. .NET 11 previews were not tested (no .NET 11 SDK installed).
Other information
The JIT on osx-arm64 passes even with full optimization forced (DOTNET_TieredCompilation=0 DOTNET_ReadyToRun=0, and separately DOTNET_TieredPGO=0 DOTNET_TC_QuickJitForLoops=0), so this seems specific to NativeAOT (ILC) code generation for ARM64. It may be register allocation or spilling of a long-lived double across a loop that contains a call that can throw, but that is a guess.
Metadata
Metadata
Labels
Type
Projects
- StatusShow more project fieldsNo status
Activity
dotnet-policy-service commentedon Oct 12, 2026
Tagging subscribers to this area: @dotnet/area-system-numerics
See info in area-owners.md if you want to be subscribed.
dotnet-policy-service commentedon Oct 12, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
EgorBo commentedon Oct 12, 2026
The root cause appears to be incorrect NativeAOT ARM64 Mach-O compact-unwind metadata, rather than loop optimization or register allocation.
In
GetArm64CompactUnwindCode, the floating-point register-pair flags are shifted using the absolute array index.istarts atREG_IDX_D8 == 12, so the flags end up six bits too high. The calculation should be:This explains the exact
mac == 1observation:macin the callee-saved registerd8and passes it correctly to the finalRecoverycall.BurnSeconds(1, 0, 1, 1)savesd8/d9, overwrites them with its flow/mass arguments (1), and then throws because the thrust is zero.0x44004001forBurnSeconds, instead of0x44000101. The unwinder therefore misses the saved FP registers, and the catch resumes withd8 == 1instead of the originalmac.The loop is incidental.
NoOptimizationavoids the symptom by keeping the value on the stack, while the JIT and non-Apple targets use different unwind paths.The issue is also present on current main: invoking the actual encoder produces incorrect flags for all four FP register pairs. An isolated run of the actual ARM64 compact unwinder on Windows leaves
d8 == 1with the emitted encoding and restores the saved value with the corrected encoding. The complete NativeAOT executable has not been run on macOS as part of this investigation. This calculation was introduced in #111451.AI disclosure: This investigation and comment were generated by GitHub Copilot.
mathewritter commentedon Oct 13, 2026
Confirmed on Apple Silicon: M3 Pro, macOS 27.0.1 (26A434), .NET SDK 10.0.400, Apple clang 21.0.0. ILCompiler 10.0.11 and 10.0.12 give identical results.
-p:StripSymbols=false, printsREPRO FAILon both ILCompiler versions.llvm-objdump --unwind-infoon the ILC object showsBurnSecondsas0x44004001. Its prologue isstp d9, d8, [sp,#-0x30]!; stp x20, x19, [sp,#0x10]; stp x29, x30, [sp,#0x20], so the expected encoding is0x44000101. The D8/D9 flag is at0x4000instead of0x100, exactly as described in the comment above.0x40→0x01, giving0x44000101) and relinked with the build's exact clang command. The patched binary printsREPRO PASS. A control relink of the unmodified object still fails.Mainlambda saves d8–d15 and x19–x22, and is encoded0x4403c003instead of0x44000f03. D10/D11, D12/D13 and D14/D15 land at0x8000,0x10000and0x20000, as predicted. The proposed<< ((i - REG_IDX_D8) >> 1)should cover all four. A regression test that checks the emitted compact-unwind encoding for a function saving FP register pairs would catch this class of bug.0x0003C000: 1,872 with D8/D9, 885 with D10/D11, 548 with D12/D13 and 371 with D14/D15. No frame-mode entry uses the valid D-pair bits (0xF00), so every frame-mode function that saves d8–d15 appears to be misencoded. Our 25 osx-arm64-NativeAOT-only fixture failures (of 1,634) are nearly all exception or refusal-path tests, which is consistent with this. I haven't traced each one individually.Thanks for the quick diagnosis.
sirforce commentedon Dec 3, 2026
Still reproduces on 10.0.14 and 10.0.15 (osx-arm64 NativeAOT), so it isn't fixed in the current servicing releases. A smaller repro, in case it's useful as a regression test: the exception is caught in a callee, with no loop needed.
lo=-1 hi=1, exit 1)lo=-1 hi=1, exit 1)The win-x64 pass is consistent with the compact-unwind diagnosis above (Mach-O only).
Program.cs (repro)
aot-fp-repro.csproj