diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md
index b12b6f2cd..4bb1b2b2d 100644
--- a/BREAKING-CHANGES.md
+++ b/BREAKING-CHANGES.md
@@ -244,6 +244,31 @@ complex constant, an argument of any other shape. With `Simplify`, against mpmat
A symbol is read as real here, as everywhere the breaks are read, so `integral(1/(1+(t-y)^2), t, -oo, +oo)` is still
`pi`, which is the value for `|Im y| < 1`.
+### A value cached on a node is the value under the settings in force
+
+**Silent: a stale value is corrected.** `Evaled`, `InnerSimplified`, `DomainCondition`, a matrix's `Determinant`,
+`Inverse`, `Adjugate`, `Rank`, `Eigenvalues` and row echelon forms, and the ends of an interval as `Contains` reads them,
+are computed once per node and kept. Each was kept whatever the settings were then, and answered under any settings
+afterwards, on any thread; only `Evaled` noted `DecimalPrecisionContext`. An evaluation rounds by the settings —
+`PrecisionErrorZeroRange` decides what is zero — so the same node answered differently depending on where it had first
+been asked ([#2479](https://github.com/asc-community/AngouriMath/issues/2479)). Each is now kept with the settings it
+was computed under and answered only under those. Asked of one node first inside `PrecisionErrorZeroRange.Set(1e-10)`,
+then at the defaults:
+
+| Input | At the defaults, was (2.7.0) | Now |
+|---|---|---|
+| `(1/3 - 0.33333333333333333333).Evaled` | `0` | `3.333…E-21` |
+| `(1 + 1e-20).Evaled` | `1` | `1.00000000000000000001` |
+| `(x * (1/3 - 0.33333333333333333333)).InnerSimplified` | `0` | `x * (1/3 - 0.33333333333333333333)` |
+| `(1 / (x - (1/3 - 0.33333333333333333333))).DomainCondition` | `not x = 0` | `not x - (1/3 - 0.33333333333333333333) = 0` |
+| `[[0.333333333333333333333333, 1], [1, 3]].Determinant` | `0` | `0.333333333333333333333333 * 3 - 1` |
+| the same matrix's `Rank` | `1` | `2` |
+| the same matrix's `Inverse` | `null` | `[[-3000000000000000000000000, 1000000000000000000000000], [1000000000000000000000000, -333333333333333333333333]]` |
+| `[1/3 - 0.33333333333333333333; 1].Contains(0)` | `True` | `False` |
+
+In the other order each value computed at the defaults came back inside the scope: `Evaled` of the first was
+`3.333…E-21` there, where the scope's answer is `0`. Outside any scope nothing moves.
+
### `dot` and `cross` of a name for a vector are nodes
**Not silent: what was refused now parses.** `dot(a, b)` and `cross(a, b)` threw `InvalidArgumentParseException`
diff --git a/Sources/AngouriMath/Convenience/SettingClass.cs b/Sources/AngouriMath/Convenience/SettingClass.cs
index fbe2920a3..ea88d5e2b 100644
--- a/Sources/AngouriMath/Convenience/SettingClass.cs
+++ b/Sources/AngouriMath/Convenience/SettingClass.cs
@@ -1,4 +1,4 @@
-//
+//
// Copyright (c) 2019-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
@@ -24,8 +24,9 @@ internal interface ISettingState
}
///
- /// What every setting reads as, taken together, so that something holding a result computed
- /// under the settings of a moment can tell whether those settings still hold.
+ /// What every setting reads as, taken together, as one object, so that something holding a
+ /// result computed under the settings of a moment can tell whether those settings still hold
+ /// with one async-local read and one reference comparison.
///
///
///
@@ -38,26 +39,30 @@ internal interface ISettingState
/// the counter was built first and threw away the whole benefit.
///
///
- /// The state of one setting is the reference to the frame on top of its stack, which
- /// is exact rather than a hash — releasing a scope restores the very frame object that was
- /// there before it, since the chain below a pushed frame is never rebuilt. So comparing
- /// snapshots is a handful of reference comparisons with no chance of collision, and a
- /// balanced open-and-close compares equal, which is the whole point.
+ /// A is reached from the defaults by the scopes opened to reach it,
+ /// setting by setting and value by value, and is made once for each path: opening a scope of
+ /// a setting at a value from a state gives the state it gave before. So the scopes the
+ /// library opens on every call — Solve opens two — reach the same state on every
+ /// call, and a value cached under them is found again. A scope closed in order puts back
+ /// the very state it replaced, so a balanced open and close compares equal, and one closed out
+ /// of order reaches the state the scopes left open reach. Values compare by
+ /// , so a value compared by reference only is conservative:
+ /// it reaches a state of its own, and a value cached under it is not found again.
+ /// https://github.com/asc-community/AngouriMath/issues/2479
///
///
internal static class SettingsState
{
///
- /// Every setting there is. Replaced rather than appended to, so that a reader can walk it
- /// without a lock: registering happens as the settings are constructed and a reader is on
- /// the integrator's hot path, where taking a lock per call would be contention bought for
- /// a list that stops changing before any real work starts.
+ /// Every setting there is, at the index it reads its value from in a .
+ /// Replaced rather than appended to, so that a reader can walk it without a lock.
///
[ConcurrentField] private static ISettingState[] registered = System.Array.Empty();
[ConcurrentField] private static readonly object registering = new();
- internal static void Register(ISettingState setting)
+ /// Registers a setting, and answers its index.
+ internal static int Register(ISettingState setting)
{
lock (registering)
{
@@ -65,59 +70,328 @@ internal static void Register(ISettingState setting)
System.Array.Copy(registered, grown, registered.Length);
grown[^1] = setting;
System.Threading.Volatile.Write(ref registered, grown);
+ return grown.Length - 1;
}
}
+ /// One value a scope put on a setting, with the one it covers. Never mutated once built.
+ internal sealed class Entry
+ {
+ internal readonly object Setting;
+ internal readonly object Value;
+ internal readonly Entry? Below;
+ internal Entry(object setting, object value, Entry? below) => (Setting, Value, Below) = (setting, value, below);
+ }
+
+ ///
+ /// What every setting reads as: the top of each setting's stack, by its index. Never mutated
+ /// once built, but for the table of the states one scope away, which only grows, and only
+ /// by an atomic exchange.
+ ///
+ internal sealed class State
+ {
+ private readonly Entry?[] tops;
+
+ ///
+ /// The state this one was reached from, held so that a state kept alive keeps the path
+ /// to it alive: a value cached under it is found again by a flow that opens the same
+ /// scopes from the defaults, which it would not be if a state on the way had been
+ /// collected and made again as another object.
+ ///
+ private readonly State? parent;
+
+ ///
+ /// The states one scope away, with the setting and the value that reach each, held
+ /// weakly: a state is kept by the scopes open in it and by the values cached under it,
+ /// and once neither is left it is collected and its entry dropped the next time one is
+ /// added. So a program that scopes a value that differs on every call -- a precision
+ /// computed from its data -- keeps no more states than it has scopes open and values
+ /// cached. And at most of the entries are of one setting, so that
+ /// those values, while they are alive, do not crowd out the scopes of the others, which
+ /// the library opens on every call; past it a scope of that setting reaches a state of
+ /// its own, which only costs its values a cache miss.
+ ///
+ ///
+ /// Two flows opening the same scope at once both read the table; the one whose exchange
+ /// fails reads it again, finds the state the other added and answers that one, so both
+ /// get the same object. Where they do not -- past the bound, or a state collected and
+ /// made again -- two states with the same values are only a cache miss: a value is
+ /// answered under the state object it was computed under, never under another with the
+ /// same contents, and a state object is never changed once made.
+ ///
+ private (object Setting, object Value, WeakReference Reached)[] next = System.Array.Empty<(object, object, WeakReference)>();
+ internal const int Bound = 32;
+
+ internal State(Entry?[] tops, State? parent) => (this.tops, this.parent) = (tops, parent);
+
+ internal Entry? Top(int index) => index < tops.Length ? tops[index] : null;
+
+ /// The state with on ; compared as , so that a value type is not boxed to look it up.
+ internal State After(Setting setting, int index, T value) where T : notnull
+ {
+ var known = System.Threading.Volatile.Read(ref next);
+ while (true)
+ {
+ foreach (var (s, v, reached) in known)
+ if (ReferenceEquals(s, setting) && v is T seen && System.Collections.Generic.EqualityComparer.Default.Equals(seen, value)
+ && reached.TryGetTarget(out var state))
+ return state;
+ if (Added(setting, index, value, ref known) is { } made)
+ return made;
+ }
+ }
+
+ /// The same for a value already boxed, as a scope closed out of order replays the ones above it.
+ internal State After(object setting, int index, object value)
+ {
+ var known = System.Threading.Volatile.Read(ref next);
+ while (true)
+ {
+ foreach (var (s, v, reached) in known)
+ if (ReferenceEquals(s, setting) && Equals(v, value) && reached.TryGetTarget(out var state))
+ return state;
+ if (Added(setting, index, value, ref known) is { } made)
+ return made;
+ }
+ }
+
+ // The state reached, added to the table, with the entries of collected states dropped,
+ // where there is room for one more of its setting; null where another flow changed the
+ // table first, with known set to what it changed it to, to be read again.
+ private State? Added(object setting, int index, object value, ref (object, object, WeakReference)[] known)
+ {
+ var pushed = new Entry?[System.Math.Max(tops.Length, index + 1)];
+ System.Array.Copy(tops, pushed, tops.Length);
+ pushed[index] = new Entry(setting, value, Top(index));
+ var made = new State(pushed, this);
+ var kept = new System.Collections.Generic.List<(object, object, WeakReference)>(known.Length + 1);
+ var ofThisSetting = 0;
+ foreach (var entry in known)
+ if (entry.Item3.TryGetTarget(out _))
+ {
+ kept.Add(entry);
+ if (ReferenceEquals(entry.Item1, setting))
+ ofThisSetting++;
+ }
+ if (ofThisSetting >= Bound)
+ return made;
+ kept.Add((setting, value, new WeakReference(made)));
+ var was = System.Threading.Interlocked.CompareExchange(ref next, kept.ToArray(), known);
+ if (ReferenceEquals(was, known))
+ return made;
+ known = was;
+ return null;
+ }
+ }
+
+ ///
+ /// One scope open in a flow: its id, which is what releases it, the setting it is on, the
+ /// state with it open, and the scope that was innermost when it opened. Made for each scope
+ /// opened, so that a scope is released by its own id and by nothing
+ /// else: a copy of the disposal struct disposed twice, or after the same scope was opened
+ /// again, finds no scope with its id and does nothing.
+ ///
+ internal sealed class Scope
+ {
+ internal readonly long Id;
+ internal readonly int Index;
+ internal readonly State State;
+ internal readonly Scope? Below;
+ internal Scope(long id, int index, State state, Scope? below) => (Id, Index, State, Below) = (id, index, state, below);
+ }
+
+ /// The defaults, from which the states are reached; a flow at them reads .
+ [ConstantField] private static readonly State defaults = new(System.Array.Empty(), parent: null);
+
+ [ConcurrentField] private static readonly AsyncLocal scopes = new();
+
+ [ConcurrentField] private static long lastId;
+
+ /// Whether any setting has been scoped, in any flow, since the process started.
[ConcurrentField] private static bool anyEverScoped;
- /// Called by every , before its frame is pushed.
- internal static void NoteScoped()
+ ///
+ /// What every setting reads as in this flow: where every setting
+ /// reads its default, which costs one read of a flag until a scope has been opened.
+ ///
+ internal static State? Current => System.Threading.Volatile.Read(ref anyEverScoped) ? scopes.Value?.State : null;
+
+ /// Whether any setting reads, in this flow, from a scope rather than from its default.
+ internal static bool AnyScopeOpen() => Current is not null;
+
+ /// Opens a scope of at , and answers the id that releases it.
+ internal static long Open(Setting setting, int index, T value) where T : notnull
{
if (!anyEverScoped)
System.Threading.Volatile.Write(ref anyEverScoped, true);
+ var id = Interlocked.Increment(ref lastId);
+ var below = scopes.Value;
+ scopes.Value = new Scope(id, index, (below?.State ?? defaults).After(setting, index, value), below);
+ return id;
}
///
- /// 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.
+ /// Releases the scope numbered , wherever in this flow's scopes it sits.
+ /// Released in order, which is the cheap case, the scope below it is back; out of order, the
+ /// scopes above it are opened again over the one below it, so the flow reaches the state it
+ /// would have reached without it. An id that is not in this flow's scopes -- opened in another
+ /// flow, or released already -- is not an error and undoes nothing.
+ ///
+ internal static void Close(long id)
+ {
+ var top = scopes.Value;
+ if (top is null)
+ return;
+ if (top.Id == id)
+ {
+ scopes.Value = top.Below;
+ return;
+ }
+ var above = new System.Collections.Generic.List();
+ var current = top;
+ while (current is not null && current.Id != id)
+ {
+ above.Add(current);
+ current = current.Below;
+ }
+ if (current is null)
+ return;
+ var rebuilt = current.Below;
+ for (var i = above.Count - 1; i >= 0; i--)
+ {
+ var scope = above[i];
+ var entry = scope.State.Top(scope.Index)!;
+ rebuilt = new Scope(scope.Id, scope.Index, (rebuilt?.State ?? defaults).After(entry.Setting, scope.Index, entry.Value), rebuilt);
+ }
+ scopes.Value = rebuilt;
+ }
+
+ /// What every setting reads as right now, in this flow.
+ internal static object?[] Snapshot() => new object?[] { Current };
+
+ /// Whether is still what every setting reads as.
+ internal static bool StillHolds(object?[] snapshot)
+ => snapshot.Length == 1 && ReferenceEquals(snapshot[0], Current);
+ }
+
+ ///
+ /// A value of a with the state it was computed under,
+ /// for the defaults, and the one value before it computed under another
+ /// state, if any. Two are kept because the library's own scopes ask a node under two states in
+ /// turn -- Solve's, and its analytical solver's inside it, with the zero range at 1e-7 --
+ /// and one slot recomputed the value at every turn: 46% more allocation on solving a quadratic.
+ /// Not generic, so that the type test on every read needs no lookup of the type in the code
+ /// shared between the instantiations over reference types.
+ ///
+ internal sealed class SettingsStamped
+ {
+ internal readonly object? Value;
+ internal readonly SettingsState.State? State;
+ internal readonly SettingsStamped? Previous;
+ internal SettingsStamped(object? value, SettingsState.State? state, SettingsStamped? previous)
+ => (Value, State, Previous) = (value, state, previous);
+
+ /// Stands for a value of computed at the defaults, which an empty slot cannot.
+ [ConstantField] internal static readonly object NullAtDefaults = new();
+ }
+
+ ///
+ /// A cached value that depends on the settings it was computed under -- an evaluation, whose
+ /// numbers are rounded by the precision and the zero range, and anything computed from one.
+ /// Answered only under the settings it was computed under:
+ /// is the stamp, and a value computed with every setting at its default is held as it is, so
+ /// that the common case costs no more than .
+ /// Equal to every other, as a cache on a record has to be, so that it takes no part in the
+ /// record's equality.
+ /// https://github.com/asc-community/AngouriMath/issues/2479
+ ///
+ internal struct SettingsDependent : IEquatable>
+ {
+ // Null, nothing yet; a SettingsStamped, the values of up to two states; anything else, the
+ // value computed at the defaults alone, or NullAtDefaults. One field, written in one store,
+ // so that no flow reads one flow's value under another's stamp.
+ private object? slot;
+
+ [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+ public T GetValue(Func compute, TOwner owner)
+ => TryGetValue(out var value) ? value : Computed(compute, owner);
+
+ ///
+ /// The value computed under the settings in force, where there is one. Apart from
+ /// so that a reader on a hot path pays for the delegate only on a miss.
///
- internal static bool AnyScopeOpen()
+ [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+ public bool TryGetValue(out T value)
{
- if (!System.Threading.Volatile.Read(ref anyEverScoped))
+ var seen = Volatile.Read(ref slot);
+ if (seen is null)
+ {
+ value = default!;
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)
+ }
+ var current = SettingsState.Current;
+ if (seen is SettingsStamped stamped)
+ {
+ if (ReferenceEquals(stamped.State, current))
+ {
+ value = Read(stamped.Value);
+ return true;
+ }
+ if (stamped.Previous is { } previous && ReferenceEquals(previous.State, current))
+ {
+ value = Read(previous.Value);
return true;
+ }
+ }
+ else if (current is null)
+ {
+ value = Read(seen);
+ return true;
+ }
+ value = default!;
return false;
}
- /// What every setting reads as right now, in this flow.
- internal static object?[] Snapshot()
+ // Only a T, or NullAtDefaults for a null, is ever stored, so a reference is read without
+ // the type check a cast to a type that is not sealed costs on every read.
+ [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+ private static T Read(object? stored)
{
- var settings = System.Threading.Volatile.Read(ref registered);
- var snapshot = new object?[settings.Length];
- for (var i = 0; i < snapshot.Length; i++)
- snapshot[i] = settings[i].CurrentState;
- return snapshot;
+ if (ReferenceEquals(stored, SettingsStamped.NullAtDefaults) || stored is null)
+ return default!;
+#if NET
+ return typeof(T).IsValueType ? (T)stored : System.Runtime.CompilerServices.Unsafe.As