Repository navigation
Observability and structured logging layer - #14
Merged
Merged
Conversation
…metry layer - Add core logging module (context, formatters, filters, config) under src/goalcoach/infrastructure/logging - Implement task-local ContextVar propagation for trace_id, request_id, learner_id, session_id, concept_id - Add SecretScrubbingFilter for regex-based secret/key redaction and ContextFilter for log record injection - Add JSONFormatter (NDJSON) and DevelopmentFormatter (colorized console) - Add ObservabilityMiddleware for ASGI request correlation, latency tracking, and X-Request-ID/X-Response-Time-Ms headers - Attach SQLAlchemy cursor duration hooks for slow query tracking (>25ms) and error capture in database.py - Instrument DeterministicOrchestrator and ProgressService for continuous Bayesian DSR transition telemetry - Instrument GraderComponent for fast-path vs LLM rubric timing and PydanticAI model gateway failover telemetry - Add quiet file-based logging for terminal harness with --verbose option - Add comprehensive test suite in tests/unit/test_observability.py (12 passed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR adds an extensive observation and logging functionality to measure the performance of the backend system.
These are the options you can log using this functionality:
1. Ubiquitous Request & Context Metadata
Every single log record automatically includes task-local identifiers propagated via context.py:
• request_id: Extracted from X-Request-ID or generated as a UUID.
• trace_id: Extracted from W3C traceparent headers or generated for tracing across distributed calls.
• learner_id: The ID of the student currently active in the session.
• session_id: The active study session ID.
• concept_id: The curriculum concept currently being taught or reviewed.
2. The 6 Specific Telemetry Streams
A. HTTP Gateway & Access Logs
• Source: observability.py
• What it logs:
• http.method & http.route (e.g. POST /api/v1/events).
• http.status_code (e.g. 200, 422, 500).
• duration_ms: Total HTTP roundtrip duration in milliseconds.
• client_ip: Inbound client IP.
• Headers Injected: Injects X-Request-ID and X-Response-Time-Ms into outbound HTTP responses.
B. Deterministic Orchestrator & State Flow
• Source: orchestrator.py
• What it logs:
• event_received: Event type (GOAL_CREATED, SESSION_STARTED, ANSWER_SUBMITTED, HELP_REQUESTED, REPLAN_REQUESTED)
and inbound payload keys.
• action_resolved: Chosen client instruction (teach, plan, complete, set_goal), whether an adaptive replan occurred
(replanned), and the deterministic decision latency in microseconds (routing_latency_us).
C. Spaced Repetition Math & Bayesian DSR State Manifold
• Source: progress_service.py
• What it logs:
• progress_state_mutated: Captures the exact mathematical state diff for the concept:
• prior_mastery vs new_mastery (e.g. 0.40 → 0.65).
• retention_r: Calculated memory recall probability (R(Δt, S)).
• stability_s: Memory half-life / spaced interval in days (S).
• quality: Rubric composite quality score (0.0 → 1.0).
• next_review_days: Scheduled next review date.
• remediation_threshold_exceeded (WARN): Logged when unresolved learner mistakes reach ≥ 2, automatically setting
needs_replanning = True
D. Grader Component Telemetry
• Source: grader_component.py
• What it logs:
• Fast-Path Branch (grader_fast_path_resolved): Logged when exact matches or multiple-choice questions bypass the
LLM. Records execution latency (< 0.05 ms).
• LLM Rubric Branch (grader_llm_evaluated): Logged when open-ended evaluations complete:
• 3-axis scores: grammatical_correctness, semantic_precision, pragmatic_appropriateness.
• passed_gates: Boolean pass/fail based on rubric thresholds.
• detected_errors: Specific taxonomy tags (e.g. ERR_QUESTION_MA, ERR_WORD_ORDER).
• confidence: Model confidence score.
E. Dual SQLite Engine & Slow-Query Profiling
• Source: database.py
• What it logs:
• db.name: Identifies the database target (content for Database #1 vs learner_state for Database #2).
• statement_type: SQL command prefix (SELECT, INSERT, UPDATE, PRAGMA).
• duration_ms: Execution time down to the microsecond.
• db_slow_query (WARN): Automatically alerts when any database operation exceeds 25 ms (catching SQLite WAL lock
contention or unindexed queries).
• db_query_failed (ERROR): Database errors with sanitized query statements.
F. PydanticAI Reasoning Agents & Model Gateway
• Sources: pydantic_ai_models.py & content_service.py
• What it logs:
• llm_inference_started: Target provider (openrouter), model name, and prompt character count.
• AgentTelemetryEvent: Token counts (input_tokens, output_tokens), completion latency, and validation status.
• llm_fallback_engaged (WARN): Failover alerts when hosted OpenRouter requests fail (e.g. HTTP 429, timeout) and the system switches to local quantized Ollama (gemma-4).
• content_query: Tool lookups for concepts, prerequisites, and exercises.
3. Built-In Security Filter
• Source: filters.py
• What it scrubs: Automatically intercepts log records and redacts any API tokens (e.g. sk-..., Bearer ...), passwords,
or credentials into REDACTED before writing to console or disk.