Skip to content

Conversation

chojuninengu
Copy link
Contributor

@chojuninengu chojuninengu commented Apr 29, 2025

This PR addresses issue #108 by improving the application's error handling and session state management with the following changes:

Error Handling Improvements

  • Added specific error types (ValidationError, ProcessingError, QueryEngineError, SessionError)
  • Implemented retry mechanism for API calls with configurable retries and delay
  • Enhanced error messages with more context and better user feedback
  • Added proper cleanup procedures in error cases
  • Improved logging with timestamps and log levels

Session State Management

  • Created dedicated session state initialization function
  • Added proper cleanup procedures for resources
  • Improved state variable organization
  • Added context management for better data handling

Code Organization

  • Separated concerns into dedicated functions
  • Added proper docstrings and type hints
  • Improved function signatures
  • Better error handling patterns

These changes make the application more robust, easier to maintain, and provide better feedback to users when errors occur.

Closes #108

Summary by CodeRabbit

  • New Features

    • Improved error messages with more specific feedback for different error types.
    • Added automatic retry for certain operations to increase reliability.
    • Enhanced session management with better cleanup and reset capabilities.
  • Refactor

    • Streamlined and modularized the user interface for easier navigation and clearer workflows.
    • Improved logging with timestamps and log levels for better user support and troubleshooting.
  • Bug Fixes

    • Resolved issues with session cleanup and error handling during repository loading and chat interactions.

…handling, added new custom exceptions for validation and processing errors, improved session cleanup logic, and refined repository name extraction. Updated logging format for better traceability.
…G application: Introduced dedicated functions for initializing session state and handling repository loading with improved error handling. Enhanced chat message processing and updated logging for better traceability.
Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Walkthrough

The code refactors the Streamlit application in github-rag/app.py by introducing structured exception classes for different error categories, replacing generic exceptions. It adds a retry decorator to handle transient failures and modularizes the application logic into dedicated functions for session state initialization, repository loading, and chat message handling. Session cleanup is centralized in a new function that manages cached files and memory. Error handling is enhanced with specific exceptions, user-friendly messages, and detailed logging. The main application flow is restructured for clarity, and logging is improved with timestamps and log levels.

Changes

File(s) Change Summary
github-rag/app.py Refactored to introduce custom exception classes for validation, processing, query engine, and session errors; added a retry decorator for retrying operations; modularized logic into functions for session state, repository loading, and chat handling; centralized session cleanup; improved error handling and logging; restructured main Streamlit app flow.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant StreamlitApp
    participant RepoProcessor
    participant QueryEngine

    User->>StreamlitApp: Enter GitHub URL & click Load
    StreamlitApp->>RepoProcessor: validate_github_url(url)
    RepoProcessor-->>StreamlitApp: ValidationError? (if invalid)
    StreamlitApp->>RepoProcessor: process_with_gitingets(url) (with retry)
    RepoProcessor-->>StreamlitApp: ProcessingError? (on failure)
    RepoProcessor->>QueryEngine: create_query_engine(content_path, repo_name)
    QueryEngine-->>StreamlitApp: QueryEngineError? (on failure)
    StreamlitApp->>SessionState: Update with repo & engine

    User->>StreamlitApp: Enter chat prompt
    StreamlitApp->>QueryEngine: Query with prompt
    QueryEngine-->>StreamlitApp: Return response
    StreamlitApp->>SessionState: Append chat history

    User->>StreamlitApp: Click Reset
    StreamlitApp->>SessionState: cleanup_session()
Loading

Assessment against linked issues

