Skip to content

Fix/agent runtime delete session#426

Open
vivek41-glitch wants to merge 6 commits into
volcano-sh:mainfrom
vivek41-glitch:fix/agent-runtime-delete-session
Open

Fix/agent runtime delete session#426
vivek41-glitch wants to merge 6 commits into
volcano-sh:mainfrom
vivek41-glitch:fix/agent-runtime-delete-session

Conversation

@vivek41-glitch

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind enhancement

What this PR does / why we need it:

This PR implements server-side session deletion for AgentRuntimeClient, bringing it in line with the existing lifecycle management of CodeInterpreterClient.

Previously, AgentRuntimeClient could create sessions via bootstrap_session_id() but had no way to delete them server-side. The close() method only closed the local HTTP connection, leaving the remote sandbox/session running indefinitely on the cluster. This caused resource leaks and inconsistency with CodeInterpreterClient, which already has a proper stop() method.

Changes introduced:

  • Added delete_agent_runtime_session() to ControlPlaneClient to call DELETE /v1/agent-runtime/sessions/:sessionId
  • Added stop() method to AgentRuntimeClient that:
    • Closes the local data-plane connection
    • Deletes the server-side session only if the session is owned by this client
  • Updated __exit__ to call stop() instead of close() for proper cleanup in context managers
  • Added workload_manager_url and auth_token parameters with environment variable fallback (AGENTCUBE_WORKLOAD_MANAGER_URL, AGENTCUBE_AUTH_TOKEN)
  • Updated example to demonstrate stop() usage
  • Added unit tests for owned session deletion, attached session preservation, and context manager behavior

Which issue(s) this PR fixes:
Fixes #395

Special notes for reviewer:

This is a Python SDK-only change. No Go backend changes are required as the endpoint DELETE /v1/agent-runtime/sessions/:sessionId already exists in pkg/workloadmanager/server.go (shared handleDeleteSandbox handler).

The implementation follows the exact same pattern as CodeInterpreterClient.stop():

  • Owned sessions (created by the client) are deleted
  • Attached sessions (provided via session_id) are preserved
  • Context managers automatically clean up

Does this PR introduce a user-facing change?:

AgentRuntimeClient now supports server-side session deletion via the new `stop()` method, matching the lifecycle behavior of CodeInterpreterClient.

test: remove duplicate TestHandleHealth function
Copilot AI review requested due to automatic review settings July 7, 2026 18:35
@volcano-sh-bot

Copy link
Copy Markdown
Contributor

Adding label do-not-merge/contains-merge-commits because PR contains merge commits, which are not allowed in this repository.
Use git rebase to reapply your commits on top of the target branch. Detailed instructions for doing so can be found here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@volcano-sh-bot

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign acsoto for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request integrates server-side session management into the AgentRuntimeClient using a new ControlPlaneClient. Key changes include adding configuration for a workload manager, implementing a stop() method to delete owned sessions, and updating examples and tests. The review feedback highlights several critical issues: first, ControlPlaneClient lacks the create_agent_runtime_session method, which will cause an AttributeError on startup; second, an exception in self.close() during stop() can prevent session deletion, risking resource leaks; third, parsing an empty 200 OK response as JSON will trigger a JSONDecodeError; and finally, the unit tests must be updated to mock the correct bootstrapping behavior.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment thread sdk-python/agentcube/clients/control_plane.py Outdated
Comment thread sdk-python/tests/test_agent_runtime.py Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the Python SDK’s AgentRuntimeClient lifecycle management to support server-side session deletion (similar to CodeInterpreterClient), aiming to prevent sandbox/session resource leaks when clients are done.

Changes:

  • Add ControlPlaneClient.delete_agent_runtime_session() for DELETE /v1/agent-runtime/sessions/:sessionId.
  • Add AgentRuntimeClient.stop() and switch context-manager cleanup to call stop() instead of close().
  • Add/update example and tests to cover owned vs attached session behavior and context manager cleanup.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 9 comments.

