Skip to content

Conversation

@wendigo
Copy link
Contributor

@wendigo wendigo commented Oct 29, 2025

Mostly around:

  • eliminating unnecessary Streams
  • reducing (un)boxing of Integer/Longs:
    • by using OptionalInt instead of Optional
    • using Comparator.comparingLong/comparingInt instead of boxing
    • using Int2ObjectMap when keys are primitive ints
  • using presized Immutable*.Builders if size is known
  • using LongAdder when writes are frequent but reads are not

Description

Additional context and related issues

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:

## Section
* Fix some things. ({issue}`issuenumber`)

Summary by Sourcery

Refactor codebase to reduce boxing and Stream overhead, improve performance, and standardize on primitive-based APIs

Enhancements:

  • Replace Optional and boxing-heavy comparators with OptionalInt and primitive comparators to reduce allocation
  • Migrate Stream-based matching and lookup APIs to Iterable or Guava Iterables, eliminating unnecessary Stream usage
  • Use LongAdder instead of AtomicLong for concurrent counters and Int2ObjectMap for primitive-keyed maps to reduce overhead
  • Presize ImmutableList/Map builders when size is known and leverage records and sealed interfaces for cleaner implementations

@cla-bot cla-bot bot added the cla-signed label Oct 29, 2025
@sourcery-ai
Copy link

sourcery-ai bot commented Oct 29, 2025

Reviewer's Guide

This PR systematically removes unnecessary stream allocations and boxing, replacing Stream-based APIs with Iterable or for-loops, introduces primitive-specialized types (OptionalInt, Int2ObjectMap, LongAdder) and presized Immutable builders, and restructures Lookup and related pattern matching interfaces for minimal overhead.

Class diagram for updated Lookup interface and implementations

classDiagram
    class Lookup {
        <<sealed interface>>
        +resolve(PlanNode): PlanNode
        +resolveGroup(PlanNode): Iterable<PlanNode>
        +static noLookup(): Lookup
        +static from(Function<GroupReference, Iterable<PlanNode>>): Lookup
    }
    class ThrowingLookup {
        +resolveGroup(PlanNode): Iterable<PlanNode>
    }
    class LookupFromFunction {
        +resolver: Function<GroupReference, Iterable<PlanNode>>
        +resolveGroup(PlanNode): Iterable<PlanNode>
    }
    Lookup <|.. ThrowingLookup
    Lookup <|.. LookupFromFunction
    Lookup o-- "1" PlanNode
    LookupFromFunction o-- "1" Function
    ThrowingLookup o-- "1" PlanNode
Loading

Class diagram for Assignments and Builder changes

classDiagram
    class Assignments {
        +assignments: Map<Symbol, Expression>
        +static builder(): Builder
        +static builderWithExpectedSize(int): Builder
        +static identity(Symbol...): Assignments
        +static identity(Iterable<Symbol>): Assignments
        +static copyOf(Map<Symbol, Expression>): Assignments
        +static of(): Assignments
        +static of(Symbol, Expression): Assignments
        +static of(Symbol, Expression, Symbol, Expression): Assignments
        +static of(Collection<Expression>, SymbolAllocator): Assignments
    }
    class Builder {
        -assignments: ImmutableMap.Builder<Symbol, Expression>
        +putAll(Assignments): Builder
        +putAll(Map<Symbol, Expression>): Builder
        +put(Symbol, Expression): Builder
        +putIdentity(Symbol): Builder
        +putIdentities(Iterable<Symbol>): Builder
        +build(): Assignments
    }
    Assignments o-- "1" Builder
Loading

Class diagram for PartitioningScheme changes

classDiagram
    class PartitioningScheme {
        -partitioning: Partitioning
        -outputLayout: List<Symbol>
        -outputTypes: Supplier<List<Type>>
        -replicateNullsAndAny: boolean
        -bucketToPartition: Optional<int[]>
        -bucketCount: OptionalInt
        -partitionCount: OptionalInt
        +getOutputLayout(): List<Symbol>
        +getOutputTypes(): List<Type>
        +isReplicateNullsAndAny(): boolean
        +getBucketToPartition(): Optional<int[]>
        +getBucketCount(): OptionalInt
        +getPartitionCount(): OptionalInt
        +withBucketToPartition(Optional<int[]>): PartitioningScheme
        +withBucketCount(OptionalInt): PartitioningScheme
        +withPartitioningHandle(PartitioningHandle): PartitioningScheme
        +withPartitionCount(OptionalInt): PartitioningScheme
    }
    PartitioningScheme o-- "1" Partitioning
    PartitioningScheme o-- "*" Symbol
Loading

Class diagram for QueryPlanOptimizerStats changes

classDiagram
    class QueryPlanOptimizerStats {
        -rule: String
        -invocations: LongAdder
        -applied: LongAdder
        -totalTime: LongAdder
        -failures: LongAdder
        +record(long, boolean): void
        +recordFailure(): void
        +getRule(): String
        +getInvocations(): long
        +getApplied(): long
        +getFailures(): long
        +getTotalTime(): long
        +snapshot(): QueryPlanOptimizerStatistics
        +merge(QueryPlanOptimizerStats): QueryPlanOptimizerStats
    }
    QueryPlanOptimizerStats o-- "1" LongAdder
