Skip to content

Conversation

pettyjamesm
Copy link
Member

@pettyjamesm pettyjamesm commented Oct 8, 2025

Description

OutputBufferMemoryManager

  • Switch the relatively more expensive AtomicLong#updateAndGet for AtomicLong#accumulateAndGet operation
  • Check currentBufferedBytes > bufferedBytes.get() before calling bufferedBytes.accumulateAndGet(currentBufferedBytes, Math::max) since a volatile read is cheaper than a volatile write and updating the maximum is not the common case.
  • Refactor getUtilization logic to avoid unnecessary volatile reads
  • Make the class final

Peak Memory Calculations

  • Updates various places where peak memory is calculated using AtomicLong to check whether the value is greater than peak before calling into AtomicLong::accumulateAndGet so to avoid unnecessary contention on volatile updates

Release notes

(x) This is not user-visible or is docs only, and no release notes are required.
( ) Release notes are required. Please propose a release note for me.
( ) Release notes are required, with the following suggested text:

Summary by Sourcery

Improve performance and simplify synchronization in OutputBufferMemoryManager by replacing atomic operations, reducing volatile writes, refactoring utilization tracking, and marking the class as final

Bug Fixes:

  • Introduce an IllegalStateException on negative buffer adjustments instead of using updateAndGet’s argument check

Enhancements:

  • Replace AtomicLong#updateAndGet with AtomicLong#addAndGet and explicit negative-value check to reduce overhead
  • Guard peakMemoryUsage updates behind a conditional volatile read to avoid unnecessary writes
  • Refactor getUtilization and recordBufferUtilization to accept the currentBufferedBytes parameter and eliminate redundant volatile reads
  • Mark OutputBufferMemoryManager as a final class to prevent subclassing

@cla-bot cla-bot bot added the cla-signed label Oct 8, 2025
Copy link

sourcery-ai bot commented Oct 8, 2025

Reviewer's Guide

This PR refactors OutputBufferMemoryManager to improve performance by replacing expensive atomic operations with cheaper alternatives, reducing volatile writes for peak memory tracking, streamlining utilization recording logic, and enforcing immutability by making the class final.

Class diagram for refactored OutputBufferMemoryManager

classDiagram
    class OutputBufferMemoryManager {
        -AtomicLong bufferedBytes
        -AtomicLong peakMemoryUsage
        -long maxBufferedBytes
        -TDigest bufferUtilization
        -long lastBufferUtilizationRecordTime
        -double lastBufferUtilization
        -Ticker ticker
        -ListenableFuture<Void> blockedOnMemory
        -ListenableFuture<Void> bufferBlockedFuture
        -MemoryContext memoryContext
        +updateMemoryUsage(long bytesAdded)
        +getBufferedBytes()
        +getUtilization()
        +getUtilizationHistogram()
        -recordBufferUtilization(long currentBufferedBytes)
        -getUtilization(long currentBufferedBytes)
    }
    note for OutputBufferMemoryManager "Class is now final"
Loading

File-Level Changes

Change Details Files
Enforce immutability of OutputBufferMemoryManager
  • Declared class as final
core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java
Replace AtomicLong#updateAndGet with addAndGet and manual overflow check
  • Switched to bufferedBytes.addAndGet(bytesAdded)
  • Added check for negative result and fallback set with exception on error
core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java
Optimize peakMemoryUsage update to avoid unnecessary volatile writes
  • Moved accumulateAndGet under a conditional volatile read check
  • Removed unconditional peakMemoryUsage update
core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java
Refactor buffer utilization logic to reduce volatile reads
  • Changed recordBufferUtilization to accept currentBufferedBytes parameter
  • Extracted getUtilization(long) and updated calls to pass bufferedBytes
  • Updated utilization histogram method to record after reading bufferedBytes
core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@pettyjamesm pettyjamesm requested a review from wendigo October 8, 2025 20:53
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java:102-105` </location>
<code_context>
-                checkArgument(result >= 0, "bufferedBytes (%s) plus delta (%s) would be negative", bytes, bytesAdded);
-                return result;
-            });
+            currentBufferedBytes = bufferedBytes.addAndGet(bytesAdded);
+            if (currentBufferedBytes < 0) {
+                bufferedBytes.set(currentBufferedBytes - bytesAdded);
+                throw new IllegalStateException("bufferedBytes (%s) plus delta (%s) is negative".formatted(bufferedBytes.get(), bytesAdded));
+            }
             ListenableFuture<Void> blockedOnMemory = memoryContext.setBytes(currentBufferedBytes);
</code_context>

<issue_to_address>
**issue (bug_risk):** Switching from updateAndGet with checkArgument to addAndGet with post-check changes error handling.

This method allows bufferedBytes to be negative briefly, which may be visible to other threads. Evaluate if this could lead to issues, or consider using a compare-and-set loop for stricter consistency.
</issue_to_address>

### Comment 2
<location> `core/trino-main/src/main/java/io/trino/execution/buffer/OutputBufferMemoryManager.java:127-128` </location>
<code_context>
+            recordBufferUtilization(currentBufferedBytes);
+        }
+        // Reduce contention by reading first and only updating if the new value might become the maximum (uncommon)
+        if (currentBufferedBytes > peakMemoryUsage.get()) {
+            peakMemoryUsage.accumulateAndGet(currentBufferedBytes, Math::max);
         }
-        peakMemoryUsage.accumulateAndGet(currentBufferedBytes, Math::max);
</code_context>

<issue_to_address>
**issue (bug_risk):** Optimizing peakMemoryUsage update reduces contention but may miss some updates.

This approach can miss updates to peakMemoryUsage due to race conditions between threads. Assess if this potential inaccuracy aligns with your application's requirements.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@pettyjamesm pettyjamesm force-pushed the cleanup-output-buffer-memory-manager branch 2 times, most recently from a429b22 to 8faba62 Compare October 9, 2025 13:05
@pettyjamesm pettyjamesm changed the title Cleanup OutputBufferMemoryManager Cleanup OutputBufferMemoryManager and peak memory calculations Oct 9, 2025
@pettyjamesm pettyjamesm force-pushed the cleanup-output-buffer-memory-manager branch from 8faba62 to 731ee19 Compare October 10, 2025 18:53
@pettyjamesm pettyjamesm force-pushed the cleanup-output-buffer-memory-manager branch from 731ee19 to 6536da3 Compare October 13, 2025 14:31
@pettyjamesm pettyjamesm merged commit 3b372de into trinodb:master Oct 13, 2025
204 of 205 checks passed
@pettyjamesm pettyjamesm deleted the cleanup-output-buffer-memory-manager branch October 13, 2025 17:12
@github-actions github-actions bot added this to the 478 milestone Oct 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

2 participants