🔍 Code Extractor

function debug_session_results

Maturity: 47

Flask debug endpoint that retrieves and categorizes analysis session results, providing detailed file summaries and metadata for troubleshooting purposes.

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1302 - 1343
Complexity:
moderate

Purpose

This debug endpoint is designed for development and troubleshooting of the statistical analysis system. It fetches session results, categorizes generated files (scripts, plots, tables), and provides comprehensive metadata about file counts, content availability, and processing status. It helps developers verify that analysis sessions are generating expected outputs and diagnose issues with file generation or content retrieval.

Source Code

def debug_session_results(session_id):
    """Debug endpoint to compare results from different routes"""
    try:
        # Get results using the main results route logic
        main_results = analysis_service.get_session_results(session_id)
        
        # Get generated files info
        generated_files = analysis_service._get_generated_files_info(session_id)
        
        # Categorize files
        file_summary = {}
        for file_info in generated_files:
            file_type = file_info.get('type', 'unknown')
            if file_type not in file_summary:
                file_summary[file_type] = []
            file_summary[file_type].append({
                'name': file_info.get('name'),
                'has_content': 'content' in file_info,
                'has_preview': 'content_preview' in file_info,
                'content_length': len(file_info.get('content', '')) if file_info.get('content') else 0
            })
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'total_files': len(generated_files),
            'file_summary': file_summary,
            'results_success': main_results.get('success', False),
            'debug_info': {
                'generated_files_count': len(generated_files),
                'script_files': len([f for f in generated_files if f.get('type') == 'script']),
                'plot_files': len([f for f in generated_files if f.get('type') == 'plot']),
                'table_files': len([f for f in generated_files if f.get('type') == 'table'])
            }
        })
        
    except Exception as e:
        logger.error(f"Error in debug results for session {session_id}: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: String identifier for the analysis session. This ID is used to retrieve session-specific results and generated files from the analysis service. Must be a valid session ID that exists in the system.

Return Value

Returns a Flask JSON response object. On success (HTTP 200), returns a dictionary containing: 'success' (boolean), 'session_id' (string), 'total_files' (integer count), 'file_summary' (dictionary categorizing files by type with metadata), 'results_success' (boolean indicating if main results retrieval succeeded), and 'debug_info' (dictionary with file type counts). On error (HTTP 500), returns a dictionary with 'success' (False) and 'error' (string error message).

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# This is a Flask route endpoint, typically called via HTTP request
# Example HTTP request:
# GET /debug/session/abc123-session-id/results

# Example programmatic usage (within Flask app context):
from flask import Flask
from services import StatisticalAnalysisService
import logging

app = Flask(__name__)
analysis_service = StatisticalAnalysisService()
logger = logging.getLogger(__name__)

@app.route('/debug/session/<session_id>/results')
def debug_session_results(session_id):
    # Function implementation here
    pass

# To test the endpoint:
# curl http://localhost:5000/debug/session/my-session-123/results

# Expected response format:
# {
#   "success": true,
#   "session_id": "my-session-123",
#   "total_files": 5,
#   "file_summary": {
#     "script": [{"name": "analysis.py", "has_content": true, "has_preview": true, "content_length": 1024}],
#     "plot": [{"name": "chart.png", "has_content": true, "has_preview": false, "content_length": 2048}]
#   },
#   "results_success": true,
#   "debug_info": {
#     "generated_files_count": 5,
#     "script_files": 2,
#     "plot_files": 2,
#     "table_files": 1
#   }
# }

Best Practices

  • This endpoint should only be enabled in development/debug environments, not in production
  • Ensure proper authentication/authorization is added before exposing this endpoint
  • The endpoint relies on analysis_service being properly initialized in the module scope
  • Session IDs should be validated to prevent unauthorized access to session data
  • Consider adding rate limiting to prevent abuse of this debug endpoint
  • The endpoint catches all exceptions and returns 500 errors, which is appropriate for debugging but may need more specific error handling in production
  • File content lengths are calculated which could be memory-intensive for large files; consider adding size limits
  • The logger must be configured before this function is called to ensure error logging works properly

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_results 78.8% similar

    Flask route handler that retrieves and returns comprehensive analysis results for a given session, including summary data, generated files, interpretations, and execution tracking information.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_results_v1 76.0% similar

    Flask route handler that retrieves and returns statistical analysis results, generated files, and AI-generated interpretations for a given session ID.

    From: /tf/active/vicechatdev/smartstat/app.py
  • function debug_analysis 72.1% similar

    Flask route handler that debugs and retries a failed analysis step by delegating to the analysis service and returning the debug result as JSON.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_session_status 69.3% similar

    Flask API endpoint that retrieves the current status and summary of an analysis session by its ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function view_session 69.2% similar

    Flask route handler that retrieves and displays an analysis session by its ID, rendering the session details in a template or redirecting on error.

    From: /tf/active/vicechatdev/full_smartstat/app.py
← Back to Browse