Loading

Class diagram for Pattern and related matching changes

classDiagram
    class Pattern {
        +previous: Optional<Pattern>
        +accept(Object, Captures, C): Iterable<Match>
        +matches(Object, C): boolean
        +match(Object): Iterable<Match>
        +match(Object, C): Iterable<Match>
        +match(Object, Captures, C): Iterable<Match>
    }
    class OrPattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    class WithPattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    class EqualsPattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    class FilterPattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    class TypeOfPattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    class CapturePattern {
        +accept(Object, Captures, C): Iterable<Match>
    }
    Pattern <|.. OrPattern
    Pattern <|.. WithPattern
    Pattern <|.. EqualsPattern
    Pattern <|.. FilterPattern
    Pattern <|.. TypeOfPattern
    Pattern <|.. CapturePattern
Loading

Class diagram for Capture changes

classDiagram
    class Capture {
        -number: int
        +static newCapture(): Capture
    }
Loading

Class diagram for Memo changes (use of Int2ObjectMap)

classDiagram
    class Memo {
        -groups: Int2ObjectMap<Group>
        +extract(): PlanNode
        +replace(int, PlanNode, String): void
        +getAllReferences(PlanNode): Set<Integer>
        +deleteGroup(int): void
        +insertChildrenAndRewrite(PlanNode): PlanNode
    }
    Memo o-- "*" Group
Loading

Class diagram for PlanFragment changes

classDiagram
    class PlanFragment {
        -partitionCount: OptionalInt
        -outputPartitioningScheme: PartitioningScheme
        +getPartitionCount(): OptionalInt
        +getTypes(): List<Type>
    }
    PlanFragment o-- "1" PartitioningScheme
Loading

Class diagram for NodeScheduler and related node selection changes

classDiagram
    class NodeScheduler {
        +static getAllNodes(NodeMap, boolean): Set<InternalNode>
        +static filterNodes(NodeMap, boolean, Set<InternalNode>): Set<InternalNode>
        +static selectExactNodes(NodeMap, List<HostAddress>, boolean): List<InternalNode>
    }
    NodeScheduler o-- "*" InternalNode
Loading

Class diagram for usage of Int2ObjectMap in PipelinedStageExecution

classDiagram
    class PipelinedStageExecution {
        -tasks: Int2ObjectMap<RemoteTask>
    }
    PipelinedStageExecution o-- "*" RemoteTask
Loading

File-Level Changes

Change Details Files
Stream-to-Iterable refactoring across internal APIs
  • Change resolveGroup/resolve in Lookup to return Iterable instead of Stream
  • Replace Pattern.match()/accept() streams with Iterable and use Guava Iterables.concat/transform
  • Convert Plans visitor and Memo child traversal from stream.collect() to ImmutableList.Builder loops
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Lookup.java
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Plans.java
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Memo.java
lib/trino-matching/src/main/java/io/trino/matching/Pattern.java
lib/trino-matching/src/main/java/io/trino/matching/OrPattern.java
lib/trino-matching/src/main/java/io/trino/matching/WithPattern.java
Primitive specializations to avoid boxing
  • Replace Optional/Optional with OptionalInt
  • Use Comparator.comparingInt/comparingLong instead of boxing comparators
  • Switch AtomicLong to LongAdder and Int-based maps to Int2ObjectMap
core/trino-main/src/main/java/io/trino/sql/planner/plan/Assignments.java
core/trino-main/src/main/java/io/trino/sql/planner/plan/PartitioningScheme.java
core/trino-main/src/main/java/io/trino/execution/querystats/QueryPlanOptimizerStats.java
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Memo.java
Optimize Immutable collections with presized builders
  • Provide builderWithExpectedSize for known collection sizes
  • Use ImmutableList.builderWithExpectedSize and ImmutableMap.builderWithExpectedSize
  • Replace LinkedHashMap backing in Assignments.Builder with ImmutableMap.Builder
core/trino-main/src/main/java/io/trino/sql/planner/plan/Assignments.java
core/trino-main/src/main/java/io/trino/sql/planner/plan/PartitioningScheme.java
Restructure Lookup interface into sealed types
  • Define Lookup as a sealed interface with ThrowingLookup constant
  • Introduce record LookupFromFunction for wrapping resolvers
  • Remove legacy Stream-based from() and noLookup() implementations
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Lookup.java
Replace stream-based set/list transformations in schedulers
  • Switch NodeScheduler.getAllNodes/filterNodes to return Set via ImmutableSet or Sets.difference
  • Unroll stream.forEach() into explicit loops for selectExactNodes
  • Collect schedulable nodes without intermediate streams
core/trino-main/src/main/java/io/trino/execution/scheduler/NodeScheduler.java
Simplify matching tests by dropping toOptional() and onlyElement()
  • Replace .collect(toOptional())/collect(onlyElement()) with direct Iterable checks
  • Use Iterables.getOnlyElement() and assertThat(...).isEmpty()
  • Remove Stream imports in TestMatcher and related tests
