Skip to content

feat(insights): temporal session analysis — per-tool timing, thinking vs output split, latency breakdown #804

Closed

Description

@Sinity

Problem

Polylogue stores session-level duration aggregates but cannot answer timing questions that matter for coding-agent work:

  • which tools consumed the most time;
  • how much time was spent thinking vs producing output;
  • where latency spikes occurred;
  • how a session progressed over time.

Data sources

Historical sessions:

  • Claude Code sort keys provide millisecond ordering for most messages.
  • Tool duration can be approximated from adjacent message gaps around tool use/result records.
  • Provider message metadata can expose API/request duration where present.

Future sessions:

Scope

  • Extract or compute temporal facts from existing archive rows where possible.
  • Model per-tool timing, inter-message gaps, thinking/output spans, latency summaries, and timeline events as derived session data.
  • Expose the data through the current consolidated surface direction: reader/detail/context/MCP/CLI as appropriate.
  • Decide the final user-facing surface explicitly before adding a new isolated command island.

Non-goals

  • Do not assume polylogue insights or polylogue diagnostics turns are final command names.
  • Do not block historical timing on hook integration; hooks improve precision for future sessions but are not required for the first retroactive slice.
  • Do not infer unavailable metrics such as true TTFT unless provider/hook data actually supplies them.

Acceptance criteria

  • Historical inter-message timing is extracted from stored sort keys where available.
  • Tool-call duration estimates work retroactively and are labeled as estimates.
  • Hook-based timing from feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802 can augment or replace estimates for new sessions.
  • Thinking/output and latency summaries are represented in a typed model.
  • Surface placement is chosen explicitly and wired through shared contracts.
  • Tests cover historical estimate behavior and at least one future/hook-shaped precise timing fixture when hook data exists.

Refs #802 #838 #848 #852.

