Skip to content

Commit ecb43fa

Browse files
Extraction is a fixed point from the leaves up, and a budget is honoured to the millisecond (#1202)
#1199 recorded Saturation overshooting a two-second wall by up to thirty-five times. Instrumenting the loop on the worst input put 99% of the time in e-match attempts, one of which ran 1.9 s on a thirteen-member class; timing the steps of that one attempt's first binding put the whole 1.9 s in a single graph.Extract of one bound class -- on a graph of 253 e-nodes. The walk was top-down with a visiting-set cycle guard and a memo that fills only on completion, and a graph full of union-made cycles defeats that: any class on the stack blocks memoisation of everything beneath it, so sibling paths walk the same subgraph again and again. That, not the ledger, was the overshoot. Extraction is now a fixed point from the leaves up: a round recomputes every class from its children's current best, in class order and member order so ties fall the same way they did, and the rounds stop when one changes nothing. No recursion, so no depth guard and no stack to exhaust -- a chain three hundred deep extracts as itself where it used to come back null. The result is kept for as long as the graph does not change and the cost is the same delegate, and only a union can change what an existing class extracts as, so Union is where it is dropped. And the e-matcher charges the ledger once per binding it tries after the first, so an attempt over a class with a thousand members is a thousand steps and not one. Measured on the inputs of #1199, same budget of 20,000 steps and 2 s: total 2000 ms and 2000 ms where it was 2435 and 2595, the longest single attempt 4 ms where it was 1918, the longest extraction 3 ms. The Transformations tests hold every pin they held, the corpus figures included. One of my own claims does not survive this and is corrected where it was made. With the walk no longer the cost, the inputs #1200 called a stall are two things: x ^ 2 / x, x / x * -x and x / x * x * 1/2 are genuine runaways, ten to twelve thousand e-nodes in thirty seconds, and 2 * x * 1/2 and its relatives plateau at some 560 e-nodes and stop only when 200,000 steps run out. "Bounded at 135-583 e-nodes after thirty seconds" was the slow extraction, not the graph. ConstantFoldTest says so now, and its pin is renamed to what it pins: bounded by the budget, and extracting right. Part of #746. Fixes #1199. Full suite 9610 passed, 0 failed. Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 0285c71 commit ecb43fa

5 files changed

Lines changed: 115 additions & 64 deletions

File tree

‎Sources/AngouriMath/Core/Transformations/EGraph.cs‎

Lines changed: 70 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,6 @@ public override int GetHashCode()
9898
/// </remarks>
9999
internal sealed class EGraph
100100
{
101-
/// <summary>
102-
/// How deep <see cref="Extract(int, Func{Entity, double})"/> will chain through child
103-
/// classes before declining to build. A crash guard rather than a quality knob: textbook
104-
/// input nests nowhere near this far, so the cap is only reached where the alternative is
105-
/// an uncatchable stack overflow.
106-
/// </summary>
107-
private const int MaxExtractionDepth = 256;
108-
109101
private readonly List<int> parent = new();
110102
private readonly Dictionary<ENode, int> hashcons = new();
111103
private readonly Dictionary<int, HashSet<ENode>> classes = new();
@@ -336,6 +328,7 @@ internal bool Union(int left, int right)
336328
left = Find(left);
337329
right = Find(right);
338330
if (left == right) return false;
331+
extractMemo = null;
339332
parent[right] = left;
340333
foreach (var node in classes[right]) classes[left].Add(node);
341334
classes.Remove(right);
@@ -408,7 +401,25 @@ internal int AddEntity(Entity expr)
408401
/// type <see cref="MatchPattern.ConstructNode"/> does not build.
409402
/// </summary>
410403
internal Entity? Extract(int id, Func<Entity, double> cost)
411-
=> Extract(id, new Cheapest(cost), new Dictionary<int, Entity>(), new HashSet<int>());
404+
{
405+
// One extraction of the whole graph, kept for as long as the graph does not change
406+
// and the cost is the same delegate. Only a union can change what an existing class
407+
// extracts as -- a new class never alters an old one -- so Union is where it is
408+
// dropped. Before this, every witness an e-match attempt wanted was a fresh walk,
409+
// once per bound name per binding and once per predicated hole per candidate class,
410+
// and one such walk of a 253-node graph took 1.9 s: the walk was top-down with a
411+
// cycle guard, and a graph full of union-made cycles defeats a memo that fills only
412+
// on completion. https://github.com/asc-community/AngouriMath/issues/1199
413+
if (!ReferenceEquals(cost, memoCost) || extractMemo is null)
414+
{
415+
memoCost = cost;
416+
extractMemo = ExtractAll(new Cheapest(cost));
417+
}
418+
return extractMemo.TryGetValue(Find(id), out var best) ? best : null;
419+
}
420+
421+
private Dictionary<int, Entity>? extractMemo;
422+
private Func<Entity, double>? memoCost;
412423

413424
/// <summary>
414425
/// The least entity the e-class <paramref name="id"/> can be built as under
@@ -421,7 +432,7 @@ internal int AddEntity(Entity expr)
421432
/// well-defined expression where "the least member" is. See <see cref="EntityOrder"/>.
422433
/// </remarks>
423434
internal Entity? ExtractLeast(int id, IComparer<Entity> order)
424-
=> Extract(id, new Least(order), new Dictionary<int, Entity>(), new HashSet<int>());
435+
=> ExtractAll(new Least(order)).TryGetValue(Find(id), out var least) ? least : null;
425436

426437
/// <summary>
427438
/// How <c>Extract</c> chooses between the members of one e-class. A
@@ -488,46 +499,61 @@ public void Offer(Entity candidate)
488499
public readonly Entity? Best => best;
489500
}
490501

491-
private Entity? Extract<TSelection>(int id, TSelection seed,
492-
Dictionary<int, Entity> memo, HashSet<int> visiting)
502+
/// <summary>
503+
/// The best member of every class under <paramref name="seed"/>, from the leaves up: a
504+
/// round recomputes each class from its children's current best, and the rounds stop
505+
/// when one changes nothing. No recursion, so no depth to guard and no stack to exhaust;
506+
/// a member that reaches back into its own class through a union is built from that
507+
/// class's current best and offered like any other, and loses to it under any selection
508+
/// that does not prefer the larger of two writings of one thing. Rounds are bounded by
509+
/// the longest chain of classes, and capped at the class count for a selection that is
510+
/// not monotone in its children.
511+
/// </summary>
512+
private Dictionary<int, Entity> ExtractAll<TSelection>(TSelection seed)
493513
where TSelection : struct, ISelection
494514
{
495-
id = Find(id);
496-
if (memo.TryGetValue(id, out var done)) return done;
497-
// visiting is the chain currently being expanded, so its size is this call's depth.
498-
// The cycle guard below bounds that chain only by the number of distinct classes,
499-
// which unions grow past the input expression's own syntactic depth -- and a
500-
// StackOverflowException cannot be caught, so exhausting the stack takes the process
501-
// down rather than failing one call. Declining to build is the answer the cycle case
502-
// already gives, and the same shape as Gruntz's own MaxDepth.
503-
if (visiting.Count >= MaxExtractionDepth) return null;
504-
if (!visiting.Add(id)) return null; // a cycle; the other node will do
505-
var selection = seed;
506-
selection.Begin();
507-
// Ordered, not as the set enumerates: where the selection ties, the answer is
508-
// whichever candidate was reached first, and set order is neither specified nor
509-
// stable across processes.
510-
foreach (var node in NodesOf(id).OrderBy(node => node))
515+
var best = new Dictionary<int, Entity>();
516+
var leaves = new Dictionary<string, Entity?>();
517+
// Ordered, not as the dictionary enumerates: where the selection ties, the answer is
518+
// whichever candidate was reached first, and dictionary and set order are neither
519+
// specified nor stable across processes.
520+
var ids = classes.Keys.OrderBy(id => id).ToList();
521+
for (var round = 0; round <= ids.Count; round++)
511522
{
512-
var parts = new Entity[node.Children.Length];
513-
var ok = true;
514-
for (var i = 0; i < parts.Length && ok; i++)
523+
var changed = false;
524+
foreach (var id in ids)
515525
{
516-
var part = Extract(node.Children[i], seed, memo, visiting);
517-
if (part is null) ok = false;
518-
else parts[i] = part;
526+
var selection = seed;
527+
selection.Begin();
528+
foreach (var node in classes[id].OrderBy(node => node))
529+
{
530+
var parts = new Entity[node.Children.Length];
531+
var ok = true;
532+
for (var i = 0; i < parts.Length && ok; i++)
533+
if (best.TryGetValue(Find(node.Children[i]), out var part)) parts[i] = part;
534+
else ok = false;
535+
if (!ok) continue;
536+
Entity? built;
537+
if (parts.Length == 0)
538+
{
539+
if (!leaves.TryGetValue(node.Op, out built))
540+
leaves[node.Op] = built = TryParseLeaf(node.Op);
541+
}
542+
else built = MatchPattern.ConstructNode(OperatorType(node.Op), parts);
543+
if (built is null) continue;
544+
if (node.Codomain is { } domain) built = built.WithCodomain(domain);
545+
selection.Offer(built);
546+
}
547+
var chosen = selection.Best;
548+
if (chosen is null) continue;
549+
if (!best.TryGetValue(id, out var incumbent) || !chosen.Equals(incumbent))
550+
{
551+
best[id] = chosen;
552+
changed = true;
553+
}
519554
}
520-
if (!ok) continue;
521-
Entity? built = parts.Length == 0
522-
? TryParseLeaf(node.Op)
523-
: MatchPattern.ConstructNode(OperatorType(node.Op), parts);
524-
if (built is null) continue;
525-
if (node.Codomain is { } domain) built = built.WithCodomain(domain);
526-
selection.Offer(built);
555+
if (!changed) break;
527556
}
528-
visiting.Remove(id);
529-
var best = selection.Best;
530-
if (best is not null) memo[id] = best;
531557
return best;
532558
}
533559

‎Sources/AngouriMath/Core/Transformations/Matching/MatchedRule.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,14 +264,31 @@ private MatchedRule(
264264
/// </summary>
265265
internal bool TryEMatchApply(
266266
EGraph graph, int classId, Func<Entity, double> cost, out int resultClassId)
267+
=> TryEMatchApply(graph, classId, cost, null, out resultClassId);
268+
269+
/// <summary>
270+
/// <see cref="TryEMatchApply(EGraph, int, Func{Entity, double}, out int)"/>, charging
271+
/// <paramref name="spend"/> once for every binding tried after the first. A binding tried
272+
/// is a match attempt: the caller charged the first, and an attempt over a class with a
273+
/// thousand members is a thousand of them and not one -- which is what let a two-second
274+
/// budget run for sixty-nine. A <see langword="false"/> from <paramref name="spend"/>
275+
/// ends the attempt as not matched; the caller's ledger says why.
276+
/// https://github.com/asc-community/AngouriMath/issues/1199
277+
/// </summary>
278+
internal bool TryEMatchApply(
279+
EGraph graph, int classId, Func<Entity, double> cost, Func<bool>? spend, out int resultClassId)
267280
{
268281
if (!Left.CanEMatch)
269282
throw new InvalidOperationException(
270283
$"'{Name}' cannot e-match; check {nameof(Left)}.{nameof(MatchPattern.CanEMatch)} first.");
271284

272285
resultClassId = 0;
286+
var first = true;
273287
foreach (var ebindings in Left.EMatch(graph, classId, EBindings.Empty, cost))
274288
{
289+
if (!first && spend is not null && !spend()) return false;
290+
first = false;
291+
275292
Bindings? entityBindings = null;
276293
bool TryEntityBindings(out Bindings result)
277294
{

‎Sources/AngouriMath/Core/Transformations/Saturation.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,10 @@ bool ChargeGrowthSinceLastCall()
120120
return ledger.Spend(delta);
121121
}
122122

123+
// Handed to the e-matcher so that a binding tried is a step, not only the attempt --
124+
// allocated once here rather than per attempt.
125+
Func<bool> spend = () => ledger.Spend();
126+
123127
var saturated = false;
124128
while (!saturated && !ledger.Exhausted)
125129
{
@@ -189,7 +193,7 @@ bool TryTerm(out Entity value)
189193
// wrote, and a predicate that throws on a shape it did not expect must
190194
// decline the candidate, not escape Apply.
191195
bool matched;
192-
try { matched = rule.TryEMatchApply(graph, id, witnessCost, out other); }
196+
try { matched = rule.TryEMatchApply(graph, id, witnessCost, spend, out other); }
193197
catch { continue; }
194198
if (!matched) continue;
195199
}

‎Sources/Tests/UnitTests/Core/Transformations/ConstantFoldTest.cs‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,18 @@ namespace AngouriMath.Tests.Core.Transformations
3535
/// to 7, and the run from more than ten minutes to 24 seconds.
3636
/// </para>
3737
/// <para>
38-
/// <b>What is left is a stall, not a runaway.</b> The seven are a rational coefficient
39-
/// beside a variable — <c>2 * x * 1/2</c>, <c>x / x * -x</c>, <c>x ^ 2 / x</c> — whose
40-
/// spellings <c>1/2 * x</c>, <c>x / 2</c>, <c>x * 2 ^ (-1)</c> the <c>Rearranges</c> rules
41-
/// keep exchanging. Given fifteen times the budget they still report no fixed point, but
42-
/// the graph barely grows (135–583 e-nodes after thirty seconds) and every one extracts
43-
/// the right answer. So the claim in <c>RunawayBreadthTest</c> that the coefficient rules
44-
/// are confluent on plain arithmetic is true of the three inputs it pins and not of the
45-
/// family; the honest statement is that they are bounded and correct, and not confluent.
38+
/// <b>What is left is bounded by the budget and by nothing else.</b> The seven are a
39+
/// rational coefficient beside a variable — <c>2 * x * 1/2</c>, <c>x / x * -x</c>,
40+
/// <c>x ^ 2 / x</c> — whose spellings <c>1/2 * x</c>, <c>x / 2</c>, <c>x * 2 ^ (-1)</c> the
41+
/// <c>Rearranges</c> rules keep exchanging. Measured once extraction stopped being the
42+
/// cost (<a href="https://github.com/asc-community/AngouriMath/issues/1199">#1199</a>):
43+
/// <c>x ^ 2 / x</c>, <c>x / x * -x</c> and <c>x / x * x * 1/2</c> are genuine runaways,
44+
/// ten to twelve thousand e-nodes in thirty seconds; <c>2 * x * 1/2</c> and its relatives
45+
/// plateau at some 560 e-nodes and stop only when 200,000 steps run out. An earlier
46+
/// version of this remark called them stalls at 135–583 e-nodes, which was the slow
47+
/// extraction and not the graph. Every one extracts the right answer regardless, and the
48+
/// claim in <c>RunawayBreadthTest</c> that the coefficient rules are confluent on plain
49+
/// arithmetic is true of the three inputs it pins and not of the family.
4650
/// </para>
4751
/// <para>
4852
/// <b>On the corpus the ceiling is cheap and finds a little more.</b> Every one of the 40
@@ -131,11 +135,12 @@ public void ConstantOnlyArithmeticSaturatesAtTheSafeCeiling(string source)
131135
}
132136

133137
/// <summary>
134-
/// Pinned in both directions: an entry that starts saturating is to be deleted, and one
135-
/// whose graph grows past a thousand e-nodes has stopped being a stall.
138+
/// Pinned in both directions under a three-thousand-step budget: an entry that starts
139+
/// saturating is to be deleted, and one whose graph passes a thousand e-nodes within
140+
/// those steps has changed character. The extraction must be right either way.
136141
/// </summary>
137142
[Fact]
138-
public void ACoefficientBesideAVariableStallsRatherThanRunsAway()
143+
public void ACoefficientBesideAVariableIsBoundedByTheBudgetAndExtractsRight()
139144
{
140145
var stalls = new[] { "2 * x * 1/2", "x * 1/2 * 2", "x ^ 2 / x", "x / x * -x" };
141146
var answers = new[] { "x", "x", "x", "-x" };

‎Sources/Tests/UnitTests/Core/Transformations/EGraphTest.cs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -282,15 +282,14 @@ public void ExtractSettlesACostTieOnADefinedOrder()
282282
}
283283

284284
/// <summary>
285-
/// <see cref="EGraph.Extract"/> recurses through an e-class's children, and its cycle
286-
/// guard bounds the chain only by the number of distinct classes -- which unions grow
287-
/// past the input expression's own syntactic depth. Past the cap it declines to build,
288-
/// the same answer the cycle case already gives, rather than exhausting the stack: a
289-
/// <see cref="System.StackOverflowException"/> cannot be caught, so it takes the process
290-
/// down instead of failing one call.
285+
/// <see cref="EGraph.Extract"/> used to recurse through an e-class's children and decline
286+
/// to build past 256 levels, because a <see cref="System.StackOverflowException"/> cannot
287+
/// be caught. It is a fixed point from the leaves up now, with no stack to exhaust, so a
288+
/// chain three hundred deep extracts as itself -- this test asserted <see langword="null"/>
289+
/// for that input while the guard existed.
291290
/// </summary>
292291
[Fact]
293-
public void ExtractDeclinesToBuildPastItsDepthCap()
292+
public void ExtractBuildsAChainDeeperThanTheOldCap()
294293
{
295294
Entity deep = "x".ToEntity();
296295
for (var i = 0; i < 300; i++) deep += 1;
@@ -299,7 +298,7 @@ public void ExtractDeclinesToBuildPastItsDepthCap()
299298

300299
var extracted = graph.Extract(root, CostModel.Default.Cost);
301300

302-
Assert.Null(extracted);
301+
Assert.Equal(deep, extracted);
303302
}
304303

305304
/// <summary>

0 commit comments

Comments
 (0)