From d6f288339cf4443bca4de5d731a70871f67aa277 Mon Sep 17 00:00:00 2001 From: meisa Date: Tue, 4 Aug 2026 17:31:39 +0200 Subject: [PATCH 1/2] Add package consumer acceptance gate --- .github/workflows/ci.yml | 4 + docs/38-release-validation.md | 32 +- eng/package-consumer-acceptance.ps1 | 489 +++++++++++++ .../FluxFlow.PackageConsumerAcceptance.csproj | 26 + eng/package-consumer-acceptance/Program.cs | 282 +++++++ .../README.md | 363 +++++++++ memory/00-index.md | 3 + memory/01-current-state.md | 15 +- .../295-package-consumer-acceptance-gate.md | 76 ++ .../PackageConsumerAcceptanceScriptTests.cs | 692 ++++++++++++++++++ 10 files changed, 1979 insertions(+), 3 deletions(-) create mode 100644 eng/package-consumer-acceptance.ps1 create mode 100644 eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj create mode 100644 eng/package-consumer-acceptance/Program.cs create mode 100644 goals/2026-08-04-package-consumer-acceptance-gate/README.md create mode 100644 memory/295-package-consumer-acceptance-gate.md create mode 100644 tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88a37274..abe8da61 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,3 +32,7 @@ jobs: - name: Test run: dotnet test FluxFlow.sln --configuration Release --no-build --logger "trx;LogFileName=test-results.trx" + + - name: Validate package consumer behavior + shell: pwsh + run: ./eng/package-consumer-acceptance.ps1 -PackPackages diff --git a/docs/38-release-validation.md b/docs/38-release-validation.md index f854408b..e4b568b1 100644 --- a/docs/38-release-validation.md +++ b/docs/38-release-validation.md @@ -77,9 +77,39 @@ helpers use work-directory-local package caches; this prevents an installed same-id/same-version package from substituting stale dependency metadata for the candidate archive. +After every archive and per-package dry run succeeds, execute the representative +behavioral consumer once over that complete candidate source: + +```powershell +./eng/package-consumer-acceptance.ps1 -PackageSource +``` + +The checked-in consumer is copied outside the repository and contains package +references only. It restores with a work-directory-local package cache and a +temporary package-source configuration that clears machine sources, lists the +candidate directory first, and uses the public source only for external +dependencies. After restore, the runner rejects project libraries, requires +the exact nine-package FluxFlow closure, and compares the SHA-256 value of every +restored FluxFlow archive with the corresponding candidate archive. Source +ordering alone is not accepted as proof. + +The executable then deserializes and runs a canonical Engine application +through normal dependency injection, runs a typed Fluent graph, and proves real +SQL-file durable-input and durable-output persistence after provider disposal +and reopen. It must emit the exact Engine, Fluent, durability, and final success +markers. A missing marker, archive, candidate-byte match, or behavior fails the +rehearsal. + +Normal CI runs the same gate with `-PackPackages` after the solution tests. That +mode packs the explicit nine-alias candidate closure from the already completed +Release build into a runner-owned temporary source. It does not rebuild runtime +projects, contact a network database, publish a package, or replace the +per-package assembly-load smoke. + Preparation and dry-run commands do not create a tag, release, or publication. Remove the temporary source and consumer caches only after recording the exact -preflight, prepare, archive, symbol, and `DRY_RUN_OK` counts. +preflight, prepare, archive, symbol, `DRY_RUN_OK`, verified candidate-package, +and behavioral acceptance counts. Before a real release, every manifest entry must carry `binaryCompatibilityBaseline`. A semantic version selects the exact published diff --git a/eng/package-consumer-acceptance.ps1 b/eng/package-consumer-acceptance.ps1 new file mode 100644 index 00000000..4e708171 --- /dev/null +++ b/eng/package-consumer-acceptance.ps1 @@ -0,0 +1,489 @@ +param( + [string] $PackageSource = "", + + [switch] $PackPackages, + + [string] $Configuration = "Release", + + [string] $Framework = "net8.0", + + [string] $ManifestPath = "eng/packages.json", + + [string] $FixturePath = "eng/package-consumer-acceptance", + + [string] $PublicPackageSource = "https://api.nuget.org/v3/index.json", + + [string] $WorkDirectory = "", + + [switch] $PrepareOnly +) + +$ErrorActionPreference = "Stop" + +$semanticVersionPattern = "^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$" +$requiredAliases = @( + "nodes", + "mapping", + "composition", + "engine", + "fluent", + "engine-durable-input", + "engine-durable-input-sqlfile", + "engine-durable-output", + "engine-durable-output-sqlfile" +) +$topLevelVersionProperties = [ordered]@{ + "engine" = "FluxFlowEngineVersion" + "fluent" = "FluxFlowFluentVersion" + "engine-durable-input-sqlfile" = "FluxFlowDurableInputSqlFileVersion" + "engine-durable-output-sqlfile" = "FluxFlowDurableOutputSqlFileVersion" +} +$requiredMarkers = @( + "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_FLUENT_OK=True", + "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", + "PACKAGE_ACCEPTANCE_OK=True" +) + +function Invoke-Step { + param( + [string] $Command, + [string[]] $Arguments, + [string] $FailureMessage + ) + + & $Command @Arguments + if ($LASTEXITCODE -ne 0) { + throw $FailureMessage + } +} + +function Invoke-CapturedStep { + param( + [string] $Command, + [string[]] $Arguments, + [string] $FailureMessage + ) + + $lines = @(& $Command @Arguments 2>&1 | ForEach-Object { $_.ToString() }) + foreach ($line in $lines) { + Write-Host $line + } + + if ($LASTEXITCODE -ne 0) { + throw $FailureMessage + } + + return $lines +} + +function Resolve-RepoPath { + param( + [string] $Root, + [string] $Path + ) + + if ([System.IO.Path]::IsPathRooted($Path)) { + return [System.IO.Path]::GetFullPath($Path) + } + + return [System.IO.Path]::GetFullPath((Join-Path $Root $Path)) +} + +function Assert-PackageSource { + param( + [string] $Source, + [string] $Name + ) + + if ([string]::IsNullOrWhiteSpace($Source)) { + throw "$Name is required." + } + + if ($Source -match "^[a-zA-Z][a-zA-Z0-9+.-]*://") { + return + } + + $sourcePath = [System.IO.Path]::GetFullPath($Source) + if (-not (Test-Path -LiteralPath $sourcePath -PathType Container)) { + throw "$Name '$sourcePath' was not found." + } +} + +function Read-ProjectVersion { + param([string] $ProjectPath) + + $versionNode = Select-Xml -Path $ProjectPath -XPath "/Project/PropertyGroup/Version" | + Select-Object -First 1 + if ($null -eq $versionNode -or [string]::IsNullOrWhiteSpace($versionNode.Node.InnerText)) { + throw "Project '$ProjectPath' does not declare Version." + } + + $version = $versionNode.Node.InnerText.Trim() + if ($version -notmatch $semanticVersionPattern) { + throw "Project '$ProjectPath' has invalid package version '$version'." + } + + return $version +} + +function Resolve-RequiredPackages { + param( + [string] $Root, + [string] $ResolvedManifestPath + ) + + $manifest = Get-Content -LiteralPath $ResolvedManifestPath -Raw | ConvertFrom-Json + $resolved = @() + foreach ($alias in $requiredAliases) { + $matches = @($manifest | Where-Object { + [string]::Equals($_.alias, $alias, [System.StringComparison]::Ordinal) + }) + if ($matches.Count -ne 1) { + throw "Package manifest must contain exactly one '$alias' entry." + } + + $entry = $matches[0] + if ([string]::IsNullOrWhiteSpace($entry.packageId) -or + [string]::IsNullOrWhiteSpace($entry.project)) { + throw "Package manifest entry '$alias' must define packageId and project." + } + + $projectPath = Resolve-RepoPath $Root $entry.project + if (-not (Test-Path -LiteralPath $projectPath -PathType Leaf)) { + throw "Package project '$projectPath' was not found." + } + + $resolved += [pscustomobject]@{ + Alias = $alias + PackageId = [string] $entry.packageId + Project = $projectPath + Version = Read-ProjectVersion $projectPath + } + } + + return $resolved +} + +function Get-ExactCandidateArchive { + param( + [string] $SourcePath, + [string] $PackageId, + [string] $Version + ) + + $expectedName = "$PackageId.$Version.nupkg" + $matches = @(Get-ChildItem -LiteralPath $SourcePath -File -Filter "*.nupkg" | + Where-Object { [string]::Equals($_.Name, $expectedName, [System.StringComparison]::OrdinalIgnoreCase) }) + if ($matches.Count -ne 1) { + throw "Candidate source '$SourcePath' must contain exactly one '$expectedName' archive." + } + + return $matches[0].FullName +} + +function Get-Sha256 { + param([string] $Path) + + $stream = [System.IO.File]::OpenRead($Path) + try { + $algorithm = [System.Security.Cryptography.SHA256]::Create() + try { + return ([System.BitConverter]::ToString($algorithm.ComputeHash($stream))).Replace("-", "") + } + finally { + $algorithm.Dispose() + } + } + finally { + $stream.Dispose() + } +} + +function Assert-RestoredFluxFlowPackages { + param( + [string] $AssetsPath, + [string] $SourcePath, + [string] $PackageCachePath, + [object[]] $RequiredPackages + ) + + if (-not (Test-Path -LiteralPath $AssetsPath -PathType Leaf)) { + throw "Consumer restore did not create '$AssetsPath'." + } + + $assets = Get-Content -LiteralPath $AssetsPath -Raw | ConvertFrom-Json + $projectLibraries = @($assets.libraries.PSObject.Properties | Where-Object { + [string]::Equals($_.Value.type, "project", [System.StringComparison]::OrdinalIgnoreCase) + }) + if ($projectLibraries.Count -ne 0) { + throw "Consumer restore resolved a project library instead of package-only dependencies." + } + + $fluxFlowLibraries = @($assets.libraries.PSObject.Properties | Where-Object { + $_.Name.StartsWith("FluxFlow.", [System.StringComparison]::Ordinal) + }) + $resolvedCoordinates = @($fluxFlowLibraries | ForEach-Object { $_.Name } | Sort-Object) + $requiredCoordinates = @($RequiredPackages | ForEach-Object { + "$($_.PackageId)/$($_.Version)" + } | Sort-Object) + $coordinateDifference = @(Compare-Object $requiredCoordinates $resolvedCoordinates) + if ($coordinateDifference.Count -ne 0) { + throw "Restored FluxFlow package closure does not match the explicit candidate closure: $($coordinateDifference -join '; ')." + } + + foreach ($library in $fluxFlowLibraries) { + $separator = $library.Name.LastIndexOf("/") + if ($separator -le 0 -or $separator -eq $library.Name.Length - 1) { + throw "Restored package coordinate '$($library.Name)' is invalid." + } + + $packageId = $library.Name.Substring(0, $separator) + $version = $library.Name.Substring($separator + 1) + $candidatePath = Get-ExactCandidateArchive $SourcePath $packageId $version + $cacheRelativePath = [string] $library.Value.path + if ([string]::IsNullOrWhiteSpace($cacheRelativePath)) { + throw "Restored package '$($library.Name)' does not declare a package-cache path." + } + + $cachedArchiveName = "$($packageId.ToLowerInvariant()).$($version.ToLowerInvariant()).nupkg" + $cachedArchivePath = Join-Path (Join-Path $PackageCachePath $cacheRelativePath) $cachedArchiveName + if (-not (Test-Path -LiteralPath $cachedArchivePath -PathType Leaf)) { + throw "Restored package archive '$cachedArchivePath' was not found." + } + + $candidateHash = Get-Sha256 $candidatePath + $cachedHash = Get-Sha256 $cachedArchivePath + if (-not [string]::Equals( + $candidateHash, + $cachedHash, + [System.StringComparison]::OrdinalIgnoreCase)) { + throw "Restored package '$($library.Name)' does not match candidate archive '$candidatePath'." + } + + Write-Host "PACKAGE_ACCEPTANCE_VERIFIED=$($library.Name)" + } +} + +function Format-CommandArgument { + param([string] $Argument) + + if ($Argument -notmatch "\s") { + return $Argument + } + + return "'" + $Argument.Replace("'", "''") + "'" +} + +function Format-CommandLine { + param( + [string] $Command, + [string[]] $Arguments + ) + + return (@($Command) + ($Arguments | ForEach-Object { Format-CommandArgument $_ })) -join " " +} + +function Escape-Xml { + param([string] $Value) + + return [System.Security.SecurityElement]::Escape($Value) +} + +if ($Configuration -notmatch "^[A-Za-z][A-Za-z0-9_-]*$") { + throw "Configuration '$Configuration' is not supported by package-consumer acceptance." +} + +if ($Framework -ne "net8.0") { + throw "Framework '$Framework' is not supported; the acceptance consumer targets net8.0." +} + +Assert-PackageSource $PublicPackageSource "Public package source" + +$repoRoot = (Get-Location).Path +$resolvedManifestPath = Resolve-RepoPath $repoRoot $ManifestPath +$resolvedFixturePath = Resolve-RepoPath $repoRoot $FixturePath +if (-not (Test-Path -LiteralPath $resolvedManifestPath -PathType Leaf)) { + throw "Package manifest '$resolvedManifestPath' was not found." +} +if (-not (Test-Path -LiteralPath $resolvedFixturePath -PathType Container)) { + throw "Consumer fixture '$resolvedFixturePath' was not found." +} + +$fixtureProject = Join-Path $resolvedFixturePath "FluxFlow.PackageConsumerAcceptance.csproj" +$fixtureProgram = Join-Path $resolvedFixturePath "Program.cs" +if (-not (Test-Path -LiteralPath $fixtureProject -PathType Leaf) -or + -not (Test-Path -LiteralPath $fixtureProgram -PathType Leaf)) { + throw "Consumer fixture must contain FluxFlow.PackageConsumerAcceptance.csproj and Program.cs." +} + +[xml] $fixtureXml = Get-Content -LiteralPath $fixtureProject -Raw +if (@($fixtureXml.SelectNodes("//ProjectReference")).Count -ne 0) { + throw "Consumer fixture cannot contain ProjectReference items." +} + +$requiredPackages = @(Resolve-RequiredPackages $repoRoot $resolvedManifestPath) +$ownsPackageSource = $PackPackages -and [string]::IsNullOrWhiteSpace($PackageSource) +if (-not $PackPackages -and [string]::IsNullOrWhiteSpace($PackageSource)) { + throw "PackageSource is required unless PackPackages is selected." +} + +$sourcePath = if ($ownsPackageSource) { + Join-Path ([System.IO.Path]::GetTempPath()) "fluxflow-package-candidates-$([Guid]::NewGuid().ToString('N'))" +} +else { + Resolve-RepoPath $repoRoot $PackageSource +} +$ownsWorkDirectory = [string]::IsNullOrWhiteSpace($WorkDirectory) +$workRoot = if ($ownsWorkDirectory) { + Join-Path ([System.IO.Path]::GetTempPath()) "fluxflow-package-consumer-acceptance-$([Guid]::NewGuid().ToString('N'))" +} +else { + Resolve-RepoPath $repoRoot $WorkDirectory +} +$consumerProject = Join-Path $workRoot "FluxFlow.PackageConsumerAcceptance.csproj" +$packageCache = Join-Path $workRoot "packages" +$nugetConfig = Join-Path $workRoot "NuGet.config" + +$versionArguments = @() +foreach ($entry in $topLevelVersionProperties.GetEnumerator()) { + $package = @($requiredPackages | Where-Object { + [string]::Equals($_.Alias, $entry.Key, [System.StringComparison]::Ordinal) + })[0] + $versionArguments += "-p:$($entry.Value)=$($package.Version)" +} + +$restoreArguments = @( + "restore", + $consumerProject, + "--no-cache", + "--packages", + $packageCache, + "--configfile", + $nugetConfig +) + $versionArguments +$buildArguments = @( + "build", + $consumerProject, + "--configuration", + $Configuration, + "--framework", + $Framework, + "--no-restore" +) + $versionArguments +$runArguments = @( + "run", + "--project", + $consumerProject, + "--configuration", + $Configuration, + "--framework", + $Framework, + "--no-build", + "--no-restore" +) + $versionArguments + +Write-Host "PACKAGE_ACCEPTANCE_PACKAGE_SOURCE=$sourcePath" +Write-Host "PACKAGE_ACCEPTANCE_WORK_DIR=$workRoot" +Write-Host "PACKAGE_ACCEPTANCE_PACKAGE_CACHE=$packageCache" +Write-Host "PACKAGE_ACCEPTANCE_PACK_PACKAGES=$($PackPackages.IsPresent)" +foreach ($package in $requiredPackages) { + Write-Host "PACKAGE_ACCEPTANCE_CANDIDATE=$($package.Alias)|$($package.PackageId)|$($package.Version)" +} +Write-Host "PACKAGE_ACCEPTANCE_RESTORE_COMMAND=$(Format-CommandLine 'dotnet' $restoreArguments)" +Write-Host "PACKAGE_ACCEPTANCE_BUILD_COMMAND=$(Format-CommandLine 'dotnet' $buildArguments)" +Write-Host "PACKAGE_ACCEPTANCE_RUN_COMMAND=$(Format-CommandLine 'dotnet' $runArguments)" + +if ($PrepareOnly) { + Write-Host "PACKAGE_ACCEPTANCE_PREPARED=True" + return +} + +try { + if ($PackPackages) { + if (Test-Path -LiteralPath $sourcePath -PathType Leaf) { + throw "Package source '$sourcePath' must be a directory." + } + New-Item -ItemType Directory -Path $sourcePath -Force | Out-Null + + foreach ($package in $requiredPackages) { + $packArguments = @( + "pack", + $package.Project, + "--configuration", + $Configuration, + "--no-build", + "--no-restore", + "--output", + $sourcePath + ) + Write-Host "PACKAGE_ACCEPTANCE_PACK_COMMAND=$(Format-CommandLine 'dotnet' $packArguments)" + Invoke-Step "dotnet" $packArguments "Candidate package creation failed for '$($package.PackageId)'." + } + } + elseif (-not (Test-Path -LiteralPath $sourcePath -PathType Container)) { + throw "Package source '$sourcePath' was not found." + } + + foreach ($package in $requiredPackages) { + $candidatePath = Get-ExactCandidateArchive $sourcePath $package.PackageId $package.Version + Write-Host "PACKAGE_ACCEPTANCE_ARCHIVE=$candidatePath" + } + + if (Test-Path -LiteralPath $workRoot) { + if ($ownsWorkDirectory) { + throw "Owned work directory '$workRoot' already exists." + } + + if ($null -ne (Get-ChildItem -LiteralPath $workRoot -Force | Select-Object -First 1)) { + throw "Caller-owned work directory '$workRoot' must be empty." + } + } + else { + New-Item -ItemType Directory -Path $workRoot -Force | Out-Null + } + + Copy-Item -LiteralPath $fixtureProject -Destination $consumerProject + Copy-Item -LiteralPath $fixtureProgram -Destination (Join-Path $workRoot "Program.cs") + + $escapedCandidateSource = Escape-Xml $sourcePath + $escapedPublicSource = Escape-Xml $PublicPackageSource + @" + + + + + + + + +"@ | Set-Content -LiteralPath $nugetConfig -Encoding utf8 + + Invoke-Step "dotnet" $restoreArguments "Package-consumer restore failed." + Assert-RestoredFluxFlowPackages ` + (Join-Path $workRoot "obj/project.assets.json") ` + $sourcePath ` + $packageCache ` + $requiredPackages + Invoke-Step "dotnet" $buildArguments "Package-consumer build failed." + $runOutput = @(Invoke-CapturedStep "dotnet" $runArguments "Package-consumer execution failed.") + + foreach ($marker in $requiredMarkers) { + $count = @($runOutput | Where-Object { + [string]::Equals($_, $marker, [System.StringComparison]::Ordinal) + }).Count + if ($count -ne 1) { + throw "Package consumer must emit '$marker' exactly once; observed $count." + } + } + + Write-Host "PACKAGE_ACCEPTANCE_COMPLETE=True" +} +finally { + if ($ownsWorkDirectory) { + Remove-Item -LiteralPath $workRoot -Recurse -Force -ErrorAction SilentlyContinue + } + if ($ownsPackageSource) { + Remove-Item -LiteralPath $sourcePath -Recurse -Force -ErrorAction SilentlyContinue + } +} diff --git a/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj b/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj new file mode 100644 index 00000000..fb69d0b0 --- /dev/null +++ b/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj @@ -0,0 +1,26 @@ + + + + Exe + net8.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + diff --git a/eng/package-consumer-acceptance/Program.cs b/eng/package-consumer-acceptance/Program.cs new file mode 100644 index 00000000..6483b610 --- /dev/null +++ b/eng/package-consumer-acceptance/Program.cs @@ -0,0 +1,282 @@ +using System.Text.Json; +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Model; +using FluxFlow.Data; +using FluxFlow.Engine; +using FluxFlow.Engine.DurableInput; +using FluxFlow.Engine.DurableInput.SqlFile; +using FluxFlow.Engine.DurableOutput; +using FluxFlow.Engine.DurableOutput.SqlFile; +using FluxFlow.Engine.Ports; +using FluxFlow.Fluent; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; + +await RunEngineScenarioAsync(); +Console.WriteLine("PACKAGE_ACCEPTANCE_ENGINE_OK=True"); + +await RunFluentScenarioAsync(); +Console.WriteLine("PACKAGE_ACCEPTANCE_FLUENT_OK=True"); + +await RunDurabilityScenarioAsync(); +Console.WriteLine("PACKAGE_ACCEPTANCE_DURABILITY_OK=True"); + +Console.WriteLine("PACKAGE_ACCEPTANCE_OK=True"); + +return 0; + +static async Task RunEngineScenarioAsync() +{ + const string definitionJson = """ + { + "Resources": {}, + "Workflows": { + "Acceptance": { + "Uppercase": { + "Type": "acceptance.uppercase" + } + } + } + } + """; + + var services = new ServiceCollection(); + services.AddFluxFlow( + ApplicationDefinitionJson.Deserialize(definitionJson), + options => options.StartWithHost = false); + services.AddFluxFlowComponents() + .AddRuntimeComponent("acceptance.uppercase", component => + { + component.UseFactory(_ => + { + var node = new UppercaseNode(); + return ValueTask.FromResult(ComponentInstance.Create( + node, + inputs: [ComponentPorts.Input("Input", node.Input)], + outputs: [ComponentPorts.Output("Output", node.Output)], + events: node.Events)); + }); + component.AddInput("Input"); + component.AddOutput("Output"); + }); + + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + var started = await application.StartAsync(); + Ensure(started.IsApplied, "The canonical package application was not applied."); + + var receive = application.Ports.ReceiveAsync( + "Acceptance.Uppercase.Output", + TimeSpan.FromSeconds(10)); + var sent = await application.Ports.SendAsync( + "Acceptance.Uppercase.Input", + FlowMessage.Create("package-json")); + Ensure(sent.Status == PortSendStatus.Accepted, "The canonical package input was not accepted."); + + var received = await receive; + Ensure(received.Status == PortReceiveStatus.Received, "The canonical package output was not received."); + Ensure( + string.Equals(received.Message?.Value, "PACKAGE-JSON", StringComparison.Ordinal), + "The canonical package output was not transformed exactly."); + + await application.StopAsync(); +} + +static async Task RunFluentScenarioAsync() +{ + var collector = new StringCollector(); + await using var graph = Flow + .From(new SingleValueSource("package-fluent")) + .Then(new UppercaseNode()) + .To(new CollectSink(collector)) + .Build(); + + await graph.StartAsync(); + await graph.Completion.WaitAsync(TimeSpan.FromSeconds(10)); + + Ensure(collector.Items.Count == 1, "The Fluent package graph did not produce exactly one value."); + Ensure( + string.Equals(collector.Items[0], "PACKAGE-FLUENT", StringComparison.Ordinal), + "The Fluent package graph did not transform the exact value."); +} + +static async Task RunDurabilityScenarioAsync() +{ + var dataDirectory = Path.Combine( + Path.GetTempPath(), + $"fluxflow-package-consumer-acceptance-{Guid.NewGuid():N}"); + var inputPath = Path.Combine(dataDirectory, "input.db"); + var outputPath = Path.Combine(dataDirectory, "output.db"); + Exception? primaryFailure = null; + + try + { + var occurredAt = new DateTimeOffset(2026, 8, 4, 8, 0, 0, TimeSpan.Zero); + var input = new DurableInputEnvelope( + ApplicationAddress.WorkflowPort("Acceptance", "Persist", "Input"), + "acceptance.input.v1", + isError: false, + JsonSerializer.SerializeToElement(new { value = "durable-input" }), + error: null, + new MessageId("package-input"), + new TraceId("package-input-trace"), + occurredAt, + occurredAt, + headers: new Dictionary { ["source"] = "package-consumer" }); + var output = new DurableOutputEnvelope( + ApplicationAddress.WorkflowPort("Acceptance", "Persist", "Output"), + "acceptance.output.v1", + isError: false, + JsonSerializer.SerializeToElement(new { value = "durable-output" }), + error: null, + new MessageId("package-output"), + new TraceId("package-output-trace"), + occurredAt, + occurredAt, + headers: new Dictionary { ["source"] = "package-consumer" }); + + await using (var writer = CreateDurabilityProvider(inputPath, outputPath)) + { + var inputStore = writer.GetRequiredService(); + var outputStore = writer.GetRequiredService(); + Ensure( + (await inputStore.EnqueueAsync(input)).Status == DurableInputEnqueueStatus.Enqueued, + "The package durable input was not newly persisted."); + Ensure( + (await outputStore.EnqueueAsync(output)).Status == DurableOutputEnqueueStatus.Enqueued, + "The package durable output was not newly persisted."); + } + + await using (var reader = CreateDurabilityProvider(inputPath, outputPath)) + { + var inputStore = reader.GetRequiredService(); + var outputStore = reader.GetRequiredService(); + var outputDelivery = reader.GetRequiredService(); + + Ensure( + (await inputStore.EnqueueAsync(input)).Status == DurableInputEnqueueStatus.AlreadyExists, + "The reopened input store did not retain the persisted identity."); + Ensure( + (await outputStore.EnqueueAsync(output)).Status == DurableOutputEnqueueStatus.AlreadyExists, + "The reopened output store did not retain the persisted identity."); + + var leaseAt = occurredAt.AddMinutes(1); + var inputLease = (await inputStore.LeaseAsync(new DurableInputLeaseRequest( + "package-consumer", + leaseAt, + leaseAt.AddMinutes(1), + maxCount: 1))).Single(); + var outputLease = await outputDelivery.TryLeaseAsync(new DurableOutputDeliveryLeaseRequest( + "package-consumer", + leaseAt, + leaseAt.AddMinutes(1))); + + Ensure(inputLease.Envelope.Key == input.Key, "The reopened input identity changed."); + Ensure( + string.Equals(inputLease.Envelope.ContractName, input.ContractName, StringComparison.Ordinal), + "The reopened input contract changed."); + Ensure( + string.Equals(inputLease.Envelope.Payload.GetRawText(), input.Payload.GetRawText(), StringComparison.Ordinal), + "The reopened input payload changed."); + Ensure(outputLease is not null, "The reopened output was not available for delivery."); + var persistedOutput = outputLease!; + Ensure(persistedOutput.Envelope.Key == output.Key, "The reopened output identity changed."); + Ensure( + string.Equals(persistedOutput.Envelope.ContractName, output.ContractName, StringComparison.Ordinal), + "The reopened output contract changed."); + Ensure( + string.Equals(persistedOutput.Envelope.Payload.GetRawText(), output.Payload.GetRawText(), StringComparison.Ordinal), + "The reopened output payload changed."); + } + } + catch (Exception exception) + { + primaryFailure = exception; + throw; + } + finally + { + try + { + if (Directory.Exists(dataDirectory)) + Directory.Delete(dataDirectory, recursive: true); + } + catch when (primaryFailure is not null) + { + // Preserve the scenario failure if cleanup also fails. + } + } +} + +static ServiceProvider CreateDurabilityProvider(string inputPath, string outputPath) +{ + var services = new ServiceCollection(); + services.AddFluxFlowSqlFileDurableInput(options => + { + options.DatabasePath = inputPath; + options.AllowAbsoluteDatabasePath = true; + }); + services.AddFluxFlowSqlFileDurableOutput(options => + { + options.DatabasePath = outputPath; + options.AllowAbsoluteDatabasePath = true; + }); + return services.BuildServiceProvider(); +} + +static void Ensure(bool condition, string message) +{ + if (!condition) + throw new InvalidOperationException(message); +} + +internal sealed class SingleValueSource(string value) : FlowSource +{ + protected override async Task RunAsync(CancellationToken cancellationToken) + { + await EmitAsync(FlowMessage.Create(value), cancellationToken).ConfigureAwait(false); + } +} + +internal sealed class UppercaseNode : FlowNode +{ + protected override async Task ProcessAsync(FlowMessage message) + { + await EmitAsync(message.With(message.Value.ToUpperInvariant()), Stopping) + .ConfigureAwait(false); + } +} + +internal sealed class CollectSink(StringCollector collector) : FlowNode +{ + protected override async Task ProcessAsync(FlowMessage message) + { + collector.Add(message.Value); + await EmitAsync(message, Stopping).ConfigureAwait(false); + } +} + +internal sealed class StringCollector +{ + private readonly List _items = []; + + public IReadOnlyList Items + { + get + { + lock (_items) + { + return _items.ToArray(); + } + } + } + + public void Add(string item) + { + lock (_items) + { + _items.Add(item); + } + } +} diff --git a/goals/2026-08-04-package-consumer-acceptance-gate/README.md b/goals/2026-08-04-package-consumer-acceptance-gate/README.md new file mode 100644 index 00000000..0487ea49 --- /dev/null +++ b/goals/2026-08-04-package-consumer-acceptance-gate/README.md @@ -0,0 +1,363 @@ +# Goal: Automate External Package-Consumer Acceptance + +## Status + +- State: ready for review +- Date: 2026-08-04 +- Repository: `C:\Projects\FluxFlow` +- Accepted base branch: `main` +- Accepted base commit: `d9432c81d2102fedaea2ef57ede85e89aac7020e` +- Working branch: `work/package-consumer-acceptance` +- Runtime feature scope: none +- Publication scope: none + +## Objective + +Turn the representative package-only execution proof used during the canonical +release train into a small, deterministic, repeatable acceptance gate. The gate +must prove that a real external consumer can restore only package artifacts, +compile against their public APIs, and execute the three most important +consumer paths: + +1. strict canonical JSON through normal dependency injection and the Engine + lifecycle; +2. the type-safe Fluent DSL; and +3. real SQL-file durable-input and durable-output persistence across container + disposal and store reopen. + +This is a release-confidence and packaging-boundary round. It must not change +runtime behavior, public APIs, packages, schemas, versions, or published state. +The existing per-package assembly-load smoke remains useful and must stay. The +new gate adds behavior proof for a deliberately small representative package +closure instead of attempting bespoke behavior tests for all 59 packages. + +## Current Evidence And Gap + +- `eng/package-consumer-smoke.ps1` already restores one archive into an + isolated cache, builds a temporary consumer, loads the package assembly, and + enumerates its types. +- The coordinated release train separately proved that a public-feed-only + executable could resolve Engine, run a Fluent graph, and perform SQL-file + durable-input/output operations. +- That executable was intentionally temporary and removed after the release, + so the behavioral proof is not currently a checked-in repeatable gate. +- The normal release workflow now validates package binary compatibility, + archive integrity, assembly loading, feed visibility, and release ordering. + It does not execute representative public APIs from the complete candidate + package closure. +- The complete package rehearsal is documented as an explicit manifest-wide + process but has no final behavioral consumer command. + +## Architecture Decision + +Add one checked-in external consumer fixture and one direct PowerShell runner: + +- `eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj` +- `eng/package-consumer-acceptance/Program.cs` +- `eng/package-consumer-acceptance.ps1` + +The fixture is not added to `FluxFlow.sln`. It is an external-consumer artifact, +contains package references only, and is copied to a fresh temporary directory +before restore/build/run so repository-wide build properties, project outputs, +and source references cannot become hidden inputs. + +The runner owns orchestration, validation, and cleanup. It uses an explicit +nine-alias package closure rather than reflection, project-graph discovery, or +a generalized dependency framework: + +1. `nodes`; +2. `mapping`; +3. `composition`; +4. `engine`; +5. `fluent`; +6. `engine-durable-input`; +7. `engine-durable-input-sqlfile`; +8. `engine-durable-output`; and +9. `engine-durable-output-sqlfile`. + +Those aliases are the complete maintained FluxFlow closure required by the +three acceptance scenarios. The manifest remains authoritative for package id, +project path, and project version. + +## Implementation Plan + +### 1. Checked-in external consumer + +Create a small `net8.0` executable that: + +1. references only the four top-level candidate packages needed by source code: + - `FluxFlow.Engine`; + - `FluxFlow.Fluent`; + - `FluxFlow.Engine.DurableInput.SqlFile`; and + - `FluxFlow.Engine.DurableOutput.SqlFile`; +2. obtains their versions from explicit MSBuild properties supplied by the + runner, avoiding copied hard-coded release versions; +3. contains no `ProjectReference`, repository path, generated source, dynamic + assembly loading, reflection, or test-framework dependency; +4. uses only public package APIs; +5. treats every missing/incorrect outcome as an exception and non-zero process + result; and +6. emits one exact success marker per scenario plus one final marker. + +### 2. Canonical Engine scenario + +The consumer must: + +1. deserialize a literal strict canonical document with exactly `Resources` + and `Workflows` through `ApplicationDefinitionJson`; +2. register the definition through normal `ServiceCollection` and + `AddFluxFlow(...)` with explicit lifecycle control; +3. explicitly register one small consumer-owned uppercase component without + scanning or reflection; +4. start `FluxFlowApplication` and require an applied result; +5. install the output receive before sending input through stable canonical + ports; +6. send one typed message and require the exact transformed value; +7. stop and dispose the application/provider cleanly; and +8. emit `PACKAGE_ACCEPTANCE_ENGINE_OK=True` only after all assertions pass. + +### 3. Fluent DSL scenario + +The consumer must: + +1. construct a small source-transform-sink graph with the public Fluent API; +2. use consumer-owned typed nodes and normal `FlowMessage` values; +3. start the graph, await bounded completion, and dispose it; +4. require the exact transformed sink result; and +5. emit `PACKAGE_ACCEPTANCE_FLUENT_OK=True` only after success. + +### 4. SQL-file durability scenario + +The consumer must: + +1. create a unique temporary data directory; +2. register SQL-file durable input and output stores through their flat public + DI callbacks using explicit allowed absolute paths; +3. resolve provider-neutral input/output store interfaces; +4. enqueue complete deterministic input and output envelopes and require the + exact `Enqueued` results; +5. dispose the first provider so no live connection or provider instance can + satisfy the next assertions; +6. construct a new provider over the same files; +7. prove both records persisted by requiring equivalent duplicate enqueue to + return `AlreadyExists` and by leasing each stored envelope through the + provider-neutral input/delivery interfaces; +8. compare exact identities, contracts, and JSON payloads; +9. dispose the reopened provider and remove the temporary data directory; and +10. emit `PACKAGE_ACCEPTANCE_DURABILITY_OK=True` only after cleanup-safe success. + +The scenario verifies local persistence and public provider wiring. It does not +start dispatch workers, contact a network server, or claim exactly-once +delivery. + +### 5. Acceptance runner + +`eng/package-consumer-acceptance.ps1` must: + +1. validate framework, configuration, manifest, fixture, source, and work-path + inputs before mutation; +2. reject a fixture containing `ProjectReference` before restore; +3. resolve the nine explicit aliases from `eng/packages.json` and their exact + versions from the declared project files; +4. support two explicit modes: + - caller-supplied `-PackageSource` containing an already completed package + rehearsal; and + - `-PackPackages`, which packs the nine declared projects from an already + completed controlled build into a runner-owned temporary source; +5. reject ambiguous use of both an absent source and no packing request; +6. require one exact candidate `.nupkg` for every declared closure package; +7. copy the checked-in fixture into a fresh isolated work directory; +8. restore with `--no-cache`, a work-directory-local `--packages` root, the + candidate source first, and the public source only for external packages; +9. pass the four exact top-level versions as MSBuild properties; +10. inspect the restored `project.assets.json` and, for every resolved + `FluxFlow.*` package, require a matching candidate archive and an exact + SHA-256 match with the archive stored in the isolated package root; +11. build with `--no-restore`, run with `--no-build`, and require the three + scenario markers plus `PACKAGE_ACCEPTANCE_OK=True` exactly once; +12. print stable preparation, resolved-version, source/cache, command, package + verification, and success markers suitable for tests and CI evidence; +13. provide `-PrepareOnly` for deterministic structural verification without + packing or process execution; +14. delete only directories it owns in `finally`; +15. retain an explicitly caller-provided work directory for diagnostics and + never delete a caller-owned package source; and +16. add no dependency, reflection, assembly scan, network inference, or broad + reusable framework. + +### 6. Automation and rehearsal integration + +1. Add one normal CI step after the complete solution tests. +2. Invoke the runner with `-PackPackages`; reuse the existing controlled Release + build and never build runtime projects through project references in the + consumer. +3. Keep the existing solution restore/build/test steps and their order. +4. Keep both real network-provider suites release-only; the new gate uses only + local SQL-file providers and requires no credentials, container, port, or + external server. +5. Update the complete package rehearsal guide to invoke the acceptance runner + once after every candidate archive and per-package dry run succeeds. +6. Do not add the manifest-wide consumer to each single-package publication + workflow because one package workflow does not contain the complete + candidate closure. + +### 7. Focused verification + +Add release tests proving: + +- the checked-in fixture exists, targets `net8.0`, contains the four expected + package references, uses version properties, and contains no project + references; +- source contains the exact Engine, Fluent, durability, and final markers; +- the runner has the exact nine-alias closure and no manifest-wide implicit + discovery; +- `-PrepareOnly` resolves exact manifest/project versions without creating + package or work directories; +- missing candidate archives fail before restore/run; +- a fixture with a project reference fails before restore/run; +- restore uses `--no-cache`, one isolated `--packages` root, candidate source + first, and explicit version properties; +- candidate hash verification covers every restored `FluxFlow.*` package and + fails on missing/mismatched archives; +- build and run are each invoked once and require exact success markers; +- owned temporary directories are removed on success and failure; +- a caller-owned work directory and package source remain; and +- CI invokes the runner after solution tests with `-PackPackages` exactly once. + +Use the existing xUnit/Shouldly release-test conventions. Fake process commands +must remain deterministic and network-free. Run a real package-only acceptance +execution separately as final proof. + +### 8. Documentation and memory + +Update: + +- `docs/38-release-validation.md` with the two package checks, the one-command + behavioral gate, its candidate-byte verification, and rehearsal ordering; +- `docs/README.md` only if a new documentation page is added (none is planned); +- `memory/00-index.md`; +- `memory/01-current-state.md`; +- one new numbered memory record; and +- this goal with exact completion evidence. + +No package README or changelog entry is required because consumer-facing +runtime behavior and package versions do not change. + +## Non-Negotiable Principles + +1. KISS, SRP, explicit data flow, and a small package-validation boundary. +2. No reflection, assembly scanning, service locator, hidden project fallback, + global package cache, generated application code, or generalized framework. +3. No runtime or public API change. +4. No package, schema, dependency, target-framework, or version change. +5. No package publication, tag, or release operation. +6. No claim that four scenarios behaviorally cover all 59 packages. +7. Keep the existing per-package restore/load smoke test. +8. Candidate bytes must be proven, not inferred from source ordering. +9. All work and data directories are bounded and have explicit ownership. +10. Preserve unrelated work and avoid broad cleanup. +11. Update goal, documentation, documentation-site content, and memory. +12. Use the normal branch, commit, pull-request, checks, review, and merge path. + +## Explicit Non-Goals + +- no workflow-engine feature or component; +- no transport, broker, HTTP, AI, IoT, or network-server scenario; +- no T-SQL provider execution; +- no behavioral scenario for every package; +- no replacement of unit, integration, conformance, archive, API, or binary + compatibility tests; +- no package-source mapping framework or dependency graph engine; +- no release workflow publication change; +- no new health/readiness API; +- no unrelated refactoring. + +## Validation Sequence + +1. Run focused release tests during implementation. +2. Run structural `-PrepareOnly` proof. +3. Run the runner against a real isolated set of candidate archives produced + from the controlled Release build. +4. Require all four exact consumer markers. +5. Run the complete `FluxFlow.Release.Tests` project. +6. Run the complete solution test suite in Release configuration. +7. Run the complete solution Release build with continuous-integration flags + and zero warnings. +8. Run formatting, vulnerable-package, diff/whitespace, scope, and neutral-name + checks. +9. Confirm no runtime source, public API baseline, package version, changelog, + tag, release, or public package state changed. +10. Remove runner-owned candidate, consumer, cache, build, and SQL-file + artifacts and confirm no residue remains. + +## Review And Closeout + +1. Commit only goal-owned files with a neutral subject. +2. Push the branch and open a ready pull request against `main`. +3. Require successful remote checks on the exact head, including the new real + package-consumer acceptance step. +4. Resolve every actionable finding without bypassing policy. +5. Merge normally using the repository's established strategy. +6. Synchronize local `main` with `origin/main` and require a clean worktree. +7. Mark this goal complete only after implementation, validation, + documentation, memory, review, merge, cleanup, and synchronization finish. + +## Acceptance Criteria + +The goal is complete only when: + +- one checked-in package-only consumer executes canonical Engine, Fluent, and + SQL-file persistence/reopen scenarios; +- its project contains package references only; +- the consumer runs from a fresh external work directory and isolated package + cache; +- every restored FluxFlow package exactly matches a candidate archive; +- missing or mismatched candidates, project references, scenario failures, and + missing markers fail closed; +- CI invokes the gate automatically from an already completed Release build; +- the complete rehearsal guide invokes the same gate once over its full + candidate source; +- the existing per-package assembly smoke remains intact; +- focused and full validation pass with exact evidence; +- runtime source, APIs, package versions, dependencies, schemas, and public + state remain unchanged; +- goal, documentation, documentation site, and memory are updated; and +- local `main` is clean and synchronized after normal review and merge. + +## Completion Evidence + +### Implementation + +- Added one checked-in `net8.0` package-only console consumer with the four + explicit top-level package references and no `ProjectReference`. +- Added one explicit runner over the maintained nine-package closure. Restore + uses a cleared, work-local source configuration and isolated package cache; + every resolved FluxFlow archive is checked against the candidate archive by + SHA-256 before build or execution. +- Added canonical JSON/DI Engine, typed Fluent, and SQL-file durability + dispose/reopen scenarios with four exact success markers. +- Added the normal CI gate, complete-rehearsal documentation, 12 focused + release contracts, and memory updates. The existing per-package smoke is + unchanged. + +### Local validation + +- Windows PowerShell real execution: nine candidates packed and verified; + Engine, Fluent, durability, final, and completion markers passed. +- PowerShell 7 real execution: the same nine candidates and all markers passed. +- Focused `PackageConsumerAcceptanceScriptTests`: 12 passed, 0 warnings. +- Complete `FluxFlow.Release.Tests`: 163 passed, 0 warnings. +- Controlled Release build: 134 projects, 0 errors, 0 warnings. +- Complete Release solution tests: 2,531 passed across 66 projects, 0 warnings. +- Solution formatting and standalone-consumer whitespace checks passed. +- Full transitive vulnerable-package audit reported no vulnerable packages. +- Test/source pairing audit inspected 766 source files and 318 test files in + 2,868 ms; it was retained as static routing evidence rather than a coverage + claim. +- Runner-owned real candidate and consumer directories were removed after + execution. No package was published and no release state was changed. + +### Review and merge + +Pending pull-request checks, normal review, merge, and synchronized-main +closeout. The goal remains open until those steps complete. diff --git a/memory/00-index.md b/memory/00-index.md index 69e73fc8..13f1df66 100644 --- a/memory/00-index.md +++ b/memory/00-index.md @@ -745,6 +745,9 @@ This folder records the extraction work for `FluxFlow.Engine`. - `294-binary-compatibility-release-gate.md`: explicit per-package binary baselines, fail-closed manifest resolution, single-path compatibility-aware release packaging, validation evidence, and the no-publication boundary. +- `295-package-consumer-acceptance-gate.md`: isolated package-only Engine, + Fluent, and SQL-file durability execution, exact candidate-byte verification, + automatic CI/rehearsal integration, and the no-runtime-change boundary. - `report.md`: original FluxMq migration spike report supplied for review. - `legacy-docs/`: historical pre-cleanup docs; current decisions override older API descriptions in this folder. diff --git a/memory/01-current-state.md b/memory/01-current-state.md index 3c05bfba..d1aa218b 100644 --- a/memory/01-current-state.md +++ b/memory/01-current-state.md @@ -1,7 +1,7 @@ # Current State -Updated 2026-08-03 after the coordinated canonical package release train, its -concurrency-reliability hardening, and the binary-compatibility release gate. +Updated 2026-08-04 after the coordinated canonical package release train and +its concurrency, binary-compatibility, and external-consumer reliability gates. ## Published Package Boundary @@ -24,6 +24,12 @@ concurrency-reliability hardening, and the binary-compatibility release gate. archive inspection or publication. Explicit JSON `null` is reserved for a genuine first release and skips only the unavailable prior-package comparison. +- Normal CI and complete package rehearsals use one checked-in external + package-only consumer for representative behavior. Its isolated restore + rejects project libraries and proves every restored FluxFlow archive exactly + matches the candidate source before executing canonical Engine, Fluent, and + SQL-file durable-input/output reopen scenarios. The existing per-package + restore/load smoke remains the inventory-wide check. - The complete execution, workflow run ids, recoveries, and cleanup evidence are recorded in `memory/292-coordinated-release-train.md`. @@ -270,6 +276,11 @@ concurrency-reliability hardening, and the binary-compatibility release gate. ## Documentation And Verification +- The package-consumer acceptance round changes release/CI tooling, a + checked-in external fixture, release governance tests, documentation, goals, + and memory only. It changes no runtime assembly, API, schema, dependency, + package version, changelog, tag, release, or published artifact. Detailed + evidence is recorded in `memory/295-package-consumer-acceptance-gate.md`. - The binary-compatibility release-gate round changes release policy, tooling, workflow, focused governance tests, documentation, and memory only. It does not change runtime assemblies, schemas, dependencies, public APIs, package diff --git a/memory/295-package-consumer-acceptance-gate.md b/memory/295-package-consumer-acceptance-gate.md new file mode 100644 index 00000000..e59ce80c --- /dev/null +++ b/memory/295-package-consumer-acceptance-gate.md @@ -0,0 +1,76 @@ +# Package-Consumer Acceptance Gate + +Date: 2026-08-04 + +## Outcome + +FluxFlow now retains the representative external-consumer execution proof that +was previously performed only during the coordinated release train. Normal CI +and complete package rehearsals can restore package artifacts into a fresh +consumer, verify the exact candidate bytes, compile against public APIs, and +execute the canonical Engine, Fluent DSL, and local durability paths. + +## Small Boundary + +- `eng/package-consumer-acceptance/` is a checked-in `net8.0` console consumer. + It has four package references, versioned through runner-supplied properties, + and no project reference, test framework, repository path, reflection, or + generated application code. +- `eng/package-consumer-acceptance.ps1` owns orchestration. It names the exact + nine-package FluxFlow dependency closure, resolves identity and version from + the existing manifest/project files, and either consumes a completed + rehearsal source or packs that closure from an already completed Release + build. +- Restore occurs in a new external work directory with `--no-cache`, a local + package root, and a temporary source configuration containing ``, the + candidate source first, and the public source for external dependencies. +- The runner rejects project libraries and requires the restored FluxFlow + coordinates to equal the explicit closure. Each cached FluxFlow `.nupkg` + must have the same SHA-256 value as its candidate-source archive. +- The existing per-package consumer smoke remains unchanged. It provides broad + restore/load coverage; the new gate provides narrow representative behavior. + +## Consumer Scenarios + +1. Strict canonical JSON is deserialized, registered through ordinary DI, + started through `FluxFlowApplication`, exercised through stable input/output + ports, and stopped. +2. A consumer-owned typed source/transform/sink graph runs through the public + Fluent DSL and produces the exact expected value. +3. Provider-neutral durable input and output envelopes are persisted through + the SQL-file providers, the first container is disposed, a new container + reopens the files, idempotent duplicate results are required, and both exact + envelopes are leased from persisted state. + +Each scenario and the overall executable emit an exact success marker. The +runner requires every marker exactly once. + +## Automation + +Normal CI invokes the runner with `-PackPackages` after the complete solution +tests. A complete manifest rehearsal invokes the same runner once with its +already-populated candidate source after all archive inspections and +per-package dry runs succeed. The individual publication workflow remains +single-package and does not pretend to own a complete candidate closure. + +## Verification + +- The real runner passed under Windows PowerShell and PowerShell 7. Both runs + packed and hash-verified the exact nine-package closure and emitted the + Engine, Fluent, durability, final, and completion markers. +- The 12 focused package-consumer contracts passed, and the complete release + test project passed 163 tests with zero warnings. +- The controlled Release build passed 134 projects with zero warnings and zero + errors; the complete solution passed 2,531 tests across 66 projects with + zero warnings. +- Solution formatting, standalone-consumer whitespace, and the full transitive + vulnerable-package audit passed. +- Remote checks, merge, and synchronized-main closeout remain pending. + +## Boundaries + +This round adds release/CI validation, a package-only fixture, focused +governance tests, documentation, goal records, and memory only. It does not +change runtime source, public APIs, public API baselines, package projects, +dependencies, schemas, package versions, changelog entries, tags, repository +releases, or public package state. diff --git a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs new file mode 100644 index 00000000..0fd5162f --- /dev/null +++ b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs @@ -0,0 +1,692 @@ +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Xml.Linq; +using Shouldly; +using Xunit; + +namespace FluxFlow.Release.Tests; + +[Collection(ReleaseProcessCollection.Name)] +public sealed class PackageConsumerAcceptanceScriptTests +{ + private const string FixtureDirectory = "package-consumer-acceptance"; + private const string FixtureProject = "FluxFlow.PackageConsumerAcceptance.csproj"; + + private static readonly IReadOnlyDictionary ExpectedPackageVersions = + new Dictionary(StringComparer.Ordinal) + { + ["FluxFlow.Engine"] = "$(FluxFlowEngineVersion)", + ["FluxFlow.Engine.DurableInput.SqlFile"] = "$(FluxFlowDurableInputSqlFileVersion)", + ["FluxFlow.Engine.DurableOutput.SqlFile"] = "$(FluxFlowDurableOutputSqlFileVersion)", + ["FluxFlow.Fluent"] = "$(FluxFlowFluentVersion)" + }; + + private static readonly string[] RequiredAliases = + [ + "nodes", + "mapping", + "composition", + "engine", + "fluent", + "engine-durable-input", + "engine-durable-input-sqlfile", + "engine-durable-output", + "engine-durable-output-sqlfile" + ]; + + [Fact] + public void Acceptance_fixture_is_a_net8_package_only_consumer() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var projectPath = GetFixturePath(root, FixtureProject); + + File.Exists(projectPath).ShouldBeTrue(); + var project = XDocument.Load(projectPath); + project.Descendants().Single(element => element.Name.LocalName == "TargetFramework") + .Value.ShouldBe("net8.0"); + + var packageVersions = project + .Descendants() + .Where(element => element.Name.LocalName == "PackageReference") + .ToDictionary( + element => element.Attribute("Include")!.Value, + element => element.Attribute("Version")!.Value, + StringComparer.Ordinal); + + packageVersions.ShouldBe(ExpectedPackageVersions); + project.Descendants().ShouldNotContain(element => element.Name.LocalName == "ProjectReference"); + + var projectText = File.ReadAllText(projectPath); + projectText.ShouldNotContain("..\\"); + projectText.ShouldNotContain("../"); + projectText.ShouldNotContain("/src/"); + projectText.ShouldNotContain("\\src\\"); + } + + [Fact] + public void Acceptance_fixture_exercises_engine_fluent_and_sql_file_reopen_paths() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(GetFixturePath(root, "Program.cs")); + + CountOccurrences(source, "PACKAGE_ACCEPTANCE_ENGINE_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_FLUENT_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_DURABILITY_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_OK=True").ShouldBe(1); + source.ShouldNotContain("System.Reflection"); + source.ShouldNotContain("Assembly.Load("); + source.ShouldNotContain("GetAssemblies("); + + source.ShouldContain("ApplicationDefinitionJson.Deserialize(definitionJson)"); + source.ShouldContain("services.AddFluxFlow("); + source.ShouldContain("GetRequiredService()"); + source.ShouldContain("Ensure(started.IsApplied"); + source.IndexOf("Ports.ReceiveAsync", StringComparison.Ordinal).ShouldBeLessThan( + source.IndexOf("Ports.SendAsync(", StringComparison.Ordinal)); + source.ShouldContain("PortSendStatus.Accepted"); + source.ShouldContain("PortReceiveStatus.Received"); + source.ShouldContain("PACKAGE-JSON"); + + source.ShouldContain("var graph = Flow"); + source.ShouldContain(".From(new SingleValueSource("); + source.ShouldContain(".Then(new UppercaseNode())"); + source.ShouldContain(".To(new CollectSink(collector))"); + source.ShouldContain("await graph.StartAsync()"); + source.ShouldContain("await graph.Completion.WaitAsync("); + source.ShouldContain("PACKAGE-FLUENT"); + + source.ShouldContain("AddFluxFlowSqlFileDurableInput"); + source.ShouldContain("AddFluxFlowSqlFileDurableOutput"); + source.ShouldContain("GetRequiredService()"); + source.ShouldContain("GetRequiredService()"); + source.ShouldContain("GetRequiredService()"); + source.ShouldContain("DurableInputEnqueueStatus.Enqueued"); + source.ShouldContain("DurableOutputEnqueueStatus.Enqueued"); + source.ShouldContain("DurableInputEnqueueStatus.AlreadyExists"); + source.ShouldContain("DurableOutputEnqueueStatus.AlreadyExists"); + source.IndexOf("await using (var writer", StringComparison.Ordinal).ShouldBeLessThan( + source.IndexOf("await using (var reader", StringComparison.Ordinal)); + source.ShouldContain("inputStore.LeaseAsync("); + source.ShouldContain("outputDelivery.TryLeaseAsync("); + source.ShouldContain("inputLease.Envelope.Payload.GetRawText()"); + source.ShouldContain("persistedOutput.Envelope.Payload.GetRawText()"); + } + + [Fact] + public void Acceptance_gate_is_part_of_the_complete_ci_rehearsal() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var workflow = File.ReadAllText(Path.Combine(root, ".github", "workflows", "ci.yml")); + + CountOccurrences( + workflow, + "./eng/package-consumer-acceptance.ps1 -PackPackages").ShouldBe(1); + } + + [Fact] + public async Task Acceptance_script_prepare_only_resolves_exact_closure_without_mutation() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root, createCandidateSource: false); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + fixture.CreateEnvironment(), + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory, + "-PrepareOnly"); + + result.ExitCode.ShouldBe(0, result.ToString()); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_PACK_PACKAGES=False"); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_PREPARED=True"); + ReadLines(result.StandardOutput) + .Where(line => line.StartsWith("PACKAGE_ACCEPTANCE_CANDIDATE=", StringComparison.Ordinal)) + .ShouldBe(fixture.Packages.Select(package => + $"PACKAGE_ACCEPTANCE_CANDIDATE={package.Alias}|{package.PackageId}|{package.Version}")); + + var restoreCommand = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_RESTORE_COMMAND="); + restoreCommand.ShouldContain(" --no-cache --packages "); + restoreCommand.ShouldContain($"--packages {fixture.PackageCache}"); + restoreCommand.ShouldContain($"--configfile {Path.Combine(fixture.WorkDirectory, "NuGet.config")}"); + restoreCommand.ShouldNotContain("--source"); + AssertTopLevelVersionArguments(restoreCommand, fixture.Packages); + + Directory.Exists(fixture.PackageSource).ShouldBeFalse(); + Directory.Exists(fixture.WorkDirectory).ShouldBeFalse(); + File.Exists(fixture.DotnetArgumentsPath).ShouldBeFalse(); + } + + [Fact] + public async Task Acceptance_script_rejects_a_fixture_project_reference_before_process_execution() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root, createCandidateSource: false); + var rejectedFixture = Directory.CreateDirectory(Path.Combine(fixture.Root, "rejected-fixture")).FullName; + var project = XDocument.Load(GetFixturePath(root, FixtureProject)); + project.Root!.Add(new XElement( + "ItemGroup", + new XElement("ProjectReference", new XAttribute("Include", "repository.csproj")))); + project.Save(Path.Combine(rejectedFixture, FixtureProject)); + File.Copy(GetFixturePath(root, "Program.cs"), Path.Combine(rejectedFixture, "Program.cs")); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + fixture.CreateEnvironment(), + "-FixturePath", + rejectedFixture, + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory, + "-PrepareOnly"); + + result.ExitCode.ShouldNotBe(0); + result.ToString().ShouldContain("cannot contain ProjectReference"); + Directory.Exists(fixture.PackageSource).ShouldBeFalse(); + Directory.Exists(fixture.WorkDirectory).ShouldBeFalse(); + File.Exists(fixture.DotnetArgumentsPath).ShouldBeFalse(); + } + + [Theory] + [InlineData("nodes")] + [InlineData("engine-durable-output-sqlfile")] + public async Task Acceptance_script_rejects_incomplete_candidate_closure_before_restore( + string missingAlias) + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root); + var missing = fixture.Packages.Single(package => package.Alias == missingAlias); + File.Delete(fixture.GetCandidateArchive(missing)); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + fixture.CreateEnvironment(), + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory); + + result.ExitCode.ShouldNotBe(0); + result.ToString().ShouldContain($"{missing.PackageId}.{missing.Version}.nupkg"); + result.ToString().ShouldContain("must contain exactly one"); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + File.Exists(fixture.DotnetArgumentsPath).ShouldBeFalse(); + Directory.Exists(fixture.WorkDirectory).ShouldBeFalse(); + Directory.Exists(fixture.PackageSource).ShouldBeTrue(); + } + + [Fact] + public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retained_isolated_workdir() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + fixture.CreateEnvironment(), + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory); + + result.ExitCode.ShouldBe(0, result.ToString()); + var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); + invocations.Length.ShouldBe(3); + invocations[0].ShouldStartWith("restore "); + invocations[1].ShouldStartWith("build "); + invocations[2].ShouldStartWith("run "); + + CountOccurrences(invocations[0], "--no-cache").ShouldBe(1); + CountOccurrences(invocations[0], "--packages").ShouldBe(1); + CountOccurrences(invocations[0], "--configfile").ShouldBe(1); + invocations[0].ShouldContain($"--packages {fixture.PackageCache}"); + invocations[0].ShouldContain($"--configfile {Path.Combine(fixture.WorkDirectory, "NuGet.config")}"); + invocations[0].ShouldNotContain("--source"); + invocations[1].ShouldContain("--no-restore"); + invocations[2].ShouldContain("--no-build"); + invocations[2].ShouldContain("--no-restore"); + foreach (var invocation in invocations) + AssertTopLevelVersionArguments(invocation, fixture.Packages); + + var sourceConfig = XDocument.Load(Path.Combine(fixture.WorkDirectory, "NuGet.config")); + var packageSources = sourceConfig + .Descendants("packageSources") + .Single() + .Elements() + .ToArray(); + packageSources.Select(element => element.Name.LocalName).ShouldBe(["clear", "add", "add"]); + packageSources.Skip(1).Select(element => element.Attribute("key")!.Value) + .ShouldBe(["candidate", "public"]); + packageSources.Skip(1).Select(element => element.Attribute("value")!.Value) + .ShouldBe([fixture.PackageSource, "https://api.nuget.org/v3/index.json"]); + + ReadLines(result.StandardOutput) + .Where(line => line.StartsWith("PACKAGE_ACCEPTANCE_VERIFIED=", StringComparison.Ordinal)) + .OrderBy(line => line, StringComparer.Ordinal) + .ShouldBe(fixture.Packages + .Select(package => $"PACKAGE_ACCEPTANCE_VERIFIED={package.PackageId}/{package.Version}") + .OrderBy(line => line, StringComparer.Ordinal)); + foreach (var marker in RequiredMarkers()) + CountOccurrences(result.StandardOutput, marker).ShouldBe(1); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + + Directory.Exists(fixture.WorkDirectory).ShouldBeTrue(); + Directory.Exists(fixture.PackageSource).ShouldBeTrue(); + foreach (var package in fixture.Packages) + { + var cachedArchive = Path.Combine( + fixture.PackageCache, + package.PackageId.ToLowerInvariant(), + package.Version.ToLowerInvariant(), + $"{package.PackageId.ToLowerInvariant()}.{package.Version.ToLowerInvariant()}.nupkg"); + File.ReadAllBytes(cachedArchive).ShouldBe(File.ReadAllBytes(fixture.GetCandidateArchive(package))); + } + } + + public static TheoryData InvalidResolutionModes => + new() + { + { "project", "resolved a project library" }, + { "hash", "does not match candidate archive" } + }; + + [Theory] + [MemberData(nameof(InvalidResolutionModes))] + public async Task Acceptance_script_rejects_project_or_non_candidate_resolution( + string mode, + string expectedFailure) + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root); + var environment = fixture.CreateEnvironment(); + environment["FAKE_DOTNET_PROJECT_LIBRARY"] = mode == "project" ? "true" : null; + environment["FAKE_DOTNET_MISMATCH_PACKAGE"] = mode == "hash" ? "FluxFlow.Engine" : null; + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + environment, + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory); + + result.ExitCode.ShouldNotBe(0); + result.ToString().ShouldContain(expectedFailure); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); + invocations.ShouldHaveSingleItem().ShouldStartWith("restore "); + Directory.Exists(fixture.WorkDirectory).ShouldBeTrue(); + Directory.Exists(fixture.PackageSource).ShouldBeTrue(); + } + + [Fact] + public async Task Acceptance_script_cleans_owned_workdir_after_missing_marker_failure() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root); + var environment = fixture.CreateEnvironment(); + environment["FAKE_DOTNET_OMIT_MARKER"] = "PACKAGE_ACCEPTANCE_DURABILITY_OK=True"; + var candidateBytes = fixture.Packages.ToDictionary( + package => package.PackageId, + package => File.ReadAllBytes(fixture.GetCandidateArchive(package)), + StringComparer.Ordinal); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + environment, + "-PackageSource", + fixture.PackageSource); + + result.ExitCode.ShouldNotBe(0); + result.ToString().ShouldContain("PACKAGE_ACCEPTANCE_DURABILITY_OK=True"); + result.ToString().ShouldContain("observed 0"); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + File.ReadAllLines(fixture.DotnetArgumentsPath).Length.ShouldBe(3); + + var ownedWorkDirectory = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_WORK_DIR="); + Directory.Exists(ownedWorkDirectory).ShouldBeFalse(); + Directory.Exists(fixture.PackageSource).ShouldBeTrue(); + foreach (var package in fixture.Packages) + File.ReadAllBytes(fixture.GetCandidateArchive(package)).ShouldBe(candidateBytes[package.PackageId]); + } + + [Fact] + public async Task Acceptance_script_pack_mode_cleans_owned_source_and_workdir_after_success() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root, createCandidateSource: false); + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + fixture.CreateEnvironment(), + "-PackPackages"); + + result.ExitCode.ShouldBe(0, result.ToString()); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_PACK_PACKAGES=True"); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); + invocations.Length.ShouldBe(12); + invocations.Take(9).ShouldAllBe(invocation => invocation.StartsWith("pack ", StringComparison.Ordinal)); + invocations[9].ShouldStartWith("restore "); + invocations[10].ShouldStartWith("build "); + invocations[11].ShouldStartWith("run "); + + var ownedPackageSource = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_PACKAGE_SOURCE="); + var ownedWorkDirectory = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_WORK_DIR="); + Directory.Exists(ownedPackageSource).ShouldBeFalse(); + Directory.Exists(ownedWorkDirectory).ShouldBeFalse(); + } + + private static string GetFixturePath(string root, string fileName) + => Path.Combine(root, "eng", FixtureDirectory, fileName); + + private static RequiredPackage[] ReadRequiredPackages(string root) + { + var manifest = PackageManifest.Read(root); + return RequiredAliases.Select(alias => + { + var entry = manifest.Single(package => package.Alias == alias); + var projectPath = Path.Combine(root, NormalizePath(entry.Project)); + var project = XDocument.Load(projectPath); + var version = project + .Descendants() + .Where(element => element.Name.LocalName == "Version") + .Select(element => element.Value.Trim()) + .First(value => value.Length > 0); + return new RequiredPackage(alias, entry.PackageId, version, projectPath); + }).ToArray(); + } + + private static void AssertTopLevelVersionArguments( + string invocation, + IReadOnlyCollection packages) + { + foreach (var expected in ExpectedPackageVersions) + { + var alias = expected.Key switch + { + "FluxFlow.Engine" => "engine", + "FluxFlow.Fluent" => "fluent", + "FluxFlow.Engine.DurableInput.SqlFile" => "engine-durable-input-sqlfile", + "FluxFlow.Engine.DurableOutput.SqlFile" => "engine-durable-output-sqlfile", + _ => throw new InvalidOperationException($"Unexpected top-level package '{expected.Key}'.") + }; + var package = packages.Single(candidate => candidate.Alias == alias); + var propertyName = expected.Value.TrimStart('$', '(').TrimEnd(')'); + var expectedArgument = $"-p:{propertyName}={package.Version}"; + var arguments = invocation.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var exactCount = arguments.Count(argument => argument == expectedArgument); + var commandWrapperCount = arguments + .Zip(arguments.Skip(1)) + .Count(pair => pair.First == $"-p:{propertyName}" && pair.Second == package.Version); + (exactCount + commandWrapperCount).ShouldBe(1, invocation); + } + } + + private static string[] RequiredMarkers() + => + [ + "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_FLUENT_OK=True", + "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", + "PACKAGE_ACCEPTANCE_OK=True" + ]; + + private static string[] ReadLines(string text) + => text.Split( + ['\r', '\n'], + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + private static string ReadOutputValue(string output, string prefix) + { + var line = ReadLines(output).Single(line => line.StartsWith(prefix, StringComparison.Ordinal)); + return line[prefix.Length..]; + } + + private static string NormalizePath(string path) + => path + .Replace('/', Path.DirectorySeparatorChar) + .Replace('\\', Path.DirectorySeparatorChar); + + private static int CountOccurrences(string text, string value) + { + var count = 0; + var startIndex = 0; + + while ((startIndex = text.IndexOf(value, startIndex, StringComparison.Ordinal)) >= 0) + { + count++; + startIndex += value.Length; + } + + return count; + } + + private sealed record RequiredPackage( + string Alias, + string PackageId, + string Version, + string ProjectPath); + + private sealed class AcceptanceTestFixture : IDisposable + { + private AcceptanceTestFixture(string repositoryRoot, bool createCandidateSource) + { + Root = Directory.CreateDirectory(Path.Combine( + Path.GetTempPath(), + $"fluxflow-package-acceptance-test-{Guid.NewGuid():N}")).FullName; + Packages = ReadRequiredPackages(repositoryRoot); + PackageSource = Path.Combine(Root, "candidate-source"); + WorkDirectory = Path.Combine(Root, "consumer-work"); + PackageCache = Path.Combine(WorkDirectory, "packages"); + DotnetArgumentsPath = Path.Combine(Root, "dotnet-arguments.txt"); + DotnetCurrentArgumentsPath = Path.Combine(Root, "dotnet-current-arguments.txt"); + var metadataPath = Path.Combine(Root, "packages.json"); + File.WriteAllText(metadataPath, JsonSerializer.Serialize(Packages)); + var driverPath = Path.Combine(Root, "fake-dotnet.ps1"); + File.WriteAllText(driverPath, FakeDotnetDriver); + FakeDotnetDirectory = CreateFakeDotnetCommand(Root); + Environment = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["FAKE_DOTNET_ARGUMENTS"] = DotnetArgumentsPath, + ["FAKE_DOTNET_CURRENT_ARGUMENTS"] = DotnetCurrentArgumentsPath, + ["FAKE_DOTNET_DRIVER"] = driverPath, + ["FAKE_DOTNET_METADATA"] = metadataPath, + ["PATH"] = FakeDotnetDirectory + Path.PathSeparator + + System.Environment.GetEnvironmentVariable("PATH") + }; + + if (createCandidateSource) + { + Directory.CreateDirectory(PackageSource); + foreach (var package in Packages) + { + File.WriteAllText( + GetCandidateArchive(package), + $"candidate:{package.PackageId}/{package.Version}"); + } + } + } + + public string Root { get; } + + public RequiredPackage[] Packages { get; } + + public string PackageSource { get; } + + public string WorkDirectory { get; } + + public string PackageCache { get; } + + public string DotnetArgumentsPath { get; } + + private string DotnetCurrentArgumentsPath { get; } + + private string FakeDotnetDirectory { get; } + + private Dictionary Environment { get; } + + public static AcceptanceTestFixture Create( + string repositoryRoot, + bool createCandidateSource = true) + => new(repositoryRoot, createCandidateSource); + + public Dictionary CreateEnvironment() + => new(Environment, StringComparer.OrdinalIgnoreCase); + + public string GetCandidateArchive(RequiredPackage package) + => Path.Combine(PackageSource, $"{package.PackageId}.{package.Version}.nupkg"); + + public void Dispose() + { + if (Directory.Exists(Root)) + Directory.Delete(Root, recursive: true); + } + + private static string CreateFakeDotnetCommand(string root) + { + var directory = Directory.CreateDirectory(Path.Combine(root, "fake-bin")).FullName; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + File.WriteAllText(Path.Combine(directory, "dotnet.cmd"), """ + @echo off + type nul > "%FAKE_DOTNET_CURRENT_ARGUMENTS%" + :collect_arguments + if "%~1"=="" goto run_driver + >> "%FAKE_DOTNET_CURRENT_ARGUMENTS%" echo(%~1 + shift + goto collect_arguments + :run_driver + pwsh -NoLogo -NoProfile -File "%FAKE_DOTNET_DRIVER%" + exit /b %ERRORLEVEL% + """); + return directory; + } + + var scriptPath = Path.Combine(directory, "dotnet"); + File.WriteAllText(scriptPath, """ + #!/usr/bin/env bash + printf '%s\n' "$@" > "$FAKE_DOTNET_CURRENT_ARGUMENTS" + exec pwsh -NoLogo -NoProfile -File "$FAKE_DOTNET_DRIVER" + """.ReplaceLineEndings("\n")); + File.SetUnixFileMode( + scriptPath, + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + return directory; + } + + private const string FakeDotnetDriver = """ + $ErrorActionPreference = "Stop" + $CommandArguments = @(Get-Content -LiteralPath $env:FAKE_DOTNET_CURRENT_ARGUMENTS) + Add-Content -LiteralPath $env:FAKE_DOTNET_ARGUMENTS -Value ($CommandArguments -join " ") + $packages = @(Get-Content -LiteralPath $env:FAKE_DOTNET_METADATA -Raw | ConvertFrom-Json) + + function Read-Argument { + param([string] $Name) + + for ($index = 0; $index -lt $CommandArguments.Count - 1; $index++) { + if ($CommandArguments[$index] -eq $Name) { + return $CommandArguments[$index + 1] + } + } + + throw "Fake dotnet did not receive '$Name'." + } + + $operation = $CommandArguments[0] + if ($operation -eq "pack") { + $projectPath = [System.IO.Path]::GetFullPath($CommandArguments[1]) + $package = @($packages | Where-Object { + [string]::Equals( + [System.IO.Path]::GetFullPath($_.ProjectPath), + $projectPath, + [System.StringComparison]::OrdinalIgnoreCase) + })[0] + if ($null -eq $package) { + throw "Fake dotnet could not map pack project '$projectPath'." + } + + $outputPath = Read-Argument "--output" + New-Item -ItemType Directory -Path $outputPath -Force | Out-Null + Set-Content ` + -LiteralPath (Join-Path $outputPath "$($package.PackageId).$($package.Version).nupkg") ` + -Value "candidate:$($package.PackageId)/$($package.Version)" ` + -NoNewline + exit 0 + } + + if ($operation -eq "restore") { + $projectPath = [System.IO.Path]::GetFullPath($CommandArguments[1]) + $workRoot = Split-Path -Parent $projectPath + $packageCache = Read-Argument "--packages" + $configPath = Read-Argument "--configfile" + [xml] $config = Get-Content -LiteralPath $configPath -Raw + $candidateSource = [string] (@($config.configuration.packageSources.add | Where-Object { + $_.key -eq "candidate" + })[0].value) + + $libraries = [ordered]@{} + if ($env:FAKE_DOTNET_PROJECT_LIBRARY -eq "true") { + $libraries["Repository.Project/1.0.0"] = [ordered]@{ + type = "project" + path = "../src/Repository.Project.csproj" + } + } + + foreach ($package in $packages) { + $lowerId = $package.PackageId.ToLowerInvariant() + $lowerVersion = $package.Version.ToLowerInvariant() + $relativePath = "$lowerId/$lowerVersion" + $libraries["$($package.PackageId)/$($package.Version)"] = [ordered]@{ + type = "package" + path = $relativePath + } + + $packageDirectory = Join-Path $packageCache $relativePath + New-Item -ItemType Directory -Path $packageDirectory -Force | Out-Null + $candidateArchive = Join-Path $candidateSource "$($package.PackageId).$($package.Version).nupkg" + $cachedArchive = Join-Path $packageDirectory "$lowerId.$lowerVersion.nupkg" + Copy-Item -LiteralPath $candidateArchive -Destination $cachedArchive + if ($env:FAKE_DOTNET_MISMATCH_PACKAGE -eq $package.PackageId) { + Add-Content -LiteralPath $cachedArchive -Value "mismatch" + } + } + + $assetsDirectory = Join-Path $workRoot "obj" + New-Item -ItemType Directory -Path $assetsDirectory -Force | Out-Null + [ordered]@{ + version = 3 + libraries = $libraries + } | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $assetsDirectory "project.assets.json") + exit 0 + } + + if ($operation -eq "run") { + $markers = @( + "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_FLUENT_OK=True", + "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", + "PACKAGE_ACCEPTANCE_OK=True" + ) + foreach ($marker in $markers) { + if ($marker -ne $env:FAKE_DOTNET_OMIT_MARKER) { + Write-Output $marker + } + } + } + + exit 0 + """; + } +} From 6372051316a7eda3617999ece00c248b187cc8ee Mon Sep 17 00:00:00 2001 From: meisa Date: Tue, 4 Aug 2026 17:41:57 +0200 Subject: [PATCH 2/2] Make acceptance error contract portable --- .../PackageConsumerAcceptanceScriptTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs index 0fd5162f..c0fd5f8b 100644 --- a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs +++ b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs @@ -293,14 +293,14 @@ public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retai new() { { "project", "resolved a project library" }, - { "hash", "does not match candidate archive" } + { "hash", "does not match candidate" } }; [Theory] [MemberData(nameof(InvalidResolutionModes))] public async Task Acceptance_script_rejects_project_or_non_candidate_resolution( string mode, - string expectedFailure) + string expectedFailureFragment) { var root = ReleaseTestPaths.FindRepositoryRoot(); using var fixture = AcceptanceTestFixture.Create(root); @@ -318,7 +318,7 @@ public async Task Acceptance_script_rejects_project_or_non_candidate_resolution( fixture.WorkDirectory); result.ExitCode.ShouldNotBe(0); - result.ToString().ShouldContain(expectedFailure); + result.ToString().ShouldContain(expectedFailureFragment); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); invocations.ShouldHaveSingleItem().ShouldStartWith("restore ");