package controlplane

import (
	"context"
	"database/sql"
	"strings"
	"testing"
	"time"

	"github.com/nexuscrm/metadata"
	cp "github.com/pingcap-inc/nexuscrm-contract/pkg/controlplane"
	"github.com/pingcap-inc/nexuscrm-controlplane/packs"
)

func TestBindApplyAllSourceRevisionAdvanceExecutionProofReplaysUnchangedComponentsForFreshIncarnation(t *testing.T) {
	advance := testApplyAllSourceRevisionAdvance("crm", 0)
	current, _ := testApplyAllSourceRevisionAdvanceObjectTarget(t, advance.Name, advance.FromRevision, "Account")
	sourceTarget, _ := testApplyAllSourceRevisionAdvanceObjectTarget(t, advance.Name, advance.ToRevision, "Account")
	compatibilityTarget, _ := testApplyAllSourceRevisionAdvanceObjectTarget(t, advance.Name, advance.ToRevision, "Account")
	precondition := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
		t, advance, current, installedPackStatusActive, advance.Kind, testCurrentTargetV1Hash, nil,
	)
	precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: sourceTarget},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: compatibilityTarget},
	})
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	runner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)

	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(runner, precondition, source, compatibility)
	if err != nil {
		t.Fatalf("bind execution proof: %v", err)
	}
	if len(proof.entries) != 1 || proof.entries[0].atom == nil {
		t.Fatalf("execution proof entries = %#v, want one complete atom", proof.entries)
	}
	// Current and target declarations are identical. A delta atom would have an
	// empty plan and succeed with empty dependencies. The fresh-incarnation atom
	// must retain the unchanged ObjectSpec write, which fails closed here because
	// the metadata apply dependency is deliberately absent.
	err = proof.entries[0].atom.Execute(context.Background(), packs.ApplyDeps{}, packs.InstallPlanHooks{})
	if err == nil {
		t.Fatal("fresh-incarnation execution skipped the unchanged component")
	}
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofRetainsTransitionExactSetForDropToZero(t *testing.T) {
	advance := testApplyAllSourceRevisionAdvance("crm", 0)
	registrations := testApplyAllSourceRevisionAdvanceExactSetRegistrationSet(t)
	current := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.FromRevision, registrations, true)
	sourceTarget := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.ToRevision, registrations, false)
	compatibilityTarget := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.ToRevision, registrations, false)
	precondition := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
		t, advance, current, installedPackStatusActive, advance.Kind, testCurrentTargetV1Hash, nil,
	)
	precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: sourceTarget},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: compatibilityTarget},
	})
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	runner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)
	runner.SvcMgr.(*runnerServiceGraph).options.ComponentKindRegistrationSet = registrations

	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(runner, precondition, source, compatibility)
	if err != nil {
		t.Fatalf("bind execution proof: %v", err)
	}
	if len(proof.entries) != 1 || proof.entries[0].atom == nil {
		t.Fatalf("execution proof entries = %#v, want one replay atom", proof.entries)
	}
	// A full target atom has an empty plan because the target declares no item.
	// The transition replay must instead retain the delta-proven empty exact set,
	// which reaches lifecycle preparation and fails closed without a database.
	err = proof.entries[0].atom.Execute(context.Background(), packs.ApplyDeps{}, packs.InstallPlanHooks{})
	if err == nil || !strings.Contains(err.Error(), "prepare managed component set") {
		t.Fatalf("drop-to-zero replay error = %v, want retained exact-set lifecycle", err)
	}
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofRetryRetainsOriginalTransitionExactSet(t *testing.T) {
	advance := testApplyAllSourceRevisionAdvance("crm", 0)
	registrations := testApplyAllSourceRevisionAdvanceExactSetRegistrationSet(t)
	replayBase := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.FromRevision, registrations, true)
	currentTarget := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.ToRevision, registrations, false)
	sourceTarget := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.ToRevision, registrations, false)
	compatibilityTarget := testApplyAllSourceRevisionAdvanceExactSetTarget(t, advance, advance.ToRevision, registrations, false)
	precondition := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
		t, advance, currentTarget, installedPackStatusFailed, advance.Kind, nil, testCurrentTargetV1Hash,
	)
	precondition.replay = applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: replayBase},
	}
	precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: sourceTarget},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{advance},
		targets: map[string]*packs.SourceBackedPack{advance.Name: compatibilityTarget},
	})
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	runner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)
	runner.SvcMgr.(*runnerServiceGraph).options.ComponentKindRegistrationSet = registrations

	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(runner, precondition, source, compatibility)
	if err != nil {
		t.Fatalf("bind retry execution proof: %v", err)
	}
	if len(proof.entries) != 1 || proof.entries[0].atom == nil {
		t.Fatalf("retry execution proof entries = %#v, want one replay atom", proof.entries)
	}
	// Begin has already moved the mutable InstalledPack row to ToRevision, so
	// currentTarget and target are intentionally identical. The durable retry
	// proof must still replay the original FromRevision -> ToRevision removal.
	err = proof.entries[0].atom.Execute(context.Background(), packs.ApplyDeps{}, packs.InstallPlanHooks{})
	if err == nil || !strings.Contains(err.Error(), "prepare managed component set") {
		t.Fatalf("retry drop-to-zero replay error = %v, want retained original exact-set lifecycle", err)
	}
}

func testApplyAllSourceRevisionAdvanceExactSetRegistrationSet(t *testing.T) packs.ComponentKindRegistrationSet {
	t.Helper()
	kind := cp.ComponentKind("execution_proof_exact_set")
	manageabilities := map[cp.Manageability]struct{}{cp.ManageabilityLocked: {}}
	registration := cp.ComponentKindRegistration{
		Contract: cp.ComponentKindContract{
			Kind: kind, Phase: cp.InstallPlanPhaseAutomation,
			WriteSet:           []cp.ComponentWriteSurface{{Table: "ExecutionProofExactSet", Fact: "managed rows"}},
			BusinessKey:        "test key",
			OwnerDiscriminator: cp.ComponentOwnerStrategyOwnerPack,
			Manageabilities:    manageabilities,
			VerifyProjection:   "managed rows",
			CollisionKey:       "test key",
		},
		Capability: cp.SourceBackedComponentCapability{
			Kind: kind, Installable: true, Manageabilities: manageabilities,
		},
		AllowedCategories: []cp.PackCategory{cp.AppPack},
		BuildHandler: func(ctx cp.ComponentBuildContext, request cp.ComponentBuildRequest) error {
			return ctx.AddManagedComponent(cp.ComponentBuildManagedComponent{
				ExpectedProjection: append([]byte(nil), request.Payload...),
			})
		},
	}
	lifecycle, err := cp.NewComponentManagedLifecycleRegistration(cp.ComponentManagedLifecycleRegistrationSpec{
		Kind:    kind,
		ReadSet: []cp.ComponentReadSurface{{Table: "ExecutionProofExactSet", Fact: "managed rows"}},
		Capabilities: []cp.ComponentManagedCapability{
			cp.ComponentManagedCapabilityTargetSerialization,
			cp.ComponentManagedCapabilityStructuredMutation,
			cp.ComponentManagedCapabilityEvidence,
			cp.ComponentManagedCapabilityFreshProjection,
			cp.ComponentManagedCapabilityExactSet,
		},
		TransactionMode: cp.ComponentManagedTransactionPessimisticReadCommitted,
		Budget: cp.ComponentManagedBudget{
			MaxTargets: 10, MaxCurrentItems: 10, MaxDesiredItems: 10, MaxDeltaRows: 10,
			MaxMutationBytes: 1024, MaxMutationStatements: 10, MaxBatchRows: 10,
			MaxEvidenceWrites: 1, MaxEffectCalls: 1,
			MaxLockWait: time.Second, MaxElapsed: time.Second, MaxAttempts: 3,
		},
		Lifecycle: cp.ComponentManagedLifecycleProvider{
			Plan: func(context.Context, cp.ComponentManagedScope, cp.ComponentManagedLifecycleRequest, cp.ComponentManagedReadStore) (cp.ComponentManagedPlan, error) {
				return cp.ComponentManagedPlan{}, nil
			},
			Mutate: func(context.Context, cp.ComponentManagedScope, cp.ComponentManagedLifecycleRequest, cp.ComponentManagedPlan, cp.ComponentManagedMutationStore) (cp.ComponentManagedMutationResult, error) {
				return cp.ComponentManagedMutationResult{}, nil
			},
			Project: func(context.Context, cp.ComponentManagedScope, cp.ComponentManagedLifecycleRequest, cp.ComponentManagedReadStore) (cp.ComponentManagedProjection, error) {
				return cp.ComponentManagedProjection{}, nil
			},
		},
	})
	if err != nil {
		t.Fatalf("exact-set lifecycle: %v", err)
	}
	bound, err := registration.WithManagedLifecycle(lifecycle)
	if err != nil {
		t.Fatalf("bind exact-set lifecycle: %v", err)
	}
	set, err := packs.NewComponentKindRegistrationSetWithManagedLifecycles(
		nil, []cp.ComponentKindManagedLifecycleRegistration{bound},
	)
	if err != nil {
		t.Fatalf("registration set: %v", err)
	}
	return set
}

