dp-zp-agent/tools/answers/route_trace.py
jp170na a232f7be40 spájanie wiki a CRZP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:23:43 +01:00

119 lines
5.3 KiB
Python

"""The path of one answer in the timing log: which rewrite, plan, branch and source produced it.
Every traced function that returns something adds a short label to the answer's timing record
("unified.work_title", "crzp.find=12", "plan=meeting/ambiguous_work"), so an evaluation can tell
where a question failed. Labels only, never user text; the answer itself is unchanged.
ANSWER_ROUTE_TRACE=0 turns it off.
"""
from __future__ import annotations
import functools
import os
import sys
from tools.answers import timing
LIMIT = 80
# module -> (function, label); a missing function is skipped
TRACED = {
"tools.answers.combined": [
("ellipsis", "rewrite.ellipsis"), ("again", "rewrite.again"), ("named_back", "rewrite.named_back"),
("with_subject", "rewrite.with_subject"), ("_subject_retry", "rewrite.subject_retry"),
("_back_to_person", "rewrite.back_to_person"), ("_newest_of", "combined.newest_of"),
("_future_defences", "combined.future_defences"), ("_schools_answer", "combined.schools"),
("_next_page", "combined.next_page"), ("_crzp_work_answer", "combined.crzp_work"),
("_reference", "combined.reference"), ("_answer_choice", "combined.choice"), ("_return_to", "combined.return_to"),
("_ask_choice", "combined.ask_choice"), ("_with_people", "combined.with_people"),
("crzp_plan", "crzp.plan"), ("_crzp_part", "crzp.part"), ("_unified", "unified"),
],
"tools.answers.presentation.unified": [
("person_works", "unified.person_works"), ("work_title", "unified.work_title"),
("work_count", "unified.work_count"), ("roles", "unified.roles"), ("who", "unified.who"),
("works_list", "unified.works_list"), ("comparison", "unified.comparison"), ("methods", "unified.methods"),
("meeting", "unified.meeting"), ("start_year", "unified.start_year"), ("same_supervisor", "unified.same_supervisor"),
("supervisor_overview", "unified.supervisor_overview"), ("intern_overview", "unified.intern_overview"),
("tag_answer", "unified.tag_answer"), ("top_topics", "unified.top_topics"), ("started_answer", "unified.started"),
("supervisor_in", "unified.supervisor_in"),
],
"tools.crzp.answering.answer": [("find", "crzp.find"), ("topical", "crzp.topical"), ("answer", "crzp.answer")],
"tools.answers.planning.question_plan": [("build_question_plan", "plan")],
"tools.answers.planning.question_catalog": [("classify", "catalog"), ("route_for", "catalog.route")],
"tools.answers.answer_delivery": [("deliver_answer", "wiki.deliver")],
"app.routes": [("deliver_answer", "wiki.deliver")],
}
def mark(label: str) -> None:
record = timing._current.get()
if record is None:
return
with record["_lock"]:
trail = record.setdefault("route", [])
if len(trail) < LIMIT:
trail.append(label[:90])
def summary(result) -> str:
"""A short machine description of a returned value."""
if isinstance(result, str):
return ""
if isinstance(result, dict):
parts = [str(result.get(k)) for k in ("status", "reason") if result.get(k)]
return "/".join(parts)
if isinstance(result, (list, tuple)):
if isinstance(result, tuple) and result and isinstance(result[0], str):
mode = result[0]
query = result[1] if len(result) > 1 else None
intent = getattr(query, "intent", None)
roles = ",".join(p.role for p in getattr(query, "people", []) or [])
topics = len(getattr(query, "topics", []) or [])
return f"{mode}/{intent}/people:{roles or '-'}/topics:{topics}"
if isinstance(result, tuple):
return "/".join(str(len(x)) if isinstance(x, list) else type(x).__name__ for x in result[:2])
return str(len(result))
spec = getattr(result, "spec", None)
if spec is not None or hasattr(result, "reason"):
return "/".join(str(v) for v in (getattr(spec, "intent", None), getattr(result, "reason", None),
getattr(result, "origin", None)) if v)
kind = getattr(result, "type", None)
return str(kind) if kind else type(result).__name__
def _wrap(module, name: str, label: str) -> None:
original = getattr(module, name, None)
if original is None or not callable(original) or getattr(original, "_route_traced", False):
return
@functools.wraps(original)
def traced(*args, **kwargs):
try:
result = original(*args, **kwargs)
except Exception as error:
mark(f"{label}!{type(error).__name__}")
raise
if result is not None and result is not False and result != "":
detail = summary(result)
mark(label + (f"={detail}" if detail else ""))
return result
traced._route_traced = True
setattr(module, name, traced)
def install() -> None:
if os.getenv("ANSWER_ROUTE_TRACE", "1") == "0":
return
import importlib
for module_name, functions in TRACED.items():
module = sys.modules.get(module_name)
if module is None and module_name != "app.routes":
try:
module = importlib.import_module(module_name)
except Exception:
continue
if module is None:
continue
for name, label in functions:
_wrap(module, name, label)