Objective Addressed Explanation
Standardize error handling, improve error messages, add recovery mechanisms (#108)
Implement retry mechanisms and standardize error handling for API/integration (#108)
Implement proper session cleanup, resource management, and standardize session state (#108)
Address Unsloth/model loading warnings and memory management (#108) No changes related to Unsloth or model loading in this PR.

Possibly related PRs

Suggested reviewers

  • patchy631

Poem

In the garden of code, I hop with delight,
Structured errors now guide us through night.
With retries and logs, the bugs take their flight,
Sessions are tidy, the logic is bright.
Modular bunnies, we leap without fright—
This patch brings stability, all feels just right!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (3)
github-rag/app.py (3)

52-69: Propagate the root cause when exhausting retries

raise last_exception drops the causal chain. Wrap with from last_exception (Ruff B904) to preserve traceback context:

-            raise last_exception
+            raise last_exception from None

This small change greatly improves debuggability.


118-129: Re-raise with cause inside process_with_gitingets

Same Ruff B904 concern – chain the original exception so callers can differentiate between ingest-failures and decorator retries.

-    except Exception as e:
-        logger.error(f"Error processing repository: {str(e)}")
-        raise ProcessingError(f"Failed to process repository: {str(e)}")
+    except Exception as e:
+        logger.error("Error processing repository: %s", e)
+        raise ProcessingError("Failed to process repository") from e
🧰 Tools
🪛 Ruff (0.8.2)

128-128: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


170-186: Session init: preserve cause on failure

Minor, but consistent with earlier comments:

-    except Exception as e:
-        logger.error(f"Error initializing session state: {str(e)}")
-        raise SessionError("Failed to initialize session state")
+    except Exception as e:
+        logger.error("Error initializing session state: %s", e)
+        raise SessionError("Failed to initialize session state") from e
🧰 Tools
🪛 Ruff (0.8.2)

186-186: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68f5e09 and bec6a16.

📒 Files selected for processing (1)
  • github-rag/app.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
github-rag/app.py (1)
github-rag/app_local.py (2)
  • reset_chat (31-34)
  • process_with_gitingets (36-39)
🪛 Ruff (0.8.2)
github-rag/app.py

89-89: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


105-105: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


116-116: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


128-128: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


168-168: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


186-186: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (2)
github-rag/app.py (2)

130-168: Streaming responses may not stringify cleanly

streaming=True returns a generator / StreamingResponse object.
Downstream (handle_chat_message) concatenates it directly into a string which can yield "<generator object …>".

Consider:

-        query_engine = index.as_query_engine(streaming=True)
+        query_engine = index.as_query_engine(streaming=False)

or consume the stream before storing.

🧰 Tools
🪛 Ruff (0.8.2)

168-168: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


252-257: Ensure response is serialisable

If query_engine.query() returns an object, wrap with str() to avoid “Object of type … is not JSON serialisable” errors when Streamlit serialises session state.

-        full_response = f"Repository: {st.session_state.current_repo}\n\n{response}"
+        full_response = f"Repository: {st.session_state.current_repo}\n\n{str(response)}"

Comment on lines 107 to 117
def reset_chat():
"""Reset chat session and clean up resources"""
try:
st.session_state.messages = []
st.session_state.context = None
gc.collect()
cleanup_session()
logger.info("Chat session reset successfully")
except Exception as e:
logger.error(f"Error resetting chat: {str(e)}")
raise GitHubRAGError("Failed to reset chat session")
raise SessionError("Failed to reset chat session")

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

reset_chat should also reset the loaded engine

After a reset the previous query_engine lingers in memory, allowing questions against a supposedly “cleared” session.

-        st.session_state.context = None
+        st.session_state.context = None
+        st.session_state.query_engine = None
📝 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.

Suggested change
def reset_chat():
"""Reset chat session and clean up resources"""
try:
st.session_state.messages = []
st.session_state.context = None
gc.collect()
cleanup_session()
logger.info("Chat session reset successfully")
except Exception as e:
logger.error(f"Error resetting chat: {str(e)}")
raise GitHubRAGError("Failed to reset chat session")
raise SessionError("Failed to reset chat session")
def reset_chat():
"""Reset chat session and clean up resources"""
try:
st.session_state.messages = []
st.session_state.context = None
st.session_state.query_engine = None
cleanup_session()
logger.info("Chat session reset successfully")
except Exception as e:
logger.error(f"Error resetting chat: {str(e)}")
raise SessionError("Failed to reset chat session")
🧰 Tools
🪛 Ruff (0.8.2)

116-116: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines 78 to +90
def get_repo_name(url: str) -> str:
"""Extract repository name from URL"""
try:
return url.split('/')[-1].replace('.git', '')
parts = url.split('/')
if len(parts) < 5:
raise ValidationError("Invalid repository URL format")
repo_name = parts[-1].replace('.git', '')
if not repo_name:
raise ValidationError("Could not extract repository name from URL")
return repo_name
except Exception as e:
raise ValidationError(f"Failed to extract repository name: {str(e)}")

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle trailing slashes and preserve exception context in get_repo_name

  1. URLs ending with a trailing slash (…/repo/) trigger a false “invalid format” error because parts[-1] is empty.
  2. except Exception as e: re-raises without from e, losing the stack.
-        repo_name = parts[-1].replace('.git', '')
+        repo_segment = parts[-1] or parts[-2]          # supports trailing “/”
+        repo_name = repo_segment.replace('.git', '')
@@
-    except Exception as e:
-        raise ValidationError(f"Failed to extract repository name: {str(e)}")
+    except Exception as e:
+        raise ValidationError(
+            f"Failed to extract repository name: {e}"
+        ) from e
📝 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.

Suggested change
def get_repo_name(url: str) -> str:
"""Extract repository name from URL"""
try:
return url.split('/')[-1].replace('.git', '')
parts = url.split('/')
if len(parts) < 5:
raise ValidationError("Invalid repository URL format")
repo_name = parts[-1].replace('.git', '')
if not repo_name:
raise ValidationError("Could not extract repository name from URL")
return repo_name
except Exception as e:
raise ValidationError(f"Failed to extract repository name: {str(e)}")
def get_repo_name(url: str) -> str:
"""Extract repository name from URL"""
try:
parts = url.split('/')
if len(parts) < 5:
raise ValidationError("Invalid repository URL format")
- repo_name = parts[-1].replace('.git', '')
+ repo_segment = parts[-1] or parts[-2] # supports trailing “/”
+ repo_name = repo_segment.replace('.git', '')
if not repo_name:
raise ValidationError("Could not extract repository name from URL")
return repo_name
- except Exception as e:
- raise ValidationError(f"Failed to extract repository name: {str(e)}")
+ except Exception as e:
+ raise ValidationError(
+ f"Failed to extract repository name: {e}"
+ ) from e
🧰 Tools
🪛 Ruff (0.8.2)

89-89: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines +18 to 23
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid duplicating log handlers on every Streamlit rerun

logging.basicConfig() gets executed on every Streamlit script rerun, which may attach multiple handlers and cause duplicated log lines.
Guard the configuration or add handlers only once:

-logging.basicConfig(
-    level=logging.INFO,
-    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
-)
-if not logger.handlers:
-    logger = logging.getLogger(__name__)
+logger = logging.getLogger(__name__)
+if not logger.handlers:
+    logging.basicConfig(
+        level=logging.INFO,
+        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+    )

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +194 to +238
with st.spinner(f"Processing repository {repo_name}..."):
summary, tree, content = process_with_gitingets(github_url)

try:
repo_name = get_repo_name(github_url)
file_key = f"{session_id}-{repo_name}"
query_engine = st.session_state.file_cache.get(file_key)
# Create temporary directory for repository content
with tempfile.TemporaryDirectory() as temp_dir:
content_path = os.path.join(temp_dir, repo_name)
os.makedirs(content_path, exist_ok=True)

if query_engine is None:
raise GitHubRAGError("Please load a repository first!")
# Save repository content
for file_path, file_content in content.items():
file_dir = os.path.dirname(os.path.join(content_path, file_path))
os.makedirs(file_dir, exist_ok=True)
with open(os.path.join(content_path, file_path), 'w', encoding='utf-8') as f:
f.write(file_content)

response = query_engine.query(prompt)
# Create query engine
query_engine = create_query_engine(content_path, repo_name)

if hasattr(response, 'response_gen'):
for chunk in response.response_gen:
if isinstance(chunk, str):
full_response += chunk
message_placeholder.markdown(full_response + "▌")
else:
full_response = str(response)
message_placeholder.markdown(full_response)

message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
# Update session state
st.session_state.query_engine = query_engine
st.session_state.current_repo = repo_name
st.session_state.context = {
'summary': summary,
'tree': tree,
'content': content
}

except GitHubRAGError as e:
st.error(str(e))
logger.error(f"Error in chat processing: {str(e)}")
except Exception as e:
st.error("An unexpected error occurred while processing your query")
logger.error(f"Unexpected error in chat: {str(e)}")
st.success(f"Successfully loaded repository: {repo_name}")
logger.info(f"Repository {repo_name} loaded successfully")

except ValidationError as e:
st.error(f"Validation error: {str(e)}")
logger.warning(f"Validation error for URL {github_url}: {str(e)}")
except ProcessingError as e:
st.error(f"Processing error: {str(e)}")
logger.error(f"Error processing repository {github_url}: {str(e)}")
except QueryEngineError as e:
st.error(f"Query engine error: {str(e)}")
logger.error(f"Error creating query engine for {github_url}: {str(e)}")
except Exception as e:
st.error(f"Unexpected error: {str(e)}")
logger.error(f"Unexpected error processing {github_url}: {str(e)}")
finally:
cleanup_session()

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Path-traversal & binary-file issues when writing repo content

  1. A malicious repo file path such as ../../etc/passwd escapes temp_dir.
  2. Opening files with 'w' fails on binary blobs.
-                for file_path, file_content in content.items():
-                    file_dir = os.path.dirname(os.path.join(content_path, file_path))
+                for file_path, file_content in content.items():
+                    safe_path = os.path.normpath(os.path.join(content_path, file_path))
+                    if not safe_path.startswith(content_path):
+                        logger.warning("Skipping suspicious path: %s", file_path)
+                        continue
+                    file_dir = os.path.dirname(safe_path)
@@
-                    with open(os.path.join(content_path, file_path), 'w', encoding='utf-8') as f:
-                        f.write(file_content)
+                    mode, kwargs = ('wb', {}) if isinstance(file_content, (bytes, bytearray)) else ('w', {'encoding': 'utf-8'})
+                    with open(safe_path, mode, **kwargs) as f:
+                        f.write(file_content)

This mitigates a critical security flaw and handles binary assets gracefully.

📝 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.

Suggested change
with st.spinner(f"Processing repository {repo_name}..."):
summary, tree, content = process_with_gitingets(github_url)
try:
repo_name = get_repo_name(github_url)
file_key = f"{session_id}-{repo_name}"
query_engine = st.session_state.file_cache.get(file_key)
# Create temporary directory for repository content
with tempfile.TemporaryDirectory() as temp_dir:
content_path = os.path.join(temp_dir, repo_name)
os.makedirs(content_path, exist_ok=True)
if query_engine is None:
raise GitHubRAGError("Please load a repository first!")
# Save repository content
for file_path, file_content in content.items():
file_dir = os.path.dirname(os.path.join(content_path, file_path))
os.makedirs(file_dir, exist_ok=True)
with open(os.path.join(content_path, file_path), 'w', encoding='utf-8') as f:
f.write(file_content)
response = query_engine.query(prompt)
# Create query engine
query_engine = create_query_engine(content_path, repo_name)
if hasattr(response, 'response_gen'):
for chunk in response.response_gen:
if isinstance(chunk, str):
full_response += chunk
message_placeholder.markdown(full_response + "▌")
else:
full_response = str(response)
message_placeholder.markdown(full_response)
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
# Update session state
st.session_state.query_engine = query_engine
st.session_state.current_repo = repo_name
st.session_state.context = {
'summary': summary,
'tree': tree,
'content': content
}
except GitHubRAGError as e:
st.error(str(e))
logger.error(f"Error in chat processing: {str(e)}")
except Exception as e:
st.error("An unexpected error occurred while processing your query")
logger.error(f"Unexpected error in chat: {str(e)}")
st.success(f"Successfully loaded repository: {repo_name}")
logger.info(f"Repository {repo_name} loaded successfully")
except ValidationError as e:
st.error(f"Validation error: {str(e)}")
logger.warning(f"Validation error for URL {github_url}: {str(e)}")
except ProcessingError as e:
st.error(f"Processing error: {str(e)}")
logger.error(f"Error processing repository {github_url}: {str(e)}")
except QueryEngineError as e:
st.error(f"Query engine error: {str(e)}")
logger.error(f"Error creating query engine for {github_url}: {str(e)}")
except Exception as e:
st.error(f"Unexpected error: {str(e)}")
logger.error(f"Unexpected error processing {github_url}: {str(e)}")
finally:
cleanup_session()
with st.spinner(f"Processing repository {repo_name}..."):
summary, tree, content = process_with_gitingets(github_url)
# Create temporary directory for repository content
with tempfile.TemporaryDirectory() as temp_dir:
content_path = os.path.join(temp_dir, repo_name)
os.makedirs(content_path, exist_ok=True)
# Save repository content
for file_path, file_content in content.items():
safe_path = os.path.normpath(os.path.join(content_path, file_path))
if not safe_path.startswith(content_path):
logger.warning("Skipping suspicious path: %s", file_path)
continue
file_dir = os.path.dirname(safe_path)
os.makedirs(file_dir, exist_ok=True)
mode, kwargs = (
("wb", {})
if isinstance(file_content, (bytes, bytearray))
else ("w", {"encoding": "utf-8"})
)
with open(safe_path, mode, **kwargs) as f:
f.write(file_content)
# Create query engine
query_engine = create_query_engine(content_path, repo_name)
# Update session state
st.session_state.query_engine = query_engine
st.session_state.current_repo = repo_name
st.session_state.context = {
"summary": summary,
"tree": tree,
"content": content,
}
st.success(f"Successfully loaded repository: {repo_name}")
logger.info(f"Repository {repo_name} loaded successfully")
except ValidationError as e:
finally:
cleanup_session()

Comment on lines +91 to 106
def cleanup_session():
"""Clean up session resources"""
try:
if hasattr(st.session_state, 'file_cache'):
for key, value in st.session_state.file_cache.items():
try:
del value
except Exception as e:
logger.warning(f"Failed to cleanup cache entry {key}: {str(e)}")
st.session_state.file_cache.clear()
gc.collect()
logger.info("Session cleanup completed successfully")
except Exception as e:
raise GitHubRAGError(f"Invalid repository URL: {str(e)}")
logger.error(f"Error during session cleanup: {str(e)}")
raise SessionError(f"Failed to cleanup session: {str(e)}")

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

cleanup_session does not actually remove cached objects

del value only deletes the local reference, not the entry stored in st.session_state.file_cache.
Also adopt from e per Ruff B904.

-        if hasattr(st.session_state, 'file_cache'):
-            for key, value in st.session_state.file_cache.items():
-                try:
-                    del value
-                except Exception as e:
-                    logger.warning(f"Failed to cleanup cache entry {key}: {str(e)}")
-            st.session_state.file_cache.clear()
+        cache = getattr(st.session_state, "file_cache", {})
+        for key in list(cache.keys()):
+            try:
+                del cache[key]
+            except Exception as e:
+                logger.warning("Failed to cleanup cache entry %s: %s", key, e)
📝 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.

Suggested change
def cleanup_session():
"""Clean up session resources"""
try:
if hasattr(st.session_state, 'file_cache'):
for key, value in st.session_state.file_cache.items():
try:
del value
except Exception as e:
logger.warning(f"Failed to cleanup cache entry {key}: {str(e)}")
st.session_state.file_cache.clear()
gc.collect()
logger.info("Session cleanup completed successfully")
except Exception as e:
raise GitHubRAGError(f"Invalid repository URL: {str(e)}")
logger.error(f"Error during session cleanup: {str(e)}")
raise SessionError(f"Failed to cleanup session: {str(e)}")
def cleanup_session():
"""Clean up session resources"""
try:
- if hasattr(st.session_state, 'file_cache'):
- for key, value in st.session_state.file_cache.items():
- try:
- del value
- except Exception as e:
- logger.warning(f"Failed to cleanup cache entry {key}: {str(e)}")
- st.session_state.file_cache.clear()
+ cache = getattr(st.session_state, "file_cache", {})
+ for key in list(cache.keys()):
+ try:
+ del cache[key]
+ except Exception as e:
+ logger.warning("Failed to cleanup cache entry %s: %s", key, e)
gc.collect()
logger.info("Session cleanup completed successfully")
except Exception as e:
- logger.error(f"Error during session cleanup: {str(e)}")
- raise SessionError(f"Failed to cleanup session: {str(e)}")
+ logger.error(f"Error during session cleanup: {str(e)}")
+ raise SessionError(f"Failed to cleanup session: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

105-105: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

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.

Bug Fixes: Error Handling and Stability Improvements

1 participant