Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/guides/getting-started/repo-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,10 @@ upgraded keeps working there (the warning appears only in public
repositories). Any upgrade to a fullsend version with the new shim installs
the same `pull_request` shim, with the effects below.
`fullsend repos install` rewrites the trigger and the workflow pin in one
commit. After the upgrade:
commit. If it cannot fetch the templates of the new version, it upgrades
only the pin and prints `template fetch at the target ref failed: delivering
the pin upgrade only; run install again to deliver template changes`. Run it
again once the fetch works to deliver the trigger. After the upgrade:

- **Same-repo PRs** are reviewed automatically, as before, except while the
PR has a merge conflict: GitHub does not run `pull_request` workflows until
Expand Down
177 changes: 153 additions & 24 deletions internal/repos/converge.go
Original file line number Diff line number Diff line change
Expand Up @@ -3517,17 +3517,23 @@ func convergeScaffoldFiles(ctx context.Context,
// isUnstampedInstallRef). When neither fullsend_ref nor a release ref is
// available, the expected content is then still rendered, at
// config.DefaultUpstreamRef, exactly as that install rendered it.
//
// targetTemplates reports whether the expected files were rendered from
// templates that match the target ref: the remote fetch at the pinned ref
// succeeded, the install is vendored, or no explicit pin was set. It is
// false when a GitHub fetch failed and the running binary's embedded
// templates were used instead.
func convergeContentDriftFiles(ctx context.Context,
resolved ResolvedConfig,
cfg ConvergeConfig,
refResolver *RefResolver,
coveredPaths map[string]bool,
dcfg DriftConfig,
unstampedInstall bool,
progress ProgressFunc) ([]forge.TreeFile, []ComponentAction) {
progress ProgressFunc) (files []forge.TreeFile, actions []ComponentAction, targetTemplates bool) {
Comment thread
waynesun09 marked this conversation as resolved.
Resolved

repoFullName := resolved.Owner + "/" + resolved.Repo
var actions []ComponentAction
targetTemplates = true

targetRef := resolved.FullsendRef
if targetRef == "" && cfg.UpstreamRef == "" && !unstampedInstall {
Expand All @@ -3538,7 +3544,7 @@ func convergeContentDriftFiles(ctx context.Context,
progress(repoFullName, "content-drift",
fmt.Sprintf("scaffold content drift not checked: %s.fullsend_ref is not set and this build has no release ref; "+
"set %s.fullsend_ref to converge template changes such as runner tags", resolved.Forge, resolved.Forge))
return nil, actions
return nil, actions, targetTemplates
}

rref := resolveTargetRef(ctx, resolved.FullsendRef, cfg.UpstreamRef, cfg.UpstreamTag, refResolver)
Expand All @@ -3565,21 +3571,30 @@ func convergeContentDriftFiles(ctx context.Context,
installCfg.PrebuiltScaffoldFiles = scaffoldFiles
} else {
if resolved.Forge == ForgeGitLab {
return nil, []ComponentAction{{Component: "scaffold", Action: "error", Detail: fmt.Sprintf("fetching pinned GitLab scaffold: %v", fetchErr)}}
return nil, []ComponentAction{{Component: "scaffold", Action: "error", Detail: fmt.Sprintf("fetching pinned GitLab scaffold: %v", fetchErr)}}, false
}
targetTemplates = false
progress(repoFullName, "content-drift",
fmt.Sprintf("remote scaffold fetch failed, using embedded templates: %v", fetchErr))
}
}

// An explicit pin renders the target ref's templates only when they
// were fetched (or the install is vendored). Without a resolver the
// fetch never ran and the embedded templates are used, as after a
// failed fetch.
if manifestRef != "" && !installCfg.VendorBinary && installCfg.PrebuiltScaffoldFiles == nil {
targetTemplates = false
}

expectedFiles, buildErr := BuildScaffoldFiles(installCfg)
if buildErr != nil {
actions = append(actions, ComponentAction{
Component: "scaffold",
Action: "error",
Detail: fmt.Sprintf("failed to build expected scaffold for content drift check: %v", buildErr),
})
return nil, actions
return nil, actions, targetTemplates
}

// Content drift detection — shared between dry-run and live paths.
Expand All @@ -3595,7 +3610,7 @@ func convergeContentDriftFiles(ctx context.Context,
Action: "error",
Detail: fmt.Sprintf("content drift check failed: %v", driftErr),
})
return nil, actions
return nil, actions, targetTemplates
}

var repairFiles []forge.TreeFile
Expand Down Expand Up @@ -3624,13 +3639,9 @@ func convergeContentDriftFiles(ctx context.Context,
}
}

