Files
ss-tools/backend/src/services/reports/log_gap_service.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

117 lines
4.6 KiB
Python

# #region Services.Reports.LogGapService [C:3] [TYPE Module] [SEMANTICS reports,triangulation,gap,belief,task-logs]
# @defgroup Services Module group.
# @BRIEF Ground-truth triangulation of invisible task failures (ADR-0021 / decision D2):
# a task that ended FAILED is a FACT; absence of any EXPLORE marker in its task_logs
# is a FACT — together they prove the falsification channel stayed silent. No parser,
# no AST guessing: semantics come from outcomes, not from code shape.
# @LAYER Domain
# @RELATION DEPENDS_ON -> [Models.Task.TaskRecord]
# @RELATION DEPENDS_ON -> [Models.Task.TaskLogRecord]
# @INVARIANT Read-only: never writes task_records/task_logs.
# @DATA_CONTRACT (Session, since_days, limit) -> {tier1_invisible_failures,
# tier2_unbound_explore, tier3_silent_fallbacks, generated_at, since_days}
# @RATIONALE Tiers: T1 = FAILED and no EXPLORE at all (worst: invisible failure);
# T2 = FAILED with EXPLORE but none carries error_code/contract_id in payload
# (visible but not bound to a contract — measures ADR-0021 adoption);
# T3 = SUCCESS with EXPLORE (systematic fallbacks under a green task — early
# degradation signal, advisory).
import json
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import exists, select
from sqlalchemy.orm import Session
from ...models.task import TaskLogRecord, TaskRecord
_ENRICH_KEYS = ("contract_id", "claim", "error_code", "loc")
# #region Services.Reports.LogGapService.ComputeGaps [C:3] [TYPE Function] [SEMANTICS gap,query,tiers]
# @ingroup Services
# @BRIEF Compute the three-tier invisible-failure report for recent tasks.
# @PRE db is an active Session; since_days >= 1.
# @POST Returns JSON-serializable report dict; lists capped by `limit`.
# @SIDE_EFFECT None (read-only queries).
def compute_task_log_gaps(db: Session, since_days: int = 7, limit: int = 200) -> dict[str, Any]:
since_days = max(1, int(since_days or 7))
limit = max(1, min(int(limit or 200), 1000))
cutoff = datetime.now(UTC) - timedelta(days=since_days)
explore_exists = exists(
select(TaskLogRecord.id).where(
TaskLogRecord.task_id == TaskRecord.id,
TaskLogRecord.marker == "EXPLORE",
)
)
recent = TaskRecord.created_at >= cutoff
tier1_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "FAILED", recent, ~explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
tier3_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "SUCCESS", recent, explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
failed_bound_rows = db.execute(
select(TaskRecord)
.where(TaskRecord.status == "FAILED", recent, explore_exists)
.order_by(TaskRecord.created_at.desc())
.limit(limit)
).scalars().all()
tier2_rows = []
for task in failed_bound_rows:
payloads = db.execute(
select(TaskLogRecord.payload).where(
TaskLogRecord.task_id == task.id,
TaskLogRecord.marker == "EXPLORE",
)
).all()
bound = False
for (payload,) in payloads:
data = payload if isinstance(payload, dict) else _as_dict(payload)
if data and any(data.get(key) for key in ("contract_id", "error_code")):
bound = True
break
if not bound:
tier2_rows.append(task)
def _task_view(task: TaskRecord) -> dict[str, Any]:
return {
"task_id": task.id,
"type": task.type,
"status": task.status,
"error": (task.error or "")[:300] or None,
"created_at": task.created_at.isoformat() if task.created_at else None,
"finished_at": task.finished_at.isoformat() if task.finished_at else None,
}
return {
"since_days": since_days,
"generated_at": datetime.now(UTC).isoformat(timespec="seconds"),
"tier1_invisible_failures": [_task_view(t) for t in tier1_rows],
"tier2_unbound_explore": [_task_view(t) for t in tier2_rows],
"tier3_silent_fallbacks": [_task_view(t) for t in tier3_rows],
}
def _as_dict(payload: Any) -> dict[str, Any] | None:
if isinstance(payload, (str, bytes)):
try:
parsed = json.loads(payload)
return parsed if isinstance(parsed, dict) else None
except (TypeError, ValueError):
return None
return None
# #endregion Services.Reports.LogGapService.ComputeGaps
# #endregion Services.Reports.LogGapService