func testApplyAllSourceRevisionAdvanceExactSetTarget(
	t *testing.T,
	advance normalizedApplyAllSourceRevisionAdvance,
	revision string,
	registrations packs.ComponentKindRegistrationSet,
	declared bool,
) *packs.SourceBackedPack {
	t.Helper()
	components := []packs.ManifestComponent{}
	if declared {
		components = append(components, packs.ManifestComponent{
			Kind: packs.ComponentKind("execution_proof_exact_set"), BusinessKey: "One",
			Manageability: packs.ManageabilityLocked, Payload: []byte(`{"value":"one"}`),
		})
	}
	target, err := packs.NewSourceBackedPack(&packs.ResolvedPackSource{
		Kind: string(packs.PackSourceKindOfficialRepo), URI: advance.URI, Revision: revision,
		Manifest: &packs.PackManifest{
			ManifestFormatVersion: packs.SupportedManifestFormatVersion,
			Name:                  advance.Name, DisplayName: advance.Name, Category: packs.AppPack, Version: "1.0.0",
			PlatformCompatibility: packs.PlatformCompatibility{Min: "0.2.0", MaxExclusive: "0.3.0"},
			Components:            components,
		},
		Files: map[string][]byte{}, FileRefs: []string{},
	}, packs.WithComponentKindRegistrationSet(registrations))
	if err != nil {
		t.Fatalf("new exact-set target: %v", err)
	}
	return target
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofJoinsAndDetachesInputs(t *testing.T) {
	provider := testApplyAllSourceRevisionAdvance("provider", 4)
	consumer := testApplyAllSourceRevisionAdvance("consumer", 7)
	dependency := packs.PackDependency{Name: provider.Name, VersionConstraint: ">=2.0.0"}

	consumerCurrent := testApplyAllSourceRevisionTarget(
		t, consumer.Name, "1.0.0", consumer.Kind, consumer.URI, consumer.FromRevision,
	)
	providerCurrent := testApplyAllSourceRevisionTarget(
		t, provider.Name, "2.1.0", provider.Kind, provider.URI, provider.ToRevision,
	)
	consumerProof := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
		t, consumer, consumerCurrent, installedPackStatusActive, consumer.Kind,
		testCurrentTargetV1Hash, nil,
	)
	providerProof := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
		t, provider, providerCurrent, installedPackStatusActive, provider.Kind,
		testCurrentTargetV1Hash, nil,
	)
	precondition := applyAllSourceRevisionAdvancePreconditionProof{
		snapshot: applyAllSourceRevisionAdvanceCurrentSnapshot{entries: []applyAllSourceRevisionAdvanceCurrentSnapshotEntry{
			consumerProof.snapshot.entries[0], providerProof.snapshot.entries[0],
		}},
		current: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{consumer, provider},
			targets: map[string]*packs.SourceBackedPack{
				"consumer": consumerCurrent,
				"provider": providerCurrent,
			},
		},
		replay: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{consumer, provider},
			targets: map[string]*packs.SourceBackedPack{
				"consumer": consumerCurrent,
				"provider": providerCurrent,
			},
		},
	}
	precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()

	sourceProvider := testApplyAllSourceRevisionTarget(
		t, provider.Name, "2.1.0", provider.Kind, provider.URI, provider.ToRevision,
	)
	sourceConsumer := testApplyAllSourceRevisionTarget(
		t, consumer.Name, "1.0.0", consumer.Kind, consumer.URI, consumer.ToRevision, dependency,
	)
	compatibilityProvider := testApplyAllSourceRevisionTarget(
		t, provider.Name, "2.1.0", provider.Kind, provider.URI, provider.ToRevision,
	)
	compatibilityConsumer := testApplyAllSourceRevisionTarget(
		t, consumer.Name, "1.0.0", consumer.Kind, consumer.URI, consumer.ToRevision, dependency,
	)
	ordered := []normalizedApplyAllSourceRevisionAdvance{provider, consumer}
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan: append([]normalizedApplyAllSourceRevisionAdvance(nil), ordered...),
		targets: map[string]*packs.SourceBackedPack{
			"provider": sourceProvider,
			"consumer": sourceConsumer,
		},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan: append([]normalizedApplyAllSourceRevisionAdvance(nil), ordered...),
		targets: map[string]*packs.SourceBackedPack{
			"provider": compatibilityProvider,
			"consumer": compatibilityConsumer,
		},
	})
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	runner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)

	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(runner, precondition, source, compatibility)
	if err != nil {
		t.Fatalf("bind execution proof: %v", err)
	}
	if proof.entries == nil || len(proof.entries) != 2 {
		t.Fatalf("proof entries = %#v, want two dependency-ordered entries", proof.entries)
	}
	if proof.activeRuntimeIdentity != precondition.activeRuntime.identity {
		t.Fatalf("proof runtime identity = %p, want exact observation identity %p", proof.activeRuntimeIdentity, precondition.activeRuntime.identity)
	}
	if proof.executionRuntime == nil || proof.executionRuntime.runner != runner ||
		proof.provenance.executionRuntime != proof.executionRuntime {
		t.Fatalf("proof execution runtime = %p/%p, want exact runner-bound token", proof.executionRuntime, proof.provenance.executionRuntime)
	}
	if !proof.provenance.minted || proof.provenance.entryCount != 2 ||
		proof.provenance.entries == nil || len(proof.provenance.entries) != 2 {
		t.Fatalf("proof provenance = %#v, want minted two-entry witness", proof.provenance)
	}
	if proof.provenance.activeRuntimeIdentity != precondition.activeRuntime.identity ||
		proof.provenance.activeRuntimeDatabase != precondition.activeRuntime.identity.db ||
		proof.provenance.activeRuntimeSnapshot != precondition.activeRuntime.identity.snapshot {
		t.Fatalf("proof runtime provenance = %#v, want exact identity, database, and snapshot", proof.provenance)
	}
	wantTargets := []*packs.SourceBackedPack{compatibilityProvider, compatibilityConsumer}
	wantCurrentTargets := []*packs.SourceBackedPack{providerCurrent, consumerCurrent}
	wantNames := []string{"provider", "consumer"}
	for index, entry := range proof.entries {
		provenance := proof.provenance.entries[index]
		if entry.name != wantNames[index] || entry.current.advance != ordered[index] {
			t.Fatalf("entry %d = name %q advance %#v, want %q %#v", index, entry.name, entry.current.advance, wantNames[index], ordered[index])
		}
		if entry.installedCompatibility != wantTargets[index] {
			t.Fatalf("entry %d retained target %p, want exact compatibility target %p", index, entry.installedCompatibility, wantTargets[index])
		}
		if entry.currentTarget != wantCurrentTargets[index] {
			t.Fatalf("entry %d retained current target %p, want exact frozen current target %p", index, entry.currentTarget, wantCurrentTargets[index])
		}
		if provenance.expected.name != entry.name ||
			provenance.expected.current.advance != entry.current.advance ||
			provenance.expected.current.row != entry.current.row ||
			!equalApplyAllSourceRevisionAdvancePending(provenance.expected.current.pending, entry.current.pending) ||
			provenance.expected.currentTarget != entry.currentTarget ||
			provenance.expected.installedCompatibility != entry.installedCompatibility ||
			provenance.expected.atom != entry.atom {
			t.Fatalf("entry %d provenance = %#v, want independently retained complete entry %#v", index, provenance.expected, entry)
		}
		if entry.current.pending != nil && provenance.expected.current.pending == entry.current.pending {
			t.Fatalf("entry %d provenance aliases the operational pending pointer", index)
		}
		if err := packs.ValidateSourceBackedPackIdentityTarget(provenance.currentTargetIdentity, entry.currentTarget); err != nil {
			t.Fatalf("entry %d current-target identity: %v", index, err)
		}
		if err := packs.ValidateSourceBackedExecutionAtomIdentityTarget(
			provenance.atomIdentity,
			entry.atom,
			entry.installedCompatibility,
		); err != nil {
			t.Fatalf("entry %d atom identity: %v", index, err)
		}
		if entry.installedCompatibility == source.targets[entry.name] {
			t.Fatalf("entry %d retained fresh-source pointer instead of installed-compatibility pointer", index)
		}
		facts, err := entry.atom.Facts()
		if err != nil {
			t.Fatalf("entry %d atom facts: %v", index, err)
		}
		fingerprint, err := fingerprintApplyAllSourceRevisionAdvanceTarget(wantTargets[index])
		if err != nil {
			t.Fatalf("entry %d target fingerprint: %v", index, err)
		}
		if facts.Name != wantTargets[index].Name() || facts.Category != wantTargets[index].Category() ||
			facts.Metadata != fingerprint.metadata || facts.PayloadHash != fingerprint.payloadHash ||
			facts.HostRequirementsDigest != fingerprint.hostRequirementsDigest {
			t.Fatalf("entry %d atom facts = %#v, want exact installed-compatibility facts", index, facts)
		}
	}

	precondition.snapshot.entries[0].row.SourceRevision.String = "mutated"
	precondition.snapshot.entries[0].pending.Kind = ApplyAllSourceRevisionAdvancePendingRetry
	precondition.current.targets["provider"] = sourceProvider
	delete(precondition.current.targets, "consumer")
	compatibility.plan[0].Name = "mutated"
	compatibility.targets["provider"] = sourceProvider
	delete(compatibility.targets, "consumer")
	compatibility.activeRuntimeIdentity = &applyAllSourceRevisionAdvanceActiveRuntimeIdentity{
		db: precondition.activeRuntime.identity.db, snapshot: precondition.activeRuntime.identity.snapshot,
	}
	if proof.activeRuntimeIdentity != precondition.activeRuntime.identity {
		t.Fatalf("proof runtime identity changed through compatibility mutation: %p", proof.activeRuntimeIdentity)
	}
	if proof.entries[0].current.row.SourceRevision.String != provider.ToRevision {
		t.Fatalf("provider frozen row changed through input alias: %#v", proof.entries[0].current.row)
	}
	if proof.entries[1].current.row.SourceRevision.String != consumer.FromRevision ||
		proof.entries[1].current.pending == nil ||
		proof.entries[1].current.pending.Kind != ApplyAllSourceRevisionAdvancePendingAdvance {
		t.Fatalf("consumer frozen entry changed through input alias: %#v", proof.entries[1].current)
	}
	if proof.entries[0].installedCompatibility != compatibilityProvider ||
		proof.entries[1].installedCompatibility != compatibilityConsumer {
		t.Fatal("retained installed-compatibility pointers changed through tuple-map mutation")
	}
	if proof.entries[0].currentTarget != providerCurrent || proof.entries[1].currentTarget != consumerCurrent {
		t.Fatal("retained frozen-current pointers changed through current-tuple mutation")
	}
	if proof.provenance.entries[0].expected.current.row.SourceRevision.String != provider.ToRevision ||
		proof.provenance.entries[1].expected.current.row.SourceRevision.String != consumer.FromRevision ||
		proof.provenance.entries[1].expected.current.pending == nil ||
		proof.provenance.entries[1].expected.current.pending.Kind != ApplyAllSourceRevisionAdvancePendingAdvance {
		t.Fatalf("provenance changed through input mutation: %#v", proof.provenance.entries)
	}

	proof.provenance.entries[1].expected.current.pending.Kind = ApplyAllSourceRevisionAdvancePendingCanonicalize
	if proof.entries[1].current.pending.Kind != ApplyAllSourceRevisionAdvancePendingAdvance {
		t.Fatal("operational pending changed through provenance mutation")
	}
	proof.provenance.entries[1].expected.current.pending.Kind = ApplyAllSourceRevisionAdvancePendingAdvance
	proof.entries[1].name = "mutated"
	proof.entries[1].current.row.SourceRevision.String = "mutated"
	proof.entries[1].current.pending.Kind = ApplyAllSourceRevisionAdvancePendingRetry
	proof.entries[1].currentTarget = providerCurrent
	proof.entries[1].installedCompatibility = compatibilityProvider
	proof.entries[1].atom = proof.entries[0].atom
	if proof.provenance.entries[1].expected.name != "consumer" ||
		proof.provenance.entries[1].expected.current.row.SourceRevision.String != consumer.FromRevision ||
		proof.provenance.entries[1].expected.current.pending.Kind != ApplyAllSourceRevisionAdvancePendingAdvance ||
		proof.provenance.entries[1].expected.currentTarget != consumerCurrent ||
		proof.provenance.entries[1].expected.installedCompatibility != compatibilityConsumer {
		t.Fatalf("provenance changed through operational proof mutation: %#v", proof.provenance.entries[1])
	}

	wantRuntimeDatabase := proof.provenance.activeRuntimeDatabase
	wantRuntimeSnapshot := proof.provenance.activeRuntimeSnapshot
	proof.activeRuntimeIdentity.db = &sql.DB{}
	proof.activeRuntimeIdentity.snapshot = &packs.ActiveInstalledRuntimeSnapshot{}
	if proof.provenance.activeRuntimeDatabase != wantRuntimeDatabase ||
		proof.provenance.activeRuntimeSnapshot != wantRuntimeSnapshot {
		t.Fatal("runtime provenance changed through identity mutation")
	}
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofAcceptsMintedEmptyRoles(t *testing.T) {
	precondition := applyAllSourceRevisionAdvancePreconditionProof{
		snapshot: applyAllSourceRevisionAdvanceCurrentSnapshot{entries: []applyAllSourceRevisionAdvanceCurrentSnapshotEntry{}},
		current: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
		},
		replay: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
		},
	}
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
	})
	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(nil, precondition, source, compatibility)
	if err != nil {
		t.Fatalf("bind empty execution proof: %v", err)
	}
	if proof.activeRuntimeIdentity != nil || proof.executionRuntime != nil || proof.entries == nil || len(proof.entries) != 0 ||
		!proof.provenance.minted || proof.provenance.entryCount != 0 ||
		proof.provenance.activeRuntimeIdentity != nil || proof.provenance.executionRuntime != nil ||
		proof.provenance.activeRuntimeDatabase != nil || proof.provenance.activeRuntimeSnapshot != nil ||
		proof.provenance.entries == nil || len(proof.provenance.entries) != 0 {
		t.Fatalf("empty proof entries = %#v, want non-nil empty slice", proof.entries)
	}

	identifiedPrecondition := precondition
	identifiedPrecondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()
	identifiedCompatibility := compatibility
	identifiedCompatibility.activeRuntimeIdentity = identifiedPrecondition.activeRuntime.identity
	proof, err = bindApplyAllSourceRevisionAdvanceExecutionProof(
		nil, identifiedPrecondition, source, identifiedCompatibility,
	)
	assertApplyAllSourceRevisionComposeError(t, err, -1, "")
	assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, proof)

	proof, err = bindApplyAllSourceRevisionAdvanceExecutionProof(
		nil, applyAllSourceRevisionAdvancePreconditionProof{}, source, compatibility,
	)
	assertApplyAllSourceRevisionAdvancePreconditionError(
		t, err, ApplyAllSourceRevisionAdvancePlanState, -1, "",
	)
	assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, proof)
	proof, err = bindApplyAllSourceRevisionAdvanceExecutionProof(
		nil, precondition, applyAllSourceRevisionAdvanceSourceTuple{}, compatibility,
	)
	assertApplyAllSourceRevisionComposeError(t, err, -1, "")
	assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, proof)
	proof, err = bindApplyAllSourceRevisionAdvanceExecutionProof(
		nil, precondition, source, applyAllSourceRevisionAdvanceInstalledCompatibilityTuple{},
	)
	assertApplyAllSourceRevisionComposeError(t, err, -1, "")
	assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, proof)
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofRejectsRoleSubstitution(t *testing.T) {
	advance := testApplyAllSourceRevisionAdvance("crm", 19)
	tests := []struct {
		name      string
		mutate    func(*applyAllSourceRevisionAdvancePreconditionProof, *applyAllSourceRevisionAdvanceSourceTuple, *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple)
		wantStage ApplyAllSourceRevisionAdvancePlanErrorStage
		wantIndex int
		wantName  string
	}{
		{
			name: "current target",
			mutate: func(precondition *applyAllSourceRevisionAdvancePreconditionProof, _ *applyAllSourceRevisionAdvanceSourceTuple, _ *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple) {
				precondition.current.targets["crm"] = testApplyAllSourceRevisionTarget(t, advance.Name, "2.0.0", advance.Kind, advance.URI, advance.ToRevision)
			},
			wantStage: ApplyAllSourceRevisionAdvancePlanState, wantIndex: advance.index, wantName: advance.Name,
		},
		{
			name: "fresh source target",
			mutate: func(_ *applyAllSourceRevisionAdvancePreconditionProof, source *applyAllSourceRevisionAdvanceSourceTuple, _ *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple) {
				source.targets["crm"] = testApplyAllSourceRevisionTarget(t, advance.Name, "2.0.0", advance.Kind, advance.URI, advance.ToRevision)
			},
			wantStage: ApplyAllSourceRevisionAdvancePlanCompose, wantIndex: advance.index, wantName: advance.Name,
		},
		{
			name: "installed compatibility target",
			mutate: func(_ *applyAllSourceRevisionAdvancePreconditionProof, _ *applyAllSourceRevisionAdvanceSourceTuple, compatibility *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple) {
				compatibility.targets["crm"] = testApplyAllSourceRevisionTarget(t, advance.Name, "2.0.0", advance.Kind, advance.URI, advance.ToRevision)
			},
			wantStage: ApplyAllSourceRevisionAdvancePlanCompose, wantIndex: advance.index, wantName: advance.Name,
		},
		{
			name: "active runtime observation",
			mutate: func(precondition *applyAllSourceRevisionAdvancePreconditionProof, _ *applyAllSourceRevisionAdvanceSourceTuple, compatibility *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple) {
				compatibility.activeRuntimeIdentity = &applyAllSourceRevisionAdvanceActiveRuntimeIdentity{
					db: precondition.activeRuntime.identity.db, snapshot: precondition.activeRuntime.identity.snapshot,
				}
			},
			wantStage: ApplyAllSourceRevisionAdvancePlanCompose, wantIndex: -1,
		},
		{
			name: "missing active runtime observation",
			mutate: func(precondition *applyAllSourceRevisionAdvancePreconditionProof, _ *applyAllSourceRevisionAdvanceSourceTuple, _ *applyAllSourceRevisionAdvanceInstalledCompatibilityTuple) {
				precondition.activeRuntime = applyAllSourceRevisionAdvanceActiveRuntimeObservation{}
			},
			wantStage: ApplyAllSourceRevisionAdvancePlanCompose, wantIndex: -1,
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			current := testApplyAllSourceRevisionTarget(t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision)
			precondition := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
				t, advance, current, installedPackStatusActive, advance.Kind,
				testCurrentTargetV1Hash, nil,
			)
			precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservation()
			source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
				plan: []normalizedApplyAllSourceRevisionAdvance{advance},
				targets: map[string]*packs.SourceBackedPack{
					"crm": testApplyAllSourceRevisionTarget(t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision),
				},
			})
			compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
				plan: []normalizedApplyAllSourceRevisionAdvance{advance},
				targets: map[string]*packs.SourceBackedPack{
					"crm": testApplyAllSourceRevisionTarget(t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision),
				},
			})
			compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
			runner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)
			test.mutate(&precondition, &source, &compatibility)
			proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(runner, precondition, source, compatibility)
			if test.wantStage == ApplyAllSourceRevisionAdvancePlanState {
				assertApplyAllSourceRevisionAdvancePreconditionError(t, err, test.wantStage, test.wantIndex, test.wantName)
			} else {
				assertApplyAllSourceRevisionComposeError(t, err, test.wantIndex, test.wantName)
			}
			assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, proof)
		})
	}
}

