Skip to content

fix(core): disable DecorrelatePredicateSubquery rule#1297

Merged
douenergy merged 1 commit intoCanner:mainfrom
goldmedal:fix/disable-decorrelate-subquery
Aug 22, 2025
Merged

fix(core): disable DecorrelatePredicateSubquery rule#1297
douenergy merged 1 commit intoCanner:mainfrom
goldmedal:fix/disable-decorrelate-subquery

Conversation

@goldmedal
Copy link
Copy Markdown
Contributor

@goldmedal goldmedal commented Aug 22, 2025

DecorrelatePredicateSubquery will generate an invalid plan for the DataFusion Unparser.

Summary by CodeRabbit

  • Bug Fixes

    • Disabled a transformation that decorrelates predicate subqueries during SQL export, resulting in more stable and readable SQL for queries using IN/EXISTS patterns.
  • Tests

    • Added a snapshot test to validate SQL output when predicate subqueries are present in Unparse mode.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

Removed DecorrelatePredicateSubquery from the unparse optimization rule set in mdl/context.rs. Added an async test in mdl/mod.rs to validate behavior when analyzing SQL with an IN-subquery under Unparse mode via snapshot assertion. No public APIs changed.

Changes

Cohort / File(s) Summary
Unparse optimization rules
wren-core/core/src/mdl/context.rs
Removed import and usage of DecorrelatePredicateSubquery from optimize_rule_for_unparsing; left explanatory comments; other rules unchanged.
Tests
wren-core/core/src/mdl/mod.rs
Added async test test_disable_decorrelate_predicate_subquery asserting snapshot of analyzed SQL with IN-subquery under Mode::Unparse.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant T as Test
  participant M as AnalyzedWrenMDL
  participant C as Context (Unparse)
  participant O as Optimizer

  T->>M: analyze(manifest, Mode::Unparse, sql)
  M->>C: build unparse optimization rules
  Note over C: DecorrelatePredicateSubquery is excluded
  C->>O: provide rule set (without decorrelation)
  O-->>M: optimized plan for unparsing
  M-->>T: transformed SQL (snapshot assertion)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

core, rust

Suggested reviewers

  • douenergy

Poem

A nibble of rules, a hop through the hay,
I tucked one decorrelator neatly away.
Tests thump-thump with snapshots bright,
Unparse moon glows soft tonight.
Ears up, code clean—hippity hooray! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@github-actions github-actions bot added core rust Pull requests that update Rust code labels Aug 22, 2025
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (3)
wren-core/core/src/mdl/context.rs (2)

228-229: Add a tracking note (with link) so we remember to re-enable later.

Please enrich the comment with a reference to this PR (and ideally the upstream tracker) to make reversal straightforward when Unparser supports decorrelated predicate subqueries.

Apply this diff to improve the inline comment:

-        // Unparser has some issues for handling decorrelated plans
-        // Arc::new(DecorrelatePredicateSubquery::new()),
+        // Unparser currently has issues handling decorrelated predicate-subquery plans.
+        // Temporarily disabled to prevent invalid SQL emission.
+        // TODO(wren-engine#1297): Re-enable once upstream Unparser can serialize these plans correctly.
+        // Arc::new(DecorrelatePredicateSubquery::new()),

228-229: Optional: make this toggleable via a session/config flag.

If you foresee testing with engines that can handle the decorrelated shape, consider gating this rule behind a config (e.g., x-wren-enable-decorrelate-subquery) so we can flip it without a code change.

wren-core/core/src/mdl/mod.rs (1)

1036-1067: Broaden coverage: add correlated IN and NOT IN cases.

Two additional tests will harden against future optimizer changes:

  • Correlated IN: WHERE t.a IN (SELECT u.a FROM t u WHERE u.b = t.b)
  • NOT IN null-semantics: WHERE c NOT IN (SELECT c FROM ...), ensuring Unparser retains subquery form.

Example additions (place near this test):

#[tokio::test]
async fn test_disable_decorrelate_predicate_subquery_correlated_in() -> Result<()> {
    let manifest = ManifestBuilder::new()
        .catalog("wren").schema("test")
        .model(
            ModelBuilder::new("t")
                .table_reference("t")
                .column(ColumnBuilder::new("a", "int").build())
                .column(ColumnBuilder::new("b", "int").build())
                .build(),
        )
        .build();
    let analyzed_mdl = Arc::new(AnalyzedWrenMDL::analyze(manifest, Arc::new(HashMap::default()), Mode::Unparse)?);
    let sql = r#"SELECT * FROM wren.test.t AS t1 WHERE t1.b IN (SELECT t2.b FROM wren.test.t AS t2 WHERE t2.a = t1.a)"#;
    let actual = transform_sql_with_ctx(&SessionContext::new(), Arc::clone(&analyzed_mdl), &[], Arc::new(HashMap::new()), sql).await?;
    // Assert the predicate remains an IN-subquery (not rewritten to a join)
    assert!(actual.contains("IN (SELECT"));
    Ok(())
}

#[tokio::test]
async fn test_disable_decorrelate_predicate_subquery_not_in() -> Result<()> {
    let manifest = ManifestBuilder::new()
        .catalog("wren").schema("test")
        .model(
            ModelBuilder::new("t")
                .table_reference("t")
                .column(ColumnBuilder::new("c", "int").build())
                .build(),
        )
        .build();
    let analyzed_mdl = Arc::new(AnalyzedWrenMDL::analyze(manifest, Arc::new(HashMap::default()), Mode::Unparse)?);
    let sql = r#"SELECT * FROM wren.test.t WHERE c NOT IN (SELECT c FROM wren.test.t)"#;
    let actual = transform_sql_with_ctx(&SessionContext::new(), Arc::clone(&analyzed_mdl), &[], Arc::new(HashMap::new()), sql).await?;
    // Assert NOT IN subquery shape is preserved
    assert!(actual.contains("NOT IN (SELECT"));
    Ok(())
}
📜 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 92a1c7d and abd1d82.

📒 Files selected for processing (2)
  • wren-core/core/src/mdl/context.rs (1 hunks)
  • wren-core/core/src/mdl/mod.rs (1 hunks)
⏰ 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). (6)
  • GitHub Check: cargo test (macos-aarch64)
  • GitHub Check: cargo test (win64)
  • GitHub Check: cargo test (macos)
  • GitHub Check: cargo check
  • GitHub Check: ci
  • GitHub Check: test
🔇 Additional comments (3)
wren-core/core/src/mdl/context.rs (2)

228-229: Disabling DecorrelatePredicateSubquery for Unparse mode looks correct.

This avoids generating semi-join style plans that the Unparser cannot reliably serialize. Given ScalarSubqueryToJoin is already disabled, keeping IN-subqueries intact is the safer path for SQL generation.


228-229: No remaining references to DecorrelatePredicateSubquery

A search for any live occurrences of DecorrelatePredicateSubquery only turned up the commented‐out line in context.rs (lines 227–231). There are no active imports or usages elsewhere in the repo, so this cleanup is complete.

wren-core/core/src/mdl/mod.rs (1)

1036-1067: Good targeted snapshot test to assert IN-subquery remains undecorrelated.

Covers the intended regression surface and matches the Unparse-mode contract. Nice use of Unicode identifiers to exercise quoting paths.

@goldmedal goldmedal requested a review from douenergy August 22, 2025 09:25
@douenergy douenergy merged commit 2d99a91 into Canner:main Aug 22, 2025
14 checks passed
nhaluc1005 pushed a commit to nhaluc1005/text2sql-practice that referenced this pull request Apr 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants