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.
Why refactor?
For the large db the stock balance report was not generating even though prepared report and the state was remaining in the Queued state and it was never completing
Investigation
During investigation, we found that if the user has not set item or warehouse filters then this issue happens. System fetch all the stock ledger entries to calculate the Opening Quantity and Opening Stock Value. If the number of stock ledger entries are more than 1 million and multiple users try to access the stock balance report without filters then RAM gets consumed fully and get the error "Work-horse was terminated unexpectedly (waitpid returned 15)".
New Changes
Added new doctype "Closing Stock Balance" to avoid calculation of Opening Quantity and Opening Stock Value. If you have closed the period then create the Closing Stock Balance for that period so that while preparing the stock balance report system will use the data of Closing Stock Balance and avoid Opening Quantity and Opening Stock calculations.
While watching process log we have found that one query is taking time and that was

item_code in ()
(see below image).The IN operator works slowly if the number of data is huge and it's better to use join query
Profiling Result
Before Change
After Change