Skip to content

Commit 31cc3f0

Browse files
The parse cache is bypassed while any setting is scoped (#2480)
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 <noreply@anthropic.com>
1 parent 147ac04 commit 31cc3f0

5 files changed

Lines changed: 173 additions & 16 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,32 @@ behind it still answers.
329329

330330
---
331331

332+
### A string parsed inside a settings scope is parsed under that scope
333+
334+
**Silent: a stale value is corrected.** `MathS.FromString`, and with it the implicit conversion from `string` and
335+
`ToEntity`, cached its parse by the string object and returned it under whatever settings were in force later, on any
336+
thread. A literal is rounded as it is parsed, by `PrecisionErrorZeroRange`, `DecimalPrecisionContext`,
337+
`MaxAbsNumeratorOrDenominatorValue` and `DowncastingEnabled`, so the same string answered differently depending on
338+
where it had been parsed first ([#2478](https://github.com/asc-community/AngouriMath/issues/2478)). The cache now holds
339+
only parses made with every setting at its default, and inside a scope of any setting each call parses afresh, as
340+
`FromString(s, useCache: false)` always did. Measured with one string object parsed first at the defaults and then in
341+
the scope:
342+
343+
| Input | Scope | Was (2.7.0) | Now |
344+
|---|---|---|---|
345+
| `1e-20` | `PrecisionErrorZeroRange` at `1e-10` | `1E-20` (`Real`) | `0` (`Integer`) |
346+
| `1e-20` | `DecimalPrecisionContext` at 20 digits | `1E-20` (`Real`) | `0` (`Integer`) |
347+
| `1.00000000001` | `PrecisionErrorZeroRange` at `1e-10` | `1.00000000001` | `1` |
348+
| `0.142857142857142857142857142857` | `DecimalPrecisionContext` at 20 digits | the decimal (`Real`) | `1/7` |
349+
| `0.12345679` | `MaxAbsNumeratorOrDenominatorValue` at 100 | `12345679/100000000` | `0.12345679` (`Real`) |
350+
351+
In the other order, the scope's parse came back at the defaults: `1e-20` parsed first in the `1e-10` scope was `0`
352+
afterwards everywhere. And `0`, `1` and `-1`, which the cache answered without parsing, were `Integer` with
353+
`DowncastingEnabled` off, where every other whole number is `Real`; they are `Real` there now, as `FromString(s,
354+
useCache: false)` gave on 2.7.0. Outside any scope nothing moves.
355+
356+
---
357+
332358
### An indexed union or intersection binds its index
333359

334360
**Silent: a bound name is no longer reported free.** `FreeVariables` of `union(A_k, k in I)` and `intersection(A_k, k in I)`

‎Sources/AngouriMath/Convenience/MathS.cs‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4591,6 +4591,14 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name
45914591
/// First occurance will be parsed, others will be replaced with the cached entity
45924592
/// </param>
45934593
/// <returns>The parsed expression</returns>
4594+
/// <remarks>
4595+
/// The cache holds parses made with every setting at its default, and is neither read nor
4596+
/// written while a scope of any setting is open in the calling flow: a literal is rounded
4597+
/// as it is parsed, by <see cref="Settings.PrecisionErrorZeroRange"/>,
4598+
/// <see cref="Settings.DecimalPrecisionContext"/> and the other numeric settings, so
4599+
/// <c>1e-20</c> is a number under the defaults and <c>0</c> with the zero range at
4600+
/// <c>1e-10</c>. Inside such a scope every call parses afresh.
4601+
/// </remarks>
45944602
/// <example>
45954603
/// Multiple ways to parse an expression.
45964604
/// <code>
@@ -4612,7 +4620,16 @@ public static (Variable, Variable, Variable, Variable, Variable) Var(string name
46124620
public static Entity FromString(string expr, bool useCache)
46134621
=> expr
46144622
.LetLazy(out var parsed, Parser.Parse)
4615-
.ReplaceWith(useCache)
4623+
// Only a parse made under the defaults is cached. The parse reads the settings, and
4624+
// not a fixed few of them: a literal is rounded by PrecisionErrorZeroRange,
4625+
// DecimalPrecisionContext, MaxAbsNumeratorOrDenominatorValue, FloatToRationalIterCount
4626+
// and DowncastingEnabled, ExplicitParsingOnly decides what juxtaposition means, and
4627+
// det, trace, dot, cross, an entry and resultant are computed while parsing, by
4628+
// whatever those computations read. A cache keyed by a list of them is wrong the day
4629+
// the parse reads one more, so an open scope of any setting bypasses it: the scope's
4630+
// parse is neither answered from it nor written to it.
4631+
// https://github.com/asc-community/AngouriMath/issues/2478
4632+
.ReplaceWith(useCache && !Convenience.SettingsState.AnyScopeOpen())
46164633
switch
46174634
{
46184635
false => parsed.Value,
@@ -4624,23 +4641,10 @@ public static Entity FromString(string expr, bool useCache)
46244641
"-1" => Integer.Create(-1),
46254642
"+oo" => Real.PositiveInfinity,
46264643
"-oo" => Real.NegativeInfinity,
4627-
// One cache per pair of the settings the parse reads: with the
4628-
// downcasting off a whole number parses as a decimal, so a string
4629-
// parsed under one setting is not the other's parse.
4630-
// https://github.com/asc-community/AngouriMath/issues/1513
4631-
_ => (Settings.ExplicitParsingOnly.Value, Settings.DowncastingEnabled.Value) switch
4632-
{
4633-
(false, true) => stringToEntityCache.GetValue(expr, _ => parsed.Value),
4634-
(true, true) => stringToEntityCacheExplicitOnly.GetValue(expr, _ => parsed.Value),
4635-
(false, false) => stringToEntityCacheNotDowncasting.GetValue(expr, _ => parsed.Value),
4636-
(true, false) => stringToEntityCacheExplicitOnlyNotDowncasting.GetValue(expr, _ => parsed.Value)
4637-
}
4644+
_ => stringToEntityCache.GetValue(expr, _ => parsed.Value)
46384645
}
46394646
};
4640-
private static ConditionalWeakTable<string, Entity> stringToEntityCacheExplicitOnly = new();
46414647
private static ConditionalWeakTable<string, Entity> stringToEntityCache = new();
4642-
private static ConditionalWeakTable<string, Entity> stringToEntityCacheNotDowncasting = new();
4643-
private static ConditionalWeakTable<string, Entity> stringToEntityCacheExplicitOnlyNotDowncasting = new();
46444648

46454649
/// <summary>Converts a <see cref="string"/> to an expression</summary>
46464650
/// <param name="expr"><see cref="string"/> expression, for example, <code>"2 * x + 3 + sqrt(x)"</code></param>
@@ -6226,6 +6230,10 @@ public static Matrix Matrix(int rows, int columns, params Entity[] values) =>
62266230
/// // here you write your code normally
62276231
/// </code>
62286232
/// </summary>
6233+
/// <remarks>
6234+
/// While any setting is scoped, <see cref="FromString(string, bool)"/> does not use its cache,
6235+
/// and parsing the same string repeatedly inside the scope costs a parse each time.
6236+
/// </remarks>
62296237
public static partial class Settings
62306238
{
62316239
/// <summary>

‎Sources/AngouriMath/Convenience/SettingClass.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ internal interface ISettingState
1818
/// <see langword="null"/> where nothing is set and the default applies.
1919
/// </summary>
2020
object? CurrentState { get; }
21+
22+
/// <summary>Whether a scope of this setting has been opened, in any flow, since the process started.</summary>
23+
bool EverScoped { get; }
2124
}
2225

2326
/// <summary>
@@ -65,6 +68,31 @@ internal static void Register(ISettingState setting)
6568
}
6669
}
6770

71+
[ConcurrentField] private static bool anyEverScoped;
72+
73+
/// <summary>Called by every <see cref="Setting{T}.Set"/>, before its frame is pushed.</summary>
74+
internal static void NoteScoped()
75+
{
76+
if (!anyEverScoped)
77+
System.Threading.Volatile.Write(ref anyEverScoped, true);
78+
}
79+
80+
/// <summary>
81+
/// Whether any setting reads, in this flow, from a scope rather than from its default.
82+
/// Until a scope of any setting has been opened somewhere this is one read of a flag; after
83+
/// that, one async-local read for each setting that has ever been scoped.
84+
/// </summary>
85+
internal static bool AnyScopeOpen()
86+
{
87+
if (!System.Threading.Volatile.Read(ref anyEverScoped))
88+
return false;
89+
var settings = System.Threading.Volatile.Read(ref registered);
90+
for (var i = 0; i < settings.Length; i++)
91+
if (settings[i].EverScoped && settings[i].CurrentState is not null)
92+
return true;
93+
return false;
94+
}
95+
6896
/// <summary>What every setting reads as right now, in this flow.</summary>
6997
internal static object?[] Snapshot()
7098
{
@@ -156,6 +184,8 @@ internal Setting(T defaultValue)
156184
/// </summary>
157185
object? ISettingState.CurrentState => frames.Value;
158186

187+
bool ISettingState.EverScoped => EverScoped;
188+
159189
/// <summary>
160190
/// Whether a scope of this setting has been opened, in any flow, since the process
161191
/// 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)
185215
// Before the frame, so that no flow can see the frame without the flag.
186216
if (!everScoped)
187217
Volatile.Write(ref everScoped, true);
218+
SettingsState.NoteScoped();
188219
frames.Value = new Frame(id, value, frames.Value);
189220
return new AutoBackRollableTemporarySettingUnit(this, id);
190221
}

‎Sources/AngouriMath/Convenience/UnsafeAndInternal/MathS.UnsafeAndInternal.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public static class UnsafeAndInternal
2727
/// instead and set the flag useCache to false)
2828
/// </summary>
2929
public static void ClearFromStringCache()
30-
=> (stringToEntityCache, stringToEntityCacheExplicitOnly) = (new(), new());
30+
=> stringToEntityCache = new();
3131

3232
/// <summary>
3333
/// Checks if two expressions are equivalent if

‎Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,98 @@ public void Issue602_ExplicitToleranceIsStillRespected()
170170
Assert.Equal(Entity.Number.Integer.Create(0), "1e-20".ToEntity().EvalNumerical());
171171
}
172172

