Skip to content

Materialize chains of symlinks in remote repos - #29767

Closed
fmeum wants to merge 1 commit into
bazelbuild:masterfrom
fmeum:fix-29656-repo-symlink-prefetch
Closed

fmeum wants to merge 1 commit into
bazelbuild:masterfrom
fmeum:fix-29656-repo-symlink-prefetch

Conversation

@fmeum

@fmeum fmeum commented Jun 7, 2026 •

Copy link
Copy Markdown
Collaborator

Description

When a remotely cached repo is partially materialized since it contains action inputs, Skyframe provides the metadata of these inputs after following all symlinks as it does for all source files. Since (chains of) symlinks need to be preserved and materialized in the same way as if the repo rule ran locally or was fully materialized as a dependency of another repo rule, AbstractActionInputPrefetcher is changed to walk the full chain of symlinks behind a prefetched external repo path replant every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing into the main repo as such symlinks would cross over into the host filesystem. For this reason such symlinks now exclude a repo from being cached remotely. Note that the local repo contents cache already doesn't cache such repos. Since main repo files are readily available, this is considered a minor loss in usefulness only.

Motivation

Fixes #29656
Fixes #29515

Build API Changes

No

Checklist

  • I have added tests for the new use cases (if any).
  • I have updated the documentation (if applicable).

Release Notes

RELNOTES: The remote repo contents cache now correctly materializes chains of symlinks as action inputs, but no longer supports symlinks into the main repository.

@fmeum
fmeum force-pushed the fix-29656-repo-symlink-prefetch branch from 7a2cd3d to a26c38b Compare June 7, 2026 21:26
@fmeum
fmeum force-pushed the fix-29656-repo-symlink-prefetch branch 9 times, most recently from a1bf043 to 61200a3 Compare June 11, 2026 19:41
@fmeum fmeum changed the title Materialize repo source symlinks for locally executed actions Materialize chains of symlinks in remote repos Jun 11, 2026
@fmeum
fmeum force-pushed the fix-29656-repo-symlink-prefetch branch 3 times, most recently from 0f0c4b8 to 9ea20b8 Compare June 11, 2026 21:06
@fmeum

fmeum commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator Author

@bazel-io fork 9.2.0

@fmeum
fmeum marked this pull request as ready for review June 11, 2026 21:13
@fmeum
fmeum requested review from a team, Wyverald and meteorcloudy as code owners June 11, 2026 21:13
@fmeum
fmeum requested review from tjgq and removed request for a team and meteorcloudy June 11, 2026 21:13
@github-actions github-actions Bot added team-ExternalDeps External dependency handling, remote repositiories, WORKSPACE file. team-Remote-Exec Issues and PRs for the Execution (Remote) team area-Bzlmod Bzlmod-specific PRs, issues, and feature requests awaiting-review PR is awaiting review from an assigned reviewer labels Jun 11, 2026
@github-actions github-actions Bot removed the awaiting-PR-merge PR has been approved by a reviewer and is ready to be merge internally label Jun 23, 2026
fmeum added a commit to fmeum/bazel that referenced this pull request Jun 23, 2026
When a remotely cached repo is partially materialized since it contains action inputs, Skyframe provides the metadata of these inputs after following all symlinks as it does for all source files. Since (chains of) symlinks need to be preserved and materialized in the same way as if the repo rule ran locally or was fully materialized as a dependency of another repo rule, `AbstractActionInputPrefetcher` is changed to walk the full chain of symlinks behind a prefetched external repo path replant every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing into the main repo as such symlinks would cross over into the host filesystem. For this reason such symlinks now exclude a repo from being cached remotely. Note that the local repo contents cache already doesn't cache such repos. Since main repo files are readily available, this is considered a minor loss in usefulness only.

Fixes bazelbuild#29656
Fixes bazelbuild#29515

No

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (if applicable).

RELNOTES: The remote repo contents cache now correctly materializes chains of symlinks as action inputs, but no longer supports symlinks into the main repository.

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jun 23, 2026
When a remotely cached repo is partially materialized since it contains action inputs, Skyframe provides the metadata of these inputs after following all symlinks as it does for all source files. Since (chains of) symlinks need to be preserved and materialized in the same way as if the repo rule ran locally or was fully materialized as a dependency of another repo rule, `AbstractActionInputPrefetcher` is changed to walk the full chain of symlinks behind a prefetched external repo path replant every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing into the main repo as such symlinks would cross over into the host filesystem. For this reason such symlinks now exclude a repo from being cached remotely. Note that the local repo contents cache already doesn't cache such repos. Since main repo files are readily available, this is considered a minor loss in usefulness only.

Fixes bazelbuild#29656
Fixes bazelbuild#29515

No

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (if applicable).

RELNOTES: The remote repo contents cache now correctly materializes chains of symlinks as action inputs, but no longer supports symlinks into the main repository.

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
@fmeum
fmeum deleted the fix-29656-repo-symlink-prefetch branch June 23, 2026 14:36
bazel-io pushed a commit to bazel-io/bazel that referenced this pull request Jun 24, 2026
)

When a remotely cached repo is partially materialized since it contains
action inputs, Skyframe provides the metadata of these inputs after
following all symlinks as it does for all source files. Since (chains
of) symlinks need to be preserved and materialized in the same way as if
the repo rule ran locally or was fully materialized as a dependency of
another repo rule, `AbstractActionInputPrefetcher` is changed to walk
the full chain of symlinks behind a prefetched external repo path
replant every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing
into the main repo as such symlinks would cross over into the host
filesystem. For this reason such symlinks now exclude a repo from being
cached remotely. Note that the local repo contents cache already doesn't
cache such repos. Since main repo files are readily available, this is
considered a minor loss in usefulness only.

Fixes bazelbuild#29656
Fixes bazelbuild#29515

RELNOTES: The remote repo contents cache now correctly materializes
chains of symlinks as action inputs, but no longer supports symlinks
into the main repository.

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08 
(cherry picked from commit c310e3e)

Fixes bazelbuild#29816
fmeum added a commit to fmeum/bazel that referenced this pull request Jun 26, 2026
When a remotely cached repo is partially materialized since it contains action
inputs, Skyframe provides the metadata of these inputs after following all
symlinks as it does for all source files. Since (chains of) symlinks need to be
preserved and materialized in the same way as if the repo rule ran locally or
was fully materialized as a dependency of another repo rule,
`AbstractActionInputPrefetcher` is changed to walk the full chain of symlinks
behind a prefetched external repo path and replant every link verbatim on the
host file system.

This proves very difficult to get right for repos with symlinks pointing into
the main repo as such symlinks would cross over into the host filesystem. For
this reason such symlinks now exclude a repo from being cached remotely. Note
that the local repo contents cache already doesn't cache such repos. Since main
repo files are readily available, this is considered a minor loss in usefulness
only.

