9.8 KiB
Quality And Audit Logging Plan
Goal
Build a minimal but complete logging and telemetry contour that lets us:
- reconstruct any user turn end to end;
- compare model, prompt, RAG, and tool variants;
- detect regressions and failure clusters;
- export clean datasets for evals and later fine-tuning;
- do this without leaking secrets into long-term storage.
This plan treats logging as a cross-cutting platform capability under core,
while each plugin keeps its domain-specific fields and labels.
Current State
What already exists:
plugins/1c/agentstores chat messages and payload JSON in SQLite.1c-agentpersists outbound model context, inbound provider response,latency_ms, tool results, and RAG context.trace_idexists at the API level for the agent.
What is missing:
- no centralized event schema across plugins and services;
- no guaranteed trace propagation across agent -> adapter/MCP -> model backend;
- no normalized turn-level analytics tables;
- no token/cost accounting;
- no quality labels or review workflow;
- no retention/sanitization/export policy for long-term analysis.
Target Outcome
For every important request we should be able to answer:
- What the user asked.
- Which prompt, model, route, tools, and knowledge sources were used.
- What the system returned.
- Whether the result was successful, partial, wrong, unsafe, or abandoned.
- Which change caused quality to improve or regress.
Logging Layers
1. Access Log
Capture every inbound HTTP request and outbound response for platform services.
Required fields:
timestampserviceinstanceenvironmentrequest_idtrace_idmethodpath_templatestatus_codeduration_msrequest_size_bytesresponse_size_bytesclient_typeerror_code
Notes:
- Do not store raw request/response bodies here by default.
- This is for traffic, latency, and error-rate analysis.
2. Turn Audit Log
Capture one normalized record per user-visible turn.
Required fields:
turn_idtimestampproject_idchat_idpluginservicetrace_idrequest_iduser_message_idassistant_message_iduser_textassistant_textoutcomefailure_typeduration_mshuman_review_status
Recommended enums:
outcome:success,partial,failure,refused,abandonedfailure_type:none,routing,tool_misuse,hallucination,format_error,timeout,provider_error,adapter_error,rag_miss,policy_error,unknown
3. Model Call Log
Capture each actual provider/model request.
Required fields:
model_call_idturn_idtrace_idprovider_idprovider_typebase_urlmodel_registry_idserved_model_nameroute_nametemperaturemax_tokensprompt_messages_jsonresponse_jsonprompt_tokenscompletion_tokenstotal_tokenscost_estimatelatency_msfinish_reasoncache_hit
Notes:
prompt_messages_jsonis the exact payload sent to the model after prompt assembly and tool/RAG injection.response_jsonis the raw provider response after secret stripping.
4. Tool Call Log
Capture every tool or adapter call.
Required fields:
tool_call_idturn_idtrace_idtool_familytool_nametarget_servicerequest_jsonresponse_jsonstatusduration_msretry_count
Recommended tool families:
adaptermcpraginternalexternal-http
5. Retrieval Log
Capture what RAG actually did.
Required fields:
retrieval_idturn_idtrace_idpluginprofileindex_versionquery_texttop_ksources_jsoncontext_charsretrieval_latency_ms
6. Review Log
Capture human or automated quality judgments.
Required fields:
review_idturn_idreviewerreview_sourcescore_helpfulnessscore_correctnessscore_tool_usescore_safetylabel_primary_issuenotescreated_at
Recommended review_source values:
humanevalheuristicllm-judge
Trace Propagation Rules
Every inbound request creates or adopts:
request_idtrace_id
Propagation rules:
- agent must pass
trace_idandrequest_idto adapter/MCP/model wrappers; - adapter and MCP must echo them in responses and logs;
- background jobs must generate child spans but preserve the parent
trace_id; - exported reports must include source
trace_idwhere possible.
If a downstream protocol cannot carry headers directly, include these IDs in the JSON payload envelope.
Secret And Privacy Rules
Never persist raw secrets in long-term logs.
Must redact or hash before storage:
- API keys
- bearer tokens
- cookies
- passwords
- connection strings with credentials
- user-uploaded files containing secrets or personal data
Recommended approach:
- keep raw payload only in short-lived memory for request execution;
- write sanitized JSON to persistent audit storage;
- store a
redaction_applied=trueflag and optionalredaction_rules_version.
Retention Policy
Use three storage horizons.
Hot
- Purpose: active debugging and operator support.
- Storage: local SQLite or service-local JSONL.
- Retention:
7-14days.
Warm
- Purpose: quality analytics and regression analysis.
- Storage: central SQL tables or partitioned JSONL/Parquet under
reports/. - Retention:
30-90days.
Cold
- Purpose: curated datasets and incident forensics.
- Storage: exported reviewed samples only.
- Retention: explicit/manual.
Minimal Schema Proposal
Add a new cross-cutting audit storage layer under core.
Suggested logical entities:
access_eventsturn_auditmodel_callstool_callsretrieval_eventsquality_reviews
Suggested implementation path:
- phase 1: SQLite in each service plus nightly export to JSONL
- phase 2: normalized central SQLite/Postgres
- phase 3: dashboards and automated quality reports
Implementation Order
Phase 1. Fast Wins
Goal: get useful forensic visibility with minimal code churn.
Tasks:
- Add access logging middleware/pattern to
1c-agentand other HTTP services. - Split current message journal into explicit
turn_auditandmodel_callrecords in addition to existing message history. - Add stable
turn_idandmodel_call_id. - Start persisting token usage if the provider returns it.
- Add redaction helper for secrets before writing payload JSON.
- Export daily JSONL snapshots into
reports/observability/.
Definition of done:
- any turn can be reconstructed from one
turn_id; - any provider failure can be grouped by model, route, and error code;
- secrets are not written as plain text.
Phase 2. Cross-Service Correlation
Goal: see one trace across agent, adapter, MCP, and model route.
Tasks:
- Propagate
trace_idandrequest_idthrough agent -> adapter/MCP. - Add the same IDs to adapter logs and tool results.
- Normalize tool-call audit records.
- Record RAG index version and exact retrieved sources.
- Add per-turn
outcomeandfailure_type.
Definition of done:
- a bad answer can be traced to routing, retrieval, tool use, or model output;
- one trace can be joined across at least agent and adapter/MCP logs.
Phase 3. Quality Loop
Goal: turn logs into a real quality improvement loop.
Tasks:
- Add review/export scripts for bad turns and representative samples.
- Add quality labels and scoring workflow.
- Produce weekly aggregate reports:
- error rate by plugin
- failure types by route/model
- tool success rate
- latency percentiles
- token usage and cost
- Feed reviewed samples into eval datasets and training candidates.
Definition of done:
- we can say which model/prompt/route is better using saved evidence;
- we can build eval slices from production-like failures.
Metrics To Track
Minimum operational metrics:
- request count
- non-2xx rate
- timeout rate
- p50/p95/p99 latency
- tool-call success rate
- empty-response rate
- average prompt/completion tokens
Minimum quality metrics:
- turn success rate
- partial-answer rate
- hallucination rate
- tool-misuse rate
- retrieval-miss rate
- human review score averages
- regression rate after route/prompt/model changes
Suggested Repo Additions
Recommended folders:
core/observability/docs/runbooks/observability.mdscripts/export_audit_logs.pyscripts/report_quality_metrics.py
Recommended first shared modules:
core/observability/schema.pycore/observability/redaction.pycore/observability/trace.pycore/observability/store.py
1C-Specific Additions
For the 1c plugin, also record:
base_id- adapter method list
- saved-state vs active/effective mode
- resolved object/module selectors
- truncation/partial flags from adapter
- extension/base layer hints
This is important because many 1C failures are not generic model failures. They come from incomplete evidence, wrong search strategy, or extension-layer blind spots.
Immediate Next Step
The best next implementation step is:
- introduce
core/observabilitywith redaction, trace helpers, and JSONL writers; - wire
1c-agentto emitaccess_events,turn_audit, andmodel_calls; - add one export script and one weekly report script;
- then extend the same contract to other plugins.
This gives us a usable quality loop without waiting for a full observability platform rollout.
Current Implemented Foundation
Already present in the repo:
core/observability/trace.pycore/observability/redaction.pycore/observability/store.pyplugins/1c/agent/agent_server.pyemitsaccess_events,turn_audit,model_calls,tool_calls, andretrieval_eventsscripts/summarize_observability_reports.pyscripts/report_failed_turns.pyscripts/report_quality_metrics.pyscripts/report_repeated_failures.pyscripts/export_quality_snapshot.py