func TestValidateApplyAllSourceRevisionAdvanceExecutionProofAcceptsMintedProofs(t *testing.T) {
	for _, count := range []int{0, 2} {
		proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, count)
		if err := validateApplyAllSourceRevisionAdvanceExecutionProof(proof); err != nil {
			t.Fatalf("validate %d-entry proof: %v", count, err)
		}
	}
}

func TestBindApplyAllSourceRevisionAdvanceExecutionProofRejectsDifferentRuntimeDatabase(t *testing.T) {
	proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, 1)
	precondition := applyAllSourceRevisionAdvancePreconditionProof{
		activeRuntime: applyAllSourceRevisionAdvanceActiveRuntimeObservation{
			identity: proof.activeRuntimeIdentity,
			minted:   true,
		},
		snapshot: applyAllSourceRevisionAdvanceCurrentSnapshot{
			entries: []applyAllSourceRevisionAdvanceCurrentSnapshotEntry{proof.entries[0].current},
		},
		current: applyAllSourceRevisionAdvanceTuple{
			plan:    []normalizedApplyAllSourceRevisionAdvance{proof.entries[0].current.advance},
			targets: map[string]*packs.SourceBackedPack{proof.entries[0].name: proof.entries[0].currentTarget},
		},
		replay: applyAllSourceRevisionAdvanceTuple{
			plan:    []normalizedApplyAllSourceRevisionAdvance{proof.entries[0].current.advance},
			targets: map[string]*packs.SourceBackedPack{proof.entries[0].name: proof.entries[0].currentTarget},
		},
	}
	source := testApplyAllSourceRevisionAdvanceSourceTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{proof.entries[0].current.advance},
		targets: map[string]*packs.SourceBackedPack{proof.entries[0].name: proof.entries[0].installedCompatibility},
	})
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(applyAllSourceRevisionAdvanceTuple{
		plan:    []normalizedApplyAllSourceRevisionAdvance{proof.entries[0].current.advance},
		targets: map[string]*packs.SourceBackedPack{proof.entries[0].name: proof.entries[0].installedCompatibility},
	})
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	differentDatabaseRunner := testApplyAllSourceRevisionAdvanceExecutionProofRunner(&sql.DB{})

	got, err := bindApplyAllSourceRevisionAdvanceExecutionProof(
		differentDatabaseRunner, precondition, source, compatibility,
	)
	if err == nil || !strings.Contains(err.Error(), "execution runtime and active-runtime observation use different databases") {
		t.Fatalf("bind with different runtime database error = %v, want exact database-lineage rejection", err)
	}
	assertZeroApplyAllSourceRevisionAdvanceExecutionProof(t, got)
}

