victormacaubas opened a new issue, #77495:
URL: https://github.com/apache/airflow/issues/77495

   ### Under which category would you file this issue?
   
   Providers
   
   ### Apache Airflow version
   
   3.3.2
   
   ### What happened and how to reproduce it?
   
   ### Issue description
   
   After upgrading from Airflow 2.11.2 to 3.3.2 (`CeleryExecutor` on ECS 
Fargate, Python 3.12, `apache-airflow-providers-amazon==9.36.0`, 
`watchtower==3.4.0`, CloudWatch remote logging enabled), both our Triggerer and 
our Celery workers started leaking one idle `watchtower` thread, `queue.Queue`, 
and sequence-token entry for every completed task try / trigger stream. Neither 
leak happened on 2.11.2.
   
   There is already an open PR that fixes the underlying stream lifecycle 
(#73004, plus worker confirmation in 
https://github.com/apache/airflow/pull/73004#issuecomment-6577601794), but it 
doesn't have a linked issue yet and is still waiting on workflow approval and 
review. Opening this issue to document the Celery worker impact and our 
production investigation.
   
   ### Why it happens on Airflow 3.3
   
   Tracing the code in `airflow/sdk/execution_time/supervisor.py`, 
`airflow/sdk/log.py`, 
`airflow/providers/amazon/aws/log/cloudwatch_task_handler.py`, and 
`watchtower/__init__.py`:
   
   1. In Airflow 2.11, `CeleryExecutor` forked per task (`_execute_in_fork`), 
called `CloudwatchTaskHandler.close()` (which called 
`watchtower_handler.close()`), and exited the child process via `os._exit()`.
   2. In Airflow 3.3, `execute_workload` runs `supervise_task()` inside the 
long-lived Celery prefork pool process. Each pool process holds a singleton 
`CloudWatchRemoteLogIO` (`_ActiveLoggingConfig.remote_task_log`) with a single 
cached `watchtower.CloudWatchLogHandler(use_queues=True)`.
   3. On each task try, `CloudWatchRemoteLogIO.processors` mutates 
`handler.log_stream_name` to that task's path 
(`dag_id=.../run_id=.../task_id=.../attempt=N.log`). In `watchtower==3.4.0`, 
`emit()` sees a new `stream_name`, allocates `self.queues[stream_name] = 
queue.Queue()` and `self.sequence_tokens[stream_name]`, and starts a new daemon 
thread running `_dequeue_batch`.
   4. When the task finishes, `_upload_logs()` calls 
`CloudWatchRemoteLogIO.upload()` -> `self.close()`, which only calls 
`handler.flush()`. `flush()` drains queued events via `self.FLUSH`, whereas 
`_dequeue_batch` only exits on `self.END` (sent only by `handler.close()`). 
Every completed task try leaves its daemon thread sleeping on `my_queue.get()` 
for the lifetime of the Celery pool process, and every subsequent `flush()` 
iterates over all historical queues in `self.queues.values()`.
   
   ### Investigation & production evidence
   
   1. **Process / `/proc` inspection:**
      - **Triggerer (1 GiB task):** After the 3.3.2 cutover, memory jumped from 
~47% to ~75% and climbed at ~2 MiB/h. At ~29h uptime, the supervisor process 
had 209 idle threads (193 created post-startup at ~6.7/h, matching trigger 
completions), while open file descriptors stayed flat at 31.
      - **Celery workers (4 tasks x 8 GiB, `worker_concurrency = 12`):** At 
~32h uptime, thread counts across the 12 prefork pool processes on one worker 
ranged from 7 to 514 (the busiest slot had run ~500 tasks). `RssAnon` scaled 
linearly with thread count at ~327 kB per leaked thread (194 MiB at 7 threads 
vs 356 MiB at 514 threads), totaling ~1,660 leaked threads and ~530 MiB on that 
worker alone.
   
   2. **Two 7-day production memory cycles on ECS CloudWatch (Nov 1 to Nov 
23):**
      - **Pre-upgrade on 2.11.2 (Nov 1 to Nov 8):** Daily average memory across 
the 4 workers stayed flat at 28% to 32% of 8 GiB, with a flat idle floor 
(`min`) of 18.2% to 18.7%.
      - **Cycle 1 on 3.3.2 (Nov 9 upgrade to Nov 16):** Idle floor climbed 
steadily from 17.7% to 43.7%, average climbed to 60.0%, and peak hit **87.8% 
(7,197 MiB / 8,192 MiB)** right before an unrelated config deploy on Nov 16 
replaced the tasks and reset memory.
      - **Cycle 2 on 3.3.2 (Nov 16 deploy to Nov 23, ~167h uptime):** Repeated 
the same slope. The 3h average climbed from 21.8% to 61.3% (~19.4 MiB/h), the 
min floor climbed from 13.9% to 47.1% (~16.3 MiB/h), and peak hit **87.7% 
(7,184 MiB / 8,192 MiB)**, leaving ~1 GiB of headroom under morning bursts.
   
   Celery worker daily memory utilization (Nov 1-23)
   
   <img width="2702" height="1196" alt="Screenshot 2026-11-23 at 10 29 51" 
src="https://github.com/user-attachments/assets/8e3b420f-4998-4c69-8794-42cae7540258";
 />
   
   ### Minimal reproducer (no AWS credentials needed)
   
   ```python
   import os
   from itertools import count
   from pathlib import Path
   
   import structlog
   import watchtower
   from airflow.providers.amazon.aws.log.cloudwatch_task_handler import 
CloudWatchRemoteLogIO
   
   
   class FakeLogsClient:
       def __init__(self):
           self.tokens = count(1)
   
       def put_log_events(self, **kwargs):
           return {"nextSequenceToken": str(next(self.tokens))}
   
   
   base = Path("/tmp/cw_repro_logs")
   os.environ["AIRFLOW__LOGGING__BASE_LOG_FOLDER"] = str(base)
   
   io = CloudWatchRemoteLogIO(
       base_log_folder=base,
       log_group_arn="arn:aws:logs:us-east-1:123456789012:log-group:test-group",
       delete_local_copy=True,
   )
   io._cached_handler = watchtower.CloudWatchLogHandler(
       log_group_name="test-group",
       boto3_client=FakeLogsClient(),
       create_log_group=False,
       create_log_stream=False,
       use_queues=True,
   )
   proc = io.processors[0]
   
   for i in range(50):
       rel = f"dag_id=d/run_id=run_{i}/task_id=t/attempt=1.log"
       p = base / rel
       p.parent.mkdir(parents=True, exist_ok=True)
       with p.open("w") as f:
           proc(structlog.PrintLogger(f), "info", {"event": f"task {i}"})
       io.upload(rel)
   
   print("queues:", len(io.handler.queues))
   print("sequence_tokens:", len(io.handler.sequence_tokens))
   print("live watchtower threads:", sum(t.is_alive() for t in 
io.handler.threads))
   io.handler.close()
   
   ### What you think should happen instead?
   
   When `CloudWatchRemoteLogIO.upload(path)` finishes a task try or trigger log 
stream, the Watchtower worker thread, queue, and sequence-token state for that 
completed stream should be closed and released so long-lived processes (Celery 
prefork pool workers and Triggerer) keep a constant thread count and flat 
baseline memory across tasks.
   
   We checked the diff in https://github.com/apache/airflow/pull/73004 against 
`airflow/sdk/log.py`: even though the PR title/body focus on the Triggerer, 
Celery workers also load `CloudWatchRemoteLogIO.processors` (setting 
`_streaming_by_path = True`), and `upload_to_remote()` passes the matching 
relative stream path into `upload(path, ti)`. Closing the per-stream handler in 
`_close_stream()` sends `END` to that stream's Watchtower queue and fixes the 
leak for Celery workers as well, while `create_log_group=False` on stream 
handlers avoids extra `DescribeLogGroups` calls.
   
   ### Operating System
   
   Debian GNU/Linux 12 (bookworm) (apache/airflow:slim-3.3.2-python3.12)
   
   ### Deployment
   
   Other Docker-based deployment
   
   ### Apache Airflow Provider(s)
   
   amazon
   
   ### Versions of Apache Airflow Providers
   
   apache-airflow-providers-amazon==9.36.0 (also still present in 9.40.0 / main)
   apache-airflow-providers-celery==3.24.0
   watchtower==3.4.0
   celery==5.6.3
   billiard==4.2.4
   
   ### Official Helm Chart version
   
   Not Applicable
   
   ### Kubernetes Version
   
   _No response_
   
   ### Helm Chart configuration
   
   _No response_
   
   ### Docker Image customizations
   
   Extended apache/airflow:slim-3.3.2-python3.12 with 
apache-airflow-providers-amazon[s3fs]==9.36.0 and CloudWatch remote logging 
enabled (remote_logging = True, delete_local_logs = True, 
remote_base_log_folder = cloudwatch://...).
   
   ### Anything else?
   
   ### Current stopgaps
   
   - **Triggerer:** We set `AIRFLOW__LOGGING__REMOTE_LOGGING=False` on the 
Triggerer container only (since the UI doesn't read completed `.trigger.*` 
streams anyway per #70317). Triggerer memory has stayed flat at ~31% to 32% 
over 7 days since making that change.
   - **Celery workers:** Turning off remote logging isn't an option on workers 
since we'd lose completed task logs. As a stopgap, we are setting 
`AIRFLOW__CELERY__EXTRA_CELERY_CONFIG={"worker_max_tasks_per_child": 100}` on 
the worker containers so Celery recycles each pool child every 100 tasks 
(bounding the leak to ~100 threads / ~33 MiB per pool process, since 
replacement children fork from `MainProcess` with empty `queues` and 
`threads`). We haven't validated this over a multi-day production run yet.
   
   ### Request
   
   Since https://github.com/apache/airflow/pull/73004 already implements 
per-stream handler teardown with unit tests covering sequential streams and 
close races (and currently sits with `need workflow approval`), could a 
maintainer please approve the CI workflow and take a look at reviewing that PR?
   
   ### Are you willing to submit PR?
   
   - [ ] Yes I am willing to submit a PR!
   
   ### Code of Conduct
   
   - [x] I agree to follow this project's [Code of 
Conduct](https://github.com/apache/airflow/blob/main/CODE_OF_CONDUCT.md)
   


-- 
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]

  • [I] CloudWatchRemoteLogIO leak... victormacaubas (via GitHub) via commits

Reply via email to