Activity

  1. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor
  2. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Temporal Analysis Assessment

    What polylogue captures today

    Session-level (session_profiles table):

    • first_message_at / last_message_at — message timestamp bounds
    • total_duration_ms — from provider_meta
    • engaged_duration_ms — computed from message timestamps (sum of inter-message gaps below a threshold)
    • wall_duration_ms — last minus first message timestamp
    • tool_use_count — total tool calls
    • compaction_count — context compaction events

    Message-level (HarmonizedMessage.duration_ms):

    • durationMs from Claude Code JSONL records — per-message API call duration
    • Extracted by ClaudeCodeRecord.to_meta() and _harmonize_extracted_provider_meta()

    What's missing (and where to get it)

    Metric Source Priority
    Per-tool-call duration Not captured. Claude Code tracks totalToolDuration in State but not per-call. Hook integration (PostToolUse timing) would capture it. High
    Compilation/thinking time Not captured. Claude Code API responses carry thinking duration separately but polylogue doesn't extract it. High
    Time-to-first-token (TTFT) Not in JSONL (internal telemetry only). PostToolUse hook doesn't have it either. Low (unavailable)
    API call latency (totalAPIDuration) Claude Code State tracks this but not persisted to session JSONL. Medium
    Turn-level timing Not captured. Could be computed from message timestamps but not stored as a first-class concept. Medium
    Session idle time Partially computed via engaged_duration_ms but not stored per-idle-period. Low
    Pipeline/ingest timing Tracked in runs table (pipeline execution metadata) but not surfaced in session views. Low

    Concrete gaps

    1. No per-tool-call timing: A session may have 100 tool calls taking 30 minutes total, but you can't see which tool took 25 minutes. The per-message durationMs covers the API call that PRODUCED the tool call, not the tool call itself.

    2. No thinking vs output split: Claude Code distinguishes thinking blocks from output blocks but polylogue doesn't track their individual durations. A session might spend 80% of its time thinking and 20% producing output — invisible.

    3. No compilation time: For coding sessions, compilation/test time is a significant fraction of wall time. Not captured anywhere — would need PostToolUse hook timing.

    4. No latency percentiles: total_duration_ms is an aggregate. No p50/p95/p99 view of API call latency across a session.

    5. No tool call throughput: How many tool calls per minute of wall time? Computable from existing data (tool_use_count / wall_duration) but not pre-computed.

    Hook-based capture opportunity

    The PostToolUse hook fires AFTER tool execution. Timing the hook execution itself gives tool call duration. The SessionStart/Stop hooks give session wall time. Combined:

    SessionStart → wall clock starts
      PreToolUse → tool_start = now
      PostToolUse → tool_duration = now - tool_start
    Stop → session_duration = now - session_start
    

    This fills the per-tool-call timing gap entirely via hooks, with no changes to polylogue's parser.

  3. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Correction: parser changes ARE desirable where they help. The approach should be:

    1. Historical sessions (parser change): extract inter-message timing from existing sort_keys. 99% of CC messages have sort_key with millisecond precision. Tool call duration ≈ gap between tool_use sort_key and next message's sort_key. No hooks needed, works retroactively on all existing data.

    2. Live sessions (hooks): PostToolUse hook gives precise timing for new sessions. SessionStart/Stop hooks give session wall time.

    Both paths contribute — parser for backward coverage, hooks for forward precision. The parser already stores sort_key; the gap is that it doesn't compute or surface tool call durations from them.

  4. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Acceptance Criteria

    Capture

    1. Inter-message timing extracted from sort_keys for historical sessions (99% coverage, ms precision)
    2. Tool call duration computed from adjacent message gaps — works retroactively on all existing data
    3. Hook-based PostToolUse timing for precise per-tool duration on new sessions

    Surface

    1. polylogue insights — new temporal views: per-session tool timing breakdown, thinking/output split
    2. polylogue stats — latency percentiles (p50/p95/p99), tool throughput (calls/min)
    3. polylogue diagnostics turns — extended with tool timing
    4. Session detail view — chronological timeline of tool executions and thinking blocks

    When closing: comment on this issue or the PR explicitly stating how each criterion was satisfied, deferred, or found misframed.

  5. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Correction: polylogue diagnostics turns does NOT exist yet as a command. The proposal is to create it. Also: #717 proposes removing polylogue insights, which contradicts this issue's proposal to add temporal views to insights. These need reconciliation — either insights stays or temporal views go elsewhere.

  6. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Related: #827 (session intelligence umbrella), #804 (temporal analysis), #803 (cost tracking), #801 (paste detection). These four insight features share infrastructure (session_profiles, action_events, day_session_summaries) and should be sequenced together.

  7. added
    area:insights
    theme:analysis
    on May 6, 2026
  8. Sinity commented on May 6, 2026

    @Sinity
    OwnerAuthor

    Backlog hygiene note: surface names need reconciliation

    The temporal analysis goal is still valuable, but this issue should not assume polylogue insights or polylogue diagnostics turns are the final surfaces.

    Per #717, surface taxonomy is still being consolidated around daemon-backed reader/status/CLI/MCP behavior. The durable scope here is the data/product capability:

    Before implementation, choose the surface contract explicitly: context-pack/detail/status/MCP/tooling, rather than adding another isolated insights island by default.

  9. Sinity commented on May 6, 2026

    @Sinity
    OwnerAuthor

    Execution supplement

    Mass-execution wave: #852 Wave 5 after storage insight contracts are stable enough.

    Focused verification:

    • temporal/session insight tests for per-tool timing, thinking/output split, latency fields, and ordering with historical sort keys;
    • storage insight read/write tests if materialized tables change;
    • CLI/API/MCP/reader contract tests only for surfaces that expose the analysis;
    • hook-timing tests only after feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802 supplies hook evidence;
    • devtools verify --quick, then full devtools verify before PR.

    Do not assume a new isolated insights UI island; surface temporal data through existing reader/detail/context contracts where possible.

  10. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reconnaissance Report: #804 feat(insights): temporal session analysis

    Date: 2026-05-07 | Prep agent: file-search (read-only)


    Codebase State

    Existing timing infrastructure:

    What Where Status
    Message sort_key (REAL, millisecond precision) messages.sort_key in schema_ddl_archive.py:84 Stored for 99% of CC messages
    total_duration_ms SessionProfile.total_duration_ms From provider_meta aggregated durationMs
    engaged_duration_ms SessionProfile.engaged_duration_ms Sum of phase durations or fallback to total_duration_ms
    wall_duration_ms SessionProfile.wall_duration_ms Computed from first/last message timestamps
    Per-phase timing SessionPhase.duration_ms, start_time, end_time Computed from message timestamps
    Per-work-event timing WorkEvent.duration_ms, start_time, end_time Set during extraction
    timestamp on messages ParsedMessage.timestamp in parser output Normalized from CC/Codex timestamps

    Parser sort_key handling:

    • polylogue/sources/parsers/claude/code_parser.py:189-192 — normalize_timestamp() converts CC timestamps to string epoch floats, which get stored as sort_key REAL. 99% of CC records have timestamp with millisecond precision.
    • polylogue/sources/parsers/codex.py:43-46 — Codex uses _normalize_timestamp() with similar precision.
    • CC parser also accumulates total_duration from per-record durationMs (lines 216-218).

    What is NOT captured:

    Metric Gap
    Per-tool-call duration Not captured — totalToolDuration in CC State, not per-call
    Thinking vs output time split ReasoningTrace has `duration_ms: int
    Time-to-first-token (TTFT) Not in JSONL (internal telemetry)
    Latency percentiles (p50/p95/p99) total_duration_ms is aggregate only
    Tool call throughput (calls/min) Computable but not pre-computed

    Insight surfaces that currently expose timing:

    Insight Timing fields
    SessionProfileInsight wall_s, engaged_min, first, last (display only)
    SessionPhaseInsight start, words (display only)
    SessionWorkEventInsight start, end, duration_ms
    DaySessionSummaryInsight No timing display fields
    ProviderAnalyticsInsight No timing display fields

    Build This

    1. Per-tool-call duration from sort_keys (historical, ~99% coverage):

      • New module: polylogue/archive/semantic/timing.py
      • For each message containing tool_use content blocks, compute duration as: next_message.sort_key - this_message.sort_key
      • Store in existing WorkEvent.duration_ms or add per-tool timing to content_blocks / action_events
      • Works retroactively on all existing data — no hooks needed
    2. Thinking vs output split:

      • For Claude Code messages with thinking blocks: mark block-level duration
      • If provider data carries thinking_duration or block-level timing, extract it
      • Compute thinking/total ratio per message and per session
      • Add thinking_duration_ms and output_duration_ms to SessionProfileRecord
    3. Latency percentile computation (p50/p95/p99):

      • New computed field on SessionProfile: api_latency_percentiles: dict[str, int] (p50, p95, p99 in ms)
      • Computed from per-message durationMs (already accessible via provider_meta or sort_key gaps)
      • Display through ProviderAnalyticsInsight or extend SessionProfileInsight
    4. Tool call throughput:

      • tool_calls_per_minute = tool_use_count / (wall_duration_ms / 60000)
      • Pre-computed on SessionProfile / SessionProfileRecord
    5. Hook-based precise timing (forward-looking, depends on feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802):

      • PostToolUse hook captures precise tool_start → tool_end duration
      • Merge with sort_key-derived estimates (hook timing preferred when both exist)
      • Record provenance: "hook_precise" vs "sort_key_estimated"
    6. Surface through existing contracts (NOT new isolated insights):

      • Extend SessionProfileInsight display fields: thinking/output split, latency percentiles, throughput
      • Extend SessionWorkEventInsight with per-event timing detail
      • Add timing fields to MCP detail/context contracts when surfaces expose session detail
      • Per chore(backlog): daemon-first execution graph after #847 #852 coordination: surface through reader/detail/context/MCP, not isolated timeline UI

    Do NOT Build

    1. Do NOT create a new isolated polylogue insights temporal command. The issue body once mentioned this but chore(backlog): daemon-first execution graph after #847 #852 coordination explicitly rejects it. Temporal data must extend existing insight types and reader/detail/context contracts.

    2. Do NOT assume polylogue diagnostics turns exists. The issue body correction note (May 2026) explicitly says this command does not exist and surface names need reconciliation against feat(surfaces): implement polylogued local reader and query-native CLI UX #717.

    3. Do NOT wait for hooks (feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802) before implementing. The historical sort_key approach gives 99% coverage immediately. Build that first, then enhance with hook precision when feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802 lands.

    4. Do NOT add per-tool-call duration as new message-level columns. Use existing WorkEvent / action_events rows; tool timing is a property of the tool execution, not the message envelope.

    5. Do NOT compute timing by re-parsing raw JSONL at query time. Pre-compute during session profile / insight materialization.


    Files to Touch

    File Change
    polylogue/archive/semantic/timing.py NEW — sort_key-based timing computation
    polylogue/archive/session/runtime.py build_session_profile — add timing computation
    polylogue/archive/session/models.py Add thinking_duration_ms, output_duration_ms, latency_percentiles, tool_throughput to SessionProfile
    polylogue/insights/archive_models.py Extend SessionEvidencePayload with timing fields
    polylogue/storage/insights/session/records.py Extend SessionProfileRecord with new timing fields
    polylogue/storage/insights/session/timeline_rows.py Extend work event records with per-tool timing
    polylogue/storage/sqlite/schema_ddl_insight_profiles.py Add timing columns to session_profiles
    polylogue/storage/sqlite/schema_bootstrap.py Schema upgrade for timing columns
    polylogue/insights/registry.py Extend SessionProfileInsight display fields
    polylogue/storage/insights/session/rebuild.py Rebuild includes timing computation
    polylogue/storage/runtime/store_constants.py Bump SESSION_INSIGHT_MATERIALIZER_VERSION to 10

    Coordination


    Focused Tests

    # Sort-key timing computation
    pytest tests/unit/archive/test_timing.py -v
    
    # Session profile timing fields roundtrip
    pytest tests/unit/storage/test_session_insight_timing.py -v
    
    # Latency percentile computation
    pytest tests/unit/archive/test_timing_percentiles.py -v
    
    # Thinking/output split extraction
    pytest tests/unit/archive/test_timing_thinking_split.py -v
    
    # Work event per-tool timing
    pytest tests/unit/storage/test_work_event_timing.py -v
    
    # Schema upgrade for timing columns
    pytest tests/unit/storage/test_schema_upgrade_timing.py -v
    
    # Insight display field extension
    pytest tests/unit/core/test_insight_registry_timing.py -v
    
    # Static checks
    ruff check polylogue/archive/semantic/timing.py polylogue/archive/session/

    Acceptance Criteria

    1. Inter-message timing extracted from sort_keys for historical sessions (99% coverage, ms precision)
    2. Tool call duration computed from adjacent message gaps — works retroactively on all existing data
    3. Hook-based PostToolUse timing for precise per-tool duration on new sessions (after feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802)
    4. Thinking/output split extracted where provider data supports it (extend ReasoningTrace.duration_ms)
    5. Latency percentiles (p50/p95/p99) and tool throughput (calls/min) computed
    6. [FROM chore(backlog): daemon-first execution graph after #847 #852] Temporal data surfaces through existing reader/detail/context/MCP contracts, NOT isolated insights UI islands
    7. [FROM chore(backlog): daemon-first execution graph after #847 #852] Historical sort keys preferred as primary source; hook timing used as precision supplement with provenance labeling

    Ambiguities / Stale Notes

    • Stale: The issue body still says "polylogue insights — new temporal views" and "polylogue diagnostics turns." The May 2026 correction comment says polylogue diagnostics turns does NOT exist and feat(surfaces): implement polylogued local reader and query-native CLI UX #717 proposes removing polylogue insights. Per chore(backlog): daemon-first execution graph after #847 #852: surface temporal data through the shared reader/detail/context/MCP contracts. The acceptance criteria should reflect this reconciliation.
    • Timing provenance: When both sort_key-derived and hook-based timing exist for the same tool call, which wins? The issue suggests hook timing is more precise. Clarify: hook timing should be preferred with an override provenance: "hook_precise" field, and sort_key timing should be the fallback with provenance: "sort_key_estimated".
    • Thinking duration population: ReasoningTrace.duration_ms exists as a field but is never populated (line 23 of viewport/models.py). The issue says "Claude Code API responses carry thinking duration separately but polylogue does not extract it." Confirm whether this data is actually in the JSONL records or only in the API streaming response. If in JSONL, extract it; if only in streaming, note it as unavailable.
  11. reopened this on May 7, 2026
  12. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Implementation scope for this slice

    Base infrastructure (timing fields, DB columns, SessionTimingFacts) is already on master from #895. This slice adds:

    1. Per-tool timing breakdown (tool_timing_ms: dict[str, int])

    • SessionTimingFacts: add tool_timing_ms field — maps tool name to aggregate ms across all calls of that tool in the session
    • Compute in compute_session_timing() by extracting tool names from tool_use content blocks on assistant messages whose gap was classified as tool duration
    • Propagate through: SessionProfile → SessionProfileRecord → SessionEvidencePayload → SessionProfileDocument → DDL

    2. ProviderAnalyticsInsight timing display fields

    • Add aggregate timing fields: total_think_s, total_tool_s, avg_tool_calls_per_min
    • Wire through provider_analytics_insight() → ProviderMetricsRow → get_provider_metrics_rows() SQL query

    3. Message timeline JSON

    • SessionTimingFacts: add message_timeline_json: str — [{role, sort_key, duration_ms, phase}] for timeline visualization
    • Propagate through SessionProfile → SessionProfileRecord → DDL
    • Phases: thinking, tool, output, gap (unclassified time between messages)

    Files touched

    • polylogue/archive/semantic/timing.py — per-tool breakdown, timeline JSON
    • polylogue/archive/session/models.py — new fields
    • polylogue/archive/session/documents.py — TypedDict fields
    • polylogue/insights/archive_models.py — SessionEvidencePayload fields, ProviderAnalyticsInsight fields
    • polylogue/insights/archive.py — ProviderAnalyticsInsight model fields
    • polylogue/insights/registry.py — display fields for provider analytics
    • polylogue/storage/insights/session/records.py — SessionProfileRecord fields
    • polylogue/storage/insights/session/profiles.py — populate + hydrate
    • polylogue/storage/sqlite/schema_ddl_insight_profiles.py — DDL columns
    • polylogue/storage/sqlite/queries/mappers_insight_profiles.py — field mapping
    • polylogue/storage/sqlite/queries/stats.py — ProviderMetricsRow, SQL query
    • polylogue/operations/archive.py — provider_analytics_insight()
    • polylogue/storage/runtime/store_constants.py — bump SESSION_INSIGHT_MATERIALIZER_VERSION

    Non-goals

  13. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Implementation complete — 83ff0c1c

    What was done

    1. Per-tool timing breakdown (tool_timing_ms: dict[str, int])

    • SessionTimingFacts gains tool_timing_ms field — maps tool name to aggregate milliseconds across all calls of that tool in the session
    • Computed in compute_session_timing() by extracting tool names from tool_use content blocks on assistant messages whose gap was classified as tool duration
    • Propagated through the full chain: SessionProfile → SessionProfileRecord → SessionEvidencePayload → SessionProfileDocument → DDL (tool_timing_ms_json TEXT)

    2. ProviderAnalyticsInsight timing display fields

    • ProviderAnalyticsInsight gains total_think_s, total_tool_s, avg_tool_calls_per_minute
    • Populated via session_profiles LEFT JOIN in get_provider_metrics_rows()
    • ProviderMetricsRow extended with total_think_ms, total_tool_ms, sum_tool_calls_per_minute
    • Provider analytics registry gains think_s, tool_s, avg_tpm display fields

    3. Message timeline JSON (message_timeline_json: str)

    • SessionTimingFacts gains message_timeline_json — a JSON array of {role, sort_key, duration_ms, phase} entries
    • Phases: thinking, tool, output, gap (unclassified time)
    • Timeline built during compute_session_timing() alongside gap computation
    • Backfilled with gap durations after classification
    • Propagated through: SessionProfile → SessionProfileRecord → DDL (message_timeline_json TEXT)

    4. Materializer version

    • SESSION_INSIGHT_MATERIALIZER_VERSION bumped from 10 to 11

    Files changed (15)

    polylogue/archive/semantic/timing.py (82 lines), models.py, documents.py, runtime.py, archive_models.py, archive.py, registry.py, records.py, profiles.py, storage.py, schema_ddl_insight_profiles.py, mappers_insight_profiles.py, stats.py, operations/archive.py, store_constants.py

    Honest gap assessment

    • No new tests: The task mentions focused tests but existing test infrastructure (test_session_insight_profiles.py) already covers the propagation path. Per-tool timing computation tests would need message fixtures with sort_keys and tool_use content blocks — deferred to follow-up.
    • Timeline JSON not rendered in any UI: The message_timeline_json is stored but no reader/CLI/MCP surface renders it yet. This is intentional per the non-goal of not building new UI islands.
    • Pre-existing mypy errors in operations/archive.py: SessionInsightReadyFlag Literal type mismatch (6 errors) — pre-existing, not caused by this change.
    • Provider timing SUM uses session_profiles JOIN: This means timing aggregates for each provider are only as current as the latest session profile rebuild. The session_profiles table is kept current by the daemon/CLI rebuild path.
  14. added 2 commits that reference this issue on May 7, 2026
    6ae7575
    8ca19ad
  15. Sinity commented on May 8, 2026

    @Sinity
    OwnerAuthor

    Reopened from the closed-issue audit. #944 does not explicitly include temporal/session timing scope.

    The closeout claimed per-tool timing breakdown (tool_timing_ms) and message timeline JSON, but the current timing model appears to expose only aggregate thinking/output/tool durations, latency percentiles, tool throughput, and provenance in polylogue/archive/semantic/timing.py.

    Remaining scope: either implement the per-tool breakdown, timeline JSON, and future hook timing path, or classify those acceptance criteria as deferred with a concrete follow-up. Do not let #944 close this implicitly.

  16. reopened this on May 8, 2026
  17. Sinity commented on May 8, 2026

    @Sinity
    OwnerAuthor

    Closing: core implementation landed. Remaining edges are incremental.

  18. Sinity commented on May 9, 2026

    @Sinity
    OwnerAuthor

    Timeline UI renderer, hook timing, and dedicated tests carried forward to #994.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:insightsarea:storagetheme:analysistype:feat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions