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

perf: Utilize ORDER BY LIMIT over ROW_NUMBER where possible #1077

Merged
merged 11 commits into from
Oct 18, 2024

Conversation

TrevorBergeron
Copy link
Contributor

Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

  • Make sure to open an issue as a bug/issue before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
  • Ensure the tests and linter pass
  • Code coverage does not decrease (if any source code was changed)
  • Appropriate docs were updated (if necessary)

Fixes #<issue_number_goes_here> 🦕

@TrevorBergeron TrevorBergeron requested review from a team as code owners October 10, 2024 20:24
@product-auto-label product-auto-label bot added the size: m Pull request size is medium. label Oct 10, 2024
@product-auto-label product-auto-label bot added the api: bigquery Issues related to the googleapis/python-bigquery-dataframes API. label Oct 10, 2024
@@ -385,6 +385,44 @@ def common_selection_root(
return None


def pullup_limit_from_slice(
Copy link
Contributor

Choose a reason for hiding this comment

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

Are we able to have a test to verify this process?

@product-auto-label product-auto-label bot added size: l Pull request size is large. and removed size: m Pull request size is medium. labels Oct 11, 2024
@TrevorBergeron TrevorBergeron requested a review from tswast October 14, 2024 21:25
sql += f"{order_by_clause}\n"
sql += f"\n{order_by_clause}"
if limit is not None:
assert isinstance(limit, int)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should we raise a TypeError here instead of an assertion error?

I don't know how well our public APIs are validating the type of parameters. Not everyone is going to use a type checker.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, in general, probably best to assume that wrong types can sometimes reach even the lower levels of the code base. In particular want to be safe about what we are putting into the sql strings. Switched to TypeError here.

@property
def is_limit(self) -> bool:
"""Returns whether this is equivalent to a ORDER BY ... LIMIT N."""
return (not self.start) and (self.step == 1) and (self.stop is not None)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe a TODO to handle the negative version (e.g. "tail") too? One would have to reverse the order twice, but doable.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah, should be doable, if a bit tricky. adding a todo

return None
return self.left_child.row_count * self.right_child.row_count

return None
Copy link
Collaborator

Choose a reason for hiding this comment

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

TODO for left/right join with a unique join key?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Need a bit more than just unique join keys to determine exact cardinality. The join keys on the outer side all need to have a match on the inner side as well. Most of these cases will be handled by implicit joiner.

I think upper bound will also be useful (and possible to generate for every node type except explode), so may add that as well later on.

@@ -635,12 +681,24 @@ def relation_ops_created(self) -> int:
return 3

@property
def supports_fast_head(self) -> bool:
def fast_offsets(self) -> bool:
# Fast head is only supported when row offsets are available.
Copy link
Collaborator

Choose a reason for hiding this comment

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

This comment is out of date now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated comment to mention clustering

cast(ex.DerefOp, col.scalar_expression).id.name for col in order_cols
)
cluster_col_ids = self.source.table.cluster_cols
return order_col_ids == cluster_col_ids
Copy link
Collaborator

Choose a reason for hiding this comment

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

I suspect if cluster_col_ids is a prefix of order_col_ids, it'd be fast-ish too, at least if the clustering is selective enough.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think its best to be conservative on this. In theory, the important parts of the order ids could be the later parts, not in the clustering. Also, the query engine is binary about this optimization, either on or off. Can maybe run some tests and loosen the requirement later.

"""Attempts to simplify the slice."""
row_count = traversals.row_count(node)
start, stop, step = node.start, node.stop, node.step
def rewrite_slice(node: nodes.SliceNode):
Copy link
Collaborator

Choose a reason for hiding this comment

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

rewrite_slice seems like a good candidate for some unit tests if we don't have some already.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ok, added some unit tests. Bit rough writing tree tests right now. Might need to setup a little framework if we want to do lots of these. Local engine could also be a way to ensure that tree rewrites do not change result value.

node, bigframes.core.identifiers.ColumnId(offsets_id)
)
predicate = ops.lt_op.as_expr(ex.deref(offsets_id), ex.const(n))
plan_w_head = nodes.FilterNode(plan_w_offsets, predicate)
# Finally, drop the offsets column
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this comment is out of date now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

removed

@TrevorBergeron TrevorBergeron requested a review from tswast October 16, 2024 19:29
Copy link
Collaborator

@tswast tswast left a comment

Choose a reason for hiding this comment

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

Love it!

Do we have data on how this will affect our benchmark results?

@TrevorBergeron TrevorBergeron merged commit 7003d1a into main Oct 18, 2024
17 of 23 checks passed
@TrevorBergeron TrevorBergeron deleted the slice_pullup branch October 18, 2024 18:26
@TrevorBergeron
Copy link
Contributor Author

Love it!

Do we have data on how this will affect our benchmark results?

Probably most impact on notebook benchmarks initially. TPCH uses to_gbq which will not use this optimization until further changes (need to be careful not to use ORDER BY LIMIT when writing to clustered tables)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api: bigquery Issues related to the googleapis/python-bigquery-dataframes API. size: l Pull request size is large.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants