Skip to content

Commit c2321d2

Browse files
fix(examples): keep Redis connection details out of diagnostics (#5205)
* fix(examples): keep Redis connection details out of diagnostics * fix(examples): preserve Redis demo failure exit status
1 parent 5813d84 commit c2321d2

4 files changed

Lines changed: 202 additions & 23 deletions

File tree

‎examples/memory/redis_session_example.py‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ async def main():
2626

2727
print("=== Redis Session Example ===")
2828
redis_url = os.environ.get("REDIS_URL", DEFAULT_REDIS_URL)
29-
print(f"This example uses Redis at {redis_url}")
29+
print("This example uses Redis session memory.")
3030
print("Set REDIS_URL to use a different Redis server.")
3131
print()
3232

@@ -145,23 +145,22 @@ async def main():
145145
# Close the main session
146146
await session.close()
147147

148-
except Exception as e:
149-
print(f"Error: {e}")
150-
print(f"Make sure Redis is running and reachable at {redis_url}")
148+
except Exception:
149+
# Connection exceptions can contain credentials from REDIS_URL.
150+
print("Redis session example failed. Check the Redis configuration and connection.")
151151

152152

153153
async def demonstrate_advanced_features():
154154
"""Demonstrate advanced Redis session features."""
155155
print("\n=== Advanced Features Demo ===")
156156

157-
# Custom key prefix for multi-tenancy
158-
tenant_session = RedisSession.from_url(
159-
"user_123",
160-
url=os.environ.get("REDIS_URL", DEFAULT_REDIS_URL),
161-
key_prefix="tenant_abc:sessions", # Custom prefix for isolation
162-
)
163-
164157
try:
158+
# Custom key prefix for multi-tenancy
159+
tenant_session = RedisSession.from_url(
160+
"user_123",
161+
url=os.environ.get("REDIS_URL", DEFAULT_REDIS_URL),
162+
key_prefix="tenant_abc:sessions", # Custom prefix for isolation
163+
)
165164
if await tenant_session.ping():
166165
print("Custom key prefix demo:")
167166
await Runner.run(
@@ -172,8 +171,13 @@ async def demonstrate_advanced_features():
172171
print("Session with custom key prefix created successfully")
173172

174173
await tenant_session.close()
175-
except Exception as e:
176-
print(f"Advanced features error: {e}")
174+
return
175+
except Exception:
176+
# Do not include backend exception text in captured example output.
177+
print("Advanced Redis features failed. Check the Redis configuration and connection.")
178+
179+
# Exit outside the handler so the original exception is not retained as context.
180+
raise SystemExit(1)
177181

178182

179183
if __name__ == "__main__":

‎examples/run_examples.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -236,11 +236,15 @@ def choose_loopback_port() -> int:
236236

237237

238238
def redis_url_host_port(url: str) -> tuple[str, int] | None:
239-
parsed = urlparse(url)
240-
if parsed.scheme not in {"redis", "rediss"}:
239+
try:
240+
parsed = urlparse(url)
241+
if parsed.scheme not in {"redis", "rediss"}:
242+
return None
243+
host = parsed.hostname or "localhost"
244+
port = parsed.port or 6379
245+
except ValueError:
246+
# Leave invalid configuration to the example without logging URL parser errors.
241247
return None
242-
host = parsed.hostname or "localhost"
243-
port = parsed.port or 6379
244248
return host, port
245249

246250

@@ -356,11 +360,11 @@ def prepare_redis_for_example(
356360
redis_url = configured_url or DEFAULT_REDIS_URL
357361
if redis_url_is_local(redis_url) and redis_ping_url(redis_url):
358362
env["REDIS_URL"] = redis_url
359-
return None, [f"Using existing Redis server at {redis_url}."]
363+
return None, ["Using existing local Redis server."]
360364

361365
if configured_url:
362366
env["REDIS_URL"] = redis_url
363-
return None, [f"REDIS_URL is set but not reachable before example start: {redis_url}."]
367+
return None, ["Using configured REDIS_URL; local preflight did not confirm availability."]
364368

365369
server = start_temporary_redis_server()
366370
if server is None:
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
from __future__ import annotations
2+
3+
from types import SimpleNamespace
4+
from unittest.mock import AsyncMock, Mock
5+
from urllib.parse import unquote
6+
7+
import pytest
8+
9+
from examples.memory import redis_session_example as example
10+
11+
URL = "rediss://synthetic-user:synthetic%2Fpassword@localhost:6380/2?password=query-secret"
12+
13+
14+
@pytest.fixture
15+
def redis_demo(monkeypatch):
16+
monkeypatch.setenv("REDIS_URL", URL)
17+
session = SimpleNamespace(
18+
ping=AsyncMock(return_value=True),
19+
clear_session=AsyncMock(),
20+
get_items=AsyncMock(return_value=[]),
21+
close=AsyncMock(),
22+
)
23+
factory = Mock(return_value=session)
24+
monkeypatch.setattr(example.RedisSession, "from_url", factory)
25+
monkeypatch.setattr(
26+
example.Runner, "run", AsyncMock(return_value=SimpleNamespace(final_output="Demo response"))
27+
)
28+
return session, factory
29+
30+
31+
def assert_safe_output(capsys, caplog):
32+
captured = capsys.readouterr()
33+
output = captured.out + captured.err + caplog.text
34+
for value in (URL, unquote(URL), "synthetic-user", "synthetic%2Fpassword", "query-secret"):
35+
assert value not in output
36+
return output
37+
38+
39+
@pytest.mark.asyncio
40+
async def test_demos_preserve_connection_url_without_printing_it(redis_demo, capsys, caplog):
41+
session, factory = redis_demo
42+
await example.main()
43+
await example.demonstrate_advanced_features()
44+
45+
output = assert_safe_output(capsys, caplog)
46+
assert "Conversation Complete" in output
47+
assert "custom key prefix created successfully" in output
48+
assert factory.call_count == 4
49+
assert all(call.kwargs["url"] == URL for call in factory.call_args_list)
50+
assert factory.call_args_list[2].kwargs["ttl"] == 3600
51+
assert factory.call_args_list[3].kwargs["key_prefix"] == "tenant_abc:sessions"
52+
assert session.close.await_count == 4
53+
54+
55+
@pytest.mark.asyncio
56+
@pytest.mark.parametrize("demo", [example.main, example.demonstrate_advanced_features])
57+
@pytest.mark.parametrize("failure", ["construct", "operation", "unreachable"])
58+
async def test_demo_failures_do_not_render_connection_details(
59+
redis_demo, capsys, caplog, demo, failure
60+
):
61+
session, factory = redis_demo
62+
# Include decoded data and a chained backend error, not just the complete URL.
63+
error = ValueError(f"Could not connect: {unquote(URL)}")
64+
error.__cause__ = RuntimeError("query-secret")
65+
if failure == "construct":
66+
factory.side_effect = error
67+
elif failure == "operation":
68+
session.ping.side_effect = error
69+
else:
70+
session.ping.return_value = False
71+
72+
if demo is example.demonstrate_advanced_features and failure != "unreachable":
73+
with pytest.raises(SystemExit) as exit_info:
74+
await demo()
75+
assert exit_info.value.code == 1
76+
assert exit_info.value.__context__ is None
77+
assert exit_info.value.__cause__ is None
78+
else:
79+
await demo()
80+
81+
output = assert_safe_output(capsys, caplog)
82+
factory.assert_called_once()
83+
assert factory.call_args.kwargs["url"] == URL
84+
if failure != "unreachable":
85+
assert "Check the Redis configuration and connection." in output
86+
assert "Traceback" not in output
87+
88+
89+
@pytest.mark.asyncio
90+
async def test_invalid_query_configuration_is_reported_safely(monkeypatch, capsys, caplog):
91+
# The real client parser includes invalid option values in its exception message.
92+
monkeypatch.setenv("REDIS_URL", "redis://localhost/0?socket_timeout=query-secret")
93+
await example.main()
94+
with pytest.raises(SystemExit) as exit_info:
95+
await example.demonstrate_advanced_features()
96+
assert exit_info.value.code == 1
97+
assert exit_info.value.__context__ is None
98+
output = assert_safe_output(capsys, caplog)
99+
assert output.count("Check the Redis configuration and connection.") == 2

‎tests/test_run_examples_script.py‎

Lines changed: 76 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def test_prepare_redis_for_example_uses_existing_local_redis(monkeypatch) -> Non
110110

111111
assert redis_server is None
112112
assert env["REDIS_URL"] == run_examples.DEFAULT_REDIS_URL
113-
assert messages == [f"Using existing Redis server at {run_examples.DEFAULT_REDIS_URL}."]
113+
assert messages == ["Using existing local Redis server."]
114114

115115

116116
def test_prepare_redis_for_example_starts_managed_redis(monkeypatch) -> None:
@@ -152,9 +152,7 @@ def test_prepare_redis_for_example_respects_configured_url(monkeypatch) -> None:
152152

153153
assert redis_server is None
154154
assert env["REDIS_URL"] == "redis://localhost:6380/2"
155-
assert messages == [
156-
"REDIS_URL is set but not reachable before example start: redis://localhost:6380/2."
157-
]
155+
assert messages == ["Using configured REDIS_URL; local preflight did not confirm availability."]
158156

159157

160158
def test_prerequisite_skip_reasons_skip_dapr_without_sidecar(monkeypatch) -> None:
@@ -199,3 +197,77 @@ def test_prerequisite_skip_reasons_allow_non_dapr_example(monkeypatch) -> None:
199197
)
200198

201199
assert reasons == set()
200+
201+
202+
@pytest.mark.parametrize("buffered", [True, False])
203+
@pytest.mark.parametrize(
204+
"url,reachable",
205+
[
206+
("redis://synthetic-user:synthetic-pass@localhost/0?password=query-secret", True),
207+
("rediss://synthetic-user:[email protected]/0?password=query-secret", False),
208+
("redis://localhost:query-secret/0", False),
209+
],
210+
)
211+
def test_redis_runner_output_and_logs_omit_configured_connection_details(
212+
monkeypatch, tmp_path, capsys, url, reachable, buffered
213+
):
214+
monkeypatch.setenv("REDIS_URL", url)
215+
monkeypatch.setenv("EXAMPLES_BUFFER_OUTPUT", "1")
216+
monkeypatch.setattr(run_examples, "build_command_path", lambda: "")
217+
monkeypatch.setattr(run_examples, "redis_ping_url", lambda url: reachable)
218+
monkeypatch.setattr(
219+
run_examples,
220+
"start_temporary_redis_server",
221+
lambda: pytest.fail("Configured Redis must not be replaced"),
222+
)
223+
# Run the actual example entry point in a child. Fail construction after verifying
224+
# that the complete configured URL survived the runner's environment forwarding.
225+
child = """
226+
import os
227+
import runpy
228+
from unittest.mock import patch
229+
from agents.extensions.memory import RedisSession
230+
231+
def fail_construction(*args, **kwargs):
232+
assert kwargs['url'] == os.environ['REDIS_URL']
233+
raise ValueError('Connection failed: ' + kwargs['url'])
234+
235+
with patch.object(RedisSession, 'from_url', side_effect=fail_construction):
236+
runpy.run_module('examples.memory.redis_session_example', run_name='__main__')
237+
"""
238+
monkeypatch.setattr(
239+
run_examples.ExampleScript,
240+
"command",
241+
property(lambda self: [sys.executable, "-c", child]),
242+
)
243+
monkeypatch.setattr(
244+
sys,
245+
"argv",
246+
[
247+
"run_examples.py",
248+
"--include-external",
249+
"--logs-dir",
250+
str(tmp_path / "logs"),
251+
"--main-log",
252+
str(tmp_path / "main.log"),
253+
"--artifacts-dir",
254+
str(tmp_path / "artifacts"),
255+
*([] if buffered else ["--no-buffer-output"]),
256+
],
257+
)
258+
script = run_examples.ExampleScript(run_examples.ROOT_DIR / run_examples.REDIS_SESSION_EXAMPLE)
259+
assert run_examples.run_examples([script], run_examples.parse_args()) == 1
260+
261+
captured = capsys.readouterr()
262+
logs = "".join(path.read_text() for path in tmp_path.rglob("*.log"))
263+
main_log = (tmp_path / "main.log").read_text()
264+
assert "FAILED examples/memory/redis_session_example.py exit=1" in main_log
265+
assert "PASSED" not in main_log
266+
for output in (captured.out + captured.err, logs):
267+
assert "[runner]" in output
268+
assert "Check the Redis configuration and connection." in output
269+
assert url not in output
270+
assert "synthetic-user" not in output
271+
assert "synthetic-pass" not in output
272+
assert "query-secret" not in output
273+
assert "Traceback" not in output

0 commit comments

Comments
 (0)