From this reply by Jan W.
… one should be aware that calling write/1 twice on the same variable may not print the same value. This is because the print output are stack offsets and GC changes these. There is not a good way around that. For this type of exploration you may consider
?- set_prolog_flag(gc, false).
to disable garbage collection. Be careful, you easily run out of memory.
As is, variables appearing in a term that is printed as a whole are consistent, unless portray hooks are used. Printing a term reliably is pretty hard. The toplevel uses copy_term/3 to move the constraints out, if the term is cyclic it factorizes the cycles. Next it uses numbervars/4 with the singletons(true) argument and finally prints using portray and numbervars options.