func TestValidateApplyAllSourceRevisionAdvanceExecutionProofRejectsMutation(t *testing.T) {
	tests := []struct {
		name   string
		mutate func(*applyAllSourceRevisionAdvanceExecutionProof)
	}{
		{name: "unminted provenance", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.provenance.minted = false
		}},
		{name: "coordinated truncation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries = proof.entries[:1]
			proof.provenance.entries = proof.provenance.entries[:1]
		}},
		{name: "runtime identity substitution", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.activeRuntimeIdentity = &applyAllSourceRevisionAdvanceActiveRuntimeIdentity{
				db: proof.provenance.activeRuntimeDatabase, snapshot: proof.provenance.activeRuntimeSnapshot,
			}
		}},
		{name: "runtime database mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.activeRuntimeIdentity.db = &sql.DB{}
		}},
		{name: "execution runtime substitution", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime = nil
		}},
		{name: "execution runtime database mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.runner.DB = nil
		}},
		{name: "execution runtime service graph mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.serviceGraph = newTestServiceGraph(testServiceGraphConfig{})
		}},
		{name: "execution runtime retained service graph database mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.serviceGraph.(*runnerServiceGraph).ServiceGraph = newTestServiceGraph(
				testServiceGraphConfig{DB: &sql.DB{}},
			)
		}},
		{name: "execution runtime apply dependency mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.applyDeps.Metadata = &metadata.MetadataService{}
		}},
		{name: "execution runtime apply option mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.applyDeps.Options.SkipPolymorphicDiscriminatorBackfill = true
		}},
		{name: "execution runtime registration mutation", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.executionRuntime.componentKindRegistrationSet = runnerTestRegistrationSet(t)
		}},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, 2)
			test.mutate(&proof)
			err := validateApplyAllSourceRevisionAdvanceExecutionProof(proof)
			assertApplyAllSourceRevisionComposeError(t, err, -1, "")
		})
	}
}

