pietroppeter / nimib

nimib 🐳 - nim 👑 driven ⛵ publishing ✍
https://pietroppeter.github.io/nimib/
MIT License
181 stars 10 forks source link

import of nimib breaks expected behaviour of std / random #204

Closed pietroppeter closed 1 year ago

pietroppeter commented 1 year ago

expected behaviour of std / random is that the following should output always the same result, which it does not unless I remove nimib import:

import std / random
import nimib # if I comment this lines results are reproducible
echo rand(100)

this is a side effect of the dependency on tempfile, see: https://github.com/OpenSystemsLab/tempfile.nim/issues/13

this is particular bad in nimib since tempfile is called every time a new nbCode is created (a temporary file is created to save the output) and this seems to trigger a new call to randomize. This means that a single randomize(42) call after importing nimib is not enough to guarantee reproducible results, the user must call randomize with a fixed seed inside every code block that calls random functions.

import nimib
import std / random
randomize(42) # putting a randomize here does not guarantee reproducible results
nbInit
nbCode:
  randomize(42) # putting randomize here does!
  echo rand(100)
echo nb.blk.output

An alternative to tempfile are some utilities in std lib but they do not yet support the same functionalities of tempfile: https://nim-lang.org/docs/tempfiles.html

pietroppeter commented 1 year ago

this is where nimib uses tempfile: https://github.com/pietroppeter/nimib/blob/aae72e4e2cce452c53c4c940edfe5a204b0c256c/src/nimib/capture.nim#L18

it is not completely clear to me why randomize seems to be called every time we capture output...

pietroppeter commented 1 year ago

btw the file that we use for capturing output could be something with a more predictable name and we could probably reuse the same file every time (we would need to change captureStdout api)

pietroppeter commented 1 year ago

Indeed they say tempfile is deprecated and we should switch to tempfiles from stdlib (see issue referenced above)