import { requireEnvironment } from "./requires"; /** * The XCFramework cache key names the Rust the asked slices compile — not the * whole workspace. * * Measured 29 Sep 2026: the swift job's framework step was 3m04 on a miss, and * it missed on ANY crate change because the key was `HEAD:crates`. A slice * compiles cotton-ffi's dependency closure for its own feature set: the iOS * slices (`--no-default-features`) never link cotton-server, and neither slice * links cotton-gen or the conformance recorder. So the key is that closure, * from `cargo metadata`: workspace crates by committed tree hash, everything * else by package id, plus the workspace manifest and toolchain file. * * What makes the narrower key SOUND is held here: every crate reachable from * cotton-ffi reads no file outside its own directory, so its tree is its whole * input; dev-only edges (never compiled into an archive) are not followed; and * whenever the closure cannot be read the key falls back to the whole tree — * a spare input costs a miss, a missing one would serve a stale archive. * `cargo` is a stub here, so this runs where no toolchain is installed. */ import { execFileSync, spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; const ROOT = resolve(__dirname, "../.."); const SCRIPT = join(ROOT, "scripts/build-xcframework.sh"); const CRATES = join(ROOT, "crates"); const HAS_JQ = spawnSync("sh", ["-c", "command -v jq"]).status === 0; const temps: string[] = []; afterAll(() => temps.forEach((d) => rmSync(d, { recursive: true, force: true }))); const tree = (rel: string) => execFileSync("git", ["-C", ROOT, "rev-parse", `HEAD:${rel}`], { encoding: "utf8" }).trim(); type Pkg = { name: string; path?: string; reg?: string }; type Edge = [string, string, "normal" | "dev" | "build"]; /** A `cargo metadata` document: packages by name, edges from -> to with a kind. */ function metadata(pkgs: Pkg[], edges: Edge[]) { const id = (p: Pkg) => (p.path ? `path+file://${p.path}#${p.name}@0.1.0` : `registry+https://github.com/rust-lang/crates.io-index#${p.name}@${p.reg}`); const byName = Object.fromEntries(pkgs.map((p) => [p.name, id(p)])); return JSON.stringify({ packages: pkgs.map((p) => ({ name: p.name, id: id(p), source: p.path ? null : "registry+https://github.com/rust-lang/crates.io-index", manifest_path: p.path ? join(p.path, "Cargo.toml") : `/registry/${p.name}/Cargo.toml`, })), resolve: { nodes: pkgs.map((p) => ({ id: byName[p.name], deps: edges .filter(([from]) => from === p.name) .map(([, to, kind]) => ({ pkg: byName[to], dep_kinds: [{ kind: kind === "normal" ? null : kind }] })), })), }, }); } /** A bin dir whose `cargo metadata` answers per feature flag (or fails). */ function stubCargo(byFlag: Record): string { const bin = mkdtempSync(join(tmpdir(), "xc-closure-")); temps.push(bin); for (const [flag, doc] of Object.entries(byFlag)) if (doc) writeFileSync(join(bin, `meta${flag}.json`), doc); writeFileSync( join(bin, "cargo"), `#!/bin/sh\nfor a in "$@"; do case "$a" in --all-features|--no-default-features) f="$a";; esac; done\n` + `[ -f "${bin}/meta$f.json" ] || exit 101\ncat "${bin}/meta$f.json"\n`, ); chmodSync(join(bin, "cargo"), 0o755); return bin; } function rustInputs(args: string[], bin: string | null): { lines: string[]; out: string } { const home = mkdtempSync(join(tmpdir(), "xc-closure-home-")); temps.push(home); const path = bin ? `${bin}:${process.env.PATH}` : `/usr/bin:/bin`; const r = spawnSync("bash", [SCRIPT, ...args, "--print-rust-inputs"], { cwd: ROOT, encoding: "utf8", env: { PATH: path, HOME: home } }); expect(r.status, r.stderr).toBe(0); return { lines: r.stdout.split("\n").filter(Boolean), out: r.stdout + r.stderr }; } const C = (name: string) => join(realpathSync(CRATES), name); const PKGS: Pkg[] = [ { name: "cotton-ffi", path: C("cotton-ffi") }, { name: "cotton-core", path: C("cotton-core") }, { name: "cotton-server", path: C("cotton-server") }, { name: "cotton-gen", path: C("cotton-gen") }, { name: "serde", reg: "1.0.0" }, { name: "proptest", reg: "1.0.0" }, ]; const IOS = metadata(PKGS, [["cotton-ffi", "cotton-core", "normal"], ["cotton-core", "serde", "normal"], ["cotton-core", "proptest", "dev"], ["cotton-gen", "cotton-core", "normal"]]); describe("the Rust half of the key", () => { requireEnvironment({ probe: () => HAS_JQ, reason: "jq is unavailable on this runner" }); // RULE: The iOS slices' key names cotton-ffi's --no-default-features closure — its crates by tree hash, its packages by id — and no crate outside it. it("names the iOS slices' closure and nothing else", () => { const { lines } = rustInputs([], stubCargo({ "--no-default-features": IOS })); expect(lines).toContain(`path cotton-ffi ${tree("crates/cotton-ffi")}`); expect(lines).toContain(`path cotton-core ${tree("crates/cotton-core")}`); expect(lines.some((l) => l.startsWith("pkg ") && l.includes("#serde@1.0.0"))).toBe(true); expect(lines.join("\n")).not.toMatch(/cotton-server|cotton-gen/); expect(lines).toContain(`workspace ${tree("crates/Cargo.toml")} ${tree("crates/rust-toolchain.toml")}`); }); // RULE: A dev-only dependency is not a key input — it is never compiled into an archive. it("does not follow a dev-only edge", () => { const { lines } = rustInputs([], stubCargo({ "--no-default-features": IOS })); expect(lines.join("\n")).not.toMatch(/proptest/); }); // When the closure cannot be read — no cargo, metadata refused, cotton-ffi absent, a crate outside crates/ — the key is the whole workspace tree. it.each([ ["no cargo on PATH", null], ["cargo metadata refused", {}], ["cotton-ffi not in the graph", { "--no-default-features": metadata([{ name: "serde", reg: "1.0.0" }], []) }], [ "a path crate outside crates/", { "--no-default-features": metadata([{ name: "cotton-ffi", path: C("cotton-ffi") }, { name: "vendored", path: "/elsewhere/vendored" }], [["cotton-ffi", "vendored", "normal"]]) }, ], ] as const)("falls back to the whole tree when %s", (_why, byFlag) => { const bin = byFlag === null ? null : stubCargo(byFlag as Record); const { lines } = rustInputs([], bin); expect(lines).toEqual([`tree ${tree("crates")}`]); }); // RULE: Asking for the Rust inputs is a question — it takes no build lock and runs no disk guard. it("asks without side effects", () => { const { out } = rustInputs([], stubCargo({ "--no-default-features": IOS })); expect(out).not.toMatch(/\[build-lock\]|disk-guard/); }); }); describe("what makes a crate's tree its whole input", () => { /** Every workspace crate reachable from cotton-ffi by any `path =` dependency, optional ones included. */ function reachable(): string[] { const seen = new Set(["cotton-ffi"]); const todo = ["cotton-ffi"]; while (todo.length) { const crate = todo.pop()!; const manifest = readFileSync(join(CRATES, crate, "Cargo.toml"), "utf8"); for (const m of manifest.matchAll(/path\s*=\s*"\.\.\/([^"/]+)"/g)) { if (!seen.has(m[1])) { seen.add(m[1]); todo.push(m[1]); } } } return [...seen].sort(); } /** * The workspace crates EVERY slice compiles: reachable from cotton-ffi through * `[dependencies]` / `[build-dependencies]` path edges that are not optional. * Their committed trees are always in the key, whatever features a slice asks for. */ function alwaysInKey(): string[] { const seen = new Set(["cotton-ffi"]); const todo = ["cotton-ffi"]; while (todo.length) { const crate = todo.pop()!; let section = ""; for (const line of readFileSync(join(CRATES, crate, "Cargo.toml"), "utf8").split("\n")) { const header = line.match(/^\s*\[([^\]]+)\]/); if (header) { section = header[1]; continue; } if (!/(^|\.)(dependencies|build-dependencies)$/.test(section) || /dev-dependencies$/.test(section)) continue; const dep = line.match(/path\s*=\s*"\.\.\/([^"/]+)"/); if (!dep || /optional\s*=\s*true/.test(line) || seen.has(dep[1])) continue; seen.add(dep[1]); todo.push(dep[1]); } } return [...seen].sort(); } function rustFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap((e) => { const p = join(dir, e.name); if (e.isDirectory()) return e.name === "target" ? [] : rustFiles(p); return e.name.endsWith(".rs") ? [p] : []; }); } it("finds cotton-ffi's crates (the walk is not silently empty)", () => { expect(reachable()).toEqual(expect.arrayContaining(["cotton-client", "cotton-core", "cotton-ffi", "cotton-store", "cotton-tools"])); }); // RULE: No crate reachable from cotton-ffi reads a file outside its own directory or a crate every slice compiles (include_str!, include_bytes!, include!, #[path], or CARGO_MANIFEST_DIR with ..), so the committed trees the key names are the whole input to the XCFramework key. // A read into a crate every slice compiles (cotton-store's built-in package tables include cotton-core's // definitions) is inside the key already: that crate's tree is hashed for every slice. A read into an // optional or dev-only crate is not, and would serve a stale archive. // Test-only sources are not that input: a `*_tests.rs` / `tests.rs` module and the crate's `tests/` // directory are compiled by `cargo test` alone, never into an archive, so a fixture they include from // another crate (cotton-client's bootstrap tests read cotton-store's schema-v128.json) changes no slice. const testOnly = (file: string, root: string) => /(^|\/)(tests|[^/]+_tests)\.rs$/.test(file) || file.startsWith(join(root, "tests") + "/"); it("no crate reachable from cotton-ffi reads a file outside its own directory or a crate every slice compiles", () => { const escapes: string[] = []; const keyed = alwaysInKey().map((crate) => realpathSync(join(CRATES, crate))); expect(keyed.map((dir) => dir.split("/").pop())).toEqual(expect.arrayContaining(["cotton-core", "cotton-ffi", "cotton-store"])); for (const crate of reachable()) { const root = realpathSync(join(CRATES, crate)); for (const file of rustFiles(root)) { if (testOnly(file, root)) continue; const text = readFileSync(file, "utf8"); for (const m of text.matchAll(/(?:include_str!|include_bytes!|include!|#\[path\s*=)\s*\(?\s*"([^"]+)"/g)) { const target = m[1].startsWith("/") ? m[1] : resolve(dirname(file), m[1]); if (!target.startsWith(root + "/") && !keyed.some((dir) => target.startsWith(dir + "/"))) escapes.push(`${file.slice(ROOT.length + 1)}: ${m[1]}`); } if (/CARGO_MANIFEST_DIR[^;\n]*\.\.\//.test(text)) escapes.push(`${file.slice(ROOT.length + 1)}: CARGO_MANIFEST_DIR/..`); } if (existsSync(join(root, "build.rs")) && /\.\.\//.test(readFileSync(join(root, "build.rs"), "utf8"))) { escapes.push(`crates/${crate}/build.rs reads ../`); } } expect(escapes).toEqual([]); }); });