1+ from __future__ import annotations
2+
13import contextlib
24import datetime
35import importlib
1012import threading
1113import time
1214from collections import defaultdict
13-
14- # _original_import = builtins.__import__
15- #
16- # def custom_import(name, globals=None, locals=None, fromlist=(), level=0):
17- # module = _original_import(name, globals, locals, fromlist, level)
18- # if name in sys.modules:
19- # mod = sys.modules[name]
20- # file = getattr(mod, '__file__', '') or ''
21- #
22- # if ("logfire" in name) or ("logfire" in file):
23- # if hasattr(mod, '__file__'):
24- # print(f"Imported {name} from {mod.__file__}")
25- # else:
26- # print(f"Imported {name} (built-in or dynamic)")
27- # for line in traceback.format_stack():
28- # print(line.strip())
29- # return module
30- #
31- # builtins.__import__ = custom_import
3215from pathlib import Path
33- from types import FrameType , TracebackType
34- from typing import Any , Callable , ClassVar
16+ from typing import TYPE_CHECKING , Any , Callable , ClassVar
3517
3618from rich .align import Align
3719from rich .panel import Panel
4224from codeflash .picklepatch .pickle_patcher import PicklePatcher
4325from codeflash .tracing .tracing_utils import FunctionModules , filter_files_optimized , module_name_from_file_path
4426
45- # Debug this file by simply adding print statements. This file is not meant to be debugged by the debugger.
27+ if TYPE_CHECKING :
28+ from types import FrameType , TracebackType
4629
4730
4831class FakeCode :
@@ -57,12 +40,13 @@ def __repr__(self) -> str:
5740
5841
5942class FakeFrame :
60- def __init__ (self , code : FakeCode , prior : " FakeFrame | None" ) -> None :
43+ def __init__ (self , code : FakeCode , prior : FakeFrame | None ) -> None :
6144 self .f_code = code
6245 self .f_back = prior
6346 self .f_locals : dict = {}
6447
6548
49+ # Debug this file by simply adding print statements. This file is not meant to be debugged by the debugger.
6650class Tracer :
6751 """Use this class as a 'with' context manager to trace a function call.
6852
@@ -71,7 +55,7 @@ class Tracer:
7155
7256 def __init__ (
7357 self ,
74- config ,
58+ config : dict ,
7559 result_pickle_file_path : Path ,
7660 output : str = "codeflash.trace" ,
7761 functions : list [str ] | None = None ,
@@ -199,16 +183,12 @@ def __enter__(self) -> None:
199183 console .rule ("Codeflash: Traced Program Output Begin" , style = "bold blue" )
200184 frame = sys ._getframe (0 ) # Get this frame and simulate a call to it # noqa: SLF001
201185 self .dispatch ["call" ](self , frame , 0 )
202- print (dir (self ))
203- for att in dir (self ):
204- if att [:2 ] != "__" :
205- print (att , getattr (self , att ))
206186 self .start_time = time .time ()
207187 sys .setprofile (self .trace_callback )
208188 threading .setprofile (self .trace_callback )
209189
210190 def __exit__ (
211- self , exc_type : type [BaseException ] | None , exc_val : BaseException | None , exc_tb : " TracebackType | None"
191+ self , exc_type : type [BaseException ] | None , exc_val : BaseException | None , exc_tb : TracebackType | None
212192 ) -> None :
213193 if self .disable or self ._db_lock is None :
214194 return
@@ -305,10 +285,10 @@ def __exit__(
305285 pickle_data = {"replay_test_file_path" : self .replay_test_file_path }
306286 import pickle
307287
308- with open ( self .result_pickle_file_path , "wb" ) as file :
288+ with self .result_pickle_file_path . open ( "wb" ) as file :
309289 pickle .dump (pickle_data , file )
310290
311- def tracer_logic (self , frame : " FrameType" , event : str ) -> None : # noqa: PLR0911
291+ def tracer_logic (self , frame : FrameType , event : str ) -> None : # noqa: PLR0911
312292 if event != "call" :
313293 return
314294 if None is not self .timeout and (time .time () - self .start_time ) > self .timeout :
@@ -580,7 +560,7 @@ def trace_dispatch_return(self, frame: FrameType, t: int) -> int:
580560
581561 return 1
582562
583- dispatch : ClassVar [dict [str , Callable [[" Tracer" , FrameType , int ], int ]]] = {
563+ dispatch : ClassVar [dict [str , Callable [[Tracer , FrameType , int ], int ]]] = {
584564 "call" : trace_dispatch_call ,
585565 "exception" : trace_dispatch_exception ,
586566 "return" : trace_dispatch_return ,
@@ -806,10 +786,9 @@ def snapshot_stats(self) -> None:
806786 nc += callcnt
807787 self .stats [func ] = cc , nc , tt , ct , callers
808788
809- def runctx (self , cmd : str , global_vars : dict [str , Any ], local_vars : dict [str , Any ]) -> " Tracer | None" :
789+ def runctx (self , cmd : str , global_vars : dict [str , Any ], local_vars : dict [str , Any ]) -> Tracer | None :
810790 self .__enter__ ()
811791 try :
812- # pdb.set_trace()
813792 exec (cmd , global_vars , local_vars ) # noqa: S102
814793 finally :
815794 self .__exit__ (None , None , None )
@@ -821,7 +800,6 @@ def runctx(self, cmd: str, global_vars: dict[str, Any], local_vars: dict[str, An
821800 sys .argv = sys .argv [1 :- 1 ]
822801 print ("Args dict" , args_dict )
823802 print ("sys.argv " , sys .argv )
824- # pdb.set_trace()
825803 if args_dict ["module" ]:
826804 import runpy
827805
@@ -830,7 +808,6 @@ def runctx(self, cmd: str, global_vars: dict[str, Any], local_vars: dict[str, An
830808 code = "run_module(modname, run_name='__main__')"
831809 globs = {"run_module" : runpy .run_module , "modname" : args_dict ["progname" ]}
832810 else :
833- # progname = unknown_args[0]
834811 sys .path .insert (0 , str (Path (args_dict ["progname" ]).resolve ().parent ))
835812 with io .open_code (args_dict ["progname" ]) as fp :
836813 code = compile (fp .read (), args_dict ["progname" ], "exec" )
@@ -846,8 +823,6 @@ def runctx(self, cmd: str, global_vars: dict[str, Any], local_vars: dict[str, An
846823 print ("raw config type" , type (args_dict ["config" ]))
847824 args_dict ["config" ]["module_root" ] = Path (args_dict ["config" ]["module_root" ])
848825 args_dict ["config" ]["tests_root" ] = Path (args_dict ["config" ]["tests_root" ])
849- # config = json.loads(args_dict["config"])
850- # print("parsed config", config)
851826 tracer = Tracer (
852827 config = args_dict ["config" ],
853828 output = Path (args_dict ["output" ]),
0 commit comments