seanghaeli commented on code in PR #77293:
URL: https://github.com/apache/airflow/pull/77293#discussion_r4733909191


##########
airflow-core/src/airflow/jobs/triggerer_job_runner.py:
##########
@@ -914,23 +927,84 @@ def clean_unused(self) -> None:
 
     def finalize_trigger_log(self, trigger_id: int) -> None:
         """
-        Upload and close the log file of a trigger that no longer runs here.
+        Hand the log file of a trigger that no longer runs here to the pool to 
upload and close.
 
         Every path that drops an id from ``running_triggers`` has to call it: 
re-creation
         reuses the log path, so a leftover entry is lost.
         """
         if factory := self.logger_cache.pop(trigger_id, None):
+            future = 
self._get_log_upload_pool().submit(self._upload_and_close_log, trigger_id, 
factory)
+            with self._pending_log_uploads_lock:
+                self._pending_log_uploads[factory.log_path] = future
+            
future.add_done_callback(functools.partial(self._forget_log_upload, 
factory.log_path))
+
+    def _get_log_upload_pool(self) -> ThreadPoolExecutor:
+        if self._log_upload_pool is None:
+            from airflow.sdk.log import load_remote_log_handler  # noqa: SDK001
+
+            # Loading the handler isn't thread-safe; load it here so the 
pool's threads find it loaded.
+            load_remote_log_handler()
+            self._log_upload_pool = ThreadPoolExecutor(
+                max_workers=self.log_upload_workers, 
thread_name_prefix="triggerer-log-upload"
+            )
+        return self._log_upload_pool
+
+    @staticmethod
+    def _upload_and_close_log(trigger_id: int, factory: TriggerLoggingFactory) 
-> None:
+        try:
+            factory.upload_to_remote()
+        except Exception:
+            log.exception("Failed to upload trigger logs to remote", 
trigger_id=trigger_id)
+        finally:
+            # Close the FD explicitly even if upload raised, otherwise the 
file handle
+            # leaks for every failed upload. close() flushes, so it can raise 
too.
             try:
-                factory.upload_to_remote()
+                factory.close()
             except Exception:
-                log.exception("Failed to upload trigger logs to remote", 
trigger_id=trigger_id)
-            finally:
-                # Close the FD explicitly even if upload raised, otherwise the 
file handle
-                # leaks for every failed upload. close() flushes, so it can 
raise too.
-                try:
-                    factory.close()
-                except Exception:
-                    log.exception("Failed to close trigger log file", 
trigger_id=trigger_id)
+                log.exception("Failed to close trigger log file", 
trigger_id=trigger_id)
+
+    def _forget_log_upload(self, log_path: str, future: Future[None]) -> None:
+        with self._pending_log_uploads_lock:
+            if self._pending_log_uploads.get(log_path) is future:
+                del self._pending_log_uploads[log_path]
+
+    def _create_trigger_log(self, trigger_id: int, log_path: str, ti: 
RuntimeTI | None = None) -> None:
+        """
+        Cache a log factory for ``trigger_id`` once any pending upload of 
``log_path`` has finished.
+
+        Opening the log truncates the file, so wait up to 
``log_upload_timeout`` for an upload of the
+        same path, left by a re-created trigger or an earlier deferral of the 
same task try.
+        """
+        with self._pending_log_uploads_lock:
+            future = self._pending_log_uploads.get(log_path)
+        if future is not None and wait([future], 
timeout=self.log_upload_timeout).not_done:
+            log.warning(
+                "Previous log upload is still running; opening the trigger log 
anyway",
+                trigger_id=trigger_id,
+                log_path=log_path,
+                timeout=self.log_upload_timeout,
+            )
+        self.logger_cache[trigger_id] = 
TriggerLoggingFactory(log_path=log_path, ti=ti)
+
+    def drain_log_uploads(self) -> None:
+        """Wait, up to ``log_upload_timeout``, for pending log uploads, then 
cancel those not yet started."""
+        if (pool := self._log_upload_pool) is None:
+            return
+        self._log_upload_pool = None
+        with self._pending_log_uploads_lock:
+            futures = list(self._pending_log_uploads.values())
+        not_done = wait(futures, timeout=self.log_upload_timeout).not_done

