Merge branch 'feat/47-H2-corrections-d' into feat/47-H2-corrections-b

This commit is contained in:
2026-11-25 19:50:25 +01:00
11 changed files with 401 additions and 30 deletions
@@ -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
@@ -298,6 +298,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
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
@@ -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()
@@ -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 // "<module> <version>": 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)
@@ -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 <delay>
}
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)
@@ -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"
)
@@ -666,6 +667,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
@@ -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:<R>, kept
// under <module>.<fingerprint>.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)
@@ -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, ", "))
}
@@ -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, `<module> <version>`.
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, ": ")) {
@@ -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"
)
@@ -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
}
@@ -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")
@@ -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
}