diff --git a/service/src/ai_document_plugin_service/ai/assignment/llm.py b/service/src/ai_document_plugin_service/ai/assignment/llm.py index 1d9b3771..c7d916c4 100644 --- a/service/src/ai_document_plugin_service/ai/assignment/llm.py +++ b/service/src/ai_document_plugin_service/ai/assignment/llm.py @@ -71,6 +71,7 @@ async def match_questions_to_sections( messages = self._assignment_messages(sections_xml, question_chunk_xml) response = await self.client.completion( + stage='assignment', stats=stats, messages=messages, temperature=self.config.assignment.temperature, diff --git a/service/src/ai_document_plugin_service/ai/common/execution_logging.py b/service/src/ai_document_plugin_service/ai/common/execution_logging.py deleted file mode 100644 index 8b6105df..00000000 --- a/service/src/ai_document_plugin_service/ai/common/execution_logging.py +++ /dev/null @@ -1,68 +0,0 @@ -import logging -from contextlib import contextmanager -from contextvars import ContextVar -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any -from uuid import UUID - -if TYPE_CHECKING: - from collections.abc import Iterator - -_run_log_context: ContextVar['RunLogContext | None'] = ContextVar('run_log_context', default=None) -_LLM_EVENT_LOGGER = logging.getLogger('ai_document_plugin_service.execution.llm') -_PIPELINE_EVENT_LOGGER = logging.getLogger('ai_document_plugin_service.execution.pipeline') - - -@dataclass(frozen=True) -class RunLogContext: - run_id: UUID - questionnaire_uuid: UUID | None = None - template_uuid: UUID | None = None - template_title: str | None = None - knowledge_model_uuid: UUID | None = None - user_uuid: UUID | None = None - tenant_uuid: UUID | None = None - - -@contextmanager -def run_log_context(context: RunLogContext) -> 'Iterator[None]': - token = _run_log_context.set(context) - try: - yield - finally: - _run_log_context.reset(token) - - -def get_run_log_context() -> RunLogContext | None: - return _run_log_context.get() - - -def log_llm_event(record: dict[str, Any]) -> None: - _emit_event(_LLM_EVENT_LOGGER, record) - - -def log_timing_event(event: str, **fields: Any) -> None: # ruff: ignore[any-type] - _emit_event(_PIPELINE_EVENT_LOGGER, {'event': event, **fields}) - - -def _with_context(record: dict[str, Any]) -> dict[str, Any]: - payload: dict[str, Any] = { - **record, - } - context = get_run_log_context() - if context is None: - return payload - - payload.update({field: value for field, value in context.__dict__.items() if value is not None}) - return payload - - -def _emit_event(logger: logging.Logger, record: dict[str, Any]) -> None: - payload = _with_context(record) - logger.log(_event_log_level(payload), 'Execution event', extra=payload) - - -def _event_log_level(record: dict[str, Any]) -> int: - if record.get('status') in {'error', 'failed'} or record.get('state') == 'failed' or 'error_type' in record: - return logging.ERROR - return logging.INFO diff --git a/service/src/ai_document_plugin_service/ai/common/llm_client.py b/service/src/ai_document_plugin_service/ai/common/llm_client.py index 678f6746..81aa492f 100644 --- a/service/src/ai_document_plugin_service/ai/common/llm_client.py +++ b/service/src/ai_document_plugin_service/ai/common/llm_client.py @@ -2,13 +2,12 @@ import logging import time import uuid -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from openai import APIError, AsyncOpenAI from openai.types.chat import ChatCompletion from ai_document_plugin_service.ai.common.dynamic_semaphore import DynamicSemaphore -from ai_document_plugin_service.ai.common.execution_logging import log_llm_event from ai_document_plugin_service.ai.common.llm_error import LLMError, llm_error_from_exception if TYPE_CHECKING: @@ -16,6 +15,8 @@ logger = logging.getLogger(__name__) +type LLMStage = Literal['assignment', 'generation', 'polishing'] + MAX_RETRIES = 3 RETRY_DELAY_S = 2.0 @@ -137,6 +138,7 @@ def get_model_name(self) -> str: async def completion( self, *args: Any, # ruff: ignore[any-type] + stage: LLMStage, stats: 'AssignmentStats | None' = None, **kwargs: Any, # ruff: ignore[any-type] ) -> ChatCompletion: @@ -147,17 +149,18 @@ async def completion( """ for _ in range(MAX_RETRIES - 1): try: - return await self._completion(*args, stats=stats, **kwargs) + return await self._completion(*args, stage=stage, stats=stats, **kwargs) except LLMError as error: if not error.retryable: raise logger.warning('Error calling LLM, retrying: %s', error.__cause__ or error) await asyncio.sleep(RETRY_DELAY_S) - return await self._completion(*args, stats=stats, **kwargs) + return await self._completion(*args, stage=stage, stats=stats, **kwargs) async def _completion( self, *args: Any, # ruff: ignore[any-type] + stage: LLMStage, stats: 'AssignmentStats | None' = None, **kwargs: Any, # ruff: ignore[any-type] ) -> ChatCompletion: @@ -188,9 +191,11 @@ async def _completion( raise RuntimeError(msg) req_id = uuid.uuid4().hex[:8] wait_start = time.perf_counter() - log_llm_event( - { + logger.debug( + 'Waiting for LLM semaphore', + extra={ 'state': 'waiting_for_semaphore', + 'stage': stage, 'req_id': req_id, 'tenant_uuid': str(self.tenant_uuid), 'model': self.model, @@ -201,9 +206,11 @@ async def _completion( ) async with self.semaphore: wait_s = time.perf_counter() - wait_start - log_llm_event( - { + logger.debug( + 'Waiting for LLM response', + extra={ 'state': 'waiting_for_llm_response', + 'stage': stage, 'req_id': req_id, 'tenant_uuid': str(self.tenant_uuid), 'model': self.model, @@ -222,6 +229,7 @@ async def _completion( _add_timing(stats, wait_s, duration_s) self._log_llm_completion( req_id=req_id, + stage=stage, status='error', wait_s=wait_s, duration_s=duration_s, @@ -236,6 +244,7 @@ async def _completion( _add_timing(stats, wait_s, duration_s) self._log_llm_completion( req_id=req_id, + stage=stage, status='success', wait_s=wait_s, duration_s=duration_s, @@ -256,6 +265,7 @@ def _log_llm_completion( self, *, req_id: str, + stage: LLMStage, status: str, wait_s: float, duration_s: float, @@ -265,6 +275,7 @@ def _log_llm_completion( ) -> None: payload = { 'state': 'completed' if status == 'success' else 'failed', + 'stage': stage, 'status': status, 'req_id': req_id, 'tenant_uuid': str(self.tenant_uuid), @@ -292,7 +303,10 @@ def _log_llm_completion( 'error_message': str(error), }, ) - log_llm_event(payload) + if error is None: + logger.info('LLM call completed', extra=payload) + else: + logger.error('LLM call failed', extra=payload) def _count_messages(messages: object) -> int | None: diff --git a/service/src/ai_document_plugin_service/ai/common/logging_utils.py b/service/src/ai_document_plugin_service/ai/common/logging_utils.py index 5d52ece5..0e0faf75 100644 --- a/service/src/ai_document_plugin_service/ai/common/logging_utils.py +++ b/service/src/ai_document_plugin_service/ai/common/logging_utils.py @@ -1,5 +1,9 @@ import logging +from dataclasses import asdict +from typing import override +from uuid import UUID +from ai_document_plugin_service.ai.common.run_context import get_run_log_context from ai_document_plugin_service.ai.common.trace_context import get_trace_uuid LOG_FORMAT = '%(asctime)s | %(levelname)8s | %(name)s: [T:%(traceId)s] %(message)s' @@ -7,12 +11,30 @@ _STANDARD_LOG_RECORD_FIELDS = frozenset(logging.makeLogRecord({}).__dict__) | {'asctime', 'message', 'traceId'} +class RunContextFilter(logging.Filter): + """Adds the identifiers of the pipeline run in progress to every log record under ``context``. + + A ``context`` a log call passes explicitly through ``extra`` is kept as it is. + """ + + @override + def filter(self, record: logging.LogRecord) -> bool: + context = get_run_log_context() + if context is not None and not hasattr(record, 'context'): + record.context = {field: str(value) for field, value in asdict(context).items() if value is not None} + return True + + class ExtraFormatter(logging.Formatter): """Appends application fields supplied through ``extra`` to text logs.""" def format(self, record: logging.LogRecord) -> str: formatted = super().format(record) - extra = {key: value for key, value in record.__dict__.items() if key not in _STANDARD_LOG_RECORD_FIELDS} + extra = { + key: str(value) if isinstance(value, UUID) else value + for key, value in record.__dict__.items() + if key not in _STANDARD_LOG_RECORD_FIELDS + } return f'{formatted} | extra={extra!r}' if extra else formatted @@ -46,6 +68,8 @@ def _configure_root_stdout_logging(level: int) -> None: for handler in root_logger.handlers: handler.setLevel(level) handler.setFormatter(ExtraFormatter(LOG_FORMAT)) + if not any(isinstance(log_filter, RunContextFilter) for log_filter in handler.filters): + handler.addFilter(RunContextFilter()) def _configure_library_log_levels() -> None: diff --git a/service/src/ai_document_plugin_service/ai/common/run_context.py b/service/src/ai_document_plugin_service/ai/common/run_context.py new file mode 100644 index 00000000..062de93f --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/common/run_context.py @@ -0,0 +1,33 @@ +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from uuid import UUID + +_RUN_CONTEXT: ContextVar['RunLogContext | None'] = ContextVar('run_log_context', default=None) + + +@dataclass(frozen=True) +class RunLogContext: + """Identifiers of the pipeline run in progress; the logging filter adds them to every log record.""" + + run_id: UUID + questionnaire_uuid: UUID | None = None + template_uuid: UUID | None = None + template_title: str | None = None + knowledge_model_uuid: UUID | None = None + user_uuid: UUID | None = None + tenant_uuid: UUID | None = None + + +def get_run_log_context() -> RunLogContext | None: + return _RUN_CONTEXT.get() + + +@contextmanager +def run_log_context(context: RunLogContext) -> Iterator[None]: + token = _RUN_CONTEXT.set(context) + try: + yield + finally: + _RUN_CONTEXT.reset(token) diff --git a/service/src/ai_document_plugin_service/ai/generation/llm.py b/service/src/ai_document_plugin_service/ai/generation/llm.py index 96ff48df..152b80a0 100644 --- a/service/src/ai_document_plugin_service/ai/generation/llm.py +++ b/service/src/ai_document_plugin_service/ai/generation/llm.py @@ -64,6 +64,7 @@ async def section_from_qa( _ = previously_generated messages = self._section_from_qa_messages(prompt) response = await self.client.completion( + stage='generation', stats=stats, messages=messages, temperature=self.config.dmp_generation.temperature, diff --git a/service/src/ai_document_plugin_service/ai/persistence/assignment_saver_component.py b/service/src/ai_document_plugin_service/ai/persistence/assignment_saver_component.py index 401d8ce7..14c0f6a2 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/assignment_saver_component.py +++ b/service/src/ai_document_plugin_service/ai/persistence/assignment_saver_component.py @@ -17,20 +17,14 @@ SerializedSectionAssignment, ) -# Haystack inspects component input annotations at runtime. -from ai_document_plugin_service.ai.common.types import AssignmentStats - if TYPE_CHECKING: from ai_document_plugin_service.ai.persistence.database import Database logger = logging.getLogger(__name__) -StatsJson = dict[str, dict[str, int | float]] - class AssignmentSaverComponentResult(TypedDict): assignments: list[SerializedSectionAssignment] - stats: AssignmentStats | None @component @@ -38,7 +32,7 @@ class AssignmentSaverComponent: def __init__(self, saver: Saver) -> None: self.saver = saver - @component.output_types(assignments=list[SerializedSectionAssignment], stats=AssignmentStats | None) + @component.output_types(assignments=list[SerializedSectionAssignment]) async def run_async( self, knowledge_model_uuid: UUID, @@ -47,11 +41,10 @@ async def run_async( template_uuid: UUID, tenant_uuid: UUID, assignments: list[SectionAssignment], - stats: AssignmentStats | None = None, *, has_new_assignments: bool = True, ) -> AssignmentSaverComponentResult: - """Save assignments to storage, optionally including token usage stats. + """Save assignments to storage. Skips the write when ``has_new_assignments`` is false: everything came from storage unchanged. """ @@ -61,7 +54,7 @@ async def run_async( 'Reusing stored assignments without saving', extra={'knowledge_model_uuid': knowledge_model_uuid, 'template_uuid': str(template_uuid)}, ) - return {'assignments': serializable, 'stats': stats} + return {'assignments': serializable} logger.info( 'Persisting generated assignments', @@ -71,29 +64,23 @@ async def run_async( 'template_uuid': str(template_uuid), 'tenant_uuid': str(tenant_uuid), 'assignment_count': len(assignments), - 'has_stats': stats is not None, }, ) question_paths = collect_leaf_question_paths(assignments) - stats_payload = _serialize_stats(stats) await self.saver.save( knowledge_model_uuid=knowledge_model_uuid, knowledge_model_name=knowledge_model_name, knowledge_model_version=knowledge_model_version, question_paths=question_paths, - stats=stats_payload, template_uuid=template_uuid, tenant_uuid=tenant_uuid, created_at=datetime.now(tz=UTC), ) - return { - 'assignments': serializable, - 'stats': stats, - } + return {'assignments': serializable} - @component.output_types(assignments=list[SerializedSectionAssignment], stats=AssignmentStats | None) + @component.output_types(assignments=list[SerializedSectionAssignment]) def run( self, knowledge_model_uuid: UUID, @@ -102,7 +89,6 @@ def run( template_uuid: UUID, tenant_uuid: UUID, assignments: list[SectionAssignment], - stats: AssignmentStats | None = None, *, has_new_assignments: bool = True, ) -> AssignmentSaverComponentResult: @@ -121,7 +107,6 @@ async def save( knowledge_model_name: str, knowledge_model_version: str, question_paths: SectionQuestionPaths, - stats: StatsJson | None, template_uuid: UUID, tenant_uuid: UUID, created_at: datetime | None = None, @@ -139,7 +124,6 @@ async def save( knowledge_model_name: str, knowledge_model_version: str, question_paths: SectionQuestionPaths, - stats: StatsJson | None, template_uuid: UUID, tenant_uuid: UUID, created_at: datetime | None = None, @@ -157,7 +141,6 @@ async def save( knowledge_model_name=knowledge_model_name, knowledge_model_version=knowledge_model_version, question_paths=question_paths, - stats=stats, created_at=created_at, template_uuid=template_uuid, ) @@ -169,18 +152,3 @@ async def save( 'tenant_uuid': str(tenant_uuid), }, ) - - -def _serialize_stats(stats: AssignmentStats | None) -> StatsJson | None: - if stats is None: - return None - return { - 'stats': { - 'total_calls': stats.total_calls, - 'total_input_tokens': stats.total_input_tokens, - 'total_output_tokens': stats.total_output_tokens, - 'total_llm_wait_ms': stats.total_llm_wait_ms, - 'total_llm_response_ms': stats.total_llm_response_ms, - 'total_duration_ms': stats.total_duration_ms, - }, - } diff --git a/service/src/ai_document_plugin_service/ai/persistence/database.py b/service/src/ai_document_plugin_service/ai/persistence/database.py index ac97f258..af9ba38c 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/database.py +++ b/service/src/ai_document_plugin_service/ai/persistence/database.py @@ -1,6 +1,6 @@ import logging from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Mapping, Sequence +from collections.abc import AsyncIterator, Sequence from contextlib import AbstractAsyncContextManager, asynccontextmanager from contextvars import ContextVar from dataclasses import dataclass @@ -25,7 +25,6 @@ logger = logging.getLogger(__name__) -JsonValue = Mapping[str, Any] | Sequence[Any] # Holds the connection of the transaction currently active on this asyncio task, if any. # Set by PostgresDB.transaction(); read by every operation so it can join that transaction @@ -94,16 +93,6 @@ class GenerationUpdate(TypedDict, total=False): class GenerationStats(TypedDict, total=False): dmp_pre_polished: str | None dmp_polished: str | None - assignment_llm_calls: int | None - assignment_input_tokens: int | None - assignment_output_tokens: int | None - generation_llm_calls: int | None - generation_input_tokens: int | None - generation_output_tokens: int | None - polishing_llm_calls: int | None - polishing_input_tokens: int | None - polishing_output_tokens: int | None - elapsed_seconds: float | None @dataclass(frozen=True) @@ -207,7 +196,6 @@ async def save_assignments( knowledge_model_version: str, question_paths: SectionQuestionPaths, template_uuid: UUID, - stats: JsonValue | None = None, created_at: datetime | None = None, ) -> None: """Persist the question paths of each leaf section by section id, replacing the stored sections.""" @@ -428,7 +416,6 @@ async def save_assignments( knowledge_model_version: str, question_paths: SectionQuestionPaths, template_uuid: UUID, - stats: JsonValue | None = None, created_at: datetime | None = None, ) -> None: await self._ensure_schema() @@ -439,7 +426,6 @@ async def save_assignments( knowledge_model_version=knowledge_model_version, created_at=created_at_value, updated_at=created_at_value, - stats=stats, template_uuid=template_uuid, ) upsert_statement = statement.on_conflict_do_update( diff --git a/service/src/ai_document_plugin_service/ai/persistence/schema.py b/service/src/ai_document_plugin_service/ai/persistence/schema.py index 688436d6..7e70c12e 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/schema.py +++ b/service/src/ai_document_plugin_service/ai/persistence/schema.py @@ -4,7 +4,6 @@ JSON, Column, DateTime, - Float, ForeignKey, ForeignKeyConstraint, Index, @@ -80,7 +79,6 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: server_default=func.now(), ), Column('updated_at', DateTime(timezone=True), nullable=False, server_default=func.now()), - Column('stats', JSON, nullable=True), Column('template_uuid', UUID(as_uuid=True), ForeignKey('template.uuid'), primary_key=True, nullable=False), ) @@ -140,7 +138,7 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: ), ) - # Analysis-only data, one row per generation (created together with it). + # Analysis-only documents, one row per generation (created together with it). generation_stats_table = Table( 'generation_stats', metadata, @@ -150,18 +148,6 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: Column('dmp_pre_polished', Text, nullable=True), # at start same as generation.result_markdown, but not editable. Older rows don't have the original value saved Column('dmp_polished', Text, nullable=True), - # LLM usage per pipeline step. NULL when the step did not run (assignment is skipped - # when cached assignments are reused) or the run has no stats (failed or old runs). - Column('assignment_llm_calls', Integer, nullable=True), - Column('assignment_input_tokens', Integer, nullable=True), - Column('assignment_output_tokens', Integer, nullable=True), - Column('generation_llm_calls', Integer, nullable=True), - Column('generation_input_tokens', Integer, nullable=True), - Column('generation_output_tokens', Integer, nullable=True), - Column('polishing_llm_calls', Integer, nullable=True), - Column('polishing_input_tokens', Integer, nullable=True), - Column('polishing_output_tokens', Integer, nullable=True), - Column('elapsed_seconds', Float, nullable=True), Column( 'created_at', DateTime(timezone=True), diff --git a/service/src/ai_document_plugin_service/ai/polishing/llm.py b/service/src/ai_document_plugin_service/ai/polishing/llm.py index 3a42e4ba..1cc8e29d 100644 --- a/service/src/ai_document_plugin_service/ai/polishing/llm.py +++ b/service/src/ai_document_plugin_service/ai/polishing/llm.py @@ -49,6 +49,7 @@ async def polish_dmp( ] response = await self.client.completion( + stage='polishing', stats=stats, messages=messages, temperature=self.config.dmp_polishing.temperature, diff --git a/service/src/ai_document_plugin_service/ai/run_pipeline.py b/service/src/ai_document_plugin_service/ai/run_pipeline.py index 4f824a2b..0e10177f 100644 --- a/service/src/ai_document_plugin_service/ai/run_pipeline.py +++ b/service/src/ai_document_plugin_service/ai/run_pipeline.py @@ -20,7 +20,6 @@ get_component_markdown, get_component_stats, ) -from ai_document_plugin_service.ai.common.execution_logging import log_timing_event from ai_document_plugin_service.ai.common.pipeline_runner import run_haystack_pipeline from ai_document_plugin_service.ai.generation.cover_page_component import CoverPageComponent from ai_document_plugin_service.ai.generation.dmp_generator_component import DmpGeneratorComponent @@ -113,7 +112,6 @@ def build_pipeline( pipeline.connect('parser_component.data', 'assignment_component.data') # assignment_component -> assignment_saver_component pipeline.connect('assignment_component.assignments', 'assignment_saver_component.assignments') - pipeline.connect('assignment_component.stats', 'assignment_saver_component.stats') pipeline.connect('assignment_component.has_new_assignments', 'assignment_saver_component.has_new_assignments') # assignment_saver_component -> dmp_generator_component pipeline.connect('assignment_saver_component.assignments', 'dmp_generator_component.assignments') @@ -147,9 +145,9 @@ async def run_pipeline( except Exception: logger.exception('Failed to load questionnaire detail', extra={'questionnaire_uuid': str(questionnaire_uuid)}) raise - log_timing_event( - 'questionnaire_detail_loaded', - duration_ms=round((time.perf_counter() - questionnaire_fetch_started) * 1000, 3), + logger.info( + 'Questionnaire detail loaded', + extra={'duration_ms': round((time.perf_counter() - questionnaire_fetch_started) * 1000, 3)}, ) replies = km_data['replies'] km = km_data['knowledgeModel'] @@ -198,6 +196,7 @@ async def run_pipeline( }, }, include_outputs_from={ + 'assignment_component', 'assignment_saver_component', 'dmp_generator_component', 'dmp_polisher_component', @@ -210,9 +209,9 @@ async def run_pipeline( extra={'questionnaire_uuid': str(questionnaire_uuid), 'template_uuid': str(template_uuid)}, ) raise - log_timing_event( - 'pipeline_components_finished', - duration_ms=round((time.perf_counter() - pipeline_started) * 1000, 3), + logger.info( + 'Pipeline components finished', + extra={'duration_ms': round((time.perf_counter() - pipeline_started) * 1000, 3)}, ) total_time = time.perf_counter() - pipeline_total_started @@ -230,32 +229,21 @@ async def run_pipeline( logger.error(msg, extra={'template_uuid': str(template_uuid)}) raise RuntimeError(msg) - assignment_stats = get_component_stats(result, 'assignment_saver_component') + assignment_stats = get_component_stats(result, 'assignment_component') generation_stats = get_component_stats(result, 'dmp_generator_component') polishing_stats = get_component_stats(result, 'dmp_polisher_component') pipeline_stats = collect_stats(result, total_time) - log_timing_event( - 'pipeline_summary', - generation_ms=generation_stats.total_duration_ms if generation_stats is not None else None, - polishing_ms=polishing_stats.total_duration_ms if polishing_stats is not None else None, - total_pipeline_ms=round(total_time * 1000, 3), - total_llm_wait_ms=round( - sum( - stats.total_llm_wait_ms - for stats in (assignment_stats, generation_stats, polishing_stats) - if stats is not None - ), - 3, - ), - total_llm_response_ms=round( - sum( - stats.total_llm_response_ms - for stats in (assignment_stats, generation_stats, polishing_stats) - if stats is not None - ), - 3, - ), + step_stats = [stats for stats in (assignment_stats, generation_stats, polishing_stats) if stats is not None] + logger.info( + 'Pipeline summary', + extra={ + 'generation_ms': generation_stats.total_duration_ms if generation_stats is not None else None, + 'polishing_ms': polishing_stats.total_duration_ms if polishing_stats is not None else None, + 'total_pipeline_ms': round(total_time * 1000, 3), + 'total_llm_wait_ms': round(sum(stats.total_llm_wait_ms for stats in step_stats), 3), + 'total_llm_response_ms': round(sum(stats.total_llm_response_ms for stats in step_stats), 3), + }, ) return PipelineOutput( knowledge_model_uuid=knowledge_model_uuid, @@ -267,7 +255,7 @@ async def run_pipeline( def collect_stats(result: Mapping[str, object], total_time: float) -> PipelineStats: """Collect per-step LLM usage. Pure, so it can never fail a finished run.""" - assignment_stats = get_component_stats(result, 'assignment_saver_component') + assignment_stats = get_component_stats(result, 'assignment_component') generation_stats = get_component_stats(result, 'dmp_generator_component') polishing_stats = get_component_stats(result, 'dmp_polisher_component') diff --git a/service/src/ai_document_plugin_service/migrations/versions/20261113_01_remove_persisted_stats.py b/service/src/ai_document_plugin_service/migrations/versions/20261113_01_remove_persisted_stats.py new file mode 100644 index 00000000..7bbee2bb --- /dev/null +++ b/service/src/ai_document_plugin_service/migrations/versions/20261113_01_remove_persisted_stats.py @@ -0,0 +1,29 @@ +"""Remove persisted run statistics. + +Lossy migration. Drops the LLM call counts, token counts and elapsed time from generation_stats (the table keeps +the pre-polished and polished documents) and drops assignment.stats. The statistics are emitted to the +application log instead. Existing values are discarded. +""" + +from alembic import context, op + +revision = '20261113_01' +down_revision = '20261023_01' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + schema = context.get_context().version_table_schema + op.drop_column('generation_stats', 'assignment_llm_calls', schema=schema) + op.drop_column('generation_stats', 'assignment_input_tokens', schema=schema) + op.drop_column('generation_stats', 'assignment_output_tokens', schema=schema) + op.drop_column('generation_stats', 'generation_llm_calls', schema=schema) + op.drop_column('generation_stats', 'generation_input_tokens', schema=schema) + op.drop_column('generation_stats', 'generation_output_tokens', schema=schema) + op.drop_column('generation_stats', 'polishing_llm_calls', schema=schema) + op.drop_column('generation_stats', 'polishing_input_tokens', schema=schema) + op.drop_column('generation_stats', 'polishing_output_tokens', schema=schema) + op.drop_column('generation_stats', 'elapsed_seconds', schema=schema) + + op.drop_column('assignment', 'stats', schema=schema) diff --git a/service/src/ai_document_plugin_service/service/pipeline_service.py b/service/src/ai_document_plugin_service/service/pipeline_service.py index 739e65c1..d9fdffc5 100644 --- a/service/src/ai_document_plugin_service/service/pipeline_service.py +++ b/service/src/ai_document_plugin_service/service/pipeline_service.py @@ -6,11 +6,9 @@ from zoneinfo import ZoneInfo from ai_document_plugin_service.ai.common.config import Config -from ai_document_plugin_service.ai.common.execution_logging import ( - log_timing_event, -) from ai_document_plugin_service.ai.common.llm_client import LLMClient from ai_document_plugin_service.ai.common.llm_error import LLMError +from ai_document_plugin_service.ai.common.run_context import RunLogContext, run_log_context from ai_document_plugin_service.ai.common.trace_context import get_trace_uuid from ai_document_plugin_service.ai.knowledgemodel.dsw_client import DSWClient from ai_document_plugin_service.ai.knowledgemodel.project_version import resolve_named_version @@ -106,24 +104,27 @@ def _succeeded_update(output: PipelineOutput) -> GenerationUpdate: } -def _succeeded_stats(output: PipelineOutput) -> GenerationStats: - """The stats a finished run writes. Per-step usage stays NULL for steps that did not run.""" +def _log_run_stats(output: PipelineOutput) -> None: + """Emit the run statistics to the log; they are no longer persisted. + + Per-step usage is None for steps that did not run (e.g. assignment when cached assignments are reused). + """ stats = output.stats - assignment, generation, polishing = stats.assignment, stats.generation, stats.polishing - return { - 'dmp_pre_polished': output.dmp_pre_polished, - 'dmp_polished': output.markdown, - 'assignment_llm_calls': assignment.llm_calls if assignment else None, - 'assignment_input_tokens': assignment.input_tokens if assignment else None, - 'assignment_output_tokens': assignment.output_tokens if assignment else None, - 'generation_llm_calls': generation.llm_calls if generation else None, - 'generation_input_tokens': generation.input_tokens if generation else None, - 'generation_output_tokens': generation.output_tokens if generation else None, - 'polishing_llm_calls': polishing.llm_calls if polishing else None, - 'polishing_input_tokens': polishing.input_tokens if polishing else None, - 'polishing_output_tokens': polishing.output_tokens if polishing else None, - 'elapsed_seconds': stats.elapsed_seconds, - } + fields: dict[str, object] = {'trace_id': get_trace_uuid(), 'elapsed_seconds': stats.elapsed_seconds} + for step_name, usage in ( + ('assignment', stats.assignment), + ('generation', stats.generation), + ('polishing', stats.polishing), + ): + fields[f'{step_name}_llm_calls'] = usage.llm_calls if usage else None + fields[f'{step_name}_input_tokens'] = usage.input_tokens if usage else None + fields[f'{step_name}_output_tokens'] = usage.output_tokens if usage else None + logger.info('Generation stats', extra=fields) + + +def _succeeded_stats(output: PipelineOutput) -> GenerationStats: + """The analysis-only documents a finished run writes.""" + return {'dmp_pre_polished': output.dmp_pre_polished, 'dmp_polished': output.markdown} class LlmClientTenantStore: @@ -453,19 +454,32 @@ def on_progress(message: str) -> None: ) task.add_done_callback(_log_background_update_failure) - output = await run_pipeline( + # Every execution event (LLM calls, timings, stats) logged inside carries the run identifiers. + log_context = RunLogContext( + run_id=run_id, questionnaire_uuid=questionnaire_uuid, template_uuid=template_uuid, - template_data=template.content, + template_title=template.title, + user_uuid=auth.user_uuid, tenant_uuid=auth.tenant_uuid, - pipeline=pipeline, - on_progress=on_progress, - dsw_client=DSWClient(auth.token, auth.api_url), - created_at=record.created_at.astimezone(ZoneInfo(time_zone)), - project_versions=project_versions, - include_cover_page=include_cover_page, ) - log_timing_event('pipeline_generation_finished', knowledge_model_uuid=str(output.knowledge_model_uuid)) + with run_log_context(log_context): + output = await run_pipeline( + questionnaire_uuid=questionnaire_uuid, + template_uuid=template_uuid, + template_data=template.content, + tenant_uuid=auth.tenant_uuid, + pipeline=pipeline, + on_progress=on_progress, + dsw_client=DSWClient(auth.token, auth.api_url), + created_at=record.created_at.astimezone(ZoneInfo(time_zone)), + project_versions=project_versions, + include_cover_page=include_cover_page, + ) + logger.info( + 'Pipeline generation finished', extra={'knowledge_model_uuid': str(output.knowledge_model_uuid)} + ) + _log_run_stats(output) # Everything the run produced is written in one transaction, so it lands atomically. async with self.database.transaction(): diff --git a/service/tests/persistence/test_assignment_sections.py b/service/tests/persistence/test_assignment_sections.py index 684337b8..31391d22 100644 --- a/service/tests/persistence/test_assignment_sections.py +++ b/service/tests/persistence/test_assignment_sections.py @@ -150,11 +150,11 @@ async def test_saver_skips_the_write_when_nothing_new_was_assigned(): generated = _generated_assignments() result = await AssignmentSaverComponent(saver).run_async( - uuid4(), 'Model', '1', uuid4(), uuid4(), generated, None, has_new_assignments=False + uuid4(), 'Model', '1', uuid4(), uuid4(), generated, has_new_assignments=False ) saver.save.assert_not_awaited() - assert result == {'assignments': [assignment.to_dict() for assignment in generated], 'stats': None} + assert result == {'assignments': [assignment.to_dict() for assignment in generated]} def _database_with_recorded_statements(monkeypatch) -> tuple[PostgresDB, SimpleNamespace]: