Skip to content

feat(insights): add session latency profiles - #1539

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/session-latency-profile
May 25, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/session-latency-profile

Conversation

@Sinity

@Sinity Sinity commented May 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a durable session-latency read model for #1530. The new session_latency_profiles table materializes provider tool-call latency, stuck unpaired tool starts, agent/user response-gap aggregates, and tool category counts through the same rebuild and incremental-refresh paths as session profiles.

Problem

The insights sprint had workflow-shape and terminal-state primitives, but no durable runtime-latency surface. Computing this ad hoc from raw provider events would make MCP/API reads expensive and would leave daemon catch-up unable to converge the read model incrementally. Also, gating latency reads on generic profile readiness would allow stale or missing latency rows to be served silently.

Solution

  • Added semantic latency facts in polylogue/archive/semantic/timing.py.
  • Added schema v12 session_latency_profiles plus sync/async storage write/read helpers.
  • Wired both full rebuild and targeted incremental refresh to delete/write latency rows with profile rows.
  • Added latency_profile_rows_ready to session insight status/repair and made latency API reads require it.
  • Exposed Python API readers and MCP tools: session_latency_profile, tool_call_latency_distribution, and find_stuck_sessions.
  • Updated MCP schema witnesses, facade/envelope contracts, docs, and topology projection.

Verification

  • pytest tests/unit/core/test_semantic_facts.py tests/unit/storage/test_session_insight_refresh.py tests/unit/storage/test_session_insight_status_descriptors.py tests/unit/storage/test_repair.py tests/unit/storage/test_derived_status.py tests/unit/storage/test_dead_schema_sweep.py tests/unit/mcp/test_insight_shape_tools.py tests/unit/insights/test_fallback_markers.py::test_profile_inference_payload_serializes_fallback_reasons tests/unit/mcp/test_envelope_contracts.py::TestRegistryWideClassification tests/unit/api/test_facade_contracts.py::test_no_undiscovered_async_methods tests/unit/mcp/test_tool_schema_witness.py::test_mcp_tool_catalog_matches_witness -q → 92 passed.
  • Exact reruns for broad-suite failures classified as flaky/unrelated: pytest 'tests/unit/sources/test_parsers_props.py::test_provider_parser_contract[gemini]' -q → 1 passed; pytest tests/unit/ui/test_tui.py::test_browser_node_selection -q → 1 passed.
  • devtools render-all --check → OK.
  • devtools verify --quick → PASS in 36.57s before commit and PASS in 34.86s from the pre-push hook on committed HEAD.
  • devtools verify widened to pytest --testmon-noselect and ran 9,487 tests in 293.16s; it failed before the contract/witness fixes above plus the two exact-node flaky failures. I did not repeat the widened broad run after focused fixes to avoid another 5-minute full-suite-equivalent loop.

Follow-up

Ref #1530. This PR intentionally does not close #1530 until a schema-v12 live archive rebuild produces real distribution stats and representative stuck-session hand checks.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added "Session Latency Profiles" insight type to track tool-call latencies (median, p90, max), stuck tool counts, and agent/user response times
    • New query methods to retrieve and filter sessions by latency metrics and identify stuck sessions
    • Three new insight analysis tools for latency distribution and identifying delayed/stuck conversations
  • Documentation

    • Updated guidance for the new session latency profiling metrics and how to query them

Review Change Stack

Problem: session insight surfaces exposed workflow shape and terminal state, but still lacked a durable read model for runtime latency, stuck tool calls, and response-gap signals. The live-read plan for #1530 needs those signals materialized through the same convergence paths as session profiles, not recomputed ad hoc from raw provider events.

What changed: add session latency facts, a v12 session_latency_profiles table, sync/async rebuild and incremental-refresh writes, repository/API/operations readers, MCP tools for latency profiles/distributions/stuck sessions, and a dedicated latency readiness flag in session-insight status/repair. Document the construct boundary and refresh generated topology/MCP witness artifacts.

Verification: pytest tests/unit/core/test_semantic_facts.py tests/unit/storage/test_session_insight_refresh.py tests/unit/storage/test_session_insight_status_descriptors.py tests/unit/storage/test_repair.py tests/unit/storage/test_derived_status.py tests/unit/storage/test_dead_schema_sweep.py tests/unit/mcp/test_insight_shape_tools.py tests/unit/insights/test_fallback_markers.py::test_profile_inference_payload_serializes_fallback_reasons tests/unit/mcp/test_envelope_contracts.py::TestRegistryWideClassification tests/unit/api/test_facade_contracts.py::test_no_undiscovered_async_methods tests/unit/mcp/test_tool_schema_witness.py::test_mcp_tool_catalog_matches_witness -q -> 92 passed. Exact reruns for broad-suite flakes passed: tests/unit/sources/test_parsers_props.py::test_provider_parser_contract[gemini] and tests/unit/ui/test_tui.py::test_browser_node_selection. devtools render-all --check -> OK. devtools verify --quick -> PASS in 36.57s. A widened devtools verify run executed pytest --testmon-noselect and failed before these contract/witness fixes plus two independently passing flaky nodes; not repeated to avoid another broad 5-minute run.

