- 
                Notifications
    You must be signed in to change notification settings 
- Fork 749
fix: Enable stub mechanism for caching un-pickable objects #6657
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 10 commits
      Commits
    
    
            Show all changes
          
          
            11 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      54e05a0
              
                feat: add custom stubs for caching
              
              
                dmadisetti b59dc00
              
                feat: custom stubs registration for pydantic
              
              
                dmadisetti 9b53c30
              
                tests: stub tests for pydantic
              
              
                dmadisetti 3c49722
              
                feat: add custom stubds for content resolution
              
              
                dmadisetti 77525f6
              
                tests: Add a hash test to ensure deterministic hits
              
              
                dmadisetti abf1fc5
              
                Merge branch 'main' of github:marimo-team/marimo into dm/stubs
              
              
                dmadisetti 845a89c
              
                tests: tighten testing procedure
              
              
                dmadisetti a6f0ec3
              
                tests: restrict tests w/o pydantic_core
              
              
                dmadisetti a0f5c4d
              
                tests: more restrictions for tests w/o pydantic_core
              
              
                dmadisetti 6dfbc8f
              
                [pre-commit.ci] auto fixes from pre-commit.com hooks
              
              
                pre-commit-ci[bot] 88a5730
              
                comments: fix mro issue
              
              
                dmadisetti File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # Copyright 2025 Marimo. All rights reserved. | ||
| """Stub system for cache serialization.""" | ||
|  | ||
| from __future__ import annotations | ||
|  | ||
| from typing import Any, Callable | ||
|  | ||
| from marimo._save.stubs.function_stub import FunctionStub | ||
| from marimo._save.stubs.module_stub import ModuleStub | ||
| from marimo._save.stubs.pydantic_stub import PydanticStub | ||
| from marimo._save.stubs.stubs import ( | ||
| CUSTOM_STUBS, | ||
| CustomStub, | ||
| register_stub, | ||
| ) | ||
| from marimo._save.stubs.ui_element_stub import UIElementStub | ||
|  | ||
| # Track which class names we've already attempted to register | ||
| _REGISTERED_NAMES: set[str] = set() | ||
|  | ||
| # Dictionary mapping fully qualified class names to registration functions | ||
| STUB_REGISTRATIONS: dict[str, Callable[[Any], None]] = { | ||
| "pydantic.main.BaseModel": PydanticStub.register, | ||
| } | ||
|  | ||
|  | ||
| def maybe_register_stub(value: Any) -> bool: | ||
| """Lazily register a stub for a value's type if not already registered. | ||
|  | ||
| This allows us to avoid importing third-party packages until they're | ||
| actually used in the cache. Walks the MRO to check if any parent class | ||
| matches a registered stub type. | ||
|  | ||
| Returns: | ||
| True if the value's type is in CUSTOM_STUBS (either already registered | ||
| or newly registered), False otherwise. | ||
| """ | ||
| value_type = type(value) | ||
|  | ||
| # Already registered in CUSTOM_STUBS | ||
| if value_type in CUSTOM_STUBS: | ||
| return True | ||
|  | ||
| # Walk MRO to find matching base class | ||
| for cls in value_type.__mro__: | ||
| if not (hasattr(cls, "__module__") and hasattr(cls, "__name__")): | ||
| continue | ||
|  | ||
| cls_name = f"{cls.__module__}.{cls.__name__}" | ||
|  | ||
| if cls_name in STUB_REGISTRATIONS: | ||
| if cls_name not in _REGISTERED_NAMES: | ||
| _REGISTERED_NAMES.add(cls_name) | ||
| STUB_REGISTRATIONS[cls_name](value) | ||
| # After registration attempt, check if now in CUSTOM_STUBS | ||
| return value_type in CUSTOM_STUBS | ||
|  | ||
| return False | ||
|  | ||
|  | ||
| def maybe_get_custom_stub(value: Any) -> CustomStub | None: | ||
| """Get the registered stub for a value's type, if any. | ||
|  | ||
| Args: | ||
| value: The value to get the stub for | ||
|  | ||
| Returns: | ||
| A stub instance if registered, None otherwise | ||
| """ | ||
| # Fallback to custom cases | ||
| if maybe_register_stub(value): | ||
| value_type = type(value) | ||
| if value_type in CUSTOM_STUBS: | ||
| return CUSTOM_STUBS[value_type](value) | ||
| return None | ||
|  | ||
|  | ||
| __all__ = [ | ||
| "CUSTOM_STUBS", | ||
| "CustomStub", | ||
| "FunctionStub", | ||
| "ModuleStub", | ||
| "UIElementStub", | ||
| "maybe_register_stub", | ||
| "maybe_get_custom_stub", | ||
| "register_stub", | ||
| ] | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # Copyright 2025 Marimo. All rights reserved. | ||
| from __future__ import annotations | ||
|  | ||
| import inspect | ||
| import textwrap | ||
| from typing import Any | ||
|  | ||
| __all__ = ["FunctionStub"] | ||
|  | ||
|  | ||
| class FunctionStub: | ||
| """Stub for function objects, storing the source code.""" | ||
|  | ||
| def __init__(self, function: Any) -> None: | ||
| self.code = textwrap.dedent(inspect.getsource(function)) | ||
|  | ||
| def load(self, glbls: dict[str, Any]) -> Any: | ||
| """Reconstruct the function by executing its source code.""" | ||
| # TODO: Fix line cache and associate with the correct module. | ||
| code_obj = compile(self.code, "<string>", "exec") | ||
| lcls: dict[str, Any] = {} | ||
| exec(code_obj, glbls, lcls) | ||
| # Update the global scope with the function. | ||
| for value in lcls.values(): | ||
| return value | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| # Copyright 2025 Marimo. All rights reserved. | ||
| from __future__ import annotations | ||
|  | ||
| import importlib | ||
| from typing import Any | ||
|  | ||
| __all__ = ["ModuleStub"] | ||
|  | ||
|  | ||
| class ModuleStub: | ||
| """Stub for module objects, storing only the module name.""" | ||
|  | ||
| def __init__(self, module: Any) -> None: | ||
| self.name = module.__name__ | ||
|  | ||
| def load(self) -> Any: | ||
| """Reload the module by name.""" | ||
| return importlib.import_module(self.name) | 
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i did this in formatters, and it has a chance of raising errors in odd edge maybe either catch the exception or comment if we just want to propoage it up
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, looked at the formatters change, and a little too small to meaningfully DRY- but hopefully this saves us a bug report