This is an automated email from the ASF dual-hosted git repository.

ephraimbuddy pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 6b85b1dcf7c Add a versioned local Dag bundle backed by manifest 
snapshots (#75502)
6b85b1dcf7c is described below

commit 6b85b1dcf7c9dcc6b3b3d81780d1f5deae5b4f25
Author: Ephraim Anierobi <[email protected]>
AuthorDate: Wed Nov 25 11:32:16 2026 +0100

    Add a versioned local Dag bundle backed by manifest snapshots (#75502)
    
    * Add a versioned local Dag bundle backed by manifest snapshots
    
    Dag runs must keep using the release they pinned after new deployments.
    Published snapshots allow processors and workers to use the same verified
    release while keeping cache cleanup independent of authoritative artifacts.
    
    * Autospec the patched functions in the manifest local bundle tests
    
    A plain patch accepts any call, so a test keeps passing after the
    patched function's signature changes and the code under test calls it
    wrongly. Autospec makes those calls fail the same way the real function
    would.
---
 .../airflow/dag_processing/bundles/_filesystem.py  |   18 +-
 .../src/airflow/dag_processing/bundles/manifest.py |    5 +-
 .../dag_processing/bundles/manifest_bundle.py      | 1032 ++++++++++++++
 .../dag_processing/bundles/manifest_local.py       |   78 ++
 .../tests/unit/dag_processing/bundles/conftest.py  |   36 +
 .../dag_processing/bundles/test__filesystem.py     |   30 +
 .../dag_processing/bundles/test_manifest_bundle.py |  298 ++++
 .../dag_processing/bundles/test_manifest_local.py  | 1452 ++++++++++++++++++++
 8 files changed, 2946 insertions(+), 3 deletions(-)

diff --git a/airflow-core/src/airflow/dag_processing/bundles/_filesystem.py 
b/airflow-core/src/airflow/dag_processing/bundles/_filesystem.py
index 1ba487d75d8..2e4faf7f4ea 100644
--- a/airflow-core/src/airflow/dag_processing/bundles/_filesystem.py
+++ b/airflow-core/src/airflow/dag_processing/bundles/_filesystem.py
@@ -29,7 +29,7 @@ import os
 import shutil
 import stat
 from pathlib import Path
-from typing import Any, NoReturn
+from typing import TYPE_CHECKING, Any, NoReturn
 
 from airflow.dag_processing.bundles.artifact_store import 
BundleManifestNotFoundError
 from airflow.dag_processing.bundles.manifest import (
@@ -38,6 +38,9 @@ from airflow.dag_processing.bundles.manifest import (
     is_sha256_hex,
 )
 
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
 log = logging.getLogger(__name__)
 
 
@@ -173,3 +176,16 @@ def fsync_tree_directories(root: Path) -> None:
     directories = [Path(dirpath) for dirpath, _, _ in os.walk(root, 
onerror=raise_walk_error)]
     for directory in sorted(directories, key=lambda path: len(path.parts), 
reverse=True):
         fsync_directory(directory)
+
+
+def fsync_tree(root: Path, *, ignore_file: Callable[[Path], bool] | None = 
None) -> None:
+    """Make regular files and directory entries durable, excluding files 
matched by ``ignore_file``."""
+    for dirpath, dirnames, filenames in os.walk(root):
+        dirnames.sort()
+        for filename in sorted(filenames):
+            path = Path(dirpath) / filename
+            if ignore_file is not None and ignore_file(path):
+                continue
+            if not path.is_symlink():
+                fsync_file(path)
+    fsync_tree_directories(root)
diff --git a/airflow-core/src/airflow/dag_processing/bundles/manifest.py 
b/airflow-core/src/airflow/dag_processing/bundles/manifest.py
index 91a1ba46c6a..0147c6bc347 100644
--- a/airflow-core/src/airflow/dag_processing/bundles/manifest.py
+++ b/airflow-core/src/airflow/dag_processing/bundles/manifest.py
@@ -349,7 +349,8 @@ def build_ref_payload(
     }
 
 
-def _build_ref_payload_from_manifest(manifest: dict[str, Any]) -> dict[str, 
Any]:
+def build_ref_payload_from_manifest(manifest: dict[str, Any]) -> dict[str, 
Any]:
+    """Build the release-reference payload that names ``manifest`` by its 
digest."""
     manifest_sha256 = 
hashlib.sha256(serialize_bundle_version_manifest(manifest)).hexdigest()
     return build_ref_payload(
         bundle_name=manifest["bundle_name"],
@@ -434,7 +435,7 @@ def build_bundle_version_manifest(
     return BundleVersionManifest(
         version=version,
         manifest=manifest,
-        ref_payload=_build_ref_payload_from_manifest(manifest),
+        ref_payload=build_ref_payload_from_manifest(manifest),
         source_snapshot=source_snapshot,
     )
 
diff --git a/airflow-core/src/airflow/dag_processing/bundles/manifest_bundle.py 
b/airflow-core/src/airflow/dag_processing/bundles/manifest_bundle.py
new file mode 100644
index 00000000000..10f8cc46de0
--- /dev/null
+++ b/airflow-core/src/airflow/dag_processing/bundles/manifest_bundle.py
@@ -0,0 +1,1032 @@
+# 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.
+"""Shared lifecycle for immutable, content-addressed manifest-backed Dag 
bundles."""
+
+from __future__ import annotations
+
+import logging
+import math
+import os
+import stat
+import tempfile
+import weakref
+from abc import ABC, abstractmethod
+from contextlib import contextmanager, suppress
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from airflow.dag_processing.bundles._filesystem import (
+    ensure_destination_is_within_root,
+    fsync_directory,
+    fsync_file,
+    fsync_tree,
+    get_temp_snapshot_prefix,
+    raise_walk_error,
+    read_json_file,
+    remove_bundle_tree_forcefully,
+    remove_orphaned_temp_snapshots,
+)
+from airflow.dag_processing.bundles.artifact_store import (
+    ArtifactStoreConflictError,
+    BundleManifestNotFoundError,
+)
+from airflow.dag_processing.bundles.base import (
+    BaseDagBundle,
+    BundleVersion,
+    BundleVersionLock,
+    get_bundle_storage_root_path,
+    get_bundle_tracking_file,
+)
+from airflow.dag_processing.bundles.filesystem_artifact_store import (
+    DEFAULT_PUBLICATION_LOCK_TIMEOUT,
+    FilesystemArtifactStore,
+)
+from airflow.dag_processing.bundles.manifest import (
+    MANIFEST_FILE_NAME,
+    MANIFEST_SCHEMA_VERSION,
+    BundleManifestError,
+    BundleSourceSnapshot,
+    build_bundle_version_manifest,
+    build_ref_payload,
+    build_ref_payload_from_manifest,
+    compute_file_sha256,
+    is_valid_bundle_version,
+    validate_bundle_relative_path,
+    validate_bundle_version,
+    validate_bundle_version_manifest_structure,
+    verify_bundle_version_manifest,
+)
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator, Mapping
+
+    from airflow.dag_processing.bundles.artifact_store import ArtifactStore
+    from airflow.dag_processing.bundles.manifest import BundleVersionManifest
+
+log = logging.getLogger(__name__)
+
+
+@contextmanager
+def _reraise_oserror_as_manifest_error():
+    """
+    Re-raise ``OSError`` from published-artifact or cache access as 
``BundleManifestError``.
+
+    Keeps the Airflow-facing entry points to one error type for "this bundle 
cannot be read".
+    A ``BundleManifestNotFoundError`` is already a ``BundleManifestError`` and 
passes through.
+    """
+    try:
+        yield
+    except BundleManifestError:
+        raise
+    except OSError as e:
+        raise BundleManifestError(str(e)) from e
+
+
+class BundleManifestReferenceChangedError(BundleManifestError):
+    """Raised when a publisher's expected manifest reference is stale."""
+
+
+@dataclass(frozen=True)
+class BundleManifestRef:
+    """Compact pointer to an immutable manifest bundle artifact."""
+
+    version: str
+    ref_payload: dict[str, Any]
+    manifest_sha256: str
+
+
+@dataclass(frozen=True)
+class BundlePublishResult:
+    """
+    Result of publishing an immutable manifest bundle snapshot.
+
+    ``snapshot_locator`` and ``ref_locator`` are the store's opaque 
identifiers of the snapshot
+    and the release reference.
+    """
+
+    bundle_name: str
+    version: str
+    ref_payload: dict[str, Any]
+    snapshot_locator: str
+    ref_locator: str
+    manifest_sha256: str
+    file_count: int
+    total_size: int
+    created_snapshot: bool
+
+
+@dataclass(frozen=True)
+class PreparedPublishSource:
+    """
+    One materialized source observation prepared by a concrete adapter.
+
+    ``file_version_ids`` maps each relative path to the backend's identifier 
for the stored
+    object it was materialized from, such as an S3 ``VersionId``; the manifest 
records them.
+    """
+
+    root: Path
+    source_snapshot: BundleSourceSnapshot
+    file_version_ids: Mapping[str, str] | None = None
+
+
+class ManifestDagBundleBase(BaseDagBundle, ABC):
+    """
+    Shared runtime for content-addressed manifest-backed Dag bundles.
+
+    Publishers write immutable snapshots and a release reference to the 
artifact store that
+    ``create_artifact_store`` builds. Airflow parses and runs only validated, 
read-only cache
+    copies of those snapshots, made in ``versions_dir``. The version hashes 
the canonical file
+    entries (paths, content hashes, sizes, and executable flags), excluding 
backend metadata
+    and object version IDs. The release reference separately records the full 
manifest's digest.
+
+    :param published_root: Shared filesystem path containing published 
snapshots and the
+        current release reference. Provision this directory on the mounted 
filesystem before
+        publication; the store creates only its subdirectories. Required by 
the default
+        ``create_artifact_store``; a subclass whose store has no published 
root may omit it.
+    :param allow_empty_source: Permit publication of a source tree with no 
files. Off by
+        default so that a failed or incomplete sync cannot remove every Dag 
from the release.
+    :param publication_lock_timeout: Seconds a publisher waits for another 
publisher to
+        release the publication lock before failing.
+    """
+
+    supports_versioning = True
+
+    def __init__(
+        self,
+        *,
+        published_root: str | None = None,
+        allow_empty_source: bool = False,
+        publication_lock_timeout: float = DEFAULT_PUBLICATION_LOCK_TIMEOUT,
+        **kwargs,
+    ) -> None:
+        super().__init__(**kwargs)
+        if not isinstance(allow_empty_source, bool):
+            raise TypeError("allow_empty_source must be a boolean")
+        self._configured_published_root = published_root
+        self._publication_lock_timeout = publication_lock_timeout
+        self._store: ArtifactStore = self.create_artifact_store()
+        self.allow_empty_source = allow_empty_source
+        self._validated_version_paths: set[tuple[str, str, str]] = set()
+        self._current_manifest_ref: BundleManifestRef | None = None
+        self._release_version_in_use: weakref.finalize | None = None
+
+    def create_artifact_store(self) -> ArtifactStore:
+        """
+        Build the artifact store that holds this bundle's release reference 
and snapshots.
+
+        Called once from ``__init__``, after ``BaseDagBundle.__init__``, so an 
override can use
+        ``self.name``. Set any attributes the override needs before calling
+        ``super().__init__``. Report configuration errors as ``TypeError``: 
callback bundle
+        preparation treats a ``ValueError`` from bundle construction as 
"bundle no longer
+        configured" and silently drops the callback.
+
+        The default keeps the artifacts on a shared filesystem under 
``published_root``.
+        """
+        published_root = self._configured_published_root
+        if not published_root:
+            raise TypeError("published_root must be provided")
+        published_root_str = str(published_root)
+        # A URL-shaped value must fail loudly instead of becoming a filesystem 
directory
+        # literally named after the URL. This also catches a URL mangled by 
pathlib
+        # (``Path("s3://b")`` collapses to ``s3:/b``).
+        if ":" in published_root_str.split("/", 1)[0]:
+            raise TypeError(
+                f"Unsupported published_root scheme: {published_root_str!r}. 
Use a filesystem path."
+            )
+        published_root_path = Path(published_root)
+        if _paths_overlap(published_root_path, get_bundle_storage_root_path()):
+            raise TypeError(
+                "published_root must not overlap Airflow's bundle cache. 
Configure separate "
+                "authoritative publication and dag_bundle_storage_path 
locations."
+            )
+        publication_lock_timeout = self._publication_lock_timeout
+        if (
+            not isinstance(publication_lock_timeout, (int, float))
+            or isinstance(publication_lock_timeout, bool)
+            or not math.isfinite(publication_lock_timeout)
+            or publication_lock_timeout < 0
+        ):
+            raise TypeError("publication_lock_timeout must be a finite, 
non-negative number of seconds")
+        return FilesystemArtifactStore(
+            bundle_name=self.name,
+            published_root=published_root_path,
+            lock_timeout=publication_lock_timeout,
+        )
+
+    @abstractmethod
+    def confirm_publish_source(self, prepared: PreparedPublishSource) -> None:
+        """Raise if the concrete source no longer matches ``prepared``."""
+
+    def get_current_version(self) -> BundleVersion:
+        """
+        Return the current version.
+
+        The version string alone is the whole contract: it is the content hash 
of the
+        snapshot's manifest entries, so a pinned snapshot is self-certifying 
and no
+        side-channel metadata needs to flow through Airflow.
+        """
+        if self.version:
+            return BundleVersion(version=self.version)
+        with _reraise_oserror_as_manifest_error():
+            manifest_ref = self._ensure_current_manifest_ref()
+        return BundleVersion(version=manifest_ref.version)
+
+    def initialize(self) -> None:
+        if self.version:
+            self._validated_version_paths.clear()
+            version = validate_bundle_version(self.version, source="pinned 
version")
+            with _reraise_oserror_as_manifest_error():
+                if not self._has_validated_cache(version, manifest_ref=None):
+                    with self.lock():
+                        self._materialize_cached_version(version=version, 
manifest_ref=None)
+        else:
+            self.refresh()
+        super().initialize()
+
+    def refresh(self) -> None:
+        if self.version:
+            raise ValueError("Refreshing a specific bundle version is not 
supported")
+
+        self._validated_version_paths.clear()
+        with _reraise_oserror_as_manifest_error():
+            manifest_ref = self._read_current_manifest_ref()
+            version_lock = self._acquire_version_in_use(manifest_ref.version)
+            try:
+                # Keep the previous release protected until the candidate is 
usable.
+                if not self._has_validated_cache(manifest_ref.version, 
manifest_ref=manifest_ref):
+                    with self.lock():
+                        self._materialize_cached_version(
+                            version=manifest_ref.version, 
manifest_ref=manifest_ref
+                        )
+                        if version_lock is not None and not 
self._is_version_lock_current(version_lock):
+                            replacement_lock = 
self._acquire_version_in_use(manifest_ref.version)
+                            version_lock.release()
+                            version_lock = replacement_lock
+                self._current_manifest_ref = manifest_ref
+            except BaseException:
+                # Another materializer may have replaced the tracking inode. 
Only remove
+                # our own record, and serialize the missing-cache check with 
cache writers.
+                with suppress(OSError), self.lock():
+                    if (
+                        version_lock is not None
+                        and not (self.versions_dir / 
manifest_ref.version).exists()
+                        and self._is_version_lock_current(version_lock)
+                    ):
+                        get_bundle_tracking_file(self.name, 
manifest_ref.version).unlink(missing_ok=True)
+                raise
+            else:
+                if version_lock is not None:
+                    previous_release = self._release_version_in_use
+                    self._release_version_in_use = weakref.finalize(self, 
version_lock.release)
+                    version_lock = None
+                    if previous_release is not None:
+                        previous_release()
+            finally:
+                if version_lock is not None:
+                    version_lock.release()
+
+    def _acquire_version_in_use(self, version: str) -> BundleVersionLock | 
None:
+        """
+        Acquire a candidate lock without releasing the currently served 
version's lock.
+
+        The unpinned tree is served from ``versions_dir``, which that cleanup 
prunes by when
+        tasks last used each version rather than by release order, so the 
current release can
+        rank as stale. The cleanup skips a version whose tracking file is 
share-locked, and
+        taking the lock before the cache is checked lets a removal already 
under way finish
+        first. It is re-taken on every refresh: that keeps the timestamp 
current, and a
+        corrupt-cache rebuild elsewhere deletes the tracking file, stranding 
an older lock.
+        """
+        version_lock = BundleVersionLock(bundle_name=self.name, 
bundle_version=version)
+        try:
+            version_lock.acquire()
+        except OSError:
+            with suppress(OSError):
+                version_lock.release()
+            # Like a task's lock, this must not stop the bundle from being 
served, e.g. when
+            # another OS user owns the tracking file.
+            log.warning(
+                "Could not mark the bundle version as in use; stale-version 
cleanup may remove "
+                "its cache. bundle=%s version=%s",
+                self.name,
+                version,
+                exc_info=True,
+            )
+            return None
+        return version_lock
+
+    @staticmethod
+    def _is_version_lock_current(version_lock: BundleVersionLock) -> bool:
+        if version_lock.lock_file is None or version_lock.lock_file_path is 
None:
+            return False
+        try:
+            return os.path.samestat(
+                os.fstat(version_lock.lock_file.fileno()), 
version_lock.lock_file_path.stat()
+            )
+        except FileNotFoundError:
+            return False
+
+    def _get_validation_marker_path(self, version: str) -> Path:
+        # A file, not a directory: the orphan sweep only matches temp snapshot 
directories.
+        # Airflow's stale-version cleanup does not know about the marker; a 
marker without
+        # its version dir is reaped by _remove_orphaned_validation_markers.
+        return self.versions_dir / f".{version}.validated"
+
+    def _has_validated_cache(self, version: str, *, manifest_ref: 
BundleManifestRef | None) -> bool:
+        """
+        Return whether a validated cache tree exists for the version.
+
+        The persisted marker skips only the per-file hashing pass, not 
validation entirely:
+        Airflow's stale cleanup can leave a truncated tree behind (an 
interrupted plain rmtree
+        that knows nothing about the marker), and cache directories are 
owner-writable (a
+        stale-cleanup requirement), so structure -- file set, types, no 
symlinks -- is
+        re-checked on each initialization or refresh even when the marker 
vouches for the
+        content hashes. Only repeated path lookups within that instance reuse 
the result.
+        """
+        cached_version_path = self.versions_dir / version
+        if not cached_version_path.exists():
+            return False
+        cache_key = (self.name, version, str(cached_version_path))
+        if cache_key in self._validated_version_paths:
+            return True
+        if not self._get_validation_marker_path(version).exists():
+            return False
+        try:
+            self._validate_materialized_version(
+                version_path=cached_version_path,
+                version=version,
+                manifest_ref=manifest_ref,
+                check_content=False,
+                allow_cached_bytecode=True,
+            )
+        except (BundleManifestError, OSError):
+            log.warning(
+                "Cached snapshot has a validation marker but failed the 
structural check; "
+                "it must be rebuilt. bundle=%s version=%s",
+                self.name,
+                version,
+                exc_info=True,
+            )
+            return False
+        self._validated_version_paths.add(cache_key)
+        return True
+
+    def _record_validated_cache(self, version: str, cache_key: tuple[str, str, 
str]) -> None:
+        """Persist a marker after the cache tree and its parent entry are 
durable."""
+        marker_path = self._get_validation_marker_path(version)
+        marker_path.write_text(version)
+        with suppress(OSError):
+            marker_path.chmod(0o644)
+        fsync_file(marker_path)
+        fsync_directory(marker_path.parent)
+        self._validated_version_paths.add(cache_key)
+
+    def acquire_publication_lock(self):
+        """
+        Return the artifact store's publication guard.
+
+        The guard either serializes publishers with a lock or scopes 
compare-and-swap
+        baselines without mutual exclusion.
+        """
+        return self._store.publication_guard()
+
+    def _materialize_cached_version(
+        self,
+        *,
+        version: str,
+        manifest_ref: BundleManifestRef | None,
+    ) -> None:
+        self.versions_dir.mkdir(parents=True, exist_ok=True)
+        remove_orphaned_temp_snapshots(self.versions_dir)
+        self._remove_orphaned_validation_markers()
+        cached_version_path = self.versions_dir / version
+        cache_key = (self.name, version, str(cached_version_path))
+        if cached_version_path.exists():
+            # Cache files are read-only, so one full checksum validation per 
host is
+            # enough; later calls need only the marker plus a structural 
re-check.
+            if self._has_validated_cache(version, manifest_ref=manifest_ref):
+                return
+            try:
+                self._validate_materialized_version(
+                    version_path=cached_version_path,
+                    version=version,
+                    manifest_ref=manifest_ref,
+                    allow_cached_bytecode=True,
+                )
+            except (BundleManifestError, OSError):
+                log.warning(
+                    "Cached snapshot failed validation and will be rebuilt. 
bundle=%s version=%s",
+                    self.name,
+                    version,
+                    exc_info=True,
+                )
+                self._move_cached_version_aside(cached_version_path, 
version=version)
+            else:
+                snapshot_manifest = 
self._read_local_snapshot_manifest(cached_version_path)
+                source_paths = {file_info["path"] for file_info in 
snapshot_manifest["files"]}
+                fsync_tree(
+                    cached_version_path,
+                    ignore_file=lambda path: _is_cached_bytecode_file(
+                        path.relative_to(cached_version_path), source_paths
+                    ),
+                )
+                fsync_directory(self.versions_dir)
+                self._record_validated_cache(version, cache_key)
+                return
+
+        tmp_path = Path(
+            tempfile.mkdtemp(
+                prefix=get_temp_snapshot_prefix(version),
+                dir=self.versions_dir,
+            )
+        )
+        try:
+            # The store runs a structural pass on the published tree first (no 
hashing):
+            # reject symlinks, special files, and unexpected entries before 
any bytes
+            # are transferred.
+            self._store.fetch_snapshot(
+                version,
+                tmp_path,
+                structural_validator=lambda tree: 
self._validate_materialized_version(
+                    version_path=tree,
+                    version=version,
+                    manifest_ref=manifest_ref,
+                    check_content=False,
+                ),
+            )
+            # Validating the copy also validates the published source in one 
read pass.
+            self._validate_materialized_version(
+                version_path=tmp_path,
+                version=version,
+                manifest_ref=manifest_ref,
+            )
+            _set_cache_tree_permissions(tmp_path)
+            fsync_tree(tmp_path)
+            os.replace(tmp_path, cached_version_path)
+            fsync_directory(self.versions_dir)
+        except Exception:
+            # Best effort only: a cleanup failure must not mask the original 
error.
+            with suppress(OSError):
+                remove_bundle_tree_forcefully(tmp_path)
+            raise
+        self._record_validated_cache(version, cache_key)
+
+    def _move_cached_version_aside(self, cached_version_path: Path, *, 
version: str) -> None:
+        # Rename instead of delete: a concurrent task may still read the old 
tree, and a
+        # POSIX rename keeps its already-open files valid. The orphan sweep 
removes it later.
+        self._get_validation_marker_path(version).unlink(missing_ok=True)
+        # Also drop Airflow's usage-tracking file: its stale cleanup rmtree's 
the tracked
+        # path catching only BlockingIOError, so a tracking file pointing at a 
version dir
+        # this rename removes would crash every future cleanup sweep (and, on 
a scheduler
+        # with a local executor, the scheduler itself). The next task run's
+        # BundleVersionLock recreates the file.
+        with suppress(OSError):
+            get_bundle_tracking_file(bundle_name=self.name, 
version=version).unlink(missing_ok=True)
+        cache_key = (self.name, version, str(cached_version_path))
+        self._validated_version_paths.discard(cache_key)
+        aside_dir = Path(
+            tempfile.mkdtemp(
+                prefix=get_temp_snapshot_prefix(version),
+                dir=self.versions_dir,
+            )
+        )
+        with suppress(OSError):
+            
cached_version_path.chmod(stat.S_IMODE(cached_version_path.stat().st_mode) | 
0o700)
+        # FileNotFoundError: a concurrent stale-version cleanup already 
removed the tree;
+        # the rebuild that follows is all that is needed.
+        with suppress(FileNotFoundError):
+            os.rename(cached_version_path, aside_dir / "snapshot")
+
+    def _validate_materialized_version(
+        self,
+        *,
+        version_path: Path,
+        version: str,
+        manifest_ref: BundleManifestRef | None,
+        check_content: bool = True,
+        allow_cached_bytecode: bool = False,
+    ) -> None:
+        if manifest_ref:
+            if manifest_ref.version != version:
+                raise BundleManifestError(
+                    f"Bundle manifest reference contains version 
{manifest_ref.version!r}, "
+                    f"expected {version!r}"
+                )
+            self._validate_snapshot_for_ref(
+                manifest_ref,
+                version_path,
+                check_content=check_content,
+                allow_cached_bytecode=allow_cached_bytecode,
+            )
+            return
+
+        snapshot_manifest = self._read_local_snapshot_manifest(version_path)
+        self._validate_snapshot_manifest(snapshot_manifest, 
expected_version=version)
+        self._validate_snapshot_files(
+            snapshot_manifest,
+            version_path,
+            check_content=check_content,
+            allow_cached_bytecode=allow_cached_bytecode,
+        )
+
+    def _ensure_current_manifest_ref(self) -> BundleManifestRef:
+        # Only a cheap read of the release reference. Snapshot materialization 
and full
+        # checksum validation happen in initialize()/refresh(); ``path`` can 
still do the
+        # required structural check of a cache copy that has a validation 
marker.
+        if self._current_manifest_ref is None:
+            self._current_manifest_ref = self._read_current_manifest_ref()
+        return self._current_manifest_ref
+
+    def _read_current_manifest_ref(self) -> BundleManifestRef:
+        try:
+            payload = self._store.read_ref()
+        except BundleManifestNotFoundError as e:
+            raise BundleManifestNotFoundError(
+                f"{e}. Publish the bundle or restore the release reference 
before using it."
+            ) from e
+        return self._build_manifest_ref_from_payload(payload, 
source=self._store.ref_locator)
+
+    def _build_manifest_ref_from_payload(self, payload: dict[str, Any], 
source: str) -> BundleManifestRef:
+        schema_version = payload.get("schema_version")
+        if schema_version != MANIFEST_SCHEMA_VERSION:
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} has unsupported 
schema_version {schema_version!r}"
+            )
+
+        bundle_name = payload.get("bundle_name")
+        if bundle_name != self.name:
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} is for bundle 
{bundle_name!r}, expected {self.name!r}"
+            )
+
+        version = payload.get("version")
+        if not isinstance(version, str) or not version:
+            raise BundleManifestError(f"Bundle manifest reference {source} 
does not contain a version")
+        version = validate_bundle_version(version, source=f"manifest reference 
{source} version")
+
+        backend = payload.get("backend")
+        backend_type = self._store.backend_type
+        if not isinstance(backend, dict) or backend.get("type") != 
backend_type:
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} is not for a 
{backend_type} backend"
+            )
+
+        manifest_data = payload.get("manifest")
+        if not isinstance(manifest_data, dict):
+            raise BundleManifestError(f"Bundle manifest reference {source} 
does not contain manifest data")
+
+        manifest_path = manifest_data.get("path")
+        manifest_sha256 = manifest_data.get("sha256")
+        if not isinstance(manifest_path, str):
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} does not contain a valid 
manifest path"
+            )
+        if not isinstance(manifest_sha256, str) or not manifest_sha256:
+            raise BundleManifestError(f"Bundle manifest reference {source} 
does not contain manifest sha256")
+        self._validate_manifest_ref_path(manifest_path)
+
+        file_count = payload.get("file_count")
+        total_size = payload.get("total_size")
+        # bool is an int subclass and True == 1, so it would slip through 
every check below.
+        if not isinstance(file_count, int) or isinstance(file_count, bool) or 
file_count < 0:
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} does not contain a valid 
file_count"
+            )
+        if not isinstance(total_size, int) or isinstance(total_size, bool) or 
total_size < 0:
+            raise BundleManifestError(
+                f"Bundle manifest reference {source} does not contain a valid 
total_size"
+            )
+
+        ref_payload = build_ref_payload(
+            bundle_name=bundle_name,
+            version=version,
+            backend={"type": backend_type},
+            manifest_sha256=manifest_sha256,
+            file_count=file_count,
+            total_size=total_size,
+        )
+        return BundleManifestRef(
+            version=version,
+            ref_payload=ref_payload,
+            manifest_sha256=manifest_sha256,
+        )
+
+    @staticmethod
+    def _validate_manifest_ref_path(manifest_path: str) -> None:
+        relative_path = validate_bundle_relative_path(manifest_path)
+        if relative_path.as_posix() != MANIFEST_FILE_NAME:
+            raise BundleManifestError(
+                f"Bundle manifest reference must point to 
{MANIFEST_FILE_NAME!r}, got {manifest_path!r}"
+            )
+
+    def _validate_snapshot_for_ref(
+        self,
+        manifest_ref: BundleManifestRef,
+        version_path: Path,
+        *,
+        check_content: bool = True,
+        allow_cached_bytecode: bool = False,
+    ) -> None:
+        snapshot_manifest = self._read_local_snapshot_manifest(version_path)
+        self._validate_snapshot_manifest(snapshot_manifest, 
expected_version=manifest_ref.version)
+        expected_file_count = manifest_ref.ref_payload["file_count"]
+        if snapshot_manifest["file_count"] != expected_file_count:
+            raise BundleManifestError(
+                f"Bundle manifest file_count 
{snapshot_manifest['file_count']!r} does not match "
+                f"manifest reference {expected_file_count!r}"
+            )
+        expected_total_size = manifest_ref.ref_payload["total_size"]
+        if snapshot_manifest["total_size"] != expected_total_size:
+            raise BundleManifestError(
+                f"Bundle manifest total_size 
{snapshot_manifest['total_size']!r} does not match "
+                f"manifest reference {expected_total_size!r}"
+            )
+        verify_bundle_version_manifest(snapshot_manifest, 
manifest_ref.manifest_sha256)
+        self._validate_snapshot_files(
+            snapshot_manifest,
+            version_path,
+            check_content=check_content,
+            allow_cached_bytecode=allow_cached_bytecode,
+        )
+
+    def _validate_snapshot_manifest(self, manifest: dict[str, Any], *, 
expected_version: str) -> None:
+        validate_bundle_version_manifest_structure(
+            manifest,
+            expected_version=expected_version,
+            expected_bundle_name=self.name,
+            expected_backend_type=self._store.backend_type,
+        )
+
+    def _validate_snapshot_files(
+        self,
+        snapshot_manifest: dict[str, Any],
+        version_path: Path,
+        *,
+        check_content: bool = True,
+        allow_cached_bytecode: bool = False,
+    ) -> None:
+        # check_content=False keeps the structural checks (path safety, 
symlinks, file
+        # types, unexpected files) but skips the per-file hashing pass.
+        expected_paths = {file_info["path"] for file_info in 
snapshot_manifest["files"]}
+        observed_paths = {
+            path.relative_to(version_path).as_posix()
+            for path in self._iter_snapshot_files(
+                version_path, cached_source_paths=expected_paths if 
allow_cached_bytecode else None
+            )
+        }
+        unexpected_paths = sorted(observed_paths - expected_paths)
+        if unexpected_paths:
+            raise BundleManifestError(
+                f"Bundle snapshot {version_path} contains files not present in 
the manifest: "
+                f"{', '.join(unexpected_paths)}"
+            )
+
+        for file_info in snapshot_manifest["files"]:
+            relative_path = validate_bundle_relative_path(file_info["path"])
+            source = version_path / relative_path
+            ensure_destination_is_within_root(version_path, source)
+            if source.is_symlink():
+                raise BundleManifestError(
+                    f"Bundle snapshot file {file_info['path']!r} is a symlink; 
symlinks are not "
+                    "supported in manifest bundle snapshots"
+                )
+            try:
+                file_stat = source.stat()
+            except FileNotFoundError:
+                raise BundleManifestError(
+                    f"Bundle snapshot {version_path} is missing manifest entry 
{file_info['path']!r}"
+                ) from None
+            if not stat.S_ISREG(file_stat.st_mode):
+                raise BundleManifestError(f"Bundle snapshot file 
{file_info['path']!r} is not a regular file")
+            if not check_content:
+                continue
+            file_sha256, size = compute_file_sha256(source)
+            executable = bool(stat.S_IMODE(file_stat.st_mode) & 0o111)
+            if (
+                size != file_info["size"]
+                or file_sha256 != file_info["sha256"]
+                or executable != file_info["executable"]
+            ):
+                raise BundleManifestError(
+                    f"Bundle snapshot file {file_info['path']!r} does not 
match local snapshot manifest"
+                )
+
+    @staticmethod
+    def _iter_snapshot_files(
+        snapshot_root: Path, *, cached_source_paths: set[str] | None = None
+    ) -> Iterator[Path]:
+        def raise_walk_error(error: OSError) -> None:
+            raise BundleManifestError(
+                f"Bundle snapshot {snapshot_root} changed or became unreadable 
while validating: "
+                f"{error.filename}"
+            ) from error
+
+        for dirpath, dirnames, filenames in os.walk(
+            snapshot_root,
+            followlinks=False,
+            onerror=raise_walk_error,
+        ):
+            dirpath_path = Path(dirpath)
+            relative_dirpath = 
dirpath_path.relative_to(snapshot_root).as_posix()
+            if dirpath_path.is_symlink():
+                raise BundleManifestError(
+                    f"Bundle snapshot {snapshot_root} contains symlinked 
directory "
+                    f"{relative_dirpath!r}; symlinks are not supported in 
manifest bundle snapshots"
+                )
+
+            for dirname in dirnames:
+                path = dirpath_path / dirname
+                if path.is_symlink():
+                    relative_path = path.relative_to(snapshot_root).as_posix()
+                    raise BundleManifestError(
+                        f"Bundle snapshot {snapshot_root} contains symlinked 
directory "
+                        f"{relative_path!r}; symlinks are not supported in 
manifest bundle snapshots"
+                    )
+                if not path.is_dir():
+                    relative_path = path.relative_to(snapshot_root).as_posix()
+                    raise BundleManifestError(
+                        f"Bundle snapshot {snapshot_root} contains 
non-directory entry "
+                        f"{relative_path!r} where a directory was expected"
+                    )
+            dirnames[:] = sorted(dirnames)
+            for filename in sorted(filenames):
+                path = Path(dirpath) / filename
+                relative_path = path.relative_to(snapshot_root).as_posix()
+                is_cached_bytecode = cached_source_paths is not None and 
_is_cached_bytecode_file(
+                    Path(relative_path), cached_source_paths
+                )
+                if path.is_symlink():
+                    raise BundleManifestError(
+                        f"Bundle snapshot {snapshot_root} contains symlinked 
file "
+                        f"{relative_path!r}; symlinks are not supported in 
manifest bundle snapshots"
+                    )
+                try:
+                    file_stat = path.stat()
+                except FileNotFoundError as e:
+                    if is_cached_bytecode:
+                        # Python replaces its temporary bytecode file 
atomically.
+                        continue
+                    # Not BundleManifestSourceChangedError: snapshots are 
immutable, so a file
+                    # vanishing from one is damage or a concurrent removal, 
not a source edit.
+                    raise BundleManifestError(
+                        f"Bundle snapshot file disappeared during validation: 
{relative_path}"
+                    ) from e
+                if not stat.S_ISREG(file_stat.st_mode):
+                    raise BundleManifestError(
+                        f"Bundle snapshot {snapshot_root} contains non-regular 
file {relative_path!r}"
+                    )
+                if relative_path == MANIFEST_FILE_NAME or is_cached_bytecode:
+                    continue
+                yield path
+
+    @staticmethod
+    def _read_local_snapshot_manifest(version_path: Path) -> dict[str, Any]:
+        manifest_file = version_path / MANIFEST_FILE_NAME
+        missing_message = (
+            f"Bundle snapshot at {version_path} does not contain 
{MANIFEST_FILE_NAME}. "
+            "Publish or restore the immutable snapshot before updating the 
manifest reference."
+        )
+        if not manifest_file.exists():
+            raise BundleManifestNotFoundError(missing_message)
+        if manifest_file.is_symlink():
+            raise BundleManifestError(
+                f"Bundle snapshot manifest {manifest_file} is a symlink; 
symlinks are not supported "
+                "in manifest bundle snapshots"
+            )
+        if not manifest_file.is_file():
+            raise BundleManifestError(f"Bundle snapshot manifest 
{manifest_file} is not a regular file")
+        return read_json_file(
+            manifest_file,
+            missing_message=missing_message,
+            invalid_message=f"Bundle snapshot manifest is not valid JSON: 
{manifest_file}",
+        )
+
+    @property
+    def path(self) -> Path:
+        if self.version:
+            version = validate_bundle_version(self.version, source="pinned 
version")
+            return self.versions_dir / version
+        with _reraise_oserror_as_manifest_error():
+            manifest_ref = self._ensure_current_manifest_ref()
+            version = manifest_ref.version
+            current_version_path = self.versions_dir / version
+            if self._has_validated_cache(version, manifest_ref=manifest_ref):
+                return current_version_path
+
+            # Never another version's tree: callers record 
get_current_version() against
+            # whatever they parse here.
+            if current_version_path.exists():
+                raise BundleManifestError(
+                    f"Bundle '{self.name}' version '{version}' has an 
unvalidated or structurally "
+                    f"invalid cache copy at {current_version_path}. Initialize 
or refresh the bundle "
+                    "to rebuild it before use."
+                )
+            return current_version_path
+
+    def _remove_orphaned_validation_markers(self) -> None:
+        """
+        Reap validation markers whose version dir is gone.
+
+        Airflow's stale-version cleanup removes only the version dir and its 
tracking file;
+        without this sweep every version ever materialized would leak one 
marker file.
+        """
+        try:
+            entries = list(self.versions_dir.iterdir())
+        except OSError:
+            return
+        for entry in entries:
+            version = _get_marker_file_version(entry)
+            if version is None:
+                continue
+            if not (self.versions_dir / version).exists():
+                with suppress(OSError):
+                    entry.unlink()
+
+
+def publish_prepared_manifest_dag_bundle(
+    *,
+    bundle: ManifestDagBundleBase,
+    prepared_source: PreparedPublishSource,
+    expected_current_version: str | None = None,
+) -> BundlePublishResult:
+    """Publish one prepared local tree as an immutable manifest-backed 
snapshot."""
+    source_path = prepared_source.root
+    _validate_publish_source_path(
+        source_path=source_path,
+        store=bundle._store,
+        versions_dir=bundle.versions_dir,
+    )
+    if not prepared_source.source_snapshot.files and not 
bundle.allow_empty_source:
+        raise BundleManifestError(
+            f"Refusing to explicitly publish empty source tree {source_path} 
for bundle "
+            f"'{bundle.name}'; set allow_empty_source=True if removing every 
Dag is intended"
+        )
+    bundle._store.prepare_publish_areas()
+    with bundle.acquire_publication_lock():
+        if expected_current_version is not None:
+            expected_current_version = validate_bundle_version(
+                expected_current_version, source="expected current version"
+            )
+            try:
+                current_version = bundle._read_current_manifest_ref().version
+            except BundleManifestNotFoundError as e:
+                raise BundleManifestReferenceChangedError(
+                    f"Bundle '{bundle.name}' has no published version to 
compare with "
+                    "expected_current_version. Omit it for the initial 
publication."
+                ) from e
+            if current_version != expected_current_version:
+                raise BundleManifestReferenceChangedError(
+                    f"Bundle '{bundle.name}' manifest reference changed: 
expected "
+                    f"{expected_current_version!r}, found {current_version!r}"
+                )
+
+        manifest_result = build_bundle_version_manifest(
+            bundle_name=bundle.name,
+            root=source_path,
+            backend_type=bundle._store.backend_type,
+            source_snapshot=prepared_source.source_snapshot,
+            file_version_ids=prepared_source.file_version_ids,
+        )
+        try:
+            return _publish_manifest_result(
+                bundle=bundle,
+                manifest_result=manifest_result,
+                prepared_source=prepared_source,
+            )
+        except ArtifactStoreConflictError as e:
+            raise BundleManifestReferenceChangedError(
+                f"Bundle '{bundle.name}' manifest reference changed during 
publication: "
+                "another publisher updated the release concurrently"
+            ) from e
+
+
+def _publish_manifest_result(
+    *,
+    bundle: ManifestDagBundleBase,
+    manifest_result: BundleVersionManifest,
+    prepared_source: PreparedPublishSource,
+) -> BundlePublishResult:
+    """Publish a precomputed manifest inside the artifact store's publication 
guard."""
+    version = manifest_result.version
+    publication = bundle._store.publish_snapshot(
+        manifest=manifest_result.manifest,
+        source_root=prepared_source.root,
+        validate_existing=lambda tree: bundle._validate_materialized_version(
+            version_path=tree, version=version, manifest_ref=None
+        ),
+    )
+    # A republish can carry different object version ids for the same version; 
the reference
+    # must name the manifest the store kept, which a store may return without 
validating.
+    bundle._validate_snapshot_manifest(publication.manifest, 
expected_version=version)
+    ref_payload = build_ref_payload_from_manifest(publication.manifest)
+    manifest_ref = bundle._build_manifest_ref_from_payload(ref_payload, 
source="publisher")
+
+    bundle.confirm_publish_source(prepared_source)
+    bundle._store.write_ref(ref_payload)
+
+    return BundlePublishResult(
+        bundle_name=bundle.name,
+        version=version,
+        ref_payload=ref_payload,
+        snapshot_locator=bundle._store.snapshot_locator(version),
+        ref_locator=bundle._store.ref_locator,
+        manifest_sha256=manifest_ref.manifest_sha256,
+        file_count=ref_payload["file_count"],
+        total_size=ref_payload["total_size"],
+        created_snapshot=publication.created,
+    )
+
+
+def _validate_publish_source_path(*, source_path: Path, store: ArtifactStore, 
versions_dir: Path) -> None:
+    # The store cannot check these: it does not know the local cache, and a 
source inside a
+    # filesystem published_root would publish into itself. Other stores have 
no such root.
+    if isinstance(store, FilesystemArtifactStore):
+        published_root = store.published_root
+        if _is_same_or_nested_path(published_root, source_path):
+            raise ValueError(
+                "published_root must not be inside source_path. Keep published 
snapshots "
+                "outside the Dag source tree before publishing a manifest 
bundle."
+            )
+
+        if _is_same_or_nested_path(source_path, published_root):
+            raise ValueError(
+                "source_path must not be inside published_root. Keep the Dag 
source tree "
+                "outside the published snapshots before publishing a manifest 
bundle."
+            )
+
+    if _paths_overlap(source_path, versions_dir):
+        raise ValueError(
+            "source_path and versions_dir must not overlap. Keep Airflow's 
bundle cache outside "
+            "the Dag source tree before publishing a manifest bundle."
+        )
+
+
+def _is_same_or_nested_path(path: Path, root: Path) -> bool:
+    absolute_path = Path(os.path.abspath(path))
+    absolute_root = Path(os.path.abspath(root))
+    return absolute_path.is_relative_to(absolute_root) or 
path.resolve(strict=False).is_relative_to(
+        root.resolve(strict=False)
+    )
+
+
+def _paths_overlap(first: Path, second: Path) -> bool:
+    return _is_same_or_nested_path(first, second) or 
_is_same_or_nested_path(second, first)
+
+
+def _set_cache_tree_permissions(cache_path: Path) -> None:
+    # Cache copies keep files read-only (content drift stays detectable) but 
leave
+    # directories writable: Airflow's stale-bundle cleanup removes cached 
versions
+    # with a plain shutil.rmtree, which fails on read-only directories.
+    for dirpath, _, filenames in os.walk(cache_path, onerror=raise_walk_error):
+        directory = Path(dirpath)
+        for filename in filenames:
+            path = directory / filename
+            if path.is_symlink():
+                continue
+            executable = stat.S_IMODE(path.stat().st_mode) & 0o111
+            path.chmod(0o555 if executable else 0o444)
+        directory.chmod(0o755)
+
+
+def _is_cached_bytecode_file(path: Path, source_paths: set[str]) -> bool:
+    """Recognize Python bytecode (including atomic-write temps) for 
manifest-listed sources."""
+    if path.parent.name != "__pycache__":
+        return False
+    suffix = path.suffix.removeprefix(".")
+    if suffix.isascii() and suffix.isdecimal():
+        path = path.with_suffix("")
+    if path.suffix != ".pyc":
+        return False
+    stem, separator, tag = path.stem.rpartition(".")
+    if tag.startswith("opt-"):
+        if not tag.removeprefix("opt-").isalnum():
+            return False
+        stem, separator, tag = stem.rpartition(".")
+    return bool(separator and tag) and (path.parent.parent / 
f"{stem}.py").as_posix() in source_paths
+
+
+def _get_marker_file_version(path: Path) -> str | None:
+    """Return the version a ``.{version}.validated`` marker file certifies, or 
None."""
+    name = path.name
+    if not (name.startswith(".") and name.endswith(".validated")):
+        return None
+    version = name[1 : -len(".validated")]
+    if not is_valid_bundle_version(version):
+        return None
+    if path.is_symlink() or not path.is_file():
+        return None
+    return version
diff --git a/airflow-core/src/airflow/dag_processing/bundles/manifest_local.py 
b/airflow-core/src/airflow/dag_processing/bundles/manifest_local.py
new file mode 100644
index 00000000000..71b24c3e24e
--- /dev/null
+++ b/airflow-core/src/airflow/dag_processing/bundles/manifest_local.py
@@ -0,0 +1,78 @@
+# 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.
+"""Local source adapter for manifest-backed Dag bundles."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from airflow.dag_processing.bundles.manifest import (
+    BundleManifestError,
+    BundleManifestSourceChangedError,
+    collect_bundle_source_snapshot,
+)
+from airflow.dag_processing.bundles.manifest_bundle import (
+    ManifestDagBundleBase,
+    PreparedPublishSource,
+    publish_prepared_manifest_dag_bundle,
+)
+
+if TYPE_CHECKING:
+    from airflow.dag_processing.bundles.manifest_bundle import 
BundlePublishResult
+
+
+class ManifestLocalDagBundle(ManifestDagBundleBase):
+    """
+    Manifest-backed Dag bundle whose snapshots are published from a local 
directory.
+
+    Publish with ``publish_manifest_local_dag_bundle``; the bundle serves the 
release that
+    publication recorded, never the mutable source directory itself.
+    """
+
+    def confirm_publish_source(self, prepared: PreparedPublishSource) -> None:
+        current_snapshot = collect_bundle_source_snapshot(prepared.root)
+        if current_snapshot.signature != prepared.source_snapshot.signature:
+            raise BundleManifestSourceChangedError(
+                "Bundle source changed while publishing the bundle snapshot"
+            )
+
+
+def publish_manifest_local_dag_bundle(
+    *,
+    bundle: ManifestLocalDagBundle,
+    source_path: str | Path,
+    expected_current_version: str | None = None,
+) -> BundlePublishResult:
+    """
+    Publish a local source tree as an immutable manifest-backed snapshot.
+
+    :param expected_current_version: Publish only if this is still the current 
release, so
+        that a publisher working from a stale view cannot overwrite a newer 
release.
+    """
+    if bundle.version:
+        raise BundleManifestError(
+            f"Cannot explicitly publish pinned bundle '{bundle.name}' at 
version {bundle.version!r}"
+        )
+    source_path = Path(source_path)
+    return publish_prepared_manifest_dag_bundle(
+        bundle=bundle,
+        prepared_source=PreparedPublishSource(
+            root=source_path, 
source_snapshot=collect_bundle_source_snapshot(source_path)
+        ),
+        expected_current_version=expected_current_version,
+    )
diff --git a/airflow-core/tests/unit/dag_processing/bundles/conftest.py 
b/airflow-core/tests/unit/dag_processing/bundles/conftest.py
new file mode 100644
index 00000000000..6a4fad96b14
--- /dev/null
+++ b/airflow-core/tests/unit/dag_processing/bundles/conftest.py
@@ -0,0 +1,36 @@
+# 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
+
+from unittest import mock
+
+import pytest
+
+from tests_common.test_utils.config import conf_vars
+
+
[email protected]
+def isolate_bundle_storage(tmp_path):
+    """Keep a test's bundle cache and version tracking files under its 
``tmp_path``."""
+    with (
+        conf_vars({("dag_processor", "dag_bundle_storage_path"): str(tmp_path 
/ "bundles")}),
+        # The tracking folder is resolved once at import time, not from the 
config above.
+        mock.patch(
+            
"airflow.dag_processing.bundles.base.STALE_BUNDLE_TRACKING_FOLDER", tmp_path / 
"bundles/_tracking"
+        ),
+    ):
+        yield
diff --git a/airflow-core/tests/unit/dag_processing/bundles/test__filesystem.py 
b/airflow-core/tests/unit/dag_processing/bundles/test__filesystem.py
index b632fb83a35..987692f25ef 100644
--- a/airflow-core/tests/unit/dag_processing/bundles/test__filesystem.py
+++ b/airflow-core/tests/unit/dag_processing/bundles/test__filesystem.py
@@ -26,6 +26,7 @@ import pytest
 from airflow.dag_processing.bundles import _filesystem as filesystem_module
 from airflow.dag_processing.bundles._filesystem import (
     fsync_directory,
+    fsync_tree,
     fsync_tree_directories,
     read_json_file,
     remove_bundle_tree_forcefully,
@@ -92,3 +93,32 @@ class TestRemoveBundleTreeForcefully:
 
         assert not link.exists()
         assert target.is_dir()
+
+
+class TestFsyncTree:
+    @mock.patch.object(
+        filesystem_module, "fsync_file", autospec=True, 
side_effect=filesystem_module.fsync_file
+    )
+    def 
test_ignored_file_can_disappear_while_authoritative_files_are_synced(self, 
mock_fsync, tmp_path):
+        tree = tmp_path / "tree"
+        (tree / "dags").mkdir(parents=True)
+        (tree / "dags" / "example.py").write_text("print('dag')\n")
+        manifest = tree / "manifest.json"
+        manifest.write_text("{}")
+        temporary_bytecode = tree / "dags" / "__pycache__" / 
"example.cpython-312.pyc.123"
+        temporary_bytecode.parent.mkdir()
+        temporary_bytecode.write_bytes(b"partial bytecode")
+
+        def ignore_file(path: Path) -> bool:
+            if path != temporary_bytecode:
+                return False
+            temporary_bytecode.unlink()
+            return True
+
+        fsync_tree(tree, ignore_file=ignore_file)
+
+        assert not temporary_bytecode.exists()
+        assert mock_fsync.call_count == 2
+        mock_fsync.assert_has_calls(
+            [mock.call(manifest), mock.call(tree / "dags" / "example.py")], 
any_order=True
+        )
diff --git 
a/airflow-core/tests/unit/dag_processing/bundles/test_manifest_bundle.py 
b/airflow-core/tests/unit/dag_processing/bundles/test_manifest_bundle.py
new file mode 100644
index 00000000000..e1bb42f29dc
--- /dev/null
+++ b/airflow-core/tests/unit/dag_processing/bundles/test_manifest_bundle.py
@@ -0,0 +1,298 @@
+# 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.
+"""Tests for the artifact store seam of manifest-backed Dag bundles."""
+
+from __future__ import annotations
+
+import json
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+from unittest import mock
+
+import pytest
+
+from airflow.dag_processing.bundles.artifact_store import (
+    ArtifactStore,
+    ArtifactStoreConflictError,
+    BundleManifestNotFoundError,
+    PublishedSnapshot,
+)
+from airflow.dag_processing.bundles.manifest import (
+    MANIFEST_FILE_NAME,
+    BundleManifestError,
+    build_bundle_version_manifest,
+    collect_bundle_source_snapshot,
+    serialize_bundle_version_manifest,
+    validate_bundle_relative_path,
+)
+from airflow.dag_processing.bundles.manifest_bundle import (
+    BundleManifestReferenceChangedError,
+    BundlePublishResult,
+    ManifestDagBundleBase,
+    PreparedPublishSource,
+    publish_prepared_manifest_dag_bundle,
+)
+from airflow.dag_processing.bundles.manifest_local import 
ManifestLocalDagBundle
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+pytestmark = pytest.mark.usefixtures("isolate_bundle_storage")
+
+BUNDLE_NAME = "manifest-memory"
+DAG_FILE = "dags/example.py"
+
+
+@dataclass
+class _VersionedBucket:
+    """What a versioned object store holds: object versions, snapshot 
manifests and the reference."""
+
+    objects: dict[str, dict[str, bytes]] = field(default_factory=dict)
+    manifests: dict[str, bytes] = field(default_factory=dict)
+    ref: bytes | None = None
+    ref_generation: int = 0
+
+
+class _InMemoryArtifactStore(ArtifactStore):
+    """
+    Store with no published root that fetches files by object version id.
+
+    Its guard is not a lock: entering it resets the compare-and-swap baseline, 
so ``write_ref``
+    is conditioned on the reference read inside the guard, or on the current 
one when there
+    was no such read.
+    """
+
+    backend_type = "memory"
+
+    def __init__(self, *, bundle_name: str, bucket: _VersionedBucket) -> None:
+        self.bundle_name = bundle_name
+        self._bucket = bucket
+        self._ref_baseline: int | None = None
+
+    @property
+    def ref_locator(self) -> str:
+        return f"memory://{self.bundle_name}/latest.json"
+
+    def snapshot_locator(self, version: str) -> str:
+        return f"memory://{self.bundle_name}/versions/{version}"
+
+    def read_ref(self) -> dict[str, Any]:
+        # Set even when there is no reference, so the next write requires it 
to stay absent.
+        self._ref_baseline = self._bucket.ref_generation
+        if self._bucket.ref is None:
+            raise BundleManifestNotFoundError(f"Bundle '{self.bundle_name}' 
has no release reference")
+        return json.loads(self._bucket.ref)
+
+    def write_ref(self, payload: dict[str, Any]) -> None:
+        content = serialize_bundle_version_manifest(payload)
+        baseline = self._bucket.ref_generation if self._ref_baseline is None 
else self._ref_baseline
+        if self._bucket.ref_generation != baseline and self._bucket.ref != 
content:
+            raise ArtifactStoreConflictError(f"Another publisher updated 
{self.ref_locator}")
+        self._bucket.ref = content
+        self._bucket.ref_generation += 1
+
+    @contextmanager
+    def publication_guard(self):
+        self._ref_baseline = None
+        yield
+
+    def prepare_publish_areas(self) -> None:
+        pass
+
+    def snapshot_exists(self, version: str) -> bool:
+        return version in self._bucket.manifests
+
+    def fetch_snapshot(
+        self, version: str, destination: Path, *, structural_validator: 
Callable[[Path], None]
+    ) -> None:
+        if version not in self._bucket.manifests:
+            raise BundleManifestNotFoundError(f"Bundle version {version!r} is 
not published")
+        manifest_bytes = self._bucket.manifests[version]
+        for file_info in json.loads(manifest_bytes)["files"]:
+            path = destination / 
validate_bundle_relative_path(file_info["path"])
+            path.parent.mkdir(parents=True, exist_ok=True)
+            
path.write_bytes(self._bucket.objects[file_info["path"]][file_info["version_id"]])
+            if file_info["executable"]:
+                path.chmod(0o755)
+        (destination / MANIFEST_FILE_NAME).write_bytes(manifest_bytes)
+
+    def publish_snapshot(
+        self,
+        *,
+        manifest: dict[str, Any],
+        source_root: Path,
+        validate_existing: Callable[[Path], None],
+    ) -> PublishedSnapshot:
+        version = manifest["version"]
+        if version not in self._bucket.manifests:
+            for file_info in manifest["files"]:
+                object_versions = 
self._bucket.objects.setdefault(file_info["path"], {})
+                object_versions[file_info["version_id"]] = (source_root / 
file_info["path"]).read_bytes()
+        # The manifest commits the snapshot: written last, and only if absent.
+        manifest_bytes = serialize_bundle_version_manifest(manifest)
+        committed = self._bucket.manifests.setdefault(version, manifest_bytes)
+        return PublishedSnapshot(manifest=json.loads(committed), 
created=committed is manifest_bytes)
+
+
+class _MemoryManifestDagBundle(ManifestDagBundleBase):
+    def __init__(self, *, bucket: _VersionedBucket, **kwargs) -> None:
+        self.bucket = bucket
+        super().__init__(**kwargs)
+
+    def create_artifact_store(self) -> ArtifactStore:
+        return _InMemoryArtifactStore(bundle_name=self.name, 
bucket=self.bucket)
+
+    def confirm_publish_source(self, prepared: PreparedPublishSource) -> None:
+        pass
+
+
+def _write_source(root: Path, content: str = "print('dag')") -> Path:
+    path = root / DAG_FILE
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(content)
+    return root
+
+
+def _publish(
+    bundle: ManifestDagBundleBase,
+    source: Path,
+    version_id: str,
+    *,
+    expected_current_version: str | None = None,
+) -> BundlePublishResult:
+    return publish_prepared_manifest_dag_bundle(
+        bundle=bundle,
+        prepared_source=PreparedPublishSource(
+            root=source,
+            source_snapshot=collect_bundle_source_snapshot(source),
+            file_version_ids={DAG_FILE: version_id},
+        ),
+        expected_current_version=expected_current_version,
+    )
+
+
+class TestStoreWithoutPublishedRoot:
+    def test_create_artifact_store_runs_after_base_initialization(self):
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, 
bucket=_VersionedBucket())
+
+        assert bundle._store.bundle_name == BUNDLE_NAME
+
+    def test_publishes_and_serves_a_release_with_object_version_ids(self, 
tmp_path):
+        bucket = _VersionedBucket()
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, bucket=bucket)
+
+        result = _publish(bundle, _write_source(tmp_path / "source"), 
"object-version-1")
+        bundle.refresh()
+
+        committed = json.loads(bucket.manifests[result.version])
+        assert committed["backend"] == {"type": "memory"}
+        assert [file_info["version_id"] for file_info in committed["files"]] 
== ["object-version-1"]
+        assert json.loads(bucket.ref) == result.ref_payload
+        assert (bundle.path / DAG_FILE).read_text() == "print('dag')"
+
+    def test_publish_still_rejects_a_source_overlapping_the_cache(self, 
tmp_path):
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, 
bucket=_VersionedBucket())
+        source = _write_source(bundle.versions_dir / "publisher-source")
+
+        with pytest.raises(ValueError, match="source_path and versions_dir 
must not overlap"):
+            _publish(bundle, source, "object-version-1")
+
+    def 
test_republish_with_new_object_version_ids_keeps_the_committed_manifest(self, 
tmp_path):
+        bucket = _VersionedBucket()
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, bucket=bucket)
+        source = _write_source(tmp_path / "source")
+        first = _publish(bundle, source, "object-version-1")
+
+        second = _publish(bundle, source, "object-version-2")
+        bundle.refresh()
+
+        assert second.version == first.version
+        assert second.created_snapshot is False
+        assert second.ref_payload == first.ref_payload
+        assert json.loads(bucket.ref) == first.ref_payload
+        assert (bundle.path / DAG_FILE).read_text() == "print('dag')"
+
+    def test_publish_rejects_a_committed_manifest_for_another_version(self, 
tmp_path):
+        bucket = _VersionedBucket()
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, bucket=bucket)
+        source = _write_source(tmp_path / "source")
+        version = build_bundle_version_manifest(
+            bundle_name=BUNDLE_NAME, root=source, backend_type="memory"
+        ).version
+        other_manifest = build_bundle_version_manifest(
+            bundle_name=BUNDLE_NAME,
+            root=_write_source(tmp_path / "other-source", "print('other')"),
+            backend_type="memory",
+            file_version_ids={DAG_FILE: "object-version-0"},
+        ).manifest
+        # The store hands back whatever is committed under the version without 
checking it.
+        bucket.manifests[version] = 
serialize_bundle_version_manifest(other_manifest)
+
+        with pytest.raises(BundleManifestError, match="Bundle manifest 
contains version"):
+            _publish(bundle, source, "object-version-1")
+
+        assert bucket.ref is None
+
+    def 
test_concurrent_reference_update_is_reported_as_a_reference_change(self, 
tmp_path):
+        bucket = _VersionedBucket()
+        bundle = _MemoryManifestDagBundle(name=BUNDLE_NAME, bucket=bucket)
+        rival = _MemoryManifestDagBundle(name=BUNDLE_NAME, bucket=bucket)
+        first = _publish(bundle, _write_source(tmp_path / "source"), 
"object-version-1")
+        rival_source = _write_source(tmp_path / "rival-source", 
"print('rival')")
+        rival_results: list[BundlePublishResult] = []
+
+        def publish_rival_first(prepared: PreparedPublishSource) -> None:
+            rival_results.append(_publish(rival, rival_source, 
"object-version-2"))
+
+        with (
+            mock.patch.object(
+                bundle, "confirm_publish_source", autospec=True, 
side_effect=publish_rival_first
+            ),
+            pytest.raises(
+                BundleManifestReferenceChangedError,
+                match="another publisher updated the release concurrently",
+            ) as raised,
+        ):
+            _publish(
+                bundle,
+                _write_source(tmp_path / "next-source", "print('next')"),
+                "object-version-3",
+                expected_current_version=first.version,
+            )
+
+        assert isinstance(raised.value.__cause__, ArtifactStoreConflictError)
+        assert json.loads(bucket.ref) == rival_results[0].ref_payload
+
+
+class TestFilesystemStoreRepublish:
+    def 
test_existing_snapshot_is_checked_against_its_version_not_the_new_manifest(self,
 tmp_path):
+        published_root = tmp_path / "published"
+        published_root.mkdir()
+        bundle = ManifestLocalDagBundle(name=BUNDLE_NAME, 
published_root=str(published_root))
+        source = _write_source(tmp_path / "source")
+        first = _publish(bundle, source, "object-version-1")
+
+        second = _publish(bundle, source, "object-version-2")
+
+        assert second.created_snapshot is False
+        assert second.ref_payload == first.ref_payload
+        committed = json.loads(
+            (published_root / "versions" / BUNDLE_NAME / first.version / 
MANIFEST_FILE_NAME).read_text()
+        )
+        assert [file_info["version_id"] for file_info in committed["files"]] 
== ["object-version-1"]
diff --git 
a/airflow-core/tests/unit/dag_processing/bundles/test_manifest_local.py 
b/airflow-core/tests/unit/dag_processing/bundles/test_manifest_local.py
new file mode 100644
index 00000000000..985c1a51105
--- /dev/null
+++ b/airflow-core/tests/unit/dag_processing/bundles/test_manifest_local.py
@@ -0,0 +1,1452 @@
+# 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 (
+            mock.patch.object(filesystem_module, "fsync_file", autospec=True, 
side_effect=record_fsync_file),
+            mock.patch.object(bundle_module, "fsync_file", autospec=True, 
side_effect=record_fsync_file),
+            mock.patch.object(
+                bundle_module, "fsync_directory", autospec=True, 
side_effect=record_fsync_directory
+            ),
+            mock.patch.object(bundle_module.os, "replace", autospec=True, 
side_effect=record_replace),
+        ):
+            bundle.refresh()
+
+        replace_index = calls.index(("replace_cache", cached_version_path))
+        marker_fsync_index = calls.index(("fsync_file", marker_path))
+        cache_file_fsync_indices = [
+            index
+            for index, (operation, path) in enumerate(calls)
+            if operation == "fsync_file" and path != marker_path
+        ]
+        versions_dir_fsync_indices = [
+            index for index, call in enumerate(calls) if call == 
("fsync_directory", bundle.versions_dir)
+        ]
+
+        assert cache_file_fsync_indices
+        assert max(cache_file_fsync_indices) < replace_index
+        assert any(replace_index < index < marker_fsync_index for index in 
versions_dir_fsync_indices)
+        assert any(index > marker_fsync_index for index in 
versions_dir_fsync_indices)
+        assert marker_path.read_text() == published.version
+
+
+class TestPinned:
+    def test_pinned_bundle_uses_materialized_snapshot(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        pinned_bundle = _make_bundle(tmp_path, version=published.version)
+
+        pinned_bundle.initialize()
+
+        assert pinned_bundle.get_current_version().version == published.version
+        assert pinned_bundle.path == bundle.versions_dir / published.version
+        assert (pinned_bundle.path / "dags/example.py").read_text() == 
"print('dag')"
+
+    def test_pinned_bundle_rematerializes_deleted_cache(self, tmp_path):
+        _, _, published = _published_bundle(tmp_path)
+        pinned_bundle = _make_bundle(tmp_path, version=published.version)
+        pinned_bundle.initialize()
+        remove_bundle_tree_forcefully(pinned_bundle.path)
+
+        fresh_pinned_bundle = _make_bundle(tmp_path, version=published.version)
+        fresh_pinned_bundle.initialize()
+
+        assert _get_snapshot_dir(pinned_bundle, published.version).exists()
+        assert (fresh_pinned_bundle.path / "dags/example.py").read_text() == 
"print('dag')"
+
+    def test_pinned_bundle_rebuilds_corrupt_cache(self, tmp_path):
+        _, _, published = _published_bundle(tmp_path)
+        pinned_bundle = _make_bundle(tmp_path, version=published.version)
+        pinned_bundle.initialize()
+        cached_dag = pinned_bundle.path / "dags/example.py"
+        _add_write_bits(cached_dag)
+        cached_dag.write_text("print('corrupt')")
+
+        # A host whose validation state was invalidated must detect the 
corruption.
+        pinned_bundle._get_validation_marker_path(published.version).unlink()
+        fresh_pinned_bundle = _make_bundle(tmp_path, version=published.version)
+        fresh_pinned_bundle.initialize()
+
+        assert cached_dag.read_text() == "print('dag')"
+        assert (
+            _get_snapshot_dir(pinned_bundle, published.version) / 
"dags/example.py"
+        ).read_text() == "print('dag')"
+
+    def test_validation_marker_lets_fresh_bundle_skip_hashing(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        assert bundle._get_validation_marker_path(published.version).exists()
+
+        fresh_bundle = _make_bundle(tmp_path, version=published.version)
+        # The marker skips only the hashing pass; the structural pass still 
runs so
+        # that truncated or mutated cache trees are detected and rebuilt.
+        with mock.patch.object(
+            bundle_module,
+            "compute_file_sha256",
+            autospec=True,
+            side_effect=AssertionError("marker must skip the hashing pass"),
+        ):
+            fresh_bundle.initialize()
+        assert (fresh_bundle.path / "dags/example.py").read_text() == 
"print('dag')"
+
+    def test_missing_pinned_snapshot_raises_clear_error(self, tmp_path):
+        bundle = _make_bundle(tmp_path, version=f"sha256-{'0' * 64}")
+
+        with pytest.raises(BundleManifestNotFoundError, match="is not 
published"):
+            bundle.initialize()
+
+    @pytest.mark.parametrize("entry_point", ["initialize", "path"])
+    def test_pinned_bundle_rejects_invalid_version_before_path_lookup(self, 
tmp_path, entry_point):
+        bundle = _make_bundle(tmp_path, version="../outside")
+
+        with pytest.raises(BundleManifestError, match="pinned version is not a 
valid sha256 version"):
+            _call_entry_point(bundle, entry_point)
+
+    def test_pinned_refresh_is_not_supported(self, tmp_path):
+        bundle = _make_bundle(tmp_path, version=f"sha256-{'0' * 64}")
+
+        with pytest.raises(ValueError, match="Refreshing a specific bundle 
version is not supported"):
+            bundle.refresh()
+
+    @pytest.mark.skipif(os.geteuid() == 0, reason="permission checks are 
bypassed as root")
+    def test_pinned_initialize_wraps_permission_error(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+
+        pinned = _make_bundle(tmp_path, version=published.version)
+        storage_root = tmp_path / "bundles"
+        storage_root.chmod(0o000)
+        try:
+            with pytest.raises(BundleManifestError) as excinfo:
+                pinned.initialize()
+        finally:
+            storage_root.chmod(0o755)
+        assert isinstance(excinfo.value.__cause__, PermissionError)
+
+
+class TestPublish:
+    def test_publish_and_refresh_support_nested_paths_before_root_files(self, 
tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "z.py", "print('root')")
+        _write_file(source, "a/example.py", "print('nested')")
+        bundle = _make_bundle(tmp_path)
+
+        published = publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+        snapshot_manifest = json.loads(
+            (_get_snapshot_dir(bundle, published.version) / 
MANIFEST_FILE_NAME).read_text(encoding="utf-8")
+        )
+        bundle.refresh()
+
+        assert [file_info["path"] for file_info in snapshot_manifest["files"]] 
== ["a/example.py", "z.py"]
+        assert (bundle.path / "a/example.py").read_text() == "print('nested')"
+        assert (bundle.path / "z.py").read_text() == "print('root')"
+
+    def test_publish_is_idempotent(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        bundle = _make_bundle(tmp_path)
+
+        first = publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+        second = publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert first.version == second.version
+        assert first.created_snapshot is True
+        assert second.created_snapshot is False
+        assert json.loads(_get_ref_path(bundle).read_text()) == 
second.ref_payload
+        assert not stat.S_IMODE(_get_snapshot_dir(bundle, 
second.version).stat().st_mode) & 0o222
+        assert not (bundle.versions_dir / second.version).exists()
+
+    def test_publish_result_reports_the_store_locators(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+
+        assert published.snapshot_locator == str(_get_snapshot_dir(bundle, 
published.version))
+        assert published.ref_locator == str(_get_ref_path(bundle))
+
+    def test_republish_rejects_damaged_existing_snapshot(self, tmp_path):
+        bundle, source, published = _published_bundle(tmp_path)
+        _add_write_bits(_get_snapshot_dir(bundle, published.version) / 
"dags/example.py")
+        _write_file(_get_snapshot_dir(bundle, published.version), 
"dags/example.py", "print('drift')")
+
+        with pytest.raises(BundleManifestError, match="does not match local 
snapshot manifest"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+    def test_explicit_publish_rejects_empty_source_by_default(self, tmp_path):
+        source = tmp_path / "source"
+        source.mkdir()
+        bundle = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestError, match="explicitly publish 
empty source tree"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert not _get_ref_path(bundle).exists()
+
+        allowed = _make_bundle(tmp_path, allow_empty_source=True)
+        published = publish_manifest_local_dag_bundle(bundle=allowed, 
source_path=source)
+
+        assert published.file_count == 0
+        assert json.loads(_get_ref_path(allowed).read_text())["version"] == 
published.version
+
+    def test_explicit_publish_rejects_pinned_bundle(self, tmp_path):
+        bundle = _make_bundle(tmp_path, version=f"sha256-{'a' * 64}")
+
+        with pytest.raises(BundleManifestError, match="Cannot explicitly 
publish pinned bundle"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=tmp_path / "explicit-source")
+
+    def test_publish_rejects_stale_expected_current_version(self, tmp_path):
+        source = tmp_path / "source"
+        dag_file = _write_file(source, "dags/example.py", "print('first')")
+        bundle = _make_bundle(tmp_path)
+
+        first = publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+        dag_file.write_text("print('second')")
+        second = publish_manifest_local_dag_bundle(
+            bundle=bundle, source_path=source, 
expected_current_version=first.version
+        )
+        dag_file.write_text("print('stale')")
+
+        with pytest.raises(
+            BundleManifestReferenceChangedError,
+            match=f"expected {first.version!r}, found {second.version!r}",
+        ):
+            publish_manifest_local_dag_bundle(
+                bundle=bundle, source_path=source, 
expected_current_version=first.version
+            )
+
+        assert json.loads(_get_ref_path(bundle).read_text())["version"] == 
second.version
+
+    def 
test_first_publish_rejects_expected_current_version_with_clear_error(self, 
tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        bundle = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestReferenceChangedError, match="no 
published version to compare"):
+            publish_manifest_local_dag_bundle(
+                bundle=bundle, source_path=source, 
expected_current_version=f"sha256-{'0' * 64}"
+            )
+
+        assert not _get_ref_path(bundle).exists()
+
+    def test_publish_rejects_invalid_expected_current_version(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        bundle = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestError, match="expected current 
version is not a valid sha256"):
+            publish_manifest_local_dag_bundle(
+                bundle=bundle, source_path=source, 
expected_current_version="v1"
+            )
+
+    def test_publish_rejects_file_added_during_publication(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        real_materialize = store_module._materialize_manifest_snapshot
+
+        def materialize_and_add_file(**kwargs):
+            committed = real_materialize(**kwargs)
+            _write_file(source, "dags/added.py", "print('added')")
+            return committed
+
+        bundle = _make_bundle(tmp_path)
+        with (
+            mock.patch.object(
+                store_module,
+                "_materialize_manifest_snapshot",
+                autospec=True,
+                side_effect=materialize_and_add_file,
+            ),
+            pytest.raises(BundleManifestSourceChangedError, match="changed 
while publishing"),
+        ):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert not _get_ref_path(bundle).exists()
+
+    def test_publish_rejects_published_root_inside_source(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        bundle = ManifestLocalDagBundle(name=BUNDLE_NAME, 
published_root=str(source / "published"))
+
+        with pytest.raises(ValueError, match="published_root must not be 
inside source_path"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert not _get_ref_path(bundle).exists()
+
+    def test_publish_rejects_source_inside_published_root(self, tmp_path):
+        published_root = tmp_path / "published"
+        source = published_root / "refs" / BUNDLE_NAME
+        _write_file(source, "dags/example.py", "print('dag')")
+        bundle = ManifestLocalDagBundle(name=BUNDLE_NAME, 
published_root=str(published_root))
+
+        with pytest.raises(ValueError, match="source_path must not be inside 
published_root"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert not _get_ref_path(bundle).exists()
+
+    def test_publish_rejects_versions_dir_inside_source(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        storage_path = source / ".airflow-bundles"
+
+        with conf_vars({("dag_processor", "dag_bundle_storage_path"): 
str(storage_path)}):
+            bundle = _make_bundle(tmp_path)
+
+            with pytest.raises(ValueError, match="source_path and versions_dir 
must not overlap"):
+                publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert not _get_ref_path(bundle).exists()
+        assert not storage_path.exists()
+
+    def test_publish_rejects_source_inside_versions_dir(self, tmp_path):
+        bundle = _make_bundle(tmp_path)
+        source = bundle.versions_dir / "publisher-source"
+        dag_file = _write_file(source, "dags/example.py", "print('dag')")
+
+        with pytest.raises(ValueError, match="source_path and versions_dir 
must not overlap"):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        assert dag_file.exists()
+        assert not _get_ref_path(bundle).exists()
+
+    def test_publish_fsyncs_versions_dir_before_ref_write(self, tmp_path):
+        source = tmp_path / "source"
+        _write_file(source, "dags/example.py", "print('dag')")
+        calls = []
+        real_write_json_atomically = store_module._write_json_atomically
+
+        def record_fsync_directory(path):
+            calls.append(("fsync_directory", Path(path)))
+
+        def record_write_json_atomically(destination_path, payload):
+            calls.append(("write_json", Path(destination_path)))
+            real_write_json_atomically(destination_path, payload)
+
+        bundle = _make_bundle(tmp_path)
+        with (
+            mock.patch.object(
+                store_module, "fsync_directory", autospec=True, 
side_effect=record_fsync_directory
+            ),
+            mock.patch.object(
+                store_module,
+                "_write_json_atomically",
+                autospec=True,
+                side_effect=record_write_json_atomically,
+            ),
+        ):
+            publish_manifest_local_dag_bundle(bundle=bundle, 
source_path=source)
+
+        versions_dir_fsync = ("fsync_directory", _get_snapshots_dir(bundle))
+        ref_write = ("write_json", _get_ref_path(bundle))
+        assert versions_dir_fsync in calls
+        assert ref_write in calls
+        assert calls.index(versions_dir_fsync) < calls.index(ref_write)
+
+
+class TestValidation:
+    def test_refresh_rejects_missing_manifest_ref(self, tmp_path):
+        bundle = _make_bundle(tmp_path)
+
+        with pytest.raises(
+            BundleManifestNotFoundError,
+            match="has no release reference at .*Publish the bundle or restore 
the release reference",
+        ):
+            bundle.refresh()
+
+    def test_refresh_rejects_invalid_json_ref(self, tmp_path):
+        bundle = _make_bundle(tmp_path)
+        _get_ref_path(bundle).parent.mkdir(parents=True)
+        _get_ref_path(bundle).write_text("{not-json")
+
+        with pytest.raises(BundleManifestError, match="release reference .* is 
not a JSON object"):
+            bundle.refresh()
+
+    @pytest.mark.parametrize("entry_point", ["path", "get_current_version", 
"refresh", "initialize"])
+    def test_entry_points_reject_non_utf8_manifest_ref(self, tmp_path, 
entry_point):
+        bundle = _make_bundle(tmp_path)
+        _get_ref_path(bundle).parent.mkdir(parents=True)
+        _get_ref_path(bundle).write_bytes(b"\xff")
+
+        with pytest.raises(BundleManifestError, match="release reference .* is 
not a JSON object") as excinfo:
+            _call_entry_point(bundle, entry_point)
+
+        assert isinstance(excinfo.value.__cause__, UnicodeDecodeError)
+
+    @pytest.mark.parametrize("entry_point", ["path", "get_current_version", 
"refresh", "initialize"])
+    def test_entry_points_raise_airflow_exception_when_ref_missing(self, 
tmp_path, entry_point):
+        bundle = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestError, match="has no release 
reference") as excinfo:
+            _call_entry_point(bundle, entry_point)
+        assert isinstance(excinfo.value, AirflowException)
+
+    @pytest.mark.parametrize(
+        ("mutate", "match"),
+        [
+            (lambda payload: payload.update({"schema_version": 2}), 
"unsupported schema_version"),
+            (lambda payload: payload.update({"bundle_name": "other"}), 
"expected 'manifest-local'"),
+            (lambda payload: payload.update({"version": None}), "does not 
contain a version"),
+            (lambda payload: payload.update({"version": "../outside"}), "valid 
sha256 version"),
+            (lambda payload: payload.update({"version": "sha256-bad"}), "valid 
sha256 version"),
+            (lambda payload: payload.update({"version": f"sha256-{'A' * 
64}"}), "valid sha256 version"),
+            (lambda payload: payload.update({"backend": {"type": "s3"}}), "not 
for a local backend"),
+            (lambda payload: payload.update({"manifest": None}), "does not 
contain manifest data"),
+            (
+                lambda payload: payload.update({"manifest": {"path": None, 
"sha256": "x"}}),
+                "valid manifest path",
+            ),
+            (
+                lambda payload: payload.update({"manifest": {"path": 
MANIFEST_FILE_NAME, "sha256": ""}}),
+                "does not contain manifest sha256",
+            ),
+            (
+                lambda payload: payload.update({"manifest": {"path": 
"../manifest.json", "sha256": "x"}}),
+                "unsafe",
+            ),
+            (
+                lambda payload: payload.update({"manifest": {"path": 
"/tmp/manifest.json", "sha256": "x"}}),
+                "unsafe",
+            ),
+            (
+                lambda payload: payload.update(
+                    {"manifest": {"path": 
"nested/.airflow-bundle-manifest.json", "sha256": "x"}}
+                ),
+                "must point",
+            ),
+            (lambda payload: payload.update({"file_count": -1}), "valid 
file_count"),
+            (lambda payload: payload.update({"file_count": True}), "valid 
file_count"),
+            (lambda payload: payload.update({"total_size": -1}), "valid 
total_size"),
+            (lambda payload: payload.update({"total_size": True}), "valid 
total_size"),
+        ],
+    )
+    def test_refresh_rejects_invalid_ref_payload(self, tmp_path, mutate, 
match):
+        bundle, _, published = _published_bundle(tmp_path)
+        payload = dict(published.ref_payload)
+        payload["backend"] = dict(payload["backend"])
+        payload["manifest"] = dict(payload["manifest"])
+        mutate(payload)
+        _write_manifest_ref(_get_ref_path(bundle), payload)
+
+        with pytest.raises(BundleManifestError, match=match):
+            bundle.refresh()
+
+    @pytest.mark.parametrize(
+        ("field", "match"),
+        [("file_count", "file_count 1 does not match manifest reference 2"), 
("total_size", "total_size")],
+    )
+    def test_refresh_rejects_ref_counts_that_disagree_with_snapshot(self, 
tmp_path, field, match):
+        bundle, _, published = _published_bundle(tmp_path)
+        payload = dict(published.ref_payload)
+        payload[field] += 1
+        _write_manifest_ref(_get_ref_path(bundle), payload)
+
+        with pytest.raises(BundleManifestError, match=match):
+            bundle.refresh()
+
+    @pytest.mark.parametrize(
+        ("mutate", "match"),
+        [
+            (lambda manifest: manifest.update({"schema_version": 2}), 
"unsupported schema_version"),
+            (lambda manifest: manifest.update({"bundle_name": "other"}), 
"expected 'manifest-local'"),
+            (lambda manifest: manifest.update({"backend": {"type": "s3"}}), 
"not for a local backend"),
+            (lambda manifest: manifest.update({"file_count": 99}), 
"file_count"),
+            (lambda manifest: manifest.update({"total_size": 99}), 
"total_size"),
+            (lambda manifest: 
manifest["files"].append(dict(manifest["files"][0])), "duplicate path"),
+            (lambda manifest: manifest["files"][0].update({"path": 
"../evil.py"}), "unsafe relative path"),
+            (
+                lambda manifest: manifest["files"][0].update({"path": 
"dags//example.py"}),
+                "unsafe relative path",
+            ),
+            (
+                lambda manifest: manifest["files"][0].update({"path": 
"dags/./example.py"}),
+                "unsafe relative path",
+            ),
+        ],
+    )
+    def test_refresh_rejects_corrupt_snapshot_manifest(self, tmp_path, mutate, 
match):
+        bundle, _, published = _published_bundle(tmp_path)
+        manifest_path = _get_snapshot_dir(bundle, published.version) / 
MANIFEST_FILE_NAME
+        manifest = json.loads(manifest_path.read_text())
+        mutate(manifest)
+        _add_write_bits(manifest_path)
+        manifest_path.write_text(json.dumps(manifest))
+
+        with pytest.raises(BundleManifestError, match=match):
+            bundle.refresh()
+
+    def test_refresh_rejects_corrupt_snapshot_manifest_json(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        manifest_path = _get_snapshot_dir(bundle, published.version) / 
MANIFEST_FILE_NAME
+        _add_write_bits(manifest_path)
+        manifest_path.write_text("{not-json")
+
+        with pytest.raises(BundleManifestError, match="snapshot manifest is 
not valid JSON"):
+            bundle.refresh()
+
+    def test_refresh_rejects_missing_snapshot_manifest(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        manifest_path = _get_snapshot_dir(bundle, published.version) / 
MANIFEST_FILE_NAME
+        _add_write_bits(manifest_path.parent)
+        manifest_path.unlink()
+
+        with pytest.raises(BundleManifestNotFoundError, 
match=MANIFEST_FILE_NAME):
+            bundle.refresh()
+
+    def test_refresh_rejects_symlinked_snapshot_manifest(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        manifest_path = _get_snapshot_dir(bundle, published.version) / 
MANIFEST_FILE_NAME
+        real_manifest = tmp_path / "real-manifest.json"
+        shutil.copy(manifest_path, real_manifest)
+        _add_write_bits(manifest_path.parent)
+        manifest_path.unlink()
+        _create_symlink_or_skip(real_manifest, manifest_path)
+
+        with pytest.raises(BundleManifestError, match="snapshot manifest .* is 
a symlink"):
+            bundle.refresh()
+
+    def test_refresh_rejects_snapshot_manifest_digest_mismatch(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        payload = dict(published.ref_payload)
+        payload["manifest"] = dict(payload["manifest"])
+        payload["manifest"]["sha256"] = "sha256:bad"
+        _write_manifest_ref(_get_ref_path(bundle), payload)
+
+        with pytest.raises(BundleManifestError, match="digest mismatch"):
+            bundle.refresh()
+
+    def test_refresh_rejects_snapshot_file_content_drift(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        _add_write_bits(_get_snapshot_dir(bundle, published.version) / 
"dags/example.py")
+        _write_file(_get_snapshot_dir(bundle, published.version), 
"dags/example.py", "print('drift')")
+
+        with pytest.raises(BundleManifestError, match="does not match local 
snapshot manifest"):
+            bundle.refresh()
+
+    def test_refresh_rejects_unexpected_snapshot_files(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        _add_write_bits(_get_snapshot_dir(bundle, published.version) / "dags")
+        _write_file(_get_snapshot_dir(bundle, published.version), 
"dags/unexpected.py", "print('extra')")
+
+        with pytest.raises(BundleManifestError, match="files not present in 
the manifest"):
+            bundle.refresh()
+
+    def 
test_refresh_rejects_unexpected_snapshot_file_under_ignored_directory(self, 
tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        snapshot_dags_dir = _get_snapshot_dir(bundle, published.version) / 
"dags"
+        _add_write_bits(snapshot_dags_dir)
+        _write_file(snapshot_dags_dir, "__pycache__/unexpected.py", 
"print('extra')")
+
+        with pytest.raises(BundleManifestError, match="files not present in 
the manifest"):
+            bundle.refresh()
+
+    def test_refresh_rejects_symlinked_snapshot_directory(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        symlink_target = tmp_path / "outside"
+        _write_file(symlink_target, "outside.py", "print('outside')")
+        snapshot_dags_dir = _get_snapshot_dir(bundle, published.version) / 
"dags"
+        _add_write_bits(snapshot_dags_dir)
+        _create_symlink_or_skip(symlink_target, snapshot_dags_dir / "linked", 
target_is_directory=True)
+
+        with pytest.raises(BundleManifestError, match="symlinked directory"):
+            bundle.refresh()
+
+    def test_refresh_rejects_symlinked_snapshot_file(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        symlink_target = tmp_path / "outside.py"
+        symlink_target.write_text("print('outside')")
+        snapshot_dags_dir = _get_snapshot_dir(bundle, published.version) / 
"dags"
+        _add_write_bits(snapshot_dags_dir)
+        _create_symlink_or_skip(symlink_target, snapshot_dags_dir / 
"linked.py")
+
+        with pytest.raises(BundleManifestError, match="symlinked file"):
+            bundle.refresh()
+
+    def test_refresh_rejects_non_regular_snapshot_file(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        snapshot_dags_dir = _get_snapshot_dir(bundle, published.version) / 
"dags"
+        _add_write_bits(snapshot_dags_dir)
+        try:
+            os.mkfifo(snapshot_dags_dir / "fifo.py")
+        except OSError as e:
+            pytest.skip(f"mkfifo is not supported in this test environment: 
{e}")
+
+        with pytest.raises(BundleManifestError, match="non-regular file"):
+            bundle.refresh()
+
+    def test_snapshot_validation_rejects_walk_error(self, tmp_path):
+        snapshot_root = tmp_path / "snapshot"
+        snapshot_root.mkdir()
+
+        def fail_walk(*args, onerror, **kwargs):
+            onerror(PermissionError(13, "Permission denied", str(snapshot_root 
/ "unreadable")))
+
+        with (
+            mock.patch.object(bundle_module.os, "walk", autospec=True, 
side_effect=fail_walk),
+            pytest.raises(BundleManifestError, match="changed or became 
unreadable"),
+        ):
+            list(ManifestLocalDagBundle._iter_snapshot_files(snapshot_root))
+
+    def 
test_snapshot_file_vanishing_during_validation_is_not_a_source_change(self, 
tmp_path):
+        snapshot_root = tmp_path / "snapshot"
+        snapshot_root.mkdir()
+
+        with (
+            mock.patch.object(
+                bundle_module.os, "walk", autospec=True, 
return_value=[(str(snapshot_root), [], ["gone.py"])]
+            ),
+            pytest.raises(BundleManifestError, match="disappeared during 
validation") as excinfo,
+        ):
+            list(ManifestLocalDagBundle._iter_snapshot_files(snapshot_root))
+        assert not isinstance(excinfo.value, BundleManifestSourceChangedError)
+
+
+class TestCacheRecovery:
+    @mock.patch.object(bundle_module.os, "scandir", autospec=True, 
side_effect=_scandir_unless_unlistable)
+    def test_cache_permissions_fail_on_an_unlistable_directory(self, 
mock_scandir, tmp_path):
+        (tmp_path / "cache" / "unlistable").mkdir(parents=True)
+
+        with pytest.raises(PermissionError, match="cannot list directory"):
+            bundle_module._set_cache_tree_permissions(tmp_path / "cache")
+
+    @pytest.mark.parametrize("has_validation_marker", [True, False])
+    def test_helper_import_bytecode_does_not_invalidate_cached_snapshot(
+        self, tmp_path, monkeypatch, has_validation_marker
+    ):
+        source = tmp_path / "source"
+        helper_name = "manifest_local_bundle_helper"
+        _write_file(source, f"{helper_name}.py", "VALUE = 'helper'\n")
+        bundle = _make_bundle(tmp_path)
+        published = _publish(bundle, source)
+        bundle.refresh()
+        cached_helper = bundle.path / f"{helper_name}.py"
+        tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version)
+        tracking_inode = tracking_file.stat().st_ino
+        monkeypatch.syspath_prepend(str(bundle.path))
+        # Breeze disables bytecode generation; production helper imports 
normally enable it.
+        monkeypatch.setattr(sys, "dont_write_bytecode", False)
+        monkeypatch.setattr(sys, "pycache_prefix", None)
+        try:
+            helper = importlib.import_module(helper_name)
+            assert helper.VALUE == "helper"
+        finally:
+            sys.modules.pop(helper_name, None)
+        cached_bytecode = Path(cache_from_source(str(cached_helper)))
+        assert cached_bytecode.exists()
+        remove_bundle_tree_forcefully(_get_snapshot_dir(bundle, 
published.version))
+        if not has_validation_marker:
+            bundle._get_validation_marker_path(published.version).unlink()
+
+        fresh = _make_bundle(tmp_path, version=published.version)
+        fresh.initialize()
+
+        assert cached_helper.read_text() == "VALUE = 'helper'\n"
+        assert cached_bytecode.exists()
+        assert tracking_file.stat().st_ino == tracking_inode
+
+    @pytest.mark.parametrize("location", ["cache", "published"])
+    @pytest.mark.parametrize(
+        ("source_file", "bytecode_file"),
+        [
+            ("dags/example.py", "dags/__pycache__/example.cpython-313.pyc"),
+            ("dags/example.py", 
"dags/__pycache__/example.cpython-313.opt-1.pyc"),
+            ("dags/example.py", 
"dags/__pycache__/example.cpython-313.opt-O2.pyc"),
+            ("dags/example.py", "dags/__pycache__/example.pypy310.pyc"),
+            ("dags/example.helper.py", 
"dags/__pycache__/example.helper.cpython-313.pyc"),
+            ("dags/example.py", 
"dags/__pycache__/example.cpython-313.pyc.123456789"),
+        ],
+    )
+    def test_runtime_bytecode_is_accepted_only_in_cache(self, tmp_path, 
location, source_file, bytecode_file):
+        source = tmp_path / "source"
+        _write_file(source, source_file, "VALUE = 'helper'\n")
+        bundle = _make_bundle(tmp_path)
+        published = _publish(bundle, source)
+        if location == "cache":
+            bundle.refresh()
+            snapshot_path = bundle.path
+        else:
+            snapshot_path = _get_snapshot_dir(bundle, published.version)
+            _add_write_bits(snapshot_path / Path(source_file).parent)
+        bytecode_path = _write_file(snapshot_path, bytecode_file, "bytecode")
+
+        if location == "cache":
+            remove_bundle_tree_forcefully(_get_snapshot_dir(bundle, 
published.version))
+            fresh = _make_bundle(tmp_path, version=published.version)
+            fresh.initialize()
+            assert (fresh.path / source_file).read_text() == "VALUE = 
'helper'\n"
+            assert bytecode_path.exists()
+        else:
+            with pytest.raises(BundleManifestError, match="files not present 
in the manifest"):
+                bundle.refresh()
+
+    @pytest.mark.parametrize(
+        ("relative_path", "entry_type"),
+        [
+            ("dags/__pycache__/orphan.cpython-313.pyc", "file"),
+            ("dags/__pycache__/example.pyc", "file"),
+            ("dags/__pycache__/example.cpython-313.pyc.tmp", "file"),
+            ("dags/__pycache__/nested/example.cpython-313.pyc", "file"),
+            ("dags/example.cpython-313.pyc", "file"),
+            ("dags/__pycache__/example.cpython-313.opt-.pyc", "file"),
+            ("dags/__pycache__/example.cpython-313.py", "file"),
+            ("dags/__pycache__/example.cpython-313.pyc", "symlink"),
+            ("dags/__pycache__/example.cpython-313.pyc", "fifo"),
+        ],
+    )
+    def test_bytecode_tolerance_does_not_hide_invalid_cache_entries(
+        self, tmp_path, relative_path, entry_type
+    ):
+        bundle, _, _ = _published_bundle(tmp_path)
+        bundle.refresh()
+        extra_path = bundle.path / relative_path
+        extra_path.parent.mkdir(parents=True, exist_ok=True)
+        if entry_type == "symlink":
+            target = _write_file(tmp_path, "outside.pyc", "bytecode")
+            _create_symlink_or_skip(target, extra_path)
+        elif entry_type == "fifo":
+            try:
+                os.mkfifo(extra_path)
+            except OSError as e:
+                pytest.skip(f"mkfifo is not supported in this test 
environment: {e}")
+        else:
+            extra_path.write_text("unexpected")
+
+        fresh = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestError, match="structurally invalid 
cache copy"):
+            _ = fresh.path
+
+    @mock.patch.object(bundle_module.os, "walk", autospec=True)
+    def 
test_cache_validation_tolerates_bytecode_temp_removed_after_directory_scan(self,
 mock_walk, tmp_path):
+        cache_dir = tmp_path / "__pycache__"
+        cache_dir.mkdir()
+        mock_walk.return_value = [
+            (str(tmp_path), ["__pycache__"], []),
+            (str(cache_dir), [], ["example.cpython-313.pyc.123456789"]),
+        ]
+
+        assert (
+            list(ManifestLocalDagBundle._iter_snapshot_files(tmp_path, 
cached_source_paths={"example.py"}))
+            == []
+        )
+
+    def test_marker_does_not_certify_truncated_cache_tree(self, tmp_path):
+        # Simulates stale cleanup's shutil.rmtree being interrupted partway: 
the version
+        # dir still exists (truncated) and the marker survives. The structural 
pass behind
+        # the marker must detect this and rebuild.
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        cached_dag = bundle.versions_dir / published.version / 
"dags/example.py"
+        cached_dag.unlink()
+
+        _make_bundle(tmp_path).refresh()
+
+        assert cached_dag.read_text() == "print('dag')"
+
+    def test_marker_does_not_certify_mutated_cache_tree(self, tmp_path):
+        # Cache dirs are owner-writable (a stale-cleanup requirement), so Dag 
code could
+        # inject files; the structural pass behind the marker must catch it.
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        injected = bundle.versions_dir / published.version / 
"dags/generated.py"
+        injected.write_text("print('injected')")
+
+        _make_bundle(tmp_path).refresh()
+
+        assert not injected.exists()
+
+    def test_path_does_not_serve_another_version_before_materialization(self, 
tmp_path):
+        # get_current_version() already reports the new release, so serving 
the previous
+        # cached tree here would pair that version with another version's code.
+        bundle, source, first = _published_bundle(tmp_path)
+        bundle.refresh()
+        _write_file(source, "dags/example.py", "print('dag v2')")
+        second = _publish(bundle, source)
+
+        fresh = _make_bundle(tmp_path)
+
+        assert fresh.get_current_version().version == second.version
+        assert fresh.path == fresh.versions_dir / second.version
+        assert not fresh.path.exists()
+        assert (fresh.versions_dir / first.version).is_dir()
+
+    def test_path_rejects_truncated_current_cache(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        (bundle.versions_dir / published.version / "dags/example.py").unlink()
+
+        fresh = _make_bundle(tmp_path)
+
+        with pytest.raises(BundleManifestError, match="structurally invalid 
cache copy"):
+            _ = fresh.path
+
+    @conf_vars(
+        {
+            ("dag_processor", "stale_bundle_cleanup_min_versions"): "0",
+            ("dag_processor", "stale_bundle_cleanup_age_threshold"): "60",
+        }
+    )
+    def test_corrupt_cache_rebuild_restores_tracking_lock(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+
+        tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version)
+        assert tracking_file.exists()
+
+        cached_dag = bundle.versions_dir / published.version / 
"dags/example.py"
+        _add_write_bits(cached_dag)
+        cached_dag.write_text("corrupted!!")
+        bundle._get_validation_marker_path(published.version).unlink()
+
+        fresh = _make_bundle(tmp_path)
+        fresh.refresh()
+
+        assert tracking_file.exists()
+        _set_tracking_timestamp(fresh, published.version, 
"2000-01-01T00:00:00+00:00")
+        
BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=bundle.name)
+        assert (fresh.versions_dir / published.version / 
"dags/example.py").read_text() == "print('dag')"
+
+
+def _set_tracking_timestamp(bundle: ManifestLocalDagBundle, version: str, 
timestamp: str) -> Path:
+    # Written in place, so a lock already held on the tracking file stays on 
it.
+    tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=version)
+    tracking_file.parent.mkdir(parents=True, exist_ok=True)
+    tracking_file.write_text(timestamp)
+    return tracking_file
+
+
+class TestStaleVersionCleanup:
+    STALE = "2000-01-01T00:00:00+00:00"
+
+    @pytest.fixture(autouse=True)
+    def _evict_every_stale_version(self):
+        with conf_vars(
+            {
+                ("dag_processor", "stale_bundle_cleanup_min_versions"): "0",
+                ("dag_processor", "stale_bundle_cleanup_age_threshold"): "60",
+            }
+        ):
+            yield
+
+    @staticmethod
+    def _remove_stale_versions(bundle: ManifestLocalDagBundle) -> None:
+        
BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=bundle.name)
+
+    @pytest.mark.parametrize("snapshot_failure", ["missing", "corrupt"])
+    def test_failed_first_refresh_leaves_no_tracking_file(self, tmp_path, 
snapshot_failure):
+        bundle, _, published = _published_bundle(tmp_path)
+        if snapshot_failure == "missing":
+            remove_bundle_tree_forcefully(_get_snapshot_dir(bundle, 
published.version))
+        else:
+            published_dag = _get_snapshot_dir(bundle, published.version) / 
"dags/example.py"
+            _add_write_bits(published_dag)
+            published_dag.write_text("corrupt")
+        tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version)
+
+        with pytest.raises(BundleManifestError):
+            bundle.refresh()
+
+        assert not (bundle.versions_dir / published.version).exists()
+        assert not tracking_file.exists()
+        del bundle
+        gc.collect()
+        
BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=BUNDLE_NAME)
+        assert not tracking_file.exists()
+
+    @pytest.mark.parametrize("snapshot_failure", ["missing", "corrupt"])
+    def test_failed_refresh_preserves_previous_version_lock(self, tmp_path, 
snapshot_failure):
+        bundle, source, first = _published_bundle(tmp_path)
+        bundle.refresh()
+        first_path = bundle.path
+        _write_file(source, "dags/example.py", "print('dag v2')")
+        second = _publish(bundle, source)
+        if snapshot_failure == "missing":
+            remove_bundle_tree_forcefully(_get_snapshot_dir(bundle, 
second.version))
+        else:
+            published_dag = _get_snapshot_dir(bundle, second.version) / 
"dags/example.py"
+            _add_write_bits(published_dag)
+            published_dag.write_text("corrupt")
+
+        with pytest.raises(BundleManifestError):
+            bundle.refresh()
+
+        assert bundle.get_current_version().version == first.version
+        assert bundle.path == first_path
+        assert not (bundle.versions_dir / second.version).exists()
+        assert not get_bundle_tracking_file(bundle_name=bundle.name, 
version=second.version).exists()
+        first_tracking_file = _set_tracking_timestamp(bundle, first.version, 
self.STALE)
+        self._remove_stale_versions(bundle)
+        assert (first_path / "dags/example.py").read_text() == "print('dag')"
+
+        del bundle
+        gc.collect()
+        
BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=BUNDLE_NAME)
+        assert not first_path.exists()
+        assert not first_tracking_file.exists()
+
+    @mock.patch.object(ManifestLocalDagBundle, "_materialize_cached_version", 
autospec=True)
+    def test_failed_refresh_preserves_another_refreshers_tracking_record(self, 
mock_materialize, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version)
+
+        def replace_tracking_then_fail(*args, **kwargs):
+            replacement = tracking_file.with_suffix(".replacement")
+            replacement.write_text(self.STALE)
+            replacement.replace(tracking_file)
+            raise BundleManifestError("materialization failed")
+
+        mock_materialize.side_effect = replace_tracking_then_fail
+
+        with pytest.raises(BundleManifestError, match="materialization 
failed"):
+            bundle.refresh()
+
+        assert not (bundle.versions_dir / published.version).exists()
+        assert tracking_file.read_text() == self.STALE
+
+    def test_cleanup_keeps_the_version_being_served(self, tmp_path):
+        # Cleanup ranks versions by when tasks last used them, not by release 
order, so the
+        # current release can look stale.
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        _set_tracking_timestamp(bundle, published.version, self.STALE)
+
+        self._remove_stale_versions(bundle)
+
+        assert (bundle.versions_dir / published.version / 
"dags/example.py").read_text() == "print('dag')"
+
+    def test_refresh_marks_the_version_in_use_before_checking_the_cache(self, 
tmp_path, monkeypatch):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        del bundle
+        gc.collect()
+        has_validated_cache = ManifestLocalDagBundle._has_validated_cache
+
+        def run_cleanup_after_cache_check(bundle, version, *, manifest_ref):
+            has_cache = has_validated_cache(bundle, version, 
manifest_ref=manifest_ref)
+            _set_tracking_timestamp(bundle, version, self.STALE)
+            self._remove_stale_versions(bundle)
+            return has_cache
+
+        monkeypatch.setattr(ManifestLocalDagBundle, "_has_validated_cache", 
run_cleanup_after_cache_check)
+        bundle = _make_bundle(tmp_path)
+
+        bundle.refresh()
+
+        assert (bundle.versions_dir / published.version / 
"dags/example.py").read_text() == "print('dag')"
+
+    def test_cleanup_can_remove_a_version_no_longer_served(self, tmp_path):
+        bundle, source, first = _published_bundle(tmp_path)
+        bundle.refresh()
+        _write_file(source, "dags/example.py", "print('dag v2')")
+        second = _publish(bundle, source)
+        bundle.refresh()
+        _set_tracking_timestamp(bundle, first.version, self.STALE)
+        _set_tracking_timestamp(bundle, second.version, self.STALE)
+
+        self._remove_stale_versions(bundle)
+
+        assert not (bundle.versions_dir / first.version).exists()
+        assert (bundle.versions_dir / second.version).is_dir()
+
+    @pytest.mark.parametrize("pinned", [True, False])
+    @pytest.mark.parametrize("reuse_bundle", [True, False])
+    def test_partial_cleanup_failure_rebuilds_previously_validated_version(
+        self, tmp_path, pinned, reuse_bundle
+    ):
+        bundle, source, first = _published_bundle(tmp_path)
+        bundle.refresh()
+        if reuse_bundle:
+            restored = _make_bundle(tmp_path, version=first.version) if pinned 
else bundle
+            restored.initialize()
+        _write_file(source, "dags/example.py", "print('dag v2')")
+        second = _publish(bundle, source)
+        bundle.refresh()
+        first_path = bundle.versions_dir / first.version
+        cached_dag = first_path / "dags/example.py"
+        _set_tracking_timestamp(bundle, first.version, self.STALE)
+
+        def remove_cache_partially(path):
+            assert path == first_path
+            cached_dag.unlink()
+            raise PermissionError("partial stale cleanup")
+
+        with (
+            mock.patch(
+                "airflow.dag_processing.bundles.base.shutil.rmtree",
+                autospec=True,
+                side_effect=remove_cache_partially,
+            ),
+            pytest.raises(PermissionError, match="partial stale cleanup"),
+        ):
+            self._remove_stale_versions(bundle)
+
+        assert first_path.is_dir()
+        assert not cached_dag.exists()
+        published_dag = _get_snapshot_dir(bundle, first.version) / 
"dags/example.py"
+        assert published_dag.read_text() == "print('dag')"
+        assert bundle.get_current_version().version == second.version
+        assert (bundle.path / "dags/example.py").read_text() == "print('dag 
v2')"
+        if not reuse_bundle:
+            restored = _make_bundle(tmp_path, version=first.version if pinned 
else None)
+        if pinned:
+            restored.initialize()
+        else:
+            _write_manifest_ref(_get_ref_path(bundle), first.ref_payload)
+            restored.refresh()
+
+        assert restored.get_current_version().version == first.version
+        assert (restored.path / "dags/example.py").read_text() == 
published_dag.read_text()
+
+    def 
test_refresh_retakes_the_lock_after_the_tracking_file_is_replaced(self, 
tmp_path):
+        # A corrupt-cache rebuild in another process deletes the tracking 
file, leaving the
+        # lock this bundle held on a file the cleanup no longer looks at.
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version).unlink()
+
+        bundle.refresh()
+        _set_tracking_timestamp(bundle, published.version, self.STALE)
+        self._remove_stale_versions(bundle)
+
+        assert (bundle.versions_dir / published.version).is_dir()
+
+    @mock.patch.object(bundle_module.BundleVersionLock, "acquire", 
autospec=True, side_effect=PermissionError)
+    def 
test_refresh_serves_the_bundle_when_the_version_cannot_be_marked_in_use(self, 
mock_acquire, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+
+        bundle.refresh()
+
+        mock_acquire.assert_called_once()
+        assert bundle.path == bundle.versions_dir / published.version
+        assert bundle._release_version_in_use is None
+
+    def test_refresh_preserves_current_lock_when_reacquisition_fails(self, 
tmp_path, monkeypatch):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        mock_acquire = mock.create_autospec(
+            bundle_module.BundleVersionLock.acquire, 
side_effect=PermissionError
+        )
+        monkeypatch.setattr(bundle_module.BundleVersionLock, "acquire", 
mock_acquire)
+
+        bundle.refresh()
+
+        mock_acquire.assert_called_once()
+        assert bundle.get_current_version().version == published.version
+        _set_tracking_timestamp(bundle, published.version, self.STALE)
+        self._remove_stale_versions(bundle)
+        assert (bundle.path / "dags/example.py").read_text() == "print('dag')"
+
+    @pytest.mark.filterwarnings("error::ResourceWarning", 
"error::pytest.PytestUnraisableExceptionWarning")
+    def test_discarded_bundle_closes_its_lock_file(self, tmp_path):
+        bundle, _, published = _published_bundle(tmp_path)
+        bundle.refresh()
+        tracking_file = get_bundle_tracking_file(bundle_name=bundle.name, 
version=published.version)
+
+        del bundle
+        gc.collect()
+
+        _set_tracking_timestamp(_make_bundle(tmp_path), published.version, 
self.STALE)
+        
BundleUsageTrackingManager().remove_stale_bundle_versions_for_bundle(bundle_name=BUNDLE_NAME)
+        assert not tracking_file.exists()

Reply via email to