Exception while Upserting Search Attributes

While invoking the below method,

Workflow.upsertSearchAttributes

we are getting the below exception sometimes.

java.lang.IllegalStateException: Operation allowed only while eventLoop is running at io.temporal.internal.statemachines

Questions

  1. What causes this error?
  2. Why is it happening only sometimes?

This can be caused by for example calling Workflow.upsertSearchAttributes outside of workflow code or from
a query handler, reuse of workflow / child workflow stubs across multiple executions (for example issues with dependency injection),
or can follow PotentialDeadllockException, for example if you have some non-deterministic code that fails the workflow task right before the call to upsertSearchAttributes.
It could also happen during debugging if you do not set TEMPORAL_DEBUG to true while debugging.