File Description
sdk-python/agentcube/agent_runtime.py Adds control-plane integration, ownership tracking, and stop() cleanup for AgentRuntime sessions.
sdk-python/agentcube/clients/control_plane.py Adds an agent-runtime session delete helper on the control-plane client.
sdk-python/examples/agent_runtime_usage.py Updates example usage to demonstrate stopping clients.
sdk-python/tests/test_agent_runtime.py Adds tests for stop() behavior and context-manager cleanup.

Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment thread sdk-python/agentcube/clients/control_plane.py
Comment thread sdk-python/examples/agent_runtime_usage.py Outdated
Comment thread sdk-python/tests/test_agent_runtime.py Outdated
Comment thread sdk-python/tests/test_agent_runtime.py Outdated
Comment thread sdk-python/tests/test_agent_runtime.py Outdated
Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment thread sdk-python/tests/test_agent_runtime.py Outdated
@vivek41-glitch
vivek41-glitch force-pushed the fix/agent-runtime-delete-session branch from c3574b0 to eebdda2 Compare July 7, 2026 19:00
@vivek41-glitch vivek41-glitch reopened this Jul 7, 2026
@vivek41-glitch

Copy link
Copy Markdown
Contributor Author

/remove-label do-not-merge/contains-merge-commits

@volcano-sh-bot

Copy link
Copy Markdown
Contributor

@vivek41-glitch: The label(s) /remove-label do-not-merge/contains-merge-commits cannot be applied. These labels are supported: tide/merge-method-merge, tide/merge-method-rebase, tide/merge-method-squash, area/ads, ara/workload, area/bpf. Is this label configured under labels -> additional_labels or labels -> restricted_labels in plugin.yaml?

Details

In response to this:

/remove-label do-not-merge/contains-merge-commits

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

Copilot AI review requested due to automatic review settings July 7, 2026 19:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.

Comments suppressed due to low confidence (1)

sdk-python/agentcube/agent_runtime.py:106

  • AgentRuntimeDataPlaneClient.invoke() currently only accepts (session_id, payload, timeout). Adding path to AgentRuntimeClient.invoke() and passing it through will raise TypeError: invoke() got an unexpected keyword argument 'path'.
    def invoke(self, payload: Dict[str, Any], timeout: Optional[float] = None, path: str = "") -> Any:
        if not self.session_id:
            raise ValueError("AgentRuntime session_id is not initialized")

        resp = self.dp_client.invoke(

Comment on lines +63 to +76
# Resolve auth: auth param > auth_token > k8s SA token file
if auth:
self._auth = auth
elif auth_token:
from agentcube.auth import TokenAuth
self._auth = TokenAuth(auth_token)
else:
token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
token = read_token_from_file(token_path)
if token:
from agentcube.auth import TokenAuth
self._auth = TokenAuth(token)
else:
self._auth = None
Comment on lines +94 to +99
def _apply_auth(self, request_kwargs: dict) -> None:
"""Add Authorization header from auth provider if available."""
if not self._auth:
return
headers = request_kwargs.setdefault("headers", {})
headers["Authorization"] = f"Bearer {self._auth.get_token()}"
Comment on lines 19 to 21
from requests.exceptions import JSONDecodeError
from agentcube.auth import AuthProvider
from agentcube.clients.agent_runtime_data_plane import AgentRuntimeDataPlaneClient
Comment on lines +35 to 38
workload_manager_url: Optional[str] = None,
auth_token: Optional[str] = None,
auth: Optional[AuthProvider] = None,
):
Comment thread sdk-python/agentcube/agent_runtime.py Outdated
Comment on lines +47 to +50
self._auth = auth
if not self._auth and auth_token:
from agentcube.auth import TokenAuth
self._auth = TokenAuth(auth_token)
Comment on lines 78 to 85
self.dp_client = AgentRuntimeDataPlaneClient(
router_url=self.router_url,
namespace=self.namespace,
agent_name=self.agent_name,
timeout=self.timeout,
connect_timeout=self.connect_timeout,
auth=self._auth,
)
Comment on lines +123 to +135
def stop(self) -> None:
"""Close local connection and delete server-side session if owned."""
try:
self.close()
except Exception as e:
self.logger.warning(f"Error closing local connection: {e}")

if self._owned_session and self.session_id and self._control_plane:
try:
self._control_plane.delete_agent_runtime_session(self.session_id)
self.logger.info(f"Deleted AgentRuntime session: {self.session_id}")
except Exception as e:
self.logger.warning(f"Error deleting AgentRuntime session: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python AgentRuntimeClient can create sessions but cannot delete them

3 participants