As @kschirrmacher mentioned above, the Keep variable references inside the query in sync with your app will likely solve your issue.
Linking to a discussion last year where it came up that some of these headaches could be prevented by having this state in sync by default, with the option to turn it off for performance optimization.
My vote is that such an inversion is preferable for the general user.