Skip to content

refactor: shared session load path for session and export APIs#125

Merged
wpak-ai merged 3 commits into
masterfrom
refactor/session-handler-decorator
Jul 9, 2026
Merged

refactor: shared session load path for session and export APIs#125
wpak-ai merged 3 commits into
masterfrom
refactor/session-handler-decorator

Conversation

@clean6378-max-it

@clean6378-max-it clean6378-max-it commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

Closes #119

get_session, get_session_stats, and export_session all repeated the same steps: resolve the projects dir, safe_join the JSONL path, check the file exists, load through the cache, run exclusion rules, and map parse failures to structured ErrorCode responses. The exception tuple was also defined twice (_PARSE_ERRORS in api/sessions.py and EXPORT_ERRORS in utils/export_engine.py), so any change to that list had to be kept in sync by hand.

This branch pulls that flow into api/_session_handlers.py (resolve_loaded_session and compute_stats_or_error) and defines SESSION_LOAD_ERRORS once in utils/session_errors.py. export_engine.EXPORT_ERRORS now aliases that tuple. The three route handlers are thin wrappers around the shared helpers. HTTP status codes, error messages, and the issue #25 no-leakage behavior are unchanged.

To sanity-check: run pytest tests/test_error_propagation.py tests/test_api_routes.py tests/test_export_api_bulk.py, then full pytest, mypy -p api -p utils -p models, and ruff check ..

Summary by CodeRabbit

  • Bug Fixes
    • Improved session, session-stats, and export-session error handling with consistent responses for invalid paths, missing sessions, excluded sessions, and parse/load failures.
    • Prevented internal exception details from leaking into API responses.
    • Refined which failures are classified as parse vs internal errors during export.
  • Refactor
    • Centralized session resolution and stats computation, and updated session-related API endpoints to use shared helpers.
  • Tests
    • Updated monkeypatch targets and expanded regression coverage for parse-failure and exclusion-failure paths, including the export-session endpoint.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fa2d66e6-5a40-47f1-8ec3-36da46f59fa7

📥 Commits

Reviewing files that changed from the base of the PR and between b6915ba and 1b29cca.

📒 Files selected for processing (1)
  • tests/test_error_propagation.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_error_propagation.py

📝 Walkthrough

Walkthrough

This PR adds shared session-resolution helpers, refactors session and export routes to use them, and updates error-propagation tests. It also centralizes session-load exception classification in a shared constant reused by export error handling.

Changes

Session handler consolidation

Layer / File(s) Summary
Shared session helpers
utils/session_errors.py, api/_session_handlers.py
Adds SESSION_LOAD_ERRORS, LoadedSession, resolve_loaded_session, and compute_stats_or_error.
Session routes delegation
api/sessions.py
Delegates session lookup and stats endpoints to the shared helpers.
Export route delegation
api/export_api.py, utils/export_engine.py
Delegates export-session loading and stats computation to the shared helpers and reuses the shared session-load error tuple.
Error propagation tests
tests/test_api_routes.py, tests/test_error_propagation.py
Updates monkeypatch targets and adds exclusion-failure coverage for session and export routes.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant sessions.py
  participant api._session_handlers
  participant get_cached_session
  participant compute_stats_or_error

  Client->>sessions.py: request session or stats
  sessions.py->>api._session_handlers: resolve_loaded_session(project, session_id)
  api._session_handlers->>get_cached_session: load cached session
  get_cached_session-->>api._session_handlers: session or exception
  api._session_handlers-->>sessions.py: LoadedSession or error response
  sessions.py->>api._session_handlers: compute_stats_or_error(session, session_id)
  api._session_handlers-->>sessions.py: stats dict or error response
  sessions.py-->>Client: JSON response or error response
Loading

Possibly related PRs

Suggested reviewers: timon0305, wpak-ai

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the refactor to a shared session-loading path across session and export APIs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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 refactor/session-handler-decorator

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

Comment thread api/_session_handlers.py
Comment thread utils/session_errors.py Outdated
Comment thread tests/test_error_propagation.py

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
tests/test_error_propagation.py (1)

204-226: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Export endpoint test coverage only covers the exclusion-raise path, not the parse-failure path.

TestExportSessionErrorBody only exercises is_session_excluded raising. The sibling classes (TestGetSessionErrorBody, TestGetSessionStatsErrorBody) each also test a get_cached_session raise (KeyError/ValueError) to confirm no leakage on parse failures. Adding an equivalent test for the export endpoint would keep coverage symmetric across all three routes sharing resolve_loaded_session.

Suggested additional test
    def test_500_on_parse_failure_does_not_leak_class_name(
        self, tmp_path, export_client, monkeypatch
    ):
        _write_session(tmp_path, "proj", "abc", "{}")

        def _boom(*args, **kwargs):
            raise KeyError("internal_secret_field_id")

        monkeypatch.setattr("api._session_handlers.get_cached_session", _boom)

        resp = export_client.get("/api/export/session/proj/abc")
        assert resp.status_code == 500
        body = resp.get_json()
        assert body.get("error") == "Failed to parse session"
        assert "internal_secret_field_id" not in json.dumps(body)
        _assert_no_class_name_leak(json.dumps(body))
🤖 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/test_error_propagation.py` around lines 204 - 226, Add a parse-failure
coverage test for ExportSessionErrorBody to match the other session error-body
suites. In TestExportSessionErrorBody, add a case that patches
get_cached_session to raise a parsing-related error (for example via
api._session_handlers.get_cached_session) and verifies
/api/export/session/proj/abc still returns 500 with the same sanitized error
body. Keep the existing exclusion-raise test, and ensure the new test checks
that sensitive details and class names do not leak from
resolve_loaded_session/export_bp handling.
🤖 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.

Nitpick comments:
In `@tests/test_error_propagation.py`:
- Around line 204-226: Add a parse-failure coverage test for
ExportSessionErrorBody to match the other session error-body suites. In
TestExportSessionErrorBody, add a case that patches get_cached_session to raise
a parsing-related error (for example via
api._session_handlers.get_cached_session) and verifies
/api/export/session/proj/abc still returns 500 with the same sanitized error
body. Keep the existing exclusion-raise test, and ensure the new test checks
that sensitive details and class names do not leak from
resolve_loaded_session/export_bp handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c6d532b1-ae15-4104-ae77-74c670efe76b

📥 Commits

Reviewing files that changed from the base of the PR and between f333e93 and b6915ba.

📒 Files selected for processing (3)
  • api/_session_handlers.py
  • tests/test_error_propagation.py
  • utils/session_errors.py
💤 Files with no reviewable changes (1)
  • utils/session_errors.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/_session_handlers.py

@clean6378-max-it clean6378-max-it requested a review from wpak-ai July 9, 2026 20:25
@wpak-ai wpak-ai merged commit 964813f into master Jul 9, 2026
16 checks passed
@wpak-ai wpak-ai deleted the refactor/session-handler-decorator branch July 9, 2026 22:04
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.

claude-code-chat-browser: Shared session-handler decorator for resolve/load/exclude/error pattern

3 participants