func TestValidateApplyAllSourceRevisionAdvanceExecutionProofRejectsEntryMutation(t *testing.T) {
	tests := []struct {
		name   string
		mutate func(*applyAllSourceRevisionAdvanceExecutionProof)
	}{
		{name: "reorder", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0], proof.entries[1] = proof.entries[1], proof.entries[0]
		}},
		{name: "row", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.row.Name = "other"
		}},
		{name: "pending alias", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.pending = proof.provenance.entries[0].expected.current.pending
		}},
		{name: "canonical name", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].name = "other"
			proof.provenance.entries[0].expected.name = "other"
		}},
		{name: "current target identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			entry := &proof.entries[0]
			advance := entry.current.advance
			replacement := testApplyAllSourceRevisionTarget(
				t, advance.Name, "1.0.0", advance.Kind, advance.URI, entry.current.row.SourceRevision.String,
			)
			entry.currentTarget = replacement
			proof.provenance.entries[0].expected.currentTarget = replacement
		}},
		{name: "replay base identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			entry := &proof.entries[0]
			advance := entry.current.advance
			replacement := testApplyAllSourceRevisionTarget(
				t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.FromRevision,
			)
			entry.replayBase = replacement
			proof.provenance.entries[0].expected.replayBase = replacement
		}},
		{name: "installed target identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			entry := &proof.entries[0]
			advance := entry.current.advance
			replacement := testApplyAllSourceRevisionTarget(
				t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision,
			)
			entry.installedCompatibility = replacement
			proof.provenance.entries[0].expected.installedCompatibility = replacement
		}},
		{name: "atom identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			replacement, err := packs.FreezeSourceBackedExecutionAtom(proof.entries[0].installedCompatibility)
			if err != nil {
				t.Fatalf("freeze replacement atom: %v", err)
			}
			proof.entries[0].atom = replacement
			proof.provenance.entries[0].expected.atom = replacement
		}},
		{name: "missing identities", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.provenance.entries[0].currentTargetIdentity = nil
			proof.provenance.entries[0].replayBaseIdentity = nil
			proof.provenance.entries[0].atomIdentity = nil
		}},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, 2)
			test.mutate(&proof)
			assertApplyAllSourceRevisionComposeError(
				t, validateApplyAllSourceRevisionAdvanceExecutionProof(proof), 3, "alpha",
			)
		})
	}
}

