Skip to content

Make Private.SourceBuilt.Artifacts tarball reproducible - #7817

Open
omajid wants to merge 2 commits into
dotnet:mainfrom
omajid:reproducible-try-11
Open

omajid wants to merge 2 commits into
dotnet:mainfrom
omajid:reproducible-try-11

Conversation

@omajid

@omajid omajid commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Generate tarball (and nested tarballs), and with deterministic contents

  • Make the tarball-creation code reproducible across builds.

    Use a custom CreateCompressedTarball task.

  • finish-source-only.proj doesn't receive DeterministicTimestamp

    finish-source-only.proj uses Microsoft.Build.NoTargets SDK. So Deterministic and DeterministicTimestamp are never set (let alone from SOURCE_DATE_EPOCH).

  • BuildOutputPropsCreationTime uses DateTime.UtcNow

    WritePackageVersionsProps.cs writes DateTime.UtcNow.Ticks into PackageVersions.props, producing a different value on every build.

    Add Deterministic and DeterministicTimestamp properties to the task, passed from the calling site in PublishSourceBuild.props.

  • Default Deterministic=true in Packaging.targets for pkgproj builds

    The arcade Packaging SDK's NuGetPack task passes Deterministic="$(Deterministic)" to PackageBuilder, but $(Deterministic) is never set for .pkgproj files.

    The affected packages are the coreclr pkgproj-based packages:

    • Microsoft.NETCore.ILAsm
    • Microsoft.NETCore.ILDAsm
    • Microsoft.NETCore.TestHost
    • runtime..Microsoft.NETCore.ILAsm
    • runtime..Microsoft.NETCore.ILDAsm
    • runtime..Microsoft.NETCore.TestHost

@omajid
omajid requested review from a team as code owners July 17, 2026 13:45
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
1 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service
dotnet-policy-service Bot requested a review from a team July 17, 2026 13:46
@mthalman
mthalman self-requested a review July 17, 2026 13:53
Comment thread eng/finish-source-only.proj Outdated
<TarTimestamp Condition="$(DeterministicTimestamp.Contains('-'))">$(DeterministicTimestamp)</TarTimestamp>
<TarTimestamp Condition="'$(DeterministicTimestamp)' != '' and '$(DeterministicTimestamp)' != 'false' and !$(DeterministicTimestamp.Contains('-'))">@$(DeterministicTimestamp)</TarTimestamp>
<TarTimestampArgument Condition="'$(TarTimestamp)' != '' and '$(DeterministicTimestamp)' != 'false'">--mtime="$(TarTimestamp)" </TarTimestampArgument>
<ReproducibleTarArgs>--sort=name $(TarTimestampArgument) --owner=0 --group=0 --numeric-owner</ReproducibleTarArgs>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tar on Alpine doesn't seem to support these flags either:

/ # tar --help
BusyBox v1.37.0 (2025-12-16 14:19:28 UTC) multi-call binary.

Usage: tar c|x|t [-ZzJjahmvokO] [-f TARFILE] [-C DIR] [-T FILE] [-X FILE] [LONGOPT]... [FILE]...

