Skip to content

A value cached on a node is the value under the settings in force - #2483

Merged
Rafael-SOWNet merged 2 commits into
masterfrom
fix/evaled-cache-under-settings
Nov 16, 2026
Merged

Rafael-SOWNet merged 2 commits into
masterfrom
fix/evaled-cache-under-settings

Conversation

@Rafael-SOWNet

Copy link
Copy Markdown
Member

Entity.Evaled cached its value on the node and recorded only the DecimalPrecisionContext it was computed under, so a value computed inside a settings scope was returned afterwards under other settings, and on other threads (#2479). The same held for several other caches on a node. This makes a cached value the value under the settings in force.

How settings are stored

A cache that checks the full settings state on every read (SettingsState.Snapshot/StillHolds, 18 async-local reads) was too dear for Evaled, and a state object made fresh per opened scope missed every value cached inside Solve, which opens scopes on every call. So settings are now stored as one shared state per path of scopes (Convenience/SettingClass.cs):

  • Every setting's value lives in one async-local state; a setting reads its value at its own index.
  • A state is made once per path of scopes from the defaults (values compared by Equals), so the scopes the library opens on every call reach the same state each time. States never change after creation; the table of states one scope away is replaced whole by Interlocked.CompareExchange, so two threads making the same state get the same instance, and an equal duplicate (past the bound, or after a collection) can only cause a cache miss, never a wrong value.
  • Bounded: a state holds the states one scope away weakly and its parent strongly, at most 32 entries per setting. After 100,000 and after 1,000,000 distinct scopes (precision and zero range, then an int setting) and a forced GC, the branch retains 9.6 KB and 2.2 KB, constant in the count.
  • Disposal as master: a disposal releases only its own scope, by id; disposing twice, or a stale copy after the scope was opened again, is a no-op; scopes closed out of order leave the others.
  • Snapshot/StillHolds (simplifier, integrator) become one reference comparison.

The caches

SettingsDependent<T>, equality-neutral like LazyPropertyA: a value computed at the defaults is stored as is (no EvaledValue per node any more), one computed in a scope with its state, and the last two states are kept (a node is asked under Solve's settings and its analytical solver's in turn). Entity gets a copy constructor, so a with copy keeps the structural caches and drops computed values.

  • Changed, each measured stale on master and on 2.7.0: Evaled (and so EvaluableNumerical), InnerSimplified, DomainCondition, a matrix's Determinant, Inverse, Rank, an interval's ends.
  • Changed, computed through InnerSimplified: a matrix's Eigenvalues, Ref, Rref, Adjugate.
  • Checked and left, structural: DirectChildren, Complexity, Vars, VarsAndConsts, FreeVariables, IsFinite (measured the same in and out of a scope), SimplifiedRate (already bypasses a scoped criterion), sort keys, a matrix's T, MainDiagonal, Trace, Linear, set finiteness, numerator and denominator, the power set, the hash code.

TryDowncast (analytical solver) now simplifies the root it keeps outside the 1e-7 zero range it uses to guess a rational: inside it, the root's value was rounded by the loose tolerance and that became the cached value. (The tolerance's other effect, a guessed root checked inside the same range, is #2482.)

at defaults, after the same entity was evaluated inside PrecisionErrorZeroRange = 1e-10 was (2.7.0) now
(1/3 - 0.33333333333333333333).Evaled 0 3.333…E-21, as a fresh entity

and likewise InnerSimplified, DomainCondition, Determinant, Rank, Inverse and an interval's ends, all in BREAKING-CHANGES.md, measured on the 2.7.0 package.

Checks

Tests in NumericsRegressionTest and Core/Settings.cs: nine caches each read defaults → scope → defaults and scope → defaults → scope; two threads on one node; a balanced scope keeps the cached value (Assert.Same); eight threads × 150 rounds of random nested scopes (some closed out of order) each reading one shared node against a from-scratch evaluation under its own settings; disposing twice, a stale copy, out-of-order closing. 9 of the 11 cache tests and the stress test fail on master.

Kernel performance gate, locally, against the committed baseline: allocation down on Derivate (−4.1%), EvalPolynomialFresh (−3.5%), SimplifyEasy (−3.4%), SimplifyHard (−5.1%), and up on SolveEasy (+9.1%). The SolveEasy cost is the fix working: SolveStatement's residual check deliberately evaluates with downcasting off, and on master it read values cached with downcasting on, which defeated it. EvalEasy is +1.3 ns, one async-local read on a cached Evaled, which master also paid once precision had been scoped anywhere in the process. The baseline follows from this PR's CI run.

Full check: 20,763 unit tests, 0 failed; MCP 452, Terminal 69, F# 135, Interactive 19; AOT 78/78; BoundCheck 0 disagreements, RootCheck 596/596, CasBench 120/121 with 0 wrong, SimpSweep 10463/10463, RuleCheck clean, CanonCheck, Confluence and the Modenov corpus at their baselines.

Closes #2479.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.58824% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.88%. Comparing base (64a7160) to head (a4ab4a5).

Files with missing lines Patch % Lines
Sources/AngouriMath/Convenience/SettingClass.cs 94.82% 3 Missing and 3 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##           master    #2483   +/-   ##
=======================================
  Coverage   86.87%   86.88%           
=======================================
  Files         326      326           
  Lines       72636    72707   +71     
  Branches    21180    21202   +22     
=======================================
+ Hits        63105    63172   +67     
- Misses       5135     5138    +3     
- Partials     4396     4397    +1     
Flag Coverage Δ
cpp 37.77% <ø> (ø)
csharp 87.40% <95.58%> (+<0.01%) ⬆️
fsharp 32.79% <ø> (ø)
interactive 39.95% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...urces/AngouriMath/Core/Entity/Entity.Definition.cs 94.77% <100.00%> (+0.46%) ⬆️
...rces/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs 85.25% <ø> (ø)
...ngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs 88.63% <ø> (ø)
...Solvers/EquationSolver/AnalyticalEquationSolver.cs 96.91% <100.00%> (+0.03%) ⬆️
...Math/Functions/Evaluation/Evaluation.Definition.cs 91.32% <100.00%> (-0.32%) ⬇️
Sources/AngouriMath/Convenience/SettingClass.cs 94.66% <94.82%> (+0.76%) ⬆️

... and 7 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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<T>: 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 <noreply@anthropic.com>
@Rafael-SOWNet
Rafael-SOWNet force-pushed the fix/evaled-cache-under-settings branch from ed82ad7 to 1f23e1c Compare November 16, 2026 07:52
@Rafael-SOWNet

Copy link
Copy Markdown
Member Author

Rebased onto 64a7160 (#2481, the families of roots, merged meanwhile), so the CI run that the baseline is taken from measures this change together with #2481's. Trial merge first: the whole unit suite on the combination, 20,782 passed, 0 failed.

… the performance baseline

The kernel performance gate on this PR's run against 64a7160 (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 <noreply@anthropic.com>
@Rafael-SOWNet

Copy link
Copy Markdown
Member Author

Kernel performance gate on the rebased run (43826905331): Derivate −4.1%, EvalPolynomialFresh −3.5%, SimplifyEasy −3.4%, SimplifyHard −5.2%; SolveEasy +9.1%, SolveMediumHard +6.6%. Both increases are values now computed under the settings they are asked under, attributed by instrumenting the cache misses: 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 that #2481's family binding asks for at the caller's settings after Solve's scopes have closed, which master answered from values cached under Solve's. No settings state is created and no bound is hit. The baseline is updated in this PR from that run's measurement.

@Rafael-SOWNet
Rafael-SOWNet merged commit bc3b0b4 into master Nov 16, 2026
35 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in AngouriMath Nov 16, 2026
@Rafael-SOWNet
Rafael-SOWNet deleted the fix/evaled-cache-under-settings branch November 16, 2026 08:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Evaled returns a value computed under other precision settings

1 participant