Skip to content

Commit acf4a84

Browse files
Evaled is cached with the precision frame it was computed in (#1514)
The cache was stamped with the evaluation epoch, one counter for the whole process that every change of the precision advanced, while a precision scope belongs to one flow: a flow that opened a scope and evaluated a node another flow shares left the value current for every flow, so a flow at a hundred digits read pi at three hundred. The stamp is now the precision setting's frame for the flow, compared by reference; the value, the node it was computed for and the frame are one object published in one store. The epoch had no other reader and is gone, with its increment on every Set and every scope's end. Until a precision scope has been opened somewhere, no flow has a frame, and the async-local read is skipped. Closes #1505. Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dd7f10d commit acf4a84

4 files changed

Lines changed: 81 additions & 54 deletions

File tree

‎Sources/AngouriMath/Convenience/MathS.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6105,7 +6105,7 @@ internal static EDecimal DowncastingTolerance
61056105
/// Settings for <see cref="EDecimal"/> precisions of <a href="https://github.com/peteroupc/Numbers">PeterO.Numbers</a>
61066106
/// </summary>
61076107
public static Setting<EContext> DecimalPrecisionContext { get; } =
6108-
new(new EContext(100, ERounding.HalfUp, -100, 1000, false)) { AdvancesEvaluationEpoch = true };
6108+
new(new EContext(100, ERounding.HalfUp, -100, 1000, false));
61096109

61106110
/// <summary>
61116111
/// Whether functions are being read as real-valued or complex-valued. It is a

‎Sources/AngouriMath/Convenience/SettingClass.cs‎

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -92,28 +92,6 @@ internal static bool StillHolds(object?[] snapshot)
9292
}
9393
}
9494

95-
/// <summary>
96-
/// A count of the changes to what a numerical evaluation depends on -- the precision
97-
/// context, set or its scope ended, on any thread. An <see cref="Entity"/> records the
98-
/// epoch its <see cref="Entity.Evaled"/> was computed at and recomputes when it has moved,
99-
/// since a hundred digits of pi cached at one precision are the wrong answer at another.
100-
/// One counter for every thread: a change on another thread costs a recomputation and
101-
/// never a stale value. The downcasting setting does not advance it: the integrator's
102-
/// sampled checks turn the downcasting off and on around every candidate, and an epoch
103-
/// moved by those made every cached evaluation in the process stale each time -- the
104-
/// unit suite took four times as long. What the downcasting changed in a cached value
105-
/// that mattered, a constant's type, no longer depends on it.
106-
/// https://github.com/asc-community/AngouriMath/issues/1367
107-
/// </summary>
108-
internal static class EvaluationEpoch
109-
{
110-
[ConcurrentField] private static int current;
111-
112-
internal static int Current => Volatile.Read(ref current);
113-
114-
internal static void Advance() => Interlocked.Increment(ref current);
115-
}
116-
11795
/// <summary>
11896
/// This class for configuring some internal mechanisms from outside
11997
/// </summary>
@@ -161,19 +139,14 @@ private sealed class Frame
161139

162140
private readonly AsyncLocal<Frame?> frames = new();
163141
private long lastId;
142+
private bool everScoped;
164143

165144
internal Setting(T defaultValue)
166145
{
167146
Default = defaultValue;
168147
SettingsState.Register(this);
169148
}
170149

171-
/// <summary>
172-
/// Whether a change of this setting advances the <see cref="EvaluationEpoch"/>: the
173-
/// precision context does, since every cached evaluation depends on it.
174-
/// </summary>
175-
internal bool AdvancesEvaluationEpoch { get; init; }
176-
177150
/// <summary>
178151
/// The frame this setting currently reads from, as the identity of its state. Released
179152
/// in order — which <c>using</c> guarantees — a scope restores the very frame that was
@@ -183,6 +156,14 @@ internal Setting(T defaultValue)
183156
/// </summary>
184157
object? ISettingState.CurrentState => frames.Value;
185158

159+
/// <summary>
160+
/// Whether a scope of this setting has been opened, in any flow, since the process
161+
/// started, so that a reader can skip asking for the flow's frame while none can exist.
162+
/// It never goes back: a child flow that captured a scope keeps it after its parent
163+
/// disposes it, so a count of open scopes returning to zero would not mean there are none.
164+
/// </summary>
165+
internal bool EverScoped => Volatile.Read(ref everScoped);
166+
186167
/// <summary>
187168
/// Sets the new value for the setting
188169
/// </summary>
@@ -201,9 +182,10 @@ internal Setting(T defaultValue)
201182
public AutoBackRollableTemporarySettingUnit Set(T value)
202183
{
203184
var id = Interlocked.Increment(ref lastId);
185+
// Before the frame, so that no flow can see the frame without the flag.
186+
if (!everScoped)
187+
Volatile.Write(ref everScoped, true);
204188
frames.Value = new Frame(id, value, frames.Value);
205-
if (AdvancesEvaluationEpoch)
206-
EvaluationEpoch.Advance();
207189
return new AutoBackRollableTemporarySettingUnit(this, id);
208190
}
209191

