hanxdatadog opened a new issue, #77352:
URL: https://github.com/apache/airflow/issues/77352
### Under which category would you file this issue?
Airflow Core
### Apache Airflow version
3.3.2 (the code is unchanged on `main` at
9eb25f92bf25c287ff801d0897c8ee177641710c)
### What happened and how to reproduce it?
Stale bundle version cleanup
(`BundleUsageTrackingManager.remove_stale_bundle_versions()`) intermittently
aborts on busy workers. We use a custom DAG bundle on Celery/Kubernetes workers
that calls `BundleUsageTrackingManager().remove_stale_bundle_versions()` after
fetching a new version. When many tasks start concurrently, the cleanup pass
sometimes fails with `ValueError: year 0 is out of range` and no stale versions
are removed in that pass.
Two problems combine:
1. `BundleVersionLock._update_version_file` is not atomic:
```python
with tempfile.TemporaryDirectory() as td:
temp_file = Path(td, self.lock_file_path)
now = pendulum.now(tz=pendulum.UTC)
temp_file.write_text(now.isoformat())
os.replace(temp_file, self.lock_file_path)
```
`lock_file_path` is absolute, and `Path(td, <absolute path>)` discards
`td`. So `temp_file == self.lock_file_path`, the real tracking file is
truncated and rewritten in place (`write_text` opens with `"w"`), and
`os.replace(f, f)` is a no-op. For a short window the tracking file exists but
is empty.
2. `BundleUsageTrackingManager._find_all_tracking_files` reads every file in
the tracking dir and passes the content to `_parse_dt`, which calls
`pendulum.parse(val)` and only catches `ParserError`. For an empty string
pendulum raises a plain `ValueError: year 0 is out of range` (`_parse_common`
defaults to year 0), not `ParserError`, so the exception escapes and the whole
`remove_stale_bundle_versions()` pass aborts.
**Steps to reproduce**
The `Path` behaviour:
```python
import tempfile
from pathlib import Path
lock = Path("/tmp/tracking/my-bundle/abc123")
with tempfile.TemporaryDirectory() as td:
assert Path(td, lock) == lock # td is discarded; no temp file is used
```
The cleanup failure, simulating a reader that sees the file mid-write:
```python
from airflow.dag_processing.bundles.base import (
BundleUsageTrackingManager,
get_bundle_tracking_dir,
get_bundle_version_path,
)
name = "my-bundle"
d = get_bundle_tracking_dir(bundle_name=name)
d.mkdir(parents=True, exist_ok=True)
for version, content in [("old_version", "2020-01-01T00:00:00+00:00"),
("new_version", "")]:
get_bundle_version_path(bundle_name=name,
version=version).mkdir(parents=True, exist_ok=True)
(d / version).write_text(content)
BundleUsageTrackingManager()._remove_stale_bundle_versions_for_bundle(bundle_name=name)
# ValueError: year 0 is out of range
```
The race itself: with one thread calling
`BundleVersionLock(...)._update_version_file()` in a loop and another reading
the tracking file, about 3% of reads return an empty string on 3.3.2.
### What you think should happen instead?
- Tracking file updates should be atomic, so readers never see a truncated
file.
- One unreadable tracking file should be skipped and logged, like any other
unparseable value, instead of aborting cleanup for every other version.
Proposed fix:
1. In `_update_version_file`, create the temp file in the same directory as
the tracking file and `os.replace` it into place. The rename is then on the
same filesystem, so it's atomic:
```python
fd, tmp = tempfile.mkstemp(dir=self.lock_file_path.parent, prefix=".")
try:
os.fchmod(fd, 0o644) # keep the previous file mode instead of
mkstemp's 0600
with os.fdopen(fd, "w") as f:
f.write(pendulum.now(tz=pendulum.UTC).isoformat())
os.replace(tmp, self.lock_file_path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
```
Fixing only the path to `Path(td, self.lock_file_path.name)` is not
enough. `TemporaryDirectory()` lives under `$TMPDIR`, and `os.replace` raises
`OSError: [Errno 18] Invalid cross-device link` when `dag_bundle_storage_path`
is on a different mount.
2. In `_parse_dt`, also catch `ValueError`. `ParserError` subclasses
`ValueError`, so `except ValueError` covers both. A bad file is then skipped
through the existing "could not parse val as datetime" path.
3. In `_find_all_tracking_files`, skip dot-prefixed files, so in-flight temp
files are never read as tracking files.
With this change, the race test above sees 0 empty reads and cleanup
completes. I'd add unit tests for the empty-file case and for skipping temp
files.
### Operating System
Debian GNU/Linux 12 (bookworm)
### Deployment
Other
### Anything else?
This only happens when cleanup runs while another process is updating a
tracking file for the same bundle, so it's more frequent on busy workers with
many short tasks. The impact is that stale bundle versions aren't cleaned up in
the affected pass, so disk usage grows over time. The exception surfaces in
whichever caller invokes `remove_stale_bundle_versions()`.
Relevant code: `airflow-core/src/airflow/dag_processing/bundles/base.py`
(`BundleVersionLock._update_version_file`,
`BundleUsageTrackingManager._parse_dt`,
`BundleUsageTrackingManager._find_all_tracking_files`).
### Are you willing to submit PR?
- [X] Yes I am willing to submit a PR!
### Code of Conduct
- [X] I agree to follow this project's Code of Conduct
--
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]