Skip to content

Commit 0a8dff6

Browse files
The integrator stops answering the same question over and over (#1157)
The integrator stops answering the same question over and over `Simplify` of an integral it cannot evaluate took a minute and a half. Tracing every entry to the integrator on `sin(x)/(x^2 + 1)^2` says why: 562 top-level calls for 3 distinct integrands, one of them asked 500 times, and those 3 are one integral written three ways. Inside a single call there is a second layer of it -- 5330 entries for 23 distinct integrands on `e^x/(x^2 + 1)^2` -- because the solvers overlap, substitution and partial fractions and splitting a sum and by parts each decomposing the integrand differently into pieces that coincide. So the answers are kept, and the whole difficulty is knowing when to stop trusting them. An answer depends on the ambient settings -- Codomain decides whether the logarithms carry an abs, MaxExpansionTermCount bounds the by-parts recursion -- and a setting is scoped to a flow rather than a thread, so "nothing has changed" is not something a per-thread cache may assume. SettingsState answers it by comparing what every setting reads as. A state and not a change count, which is the part that had to be measured rather than reasoned about: a scope opened and closed leaves every setting exactly as it found it while moving a counter twice, and the library opens such scopes constantly -- one Simplify of one unevaluated integral opened 3520 of them, all four kinds from numeric downcasting in Number/Operators.cs. A counter therefore reports "everything has changed" continuously, and the first version of this, built on one, gave back almost none of the improvement. The state of a 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. Comparing snapshots is a handful of reference comparisons with no chance of collision, and a balanced open-and-close compares equal, which is the point. Reads are lock-free because registering happens while the settings are constructed and the reader is on the integrator's hot path. The dictionary is emptied at 4096 entries. Nothing in it expires on its own -- the settings holding still is the whole condition for keeping an answer -- so without a cap a long-lived process integrating a stream of different expressions would hold every one of them for ever. Measured, both arms on one machine. Simplify of the three integrands with no elementary antiderivative: 114,851 ms to 1163, 85,683 to 1517, 51,072 to 188, and 1/(x^4 + 1)^2 from 3811 to 9. A single cold Integrate in a fresh process is faster too, on all nine tried: sqrt(tan(x)) 154.5 ms to 79.1, x^2*sin(x) 21.0 to 10.2, 1/(x^3 + 1) 49.8 to 31.2. The three tests that matter are the ones on the codomain, since a cache like this does not fail by returning nonsense but by returning a correct answer worked out under settings the caller is no longer standing in. `1/x` integrates to ln(abs(x)) on the reals and ln(x) on the complex plane, asked in both orders and with a scope entered while an answer is already held. All three fail with the state comparison disabled, which is what makes them worth having. Full suite 9550 passed, 0 failed. Closes #1156. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura
1 parent 4e302c2 commit 0a8dff6

4 files changed

Lines changed: 309 additions & 3 deletions

File tree

‎Sources/.editorconfig‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,6 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
192192

193193
[Tests/UnitTests/Calculus/RepeatedQuadraticIntegralTest.cs]
194194
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
195+
196+
[Tests/UnitTests/Calculus/IntegralAnswerCacheTest.cs]
197+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n

‎Sources/AngouriMath/Convenience/SettingClass.cs‎

Lines changed: 98 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,88 @@
1010

1111
namespace AngouriMath.Convenience
1212
{
13+
/// <summary>A setting, without its value's type — enough to ask what it currently reads as.</summary>
14+
internal interface ISettingState
15+
{
16+
/// <summary>
17+
/// The object identifying this setting's value in the calling flow, or
18+
/// <see langword="null"/> where nothing is set and the default applies.
19+
/// </summary>
20+
object? CurrentState { get; }
21+
}
22+
23+
/// <summary>
24+
/// What every setting reads as, taken together, so that something holding a result computed
25+
/// under the settings of a moment can tell whether those settings still hold.
26+
/// </summary>
27+
/// <remarks>
28+
/// <para>
29+
/// <b>A state and not a change count.</b> Counting changes looks equivalent and is not: a
30+
/// scope opened and closed leaves every setting exactly as it found it while moving a
31+
/// counter twice, and the library opens such scopes constantly — a single
32+
/// <c>Simplify</c> of one unevaluated integral opened <b>3520</b> of them, all four from
33+
/// numeric downcasting in <c>Number/Operators.cs</c>. A counter therefore reports
34+
/// "everything has changed" continuously and is useless to a cache. Measured, not assumed:
35+
/// the counter was built first and threw away the whole benefit.
36+
/// </para>
37+
/// <para>
38+
/// The state of one setting is the <i>reference</i> to the frame on top of its stack, which
39+
/// is exact rather than a hash — releasing a scope restores the very frame object that was
40+
/// there before it, since the chain below a pushed frame is never rebuilt. So comparing
41+
/// snapshots is a handful of reference comparisons with no chance of collision, and a
42+
/// balanced open-and-close compares equal, which is the whole point.
43+
/// </para>
44+
/// </remarks>
45+
internal static class SettingsState
46+
{
47+
/// <summary>
48+
/// Every setting there is. Replaced rather than appended to, so that a reader can walk it
49+
/// without a lock: registering happens as the settings are constructed and a reader is on
50+
/// the integrator's hot path, where taking a lock per call would be contention bought for
51+
/// a list that stops changing before any real work starts.
52+
/// </summary>
53+
[ConcurrentField] private static ISettingState[] registered = System.Array.Empty<ISettingState>();
54+
55+
[ConcurrentField] private static readonly object registering = new();
56+
57+
internal static void Register(ISettingState setting)
58+
{
59+
lock (registering)
60+
{
61+
var grown = new ISettingState[registered.Length + 1];
62+
System.Array.Copy(registered, grown, registered.Length);
63+
grown[^1] = setting;
64+
System.Threading.Volatile.Write(ref registered, grown);
65+
}
66+
}
67+
68+
/// <summary>What every setting reads as right now, in this flow.</summary>
69+
internal static object?[] Snapshot()
70+
{
71+
var settings = System.Threading.Volatile.Read(ref registered);
72+
var snapshot = new object?[settings.Length];
73+
for (var i = 0; i < snapshot.Length; i++)
74+
snapshot[i] = settings[i].CurrentState;
75+
return snapshot;
76+
}
77+
78+
/// <summary>
79+
/// Whether <paramref name="snapshot"/> is still what every setting reads as. One taken
80+
/// before a setting existed has a different length and is reported stale, which is what
81+
/// should happen — that setting's value was not part of it.
82+
/// </summary>
83+
internal static bool StillHolds(object?[] snapshot)
84+
{
85+
var settings = System.Threading.Volatile.Read(ref registered);
86+
if (snapshot.Length != settings.Length)
87+
return false;
88+
for (var i = 0; i < snapshot.Length; i++)
89+
if (!ReferenceEquals(snapshot[i], settings[i].CurrentState))
90+
return false;
91+
return true;
92+
}
93+
}
94+
1395
/// <summary>
1496
/// This class for configuring some internal mechanisms from outside
1597
/// </summary>
@@ -34,7 +116,7 @@ namespace AngouriMath.Convenience
34116
/// chain and assign it, rather than editing one.
35117
/// </para>
36118
/// </remarks>
37-
public sealed class Setting<T> where T : notnull
119+
public sealed class Setting<T> : ISettingState where T : notnull
38120
{
39121
/// <summary>
40122
/// One pushed value, and the chain below it. Never mutated once built.
@@ -58,7 +140,20 @@ private sealed class Frame
58140
private readonly AsyncLocal<Frame?> frames = new();
59141
private long lastId;
60142

61-
internal Setting(T defaultValue) => Default = defaultValue;
143+
internal Setting(T defaultValue)
144+
{
145+
Default = defaultValue;
146+
SettingsState.Register(this);
147+
}
148+
149+
/// <summary>
150+
/// The frame this setting currently reads from, as the identity of its state. Released
151+
/// in order — which <c>using</c> guarantees — a scope restores the very frame that was
152+
/// on top before it, so this compares equal across a balanced open and close. Out of
153+
/// order the chain above is rebuilt and this reads as a change, which is conservative
154+
/// and not wrong.
155+
/// </summary>
156+
object? ISettingState.CurrentState => frames.Value;
62157

63158
/// <summary>
64159
/// Sets the new value for the setting
@@ -98,7 +193,7 @@ private void Remove(long id)
98193
if (top.Id == id)
99194
{
100195
frames.Value = top.Next;
101-
return;
196+
return;
102197
}
103198
var above = new System.Collections.Generic.List<Frame>();
104199
var current = top;

‎Sources/AngouriMath/Functions/Continuous/Integration/Integration.Definition.cs‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// Website: https://am.angouri.org.
66
//
77

8+
using AngouriMath.Convenience;
89
using AngouriMath.Core.Transformations;
910
using AngouriMath.Extensions;
1011
using AngouriMath.Functions.Algebra;
@@ -109,10 +110,98 @@ internal static partial class Integration
109110
private static Entity Normalized(Entity expr) =>
110111
expr.Replace(Patterns.GatherPowersOfOneBase);
111112

113+
/// <summary>
114+
/// The integrals already answered under the settings in force, so that the same question
115+
/// is not worked out again.
116+
/// </summary>
117+
/// <remarks>
118+
/// <para>
119+
/// <b>Why an integral is asked for twice at all.</b> Two layers of it. Within one call the
120+
/// solvers overlap — substitution, partial fractions, splitting a sum and integration by
121+
/// parts each decompose the integrand differently and produce pieces that coincide — and
122+
/// across calls <c>Simplify</c> asks about one integral through every
123+
/// rewritten candidate it generates. Traced on <c>sin(x)/(x^2 + 1)^2</c>, which has no
124+
/// elementary antiderivative and so runs the search to exhaustion, that is <b>562
125+
/// top-level calls for 3 distinct integrands</b>, one of them asked 500 times; on
126+
/// <c>e^x/(x^2 + 1)^2</c> a single call enters the integrator <b>5330 times for 23</b>.
127+
/// </para>
128+
/// <para>
129+
/// <b>The answers are held across calls and not only within one</b>, which is where the
130+
/// repetition is: discarding them at the end of each top-level call leaves the 562 to be
131+
/// paid in full. Measured on those three integrands, keeping them takes a
132+
/// <c>Simplify</c> from 115, 86 and 51 seconds to about 1.2, 1.5 and 0.2, and a single
133+
/// cold <c>Integrate</c> of <c>sqrt(tan(x))</c> from 155 ms to 79.
134+
/// https://github.com/asc-community/AngouriMath/issues/1156
135+
/// </para>
136+
/// <para>
137+
/// <b>Why it is sound to hold them.</b> An answer depends on the ambient settings —
138+
/// <see cref="MathS.Settings.Codomain"/> decides whether the logarithms carry an
139+
/// <c>abs</c>, <c>MaxExpansionTermCount</c> bounds the by-parts recursion — and a setting
140+
/// is scoped to a flow rather than to a thread, so "the settings have not changed" is not
141+
/// something a per-thread cache can assume. <see cref="SettingsState"/> answers it
142+
/// exactly, by comparing what every setting reads as rather than by counting changes —
143+
/// which matters, because the library opens and closes thousands of balanced scopes while
144+
/// simplifying and a change count is therefore never still.
145+
/// </para>
146+
/// </remarks>
147+
[System.ThreadStatic] private static Dictionary<(Entity, Entity.Variable, bool), Entity?>? answered;
148+
149+
/// <summary>The settings <see cref="answered"/> was filled under.</summary>
150+
[System.ThreadStatic] private static object?[]? answeredUnder;
151+
152+
/// <summary>
153+
/// How many answers to hold before starting over. Comfortably above what one call needs
154+
/// — the worst measured is 23 distinct integrands within a call and 3 across the
155+
/// candidates of one <c>Simplify</c> — and low enough that a process integrating
156+
/// different things all day does not accumulate them.
157+
/// </summary>
158+
private const int MostAnswersKept = 4096;
159+
112160
/// <summary>Does not add the constant of integration because this is called recursively.</summary>
113161
internal static Entity? ComputeIndefiniteIntegral(Entity expr, Entity.Variable x, bool integrateByParts = true)
114162
{
115163
expr = Normalized(expr);
164+
165+
if (answered is null || answeredUnder is null || !SettingsState.StillHolds(answeredUnder))
166+
{
167+
// A fresh dictionary rather than Clear(), because this flow may have inherited
168+
// the reference from the one that started it, and emptying it in place would
169+
// empty that one's too.
170+
answered = new();
171+
answeredUnder = SettingsState.Snapshot();
172+
}
173+
174+
// Held as locals over the recursive call, which reaches this method again and may
175+
// replace both fields on the way. Writing the answer into whatever the fields hold
176+
// afterwards would put it in a dictionary stamped with different settings.
177+
var into = answered;
178+
var stamp = answeredUnder;
179+
180+
var key = (expr, x, integrateByParts);
181+
if (into.TryGetValue(key, out var already))
182+
return already;
183+
184+
var computed = ComputeIndefiniteIntegralUncached(expr, x, integrateByParts);
185+
186+
// Only kept if those settings still hold. Working the answer out runs simplification,
187+
// which opens scopes of its own; one still open means this answer was computed under
188+
// settings the stamp does not describe.
189+
if (SettingsState.StillHolds(stamp))
190+
{
191+
// Emptied rather than grown without end. Nothing here expires on its own — the
192+
// settings holding still is the whole condition for keeping an answer — so a
193+
// long-lived process integrating a stream of different expressions would hold
194+
// every one of them for ever. What this is for is being asked the same question
195+
// again, which needs the recent answers and not all of them.
196+
if (into.Count >= MostAnswersKept)
197+
into.Clear();
198+
into[key] = computed;
199+
}
200+
return computed;
201+
}
202+
203+
private static Entity? ComputeIndefiniteIntegralUncached(Entity expr, Entity.Variable x, bool integrateByParts)
204+
{
116205
if (!expr.ContainsNode(x)) return expr * x; // base case, handle here
117206
if ((IntegralPatterns.TryStandardIntegrals(expr, x)) is { } answer) return answer;
118207
// The flag has to be handed on. Every one of these recurses, and a solver that
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System.Diagnostics;
9+
using AngouriMath;
10+
using AngouriMath.Core;
11+
using AngouriMath.Extensions;
12+
using Xunit;
13+
14+
namespace AngouriMath.Tests.Calculus
15+
{
16+
/// <summary>
17+
/// The integrator keeps the answers it has already worked out, because it is asked the same
18+
/// question over and over — <c>Simplify</c> puts one integral through every rewritten
19+
/// candidate it generates, which measured at 562 calls for 3 distinct integrands.
20+
/// https://github.com/asc-community/AngouriMath/issues/1156
21+
/// </summary>
22+
/// <remarks>
23+
/// The tests that matter here are the ones below on the codomain. A cache like this does not
24+
/// fail by returning nonsense; it fails by returning a <i>correct</i> answer that was worked
25+
/// out under settings the caller is no longer standing in.
26+
/// </remarks>
27+
[Trait("Area", "Calculus")]
28+
public sealed class IntegralAnswerCacheTest
29+
{
30+
/// <summary>
31+
/// <c>1/x</c> integrates to <c>ln(abs(x))</c> on the reals and <c>ln(x)</c> on the complex
32+
/// plane, so it separates the two codomains in one expression. Asked under each in turn,
33+
/// in one flow, which is where a cache that does not notice the setting would answer the
34+
/// second question with the first one's answer.
35+
/// </summary>
36+
[Fact]
37+
public void ANarrowedCodomainIsNotAnsweredFromTheWiderOne()
38+
{
39+
var complex = "1 / x".ToEntity().Integrate("x").Stringize();
40+
41+
string real;
42+
using (MathS.Settings.Codomain.Set(Domain.Real))
43+
real = "1 / x".ToEntity().Integrate("x").Stringize();
44+
45+
Assert.Contains("abs", real);
46+
Assert.DoesNotContain("abs", complex);
47+
}
48+
49+
/// <summary>The same, asked in the other order — a cache is only sound in both.</summary>
50+
[Fact]
51+
public void AWidenedCodomainIsNotAnsweredFromTheNarrowerOne()
52+
{
53+
string real;
54+
using (MathS.Settings.Codomain.Set(Domain.Real))
55+
real = "1 / x".ToEntity().Integrate("x").Stringize();
56+
57+
var complex = "1 / x".ToEntity().Integrate("x").Stringize();
58+
59+
Assert.Contains("abs", real);
60+
Assert.DoesNotContain("abs", complex);
61+
}
62+
63+
/// <summary>
64+
/// And with the scope entered while an answer for the same integrand is already held,
65+
/// which is the ordering that a cache keyed on anything coarser than the settings
66+
/// themselves gets wrong.
67+
/// </summary>
68+
[Fact]
69+
public void AnAnswerHeldFromBeforeAScopeIsNotUsedInsideIt()
70+
{
71+
var before = "1 / x".ToEntity().Integrate("x").Stringize();
72+
Assert.DoesNotContain("abs", before);
73+
74+
using (MathS.Settings.Codomain.Set(Domain.Real))
75+
Assert.Contains("abs", "1 / x".ToEntity().Integrate("x").Stringize());
76+
77+
Assert.DoesNotContain("abs", "1 / x".ToEntity().Integrate("x").Stringize());
78+
}
79+
80+
/// <summary>
81+
/// Repeating a question gives the same answer, which is the property a cache is allowed
82+
/// to have and the one that would break first if a stale entry were served.
83+
/// </summary>
84+
[Theory]
85+
[InlineData("1 / (x ^ 2 + 1)")]
86+
[InlineData("1 / (x ^ 2 + 1) ^ 2")]
87+
[InlineData("x * ln(x)")]
88+
[InlineData("sqrt(tan(x))")]
89+
[InlineData("sin(x) / (x ^ 2 + 1) ^ 2")]
90+
public void AskingTwiceAnswersTheSame(string integrand)
91+
{
92+
var first = integrand.ToEntity().Integrate("x");
93+
var second = integrand.ToEntity().Integrate("x");
94+
Assert.Equal(first, second);
95+
}
96+
97+
/// <summary>
98+
/// An integrand with no elementary antiderivative, which runs every solver to exhaustion
99+
/// and so pays the full cost of the search. It took <b>115 seconds</b> before the answers
100+
/// were kept, and about one after.
101+
/// </summary>
102+
/// <remarks>
103+
/// The bound is two orders of magnitude above what it now takes and a quarter of what it
104+
/// used to, so it is a guard against the regression rather than a measurement of the
105+
/// machine. A timing assertion tight enough to be a benchmark would only flake.
106+
/// </remarks>
107+
[Fact]
108+
public void AnIntegralWithNoAnswerStillFinishesQuickly()
109+
{
110+
var watch = Stopwatch.StartNew();
111+
var answer = "sin(x) / (x ^ 2 + 1) ^ 2".ToEntity().Integrate("x").Simplify();
112+
watch.Stop();
113+
114+
Assert.Contains("integral(", answer.Stringize());
115+
Assert.True(watch.Elapsed.TotalSeconds < 30,
116+
$"took {watch.Elapsed.TotalSeconds:F1}s; it was 115s before the answers were kept");
117+
}
118+
}
119+
}

0 commit comments

Comments
 (0)