-
Notifications
You must be signed in to change notification settings - Fork 121
[Feature] Support TTL on ShortTermMemory #657
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
da-daken
wants to merge
5
commits into
apache:main
Choose a base branch
from
da-daken:new_short_memory_ttl
base: main
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
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1ec60b6
[Feature] Support TTL on ShortTermMemory
6e9196a
[Feature] mvn spotless:apply
3772f8e
[Feature] Fix CR for TTL on ShortTermMemory
920f8c6
Merge branch 'main' into new_short_memory_ttl
ba07be0
[Feature] Fix CR for TestName & docs
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
25 changes: 25 additions & 0 deletions
25
api/src/main/java/org/apache/flink/agents/api/agents/ShortTermMemoryTtlUpdate.java
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,25 @@ | ||
| /* | ||
| * 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. | ||
| */ | ||
|
|
||
| package org.apache.flink.agents.api.agents; | ||
|
|
||
| /** Defines when short-term memory state TTL is refreshed. */ | ||
| public enum ShortTermMemoryTtlUpdate { | ||
| ON_CREATE_AND_WRITE, | ||
| ON_READ_AND_WRITE | ||
| } |
25 changes: 25 additions & 0 deletions
25
api/src/main/java/org/apache/flink/agents/api/agents/ShortTermMemoryTtlVisibility.java
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,25 @@ | ||
| /* | ||
| * 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. | ||
| */ | ||
|
|
||
| package org.apache.flink.agents.api.agents; | ||
|
|
||
| /** Defines whether expired short-term memory state can be returned before cleanup. */ | ||
| public enum ShortTermMemoryTtlVisibility { | ||
| NEVER_RETURN_EXPIRED, | ||
| RETURN_EXPIRED_IF_NOT_CLEANED_UP | ||
| } |
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 |
|---|---|---|
|
|
@@ -72,6 +72,7 @@ | |
| * public static ResourceDesc openAIResponses() { | ||
| * return ResourceDescriptor.Builder.newBuilder(OpenAIResponsesModelConnection.class.getName()) | ||
| * .addInitialArgument("api_key", System.getenv("OPENAI_API_KEY")) | ||
| * .addInitialArgument("api_base_url", System.getenv("OPENAI_API_URL")) | ||
|
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. This change is unrelated to TTL. It should be placed in a separate commit. Usually, in such cases, we add |
||
| * .addInitialArgument("timeout", 120) | ||
| * .addInitialArgument("max_retries", 3) | ||
| * .build(); | ||
|
|
||
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
178 changes: 178 additions & 0 deletions
178
python/flink_agents/e2e_tests/e2e_tests_integration/short_term_memory_ttl_test.py
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,178 @@ | ||
| ################################################################################ | ||
| # 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 os | ||
| import sysconfig | ||
| import time | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from pydantic import BaseModel | ||
| from pyflink.common import Configuration | ||
| from pyflink.datastream import KeySelector, StreamExecutionEnvironment | ||
|
|
||
| from flink_agents.api.agents.agent import Agent | ||
| from flink_agents.api.core_options import ( | ||
| AgentExecutionOptions, | ||
| ShortTermMemoryTtlUpdate, | ||
| ShortTermMemoryTtlVisibility, | ||
| ) | ||
| from flink_agents.api.decorators import action | ||
| from flink_agents.api.events.event import Event, InputEvent, OutputEvent | ||
| from flink_agents.api.execution_environment import AgentsExecutionEnvironment | ||
| from flink_agents.api.runner_context import RunnerContext | ||
|
|
||
| current_dir = Path(__file__).parent | ||
| os.environ["PYTHONPATH"] = ( | ||
| f"{current_dir.parent.parent.parent}:{sysconfig.get_paths()['purelib']}" | ||
| ) | ||
|
|
||
|
|
||
| class TtlTestInput(BaseModel): | ||
| event_key: str | ||
| sleep_ms: int | ||
|
|
||
|
|
||
| class TtlTestKeySelector(KeySelector): | ||
| def get_key(self, value: TtlTestInput) -> str: | ||
| return "test_key" | ||
|
|
||
|
|
||
| class ShortTermMemoryTtlTestAgent(Agent): | ||
| @action(InputEvent.EVENT_TYPE) | ||
| @staticmethod | ||
| def input(event: Event, ctx: RunnerContext) -> None: | ||
| input_data = TtlTestInput.model_validate(InputEvent.from_event(event).input) | ||
|
|
||
| short_term_memory = ctx.short_term_memory | ||
| existing_value = short_term_memory.get(input_data.event_key) | ||
| current_count = 0 | ||
| if isinstance(existing_value, int): | ||
| current_count = existing_value | ||
| elif isinstance(existing_value, float): | ||
| current_count = int(existing_value) | ||
|
|
||
| short_term_memory.set(input_data.event_key, current_count + 1) | ||
| time.sleep(input_data.sleep_ms / 1000) | ||
| ctx.send_event( | ||
| OutputEvent( | ||
| output=( | ||
| f"{input_data.event_key}|" | ||
| f"{'NEW' if existing_value is None else 'EXISTING'}" | ||
| ) | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| def run_scenario( | ||
| ttl_ms: int, | ||
| sleep_ms: int, | ||
| *, | ||
| configure_ttl_ms: bool, | ||
| configure_ttl_options: bool, | ||
| ) -> list[Any]: | ||
| config = Configuration() | ||
| config.set_string("python.pythonpath", os.environ["PYTHONPATH"]) | ||
| env = StreamExecutionEnvironment.get_execution_environment(config) | ||
| env.set_parallelism(1) | ||
|
|
||
| input_stream = env.from_collection( | ||
| [ | ||
| TtlTestInput(event_key="event1", sleep_ms=sleep_ms), | ||
| TtlTestInput(event_key="event2", sleep_ms=sleep_ms), | ||
| TtlTestInput(event_key="event1", sleep_ms=sleep_ms), | ||
| ] | ||
| ) | ||
|
|
||
| agents_env = AgentsExecutionEnvironment.get_execution_environment(env=env) | ||
| agents_config = agents_env.get_config() | ||
| if configure_ttl_ms: | ||
| agents_config.set(AgentExecutionOptions.SHORT_TERM_MEMORY_STATE_TTL_MS, ttl_ms) | ||
| if configure_ttl_options: | ||
| agents_config.set( | ||
| AgentExecutionOptions.SHORT_TERM_MEMORY_STATE_TTL_UPDATE_TYPE, | ||
| ShortTermMemoryTtlUpdate.ON_CREATE_AND_WRITE, | ||
| ) | ||
| agents_config.set( | ||
| AgentExecutionOptions.SHORT_TERM_MEMORY_STATE_TTL_VISIBILITY, | ||
| ShortTermMemoryTtlVisibility.NEVER_RETURN_EXPIRED, | ||
| ) | ||
|
|
||
| output_datastream = ( | ||
| agents_env.from_datastream( | ||
| input=input_stream, key_selector=TtlTestKeySelector() | ||
| ) | ||
| .apply(ShortTermMemoryTtlTestAgent()) | ||
| .to_datastream() | ||
| ) | ||
|
|
||
| return list(output_datastream.execute_and_collect()) | ||
|
|
||
|
|
||
| def test_value_still_visible_before_ttl_expiry() -> None: | ||
| results = run_scenario( | ||
| 1000, | ||
| 0, | ||
| configure_ttl_ms=True, | ||
| configure_ttl_options=True, | ||
| ) | ||
|
|
||
| assert results == ["event1|NEW", "event2|NEW", "event1|EXISTING"] | ||
|
|
||
|
|
||
| def test_ttl_configuration_disabled_with_zero_ttl() -> None: | ||
| results = run_scenario( | ||
| 0, | ||
| 2000, | ||
| configure_ttl_ms=True, | ||
| configure_ttl_options=True, | ||
| ) | ||
|
|
||
| assert results == ["event1|NEW", "event2|NEW", "event1|EXISTING"] | ||
|
|
||
|
|
||
| def test_ttl_configuration_disabled_by_default() -> None: | ||
| results = run_scenario( | ||
| 0, | ||
| 2000, | ||
| configure_ttl_ms=False, | ||
| configure_ttl_options=True, | ||
| ) | ||
|
|
||
| assert results == ["event1|NEW", "event2|NEW", "event1|EXISTING"] | ||
|
|
||
|
|
||
| def test_value_expires_after_ttl() -> None: | ||
| results = run_scenario( | ||
| 1000, | ||
| 2000, | ||
| configure_ttl_ms=True, | ||
| configure_ttl_options=True, | ||
| ) | ||
|
|
||
| assert results == ["event1|NEW", "event2|NEW", "event1|NEW"] | ||
|
|
||
|
|
||
| def test_ttl_configuration_applied_with_default_update_type_and_visibility() -> None: | ||
| results = run_scenario( | ||
| 1000, | ||
| 2000, | ||
| configure_ttl_ms=True, | ||
| configure_ttl_options=False, | ||
| ) | ||
|
|
||
| assert results == ["event1|NEW", "event2|NEW", "event1|NEW"] |
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
Oops, something went wrong.
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.
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.
Nit: 0L doubles as the "TTL disabled" sentinel, but that contract only lives in OperatorStateManager.maybeEnableShortTermMemoryTTL. A one-line javadoc here — e.g. "Set to a positive value in milliseconds to enable TTL; 0 (the default) disables it" — would spare future readers a trip into the runtime. Same applies to the two enum options below: worth noting they're only consulted when TTL_MS > 0.