Saturday, July 24, 2021

Google Apps Scripts and Schroedinger's cat

Apologies for the title - it's just a tongue-in-cheek reference to the wavefunction collapse referred to in the classic Quantum Mechanics thought example where observing the phenomenon causes it to behave differently - the reference is not really accurate for this bug in Google Docs API, it's just a joke!

The bug - A google doc was being created using a google apps script which copied a template and copied elements from other google docs, and was sometimes resulting in blank output documents. 

The initial observed behaviour was truly bizarre - once the script completes, if we immediately open the  GDoc file it has created, either directly by browsing to My Drive -> Recents and the file , or programmatically by  calling DriveApp to make a copy, the GDoc becomes blank. On the other hand, if we first open another GDoc - it can be any other GDoc - allow it to load fully, close it and then open the newly created GDoc, then the doc is not blank, it has all the data. 

Even after waiting for 5 minutes and then opening the GDoc doesn't help - it becomes blank if the procedure above is not followed. 

If we open another GDoc, but close it before it loads fully, and then open the MLP GDoc, again it becomes blank.

After a lot of trial and error, found that this was due to two separate causes.

1. The template had not been shared with the user running the script as Editor - it was shared as read-only. This was causing the script to return a "Action not allowed" error at the very end of the script just as it exits. getChild(j) and similar functions apparently need Editor access for reliable operation. 

2. If the destination directory is a shared folder, or if the destination folder is open in another window or tab, blank documents result.

The second issue is the one which made me think of Schroedinger's cat. If you watch the document as it is being created, the script behaves differently!

Workaround currently is to create it in a folder not shared with anyone (root folder) and ensure that folder is not open in any other window while the script is running. If the script is interrupted, even documents previously created "successfully" would turn out to be blank. So, we have to ensure the script doesn't time out after half an hour or stop unexpectedly due to any other reason.

No comments:

Post a Comment