Skip to content

Conversation

@yichieh-lu
Copy link
Collaborator

@yichieh-lu yichieh-lu commented Sep 1, 2025

Summary by CodeRabbit

  • New Features
    • SQL execution errors are surfaced in chart and chart-adjustment results with clear error types and messages in metadata.
  • Bug Fixes
    • Chart generation now stops immediately when SQL execution reports an error, returning a failed state with details.
  • Refactor
    • More consistent handling and propagation of SQL execution results across services for clearer, unified responses.

@yichieh-lu yichieh-lu self-assigned this Sep 1, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Renames a local return variable in SQL utility, makes the SQL executor propagate optional error_message from Engine.execute_sql, and updates chart services to short-circuit and return failed results with metadata when that SQL error is present. No public API signatures changed.

Changes

Cohort / File(s) Summary of changes
SQL utils: variable rename
wren-ai-service/src/pipelines/generation/utils/sql.py
Renamed local return variable from status to has_data in both dry-run and normal paths; no behavioral changes.
SQL executor: propagate SQL addition
wren-ai-service/src/pipelines/retrieval/sql_executor.py
Unpacks third return value as addition instead of _; if addition contains error_message, returns {"results": data, "error_message": ...}, otherwise {"results": data}.
Web chart services: early failure on SQL error
wren-ai-service/src/web/v1/services/chart.py, wren-ai-service/src/web/v1/services/chart_adjustment.py
Capture execute_sql_result, extract sql_data and optional error_message; on error_message present, mark query failed with code OTHERS, store error_type/error_message in metadata, and return early; otherwise continue chart generation.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Web as Web Service (chart / chart_adjustment)
  participant Retriever as SQL Executor (DataFetcher)
  participant Engine as Engine.execute_sql

  Client->>Web: Request (contains SQL)
  Web->>Retriever: run(sql)
  Retriever->>Engine: execute_sql(sql)
  Engine-->>Retriever: (has_data, data, addition{error_message?})
  alt addition.error_message present
    Retriever-->>Web: {results: data, error_message}
    Web->>Web: set status=failed (OTHERS), add metadata (error_type, error_message)
    Web-->>Client: Failure response with error metadata
  else no error_message
    Retriever-->>Web: {results: data}
    Web->>Web: proceed to generating -> finished / NO_CHART
    Web-->>Client: Chart result (success or NO_CHART failure)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • cyyeh
  • imAsterSun

Poem

A rabbit reads the SQL hop—so spry,
If errors scurry in, we note and sigh.
We mark "OTHERS", tuck the message tight,
Pause the charts until the fields are right.
Hops and logs and carrots — code done right! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 149a698 and 9dee608.

📒 Files selected for processing (2)
  • wren-ai-service/src/web/v1/services/chart.py (1 hunks)
  • wren-ai-service/src/web/v1/services/chart_adjustment.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • wren-ai-service/src/web/v1/services/chart.py
  • wren-ai-service/src/web/v1/services/chart_adjustment.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: pytest
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/wren-ai-service/timout-in-sql-executor

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
wren-ai-service/src/pipelines/generation/utils/sql.py (1)

83-86: Align Engine.execute_sql interface with its 3-value return
Engine.execute_sql in wren-ai-service/src/core/engine.py is declared to return only (success: bool, payload: Optional[Dict[str, Any]]), but its implementations and call sites unpack three values (success, data, addition). Update the base interface’s return annotation to include the third element (or switch to a NamedTuple/TypedDict) so it matches provider implementations and all await engine.execute_sql(…) call sites.

🧹 Nitpick comments (6)
wren-ai-service/src/pipelines/generation/utils/sql.py (2)

119-124: Defensive access on addition + retain correlation for tracing.

After defaulting addition to {}, this block becomes safe. Consider also populating invalid_generation_result["correlation_id"] with "" when absent to keep a stable schema (your code already does this later).


143-162: Consistent error typing and naming.

  • Naming: in dry-run, has_data really means “request succeeded,” not “has data.” Consider ok for clarity.
  • Error codes: elsewhere (chart services) all SQL executor failures map to "OTHERS". Here you emit "TIME_OUT"/"DRY_RUN"/"PREVIEW_EMPTY_DATA"/"PREVIEW_FAILED". Consider unifying or mapping to a smaller, consistent set to simplify client handling.