8.x adaptation: the 8.x prefetcher uses an exec-path-based symlink model
(`resolveExecPath`, `execRoot()`, `FileArtifactValue#getMaterializationExecPath`)
rather than the master model (`getResolvedPath`, `execRoot` field). The
chain-walking is therefore re-expressed on that model: the `Symlink` record
becomes `(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; `execRoot` field
accesses become `execRoot()` calls; the loop guard throws
`FileSymlinkLoopException(PathFragment)` (the 8.x constructor); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to `RepositoryFunction.replantSymlinks`
and the `RepositoryDelegatorFunction` caching path (where remote caching is now
gated on `safeForRemoteCache()` and local caching on `safeForLocalCache()`).
`VendorManager` keeps its existing private `replantSymlinks`, so the upstream
call-signature change there does not apply.

Depends on the replant prerequisite (bazelbuild#28582) backported in the preceding slot.

Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jun 26, 2026
When a remotely cached repo is partially materialized since it contains action
inputs, Skyframe provides the metadata of these inputs after following all
symlinks as it does for all source files. Since (chains of) symlinks need to be
preserved and materialized in the same way as if the repo rule ran locally or
was fully materialized as a dependency of another repo rule,
`AbstractActionInputPrefetcher` is changed to walk the full chain of symlinks
behind a prefetched external repo path and replant every link verbatim on the
host file system.

This proves very difficult to get right for repos with symlinks pointing into
the main repo as such symlinks would cross over into the host filesystem. For
this reason such symlinks now exclude a repo from being cached remotely. Note
that the local repo contents cache already doesn't cache such repos. Since main
repo files are readily available, this is considered a minor loss in usefulness
only.

8.x adaptation: the 8.x prefetcher uses an exec-path-based symlink model
(`resolveExecPath`, `execRoot()`, `FileArtifactValue#getMaterializationExecPath`)
rather than the master model (`getResolvedPath`, `execRoot` field). The
chain-walking is therefore re-expressed on that model: the `Symlink` record
becomes `(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; the loop guard throws
`FileSymlinkLoopException(PathFragment)` (the 8.x constructor); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved. Because the
exec root isn't available during external repository materialization, both
`getSymlinks` and `plantSymlink` detect external repo paths via the
`isUnderExternalRepoRoot` helper (introduced in the bazelbuild#28683 backport) instead of
`execRoot()`, which would otherwise NPE during materialization.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to `RepositoryFunction.replantSymlinks`
and the `RepositoryDelegatorFunction` caching path (where remote caching is now
gated on `safeForRemoteCache()` and local caching on `safeForLocalCache()`).
`VendorManager` keeps its existing private `replantSymlinks`, so the upstream
call-signature change there does not apply.

This commit also carries the three symlink-materialization tests added upstream
in bazelbuild#28683: on 8.x they only pass once this chain-walk change is in place, since
repo files are materialized lazily through `RemoteExternalOverlayFileSystem`
rather than fully on disk as on master.

Depends on the replant prerequisite (bazelbuild#28582) backported in the preceding slot.

Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 1, 2026
When using the remote repo contents cache, repo materialization now uses the
same code path as local action input prefetching for symlinks. This ensures
that each symlink is only materialized once and that there are no races in case
symlinking is not atomic (on Windows with default settings).

Along the way, remove unreachable code from `UploadManifest`.

8.x adaptation: `AbstractActionInputPrefetcher` on 8.x resolves input paths via
the Bazel 8.x-specific `resolveExecPath(execPath)` helper (which avoids
evaluating the WORKSPACE-named exec root when possible) and exposes the exec
root through the `execRoot()` method rather than an `execRoot` field, so the new
symlink branch is expressed in those terms. Because `execRoot()` is not
available during external repository materialization, the branch detects
external repo paths via a new `isUnderExternalRepoRoot` helper (mirroring
`DirectoryTracker.setWritable`) instead of `!inputPath.startsWith(execRoot())`,
and reads the symlink target from `UnresolvedSymlinkArtifactValue#getSymlinkTarget`
(8.x has no `FileArtifactValue#getUnresolvedSymlinkTarget`). Only the
`FileStateType` import is added; the other imports touched upstream don't apply
because 8.x resolves `VirtualActionInput` to `actions.cache.VirtualActionInput`.

