-
Notifications
You must be signed in to change notification settings - Fork 205
Expose query stats through a cursor callback #623
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
Open
hashhar
wants to merge
1
commit into
trinodb:master
Choose a base branch
from
hashhar:hashhar/578-stats-callback
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -55,6 +55,7 @@ | |
| from enum import Enum | ||
| from time import sleep | ||
| from typing import Any | ||
| from typing import Callable | ||
| from typing import cast | ||
| from typing import Dict | ||
| from typing import List | ||
|
|
@@ -885,7 +886,8 @@ def __init__( | |
| request: TrinoRequest, | ||
| query: str, | ||
| legacy_primitive_types: bool = False, | ||
| fetch_mode: Literal["mapped", "segments"] = "mapped" | ||
| fetch_mode: Literal["mapped", "segments"] = "mapped", | ||
| stats_callback: Optional[Callable[[Dict[str, Any]], None]] = None | ||
| ) -> None: | ||
| self._query_id: Optional[str] = None | ||
| self._stats: Dict[Any, Any] = {} | ||
|
|
@@ -903,6 +905,7 @@ def __init__( | |
| self._legacy_primitive_types = legacy_primitive_types | ||
| self._row_mapper: Optional[RowMapper] = None | ||
| self._fetch_mode = fetch_mode | ||
| self._stats_callback = stats_callback | ||
|
|
||
| @property | ||
| def query_id(self) -> Optional[str]: | ||
|
|
@@ -980,6 +983,7 @@ def execute(self, additional_http_headers=None) -> TrinoResult: | |
| self._stats.update({"queryId": self.query_id}) | ||
| self._update_state(status) | ||
| self._warnings = getattr(status, "warnings", []) | ||
| self._report_stats() | ||
| if status.next_uri is None: | ||
| self._finished = True | ||
|
|
||
|
|
@@ -1019,6 +1023,11 @@ def _update_state(self, status): | |
| if status.columns: | ||
| self._columns = status.columns | ||
|
|
||
| def _report_stats(self) -> None: | ||
| if self._stats_callback is not None: | ||
| # Pass a copy so the callback cannot mutate internal query state. | ||
| self._stats_callback(dict(self._stats)) | ||
|
|
||
| def fetch(self) -> Union[List[Union[List[Any], Any]], Iterator[List[Any]]]: | ||
| """Continue fetching data for the current query_id""" | ||
| try: | ||
|
|
@@ -1027,6 +1036,7 @@ def fetch(self) -> Union[List[Union[List[Any], Any]], Iterator[List[Any]]]: | |
| raise trino.exceptions.TrinoConnectionError("failed to fetch: {}".format(e)) | ||
| status = self._request.process(response) | ||
| self._update_state(status) | ||
| self._report_stats() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Feel free to resolve this comment if you think it's better to leave the calls outside. |
||
| if status.next_uri is None: | ||
| self._finished = True | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use a deep copy to prevent mutation of nested query state.
The dictionary
self._statscontains deeply nested JSON structures (such asrootStageandoperatorSummaries) returned by the Trino coordinator. A shallowdict()copy only protects the top-level keys; if the callback mutates a nested dictionary or list, it will modify the client's internal query state.To fully enforce the isolation contract promised in the documentation and comments, use a deep copy.
🛡️ Proposed fix to use deepcopy
Make sure to add
import copyat the top of the file if it is not already imported.def _report_stats(self) -> None: if self._stats_callback is not None: - # Pass a copy so the callback cannot mutate internal query state. - self._stats_callback(dict(self._stats)) + # Pass a deep copy so the callback cannot mutate internal query state. + import copy + self._stats_callback(copy.deepcopy(self._stats))📝 Committable suggestion
🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like a reasonable suggestion
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@azawlocki-sbdt, agreed. Sincecopyis already imported at module scope, the minimal change is to callcopy.deepcopy(self._stats)in_report_stats(), preventing callback mutations of nested statistics from affecting the query’s internal state.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@hashhar, can you also add a test that checks that the callback cannot modify the original stats?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Length of output: 49444
🏁 Script executed:
Length of output: 6894
@azawlocki-sbdt, yes. The regression test will mutate nestedrootStage/operatorSummariesdata in the callback and assert the query’s internal stats are unaffected. It will fail with the current shallow copy and pass withdeepcopy.copy.deepcopy()when reporting callback statistics.tests/unit/test_client.py.🧬 Code Graph Analysis Results
Relevant code snippets
trino/client.py(around lines 410-470) —TrinoQuerycaptures the callbacktrino/client.py(around lines 500-535) —_update_statemutates internal stats, which the callback seestrino/client.py(around lines 536-545) —_report_statspasses a copy so the callback can’t mutate_statstrino/client.py(around lines 445-505) —execute()calls_report_stats()after updating statetrino/client.py(around lines 560-620) —fetch()also calls_report_stats()after updating statetrino/client.py(around lines 475-485) — external reads of internal stats (what the test would assert)trino/dbapi.py(provided line numbers: 633-666) — DB-API wiresstats_callbackintoTrinoQuery