@@ -220,8 +202,6 @@ private void Remove(long id)
220202
var top = frames.Value;
221203
if (top is null)
222204
return;
223-
if (AdvancesEvaluationEpoch)
224-
EvaluationEpoch.Advance();
225205
if (top.Id == id)
226206
{
227207
frames.Value = top.Next;

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs‎

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -184,33 +184,47 @@ public Entity Evaled
184184
{
185185
get
186186
{
187-
// Cached for the epoch it was computed under -- the precision context and
188-
// the downcasting: a hundred digits of pi are the wrong answer at five
189-
// hundred, and an expression held across a change of the settings used to
190-
// answer from the first ones. The epoch is read before the computation and
191-
// recorded with its result, so that a scope opened and closed inside the
192-
// computation -- the integrator's sampled checks turn the downcasting off --
193-
// leaves a value stamped as stale, to be recomputed on the next read, and
194-
// never a slot cleared under a computation still running; the lazy slot it
195-
// was, reset on a stale epoch, was cleared that way and read back as null.
187+
// Cached with the precision it was computed at, and read back only at that
188+
// precision: a hundred digits of pi are the wrong answer at five hundred. The
189+
// stamp is the precision setting's frame for this flow, compared by reference.
190+
// Frames are immutable, a scope opened and closed in order restores the very
191+
// frame that was under it, and a flow outside every scope has none. It was a
192+
// count of precision changes for the whole process, which could not tell one
193+
// flow's scope from another's, so a flow at a hundred digits read pi at three
194+
// hundred while another flow's scope was open.
195+
// https://github.com/asc-community/AngouriMath/issues/1505
196+
// The frame is read before the computation, so a scope opened and closed inside
197+
// it leaves the value stamped with the frame it was asked in.
196198
// https://github.com/asc-community/AngouriMath/issues/1367
197199
// And stamped with its owner: a record's `with` -- WithCodomain, and the
198-
// derivative's rewrites -- copies every field, this one included, and a
199-
// value computed for the original is not the copy's; the lazy slot carried
200-
// the same stamp.
201-
var epoch = Convenience.EvaluationEpoch.Current;
202-
if (evaled is { } cached && evaledEpoch == epoch && ReferenceEquals(evaledOwner, this))
203-
return cached;
200+
// derivative's rewrites -- copies every field, this one included, and a value
201+
// computed for the original is not the copy's.
202+
// The value and its stamps are one object, published in one store, so that no
203+
// flow reads one flow's value under another's stamp.
204+
// Until a precision scope has been opened somewhere, no flow has a frame, and a
205+
// cached value is read without asking for one: the flow's frame is an async-local
206+
// read, several times the cost of the rest of this path.
207+
var precisionSetting = MathS.Settings.DecimalPrecisionContext;
208+
var precision = precisionSetting.EverScoped ? ((Convenience.ISettingState)precisionSetting).CurrentState : null;
209+
if (System.Threading.Volatile.Read(ref evaled) is { } cached
210+
&& ReferenceEquals(cached.Owner, this) && ReferenceEquals(cached.Precision, precision))
211+
return cached.Value;
204212
var computed = InnerSimplifyWithCheck(false);
205-
evaledEpoch = epoch;
206-
evaledOwner = this;
207-
evaled = computed;
213+
System.Threading.Volatile.Write(ref evaled, new EvaledValue(computed, this, precision));
208214
return computed;
209215
}
210216
}
211-
private Entity? evaled;
212-
private Entity? evaledOwner;
213-
private int evaledEpoch;
217+
218+
/// <summary>A value of <see cref="Evaled"/>, with the node and the precision it was computed for.</summary>
219+
private sealed class EvaledValue
220+
{
221+
internal readonly Entity Value;
222+
internal readonly Entity Owner;
223+
internal readonly object? Precision;
224+
internal EvaledValue(Entity value, Entity owner, object? precision)
225+
=> (Value, Owner, Precision) = (value, owner, precision);
226+
}
227+
private EvaledValue? evaled;
214228

215229
/// <summary>
216230
/// This is the result of naive simplifications, but not creating imprecise <see cref="Real"/> values unlike <see cref="Evaled"/>. In other

‎Sources/Tests/UnitTests/Core/HighPrecisionFunctionsTest.cs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,39 @@ public void ConstantsAndCachedEvaluationsFollowThePrecision()
262262
Assert.Equal(100, DigitsOf(held.EvalNumerical()));
263263
}
264264

265+
/// <summary>
266+
/// The same across two flows at once: one flow in a raised precision evaluates a shared
267+
/// node while another flow, at the default, reads it. The cache was stamped with the
268+
/// process's epoch and not with the flow's precision, so the default flow read pi at
269+
/// three hundred digits until the other scope closed.
270+
/// https://github.com/asc-community/AngouriMath/issues/1505
271+
/// </summary>
272+
[Fact]
273+
public void AnotherFlowsPrecisionIsNotServedHere()
274+
{
275+
using var evaluated = new System.Threading.ManualResetEventSlim();
276+
using var release = new System.Threading.ManualResetEventSlim();
277+
// A thread of its own, so that a busy pool cannot hold it back past the waits below.
278+
var other = System.Threading.Tasks.Task.Factory.StartNew(() =>
279+
{
280+
using var _ = MathS.Settings.DecimalPrecisionContext.Set(threeHundredDigits);
281+
var there = DigitsOf(MathS.pi.EvalNumerical());
282+
evaluated.Set();
283+
release.Wait(System.TimeSpan.FromSeconds(30));
284+
return there;
285+
}, System.Threading.Tasks.TaskCreationOptions.LongRunning);
286+
try
287+
{
288+
Assert.True(evaluated.Wait(System.TimeSpan.FromSeconds(30)));
289+
Assert.Equal(100, DigitsOf(MathS.pi.EvalNumerical()));
290+
}
291+
finally
292+
{
293+
release.Set();
294+
}
295+
Assert.Equal(300, other.Result);
296+
}
297+
265298
/// <summary>
266299
/// <c>e</c> evaluated with the downcasting off used to be a complex number with a zero
267300
/// imaginary part, and the cache on the constant kept it that way for the rest of the

0 commit comments

Comments
 (0)