Without seeing the relevant part of the code, answering is based on guessing.
I guess, that your code is a script and not a function. Inside the script some variables are defined at the first run such that the second run can use them.
Neither "installation issues" nor "cache problems" are standing to reason. Most likely this is a simple programming error. You can use the debugger to test this. Another approach is to convert the script into a function, and check, if the problem occurs every time. Then you know that the data shared with previous runs is the source of the different behaviour.