Proposed minimal rename (optional):

-                    if has_data:
+                    if ok:
                         valid_generation_result = {
wren-ai-service/src/pipelines/retrieval/sql_executor.py (1)

40-42: Include correlation_id in the return; update component outputs accordingly.

You already return an extra key (error_message) not declared in @component.output_types. Add correlation_id now for traceability and declare both keys for future-proofing.

Apply:

-            if addition.get("error_message"):
-                return {"results": data, "error_message": addition.get("error_message")}
-            return {"results": data}
+            if addition.get("error_message"):
+                return {
+                    "results": data,
+                    "error_message": addition.get("error_message"),
+                    "correlation_id": addition.get("correlation_id", ""),
+                }
+            return {
+                "results": data,
+                "correlation_id": addition.get("correlation_id", ""),
+            }

And adjust the decorator:

-    @component.output_types(
-        results=Optional[Dict[str, Any]],
-    )
+    @component.output_types(
+        results=Optional[Dict[str, Any]],
+        error_message=Optional[str],
+        correlation_id=str,
+    )
wren-ai-service/src/web/v1/services/chart.py (1)

120-131: Surface correlation_id in state and metadata for easier debugging.

If you adopt the suggested change in DataFetcher.run, include the correlation ID here.

Apply:

-            if error_message:
+            if error_message:
                 self._chart_results[query_id] = ChartResultResponse(
                     status="failed",
                     error=ChartError(
                         code="OTHERS",
                         message=error_message,
                     ),
-                    trace_id=trace_id,
+                    trace_id=trace_id,
                 )
                 results["metadata"]["error_type"] = "OTHERS"
                 results["metadata"]["error_message"] = error_message
+                results["metadata"]["correlation_id"] = execute_sql_result.get("correlation_id", "")
                 return results
wren-ai-service/src/web/v1/services/chart_adjustment.py (2)

119-127: Minor: also return and carry correlation_id for parity with Chart flow.

If DataFetcher.run returns correlation_id, keep it in results["metadata"] to aid support/debugging.

Apply:

             execute_sql_result = (
                 await self._pipelines["sql_executor"].run(
                     sql=chart_adjustment_request.sql,
                     project_id=chart_adjustment_request.project_id,
                 )
             )["execute_sql"]
 
             sql_data = execute_sql_result["results"]
             error_message = execute_sql_result.get("error_message", None)
+            correlation_id = execute_sql_result.get("correlation_id", "")

129-141: Include correlation_id in failure metadata.

Parity with other services and quicker incident correlation.

Apply:

                 self._chart_adjustment_results[
                     query_id
                 ] = ChartAdjustmentResultResponse(
                     status="failed",
                     error=ChartAdjustmentError(
                         code="OTHERS",
                         message=error_message,
                     ),
                 )
                 results["metadata"]["error_type"] = "OTHERS"
                 results["metadata"]["error_message"] = error_message
+                results["metadata"]["correlation_id"] = correlation_id
                 return results
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 912f677 and 149a698.

📒 Files selected for processing (4)
  • wren-ai-service/src/pipelines/generation/utils/sql.py (2 hunks)
  • wren-ai-service/src/pipelines/retrieval/sql_executor.py (1 hunks)
  • wren-ai-service/src/web/v1/services/chart.py (1 hunks)
  • wren-ai-service/src/web/v1/services/chart_adjustment.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
wren-ai-service/src/pipelines/generation/utils/sql.py (2)
wren-ai-service/src/core/engine.py (1)
  • execute_sql (20-27)
wren-ai-service/src/providers/engine/wren.py (3)
  • execute_sql (26-107)
  • execute_sql (127-175)
  • execute_sql (246-296)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: pytest
  • GitHub Check: pytest
  • GitHub Check: pytest
  • GitHub Check: Analyze (go)

Copy link
Member

@cyyeh cyyeh left a comment

Choose a reason for hiding this comment

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

lgtm

@cyyeh cyyeh merged commit 93a0059 into main Sep 2, 2025
12 checks passed
@cyyeh cyyeh deleted the fix/wren-ai-service/timout-in-sql-executor branch September 2, 2025 04:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants