Repository navigation
refactor(mcp): sink analysis primitives into insights/ + api facade - #2612
Conversation
Ref polylogue-9e5.24. Co-Authored-By: Claude <[email protected]>
Problem: server_insight_tools.py implemented Pearson correlation, a weighted metadata-similarity heuristic, GROUP-BY aggregation, ISO-week bucketing, a terminal-state severity rank, nearest-rank percentile, and per-key set-diff computation directly in the MCP surface -- unreachable from the CLI or the Python library facade. What changed: - polylogue/insights/archive_rollups.py: extend the existing aggregate reducers with aggregate_session_profiles_by_dimension, workflow_shape_distribution_buckets, abandoned_session_items (+ ABANDONMENT_SEVERITY_RANK), iso_week_bucket_key, and tool_call_latency_distribution_payload (reuses portfolio.py's _percentile nearest-rank algorithm rather than a second one). - polylogue/insights/session_analytics.py (new): pearson_session_correlation, compute_metadata_similarity_candidates, build_session_comparison_row + diff_session_comparison_rows -- primitives with no prior insights/ home. - polylogue/api/insights.py: PolylogueInsightsMixin gains aggregate_sessions, workflow_shape_distribution, find_abandoned_sessions, tool_call_latency_distribution, compare_sessions, find_similar_sessions_by_metadata, correlate_sessions -- each does the fetch (via list_session_profile_insights/list_session_latency_profile_insights) then delegates to the pure insights function, so CLI/library callers reach the same math MCP does. - polylogue/mcp/server_insight_tools.py: the 6 tools (correlate_sessions, find_similar_sessions's metadata lane, aggregate_sessions, workflow_shape_distribution, find_abandoned_sessions, tool_call_latency_distribution, compare_sessions) are now thin wrappers that call the facade method and format the JSON envelope; invalid-input validation still raises from the shared insights functions and MCP catches ValueError to preserve the exact original error envelopes. - tests/unit/api/test_facade_contracts.py: register the 7 new facade methods in BESPOKE_METHODS so the surface-drift gate stays green. Ref polylogue-9e5.24 Co-Authored-By: Claude <[email protected]>
… parity Problem: tests/unit/mcp/test_aggregate_sessions.py and test_session_analysis_primitives.py mocked list_session_profile_insights/ get_session_profile_insight directly and relied on the MCP tool doing GROUP BY/correlation/similarity/diff math inline. That math moved to polylogue/insights/ + the facade in the prior commit, so those mocks no longer exercise anything -- the MCP tool now delegates to a facade method that never runs against a bare MagicMock. What changed: - tests/unit/insights/test_archive_rollups.py (new): direct tests of aggregate_session_profiles_by_dimension, workflow_shape_distribution_buckets, abandoned_session_items, iso_week_bucket_key, and tool_call_latency_distribution_payload -- no MCP/mock scaffolding. - tests/unit/insights/test_session_analytics.py (new): direct tests of pearson_session_correlation, compute_metadata_similarity_candidates, build_session_comparison_row/diff_session_comparison_rows. - tests/unit/api/test_session_analytics_facade.py (new): facade-level I/O-boundary contracts (full-scope fetch, not a page-size cap; correlate_sessions validates before fetching; compare_sessions/ find_similar_sessions_by_metadata argument contracts). - tests/unit/mcp/test_analysis_primitives_facade_parity.py (new): the concrete "no behavior change" proof -- the same fixture profiles fed through the real Polylogue facade method and through the MCP tool's underlying handler (called directly against that same instance) produce byte-identical JSON for all 7 sunk primitives. - tests/unit/mcp/test_aggregate_sessions.py, test_session_analysis_primitives.py, test_insight_shape_tools.py: reduced to thin-wrapper/delegation tests (mock the facade method, assert JSON pass-through and error-envelope mapping) since the math they used to pin now lives elsewhere. Ref polylogue-9e5.24 Co-Authored-By: Claude <[email protected]>
New module added by the analysis-primitives sink (polylogue-9e5.24) needs the topology projection/status regenerated or render all --check fails. Ref polylogue-9e5.24 Co-Authored-By: Claude <[email protected]>
Ref polylogue-9e5.24. Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 28 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughSession analysis math (aggregation, workflow-shape distribution, abandonment detection, latency distribution, comparison, metadata similarity, correlation) is relocated from MCP tool handlers into new pure functions in ChangesSession analytics refactor
Estimated code review effort: 4 (Complex) | ~60 minutes Issue tracking and topology docs updates
Estimated code review effort: 1 (Trivial) | ~5 minutes Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@polylogue/insights/archive_rollups.py`:
- Around line 328-347: Validate group_by at the start of
aggregate_session_profiles_by_dimension before iterating profiles, so an invalid
value raises ValueError even when profiles is empty; mirror the upfront checks
used by workflow_shape_distribution_buckets and abandoned_session_items, and
keep the existing supported-values error message consistent.
In `@polylogue/insights/session_analytics.py`:
- Around line 198-244: The “same origin” bonus in the session scoring logic is
comparing raw source_name values instead of normalized origins. Update the
candidate comparison in the scoring loop (around ref_source/ref_origin and
profile.source_name) to use source_name_to_origin(profile.source_name) against
ref_origin, so different source tokens that map to the same origin still receive
the origin match bonus.
In `@tests/unit/api/test_session_analytics_facade.py`:
- Around line 100-129: Add coverage in test_session_analytics_facade for the
full-scope fetch contract on the remaining analytics entrypoints, especially
tool_call_latency_distribution in the Archive/Poly facade. Mirror the existing
aggregate_sessions and correlate_sessions style by stubbing the underlying fetch
helper (for example list_session_latency_profile_insights) and asserting the
call ignores the caller’s limit and uses a full-scope query instead of a paged
one; use the tool_call_latency_distribution method name and the
list_session_latency_profile_insights symbol to locate the right spot. If
similar regressions are possible, add the same pin for find_abandoned_sessions
and workflow_shape_distribution as well.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 5300bf72-afe8-40bd-ba72-139e082cad72
📒 Files selected for processing (16)
.beads/interactions.jsonl.beads/issues.jsonldocs/plans/topology-target.yamldocs/topology-status.mdpolylogue/api/insights.pypolylogue/insights/archive_rollups.pypolylogue/insights/session_analytics.pypolylogue/mcp/server_insight_tools.pytests/unit/api/test_facade_contracts.pytests/unit/api/test_session_analytics_facade.pytests/unit/insights/test_archive_rollups.pytests/unit/insights/test_session_analytics.pytests/unit/mcp/test_aggregate_sessions.pytests/unit/mcp/test_analysis_primitives_facade_parity.pytests/unit/mcp/test_insight_shape_tools.pytests/unit/mcp/test_session_analysis_primitives.py
| def aggregate_session_profiles_by_dimension( | ||
| profiles: Sequence[SessionProfileInsight], | ||
| group_by: str, | ||
| ) -> dict[str, int]: | ||
| """GROUP BY session count over workflow_shape / terminal_state / origin (#1691). | ||
|
|
||
| Raises ``ValueError`` for an unsupported ``group_by``. | ||
| """ | ||
| buckets: dict[str, int] = {} | ||
| for profile in profiles: | ||
| if group_by == "workflow_shape": | ||
| key = (profile.inference.workflow_shape if profile.inference else None) or "unknown" | ||
| elif group_by == "terminal_state": | ||
| key = (profile.inference.terminal_state if profile.inference else None) or "unknown" | ||
| elif group_by == "origin": | ||
| key = source_name_to_origin(profile.source_name) | ||
| else: | ||
| raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.") | ||
| buckets[key] = buckets.get(key, 0) + 1 | ||
| return buckets |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Validate group_by before the loop to match sibling functions.
aggregate_session_profiles_by_dimension raises ValueError inside the for loop, so an empty profiles list with an invalid group_by silently returns {} instead of raising. This is inconsistent with workflow_shape_distribution_buckets (line 359–361) and abandoned_session_items (line 394–395), which both validate upfront. Downstream, the facade returns a success envelope with empty buckets for an invalid group_by when no profiles match, rather than surfacing the error.
🛡️ Proposed fix: move validation before the loop
def aggregate_session_profiles_by_dimension(
profiles: Sequence[SessionProfileInsight],
group_by: str,
) -> dict[str, int]:
"""GROUP BY session count over workflow_shape / terminal_state / origin (`#1691`).
Raises ``ValueError`` for an unsupported ``group_by``.
"""
+ supported = {"workflow_shape", "terminal_state", "origin"}
+ if group_by not in supported:
+ raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
buckets: dict[str, int] = {}
for profile in profiles:
if group_by == "workflow_shape":
key = (profile.inference.workflow_shape if profile.inference else None) or "unknown"
elif group_by == "terminal_state":
key = (profile.inference.terminal_state if profile.inference else None) or "unknown"
elif group_by == "origin":
key = source_name_to_origin(profile.source_name)
- else:
- raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.")
buckets[key] = buckets.get(key, 0) + 1
return buckets📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def aggregate_session_profiles_by_dimension( | |
| profiles: Sequence[SessionProfileInsight], | |
| group_by: str, | |
| ) -> dict[str, int]: | |
| """GROUP BY session count over workflow_shape / terminal_state / origin (#1691). | |
| Raises ``ValueError`` for an unsupported ``group_by``. | |
| """ | |
| buckets: dict[str, int] = {} | |
| for profile in profiles: | |
| if group_by == "workflow_shape": | |
| key = (profile.inference.workflow_shape if profile.inference else None) or "unknown" | |
| elif group_by == "terminal_state": | |
| key = (profile.inference.terminal_state if profile.inference else None) or "unknown" | |
| elif group_by == "origin": | |
| key = source_name_to_origin(profile.source_name) | |
| else: | |
| raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.") | |
| buckets[key] = buckets.get(key, 0) + 1 | |
| return buckets | |
| def aggregate_session_profiles_by_dimension( | |
| profiles: Sequence[SessionProfileInsight], | |
| group_by: str, | |
| ) -> dict[str, int]: | |
| """GROUP BY session count over workflow_shape / terminal_state / origin (`#1691`). | |
| Raises ``ValueError`` for an unsupported ``group_by``. | |
| """ | |
| supported = {"workflow_shape", "terminal_state", "origin"} | |
| if group_by not in supported: | |
| raise ValueError(f"Unknown group_by: {group_by!r}. Supported: workflow_shape, terminal_state, origin.") | |
| buckets: dict[str, int] = {} | |
| for profile in profiles: | |
| if group_by == "workflow_shape": | |
| key = (profile.inference.workflow_shape if profile.inference else None) or "unknown" | |
| elif group_by == "terminal_state": | |
| key = (profile.inference.terminal_state if profile.inference else None) or "unknown" | |
| elif group_by == "origin": | |
| key = source_name_to_origin(profile.source_name) | |
| buckets[key] = buckets.get(key, 0) + 1 | |
| return buckets |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/insights/archive_rollups.py` around lines 328 - 347, Validate
group_by at the start of aggregate_session_profiles_by_dimension before
iterating profiles, so an invalid value raises ValueError even when profiles is
empty; mirror the upfront checks used by workflow_shape_distribution_buckets and
abandoned_session_items, and keep the existing supported-values error message
consistent.
| ref_evidence = ref_profile.evidence | ||
| ref_inference = ref_profile.inference | ||
| ref_shape = ref_inference.workflow_shape if ref_inference else None | ||
| ref_source = ref_profile.source_name | ||
| ref_origin = source_name_to_origin(ref_source) | ||
| ref_date = ref_evidence.canonical_session_date if ref_evidence else None | ||
| ref_tags = set(ref_evidence.tags) if ref_evidence else set() | ||
|
|
||
| scored: list[tuple[int, dict[str, object]]] = [] | ||
| for profile in candidates: | ||
| if profile.session_id == exclude_session_id: | ||
| continue | ||
| evidence = profile.evidence | ||
| inference = profile.inference | ||
| score = 0 | ||
| reasons: list[str] = [] | ||
|
|
||
| cand_shape = inference.workflow_shape if inference else None | ||
| if ref_shape and cand_shape == ref_shape: | ||
| score += 3 | ||
| reasons.append(f"same workflow_shape: {ref_shape}") | ||
|
|
||
| cand_source = profile.source_name | ||
| if ref_source and cand_source == ref_source: | ||
| score += 1 | ||
| reasons.append(f"same origin: {ref_origin}") | ||
|
|
||
| cand_date = evidence.canonical_session_date if evidence else None | ||
| if ref_date and cand_date: | ||
| try: | ||
| ref_d = date.fromisoformat(ref_date) | ||
| cand_d = date.fromisoformat(cand_date) | ||
| delta = abs((ref_d - cand_d).days) | ||
| if delta <= 3: | ||
| score += 2 | ||
| reasons.append(f"within 3 days (delta={delta})") | ||
| elif delta <= 14: | ||
| score += 1 | ||
| reasons.append(f"within 14 days (delta={delta})") | ||
| except (ValueError, TypeError): | ||
| pass | ||
|
|
||
| cand_tags = set(evidence.tags) if evidence else set() | ||
| overlap = ref_tags & cand_tags | ||
| if overlap: | ||
| score += len(overlap) | ||
| reasons.append(f"{len(overlap)} overlapping tags: {sorted(overlap)}") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect source_name_to_origin to check for many-to-one mappings.
fd -e py sources.py polylogue/core
rg -n -A20 'def source_name_to_origin' polylogue/core/sources.pyRepository: Sinity/polylogue
Length of output: 1291
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- session_analytics snippet ---'
sed -n '198,244p' polylogue/insights/session_analytics.py
echo
echo '--- source_name_to_origin / related mapping ---'
sed -n '314,390p' polylogue/core/sources.py
echo
echo '--- search for origin-related comparison helpers ---'
rg -n 'provider_from_origin|source_name_to_origin|same origin|same workflow_shape|Origin\.AISTUDIO_DRIVE|_CANONICAL_ORIGIN_VALUES' polylogue/core polylogue/insightsRepository: Sinity/polylogue
Length of output: 7407
Compare origins here, not raw source_name. source_name_to_origin() already folds distinct source tokens onto the same origin, so cand_source == ref_source can miss the intended “same origin” bonus for different source names that map to one origin. Use source_name_to_origin(profile.source_name) in the comparison.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/insights/session_analytics.py` around lines 198 - 244, The “same
origin” bonus in the session scoring logic is comparing raw source_name values
instead of normalized origins. Update the candidate comparison in the scoring
loop (around ref_source/ref_origin and profile.source_name) to use
source_name_to_origin(profile.source_name) against ref_origin, so different
source tokens that map to the same origin still receive the origin match bonus.
| @pytest.mark.asyncio | ||
| async def test_correlate_sessions_validates_metrics_before_fetching(tmp_path: Path) -> None: | ||
| poly = _archive(tmp_path) | ||
| poly.list_session_profile_insights = AsyncMock(return_value=[]) # type: ignore[method-assign] | ||
|
|
||
| with pytest.raises(ValueError, match="Unknown metric_x"): | ||
| await poly.correlate_sessions(metric_x="favorite_color", metric_y="word_count") | ||
|
|
||
| poly.list_session_profile_insights.assert_not_awaited() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_compare_sessions_rejects_out_of_range_counts(tmp_path: Path) -> None: | ||
| poly = _archive(tmp_path) | ||
|
|
||
| with pytest.raises(ValueError, match="Need at least 2"): | ||
| await poly.compare_sessions(["only-one"]) | ||
|
|
||
| with pytest.raises(ValueError, match="Too many"): | ||
| await poly.compare_sessions([f"c{i}" for i in range(11)]) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_find_similar_sessions_by_metadata_returns_none_for_unknown_session(tmp_path: Path) -> None: | ||
| poly = _archive(tmp_path) | ||
| poly.get_session_profile_insight = AsyncMock(return_value=None) # type: ignore[method-assign] | ||
|
|
||
| result = await poly.find_similar_sessions_by_metadata("nonexistent") | ||
|
|
||
| assert result is None |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Coverage gap: no full-scope-fetch pin for tool_call_latency_distribution, find_abandoned_sessions, or workflow_shape_distribution.
This module pins the "fetch full scope, not a page limit" contract only for aggregate_sessions and correlate_sessions. The same invariant matters for tool_call_latency_distribution (see the flagged issue in polylogue/api/insights.py — it currently forwards the caller's limit into the fetch query, unlike its siblings) and would have caught that regression had it existed here.
✅ Suggested additional test
`@pytest.mark.asyncio`
async def test_tool_call_latency_distribution_fetches_full_scope_not_a_page_limit(tmp_path: Path) -> None:
poly = _archive(tmp_path)
fetch_mock = AsyncMock(return_value=[])
poly.list_session_latency_profile_insights = fetch_mock # type: ignore[method-assign]
await poly.tool_call_latency_distribution(limit=5)
assert fetch_mock.await_args is not None
assert fetch_mock.await_args.args[0].limit is None🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/api/test_session_analytics_facade.py` around lines 100 - 129, Add
coverage in test_session_analytics_facade for the full-scope fetch contract on
the remaining analytics entrypoints, especially tool_call_latency_distribution
in the Archive/Poly facade. Mirror the existing aggregate_sessions and
correlate_sessions style by stubbing the underlying fetch helper (for example
list_session_latency_profile_insights) and asserting the call ignores the
caller’s limit and uses a full-scope query instead of a paged one; use the
tool_call_latency_distribution method name and the
list_session_latency_profile_insights symbol to locate the right spot. If
similar regressions are possible, add the same pin for find_abandoned_sessions
and workflow_shape_distribution as well.
…nalysis-into-insights # Conflicts: # .beads/interactions.jsonl
Summary
Moves 7 analysis primitives (
correlate_sessions,find_similar_sessions's metadata lane,aggregate_sessions,workflow_shape_distribution,find_abandoned_sessions,tool_call_latency_distribution,compare_sessions) out of the MCP-only surface (mcp/server_insight_tools.py) intoinsights/+ the asyncPolyloguefacade, so CLI/library callers can reach the same math the MCP tools use.Problem
server_insight_tools.pyimplemented analysis math directly in the MCP surface — Pearson correlation, a weighted similarity heuristic, GROUP-BY aggregation + severity-rank ordering + ISO-week bucketing, nearest-rank percentile computation, and per-key set-diff — all unreachable from CLI/library callers.Solution
insights/archive_rollups.pyextended withaggregate_session_profiles_by_dimension,workflow_shape_distribution_buckets,abandoned_session_items(+ABANDONMENT_SEVERITY_RANK),iso_week_bucket_key, andtool_call_latency_distribution_payload(reusesportfolio.py's existing_percentilenearest-rank algorithm rather than a second implementation).insights/session_analytics.pyholdspearson_session_correlation,compute_metadata_similarity_candidates,build_session_comparison_row/diff_session_comparison_rows— primitives with no prior home.api/insights.pygained 7 facade methods delegating to the pure functions above.mcp/server_insight_tools.pyshrank 1181→803 lines; the 6 MCP tools are now thin wrappers with zero residual math.Verification
Independently re-verified (not just the authoring agent's own report):
server_insight_tools.pyfor_pearson/percentile/GROUP BY/severity_rank— zero hits beyond one comment.git showagainst the pre-refactor commit.tests/unit/mcp/test_analysis_primitives_facade_parity.pydirectly and confirmed it genuinely proves what its docstring claims: constructs a realPolyloguefacade, calls the MCP tool's handler directly (not over the wire), assertsjson.loads(raw) == facade_resultacross all 7 primitives.mypy --stricton all 4 touched production files: clean.devtools testacross new/rewired test files (test_archive_rollups.py,test_session_analytics.py,test_session_analytics_facade.py,test_facade_contracts.py,test_analysis_primitives_facade_parity.py,test_aggregate_sessions.py,test_session_analysis_primitives.py,test_insight_shape_tools.py): 316 passed.devtools render all --check: clean (topology projection regenerated for the new module).Ref polylogue-9e5.24.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests