ephraimbuddy commented on code in PR #77564:
URL: https://github.com/apache/airflow/pull/77564#discussion_r4691933943


##########
airflow-core/src/airflow/dag_processing/bundles/base.py:
##########
@@ -501,11 +501,13 @@ def _update_version_file(self):
             assert self.lock_file_path
         self.lock_file_path.parent.mkdir(parents=True, exist_ok=True)
 
-        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())
+        with tempfile.NamedTemporaryFile(mode="w", 
dir=self.lock_file_path.parent, delete=False) as tmp:

Review Comment:
   `dir=self.lock_file_path.parent` puts the `tmpXXXX` file inside the tracking 
directory, and `_find_all_tracking_files` treats every entry there as a version:
   
   - `iterdir()` lists the temp file, `os.replace` renames it away, and 
`read_text()` raises `FileNotFoundError`, which aborts the whole pass. That's 
the failure this PR fixes, raised as a different exception. With one thread 
looping `_update_version_file` and another looping `_find_all_tracking_files` 
for 3 s, 1,726 of 16,381 scans aborted (main: 0 aborts on pendulum 3.3).
   - A temp file read in time comes back as a version named `tmpXXXX` and takes 
one of the `stale_bundle_cleanup_min_versions` slots.
   - `NamedTemporaryFile` creates files as `0600`, so after the replace the 
tracking file is owner-only (main: `0644`). Where processes running as 
different users share bundle storage, `acquire()` can't open the file (and 
`__enter__` swallows the error), and cleanup's `read_text()` raises 
`PermissionError`.
   
   The in-place write suggested on lines 504–510 avoids all three.



##########
airflow-core/src/airflow/dag_processing/bundles/base.py:
##########
@@ -501,11 +501,13 @@ def _update_version_file(self):
             assert self.lock_file_path
         self.lock_file_path.parent.mkdir(parents=True, exist_ok=True)
 
-        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())
+        with tempfile.NamedTemporaryFile(mode="w", 
dir=self.lock_file_path.parent, delete=False) as tmp:
+            tmp.write(pendulum.now(tz=pendulum.UTC).isoformat())
+            temp_file = Path(tmp.name)
+        try:
             os.replace(temp_file, self.lock_file_path)
+        finally:
+            temp_file.unlink(missing_ok=True)

Review Comment:
   This breaks the version lock. `flock` locks the open file, not its name: 
`acquire()` holds `LOCK_SH` on the file it opened, while `_remove_stale_bundle` 
opens whatever the path points to *now* and takes `LOCK_EX | LOCK_NB`.
   
   1. Task A acquires `v1` and keeps running (`LOCK_SH` on inode 1).
   2. Task B acquires `v1`. `os.replace` points the path at inode 2. B finishes 
and releases.
   3. Cleanup opens the path (inode 2), gets `LOCK_EX`, and `rmtree`s the 
version directory while A is still running.
   
   Every task takes this lock, so several tasks on one version is the normal 
case on a worker, and the long-running task is the one the lock exists to 
protect. I ran that sequence with these two functions patched onto main and 
`stale_bundle_cleanup_min_versions=0` / `stale_bundle_cleanup_age_threshold=0`. 
Main keeps the directory; this change deletes it.
   
   Overwriting in place keeps the same inode, so held locks stay effective:
   
   ```suggestion
           fd = os.open(self.lock_file_path, os.O_RDWR | os.O_CREAT, 0o644)
           try:
               # Overwrite in place: replacing the file would leave held flocks 
on an unlinked inode.
               # UTC isoformat with microseconds is always 32 bytes, so no 
stale bytes are left behind.
               os.pwrite(fd, 
pendulum.now(tz=pendulum.UTC).isoformat(timespec="microseconds").encode(), 0)
           finally:
               os.close(fd)
   ```
   
   A brand-new file is still empty for an instant before its first write, and 
your `_parse_dt` change covers that.



##########
airflow-core/src/airflow/dag_processing/bundles/base.py:
##########
@@ -100,7 +100,7 @@ def _parse_dt(self, val) -> DateTime | None:
         try:
             dt = pendulum.parse(val)
             return dt if isinstance(dt, pendulum.DateTime) else None
-        except ParserError:
+        except (ParserError, ValueError):

Review Comment:
   nit: `ParserError` subclasses `ValueError`, so `except ValueError` covers 
both. A short note keeps someone from narrowing it back:
   
   ```suggestion
           except ValueError:  # pendulum 3.1 raises a plain ValueError, not 
ParserError, for ""
   ```



##########
airflow-core/tests/unit/dag_processing/bundles/test_base.py:
##########
@@ -218,6 +218,17 @@ def test_that_no_version_is_noop(self):
         assert b.lock_file_path is None
         assert b.lock_file is None
 
+    def 
test_update_version_file_writes_parseable_timestamp_with_no_leftover_temp_files(self):
+        lock = BundleVersionLock(
+            bundle_name="abc",
+            bundle_version="v1",
+        )
+        lock._update_version_file()
+        assert lock.lock_file_path is not None
+        assert lock.lock_file_path.exists()
+        assert 
BundleUsageTrackingManager()._parse_dt(lock.lock_file_path.read_text()) is not 
None
+        assert list(lock.lock_file_path.parent.iterdir()) == 
[lock.lock_file_path]

Review Comment:
   This is the assertion failing CI. `STALE_BUNDLE_TRACKING_FOLDER` is computed 
at import time, so the autouse `bundle_temp_dir` fixture doesn't redirect it. 
The test writes to the shared `<tmp>/airflow/dag_bundles/_tracking/abc`, which 
already holds `this` from `LockTestHelper`. Patching `get_bundle_tracking_file` 
to `tmp_path` isolates it, as your `_find_all_tracking_files` test does with 
`get_bundle_tracking_dir`. With an in-place write there are no temp files to 
check for, so this assertion can go.



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