Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: memory allocations in the debug mode #110

Merged
merged 3 commits into from Jan 31, 2024

Conversation

rustatian
Copy link
Member

@rustatian rustatian commented Jan 31, 2024

Reason for This PR

  • Memory allocations (buffered channel) in the debug mode.

Description of Changes

  • Reduce buffer size, refactor code.

License Acceptance

By submitting this pull request, I confirm that my contribution is made under
the terms of the MIT license.

PR Checklist

[Author TODO: Meet these criteria.]
[Reviewer TODO: Verify that these criteria are met. Request changes if not]

  • All commits in this PR are signed (git commit -s).
  • The reason for this PR is clearly provided (issue no. or explanation).
  • The description of changes is clear and encompassing.
  • Any required documentation changes (code and docs) are included in this PR.
  • Any user-facing changes are mentioned in CHANGELOG.md.
  • All added/changed functionality is tested.

Summary by CodeRabbit

  • Refactor
    • Improved the handling of stream processing and worker states in the debug functionality.
    • Enhanced error logging and process management to prevent zombie processes.

Signed-off-by: Valery Piashchynski <piashchynski.valery@gmail.com>
@rustatian rustatian added B-performance Bug: performance issues B-regression Bug: regression bugs labels Jan 31, 2024
@rustatian rustatian self-assigned this Jan 31, 2024
Copy link

coderabbitai bot commented Jan 31, 2024

Important

Auto Review Skipped

Review was skipped due to path filters

