fix: improve log reliability and correlation

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-21 17:36:24 +08:00
1 parent 8eea1cb7a4
commit 8a7ca8a654
21 files changed
+698 -91

No files matched your search

+59 -3
View File
@@ -121,6 +121,7 @@ def _runtime_message(content, blocks: list[RuntimeContextBlock]) -> dict:
def _make_full_loop(tmp_path: Path) -> AgentLoop:
provider = MagicMock()
provider.provider_name = "test"
provider.get_default_model.return_value = "test-model"
provider.generation = SimpleNamespace(max_tokens=4096)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title"))
@@ -2105,8 +2106,8 @@ async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Pat
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
logs: list[str] = []
sink_id = logger.add(logs.append, level="DEBUG", format="{message}")
records = []
sink_id = logger.add(lambda message: records.append(message.record), level="DEBUG")
try:
await loop._process_message(
InboundMessage(
@@ -2129,9 +2130,64 @@ async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Pat
"_persist_turn",
"_prepare_outbound",
]
logged = "".join(logs)
logged = "\n".join(record["message"] for record in records)
for stage in ("restore", "compact", "command", "build", "run", "save", "respond"):
assert f"Stage {stage} completed in" in logged
stage_records = [record for record in records if record["extra"].get("event") == "turn_stage"]
assert {record["extra"]["stage"] for record in stage_records} == {
"restore",
"compact",
"command",
"build",
"run",
"save",
"respond",
}
assert {record["extra"]["session_key"] for record in stage_records} == {"cli:test"}
assert len({record["extra"]["turn_id"] for record in stage_records}) == 1
completion = next(
record for record in records if record["extra"].get("event") == "turn_completed"
)
assert completion["extra"]["outcome"] == "stop"
assert completion["extra"]["duration_ms"] >= 0
assert completion["extra"]["provider"] == "test"
assert completion["extra"]["model"] == "test-model"
assert "response=[content hidden]" in completion["message"]
@pytest.mark.asyncio
async def test_failed_turn_stage_logs_exception_and_correlation(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
async def fail_restore(_ctx) -> None:
raise RuntimeError("restore failed")
loop._restore_turn = fail_restore # type: ignore[method-assign]
records = []
sink_id = logger.add(lambda message: records.append(message.record), level="ERROR")
try:
with pytest.raises(RuntimeError, match="restore failed"):
await loop._process_message(
InboundMessage(
channel="cli",
sender_id="user",
chat_id="failure",
content="hello",
)
)
finally:
logger.remove(sink_id)
failure = next(
record
for record in records
if record["extra"].get("event") == "turn_stage"
and record["extra"].get("outcome") == "error"
)
assert failure["exception"] is not None
assert failure["extra"]["stage"] == "restore"
assert failure["extra"]["session_key"] == "cli:failure"
assert failure["extra"]["turn_id"].startswith("cli:failure:")
@pytest.mark.asyncio
+31
View File
@@ -22,6 +22,13 @@ from nanobot.gateway import (
)
from nanobot.gateway.runtime import monitor_gateway_clients
from nanobot.process_runtime import process_is_running
from nanobot.utils.rotating_output import (
BACKGROUND_LOG_BACKUP_COUNT_ENV,
BACKGROUND_LOG_MAX_BYTES_ENV,
BACKGROUND_LOG_PATH_ENV,
DEFAULT_BACKUP_COUNT,
DEFAULT_MAX_BYTES,
)
class FakeProcess:
@@ -234,6 +241,10 @@ def test_start_background_writes_state_and_child_command(tmp_path, monkeypatch):
"/tmp/config.json",
]
assert calls[0]["kwargs"]["start_new_session"] is True
child_env = calls[0]["kwargs"]["env"]
assert child_env[BACKGROUND_LOG_PATH_ENV] == str(runtime.paths.log_path)
assert child_env[BACKGROUND_LOG_MAX_BYTES_ENV] == str(DEFAULT_MAX_BYTES)
assert child_env[BACKGROUND_LOG_BACKUP_COUNT_ENV] == str(DEFAULT_BACKUP_COUNT)
state = json.loads(runtime.paths.state_path.read_text(encoding="utf-8"))
assert state["pid"] == 12345
assert state["identity"] == 12345
@@ -242,6 +253,26 @@ def test_start_background_writes_state_and_child_command(tmp_path, monkeypatch):
assert result.status.launch_mode == "background"
def test_read_log_tail_spans_rotated_files(tmp_path: Path) -> None:
runtime = GatewayRuntime(paths=_paths(tmp_path))
runtime.paths.logs_dir.mkdir(parents=True)
runtime.paths.log_path.write_text("current-1\ncurrent-2\n", encoding="utf-8")
runtime.paths.log_path.with_name("gateway.log.1").write_text(
"backup-1\nbackup-2\n", encoding="utf-8"
)
runtime.paths.log_path.with_name("gateway.log.2").write_text(
"oldest\n", encoding="utf-8"
)
assert runtime.read_log_tail(tail=5) == [
"oldest",
"backup-1",
"backup-2",
"current-1",
"current-2",
]
def test_foreground_gateway_claim_is_discoverable_and_released(tmp_path, monkeypatch):
runtime = GatewayRuntime(
paths=_paths(tmp_path),
+1
View File
@@ -112,6 +112,7 @@ async def test_stream_true_returns_sse(aiohttp_client) -> None:
)
assert resp.status == 200
assert resp.content_type == "text/event-stream"
assert resp.headers["X-Request-ID"]
body = await resp.text()
lines = [line for line in body.split("\n") if line.startswith("data: ")]
+26
View File
@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
import pytest_asyncio
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentRunHookContext
from nanobot.api.server import (
@@ -126,10 +127,35 @@ async def test_api_key_protects_api_routes_but_not_health(aiohttp_client, mock_a
assert missing.status == 401
assert wrong.status == 401
assert ok.status == 200
assert health.headers["X-Request-ID"]
assert ok.headers["X-Request-ID"]
assert health.headers["X-Request-ID"] != ok.headers["X-Request-ID"]
assert (await missing.json())["error"]["message"].startswith("Missing Authorization")
assert (await wrong.json())["error"]["message"] == "Invalid API key"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_request_log_has_correlation_and_completion_fields(
aiohttp_client, mock_agent
) -> None:
records = []
sink = logger.add(lambda message: records.append(message.record), level="INFO")
try:
client = await aiohttp_client(create_app(mock_agent, api_key=API_KEY))
response = await client.get("/v1/models", headers=AUTH_HEADERS)
finally:
logger.remove(sink)
completion = next(
record for record in records if record["extra"].get("event") == "http_request"
)
assert completion["extra"]["request_id"] == response.headers["X-Request-ID"]
assert completion["extra"]["outcome"] == "success"
assert completion["extra"]["status_code"] == 200
assert completion["extra"]["duration_ms"] >= 0
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_routes_allow_requests_without_configured_api_key(aiohttp_client, mock_agent) -> None:
+40
View File
@@ -0,0 +1,40 @@
from io import StringIO
from loguru import logger
from nanobot.utils.log_config import add_console_log_sink
def test_console_log_sink_includes_context_and_escapes_message_newlines() -> None:
output = StringIO()
sink = add_console_log_sink(output, level="DEBUG")
try:
with logger.contextualize(
request_id="request-1",
turn_id="turn-1",
session_key="channel:chat",
):
logger.bind(channel="test").info("first line\nsecond line")
finally:
logger.remove(sink)
rendered = output.getvalue()
assert "request=request-1 turn=turn-1 session=channel:chat" in rendered
assert "first line\\nsecond line" in rendered
assert "first line\nsecond line" not in rendered
def test_console_log_sink_keeps_exception_traceback_multiline() -> None:
output = StringIO()
sink = add_console_log_sink(output)
try:
try:
raise RuntimeError("broken")
except RuntimeError:
logger.opt(exception=True).error("operation failed")
finally:
logger.remove(sink)
rendered = output.getvalue()
assert "operation failed" in rendered
assert "RuntimeError: broken" in rendered
+94
View File
@@ -0,0 +1,94 @@
import os
import subprocess
import sys
from pathlib import Path
from nanobot.utils.rotating_output import (
BACKGROUND_LOG_BACKUP_COUNT_ENV,
BACKGROUND_LOG_MAX_BYTES_ENV,
BACKGROUND_LOG_PATH_ENV,
RotatingTextOutput,
)
def test_rotating_output_enforces_size_and_backup_count(tmp_path: Path) -> None:
log_path = tmp_path / "gateway.log"
output = RotatingTextOutput(log_path, max_bytes=8, backup_count=2)
output.write("12345678")
output.write("new")
output.write("abcdefgh")
output.close()
assert log_path.read_text(encoding="utf-8") == "abcdefgh"
assert (tmp_path / "gateway.log.1").read_text(encoding="utf-8") == "new"
assert (tmp_path / "gateway.log.2").read_text(encoding="utf-8") == "12345678"
assert not (tmp_path / "gateway.log.3").exists()
def test_rotating_output_rotates_oversized_existing_file_before_append(tmp_path: Path) -> None:
log_path = tmp_path / "gateway.log"
log_path.write_text("existing output", encoding="utf-8")
output = RotatingTextOutput(log_path, max_bytes=8, backup_count=1)
output.write("fresh")
output.close()
assert log_path.read_text(encoding="utf-8") == "fresh"
assert (tmp_path / "gateway.log.1").read_text(encoding="utf-8") == "existing output"
def test_rotating_output_falls_back_when_active_log_cannot_be_renamed(
tmp_path: Path,
monkeypatch,
) -> None:
log_path = tmp_path / "gateway.log"
log_path.write_text("existing", encoding="utf-8")
original_replace = Path.replace
def fail_active_log_rename(path: Path, target: Path) -> Path:
if path == log_path:
raise PermissionError("file is being followed")
return original_replace(path, target)
monkeypatch.setattr(Path, "replace", fail_active_log_rename)
output = RotatingTextOutput(log_path, max_bytes=8, backup_count=1)
output.write("fresh")
output.close()
assert log_path.read_text(encoding="utf-8") == "fresh"
assert (tmp_path / "gateway.log.1").read_text(encoding="utf-8") == "existing"
def test_background_output_environment_redirects_stdout_and_stderr(tmp_path: Path) -> None:
log_path = tmp_path / "gateway.log"
env = os.environ.copy()
env[BACKGROUND_LOG_PATH_ENV] = str(log_path)
env[BACKGROUND_LOG_MAX_BYTES_ENV] = "1024"
env[BACKGROUND_LOG_BACKUP_COUNT_ENV] = "1"
result = subprocess.run(
[
sys.executable,
"-c",
(
"from nanobot.utils.rotating_output import "
"configure_background_output_from_env; "
"configure_background_output_from_env(); "
"print('stdout line'); "
"print('stderr line', file=__import__('sys').stderr)"
),
],
check=True,
capture_output=True,
env=env,
text=True,
)
assert result.stdout == ""
assert result.stderr == ""
assert log_path.read_text(encoding="utf-8").splitlines() == [
"stdout line",
"stderr line",
]