From 1f23e1c30c8550df86ff1c9272481457f8848dfd Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 06:36:26 +0000 Subject: [PATCH 1/2] A value cached on a node is the value under the settings in force Evaled, InnerSimplified, DomainCondition, a matrix's determinant, inverse, adjugate, rank, eigenvalues and echelon forms, and an interval's numeric ends were kept as first computed and answered under any settings after, on any thread; Evaled alone noted the precision. 1/3 - 0.33333333333333333333 evaluated inside a zero range of 1e-10 was 0 afterwards at the defaults, where it is 3.3E-21. Every setting's stack now lives in one immutable SettingsState.State, made once per path of scopes from the defaults, so the scopes the library opens on every call reach the same state each time and a balanced open and close puts back the very state it replaced. A setting reads its value from it; Snapshot and StillHolds become one reference comparison. A flow holds one Scope per scope open, with its own id, so a scope is released by its id alone: disposing twice, or a stale copy after the same scope reopened, does nothing, and a scope closed out of order replays the ones above it. States one scope away are held weakly, each keeping the one it was reached from, so scopes of values that differ on every call are collected once nothing is open or cached under them, and at most 32 entries of one setting are kept. The caches above are SettingsDependent: a value computed at the defaults is held as it is, a value computed in a scope with its state, and the last two states are kept, so a node asked in turn under Solve's settings and its analytical solver's is not recomputed at every turn. Entity gets a copy constructor so that a `with` copy keeps the structural caches and not the values. TryDowncast now simplifies the root it does not replace outside the 1e-7 zero range it guesses a rational with. Kernel benchmark against master on one machine: allocation lower on Derivate (-4.1%), EvalPolynomialFresh (-3.5%), SimplifyEasy (-3.4%) and SimplifyHard (-5.1%), from the evaluation cache no longer allocating at the defaults; SolveEasy +9.0%, from the residual check evaluating its roots with downcasting off rather than reading values cached with it on. Part of #2479 Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 25 + .../AngouriMath/Convenience/SettingClass.cs | 461 +++++++++++++----- .../Core/Entity/Entity.Definition.cs | 22 + .../Core/Entity/Omni/Entity.Matrix.cs | 21 +- .../Core/Entity/Omni/Entity.Omni.Classes.cs | 5 +- .../AnalyticalEquationSolver.cs | 20 +- .../Evaluation/Evaluation.Definition.cs | 58 +-- .../Common/NumericsRegressionTest.cs | 166 +++++++ Sources/Tests/UnitTests/Core/Settings.cs | 48 ++ 9 files changed, 648 insertions(+), 178 deletions(-) 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(ref stored); +#else + return (T)stored; +#endif } - /// - /// Whether is still what every setting reads as. One taken - /// before a setting existed has a different length and is reported stale, which is what - /// should happen — that setting's value was not part of it. - /// - internal static bool StillHolds(object?[] snapshot) + /// Computes the value under the settings in force and keeps it, with the one kept before under other settings. + public T Computed(Func compute, TOwner owner) { - var settings = System.Threading.Volatile.Read(ref registered); - if (snapshot.Length != settings.Length) - return false; - for (var i = 0; i < snapshot.Length; i++) - if (!ReferenceEquals(snapshot[i], settings[i].CurrentState)) - return false; - return true; + // The state is taken before the computation, so a scope opened and closed inside it + // leaves the value stamped with the state it was asked in. + var current = SettingsState.Current; + var computed = compute(owner); + var seen = Volatile.Read(ref slot); + object stored = (object?)computed ?? SettingsStamped.NullAtDefaults; + SettingsStamped? kept = seen switch + { + null => null, + // Another flow got there first under the same settings: keep what it kept. + SettingsStamped stamped when ReferenceEquals(stamped.State, current) => stamped.Previous, + SettingsStamped { Previous: null } stamped => stamped, + SettingsStamped stamped => new SettingsStamped(stamped.Value, stamped.State, previous: null), + _ when current is null => null, + _ => new SettingsStamped(seen, state: null, previous: null), + }; + Volatile.Write(ref slot, current is null && kept is null ? stored : new SettingsStamped(stored, current, kept)); + return computed; } + + public bool Equals(SettingsDependent other) => true; + public override bool Equals(object? obj) => obj is SettingsDependent; + public override int GetHashCode() => 0; } /// @@ -129,7 +403,8 @@ internal static bool StillHolds(object?[] snapshot) /// /// /// A setting is one object for the whole process, and what it holds is per *flow*, not - /// per thread: the stack of values lives in an . A scope + /// per thread: the stacks of values of every setting live in one + /// , as a . A scope /// opened before an is therefore still in force after it, and a /// scope opened inside a task is invisible to that task's siblings and to whatever /// started it. Backing the field with [ThreadStatic] gave neither: a continuation @@ -137,63 +412,43 @@ internal static bool StillHolds(object?[] snapshot) /// whatever scope was left on it into the next caller. /// /// - /// The frames are immutable, which is what makes the reference safe to share. An + /// The states are immutable, which is what makes the reference safe to share. An /// copies on assignment to - /// and on nothing else, so if a frame could be mutated in place, two flows holding the - /// same chain would write over each other. Pushing and popping therefore build a new - /// chain and assign it, rather than editing one. + /// and on nothing else, so if a state could be mutated in place, two flows holding it + /// would write over each other. Opening and closing a scope therefore assign another + /// state, rather than editing one. /// /// public sealed class Setting : ISettingState where T : notnull { - /// - /// One pushed value, and the chain below it. Never mutated once built. - /// - /// - /// is what a scope is released by, rather than the frame's own - /// reference. Releasing a scope that is not on top rebuilds everything above it, and - /// a rebuilt frame is a different object — so identifying a scope by its frame would - /// leave the ones above it impossible to release afterwards. The id is a counter and - /// not a : generating a guid per scope cost more than everything - /// else does put together. - /// - private sealed class Frame - { - internal readonly long Id; - internal readonly T Value; - internal readonly Frame? Next; - internal Frame(long id, T value, Frame? next) => (Id, Value, Next) = (id, value, next); - } - - private readonly AsyncLocal frames = new(); - private long lastId; + private readonly int index; private bool everScoped; internal Setting(T defaultValue) { Default = defaultValue; - SettingsState.Register(this); + index = SettingsState.Register(this); } /// - /// The frame this setting currently reads from, as the identity of its state. Released - /// in order — which using guarantees — a scope restores the very frame that was - /// on top before it, so this compares equal across a balanced open and close. Out of - /// order the chain above is rebuilt and this reads as a change, which is conservative - /// and not wrong. + /// The value this setting currently reads from, as the identity of its state. A scope + /// released in order puts back the very state that was there before it, so this + /// compares equal across a balanced open and close. /// - object? ISettingState.CurrentState => frames.Value; + object? ISettingState.CurrentState => Top; 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. + /// started, so that a reader can skip asking for the flow's state while none can hold it. /// It never goes back: a child flow that captured a scope keeps it after its parent /// disposes it, so a count of open scopes returning to zero would not mean there are none. /// internal bool EverScoped => Volatile.Read(ref everScoped); + private SettingsState.Entry? Top => EverScoped ? SettingsState.Current?.Top(index) : null; + /// /// Sets the new value for the setting /// @@ -211,46 +466,10 @@ internal Setting(T defaultValue) /// public AutoBackRollableTemporarySettingUnit Set(T value) { - var id = Interlocked.Increment(ref lastId); - // Before the frame, so that no flow can see the frame without the flag. + // Before the state, so that no flow can see the state 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); - } - - /// - /// Takes the scope numbered back out of this flow's chain, - /// wherever in it it sits. Disposal is normally in the reverse order of - /// , which is the cheap case of popping the head; out-of-order - /// disposal rebuilds what was above it. An id that is not in this flow's chain — - /// because the scope was opened in another one, or is already released — is not an - /// error and undoes nothing. - /// - private void Remove(long id) - { - var top = frames.Value; - if (top is null) - return; - if (top.Id == id) - { - frames.Value = top.Next; - return; - } - var above = new System.Collections.Generic.List(); - var current = top; - while (current is not null && current.Id != id) - { - above.Add(current); - current = current.Next; - } - if (current is null) - return; - var rebuilt = current.Next; - for (var i = above.Count - 1; i >= 0; i--) - rebuilt = new Frame(above[i].Id, above[i].Value, rebuilt); - frames.Value = rebuilt; + return new AutoBackRollableTemporarySettingUnit(SettingsState.Open(this, index, value)); } /// @@ -303,7 +522,7 @@ public TReturnType As(T value, Func action) /// /// The current value of the setting /// - public T Value => frames.Value is { } frame ? frame.Value : Default; + public T Value => Top is { } top ? (T)top.Value : Default; /// /// The default value of the setting @@ -316,7 +535,7 @@ public TReturnType As(T value, Func action) /// Lets a default be treated as "nobody expressed an opinion" rather than as a /// deliberate choice. /// - internal bool IsOverriden => frames.Value is not null; + internal bool IsOverriden => Top is not null; /// /// This tiny struct is needed to be under `using` operator, so that your settings @@ -328,18 +547,16 @@ public TReturnType As(T value, Func action) /// public struct AutoBackRollableTemporarySettingUnit : IDisposable { - private readonly Setting setting; - private bool disposed; private readonly long id; - internal AutoBackRollableTemporarySettingUnit(Setting settingToRollBack, long id) - => (setting, disposed, this.id) = (settingToRollBack, false, id); + private bool disposed; + internal AutoBackRollableTemporarySettingUnit(long id) => (this.id, disposed) = (id, false); /// public void Dispose() { if (disposed) return; - setting.Remove(id); + SettingsState.Close(id); disposed = true; } } diff --git a/Sources/AngouriMath/Core/Entity/Entity.Definition.cs b/Sources/AngouriMath/Core/Entity/Entity.Definition.cs index b0baa4788..558f44b05 100644 --- a/Sources/AngouriMath/Core/Entity/Entity.Definition.cs +++ b/Sources/AngouriMath/Core/Entity/Entity.Definition.cs @@ -132,6 +132,28 @@ public virtual bool Equals(Entity? other) /// The same for the hash: the node's kind, with each node's parts combined in by its own record. public override int GetHashCode() => EqualityContract.GetHashCode(); + /// Makes a node, with every cache empty. + protected Entity() { } + + /// + /// The copy a with makes -- , and a derivative taken once + /// more -- which is another node: it keeps the caches of what it shares with + /// , the children and what is counted from them, and not the + /// values, which a codomain or an order of differentiation changes. + /// https://github.com/asc-community/AngouriMath/issues/2479 + /// + protected Entity(Entity original) + { + directChildren = original.directChildren; + isFinite = original.isFinite; + complexity = original.complexity; + vars = original.vars; + varsAndConsts = original.varsAndConsts; + freeVariables = original.freeVariables; + simplifiedRate = original.simplifiedRate; + sortHashes = original.sortHashes; + } + /// /// Returns the array of the direct children. Will be /// only called once, so no need to cache anything. diff --git a/Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs b/Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs index cb6173868..a628e5645 100644 --- a/Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs +++ b/Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs @@ -318,7 +318,8 @@ public Entity AsScalar() }, this ); - private LazyPropertyA determinant; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent determinant; /// /// The determinant of the rows from down and the given @@ -440,7 +441,8 @@ private static Entity Laplace(Matrix matrix, int row, int[] columns) var lambda = Variable.CreateUnique(@this, "lambda"); return @this.CharacteristicPolynomial(lambda) is { } polynomial ? polynomial.SolveEquation(lambda) : null; }, this); - private LazyPropertyA eigenvalues; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent eigenvalues; /// Returns an inverse matrix if it exists /// @@ -463,7 +465,8 @@ private static Entity Laplace(Matrix matrix, int row, int[] columns) return OfTheShapeOf(@this, MathS.Matrix(@this.RowCount, @this.ColumnCount, (row, column) => adjugate[row, column] / determinant).InnerSimplified); }, this); - private LazyPropertyA inverse; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent inverse; /// @@ -600,7 +603,8 @@ public IEnumerator GetEnumerator() @ref.GetValue(static @this => OfTheShapeOf(@this, MathS.Matrix(Eliminate(@this, reduced: false).Entries).InnerSimplified), this); - private LazyPropertyA @ref; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent @ref; /// /// Reduced row echelon form via Gaussian elimination. @@ -613,7 +617,8 @@ public IEnumerator GetEnumerator() rref.GetValue(static @this => OfTheShapeOf(@this, MathS.Matrix(Eliminate(@this, reduced: true).Entries).InnerSimplified), this); - private LazyPropertyA rref; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent rref; /// /// The number of linearly independent rows: of the elimination's pivots. For a symbolic matrix it is the @@ -622,7 +627,8 @@ public IEnumerator GetEnumerator() /// public int Rank => rank.GetValue(static @this => Eliminate(@this, reduced: false).Pivots, this); - private LazyPropertyA rank; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent rank; /// /// Gaussian elimination over the entries, to the row echelon form, or with to the @@ -723,7 +729,8 @@ private static bool IsZeroEntry(Entity entry) return ToMatrix(Functions.GenTensorGuard.Adjoint(@this.InnerMatrix)); }, this); - private LazyPropertyA adjugate; + // Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent adjugate; /// /// Returns a vector, where the i-th element diff --git a/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs b/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs index f28f20a2e..5ad700a1a 100644 --- a/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs +++ b/Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs @@ -241,10 +241,11 @@ public sealed partial record Interval(Entity Left, bool LeftClosed, Entity Right /// public bool IsNumeric => !LeftReal.IsNaN && !RightReal.IsNaN; + // Each end's value is an evaluation, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479 private Real LeftReal => fLeft.GetValue(static @this => @this.Left.EvaluableNumerical && @this.Left.Evaled is Real re ? re : Real.NaN, this); - private LazyPropertyA fLeft; + private Convenience.SettingsDependent fLeft; private Real RightReal => fRight.GetValue(static @this => @this.Right.EvaluableNumerical && @this.Right.Evaled is Real re ? re : Real.NaN, this); - private LazyPropertyA fRight; + private Convenience.SettingsDependent fRight; private static bool IsALessThanB(Real A, Real B, bool closed) => A < B || closed && A == B; diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/AnalyticalEquationSolver.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/AnalyticalEquationSolver.cs index 2fcfe0dfe..219cf04aa 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/AnalyticalEquationSolver.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/AnalyticalEquationSolver.cs @@ -164,12 +164,20 @@ static Entity TryDowncast(Entity equation, Variable x, Entity root) { if (root.Evaled is not Complex preciseValue) return root; - using var _ = MathS.Settings.FloatToRationalIterCount.Set(20); - using var __ = MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m); - var downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart); - if (equation.Substitute(x, downcasted).Evaled is not Complex error) - return root; - return IsGenuineRoot(error) && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational + Complex downcasted; + bool genuine; + using (MathS.Settings.FloatToRationalIterCount.Set(20)) + using (MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m)) + { + downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart); + if (equation.Substitute(x, downcasted).Evaled is not Complex error) + return root; + genuine = IsGenuineRoot(error); + } + // The root the guess is not, simplified under the solver's own settings rather than + // the loose tolerance the guess is made with, which would round it. + // https://github.com/asc-community/AngouriMath/issues/2479 + return genuine && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational ? downcasted : root.InnerSimplified; } diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs index 4742ababe..3eab0ba39 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs @@ -50,7 +50,9 @@ partial record Entity (Boolean(true), var r) => r, (var l, var r) => l & r, }))), this).InnerSimplified; - private LazyPropertyA domainCondition; + // What a condition simplifies to depends on the settings, as any evaluation does. + // https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent domainCondition; /// /// Where a piecewise is defined: where some case's predicate holds, no earlier one does, @@ -482,47 +484,19 @@ public Entity Evaled // WithCodomain may evaluate to NaN, and still goes through it. if (this is Number && (Codomain == DefaultCodomain || Codomain == Domain.Any)) return this; - // Cached with the precision it was computed at, and read back only at that - // precision: a hundred digits of pi are the wrong answer at five hundred. The - // stamp is the precision setting's frame for this flow, compared by reference. - // Frames are immutable, a scope opened and closed in order restores the very - // frame that was under it, and a flow outside every scope has none. It was a - // count of precision changes for the whole process, which could not tell one - // flow's scope from another's, so a flow at a hundred digits read pi at three - // hundred while another flow's scope was open. - // https://github.com/asc-community/AngouriMath/issues/1505 - // The frame is read before the computation, so a scope opened and closed inside - // it leaves the value stamped with the frame it was asked in. - // https://github.com/asc-community/AngouriMath/issues/1367 - // And stamped with its owner: a record's `with` -- WithCodomain, and the - // derivative's rewrites -- copies every field, this one included, and a value - // computed for the original is not the copy's. - // The value and its stamps are one object, published in one store, so that no - // flow reads one flow's value under another's stamp. - // Until a precision scope has been opened somewhere, no flow has a frame, and a - // cached value is read without asking for one: the flow's frame is an async-local - // read, several times the cost of the rest of this path. - var precisionSetting = MathS.Settings.DecimalPrecisionContext; - var precision = precisionSetting.EverScoped ? ((Convenience.ISettingState)precisionSetting).CurrentState : null; - if (System.Threading.Volatile.Read(ref evaled) is { } cached - && ReferenceEquals(cached.Owner, this) && ReferenceEquals(cached.Precision, precision)) - return cached.Value; - var computed = InnerSimplifyWithCheck(false); - System.Threading.Volatile.Write(ref evaled, new EvaledValue(computed, this, precision)); - return computed; + // Cached with the settings it was computed under, and read back only under those: a + // hundred digits of pi are the wrong answer at five hundred + // (https://github.com/asc-community/AngouriMath/issues/1505), and 1/3 - + // 0.33333333333333333333 is 0 with the zero range at 1e-10 and 3.3E-21 at the + // default (https://github.com/asc-community/AngouriMath/issues/2479). The state is + // taken before the computation, so a scope opened and closed inside it leaves the + // value stamped with the state it was asked in + // (https://github.com/asc-community/AngouriMath/issues/1367); a `with` copy does not + // carry it, which the copy constructor sees to. + return evaled.TryGetValue(out var value) ? value : evaled.Computed(static @this => @this.InnerSimplifyWithCheck(false), this); } } - - /// A value of , with the node and the precision it was computed for. - private sealed class EvaledValue - { - internal readonly Entity Value; - internal readonly Entity Owner; - internal readonly object? Precision; - internal EvaledValue(Entity value, Entity owner, object? precision) - => (Value, Owner, Precision) = (value, owner, precision); - } - private EvaledValue? evaled; + private Convenience.SettingsDependent evaled; /// /// This is the result of naive simplifications, but not creating imprecise values unlike . In other @@ -551,7 +525,9 @@ internal EvaledValue(Entity value, Entity owner, object? precision) /// /// public Entity InnerSimplified => innerSimplified.GetValue(static @this => @this.InnerSimplifyWithCheck(true), this); - private LazyPropertyA innerSimplified; + // Numbers are rounded as they are combined, by the settings in force: see Evaled. + // https://github.com/asc-community/AngouriMath/issues/2479 + private Convenience.SettingsDependent innerSimplified; /// /// Expands an equation trying to eliminate all the parentheses ( e. g. 2 * (x + 3) = 2 * x + 2 * 3 ) diff --git a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs index 3c919a2ce..f823c7b3f 100644 --- a/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs +++ b/Sources/Tests/UnitTests/Common/NumericsRegressionTest.cs @@ -281,6 +281,172 @@ public void Issue561_LargeValuedMatrixInvertsExactly() Assert.Equal(MathS.IdentityMatrix(4), product); } + // A value cached on a node was answered under whatever settings it had first been + // computed under, though an evaluation rounds by them: 1/3 - 0.33333333333333333333 + // evaluated inside a zero range of 1e-10 was 0 afterwards at the defaults, where it is + // 3.3E-21. https://github.com/asc-community/AngouriMath/issues/2479 + private static System.IDisposable CacheScope(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)), + _ => throw new System.ArgumentException(setting), + }; + + // Compared with Equals rather than Assert.Equal, which reads a matrix as a sequence and + // recursed until the stack overflowed on a failure. + private static void ValueIs(object expected, object actual) + => Assert.True(Equals(expected, actual), $"{actual} where {expected}"); + + private static (Entity Node, System.Func Read) CachedValue(string cache) => cache switch + { + "Evaled" => (MathS.FromString("1/3 - 0.33333333333333333333", useCache: false), e => e.Evaled), + "Evaled 1 + 1e-20" => (MathS.FromString("1 + 1e-20", useCache: false), e => e.Evaled), + "InnerSimplified" => (MathS.FromString("x * (1/3 - 0.33333333333333333333)", useCache: false), e => e.InnerSimplified), + "DomainCondition" => (MathS.FromString("1 / (x - (1/3 - 0.33333333333333333333))", useCache: false), e => e.DomainCondition), + "Determinant" => (MathS.FromString("[[0.333333333333333333333333, 1], [1, 3]]", useCache: false), e => ((Entity.Matrix)e).Determinant!), + "Rank" => (MathS.FromString("[[0.333333333333333333333333, 1], [1, 3]]", useCache: false), e => ((Entity.Matrix)e).Rank), + "Inverse" => (MathS.FromString("[[0.333333333333333333333333, 1], [1, 3]]", useCache: false), e => (object?)((Entity.Matrix)e).Inverse ?? "none"), + "Interval ends" => (MathS.FromString("[1/3 - 0.33333333333333333333; 1]", useCache: false), e => ((Entity.Set)e).Contains(0)), + _ => throw new System.ArgumentException(cache), + }; + + [Theory] + [InlineData("Evaled", "zero range 1e-10")] + [InlineData("Evaled 1 + 1e-20", "zero range 1e-10")] + [InlineData("Evaled 1 + 1e-20", "20 digits")] + [InlineData("InnerSimplified", "zero range 1e-10")] + [InlineData("DomainCondition", "zero range 1e-10")] + [InlineData("Determinant", "zero range 1e-10")] + [InlineData("Rank", "zero range 1e-10")] + [InlineData("Inverse", "zero range 1e-10")] + [InlineData("Interval ends", "zero range 1e-10")] + public void Issue2479_ACachedValueIsTheValueUnderTheSettingsInForce(string cache, string setting) + { + var atDefaults = CachedValue(cache).Read(CachedValue(cache).Node); + object inScope; + using (CacheScope(setting)) + inScope = CachedValue(cache).Read(CachedValue(cache).Node); + Assert.False(Equals(atDefaults, inScope), $"{atDefaults} is the value in the scope too"); + + // The defaults first, then the scope, then the defaults again, on one node. + var (first, read) = CachedValue(cache); + ValueIs(atDefaults, read(first)); + using (CacheScope(setting)) + ValueIs(inScope, read(first)); + ValueIs(atDefaults, read(first)); + + // The scope first, then the defaults, then the scope again. + var (second, _) = CachedValue(cache); + using (CacheScope(setting)) + ValueIs(inScope, read(second)); + ValueIs(atDefaults, read(second)); + using (CacheScope(setting)) + ValueIs(inScope, read(second)); + } + + // A scope is the calling flow's, so one thread's scope must not decide what another + // thread reads from the same node, in either order. + // https://github.com/asc-community/AngouriMath/issues/2479 + [Fact] + public void Issue2479_AScopeOnOneThreadDoesNotReachAnothersValue() + { + Entity Evaluated(Entity node, bool scoped) + { + Entity result = node; + var thread = new System.Threading.Thread(() => + { + using var _ = scoped ? CacheScope("zero range 1e-10") : null; + result = node.Evaled; + }); + thread.Start(); + thread.Join(); + return result; + } + const string expression = "1/3 - 0.33333333333333333333"; + var atDefaults = MathS.FromString(expression, useCache: false).Evaled; + Entity inScope; + using (CacheScope("zero range 1e-10")) + inScope = MathS.FromString(expression, useCache: false).Evaled; + Assert.False(Equals(atDefaults, inScope), $"{atDefaults} is the value in the scope too"); + + var first = MathS.FromString(expression, useCache: false); + ValueIs(atDefaults, Evaluated(first, scoped: false)); + ValueIs(inScope, Evaluated(first, scoped: true)); + + var second = MathS.FromString(expression, useCache: false); + ValueIs(inScope, Evaluated(second, scoped: true)); + ValueIs(atDefaults, Evaluated(second, scoped: false)); + } + + // Scopes opened and closed in order put the settings back as they were, so a value + // computed before them is still the value after them, and is not computed again. + // https://github.com/asc-community/AngouriMath/issues/2479 + [Fact] + public void Issue2479_ABalancedScopeKeepsTheCachedValue() + { + var node = MathS.FromString("sin(1) + x", useCache: false); + var before = node.Evaled; + using (CacheScope("zero range 1e-10")) + using (CacheScope("20 digits")) + { } + Assert.Same(before, node.Evaled); + } + + // Threads opening and closing scopes of their own, nested, at once, over one node, each + // read the value an evaluation from scratch gives under its own settings -- while the + // states they reach are made, raced for and shared between them. + // https://github.com/asc-community/AngouriMath/issues/2479 + [Fact] + public void Issue2479_ThreadsInScopesOfTheirOwnReadTheirOwnValues() + { + const string expression = "1/3 - 0.33333333333333333333 + sqrt(2) / 10^30"; + var shared = MathS.FromString(expression, useCache: false); + var scopes = new System.Func[] + { + () => MathS.Settings.PrecisionErrorZeroRange.Set(EDecimal.Create(1, -10)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(20, ERounding.HalfUp, -100000, 100000, false)), + () => MathS.Settings.DecimalPrecisionContext.Set(new EContext(40, ERounding.HalfUp, -100000, 100000, false)), + () => MathS.Settings.DowncastingEnabled.Set(false), + }; + var failures = new System.Collections.Concurrent.ConcurrentBag(); + var threads = new System.Threading.Thread[8]; + for (var t = 0; t < threads.Length; t++) + { + var seed = t; + threads[t] = new System.Threading.Thread(() => + { + var random = new System.Random(seed); + for (var round = 0; round < 150; round++) + { + var open = new System.Collections.Generic.List(); + for (var depth = random.Next(4); depth > 0; depth--) + { + open.Add(scopes[random.Next(scopes.Length)]()); + var expected = MathS.FromString(expression, useCache: false).Evaled; + var actual = shared.Evaled; + if (!Equals(expected, actual)) + failures.Add($"{actual} where {expected}"); + } + // Closed in a random order, so that some are out of order. + while (open.Count > 0) + { + var at = random.Next(open.Count); + open[at].Dispose(); + open.RemoveAt(at); + var expected = MathS.FromString(expression, useCache: false).Evaled; + if (!Equals(expected, shared.Evaled)) + failures.Add($"{shared.Evaled} where {expected}, after a close"); + } + } + }); + } + foreach (var thread in threads) + thread.Start(); + foreach (var thread in threads) + thread.Join(); + Assert.Empty(failures); + } + // Tightening the tolerance above stops Newton's own noise from being rounded away // with it. The iteration works in double precision and starts from a grid, so the // same root reached from different starting points differs in the last digits; diff --git a/Sources/Tests/UnitTests/Core/Settings.cs b/Sources/Tests/UnitTests/Core/Settings.cs index ece7cf9a1..08632b9a2 100644 --- a/Sources/Tests/UnitTests/Core/Settings.cs +++ b/Sources/Tests/UnitTests/Core/Settings.cs @@ -66,5 +66,53 @@ public void AssertGetBackDespiteDispose() } Assert.Equal(67, MaxExpansionTermCount.Value); } + + // A scope is released by its own id and nothing else, so a second disposal -- of the same + // struct, or of a copy of it -- releases nothing, even once a scope of the same setting at + // the same value is open again in its place. + // https://github.com/asc-community/AngouriMath/issues/2479 + [Fact] + public void DisposingTwiceReleasesNothingMore() + { + using var _ = MaxExpansionTermCount.Set(10); + var scope = MaxExpansionTermCount.Set(25); + var copy = scope; + scope.Dispose(); + scope.Dispose(); + Assert.Equal(10, MaxExpansionTermCount.Value); + copy.Dispose(); + Assert.Equal(10, MaxExpansionTermCount.Value); + } + + [Fact] + public void AStaleCopyDoesNotReleaseTheScopeOpenedAgain() + { + using var _ = MaxExpansionTermCount.Set(10); + var first = MaxExpansionTermCount.Set(25); + var copy = first; + first.Dispose(); + using var again = MaxExpansionTermCount.Set(25); + copy.Dispose(); + Assert.Equal(25, MaxExpansionTermCount.Value); + } + + [Fact] + public void ScopesClosedOutOfOrderLeaveTheOthers() + { + using var _ = MaxExpansionTermCount.Set(10); + var outer = MaxExpansionTermCount.Set(20); + var other = MaxAbsNumeratorOrDenominatorValue.Set(PeterO.Numbers.EInteger.FromInt32(77)); + var inner = MaxExpansionTermCount.Set(30); + outer.Dispose(); + Assert.Equal(30, MaxExpansionTermCount.Value); + Assert.Equal(PeterO.Numbers.EInteger.FromInt32(77), MaxAbsNumeratorOrDenominatorValue.Value); + inner.Dispose(); + Assert.Equal(10, MaxExpansionTermCount.Value); + other.Dispose(); + Assert.Equal(MaxAbsNumeratorOrDenominatorValue.Default, MaxAbsNumeratorOrDenominatorValue.Value); + outer.Dispose(); + inner.Dispose(); + Assert.Equal(10, MaxExpansionTermCount.Value); + } } } From a4ab4a5e543cd8842844cd47773bf16c48ce2b86 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 08:26:00 +0000 Subject: [PATCH 2/2] Record the allocation of values cached under the settings in force in the performance baseline The kernel performance gate on this PR's run against 64a7160c5 (run 43826905331) reported Derivate -4.1%, EvalPolynomialFresh -3.5%, SimplifyEasy -3.4%, SimplifyHard -5.2%, and SolveEasy +9.1%, SolveMediumHard +6.6%. Both increases are values now computed under the settings they are asked under: SolveEasy's residual check evaluates with downcasting off and used to read values cached with it on; SolveMediumHard's extra 87 KB is 213 values the family binding of #2481 asks for at the caller's settings after Solve's own scopes have closed, which master answered from values cached under Solve's. No settings state is created and no bound is hit (instrumented). The file is that run's own measurement, copied over the baseline. Co-Authored-By: Claude Opus 5.5 --- .../DotnetBenchmark/performance-baseline.json | 76 +++++++++---------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/Sources/Tests/DotnetBenchmark/performance-baseline.json b/Sources/Tests/DotnetBenchmark/performance-baseline.json index e905278c0..f16f372e0 100644 --- a/Sources/Tests/DotnetBenchmark/performance-baseline.json +++ b/Sources/Tests/DotnetBenchmark/performance-baseline.json @@ -1,94 +1,94 @@ { "comment": "Allocated bytes and mean nanoseconds per operation for the popular use cases of https://github.com/asc-community/AngouriMath/issues/746. Checked by PerformanceGate.cs; see Sources/AngouriMath/Docs/WhatsNew/version_performance_control.md for when updating it is legitimate.", "benchmark": "CommonFunctionsInterVersion", - "commit": "9b5562800c7ad0108e917b7cfc2b7b0561abad35", + "commit": "2a6e97a34469953b1f3d1bd00f3ff301e2d440d2", "measuredOn": "2026-11-16", "runtime": ".NET 10.0.15", "machine": "Ubuntu 26.04.1 LTS, X64, 4 logical cores", "cases": { "CompileEasy": { "allocatedBytes": 11330, - "meanNanoseconds": 409022.6770833333 + "meanNanoseconds": 427119.2446664664 }, "CompileHard": { - "allocatedBytes": 20190, - "meanNanoseconds": 509726.23365885415 + "allocatedBytes": 19722, + "meanNanoseconds": 519342.9865373884 }, "Derivate": { - "allocatedBytes": 56206, - "meanNanoseconds": 30475.74802339994 + "allocatedBytes": 53889, + "meanNanoseconds": 30003.45219930013 }, "EvalEasy": { "allocatedBytes": 0, - "meanNanoseconds": 4.070846366385619 + "meanNanoseconds": 5.893909719089667 }, "EvalPolynomialFresh": { - "allocatedBytes": 12200, - "meanNanoseconds": 8223.051967075893 + "allocatedBytes": 11768, + "meanNanoseconds": 8959.468747652494 }, "EvalPolynomialFresh15Digits": { - "allocatedBytes": 11528, - "meanNanoseconds": 9031.49921468099 + "allocatedBytes": 11344, + "meanNanoseconds": 9279.058756510416 }, "EvalTranscendentalFresh": { - "allocatedBytes": 34480, - "meanNanoseconds": 31193.30291748047 + "allocatedBytes": 34120, + "meanNanoseconds": 32774.71723351112 }, "EvalTrig": { - "allocatedBytes": 69728, - "meanNanoseconds": 61466.36498616536 + "allocatedBytes": 69368, + "meanNanoseconds": 63549.88715069111 }, "EvalTrigPrecise": { - "allocatedBytes": 336298, - "meanNanoseconds": 738449.4348493303 + "allocatedBytes": 336082, + "meanNanoseconds": 791999.7256510417 }, "ParseEasy": { - "allocatedBytes": 18360, - "meanNanoseconds": 10887.879190717425 + "allocatedBytes": 18200, + "meanNanoseconds": 10878.683246067592 }, "ParseHard": { - "allocatedBytes": 59472, - "meanNanoseconds": 53440.2626953125 + "allocatedBytes": 58944, + "meanNanoseconds": 50138.78708589994 }, "RunEasy": { "allocatedBytes": 0, - "meanNanoseconds": 48.54180003915514 + "meanNanoseconds": 35.60371223588785 }, "RunHard": { "allocatedBytes": 0, - "meanNanoseconds": 503.569855372111 + "meanNanoseconds": 435.071731703622 }, "RunMedium": { "allocatedBytes": 0, - "meanNanoseconds": 303.4584103364211 + "meanNanoseconds": 274.2248768011729 }, "SimplifyEasy": { - "allocatedBytes": 29097, - "meanNanoseconds": 60391.75784737723 + "allocatedBytes": 28120, + "meanNanoseconds": 53845.70898873465 }, "SimplifyHard": { - "allocatedBytes": 142790424, - "meanNanoseconds": 150795829.6153846 + "allocatedBytes": 135434992, + "meanNanoseconds": 149526491.31578946 }, "SolveEasy": { - "allocatedBytes": 428151, - "meanNanoseconds": 455034.2215494792 + "allocatedBytes": 467031, + "meanNanoseconds": 457333.55779157364 }, "SolveEasyMedium": { - "allocatedBytes": 64642, - "meanNanoseconds": 38239.65102539062 + "allocatedBytes": 65169, + "meanNanoseconds": 38533.42154802595 }, "SolveHard": { - "allocatedBytes": 8983620, - "meanNanoseconds": 124374926.76666667 + "allocatedBytes": 9096200, + "meanNanoseconds": 112901206.4142857 }, "SolveMedium": { - "allocatedBytes": 447504, - "meanNanoseconds": 520169.041922433 + "allocatedBytes": 451413, + "meanNanoseconds": 485002.3301827567 }, "SolveMediumHard": { - "allocatedBytes": 1314524, - "meanNanoseconds": 18749327.316666666 + "allocatedBytes": 1400974, + "meanNanoseconds": 14158501.815848215 } }, "ungated": {