Field Notes: CI & Reproducible Packages
The second set of field notes is about the pipeline: the order of dotnet commands a CI job should run, what to cache, and how far "reproducible" really goes for .NET packages.
1. Restore once, then build, test and pack without restoring
Each dotnet command restores and builds what it needs unless told otherwise. In CI that wastes time and, worse, lets later steps resolve differently from earlier ones. Restore once, in locked mode, then pass --no-restore and --no-build down the chain:
mkdir repo && cd repo
git init -q
dotnet new gitignore > /dev/null
cat > Directory.Build.props <<'XML'
<Project>
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<RestoreLockedMode Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</RestoreLockedMode>
</PropertyGroup>
</Project>
XML
dotnet new sln -n Calc > /dev/null
dotnet new classlib -n Calc -o src/Calc --no-restore > /dev/null
dotnet new xunit -n Calc.Tests -o tests/Calc.Tests --no-restore > /dev/null
dotnet sln add src/Calc tests/Calc.Tests > /dev/null
dotnet reference add src/Calc --project tests/Calc.Tests > /dev/null
echo 'namespace Calc; public static class Ops { public static int Add(int a, int b) => a + b; }' > src/Calc/Class1.cs
cat > tests/Calc.Tests/UnitTest1.cs <<'CS'
namespace Calc.Tests;
public class OpsTests
{
[Fact] public void Adds() => Assert.Equal(5, Calc.Ops.Add(2, 3));
}
CS
dotnet restore -v:q && git add -A && git commit -qm "calc"
cat > ci.sh <<'SH'
set -euo pipefail
export ContinuousIntegrationBuild=true
step() { echo "== $1"; }
step restore; dotnet restore --locked-mode -v:q
step build; dotnet build -c Release --no-restore -nologo -v:q -bl:artifacts/build.binlog > /dev/null
step test; dotnet test -c Release --no-build -nologo -v:q | grep -E 'Passed!|Failed!'
step pack; dotnet pack src/Calc -c Release --no-build -o artifacts -nologo -v:q -p:Version=1.4.0
ls artifacts
SH
bash ci.sh== restore
== build
== test
Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: 9 ms - Calc.Tests.dll (net10.0)
== pack
Calc.1.4.0.nupkg
build.binlog
ContinuousIntegrationBuildis set as an environment variable, which MSBuild reads as a property, so every command (and theRestoreLockedModecondition inDirectory.Build.props) sees it, without repeating-p:on each line. CI systems usually set their own variable (GITHUB_ACTIONS,TF_BUILD), which the deterministic lesson used instead.--no-buildontestandpackguarantees they ship exactly the binaries the build step produced (and that you tested).- The version comes from CI (
-p:Version=1.4.0, typically computed from a git tag) rather than being edited in project files. - The binlog goes into
artifacts/next to the package; upload the folder when the job fails.
2. Cache the global packages folder, keyed on lock files
Restoring from a warm ~/.nuget/packages is close to free. The cache key must change whenever any resolved version changes, and lock files are exactly that:
import hashlib
def cache_key(os_name, lock_files):
h = hashlib.sha256()
for path in sorted(lock_files): # stable order, independent of discovery order
h.update(path.encode())
h.update(lock_files[path].encode())
return f"nuget-{os_name}-{h.hexdigest()[:16]}"
locks = {
"src/Calc/packages.lock.json": '{"Newtonsoft.Json": "13.0.4"}',
"tests/Calc.Tests/packages.lock.json": '{"xunit": "2.9.3"}',
}
print(cache_key("linux", locks))
print(cache_key("linux", dict(reversed(list(locks.items())))))
locks["src/Calc/packages.lock.json"] = '{"Newtonsoft.Json": "13.0.3"}'
print(cache_key("linux", locks))nuget-linux-6d33c60f1541a735
nuget-linux-6d33c60f1541a735
nuget-linux-7d08da4468ee1ca7
That is what hashFiles('**/packages.lock.json') does in a GitHub Actions actions/cache key (and actions/setup-dotnet with cache: true does it for you). Without lock files, people key on **/*.csproj, which misses transitive changes and floating versions. Point NUGET_PACKAGES at a folder inside the workspace if the runner's home directory isn't cacheable.
3. "Reproducible" packages: compare contents, not archives
Deterministic builds make the DLL byte-identical. The .nupkg around it is a different story with this SDK:
mkdir lib && cd lib
git init -q
cat > lib.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PackageId>Ada.Repro</PackageId>
<Version>1.0.0</Version>
</PropertyGroup>
</Project>
XML
echo 'namespace Ada; public static class Repro { public static int V => 1; }' > Repro.cs
printf 'bin/\nobj/\nout*/\n' > .gitignore
git add -A && git commit -qm init
pack() { rm -rf bin obj; dotnet pack -o $1 -nologo -v:q -p:ContinuousIntegrationBuild=true; }
pack out1
sleep 2
pack out2
echo "archives:"
sha256sum out1/*.nupkg out2/*.nupkg | awk '{print substr($1,1,16), $2}'
mkdir x1 x2 && (cd x1 && unzip -q ../out1/*.nupkg) && (cd x2 && unzip -q ../out2/*.nupkg)
echo "contents:"
diff -r x1 x2 && echo "identical file by file"
sha256sum x1/lib/net10.0/lib.dll x2/lib/net10.0/lib.dll | awk '{print substr($1,1,16), $2}'archives:
b108bbe6adf96184 out1/Ada.Repro.1.0.0.nupkg
f133f69c2c70ff4c out2/Ada.Repro.1.0.0.nupkg
contents:
identical file by file
bf33f10d79bc720b x1/lib/net10.0/lib.dll
bf33f10d79bc720b x2/lib/net10.0/lib.dll
The two archives differ (zip entries carry the time they were packed), but every file inside, including the DLL, is identical. Practical consequences:
- To check that a package was built from a given commit, rebuild and compare the extracted contents (or the DLLs), not the
.nupkgchecksum. Tools likedotnet-validateand NuGet Package Explorer check the deterministic flag of the assemblies inside. - Because re-packing changes the archive hash, never re-publish an existing version, even "with the same code": every lock file in the world that recorded the old
contentHashwould fail with NU1403. - Pin everything that goes into the build: the SDK (
global.json), packages (lock files + locked mode), tools (dotnet-tools.json), and build from a clean checkout of a tagged commit.
4. A short checklist for .NET CI
global.jsonpins the SDK; the job installs exactly that one.dotnet tool restore, thendotnet restore --locked-mode, with the package cache keyed on lock files.dotnet build -c Release --no-restore -blwithContinuousIntegrationBuild=trueand warnings as errors.dotnet test --no-build, publishing test results.dotnet format --verify-no-changes(fast, can run in parallel).dotnet pack --no-build -p:Version=$VERSIONanddotnet nuget push --skip-duplicateonly on tagged builds, with the key from a secret.- Upload
artifacts/(packages, binlog) on success and on failure.
Test yourself
Why run dotnet test --no-build after a separate build step?
- It's faster only on Windows
- It guarantees the tests run against exactly the binaries the build step produced, without a second build or restore
- --no-build skips failing tests
- It's required by xunit
What is a good cache key for ~/.nuget/packages in CI?
- The branch name
- A hash of all packages.lock.json files (plus the OS)
- The date
- The SDK version only
Two clean packs of the same commit give .nupkg files with different SHA-256 hashes. What should you conclude?
- The build is not deterministic
- Nothing alarming: the zip archive records pack times; compare the extracted files, which are identical
- A package was tampered with
- The lock file is wrong