Skip to content

dbx_patch.patches.autoreload_hook_patch

[docs] module dbx_patch.patches.autoreload_hook_patch

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""AutoreloadDiscoverabilityHook Patch for Editable Installs.

This module patches the Databricks autoreload discoverability hook to allow
imports from editable install paths. The autoreload hook wraps builtins.__import__
and only allows imports from specific paths (like /Workspace). We need to add
editable install paths to this allowlist.

Environment Variables:
    DBX_PATCH_DEBUG_IMPORTS: Set to '1', 'true', or 'yes' to enable extremely verbose
        import tracing by patching builtins.__import__. This logs every single import
        that happens in the Python process and should only be used for debugging
        import-related issues with editable installs.

Example:
            import os
            os.environ['DBX_PATCH_DEBUG_IMPORTS'] = '1'
            from dbx_patch import patch_dbx
            patch_dbx()
"""

import builtins
import logging
from typing import Any

from dbx_patch.base_patch import BasePatch
from dbx_patch.models import PatchResult


class AutoreloadHookPatch(BasePatch):
    """Patch for Databricks autoreload discoverability hook.

    Registers editable install paths in the autoreload allowlist and optionally
    patches builtins.__import__ for debug logging.
    """

    def __init__(self, verbose: bool = True) -> None:
        """Initialize the patch.

        Args:
            verbose: Enable verbose logging
        """
        super().__init__(verbose)
        self._registered_check: Any = None
        self._original_builtins_import: Any = None
        self._import_patch_applied: bool = False

    def _editable_path_check(self, fname: str) -> bool:
        """Check if a file path is within an editable install directory.

        Args:
            fname: The file path to check

        Returns:
            True if the file is in an editable install directory, False otherwise
        """
        if not fname:
            return False

        from dbx_patch.pth_processor import get_editable_install_paths

        editable_paths = get_editable_install_paths()

        # Check if the file is under any editable install path
        result = any(fname.startswith(editable_path) for editable_path in editable_paths)

        # Debug logging
        logger = self._get_logger()
        if logger and result:
            matching = [p for p in editable_paths if fname.startswith(p)]
            logger.debug(f"Autoreload check: {fname} -> {result} (matched: {matching[0] if matching else 'unknown'})")

        return result

    def _patched_builtins_import(self, name: str, *args: Any, **kwargs: Any) -> Any:
        """Wrapper for builtins.__import__ that adds debug logging.

        This helps diagnose import failures when using editable installs.

        Args:
            name: Module name to import
            *args: Positional arguments for __import__
            **kwargs: Keyword arguments for __import__

        Returns:
            The imported module
        """
        logger = self._get_logger()
        if logger:
            logger.debug(f"Importing: {name} (args={args}, kwargs={kwargs})")

        if self._original_builtins_import is None:
            msg = "Original builtins.__import__ not saved"
            raise RuntimeError(msg)

        try:
            result = self._original_builtins_import(name, *args, **kwargs)
        except Exception as e:
            if logger:
                logger.debug(f"Import FAILED: {name} - {e}")
            raise
        else:
            if logger:
                module_file = getattr(result, "__file__", "<no __file__>")
                logger.debug(f"Import succeeded: {name} from {module_file}")
            return result

    def patch(self) -> PatchResult:
        """Apply the autoreload hook patch.

        Returns:
            PatchResult with operation details
        """
        logger = self._get_logger()

        # Patch builtins.__import__ for debug logging ONLY if explicitly enabled via env var
        # This is extremely verbose and should only be used for debugging import issues
        import os

        if (
            os.environ.get("DBX_PATCH_DEBUG_IMPORTS", "").lower() in ("1", "true", "yes")
            and not self._import_patch_applied
        ):
            if logger:
                logger.info("DBX_PATCH_DEBUG_IMPORTS enabled - patching builtins.__import__ for import tracing...")
            self._original_builtins_import = builtins.__import__
            builtins.__import__ = self._patched_builtins_import  # type: ignore[assignment]
            self._import_patch_applied = True
            if logger:
                logger.info("builtins.__import__ patched for import tracing (this will be very verbose!)")

        if self._is_applied:
            if logger:
                logger.info("Autoreload hook patch already applied.")
            from dbx_patch.pth_processor import get_editable_install_paths

            editable_paths = get_editable_install_paths()
            return PatchResult(
                success=True,
                already_patched=True,
                editable_paths_count=len(editable_paths),
                editable_paths=sorted(editable_paths),
                hook_found=True,
            )

        try:
            # Import the autoreload module
            from dbruntime.autoreload.file_module_utils import (  # type: ignore[import-not-found]
                register_autoreload_allowlist_check,
            )

            if logger:
                logger.info("Autoreload file_module_utils found, registering editable path check...")

            from dbx_patch.pth_processor import get_editable_install_paths

            editable_paths = get_editable_install_paths()

            if logger:
                logger.info(f"Patching autoreload hook to allow {len(editable_paths)} editable install path(s)...")

            # Debug: Log the current allowlist checks
            if logger:
                try:
                    from dbruntime.autoreload.file_module_utils import (  # type: ignore[import-not-found]
                        _AUTORELOAD_ALLOWLIST_CHECKS,
                    )

                    logger.info(f"Current allowlist checks before patch: {len(_AUTORELOAD_ALLOWLIST_CHECKS)}")
                except Exception as e:  # noqa: BLE001
                    logger.debug(f"Could not access allowlist checks: {e}")

            # Register our check function
            self._registered_check = self._editable_path_check
            register_autoreload_allowlist_check(self._registered_check)

            # Debug: Log the allowlist checks after registration
            if logger:
                try:
                    from dbruntime.autoreload.file_module_utils import (  # type: ignore[import-not-found]
                        _AUTORELOAD_ALLOWLIST_CHECKS,
                    )

                    logger.info(f"Current allowlist checks after patch: {len(_AUTORELOAD_ALLOWLIST_CHECKS)}")
                except Exception as e:  # noqa: BLE001
                    logger.debug(f"Could not access allowlist checks: {e}")

            self._is_applied = True

            if logger:
                logger.success("Autoreload hook patched successfully!")
                if editable_paths:
                    with logger.indent():
                        logger.info("Allowing imports from editable paths:")
                        for path in sorted(editable_paths):
                            logger.info(f"- {path}")
                else:
                    with logger.indent():
                        logger.warning("No editable install paths found yet.")
                        logger.info("Run 'pip install -e .' first, then reapply patches.")

            return PatchResult(
                success=True,
                already_patched=False,
                editable_paths_count=len(editable_paths),
                editable_paths=sorted(editable_paths),
                hook_found=True,
            )

        except ImportError as e:
            if logger:
                logger.warning(f"Could not import autoreload modules: {e}")
                with logger.indent():
                    logger.info("This is normal if not running in Databricks environment.")
                    logger.info("The autoreload hook is only present in Databricks runtime.")
            return PatchResult(
                success=False,
                already_patched=False,
                hook_found=False,
                error=str(e),
            )
        except Exception as e:
            if logger:
                logger.error(f"Error patching autoreload hook: {e}")  # noqa: TRY400
                import traceback

                with logger.indent():
                    logger.info(f"Traceback: {traceback.format_exc()}")
            return PatchResult(
                success=False,
                already_patched=False,
                hook_found=True,
                error=str(e),
            )

    def remove(self) -> bool:
        """Remove the patch and restore original autoreload hook behavior.

        Returns:
            True if unpatch was successful, False otherwise
        """
        logger = self._get_logger()

        success = True

        # Unpatch the allowlist check
        if self._is_applied:
            try:
                from dbruntime.autoreload.file_module_utils import (  # type: ignore[import-not-found]
                    deregister_autoreload_allowlist_check,
                )

                # Deregister our check function
                if self._registered_check is not None:
                    deregister_autoreload_allowlist_check(self._registered_check)
                    self._registered_check = None
                    self._is_applied = False

                    if logger:
                        logger.success("Autoreload hook patch removed successfully.")
                else:
                    if logger:
                        logger.warning("Check function not saved, cannot unpatch.")
                    success = False

            except Exception as e:
                if logger:
                    logger.error(f"Error removing patch: {e}")  # noqa: TRY400
                success = False
        else:
            if logger:
                logger.info("No allowlist patch to remove.")

        # Unpatch builtins.__import__ if it was patched
        if self._import_patch_applied and self._original_builtins_import is not None:
            if logger:
                logger.info("Restoring original builtins.__import__...")
            builtins.__import__ = self._original_builtins_import  # type: ignore[assignment]
            self._import_patch_applied = False
            if logger:
                logger.success("builtins.__import__ restored.")

        return success

    def is_applied(self) -> bool:
        """Check if the autoreload hook patch is currently applied.

        Returns:
            True if patched, False otherwise
        """
        return self._is_applied