Skip to content

Commit e828414

Browse files
A long chain of sums is simplified from the bottom up, not by a recursion as deep as the chain (#2167)
A sum simplifies its left operand first, and that operand's left operand, so a chain of n sums nested to the left was simplified by a recursion n deep. A sum built one term at a time is that shape: CollectLikeTerms builds one, and Simplify's search hands the collected chain on. The integral of (q + p x)/(c + b x + a x^2)^3 with its symbols pinned reached about 900, which overflowed C# Test's Debug build on a 1 MB stack on most Windows runs since 2026-09-15 (#2165 moved that leg to Release), and needed more than 384 KB in Release, where macOS gives 512 KB. Sumf and Minusf now simplify every 32nd node of a left spine at least 64 deep first, deepest first. Every node's simplification is cached, so each of those recursions stops at the checkpoint below it. The same nodes are simplified, each once, in a different order, and an ordinary sum pays for a walk of a few nodes and nothing else. On a thread of a given stack size: cubic row, Release 384 KB overflow (909 repeats) -> 256 KB passes cubic row, Debug 1 MB overflow (654 repeats) -> 1 MB passes (a_1+..+a_30)(b_1+..+b_30) expanded, Release, 256 KB: 400 terms overflow -> 900 and 1,600 pass What overflows next on the cubic row, at 192 KB in Release, is CostModel.ChildrenCost, 872 deep: a different recursion, with 2.7x headroom on macOS. Unit suite 17,128 passed, 0 failed. Against master on one machine: allocation is identical (23,356 B per round of InnerSimplified on five ordinary sums; 15.79 MB per round of Simplify on ten expressions), and time is within noise (InnerSimplified 2,525 ms vs 2,557 ms, mean of three 200,000-round runs whose spread in one arm is 5%). Fixes #2166 Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 90ac975 commit e828414

2 files changed

Lines changed: 105 additions & 4 deletions

File tree

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Continuous/Evaluation.Continuous.Arithmetics.Classes.cs‎

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,56 @@ namespace AngouriMath
1212
{
1313
partial record Entity
1414
{
15+
/// <summary>
16+
/// The operand a sum or a difference simplifies first, or <see langword="null"/> for any
17+
/// other node.
18+
/// </summary>
19+
private static Entity? LeftOperandOfASum(Entity node)
20+
=> node switch { Sumf sum => sum.Augend, Minusf difference => difference.Minuend, _ => null };
21+
22+
/// <summary>How far apart the nodes simplified ahead along a long left spine are.</summary>
23+
private const int SpineCheckpointSpacing = 32;
24+
25+
/// <summary>
26+
/// Simplifies a long chain of sums from the bottom up before <paramref name="sum"/> is
27+
/// simplified, so that no recursion through it goes deeper than
28+
/// <see cref="SpineCheckpointSpacing"/>.
29+
/// </summary>
30+
/// <remarks>
31+
/// <para>
32+
/// A sum simplifies its left operand first, and that operand's left operand, and so on, so
33+
/// a chain of n sums nested to the left is simplified by a recursion n deep. A sum built
34+
/// one term at a time is that shape. <c>CollectLikeTerms</c> builds one, and so does
35+
/// anything that adds terms up in a loop. The integrals of
36+
/// <c>(q + p x)/(c + b x + a x^2)^3</c> simplified one about 900 deep, which overflowed a
37+
/// 1 MB stack in a Debug build and 384 KB in Release.
38+
/// https://github.com/asc-community/AngouriMath/issues/2166
39+
/// </para>
40+
/// <para>
41+
/// Every node's simplification is cached, so simplifying every
42+
/// <see cref="SpineCheckpointSpacing"/>th node of the spine first, deepest first, leaves
43+
/// each of those recursions stopping at the one below it, and then the sum's own. The
44+
/// same nodes are simplified as before, each once, in another order. Under twice the
45+
/// spacing nothing is done, so an ordinary sum pays for a walk of a few nodes and nothing
46+
/// else.
47+
/// </para>
48+
/// </remarks>
49+
private static void SimplifyALongLeftSpineFirst(Entity sum, bool isExact)
50+
{
51+
var depth = 0;
52+
for (var node = LeftOperandOfASum(sum); node is not null && depth < 2 * SpineCheckpointSpacing; node = LeftOperandOfASum(node))
53+
depth++;
54+
if (depth < 2 * SpineCheckpointSpacing)
55+
return;
56+
var checkpoints = new List<Entity>();
57+
depth = 0;
58+
for (var node = LeftOperandOfASum(sum); node is Sumf or Minusf; node = LeftOperandOfASum(node)!)
59+
if (++depth % SpineCheckpointSpacing == 0)
60+
checkpoints.Add(node);
61+
for (var i = checkpoints.Count - 1; i >= 0; i--)
62+
_ = checkpoints[i].InnerSimplified(isExact);
63+
}
64+
1565
/// <summary>
1666
/// <paramref name="interval"/> scaled by <paramref name="factor"/>, or
1767
/// <see langword="null"/> where the factor's sign is not known.
@@ -83,8 +133,10 @@ public partial record Sumf
83133
{
84134
private protected override Entity IntrinsicCondition => Boolean.True;
85135
/// <inheritdoc/>
86-
protected override Entity InnerSimplify(bool isExact) =>
87-
ExpandOnTwoArguments(Augend, Addend,
136+
protected override Entity InnerSimplify(bool isExact)
137+
{
138+
SimplifyALongLeftSpineFirst(this, isExact);
139+
return ExpandOnTwoArguments(Augend, Addend,
88140
(augend, addend) => (augend, addend) switch
89141
{
90142
(Complex a, Complex b) when !isExact => a + b,
@@ -98,14 +150,17 @@ _ when Core.Sets.Cardinality.Absorbed(augend, addend) is { } larger => larger,
98150
_ => null
99151
},
100152
(@this, a, b) => ((Sumf)@this).New(a, b), isExact);
153+
}
101154
}
102155
public partial record Minusf
103156
{
104157
private protected override Entity IntrinsicCondition => Boolean.True;
105158

106159
/// <inheritdoc/>
107-
protected override Entity InnerSimplify(bool isExact) =>
108-
ExpandOnTwoArguments(Minuend, Subtrahend,
160+
protected override Entity InnerSimplify(bool isExact)
161+
{
162+
SimplifyALongLeftSpineFirst(this, isExact);
163+
return ExpandOnTwoArguments(Minuend, Subtrahend,
109164
(augend, addend) => (augend, addend) switch
110165
{
111166
(Complex a, Complex b) when !isExact => a - b,
@@ -127,6 +182,7 @@ _ when Core.Sets.Cardinality.HasNoValue(augend, addend) => MathS.NaN,
127182
_ => null
128183
},
129184
(@this, a, b) => ((Minusf)@this).New(a, b), isExact);
185+
}
130186
}
131187
public partial record Mulf
132188
{
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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.Linq;
9+
using System.Threading;
10+
using AngouriMath;
11+
using AngouriMath.Extensions;
12+
using Xunit;
13+
14+
namespace AngouriMath.Tests.Common
15+
{
16+
/// <summary>
17+
/// A sum built one term at a time is nested as deep as it is long, and a sum simplifies its
18+
/// left operand first, so it was simplified by a recursion as deep as the sum. Expanding a
19+
/// product of two sums of 30 terms collects 900, and that overflowed a 256 KB stack in a
20+
/// Release build. In C# Test's Debug build on Windows, the integral of
21+
/// <c>(q + p x)/(c + b x + a x^2)^3</c> did the same to a 1 MB stack.
22+
/// <a href="https://github.com/asc-community/AngouriMath/issues/2166">#2166</a>
23+
/// </summary>
24+
/// <remarks>
25+
/// Run on a thread of a fixed stack size, because the test runner's threads have whatever
26+
/// stack the platform gives them: 8 MB on Linux, 512 KB on macOS. A regression here is a
27+
/// stack overflow, which takes the test host down rather than failing one test.
28+
/// </remarks>
29+
[Trait("Area", "Common")]
30+
public sealed class LongSumStackDepthTest
31+
{
32+
[Fact]
33+
public void ASumOf900TermsIsCollectedOnASmallStack()
34+
{
35+
var left = string.Join(" + ", Enumerable.Range(1, 30).Select(i => "a_" + i)).ToEntity();
36+
var right = string.Join(" + ", Enumerable.Range(1, 30).Select(i => "b_" + i)).ToEntity();
37+
Entity? expanded = null;
38+
var worker = new Thread(() => expanded = (left * right).Expand(), 256 * 1024);
39+
worker.Start();
40+
worker.Join();
41+
Assert.NotNull(expanded);
42+
Assert.Equal(900, Entity.Sumf.LinearChildren(expanded!).Count());
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)