ferruzzi commented on code in PR #75502: URL: https://github.com/apache/airflow/pull/75502#discussion_r4636118128
########## airflow-core/tests/unit/dag_processing/bundles/test_manifest_local.py: ########## @@ -0,0 +1,1441 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import errno +import gc +import importlib +import json +import os +import shutil +import stat +import sys +from importlib.util import cache_from_source +from pathlib import Path +from unittest import mock + +import pytest + +from airflow.dag_processing.bundles import ( + _filesystem as filesystem_module, + filesystem_artifact_store as store_module, + manifest_bundle as bundle_module, +) +from airflow.dag_processing.bundles._filesystem import remove_bundle_tree_forcefully +from airflow.dag_processing.bundles.artifact_store import BundleManifestNotFoundError +from airflow.dag_processing.bundles.base import ( + BundleUsageTrackingManager, + BundleVersion, + get_bundle_tracking_file, +) +from airflow.dag_processing.bundles.manifest import ( + MANIFEST_FILE_NAME, + MANIFEST_SCHEMA_VERSION, + BundleManifestError, + BundleManifestSourceChangedError, + build_bundle_version_manifest, + serialize_bundle_version_manifest, +) +from airflow.dag_processing.bundles.manifest_bundle import BundleManifestReferenceChangedError +from airflow.dag_processing.bundles.manifest_local import ( + ManifestLocalDagBundle, + publish_manifest_local_dag_bundle, +) +from airflow.exceptions import AirflowException + +from tests_common.test_utils.config import conf_vars + +pytestmark = pytest.mark.usefixtures("isolate_bundle_storage") + +BUNDLE_NAME = "manifest-local" + + +_real_scandir = os.scandir + + +def _scandir_unless_unlistable(path="."): + """List directories, failing for any named ``unlistable`` as an I/O fault would.""" + if os.path.basename(os.fspath(path)) == "unlistable": + raise PermissionError(errno.EACCES, "cannot list directory", os.fspath(path)) + return _real_scandir(path) + + +def _write_file(root: Path, relative_path: str, content: str) -> Path: + path = root / relative_path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + return path + + +def _write_manifest_ref(manifest_ref_path: Path | str, ref_payload: dict) -> None: + manifest_ref_path = Path(manifest_ref_path) + manifest_ref_path.parent.mkdir(parents=True, exist_ok=True) + manifest_ref_path.write_bytes(serialize_bundle_version_manifest(ref_payload)) + + +def _add_write_bits(path: Path) -> None: + write_bits = 0o700 if path.is_dir() else 0o600 + path.chmod(stat.S_IMODE(path.stat().st_mode) | write_bits) + + +def _create_symlink_or_skip(target: Path, link: Path, *, target_is_directory: bool = False) -> None: + try: + link.symlink_to(target, target_is_directory=target_is_directory) + except OSError as e: + pytest.skip(f"Symlinks are not supported in this test environment: {e}") + + +def _make_bundle(tmp_path: Path, **kwargs) -> ManifestLocalDagBundle: + published_root = tmp_path / "published" + published_root.mkdir(parents=True, exist_ok=True) + return ManifestLocalDagBundle(name=BUNDLE_NAME, published_root=str(published_root), **kwargs) + + +def _get_published_root(bundle: ManifestLocalDagBundle) -> Path: + store = bundle._store + assert isinstance(store, store_module.FilesystemArtifactStore) + return store.published_root + + +def _get_ref_path(bundle: ManifestLocalDagBundle) -> Path: + return _get_published_root(bundle) / "refs" / bundle.name / "latest.json" + + +def _get_snapshots_dir(bundle: ManifestLocalDagBundle) -> Path: + return _get_published_root(bundle) / "versions" / bundle.name + + +def _get_snapshot_dir(bundle: ManifestLocalDagBundle, version: str) -> Path: + return _get_snapshots_dir(bundle) / version + + +def _publish(bundle: ManifestLocalDagBundle, source: Path, *, materialize_snapshot: bool = True): + if materialize_snapshot: + return publish_manifest_local_dag_bundle(bundle=bundle, source_path=source) + + result = build_bundle_version_manifest(bundle_name=bundle.name, root=source, backend_type="local") + _write_manifest_ref(_get_ref_path(bundle), result.ref_payload) + return result + + +def _published_bundle(tmp_path: Path, **bundle_kwargs): + source = tmp_path / "source" + _write_file(source, "dags/example.py", "print('dag')") + bundle = _make_bundle(tmp_path, **bundle_kwargs) + return bundle, source, _publish(bundle, source) + + +def _call_entry_point(bundle: ManifestLocalDagBundle, entry_point: str): + if entry_point == "path": + return bundle.path + return getattr(bundle, entry_point)() + + +class TestConstruction: + def test_supports_versioning(self): + assert ManifestLocalDagBundle.supports_versioning is True + + @pytest.mark.parametrize("published_root", [None, ""]) + def test_requires_published_root(self, published_root): + # TypeError, not ValueError: callback bundle preparation treats a ValueError from + # bundle construction as "bundle no longer configured", silently dropping callbacks. + with pytest.raises(TypeError, match="published_root must be provided"): + ManifestLocalDagBundle(name=BUNDLE_NAME, published_root=published_root) + + @pytest.mark.parametrize( + "published_root", ["s3://bucket/releases", "s3:/bucket/releases", "gs://bucket", "s3:releases"] + ) + def test_rejects_url_shaped_published_root(self, published_root): + with pytest.raises(TypeError, match="Unsupported published_root scheme"): + ManifestLocalDagBundle(name=BUNDLE_NAME, published_root=published_root) + + @pytest.mark.parametrize("allow_empty_source", ["true", 1, None]) + def test_rejects_non_boolean_allow_empty_source(self, tmp_path, allow_empty_source): + with pytest.raises(TypeError, match="allow_empty_source must be a boolean"): + _make_bundle(tmp_path, allow_empty_source=allow_empty_source) + + def test_published_root_derives_authoritative_locations(self, tmp_path): + bundle = _make_bundle(tmp_path) + version = "sha256-" + "a" * 64 + + assert _get_published_root(bundle) == tmp_path / "published" + assert bundle._store.ref_locator == str(tmp_path / "published/refs/manifest-local/latest.json") + assert bundle._store.snapshot_locator(version) == str( + tmp_path / "published/versions/manifest-local" / version + ) + + @pytest.mark.parametrize("publication_lock_timeout", ["600", True, -1, None, float("nan"), float("inf")]) + def test_rejects_invalid_publication_lock_timeout(self, tmp_path, publication_lock_timeout): + with pytest.raises(TypeError, match="publication_lock_timeout must be a finite, non-negative number"): + _make_bundle(tmp_path, publication_lock_timeout=publication_lock_timeout) + + def test_publication_lock_timeout_bounds_the_publisher_wait(self, tmp_path): + source = tmp_path / "source" + _write_file(source, "dags/example.py", "print('dag')") + holder = _make_bundle(tmp_path) + bundle = _make_bundle(tmp_path, publication_lock_timeout=0) + + with ( + holder.acquire_publication_lock(), + pytest.raises(BundleManifestError, match="Timed out after 0s waiting for publication lock"), + ): + publish_manifest_local_dag_bundle(bundle=bundle, source_path=source) + + assert not _get_ref_path(bundle).exists() + + @pytest.mark.parametrize("published_root_position", ["inside", "ancestor"]) + def test_rejects_published_root_overlapping_airflow_cache(self, tmp_path, published_root_position): + cache_root = tmp_path / "cache" + published_root = cache_root / "published" if published_root_position == "inside" else tmp_path + + with ( + conf_vars({("dag_processor", "dag_bundle_storage_path"): str(cache_root)}), + pytest.raises(TypeError, match="must not overlap Airflow's bundle cache"), + ): + ManifestLocalDagBundle(name=BUNDLE_NAME, published_root=str(published_root)) + + +class TestConsumer: + def test_get_current_version_returns_bundle_version_from_ref(self, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + + # The version string is the whole contract: no metadata flows through Airflow. + assert bundle.get_current_version() == BundleVersion(version=published.version, data=None) + + def test_pinned_get_current_version_does_not_read_ref(self, tmp_path): + version = f"sha256-{'a' * 64}" + bundle = _make_bundle(tmp_path, version=version) + + assert bundle.get_current_version() == BundleVersion(version=version) + + def test_path_and_get_current_version_do_not_materialize_snapshots(self, tmp_path): + missing_version = f"sha256-{'0' * 64}" + _write_manifest_ref( + tmp_path / "published/refs/manifest-local/latest.json", + { + "schema_version": MANIFEST_SCHEMA_VERSION, + "bundle_name": BUNDLE_NAME, + "version": missing_version, + "backend": {"type": "local"}, + "manifest": {"path": MANIFEST_FILE_NAME, "sha256": f"sha256:{'1' * 64}"}, + "file_count": 0, + "total_size": 0, + }, + ) + bundle = _make_bundle(tmp_path) + + with mock.patch.object( + ManifestLocalDagBundle, "_materialize_cached_version", autospec=True + ) as mock_materialize: + assert bundle.get_current_version().version == missing_version + assert bundle.path == bundle.versions_dir / missing_version + mock_materialize.assert_not_called() + + with pytest.raises(BundleManifestNotFoundError, match="not published"): + bundle.initialize() + + def test_path_loads_materialized_snapshot_before_refresh(self, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + + assert bundle._current_manifest_ref is None + assert bundle.path == bundle.versions_dir / published.version + + def test_refresh_uses_materialized_snapshot_for_latest_path(self, tmp_path): + source = tmp_path / "source" + _write_file(source, "dags/example.py", "print('dag')") + _write_file(source, "dags/__pycache__/ignored.pyc", "compiled") + bundle = _make_bundle(tmp_path) + published = _publish(bundle, source) + + bundle.refresh() + + assert bundle.path == bundle.versions_dir / published.version + assert bundle.path != source + assert (bundle.path / "dags/example.py").read_text() == "print('dag')" + assert not (bundle.path / "dags/example.py").stat().st_mode & 0o200 + assert stat.S_IMODE(bundle.path.stat().st_mode) == 0o755 + assert stat.S_IMODE((bundle.path / "dags").stat().st_mode) == 0o755 + assert not (bundle.path / "dags/__pycache__/ignored.pyc").exists() + snapshot_manifest = json.loads((bundle.path / MANIFEST_FILE_NAME).read_text()) + assert snapshot_manifest["version"] == published.version + assert [file_info["path"] for file_info in snapshot_manifest["files"]] == ["dags/example.py"] + + def test_initialize_materializes_current_release(self, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + + bundle.initialize() + + assert bundle.is_initialized + assert (bundle.versions_dir / published.version / "dags/example.py").read_text() == "print('dag')" + + def test_source_changes_without_ref_update_do_not_affect_get_current_version(self, tmp_path): + bundle, source, published = _published_bundle(tmp_path) + + _write_file(source, "dags/example.py", "print('changed')") + _write_file(source, "dags/new.py", "print('new')") + fresh_bundle = _make_bundle(tmp_path) + + assert fresh_bundle.get_current_version().version == published.version + fresh_bundle.refresh() + assert fresh_bundle.path == fresh_bundle.versions_dir / published.version + assert (fresh_bundle.path / "dags/example.py").read_text() == "print('dag')" + assert not (fresh_bundle.path / "dags/new.py").exists() + + def test_ref_update_changes_bundle_version_when_snapshot_exists(self, tmp_path): + bundle, source, first = _published_bundle(tmp_path) + bundle.refresh() + + _write_file(source, "dags/example.py", "print('changed')") + second = _publish(bundle, source) + bundle.refresh() + + assert second.version != first.version + assert bundle.get_current_version().version == second.version + assert (bundle.path / "dags/example.py").read_text() == "print('changed')" + + def test_ref_update_before_snapshot_materialization_raises_clear_error(self, tmp_path): + source = tmp_path / "source" + _write_file(source, "dags/example.py", "print('dag')") + bundle = _make_bundle(tmp_path) + published = _publish(bundle, source, materialize_snapshot=False) + + with pytest.raises(BundleManifestError, match="not published"): + bundle.refresh() + + assert not (bundle.versions_dir / published.version).exists() + + @mock.patch.object( + bundle_module, "compute_file_sha256", autospec=True, side_effect=bundle_module.compute_file_sha256 + ) + @mock.patch.object( + ManifestLocalDagBundle, + "_validate_snapshot_files", + autospec=True, + side_effect=ManifestLocalDagBundle._validate_snapshot_files, + ) + def test_refresh_rechecks_structure_without_rehashing_validated_cache( + self, mock_validate, mock_hash, tmp_path + ): + bundle, _, published = _published_bundle(tmp_path) + bundle.refresh() + mock_validate.reset_mock() + mock_hash.reset_mock() + + bundle.refresh() + + expected_path = bundle.versions_dir / published.version + for _ in range(3): + assert bundle.path == expected_path + mock_validate.assert_called_once_with( + bundle, mock.ANY, expected_path, check_content=False, allow_cached_bytecode=True + ) + mock_hash.assert_not_called() + + def test_refresh_sweeps_orphaned_temp_snapshots_from_cache(self, tmp_path): + bundle, _, _ = _published_bundle(tmp_path) + bundle.versions_dir.mkdir(parents=True, exist_ok=True) + orphan = bundle.versions_dir / f".sha256-{'a' * 64}.orphan" + _write_file(orphan, "dags/leftover.py", "print('leftover')") + + bundle.refresh() + + assert not orphan.exists() + assert (bundle.path / "dags/example.py").read_text() == "print('dag')" + + @mock.patch.object( + filesystem_module, + "remove_bundle_tree_forcefully", + autospec=True, + side_effect=PermissionError("operation not permitted"), + ) + def test_refresh_survives_undeletable_orphan_temp_snapshot(self, mock_remove, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + bundle.versions_dir.mkdir(parents=True, exist_ok=True) + orphan = bundle.versions_dir / f".sha256-{'a' * 64}.orphan" + _write_file(orphan, "dags/leftover.py", "print('leftover')") + + bundle.refresh() + + mock_remove.assert_called_once_with(orphan) + assert orphan.exists() + assert (bundle.versions_dir / published.version).is_dir() + + def test_orphaned_validation_markers_are_reaped(self, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + bundle.versions_dir.mkdir(parents=True, exist_ok=True) + orphan_marker = bundle.versions_dir / f".sha256-{'b' * 64}.validated" + orphan_marker.write_text(f"sha256-{'b' * 64}") + + bundle.refresh() + + assert not orphan_marker.exists() + # The live version's marker must survive the sweep. + assert bundle._get_validation_marker_path(published.version).exists() + + def test_cache_tree_and_marker_are_fsynced_in_durability_order(self, tmp_path): + bundle, _, published = _published_bundle(tmp_path) + cached_version_path = bundle.versions_dir / published.version + marker_path = bundle._get_validation_marker_path(published.version) + calls: list[tuple[str, Path]] = [] + real_fsync_file = filesystem_module.fsync_file + real_fsync_directory = filesystem_module.fsync_directory + real_replace = os.replace + + def record_fsync_file(path): + calls.append(("fsync_file", Path(path))) + real_fsync_file(path) + + def record_fsync_directory(path): + calls.append(("fsync_directory", Path(path))) + real_fsync_directory(path) + + def record_replace(source_path, destination_path): + if Path(destination_path) == cached_version_path: + calls.append(("replace_cache", Path(destination_path))) + real_replace(source_path, destination_path) + + with ( Review Comment: Just a nit, but I think we're supposed to be including `autsopec=True` on all of these these `mock.patch.object` instances now, but I forget where I saw hat so maybe I'm just hallucinating it. -- 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]
