Repository navigation
feat(insights): add per-tool timing and thinking/output split (#804) - #895
Conversation
Compute session timing aggregates from inter-message sort_key gaps: thinking duration, output duration, tool-call duration, latency percentiles (p50/p95/p99), and tool calls per minute. New module polylogue/archive/semantic/timing.py extracts timing from stored message timestamps and content-block classifications. Timing fields flow through SessionProfile → SessionEvidencePayload → session_profiles columns → reader/CLI/MCP display surfaces. Bumps SESSION_INSIGHT_MATERIALIZER_VERSION to 10. Ref #804 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
To continue reviewing without waiting, purchase usage credits in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (11)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a8c631aed4
ℹ️ 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".
| ) | ||
| timing = compute_session_timing( | ||
| list(conversation.messages), | ||
| tool_use_count=facts.tool_messages, |
There was a problem hiding this comment.
Compute tool calls/minute from calls, not tool messages
tool_calls_per_minute is fed from facts.tool_messages, but that counter increments for every message with is_tool_use, and is_tool_use is true for both TOOL_USE and TOOL_RESULT. In sessions with normal tool-use/result pairs, this overcounts by about 2x, so the reported throughput is systematically inflated. This should use an actual tool-call count (e.g., action/tool-call events) rather than message count.
Useful? React with 👍 / 👎.
| message.is_tool_use | ||
| or any(block.get("type") == "tool_result" for block in message.content_blocks) | ||
| ) and prev_message.is_assistant: | ||
| tool_duration_ms += gap |
There was a problem hiding this comment.
Restrict tool duration to tool_result gaps only
The tool-duration branch currently matches any message.is_tool_use (plus explicit tool_result) when the previous message is assistant. Since is_tool_use includes tool-use requests, assistant→assistant transitions into a tool_use message are counted as tool runtime even though execution has not happened yet, which inflates tool_duration_ms whenever an assistant preamble/thinking message precedes the tool call. Classify tool runtime only for the tool_use -> tool_result gap.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
This PR extends Polylogue’s session insight pipeline to compute and persist richer temporal timing analytics derived from message timestamps/content blocks, enabling retroactive timing insights (thinking vs output vs tool time, latency percentiles, and tool throughput) for existing archives.
Changes:
- Introduces
polylogue/archive/semantic/timing.pyto compute per-session timing aggregates from inter-message gaps. - Threads new timing fields through
SessionProfile→ insights evidence payload → SQLitesession_profilesstorage (DDL, record models, mappers, inserts). - Updates insights registry display fields and bumps
SESSION_INSIGHT_MATERIALIZER_VERSIONto 10.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| polylogue/archive/semantic/timing.py | New timing computation module (durations, percentiles, throughput) used during session profile build. |
| polylogue/archive/session/models.py | Adds timing fields to SessionProfile payload/serialization. |
| polylogue/archive/session/runtime.py | Wires timing computation into build_session_profile. |
| polylogue/insights/archive_models.py | Extends SessionEvidencePayload with timing fields. |
| polylogue/insights/registry.py | Adds timing-related columns to insight listing fields. |
| polylogue/storage/insights/session/profiles.py | Persists timing fields into storage record + evidence payload; hydrates into SessionProfile. |
| polylogue/storage/insights/session/records.py | Adds timing fields to SessionProfileRecord. |
| polylogue/storage/insights/session/storage.py | Adds new columns to insert column list + insert bindings. |
| polylogue/storage/runtime/store_constants.py | Bumps SESSION_INSIGHT_MATERIALIZER_VERSION to 10. |
| polylogue/storage/sqlite/queries/mappers_insight_profiles.py | Maps new SQLite columns into SessionProfileRecord. |
| polylogue/storage/sqlite/schema_ddl_insight_profiles.py | Adds new session_profiles table columns for timing metrics. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # A tool-call gap is the time before a tool_result message. | ||
| if ( | ||
| message.is_tool_use | ||
| or any(block.get("type") == "tool_result" for block in message.content_blocks) | ||
| ) and prev_message.is_assistant: |
| from polylogue.core.json import JSONDocument, json_document | ||
|
|
||
| if TYPE_CHECKING: | ||
| from polylogue.archive.conversation.models import Conversation |
| thinking_duration_ms: int = 0 | ||
| output_duration_ms: int = 0 | ||
| tool_duration_ms: int = 0 | ||
| latency_percentiles_ms: dict[str, int] = () | ||
| tool_calls_per_minute: float = 0.0 | ||
| timing_provenance: str = "sort_key_estimated" | ||
|
|
||
| def __post_init__(self) -> None: | ||
| if not isinstance(self.latency_percentiles_ms, dict): | ||
| object.__setattr__(self, "latency_percentiles_ms", dict(self.latency_percentiles_ms or {})) |
| thinking_duration_ms: int = 0 | ||
| output_duration_ms: int = 0 | ||
| tool_duration_ms: int = 0 | ||
| latency_percentiles_ms: dict[str, int] = () | ||
| tool_calls_per_minute: float = 0.0 | ||
| timing_provenance: str = "sort_key_estimated" | ||
|
|
||
| def __post_init__(self) -> None: | ||
| if not isinstance(self.latency_percentiles_ms, dict): | ||
| object.__setattr__(self, "latency_percentiles_ms", dict(self.latency_percentiles_ms or {})) |
| from polylogue.types import ConversationId | ||
|
|
||
| import json as _json | ||
|
|
||
|
|
||
| def _serialize_percentiles(percentiles: dict[str, int]) -> str: | ||
| return _json.dumps(percentiles, sort_keys=True) if percentiles else "{}" | ||
|
|
| def compute_session_timing( | ||
| messages: Sequence[Message], | ||
| *, | ||
| tool_use_count: int = 0, | ||
| wall_duration_ms: int = 0, | ||
| ) -> SessionTimingFacts: | ||
| """Compute timing aggregates from a chronological message sequence. | ||
|
|
||
| Messages are assumed to be in chronological order (as returned by the | ||
| storage layer, sorted by ``sort_key``). Timing provenance defaults to | ||
| ``"sort_key_estimated"`` because these values are derived from inter- | ||
| message gaps rather than hook-level precise measurements. | ||
| """ | ||
| if not messages: | ||
| return SessionTimingFacts() | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Per-message gap computation | ||
| # ------------------------------------------------------------------ | ||
| gaps: list[int] = [] | ||
| thinking_duration_ms = 0 | ||
| output_duration_ms = 0 | ||
| tool_duration_ms = 0 | ||
| prev_message: Message | None = None | ||
|
|
||
| for message in messages: | ||
| if prev_message is not None: | ||
| gap = _gap_ms(prev_message.timestamp, message.timestamp) | ||
| gaps.append(gap) | ||
|
|
||
| # Classify the gap based on *this* message's content. | ||
| # A tool-call gap is the time before a tool_result message. | ||
| if ( | ||
| message.is_tool_use | ||
| or any(block.get("type") == "tool_result" for block in message.content_blocks) | ||
| ) and prev_message.is_assistant: | ||
| tool_duration_ms += gap | ||
| elif message.is_thinking and not message.is_tool_use: | ||
| thinking_duration_ms += gap | ||
| elif message.is_assistant and message.is_substantive: | ||
| # Assistant response that is neither thinking-only nor tool: | ||
| # treat as output. | ||
| output_duration_ms += gap | ||
|
|
||
| prev_message = message | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Latency percentiles (p50, p95, p99) | ||
| # ------------------------------------------------------------------ | ||
| sorted_gaps = sorted(g for g in gaps if g > 0) | ||
| latency_percentiles_ms = { | ||
| "p50": _percentile(sorted_gaps, 50), | ||
| "p95": _percentile(sorted_gaps, 95), | ||
| "p99": _percentile(sorted_gaps, 99), | ||
| } | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Tool calls per minute | ||
| # ------------------------------------------------------------------ | ||
| tool_calls_per_minute = 0.0 | ||
| if tool_use_count > 0 and wall_duration_ms > 0: | ||
| minutes = wall_duration_ms / 60_000.0 | ||
| if minutes > 0: | ||
| tool_calls_per_minute = round(tool_use_count / minutes, 2) | ||
|
|
||
| return SessionTimingFacts( | ||
| thinking_duration_ms=thinking_duration_ms, | ||
| output_duration_ms=output_duration_ms, | ||
| tool_duration_ms=tool_duration_ms, | ||
| latency_percentiles_ms=latency_percentiles_ms, | ||
| tool_calls_per_minute=tool_calls_per_minute, | ||
| timing_provenance="sort_key_estimated", | ||
| ) |
Closes #804. Session profiles had wall, engaged, and total duration but no per-tool timing or thinking/output split, leaving questions like "which tools consumed time?" and "how much was spent thinking vs producing output?" unanswerable for retrospectives. Computes timing aggregates from inter-message sort-key gaps so existing data is covered retroactively. - `polylogue/archive/semantic/timing.py` (new): `SessionTimingFacts` plus `compute_session_timing()` classifying inter-message gaps as thinking (messages with thinking blocks), output (assistant text without thinking), or tool-call (tool_use → tool_result gap). - `polylogue/archive/session/{models,runtime}.py`: `SessionProfile` gains `thinking_duration_ms`, `output_duration_ms`, `tool_duration_ms`, `latency_percentiles_ms_json`, `tool_calls_per_minute`, `timing_provenance`. `build_session_profile` wires `compute_session_timing()` in. - `polylogue/insights/{archive_models,registry}.py`: `SessionEvidencePayload` and `SessionProfileInsight` carry the new fields. - `polylogue/storage/insights/session/{profiles,records,storage}.py`: evidence-payload, record-builder, and hydrate paths pick up the new columns. - Bumps `SESSION_INSIGHT_MATERIALIZER_VERSION` to 10. Note: GitHub commit-to-PR API associates this commit with PR #895 (titled per-tool timing); the local commit subject previously named #869, but the diff is the timing work. Refs #804
Direct, no-PR. Larger cleanup batch after the multi-PR merge wave landed mismatches between the agent-authored PRs. - `polylogue/protocols.py`: `TagStore` protocol return types switch from `None` to `bool` for `add_tag`, `remove_tag`, `update_metadata`, `delete_metadata`, matching the idempotency contract introduced in PR #893 (#862). - `polylogue/archive/session/{documents,models}.py`: adds the per-tool timing fields to `SessionProfileDocument` TypedDict so PR #895's timing additions roundtrip through the TypedDict consumers. - `polylogue/daemon/{health,notifications,status}.py`: fixes the circular import between `status.py` and `health.py` introduced by PR #898; tightens generic dict-type parameters in `notifications.py`. - `polylogue/storage/insights/session/profiles.py`: replaces `dict()` calls with literal `{}` where mypy's inference preferred the literal. - `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups for the `MutationResultPayload` envelope from PR #893. Refs #830, #862, #895
Closes #804. Session profiles had wall, engaged, and total duration but no per-tool timing or thinking/output split, leaving questions like "which tools consumed time?" and "how much was spent thinking vs producing output?" unanswerable for retrospectives. Computes timing aggregates from inter-message sort-key gaps so existing data is covered retroactively. - `polylogue/archive/semantic/timing.py` (new): `SessionTimingFacts` plus `compute_session_timing()` classifying inter-message gaps as thinking (messages with thinking blocks), output (assistant text without thinking), or tool-call (tool_use → tool_result gap). - `polylogue/archive/session/{models,runtime}.py`: `SessionProfile` gains `thinking_duration_ms`, `output_duration_ms`, `tool_duration_ms`, `latency_percentiles_ms_json`, `tool_calls_per_minute`, `timing_provenance`. `build_session_profile` wires `compute_session_timing()` in. - `polylogue/insights/{archive_models,registry}.py`: `SessionEvidencePayload` and `SessionProfileInsight` carry the new fields. - `polylogue/storage/insights/session/{profiles,records,storage}.py`: evidence-payload, record-builder, and hydrate paths pick up the new columns. - Bumps `SESSION_INSIGHT_MATERIALIZER_VERSION` to 10. Note: GitHub commit-to-PR API associates this commit with PR #895 (titled per-tool timing); the local commit subject previously named #869, but the diff is the timing work. Refs #804
Direct, no-PR. Larger cleanup batch after the multi-PR merge wave landed mismatches between the agent-authored PRs. - `polylogue/protocols.py`: `TagStore` protocol return types switch from `None` to `bool` for `add_tag`, `remove_tag`, `update_metadata`, `delete_metadata`, matching the idempotency contract introduced in PR #893 (#862). - `polylogue/archive/session/{documents,models}.py`: adds the per-tool timing fields to `SessionProfileDocument` TypedDict so PR #895's timing additions roundtrip through the TypedDict consumers. - `polylogue/daemon/{health,notifications,status}.py`: fixes the circular import between `status.py` and `health.py` introduced by PR #898; tightens generic dict-type parameters in `notifications.py`. - `polylogue/storage/insights/session/profiles.py`: replaces `dict()` calls with literal `{}` where mypy's inference preferred the literal. - `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups for the `MutationResultPayload` envelope from PR #893. Refs #830, #862, #895
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Compute per-session timing aggregates from inter-message sort-key gaps:
thinking duration, output duration, tool-call duration, latency
percentiles (p50/p95/p99), and tool calls per minute. All metrics
work retroactively on existing data via stored message timestamps.
Problem
Session profiles have wall_duration_ms, engaged_duration_ms, and
total_duration_ms but no per-tool timing or thinking/output split.
The archive cannot answer which tools consumed the most time or how
much time was spent thinking vs producing output.
Solution
New module
polylogue/archive/semantic/timing.py(SessionTimingFactscompute_session_timing) extracts timing from message timestamps andcontent-block classifications. The function classifies inter-message
gaps as thinking (messages with thinking blocks), output (assistant
text without thinking), or tool-call (tool_use → tool_result gap)
duration.
Timing fields flow through the existing insight pipeline:
SessionProfile(frozen dataclass, archive/session/models.py)SessionEvidencePayload(Pydantic model, insights/archive_models.py)session_profilestable columns (DDL, mappers, storage writes)SessionProfileRecord(Pydantic storage model)SessionProfileInsightdisplay fields (registry.py)New
session_profilescolumns: thinking_duration_ms, output_duration_ms,tool_duration_ms, latency_percentiles_ms_json, tool_calls_per_minute,
timing_provenance.
Bumps
SESSION_INSIGHT_MATERIALIZER_VERSIONto 10.Files touched (11 files, +264/-1):
polylogue/archive/semantic/timing.py— NEW modulepolylogue/archive/session/models.py— SessionProfile fieldspolylogue/archive/session/runtime.py— wire timing into build_session_profilepolylogue/insights/archive_models.py— SessionEvidencePayload fieldspolylogue/insights/registry.py— SessionProfileInsight display fieldspolylogue/storage/insights/session/profiles.py— evidence payload, record builder, hydratepolylogue/storage/insights/session/records.py— SessionProfileRecord fieldspolylogue/storage/insights/session/storage.py— base columns, insert valuespolylogue/storage/runtime/store_constants.py— version bumppolylogue/storage/sqlite/queries/mappers_insight_profiles.py— row mapperpolylogue/storage/sqlite/schema_ddl_insight_profiles.py— DDL columnsVerification
Deferred to wave batch per #852 policy.