In case anyone reads this, I believe I have the right
algorithm now.
First, the trick to locate an .eln regardless of OS:
(comp-lookup-eln (locate-library "my-library.el"))
Turns out I do not need the trick, because if an OS like Guix
has indeed shipped an .eln and set it up to be loaded,
then `symbol-file` should return that one.
TL;DR: it took a while to figure out, but the following
snippet is how my program chooses an .el, .elc or .eln that
corresponds to currently loaded Lisp definitions, so that we
know the file is safe to be executed by a subprocess.
If the current definitions come from an .el, then it
opportunistically builds an .eln and returns that instead.
(let ((loaded-file
(or (ignore-errors
(symbol-file 'a-func-from-my-library nil t))
(symbol-file 'a-func-from-my-library))))
(if (string-suffix-p ".el" loaded-file)
(let ((out (comp-el-to-eln-filename loaded-file)))
(native-compile loaded-file out)
out)
loaded-file))