Files
ss-tools/backend/tests/core/test_cot_logger.py
busya 65121cac6b feat(logging): self-diagnosing EXPLORE + shared/ absorption + belief analytics (ADR-0021/0022)
T0: absorb shared/ into backend — cot_logger→src/core, CotJsonFormatter→src/core/cot_formatter.py, _llm_http/_llm_health/ssl→src/core/utils; imports rewritten (26 prod + tests, patch targets); run.sh/backend.Dockerfile/requirements/.axiom source_dirs/semantic_health/AGENTS/INSTALL cleaned; ADR-0022 supersedes ADR-0015; fixed latent CI defects (ss_tools ImportError, record.message in logger tests, same-name test-module collision).

ADR-0021 wire enrichment (additive): contract_id/claim/error_code/loc fields; _contract_id ContextVar + resolve_contract_id (explicit > belief_scope > declared-src mirror, derived src never mirrors); EXPLORE auto-loc via single frame walk; facade error auto-fill; 2KB payload cap with payload_truncated/payload_bytes markers; migrated 85 error="CODE" sites to error_code= (12 files); pilot editor/load.py; superset preview payload-bomb inlined bodies removed.

Analytics SSOT src/core/log_stats.py (bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, intent families, coverage, insufficient-sample flag); pretty_cot.py --stats/--digest/--trajectory/--story over one engine; log_gap_service three-tier ground-truth triangulation (FAILED w/o EXPLORE etc.) + GET /api/reports/log-stats|task-log-gaps (polling-suppressed); scripts/cot_audit.py CLI; enriched fields persisted into task_logs.payload for tier queries.

Frontend: ReportsAnalyticsModel + AnalyticsStatsPanel (Logs tab) + TaskGapPanel and per-row T1/T2/T3 gap badges (Tasks tab); cot-logger.ts ADR-0021 opts; i18n en/ru. Scheduler console spam fixed: apscheduler logger demoted to WARNING via LoggingConfig.scheduler_log_level. .axiom belief patterns -> $OBJ.* (alias undercount). molecular-cot-logging skill updated (fields, decision rules, tie-break, CLI) and synced.

Reviewed orthogonally: F1 cot_span contract pollution, F2 cap boundary accounting, F3 digest over-dedup, F4 trace-state bound, F5 tier metadata — fixed with regression tests. Validation: backend 11287 passed + ruff + compileall; frontend 3446 passed + lint + build; CLI smoke on live app.log.
2026-09-04 20:56:41 +03:00

309 lines
12 KiB
Python