Create, extract, or list files from a tar file

	c	Create
	x	Extract
	t	List
	-f FILE	Name of TARFILE ('-' for stdin/out)
	-C DIR	Change to DIR before operation
	-v	Verbose
	-O	Extract to stdout
	-m	Don't restore mtime
	-o	Don't restore user:group
	-k	Don't replace existing files
	-Z	(De)compress using compress
	-z	(De)compress using gzip
	-J	(De)compress using xz
	-j	(De)compress using bzip2
	--lzma	(De)compress using lzma
	-a	(De)compress based on extension
	-h	Follow symlinks
	-T FILE	File with names to include
	-X FILE	File with glob patterns to exclude
	--exclude PATTERN	Glob pattern to exclude
	--overwrite		Replace existing files
	--strip-components NUM	NUM of leading components to strip
	--no-recursion		Don't descend in directories
	--numeric-owner		Use numeric user:group
	--no-same-permissions	Don't restore access permissions

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also --numeric-owner doesn't need to be here since we always pass it later

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the best way to achive byte-by-byte determinisim is to switch to System.Formats.Tar:

  <!-- Define the Custom .NET 11 TarGz Task with format parameter -->
  <UsingTask TaskName="CreateTarGz" 
             TaskFactory="RoslynCodeTaskFactory" 
             AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
    <ParameterGroup>
      <SourceDir ParameterType="System.String" Required="true" />
      <DestinationFile ParameterType="System.String" Required="true" />
      <Format ParameterType="System.String" Required="false" /> <!-- Defaults to Gnu if not specified -->
    </ParameterGroup>
    <Task>
      <Using Namespace="System" />
      <Using Namespace="System.IO" />
      <Using Namespace="System.IO.Compression" />
      <Using Namespace="System.Formats.Tar" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
          try
          {
              if (File.Exists(DestinationFile)) { File.Delete(DestinationFile); }

              // Fallback to Gnu if parameter is blank
              string formatStr = string.IsNullOrWhiteSpace(Format) ? "Gnu" : Format;
              
              // Safely parse string parameter into the TarEntryFormat Enum (Gnu, Pax, Ustar, V7)
              if (!Enum.TryParse<TarEntryFormat>(formatStr, true, out TarEntryFormat targetFormat))
              {
                  Log.LogError($"Invalid Tar Format flag: '{Format}'. Valid options are Gnu, Pax, Ustar, or V7.");
                  return false;
              }

              using (FileStream fs = new FileStream(DestinationFile, FileMode.Create, FileAccess.Write))
              using (GZipStream gzip = new GZipStream(fs, CompressionLevel.Optimal))
              {
                  // Native .NET 11 method accepting our dynamic parsed format parameter
                  TarFile.CreateFromDirectory(SourceDir, gzip, targetFormat, includeBaseDirectory: false);
              }

              Log.LogMessage(MessageImportance.High, $"Successfully created native {targetFormat} tarball: {DestinationFile}");
          }
          catch (Exception ex)
          {
              Log.LogError($"Failed to build tarball: {ex.Message}");
              return false;
          }
        ]]>
      </Code>
    </Task>
  </UsingTask>

Usage:

    <CreateTarGz SourceDir="$(OutputPath)publish\" 
                 DestinationFile="$(OutputPath)bundle.tar.gz" 
                 Format="Gnu" />