func TestValidateApplyAllSourceRevisionAdvanceExecutionProofRejectsCoordinatedSemanticMutation(t *testing.T) {
	tests := []struct {
		name   string
		mutate func(*applyAllSourceRevisionAdvanceExecutionProof)
	}{
		{name: "frozen row", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.row.Name = "other"
			proof.provenance.entries[0].expected.current.row.Name = "other"
		}},
		{name: "blank row identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.row.ID = ""
			proof.provenance.entries[0].expected.current.row.ID = ""
		}},
		{name: "blank pack install identity", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.row.PackInstallID = ""
			proof.provenance.entries[0].expected.current.row.PackInstallID = ""
		}},
		{name: "installed target plan", mutate: func(proof *applyAllSourceRevisionAdvanceExecutionProof) {
			proof.entries[0].current.advance.ToRevision = "other"
			proof.entries[0].current.pending.Authorization.ToRevision = "other"
			proof.provenance.entries[0].expected.current.advance.ToRevision = "other"
			proof.provenance.entries[0].expected.current.pending.Authorization.ToRevision = "other"
		}},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, 2)
			test.mutate(&proof)
			assertApplyAllSourceRevisionComposeError(
				t, validateApplyAllSourceRevisionAdvanceExecutionProof(proof), 3, "alpha",
			)
		})
	}
}

