From 976c1dd65400301090356bdc52b4d4779fc5dc1c Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 04:58:57 +0000 Subject: [PATCH] The parse cache is bypassed while any setting is scoped FromString cached a parse by the string object and returned it under whatever settings were in force later, on any thread, though a literal is rounded as it is parsed: 1e-20 parsed at the defaults stayed 1E-20 inside a PrecisionErrorZeroRange = 1e-10 scope, where the parse is 0, and a parse made inside a scope came back at the defaults. The cache was keyed by ExplicitParsingOnly and DowncastingEnabled only, while the parse also reads PrecisionErrorZeroRange, DecimalPrecisionContext, MaxAbsNumeratorOrDenominatorValue and FloatToRationalIterCount, and computes det, trace, dot, cross, entries and resultant under every setting those read. The cache now holds only parses made with every setting at its default; with a scope of any setting open in the calling flow it is neither read nor written. SettingsState.AnyScopeOpen is one flag read until any scope has ever been opened, then one async-local read per setting that has been scoped. The four tables become one, and ClearFromStringCache now clears all of it (it left the two non-downcasting tables). 0, 1 and -1 with downcasting off are now Real, as the uncached parse gives, where the shortcut answered Integer. Part of #2478 Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 26 ++++++ Sources/AngouriMath/Convenience/MathS.cs | 38 +++++--- .../AngouriMath/Convenience/SettingClass.cs | 31 +++++++ .../MathS.UnsafeAndInternal.cs | 2 +- .../Common/NumericsRegressionTest.cs | 92 +++++++++++++++++++ 5 files changed, 173 insertions(+), 16 deletions(-) diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index c580463c3..146af157a 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -329,6 +329,32 @@ behind it still answers. --- +### A string parsed inside a settings scope is parsed under that scope + +**Silent: a stale value is corrected.** `MathS.FromString`, and with it the implicit conversion from `string` and +`ToEntity`, cached its parse by the string object and returned it under whatever settings were in force later, on any +thread. A literal is rounded as it is parsed, by `PrecisionErrorZeroRange`, `DecimalPrecisionContext`, +`MaxAbsNumeratorOrDenominatorValue` and `DowncastingEnabled`, so the same string answered differently depending on +where it had been parsed first ([#2478](https://github.com/asc-community/AngouriMath/issues/2478)). The cache now holds +only parses made with every setting at its default, and inside a scope of any setting each call parses afresh, as +`FromString(s, useCache: false)` always did. Measured with one string object parsed first at the defaults and then in +the scope: + +| Input | Scope | Was (2.7.0) | Now | +|---|---|---|---| +| `1e-20` | `PrecisionErrorZeroRange` at `1e-10` | `1E-20` (`Real`) | `0` (`Integer`) | +| `1e-20` | `DecimalPrecisionContext` at 20 digits | `1E-20` (`Real`) | `0` (`Integer`) | +| `1.00000000001` | `PrecisionErrorZeroRange` at `1e-10` | `1.00000000001` | `1` | +| `0.142857142857142857142857142857` | `DecimalPrecisionContext` at 20 digits | the decimal (`Real`) | `1/7` | +| `0.12345679` | `MaxAbsNumeratorOrDenominatorValue` at 100 | `12345679/100000000` | `0.12345679` (`Real`) | + +In the other order, the scope's parse came back at the defaults: `1e-20` parsed first in the `1e-10` scope was `0` +afterwards everywhere. And `0`, `1` and `-1`, which the cache answered without parsing, were `Integer` with +`DowncastingEnabled` off, where every other whole number is `Real`; they are `Real` there now, as `FromString(s, +useCache: false)` gave on 2.7.0. Outside any scope nothing moves. + +--- + ### An indexed union or intersection binds its index **Silent: a bound name is no longer reported free.** `FreeVariables` of `union(A_k, k in I)` and `intersection(A_k, k in I)` diff --git a/Sources/AngouriMath/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index 57c92fe01..9b61554a0 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -4591,6 +4591,14 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name /// First occurance will be parsed, others will be replaced with the cached entity /// /// The parsed expression + /// + /// The cache holds parses made with every setting at its default, and is neither read nor + /// written while a scope of any setting is open in the calling flow: a literal is rounded + /// as it is parsed, by , + /// and the other numeric settings, so + /// 1e-20 is a number under the defaults and 0 with the zero range at + /// 1e-10. Inside such a scope every call parses afresh. + /// /// /// Multiple ways to parse an expression. /// @@ -4612,7 +4620,16 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name public static Entity FromString(string expr, bool useCache) => expr .LetLazy(out var parsed, Parser.Parse) - .ReplaceWith(useCache) + // Only a parse made under the defaults is cached. The parse reads the settings, and + // not a fixed few of them: a literal is rounded by PrecisionErrorZeroRange, + // DecimalPrecisionContext, MaxAbsNumeratorOrDenominatorValue, FloatToRationalIterCount + // and DowncastingEnabled, ExplicitParsingOnly decides what juxtaposition means, and + // det, trace, dot, cross, an entry and resultant are computed while parsing, by + // whatever those computations read. A cache keyed by a list of them is wrong the day + // the parse reads one more, so an open scope of any setting bypasses it: the scope's + // parse is neither answered from it nor written to it. + // https://github.com/asc-community/AngouriMath/issues/2478 + .ReplaceWith(useCache && !Convenience.SettingsState.AnyScopeOpen()) switch { false => parsed.Value, @@ -4624,23 +4641,10 @@ public static Entity FromString(string expr, bool useCache) "-1" => Integer.Create(-1), "+oo" => Real.PositiveInfinity, "-oo" => Real.NegativeInfinity, - // One cache per pair of the settings the parse reads: with the - // downcasting off a whole number parses as a decimal, so a string - // parsed under one setting is not the other's parse. - // https://github.com/asc-community/AngouriMath/issues/1513 - _ => (Settings.ExplicitParsingOnly.Value, Settings.DowncastingEnabled.Value) switch - { - (false, true) => stringToEntityCache.GetValue(expr, _ => parsed.Value), - (true, true) => stringToEntityCacheExplicitOnly.GetValue(expr, _ => parsed.Value), - (false, false) => stringToEntityCacheNotDowncasting.GetValue(expr, _ => parsed.Value), - (true, false) => stringToEntityCacheExplicitOnlyNotDowncasting.GetValue(expr, _ => parsed.Value) - } + _ => stringToEntityCache.GetValue(expr, _ => parsed.Value) } }; - private static ConditionalWeakTable stringToEntityCacheExplicitOnly = new(); private static ConditionalWeakTable stringToEntityCache = new(); - private static ConditionalWeakTable stringToEntityCacheNotDowncasting = new(); - private static ConditionalWeakTable stringToEntityCacheExplicitOnlyNotDowncasting = new(); /// Converts a to an expression /// expression, for example, "2 * x + 3 + sqrt(x)" @@ -6226,6 +6230,10 @@ public static Matrix Matrix(int rows, int columns, params Entity[] values) => /// // here you write your code normally /// /// + /// + /// While any setting is scoped, does not use its cache, + /// and parsing the same string repeatedly inside the scope costs a parse each time. + /// public static partial class Settings { /// diff --git a/Sources/AngouriMath/Convenience/SettingClass.cs b/Sources/AngouriMath/Convenience/SettingClass.cs index db0a27829..fbe2920a3 100644 --- a/Sources/AngouriMath/Convenience/SettingClass.cs +++ b/Sources/AngouriMath/Convenience/SettingClass.cs @@ -18,6 +18,9 @@ internal interface ISettingState /// where nothing is set and the default applies. /// object? CurrentState { get; } + + /// Whether a scope of this setting has been opened, in any flow, since the process started. + bool EverScoped { get; } } /// @@ -65,6 +68,31 @@ internal static void Register(ISettingState setting) } } + [ConcurrentField] private static bool anyEverScoped; + + /// Called by every , before its frame is pushed. + internal static void NoteScoped() + { + if (!anyEverScoped) + System.Threading.Volatile.Write(ref anyEverScoped, true); + } + + /// + /// Whether any setting reads, in this flow, from a scope rather than from its default. + /// Until a scope of any setting has been opened somewhere this is one read of a flag; after + /// that, one async-local read for each setting that has ever been scoped. + /// + internal static bool AnyScopeOpen() + { + if (!System.Threading.Volatile.Read(ref anyEverScoped)) + return false; + var settings = System.Threading.Volatile.Read(ref registered); + for (var i = 0; i < settings.Length; i++) + if (settings[i].EverScoped && settings[i].CurrentState is not null) + return true; + return false; + } + /// What every setting reads as right now, in this flow. internal static object?[] Snapshot() { @@ -156,6 +184,8 @@ internal Setting(T defaultValue) /// object? ISettingState.CurrentState => frames.Value; + bool ISettingState.EverScoped => EverScoped; + /// /// Whether a scope of this setting has been opened, in any flow, since the process /// started, so that a reader can skip asking for the flow's frame while none can exist. @@ -185,6 +215,7 @@ public AutoBackRollableTemporarySettingUnit Set(T value) // Before the frame, so that no flow can see the frame without the flag. if (!everScoped) Volatile.Write(ref everScoped, true); + SettingsState.NoteScoped(); frames.Value = new Frame(id, value, frames.Value); return new AutoBackRollableTemporarySettingUnit(this, id); } diff --git a/Sources/AngouriMath/Convenience/UnsafeAndInternal/MathS.UnsafeAndInternal.cs b/Sources/AngouriMath/Convenience/UnsafeAndInternal/MathS.UnsafeAndInternal.cs index b9168e942..57c43ef42 100644 --- a/Sources/AngouriMath/Convenience/UnsafeAndInternal/MathS.UnsafeAndInternal.cs +++ b/Sources/AngouriMath/Convenience/UnsafeAndInternal/MathS.UnsafeAndInternal.cs @@ -27,7 +27,7 @@ public static class UnsafeAndInternal /// instead and set the flag useCache to false) /// public static void ClearFromStringCache() - => (stringToEntityCache, stringToEntityCacheExplicitOnly) = (new(), new()); + => stringToEntityCache = new(); /// /// Checks if two expressions are equivalent if diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index 6646e3150..3c919a2ce 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -170,6 +170,98 @@ public void Issue602_ExplicitToleranceIsStillRespected() Assert.Equal(Entity.Number.Integer.Create(0), "1e-20".ToEntity().EvalNumerical()); } + // The parse cache answered a string with whatever it had been parsed to first, under + // whichever settings were then in force, though a literal is rounded by them as it is + // parsed. https://github.com/asc-community/AngouriMath/issues/2478 + private static System.IDisposable ScopeOf(string setting) => setting switch + { + "zero range 1e-10" => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -10)), + "20 digits" => MathS.Settings.DecimalPrecisionContext.Set(new EContext(20, ERounding.HalfUp, -100000, 100000, false)), + "max 100" => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt32(100)), + "no downcasting" => MathS.Settings.DowncastingEnabled.Set(false), + _ => throw new System.ArgumentException(setting), + }; + + // The type with the value: an Integer and a Real of one value are different parses. + private static (System.Type, Entity) Parse(string text, bool useCache = true) + { + var parsed = MathS.FromString(text, useCache); + return (parsed.GetType(), parsed); + } + + [Theory] + [InlineData("1e-20", "zero range 1e-10")] + [InlineData("1e-20", "20 digits")] + [InlineData("0.333333333333333333333333", "zero range 1e-10")] + [InlineData("0.333333333333333333333333", "20 digits")] + [InlineData("1.00000000001", "zero range 1e-10")] + [InlineData("0.142857142857142857142857142857", "20 digits")] + [InlineData("0.12345679", "20 digits")] + [InlineData("0.12345679", "max 100")] + [InlineData("1", "no downcasting")] + [InlineData("0.1", "no downcasting")] + public void Issue2478_ACachedParseIsTheParseUnderTheSettingsInForce(string text, string setting) + { + var atDefaults = Parse(text, useCache: false); + (System.Type, Entity) inScope; + using (ScopeOf(setting)) + inScope = Parse(text, useCache: false); + Assert.NotEqual(atDefaults, inScope); + + // Defaults first, then the scope, on one string object. + var first = new string(text.ToCharArray()); + Assert.Equal(atDefaults, Parse(first)); + using (ScopeOf(setting)) + Assert.Equal(inScope, Parse(first)); + + // The scope first, then the defaults. + var second = new string(text.ToCharArray()); + using (ScopeOf(setting)) + Assert.Equal(inScope, Parse(second)); + Assert.Equal(atDefaults, Parse(second)); + + // And the interned literal, which every assembly in the process shares. + var interned = string.Intern(text); + Assert.Equal(atDefaults, Parse(interned)); + using (ScopeOf(setting)) + Assert.Equal(inScope, Parse(interned)); + Assert.Equal(atDefaults, Parse(interned)); + } + + // A scope is the calling flow's, so one thread's scope must not decide what another + // thread's parse of the same string object is, in either order. + // https://github.com/asc-community/AngouriMath/issues/2478 + [Fact] + public void Issue2478_AScopeOnOneThreadDoesNotReachAnothersParse() + { + var atDefaults = Parse("1e-20", useCache: false); + (System.Type, Entity) inScope; + using (ScopeOf("zero range 1e-10")) + inScope = Parse("1e-20", useCache: false); + Assert.NotEqual(atDefaults, inScope); + + (System.Type, Entity) OnAThread(string text, bool scoped) + { + (System.Type, Entity) result = default; + var thread = new System.Threading.Thread(() => + { + using var _ = scoped ? ScopeOf("zero range 1e-10") : null; + result = Parse(text); + }); + thread.Start(); + thread.Join(); + return result; + } + + var first = new string("1e-20".ToCharArray()); + Assert.Equal(atDefaults, OnAThread(first, scoped: false)); + Assert.Equal(inScope, OnAThread(first, scoped: true)); + + var second = new string("1e-20".ToCharArray()); + Assert.Equal(inScope, OnAThread(second, scoped: true)); + Assert.Equal(atDefaults, OnAThread(second, scoped: false)); + } + // https://github.com/asc-community/AngouriMath/issues/561 // The reporter's 4x4 matrix spans 1e5 to 1e50, so entries of its inverse fall // below 1e-16 and downcasting rounded them to zero. Fixed by the same change as