Files
mesh-delivery/modules/mesh-delivery-pipeline/internal/pipeline/steps.go
T
jschoubben 9ab1c3b8f3 H-A-375: a declined pipeline step is put again on a node that has its need
A holder whose node lacks what a step's packages need (the artifact's
check-needs, now named on the integration step's ask) says the step's end
declined with needs and lacks, in place of could not run. The runner puts
it again under a new ask id naming in not-on the nodes that declined it;
a holder on a listed node hands it back at once. The nodes that can take it
are the holders of the step's seat and of the need's seat less those that
declined; when none is left the step ends could not run naming the need
and the nodes asked. The build-step part's form is 3, the runner seat's 5.

Builds: design 47 H2 H-A-375, H-A-445 (ADR 0552 §2, §4)
2026-11-22 02:08:40 +01:00

942 lines
40 KiB
Go

package pipeline
import (
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strings"
"time"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
nodebuildimage "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildimage"
nodebuildnode "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
"git.novox.be/novox/mesh-sdk/go/keys"
runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient"
)
// StepSeat is a seat whose holder runs the lint and test steps (design 47 G §22, §24): where the runner hears its
// step-ended, on the subject of the node that ran it.
type StepSeat struct {
Seat string
// Prefix is the subject before <node>.
Prefix string
// Decode reads the seat's step-ended body; nil is the build seats' one form.
Decode func([]byte) (StepEnded, error)
// Shared reads the runs a step-ended names in `shared`, carried into the step's result as they came (A-468d); nil for
// a seat whose ends name none.
Shared func([]byte) []seat.Shared
// Pins reads the pins a build's end names it was built with (H-A-207); nil for a seat whose ends name none.
Pins func([]byte) map[string]string
}
// StepSeats are the three build seats, from their contracts.
var StepSeats = []StepSeat{
{Seat: nodebuildgo.Seat, Prefix: strings.TrimSuffix(nodebuildgo.SubjectStepEndedAll, "*")},
{Seat: nodebuildnode.Seat, Prefix: strings.TrimSuffix(nodebuildnode.SubjectStepEndedAll, "*")},
{Seat: nodebuildimage.Seat, Prefix: strings.TrimSuffix(nodebuildimage.SubjectStepEndedAll, "*")},
// The seat mesh-builds answers the build step of a candidate, one entry named by its fingerprint (A-97, A-99).
{Seat: builds.Seat, Prefix: strings.TrimSuffix(builds.SubjectStepEndedAll, "*"), Decode: decodeBuildEnded, Pins: buildPins},
// The seat mesh-wants answers the composition step (§22, §24).
{Seat: wants.Seat, Prefix: strings.TrimSuffix(wants.SubjectStepEndedAll, "*"), Decode: decodeWantsEnded, Shared: wantsShared},
}
// wantsShared is the composition runs a mesh-wants step-ended names, one per machine (design 47 G §723, §729; A-468d,
// A-469t): the same form, under the same name.
func wantsShared(raw []byte) []seat.Shared {
var w wants.StepEnded
if json.Unmarshal(raw, &w) != nil || len(w.Shared) == 0 {
return nil
}
out := make([]seat.Shared, 0, len(w.Shared))
for _, x := range w.Shared {
e := seat.Shared{Machine: x.Machine, Run: x.Run, Ask: x.Ask}
if x.AskedBy != nil {
e.AskedBy = &seat.SharedAskedBy{Pipeline: x.AskedBy.Pipeline, Artifact: x.AskedBy.Artifact}
}
out = append(out, e)
}
return out
}
// decodeWantsEnded reads the composition step's end of the seat mesh-wants as the form the hearer holds each end to; a
// warning of a node asleep (a pass with a warning, ADR 0593 §9) is the step's `why` when the end says nothing else.
func decodeWantsEnded(raw []byte) (StepEnded, error) {
var w wants.StepEnded
if err := json.Unmarshal(raw, &w); err != nil {
return StepEnded{}, err
}
said := w.Said
if said == "" && len(w.Warnings) > 0 {
said = strings.Join(w.Warnings, "; ")
}
return StepEnded{V: w.V, ID: w.ID, Pipeline: w.Pipeline, Step: w.Step, Module: w.Module, Commit: w.Commit, Fingerprint: w.Fingerprint,
Node: w.Node, Outcome: w.Outcome, Said: said, Rerun: w.Rerun, By: w.By, Started: w.Started, Ended: w.Ended}, nil
}
// buildPins is the pins a build step's end of the seat mesh-builds names its entry was built with (H-A-207).
func buildPins(raw []byte) map[string]string {
var b builds.StepEnded
if json.Unmarshal(raw, &b) != nil {
return nil
}
return b.Packages
}
// decodeBuildEnded reads the build step's end of the seat mesh-builds as the form the hearer holds each end to: its one
// entry names the module, the commit and the fingerprint the step was asked at; an end naming another number of entries is
// refused (A-99).
func decodeBuildEnded(raw []byte) (StepEnded, error) {
var b builds.StepEnded
if err := json.Unmarshal(raw, &b); err != nil {
return StepEnded{}, err
}
if len(b.Entries) != 1 {
return StepEnded{}, fmt.Errorf("%w: ask %s ended a build of %d entries, asked of one", ErrRefused, b.ID, len(b.Entries))
}
e := b.Entries[0]
return StepEnded{V: b.V, ID: b.ID, Pipeline: b.Pipeline, Step: b.Step, Module: e.Module, Commit: e.Commit, Fingerprint: e.Fingerprint,
Node: b.Node, Outcome: b.Outcome, Said: b.Said, Rerun: b.Rerun, By: b.By, Started: b.Started, Ended: b.Ended}, nil
}
// StepEnded is a build seat's step-ended. The three seats' bodies are one form, the part build-step's, held equal by
// their definitions, so the runner reads each in this one type.
type StepEnded = nodebuildgo.StepEnded
// ErrRefused is a step-ended the runner does not take: not the node's holder's subject, or naming an ask, a commit or a
// fingerprint the runner did not ask (ADR 0666 §21; design 47 G §24). It is said, never taken.
var ErrRefused = errors.New("a step's end the runner does not take")
// ErrChanged is an Updater's answer to an Update whose revision is no longer the key's: another write came between.
var ErrChanged = errors.New("the pipeline was written since it was read")
// Updater is the state pipelines read and written by compare-and-set on the revision read (§27).
type Updater interface {
Get(key string) (seat.Pipeline, uint64, error)
Update(key string, p seat.Pipeline, revision uint64) (uint64, error)
// Keys are the keys matching a filter, `*` one key part.
Keys(filter string) ([]string, error)
}
// Hearer takes the steps' ends into their pipelines and ends a pipeline whose every step ended (design 47 G §24, §27).
type Hearer struct {
Store Updater
// Say says one of the runner's events of a pipeline, on its subject; Log appends to the step log.
Say func(subject string, body any) error
Log func(seat.LogEntry) error
// LogLast is the step log's last entry of a pipeline, nil when it has none (§549).
LogLast func(pipeline string) (*seat.LogEntry, error)
// Keep writes one package's passing result into the state kept, under its key (§27): only from a step's end the
// runner took, so a kept result is its seat holder's alone.
Keep func(key string, k seat.KeptResult) error
// Asker publishes an approval step's ask (§37); Name is the runner's own name, the asker a warrant names.
Asker Asker
Name string
// Where reads the router's record of one of the runner's asks, as operatorchannelclient.Client.Where does: its state and
// its warrant (design 47 G A-89, §700).
Where func(ask string) (string, *oc.Warrant, error)
Logf func(string, ...any)
Now func() time.Time
// Failures says a failed head as the finding pipeline-failed (§33); nil says none.
Failures *Failures
// RegistrationWaits judges, at every pipeline's end, the finding registration-missing of the modules no running pipeline
// still waits on (Starter.JudgeRegistrationMissing, H-A-265 (4)); nil judges none.
RegistrationWaits func()
// Ager ages the runner's own kept data at each step's end (§330); nil ages none.
Ager *Ager
// Fills says the stores' fill at each step's end (§366); nil says none.
Fills *Fills
// Widens makes, for one end, the reader of each mover's widens, kept in its value at the pipeline's end (§71, A-207;
// H-A-51): made before the end's compare-and-set, its reads shared by every mover and every retry (H-A-289); nil keeps none.
Widens func() func(p seat.Pipeline, module string) []seat.Widening
// TestRuns is the state test-runs and Clock its bound keys (§725); Runs the settings of its runs; DropRun drops a
// run's ask when its run ends unfinished (§119). A nil TestRuns keeps no test run.
TestRuns TestRuns
Clock RunClock
Runs RunSettings
DropRun Drop
// RunOutputs keeps a test run's output in test-runs-objects (§725, A-466v).
RunOutputs RunObjects
// AskSteps puts the asks a step's end made due, a mover's composition once validate passed (§745; Starter.AskSteps);
// nil asks none.
AskSteps func(key string, asks []Asked) error
// Release places the movers of a pipeline whose awaited publishes are heard now, after a build step passed (a kind-3
// edge, §746; Starter.Release); nil places none.
Release func(key string)
// AskPinHeld asks a mover's steps that waited for its entry's pins with the pins its build passed with (H-A-207;
// Starter.AskPinHeld); nil leaves them waiting.
AskPinHeld func(key, module string, pins map[string]string)
// Turn takes a pipeline's end into the queue, its running key deleted and the next placed (design 47 H §748;
// Starter.Turn); nil takes none.
Turn func(key string)
// Unplaced says why a mover of a pipeline has no step placed, for the why of its end (H-A-171; Starter.Unplaced): it
// waits on its registration or on a publish; nil says only that it has no step placed.
Unplaced func(p seat.Pipeline, module string) string
// Asks clears the finding of an ask that ended its step unanswered once it is answered after all (H-A-238 (2)); nil
// clears none.
Asks *AskClock
// Rejoin keys a pipeline running again once its approval is answered and it still runs (H-A-106 (b); Starter.Rejoin);
// nil keys none.
Rejoin func(key string)
// Unfinished keeps, at every end, the movers it leaves unfinished in the state unfinished (design 47 H2 §786); nil keeps
// none.
Unfinished *Unfinished
// NeedNodes are the nodes holding every seat of seats now, from the seat-holders view, and whether that view is read; a
// declined step is put again only on a node it names (design 47 H2 H-A-375, H-A-445). Nil knows none.
NeedNodes func(seats []string) ([]string, bool)
// AskDeclined is the ask of a declined step s of p under a new id (Verbs.DeclinedAsk), and PutAgain puts it on its seat's
// queue (Starter.PutAgain); with either nil a declined step ends could not run.
AskDeclined func(p seat.Pipeline, s seat.StepResult, now time.Time) (*Asked, error)
PutAgain func(key string, a Asked) error
}
// EndReaders ends each of readers' steps of run with r's result (§725, §726): a step that read an ended run, or the steps
// of a run that was never asked.
func (h *Hearer) EndReaders(run string, readers []seat.TestRunReader, r seat.TestRun) error {
var first error
for _, reader := range readers {
if err := h.endReader(RunReader{Pipeline: reader.Pipeline, Artifact: reader.Artifact}, run, Run{TestRun: r}); err != nil && first == nil {
first = err
}
}
return first
}
// kept is pipeline key's kept-revisions (H-A-285, H-A-286); none when they cannot be read, said.
func (h *Hearer) kept(key string) map[string]int64 {
kept, err := keptOfStore(h.Store, key)
if err != nil {
h.logf("the kept-revisions of %s are not read, so its kept movers' asks take the ids of movers not kept: %v", key, err)
}
return kept
}
func (h *Hearer) now() time.Time {
if h.Now != nil {
return h.Now().UTC()
}
return time.Now().UTC()
}
// OnStepEnded takes the step-ended heard on subject, from seat's holders. It is refused, and said, when the subject's
// node is not the one the body names, when no pipeline the runner keeps names the ask, or when the ask's step names
// another seat, commit, fingerprint, module or step (ADR 0666 §21; the bus grants step-ended.<node> to that node's
// holder alone, so the subject's node is the account's). A step already ended takes nothing (the bus gives an event again).
func (h *Hearer) OnStepEnded(bs StepSeat, subject string, ev StepEnded) (seat.Pipeline, error) {
return h.OnStepEndedShared(bs, subject, ev, nil)
}
// OnStepEndedShared is OnStepEnded of an end naming the runs it read in shared (A-468d): kept on the step's result. The end
// of a test run's ask also ends the run, its output kept in test-runs-objects, and every other step reading it (§725, §726,
// A-469m).
func (h *Hearer) OnStepEndedShared(bs StepSeat, subject string, ev StepEnded, shared []seat.Shared) (seat.Pipeline, error) {
return h.OnStepEndedPinned(bs, subject, ev, shared, nil)
}
// OnStepEndedPinned is OnStepEndedShared of a build's end naming the pins it was built with (H-A-207): a passed build's
// mover's steps that waited for its entry's pins are asked with them.
func (h *Hearer) OnStepEndedPinned(bs StepSeat, subject string, ev StepEnded, shared []seat.Shared, pins map[string]string) (seat.Pipeline, error) {
node := strings.TrimPrefix(subject, bs.Prefix)
if node == subject || node == "" || strings.Contains(node, ".") {
return seat.Pipeline{}, fmt.Errorf("%w: %s is not a subject of %s's step-ended", ErrRefused, subject, bs.Seat)
}
if ev.Node != node {
return seat.Pipeline{}, fmt.Errorf("%w: ask %s ended on %s's subject names node %q", ErrRefused, ev.ID, node, ev.Node)
}
// The end of a step another asker asked (the assigner's composer build) is not the runner's: it is read before any
// pipeline, and writes and says nothing (design 47 G §24, §69). A seat whose end names no asker is held to the store.
if ev.Asker != "" && ev.Asker != h.Name {
return seat.Pipeline{}, nil
}
wr := h.widensReads() // made before the compare-and-set, kept for its retries (H-A-289)
for {
p, rev, err := h.Store.Get(ev.Pipeline)
if err != nil {
return seat.Pipeline{}, fmt.Errorf("%w: ask %s names pipeline %q, which the runner cannot read: %v", ErrRefused, ev.ID, ev.Pipeline, err)
}
i := stepOfAsk(p, ev.ID)
// The validate ask is the pipeline's one, naming no mover (H-A-51): its end, naming the mover whose body the holder
// took, is matched by its ask alone and ends every mover's validate step under it (H-A-252).
oneValidate := i >= 0 && p.Steps[i].Step == seat.StepResultStepValidate && p.Steps[i].Seat == wants.Seat
if oneValidate {
i = validateStepOfAsk(p, ev.ID, ev.Module)
}
var m seat.Mover
if i >= 0 {
m, _ = MoverOf(p, p.Steps[i].Module)
}
switch {
case i < 0:
return p, fmt.Errorf("%w: pipeline %s asked no step under ask %s", ErrRefused, ev.Pipeline, ev.ID)
case p.Steps[i].Seat != bs.Seat:
return p, fmt.Errorf("%w: ask %s was asked of %s, not %s", ErrRefused, ev.ID, p.Steps[i].Seat, bs.Seat)
case ev.Step != p.Steps[i].Step || (!oneValidate && (ev.Commit != m.Commit || ev.Fingerprint != m.Fingerprint || ev.Module != m.Module)):
return p, fmt.Errorf("%w: ask %s ended %s of %s at %s (%s), asked as %s of %s at %s (%s)", ErrRefused, ev.ID, ev.Step,
ev.Module, ev.Commit, ev.Fingerprint, p.Steps[i].Step, p.Steps[i].Module, m.Commit, m.Fingerprint)
case !open(p.Steps[i]):
h.Asks.answeredLate(p.Steps[i], h.logf)
// An end heard late moves nothing of its step, and still places what that step's end unlocks (H-A-311 (2)).
defer h.releaseLate(ev.Pipeline)
if run := sharedRun(p.Steps[i]); run != "" && h.TestRuns != nil {
if r, _, err := h.TestRuns.Get(run); err == nil && r.Ended == nil && r.Ask == ev.ID {
// The asking step's end was written and its run's was not (a write failed): the run ends now, heard again.
return p, h.endRunOf(p, p.Steps[i], ev)
}
// The run ended before its ask's end came (its bound, a drop): the end is ignored and said (§720, §725).
h.logf("the step-ended of ask %s is ignored: its test run %s ended before it (%s)", ev.ID, run, p.Steps[i].Why)
}
return p, nil
case !endOutcome(ev.Outcome):
return p, fmt.Errorf("%w: ask %s ended %q, not an outcome of step-ended", ErrRefused, ev.ID, ev.Outcome)
}
now := h.now()
s := &p.Steps[i]
if ev.Outcome == nodebuildgo.StepEndedOutcomeDeclined {
// Declined for a need the node lacks (design 47 H2 H-A-375, H-A-445): put again on a node that has it, or, none
// left, ended could not run naming the need and the nodes asked.
old := s.Ask
a, why := h.declinedAgain(&p, i, ev, node, now)
if a != nil {
if _, err := h.Store.Update(ev.Pipeline, p, rev); errors.Is(err, ErrChanged) {
continue
} else if err != nil {
return p, fmt.Errorf("pipeline %s cannot be written: %w", ev.Pipeline, err)
}
if err := h.putDeclined(ev.Pipeline, old, p.Steps[i], *a, ev); err != nil {
h.logf("%s: the declined ask %s is written as %s and not put, put again at the next start: %v", ev.Pipeline, old, a.ID, err)
}
return p, nil
}
ev.Outcome, ev.Said = nodebuildgo.StepEndedOutcomeCouldNotRun, why
}
s.Outcome, s.Node, s.Why, s.Rerun, s.By, s.Ended = ev.Outcome, node, ev.Said, ev.Rerun, ev.By, &now
if len(shared) > 0 {
s.Shared = shared
}
if ev.Tests != nil {
s.Tests = &seat.TestCounts{Unit: ev.Tests.Unit, Integration: ev.Tests.Integration}
}
var keptKeys []string
for _, k := range ev.Kept {
keptKeys = append(keptKeys, seat.KeptByLevelDigestKey(keys.EscapeName(k.Level), keys.EscapeName(k.Digest)))
}
unlogged := endEntry(ev.Pipeline, *s, now, keptKeys...)
p.Unlogged = append(p.Unlogged, unlogged)
// The steps of this pipeline reading the run end in the same write, so the pipeline ends once (§726, §727).
readers := h.sameRunReaders(&p, i, ev, now)
// Every mover's validate reads the one run (§745, H-A-51); its end asks each mover's composition, or ends it not
// asked when validate did not pass.
var due []Asked
askHeld := false
if s.Step == seat.StepResultStepBuild {
readers = append(readers, endPinHeld(&p, *s, pins, now)...)
askHeld = stepPassed(*s) && heldOn(p, s.Module)
}
if s.Step == seat.StepResultStepValidate {
readers = append(readers, sameValidate(&p, i, now)...)
var notAsked []int
due, notAsked = releaseCompositions(&p, now, h.kept(ev.Pipeline))
readers = append(readers, notAsked...)
}
from := now
if ev.Ended != nil {
from = ev.Ended.UTC()
}
asked, err := askApproval(ev.Pipeline, &p, from, h.Asker)
if err != nil {
return p, err
}
// A mover's build passed is what a kind-3 edge waits for (§746, H-A-83 (2)); one that did not pass ends its
// dependents' steps not asked.
release := s.Step == seat.StepResultStepBuild && (!stepPassed(*s) || built(&p, s.Module))
// A build that passes, a rerun's among them, places again the steps that ended not asked on it (H-A-406): its
// dependents need no hand rerun.
var again []string
if s.Step == seat.StepResultStepBuild && stepPassed(*s) {
if again = takeOutNotAsked(&p, s.Module); len(again) > 0 {
release = true
}
}
ended := h.endPipeline(&p, now, wr)
if _, err := h.Store.Update(ev.Pipeline, p, rev); errors.Is(err, ErrChanged) {
continue
} else if err != nil {
return p, fmt.Errorf("pipeline %s cannot be written: %w", ev.Pipeline, err)
}
// The run's end is written as its step-ended is heard, before any finding the step says, so no wait elsewhere (a
// finding's event the bus is slow to take) delays it past its bound (A-470o).
runErr := h.endRunOf(p, *s, ev)
if h.Keep != nil {
for _, k := range ev.Kept {
kept := seat.KeptResult{Digest: k.Digest, Level: k.Level, Package: k.Package, Pipeline: k.Pipeline, LastRead: &now}
if k.Toolchain != nil {
kept.Toolchain = &seat.ToolchainUsed{Language: k.Toolchain.Language, Recipe: k.Toolchain.Recipe, Version: k.Toolchain.Version}
}
if kept.Pipeline == "" {
kept.Pipeline = ev.Pipeline
}
if err := h.Keep(seat.KeptByLevelDigestKey(keys.EscapeName(k.Level), keys.EscapeName(k.Digest)), kept); err != nil {
h.logf("the passing result of %s (%s) at %s is not kept, so it runs again next time: %v", k.Package, k.Level, k.Digest, err)
}
}
}
h.Failures.StepEnded(h.Store, p, *s)
if err := h.say(seat.EventStepEnded, p, s); err != nil {
return p, fmt.Errorf("pipeline %s's %s is written but not said: %w", ev.Pipeline, seat.EventStepEnded, err)
}
for _, j := range readers {
if err := h.say(seat.EventStepEnded, p, &p.Steps[j]); err != nil {
return p, fmt.Errorf("pipeline %s's %s is written but not said: %w", ev.Pipeline, seat.EventStepEnded, err)
}
}
if len(again) > 0 {
h.logf("%s: %s, not asked on %s, which built now, placed again (H-A-406)", ev.Pipeline, strings.Join(again, ", "), s.Module)
}
if release && h.Release != nil {
h.Release(ev.Pipeline)
}
if askHeld && h.AskPinHeld != nil {
h.AskPinHeld(ev.Pipeline, s.Module, pins)
}
if h.AskSteps != nil && len(due) > 0 {
if err := h.AskSteps(ev.Pipeline, due); err != nil {
h.logf("the compositions of %s are written running and not asked, asked again at the next start: %v", ev.Pipeline, err)
}
}
// The step's end is written and said before its log entry is appended, so a log that refuses ends no step (§486, §606).
h.appendUnlogged(ev.Pipeline)
h.Ager.Age()
h.Fills.Check()
if err := h.said(p, asked, ended); err != nil {
return p, err
}
return p, runErr
}
}
// sameRunReaders ends, in p, every other step reading the test run step i asked with ev, its ask's end: a running reader,
// and one the rerun that asked the run marked, which moves (A-470d, A-470e), said again marked a rerun by that caller. It
// answers their indexes.
func (h *Hearer) sameRunReaders(p *seat.Pipeline, i int, ev StepEnded, now time.Time) []int {
asker := p.Steps[i]
run := sharedRun(asker)
if run == "" || h.TestRuns == nil || asker.Ask != ev.ID {
return nil
}
marks := map[string]RunReader{}
if r, _, err := h.TestRuns.Get(run); err == nil {
for _, o := range r.Readers {
if o.Pipeline == p.Pipeline {
marks[o.Artifact] = o
}
}
}
var out []int
for j := range p.Steps {
s := &p.Steps[j]
if j == i || sharedRun(*s) != run {
continue
}
switch m := marks[s.Artifact]; {
case open(*s) && s.Ask == "":
case m.Rerun && s.Shared[0].Ask != ev.ID && s.Accepted == nil:
s.Rerun, s.By = true, m.By
s.Shared = []seat.Shared{{Run: run, Ask: ev.ID, AskedBy: &seat.SharedAskedBy{Pipeline: p.Pipeline, Artifact: asker.Artifact}}}
default:
continue
}
s.Outcome, s.Why, s.Node, s.Ended, s.Tests = asker.Outcome, asker.Why, asker.Node, &now, nil
if asker.Tests != nil {
t := *asker.Tests
s.Tests = &t
}
p.Unlogged = append(p.Unlogged, endEntry(p.Pipeline, *s, now))
out = append(out, j)
}
return out
}
// endRunOf ends the test run step s of p asked, with the end ev of its ask (§725, §726): the run's output kept in
// test-runs-objects under the run's key, its outcome, words, counts and node written, and every other reader ended with it.
// A step that asked no run ends nothing more.
func (h *Hearer) endRunOf(p seat.Pipeline, s seat.StepResult, ev StepEnded) error {
run := sharedRun(s)
if run == "" || h.TestRuns == nil || s.Ask != ev.ID {
return nil
}
end := seat.TestRun{Ask: ev.ID, Outcome: ev.Outcome, Said: ev.Said, Node: ev.Node}
if ev.Tests != nil {
end.Tests = &seat.TestCounts{Unit: ev.Tests.Unit, Integration: ev.Tests.Integration}
}
if h.RunOutputs != nil {
// The run's output object holds the packages it ran with their digests and the build seat's output (§725).
out := RunOutput{Output: ev.Output, Packages: []seat.TestRunPackage{}}
for _, k := range append(append([]nodebuildgo.KeptResult(nil), ev.Kept...), ev.Carried...) {
out.Packages = append(out.Packages, seat.TestRunPackage{Package: k.Package, Digest: k.Digest})
}
raw, err := json.Marshal(out)
if err == nil {
err = h.RunOutputs.Put(run, raw)
}
if err != nil {
return fmt.Errorf("the output of the test run %s cannot be kept: %w", run, err)
}
end.Output = run
}
return h.EndRun(run, end, &seat.TestRunReader{Pipeline: p.Pipeline, Artifact: s.Artifact})
}
// said says what a written pipeline became: an approval asked is a wait held on the operator (ADR 0283), never a stall;
// an end is said once, on <branch>.<revision> (design 47 H §746). The runner says no group-ended (§764).
func (h *Hearer) said(p seat.Pipeline, asked []int, ended bool) error {
for _, i := range asked {
if err := h.say(seat.EventWaitHeld, p, &p.Steps[i]); err != nil {
return fmt.Errorf("pipeline %s waits on the operator but %s is not said: %w", p.Pipeline, seat.EventWaitHeld, err)
}
}
// A pipeline waiting on the operator's approval alone does not count against pipelines-at-once (§748, H-A-106 (b)): its
// running key goes and the next waiting is placed, as at an end.
if !ended && h.Turn != nil && awaitsApprovalOnly(p) {
h.Turn(p.Pipeline)
}
if ended {
// The journal says which end it was (H-A-288).
if p.Why != "" {
h.logf("%s ended %s: %s", p.Pipeline, p.Outcome, p.Why)
} else {
h.logf("%s ended %s", p.Pipeline, p.Outcome)
}
h.Failures.Ended(p)
h.Unfinished.Ended(p)
if h.RegistrationWaits != nil {
h.RegistrationWaits()
}
err := h.say(seat.EventPipelineEnded, p, nil)
// Every end, a cancel's alike, places the next waiting (§748, H-A-53), said or not.
if h.Turn != nil {
h.Turn(p.Pipeline)
}
if err != nil {
return fmt.Errorf("pipeline %s ended but %s is not said: %w", p.Pipeline, seat.EventPipelineEnded, err)
}
}
return nil
}
// EndAtStart judges, at the runner's start pass, the end of every running pipeline nothing of which is still open (H-A-288
// (c)): one whose last mover left or whose last open step ended while no runner wrote its end ends as at a step's end,
// superseded, failed or passed by the end judgement, said, and the next waiting placed. It answers how many it ended.
func (h *Hearer) EndAtStart() (int, error) {
pkeys, err := allKeys(h.Store)
if err != nil {
return 0, fmt.Errorf("the pipelines are not listed: %w", err)
}
n := 0
var first error
for _, key := range pkeys {
ended, err := h.endIfNothingOpen(key)
if err != nil && first == nil {
first = err
}
if ended {
n++
}
}
return n, first
}
// endIfNothingOpen ends the running pipeline key when nothing of it is still open (H-A-288), its reads made before the
// compare-and-set (H-A-289); true when it ended.
func (h *Hearer) endIfNothingOpen(key string) (bool, error) {
wr := h.widensReads()
for {
p, rev, err := h.Store.Get(key)
if err != nil || p.Outcome != seat.PipelineOutcomeRunning {
return false, nil
}
now := h.now()
if !h.endPipeline(&p, now, wr) {
return false, nil
}
if _, err := h.Store.Update(key, p, rev); errors.Is(err, ErrChanged) {
continue
} else if err != nil {
return false, fmt.Errorf("pipeline %s cannot be written: %w", key, err)
}
h.logf("%s had nothing open at the runner's start: its end is written now (H-A-288)", key)
return true, h.said(p, nil, true)
}
}
// endEntry is the step log's entry of a step's end, with the keys of the kept results it wrote or carried.
func endEntry(key string, s seat.StepResult, at time.Time, kept ...string) seat.LogEntry {
return seat.LogEntry{Pipeline: key, Module: s.Module, Step: s.Step, Artifact: s.Artifact, What: seat.LogEntryWhatEnded, Outcome: s.Outcome,
Kept: kept, At: at}
}
// sayStepEnded is the one place a step's step-ended is said (design 47 H2 §784): it writes the journal line "step ended
// <pipeline> <mover> <step> <outcome> in <duration>" (its duration from its start to its end, "no start" for a step that
// never started) and says the event of p, at at, through say. Every end goes through it: the hearer's, the end at
// placing, a supersede, a re-pin, the approval's end, the start pass and the verbs that end a step.
func sayStepEnded(logf func(string, ...any), say func(subject string, body any) error, p seat.Pipeline, s seat.StepResult, at time.Time) error {
if logf != nil {
mover, took := s.Module, "no start"
if mover == "" {
mover = "-"
}
if s.Started != nil && s.Ended != nil {
took = s.Ended.Sub(*s.Started).Round(time.Millisecond).String()
}
logf("step ended %s %s %s %s in %s", p.Pipeline, mover, s.Step, s.Outcome, took)
}
if say == nil {
return nil
}
subject, ev := stepEvent(seat.EventStepEnded, p, s, at)
return say(subject, ev)
}
func (h *Hearer) logf(format string, args ...any) {
if h.Logf != nil {
h.Logf(format, args...)
}
}
// say says one event of p on the runner's subject for it; step, when not nil, is the result a step event or a wait
// carries. A step's events are said on <module>.<branch>.<commit> of its mover; a pipeline's end and its waits on
// <branch>.<source> (design 47 H §746, H-A-72 (3), (4)).
func (h *Hearer) say(event string, p seat.Pipeline, step *seat.StepResult) error {
at := h.now()
switch event {
case seat.EventStepEnded:
return sayStepEnded(h.logf, h.Say, p, *step, at)
case seat.EventStepStarted:
subject, ev := stepEvent(event, p, *step, at)
return h.Say(subject, ev)
case seat.EventPipelineEnded:
return h.Say(runnerclient.RevisionSubject(event, p.Branch, subjectRevision(p)), pipelineEnded(p))
default:
w := seat.Wait{V: 1, Pipeline: p.Pipeline, Branch: p.Branch, Revision: p.Revision, Source: p.Source, Run: p.Run,
Step: seat.WaitStepApproval, On: seat.WaitOnPerson, Since: at}
if step != nil {
m, _ := MoverOf(p, step.Module)
w.Module, w.Commit, w.Fingerprint, w.Step, w.Ask = m.Module, m.Commit, m.Fingerprint, step.Step, step.Ask
}
return h.Say(runnerclient.RevisionSubject(event, p.Branch, subjectRevision(p)), w)
}
}
// stepEvent is a step's step-started or step-ended of p, on the runner's subject for its mover: its result as it stands,
// with its shared when it reads a run (§729; A-468e, A-469q; H §746).
func stepEvent(event string, p seat.Pipeline, step seat.StepResult, at time.Time) (string, seat.StepEvent) {
if event == seat.EventStepStarted {
// A step-started names the run and its ask, never the step that asked it (A-469q).
var shared []seat.Shared
for _, x := range step.Shared {
x.AskedBy = nil
shared = append(shared, x)
}
step.Shared = shared
}
m, _ := MoverOf(p, step.Module)
return runnerclient.Subject(event, m.Module, p.Branch, m.Commit), seat.StepEvent{V: 1, At: &at, Pipeline: p.Pipeline,
Branch: p.Branch, Module: m.Module, Commit: m.Commit, Fingerprint: m.Fingerprint, Revision: p.Revision, Source: p.Source,
Run: p.Run, Result: step}
}
// The test budget per catalog module (design 47 G §24, §419; the test budget): at most 500 unit and 50 integration tests.
const (
budgetUnit = 500
budgetIntegration = 50
)
// testCounts is the module's test counts, the sum of its test steps' own counts, each test run counted once however many
// steps read it (§726, A-466i); nil when no step counted any.
func testCounts(steps []seat.StepResult) *seat.TestCounts {
var t seat.TestCounts
counted := false
runs := map[string]bool{}
for _, s := range steps {
if run := sharedRun(s); run != "" && s.Seat != wants.Seat {
if runs[run] {
continue
}
runs[run] = true
}
if s.Tests != nil {
t.Unit, t.Integration, counted = t.Unit+s.Tests.Unit, t.Integration+s.Tests.Integration, true
}
}
if !counted {
return nil
}
return &t
}
// stepsOf are the steps of p's mover module.
func stepsOf(p seat.Pipeline, module string) []seat.StepResult {
out := []seat.StepResult{}
for _, s := range p.Steps {
if s.Module == module {
out = append(out, s)
}
}
return out
}
// pipelineEnded is p's pipeline-ended (design 47 H §746): its key, branch, source, call, revision and outcome, and per
// mover, in the delivery order of its tiers, its module, fingerprint, commit, widens (H-A-119), released version, step results
// and tier; and the movers its end left unfinished (design 47 H2 §786).
func pipelineEnded(p seat.Pipeline) seat.PipelineEnded {
movers := make([]seat.MoverEnded, 0, len(p.Movers))
for _, m := range p.Movers {
movers = append(movers, seat.MoverEnded{Module: m.Module, Fingerprint: m.Fingerprint, Commit: m.Commit, Widens: m.Widens, Version: m.Version,
Steps: stepsOf(p, m.Module), Tier: m.Tier})
}
sort.SliceStable(movers, func(i, j int) bool { return movers[i].Tier < movers[j].Tier })
return seat.PipelineEnded{V: 1, Pipeline: p.Pipeline, Branch: p.Branch, Source: p.Source, Call: p.Call, Revision: p.Revision,
Run: p.Run, Outcome: p.Outcome, Why: p.Why, Started: p.Started, Ended: p.Ended, EndCount: p.EndCount, Movers: movers,
Phases: phasesOf(p), Unfinished: unfinishedOf(p)}
}
// phasesOf is p's phases (design 47 H2 §785): taken, when the runner wrote the pipeline at its take-in; placed, the
// earliest start of any of its steps; ended, its end; and for each step kind the earliest start and the latest end across
// its movers. A kind none of whose steps started has no span.
func phasesOf(p seat.Pipeline) *seat.PipelineEndedPhases {
type span struct{ start, end *time.Time }
spans := map[string]*span{}
var placed *time.Time
for _, st := range p.Steps {
if st.Started == nil {
continue
}
if placed == nil || st.Started.Before(*placed) {
placed = st.Started
}
sp := spans[st.Step]
if sp == nil {
sp = &span{}
spans[st.Step] = sp
}
if sp.start == nil || st.Started.Before(*sp.start) {
sp.start = st.Started
}
if st.Ended != nil && (sp.end == nil || st.Ended.After(*sp.end)) {
sp.end = st.Ended
}
}
ph := &seat.PipelineEndedPhases{Taken: p.Started, Placed: placed, Ended: p.Ended}
if sp := spans[seat.StepResultStepBuild]; sp != nil {
ph.Build = &seat.PipelineEndedPhasesBuild{Start: sp.start, End: sp.end}
}
if sp := spans[seat.StepResultStepLint]; sp != nil {
ph.Lint = &seat.PipelineEndedPhasesLint{Start: sp.start, End: sp.end}
}
if sp := spans[seat.StepResultStepUnit]; sp != nil {
ph.Unit = &seat.PipelineEndedPhasesUnit{Start: sp.start, End: sp.end}
}
if sp := spans[seat.StepResultStepIntegration]; sp != nil {
ph.Integration = &seat.PipelineEndedPhasesIntegration{Start: sp.start, End: sp.end}
}
if sp := spans[seat.StepResultStepValidate]; sp != nil {
ph.Validate = &seat.PipelineEndedPhasesValidate{Start: sp.start, End: sp.end}
}
if sp := spans[seat.StepResultStepComposition]; sp != nil {
ph.Composition = &seat.PipelineEndedPhasesComposition{Start: sp.start, End: sp.end}
}
return ph
}
func endOutcome(o string) bool {
switch o {
case nodebuildgo.StepEndedOutcomePassed, nodebuildgo.StepEndedOutcomeFailed, nodebuildgo.StepEndedOutcomeNothingToRun,
nodebuildgo.StepEndedOutcomeCouldNotRun, nodebuildgo.StepEndedOutcomeDeclined:
return true
}
return false
}
// validateStepOfAsk is the validate step the end of the shared validate ask id ends first (H-A-252): the open one of the mover
// the end names, else any open one under the ask (sameValidate ends the rest), else the first under it.
func validateStepOfAsk(p seat.Pipeline, id, module string) int {
first, anyOpen := -1, -1
for i, s := range p.Steps {
if s.Step != seat.StepResultStepValidate || s.Ask == "" || s.Ask != id {
continue
}
if first < 0 {
first = i
}
if open(s) {
if s.Module == module {
return i
}
if anyOpen < 0 {
anyOpen = i
}
}
}
if anyOpen >= 0 {
return anyOpen
}
return first
}
func stepOfAsk(p seat.Pipeline, id string) int {
for i, s := range p.Steps {
if id != "" && s.Ask == id {
return i
}
}
return -1
}
// stepPassed says a required step holds nothing: it passed, was carried, or had nothing to run (design 47 H §746, ADR
// 0682 §8, H-A-3).
func stepPassed(s seat.StepResult) bool {
return s.Outcome == seat.StepResultOutcomePassed || s.Outcome == seat.StepResultOutcomeCarried || s.Outcome == seat.StepResultOutcomeNothingToRun
}
// endPipeline ends a pipeline whose every mover is placed and every step ended: passed when every mover's required steps
// passed, were carried or had nothing to run, else failed, naming each required step that held it (ADR 0666 §7, §9;
// design 47 H §746). A mover with no step placed, waiting on its registration (A-327) or on the publish of a mover it
// builds on (§746), holds the end only while the pipeline could still pass: once a placed mover's required step did not
// pass and none is open, it ends failed, the why naming each unplaced mover with the reason unplaced gives (H-A-163,
// H-A-171; nil says only that it has no step placed). A failed optional step, and an optional step still waiting, hold
// nothing. An approval step still waiting when a required step did not pass is `not asked` (§26). It says whether the
// pipeline ended now, its end count one higher.
func endPipeline(p *seat.Pipeline, now time.Time, unplaced func(seat.Pipeline, string) string) bool {
if p.Outcome != seat.PipelineOutcomeRunning {
return false
}
// A mover with no step placed waits on its registration or a publish: it holds the end only while every placed mover's
// required steps passed, since once one failed or could not run the pipeline can no longer pass (H-A-163, H-A-171).
// A mover that left for a newer pipeline (H-A-223) holds nothing and fails nothing: its steps are not judged, and a
// pipeline every mover left ends superseded.
if allLeft(*p) {
p.Outcome, p.Why, p.Ended = seat.PipelineOutcomeSuperseded, "every mover left it for a newer pipeline (H-A-223)", &now
p.EndCount++
return true
}
var waiting []string
for _, m := range p.Movers {
if !placed(*p, m.Module) && !slices.Contains(p.Superseded, m.Module) {
waiting = append(waiting, m.Module)
}
}
var held []string
var notAsked []int
for i, s := range p.Steps {
switch {
case slices.Contains(p.Superseded, s.Module):
continue
case s.Step == seat.StepResultStepApproval && s.Outcome == seat.StepResultOutcomeWaiting:
notAsked = append(notAsked, i)
continue
case s.Outcome == seat.StepResultOutcomeWaiting && s.Status != seat.StepResultStatusRequired:
// An optional step still waiting (a code review nobody has given) holds nothing: only a required one holds the
// pipeline's end (A-104).
continue
case s.Outcome == seat.StepResultOutcomeWaiting, open(s):
return false
}
if s.Status == seat.StepResultStatusRequired && !stepPassed(s) {
held = append(held, strings.TrimSpace(s.Module+" "+s.Artifact+" "+s.Step)+" "+s.Outcome)
}
}
if len(waiting) > 0 && len(held) == 0 {
return false
}
if len(notAsked) > 0 {
if len(held) == 0 {
return false
}
for _, i := range notAsked {
p.Steps[i].Outcome = seat.StepResultOutcomeNotAsked
}
}
p.Ended = &now
p.EndCount++
p.Outcome, p.Why = seat.PipelineOutcomePassed, ""
if len(held) > 0 {
p.Outcome, p.Why = seat.PipelineOutcomeFailed, "required steps not passed: "+strings.Join(held, ", ")
for _, m := range waiting {
why := m + " has no step placed"
if unplaced != nil {
why = unplaced(*p, m)
}
p.Why += "; " + why
}
}
for i := range p.Movers {
m := &p.Movers[i]
m.Tests = testCounts(stepsOf(*p, m.Module))
m.OverBudget = m.Tests != nil && (m.Tests.Unit > budgetUnit || m.Tests.Integration > budgetIntegration)
}
return true
}
// endPipeline is endPipeline with each mover's widens computed into its value at the end (§71, A-207; H-A-51), by wr, the
// reads the caller made before its compare-and-set (H-A-289); nil computes none.
func (h *Hearer) endPipeline(p *seat.Pipeline, now time.Time, wr func(seat.Pipeline, string) []seat.Widening) bool {
if !endPipeline(p, now, h.Unplaced) {
return false
}
if wr != nil {
for i := range p.Movers {
p.Movers[i].Widens = wr(*p, p.Movers[i].Module)
}
}
return true
}
// widensReads is the reader of one end's widens, made before its compare-and-set and kept for every retry (H-A-289).
func (h *Hearer) widensReads() func(seat.Pipeline, string) []seat.Widening {
if h.Widens == nil {
return nil
}
return h.Widens()
}
// EndedAtPlacing says a pipeline its starter ended at placing, a seat with no holder (A-470g, A-470h): the step-ended of each
// step of steps, its step log entries appended, the head's finding pipeline-failed (§33), then its pipeline-ended.
func (h *Hearer) EndedAtPlacing(p seat.Pipeline, steps []int) error {
var first error
for _, i := range steps {
if err := h.say(seat.EventStepEnded, p, &p.Steps[i]); err != nil && first == nil {
first = fmt.Errorf("pipeline %s's %s is written but not said: %w", p.Pipeline, seat.EventStepEnded, err)
}
}
h.appendUnlogged(p.Pipeline)
if len(steps) > 0 {
h.Failures.StepEnded(h.Store, p, p.Steps[steps[0]])
}
if err := h.said(p, nil, true); err != nil && first == nil {
first = err
}
return first
}
// sameValidate ends, in p, every other mover's validate step reading the ask step i's end ended, with its result (§745,
// H-A-51). It answers their indexes.
func sameValidate(p *seat.Pipeline, i int, now time.Time) []int {
v := p.Steps[i]
var out []int
for j := range p.Steps {
s := &p.Steps[j]
if j == i || s.Step != seat.StepResultStepValidate || s.Ask != v.Ask || !open(*s) {
continue
}
s.Outcome, s.Why, s.Node, s.Ended = v.Outcome, v.Why, v.Node, &now
p.Unlogged = append(p.Unlogged, endEntry(p.Pipeline, *s, now))
out = append(out, j)
}
return out
}