Files
LangBot/sdk/tests/test_plugin_logbuffer.py
RockChinQandmultica-agent ba6c4c1881 Unify service logs and correlate warnings across runtime actions (#3148)
* feat(logging): unify service logs and propagate query traces

Co-authored-by: multica-agent <github@multica.ai>

* test(logging): verify debug request traces and plugin warning delivery

Co-authored-by: multica-agent <github@multica.ai>

* fix(logging): route application records through the root handlers

Co-authored-by: multica-agent <github@multica.ai>

* fix(logging): distinguish service modules and expected worker shutdown

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: multica-agent <github@multica.ai>
2026-11-23 17:29:36 +08:00

173 lines
5.4 KiB
Python

from __future__ import annotations
import asyncio
import pytest
from langbot_plugin.runtime.plugin.logbuffer import MAX_LOG_LINE_BYTES, PluginLogBuffer
def test_parses_standard_log_line_level():
buf = PluginLogBuffer()
buf.add_line("[06-13 10:30:00.123] main.py (45) - [INFO] : hello world")
logs = buf.get_logs()
assert len(logs) == 1
assert logs[0]["level"] == "INFO"
assert logs[0]["text"].endswith("hello world")
def test_continuation_line_inherits_level():
buf = PluginLogBuffer()
buf.add_line("[06-13 10:30:00.123] main.py (45) - [ERROR] : boom")
buf.add_line("Traceback (most recent call last):")
buf.add_line(' File "x.py", line 1, in <module>')
logs = buf.get_logs()
assert len(logs) == 3
assert all(e["level"] == "ERROR" for e in logs)
def test_level_filter():
buf = PluginLogBuffer()
buf.add_line("[06-13 10:30:00.1] a.py (1) - [INFO] : i")
buf.add_line("[06-13 10:30:00.2] a.py (2) - [WARNING] : w")
buf.add_line("[06-13 10:30:00.3] a.py (3) - [ERROR] : e")
warn_and_up = buf.get_logs(level="WARNING")
assert [e["level"] for e in warn_and_up] == ["WARNING", "ERROR"]
def test_traceback_only_forwards_header(caplog):
buf = PluginLogBuffer(plugin="tester/demo")
lines = [
"[06-13 10:30:00.123] a.py (1) - [ERROR] : request failed",
"\tTraceback (most recent call last):",
*['\t File "a.py", line 1'] * 55,
"\tValueError: bad input",
]
for line in lines:
buf.add_line(line)
buf.add_line("[06-13 10:30:00.124] b.py (2) - [WARNING] : next warning")
entries = buf.get_logs()
assert [row["text"] for row in entries[:-1]] == lines
assert all(row["level"] == "ERROR" for row in entries[:-1])
assert caplog.messages == ["request failed", "next warning"]
def test_ring_buffer_cap():
buf = PluginLogBuffer(max_lines=5)
for i in range(20):
buf.add_line(f"[06-13 10:30:00.1] a.py (1) - [INFO] : line {i}")
logs = buf.get_logs(limit=100)
assert [entry["text"].rsplit(": ", 1)[-1] for entry in logs] == [
f"line {i}" for i in range(15, 20)
]
def test_rate_limited_forwarding_keeps_all_entries(caplog, monkeypatch):
from langbot_plugin.runtime.plugin import logbuffer
clock = [100.0]
monkeypatch.setattr(logbuffer.time, "monotonic", lambda: clock[0])
buf = PluginLogBuffer(plugin="tester/demo")
line = "[06-13 10:30:00.1] a.py (1) - [WARNING] : warning"
for _ in range(54):
buf.add_line(line)
clock[0] += 10
buf.add_line(line)
assert len(buf.get_logs()) == 55
assert caplog.messages == ["warning"] * 50 + ["suppressed 4 lines", "warning"]
def test_limit():
buf = PluginLogBuffer()
for i in range(50):
buf.add_line(f"[06-13 10:30:00.1] a.py (1) - [INFO] : line {i}")
logs = buf.get_logs(limit=10)
assert [entry["text"].rsplit(": ", 1)[-1] for entry in logs] == [
f"line {i}" for i in range(40, 50)
]
def test_empty_lines_skipped():
buf = PluginLogBuffer()
buf.add_line("")
buf.add_line(" \n")
assert buf.get_logs() == []
def test_add_entry_appends_synthetic_log():
buf = PluginLogBuffer()
buf.add_entry("ERROR", "deferred response failed")
logs = buf.get_logs()
assert logs == [
{
"ts": logs[0]["ts"],
"level": "ERROR",
"text": "deferred response failed",
}
]
def test_has_active_reader_reports_reader_state():
async def run():
reader = asyncio.StreamReader()
buf = PluginLogBuffer()
buf.start_reader(reader)
assert buf.has_active_reader is True
reader.feed_eof()
await asyncio.sleep(0)
return buf.has_active_reader
assert asyncio.run(run()) is False
def test_attach_stream_reads_to_eof():
async def run():
reader = asyncio.StreamReader()
reader.feed_data(b"[06-13 10:30:00.1] a.py (1) - [INFO] : streamed\n")
reader.feed_eof()
buf = PluginLogBuffer()
await buf.attach_stream(reader)
return buf.get_logs()
logs = asyncio.run(run())
assert len(logs) == 1
assert logs[0]["text"].endswith("streamed")
def test_attach_stream_drains_and_clips_line_without_newline():
async def run():
reader = asyncio.StreamReader(limit=1024)
reader.feed_data(b"x" * (MAX_LOG_LINE_BYTES * 3))
reader.feed_eof()
buf = PluginLogBuffer()
await buf.attach_stream(reader)
return buf.get_logs()
logs = asyncio.run(run())
assert len(logs) == 1
assert logs[0]["text"].startswith("x" * 100)
assert f"clipped at {MAX_LOG_LINE_BYTES} bytes" in logs[0]["text"]
assert len(logs[0]["text"]) < MAX_LOG_LINE_BYTES + 100
@pytest.mark.anyio
async def test_attach_stream_recovers_after_clipping_and_keeps_utf8():
reader = asyncio.StreamReader()
oversized = "é".encode() * MAX_LOG_LINE_BYTES
next_line = "[06-13 10:30:00.1] a.py (1) - [WARNING] : après"
reader.feed_data(oversized + b"\n" + next_line.encode() + b"\n")
reader.feed_eof()
buf = PluginLogBuffer()
await buf.attach_stream(reader)
clipped, following = buf.get_logs()
assert clipped["text"] == (
"é" * (MAX_LOG_LINE_BYTES // len("é".encode()))
+ f"... [log line clipped at {MAX_LOG_LINE_BYTES} bytes]"
)
assert (following["level"], following["text"]) == ("WARNING", next_line)
assert buf.get_logs(limit=1, level="WARNING") == [following]