(or define the task in C# file like the one this PR is touching)

@akoeplinger akoeplinger Jul 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not a bad idea, we could make it an arcade task too (we'd need to wait for rebootstrap before we could use it though)

@am11 am11 Jul 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could add it in tasks dir for now main...am11:dotnet:patch-9 and in this context, use it like:

    <CreateCompressedTar SourceDir="$(IntermediateSymbolsRootDir)" 
                         DestinationFile="$(UnifiedSymbolsTarball)" 
                         CompressionType="gz" 
                         Format="Gnu" />

and add more options like mtime / entry.ModificationTime, entry.Mode etc. as needed. There is an open request upstream dotnet/msbuild#7944, maybe it will be included and this could become a precursor implementation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our recommendation is to not use inline tasks. They behave badly (in terms of perf) with some newer MSBuild features like multi-threaded MSBuild.

@mthalman

Copy link
Copy Markdown
Member

So it looks like in order to validate this currently we need to be using the version of Arcade with these changes rather than the current version. That hampers my suggestion here a bit as it will need to be delayed. My suggestion is that we update the existing reproducibility testing to include the artifacts tarball in its scope. @omajid, let me know if you're interested in working on that; otherwise I can do it. But it wouldn't validate successfully until after the VMR is re-bootstrapped to reference the new version of Arcade with these changes.

@ViktorHofer

Copy link
Copy Markdown
Member

The Arcade changes are automatically live in the subsequent inner repo builds. With am11's suggestion above, I don't see a strong evidence that a re-bootstrap is needed but maybe I'm missing something.

@mthalman

Copy link
Copy Markdown
Member

The Arcade changes are automatically live in the subsequent inner repo builds. With am11's suggestion above, I don't see a strong evidence that a re-bootstrap is needed but maybe I'm missing something.

The outer publish uses the older Arcade, which does not map SOURCE_DATE_EPOCH to DeterministicTimestamp. Because of that, the VMR's WritePackageVersionsProps task receives no timestamp and writes a wall-clock value into PackageVersions.props.

This is what I'm seeing in my own local testing of these changes.

@ViktorHofer

Copy link
Copy Markdown
Member

Makes sense. Can't we just add this line to PublishSourceBuild.props as it was done in finish-source-build.proj? https://github.com/dotnet/dotnet/pull/7817/changes#diff-51df42003639a4e7f8fee2802702ae4688296f9db5f5f3c3e990a56f6ccb65dbR24

@omajid

omajid commented Jul 23, 2026

Copy link
Copy Markdown
Member Author

@mthalman I put a PR for tests at #7928

I will now work on fixing this PR based on the discussions here.

@omajid

omajid commented Jul 30, 2026

Copy link
Copy Markdown
Member Author

I am a bit stumped. I created CreateCompressedTar based on main...am11:dotnet:patch-9, but I am having trouble placing it somewhere appropriate.

Top level unified build projects like eng/PublishSourceBuild.props need a task at the top-level (eg eng/tools/tasks/Microsoft.DotNet.UnifiedBuild.Tasks/CreateCompressedTar.cs)

Arcade (eg archives.targets) needs a task in arcade (eg src/arcade/src/Microsoft.DotNet.Arcade.Sdk/src/CreateCompressedTar.cs).

I don't know how to make a task that can be used by both the top-level and arcade.

Arcade bootstrapping doesn't seem to be a build-breaking issue. I can build the full VMR with the updated arcade.

@mthalman

Copy link
Copy Markdown
Member

I think we can put CreateCompressedTar in Microsoft.DotNet.Arcade.Sdk without duplicating it.

Arcade initially builds using the old bootstrap SDK, but it still compiles the current Arcade sources and produces a new Arcade SDK containing the task. The VMR then extracts that newly built SDK. The top-level publishing/finish targets run after Arcade has built, so they can load the task from that extracted SDK. Downstream repos already use the newly built Arcade SDK.

This is temporarily dependent on build ordering. After the next Arcade bootstrap, the task will be available directly from the bootstrap SDK and the temporary lookup can be removed.

So it would look like this for the consumption:

<PropertyGroup>
  <SourceBuiltArcadeTasksAssembly>
    $(ArtifactsDir)source-built-sdks/Microsoft.DotNet.Arcade.Sdk/tools/net/Microsoft.DotNet.Arcade.Sdk.dll
  </SourceBuiltArcadeTasksAssembly>
</PropertyGroup>

<UsingTask
    TaskName="Microsoft.DotNet.Arcade.Sdk.CreateCompressedTar"
    AssemblyFile="$(SourceBuiltArcadeTasksAssembly)" />

This would need to be followed up with removal of this temporary reference upon the bootstrap of the next Arcade version. An issue should be logged to track that.

@ViktorHofer

ViktorHofer commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

I would just duplicate the source temporarily in both Arcade and the UnifiedBuild.Tasks project and then remove the latter with the next re-bootstrap. @mthalman's suggestion above can easily run into issues around which UsingTask would win when both are defined (which afaik would be the case).

Comment on lines +63 to +65
if (algorithm is not "gz")
{
Log.LogError($"Unsupported compression type: '{CompressionType}'. Valid choices are 'gz'.");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit - zstd is also available in net11.0 (and used out in the wild; https://stackoverflow.com/a/45704163):

Suggested change
if (algorithm is not "gz")
{
Log.LogError($"Unsupported compression type: '{CompressionType}'. Valid choices are 'gz'.");
if (algorithm is not ("gz" or "zstd"))
{
Log.LogError($"Unsupported compression type: '{CompressionType}'. Valid choices are 'gz', 'zstd'.");

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I implemented this, but it doesn't seem to work in the arcade non-source build. Arcade is using TargetFramework=$(NetMinimum) = net10.0.

Besides, we aren't using it to create the compressed source tarball for this PR, are we? Perhaps this is something more useful for dotnet/msbuild#14451 ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I implemented this, but it doesn't seem to work in the arcade non-source build. Arcade is using TargetFramework=$(NetMinimum) = net10.0.

Ok, I thought we are using net11 in arcade SDK.

Besides, we aren't using it to create the compressed source tarball for this PR, are we? Perhaps this is something more useful for dotnet/msbuild#14451 ?

Yup, but neither are we using non-PAX format in this PR.

@omajid
omajid force-pushed the reproducible-try-11 branch 2 times, most recently from c87b1aa to 53491f6 Compare August 4, 2026 03:59
@omajid

omajid commented Aug 4, 2026

Copy link
Copy Markdown
Member Author

The artifacts tarballs are reproducible now, but I still need to verify that they contain similar contents as before.

@am11

am11 commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

dotnet/msbuild#14451 and #8252 were merged in the meantime, so let's use that instead. It has deterministic option as well which I'm not very thrilled about because there is no standard definition of "determinism", so there is no interoperability. Two tar implementations can agree on:

  • create a tarball in X format with Y header

but not:

  • create a deterministic tarball in X format

@ViktorHofer

Copy link
Copy Markdown
Member

That requires a re-bootstrap

@ViktorHofer

Copy link
Copy Markdown
Member

@am11 feel free to open an issue in msbuild to discuss that. @omajid proposed the deterministic option in the tar tasks with a naive implementation (deterministic file ordering).

@omajid

omajid commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

I tried updating this to make use of TarDirectory but ran into dotnet/msbuild#15331. We can block on that, or we can consider merging this as a known-duplicate to later remove?

@mthalman

Copy link
Copy Markdown
Member

Marking it as known duplicate should be fine so we can move forward and get everything tracked.

@akoeplinger

Copy link
Copy Markdown
Member

I think the msbuild in main should already have the fix for dotnet/msbuild#15331 now

@am11

am11 commented Nov 9, 2026

Copy link
Copy Markdown
Member

It also landed in net11.0 #10411 (and main).

Generate tarball (and nested tarballs), and with deterministic contents

- Make the tarball-creation code reproducible across builds.

  Define ReproducibleTarArgs in PublishSourceBuild.props,
  archives.targets, and finish-source-only.proj. Add it to the tar
  command. When DeterministicTimestamp is set, this adds:
  --sort=name   (deterministic file ordering)
  --mtime=...   (fixed modification time from DeterministicTimestamp)
  --owner=0 --group=0 --numeric-owner  (zero out uid/gid)

  These flags are only going to work with GNU tar. This The
  ReproducibleTarArgs property is only defined on Linux (guarded by
  IsOSPlatform), so Windows/macOS builds are unaffected.

- finish-source-only.proj doesn't receive DeterministicTimestamp

  finish-source-only.proj uses Microsoft.Build.NoTargets SDK. So
  Deterministic and DeterministicTimestamp are never set (let alone from
  SOURCE_DATE_EPOCH).

- BuildOutputPropsCreationTime uses DateTime.UtcNow

  WritePackageVersionsProps.cs writes DateTime.UtcNow.Ticks into
  PackageVersions.props, producing a different value on every build.

  Add Deterministic and DeterministicTimestamp properties to the task,
  passed from the calling site in PublishSourceBuild.props.

- Default Deterministic=true in Packaging.targets for pkgproj builds

  The arcade Packaging SDK's NuGetPack task passes
  Deterministic="$(Deterministic)" to PackageBuilder, but
  $(Deterministic) is never set for .pkgproj files.

  The affected packages are the coreclr pkgproj-based packages:
  - Microsoft.NETCore.ILAsm
  - Microsoft.NETCore.ILDAsm
  - Microsoft.NETCore.TestHost
  - runtime.<rid>.Microsoft.NETCore.ILAsm
  - runtime.<rid>.Microsoft.NETCore.ILDAsm
  - runtime.<rid>.Microsoft.NETCore.TestHost

- pigz multithreaded compression is non-deterministic

  When pigz is available, tar.gz archives (runtime, aspnetcore, symbols)
  are compressed using pigz's default multithreaded mode. Thread scheduling
  differences cause the compressed output to vary between runs, even though
  the underlying tar content is byte-identical.

  Fix: add -p1 to pigz invocations in archives.targets. This flag forces
  single-thread mode. This makes the pigz command slower, but makes it
  reproducible.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Assisted-by: GPT-6 Luna <[email protected]>
Assisted-by: Claude Opus 4.6 <[email protected]>
@omajid
omajid force-pushed the reproducible-try-11 branch from d540909 to 247e4aa Compare November 11, 2026 13:56
<Exec Command="tar --numeric-owner --owner=2001 --group=2001 -czf $(UnifiedSymbolsTarball) *"
WorkingDirectory="$(IntermediateSymbolsRootDir)" />

<TarDirectory SourceDirectory="$(IntermediateSymbolsRootDir)"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wtgodbe This is undo'ing 4ca0a61

Are there uses where this is safe as-is?

Should we enhance TarDirectory to support the owner/group attributes?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we enhance TarDirectory to support the owner/group attributes?

I think we will need this, yes

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1, we should support owner/group attributes here

@omajid

omajid commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

cc @tmds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants