@@ -526,6 +526,8 @@ impl Database {
526526 pub fn create_session_context ( & self ) -> SessionContext {
527527 use datafusion:: config:: ConfigOptions ;
528528 use datafusion:: execution:: context:: SessionContext ;
529+ use datafusion:: execution:: runtime_env:: RuntimeEnvBuilder ;
530+ use std:: sync:: Arc ;
529531
530532 let mut options = ConfigOptions :: new ( ) ;
531533 let _ = options. set ( "datafusion.sql_parser.enable_information_schema" , "true" ) ;
@@ -568,7 +570,38 @@ impl Database {
568570 // Enable all optimizer rules for maximum optimization
569571 let _ = options. set ( "datafusion.optimizer.max_passes" , "5" ) ;
570572
571- SessionContext :: new_with_config ( options. into ( ) )
573+ // Configure memory limit for DataFusion operations
574+ let memory_limit_gb = env:: var ( "TIMEFUSION_MEMORY_LIMIT_GB" )
575+ . unwrap_or_else ( |_| "8" . to_string ( ) )
576+ . parse :: < usize > ( )
577+ . unwrap_or ( 8 ) ;
578+
579+ // Configure memory fraction (how much of the memory pool to use for execution)
580+ let memory_fraction = env:: var ( "TIMEFUSION_MEMORY_FRACTION" )
581+ . unwrap_or_else ( |_| "0.9" . to_string ( ) )
582+ . parse :: < f64 > ( )
583+ . unwrap_or ( 0.9 ) ;
584+
585+ // Configure external sort spill size
586+ let sort_spill_reservation_bytes = env:: var ( "TIMEFUSION_SORT_SPILL_RESERVATION_BYTES" )
587+ . unwrap_or_else ( |_| "67108864" . to_string ( ) ) // Default 64MB
588+ . parse :: < usize > ( )
589+ . unwrap_or ( 67108864 ) ;
590+
591+ // Set memory-related configuration options
592+ let _ = options. set ( "datafusion.execution.memory_fraction" , & memory_fraction. to_string ( ) ) ;
593+ let _ = options. set ( "datafusion.execution.sort_spill_reservation_bytes" , & sort_spill_reservation_bytes. to_string ( ) ) ;
594+
595+ // Create runtime environment with memory limit
596+ let runtime_env = RuntimeEnvBuilder :: new ( )
597+ . with_memory_limit ( memory_limit_gb * 1024 * 1024 * 1024 , memory_fraction)
598+ . build ( )
599+ . expect ( "Failed to create runtime environment" ) ;
600+
601+ let runtime_env = Arc :: new ( runtime_env) ;
602+
603+ // Create session context with both config options and runtime environment
604+ SessionContext :: new_with_config_rt ( options. into ( ) , runtime_env)
572605 }
573606
574607 /// Setup the session context with tables and register DataFusion tables
0 commit comments