diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go index 6b189f44f..23c703af6 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go @@ -17,6 +17,7 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "github.com/nats-io/nats-server/v2/server" @@ -700,8 +701,9 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7 } // The reservations' states, as the controller makes them from the builder's manifest, and the catalog seat's versions, which // a first reservation reads (none released yet). + // The state acted is declared key-ttl (design 47 H2 H-A-720 (1)): its marks take a lifetime, so the bucket holds per-message lifetimes. for _, state := range []string{versions.ReservedState, versions.ActedState} { // acted keeps the release record - if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, state)}); err != nil { + if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, state), LimitMarkerTTL: time.Second}); err != nil { t.Fatal(err) } } @@ -808,6 +810,43 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7 if v := b.awaitFP(t, "netcheck", fifth, isState(builds.BuildDone)); v.Packages[pkg] != want { t.Errorf("netcheck built with %v once disk-load %s was released, want %s at %s from its release record (H-A-551)", v.Packages, reserved.Version, pkg, want) } + + // Design 47 H2 H-A-695 (AC-B16c, whole): the manifest-reads-changed of node n2 asks its engine, which never answers (no engine of n2 is + // listening); the running of the build module on node n1, stopped, is handled all the same (its toolchain key is deleted), and no event + // of the builder's durable is given again or ends in the dead letters (a delivery limit reached is advised on the bus). + deadLetters, err := b.js.Conn().SubscribeSync("$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES." + eventsStream + ".*") + if err != nil { + t.Fatal(err) + } + defer deadLetters.Unsubscribe() + toolchainKey, _ := sdkstep.ToolchainKey("n1", "go") + if _, err := b.heard.Get(b.ctx, toolchainKey); err != nil { + t.Fatalf("the builder holds no toolchain of n1 before the events: %v", err) + } + changed, _ := json.Marshal(nodeengine.ManifestReadsChanged{Node: "n2", Why: "changed", At: time.Now().UTC().Format(time.RFC3339Nano)}) + if _, err := b.js.Publish(b.ctx, nodeengine.SubjectManifestReadsChanged("n2"), changed); err != nil { + t.Fatal(err) + } + stopped, _ := json.Marshal(nodeengine.Running{Module: testGo, Node: "n1", At: time.Now().UTC()}) + if _, err := b.js.Publish(b.ctx, nodeengine.SubjectRunning("n1", testGo), stopped); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(20 * time.Millisecond) { + if _, err := b.heard.Get(b.ctx, toolchainKey); errors.Is(err, jetstream.ErrKeyNotFound) { + break + } + if time.Now().After(deadline) { + t.Fatal("the running of n1 was not handled within 20 s while the manifest-reads-changed of n2 waited on its ask") + } + } + if m, err := deadLetters.NextMsg(10 * time.Millisecond); err == nil { + t.Errorf("the bus advised a delivery limit reached: %s", m.Subject) + } + if c, err := b.js.Consumer(b.ctx, eventsStream, "n1_mesh-delivery-builder"); err != nil { + t.Fatal(err) + } else if info, err := c.Info(b.ctx); err != nil || info.NumRedelivered != 0 { + t.Errorf("the builder's durable gave %d events again (%v), want none", info.NumRedelivered, err) + } } // TestAnArchiveOnlyModuleAndARootModuleAreBuilt: the indexer gives an archive no language, so modules.ca-trust has no diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go index a5cdbc2c2..61b6b1c47 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go @@ -235,6 +235,11 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro // heard (design 47 H2 H-A-552: no fill is waited for). reservedKV := process.AwaitBucket(ctx, js, conn, own.reserved, "no version is reserved: builds are made unreserved", logger.Printf) reserved := newReservations(awaitedReserved{awaitedState{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, logger.Printf) + publishAck, err := numberFile(getenv("MESH_BUILDER_PUBLISH_ACK_FILE"), defaultPublishAckMinutes) + if err != nil { + return err + } + reserved.setBound(time.Duration(publishAck) * time.Minute) // the finding version-unreleased is timed by the same setting (H-A-613 (3)) // The index by digest and by version beside the reservations is written again once the state is bound (H-A-269 (1), H-A-271). reservedKV.Ready(func(jetstream.KeyValue) { reserved.reindex(ctx) }) // Each artifact the holder says published at a reserved version is said as the seat mesh-builds' package-published (design 47 G §52). @@ -289,15 +294,12 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro reserved.r.HeldElsewhere = func(ctx context.Context, module string, skipped []string) { reserved.heldElsewhere(ctx, module, "the registries hold "+strings.Join(skipped, ", ")+", so the reserve skipped them") } - publishAck, err := numberFile(getenv("MESH_BUILDER_PUBLISH_ACK_FILE"), defaultPublishAckMinutes) - if err != nil { - return err - } republishMax, err := numberFile(getenv("MESH_BUILDER_REPUBLISH_MAX_FILE"), versions.DefaultRepublishMaxVersions) if err != nil { return err } pq.ackWait = time.Duration(publishAck) * time.Minute // a sent item unheard is given again after the publish bound (H-A-613 (3)) + republish.Bound = pq.ackWait // a send's calls wait that long at most, then the item is given again (H-A-613 (3), H-A-745) actedDays, err := numberFile(getenv("MESH_BUILDER_ACTED_DAYS_FILE"), versions.DefaultActedDays) if err != nil { return err diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go index 5caf84658..4c6550b68 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go @@ -16,6 +16,7 @@ import ( "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" @@ -23,6 +24,7 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-sdk/go/process" + "git.novox.be/novox/mesh-sdk/go/seatlist" "git.novox.be/novox/mesh-sdk/go/testbus" "git.novox.be/novox/mesh-sdk/go/views" @@ -557,6 +559,55 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { republish.Ended = items.Ended pq.take = items.take wirePublishItems(rv, items, &lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, versions.DefaultReleasedKept) + // The publish again hears the node-engine seat's events from the bus, as the builder's events consumer gives them (H-A-606, ADR 0674 §2): + // the registry holder's module runs on the node ace, and its catalog entry serves the registry seat. + entries[fpOf+holder] = meshcatalog.CatalogEntry{Module: holder, Fp: fpOf + holder, Serves: []string{versions.SeatGoPackages + ".publish"}} + againer := &publishingAgain{a: &versions.Againer{Republisher: republish, Acted: &lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, + Nodes: func(seat string) []seatlist.HolderNode { + if seat == versions.SeatGoPackages { + return []seatlist.HolderNode{{Module: holder, Node: "ace"}} + } + return nil + }}} + handled := make(chan uint64, 16) + engineEvents, err := b.js.CreateOrUpdateConsumer(ctx, eventsStream, jetstream.ConsumerConfig{Durable: "publish-again-test", AckPolicy: jetstream.AckExplicitPolicy, + DeliverPolicy: jetstream.DeliverNewPolicy, FilterSubjects: []string{nodeengine.SubjectRunningAll, nodeengine.SubjectManifestReadsChanged("*")}}) + if err != nil { + t.Fatal(err) + } + hearing, err := engineEvents.Consume(func(m jetstream.Msg) { + againer.heard(ctx, m, t.Logf) + _ = m.Ack() + if md, err := m.Metadata(); err == nil { + handled <- md.Sequence.Stream + } + }) + if err != nil { + t.Fatal(err) + } + defer hearing.Stop() + // said puts one event of the node-engine seat on the bus and waits until the publish again has handled it; it answers its stream sequence. + said := func(subject string, body any) uint64 { + t.Helper() + data, _ := json.Marshal(body) + ack, err := b.js.Publish(ctx, subject, data) + if err != nil { + t.Fatal(err) + } + for bound := time.After(testbus.SetupBound(t)); ; { + select { + case seq := <-handled: + if seq == ack.Sequence { + return seq + } + case <-bound: + t.Fatalf("the publish again did not handle %s", subject) + } + } + } + returned := func() uint64 { + return said(nodeengine.SubjectManifestReadsChanged("ace"), nodeengine.ManifestReadsChanged{Node: "ace", Why: nodeengine.ManifestReadsChangedWhyReturned}) + } // build is the reserve and the end of a build of module at fp: its digests are built+artifact. build := func(module, fp, built string, arts ...string) versions.ReservedVersion { t.Helper() @@ -603,16 +654,55 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { t.Errorf("the refused publish was called %d times, want once: it waits for the next running", got) } reg.refuse("x.example/refused/a", "") - republish.Started = time.Now() // the holder's next running, in a run later than the build's: its put is of the start class, another message id - if _, err := republish.Republish(ctx, "refused", "0.1.0"); err != nil { - t.Fatal(err) - } + // The holder's running, heard from the bus, puts it again once, as an item of the class again (H-A-606, H-A-613 (1), H-A-620 (1)). + liveBefore, againBefore := delivered(t, b.js, bind.Stream, holder, versions.PublishClassLive), delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart) + said(nodeengine.SubjectRunning("ace", holder), nodeengine.Running{Module: holder, Node: "ace", Fingerprint: fpOf + holder}) reg.await(t, "x.example/refused/a", "0.1.0") if got := stored("refused", "0.1.0", "a"); got != "sha256:ra" { t.Errorf("the refused publish put again stored %q, want sha256:ra", got) } reg.published(t, rv, "x.example/refused/a", "0.1.0") reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "refused", "0.1.0") }) + if l, a := delivered(t, b.js, bind.Stream, holder, versions.PublishClassLive), delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart); l != liveBefore || a != againBefore+1 { + t.Errorf("the running put %d live and %d again items, want one item of the class again", l-liveBefore, a-againBefore) + } + + // H-A-620 (1) (AC-B8a): two returns of one holder queue a version once while its send runs: the holder is away, the first return puts + // the version and its send waits at the kept call's pace, the second finds the version held by the work queue and puts nothing. + entryOf("twice", fpOf+"t", "a") + reg.refuse("x.example/twice/a", "the cap") + build("twice", fpOf+"t", "t", "a") + reg.await(t, "x.example/twice/a", "0.1.0") + reg.settle(t, b.js, bind.Stream, holder, nil) + reg.refuse("x.example/twice/a", "") + reg.goAway() + againBefore = delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart) + returned() + select { + case <-reg.firstAway: + case <-time.After(testbus.SetupBound(t)): + t.Fatal("the first return did not put the version") + } + returned() + if st, err := b.js.Stream(ctx, bind.Stream); err != nil { + t.Fatal(err) + } else if info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish."+holder+".again."+versions.EscapeToken("twice")+".>")); err != nil { + t.Fatal(err) + } else if n := func() (n uint64) { + for _, c := range info.State.Subjects { + n += c + } + return + }(); n != 1 { + t.Errorf("two returns left %d items of twice on the work queue (%v), want one", n, info.State.Subjects) + } + reg.answer() + reg.await(t, "x.example/twice/a", "0.1.0") + reg.published(t, rv, "x.example/twice/a", "0.1.0") + reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "twice", "0.1.0") }) + if got := delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart); got != againBefore+1 { + t.Errorf("two returns made %d deliveries of again items, want one", got-againBefore) + } // H-A-593 (5): a build of F publishes two of three artifacts at V and fails on the third (the holder refuses it). Built again, the // two held for F keep their held digests, the third is stored and V is released, with no refusal and no new number. @@ -713,7 +803,14 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { t.Fatal(err) } reg.await(t, "x.example/other/a", res.Version) + // The item is ended at once, never held for its publish nor left on either durable (H-A-593 (5), H-A-729): the build is of a run + // before the last start here, so its item is of the class again, which the settle reads as the live class. reg.settle(t, b.js, bind.Stream, holder, nil) + if st, err := b.js.Stream(ctx, bind.Stream); err != nil { + t.Fatal(err) + } else if info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish."+holder+".*.other.>")); err != nil || len(info.State.Subjects) != 0 { + t.Errorf("after other bytes the work queue holds %v (%v) of the item, want it terminated", info.State.Subjects, err) + } if got := reg.callsOf("x.example/other/a"); got != 1 { t.Errorf("other bytes of another build: called %d times, want once", got) } @@ -895,31 +992,57 @@ func (r *fakeRegistry) await(t *testing.T, name, version string) { } } -// settle waits until the holder's queue holds nothing sent and unacknowledged: every item taken is ended. +// settle waits until the holder's queue holds nothing sent and unacknowledged on either durable, the live class's and the again +// class's: every item taken is ended. func (r *fakeRegistry) settle(t *testing.T, js jetstream.JetStream, stream string, holder string, each func()) { t.Helper() - c, err := js.Consumer(context.Background(), stream, publishesConsumer(holder, versions.PublishClassLive)) - if err != nil { - t.Fatal(err) + var cs []jetstream.Consumer + for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} { + c, err := js.Consumer(context.Background(), stream, publishesConsumer(holder, class)) + if err != nil { + t.Fatal(err) + } + cs = append(cs, c) } for deadline := time.Now().Add(testbus.SetupBound(t)); ; { if each != nil { each() } - info, err := c.Info(context.Background()) - if err != nil { - t.Fatal(err) + var ack, pending int + for _, c := range cs { + info, err := c.Info(context.Background()) + if err != nil { + t.Fatal(err) + } + ack, pending = ack+info.NumAckPending, pending+int(info.NumPending) } - if info.NumAckPending == 0 && info.NumPending == 0 { + if ack == 0 && pending == 0 { return } if time.Now().After(deadline) { - t.Fatalf("the queue of %s holds %d unacknowledged and %d pending", holder, info.NumAckPending, info.NumPending) + t.Fatalf("the queue of %s holds %d unacknowledged and %d pending", holder, ack, pending) } time.Sleep(10 * time.Millisecond) } } +// delivered is how many items the holder's durable of a class has given since it was made. +func delivered(t *testing.T, js jetstream.JetStream, stream, holder, class string) uint64 { + t.Helper() + c, err := js.Consumer(context.Background(), stream, publishesConsumer(holder, class)) + if err != nil { + t.Fatal(err) + } + info, err := c.Info(context.Background()) + if err != nil { + t.Fatal(err) + } + return info.Delivered.Consumer +} + +// goAway makes the holder answer as the bus does when no one listens: its publish is met by no responders. +func (r *fakeRegistry) goAway() { r.mu.Lock(); r.away = true; r.mu.Unlock() } + // published says the holder's published of name at version, as it says it after a publish: the reservation marks it from the digest held. func (r *fakeRegistry) published(t *testing.T, rv *reservations, name, version string) { t.Helper() diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go index ae7b75c39..876107baa 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go @@ -17,6 +17,7 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-sdk/go/buscompose" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/process" @@ -48,6 +49,9 @@ type publishItems struct { // unreleased raises version-unreleased about a version with the words given (Republisher's Unreleased); nil raises none. unreleased func(ctx context.Context, v versions.ReservedVersion, why string) logf func(string, ...any) + // progressEvery is the pace the bus is told an item is in progress at while its send's calls wait: the kept call's pace + // (busretry.KeptPace's most) when zero (design 47 H2 H-A-613 (3)). + progressEvery time.Duration mu sync.Mutex held map[string][]heldItem // " ": the items sent, their publish not yet heard @@ -75,6 +79,7 @@ func (p *publishItems) Done(ctx context.Context, module, version string) { // itemMsg is what take reads of an item pulled from the work queue (jetstream.Msg). type itemMsg interface { Data() []byte + InProgress() error Ack() error NakWithDelay(time.Duration) error Term() error @@ -133,7 +138,11 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) { } fate := versions.SendFate{Failed: "this builder sends no publish"} if p.send != nil { + // The item is marked in progress while its calls wait, so the bus gives it again only when the builder itself stopped + // (design 47 H2 H-A-613 (3)). + stop := p.inProgress(m) fate = p.send(ctx, q) + stop() } if fate.Unread != "" { // A read of the builder's own state that failed is no answer of a holder: the item is left unacknowledged, given again after the @@ -152,6 +161,37 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) { return } p.hold(q, m) + // Its publish heard between the send and the hold would be missed by both: read again once held. + p.heard(ctx, q.Module, q.Version) +} + +// inProgress tells the bus the item is in progress now and at the kept call's pace until the returned function is called. +func (p *publishItems) inProgress(m itemMsg) (stop func()) { + every := p.progressEvery + if every <= 0 { + every = busretry.KeptPace().Max + } + say := func() { + if err := m.InProgress(); err != nil { + p.logf("an item in progress is not said to the bus: %v", err) + } + } + done, ended := make(chan struct{}), make(chan struct{}) + go func() { + defer close(ended) + say() + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-t.C: + say() + case <-done: + return + } + } + }() + return func() { close(done); <-ended } } // allPublished says none of q's artifacts is missing from v: its publish is heard. @@ -407,7 +447,7 @@ func (pq *publishQueue) put(ctx context.Context, q versions.QueuedPublish) (bool } else if !errors.Is(err, jetstream.ErrMsgNotFound) { return false, err } - ack, err := pq.js.PublishMsg(ctx, &nats.Msg{Subject: pq.subject(b, q), Data: data}, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version))) + ack, err := pq.js.PublishMsg(ctx, &nats.Msg{Subject: pq.subject(b, q), Data: data}, jetstream.WithMsgID(q.MsgID())) if err != nil { if w := err.Error(); strings.Contains(w, "maximum bytes") || strings.Contains(w, "maximum messages") || errors.Is(err, jetstream.ErrMaxBytesExceeded) { return false, fmt.Errorf("%w: %v", versions.ErrQueueFull, err) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go index 91fafe287..666eb6960 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go @@ -8,6 +8,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "testing" "time" @@ -103,14 +104,23 @@ func (l itemKeys) Stop() error { return nil } // itemMsgFake is an item pulled from the work queue: what take settled it with. type itemMsgFake struct { + progress atomic.Int64 // InProgress calls + onWorking func(n int64) // told the count after each data []byte delivered uint64 // the delivery count Metadata says; 0 says none settled []string // ack, term, nak } func (m *itemMsgFake) Data() []byte { return m.data } -func (m *itemMsgFake) Ack() error { m.settled = append(m.settled, "ack"); return nil } -func (m *itemMsgFake) Term() error { m.settled = append(m.settled, "term"); return nil } +func (m *itemMsgFake) InProgress() error { + n := m.progress.Add(1) + if m.onWorking != nil { + m.onWorking(n) + } + return nil +} +func (m *itemMsgFake) Ack() error { m.settled = append(m.settled, "ack"); return nil } +func (m *itemMsgFake) Term() error { m.settled = append(m.settled, "term"); return nil } func (m *itemMsgFake) Metadata() (*jetstream.MsgMetadata, error) { if m.delivered == 0 { return nil, errors.New("no metadata") @@ -182,6 +192,33 @@ func TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer(t *testing.T) { if len(sent) != 2 || len(m.settled) != 0 { t.Fatalf("an unread send: sent %v, settled %v, want it left unacknowledged", sent, m.settled) } + // design 47 H2 H-A-613 (3): while its calls wait the item is marked in progress at the kept call's pace, so the bus gives it again only + // when the builder itself stopped; the send here answers once the bus has been told three times. + told := make(chan struct{}) + p.progressEvery = time.Millisecond + p.send = func(context.Context, versions.QueuedPublish) versions.SendFate { + select { + case <-told: + return versions.SendFate{Unread: "not answered within the bound"} + case <-time.After(10 * time.Second): + return versions.SendFate{Failed: "the item was never marked in progress"} + } + } + m = queuedMsg(t, "m", "0.1.2") + var once sync.Once + m.onWorking = func(n int64) { + if n >= 3 { + once.Do(func() { close(told) }) + } + } + p.take(ctx, m) + if n := m.progress.Load(); n < 3 || len(m.settled) != 0 { + t.Fatalf("a send whose call waits: told in progress %d times, settled %v, want 3 or more and the item left, never ended", n, m.settled) + } + p.send = func(_ context.Context, q versions.QueuedPublish) versions.SendFate { + sent = append(sent, q.Module+" "+q.Version) + return fate + } fate = versions.SendFate{Sent: true} m = queuedMsg(t, "m", "0.1.2") p.take(ctx, m) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go index c3ab95aed..143b36f19 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go @@ -119,7 +119,7 @@ func sayReservedOn(js jetstream.JetStream, cred process.Account) func(context.Co // newReservations makes the reserving over store; the released versions of a module are asked of the seat mesh-catalog's // verb versions through call (design 47 G §348), the only source numbering reads them from. func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, logf func(string, ...any)) *reservations { - rv := &reservations{bounds: bounds, found: found, bound: versions.UnreleasedBound, logf: logf} + rv := &reservations{bounds: bounds, found: found, bound: defaultPublishAckMinutes * time.Minute, logf: logf} rv.r = &versions.Reserver{Store: store, ReleasedOf: func(_ context.Context, module string) ([]string, error) { raw, err := call("seat:"+meshcatalog.Seat+".versions", meshcatalog.VersionsInput{Module: module}) if err != nil { @@ -136,9 +136,17 @@ func newReservations(store versions.ReserveStore, call toolCaller, bounds func() return out, nil }} rv.r.Took, rv.r.Logf, rv.r.Reserved = rv.took, logf, rv.reservedSaid + rv.setBound(rv.bound) return rv } +// setBound sets the publish's bound, the setting publish-ack-minutes (design 47 H2 H-A-613 (3)): past it a built reservation +// with an artifact unpublished is the finding version-unreleased, armed and judged by this one value. +func (rv *reservations) setBound(d time.Duration) { + rv.bound = d + rv.r.Bound = d +} + // reindex writes the reservations' index again from the reservations, once at the builder's start (H-A-269 (1), H-A-271), and // says so. func (rv *reservations) reindex(ctx context.Context) { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go index 45b8e01f8..0144304dc 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go @@ -20,6 +20,7 @@ import ( stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/process" + "mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/versions" ) @@ -494,13 +495,27 @@ func TestABuiltReservationIsTakenInFromItsState(t *testing.T) { if !slices.Equal(said, []string{"look:a@" + v.Version + " sha256:looka"}) || !slices.Equal(asked, []string{"look " + v.Version}) { t.Errorf("at a look: said %v, publish items asked %v; want look:a's package-published said and its item asked", said, asked) } - if ends := boundEnds("look"); !ends.Equal(v.BuiltAt.Add(versions.UnreleasedBound)) { - t.Errorf("the bound armed at a look ends %v, want %v: counted from the build's end", ends, v.BuiltAt.Add(versions.UnreleasedBound)) + if ends := boundEnds("look"); !ends.Equal(v.BuiltAt.Add(defaultPublishAckMinutes * time.Minute)) { + t.Errorf("the bound armed at a look ends %v, want %v: counted from the build's end", ends, v.BuiltAt.Add(defaultPublishAckMinutes*time.Minute)) } if cur, _, _ := rv.r.Of(ctx, "look", v.Version); len(cur.Kept) != 0 || !cur.Published["look:a"] { t.Errorf("after the look: kept %v, published %v; want the kept published taken in", cur.Kept, cur.Published) } }) + t.Run("at a look with publish-ack-minutes at 30", func(t *testing.T) { + rv.setBound(30 * time.Minute) + defer rv.setBound(defaultPublishAckMinutes * time.Minute) + v := recordedLost("thirty", now.Add(-5*time.Minute), "a") + if err := rv.Built(ctx, "thirty", v.Version, v.Artifacts, nil); err != nil { + t.Fatal(err) + } + if ends := boundEnds("thirty"); !ends.Equal(v.BuiltAt.Add(30 * time.Minute)) { + t.Errorf("the bound armed ends %v, want %v: the setting's 30 minutes, not 10", ends, v.BuiltAt.Add(30*time.Minute)) + } + if unreleased("thirty") != "" { + t.Errorf("a build 5 minutes old raised %s with the bound at 30 minutes", unreleased("thirty")) + } + }) t.Run("at the start", func(t *testing.T) { v := recordedLost("start", now.Add(-time.Minute), "a") said = nil @@ -515,7 +530,7 @@ func TestABuiltReservationIsTakenInFromItsState(t *testing.T) { t.Run("past its bound", func(t *testing.T) { for _, when := range []string{"a look", "the start"} { module := map[string]string{"a look": "pastlook", "the start": "paststart"}[when] - v := recordedLost(module, now.Add(-versions.UnreleasedBound-time.Minute), "a") + v := recordedLost(module, now.Add(-defaultPublishAckMinutes*time.Minute-time.Minute), "a") takeIn := func() { if when == "a look" { if err := rv.Built(ctx, module, v.Version, v.Artifacts, nil); err != nil { @@ -542,7 +557,7 @@ func TestABuiltReservationIsTakenInFromItsState(t *testing.T) { // Note 8's own case: every artifact's published kept on it is taken in before its bound is judged, so nothing is // unpublished and nothing is raised; each is said as package-published. module = map[string]string{"a look": "keptlook", "the start": "keptstart"}[when] - v = recordedLost(module, now.Add(-versions.UnreleasedBound-time.Minute), "a", "b") + v = recordedLost(module, now.Add(-defaultPublishAckMinutes*time.Minute-time.Minute), "a", "b") said = nil takeIn() if got := unreleased(module); got != "" { @@ -666,6 +681,39 @@ func (e ansEntry) Revision() uint64 { return 1 } func (e ansEntry) Value() []byte { return e.value } func (e ansEntry) Operation() jetstream.KeyValueOp { return jetstream.KeyValuePut } +// noAskKnown is a builder none of whose lanes waits: it records the keys asked again and builds, announces and releases nothing. +type noAskKnown struct{ asked []string } + +func (n *noAskKnown) AskAgain(key, _ string) []string { n.asked = append(n.asked, key); return nil } +func (n *noAskKnown) BuildAgain(context.Context, string, string, string, string, time.Duration) build.BuildAgainResult { + return build.BuildAgainResult{} +} +func (n *noAskKnown) AnnounceAgain(context.Context, string, string, string, string) build.BuildAgainResult { + return build.BuildAgainResult{} +} +func (n *noAskKnown) Release(context.Context, string, string, string, string) string { return "" } + +// TestAReserveDoneReAskIsNoAskTheBuilderKnows: design 47 H2 H-A-706 (DQ-39), AC-B14b — builder_reserve_done is gone, so a re-ask of its mode +// reserve-done is no hand act of a version: it is answered as any ask of a key no lane of the builder waits on, and writes no reservation. +func TestAReserveDoneReAskIsNoAskTheBuilderKnows(t *testing.T) { + kv := &ansKV{wrote: make(chan []byte, 1)} + raw, _ := json.Marshal(build.ReAsk{V: 1, Why: "a test asks it", By: "op@node", At: time.Now(), Mode: "reserve-done", Name: "m", Version: "0.1.0"}) + b := &noAskKnown{} + reAsked(context.Background(), b, versions.Acts{}, nil, kv, ansEntry{key: "m.fp", value: raw}, t.Logf) + var got build.ReAsk + select { + case v := <-kv.wrote: + if err := json.Unmarshal(v, &got); err != nil { + t.Fatal(err) + } + default: + t.Fatal("the re-ask was not answered") + } + if !strings.Contains(got.Answer, "no ask of this key waits in this builder") || !slices.Equal(b.asked, []string{"m.fp"}) || got.Answered.IsZero() { + t.Errorf("a re-ask of mode reserve-done answered %q (asked %v), want it answered as an ask no lane waits on", got.Answer, b.asked) + } +} + // TestARegistrysRecordEndsOrMovesAPublish: design 47 H H-A-274 — the artifacts a registry's record holds with the built digest are // marked published from it and package-published is said, as a heard published would; H-A-275 — a done build whose number a // registry holds at another digest (H-A-279) has its number withdrawn, raises version-held-elsewhere naming both digests, and is diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/step_integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/step_integration_test.go index 500578b53..a5693df9d 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/step_integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/step_integration_test.go @@ -68,6 +68,33 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) { case <-time.After(20 * time.Second): t.Fatal("no step-ended within 20 s") } + // Design 47 H2 H-A-577 (1), AC-B2: an ask whose revision the picture does not hold says wait-held (step build, on revision:, kept + // under ..revision) and wait-ended with how ran once it does. + waits := make(chan *nats.Msg, 8) + for _, ev := range []string{"wait-held", "wait-ended"} { + w, err := sub.ChanSubscribe("mesh.mod.*.event."+ev+".netcheck.>", waits) + if err != nil { + t.Fatal(err) + } + defer w.Unsubscribe() + } + revisionWait := func(event string) waitBody { + t.Helper() + for bound := time.After(20 * time.Second); ; { + select { + case m := <-waits: + var w waitBody + if err := json.Unmarshal(m.Data, &w); err != nil { + t.Fatal(err) + } + if strings.Contains(m.Subject, ".event."+event+".") && strings.HasSuffix(m.Subject, ".revision") { + return w + } + case <-bound: + t.Fatalf("no %s of the revision wait within 20 s", event) + } + } + } // H-A-155: an ask naming a source revision the builder's picture of main does not hold yet waits for it, said in the // journal, and is answered once a revision taken in from it arrives. run.Pipeline, run.Revision, run.Source = "main.2.netcheck", 2, 2 @@ -79,6 +106,9 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) { t.Fatal(err) } b.awaitSaid(t, "main.2.netcheck: revision 2 of main not in the builder's picture yet") + if w := revisionWait("wait-held"); w.On != "revision:2" || w.Step != "build" || w.Module != "netcheck" || w.Fingerprint != fp { + t.Errorf("wait-held of the ask for revision 2 = %+v, want step build, on revision:2, netcheck at %s", w, fp) + } b.catalog.mu.Lock() b.catalog.source = 2 b.catalog.mu.Unlock() @@ -93,6 +123,9 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) { case <-time.After(20 * time.Second): t.Fatal("no step-ended for ask-2 within 20 s") } + if w := revisionWait("wait-ended"); w.On != "revision:2" || w.How != "ran" { + t.Errorf("wait-ended of the ask for revision 2 = %+v, want on revision:2 ended ran", w) + } // Each ask is acknowledged once its end was said: the seat's worker holds none pending. stream, worker := buscompose.SeatQueueStreamName(meshbuilds.Seat), buscompose.SeatQueueWorkerName(meshbuilds.Seat) deadline := time.Now().Add(10 * time.Second) diff --git a/modules/mesh-delivery-builder/internal/versions/publishagain.go b/modules/mesh-delivery-builder/internal/versions/publishagain.go index 8469514e2..e1cde408d 100644 --- a/modules/mesh-delivery-builder/internal/versions/publishagain.go +++ b/modules/mesh-delivery-builder/internal/versions/publishagain.go @@ -60,7 +60,7 @@ func (a *Againer) Heard(ctx context.Context, subject string, data []byte, seq ui holders = a.returnedHolders(data) } if holders != nil { - if err := a.again(ctx, holders); err != nil { + if err := a.again(ctx, holders, seq); err != nil { return true, err } } @@ -159,7 +159,7 @@ func (a *Againer) unreleased(ctx context.Context) ([]ReservedVersion, error) { } // again queues the unreleased versions at the holders holdersOf names, at most MaxVersions of them. -func (a *Againer) again(ctx context.Context, holdersOf func(seat string) []string) error { +func (a *Againer) again(ctx context.Context, holdersOf func(seat string) []string, seq uint64) error { vs, err := a.unreleased(ctx) if err != nil { return fmt.Errorf("the reserved versions cannot be read: %w", err) @@ -171,7 +171,7 @@ func (a *Againer) again(ctx context.Context, holdersOf func(seat string) []strin if max <= 0 { max = DefaultRepublishMaxVersions } - queued, err := a.Republisher.queue(ctx, vs, holdersOf, max) + queued, err := a.Republisher.queue(ctx, vs, holdersOf, max, seq) if len(queued) > 0 { a.logf("publish again on an event: %d versions put on the work queue: %s", len(queued), strings.Join(queued, ", ")) } diff --git a/modules/mesh-delivery-builder/internal/versions/republish.go b/modules/mesh-delivery-builder/internal/versions/republish.go index 4e16fb134..4680aae72 100644 --- a/modules/mesh-delivery-builder/internal/versions/republish.go +++ b/modules/mesh-delivery-builder/internal/versions/republish.go @@ -14,6 +14,7 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + "git.novox.be/novox/mesh-sdk/go/busretry" ) // **A reserved version of a done build is published by the builder until its release is written** (design 47 G §588, A-457a): the @@ -94,6 +95,19 @@ type QueuedPublish struct { Queued time.Time `json:"queued"` // Class is PublishClassLive or PublishClassStart (H-A-290 (1)); a value written before it had one is of the start. Class string `json:"class,omitempty"` + // Sequence is the stream sequence of the event whose publish again this item is, the last token of its message id (H-A-613 (1)); zero + // for an item no event asked, which is not kept on the item. + Sequence uint64 `json:"-"` +} + +// MsgID is the message id of the item: PublishMsgID, and for an event's publish again the event's stream sequence after it, so the same +// event heard again puts nothing (design 47 H2 H-A-613 (1)). +func (q QueuedPublish) MsgID() string { + id := PublishMsgID(q.Holder, q.Class, q.Module, q.Version) + if q.Sequence > 0 { + id += "." + strconv.FormatUint(q.Sequence, 10) + } + return id } // streamOrder sorts the keys of the work queue's items in stream order: each key is its item's stream sequence (the builder's @@ -186,6 +200,9 @@ type Republisher struct { // Ended ends the publish item of a version that never publishes, its reservation withdrawn or taken over (H-A-290 (2)); // nil ends none. Ended func(ctx context.Context, module, version string) + // Bound is how long one item's send waits on its calls, the setting publish-ack-minutes (design 47 H2 H-A-613 (3), H-A-745); past it + // the item is left to be given again, never ended. Zero bounds the send by its context alone. + Bound time.Duration mu sync.Mutex // lastQueued is the newest time a version was queued at: a clock that has not moved between two versions (a coarse clock, @@ -369,7 +386,7 @@ type view struct { // queue queues vs newest first, at most max of them (0 is no limit), each artifact to the first holder holdersOf names for // its seat. It answers the versions queued, ` `. -func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf func(seat string) []string, max int) ([]string, error) { +func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf func(seat string) []string, max int, event uint64) ([]string, error) { sort.SliceStable(vs, func(i, j int) bool { return vs[i].At.After(vs[j].At) }) var queued []string var errs []error @@ -420,7 +437,7 @@ func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf } did := false for holder, arts := range byHolder { - ok, err := r.enqueue(ctx, v, holder, arts) + ok, err := r.enqueue(ctx, v, holder, arts, event) if err != nil { return queued, err } @@ -435,8 +452,13 @@ func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf // enqueue puts one holder's artifacts of a version on the work queue under its message id: not again while the queue holds that // id (its duplicates window), which stands queued, and not past the queue's cap (said as queue full). -func (r *Republisher) enqueue(ctx context.Context, v ReservedVersion, holder string, arts map[string]string) (bool, error) { +// An event's publish again (event is its stream sequence, not zero) is always of the class again, whenever its build ended +// (H-A-613 (1), H-A-620 (1)). +func (r *Republisher) enqueue(ctx context.Context, v ReservedVersion, holder string, arts map[string]string, event uint64) (bool, error) { q := QueuedPublish{V: 1, Holder: holder, Module: v.Module, Version: v.Version, Artifacts: arts, Queued: r.queuedAt(), Class: r.classOf(v)} + if event > 0 { + q.Class, q.Sequence = PublishClassStart, event + } dup, err := r.Put(ctx, q) switch { case errors.Is(err, ErrQueueFull): @@ -495,7 +517,7 @@ func (r *Republisher) Republish(ctx context.Context, module, version string) ([] return nil, fmt.Errorf("%s holds no reserved version%s with an artifact unpublished", module, map[bool]string{true: " " + version, false: ""}[version != ""]) } } - return r.queue(ctx, vs, r.holdersFn, 0) + return r.queue(ctx, vs, r.holdersFn, 0, 0) } // Queued is builder_publish_queue's answer, small at any size of the queue (design 47 H H-A-290 (5)): the queued versions' @@ -693,17 +715,21 @@ func (r *Republisher) MoveQueued(ctx context.Context, vals []json.RawMessage) (i // SendFate is what SendQueued did with one item (§793): Sent, every artifact sent (its item acknowledged when its publish is // heard or confirmed); Ended, why the version never publishes (its item terminated); Failed, the holder's or the call's words -// (its item ended, the version staying reserved); Unread, why a read of the builder's own state failed: nothing was sent, the item is -// left unacknowledged and given again after the ack wait (design 47 H2 H-A-745). +// (its item ended, the version staying reserved); Unread, why a read of the builder's own state failed or a call was not answered within the bound: +// the item is left unacknowledged and given again after the ack wait (design 47 H2 H-A-745, H-A-613 (3)). type SendFate struct { Sent bool Ended, Failed, Unread string } -// SendQueued publishes one item's artifacts and says the outcome. Every call it makes honours the one bound it is given, -// UnreleasedBound (a context's bound, no timer, ADR 0437 §8), and a send that returns without sending says why (H-A-290 (4)). +// SendQueued publishes one item's artifacts and says the outcome. Every call it makes honours the one bound it is given, Bound +// (a context's bound, no timer, ADR 0437 §8), and a send that returns without sending says why (H-A-290 (4)). A call not answered +// within the bound, or stopped with the builder, leaves the item to be given again (Unread), never ended (H-A-613 (3), H-A-745). func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate { - bound, cancel := context.WithTimeout(ctx, UnreleasedBound) + bound, cancel := ctx, context.CancelFunc(func() {}) + if r.Bound > 0 { + bound, cancel = context.WithTimeout(ctx, r.Bound) + } defer cancel() all, err := r.Reserved.All(bound) if err != nil { @@ -798,6 +824,13 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate r.end(ctx, q.Module, q.Version, words) return SendFate{Ended: words} } + var unanswered *busretry.Unanswered + if bound.Err() != nil || errors.As(err, &unanswered) { + // Not answered within the bound, or the builder stopped: no holder refused it, so the item is left, given again after the ack + // wait, and the queue's tenth delivery ends it loud (design 47 H2 H-A-613 (3), H-A-745, H-A-653). + r.logf("publish again: %s %s: %s is not answered by %s: %v; the item is left, given again after the ack wait", q.Module, q.Version, ref, seat, err) + return SendFate{Unread: fmt.Sprintf("%s is not answered by %s: %v", ref, seat, err)} + } r.logf("publish again: %s %s: %s refused by %s: %v", q.Module, q.Version, ref, seat, err) words := err.Error() if strings.Contains(words, strings.TrimSuffix(NotStoredWords, ": ")) { diff --git a/modules/mesh-delivery-builder/internal/versions/republish_test.go b/modules/mesh-delivery-builder/internal/versions/republish_test.go index 926eff578..48bb0b0fe 100644 --- a/modules/mesh-delivery-builder/internal/versions/republish_test.go +++ b/modules/mesh-delivery-builder/internal/versions/republish_test.go @@ -16,6 +16,7 @@ import ( "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/seatlist" ) @@ -46,7 +47,7 @@ type republishBed struct { func newRepublishBed(t *testing.T) *republishBed { t.Helper() b := &republishBed{reserved: &reserveMem{mem: newMem()}, now: time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC), ids: map[string]bool{}} - res := &Reserver{Store: b.reserved, Now: func() time.Time { return b.now }, ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} + res := &Reserver{Store: b.reserved, Bound: testBound, Now: func() time.Time { return b.now }, ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} b.Republisher = &Republisher{Reserved: res, Now: func() time.Time { return b.now }, Entry: func(_ context.Context, fp string) (meshcatalog.CatalogEntry, error) { if fp == "src2:holder" { @@ -84,7 +85,7 @@ func newRepublishBed(t *testing.T) *republishBed { if b.full { return false, fmt.Errorf("%w: maximum bytes exceeded", ErrQueueFull) } - id := PublishMsgID(q.Holder, q.Class, q.Module, q.Version) + id := q.MsgID() if b.window && b.ids[id] { return true, nil } @@ -111,7 +112,7 @@ func (b *republishBed) reserve(t *testing.T, module string) ReservedVersion { if _, _, err := b.Reserved.Built(ctx, module, v.Version, map[string]string{module + ":prog": "sha256:aa", module + ":lib": "sha256:bb"}, nil); err != nil { t.Fatal(err) } - b.now = b.now.Add(UnreleasedBound + time.Minute) + b.now = b.now.Add(testBound + time.Minute) return v } @@ -474,6 +475,25 @@ func TestAQueuedItemIsSentWhileItsBuildStands(t *testing.T) { t.Errorf("an unreadable reservation answered %+v: want it unread", f) } }) + // design 47 H2 H-A-613 (3), H-A-745: a call not answered within the bound, and one stopped with the builder, is no answer of a holder: the + // item is left to be given again, never ended as failed. + t.Run("a call not answered within the bound leaves the item to be given again", func(t *testing.T) { + b := newRepublishBed(t) + v := b.reserve(t, "u") + b.holders = map[string][]string{SeatArtifacts: {"oci"}} + b.Bound = time.Minute + b.Send = func(context.Context, Publish) error { + return fmt.Errorf("oci's publish of u: %w", &busretry.Unanswered{Seat: SeatArtifacts, Verb: VerbPublish, Bound: time.Minute, Last: errors.New("no responders")}) + } + if f := b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)); f.Unread == "" || f.Failed != "" || f.Ended != "" || f.Sent { + t.Errorf("a call not answered within the bound answered %+v, want it unread, given again", f) + } + stopped, stop := context.WithCancel(ctx) + b.Send = func(c context.Context, _ Publish) error { stop(); return c.Err() } + if f := b.SendQueued(stopped, b.queueAt(v, PublishClassLive, b.now)); f.Unread == "" || f.Failed != "" || f.Ended != "" { + t.Errorf("a send stopped with the builder answered %+v, want it unread, given again", f) + } + }) // design 47 H2 H-A-746: a publish dropped by hand is kept on its reservation, which its standing reads: an event does not put it, // a send ends it unsent, and builder_publish_again puts it and clears the drop. t.Run("a publish dropped by hand is passed over and asked anew by builder_publish_again", func(t *testing.T) { @@ -645,6 +665,12 @@ func TestAPublishIsPutAgainOnAHoldersEventsOnceBySequence(t *testing.T) { if !handled || err != nil || !slices.Equal(puts(), c.want) { t.Errorf("%s: handled %v, %v, put %v, want %v", c.name, handled, err, puts(), c.want) } + // An event's publish again is always of the class again, its message id ending in the event's stream sequence (H-A-613 (1), H-A-620 (1)). + for _, q := range b.puts { + if id := q.Holder + ".again." + q.Module + "." + EscapeToken(q.Version) + "." + strconv.FormatUint(c.seq, 10); q.Class != PublishClassStart || q.MsgID() != id { + t.Errorf("%s: %s %s put as class %q with the id %q, want class again and the id %q", c.name, q.Module, q.Version, q.Class, q.MsgID(), id) + } + } } if _, _, found, _ := acted.Get(ctx, againKey(sub+"holder")); !found { t.Error("the running's mark is not kept in the state acted") diff --git a/modules/mesh-delivery-builder/internal/versions/reserve.go b/modules/mesh-delivery-builder/internal/versions/reserve.go index 800f42199..44fc1fbfd 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve.go @@ -31,9 +31,6 @@ const ( // ReservedTool is builder_reserved, ReservedDropTool builder_reserved_drop. ReservedTool = "builder_reserved" ReservedDropTool = "builder_reserved_drop" - // UnreleasedBound is the publish's bound: past it a built reservation with an artifact unpublished is the finding - // version-unreleased (§369). - UnreleasedBound = 10 * time.Minute // VersionUnreleased is that finding. VersionUnreleased = "version-unreleased" // VersionHeldElsewhere is the finding of a number a registry seat already holds, skipped at reserving or moved from (design 47 @@ -151,6 +148,9 @@ type ReserveStore interface { // Reserver reserves versions. type Reserver struct { Store ReserveStore + // Bound is the publish's bound, the setting publish-ack-minutes (design 47 H2 H-A-613 (3)): past it a built reservation with an + // artifact unpublished is the finding version-unreleased (§369). + Bound time.Duration // ReleasedOf are the patch versions (MAJOR.MINOR.PATCH) the catalog holds released for module, from its verb versions. ReleasedOf func(ctx context.Context, module string) ([]string, error) // Took is told when a build took over the series' reservation of an older build never released (design 47 G A-455): the @@ -718,7 +718,7 @@ func (r *Reserver) Released(ctx context.Context, module, version string) ([]stri return gone, nil } -// Unreleased are the reservations whose build ended more than UnreleasedBound before now with an artifact unpublished: +// Unreleased are the reservations whose build ended more than Reserver.Bound before now with an artifact unpublished: // the finding version-unreleased, naming the module, the version and the artifacts missing (published says whether an // artifact is). A reservation whose build has not ended is not one. type Unreleased struct { @@ -739,7 +739,7 @@ func (r *Reserver) Overdue(ctx context.Context, published func(module, version, if err != nil { return nil, err } - if !found || cur.BuiltAt.IsZero() || r.now().Sub(cur.BuiltAt) < UnreleasedBound { + if !found || cur.BuiltAt.IsZero() || r.now().Sub(cur.BuiltAt) < r.Bound { continue } var missing []string diff --git a/modules/mesh-delivery-builder/internal/versions/reserve_test.go b/modules/mesh-delivery-builder/internal/versions/reserve_test.go index 41bb62e44..656d9efe9 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve_test.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve_test.go @@ -39,7 +39,7 @@ func TestReservation(t *testing.T) { now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) released := []string{"0.1.18", "0.1.19", "0.2.7"} store := &reserveMem{mem: newMem()} - r := &Reserver{Store: store, Now: func() time.Time { return now }, + r := &Reserver{Store: store, Bound: testBound, Now: func() time.Time { return now }, ReleasedOf: func(context.Context, string) ([]string, error) { return released, nil }} arts := []string{"m:a", "m:b"} @@ -83,7 +83,7 @@ func TestReservation(t *testing.T) { if got, _ := r.Overdue(ctx, published); len(got) != 0 { t.Fatalf("unreleased before the bound: %v", got) } - now = now.Add(UnreleasedBound) + now = now.Add(testBound) got, err := r.Overdue(ctx, published) want := []Unreleased{{Module: "m", Version: "0.1.23", Missing: []string{"m:b"}}} if err != nil || !reflect.DeepEqual(got, want) { @@ -530,3 +530,33 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) { } } } + +// testBound is the publish bound the tests set, the setting publish-ack-minutes at its default. +const testBound = 10 * time.Minute + +// TestOverdueTakesTheSettingsBound: design 47 H2 H-A-613 (3): the finding version-unreleased is timed by the setting +// publish-ack-minutes, whatever its value, not by a constant of 10 minutes. +func TestOverdueTakesTheSettingsBound(t *testing.T) { + ctx := context.Background() + now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + r := &Reserver{Store: &reserveMem{mem: newMem()}, Bound: 30 * time.Minute, Now: func() time.Time { return now }, + ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} + v, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{}) + if err != nil { + t.Fatal(err) + } + if _, _, err := r.Built(ctx, "m", v.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + after time.Duration + want int + }{{15 * time.Minute, 0}, {29 * time.Minute, 0}, {30 * time.Minute, 1}} { + cur := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC).Add(c.after) + now = cur + got, err := r.Overdue(ctx, func(_, _, _ string) bool { return false }) + if err != nil || len(got) != c.want { + t.Errorf("%v after the build with the bound at 30 minutes: %v (%v), want %d findings", c.after, got, err, c.want) + } + } +} diff --git a/modules/mesh-delivery-builder/manifest_test.go b/modules/mesh-delivery-builder/manifest_test.go index 6540eedad..497c53e47 100644 --- a/modules/mesh-delivery-builder/manifest_test.go +++ b/modules/mesh-delivery-builder/manifest_test.go @@ -354,6 +354,11 @@ func TestServesNoRequestSubjectAndHoldsNoTicker(t *testing.T) { // 1607/AC6 (ADR } // Design 47 H2 H-A-654: the publishes' dispatch takes the step queue's shape, bound again on the consumer's created and // deleted advisories: the same one kind of subscription. + // Design 47 H2 H-A-613 (3): a publish item is marked in progress while its call waits, at the kept call's pace (the + // queue's own cadence, as the step queue's), so the bus gives it again only when the builder itself stopped. + if f == "time.NewTicker" && filepath.ToSlash(path) == "cmd/mesh-delivery-builder/publishitem.go" { + continue + } if f == "Subscribe(" && filepath.ToSlash(path) == "cmd/mesh-delivery-builder/publishitem.go" { continue } diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools.go index 97580ccc2..bfcbd8925 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools.go @@ -5,6 +5,7 @@ import ( "errors" "strings" + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -67,8 +68,10 @@ func VerbTools(ask func(key string, body any) (json.RawMessage, error)) []stdio. "Put the closed group of a mover kept in the state unfinished in a pipeline at once, by the seat verb place-unfinished (design 47 H2 H-A-607 (3), H-A-644, H-A-725): exactly one of key (.; runner_unfinished lists them) or all (every key whose carrier neither waits nor runs), and why; one hand act per call. A group none of whose movers failed joins the head's pipeline while that waits or runs; otherwise the pipeline it left is reopened for the whole group under its own key. With key the answer names the pipeline; with all it lists placed (key, pipeline) and failed (key, words), both always present, and says so when no key was there.", obj([]string{"why"}, map[string]any{"key": str, "all": map[string]any{"type": "boolean"}, "why": str}), func(in seat.PlaceUnfinishedInput) string { - if (in.Key == "") == !in.All { - return "place-unfinished names the unfinished entry's key or all, exactly one" + // The seat's client decodes the input and refuses neither or both of key and all (design 47 H2 H-A-644). + raw, _ := json.Marshal(in) + if _, err := runnerclient.PlaceUnfinished(raw); err != nil { + return err.Error() } return whyOf(in.Why) }), diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools_test.go index 73b03c924..d135b26b8 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/verbtools_test.go @@ -47,7 +47,7 @@ func TestVerbTools(t *testing.T) { // H-A-644: all places every key in one hand act; key and all together are refused. {"unfinished place all", "runner_unfinished_place", "seat:mesh-pipeline-runner.place-unfinished", "", map[string]any{"all": true, "why": "now"}, seat.PlaceUnfinishedInput{All: true, Why: "now"}}, - {"unfinished place key and all", "runner_unfinished_place", "", "exactly one", map[string]any{"key": "main.app", "all": true, "why": "now"}, nil}, + {"unfinished place key and all", "runner_unfinished_place", "", "meshpipelinerunnerclient: place-unfinished names exactly one", map[string]any{"key": "main.app", "all": true, "why": "now"}, nil}, {"ask-again no why", "runner_ask_again", "", "names why", map[string]any{"pipeline": "p"}, nil}, } { t.Run(c.name, func(t *testing.T) { diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/held_integration_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/held_integration_test.go new file mode 100644 index 000000000..26fe7fe4a --- /dev/null +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/held_integration_test.go @@ -0,0 +1,159 @@ +//go:build integration + +package main + +import ( + "context" + "encoding/json" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/nats-io/nats.go" + + builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" + catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" + stdio "git.novox.be/novox/mesh-sdk/go" + + "mesh-delivery-pipeline/internal/pipeline" +) + +// testASupersededBuildIsPassedOverOrHeldAndItsWaitEnds is a row of TestTheRunnerPlacesAPipelineAsksItsBuildTakesItsEndAndAnswersAReview +// (design 47 H2 H-A-583 (2), H-A-619): a build ended superseded naming a revision older than the pipeline's is passed over, said +// as a step-started with rerun, and its mover stays (AC-P1b, H-A-577 (3)); one ended naming a newer revision the view does not hold +// holds the step with wait-held, its bound the stalled bound at one minute and its clock the time it was held, and the view +// taking the revision in ends the wait ran (AC-P2, H-A-599). +func testASupersededBuildIsPassedOverOrHeldAndItsWaitEnds(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + t.Setenv(stdio.SettingWord(pipeline.StalledBoundSetting), "1m") + reg := catalog.Registration{Module: "app", Branches: []string{"main"}, Origin: "o/app", Policy: catalog.Policy{Steps: catalog.StepStatuses{Review: "bypass", Validate: "bypass", Composition: "bypass", Approval: "bypass"}}} + var nine atomic.Bool + w := startWhole(t, ctx, []catalog.Registration{reg}, func(raw []byte) catalog.RevisionAnswer { + var in catalog.RevisionInput + _ = json.Unmarshal(raw, &in) + // A revision the catalog keeps answers as itself: a read naming 9 is answered 9 from the start; only the newest follows nine. + if in.Revision == 9 || (nine.Load() && in.Revision == 0) { + return catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: 9, Kind: "trunk", Branch: "main", Source: 9}, + Entries: []catalog.CatalogEntry{{Module: "app", Commit: "c1", Fp: "src2:a9"}}} + } + return catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: 1, Kind: "trunk", Branch: "main", Source: 3}, + Entries: []catalog.CatalogEntry{{Module: "app", Commit: "c1", Fp: "src2:aa"}}} + }) + var mu sync.Mutex + var started []seat.StepEvent + var waits []seat.Wait + var held, ended int + for subject, hear := range map[string]func(*nats.Msg){ + seat.SubjectStepStartedAll: func(m *nats.Msg) { + var ev seat.StepEvent + if json.Unmarshal(m.Data, &ev) == nil { + mu.Lock() + started = append(started, ev) + mu.Unlock() + } + }, + seat.SubjectWaitHeldAll: func(m *nats.Msg) { hearWait(&mu, &waits, &held, m) }, + seat.SubjectWaitEndedAll: func(m *nats.Msg) { hearWait(&mu, &waits, &ended, m) }, + } { + if _, err := w.nc.Subscribe(subject, hear); err != nil { + t.Fatal(err) + } + } + taken, _ := json.Marshal(catalog.TakeInTaken{Branch: "main", Source: 3, Call: "0123456789abcdef", + Entries: []catalog.TakeInEntry{{Module: "app", Commit: "c1", Fingerprint: "src2:aa"}}}) + const key = "main.3" + var p seat.Pipeline + waitFor(t, ctx, w.logs, func() bool { + _, err := w.js.Publish(ctx, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", taken) + return err == nil && readPipeline(ctx, w.pipelines, key, &p) + }) + rev, _ := json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: 1, Kind: "trunk", Branch: "main", Source: 3}) + if _, err := w.js.Publish(ctx, catalog.SubjectCatalogRevision("main"), rev); err != nil { + t.Fatal(err) + } + waitFor(t, ctx, w.logs, func() bool { + return readPipeline(ctx, w.pipelines, key, &p) && stepOf(p, seat.StepResultStepBuild).Outcome == seat.StepResultOutcomeRunning + }) + end := func(ask string, revision int64) { + raw, _ := json.Marshal(builds.StepEnded{ID: ask, Pipeline: key, Step: "build", Node: "n1", Outcome: builds.StepEndedOutcomeSuperseded, Revision: revision, + Said: "app at src2:aa is superseded", + Entries: []builds.BuildEntry{{Module: "app", Commit: "c1", Fingerprint: "src2:aa"}}}) + if _, err := w.js.Publish(ctx, "mesh.seat.mesh-builds.event.step-ended.n1", raw); err != nil { + t.Fatal(err) + } + } + // AC-P1b: an end naming revision 2, older than the pipeline's own 3, is passed over: asked again, said as a step-started with + // rerun by the runner, and the mover stays. + first := stepOf(p, seat.StepResultStepBuild).Ask + end(first, 2) + waitFor(t, ctx, w.logs, func() bool { + return readPipeline(ctx, w.pipelines, key, &p) && stepOf(p, seat.StepResultStepBuild).Ask != first + }) + again := stepOf(p, seat.StepResultStepBuild) + // The runner says the step-started after the write: wait for the one with rerun. + var last seat.StepEvent + waitFor(t, ctx, w.logs, func() bool { + mu.Lock() + defer mu.Unlock() + for _, ev := range started { + if ev.Result.Rerun && ev.Result.Ask == again.Ask { + last = ev + return true + } + } + return false + }) + if again.Outcome != seat.StepResultOutcomeRunning || !again.Rerun || len(p.Superseded) != 0 || !last.Result.Rerun || last.Result.By != "mesh-delivery-pipeline" || last.Result.Ask != again.Ask { + t.Fatalf("a superseded end naming an older revision left %+v, superseded %v, last step-started %+v; want the build asked again as a rerun by the runner, the mover staying", again, p.Superseded, last) + } + // AC-P2: an end naming revision 9, which the view (at 1) does not hold, holds the step: wait-held with the stalled bound. + end(again.Ask, 9) + waitFor(t, ctx, w.logs, func() bool { + mu.Lock() + defer mu.Unlock() + return held == 1 + }) + mu.Lock() + h := waits[0] + mu.Unlock() + if h.On != seat.WaitOnRevisionView || h.Bound != "1m0s" || h.ClockFrom == nil || h.Module != "app" || h.How != "" { + t.Fatalf("wait-held said %+v, want app's wait on the revision view, bound 1m0s, a clock-from", h) + } + if !readPipeline(ctx, w.pipelines, key, &p) || stepOf(p, seat.StepResultStepBuild).Outcome != seat.StepResultOutcomeWaiting || p.Outcome != seat.PipelineOutcomeRunning { + t.Fatalf("the held build reads %+v in pipeline %s", stepOf(p, seat.StepResultStepBuild), p.Outcome) + } + // The view takes revision 9 in: the wait ends ran, its clock the hold's, and the mover leaves for the newer revision's pipeline. + nine.Store(true) + rev, _ = json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: 9, Kind: "trunk", Branch: "main", Source: 9}) + if _, err := w.js.Publish(ctx, catalog.SubjectCatalogRevision("main"), rev); err != nil { + t.Fatal(err) + } + waitFor(t, ctx, w.logs, func() bool { + mu.Lock() + defer mu.Unlock() + return ended == 1 + }) + mu.Lock() + e := waits[1] + mu.Unlock() + if e.How != "ran" || e.On != seat.WaitOnRevisionView || e.ClockFrom == nil || !e.ClockFrom.Equal(*h.ClockFrom) { + t.Fatalf("wait-ended said %+v, want how ran on the revision view with the hold's clock %v", e, h.ClockFrom) + } + if !strings.Contains(w.logs.String(), "judged again") { + t.Errorf("the view's move did not judge the held step again:\n%s", w.logs.String()) + } +} + +func hearWait(mu *sync.Mutex, waits *[]seat.Wait, n *int, m *nats.Msg) { + var w seat.Wait + if json.Unmarshal(m.Data, &w) == nil { + mu.Lock() + *waits = append(*waits, w) + *n++ + mu.Unlock() + } +} diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go index 3b8407d5e..1688b9b47 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go @@ -179,7 +179,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro if err != nil { return err } - hearer.StalledBound = stalledBound // the held step's wait is timed by it (H-A-738 (2)) + hearer.KeptRevision = revisionHeld(calls.CallKept) // a held step's revision the catalog answers gone ends its wait failed (H-A-599) + hearer.StalledBound = stalledBound // the held step's wait is timed by it (H-A-738 (2)) // design 47 H2 H-A-709 (2), §781: the answer bound, read as the tools program reads it; a value outside its range stops the start. answerBound, err := pipeline.AnswerBound(stdio.Setting) if err != nil { @@ -288,6 +289,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro return half.Entries, err == nil } unfinished.Pipeline = func(key string) (seat.Pipeline, bool) { p, _, err := store.Get(key); return p, err == nil } + unfinished.Kept = func(key string) map[string]int64 { + kept, err := store.KeptRevisions(key) + if err != nil { + logger.Printf("the kept-revisions of %s are not read, so its movers' entries are read at the revision its key names: %v", key, err) + } + return kept + } unfinished.Registered = func(module string) bool { _, ok := rv.Registrations.Registration(module); return ok } unfinished.Add = func(from seat.Pipeline, group []seat.Mover) (string, bool) { half, ok := rv.Catalog.View(from.Branch) diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/queue_integration_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/queue_integration_test.go index 28195f2d5..fe4ccce08 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/queue_integration_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/queue_integration_test.go @@ -12,6 +12,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "testing" "time" @@ -102,7 +103,21 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { } } answer("mesh.seat.mesh-catalog.call.registrations.*", catalog.RegistrationsAnswer{Registrations: regs}) - answer("mesh.seat.mesh-catalog.call.revision.*", catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: 100, Kind: "trunk", Branch: "main", Source: 2}, Entries: entries}) + // The view holds the revision of the newest take-in (the head, H-A-594 (1), H-A-759); take says each revision before its take-in. + var newest atomic.Int64 + newest.Store(1) + if _, err := nc.Subscribe("mesh.seat.mesh-catalog.call.revision.*", func(m *nats.Msg) { + var q catalog.RevisionInput + _ = json.Unmarshal(m.Data, &q) + n := q.Revision + if n == 0 { + n = newest.Load() + } + raw, _ := json.Marshal(map[string]any{"result": catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: n, Kind: "trunk", Branch: "main", Source: n}, Entries: entries}}) + _ = m.Respond(raw) + }); err != nil { + t.Fatal(err) + } answer("mesh.seat.mesh-hand-acts.call.hand-act.*", map[string]any{}) // The router of the operator's asks holds the seat operator-channel; its record of each ask is in its state asks. const router = "operator-router" @@ -227,6 +242,11 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { for _, m := range movers { ev.Entries = append(ev.Entries, catalog.TakeInEntry{Module: m, Commit: "c1", Fingerprint: "src2:" + m}) } + newest.Store(source) + rev, _ := json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: source, Kind: "trunk", Branch: "main", Source: source, CallKind: catalog.CatalogRevisionEventCallKindTakeIn}) + if _, err := js.Publish(ctx, catalog.SubjectCatalogRevision("main"), rev); err != nil { + t.Fatal(err) + } body, _ := json.Marshal(ev) if _, err := js.Publish(ctx, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", body); err != nil { t.Fatal(err) @@ -429,8 +449,10 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { if s.Outcome != seat.StepResultOutcomeCouldNotRun || s.Why != pipeline.UntakenWhy(builds.Seat) || s.Ended == nil || s.Ended.Sub(*build.Started) < time.Second { t.Fatalf("main.10's build = %+v, want could not run, its ask not taken, at its bound of 1s", s) } - if strings.Contains(logs.String(), "asked once more") { - t.Fatal("the untaken build's ask was asked once more for its bound") + for _, line := range strings.Split(logs.String(), "\n") { // the catalog view's own retries, as its revision moves, are no ask of a build + if strings.Contains(line, "asked once more") && !strings.Contains(line, catalog.VerbRevision) { + t.Fatalf("the untaken build's ask was asked once more for its bound: %s", line) + } } waitFor(t, ctx, logs, func() bool { e, err := findings.Get(ctx, "call."+build.Ask+".call-unanswered") diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/run_integration_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/run_integration_test.go index e62a9c912..38e206451 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/run_integration_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/run_integration_test.go @@ -57,6 +57,7 @@ func TestTheRunnerPlacesAPipelineAsksItsBuildTakesItsEndAndAnswersAReview(t *tes t.Run("a takeins bind that failed is bound again on registration-changed", testATakeInsBindThatFailedIsBoundAgainOnRegistrationChanged) t.Run("step log read does not wait for a batch it cannot fill", testStepLogReadDoesNotWaitForABatchItCannotFill) t.Run("a bound passing reads the runner's own step-ended durable", testABoundPassingReadsTheRunnersOwnStepEndedDurable) + t.Run("a superseded build is passed over or held and its wait ends", testASupersededBuildIsPassedOverOrHeldAndItsWaitEnds) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() reg := catalog.Registration{Module: "app", Branches: []string{"main"}, Origin: "o/app", Policy: catalog.Policy{Steps: catalog.StepStatuses{Review: "optional", Validate: "bypass", Composition: "required", Approval: "bypass"}}} diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/unfinished_integration_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/unfinished_integration_test.go index 80cfcaf55..13b0ebbbe 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/unfinished_integration_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/unfinished_integration_test.go @@ -13,10 +13,13 @@ import ( "github.com/nats-io/nats.go" + "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants" builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" 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" + "git.novox.be/novox/mesh-sdk/go/seatlist" "mesh-delivery-pipeline/internal/pipeline" ) @@ -30,7 +33,10 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { steps := catalog.StepStatuses{Lint: "bypass", Unit: "required", Integration: "bypass", Validate: "required", Composition: "required", Review: "bypass", Approval: "bypass"} regs := []catalog.Registration{{Module: "app", Branches: []string{"main"}, Origin: "o/app", Policy: catalog.Policy{Steps: steps}}, - {Module: "lib", Branches: []string{"main"}, Origin: "o/lib", Policy: catalog.Policy{Steps: steps}}} + {Module: "lib", Branches: []string{"main"}, Origin: "o/lib", Policy: catalog.Policy{Steps: steps}}, + {Module: "engine", Branches: []string{"main"}, Origin: "o/engine", Policy: catalog.Policy{Steps: steps}}, + {Module: "gitea", Branches: []string{"main"}, Origin: "o/gitea", Policy: catalog.Policy{Steps: steps}}, + {Module: "free", Branches: []string{"main"}, Origin: "o/free", Policy: catalog.Policy{Steps: steps}}} var newest atomic.Int64 newest.Store(1) w := startWhole(t, ctx, regs, func(in []byte) catalog.RevisionAnswer { @@ -40,15 +46,63 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { if n == 0 { n = newest.Load() } - lib := "l1" + if n == 99 { // a revision the catalog keeps no more + return catalog.RevisionAnswer{} + } + lib, goFp := "l1", "src2:go" if n == 2 { lib = "l2" } - return catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: n, Kind: "trunk", Branch: "main", Source: n + 2}, - Entries: []catalog.CatalogEntry{{Module: "app", Commit: "c1", Fp: "src2:aa"}, - {Module: "lib", Commit: lib, Fp: "src2:" + lib, Artifacts: []catalog.Artifact{{Ref: "lib:lib", Language: "go", Kind: "program"}}}, - {Module: "mesh-build-go", Commit: "c0", Fp: "src2:go", Acts: []catalog.ActingRule{{Step: "build", On: "go", Seat: nodebuildgo.Seat}}}}} + if n == 12 { // the build seat's holder moves with revision 12 (AC-P6b) + lib, goFp = "l12", "src2:go2" + } + entries := []catalog.CatalogEntry{{Module: "app", Commit: "c1", Fp: "src2:aa"}, + {Module: "lib", Commit: lib, Fp: "src2:" + lib, Artifacts: []catalog.Artifact{{Ref: "lib:lib", Language: "go", Kind: "program"}}}, + {Module: "mesh-build-go", Commit: "c0", Fp: goFp, Acts: []catalog.ActingRule{{Step: "build", On: "go", Seat: nodebuildgo.Seat}}}} + if n >= 4 { + // engine, the module gitea's build waits for (an edge of kind 3): its fingerprint is e1 at 4 and 5, e2 at 6, e3 from 7. + engine, gitea, free := "e1", "g1", "f1" + switch { + case n >= 7: + engine, gitea = "e3", "g2" + case n == 6: + engine = "e2" + } + if n >= 8 { + free = "f2" + } + app := catalog.CatalogEntry{Module: "app", Commit: "c1", Fp: "src2:aa"} + if n >= 9 { + app.Fp = "src2:a9" + } + entries[0] = app + entries = append(entries, + catalog.CatalogEntry{Module: "engine", Commit: engine, Fp: "src2:" + engine, Artifacts: []catalog.Artifact{{Ref: "engine:engine", Language: "go", Kind: "program"}}}, + catalog.CatalogEntry{Module: "gitea", Commit: gitea, Fp: "src2:" + gitea, Edges: []catalog.Edge{{From: catalog.ArtifactRef("engine:engine"), Kind: 3}}}, + catalog.CatalogEntry{Module: "free", Commit: free, Fp: "src2:" + free}) + } + return catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: n, Kind: "trunk", Branch: "main", Source: n + 2, Base: n - 1}, Entries: entries} }) + // The seat holders and the grants part answer, so a widening is named only for what a revision alters against its base: the + // build seat's holder is the module mesh-build-go, every other seat's a module the catalog holds no entry of. + var held []any + for _, name := range []string{seat.Seat, catalog.Seat, pipeline.ComposerSeat, builds.Seat, nodebuildgo.Seat, wants.Seat} { + holder := "holder-" + name + if name == nodebuildgo.Seat { + holder = "mesh-build-go" + } + held = append(held, map[string]any{"seat": name, "holders": []any{map[string]any{"module": holder}}}) + } + for subject, body := range map[string]any{"mesh.seat." + seatlist.HolderSeat + ".call." + seatlist.HolderVerb + ".*": map[string]any{"seats": held}, + "mesh.seat." + meshgrants.Seat + ".call." + meshgrants.VerbGrantsFor + ".*": meshgrants.GrantsFor{}, + // The builds seat's published answers that nothing is published: gitea's wait on engine (an edge of kind 3) is met by + // engine's build step passing, as the runner hears it. + "mesh.seat." + builds.Seat + ".call." + builds.VerbPublished + ".*": builds.PublishedAnswer{}} { + raw, _ := json.Marshal(map[string]any{"result": body}) + if _, err := w.nc.Subscribe(subject, func(m *nats.Msg) { _ = m.Respond(raw) }); err != nil { + t.Fatal(err) + } + } ended := make(chan seat.PipelineEnded, 4) if _, err := w.nc.Subscribe("mesh.seat.mesh-pipeline-runner.event.pipeline-ended.>", func(m *nats.Msg) { var pe seat.PipelineEnded @@ -70,6 +124,7 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { } // answer ends every running step of key once, as its seat's holder says it: lib's unit fails when fail says so. answered := map[string]bool{} + failing, failStep := "lib", seat.StepResultStepUnit // the step that fails where answer is told to fail answer := func(key string, fail bool) func() bool { return func() bool { var p seat.Pipeline @@ -84,7 +139,7 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { answered[s.Ask+s.Module] = true m, _ := pipeline.MoverOf(p, s.Module) outcome := "passed" - if fail && s.Module == "lib" && s.Step == seat.StepResultStepUnit { + if fail && s.Module == failing && s.Step == failStep { outcome = "failed" } body := map[string]any{"v": 1, "id": s.Ask, "pipeline": key, "step": s.Step, "module": s.Module, "commit": m.Commit, @@ -119,6 +174,12 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { t.Fatalf("the state unfinished holds no main.app: %v", err) } + // design 47 H2 H-A-607 (2), H-A-619 (AC-P4): with no pipeline running, nothing starts to carry app; main.2 is started by the next + // take-in alone. + var none seat.Pipeline + if readPipeline(ctx, w.pipelines, "main.2", &none) { + t.Fatalf("main.2 was started with no take-in: the runner starts nothing to carry a mover\n%s", w.logs.String()) + } // The next take-in moves lib alone, at a new fingerprint: its pipeline carries app, whose composition is asked and passes. newest.Store(2) rev, _ := json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: 2, Kind: "trunk", Branch: "main", Source: 4, CallKind: catalog.CatalogRevisionEventCallKindTakeIn}) @@ -182,4 +243,224 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { if !readPipeline(ctx, w.pipelines, "main.3", &third) || third.EndCount != 2 || len(ended) != 0 { t.Errorf("main.3 ended %d times and %d ends wait, want its second end and no third", third.EndCount, len(ended)) } + + // reach makes revision n the one the view holds, as the indexer's catalog-revision says it, then takes in its entries. + reach := func(n int64, entries ...catalog.TakeInEntry) { + newest.Store(n) + rev, _ := json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: n, Kind: "trunk", Branch: "main", Source: n + 2, CallKind: catalog.CatalogRevisionEventCallKindTakeIn}) + if _, err := w.js.Publish(ctx, catalog.SubjectCatalogRevision("main"), rev); err != nil { + t.Fatal(err) + } + takeIn(n+2, n, entries...) + } + unfinishedEntry := func(key string) (pipeline.UnfinishedEntry, bool) { + var e pipeline.UnfinishedEntry + raw, err := unfinished.Get(ctx, key) + if err != nil || json.Unmarshal(raw.Value(), &e) != nil { + return e, false + } + return e, true + } + moves := func(key string, modules ...string) bool { + var p seat.Pipeline + if !readPipeline(ctx, w.pipelines, key, &p) { + return false + } + for _, m := range modules { + if !pipeline.Moves(p, m) { + return false + } + } + return true + } + + // design 47 H2 H-A-594 (2), H-A-646, H-A-610 (AC-P3), whole: engine fails in main.4 and gitea, whose build waits for engine's + // build step (an edge of kind 3), passes its steps; gitea is left unfinished and tied to engine. A take-in that moves free alone + // carries nothing: main.5 moves free, gitea stays in unfinished. + failing = "engine" + reach(4, catalog.TakeInEntry{Module: "engine", Commit: "e1", Fingerprint: "src2:e1"}, catalog.TakeInEntry{Module: "gitea", Commit: "g1", Fingerprint: "src2:g1"}) + waitFor(t, ctx, w.logs, answer("main.4", true)) + if pe := endOf(); pe.Pipeline != "main.4" || pe.Outcome != seat.PipelineEndedOutcomeFailed || !slices.Equal(pe.Unfinished, []string{"gitea"}) { + t.Fatalf("pipeline-ended = %s %s unfinished %v, want main.4 failed leaving gitea unfinished\n%s", pe.Pipeline, pe.Outcome, pe.Unfinished, w.logs.String()) + } + reach(5, catalog.TakeInEntry{Module: "free", Commit: "f1", Fingerprint: "src2:f1"}) + waitFor(t, ctx, w.logs, answer("main.5", false)) + if e, ok := unfinishedEntry("main.gitea"); !ok || e.Pipeline != "main.4" || e.CarriedBy != "" || !moves("main.5", "free") || moves("main.5", "gitea") { + t.Fatalf("main.gitea = %+v (held %t), main.5 moves gitea %t: want gitea tied to engine, kept in unfinished and not carried by main.5\n%s", e, ok, moves("main.5", "gitea"), w.logs.String()) + } + if pe := endOf(); pe.Pipeline != "main.5" || pe.Outcome != seat.PipelineEndedOutcomePassed { + t.Fatalf("main.5 ended %s %s, want passed\n%s", pe.Pipeline, pe.Outcome, w.logs.String()) + } + + // AC-P3: once engine passes, in the pipeline of its newer fingerprint, gitea is carried with it and wanted; its key goes. + failing = "" + reach(6, catalog.TakeInEntry{Module: "engine", Commit: "e2", Fingerprint: "src2:e2"}) + waitFor(t, ctx, w.logs, answer("main.6", false)) + if pe := endOf(); pe.Pipeline != "main.6" || pe.Outcome != seat.PipelineEndedOutcomePassed || !moves("main.6", "engine", "gitea") { + t.Fatalf("main.6 ended %s %s, moving gitea %t: want engine passed and gitea carried with it\n%s", pe.Pipeline, pe.Outcome, moves("main.6", "gitea"), w.logs.String()) + } + if _, ok := unfinishedEntry("main.gitea"); ok { + t.Error("main.gitea is still unfinished after main.6 passed") + } + + // design 47 H2 H-A-623 (AC-P5b), whole: engine fails again in main.7, leaving gitea tied to it; place-unfinished of gitea's key + // reopens main.7 for gitea with its failed engine, whose step fails again: main.7 ends failed a second time, leaving gitea. + placeKey := func(key string) seat.PlaceUnfinishedAnswer { + var placed seat.PlaceUnfinishedAnswer + waitFor(t, ctx, w.logs, func() bool { + raw, _ := json.Marshal(seat.PlaceUnfinishedInput{Key: key, Why: "the whole test"}) + m, err := w.nc.Request("mesh.seat."+seat.Seat+".call.place-unfinished.agent~dev", raw, 15*time.Second) + var reply struct { + Result json.RawMessage `json:"result"` + Error string `json:"error"` + } + if err != nil || json.Unmarshal(m.Data, &reply) != nil || strings.Contains(reply.Error, "not yet read") { + return false + } + if reply.Error != "" { + t.Fatalf("place-unfinished %s: %s", key, reply.Error) + } + return json.Unmarshal(reply.Result, &placed) == nil + }) + return placed + } + failing, failStep = "engine", seat.StepResultStepBuild // a build step is asked again by a plain ask; a test step joins a run of its own + reach(7, catalog.TakeInEntry{Module: "engine", Commit: "e3", Fingerprint: "src2:e3"}, catalog.TakeInEntry{Module: "gitea", Commit: "g2", Fingerprint: "src2:g2"}) + waitFor(t, ctx, w.logs, answer("main.7", true)) + if pe := endOf(); pe.Pipeline != "main.7" || pe.Outcome != seat.PipelineEndedOutcomeFailed || !slices.Equal(pe.Unfinished, []string{"gitea"}) { + t.Fatalf("pipeline-ended = %s %s unfinished %v, want main.7 failed leaving gitea unfinished\n%s", pe.Pipeline, pe.Outcome, pe.Unfinished, w.logs.String()) + } + if placed := placeKey("main.gitea"); len(placed.Placed) != 1 || placed.Placed[0].Pipeline != "main.7" { + t.Fatalf("place-unfinished of main.gitea = %+v, want it placed in main.7", placed) + } + waitFor(t, ctx, w.logs, answer("main.7", true)) + var seventh seat.Pipeline + if pe := endOf(); pe.Pipeline != "main.7" || pe.Outcome != seat.PipelineEndedOutcomeFailed || !slices.Equal(pe.Unfinished, []string{"gitea"}) || + !readPipeline(ctx, w.pipelines, "main.7", &seventh) || seventh.EndCount != 2 || !pipeline.Moves(seventh, "engine") { + t.Fatalf("main.7 ended again %s unfinished %v after %d ends, want failed with engine in its group, leaving gitea\n%s", pe.Outcome, pe.Unfinished, seventh.EndCount, w.logs.String()) + } + + // AC-P3, the tie's end: engine leaves the registrations (its registration-changed heard, the first view asked again); the next + // take-in's pipeline, main.8, carries gitea although engine failed and is not moved by it. + regs[2] = regs[4] // engine, the third registration, is replaced by a copy of free's: the answer no longer names it + gone, _ := json.Marshal(catalog.RegistrationChangedEvent{V: 1, Module: "engine", Version: 9, Moved: []string{}, Warrant: "the whole test"}) + if _, err := w.js.Publish(ctx, "mesh.seat.mesh-catalog.event.registration-changed.engine", gone); err != nil { + t.Fatal(err) + } + waitFor(t, ctx, w.logs, func() bool { // the registrations' picture holds four keys once the first view is asked again + kv, err := w.js.KeyValue(ctx, "mesh-delivery-pipeline_first-views") + if err != nil { + return false + } + e, err := kv.Get(ctx, "mesh-catalog.registrations") + var view struct { + Keys int `json:"keys"` + } + return err == nil && json.Unmarshal(e.Value(), &view) == nil && view.Keys == len(regs)-1 + }) + failing, failStep = "", "" + reach(8, catalog.TakeInEntry{Module: "free", Commit: "f2", Fingerprint: "src2:f2"}) + waitFor(t, ctx, w.logs, answer("main.8", false)) + if pe := endOf(); pe.Pipeline != "main.8" || pe.Outcome != seat.PipelineEndedOutcomePassed || !moves("main.8", "free", "gitea") { + t.Fatalf("main.8 ended %s %s, moving gitea %t: want gitea carried although engine failed and left the registrations\n%s", pe.Pipeline, pe.Outcome, moves("main.8", "gitea"), w.logs.String()) + } + if _, ok := unfinishedEntry("main.gitea"); ok { + t.Error("main.gitea is still unfinished after main.8 passed") + } + + // design 47 H2 H-A-608 (AC-P4), whole: free's key names revision 99, which the catalog keeps no more; the take-in of revision 9 + // reads it at the head's revision, where free holds the key's fingerprint, and carries it; ghost's fingerprint is held at neither + // revision, so its key is dropped and the journal names the fingerprint and the revisions looked at. + for key, entry := range map[string]string{ + "main.free": `{"fingerprint":"src2:f2","revision":99,"pipeline":"main.99","outcome":"failed"}`, + "main.ghost": `{"fingerprint":"src2:zz","revision":99,"pipeline":"main.99","outcome":"failed"}`, + } { + if _, err := unfinished.Put(ctx, key, []byte(entry)); err != nil { + t.Fatal(err) + } + } + reach(9, catalog.TakeInEntry{Module: "app", Commit: "c1", Fingerprint: "src2:a9"}) + waitFor(t, ctx, w.logs, answer("main.9", false)) + if pe := endOf(); pe.Pipeline != "main.9" || pe.Outcome != seat.PipelineEndedOutcomePassed || !moves("main.9", "app", "free") { + t.Fatalf("main.9 ended %s %s, moving free %t: want free read at the head's revision and carried\n%s", pe.Pipeline, pe.Outcome, moves("main.9", "free"), w.logs.String()) + } + if _, ok := unfinishedEntry("main.ghost"); ok || !strings.Contains(w.logs.String(), "ghost is no longer unfinished at fingerprint src2:zz: its kept revision 99 is gone, the head's revision 9 of main holds it at") { + t.Errorf("main.ghost is kept, or the journal does not name its fingerprint and the revisions looked at:\n%s", w.logs.String()) + } + + // design 47 H2 H-A-571, H-A-643 (AC-P5c), whole: while the head's pipeline main.10 runs, start of free and lib, which it does not + // carry, adds both to it, each said by mover-added with the caller; no `.again.` pipeline is keyed. + added := make(chan seat.MoverAdded, 4) + if _, err := w.nc.Subscribe("mesh.seat.mesh-pipeline-runner.event.mover-added.>", func(m *nats.Msg) { + var ev seat.MoverAdded + if json.Unmarshal(m.Data, &ev) == nil { + added <- ev + } + }); err != nil { + t.Fatal(err) + } + reach(10, catalog.TakeInEntry{Module: "app", Commit: "c1", Fingerprint: "src2:a9"}) + waitFor(t, ctx, w.logs, func() bool { // its steps are placed once the view holds revision 10, the head start reads + return strings.Contains(w.logs.String(), "main.10 app build asked") + }) + var started seat.StartAnswer + waitFor(t, ctx, w.logs, func() bool { + raw, _ := json.Marshal(seat.StartInput{Branch: "main", Modules: []string{"free", "lib"}, Why: "the whole test"}) + m, err := w.nc.Request("mesh.seat."+seat.Seat+".call.start.agent~dev", raw, 15*time.Second) + var reply struct { + Result json.RawMessage `json:"result"` + Error string `json:"error"` + } + if err != nil || json.Unmarshal(m.Data, &reply) != nil || strings.Contains(reply.Error, "not yet") { + return false + } + if reply.Error != "" { + t.Fatalf("start: %s", reply.Error) + } + return json.Unmarshal(reply.Result, &started) == nil + }) + if started.Pipeline != "main.10" || !moves("main.10", "app", "free", "lib") || len(added) != 2 { + t.Fatalf("start = %+v, main.10 moves free and lib %t, %d mover-added said, want both added to main.10 and said\n%s", started, moves("main.10", "free", "lib"), len(added), w.logs.String()) + } + for range 2 { + if ev := <-added; ev.Pipeline != "main.10" || ev.Caller == "" || ev.From != "" { + t.Errorf("mover-added = %+v, want main.10 with the caller of start", ev) + } + } + keysOf, err := w.pipelines.Keys(ctx) + if err != nil { + t.Fatal(err) + } + for _, k := range keysOf { + if strings.Contains(k, ".again.") { + t.Errorf("start keyed the pipeline %s", k) + } + } + waitFor(t, ctx, w.logs, answer("main.10", false)) + if pe := endOf(); pe.Pipeline != "main.10" || pe.Outcome != seat.PipelineEndedOutcomePassed { + t.Errorf("main.10 ended %s %s, want passed with its added movers\n%s", pe.Pipeline, pe.Outcome, w.logs.String()) + } + + // design 47 H2 H-A-595 (AC-P6b), whole: lib fails in main.11 against a base that alters nothing for app, so app's first widens are + // empty and kept so in its key; main.12 carries app while the build seat's holder moves, and says app's widens as the first + // pipeline did, empty, while lib's own name the serving part. + failing, failStep = "lib", seat.StepResultStepUnit + reach(11, catalog.TakeInEntry{Module: "app", Commit: "c1", Fingerprint: "src2:a9"}, catalog.TakeInEntry{Module: "lib", Commit: "l1", Fingerprint: "src2:l1"}) + waitFor(t, ctx, w.logs, answer("main.11", true)) + if pe := endOf(); pe.Pipeline != "main.11" || !slices.Equal(pe.Unfinished, []string{"app"}) { + t.Fatalf("pipeline-ended = %s unfinished %v, want main.11 leaving app unfinished\n%s", pe.Pipeline, pe.Unfinished, w.logs.String()) + } + if e, err := unfinished.Get(ctx, "main.app"); err != nil || strings.Contains(string(e.Value()), `"widens"`) { + t.Fatalf("main.app's first widens are kept as %s (%v), want none named", e.Value(), err) + } + reach(12, catalog.TakeInEntry{Module: "lib", Commit: "l12", Fingerprint: "src2:l12"}) + waitFor(t, ctx, w.logs, answer("main.12", false)) + last := endOf() + widens := map[string][]seat.Widening{} + for _, m := range last.Movers { + widens[m.Module] = m.Widens + } + if last.Pipeline != "main.12" || len(widens["app"]) != 0 || len(widens["lib"]) != 1 || widens["lib"][0].Name != "mesh-build-go" { + t.Fatalf("%s ended with the widens %+v, want the carried app's empty as its first pipeline's and lib's naming the serving part mesh-build-go\n%s", last.Pipeline, widens, w.logs.String()) + } } diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs.go index cc02ba9c5..327195a9a 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs.go @@ -8,6 +8,7 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" "git.novox.be/novox/mesh-sdk/go/buscalls" @@ -21,15 +22,27 @@ import ( // verbOf makes the handler of one verb from its function of the proved caller and the decoded input: the caller is the bus // user the call's subject names, and a call naming none is refused (design 47 G §394, A-107). func verbOf[In any](do func(caller string, in In) (any, error)) process.SeatHandler { + return decodedVerbOf(func(body []byte) (In, error) { + var in In + if len(body) > 0 { + if err := json.Unmarshal(body, &in); err != nil { + return in, fmt.Errorf("the arguments do not fit the verb's input: %w", err) + } + } + return in, nil + }, do) +} + +// decodedVerbOf is verbOf of a verb whose input the seat's client decodes, with the refusals its contract holds it to +// (design 47 H2 H-A-644, AC-DC2d). +func decodedVerbOf[In any](decode func([]byte) (In, error), do func(caller string, in In) (any, error)) process.SeatHandler { return func(caller string, body json.RawMessage) (any, error) { if caller == "" { return nil, errors.New("the call names no caller the bus proved: it is refused") } - var in In - if len(body) > 0 { - if err := json.Unmarshal(body, &in); err != nil { - return nil, fmt.Errorf("the arguments do not fit the verb's input: %w", err) - } + in, err := decode(body) + if err != nil { + return nil, err } return do(caller, in) } @@ -47,14 +60,15 @@ func answerVerbs(conn *process.Conn, seats *seatlist.Part, v pipeline.Verbs) (fu // the test runs' verbs test-runs and test-runs-drop (A-469g, A-470i). func writeHandlers(v pipeline.Verbs) map[string]process.SeatHandler { return map[string]process.SeatHandler{ - seat.VerbRun: verbOf(func(c string, in seat.RunInput) (any, error) { return v.Run(c, in) }), - seat.VerbReview: verbOf(func(c string, in seat.ReviewInput) (any, error) { return v.Review(c, in) }), - seat.VerbRerun: verbOf(func(c string, in seat.RerunInput) (any, error) { return v.Rerun(c, in) }), - seat.VerbAccept: verbOf(func(c string, in seat.AcceptInput) (any, error) { return v.Accept(c, in) }), - seat.VerbCancel: verbOf(func(c string, in seat.CancelInput) (any, error) { return v.Cancel(c, in) }), - seat.VerbEndAgain: verbOf(func(c string, in seat.EndAgainInput) (any, error) { return v.EndAgain(c, in) }), - seat.VerbPlace: verbOf(func(c string, in seat.PlaceInput) (any, error) { return v.Place(c, in) }), - seat.VerbPlaceUnfinished: verbOf(func(c string, in seat.PlaceUnfinishedInput) (any, error) { return v.PlaceUnfinished(c, in) }), + seat.VerbRun: verbOf(func(c string, in seat.RunInput) (any, error) { return v.Run(c, in) }), + seat.VerbReview: verbOf(func(c string, in seat.ReviewInput) (any, error) { return v.Review(c, in) }), + seat.VerbRerun: verbOf(func(c string, in seat.RerunInput) (any, error) { return v.Rerun(c, in) }), + seat.VerbAccept: verbOf(func(c string, in seat.AcceptInput) (any, error) { return v.Accept(c, in) }), + seat.VerbCancel: verbOf(func(c string, in seat.CancelInput) (any, error) { return v.Cancel(c, in) }), + seat.VerbEndAgain: verbOf(func(c string, in seat.EndAgainInput) (any, error) { return v.EndAgain(c, in) }), + seat.VerbPlace: verbOf(func(c string, in seat.PlaceInput) (any, error) { return v.Place(c, in) }), + // The input is decoded by the seat's client, which refuses one naming neither or both of key and all (H-A-644). + seat.VerbPlaceUnfinished: decodedVerbOf(runnerclient.PlaceUnfinished, func(c string, in seat.PlaceUnfinishedInput) (any, error) { return v.PlaceUnfinished(c, in) }), seat.VerbStart: verbOf(func(c string, in seat.StartInput) (any, error) { return v.Start(c, in) }), seat.VerbAskAgain: verbOf(func(c string, in seat.AskAgainInput) (any, error) { return v.AskAgain(c, in) }), // §728, A-469g: a test run's drop is answered by the process, the only writer of pipelines and test-runs. diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs_test.go index 0946dd8c6..044087c51 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/verbs_test.go @@ -4,12 +4,14 @@ import ( "encoding/json" "errors" "slices" + "strings" "testing" "time" "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/seatlist" + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" "mesh-delivery-pipeline/internal/pipeline" @@ -46,6 +48,25 @@ func TestAVerbIsAnsweredOnlyForAProvedCallerAndItsOwnInput(t *testing.T) { } } +// design 47 H2 H-A-644 (AC-DC2d): place-unfinished's input is decoded by the seat's client: one naming both key and all, or +// neither, is refused with its words before the verb is asked, and `all` is read back. +func TestPlaceUnfinishedIsDecodedBytheSeatsClient(t *testing.T) { + var got seat.PlaceUnfinishedInput + h := decodedVerbOf(runnerclient.PlaceUnfinished, func(_ string, in seat.PlaceUnfinishedInput) (any, error) { got = in; return "placed", nil }) + for _, body := range []string{`{"key":"main.app","all":true,"why":"x"}`, `{"why":"x"}`} { + if _, err := h("operator", json.RawMessage(body)); err == nil || !strings.Contains(err.Error(), "meshpipelinerunnerclient: place-unfinished names exactly one of key and all") || got.Why != "" { + t.Errorf("%s was answered (%v, %+v), want it refused by the client's words", body, err, got) + } + } + if out, err := h("operator", json.RawMessage(`{"all":true,"why":"x"}`)); err != nil || out != "placed" || !got.All { + t.Errorf("all = %v, %v, %+v", out, err, got) + } + // The process answers the verb through it. + if _, err := writeHandlers(pipeline.Verbs{})[seat.VerbPlaceUnfinished]("operator", json.RawMessage(`{"key":"main.app","all":true,"why":"x"}`)); err == nil || !strings.Contains(err.Error(), "meshpipelinerunnerclient") { + t.Errorf("the process answered place-unfinished naming key and all: %v, want the client's refusal", err) + } +} + // listingCatalog is the seat mesh-catalog as the reader asks it: an empty listing, so the bootstrapped definitions stand, or, // silent, no answer at all. type listingCatalog struct{ silent bool } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/carry.go b/modules/mesh-delivery-pipeline/internal/pipeline/carry.go index 3325b1d32..85e0db329 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/carry.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/carry.go @@ -8,7 +8,6 @@ import ( runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" - "git.novox.be/novox/mesh-sdk/go/keys" ) // AddedFrom says where a mover added to a pipeline came from; exactly one field is set (design 47 H2 H-A-645). @@ -96,35 +95,43 @@ func (f AddedFrom) describe() string { return fmt.Sprintf("a take-in of source %d", f.TakeIn) } -// head is the key of the newest pipeline of branch, by its catalog revision, and the pipeline: the head's pipeline (H-A-594 (1)). -func (s *Starter) head(branch string) (seat.Pipeline, bool) { - pkeys, err := s.Store.Keys(keys.EscapeName(branch) + ".*") - if err != nil { - return seat.Pipeline{}, false - } - var best seat.Pipeline - found := false - for _, k := range pkeys { - p, _, err := s.Store.Get(k) - if err != nil || p.Run != "" || p.Branch != branch { - continue - } - if !found || p.Revision > best.Revision { - best, found = p, true - } - } - return best, found +// headKey is the key of the head's pipeline of branch, whose catalog view holds half: the head's revision is the newest one the runner's catalog +// view holds, one head for the carry and for start alike (design 47 H2 H-A-594 (1), H-A-759). +func headKey(branch string, half Half) string { + return Key(branch, keyRevision(Begin{Revision: half.Revision, Source: half.Source})) } -// CarryToHead adds the closed group of movers pipeline from left to the head's pipeline of its branch when that waits or runs, +// head reads the head's pipeline of half's branch by its key: held is false when the head's revision has no pipeline (a +// revision whose take-in is not handled yet, or that moved nothing); an older open pipeline of the branch is never the head. +func (s *Starter) head(key string) (p seat.Pipeline, held bool, err error) { + keys, err := s.Store.Keys(key) + if err != nil || len(keys) == 0 { + return seat.Pipeline{}, false, err + } + p, _, err = s.Store.Get(key) + return p, err == nil, err +} + +// CarryToHead adds the closed group of movers pipeline from left to the head's pipeline of its branch (view's newest revision) when that waits or runs, // and takes the movers out of from's movers, so none of its later ends names them (H-A-594 (3), (4), H-A-607 (2)). It // answers the head's key, false when nothing was added: the head is from itself or has ended. func (s *Starter) CarryToHead(from seat.Pipeline, group []seat.Mover, entries map[string]catalog.CatalogEntry, view func(branch string) (Half, bool)) (string, bool) { if s.Store == nil { return "", false } - head, ok := s.head(from.Branch) - if !ok || head.Pipeline == from.Pipeline || head.Revision < from.Revision || !openPipeline(head) { + if view == nil { + return "", false + } + half, ok := view(from.Branch) + if !ok { + return "", false + } + head, held, err := s.head(headKey(from.Branch, half)) + if err != nil { + s.logf("the head's pipeline of %s is not read, so the movers %v of %s are not carried to it: %v", from.Branch, moduleNames(group), from.Pipeline, err) + return "", false + } + if !held || head.Pipeline == from.Pipeline || head.Revision < from.Revision || !openPipeline(head) { return "", false } if _, err := s.AddMovers(head.Pipeline, group, entries, AddedFrom{From: from.Pipeline}, view); err != nil { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go index e0b5f7a97..818ae7cb3 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go @@ -202,6 +202,10 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { {"the same revision's entry, the builder's kept revision (H-A-563)", 117, 117, "left"}, {"a newer revision's entry the view does not hold yet", 120, 118, "held"}, {"a newer revision's entry the view holds", 120, 120, "left"}, + // H-A-599: the held step's wait ends failed when the catalog answers its revision gone, ended superseded when a newer + // pipeline takes its mover. + {"a newer revision's entry the catalog answers gone", 120, 118, "gone"}, + {"a newer revision's entry, its mover then taken by a newer pipeline", 120, 118, "taken"}, } { t.Run("H-A-561: a build superseded by "+r.name, func(t *testing.T) { store := memStore{"main.117": {p: seat.Pipeline{V: 1, Pipeline: "main.117", Branch: "main", Source: 117, Revision: 117, Outcome: seat.PipelineOutcomeRunning, @@ -209,7 +213,7 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { var put []Asked var journal []string var waitBodies []seat.Wait - var waits []string // the waits said, by event and what they wait on (H-A-563) + var waits, hows []string // the waits said, by event and what they wait on (H-A-563), and each one's how (H-A-599) var started []seat.StepEvent view := r.view say := func(subject string, body any) error { @@ -223,10 +227,17 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { } waitBodies = append(waitBodies, w) waits = append(waits, ev+" "+w.Step+" "+w.On+" "+w.Module) + hows = append(hows, w.How) } return nil } h := &Hearer{Store: store, Say: say, Now: func() time.Time { return t0 }, Name: "mesh-delivery-pipeline", StalledBound: time.Minute, + KeptRevision: func(_ string, rv int64) error { + if r.want == "gone" { + return fmt.Errorf("%w: the catalog keeps no revision %d", ErrRevisionGone, rv) + } + return nil + }, View: func(string) (Half, bool) { return Half{Revision: view, Source: view, Entries: map[string]catalog.CatalogEntry{"a": {Module: "a", Fp: "src2:a2"}}}, true }, @@ -270,6 +281,26 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { if !slices.ContainsFunc(journal, func(l string) bool { return strings.Contains(l, "passed over") }) { t.Errorf("the passed-over end is not said: %q", journal) } + case "gone", "taken": + if s := p.Steps[0]; s.Outcome != seat.StepResultOutcomeWaiting || s.On != seat.WaitOnRevisionView || len(waits) != 1 { + t.Fatalf("a's build %+v, waits %q; want it held, one wait-held said", s, waits) + } + if r.want == "taken" { + h.SupersedeRunning(seat.Pipeline{Pipeline: "main.120", Branch: "main", Revision: 120, Movers: []seat.Mover{{Module: "a", Commit: "c2", Fingerprint: "src2:a2"}}}) + } else if moved := h.RevisionHeld("main"); !slices.Equal(moved, []string{"main.117"}) { + t.Fatalf("at revision 118, with revision 120 gone, the view moved %v, want main.117", moved) + } + p, _, _ := store.Get("main.117") + if want := []string{seat.EventWaitHeld + " build revision view a", seat.EventWaitEnded + " build revision view a"}; !slices.Equal(waits, want) { + t.Fatalf("waits said %q, want %q", waits, want) + } + if r.want == "gone" { + if s := p.Steps[0]; hows[1] != "failed" || s.Outcome != seat.StepResultOutcomeFailed || !strings.Contains(s.Why, "revision 120 gone") || len(p.Superseded) != 0 || p.Outcome != seat.PipelineOutcomeRunning { + t.Errorf("how %q, a's build %+v, superseded %v, pipeline %s; want the wait ended failed, the build failed naming revision 120 gone, the mover staying", hows[1], s, p.Superseded, p.Outcome) + } + } else if hows[1] != "superseded" || !slices.Equal(p.Superseded, []string{"a"}) { + t.Errorf("how %q, superseded %v; want the wait ended superseded with its mover gone", hows[1], p.Superseded) + } case "held": if s := p.Steps[0]; len(p.Superseded) != 0 || s.Outcome != seat.StepResultOutcomeWaiting || s.On != seat.WaitOnRevisionView || s.Revision != 120 || len(put) != 0 || p.Outcome != seat.PipelineOutcomeRunning { @@ -296,6 +327,9 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { if want := []string{seat.EventWaitHeld + " build revision view a", seat.EventWaitEnded + " build revision view a"}; !slices.Equal(waits, want) { t.Errorf("waits said %q, want %q", waits, want) } + if !slices.Equal(hows, []string{"", "ran"}) { + t.Errorf("the waits' hows %q, want the held wait with none and its end ran (H-A-599)", hows) + } // H-A-599, H-A-738 (2): each carries the runner's stalled-bound and the time the step was held; none outlives the hold. for _, w := range waitBodies { if w.Bound != "1m0s" || w.ClockFrom == nil || !w.ClockFrom.Equal(t0) { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go b/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go index f707ebbf5..26e81a0be 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go @@ -50,21 +50,45 @@ func (v Verbs) Start(caller string, in seat.StartInput) (seat.StartAnswer, error if len(absent) > 0 { return seat.StartAnswer{}, fmt.Errorf("the head of %s (revision %d) holds no entry of %s: nothing was started", in.Branch, half.Revision, strings.Join(absent, ", ")) } - key := Key(in.Branch, keyRevision(Begin{Revision: half.Revision, Source: half.Source})) - held, err := s.Store.Keys(key) + key := headKey(in.Branch, half) + // A module whose own step failed in a pipeline older than the head reopens that pipeline as rerun does, never joins the head's + // (design 47 H2 H-A-643, H-A-594 (3)); the call is one hand act. + older, movers, err := v.ownFailedPipelines(in.Branch, key, movers, half.Entries) if err != nil { - return seat.StartAnswer{}, fmt.Errorf("the pipeline %s is not looked for: nothing was started: %w", key, err) + return seat.StartAnswer{}, err } - var head seat.Pipeline - if len(held) > 0 { - if head, _, err = s.Store.Get(key); err != nil { - return seat.StartAnswer{}, fmt.Errorf("the pipeline %s is not read: nothing was started: %w", key, err) + if len(older) > 0 { + if err := v.record(seat.VerbStart, fmt.Sprintf("started %s at the head of %s by hand", strings.Join(append(moduleNames(movers), olderModules(older)...), ", "), in.Branch), in.Why); err != nil { + return seat.StartAnswer{}, err } + for _, o := range older { + if err := v.reopenGroup(caller, o.from, o.group, nil, o.entries, in.Why); err != nil { + return seat.StartAnswer{}, err + } + s.markCarriedKeys(o.from, o.group, o.from.Pipeline) + } + w := v + w.noRecord = true + if len(movers) == 0 { + return seat.StartAnswer{Pipeline: older[0].from.Pipeline}, nil + } + return w.startAtHead(caller, in, half, key, movers) + } + return v.startAtHead(caller, in, half, key, movers) +} + +// startAtHead is Start's rule for the modules no older pipeline of its own takes: the head's pipeline `key` joins them while it +// waits or runs, or is started with them, or is reopened once it has ended. +func (v Verbs) startAtHead(caller string, in seat.StartInput, half Half, key string, movers []seat.Mover) (seat.StartAnswer, error) { + s := v.Starter + head, held, err := s.head(key) + if err != nil { + return seat.StartAnswer{}, fmt.Errorf("the pipeline %s is not read: nothing was started: %w", key, err) } names := moduleNames(movers) what := fmt.Sprintf("started %s at the head of %s by hand", strings.Join(names, ", "), in.Branch) switch { - case len(held) == 0: + case !held: if err := v.record(seat.VerbStart, what, in.Why); err != nil { return seat.StartAnswer{}, err } @@ -122,6 +146,83 @@ func (v Verbs) Start(caller string, in seat.StartInput) (seat.StartAnswer, error return seat.StartAnswer{Pipeline: key}, nil } +// ownPipeline is an older pipeline a started module's own step failed in, and the group its reopening puts. +type ownPipeline struct { + from seat.Pipeline + group []string + entries map[string]catalog.CatalogEntry +} + +func olderModules(o []ownPipeline) []string { + var out []string + for _, p := range o { + out = appendNew(out, p.group...) + } + return out +} + +// ownFailedPipelines splits movers: those whose own required step failed in the newest pipeline of the branch other than the +// head's `key` that moves them, which ended (design 47 H2 H-A-643), with the closed group each such pipeline reopens for, and the movers left. +func (v Verbs) ownFailedPipelines(branch, key string, movers []seat.Mover, headEntries map[string]catalog.CatalogEntry) ([]ownPipeline, []seat.Mover, error) { + s := v.Starter + pkeys, err := branchKeys(s.Store, branch) + if err != nil { + return nil, nil, fmt.Errorf("the pipelines of %s are not listed: nothing was started: %w", branch, err) + } + head, held, err := s.head(key) + if err != nil { + return nil, nil, fmt.Errorf("the pipeline %s is not read: nothing was started: %w", key, err) + } + var out []ownPipeline + var rest []seat.Mover + for _, m := range movers { + var best seat.Pipeline + found := false + if !held || !Moves(head, m.Module) { + for _, k := range pkeys { + if k == key { + continue + } + p, _, err := s.Store.Get(k) + if err != nil || p.Run != "" || p.Branch != branch || !Moves(p, m.Module) || slices.Contains(p.Superseded, m.Module) { + continue + } + if !found || p.Revision > best.Revision { + best, found = p, true + } + } + // Only the newest pipeline that moves the module counts: a newer one that passed it leaves the failure behind. + found = found && best.Ended != nil && len(failedSteps(best, m.Module)) > 0 + // H-A-761: it reopens only at the fingerprint the head's entry holds; otherwise its key is dropped and said. + if bm, _ := MoverOf(best, m.Module); found && bm.Fingerprint != m.Fingerprint { + if k := UnfinishedKey(branch, m.Module); s.Unfinished != nil { + if _, ok, _ := s.Unfinished.Entry(k); ok { + s.Unfinished.dropMoved(k, m.Module, bm.Fingerprint, fmt.Sprintf("%s moved it at %s (revision %d); the head's revision of %s holds it at %s (H-A-761)", best.Pipeline, bm.Fingerprint, best.Revision, branch, m.Fingerprint)) + } + } + found = false + } + } + if !found { + rest = append(rest, m) + continue + } + at := slices.IndexFunc(out, func(o ownPipeline) bool { return o.from.Pipeline == best.Pipeline }) + if at < 0 { + entries := headEntries + if s.Revision != nil { + if h, err := s.Revision(branch, best.Revision); err == nil && h.Entries != nil { + entries = h.Entries + } + } + out = append(out, ownPipeline{from: best, entries: entries}) + at = len(out) - 1 + } + out[at].group = appendNew(out[at].group, v.closedGroup(best, m.Module, out[at].entries)...) + } + return out, rest, nil +} + // allPassed says whether module has required steps in p and every one passed, was carried or had nothing to run: the pipeline // delivered it. func allPassed(p seat.Pipeline, module string) bool { @@ -295,22 +396,47 @@ func (v Verbs) planUnfinished(key string) (handPlan, error) { if err != nil || !Moves(from, module) { return handPlan{}, fmt.Errorf("its pipeline %s is not read or moves %s no more", e.Pipeline, module) } - var half Half - switch { - case s.Revision != nil: - if half, err = s.Revision(branch, e.Revision); err != nil { - return handPlan{}, fmt.Errorf("the revision %d of %s is not read: %w", e.Revision, branch, err) - } - case v.View != nil: - var ok bool - if half, ok = v.View(branch); !ok || half.Revision != e.Revision { - return handPlan{}, fmt.Errorf("the revision %d of %s is not held", e.Revision, branch) - } - default: + if s.Revision == nil && v.View == nil { return handPlan{}, errors.New("the runner reads no catalog revision") } - if entry, ok := half.Entries[module]; !ok || entry.Fp != e.Fingerprint || half.Source <= 0 { - return handPlan{}, fmt.Errorf("the revision %d of %s holds %s at %q, not its unfinished fingerprint %s", e.Revision, branch, module, entry.Fp, e.Fingerprint) + // The entry is read at its kept revision, else at the head's when the entry there has the same fingerprint (design 47 H2 H-A-608). + readAt := func(rev int64) (Half, error) { + if s.Revision != nil { + h, err := s.Revision(branch, rev) + if err != nil { + return Half{}, fmt.Errorf("the revision %d of %s is not read: %w", rev, branch, err) + } + return h, nil + } + if h, ok := v.View(branch); ok && h.Revision == rev { + return h, nil + } + return Half{}, fmt.Errorf("the revision %d of %s is not held", rev, branch) + } + kept := s.Unfinished.keptRevision(e, module) + half, rerr := readAt(kept) + entry, has := half.Entries[module] + if rerr != nil || !has || entry.Fp != e.Fingerprint || half.Source <= 0 { + looked := fmt.Sprintf("its kept revision %d holds it at %q", kept, entry.Fp) + if rerr != nil { + looked = rerr.Error() + } + head, hok := Half{}, false + if v.View != nil { + head, hok = v.View(branch) + } + he, hhas := head.Entries[module] + if !hok || !hhas || he.Fp != e.Fingerprint || head.Source <= 0 { + return handPlan{}, fmt.Errorf("%s at fingerprint %s is read at neither revision: %s; the head's revision %d of %s holds it at %q", module, e.Fingerprint, looked, head.Revision, branch, he.Fp) + } + half = head + } + // H-A-761: the key goes on only when the head's revision holds its module at the key's fingerprint; otherwise it is dropped and said. + if head, ok := v.View(branch); !ok || head.Entries[module].Fp != e.Fingerprint { + he := head.Entries[module] + why := fmt.Sprintf("the head's revision %d of %s holds it at %q, not at the key's %q; its entry was read at revision %d", head.Revision, branch, he.Fp, e.Fingerprint, kept) + s.Unfinished.dropMoved(key, module, e.Fingerprint, why) + return handPlan{}, fmt.Errorf("%s is no longer unfinished at fingerprint %s: %s", module, e.Fingerprint, why) } group := v.closedGroup(from, module, half.Entries) plan := handPlan{from: from, group: group, entries: half.Entries} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/repin.go b/modules/mesh-delivery-pipeline/internal/pipeline/repin.go index 75f28495e..af8f9a0b6 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/repin.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/repin.go @@ -3,6 +3,7 @@ package pipeline import ( "errors" "fmt" + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" "slices" "strings" "time" @@ -70,7 +71,7 @@ func (s *Starter) keepIn(key string, half Half, movers []seat.Mover) []seat.Move revisions := map[string]int64{} olds := slices.Clone(p.Movers) // the superseded steps are said at the fingerprint they ran for var moved, unregistered []string - var ended []seat.StepResult + var ended, held []seat.StepResult var leave, drop []seat.StepResult var asks []Asked var notAsked []int @@ -93,6 +94,7 @@ func (s *Starter) keepIn(key string, half Half, movers []seat.Mover) []seat.Move continue } live := open(st) || st.Outcome == seat.StepResultOutcomeWaiting + held = append(held, heldOf(seat.Pipeline{Steps: []seat.StepResult{st}})...) // its wait ends with it (H-A-599) l, d := supersedeStep(&p, &st, why, now) if live { leave, drop = append(leave, l...), append(drop, d...) @@ -134,6 +136,14 @@ func (s *Starter) keepIn(key string, half Half, movers []seat.Mover) []seat.Move s.logf("%s keeps the movers revision %d of its own source %d re-pinned, %s: %d steps ended superseded, %d asked again (H-A-283, H-A-284)", key, half.Revision, half.Source, strings.Join(moved, ", "), len(ended), len(asks)) s.sayRePinned(p, kept, revisions, half.Revision) + for _, st := range held { + if s.Say == nil { + break + } + if err := s.Say(runnerclient.RevisionSubject(seat.EventWaitEnded, p.Branch, subjectRevision(p)), waitOf(p, &st, now, 0, waitHowSuperseded)); err != nil { + s.logf("wait-ended of %s's %s %s on the revision view is not said: %v", key, st.Module, st.Step, err) + } + } // The re-pin says pipeline-started again with every revision its movers are kept at, so the indexer pins them (design // 47 H2 H-A-496 and its addendum). if keeps { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go index 49232dffa..a80d9d5e4 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go @@ -534,6 +534,52 @@ func TestTakenInStartsOnlyItsEntries(t *testing.T) { if p, _, _ := mem.Get("main.14"); p.Outcome != seat.PipelineOutcomeRunning || p.Ended != nil { t.Errorf("main.14 is %s ended %v, want the cancelled pipeline reopened", p.Outcome, p.Ended) } + // design 47 H2 H-A-608 (AC-P4): a key whose kept revision is gone is read at the head's revision when the fingerprint is the same, + // by the hand verb as by the carry; a key whose kept revision is still read is read there, beyond the take-in's revision. + c, rev, _ = mem.Get("main.14") + c.Outcome, c.Ended = seat.PipelineOutcomeFailed, &end + if _, err := mem.Update("main.14", c, rev); err != nil { + t.Fatal(err) + } + u["main.batched"] = `{"fingerprint":"src2:bb","revision":9,"pipeline":"main.14","outcome":"failed"}` + if a, err = v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{Key: "main.batched", Why: "kept revision gone"}); err != nil || len(a.Placed) != 1 { + t.Fatalf("place-unfinished of a key whose kept revision 9 is gone = %+v (%v), want it read at the head's revision and placed", a, err) + } + u["main.batched"] = `{"fingerprint":"src2:zz","revision":9,"pipeline":"main.14","outcome":"failed"}` + if _, err = v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{Key: "main.batched", Why: "neither"}); err == nil || !strings.Contains(err.Error(), "src2:zz") || !strings.Contains(err.Error(), "revision 9") || !strings.Contains(err.Error(), "revision 14") { + t.Errorf("place-unfinished of a key found at neither revision = %v, want it naming the fingerprint and both revisions", err) + } + // H-A-761: a key whose kept revision still holds it at its fingerprint is refused, dropped and said when the head's revision + // holds the module at another one; the same fingerprint, read at the head, is placed by the row above. + s.Revision = func(_ string, r int64) (Half, error) { + return Half{Revision: r, Source: 5, Entries: map[string]catalog.CatalogEntry{"batched": {Commit: "c0", Fp: "src2:o9"}}}, nil + } + u["main.batched"] = `{"fingerprint":"src2:o9","revision":9,"pipeline":"main.14","outcome":"failed"}` + if _, err = v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{Key: "main.batched", Why: "older fingerprint"}); err == nil || !strings.Contains(err.Error(), "src2:o9") || !strings.Contains(err.Error(), "src2:bb") || !strings.Contains(err.Error(), "revision 9") || !strings.Contains(err.Error(), "revision 14") { + t.Errorf("place-unfinished of a key at an older fingerprint = %v, want it refused naming both fingerprints and the revisions", err) + } + if _, ok := u["main.batched"]; ok { + t.Error("the key at an older fingerprint is kept, want it dropped") + } + s.Revision = nil + var said []string + held := map[int64]map[string]catalog.CatalogEntry{3: {"old": {Commit: "c3", Fp: "src2:o1"}}, 4: {"newer": {Commit: "c2", Fp: "src2:x1"}}} + cu := &Unfinished{Store: memUnfinished{ + "main.old": `{"fingerprint":"src2:o1","revision":3}`, + "main.far": `{"fingerprint":"src2:f1","revision":2}`, + "main.back": `{"fingerprint":"src2:b1","revision":2}`, + // H-A-761: its kept revision 4 still holds newer at src2:x1, the head at src2:x2: the key goes, never put in at x1. + "main.newer": `{"fingerprint":"src2:x1","revision":4}`, + }, Logf: func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, + Entries: func(_ string, r int64) (map[string]catalog.CatalogEntry, bool) { e, ok := held[r]; return e, ok }} + got := cu.Carry("main", 20, map[string]catalog.CatalogEntry{"back": {Commit: "c20", Fp: "src2:b1"}, "old": {Commit: "c20", Fp: "src2:o1"}, "newer": {Commit: "c20", Fp: "src2:x2"}}, nil) + if len(got) != 2 || got[0].Module != "back" || got[0].Commit != "c20" || got[1].Module != "old" || got[1].Commit != "c3" { + t.Errorf("the carry = %+v, want back read at the head's revision (its kept revision 2 gone) and old at its kept revision 3, the head holding it at the same fingerprint, and newer not carried at x1", got) + } + if j := strings.Join(said, "\n"); !strings.Contains(j, "far is no longer unfinished at fingerprint src2:f1") || !strings.Contains(j, "kept revision 2 is gone") || !strings.Contains(j, "head's revision 20") || + !strings.Contains(j, "newer is no longer unfinished at fingerprint src2:x1") || !strings.Contains(j, `holds it at "src2:x2", not at the key's "src2:x1"`) || cu.Store.(memUnfinished)["main.newer"] != "" { + t.Errorf("the journal says %q, want each drop naming its fingerprint and the revisions looked at", said) + } } // R16/AC1 (design 47 H §765, H-A-58, H-A-98): a take-in.taken of the old form, with no call (or no branch or source), is @@ -614,10 +660,19 @@ func TestAPublishIsTakenIntoThePipelineOfItsRevision(t *testing.T) { return nil }} st := memUnfinished{} + // design 47 H2 H-A-594 (1), H-A-759 (AC-P5 head): the head is the newest revision the view holds, its pipeline read by its + // key; with revision 7 in the view and no pipeline at main.7, the older open main.6 is never taken as the head and nothing + // is carried. + viewAt := func(rev int64) func(string) (Half, bool) { + return func(string) (Half, bool) { return Half{Revision: rev, Source: 9, Entries: entries}, true } + } + if c, ok := s.CarryToHead(failed, []seat.Mover{{Module: "free", Fingerprint: "f3"}}, entries, viewAt(7)); ok || c != "" || len(out) != 0 { + t.Fatalf("a carry with revision 7 in the view and no pipeline at main.7 = %q %t (said %d), want none: main.6 is not the head", c, ok, len(out)) + } u := &Unfinished{Store: st, Entries: func(string, int64) (map[string]catalog.CatalogEntry, bool) { return entries, true }, Add: func(from seat.Pipeline, group []seat.Mover) (string, bool) { - return s.CarryToHead(from, group, entries, nil) + return s.CarryToHead(from, group, entries, viewAt(6)) }} u.Ended(failed) if len(out) != 1 || out[0].ev.Module != "free" || out[0].ev.From != "main.5" || out[0].ev.Pipeline != "main.6" || !strings.HasSuffix(out[0].subject, ".main.6") { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/steps.go b/modules/mesh-delivery-pipeline/internal/pipeline/steps.go index 99e2a56e2..c3b172bcf 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/steps.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/steps.go @@ -164,6 +164,9 @@ type Hearer struct { Where func(ask string) (string, *oc.Warrant, error) Logf func(string, ...any) Now func() time.Time + // KeptRevision says whether the catalog still keeps a branch's revision, as Verbs.RevisionHeld does: nil when it does, an error + // wrapping ErrRevisionGone when it answers it gone (H-A-599); nil reads none and leaves a held step waiting. + KeptRevision func(branch string, revision int64) error // 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 @@ -446,6 +449,7 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s // (H-A-508, H-A-223): its other open steps end superseded, it is kept in the pipeline's superseded, and the pipeline // is judged by its other movers alone; never a failure. var leave, drop []seat.StepResult + heldBefore := heldOf(p) left := s.Step == seat.StepResultStepBuild && s.Outcome == seat.StepResultOutcomeSuperseded if left { why := "superseded: its build was superseded and its mover left for the newer revision's pipeline (H-A-508): " + s.Why @@ -521,6 +525,7 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s ev.Pipeline, s.Module, len(readers), s.Why) h.leaveSteps(ev.Pipeline, leave, drop, "the mover %s left "+ev.Pipeline+" for the newer revision's pipeline", "superseded: its build was superseded (H-A-508)") } + h.sayHeldEnded(p, heldBefore, allHow(waitHowSuperseded)) // a mover that left takes its held step's wait with it (H-A-599) 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) } @@ -763,20 +768,27 @@ func (h *Hearer) say(event string, p seat.Pipeline, step *seat.StepResult) error 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 - if step.On == seat.WaitOnRevisionView { // a build waiting for the revision that superseded it (H-A-563) - w.On = step.On - w.Bound, w.ClockFrom = boundOf(h.StalledBound), step.HeldAt // timed from its hold by the stalled bound (H-A-599, H-A-736 (1)) - } - } - return h.Say(runnerclient.RevisionSubject(event, p.Branch, subjectRevision(p)), w) + return h.Say(runnerclient.RevisionSubject(event, p.Branch, subjectRevision(p)), waitOf(p, step, at, h.StalledBound, "")) } } +// waitOf is the wait a step of p holds or ends: an approval's on a person, or a build's on the revision view, timed from its +// hold by the stalled bound (H-A-599, H-A-736 (1)); how says its end (ran, released, failed, superseded; H-A-599), empty for a +// wait held. +func waitOf(p seat.Pipeline, step *seat.StepResult, at time.Time, stalled time.Duration, how string) seat.Wait { + 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, How: how, 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 + if step.On == seat.WaitOnRevisionView { // a build waiting for the revision that superseded it (H-A-563) + w.On = step.On + w.Bound, w.ClockFrom = boundOf(stalled), step.HeldAt + } + } + return 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) { @@ -1092,8 +1104,13 @@ func (h *Hearer) endPipeline(p *seat.Pipeline, now time.Time, wr func(seat.Pipel } if wr != nil { for i := range p.Movers { - // A carried or reopened mover says the widens its first pipeline computed and never computes it again (H-A-595). + // A carried or reopened mover says the widens its first pipeline computed and never computes it again (H-A-595): the + // key of the state unfinished keeps them, an empty first one too. if len(p.Movers[i].Widens) == 0 { + if kept, ok := h.keptWidens(*p, p.Movers[i]); ok { + p.Movers[i].Widens = kept + continue + } p.Movers[i].Widens = wr(*p, p.Movers[i].Module) } } @@ -1101,6 +1118,19 @@ func (h *Hearer) endPipeline(p *seat.Pipeline, now time.Time, wr func(seat.Pipel return true } +// keptWidens are the widens of m's first pipeline, kept in m's key of the state unfinished while the key names the fingerprint m +// is at (H-A-595); false when the key holds none for it, so the mover's first pipeline computes them. +func (h *Hearer) keptWidens(p seat.Pipeline, m seat.Mover) ([]seat.Widening, bool) { + if h.Unfinished == nil || h.Unfinished.Store == nil { + return nil, false + } + e, held, err := h.Unfinished.Entry(UnfinishedKey(p.Branch, m.Module)) + if err != nil || !held || e.Fingerprint != m.Fingerprint { + return nil, false + } + return e.Widens, 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 { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go b/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go index de358ce92..5da0060c1 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go @@ -127,6 +127,7 @@ func (h *Hearer) supersedeRunningOne(key string, newer seat.Pipeline) bool { why := "superseded: the newer " + newer.Pipeline + " moved its fingerprint, and carries it (H-A-223)" var ended []int var leave, drop []seat.StepResult + before := heldOf(p) for i := range p.Steps { st := &p.Steps[i] if !slices.Contains(moved, st.Module) || (!open(*st) && st.Outcome != seat.StepResultOutcomeWaiting) { @@ -156,6 +157,7 @@ func (h *Hearer) supersedeRunningOne(key string, newer seat.Pipeline) bool { if len(again) > 0 { h.logf("%s: %s, not asked on a dependency that left, placed again (H-A-361)", key, strings.Join(again, ", ")) } + h.sayHeldEnded(p, before, allHow(waitHowSuperseded)) for _, i := range ended { if err := h.say(seat.EventStepEnded, p, &p.Steps[i]); err != nil { h.logf("step-ended of %s's %s %s, superseded, is not said: %v", key, p.Steps[i].Module, p.Steps[i].Step, err) @@ -376,8 +378,34 @@ func waitsOnRevision(st seat.StepResult, held int64) bool { return st.Outcome == seat.StepResultOutcomeWaiting && st.On == seat.WaitOnRevisionView && st.Revision > 0 && st.Revision <= held } +// goneHeld reads, of each revision p's steps are held on that the view does not hold yet, whether the catalog still keeps it +// (H-A-599): the revisions it answers gone, with its words. A read that fails otherwise is journalled and leaves the wait. +func (h *Hearer) goneHeld(p seat.Pipeline, held int64) map[int64]error { + if h.KeptRevision == nil || p.Outcome != seat.PipelineOutcomeRunning { + return nil + } + gone := map[int64]error{} + read := map[int64]bool{} + for _, st := range heldOf(p) { + if st.Revision <= held || read[st.Revision] { + continue + } + read[st.Revision] = true + if err := h.KeptRevision(p.Branch, st.Revision); errors.Is(err, ErrRevisionGone) { + gone[st.Revision] = err + } else if err != nil { + h.logf("%s: revision %d, which a build of it waits on, is not read from the catalog, so the wait stays: %v", p.Pipeline, st.Revision, err) + } + } + return gone +} + func (h *Hearer) revisionHeldOne(key string, held int64) bool { wr := h.widensReads() // made before the compare-and-set, kept for its retries (H-A-289) + var gone map[int64]error + if p, _, err := h.Store.Get(key); err == nil { + gone = h.goneHeld(p, held) // read before the compare-and-set, never inside its retries + } for { p, rev, err := h.Store.Get(key) if err != nil || p.Outcome != seat.PipelineOutcomeRunning { @@ -391,20 +419,38 @@ func (h *Hearer) revisionHeldOne(key string, held int64) bool { whys[st.Module] = st.Why } } - if len(moved) == 0 { + // A step held on a revision the catalog answers gone ends failed, naming it; its pipeline is judged as at a step's end, + // the mover staying (H-A-599). + var failed []int + for i, st := range p.Steps { + if _, ok := gone[st.Revision]; ok && st.Outcome == seat.StepResultOutcomeWaiting && st.On == seat.WaitOnRevisionView && + !slices.Contains(p.Superseded, st.Module) && !slices.Contains(moved, st.Module) { + failed = append(failed, i) + } + } + if len(moved) == 0 && len(failed) == 0 { return false } now := h.now() var ended []int - var leave, drop, waited []seat.StepResult + var leave, drop []seat.StepResult + before := heldOf(p) // each wait-ended is said as the step was held (H-A-563) + goneWhy := "" + for _, i := range failed { + st := &p.Steps[i] + why := fmt.Sprintf("revision %d gone", st.Revision) + if goneWhy == "" { + goneWhy = why + } + st.Outcome, st.Why, st.Ended, st.On, st.HeldAt = seat.StepResultOutcomeFailed, why+": "+gone[st.Revision].Error(), &now, "", nil + p.Unlogged = append(p.Unlogged, endEntry(p.Pipeline, *st, now)) + ended = append(ended, i) + } for i := range p.Steps { st := &p.Steps[i] if !slices.Contains(moved, st.Module) || (!open(*st) && st.Outcome != seat.StepResultOutcomeWaiting) { continue } - if waitsOnRevision(*st, held) { - waited = append(waited, *st) // its wait-ended is said as it was held (H-A-563) - } why := fmt.Sprintf("superseded: its build was superseded and its mover left for the newer revision's pipeline, revision %d now held (H-A-508, H-A-562): %s", held, whys[st.Module]) st.On, st.Revision, st.HeldAt = "", 0, nil l, d := supersedeStep(&p, st, why, now) @@ -414,6 +460,9 @@ func (h *Hearer) revisionHeldOne(key string, held int64) bool { p.Superseded = append(p.Superseded, moved...) again := takeOutNotAsked(&p) done := h.endPipeline(&p, now, wr) + if done && goneWhy != "" && p.Outcome == seat.PipelineOutcomeFailed { + p.Why = goneWhy + "; " + p.Why // the pipeline ends failed naming the revision gone (H-A-599) + } if _, err := h.Store.Update(key, p, rev); errors.Is(err, ErrChanged) { continue } else if err != nil { @@ -425,11 +474,17 @@ func (h *Hearer) revisionHeldOne(key string, held int64) bool { if len(again) > 0 { h.logf("%s: %s, not asked on a dependency that left, placed again (H-A-361)", key, strings.Join(again, ", ")) } - for i := range waited { - if err := h.say(seat.EventWaitEnded, p, &waited[i]); err != nil { - h.logf("wait-ended of %s's %s %s on the revision view is not said: %v", key, waited[i].Module, waited[i].Step, err) + // The wait of a step the view took in ends ran; one of the mover's that still waited for a newer revision ends with the + // mover's leaving (H-A-599). + h.sayHeldEnded(p, before, func(st seat.StepResult) string { + switch _, isGone := gone[st.Revision]; { + case isGone && !slices.Contains(moved, st.Module): + return waitHowFailed + case waitsOnRevision(st, held): + return waitHowRan } - } + return waitHowSuperseded + }) for _, i := range ended { if err := h.say(seat.EventStepEnded, p, &p.Steps[i]); err != nil { h.logf("step-ended of %s's %s %s, superseded, is not said: %v", key, p.Steps[i].Module, p.Steps[i].Step, err) diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go b/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go index 8746e02d3..2a76610dc 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go @@ -110,6 +110,9 @@ type Unfinished struct { Pipeline func(key string) (seat.Pipeline, bool) Registered func(module string) bool Add func(from seat.Pipeline, group []seat.Mover) (string, bool) + // Kept reads a pipeline's kept-revisions, the revision each re-pinned mover's entry comes from (H-A-285); nil, or a pipeline + // that keeps none, says the revision the key names (H-A-608). + Kept func(pipeline string) map[string]int64 } func (u *Unfinished) logf(format string, args ...any) { @@ -417,13 +420,13 @@ func (u *Unfinished) Carry(branch string, revision int64, entries map[string]cat } if i := slices.IndexFunc(movers, func(m seat.Mover) bool { return m.Module == module }); i >= 0 { if movers[i].Fingerprint != e.Fingerprint { - u.dropMoved(key, module, fmt.Sprintf("revision %d of %s moves it at %s", revision, branch, movers[i].Fingerprint)) + u.dropMoved(key, module, e.Fingerprint, fmt.Sprintf("revision %d of %s, the revision looked at, moves it at %s", revision, branch, movers[i].Fingerprint)) } continue } - entry, ok := entries[module] - if !ok || entry.Fp != e.Fingerprint { - u.dropMoved(key, module, fmt.Sprintf("revision %d of %s holds it at %q", revision, branch, entry.Fp)) + entry, why, ok := u.entryOf(branch, revision, entries, module, e) + if !ok { + u.dropMoved(key, module, e.Fingerprint, why) continue } if by := u.heldBack(branch, module, e); len(by) > 0 && !slices.ContainsFunc(by, func(f string) bool { @@ -438,13 +441,52 @@ func (u *Unfinished) Carry(branch string, revision int64, entries map[string]cat return movers } -// dropMoved deletes the key of an unfinished mover a newer fingerprint moves (§786). -func (u *Unfinished) dropMoved(key, module, why string) { +// keptRevision is the revision the entry of module's key comes from: its kept revision in the pipeline the key names (H-A-285), +// else the revision the key names (design 47 H2 H-A-608). +func (u *Unfinished) keptRevision(e UnfinishedEntry, module string) int64 { + if u.Kept != nil { + if r := u.Kept(e.Pipeline)[module]; r > 0 { + return r + } + } + return e.Revision +} + +// entryOf reads module's entry for the carry (design 47 H2 H-A-608, H-A-761): the module goes on only when the head's revision's +// entry (entries) holds the key's fingerprint, so an older fingerprint is never delivered after a newer one; its contents are +// read at its kept revision when that is still read and holds it at the key's fingerprint, else at the head's. Neither says why, +// naming both fingerprints and each revision looked at. +func (u *Unfinished) entryOf(branch string, head int64, entries map[string]catalog.CatalogEntry, module string, e UnfinishedEntry) (catalog.CatalogEntry, string, bool) { + hentry, ok := entries[module] + if !ok || hentry.Fp != e.Fingerprint { + kept := "" + if k := u.keptRevision(e, module); k > 0 && k != head && u.Entries != nil { + if kents, ok := u.Entries(branch, k); !ok { + kept = fmt.Sprintf("its kept revision %d is gone, ", k) + } else { + kept = fmt.Sprintf("its kept revision %d holds it at %q, ", k, kents[module].Fp) + } + } + return catalog.CatalogEntry{}, fmt.Sprintf("%sthe head's revision %d of %s holds it at %q, not at the key's %q, so a newer revision moved it or its entry is gone (H-A-761)", kept, head, branch, hentry.Fp, e.Fingerprint), false + } + if kept := u.keptRevision(e, module); kept > 0 && kept != head && u.Entries != nil { + if kents, ok := u.Entries(branch, kept); ok { + if entry, ok := kents[module]; ok && entry.Fp == e.Fingerprint { + return entry, "", true + } + } + } + return hentry, "", true +} + +// dropMoved deletes the key of an unfinished mover a newer fingerprint moves, or whose entry no revision looked at holds at its +// fingerprint (§786, H-A-608): one journal line names the fingerprint and the revisions looked at. +func (u *Unfinished) dropMoved(key, module, fingerprint, why string) { if err := u.Store.Delete(key); err != nil { u.logf("the unfinished entry of %s is not deleted: %v", module, err) return } - u.logf("%s is no longer unfinished: %s", module, why) + u.logf("%s is no longer unfinished at fingerprint %s: %s", module, fingerprint, why) } // Entry is one key's entry; false when the state holds none. diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go b/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go index c64e89328..6424a75ab 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go @@ -236,6 +236,7 @@ func (v Verbs) Cancel(caller string, in seat.CancelInput) (seat.CancelAnswer, er now := h.now() // Every ask still open is dropped and every test run read is left once the cancel is written (H-A-506). asked := openAtEnd(p.Steps) + held := heldOf(p) var cancelled []int for i := range p.Steps { s := &p.Steps[i] @@ -253,6 +254,7 @@ func (v Verbs) Cancel(caller string, in seat.CancelInput) (seat.CancelAnswer, er return seat.CancelAnswer{}, fmt.Errorf("pipeline %s cannot be written: %w", in.Pipeline, err) } h.DropOpen(in.Pipeline, asked, "the pipeline "+in.Pipeline+" is cancelled: "+in.Why) + h.sayHeldEnded(p, held, allHow(waitHowSuperseded)) // a held step's wait ends with its pipeline (H-A-599) // Each step the cancel ended is said, with its line (design 47 H2 §784). for _, i := range cancelled { if err := h.say(seat.EventStepEnded, p, &p.Steps[i]); err != nil { @@ -377,10 +379,11 @@ func (v Verbs) rerun(caller string, in seat.RerunInput, reopens bool) (seat.Reru } var ask *Asked var replaced string + var held []seat.StepResult p, _, err := v.change(in.Pipeline, seat.EventStepStarted, func() error { return v.record(seat.VerbRerun, fmt.Sprintf("asked the %s step of %s again", in.Step, in.Pipeline), in.Why) }, func(p *seat.Pipeline, now time.Time) (int, error) { - ask, replaced = nil, "" + ask, replaced, held = nil, "", heldOf(*p) switch p.Outcome { case seat.PipelineOutcomeCancelled, seat.PipelineOutcomeSuperseded: return -1, fmt.Errorf("the pipeline %s is %s: a step of it is not asked again", p.Pipeline, p.Outcome) @@ -426,6 +429,7 @@ func (v Verbs) rerun(caller string, in seat.RerunInput, reopens bool) (seat.Reru return seat.RerunAnswer{}, err } v.sayReopened(p, reopens) + v.Hearer.sayHeldEnded(p, held, allHow(waitHowReleased)) // the rerun of a held step releases its wait (H-A-599) if ask == nil || replaced != ask.ID { unmarkAsk(v.Hearer.Clock, replaced, v.Hearer.logf) // one key per ask, gone once the ask is no longer open (H-A-506 addendum) } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go index 89734ab92..78f48e7d2 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go @@ -229,6 +229,34 @@ func TestAcceptRerunAndCancelWriteByCompareAndSetAndRecordTheirHandAct(t *testin t.Errorf("end-again said %q and recorded %v, want pipeline-ended and its hand act", last, *acts) } + // H-A-599: a build held on the revision view whose step is asked again by rerun ends its wait released, and one whose pipeline + // is cancelled ends it superseded. + var hows []string + say := v.Hearer.Say + v.Hearer.Say = func(subject string, body any) error { + if w, ok := body.(seat.Wait); ok && strings.Contains(subject, seat.EventWaitEnded) { + hows = append(hows, w.Module+" "+w.On+" "+w.How) + } + return say(subject, body) + } + heldAt := time.Unix(100, 0) + held := func(key string) { + store[key] = struct { + p seat.Pipeline + rev uint64 + }{seat.Pipeline{Pipeline: key, Branch: "main", Source: 21, Outcome: seat.PipelineOutcomeRunning, Movers: []seat.Mover{{Module: "app", Commit: "c1", Fingerprint: "src2:aa"}}, + Steps: []seat.StepResult{{Module: "app", Step: seat.StepResultStepBuild, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeWaiting, + On: seat.WaitOnRevisionView, Revision: 9, HeldAt: &heldAt}}}, 1} + } + held("main.21") + if _, err := v.Rerun("operator", seat.RerunInput{Pipeline: "main.21", Step: "build", Why: "again"}); err != nil || !slices.Equal(hows, []string{"app revision view released"}) { + t.Errorf("rerun of a held build = %v, waits ended %q, want its wait ended released", err, hows) + } + held("main.22") + if _, err := v.Cancel("operator", seat.CancelInput{Pipeline: "main.22", Why: "wrong branch"}); err != nil || !slices.Equal(hows, []string{"app revision view released", "app revision view superseded"}) { + t.Errorf("cancel of a pipeline holding a build = %v, waits ended %q, want its wait ended superseded", err, hows) + } + // H-A-101 (1): on a pipeline of two movers a verb names the mover's module; one naming none, or a module the pipeline // does not move, is refused, and the module named picks that mover's step. two, store2, _, _, _, _ := verbsFixture() @@ -576,14 +604,66 @@ func TestStartWithModulesJoinsTheHeadsPipelineOrReopensIt(t *testing.T) { if got, _, _ := store.Get(pkey); got.Outcome != seat.PipelineOutcomeRunning || got.Ended != nil || len(asks.asks) == asked { t.Errorf("%s is %s ended %v, %d asks since: want reopened and its failed step asked again", pkey, got.Outcome, got.Ended, len(asks.asks)-asked) } + // H-A-643 (Q-a): a module whose own step failed in a pipeline older than the head reopens that pipeline and is never added to + // the head: with revision 10 in the view and main.9 no longer moving app, start of app reopens the pipeline whose lint failed + // again, and keys no pipeline at main.10. + nine := store["main.9"] + nine.p.Movers = slices.DeleteFunc(slices.Clone(nine.p.Movers), func(m seat.Mover) bool { return m.Module == "app" }) + nine.p.Outcome, nine.p.Ended = seat.PipelineOutcomePassed, &end + store["main.9"] = nine + p5 = store[pkey].p + for i := range p5.Steps { + if p5.Steps[i].Step == seat.StepResultStepLint { + p5.Steps[i].Outcome, p5.Steps[i].Ended = seat.StepResultOutcomeFailed, &end + } + } + p5.Outcome, p5.Ended = seat.PipelineOutcomeFailed, &end + store[pkey] = struct { + p seat.Pipeline + rev uint64 + }{p5, 3} + revision = 10 + asked = len(asks.asks) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "its lint failed again"}); err != nil || a.Pipeline != pkey { + t.Fatalf("start of app whose step failed in the older %s = %+v, %v; want %s reopened", pkey, a, err, pkey) + } + if got, _, _ := store.Get(pkey); got.Outcome != seat.PipelineOutcomeRunning || len(asks.asks) == asked || made["main.10"] != nil { + t.Errorf("%s is %s, %d asks since, main.10 written %t: want the older pipeline reopened and nothing keyed at the head", pkey, got.Outcome, len(asks.asks)-asked, made["main.10"] != nil) + } for k := range made { if strings.Contains(k, ".again.") { t.Errorf("a start keyed %s", k) } } - if len(*acts) != 5 { + if len(*acts) != 6 { t.Errorf("hand acts %v, want the five starts that did something recorded", *acts) } + // H-A-761: with the head holding app at another fingerprint than the failed pipeline moved it at, start does not reopen that + // pipeline (an older fingerprint is never delivered after a newer one): the key is dropped and said, app goes to the head. + var said761 []string + u761 := memUnfinished{"main.app": `{"fingerprint":"src2:aa","revision":5,"pipeline":"` + pkey + `","outcome":"failed"}`} + v.Starter.Unfinished = &Unfinished{Store: u761, Logf: func(f string, a ...any) { said761 = append(said761, fmt.Sprintf(f, a...)) }} + newer := entries["app"] + newer.Fp = "src2:a2" + entries["app"] = newer + revision = 11 + p5 = store[pkey].p + for i := range p5.Steps { + if p5.Steps[i].Step == seat.StepResultStepLint { + p5.Steps[i].Outcome, p5.Steps[i].Ended = seat.StepResultOutcomeFailed, &end + } + } + p5.Outcome, p5.Ended = seat.PipelineOutcomeFailed, &end + store[pkey] = struct { + p seat.Pipeline + rev uint64 + }{p5, 4} + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "head moved app on"}); err != nil || a.Pipeline != "main.11" { + t.Errorf("start of app moved on at the head = %+v, %v: want it in the head's own pipeline main.11, the older one not reopened", a, err) + } + if len(u761) != 0 || !strings.Contains(strings.Join(said761, "\n"), "src2:aa") || !strings.Contains(strings.Join(said761, "\n"), "src2:a2") { + t.Errorf("the state unfinished = %v, the journal %q: want the key dropped, naming both fingerprints", u761, said761) + } if !IsStepsKey(StepsKey("main.9.again.1", "app")) { t.Error("a mover key of an again pipeline is not read as a mover's steps") } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/waitsended.go b/modules/mesh-delivery-pipeline/internal/pipeline/waitsended.go new file mode 100644 index 000000000..b069c9930 --- /dev/null +++ b/modules/mesh-delivery-pipeline/internal/pipeline/waitsended.go @@ -0,0 +1,63 @@ +package pipeline + +import ( + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" +) + +// The ways a build step's wait on the revision view ends, the `how` of its wait-ended (design 47 H2 H-A-599): the view took the +// revision in (ran), the runner's rerun asked the step again (released), the catalog answered the revision gone (failed), or +// its pipeline ended or was cancelled, or its mover left (superseded). +const ( + waitHowRan = "ran" + waitHowReleased = "released" + waitHowFailed = "failed" + waitHowSuperseded = "superseded" +) + +// heldOf are the steps of p held on the revision view, as they stand: copies, kept before a write changes them so their +// wait-ended is said as they were held (H-A-563). +func heldOf(p seat.Pipeline) []seat.StepResult { + var out []seat.StepResult + for _, st := range p.Steps { + if st.Outcome == seat.StepResultOutcomeWaiting && st.On == seat.WaitOnRevisionView { + out = append(out, st) + } + } + return out +} + +// heldEnded are the steps among before that p, as written, no longer holds on the revision view. +func heldEnded(p seat.Pipeline, before []seat.StepResult) []seat.StepResult { + var out []seat.StepResult + for _, b := range before { + still := false + for _, st := range p.Steps { + if st.Module == b.Module && st.Step == b.Step && st.Artifact == b.Artifact && + st.Outcome == seat.StepResultOutcomeWaiting && st.On == seat.WaitOnRevisionView { + still = true + break + } + } + if !still { + out = append(out, b) + } + } + return out +} + +// sayHeldEnded says wait-ended, with its how, of each step among before that p no longer holds on the revision view (H-A-599): +// how names the end of one step. A wait not said is journalled, never a fault of the write that ended it. +func (h *Hearer) sayHeldEnded(p seat.Pipeline, before []seat.StepResult, how func(seat.StepResult) string) { + for _, st := range heldEnded(p, before) { + w := waitOf(p, &st, h.now(), h.StalledBound, how(st)) + if err := h.Say(runnerclient.RevisionSubject(seat.EventWaitEnded, p.Branch, subjectRevision(p)), w); err != nil { + h.logf("wait-ended of %s's %s %s on the revision view is not said: %v", p.Pipeline, st.Module, st.Step, err) + } + } +} + +// allHow answers how for every step. +func allHow(how string) func(seat.StepResult) string { + return func(seat.StepResult) string { return how } +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/widens.go b/modules/mesh-delivery-pipeline/internal/pipeline/widens.go index 7bf7a4725..30d151caf 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/widens.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/widens.go @@ -106,8 +106,9 @@ func (r *endReads) widens(p seat.Pipeline, module string) []seat.Widening { return could("mesh-catalog", fmt.Sprintf("the candidate's revision %d is not read: %v", p.Revision, err)) } // A change is what its movers alter against the revision's own base, never against a branch's newest (design 47 H2 H-A-582); - // the branch's first take-in has no base and alters nothing against it. - newest := cand + // a revision with no base (the branch's first) is computed against an empty one: it names every widening, all of it new + // (H-A-758). + var newest Half if cand.Base > 0 { if newest, err = r.revision(p.Branch, cand.Base); err != nil { return could("mesh-catalog", fmt.Sprintf("the base revision %d of revision %d is not read: %v", cand.Base, p.Revision, err)) diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go index b04caf628..81f206de8 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go @@ -87,6 +87,23 @@ func TestWidensIsTheCandidateAgainstItsBase(t *testing.T) { t.Errorf("%s: widens %q, want %q", c.name, got, c.want) } } + // H-A-758: a revision with no base is computed against an empty one, so it names every widening its mover holds. + first := &Widener{ + Revision: func(_ string, rev int64) (Half, error) { + if rev != 8 { + t.Errorf("a revision with no base asked revision %d, want only its own 8", rev) + } + return newest, nil + }, + Holder: func(s string) (string, error) { return holders[s], nil }, + } + var got []string + for _, x := range first.Widens(p, "app") { + got = append(got, x.What+" "+x.Name) + } + if want := "serving part build-go;serving part host;serving part indexer;serving part runner;acting rule app node-build-go.check;credential app token"; strings.Join(got, ";") != want { + t.Errorf("a revision with no base: widens %q, want every widening of its movers: %q", got, want) + } } // A pipeline's end keeps each mover's widens in its value, whether or not anything widens (design 47 G §71, A-207; H H-A-51). @@ -107,6 +124,16 @@ func TestAnEndKeepsEachMoversWidens(t *testing.T) { if !h.endPipeline(&c, time.Unix(1, 0), h.widensReads()) || len(c.Movers[0].Widens) != 1 || c.Movers[0].Widens[0].Name != "first" { t.Errorf("a carried mover's widens = %+v, want its first pipeline's", c.Movers[0].Widens) } + // H-A-595 (AC-P6b): a carried mover whose first pipeline's widens were empty keeps them empty, its key of the state unfinished + // holding them; one the key does not hold at its fingerprint is computed. + h.Unfinished = &Unfinished{Store: memUnfinished{"main.app": `{"fingerprint":"src2:aa","revision":3,"pipeline":"main.3","outcome":"failed"}`}} + e := seat.Pipeline{Branch: "main", Outcome: seat.PipelineOutcomeRunning, Movers: []seat.Mover{{Module: "app", Fingerprint: "src2:aa"}, {Module: "lib", Fingerprint: "src2:l1"}, {Module: "tool", Fingerprint: "src2:t1"}}, + Steps: []seat.StepResult{{Module: "app", Step: "build", Outcome: "passed"}, {Module: "lib", Step: "build", Outcome: "passed"}, {Module: "tool", Step: "build", Outcome: "passed"}}} + h.Unfinished.Store.Put("main.tool", []byte(`{"fingerprint":"src2:t0"}`)) + if !h.endPipeline(&e, time.Unix(1, 0), h.widensReads()) || len(e.Movers[0].Widens) != 0 || len(e.Movers[1].Widens) != 1 || len(e.Movers[2].Widens) != 1 { + t.Errorf("the ended movers' widens = %+v, want the carried app's empty and lib's and tool's (its key at another fingerprint) computed", e.Movers) + } + h.Unfinished = nil h.Widens = nil q := seat.Pipeline{Outcome: seat.PipelineOutcomeRunning, Movers: []seat.Mover{{Module: "app"}}, Steps: []seat.StepResult{{Module: "app", Step: "build", Outcome: "passed"}}} if !h.endPipeline(&q, time.Unix(1, 0), h.widensReads()) || len(q.Movers[0].Widens) != 0 {