@Aaron
I'm not a python developer nor a sympy expert but I have the impression that the problem is due to the fact that
muladd = f.atoms(Mul,Add) [1]
lead to overlapping terms which conflict among them when doing xreplace two lines below. (Eliminating Mul might help reducing the overlaps...)
Example: deep works for expr but not for expr2 (which is x**3 * expr) due to the ordering of the overlapping terms
>>> expr = 1/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2
>>> expr.atoms(Mul,Add)
{-x**2, 8*x**2, x**2 - 2, 8*x**2 + (x**2 - 2)**2, -x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2}
>>> factor(expr,deep=True)
(-x**2 + sqrt((x**2 + 2)**2) + 2)**(-2)
>>> expr2 = x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2
>>> factor(expr2,deep=True)
x**3/(x**2 - sqrt(x**4 + 4*x**2 + 4) - 2)**2
>>> expr2.atoms(Mul,Add)
{-x**2, 8*x**2, x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2, x**2 - 2, 8*x**2 + (x**2 - 2)**2, -x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2}
The fix currently proposed in the PR [2] might work but does not seem to address this problem.
ric
PS I know I know I should open a github account... sorry for my laziness
[1]
https://github.com/sympy/sympy/blob/master/sympy/polys/polytools.py#L6322
[2]
https://github.com/sympy/sympy/issues/15669