Ref #1530
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: abdddfe7-ef33-4c87-8155-4cc0d727802a

📥 Commits

Reviewing files that changed from the base of the PR and between cb08bac and 0cfb41d.

📒 Files selected for processing (38)
  • docs/insights.md
  • docs/library-api.md
  • docs/plans/topology-target.yaml
  • docs/schema-annotations.md
  • docs/topology-status.md
  • polylogue/api/insights.py
  • polylogue/archive/semantic/timing.py
  • polylogue/insights/archive.py
  • polylogue/insights/archive_models.py
  • polylogue/mcp/server_insight_tools.py
  • polylogue/operations/archive.py
  • polylogue/storage/insights/session/latency_profiles.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/records.py
  • polylogue/storage/insights/session/refresh.py
  • polylogue/storage/insights/session/repair_assessment.py
  • polylogue/storage/insights/session/runtime.py
  • polylogue/storage/insights/session/status.py
  • polylogue/storage/insights/session/storage.py
  • polylogue/storage/repository/insight/profile_reads.py
  • polylogue/storage/runtime/__init__.py
  • polylogue/storage/sqlite/queries/session_insight_profile_writes.py
  • polylogue/storage/sqlite/queries/session_latency_profile_reads.py
  • polylogue/storage/sqlite/query_store_insight_profiles.py
  • polylogue/storage/sqlite/schema_ddl.py
  • polylogue/storage/sqlite/schema_ddl_insight_latency.py
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/infra/mcp.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/insights/test_fallback_markers.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_insight_shape_tools.py
  • tests/unit/storage/test_dead_schema_sweep.py
  • tests/unit/storage/test_derived_status.py
  • tests/unit/storage/test_repair.py
  • tests/unit/storage/test_session_insight_refresh.py
  • tests/unit/storage/test_session_insight_status_descriptors.py

📝 Walkthrough

Walkthrough

This PR introduces a comprehensive per-session latency profiling system that materializes tool-call durations, stuck-tool counts, and user/agent response latencies. The implementation spans core computation, archive insight models, storage schema, database operations, API/MCP exposure, and extensive test coverage with a full schema version upgrade from 11 to 12.

Changes

Session Latency Profile Insights

