Skip to content

feat(insights): add per-tool timing and thinking/output split (#804) - #895

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/temporal-analysis-804
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/temporal-analysis-804

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

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 (SessionTimingFacts

  • compute_session_timing) extracts timing from message timestamps and
    content-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_profiles table columns (DDL, mappers, storage writes)
  • SessionProfileRecord (Pydantic storage model)
  • SessionProfileInsight display fields (registry.py)

New session_profiles columns: thinking_duration_ms, output_duration_ms,
tool_duration_ms, latency_percentiles_ms_json, tool_calls_per_minute,
timing_provenance.

Bumps SESSION_INSIGHT_MATERIALIZER_VERSION to 10.

Files touched (11 files, +264/-1):

  • polylogue/archive/semantic/timing.py — NEW module
  • polylogue/archive/session/models.py — SessionProfile fields
  • polylogue/archive/session/runtime.py — wire timing into build_session_profile
  • polylogue/insights/archive_models.py — SessionEvidencePayload fields
  • polylogue/insights/registry.py — SessionProfileInsight display fields
  • polylogue/storage/insights/session/profiles.py — evidence payload, record builder, hydrate
  • polylogue/storage/insights/session/records.py — SessionProfileRecord fields
  • polylogue/storage/insights/session/storage.py — base columns, insert values
  • polylogue/storage/runtime/store_constants.py — version bump
  • polylogue/storage/sqlite/queries/mappers_insight_profiles.py — row mapper
  • polylogue/storage/sqlite/schema_ddl_insight_profiles.py — DDL columns

Verification

Deferred to wave batch per #852 policy.

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]>
Copilot AI review requested due to automatic review settings May 7, 2026 08:56
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 57 minutes and 21 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4d1952ed-5c52-452f-978a-8d9e95ac47c1

📥 Commits

Reviewing files that changed from the base of the PR and between 8c40ce4 and a8c631a.

📒 Files selected for processing (11)
  • polylogue/archive/semantic/timing.py
  • polylogue/archive/session/models.py
  • polylogue/archive/session/runtime.py
  • polylogue/insights/archive_models.py
  • polylogue/insights/registry.py
  • polylogue/storage/insights/session/profiles.py
  • polylogue/storage/insights/session/records.py
  • polylogue/storage/insights/session/storage.py
  • polylogue/storage/runtime/store_constants.py
  • polylogue/storage/sqlite/queries/mappers_insight_profiles.py
  • polylogue/storage/sqlite/schema_ddl_insight_profiles.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/temporal-analysis-804

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 f87a2fc into master May 7, 2026
5 checks passed
@Sinity
Sinity deleted the feature/feat/temporal-analysis-804 branch May 7, 2026 08:56

@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: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +111 to +114
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copilot AI 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.

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.py to compute per-session timing aggregates from inter-message gaps.
  • Threads new timing fields through SessionProfile → insights evidence payload → SQLite session_profiles storage (DDL, record models, mappers, inserts).
  • Updates insights registry display fields and bumps SESSION_INSIGHT_MATERIALIZER_VERSION to 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.

Comment on lines +109 to +113
# 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
Comment on lines +45 to +54
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 {}))
Comment on lines +108 to +117
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 {}))
Comment on lines 39 to +46
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 "{}"

Comment on lines +78 to +150
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",
)
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
@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.

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.

2 participants