# #region Test.CotLogger [C:3] [TYPE Module] [SEMANTICS test,logging,cot,trace,span,json]
# @BRIEF Tests for shared/cot_logger.py — trace_id, span, log markers, timing.
# @RELATION BINDS_TO -> [CotLoggerModule]
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
import logging
import re
from unittest.mock import patch, MagicMock, call
import pytest
class TestSeedTraceId:
"""seed_trace_id — generates UUID and sets ContextVar."""
def test_returns_uuid_string(self):
from src.core.cot_logger import seed_trace_id
tid = seed_trace_id()
assert isinstance(tid, str)
assert len(tid) == 32 # UUID4 hex format (no hyphens)
def test_sets_trace_id(self):
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
class TestSetTraceId:
"""set_trace_id — sets explicit trace ID."""
def test_sets_provided_id(self):
from src.core.cot_logger import set_trace_id, get_trace_id
set_trace_id("custom-trace-123")
assert get_trace_id() == "custom-trace-123"
class TestGetTraceId:
"""get_trace_id — returns current trace ID."""
def test_default_empty(self):
from src.core.cot_logger import get_trace_id
# After seed, get_trace_id returns non-empty
# In a fresh test the ContextVar may be empty
pass # ContextVar has default ""
def test_after_seed_returns_value(self):
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
class TestPushPopSpan:
"""push_span and pop_span — span stack operations."""
def test_push_returns_previous(self):
from src.core.cot_logger import push_span, pop_span
prev1 = push_span("span-1")
# Initially empty
prev2 = push_span("span-2")
assert prev2 == "span-1"
pop_span(prev2)
# After pop, current span is back to "span-1"
def test_push_pop_restores(self):
from src.core.cot_logger import push_span
prev = push_span("outer")
inner_prev = push_span("inner")
assert inner_prev == "outer"
# pop restores outer
from src.core.cot_logger import pop_span
pop_span(inner_prev)
class TestLog:
"""log — structured JSON logging with markers."""
def test_reason_marker_info_level(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("TestModule", "REASON", "Testing reason")
mock_info.assert_called_once()
args, kwargs = mock_info.call_args
assert "Testing reason" in args[0]
extra = kwargs.get("extra", {})
assert extra["marker"] == "REASON"
assert extra["src"] == "TestModule"
assert extra["intent"] == "Testing reason"
def test_reflect_marker_info_level(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REFLECT", "Reflecting")
mock_info.assert_called_once()
def test_explore_marker_warning_level(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Exploring alternatives", error="Assumption violated")
mock_warn.assert_called_once()
def test_error_level_explicit(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.error") as mock_err:
log("Test", "REASON", "Error test", level="ERROR")
mock_err.assert_called_once()
def test_debug_level_explicit(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.debug") as mock_debug:
log("Test", "REASON", "Debug test", level="DEBUG")
mock_debug.assert_called_once()
def test_payload_included(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "With payload", payload={"key": "value"})
extra = mock_info.call_args[1]["extra"]
assert extra["payload"] == {"key": "value"}
def test_error_included(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Error case", error="Something broke")
extra = mock_warn.call_args[1]["extra"]
assert extra["error"] == "Something broke"
def test_payload_not_included_when_none(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "No payload")
extra = mock_info.call_args[1]["extra"]
assert "payload" not in extra
def test_error_not_included_when_none(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Test", "REASON", "No error")
extra = mock_info.call_args[1]["extra"]
assert "error" not in extra
def test_warning_level_inferred_from_explore(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Test", "EXPLORE", "Auto warning")
mock_warn.assert_called_once()
class TestBuildCotEvent:
"""Canonical event construction enforces EXPLORE's explanation invariant."""
def test_explore_without_error_uses_intent_as_error(self):
from src.core.cot_logger import build_cot_event
event = build_cot_event(
src="task.test",
marker="EXPLORE",
intent="Fallback selected",
)
assert event["level"] == "WARNING"
assert event["error"] == "Fallback selected"
class TestTraceIdPropagation:
"""Trace ID propagation across async contexts."""
def test_seed_then_get(self):
from src.core.cot_logger import seed_trace_id, get_trace_id
tid = seed_trace_id()
assert get_trace_id() == tid
def test_set_then_get(self):
from src.core.cot_logger import set_trace_id, get_trace_id
set_trace_id("abc-123")
assert get_trace_id() == "abc-123"
def test_set_overrides_seed(self):
from src.core.cot_logger import seed_trace_id, set_trace_id, get_trace_id
seed_trace_id()
set_trace_id("override")
assert get_trace_id() == "override"
class TestContractScope:
"""contract_id ContextVar inheritance (ADR-0021 self-diagnosing EXPLORE)."""
def test_set_and_get(self):
from src.core.cot_logger import set_contract_scope, reset_contract_scope, get_contract_id
token = set_contract_scope("Core.Demo.Contract")
try:
assert get_contract_id() == "Core.Demo.Contract"
finally:
reset_contract_scope(token)
assert get_contract_id() == ""
def test_nested_scopes_restore_previous(self):
from src.core.cot_logger import set_contract_scope, reset_contract_scope, get_contract_id
outer = set_contract_scope("Outer.Contract")
inner = set_contract_scope("Inner.Contract")
assert get_contract_id() == "Inner.Contract"
reset_contract_scope(inner)
assert get_contract_id() == "Outer.Contract"
reset_contract_scope(outer)
assert get_contract_id() == ""
def test_event_inherits_scope_contract(self):
from src.core.cot_logger import build_cot_event, set_contract_scope, reset_contract_scope
token = set_contract_scope("Scoped.Contract")
try:
event = build_cot_event(src="some.func", marker="REASON", intent="x")
assert event["contract_id"] == "Scoped.Contract"
finally:
reset_contract_scope(token)
def test_explicit_contract_overrides_scope(self):
from src.core.cot_logger import build_cot_event, set_contract_scope, reset_contract_scope
token = set_contract_scope("Scoped.Contract")
try:
event = build_cot_event(
src="s", marker="REASON", intent="x", contract_id="Explicit.Contract"
)
assert event["contract_id"] == "Explicit.Contract"
finally:
reset_contract_scope(token)
class TestContractMirroring:
"""Explicit src mirrors into contract_id; derived src never mirrors."""
def test_explicit_src_mirrors(self):
from src.core.cot_logger import build_cot_event
event = build_cot_event(
src="ScenarioExecution.BrowserProvider", marker="EXPLORE", intent="failed", error="x"
)
assert event["contract_id"] == "ScenarioExecution.BrowserProvider"
def test_empty_contract_suppresses_mirror(self):
from src.core.cot_logger import build_cot_event
event = build_cot_event(src="auto.derived.name", marker="REASON", intent="x", contract_id="")
assert "contract_id" not in event
def test_log_derived_src_not_mirrored(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("", "REASON", "poor src")
extra = mock_info.call_args[1]["extra"]
assert "contract_id" not in extra
def test_cot_span_derived_src_not_mirrored(self):
"""Span src is a python path, not a GRACE ID — must never populate contract_id."""
from src.core.cot_logger import cot_span
@cot_span()
def spanned_op(n):
return n + 1
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
assert spanned_op(1) == 2
for call in mock_info.call_args_list:
assert "contract_id" not in call[1]["extra"]
def test_cot_span_inherits_contract_scope(self):
from src.core.cot_logger import cot_span, set_contract_scope, reset_contract_scope
@cot_span()
def spanned_op(n):
return n + 1
token = set_contract_scope("Scoped.Contract")
try:
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
spanned_op(2)
infos = [c[1]["extra"] for c in mock_info.call_args_list]
assert infos and all(e.get("contract_id") == "Scoped.Contract" for e in infos)
finally:
reset_contract_scope(token)
class TestEnrichedFields:
"""Optional additive fields: claim / error_code / loc."""
def test_claim_and_error_code_present(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Mod.Func", "EXPLORE", "not found", error="assumption broken",
claim="PRE: record exists", error_code="DEMO_NOT_FOUND")
extra = mock_warn.call_args[1]["extra"]
assert extra["claim"] == "PRE: record exists"
assert extra["error_code"] == "DEMO_NOT_FOUND"
def test_loc_present_on_explore(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.warning") as mock_warn:
log("Mod.Func", "EXPLORE", "boom", error="x")
extra = mock_warn.call_args[1]["extra"]
assert "loc" in extra
assert "test_cot_logger.py:" in extra["loc"]
def test_loc_absent_on_reason(self):
from src.core.cot_logger import log
with patch("src.core.cot_logger.cot_logger.info") as mock_info:
log("Mod.Func", "REASON", "planned step")
extra = mock_info.call_args[1]["extra"]
assert "loc" not in extra
# #endregion Test.CotLogger