-
Notifications
You must be signed in to change notification settings - Fork 29.3k
[SPARK-40432][SS][PYTHON] Introduce GroupStateImpl and GroupStateTimeout in PySpark #37889
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
Closed
Closed
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f7706c5
[SPARK-40432][SS][PYTHON] Introduce GroupStateImpl and GroupStateTime…
HeartSaVioR a28cc53
meta-commit to credit properly on co-authorship
HyukjinKwon 64ebd20
Update sql/catalyst/src/main/java/org/apache/spark/sql/streaming/Grou…
HeartSaVioR 4b85557
add missed file
HeartSaVioR 0c63198
update SPARK-XXXXX to SPARK-40437
HeartSaVioR 59862ca
fix
HeartSaVioR 9c97c6b
trigger
HeartSaVioR dd96783
fix lint
HeartSaVioR 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| # | ||
| # Licensed to the Apache Software Foundation (ASF) under one or more | ||
| # contributor license agreements. See the NOTICE file distributed with | ||
| # this work for additional information regarding copyright ownership. | ||
| # The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| # (the "License"); you may not use this file except in compliance with | ||
| # the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| import datetime | ||
| import json | ||
| from typing import Tuple, Optional | ||
|
|
||
| from pyspark.sql.types import DateType, Row, StructType | ||
|
|
||
| __all__ = ["GroupStateImpl", "GroupStateTimeout"] | ||
|
|
||
|
|
||
| class GroupStateTimeout: | ||
| NoTimeout: str = "NoTimeout" | ||
| ProcessingTimeTimeout: str = "ProcessingTimeTimeout" | ||
| EventTimeTimeout: str = "EventTimeTimeout" | ||
|
|
||
|
|
||
| class GroupStateImpl: | ||
| NO_TIMESTAMP: int = -1 | ||
|
|
||
| def __init__( | ||
| self, | ||
| # JVM Constructor | ||
| optionalValue: Row, | ||
| batchProcessingTimeMs: int, | ||
| eventTimeWatermarkMs: int, | ||
| timeoutConf: str, | ||
| hasTimedOut: bool, | ||
| watermarkPresent: bool, | ||
| # JVM internal state. | ||
| defined: bool, | ||
| updated: bool, | ||
| removed: bool, | ||
| timeoutTimestamp: int, | ||
| # Python internal state. | ||
| keyAsUnsafe: bytes, | ||
| valueSchema: StructType, | ||
| ) -> None: | ||
| self._keyAsUnsafe = keyAsUnsafe | ||
| self._value = optionalValue | ||
| self._batch_processing_time_ms = batchProcessingTimeMs | ||
| self._event_time_watermark_ms = eventTimeWatermarkMs | ||
|
|
||
| assert timeoutConf in [ | ||
| GroupStateTimeout.NoTimeout, | ||
| GroupStateTimeout.ProcessingTimeTimeout, | ||
| GroupStateTimeout.EventTimeTimeout, | ||
| ] | ||
| self._timeout_conf = timeoutConf | ||
|
|
||
| self._has_timed_out = hasTimedOut | ||
| self._watermark_present = watermarkPresent | ||
|
|
||
| self._defined = defined | ||
| self._updated = updated | ||
| self._removed = removed | ||
| self._timeout_timestamp = timeoutTimestamp | ||
| # Python internal state. | ||
| self._old_timeout_timestamp = timeoutTimestamp | ||
|
|
||
| self._value_schema = valueSchema | ||
|
|
||
| @property | ||
| def exists(self) -> bool: | ||
| return self._defined | ||
|
|
||
| @property | ||
| def get(self) -> Tuple: | ||
| if self.exists: | ||
| return tuple(self._value) | ||
| else: | ||
| raise ValueError("State is either not defined or has already been removed") | ||
|
|
||
| @property | ||
| def getOption(self) -> Optional[Tuple]: | ||
| if self.exists: | ||
| return tuple(self._value) | ||
| else: | ||
| return None | ||
|
|
||
| @property | ||
| def hasTimedOut(self) -> bool: | ||
| return self._has_timed_out | ||
|
|
||
| # NOTE: this function is only available to PySpark implementation due to underlying | ||
| # implementation, do not port to Scala implementation! | ||
| @property | ||
| def oldTimeoutTimestamp(self) -> int: | ||
| return self._old_timeout_timestamp | ||
|
|
||
| def update(self, newValue: Tuple) -> None: | ||
| if newValue is None: | ||
| raise ValueError("'None' is not a valid state value") | ||
|
|
||
| self._value = Row(*newValue) | ||
| self._defined = True | ||
| self._updated = True | ||
| self._removed = False | ||
|
|
||
| def remove(self) -> None: | ||
| self._defined = False | ||
| self._updated = False | ||
| self._removed = True | ||
|
|
||
| def setTimeoutDuration(self, durationMs: int) -> None: | ||
| if isinstance(durationMs, str): | ||
| # TODO(SPARK-XXXXX): Support string representation of durationMs. | ||
| raise ValueError("durationMs should be int but get :%s" % type(durationMs)) | ||
|
|
||
| if self._timeout_conf != GroupStateTimeout.ProcessingTimeTimeout: | ||
| raise RuntimeError( | ||
| "Cannot set timeout duration without enabling processing time timeout in " | ||
| "applyInPandasWithState" | ||
| ) | ||
|
|
||
| if durationMs <= 0: | ||
| raise ValueError("Timeout duration must be positive") | ||
| self._timeout_timestamp = durationMs + self._batch_processing_time_ms | ||
|
|
||
| # TODO(SPARK-XXXXX): Implement additionalDuration parameter. | ||
|
HyukjinKwon marked this conversation as resolved.
Outdated
|
||
| def setTimeoutTimestamp(self, timestampMs: int) -> None: | ||
| if self._timeout_conf != GroupStateTimeout.EventTimeTimeout: | ||
| raise RuntimeError( | ||
| "Cannot set timeout duration without enabling processing time timeout in " | ||
| "applyInPandasWithState" | ||
| ) | ||
|
|
||
| if isinstance(timestampMs, datetime.datetime): | ||
| timestampMs = DateType().toInternal(timestampMs) | ||
|
|
||
| if timestampMs <= 0: | ||
| raise ValueError("Timeout timestamp must be positive") | ||
|
|
||
| if ( | ||
| self._event_time_watermark_ms != GroupStateImpl.NO_TIMESTAMP | ||
| and timestampMs < self._event_time_watermark_ms | ||
| ): | ||
| raise ValueError( | ||
| "Timeout timestamp (%s) cannot be earlier than the " | ||
| "current watermark (%s)" % (timestampMs, self._event_time_watermark_ms) | ||
| ) | ||
|
|
||
| self._timeout_timestamp = timestampMs | ||
|
|
||
| def getCurrentWatermarkMs(self) -> int: | ||
| if not self._watermark_present: | ||
| raise RuntimeError( | ||
| "Cannot get event time watermark timestamp without setting watermark before " | ||
| "applyInPandasWithState" | ||
| ) | ||
| return self._event_time_watermark_ms | ||
|
|
||
| def getCurrentProcessingTimeMs(self) -> int: | ||
| return self._batch_processing_time_ms | ||
|
|
||
| def __str__(self) -> str: | ||
| if self.exists: | ||
| return "GroupState(%s)" % (self.get, ) | ||
| else: | ||
| return "GroupState(<undefined>)" | ||
|
|
||
| def json(self) -> str: | ||
| return json.dumps( | ||
| { | ||
| # Constructor | ||
| "optionalValue": None, # Note that optionalValue will be manually serialized. | ||
| "batchProcessingTimeMs": self._batch_processing_time_ms, | ||
| "eventTimeWatermarkMs": self._event_time_watermark_ms, | ||
| "timeoutConf": self._timeout_conf, | ||
| "hasTimedOut": self._has_timed_out, | ||
| "watermarkPresent": self._watermark_present, | ||
| # JVM internal state. | ||
| "defined": self._defined, | ||
| "updated": self._updated, | ||
| "removed": self._removed, | ||
| "timeoutTimestamp": self._timeout_timestamp, | ||
| } | ||
| ) | ||
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
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.