Layer / File(s) Summary
Latency computation facts and aggregates
polylogue/archive/semantic/timing.py
SessionLatencyProfileFacts dataclass captures median/p90/max tool-call durations, stuck-tool count, and agent/user response latencies. compute_session_latency_profile pairs provider events into call durations, counts pending calls exceeding 300s threshold, and derives response deltas from message timestamps with user-response capping.
Archive insight models and query interface
polylogue/insights/archive.py, polylogue/insights/archive_models.py
SessionLatencyProfileInsight wraps latency data with SessionLatencyProfilePayload containing all metrics. SessionLatencyProfileInsightQuery extends provider/time-window base with optional conversation_id and only_stuck filters. Deserialization parses JSON evidence and category counts.
Storage record schema and validation
polylogue/storage/insights/session/records.py
SessionLatencyProfileRecord Pydantic model carries latency metrics, tool-call category breakdown, evidence payload, and search metadata. Field validator enforces non-empty conversation ID, provider name, and materialized timestamp.
Latency profile materialization builders
polylogue/storage/insights/session/latency_profiles.py
build_latency_profile_facts computes aggregates from conversation + session profile. build_session_latency_profile_record constructs storage record with materializer versioning, source timestamps, category counts, derived search text, and evidence payload.
Session rebuild and refresh workflow
polylogue/storage/insights/session/rebuild.py, polylogue/storage/insights/session/refresh.py
SessionInsightRecordBundle gains latency_profile_record field. Rebuild flow computes latency facts and includes the record in sync/async paths. Refresh extends flattening to latency records, adds bulk writes after profile writes, and integrates cleanup/deletion during hydration.
SQLite schema and write operations
polylogue/storage/sqlite/schema_ddl_insight_latency.py, polylogue/storage/insights/session/storage.py, polylogue/storage/sqlite/queries/session_insight_profile_writes.py
SESSION_INSIGHT_LATENCY_DDL creates session_latency_profiles table with latency metrics, category counts, evidence, and three indexes. _SESSION_LATENCY_PROFILE_COLUMNS and session_latency_profile_insert_values map records to SQL. replace_session_latency_profiles_bulk_sync performs bulk delete-and-insert. Async wrappers handle transaction depth. SCHEMA_VERSION bumped 11 → 12.
Data access layer: repository and query functions
polylogue/storage/sqlite/queries/session_latency_profile_reads.py, polylogue/storage/repository/insight/profile_reads.py, polylogue/storage/sqlite/query_store_insight_profiles.py
Row-mapping helper converts database rows to SessionLatencyProfileRecord. Three async query functions (get_session_latency_profile, find_stuck_session_latency_profiles, list_session_latency_profiles) with optional date/provider/limit filters and COALESCE-based date expressions. Repository mixin and query store layer delegate to queries.
Status and readiness tracking
polylogue/storage/insights/session/runtime.py, polylogue/storage/insights/session/status.py, polylogue/storage/insights/session/repair_assessment.py
SessionInsightReadyFlag extended with latency_profile_rows_ready. SessionInsightStatusSnapshot tracks latency_profile_row_count plus missing/stale/orphan counters. SQL queries compute row health metrics with freshness gating. Readiness descriptor requires row count match and zero repair debt. Repair assessment incorporates latency debt into row_debt.
Operations and API facade
polylogue/operations/archive.py, polylogue/api/insights.py, polylogue/storage/runtime/__init__.py
ArchiveInsightSessionMixin adds three async methods validating latency_profile_rows_ready readiness, fetching records, and converting to insights with optional filtering by conversation_id and only_stuck (stuck-count > 0). PolylogueInsightsMixin implements public API methods delegating to operations. SessionLatencyProfileRecord exported from runtime module.
MCP tool registration and exposure
polylogue/mcp/server_insight_tools.py
Registers tool_call_latency_distribution (computes percentile distributions with optional tool-category filter), session_latency_profile (single conversation fetch), and find_stuck_sessions (stuck-only listing). All tools use hooks.async_safe_call and MCPRootPayload for response shaping; error handling for missing conversations.
Documentation and schema annotations
docs/insights.md, docs/library-api.md, docs/schema-annotations.md, tests/data/witnesses/mcp-tool-schemas.json
Added "Session Latency Profiles" to insights overview. Documented SessionLatencyProfileInsight and query type with field descriptions and construct-boundary timing caveats. Annotated schema with latency measures, coverage notes on missing provider timestamps, and per-tool-category breakdowns. Witness MCP schemas updated with new tool definitions and argument extensions.
Tests, contracts, and witness updates
tests/unit/core/test_semantic_facts.py, tests/unit/api/test_facade_contracts.py, tests/unit/mcp/test_envelope_contracts.py, tests/unit/mcp/test_insight_shape_tools.py, tests/unit/storage/test_*.py, tests/infra/mcp.py
Unit test validates latency aggregation from synthetic events. API contract tests categorize new methods (read-by-id, nullary reads). MCP envelope tests classify tools as envelope/single-object. Three async MCP tests verify tool responses (insight_kind, latency values, stuck counts, aggregations). SQLite status descriptor test validates readiness logic with missing/stale latency rows. Helper stubs and fixtures updated for new schema fields. Schema version assertion bumped 11 → 12. Tool name expectations updated.
Infrastructure and metadata updates
docs/plans/topology-target.yaml, docs/topology-status.md, tests/unit/storage/test_dead_schema_sweep.py, tests/unit/insights/test_fallback_markers.py, tests/unit/storage/test_derived_status.py, tests/unit/storage/test_repair.py, tests/unit/storage/test_session_insight_refresh.py
Regenerated topology projection with updated loc metrics for affected modules. Updated topology status dashboard counts ("Stable" 717 → 720, total 850 → 853). Schema version assertion updated to 12. Test fixtures and stubs extended with taxonomy fields (tool_active_duration_ms, workflow_shape, terminal_state, topic inference) to match schema expectations. Status snapshot fixtures updated to set latency_profile_rows_ready=True.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#749: Both PRs extend the session-insight status computation pipeline, including new readiness flags and row-count tracking in polylogue/storage/insights/session/status.py and related gating logic.

Suggested labels

area:storage, area:schema, area:qa, type:test

Poem

🐰 A latency tale hops by—
Tool calls timed, the stuck ones cry,
From provider event to insight bright,
Sessions revealed, no more questions why.
Schema bumped, tests all pass,
The agent's speed now has a class. 🏃‍♂️

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/session-latency-profile

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 4c504ed into master May 25, 2026
6 of 7 checks passed
@Sinity
Sinity deleted the feature/feat/session-latency-profile branch May 25, 2026 03:36

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0cfb41dd7d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/operations/archive.py Resolved
Comment thread polylogue/operations/archive.py Resolved
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 68.F027 / P1: fixed-already at the checked revision: polylogue/storage/sqlite/archive_tiers/archive.py:3861-3863 restricts the requested session in SQL and lines 3899-3902 apply stuck_tool_count > 0 before pagination. LIMIT is appended only at lines 3905-3914, so recent non-matching sessions cannot consume the requested result window.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 69.F046 / P2: fixed-already at the checked revision: polylogue/storage/sqlite/archive_tiers/archive.py:3946-3955 forwards session_id, origin and both time bounds to the general latency query. That query applies origin and until as SQL predicates at lines 3866 and 3887, so stuck-session results respect the complete scope.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(insights): per-session latency profile from provider_event_tool_calls + message timestamps

1 participant