lib/trino-matching/src/test/java/io/trino/matching/TestMatcher.java
plugin/trino-base-jdbc/src/test/java/io/trino/plugin/jdbc/expression/TestExpressionMatching.java
Improve pattern-matching engine to use Iterable APIs
  • Convert accept() methods in CapturePattern, EqualsPattern, FilterPattern, TypeOfPattern to return Iterable
  • Use ImmutableList.of() for zero/one matches
  • Remove Stream imports and usages in matching library
lib/trino-matching/src/main/java/io/trino/matching/CapturePattern.java
lib/trino-matching/src/main/java/io/trino/matching/EqualsPattern.java
lib/trino-matching/src/main/java/io/trino/matching/FilterPattern.java
lib/trino-matching/src/main/java/io/trino/matching/TypeOfPattern.java
Adopt requireNonNull and record constructors
  • Replace explicit null checks or Preconditions.checkArgument with Objects.requireNonNull
  • Add canonical constructors to LookupFromFunction record
  • Use record for CacheKey in FaultTolerantPartitioningSchemeFactory
core/trino-main/src/main/java/io/trino/sql/planner/iterative/Lookup.java
core/trino-main/src/main/java/io/trino/execution/scheduler/faulttolerant/FaultTolerantPartitioningSchemeFactory.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

@github-actions github-actions bot added iceberg Iceberg connector delta-lake Delta Lake connector labels Oct 29, 2025
@wendigo wendigo requested a review from raunaqmorarka October 29, 2025 22:14
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 - here's some feedback:

  • This PR changes many public methods from Optional/Stream to OptionalInt/Iterable which is a breaking API change—please update the public API docs, release notes, and consider adding deprecation stubs or migration guidance.
  • Several JSON-annotated classes now use OptionalInt; ensure Jackson (de)serialization is configured to handle OptionalInt properly by adding custom modules or annotations where needed.
  • There are many repetitive manual loops and Guava Iterables usage replacing Stream pipelines—consider introducing a small utility method to convert sources into an ImmutableList to keep code concise and consistent.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- This PR changes many public methods from Optional<Integer>/Stream to OptionalInt/Iterable which is a breaking API change—please update the public API docs, release notes, and consider adding deprecation stubs or migration guidance.
- Several JSON-annotated classes now use OptionalInt; ensure Jackson (de)serialization is configured to handle OptionalInt properly by adding custom modules or annotations where needed.
- There are many repetitive manual loops and Guava Iterables usage replacing Stream pipelines—consider introducing a small utility method to convert sources into an ImmutableList to keep code concise and consistent.

## Individual Comments

### Comment 1
<location> `core/trino-main/src/main/java/io/trino/execution/scheduler/UniformNodeSelector.java:161` </location>
<code_context>
         Set<InternalNode> blockedExactNodes = new HashSet<>();
         boolean splitWaitingForAnyNode = false;

-        List<InternalNode> filteredNodes = filterNodes(nodeMap, includeCoordinator, ImmutableSet.of());
+        Set<InternalNode> filteredNodes = filterNodes(nodeMap, includeCoordinator, ImmutableSet.of());
         ResettableRandomizedIterator<InternalNode> randomCandidates = new ResettableRandomizedIterator<>(filteredNodes);
         Set<InternalNode> schedulableNodes = new HashSet<>(filteredNodes);
</code_context>

<issue_to_address>
**question:** Changing filteredNodes to Set may affect assignment logic if order is important.

Please verify that computeAssignments does not depend on the order of filteredNodes, as switching from List to Set removes ordering guarantees.
</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.

@wendigo wendigo force-pushed the serafin/matching-iterable branch 3 times, most recently from 063beeb to 9024bc0 Compare October 30, 2025 00:04
Copy link
Member

@raunaqmorarka raunaqmorarka left a comment

Choose a reason for hiding this comment

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

Please try to avoid stacking 20+ unrelated commits in one PR and try to organize PRs by some common theme


@Override
public <C> Stream<Match> accept(Object object, Captures captures, C context)
public <C> Iterable<Match> accept(Object object, Captures captures, C context)
Copy link
Member

Choose a reason for hiding this comment

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

What's the benefit of using Iterable instead of Stream ?
I thought Stream is usually preferred in modern java code

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We convert stream to the iterator in the usage site anyway so I don't think it is a right abstraction here. I'm not fan of streams either :)

Comment on lines -48 to +45
Stream<PlanNode> resolveGroup(PlanNode node);
Iterable<PlanNode> resolveGroup(PlanNode node);
Copy link
Member

Choose a reason for hiding this comment

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

Why does it matter ?

@wendigo wendigo force-pushed the serafin/matching-iterable branch from 9024bc0 to 218f953 Compare October 30, 2025 09:04
@wendigo wendigo force-pushed the serafin/matching-iterable branch from 218f953 to f955854 Compare October 30, 2025 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla-signed delta-lake Delta Lake connector iceberg Iceberg connector

Development

Successfully merging this pull request may close these issues.

4 participants