173+
// The parse cache answered a string with whatever it had been parsed to first, under
174+
// whichever settings were then in force, though a literal is rounded by them as it is
175+
// parsed. https://github.com/asc-community/AngouriMath/issues/2478
176+
private static System.IDisposable ScopeOf(string setting) => setting switch
177+
{
178+
"zero range 1e-10" => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -10)),
179+
"20 digits" => MathS.Settings.DecimalPrecisionContext.Set(new EContext(20, ERounding.HalfUp, -100000, 100000, false)),
180+
"max 100" => MathS.Settings.MaxAbsNumeratorOrDenominatorValue.Set(EInteger.FromInt32(100)),
181+
"no downcasting" => MathS.Settings.DowncastingEnabled.Set(false),
182+
_ => throw new System.ArgumentException(setting),
183+
};
184+
185+
// The type with the value: an Integer and a Real of one value are different parses.
186+
private static (System.Type, Entity) Parse(string text, bool useCache = true)
187+
{
188+
var parsed = MathS.FromString(text, useCache);
189+
return (parsed.GetType(), parsed);
190+
}
191+
192+
[Theory]
193+
[InlineData("1e-20", "zero range 1e-10")]
194+
[InlineData("1e-20", "20 digits")]
195+
[InlineData("0.333333333333333333333333", "zero range 1e-10")]
196+
[InlineData("0.333333333333333333333333", "20 digits")]
197+
[InlineData("1.00000000001", "zero range 1e-10")]
198+
[InlineData("0.142857142857142857142857142857", "20 digits")]
199+
[InlineData("0.12345679", "20 digits")]
200+
[InlineData("0.12345679", "max 100")]
201+
[InlineData("1", "no downcasting")]
202+
[InlineData("0.1", "no downcasting")]
203+
public void Issue2478_ACachedParseIsTheParseUnderTheSettingsInForce(string text, string setting)
204+
{
205+
var atDefaults = Parse(text, useCache: false);
206+
(System.Type, Entity) inScope;
207+
using (ScopeOf(setting))
208+
inScope = Parse(text, useCache: false);
209+
Assert.NotEqual(atDefaults, inScope);
210+
211+
// Defaults first, then the scope, on one string object.
212+
var first = new string(text.ToCharArray());
213+
Assert.Equal(atDefaults, Parse(first));
214+
using (ScopeOf(setting))
215+
Assert.Equal(inScope, Parse(first));
216+
217+
// The scope first, then the defaults.
218+
var second = new string(text.ToCharArray());
219+
using (ScopeOf(setting))
220+
Assert.Equal(inScope, Parse(second));
221+
Assert.Equal(atDefaults, Parse(second));
222+
223+
// And the interned literal, which every assembly in the process shares.
224+
var interned = string.Intern(text);
225+
Assert.Equal(atDefaults, Parse(interned));
226+
using (ScopeOf(setting))
227+
Assert.Equal(inScope, Parse(interned));
228+
Assert.Equal(atDefaults, Parse(interned));
229+
}
230+
231+
// A scope is the calling flow's, so one thread's scope must not decide what another
232+
// thread's parse of the same string object is, in either order.
233+
// https://github.com/asc-community/AngouriMath/issues/2478
234+
[Fact]
235+
public void Issue2478_AScopeOnOneThreadDoesNotReachAnothersParse()
236+
{
237+
var atDefaults = Parse("1e-20", useCache: false);
238+
(System.Type, Entity) inScope;
239+
using (ScopeOf("zero range 1e-10"))
240+
inScope = Parse("1e-20", useCache: false);
241+
Assert.NotEqual(atDefaults, inScope);
242+
243+
(System.Type, Entity) OnAThread(string text, bool scoped)
244+
{
245+
(System.Type, Entity) result = default;
246+
var thread = new System.Threading.Thread(() =>
247+
{
248+
using var _ = scoped ? ScopeOf("zero range 1e-10") : null;
249+
result = Parse(text);
250+
});
251+
thread.Start();
252+
thread.Join();
253+
return result;
254+
}
255+
256+
var first = new string("1e-20".ToCharArray());
257+
Assert.Equal(atDefaults, OnAThread(first, scoped: false));
258+
Assert.Equal(inScope, OnAThread(first, scoped: true));
259+
260+
var second = new string("1e-20".ToCharArray());
261+
Assert.Equal(inScope, OnAThread(second, scoped: true));
262+
Assert.Equal(atDefaults, OnAThread(second, scoped: false));
263+
}
264+
173265
// https://github.com/asc-community/AngouriMath/issues/561
174266
// The reporter's 4x4 matrix spans 1e5 to 1e50, so entries of its inverse fall
175267
// below 1e-16 and downcasting rounded them to zero. Fixed by the same change as

0 commit comments

Comments
 (0)