How to modify NDSolveStateData without crashing the kernel?

Probably a hard question, but it's better to cry out loud.

Reminded by Chris K, I noticed my fix function has been broken since v11.3. After some checking, I found NDSolveStateData[…], which is not an atom in v9 and becomes an atom now, can no longer be modified with pattern matching.

To keep fix up to date, I tried the solution in this excellent post about modifying data inside atom, sadly the modified NDSolveStateData crashes the kernel in the NDSolveProcessSolutions stage even in v9 and I can't figure out a workaround.

The following is a simplified example attempting to modify the difference order to 2. The last line crashes the kernel of course so please save your work before testing.

tmax = 10; lb = 0; rb = 5;
system = With[{u = u[t, x]}, {D[u, t] == D[u, x, x], u == 0 /. t -> 0,
u == Sin[t] /. x -> lb, u == 0 /. x -> rb}];

{state} = NDSolveProcessEquations[system, u, {t, 0, tmax}, {x, lb, rb}];

teststate =
state /. a_NDSolveFiniteDifferenceDerivativeFunction :>
RuleCondition@
NDSolveFiniteDifferenceDerivative[a@"DerivativeOrder", a@"Coordinates",
"DifferenceOrder" -> 2, PeriodicInterpolation -> a@"PeriodicInterpolation"];

Head[#]["DifferenceOrder"] & /@
teststate["NumericalFunction"]["FunctionExpression"][[2, 1]]
(* Should give {{2}} if the replacement succeeds. *)

(*Failed attempt: *)
ml = LinkCreate[LinkMode -> Loopback];
LinkWrite[ml, With[{e = state}, Hold[e]]];
holdstate = LinkRead[ml];

newstate = holdstate /.
a_NDSolveFiniteDifferenceDerivativeFunction :>
RuleCondition@
NDSolveFiniteDifferenceDerivative[a@"DerivativeOrder", a@"Coordinates",
"DifferenceOrder" -> 2, PeriodicInterpolation -> a@"PeriodicInterpolation"] //
ReleaseHold

NDSolveIterate[newstate, tmax]

(*Warning: the following line crashes the kernel.*)
u /. NDSolveProcessSolutions@newstate


Any way to avoid the crashing and fix my fix function?

A bit of spelunking shows this seems to be (at least partly) related to InternalBag. A minimal example:

bag = InternalBag[]
ml = LinkCreate[LinkMode -> Loopback];
LinkWrite[ml, With[{e = bag}, Hold[e]]]
holdbag = LinkRead[ml]
LinkClose[ml]
ReleaseHold[holdbag] === bag
(* False *)

• I think the relation to Bag` is only really in the fact that both are mutable object stored at the C++ level Jul 25, 2019 at 15:44