Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(agfs): close socket on error path in _check_port_available (#97)

zemuf3dd18adc722
diff --git a/openviking/agfs_manager.py b/openviking/agfs_manager.py
index 66e96a746..316bab430 100644
--- a/openviking/agfs_manager.py
+++ b/openviking/agfs_manager.py
@@ -115,12 +115,13 @@ class AGFSManager:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(("localhost", self.port))
- sock.close()
except OSError as e:
raise RuntimeError(
f"AGFS port {self.port} is already in use, cannot start service. "
f"Please check if another AGFS process is running, or use a different port."
) from e
+ finally:
+ sock.close()
def _generate_config(self) -> Path:
"""Dynamically generate AGFS configuration file based on backend type."""
diff --git a/tests/README.md b/tests/README.md
index 4c678830b..d2fb0c9ed 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -157,6 +157,7 @@ Miscellaneous tests.
| `test_config_validation.py` | Configuration validation | Config schema validation, required fields, type checking |
| `test_debug_service.py` | Debug service | Debug endpoint tests, service diagnostics |
| `test_extract_zip.py` | Zip extraction security (Zip Slip) | Path traversal prevention (`../`), absolute path rejection, symlink entry filtering, backslash traversal, UNC path rejection, directory entry skipping, normal extraction |
+| `test_port_check.py` | AGFS port check socket leak fix | Available port no leak, occupied port raises RuntimeError, occupied port no ResourceWarning |
### engine/
diff --git a/tests/misc/test_port_check.py b/tests/misc/test_port_check.py
new file mode 100644
index 000000000..e6960dc1a
--- /dev/null
+++ b/tests/misc/test_port_check.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for AGFSManager._check_port_available() socket leak fix."""
+
+import gc
+import os
+import socket
+import sys
+import warnings
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from openviking.agfs_manager import AGFSManager
+
+
+def _make_manager(port: int) -> AGFSManager:
+ """Create a minimal AGFSManager with only the port attribute set."""
+ mgr = AGFSManager.__new__(AGFSManager)
+ mgr.port = port
+ return mgr
+
+
+class TestCheckPortAvailable:
+ """Test _check_port_available() properly closes sockets."""
+
+ def test_available_port_no_leak(self):
+ """Socket should be closed after successful port check."""
+ mgr = _make_manager(0) # port 0 = OS picks a free port
+ # Should not raise and should not leak
+ mgr._check_port_available()
+
+ def test_occupied_port_raises_runtime_error(self):
+ """Should raise RuntimeError when port is in use."""
+ blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ blocker.bind(("localhost", 0))
+ port = blocker.getsockname()[1]
+ blocker.listen(1)
+
+ mgr = _make_manager(port)
+ try:
+ with pytest.raises(RuntimeError, match="already in use"):
+ mgr._check_port_available()
+ finally:
+ blocker.close()
+
+ def test_occupied_port_no_resource_warning(self):
+ """Socket must be closed even when port is occupied (no ResourceWarning)."""
+ blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ blocker.bind(("localhost", 0))
+ port = blocker.getsockname()[1]
+ blocker.listen(1)
+
+ mgr = _make_manager(port)
+ try:
+ with pytest.raises(RuntimeError):
+ mgr._check_port_available()
+
+ # Force GC and check for ResourceWarning about unclosed socket
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always", ResourceWarning)
+ gc.collect()
+ resource_warnings = [x for x in w if issubclass(x.category, ResourceWarning)]
+ assert len(resource_warnings) == 0, f"Socket leaked: {resource_warnings}"
+ finally:
+ blocker.close()