9292 from airflow .sdk .definitions .context import Context
9393 from airflow .sdk .definitions .dag import DAG
9494 from airflow .sdk .definitions .mappedoperator import MappedOperator
95- from airflow .sdk .execution_time .supervisor import RequestHandler , RequestResult
95+ from airflow .sdk .execution_time .supervisor import RequestHandler , RequestResult , ResponseSent
9696 from airflow .typing_compat import Self
9797
9898
@@ -573,18 +573,17 @@ def in_process_api_server() -> InProcessExecutionAPI:
573573
574574
575575@attrs .define (kw_only = True )
576- class DagFileProcessorProcess (WatchedSubprocess , LoggingMixin ):
576+ class BaseDagFileProcessorProcess (WatchedSubprocess , LoggingMixin ):
577577 """
578- Parses dags with Task SDK API.
579-
580- This class provides a wrapper and management around a subprocess to parse a specific DAG file.
578+ Parse one Dag file in a child process for the Dag processor manager.
581579
582- Since DAGs are written with the Task SDK, we need to parse them in a task SDK process such that
583- we can use the Task SDK definitions when serializing. This prevents potential conflicts with classes
584- in core Airflow.
580+ The child's output goes to the file's parse log, and its requests are answered with
581+ :attr:`client`. The parse is done once the child has exited and all its sockets are closed;
582+ :attr:`parsing_result` then holds what it sent. Subclasses start the child and send it the
583+ parse request.
585584 """
586585
587- logger_filehandle : BinaryIO
586+ logger_filehandle : BinaryIO | None = None
588587 parsing_result : DagFileParsingResult | None = None
589588 decoder : ClassVar [TypeAdapter [ToManager ]] = TypeAdapter [ToManager ](ToManager )
590589 had_callbacks : bool = False # Track if this process was started with callbacks to prevent stale DAG detection false positives
@@ -595,60 +594,6 @@ class DagFileProcessorProcess(WatchedSubprocess, LoggingMixin):
595594 bundle_name : str
596595 dag_file_rel_path : str
597596
598- @classmethod
599- def start ( # type: ignore[override]
600- cls ,
601- * ,
602- path : str | os .PathLike [str ],
603- bundle_path : Path ,
604- bundle_name : str ,
605- dag_file_rel_path : str ,
606- callbacks : list [CallbackRequest ],
607- target : Callable [[], None ] = _parse_file_entrypoint ,
608- client : Client ,
609- ** kwargs ,
610- ) -> Self :
611- logger = kwargs ["logger" ]
612-
613- # Parsing DAG files runs user code that can trigger macOS-unsafe ObjC
614- # initialization (secret backends, connection/variable lookups, HTTP
615- # clients). Fork+exec a clean interpreter there. Tests override `target`
616- # with a stub to exercise the base infrastructure; keep bare fork for those.
617- use_exec = target is _parse_file_entrypoint and supervisor ._should_use_exec ()
618-
619- # Pre-importing only helps the bare-fork child (it inherits the imports via
620- # copy-on-write). An exec'd child re-imports from scratch, so skip it there
621- # to avoid leaking user modules into the long-lived processor manager.
622- if not use_exec :
623- _pre_import_airflow_modules (os .fspath (path ), logger )
624-
625- proc : Self = super ().start (
626- target = target ,
627- client = client ,
628- bundle_name = bundle_name ,
629- dag_file_rel_path = dag_file_rel_path ,
630- use_exec = use_exec ,
631- ** kwargs ,
632- )
633- proc .had_callbacks = bool (callbacks ) # Track if this process had callbacks
634- proc ._on_child_started (callbacks , path , bundle_path , bundle_name )
635- return proc
636-
637- def _on_child_started (
638- self ,
639- callbacks : list [CallbackRequest ],
640- path : str | os .PathLike [str ],
641- bundle_path : Path ,
642- bundle_name : str ,
643- ) -> None :
644- msg = DagFileParseRequest (
645- file = os .fspath (path ),
646- bundle_path = bundle_path ,
647- bundle_name = bundle_name ,
648- callback_requests = callbacks ,
649- )
650- self .send_msg (msg , request_id = 0 )
651-
652597 def _get_target_loggers (self ) -> tuple [FilteringBoundLogger , ...]:
653598 base = super ()._get_target_loggers ()
654599 if not self .subprocess_logs_to_stdout :
@@ -674,11 +619,12 @@ def _create_log_forwarder(
674619
675620 def _handle_parsing_result (
676621 self , msg : DagFileParsingResult , log : FilteringBoundLogger , req_id : int
677- ) -> RequestResult :
622+ ) -> RequestResult | ResponseSent :
678623 self .parsing_result = msg
679624 return None , {}
680625
681- _request_handlers : ClassVar [dict [type [BaseModel ], RequestHandler [DagFileProcessorProcess ]]] = {
626+ # Each subclass builds its own ``_request_handlers``, typed with itself, from these.
627+ _common_request_handlers : ClassVar [dict [type [BaseModel ], RequestHandler [BaseDagFileProcessorProcess ]]] = {
682628 ** WatchedSubprocess ._get_shared_request_handlers (
683629 DeleteVariable ,
684630 GetConnection ,
@@ -720,6 +666,8 @@ def wait(self) -> int:
720666
721667 def close (self ):
722668 self .cleanup_sockets_after_kill ()
669+ if self .logger_filehandle is None :
670+ return
723671 try :
724672 self .logger_filehandle .close ()
725673 except OSError :
@@ -728,3 +676,76 @@ def close(self):
728676 self .dag_file_rel_path ,
729677 exc_info = True ,
730678 )
679+
680+
681+ @attrs .define (kw_only = True )
682+ class DagFileProcessorProcess (BaseDagFileProcessorProcess ):
683+ """
684+ Parses dags with Task SDK API.
685+
686+ This class provides a wrapper and management around a subprocess to parse a specific DAG file.
687+
688+ Since DAGs are written with the Task SDK, we need to parse them in a task SDK process such that
689+ we can use the Task SDK definitions when serializing. This prevents potential conflicts with classes
690+ in core Airflow.
691+ """
692+
693+ logger_filehandle : BinaryIO
694+
695+ _request_handlers : ClassVar [dict [type [BaseModel ], RequestHandler [DagFileProcessorProcess ]]] = {
696+ ** BaseDagFileProcessorProcess ._common_request_handlers ,
697+ }
698+
699+ @classmethod
700+ def start ( # type: ignore[override]
701+ cls ,
702+ * ,
703+ path : str | os .PathLike [str ],
704+ bundle_path : Path ,
705+ bundle_name : str ,
706+ dag_file_rel_path : str ,
707+ callbacks : list [CallbackRequest ],
708+ target : Callable [[], None ] = _parse_file_entrypoint ,
709+ client : Client ,
710+ ** kwargs ,
711+ ) -> Self :
712+ logger = kwargs ["logger" ]
713+
714+ # Parsing DAG files runs user code that can trigger macOS-unsafe ObjC
715+ # initialization (secret backends, connection/variable lookups, HTTP
716+ # clients). Fork+exec a clean interpreter there. Tests override `target`
717+ # with a stub to exercise the base infrastructure; keep bare fork for those.
718+ use_exec = target is _parse_file_entrypoint and supervisor ._should_use_exec ()
719+
720+ # Pre-importing only helps the bare-fork child (it inherits the imports via
721+ # copy-on-write). An exec'd child re-imports from scratch, so skip it there
722+ # to avoid leaking user modules into the long-lived processor manager.
723+ if not use_exec :
724+ _pre_import_airflow_modules (os .fspath (path ), logger )
725+
726+ proc : Self = super ().start (
727+ target = target ,
728+ client = client ,
729+ bundle_name = bundle_name ,
730+ dag_file_rel_path = dag_file_rel_path ,
731+ use_exec = use_exec ,
732+ ** kwargs ,
733+ )
734+ proc .had_callbacks = bool (callbacks ) # Track if this process had callbacks
735+ proc ._on_child_started (callbacks , path , bundle_path , bundle_name )
736+ return proc
737+
738+ def _on_child_started (
739+ self ,
740+ callbacks : list [CallbackRequest ],
741+ path : str | os .PathLike [str ],
742+ bundle_path : Path ,
743+ bundle_name : str ,
744+ ) -> None :
745+ msg = DagFileParseRequest (
746+ file = os .fspath (path ),
747+ bundle_path = bundle_path ,
748+ bundle_name = bundle_name ,
749+ callback_requests = callbacks ,
750+ )
751+ self .send_msg (msg , request_id = 0 )
0 commit comments