func TestValidateApplyAllSourceRevisionAdvanceExecutionProofRejectsMalformedEmptyProof(t *testing.T) {
	proof := testApplyAllSourceRevisionAdvanceExecutionProofForValidation(t, 0)
	proof.activeRuntimeIdentity = &applyAllSourceRevisionAdvanceActiveRuntimeIdentity{
		db: &sql.DB{}, snapshot: &packs.ActiveInstalledRuntimeSnapshot{},
	}
	assertApplyAllSourceRevisionComposeError(
		t, validateApplyAllSourceRevisionAdvanceExecutionProof(proof), -1, "",
	)
}

func testApplyAllSourceRevisionAdvanceExecutionProofForValidation(
	t *testing.T,
	count int,
) applyAllSourceRevisionAdvanceExecutionProof {
	t.Helper()
	return testApplyAllSourceRevisionAdvanceExecutionProofForDatabase(t, &sql.DB{}, count)
}

func testApplyAllSourceRevisionAdvanceExecutionProofForDatabase(
	t *testing.T,
	db *sql.DB,
	count int,
) applyAllSourceRevisionAdvanceExecutionProof {
	t.Helper()
	advances := []normalizedApplyAllSourceRevisionAdvance{
		testApplyAllSourceRevisionAdvance("alpha", 3),
		testApplyAllSourceRevisionAdvance("beta", 11),
		testApplyAllSourceRevisionAdvance("gamma", 19),
	}
	advances = advances[:count]
	precondition := applyAllSourceRevisionAdvancePreconditionProof{
		snapshot: applyAllSourceRevisionAdvanceCurrentSnapshot{entries: []applyAllSourceRevisionAdvanceCurrentSnapshotEntry{}},
		current: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
		},
		replay: applyAllSourceRevisionAdvanceTuple{
			plan: []normalizedApplyAllSourceRevisionAdvance{}, targets: map[string]*packs.SourceBackedPack{},
		},
	}
	sourceTuple := applyAllSourceRevisionAdvanceTuple{
		plan:    append([]normalizedApplyAllSourceRevisionAdvance{}, advances...),
		targets: map[string]*packs.SourceBackedPack{},
	}
	compatibilityTuple := applyAllSourceRevisionAdvanceTuple{
		plan:    append([]normalizedApplyAllSourceRevisionAdvance{}, advances...),
		targets: map[string]*packs.SourceBackedPack{},
	}
	for _, advance := range advances {
		currentTarget := testApplyAllSourceRevisionTarget(
			t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.FromRevision,
		)
		current := testApplyAllSourceRevisionAdvanceFrozenCurrentTargetProof(
			t, advance, currentTarget, installedPackStatusActive, advance.Kind,
			testCurrentTargetV1Hash, nil,
		)
		precondition.snapshot.entries = append(precondition.snapshot.entries, current.snapshot.entries[0])
		precondition.current.plan = append(precondition.current.plan, advance)
		precondition.current.targets[advance.Name] = currentTarget
		precondition.replay.plan = append(precondition.replay.plan, advance)
		precondition.replay.targets[advance.Name] = currentTarget
		sourceTuple.targets[advance.Name] = testApplyAllSourceRevisionTarget(
			t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision,
		)
		compatibilityTuple.targets[advance.Name] = testApplyAllSourceRevisionTarget(
			t, advance.Name, "1.0.0", advance.Kind, advance.URI, advance.ToRevision,
		)
	}
	if count != 0 {
		precondition.activeRuntime = testApplyAllSourceRevisionAdvanceActiveRuntimeObservationForDatabase(db)
	}
	compatibility := testApplyAllSourceRevisionAdvanceCompatibilityTuple(compatibilityTuple)
	compatibility.activeRuntimeIdentity = precondition.activeRuntime.identity
	var runner *Runner
	if count != 0 {
		runner = testApplyAllSourceRevisionAdvanceExecutionProofRunner(precondition.activeRuntime.identity.db)
	}
	proof, err := bindApplyAllSourceRevisionAdvanceExecutionProof(
		runner, precondition,
		testApplyAllSourceRevisionAdvanceSourceTuple(sourceTuple),
		compatibility,
	)
	if err != nil {
		t.Fatalf("bind validation fixture: %v", err)
	}
	return proof
}

func assertZeroApplyAllSourceRevisionAdvanceExecutionProof(
	t *testing.T,
	proof applyAllSourceRevisionAdvanceExecutionProof,
) {
	t.Helper()
	if proof.activeRuntimeIdentity != nil || proof.executionRuntime != nil || proof.entries != nil ||
		proof.provenance.minted || proof.provenance.activeRuntimeIdentity != nil ||
		proof.provenance.executionRuntime != nil ||
		proof.provenance.activeRuntimeDatabase != nil || proof.provenance.activeRuntimeSnapshot != nil ||
		proof.provenance.entries != nil || proof.provenance.entryCount != 0 {
		t.Fatalf("proof = %#v, want all-zero proof", proof)
	}
}

func testApplyAllSourceRevisionAdvanceActiveRuntimeObservation() applyAllSourceRevisionAdvanceActiveRuntimeObservation {
	return testApplyAllSourceRevisionAdvanceActiveRuntimeObservationForDatabase(&sql.DB{})
}

func testApplyAllSourceRevisionAdvanceActiveRuntimeObservationForDatabase(
	db *sql.DB,
) applyAllSourceRevisionAdvanceActiveRuntimeObservation {
	return applyAllSourceRevisionAdvanceActiveRuntimeObservation{
		identity: &applyAllSourceRevisionAdvanceActiveRuntimeIdentity{
			db: db, snapshot: &packs.ActiveInstalledRuntimeSnapshot{},
		},
		minted: true,
	}
}