Files ignored due to path filters (1)
  • go.sum is excluded by: !**/*.sum

Walkthrough

The update to the execDebug function in the static_pool package involves refining the process management to better handle zombies, streamlining stream processing, and enhancing worker state transitions. This overhaul includes improved channel operations, initial data transmission adjustments, and more effective error reporting mechanisms.

Changes

File Path Summary of Changes
.../static_pool/debug.go Modified zombie prevention comment, restructured stream and worker state handling, enhanced error logging.

🎉 🐰
In the code's quiet burrow, changes abound,
Where streams and states in harmony are found.
No zombies lurk, as rabbits work with glee,
Crafting code with care, for all to see. 🌟

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between fc71c6d and 10b1b2c.
Files selected for processing (1)
  • pool/static_pool/debug.go (3 hunks)
Additional comments: 5
pool/static_pool/debug.go (5)
  • 24-24: The comment on line 24 has been modified to clarify the purpose of reading the exit status, which is to prevent the process from becoming a zombie. This is a good practice as it enhances code readability and understanding.
  • 36-36: Reducing the buffer size of the channel from an unspecified size to 5 on line 36 is a targeted optimization to reduce memory allocations in debug mode. However, ensure this buffer size is sufficient for the expected workload to avoid potential bottlenecks.
  • 44-44: The deferred function starting on line 44 correctly handles the cleanup and logging for the stream worker. This includes closing the response channel, stopping the worker, and logging any errors encountered. This is a good practice for managing resources and providing debug information.
  • 64-74: The handling of the stop signal for the stream on lines 64-74 is well-implemented. It includes logging the receipt of the stop signal, attempting to cancel the stream with a timeout, and transitioning the worker's state based on the outcome. This logic is crucial for ensuring that resources are properly managed and that the system can gracefully handle termination signals.
  • 129-129: Creating a response channel with a buffer size of 1 on line 129 for non-stream responses is appropriate and aligns with the goal of optimizing memory usage in debug mode. This ensures that memory is efficiently used for synchronous operations.

Comment on lines +79 to +121
// we have to set a stream timeout on every request
switch sp.supervisedExec {
case true:
ctxT, cancelT := context.WithTimeout(context.Background(), sp.cfg.Supervisor.ExecTTL)
pld, next, errI := w.StreamIterWithContext(ctxT)
cancelT()
if errI != nil {
sp.log.Warn("stream error", zap.Error(err))

resp <- newPExec(nil, errI)

// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}

resp <- newPExec(pld, nil)

if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
case false:
// non supervised execution, can potentially hang here
pld, next, errI := w.StreamIter()
if errI != nil {
sp.log.Warn("stream iter error", zap.Error(err))
// send error response
resp <- newPExec(nil, errI)

// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}

resp <- newPExec(pld, nil)

resp <- newPExec(pld, nil)
if !next {
// we've got the last frame
runtime.Goexit()
if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic for handling stream iteration based on the supervisedExec flag from lines 79-121 introduces complexity but is necessary for supporting both supervised and unsupervised execution modes. However, there's repeated code for handling errors and transitioning worker states in both cases. Consider refactoring this logic into a separate function to adhere to the DRY (Don't Repeat Yourself) principle and simplify the code.

+ func handleStreamError(w *Worker, resp chan *PExec, err error) {
+     sp.log.Warn("stream error", zap.Error(err))
+     resp <- newPExec(nil, err)
+     w.State().Transition(fsm.StateInvalid)
+     runtime.Goexit()
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// we have to set a stream timeout on every request
switch sp.supervisedExec {
case true:
ctxT, cancelT := context.WithTimeout(context.Background(), sp.cfg.Supervisor.ExecTTL)
pld, next, errI := w.StreamIterWithContext(ctxT)
cancelT()
if errI != nil {
sp.log.Warn("stream error", zap.Error(err))
resp <- newPExec(nil, errI)
// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}
resp <- newPExec(pld, nil)
if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
case false:
// non supervised execution, can potentially hang here
pld, next, errI := w.StreamIter()
if errI != nil {
sp.log.Warn("stream iter error", zap.Error(err))
// send error response
resp <- newPExec(nil, errI)
// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}
resp <- newPExec(pld, nil)
resp <- newPExec(pld, nil)
if !next {
// we've got the last frame
runtime.Goexit()
if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
// we have to set a stream timeout on every request
switch sp.supervisedExec {
case true:
ctxT, cancelT := context.WithTimeout(context.Background(), sp.cfg.Supervisor.ExecTTL)
pld, next, errI := w.StreamIterWithContext(ctxT)
cancelT()
if errI != nil {
sp.log.Warn("stream error", zap.Error(err))
resp <- newPExec(nil, errI)
// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}
resp <- newPExec(pld, nil)
if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
case false:
// non supervised execution, can potentially hang here
pld, next, errI := w.StreamIter()
if errI != nil {
sp.log.Warn("stream iter error", zap.Error(err))
// send error response
resp <- newPExec(nil, errI)
// move worker to the invalid state to restart
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}
resp <- newPExec(pld, nil)
if !next {
w.State().Transition(fsm.StateReady)
// we've got the last frame
runtime.Goexit()
}
func handleStreamError(w *Worker, resp chan *PExec, err error) {
sp.log.Warn("stream error", zap.Error(err))
resp <- newPExec(nil, err)
w.State().Transition(fsm.StateInvalid)
runtime.Goexit()
}

Copy link

codecov bot commented Jan 31, 2024

Codecov Report

Attention: 53 lines in your changes are missing coverage. Please review.

Comparison is base (fc71c6d) 74.05% compared to head (95e5360) 72.36%.

Files Patch % Lines
pool/static_pool/debug.go 3.63% 53 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #110      +/-   ##
==========================================
- Coverage   74.05%   72.36%   -1.69%     
==========================================
  Files          23       23              
  Lines        2166     2204      +38     
==========================================
- Hits         1604     1595       -9     
- Misses        510      557      +47     
  Partials       52       52              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Signed-off-by: Valery Piashchynski <piashchynski.valery@gmail.com>
@rustatian rustatian merged commit bf0ed57 into master Jan 31, 2024
8 checks passed
@rustatian rustatian deleted the fix/memory-alloc-in-debug branch January 31, 2024 21:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
B-performance Bug: performance issues B-regression Bug: regression bugs
Projects
Status: ✅ Done
1 participant