Skip to content

Conversation

@arbiv
Copy link
Contributor

@arbiv arbiv commented Jun 18, 2025

null

Summary by CodeRabbit

  • Bug Fixes
    • Improved compatibility with dbt-databricks version 1.10.2 to prevent errors related to unsupported object types or missing configuration keys, ensuring smoother operation and enhanced stability.
    • Applied a one-time compatibility patch for Databricks integration to enhance reliability during dependency installation and runtime.

@linear
Copy link

linear bot commented Jun 18, 2025

@arbiv arbiv had a problem deploying to elementary_test_env June 18, 2025 16:21 — with GitHub Actions Error
@coderabbitai
Copy link

coderabbitai bot commented Jun 18, 2025

"""

Walkthrough

The CommandLineDbtRunner class was updated to apply a one-time compatibility patch for dbt-databricks version 1.10.2 during initialization. A new module provides safe wrapper functions to handle unsupported object types and missing attributes, which are monkey-patched onto dbt-databricks to prevent runtime errors.

Changes

File(s) Change Summary
elementary/clients/dbt/command_line_dbt_runner.py Added class variable _dbx_patch_applied; updated __init__ to call apply_databricks_patch() once.
elementary/clients/dbt/databricks_patch.py Added new module with safe accessor functions and apply_databricks_patch() to monkey-patch dbt-databricks.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CommandLineDbtRunner
    participant DatabricksPatch
    participant dbt.adapters.databricks

    User->>CommandLineDbtRunner: Instantiate
    CommandLineDbtRunner->>CommandLineDbtRunner: __init__()
    CommandLineDbtRunner->>DatabricksPatch: apply_databricks_patch()
    DatabricksPatch->>dbt.adapters.databricks: Import parse_model module
    DatabricksPatch->>dbt.adapters.databricks: Monkey-patch functions with safe wrappers
    dbt.adapters.databricks-->>DatabricksPatch: Patch success/failure
    DatabricksPatch-->>CommandLineDbtRunner: Return patch result
Loading

Poem

In the warren of code, a patch hops in,
To help dbt-databricks safely begin.
Wrappers applied with a gentle touch,
Catching errors that once hurt so much.
Now logs keep secrets, exceptions are few—
A clever fix from the rabbit crew! 🐇✨
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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.

@github-actions
Copy link
Contributor

👋 @arbiv
Thank you for raising your pull request.
Please make sure to add tests and document all user-facing changes.
You can do this by editing the docs files in this pull request.

@arbiv arbiv force-pushed the ele-4632-databricks-cli-failure branch from 62d7976 to b666dbe Compare June 18, 2025 16:21
@arbiv arbiv temporarily deployed to elementary_test_env June 18, 2025 16:21 — with GitHub Actions Inactive
Copy link

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8945614 and b666dbe.

📒 Files selected for processing (1)
  • elementary/clients/dbt/command_line_dbt_runner.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.11.9)
elementary/clients/dbt/command_line_dbt_runner.py

330-330: logging imported but unused; consider using importlib.util.find_spec to test for availability

(F401)


340-340: f-string without any placeholders

Remove extraneous f prefix

(F541)

🪛 GitHub Actions: Run pre-commit hooks
elementary/clients/dbt/command_line_dbt_runner.py

[error] 329-329: flake8: 'logging' imported but unused (F401)


[error] 342-342: flake8: f-string is missing placeholders (F541)


[error] 331-331: mypy: Cannot find implementation or library stub for module named "dbt.adapters.databricks" [import-not-found]


[error] pre-commit hook 'black' reformatted the file. Run 'black --write' to fix code style issues.


[error] pre-commit hook 'isort' modified the file to fix import sorting.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test / test

@arbiv arbiv had a problem deploying to elementary_test_env June 18, 2025 16:47 — with GitHub Actions Error
@arbiv arbiv had a problem deploying to elementary_test_env June 18, 2025 16:50 — with GitHub Actions Failure
@arbiv arbiv temporarily deployed to elementary_test_env June 18, 2025 17:38 — with GitHub Actions Inactive
@arbiv arbiv had a problem deploying to elementary_test_env June 18, 2025 19:04 — with GitHub Actions Error
@arbiv arbiv temporarily deployed to elementary_test_env June 18, 2025 19:08 — with GitHub Actions Inactive
Copy link

@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: 3

🧹 Nitpick comments (2)
elementary/clients/dbt/databricks_patch.py (2)

13-31: Consider making the default catalog configurable.

Hard-coding "unity" as the default catalog might not be appropriate for all Databricks environments, as some users might be using different catalog names.

-def safe_catalog_name(model: Any) -> str:
+def safe_catalog_name(model: Any, default_catalog: str = "unity") -> str:
     try:
         if is_unsupported_object(model):
             logger.debug(
                 "Received unsupported object type for catalog_name, using unity as default"
             )
-            return "unity"
+            return default_catalog
         # Handle RelationConfig objects
         if hasattr(model, "config") and model.config and hasattr(model.config, "get"):
             catalog = model.config.get("catalog")
             if catalog:
                 return catalog
         # Fallback to unity catalog
-        return "unity"
+        return default_catalog
     except Exception as e:
         logger.debug(
             f"Failed to parse catalog name from model: {e}. Using unity as default."
         )
-        return "unity"
+        return default_catalog

1-124: Consider the maintainability implications of monkey patching.

While this patch addresses immediate compatibility issues, monkey patching can make debugging difficult and may mask underlying problems. Consider documenting the specific issues this patch addresses and establishing a plan for its removal once the upstream issues are resolved.

Add comprehensive documentation about:

  1. The specific dbt-databricks 1.10.2 issues this patch addresses
  2. Expected timeline for upstream fixes
  3. Instructions for testing whether the patch is still needed
  4. Monitoring to detect if the patch causes unintended side effects

Consider implementing a feature flag or configuration option to enable/disable the patch for easier testing and rollback if needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a2a8c7 and 8176892.

📒 Files selected for processing (2)
  • elementary/clients/dbt/command_line_dbt_runner.py (3 hunks)
  • elementary/clients/dbt/databricks_patch.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • elementary/clients/dbt/command_line_dbt_runner.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: code-quality

Comment on lines +8 to +10
def is_unsupported_object(model: Any) -> bool:
"""Check if the object is a Macro or other unsupported type"""
return hasattr(model, "__class__") and "Macro" in str(model.__class__)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use more robust type checking instead of string-based detection.

The current approach of checking for "Macro" in the string representation of the class is fragile and could break with different Python versions or object representations.

def is_unsupported_object(model: Any) -> bool:
-    """Check if the object is a Macro or other unsupported type"""
-    return hasattr(model, "__class__") and "Macro" in str(model.__class__)
+    """Check if the object is a Macro or other unsupported type"""
+    try:
+        # Check for specific dbt Macro types
+        return (hasattr(model, "__class__") and 
+                (model.__class__.__name__ == "Macro" or 
+                 "Macro" in [cls.__name__ for cls in model.__class__.__mro__]))
+    except (AttributeError, TypeError):
+        return False
📝 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 is_unsupported_object(model: Any) -> bool:
"""Check if the object is a Macro or other unsupported type"""
return hasattr(model, "__class__") and "Macro" in str(model.__class__)
def is_unsupported_object(model: Any) -> bool:
"""Check if the object is a Macro or other unsupported type"""
try:
# Check for specific dbt Macro types
return (hasattr(model, "__class__") and
(model.__class__.__name__ == "Macro" or
"Macro" in [cls.__name__ for cls in model.__class__.__mro__]))
except (AttributeError, TypeError):
return False
🤖 Prompt for AI Agents
In elementary/clients/dbt/databricks_patch.py around lines 8 to 10, replace the
fragile string-based check for "Macro" in the class name with a more robust type
checking method. Use isinstance or check the class directly against the known
Macro type or its base class to determine if the object is a Macro, ensuring
compatibility across Python versions and avoiding reliance on string
representations.

Comment on lines +78 to +96
def safe_get(
model: Any, setting: str, case_sensitive: Union[bool, None] = False
) -> Union[str, None]:
try:
if is_unsupported_object(model):
return None
# Check if model has config attribute
if not hasattr(model, "config") or not model.config:
return None
# Check if config has get method
if not hasattr(model.config, "get"):
return None
value = model.config.get(setting)
if value:
return value if case_sensitive else value.lower()
return None
except Exception as e:
logger.debug(f"Failed to get {setting} from model config: {e}")
return None
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent parameter usage in safe_get function.

The case_sensitive parameter defaults to False but is used in a way that suggests it should default to True or None. When case_sensitive=False, the function calls .lower() on the value, but this could cause issues if the value is not a string.

def safe_get(
-    model: Any, setting: str, case_sensitive: Union[bool, None] = False
+    model: Any, setting: str, case_sensitive: bool = True
 ) -> Union[str, None]:
     try:
         if is_unsupported_object(model):
             return None
         # Check if model has config attribute
         if not hasattr(model, "config") or not model.config:
             return None
         # Check if config has get method
         if not hasattr(model.config, "get"):
             return None
         value = model.config.get(setting)
         if value:
-            return value if case_sensitive else value.lower()
+            if isinstance(value, str) and not case_sensitive:
+                return value.lower()
+            return str(value) if value is not None else None
         return None
     except Exception as e:
         logger.debug(f"Failed to get {setting} from model config: {e}")
         return 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 safe_get(
model: Any, setting: str, case_sensitive: Union[bool, None] = False
) -> Union[str, None]:
try:
if is_unsupported_object(model):
return None
# Check if model has config attribute
if not hasattr(model, "config") or not model.config:
return None
# Check if config has get method
if not hasattr(model.config, "get"):
return None
value = model.config.get(setting)
if value:
return value if case_sensitive else value.lower()
return None
except Exception as e:
logger.debug(f"Failed to get {setting} from model config: {e}")
return None
def safe_get(
model: Any, setting: str, case_sensitive: bool = True
) -> Union[str, None]:
try:
if is_unsupported_object(model):
return None
# Check if model has config attribute
if not hasattr(model, "config") or not model.config:
return None
# Check if config has get method
if not hasattr(model.config, "get"):
return None
value = model.config.get(setting)
if value:
if isinstance(value, str) and not case_sensitive:
return value.lower()
return str(value) if value is not None else None
return None
except Exception as e:
logger.debug(f"Failed to get {setting} from model config: {e}")
return None
🤖 Prompt for AI Agents
In elementary/clients/dbt/databricks_patch.py between lines 78 and 96, the
safe_get function uses the case_sensitive parameter inconsistently by defaulting
it to False and then calling .lower() on the value, which may not be a string.
To fix this, change the default of case_sensitive to True or None to reflect
that values should be returned as-is by default, and add a type check before
calling .lower() to ensure the value is a string when case_sensitive is False.

@mi-volodin
Copy link

@arbiv are there any reasons why this PR is not yet marked as ready for review? Is there any help needed?

We are critically blocked by that elementary downside, as we need to use >=1.10.5 of dbt-databricks.

@asos-dipeshbhundia
Copy link

Is there a timeline of when this PR is going to be updated and merged?

@haritamar
Copy link
Collaborator

Hey all, we were a bit cautious about this fix because it patches internal dbt-databricks functions.
That being said - it looks like the issue is solved in newer versions!
So we're removing the restriction and it will be in a version we intend to release today.

@haritamar haritamar closed this Oct 9, 2025
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.

5 participants