if cfg.DryRun && len(actions) > 0 {
progress(repoFullName, "dry-run",
fmt.Sprintf("Would repair %d files with content drift", len(actions)))
} else if len(repairFiles) > 0 {
progress(repoFullName, "repair",
fmt.Sprintf("Repairing %d files with content drift", len(repairFiles)))
}
// The caller reports the repair count after it filters the repairs
// (collectConvergeScaffoldFiles), so the count matches what is
// committed or previewed.

// Orphan file detection: check for managed scaffold files that
// exist on the forge but are no longer produced by the current
Expand All @@ -3650,7 +3661,7 @@ func convergeContentDriftFiles(ctx context.Context,
Action: "error",
Detail: fmt.Sprintf("orphan file check failed: %v", orphanErr),
})
return repairFiles, actions
return repairFiles, actions, targetTemplates
}
for _, o := range orphanFiles {
if coveredPaths[o.Path] {
Expand Down Expand Up @@ -3679,7 +3690,7 @@ func convergeContentDriftFiles(ctx context.Context,
Action: "error",
Detail: fmt.Sprintf("orphan variable check failed: %v", orphanVarErr),
})
return repairFiles, actions
return repairFiles, actions, targetTemplates
}
for _, o := range orphanVars {
actions = append(actions, ComponentAction{
Expand All @@ -3691,7 +3702,7 @@ func convergeContentDriftFiles(ctx context.Context,
fmt.Sprintf("Orphan variable %s (not in managed set)", o.Name))
}

return repairFiles, actions
return repairFiles, actions, targetTemplates
}

// resolvedRef holds the result of resolving a manifest's fullsend_ref
Expand Down Expand Up @@ -3837,6 +3848,71 @@ func convergeRepoCredentials(ctx context.Context, d convergeDiscovery, wifProvid
return actions, nil
}

// supersedePinOnlyRefFiles merges content-drift repairs into files, the
// scaffold files already queued. A repair for a pin-only ref path (see
// collectConvergeScaffoldFiles) replaces that queued file in place, so one
// run delivers both the new pin and any template change shipped with it,
// such as a changed shim trigger (#9714). The replacement keeps the pin the
// ref upgrade wrote (withQueuedPin), so the repository's pinning style
// (SHA with tag comment, plain tag or branch) does not change. A shim
// repair rendered at the other workflow extension (.yml vs .yaml) replaces
// the queued shim at its installed path instead of adding a second shim.
// Other repairs are appended.
func supersedePinOnlyRefFiles(files, driftFiles []forge.TreeFile, pinOnly map[string]bool, fc ForgeConfig) []forge.TreeFile {
workflowPaths := fc.WorkflowPaths
for _, df := range driftFiles {
idx := slices.IndexFunc(files, func(f forge.TreeFile) bool {
if !pinOnly[f.Path] {
return false
}
return f.Path == df.Path ||
(slices.Contains(workflowPaths, f.Path) && slices.Contains(workflowPaths, df.Path))
})
if idx < 0 {
files = append(files, df)
continue
}
files[idx].Content = withQueuedPin(df.Content, files[idx].Content, fc)
}
return files
}

// countUpdates counts the update actions in actions.
func countUpdates(actions []ComponentAction) int {
n := 0
for _, a := range actions {
if a.Action == "update" {
n++
}
}
return n
}

// withoutRefPathRepairs drops the content-drift repairs, and their update
// actions, for the paths skip selects.
func withoutRefPathRepairs(files []forge.TreeFile, actions []ComponentAction, skip func(string) bool) ([]forge.TreeFile, []ComponentAction) {
files = slices.DeleteFunc(files, func(f forge.TreeFile) bool { return skip(f.Path) })
actions = slices.DeleteFunc(actions, func(a ComponentAction) bool { return a.Action == "update" && skip(a.Component) })
return files, actions
}

// withQueuedPin returns full with every fullsend workflow pin replaced by
// the pin in queued, the pin-only rewrite convergeRefFiles produced. The
// content-drift template always renders a semver target as "<sha> # tag",
// while the ref upgrade keeps a repository's own style (a plain tag stays
// a plain tag). When queued has no pin, full is returned unchanged.
func withQueuedPin(full, queued []byte, fc ForgeConfig) []byte {
if fc.ShimRefPattern == nil {
return full
}
m := fc.ShimRefPattern.FindSubmatchIndex(queued)
if len(m) < 4 || m[3] < 0 {
return full
}
pin := strings.ReplaceAll(string(queued[m[3]:m[1]]), "$", "$$")
return []byte(fc.ShimRefPattern.ReplaceAllString(string(full), "${1}"+pin))
}

// collectConvergeScaffoldFiles plans atomic scaffold and configuration delivery.
// It returns the planned files and actions without writing credentials.
func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg ConvergeConfig, refResolver *RefResolver, progress ProgressFunc) ([]forge.TreeFile, []ComponentAction, error) {
Expand All @@ -3858,11 +3934,10 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg
}

