[FIX] core: reduce memory use of BaseModel._flush() #162442
Draft
+49
−35
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation: MemoryError exceptions when a large number of records on the same model have dirty fields. Such often happens during upgrades.
In the current implementation, the cached data is re-arranged in multiple steps using local data structures. The most problematic is
id_vals[record.id][field.name]
, because it creates a dictionary with a potentially long field name (think studio fields) as key for each dirty record. For thousands of records, this quickly accumulates to 10s or even 100s of MiB in RAM.The idea of this patch is:
updates
dictionary, without creating the intermediate data structures.This way, the _flush method only consumes a marginal amount of memory compared to the memory already consumed by the cache.
Using profiling while flushing 50k records in both versions of the code, it has shown that the reduction of space complexity does not increase the runtime. As one can see, the vast amount of time is consumed by the SQL operation in both versions of the code: