Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/actions/setup-bazel/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,24 @@ runs:
fi
- name: Configure the remote cache credential helper
uses: ./.github/actions/remote-cache-helper
- name: Point Bazel at a registry file cache
- name: Point Bazel at a registry file cache and the shared nested cache root
shell: bash
run: |
cache="$RUNNER_TEMP/dx-repository-cache"
contents="$RUNNER_TEMP/dx-repo-contents"
mkdir -p "$cache" "$contents"
nested="$RUNNER_TEMP/dx-nested"
mkdir -p "$cache" "$contents" "$nested"
if [ "$RUNNER_OS" = Windows ]; then
cache="$(cygpath -m "$cache")"
contents="$(cygpath -m "$contents")"
nested="$(cygpath -m "$nested")"
fi
{
echo "common --repository_cache=$cache"
echo "common --repo_contents_cache=$contents"
echo "test --sandbox_writable_path=$nested"
} >> user.bazelrc
echo "DX_NESTED_SHARED=$nested" >> "$GITHUB_ENV"
- uses: bazel-contrib/setup-bazel@104e3eea9447cdaa4b00d0fb46191a3985d26ab3 # v0.19.1
with:
bazelisk-version: ${{ steps.pin.outputs.version }}
Expand Down
20 changes: 11 additions & 9 deletions docs/design/nested-tests.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Nested tests design

This page fixes which tests may run Bazel inside a test, and how they run. Conversions follow it.
This page fixes which tests may run Bazel inside a test, and how they run.

## Kinds

Expand All @@ -26,7 +26,7 @@ Measured on Linux x86_64 with the pinned Bazel 9.3.1, an empty module and one wr
| Second build, same server | 0.04 s |

- A cold nested test takes 7 seconds before it loads rules_dx. No nested test runs under 1 second.
- The 1 second target is met by a nested test only as a cached result.
- Only a cached result meets the 1 second target.
- A test that must run under 1 second uncached is converted.

## Decisions
Expand Down Expand Up @@ -60,15 +60,17 @@ Measured on Linux x86_64 with the pinned Bazel 9.3.1, an empty module and one wr

- Bazel is `//tools/testing:nested_bazel_bin`, the binary pinned by sha256 for the `.bazelversion` release, read from runfiles.
- The harness starts it through `//tools/testing:nested_bazel_shim`.
- No bazelisk. No `DX_NESTED_BAZEL`. No lookup on `PATH`.
- No bazelisk, no `DX_NESTED_BAZEL`, no `PATH` lookup.

### Environment

- The test sets `PATH=/dx_no_path` and inherits no host variable. `NESTED_BAZEL_ENV_INHERIT` is deleted.
- The test sets `PATH=/dx_no_path` and inherits no host variable but `DX_NESTED_SHARED`. `NESTED_BAZEL_ENV_INHERIT` is deleted.
- `HOME`, the output user root and every workspace are under `TEST_TMPDIR`.
- No slot root on the host. `DX_NESTED_BAZEL_ROOT`, `DX_NESTED_BAZEL_DISK_CACHE` and `DX_NESTED_BAZEL_REPOSITORY_CACHE` are deleted.
- The nested Bazel reads one rc file that the harness writes. It reads no home, system or workspace rc of the host.
- The nested Bazel uses no disk cache and no remote cache.
- The nested Bazel uses no remote cache.
- setup-bazel exports `DX_NESTED_SHARED`, a root outside the sandbox. Servers share its install base and disk cache; fetch caches are per cache set. A starting test trims it to 6 GB, least recently used first, sparing what running tests hold.
- `nested_bazel_test(caches = "private")` opts out, for cold or fetch-failure tests. Record mode is private.
- Nested actions run with `--spawn_strategy=local`. The test sandbox is the boundary.

### Repository inputs
Expand All @@ -78,25 +80,25 @@ Measured on Linux x86_64 with the pinned Bazel 9.3.1, an empty module and one wr
- Every file the consumer downloads is a test input: registry files, module archives, toolchain archives.
- `nested_repository_cache` declares them. It reads a checked-in list of URL and hex digest, one `http_file` per entry, and gives a manifest of digest to runfile.
- The digest is the checksum Bazel keys the repository cache with: sha256, or sha384 or sha512 for a download with that integrity.
- The harness builds a repository cache under `TEST_TMPDIR` from the manifest and passes `--repository_cache`.
- The harness builds a repository cache from the manifest and passes `--repository_cache`.
- A nested test declares one cache set with `nested_bazel_test(cache = "<set>")`.
- The downloader config blocks every host, `bcr.bazel.build` included.
- A missing entry fails the test with the URL.
- A missing entry fails with the URL.
- `bazel run //tools/testing:nested_cache_update -- <test label>` runs the tests online with `DX_NESTED_BAZEL_NETWORK=1`. In that record mode the test writes `<set>.txt` and `<set>.MODULE.bazel.lock` to its undeclared outputs, and the tool copies them to `tools/testing/nested_cache`.
- Other hosts record through evidence.yml with `flags=--config=nested_record`; `harness.txt` is the union of the host records.
- The test calls `case.use_lock("<set>")` where it needs the checked-in lock; in record mode that call removes the lock and registers the workspace.
- Each case that ends rewrites the record from every workspace registered so far, so a failing test still uploads its record. The exit hook rewrites it once more and fails on a missing lock.
- `bazel run //tools/testing:nested_cache_update -- --from <dir>...` merges the records of several hosts. Each `<dir>` holds `<set>.txt` and a `<stem>.MODULE.bazel.lock` per `use_lock` stem: an unpacked evidence artifact's `test.outputs/nested_cache` or the local testlogs. The tool unions the lists by URL, fails when one URL has two digests, fails when the locks of one stem differ, and writes the result to `tools/testing/nested_cache`.
- A full re-record is one `lock-refresh.yml` dispatch with `nested=true` and `pr=<number>` on the pull request branch. It records the nested tests on linux_x86_64, macos_arm64 and windows_x86_64, merges the three hosts with `--from` and pushes `tools/testing/nested_cache` to that branch with the root lock.
- The list is the registry files, module archives, patches and overlays of the lock, and every checksummed download in the Bazel workspace rules log. Nothing is edited by hand.
- The list is the registry files, module archives, patches and overlays of the lock, and every checksummed download in the Bazel workspace rules log. None is hand-edited.
- `//core/modules:consumer_deps_test` fails a PR that bumps a registry `bazel_dep` until the same PR re-records every nested cache set.

### Tags

- No `local`, `no-sandbox`, `no-cache`, `no-remote`, `external`, `requires-network` or `manual`.
- `NESTED_BAZEL_NETWORK_TAGS`, `NESTED_BAZEL_NETWORK_ENV`, `STARTER_CONSUMER_TAGS` and `QUALIFICATION_TAGS` are deleted.
- A nested test keeps `resources:nested_bazel:1`, `resources:cpu:2` and `resources:memory:2560`.
- The result is cached like any other test. Its inputs are the pinned Bazel, the shim, `module_srcs`, the cache sets and the fixture.
- The result is cached. Its inputs are the pinned Bazel, the shim, `module_srcs`, the cache sets and the fixture.

### Size

Expand Down
2 changes: 1 addition & 1 deletion docs/design/test-budget.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Every test call follows these rules. `//tools/ci:test_budget_test` checks them.
## Nested tests