// A ref upgrade only rewrites the shim's version marker. When the
// installed GitHub shim cannot forward FULLSEND_OPENAI_API_KEY, queueing
// that marker-only rewrite would also exclude the shim from content-drift
// repair and deliver a shim that still cannot use the selected credential.
// Leave the shim to content-drift repair, which renders the full template
// at the target ref.
// installed GitHub shim cannot forward FULLSEND_OPENAI_API_KEY, that
// marker-only rewrite would deliver a shim that still cannot use the
// selected credential. Leave the shim to content-drift repair, which
// renders the full template at the target ref.
refFiles, legacyErr := withoutLegacyOpenAIConsumer(ctx, resolved, refFiles)
if legacyErr != nil {
return allScaffoldFiles, actions, legacyErr
Expand Down Expand Up @@ -3917,8 +3992,28 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg
// structure changed between releases while the ref stayed the
// same). This is the gap that caused #6576: converge only checked
// presence, not content, so stale-but-present files were skipped.
contentDriftFiles, contentDriftActions := convergeContentDriftFiles(
ctx, resolved, cfg, refResolver, refFileSet,
//
// On GitHub every ref file is a pin-only rewrite (see
// convergeRefFiles), so content drift still checks those paths and
// may supersede them with the full template at the target ref. The
// dry run queues no ref files, so this also gives both runs the same
// skip set (#9714).
driftCoveredPaths := refFileSet
var pinOnlyPaths map[string]bool
if resolved.Forge != ForgeGitLab && len(refFiles) > 0 {
pinOnlyPaths = make(map[string]bool, len(refFiles))
for _, f := range refFiles {
pinOnlyPaths[f.Path] = true
}
driftCoveredPaths = make(map[string]bool, len(refFileSet))
for p := range refFileSet {
if !pinOnlyPaths[p] {
driftCoveredPaths[p] = true
}
}
}
contentDriftFiles, contentDriftActions, targetTemplates := convergeContentDriftFiles(
ctx, resolved, cfg, refResolver, driftCoveredPaths,
DriftConfig{
ReviewAppClientID: d.reviewClientID,
AgentRunnerTags: gitlabAgentRunnerTags(cfg.Manifest),
Expand All @@ -3927,6 +4022,39 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg
unstampedWorkflow(resolved.Forge, d.components),
progress,
)
// The drift templates replace the shim and thin callers on a ref
// upgrade only when they match the target ref. After a failed remote
// fetch they are the running binary's embedded templates, which can
// call inputs the target release lacks: keep the pin-only rewrite and
// leave the template change to the next run. Filtering here, before
// the actions are recorded, keeps the dry run and the live run in step.
if !targetTemplates && resolved.Forge != ForgeGitLab && slices.ContainsFunc(refActions, func(a ComponentAction) bool {
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
return a.Component == "ref" && a.Action == "upgrade"
}) {
// Both runs drop the repairs for every ref-upgrade path: the shim
// at either workflow extension (the template always renders
// fullsend.yaml, even for an installed fullsend.yml) and the thin
// callers. A legacy shim that withoutLegacyOpenAIConsumer took out
// of the queue also waits for a run whose fetch succeeds, rather
// than taking another release's template now. Using one rule in
// both runs keeps the dry run and the live run in step.
skip := func(p string) bool {
return slices.Contains(resolved.ForgeConfig.WorkflowPaths, p) || slices.Contains(scaffold.PerRepoThinCallerPaths(), p)
}
before := len(contentDriftActions)
contentDriftFiles, contentDriftActions = withoutRefPathRepairs(contentDriftFiles, contentDriftActions, skip)
if len(contentDriftActions) < before {
progress(resolved.Owner+"/"+resolved.Repo, "content-drift",
"template fetch at the target ref failed: delivering the pin upgrade only; run install again to deliver template changes")
}
}
if n := countUpdates(contentDriftActions); n > 0 {
if cfg.DryRun {
progress(resolved.Owner+"/"+resolved.Repo, "dry-run", fmt.Sprintf("Would repair %d files with content drift", n))
} else {
progress(resolved.Owner+"/"+resolved.Repo, "repair", fmt.Sprintf("Repairing %d files with content drift", n))
}
}
actions = append(actions, contentDriftActions...)

var contentErrors []string
Expand All @@ -3938,7 +4066,8 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg
if len(contentErrors) > 0 {
return allScaffoldFiles, actions, fmt.Errorf("convergence errors: %s", strings.Join(contentErrors, "; "))
}
allScaffoldFiles = append(allScaffoldFiles, contentDriftFiles...)
allScaffoldFiles = supersedePinOnlyRefFiles(allScaffoldFiles, contentDriftFiles,
pinOnlyPaths, resolved.ForgeConfig)

// Root input migration uses the wrapper that will actually be committed,
// including ref upgrades, repairs and remote pinned templates.
Expand Down
Loading
Loading