Non-Determinism and Sleep: Is it ok to calculate sleep duration at runtime?

Hello folks. I’ve been searching for answers for a few days, but can’t find the specific answer I need.

I have a workflow activity that is set up something like this:

  ... do some things ...
  duration := calculateDurationBetweenNowAndNextMonday(workflow.Now())
  workflow.Sleep(ctx, duration)
  ... run the next activity in the workflow ...

I’m concerned that this might cause my workflow to throw NonDeterministicErrors because the duration of the sleep will be different each time the workflow runs.

Does “Sleep” even affect the “determinism” of the workflow. Or is it excepted from this concern?

This code is deterministic as workflow.Now() returns the same recorded value during replay.

1 Like

@maxim will it be deterministic if we do this inside a for loop.
Does temporal keep a record of latest recorded value in such cases?

... do some things ...
 
  for _, nextTimestamp := range timeStamps {
			if workflow.Now(ctx).Before(nextTimestamp.GetTimestamp().AsTime()) {
				sleepD := nextTimestamp.GetTimestamp().AsTime().Sub(workflow.Now(ctx))
				workflowSleepError := workflow.Sleep(ctx, sleepD)
				if workflowSleepError != nil {
					lg.Error("failed to put workflow to sleep", zap.Error(workflowSleepError))
					return workflowSleepError
				}
			}
  ... run the next activity in the workflow ...
}

Yes, there is nothing nondeterministic about a loop (unless it is a range over a map).

1 Like