Review Comment:
   On a plain SIGTERM right after 300 triggers fired, this gave up after 10 s 
and dropped 121 trigger logs (`Abandoning pending trigger log uploads 
cancelled=121`), and they're gone once the triggerer's disk is. #77290 uploaded 
all 300 in 24 s. Could the graceful path wait for the queue?



##########
airflow-core/src/airflow/jobs/triggerer_job_runner.py:
##########
@@ -914,23 +927,84 @@ def clean_unused(self) -> None:
 
     def finalize_trigger_log(self, trigger_id: int) -> None:
         """
-        Upload and close the log file of a trigger that no longer runs here.
+        Hand the log file of a trigger that no longer runs here to the pool to 
upload and close.
 
         Every path that drops an id from ``running_triggers`` has to call it: 
re-creation
         reuses the log path, so a leftover entry is lost.
         """
         if factory := self.logger_cache.pop(trigger_id, None):
+            future = 
self._get_log_upload_pool().submit(self._upload_and_close_log, trigger_id, 
factory)
+            with self._pending_log_uploads_lock:
+                self._pending_log_uploads[factory.log_path] = future
+            
future.add_done_callback(functools.partial(self._forget_log_upload, 
factory.log_path))
+
+    def _get_log_upload_pool(self) -> ThreadPoolExecutor:
+        if self._log_upload_pool is None:
+            from airflow.sdk.log import load_remote_log_handler  # noqa: SDK001
+
+            # Loading the handler isn't thread-safe; load it here so the 
pool's threads find it loaded.
+            load_remote_log_handler()
+            self._log_upload_pool = ThreadPoolExecutor(
+                max_workers=self.log_upload_workers, 
thread_name_prefix="triggerer-log-upload"
+            )
+        return self._log_upload_pool
+
+    @staticmethod
+    def _upload_and_close_log(trigger_id: int, factory: TriggerLoggingFactory) 
-> None:
+        try:
+            factory.upload_to_remote()
+        except Exception:
+            log.exception("Failed to upload trigger logs to remote", 
trigger_id=trigger_id)
+        finally:
+            # Close the FD explicitly even if upload raised, otherwise the 
file handle
+            # leaks for every failed upload. close() flushes, so it can raise 
too.
             try:
-                factory.upload_to_remote()
+                factory.close()
             except Exception:
-                log.exception("Failed to upload trigger logs to remote", 
trigger_id=trigger_id)
-            finally:
-                # Close the FD explicitly even if upload raised, otherwise the 
file handle
-                # leaks for every failed upload. close() flushes, so it can 
raise too.
-                try:
-                    factory.close()
-                except Exception:
-                    log.exception("Failed to close trigger log file", 
trigger_id=trigger_id)
+                log.exception("Failed to close trigger log file", 
trigger_id=trigger_id)
+
+    def _forget_log_upload(self, log_path: str, future: Future[None]) -> None:
+        with self._pending_log_uploads_lock:
+            if self._pending_log_uploads.get(log_path) is future:
+                del self._pending_log_uploads[log_path]
+
+    def _create_trigger_log(self, trigger_id: int, log_path: str, ti: 
RuntimeTI | None = None) -> None:
+        """
+        Cache a log factory for ``trigger_id`` once any pending upload of 
``log_path`` has finished.
+
+        Opening the log truncates the file, so wait up to 
``log_upload_timeout`` for an upload of the
+        same path, left by a re-created trigger or an earlier deferral of the 
same task try.
+        """
+        with self._pending_log_uploads_lock:
+            future = self._pending_log_uploads.get(log_path)
+        if future is not None and wait([future], 
timeout=self.log_upload_timeout).not_done:

Review Comment:
   This wait runs on the main loop, so the stall comes back when tasks defer 
again in the same try while their first log is still queued. With 300 tasks 
doing that and S3 behind 300 ms of latency, the loop stopped for up to 18 s and 
the triggerer logged "appears deadlocked" and skipped its heartbeat. #77290 
skips the trigger until the next pass instead and stayed under 3 s in the same 
run. Could this do the same? Also a conflict to deal with now that #76527 is in.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to