The three symlink-materialization tests added upstream are deferred to the
chains-of-symlinks backport (bazelbuild#29767): on 8.x, repo files are materialized lazily
through `RemoteExternalOverlayFileSystem`, and faithfully reproducing (chains
of) symlinks on disk only works with that later change, not with this commit's
single-link prefetching alone.

Fixes bazelbuild#28575.

Closes bazelbuild#28683.

PiperOrigin-RevId: 893359962
Change-Id: If0eb64e41858a4b9298c2609d83160b0ecbfd451
(cherry picked from commit 90eb56e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 1, 2026
This reuses the logic for replanting symlinks in the vendor directory, which is
improved to also cover the case of symlinks into the main repository. Before a
reproducible, non-local repo is added to the local or remote repo contents
cache, its symlinks are rewritten from absolute paths (pointing into the
workspace or external root) to relative paths, making the cached repo portable
across output bases and machines. A repo with cross-repo symlinks is not safe to
reuse from a shared local cache location and is therefore excluded from the
local repo contents cache.

8.x adaptation: 8.x has no `RepositoryUtils` class and no merged
`RepositoryFetchFunction` worker. The shared `replantSymlinks` helper (and the
`WORKSPACE_SYMLINK_NAME` constant) is therefore added to `RepositoryFunction` in
`rules/repository`, the lowest layer reachable from the caching code in
`RepositoryDelegatorFunction`. It can't live in a `bazel/repository` or `bzlmod`
utility like upstream because `rules/repository` already depends on `bzlmod`
(for `BzlmodRepoRuleValue`/`VendorFileValue`), so a back-dependency would create
a cycle. For the same reason the upstream refactor that routes `VendorManager`
through the shared helper is dropped; `VendorManager` keeps its existing private
`replantSymlinks`. The replant call and the `safeForLocalCacheReuse` gating are
added to the `RepositoryDelegatorFunction` fetch path instead of
`RepositoryFetchFunction`. The `@CanIgnoreReturnValue` annotation is dropped
because the only 8.x caller uses the result, which avoids adding an
`error_prone_annotations` build dependency.

This commit was identified as a missing prerequisite for the symlink-chain
materialization change (bazelbuild#29767) and is not part of the original cherry-pick list
in bazelbuild#29031.

Work towards bazelbuild#28575.

Closes bazelbuild#28582.

PiperOrigin-RevId: 874701377
Change-Id: I661166dc8102421e62f9a4196bd0d305e0ec2bb7
(cherry picked from commit 2ce32e7)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 1, 2026
This reuses the logic for replanting symlinks in the vendor directory, which is
improved to also cover the case of symlinks into the main repository. Before a
reproducible, non-local repo is added to the local or remote repo contents
cache, its symlinks are rewritten from absolute paths (pointing into the
workspace or external root) to relative paths, making the cached repo portable
across output bases and machines. A repo with cross-repo symlinks is not safe to
reuse from a shared local cache location and is therefore excluded from the
local repo contents cache.

8.x adaptation: 8.x has no `RepositoryUtils` class and no merged
`RepositoryFetchFunction` worker. The shared `replantSymlinks` helper (and the
`WORKSPACE_SYMLINK_NAME` constant) is therefore added to `RepositoryFunction` in
`rules/repository`, the lowest layer reachable from the caching code in
`RepositoryDelegatorFunction`. It can't live in a `bazel/repository` or `bzlmod`
utility like upstream because `rules/repository` already depends on `bzlmod`
(for `BzlmodRepoRuleValue`/`VendorFileValue`), so a back-dependency would create
a cycle. For the same reason the upstream refactor that routes `VendorManager`
through the shared helper is dropped; `VendorManager` keeps its existing private
`replantSymlinks`. The replant call and the `safeForLocalCacheReuse` gating are
added to the `RepositoryDelegatorFunction` fetch path instead of
`RepositoryFetchFunction`. The `@CanIgnoreReturnValue` annotation is dropped
because the only 8.x caller uses the result, which avoids adding an
`error_prone_annotations` build dependency.

This commit was identified as a missing prerequisite for the symlink-chain
materialization change (bazelbuild#29767) and is not part of the original cherry-pick list
in bazelbuild#29031.

Work towards bazelbuild#28575.

Closes bazelbuild#28582.

PiperOrigin-RevId: 874701377
Change-Id: I661166dc8102421e62f9a4196bd0d305e0ec2bb7
(cherry picked from commit 2ce32e7)
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

A repository restored from the remote repo contents cache can remain in
Bazel's in-memory file system after another external repository has been
materialized on disk. If the cached repository contains a symlink into the
materialized repository, the overlay selects the in-memory backing from the
symlink path and asks it to follow the whole link. That backing reports ENOENT
because the target exists only in the native file system.

Resolve the link one component at a time through the overlay, then retry the
read, digest, or followed stat at the canonical target. Keep native paths and
NOFOLLOW operations on their existing direct paths.

Replant overlay-only external symlinks before local execution, even when their
resolved metadata describes a local regular file. For remote execution, check
the resolved host target before deciding that an input cannot be uploaded.

### Motivation

Fixes bazelbuild#30149.

This follows bazelbuild#29767, which fixed bazelbuild#29656. The existing cross-repository test
restores both repositories into the in-memory file system. It does not cover a
cached repository whose symlink target has already been materialized in the
native file system.

The new integration test creates that mixed state. It removes the target blob
from the test worker's CAS, then runs a remote action to force an upload and a
local action to force symlink materialization.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: None
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

A repository restored from the remote repo contents cache can remain in
Bazel's in-memory file system after another external repository has been
materialized on disk. If the cached repository contains a symlink into the
materialized repository, the overlay selects the in-memory backing from the
symlink path and asks it to follow the whole link. That backing reports ENOENT
because the target exists only in the native file system.

Resolve the link one component at a time through the overlay, then retry the
read, digest, or followed stat at the canonical target. Keep native paths and
NOFOLLOW operations on their existing direct paths.

Replant overlay-only external symlinks before local execution, even when their
resolved metadata describes a local regular file. For remote execution, check
the resolved host target before deciding that an input cannot be uploaded.

### Motivation

Fixes bazelbuild#30149.

This follows bazelbuild#29767, which fixed bazelbuild#29656. The existing cross-repository test
restores both repositories into the in-memory file system. It does not cover a
cached repository whose symlink target has already been materialized in the
native file system.

The new integration test creates that mixed state. It removes the target blob
from the test worker's CAS, then runs a remote action to force an upload and a
local action to force symlink materialization. A focused unit test also verifies
that `statIfFound` still returns null for a child of a regular file instead of
exposing ENOTDIR.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: None
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

A repository restored from the remote repo contents cache can remain in
Bazel's in-memory file system after another external repository has been
materialized on disk. When the cached repository links to the materialized
repository, neither backing file system can resolve the whole path by itself.
The in-memory file system cannot see the native target, and the native file
system may see only an empty shadow of the cached repository.

RemoteExternalOverlayFileSystem now routes paths in the external repository
directory one component at a time. The router records the canonical path,
owning file system, and final status. It handles links from injected to native
repositories, links from native to injected repositories, and paths that cross
between the two more than once. NOFOLLOW operations resolve parent links but
leave the final component unresolved.

Paths outside the external repository directory still delegate directly to
the native file system. Within that directory, canonicalization caches only
immutable injected-repository nodes and rechecks mutable native nodes. Reads,
metadata queries, writes, and directory enumeration use the same routing
rules. Routed readdir calls retain the selected backing's optimized readdir
and reroute only symlink entries. Tree deletion continues to remove native
shadows and in-memory entries from both backings.

Before a local action runs, Bazel replants an external overlay symlink even
when its resolved metadata describes a local regular file. Replanting now
keeps an existing host symlink when its raw target already matches. The remote
cache also asks RemoteActionFileSystem whether a resolved path is available on
the host, instead of implementing action-file-system routing itself.

### Motivation

Fixes bazelbuild#30149.

This follows bazelbuild#29767, which fixed bazelbuild#29656. The existing cross-repository test
restores both repositories into the in-memory file system. It does not cover a
cached repository whose link target has already been materialized in the
native file system.

The integration tests now cover both a regular-file link and a package glob
through a directory link in that mixed state. Unit tests cover both crossing
directions, repeated crossings, NOFOLLOW parent resolution, overlapping native
shadows, same-command native changes, directory enumeration, routed
mutations, cache invalidation, and ENOTDIR handling. They also verify that
operations outside the external repository directory keep the direct native
fast path.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: None
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

`RemoteExternalOverlayFileSystem` can expose one external repository from the
in-memory `RemoteExternalFileSystem` while another repository has already been
materialized in the native file system. A symlink between those repositories
then crosses backing file systems. This is the state in bazelbuild#30149: the link is in
an injected repository, but its target is in a materialized repository.

Dispatching the complete lexical path to one backing cannot implement this
correctly. The transition can occur in either direction and more than once.
In addition, the two backings intentionally overlap: an injected repository
has a native placeholder and may have selectively prefetched native shadows,
while an external tree can remain during materialization. An operation can
therefore succeed against the wrong backing, so retrying only after ENOENT is
not sufficient. The old per-method delegation also left stats, content reads,
metadata queries, and directory enumeration with inconsistent cross-backing
behavior. For NOFOLLOW operations, the unresolved lexical path was still
confined to one backing, so a cross-backing parent could not be resolved even
though only the final component should remain unresolved.

Move this policy into one overlay-owned routing primitive. It canonicalizes
each prefix through the overlay, reevaluates the owning file system after each
symlink, and returns the selected owner, canonical path, and final no-follow
status.
`FOLLOW_ALL`, `FOLLOW_PARENT`, and `FOLLOW_NONE` make the intended treatment
of the final component explicit. Missing paths retain the canonical existing
prefix and unresolved suffix so creation can use the same router, while
`statIfFound` continues to treat ENOENT and ENOTDIR as missing and propagates
other I/O errors.

Use that routed result consistently for stats, content and digest reads,
metadata and permission queries, directory operations, and mutations. A
routed `readdir` first resolves the directory, uses the selected backing's
optimized NOFOLLOW enumeration, and reroutes only symlink entries when their
types are requested. Tree deletion removes both in-memory entries and native
shadows so selectively prefetched files cannot survive deletion and reappear
after materialization.

Cross-backing routing starts only for lexical paths under the external
repository directory, which is the namespace this overlay owns. Once routing
has started, it remains overlay-aware if a symlink leaves that directory and
later reenters it. Ordinary operations on workspace and output paths retain
direct native delegation without prefix walks. Routing them globally would
add prefix walks to hot build-artifact paths, while caching those mutable
paths would be unsound because they can be changed outside this wrapper.

Extend `PathCanonicalizer` with selective caching for paths inside that
namespace. Injected nodes are cache-stable between tracked mutations and can
be reused, while mutable native prefixes are resolved on every access. Repo
injection, eviction, materialization, and topology-changing routed mutations
clear affected prefixes, and command boundaries reset the trie. The existing
cache-all mode used by `RemoteActionFileSystem` retains a dedicated cached-hit
path and does not pay the selective-caching checks.
Fresh injection also discards any stale materialization state before changing
repository ownership.

Two action-layer fixes complete the mixed-backing flow. Remote upload now asks
`RemoteActionFileSystem` whether the resolved path is available on its host
file system instead of checking an unresolved overlay-only path. Local input
prefetching recognizes that an overlay-only symlink can have followed metadata
for a local regular-file target, and plants that logical link on the host. If
the same raw symlink already exists, planting leaves it in place.

### Motivation

Fixes bazelbuild#30149.

This is not a known regression. The test added for bazelbuild#29767 restored both
repositories into the in-memory backing, so it did not exercise a cached
repository linking to a repository that had already been materialized.

The integration tests now create that mixed state after an expunge. One test
removes the target blob from the CAS to force remote input upload through a
regular-file link, then runs a local action to verify host symlink planting.
Another loads a package whose `glob` traverses a directory link into the
materialized repository. Focused unit tests cover both transition directions,
repeated transitions, native shadows, NOFOLLOW parent resolution, directory
entry typing, creation and rename through routed parents, same-command native
symlink replacement, reinjection after materialization, ENOENT/ENOTDIR
handling, and the direct native fast path outside the external repository
directory.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: Fixed failures with `--experimental_remote_repo_contents_cache` when
a cached repository contains a symlink to a repository that has already been
materialized on disk.
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

`RemoteExternalOverlayFileSystem` can expose one external repository from the
in-memory `RemoteExternalFileSystem` while another repository has already been
materialized in the native file system. A symlink between those repositories
then crosses backing file systems. This is the state in bazelbuild#30149: the link is in
an injected repository, but its target is in a materialized repository.

Dispatching the complete lexical path to one backing cannot implement this
correctly. The transition can occur in either direction and more than once.
In addition, the two backings intentionally overlap: an injected repository
has a native placeholder and may have selectively prefetched native shadows,
while an external tree can remain during materialization. An operation can
therefore succeed against the wrong backing, so retrying only after ENOENT is
not sufficient. The old per-method delegation also left stats, content reads,
metadata queries, and directory enumeration with inconsistent cross-backing
behavior. For NOFOLLOW operations, the unresolved lexical path was still
confined to one backing, so a cross-backing parent could not be resolved even
though only the final component should remain unresolved.

Move this policy into one overlay-owned routing primitive. It canonicalizes
each prefix through the overlay, reevaluates the owning file system after each
symlink, and returns the selected owner and canonical path. The final
no-follow status is loaded and memoized only when a caller needs it. Size and
mtime queries consume that status directly, while content and directory
operations do not pay for a second, unused final status lookup. `FOLLOW_ALL`,
`FOLLOW_PARENT`, and `FOLLOW_NONE` make the intended treatment of the final
component explicit. Missing paths retain the canonical existing prefix and
unresolved suffix so creation can use the same router, while `statIfFound`
continues to treat ENOENT and ENOTDIR as missing and propagates other I/O
errors.

Use that routed result consistently for stats, content and digest reads,
metadata and permission queries, directory operations, and mutations. A
routed `readdir` first resolves the directory, uses the selected backing's
optimized NOFOLLOW enumeration, and reroutes only symlink entries when their
types are requested. Capability queries use the same routed owner and follow
mode as the operations they describe. Tree deletion removes both in-memory
entries and native shadows so selectively prefetched files cannot survive
deletion and reappear after materialization.

Cross-backing routing starts only for lexical paths under the external
repository directory, which is the namespace this overlay owns. Once routing
has started, it remains overlay-aware if a symlink leaves that directory and
later reenters it. Ordinary operations on workspace and output paths retain
direct native delegation without prefix walks. Routing them globally would
add prefix walks to hot build-artifact paths, while caching those mutable
paths would be unsound because they can be changed outside this wrapper.

Extend `PathCanonicalizer` with selective caching for paths inside that
namespace. Injected nodes are cache-stable between tracked mutations and can
be reused without rebuilding prefixes or rechecking ownership at each cached
component, while mutable native prefixes are resolved on every access. The
cache-all and selective lookup loops remain separate so
`RemoteActionFileSystem` keeps its lean non-symlink hit path; only the rare
symlink-follow branch is shared. Repository injection, eviction,
materialization, and topology-changing routed mutations
clear affected prefixes, and command boundaries reset the trie. Fresh
injection also discards stale materialization state before changing repository
ownership.

Two action-layer fixes complete the mixed-backing flow. Remote upload now asks
`RemoteActionFileSystem` whether the resolved path is available on its host
file system instead of checking an unresolved overlay-only path. Local input
prefetching recognizes that a logical external symlink can have followed
metadata for a local regular-file target even when a stale native entry exists
at the host path. External symlink planting therefore reenters the planting
task on later prefetches: a matching raw target is left in place, while a
regular file or wrong link is replaced. Concurrent planting remains deduped.

### Motivation

Fixes bazelbuild#30149.

This is not a known regression. The test added for bazelbuild#29767 restored both
repositories into the in-memory backing, so it did not exercise a cached
repository linking to a repository that had already been materialized.

The integration tests now create that mixed state after an expunge. One test
removes the target blob from the CAS to force remote input upload through a
regular-file link, then runs a local action to verify host symlink planting.
Another loads a package whose `glob` traverses a directory link into the
materialized repository. Focused unit tests cover both transition directions,
repeated transitions, native shadows, NOFOLLOW parent resolution, directory
entry typing, creation and rename through routed parents, same-command native
symlink replacement, reinjection after materialization, ENOENT/ENOTDIR
handling, stale host-link repair, selective-cache predicate and resolver
counts, lazy status-lookup counts, capability routing, and the direct native
fast path outside the external repository directory.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: Fixed failures with `--experimental_remote_repo_contents_cache` when
a cached repository contains a symlink to a repository that has already been
materialized on disk.
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

`RemoteExternalOverlayFileSystem` can expose one external repository from the
in-memory `RemoteExternalFileSystem` while another repository has already been
materialized in the native file system. A symlink between those repositories
then crosses backing file systems. This is the state in bazelbuild#30149: the link is in
an injected repository, but its target is in a materialized repository.

Dispatching the complete lexical path to one backing cannot implement this
correctly. The transition can occur in either direction and more than once.
In addition, the two backings intentionally overlap: an injected repository
has a native placeholder and may have selectively prefetched native shadows,
while an external tree can remain during materialization. An operation can
therefore succeed against the wrong backing, so retrying only after ENOENT is
not sufficient. The old per-method delegation also left stats, content reads,
metadata queries, and directory enumeration with inconsistent cross-backing
behavior. For NOFOLLOW operations, the unresolved lexical path was still
confined to one backing, so a cross-backing parent could not be resolved even
though only the final component should remain unresolved.

Move this policy into one overlay-owned routing primitive. It canonicalizes
each prefix through the overlay, reevaluates the owning file system after each
symlink, and returns the selected owner and canonical path. The final
no-follow status is loaded and memoized only when a caller needs it. Size and
mtime queries consume that status directly, while content and directory
operations do not pay for a second, unused final status lookup. `FOLLOW_ALL`,
`FOLLOW_PARENT`, and `FOLLOW_NONE` make the intended treatment of the final
component explicit. Missing paths retain the canonical existing prefix and
unresolved suffix so creation can use the same router, while `statIfFound`
continues to treat ENOENT and ENOTDIR as missing and propagates other I/O
errors.

Use that routed result consistently for stats, content and digest reads,
metadata and permission queries, directory operations, and mutations. A
routed `readdir` first resolves the directory, uses the selected backing's
optimized NOFOLLOW enumeration, and reroutes only symlink entries when their
types are requested. Capability queries use the same routed owner and follow
mode as the operations they describe. Tree deletion removes both in-memory
entries and native shadows so selectively prefetched files cannot survive
deletion and reappear after materialization.

Cross-backing routing starts only for lexical paths under the external
repository directory, which is the namespace this overlay owns. Once routing
has started, it remains overlay-aware if a symlink leaves that directory and
later reenters it. Ordinary operations on workspace and output paths retain
direct native delegation without prefix walks. Routing them globally would
add prefix walks to hot build-artifact paths, while caching those mutable
paths would be unsound because they can be changed outside this wrapper.

Extend `PathCanonicalizer` with selective caching for paths inside that
namespace. Injected nodes are cache-stable between tracked mutations and can
be reused without rebuilding prefixes or rechecking ownership at each cached
component, while mutable native prefixes are resolved on every access. The
cache-all and selective lookup loops remain separate so
`RemoteActionFileSystem` keeps its lean non-symlink hit path; only the rare
symlink-follow branch is shared. Repository injection, eviction,
materialization, and topology-changing routed mutations
clear affected prefixes, and command boundaries reset the trie. Fresh
injection also discards stale materialization state before changing repository
ownership.

Two action-layer fixes complete the mixed-backing flow. Remote upload now asks
`RemoteActionFileSystem` whether the resolved path is available on its host
file system instead of checking an unresolved overlay-only path. Local input
prefetching recognizes that a logical external symlink can have followed
metadata for a local regular-file target even when a stale native entry exists
at the host path. External symlink planting therefore reenters the planting
task on later prefetches: a matching raw target is left in place, while any
mismatched external host node, including a non-empty directory, is removed
before the logical link is restored. Ordinary output-link replacement remains
nonrecursive, and concurrent planting remains deduped.

### Motivation

Fixes bazelbuild#30149.

This is not a known regression. The test added for bazelbuild#29767 restored both
repositories into the in-memory backing, so it did not exercise a cached
repository linking to a repository that had already been materialized.

The integration tests now create that mixed state after an expunge. One test
removes the target blob from the CAS to force remote input upload through a
regular-file link, then runs a local action to verify host symlink planting.
Another loads a package whose `glob` traverses a directory link into the
materialized repository. Focused unit tests cover both transition directions,
repeated transitions, native shadows, NOFOLLOW parent resolution, directory
entry typing, creation and rename through routed parents, same-command native
symlink replacement, reinjection after materialization, ENOENT/ENOTDIR
handling, stale host-link repair, selective-cache predicate and resolver
counts, lazy status-lookup counts, capability routing, and the direct native
fast path outside the external repository directory.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: Fixed failures with `--experimental_remote_repo_contents_cache` when
a cached repository contains a symlink to a repository that has already been
materialized on disk.
michaelm-openai added a commit to michaelm-openai/bazel that referenced this pull request Jul 7, 2026
### Description

`RemoteExternalOverlayFileSystem` can expose one external repository from the
in-memory `RemoteExternalFileSystem` while another repository has already been
materialized in the native file system. A symlink between those repositories
then crosses backing file systems. This is the state in bazelbuild#30149: the link is in
an injected repository, but its target is in a materialized repository.

Dispatching the complete lexical path to one backing cannot implement this
correctly. The transition can occur in either direction and more than once.
In addition, the two backings intentionally overlap: an injected repository
has a native placeholder and may have selectively prefetched native shadows,
while an external tree can remain during materialization. An operation can
therefore succeed against the wrong backing, so retrying only after ENOENT is
not sufficient. The old per-method delegation also left stats, content reads,
metadata queries, and directory enumeration with inconsistent cross-backing
behavior. For NOFOLLOW operations, the unresolved lexical path was still
confined to one backing, so a cross-backing parent could not be resolved even
though only the final component should remain unresolved.

Move this policy into one overlay-owned routing primitive. It canonicalizes
each prefix through the overlay, reevaluates the owning file system after each
symlink, and returns the selected owner and canonical path. The final
no-follow status is loaded and memoized only when a caller needs it. Size and
mtime queries consume that status directly, while content and directory
operations do not pay for a second, unused final status lookup. `FOLLOW_ALL`,
`FOLLOW_PARENT`, and `FOLLOW_NONE` make the intended treatment of the final
component explicit. Missing paths retain the canonical existing prefix and
unresolved suffix so creation can use the same router, while `statIfFound`
continues to treat ENOENT and ENOTDIR as missing and propagates other I/O
errors.

Use that routed result consistently for stats, content and digest reads,
metadata and permission queries, directory operations, and mutations. A
routed `readdir` first resolves the directory, uses the selected backing's
optimized NOFOLLOW enumeration, and reroutes only symlink entries when their
types are requested. Capability queries use the same routed owner and follow
mode as the operations they describe. Tree deletion removes both in-memory
entries and native shadows so selectively prefetched files cannot survive
deletion and reappear after materialization.

Cross-backing routing starts only for lexical paths under the external
repository directory, which is the namespace this overlay owns. Once routing
has started, it remains overlay-aware if a symlink leaves that directory and
later reenters it. Ordinary operations on workspace and output paths retain
direct native delegation without prefix walks. Routing them globally would
add prefix walks to hot build-artifact paths, while caching those mutable
paths would be unsound because they can be changed outside this wrapper.

Extend `PathCanonicalizer` with selective caching for paths inside that
namespace. Injected nodes are cache-stable between tracked mutations and can
be reused without rebuilding prefixes or rechecking ownership at each cached
component, while mutable native prefixes are resolved on every access. The
selective resolver chooses a backing once and returns both the raw link target
and whether that result is cacheable, so an ownership change cannot classify a
result from the native backing using an earlier external-backing decision. The
cache-all and selective lookup loops remain separate so
`RemoteActionFileSystem` keeps its lean non-symlink hit path; only the rare
symlink-follow branch is shared. Repository injection, eviction,
materialization, and topology-changing routed mutations clear affected
prefixes, and command boundaries reset the trie. Fresh injection also discards
stale materialization state before changing repository ownership.

Two action-layer fixes complete the mixed-backing flow. Remote upload now asks
`RemoteActionFileSystem` whether the resolved path is available on its host
file system instead of checking an unresolved overlay-only path. Local input
prefetching recognizes that a logical external symlink can have followed
metadata for a local regular-file target even when a stale native entry exists
at the host path. External symlink planting therefore reenters the planting
task on later prefetches: a matching raw target is left in place, while any
mismatched external host node must be repaired before the logical link is
restored. For RRCC paths, planting walks downward from the overlay's declared
external root, verifies each logical and host ancestor without following
symlinks, and unlinks only the mismatched component. Repairs sharing a
repository are serialized. Only after that walk may a non-empty final node be
removed recursively. Other external sources keep parent creation with
nonrecursive replacement, output links remain nonrecursive, and concurrent
planting of the same link remains deduped.

### Motivation

Fixes bazelbuild#30149.

This is not a known regression. The test added for bazelbuild#29767 restored both
repositories into the in-memory backing, so it did not exercise a cached
repository linking to a repository that had already been materialized.

The integration tests now create that mixed state after an expunge. One test
removes the target blob from the CAS to force remote input upload through a
regular-file link, then runs a local action to verify host symlink planting.
Another loads a package whose `glob` traverses a directory link into the
materialized repository. Focused unit tests cover both transition directions,
repeated transitions, native shadows, NOFOLLOW parent resolution, directory
entry typing, creation and rename through routed parents, same-command native
symlink replacement, reinjection after materialization, ENOENT/ENOTDIR
handling, stale host-link repair, selective-cache predicate and resolver
counts, selected-owner cache coherence, stale-ancestor containment, ordinary
output preservation, lazy status-lookup counts, capability routing, and the
direct native fast path outside the external repository directory.

### Build API Changes

No

### Checklist

- [x] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (not applicable).

### Release Notes

RELNOTES: Fixed failures with `--experimental_remote_repo_contents_cache` when
a cached repository contains a symlink to a repository that has already been
materialized on disk.
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 8, 2026
This reuses the logic for replanting symlinks in the vendor directory, which is
improved to also cover the case of symlinks into the main repository. Before a
reproducible, non-local repo is added to the local or remote repo contents
cache, its symlinks are rewritten from absolute paths (pointing into the
workspace or external root) to relative paths, making the cached repo portable
across output bases and machines. A repo with cross-repo symlinks is not safe to
reuse from a shared local cache location and is therefore excluded from the
local repo contents cache.

8.x adaptation: 8.x has no `RepositoryUtils` class and no merged
`RepositoryFetchFunction` worker. The shared `replantSymlinks` helper (and the
`WORKSPACE_SYMLINK_NAME` constant) is therefore added to `RepositoryFunction` in
`rules/repository`, the lowest layer reachable from the caching code in
`RepositoryDelegatorFunction`. It can't live in a `bazel/repository` or `bzlmod`
utility like upstream because `rules/repository` already depends on `bzlmod`
(for `BzlmodRepoRuleValue`/`VendorFileValue`), so a back-dependency would create
a cycle. For the same reason the upstream refactor that routes `VendorManager`
through the shared helper is dropped; `VendorManager` keeps its existing private
`replantSymlinks`. The replant call and the `safeForLocalCacheReuse` gating are
added to the `RepositoryDelegatorFunction` fetch path instead of
`RepositoryFetchFunction`. The `@CanIgnoreReturnValue` annotation is dropped
because the only 8.x caller uses the result, which avoids adding an
`error_prone_annotations` build dependency.

This commit was identified as a missing prerequisite for the symlink-chain
materialization change (bazelbuild#29767) and is not part of the original cherry-pick list
in bazelbuild#29031.

Work towards bazelbuild#28575.

Closes bazelbuild#28582.

PiperOrigin-RevId: 874701377
Change-Id: I661166dc8102421e62f9a4196bd0d305e0ec2bb7
(cherry picked from commit 2ce32e7)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 9, 2026
When using the remote repo contents cache, repo materialization now uses
the same code path as local action input prefetching for symlinks. This
ensures that each symlink is only materialized once and that there are no
races in case symlinking is not atomic (on Windows with default settings).
Along the way, remove unreachable code from `UploadManifest`.

Furthermore, when a remotely cached repo is partially materialized since it
contains action inputs, Skyframe provides the metadata of these inputs
after following all symlinks as it does for all source files. Since (chains
of) symlinks need to be preserved and materialized in the same way as if
the repo rule ran locally or was fully materialized as a dependency of
another repo rule, `AbstractActionInputPrefetcher` is changed to walk the
full chain of symlinks behind a prefetched external repo path and replant
every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing
into the main repo as such symlinks would cross over into the host
filesystem. For this reason such symlinks now exclude a repo from being
cached remotely. Note that the local repo contents cache already doesn't
cache such repos. Since main repo files are readily available, this is
considered a minor loss in usefulness only.

This commit combines the backports of bazelbuild#28683 and bazelbuild#29767 into one: the
symlink-materialization tests added upstream in bazelbuild#28683 only pass on 8.x
once the chain-walk change from bazelbuild#29767 is in place, since repo files are
materialized lazily through `RemoteExternalOverlayFileSystem` rather than
fully on disk as on master.

8.x adaptation: `AbstractActionInputPrefetcher` on 8.x resolves input paths
via the Bazel 8.x-specific `resolveExecPath(execPath)` helper (which avoids
evaluating the WORKSPACE-named exec root when possible) and exposes the
exec root through the `execRoot()` method rather than an `execRoot` field,
so the new symlink handling is expressed in those terms. Because
`execRoot()` is not available during external repository materialization,
external repo paths are detected via a new `isUnderExternalRepoRoot`
helper (mirroring `DirectoryTracker.setWritable`) instead of
`!inputPath.startsWith(execRoot())`; both `getSymlinks` and `plantSymlink`
use it. The chain-walking is re-expressed on the exec-path-based symlink
model (`resolveExecPath`, `execRoot()`,
`FileArtifactValue#getMaterializationExecPath`) rather than the master
model (`getResolvedPath`, `execRoot` field): the `Symlink` record becomes
`(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; the loop guard
throws `FileSymlinkLoopException(PathFragment)` (the 8.x constructor); the
symlink target of an unresolved symlink artifact is read from
`UnresolvedSymlinkArtifactValue#getSymlinkTarget` (8.x has no
`FileArtifactValue#getUnresolvedSymlinkTarget`); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to
`RepositoryFunction.replantSymlinks` and the `RepositoryDelegatorFunction`
caching path (where remote caching is now gated on `safeForRemoteCache()`
and local caching on `safeForLocalCache()`). `VendorManager` keeps its
existing private `replantSymlinks`, so the upstream call-signature change
there does not apply.

Depends on the replant prerequisite (bazelbuild#28582) backported in the preceding
slot.

Fixes bazelbuild#28575.
Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#28683.

PiperOrigin-RevId: 893359962
Change-Id: If0eb64e41858a4b9298c2609d83160b0ecbfd451
(cherry picked from commit 90eb56e)

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 12, 2026
This reuses the logic for replanting symlinks in the vendor directory, which is
improved to also cover the case of symlinks into the main repository. Before a
reproducible, non-local repo is added to the local or remote repo contents
cache, its symlinks are rewritten from absolute paths (pointing into the
workspace or external root) to relative paths, making the cached repo portable
across output bases and machines. A repo with cross-repo symlinks is not safe to
reuse from a shared local cache location and is therefore excluded from the
local repo contents cache.

8.x adaptation: 8.x has no `RepositoryUtils` class and no merged
`RepositoryFetchFunction` worker. The shared `replantSymlinks` helper (and the
`WORKSPACE_SYMLINK_NAME` constant) is therefore added to `RepositoryFunction` in
`rules/repository`, the lowest layer reachable from the caching code in
`RepositoryDelegatorFunction`. It can't live in a `bazel/repository` or `bzlmod`
utility like upstream because `rules/repository` already depends on `bzlmod`
(for `BzlmodRepoRuleValue`/`VendorFileValue`), so a back-dependency would create
a cycle. For the same reason the upstream refactor that routes `VendorManager`
through the shared helper is dropped; `VendorManager` keeps its existing private
`replantSymlinks`. The replant call and the `safeForLocalCacheReuse` gating are
added to the `RepositoryDelegatorFunction` fetch path instead of
`RepositoryFetchFunction`. The `@CanIgnoreReturnValue` annotation is dropped
because the only 8.x caller uses the result, which avoids adding an
`error_prone_annotations` build dependency.

On Windows, `replantSymlinks` obtains NIO paths from the file system to create
symlinks with relative targets and expects `FileSystem#getNioPath` to return
null for file systems not backed by the local file system. This requires two
more pieces present on master but missing on 8.x: `FileSystem#getIoFile` and
`FileSystem#getNioPath` return null instead of throwing
`UnsupportedOperationException` (from commit
ec90e05) and
`RemoteExternalOverlayFileSystem` gains the delegating overrides for these two
methods that master's version has had since commit
b8589c3b2792bd83a3d29ed653a86d1729906ffb. Without them, replanting a freshly
fetched repo crashes on Windows when the remote repo contents cache is enabled.

This commit was identified as a missing prerequisite for the symlink-chain
materialization change (bazelbuild#29767) and is not part of the original cherry-pick list
in bazelbuild#29031.

Work towards bazelbuild#28575.

Closes bazelbuild#28582.

PiperOrigin-RevId: 874701377
Change-Id: I661166dc8102421e62f9a4196bd0d305e0ec2bb7
(cherry picked from commit 2ce32e7)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 12, 2026
When using the remote repo contents cache, repo materialization now uses
the same code path as local action input prefetching for symlinks. This
ensures that each symlink is only materialized once and that there are no
races in case symlinking is not atomic (on Windows with default settings).
Along the way, remove unreachable code from `UploadManifest`.

Furthermore, when a remotely cached repo is partially materialized since it
contains action inputs, Skyframe provides the metadata of these inputs
after following all symlinks as it does for all source files. Since (chains
of) symlinks need to be preserved and materialized in the same way as if
the repo rule ran locally or was fully materialized as a dependency of
another repo rule, `AbstractActionInputPrefetcher` is changed to walk the
full chain of symlinks behind a prefetched external repo path and replant
every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing
into the main repo as such symlinks would cross over into the host
filesystem. For this reason such symlinks now exclude a repo from being
cached remotely. Note that the local repo contents cache already doesn't
cache such repos. Since main repo files are readily available, this is
considered a minor loss in usefulness only.

This commit combines the backports of bazelbuild#28683 and bazelbuild#29767 into one: the
symlink-materialization tests added upstream in bazelbuild#28683 only pass on 8.x
once the chain-walk change from bazelbuild#29767 is in place, since repo files are
materialized lazily through `RemoteExternalOverlayFileSystem` rather than
fully on disk as on master.

8.x adaptation: `AbstractActionInputPrefetcher` on 8.x resolves input paths
via the Bazel 8.x-specific `resolveExecPath(execPath)` helper (which avoids
evaluating the WORKSPACE-named exec root when possible) and exposes the
exec root through the `execRoot()` method rather than an `execRoot` field,
so the new symlink handling is expressed in those terms. Because
`execRoot()` is not available during external repository materialization,
external repo paths are detected via a new `isUnderExternalRepoRoot`
helper (mirroring `DirectoryTracker.setWritable`) instead of
`!inputPath.startsWith(execRoot())`; both `getSymlinks` and `plantSymlink`
use it. The chain-walking is re-expressed on the exec-path-based symlink
model (`resolveExecPath`, `execRoot()`,
`FileArtifactValue#getMaterializationExecPath`) rather than the master
model (`getResolvedPath`, `execRoot` field): the `Symlink` record becomes
`(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; the loop guard
throws `FileSymlinkLoopException(PathFragment)` (the 8.x constructor); the
symlink target of an unresolved symlink artifact is read from
`UnresolvedSymlinkArtifactValue#getSymlinkTarget` (8.x has no
`FileArtifactValue#getUnresolvedSymlinkTarget`); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to
`RepositoryFunction.replantSymlinks` and the `RepositoryDelegatorFunction`
caching path (where remote caching is now gated on `safeForRemoteCache()`
and local caching on `safeForLocalCache()`). `VendorManager` keeps its
existing private `replantSymlinks`, so the upstream call-signature change
there does not apply.

Depends on the replant prerequisite (bazelbuild#28582) backported in the preceding
slot.

Fixes bazelbuild#28575.
Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#28683.

PiperOrigin-RevId: 893359962
Change-Id: If0eb64e41858a4b9298c2609d83160b0ecbfd451
(cherry picked from commit 90eb56e)

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 13, 2026
When using the remote repo contents cache, repo materialization now uses
the same code path as local action input prefetching for symlinks. This
ensures that each symlink is only materialized once and that there are no
races in case symlinking is not atomic (on Windows with default settings).
Along the way, remove unreachable code from `UploadManifest`.

Furthermore, when a remotely cached repo is partially materialized since it
contains action inputs, Skyframe provides the metadata of these inputs
after following all symlinks as it does for all source files. Since (chains
of) symlinks need to be preserved and materialized in the same way as if
the repo rule ran locally or was fully materialized as a dependency of
another repo rule, `AbstractActionInputPrefetcher` is changed to walk the
full chain of symlinks behind a prefetched external repo path and replant
every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing
into the main repo as such symlinks would cross over into the host
filesystem. For this reason such symlinks now exclude a repo from being
cached remotely. Note that the local repo contents cache already doesn't
cache such repos. Since main repo files are readily available, this is
considered a minor loss in usefulness only.

This commit combines the backports of bazelbuild#28683 and bazelbuild#29767 into one: the
symlink-materialization tests added upstream in bazelbuild#28683 only pass on 8.x
once the chain-walk change from bazelbuild#29767 is in place, since repo files are
materialized lazily through `RemoteExternalOverlayFileSystem` rather than
fully on disk as on master.

8.x adaptation: `AbstractActionInputPrefetcher` on 8.x resolves input paths
via the Bazel 8.x-specific `resolveExecPath(execPath)` helper (which avoids
evaluating the WORKSPACE-named exec root when possible) and exposes the
exec root through the `execRoot()` method rather than an `execRoot` field,
so the new symlink handling is expressed in those terms. Because
`execRoot()` is not available during external repository materialization,
external repo paths are detected via a new `isUnderExternalRepoRoot`
helper (mirroring `DirectoryTracker.setWritable`) instead of
`!inputPath.startsWith(execRoot())`; both `getSymlinks` and `plantSymlink`
use it. The chain-walking is re-expressed on the exec-path-based symlink
model (`resolveExecPath`, `execRoot()`,
`FileArtifactValue#getMaterializationExecPath`) rather than the master
model (`getResolvedPath`, `execRoot` field): the `Symlink` record becomes
`(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; the loop guard
throws `FileSymlinkLoopException(PathFragment)` (the 8.x constructor); the
symlink target of an unresolved symlink artifact is read from
`UnresolvedSymlinkArtifactValue#getSymlinkTarget` (8.x has no
`FileArtifactValue#getUnresolvedSymlinkTarget`); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to
`RepositoryFunction.replantSymlinks` and the `RepositoryDelegatorFunction`
caching path (where remote caching is now gated on `safeForRemoteCache()`
and local caching on `safeForLocalCache()`). `VendorManager` keeps its
existing private `replantSymlinks`, so the upstream call-signature change
there does not apply.

Depends on the replant prerequisite (bazelbuild#28582) backported in the preceding
slot.

Fixes bazelbuild#28575.
Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#28683.

PiperOrigin-RevId: 893359962
Change-Id: If0eb64e41858a4b9298c2609d83160b0ecbfd451
(cherry picked from commit 90eb56e)

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
fmeum added a commit to fmeum/bazel that referenced this pull request Jul 14, 2026
…ing (bazelbuild#30035)

When using the remote repo contents cache, repo materialization now uses
the same code path as local action input prefetching for symlinks. This
ensures that each symlink is only materialized once and that there are
no races in case symlinking is not atomic (on Windows with default
settings). Along the way, remove unreachable code from `UploadManifest`.

Furthermore, when a remotely cached repo is partially materialized since
it contains action inputs, Skyframe provides the metadata of these
inputs after following all symlinks as it does for all source files.
Since (chains of) symlinks need to be preserved and materialized in the
same way as if the repo rule ran locally or was fully materialized as a
dependency of another repo rule, `AbstractActionInputPrefetcher` is
changed to walk the full chain of symlinks behind a prefetched external
repo path and replant every link verbatim on the host file system.

This proves very difficult to get right for repos with symlinks pointing
into the main repo as such symlinks would cross over into the host
filesystem. For this reason such symlinks now exclude a repo from being
cached remotely. Note that the local repo contents cache already doesn't
cache such repos. Since main repo files are readily available, this is
considered a minor loss in usefulness only.

This PR combines the backports of bazelbuild#28683 and bazelbuild#29767 into a single
commit, subsuming bazelbuild#30028: the symlink-materialization tests added
upstream in bazelbuild#28683 only pass on 8.x once the chain-walk change from
bazelbuild#29767 is in place, since repo files are materialized lazily through
`RemoteExternalOverlayFileSystem` rather than fully on disk as on
master.

8.x adaptation: `AbstractActionInputPrefetcher` on 8.x resolves input
paths via the Bazel 8.x-specific `resolveExecPath(execPath)` helper
(which avoids evaluating the WORKSPACE-named exec root when possible)
and exposes the exec root through the `execRoot()` method rather than an
`execRoot` field, so the new symlink handling is expressed in those
terms. Because `execRoot()` is not available during external repository
materialization, external repo paths are detected via a new
`isUnderExternalRepoRoot` helper (mirroring
`DirectoryTracker.setWritable`) instead of
`!inputPath.startsWith(execRoot())`; both `getSymlinks` and
`plantSymlink` use it. The chain-walking is re-expressed on the
exec-path-based symlink model (`resolveExecPath`, `execRoot()`,
`FileArtifactValue#getMaterializationExecPath`) rather than the master
model (`getResolvedPath`, `execRoot` field): the `Symlink` record
becomes `(Path linkPath, PathFragment targetPath)` as upstream, but the
materialization case resolves `getMaterializationExecPath()` through
`resolveExecPath` instead of reading `getResolvedPath()`; the loop guard
throws `FileSymlinkLoopException(PathFragment)` (the 8.x constructor);
the symlink target of an unresolved symlink artifact is read from
`UnresolvedSymlinkArtifactValue#getSymlinkTarget` (8.x has no
`FileArtifactValue#getUnresolvedSymlinkTarget`); and the 8.x
`CacheNotFoundException` rewinding `onErrorResumeNext` is preserved.

On the repo side, 8.x has no `RepositoryUtils` or merged
`RepositoryFetchFunction`, so the `ReplantSymlinksResult` record and the
main-repo-symlink exclusion are applied to
`RepositoryFunction.replantSymlinks` and the
`RepositoryDelegatorFunction` caching path (where remote caching is now
gated on `safeForRemoteCache()` and local caching on
`safeForLocalCache()`). `VendorManager` keeps its existing private
`replantSymlinks`, so the upstream call-signature change there does not
apply.

Depends on the replant prerequisite (bazelbuild#28582) backported in bazelbuild#30034.

Fixes bazelbuild#28575.
Fixes bazelbuild#29656.
Fixes bazelbuild#29515.

Closes bazelbuild#28683.

PiperOrigin-RevId: 893359962
Change-Id: If0eb64e41858a4b9298c2609d83160b0ecbfd451
(cherry picked from commit 90eb56e)

Closes bazelbuild#29767.

PiperOrigin-RevId: 936532134
Change-Id: I48b63f6fd2d5f57e139175e3ed578d65f6abbd08
(cherry picked from commit c310e3e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-Bzlmod Bzlmod-specific PRs, issues, and feature requests team-ExternalDeps External dependency handling, remote repositiories, WORKSPACE file. team-Remote-Exec Issues and PRs for the Execution (Remote) team

Projects

None yet

2 participants