- `tools/testing/nested_smoke.txt` holds one sorted line per nested test: `<label> <seconds>`.
- `<seconds>` is the cold time measured on Linux x86_64. A test with no measurement lists its declared timeout.
- `<seconds>` is the time measured on Linux x86_64 with a fresh `TEST_TMPDIR` and a warm `DX_NESTED_SHARED` root. A test with `caches = "private"` is measured cold. A test with no measurement lists its declared timeout.
- A nested test is a test call in a BUILD file whose `tags` hold `resources:nested_bazel`, as a string or through a constant.
- A call of a macro that declares such a test is a nested test. A macro that declares one under an `if` counts when the call sets a name of the condition to `True`.
- A target whose name ends in `_upstream` is skipped.
Expand Down
1 change: 1 addition & 0 deletions tools/testing/consumer/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ nested_bazel_test(
name = "cold_start_test",
size = "small",
srcs = ["cold_start_test.rs"],
caches = "private",
crate_name = "cold_start_test",
crate_root = "cold_start_test.rs",
# //:module_srcs leaves out //patches/rules_py, which write_rules_py_patches copies.
Expand Down
9 changes: 7 additions & 2 deletions tools/testing/hermetic/defs.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -200,13 +200,15 @@ def hermetic_qualification(
**kwargs
)

def nested_bazel_test(name, *, network = False, cache = None, cache_locks = None, data = None, env = None, tags = None, target_compatible_with = None, **kwargs):
"""Declares a rust_test that runs a nested Bazel with the shared tags, env and the cache set `cache` whose locks are the label `cache_locks`."""
def nested_bazel_test(name, *, network = False, cache = None, cache_locks = None, caches = "shared", data = None, env = None, tags = None, target_compatible_with = None, **kwargs):
"""Declares a rust_test that runs a nested Bazel with the shared tags, env, the cache set `cache` whose locks are `cache_locks`, and `caches = "private"` to stay off the shared cache root."""
target_compatible_with = target_compatible_with or []
cache_data = []
cache_env = {}
if bool(cache) != bool(cache_locks):
fail("cache and cache_locks go together")
if caches not in ("shared", "private"):
fail("%s: caches is %r, want \"shared\" or \"private\"" % (name, caches))
if cache:
repository_cache = "@nested_cache_%s//:cache" % cache
locks = cache_locks
Expand All @@ -216,10 +218,13 @@ def nested_bazel_test(name, *, network = False, cache = None, cache_locks = None
"DX_NESTED_LOCKS": "$(rlocationpaths %s)" % locks,
"DX_NESTED_REPOSITORY_CACHE": "$(rlocationpath %s)" % repository_cache,
}
if caches == "private":
cache_env["DX_NESTED_CACHES"] = "private"
rust_test(
name = name,
data = (data or []) + cache_data + NESTED_BAZEL_DATA,
env = {"RUST_TEST_THREADS": "1"} | (NESTED_BAZEL_NETWORK_ENV if network else NESTED_BAZEL_ENV) | cache_env | (env or {}),
env_inherit = ["DX_NESTED_SHARED"] if caches == "shared" else [],
tags = (NESTED_BAZEL_NETWORK_TAGS if network else NESTED_BAZEL_TAGS) + (tags or []),
target_compatible_with = target_compatible_with,
**kwargs
Expand Down
1 change: 1 addition & 0 deletions tools/testing/nested/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ rust_library(
"src/plain_consumer.rs",
"src/plain_fixture.rs",
"src/record.rs",
"src/shared.rs",
],
aliases = aliases(
package_name = "tools/testing/dx_nested",
Expand Down
84 changes: 79 additions & 5 deletions tools/testing/nested/src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

pub const MANIFESTS_ENV: &str = "DX_NESTED_REPOSITORY_CACHE";

Expand Down Expand Up @@ -52,15 +53,42 @@ pub fn entry(cache: &Path, digest: &str) -> PathBuf {
.join("file")
}

/// Links to the resolved file, so the entry outlives the runfiles tree of the test that placed it.
#[cfg(unix)]
fn place(src: &Path, dst: &Path) -> std::io::Result<()> {
let src = std::path::absolute(src)?;
std::os::unix::fs::symlink(src, dst)
fn link(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(std::fs::canonicalize(src)?, dst)
}

#[cfg(not(unix))]
fn link(src: &Path, dst: &Path) -> std::io::Result<()> {
std::fs::hard_link(src, dst)
}

/// Puts `src` at `dst` with one rename, so a test reading a shared cache sees no entry or a whole one.
fn place(src: &Path, dst: &Path) -> std::io::Result<()> {
std::fs::copy(src, dst).map(|_| ())
static STAGED: AtomicU64 = AtomicU64::new(0);
let n = STAGED.fetch_add(1, Ordering::Relaxed);
// Sandboxed tests can share a PID across PID namespaces; the clock keeps their staging names apart.
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos());
let staging = dst.with_file_name(format!(".file.{}.{nanos}.{n}.tmp", std::process::id()));
let placed = match link(src, &staging) {
Ok(()) => {
std::fs::rename(&staging, dst).inspect_err(|_| dx_atomic_fs::discard_file(&staging))
}
Err(error) if cfg!(unix) => Err(error),
// A hard link cannot cross volumes; the copy is staged and renamed the same way.
Err(_) => dx_atomic_fs::copy_scratch(src, dst),
};
// Another test may have placed the same digest first, and Windows refuses to replace an entry that test has open.
placed.or_else(|error| {
if std::fs::metadata(dst).is_ok() {
Ok(())
} else {
Err(error)
}
})
}

fn id_hash(digest: &str, canonical_id: &str) -> Option<String> {
Expand Down Expand Up @@ -107,7 +135,8 @@ pub fn install(cache: &Path, files: &[Download<PathBuf>]) -> Result<(), String>
let dir = dst.parent().unwrap_or(cache);
std::fs::create_dir_all(dir)
.map_err(|error| format!("cannot create {}: {error}", dir.display()))?;
if std::fs::symlink_metadata(&dst).is_err() {
// A dangling link counts as missing: the runfiles it pointed at are gone.
if std::fs::metadata(&dst).is_err() {
place(file, &dst).map_err(|error| {
format!(
"cannot put {} at {}: {error}",
Expand Down Expand Up @@ -345,6 +374,51 @@ mod tests {
);
}

#[cfg(unix)]
#[test]
fn install_replaces_an_entry_whose_file_is_gone() {
let dir = tempfile::tempdir().expect("tempdir");
let cache = dir.path().join("cache");
let placed = entry(&cache, A);
std::fs::create_dir_all(placed.parent().expect("parent")).expect("mkdir");
std::os::unix::fs::symlink(dir.path().join("gone"), &placed).expect("dangling link");
let src = dir.path().join("download");
std::fs::write(&src, "bytes").expect("write");
let files = vec![Download {
digest: A.to_owned(),
file: src,
urls: Vec::new(),
}];
install(&cache, &files).expect("install");
assert_eq!(std::fs::read_to_string(&placed).expect("read"), "bytes");
}

#[test]
fn concurrent_installs_leave_one_whole_entry_and_no_staging_file() {
let dir = tempfile::tempdir().expect("tempdir");
let src = dir.path().join("download");
std::fs::write(&src, "bytes").expect("write");
let cache = dir.path().join("cache");
let files = vec![Download {
digest: A.to_owned(),
file: src,
urls: vec!["abc".to_owned()],
}];
std::thread::scope(|scope| {
for _ in 0..8 {
scope.spawn(|| install(&cache, &files).expect("install"));
}
});
let placed = entry(&cache, A);
assert_eq!(std::fs::read_to_string(&placed).expect("read"), "bytes");
let names: Vec<String> = std::fs::read_dir(placed.parent().expect("parent"))
.expect("list")
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.filter(|name| name.ends_with(".tmp"))
.collect();
assert!(names.is_empty(), "{names:?}");
}

#[test]
fn a_sha512_download_records_its_url_as_a_sha512_canonical_id() {
let dir = tempfile::tempdir().expect("tempdir");
Expand Down
Loading
Loading