Problem/Motivation
Consider the use case of processing some information in hook_entity_insert and in hook_entity_storage_load loading this information into the entity. We even have example in core for this - comment_entity_insert is creating a new entry into the comment statistics table and comment_entity_storage_load is loading this information into the entity's comment field.
So far so fine ... until there is some contrib or even custom module, which for some reason is loading the very same entity being saved from an inside of its comment_entity_insert hook. This will cause the load of an entity before all the processing of its previous save has been done. So if an information being prepared in the insert hook is being retrieved and set on the entity in the load hook, then the loaded entity will miss this information, as it is not yet available. This is something we cannot prevent. But a problem is caused at this point- every further entity load will be still retrieving that "incomplete" entity even if the prepared information is already written to the DB. This will happen, because we will be retrieving the entity from the entity storage's persistent cache, where it has been added to while being loaded inside of its hook_entity_insert.
Proposed resolution
Option 1
Reset the persistent cache for an entity at the end of the storage's ::postSave() method. Currently the persistent cache is being reset only at the beging of the ::postSave() method.
Option 2
If loading an entity inside its post save hooks, then serve a reference to that very same entity being currently saved. For this we have to keep track of the entity being currently saved in the storage. When loading an entity by its ID / revision ID through ::load() / ::loadReivision() then check if an entity is being currently saved and if so check if it matches the entity ID / revision ID of the requested entity. If it matches then skip all the loading process and just return a reference to the entity being currently saved.
Comments
Comment #2
hchonovIn my opinion the more natural option is "Option 2 If loading an entity inside its post save hooks, then serve a reference to that very same entity being currently saved".
Comment #12
smustgrave commentedThis came up as a daily BSI target looking at the entity system
Will admit not 100% how to verify this one but question do we know this is still an issue 8 years later? Can go from there.