diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go index a75bbcf42..1c2462905 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go @@ -329,7 +329,7 @@ const ( func main() { reasks := stdio.State(build.ReAsksState) - r := build.StuckReader{Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-builder-tools] "+f+"\n", a...) }, Builds: read(stdio.State("builds")), ReAsks: read(reasks), StepsOf: stepsOfHolder(func(seat string) (string, error) { return seatlist.HolderOf(stdio.Ask, seat) }, func(name string) build.StateRead { return read(stdio.State(name)) }), + r := build.StuckReader{Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-builder-tools] "+f+"\n", a...) }, Builds: read(stdio.State("builds")), ReAsks: read(reasks), Waits: read(stdio.State(build.WaitsState)), StepsOf: stepsOfHolder(func(seat string) (string, error) { return seatlist.HolderOf(stdio.Ask, seat) }, func(name string) build.StateRead { return read(stdio.State(name)) }), Hearing: read(stdio.State(buildrun.HearingState))} put := func(key string, value []byte) error { _, err := reasks.Put(key, json.RawMessage(value)) @@ -400,7 +400,7 @@ func main() { tools = append(tools, reservedTools(rr, buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...) as := stdio.State(versions.ActedState) tools = append(tools, publishActTools(buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...) - tools = append(tools, republishTools(publishQueueVia(stdio.Ask), readerOf(as), readerOf(reasks), buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...) + tools = append(tools, republishTools(publishQueueVia(stdio.Ask), readerOf(as), buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...) ws := stdio.State(build.WaitsState) wr := versions.Reader{Keys: ws.Keys, Get: func(key string) (json.RawMessage, bool, error) { e, err := ws.Get(key) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish.go index d22e0e513..362b92762 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish.go @@ -114,7 +114,7 @@ func publishActTools(ask queueAsker, now func() time.Time, acts meshhandactsclie // republishTools are builder_publish_again and builder_publish_queue (design 47 G §588). The publish again is a hand act: // it is recorded in the hand-act log first, then written to reasks for the builder, which owns the queue, to answer // with the versions it queued. -func republishTools(queue func(module, version string) (meshbuilds.PublishQueueAnswer, error), acted, reasks versions.Reader, ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool { +func republishTools(queue func(module, version string) (meshbuilds.PublishQueueAnswer, error), acted versions.Reader, ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool { str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) } return []stdio.Tool{ {Name: versions.PublishAgainTool, Description: versions.PublishAgainDescription, @@ -153,7 +153,7 @@ func republishTools(queue func(module, version string) (meshbuilds.PublishQueueA if err != nil { return nil, err } - return versions.AnswerQueue(q, acted, reasks) + return versions.AnswerQueue(q, acted) }}, } } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish_test.go index 03d31d86b..ca3158aad 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/republish_test.go @@ -90,7 +90,7 @@ func TestAStateIsReadInOnePage(t *testing.T) { Queue: []meshbuilds.PublishQueueAnswerQueueItem{{Holder: "oci", Module: "m", Version: "0.1.0", Class: versions.PublishClassStart}}}) } none := versions.Reader{Keys: func() ([]string, error) { return nil, nil }} - tools := republishTools(publishQueueVia(ask), none, none, nil, time.Now, meshhandactsclient.Recorder{}) + tools := republishTools(publishQueueVia(ask), none, nil, time.Now, meshhandactsclient.Recorder{}) raw, err := tools[1].Run(map[string]any{"module": "m"}) a, _ := raw.(versions.Queued) if err != nil || fmt.Sprint(asked) != "[seat:mesh-builds.publish-queue m]" || a.Total != 9000 || len(a.Queue) != 1 || a.Queue[0].Module != "m" || diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reserved.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reserved.go index a690371cd..e37488a42 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reserved.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reserved.go @@ -13,7 +13,7 @@ import ( "mesh-delivery-builder/internal/versions" ) -// reservedTools are builder_reserved, builder_reserved_drop and builder_reserve_done (A-455) (design 47 G section 369), served as tools of the bundle. The drop is a hand act: it is recorded in the hand-act log first, then written to +// reservedTools are builder_reserved and builder_reserved_drop (design 47 G section 369), served as tools of the bundle. The drop is a hand act: it is recorded in the hand-act log first, then written to // reasks for the builder, which owns the reservations, to answer. // // The seat's verb reserved is the builder's process's (design 47 G A-115, A-127), not the bundle's. @@ -25,16 +25,17 @@ func reservedTools(rr versions.Reader, ask queueAsker, now func() time.Time, act "module": map[string]any{"type": "string", "description": "only this module's reservations"}}}, Run: func(args map[string]any) (any, error) { return versions.AnswerReserved(rr, str(args, "module")) }}, {Name: versions.ReservedDropTool, Description: versions.ReservedDropDescription, - Input: map[string]any{"type": "object", "required": []string{"module", "series", "why"}, "properties": map[string]any{ - "module": map[string]any{"type": "string", "description": "the module"}, - "series": map[string]any{"type": "string", "description": "its MAJOR.MINOR"}, - "why": map[string]any{"type": "string", "description": "why, in plain words"}}}, + Input: map[string]any{"type": "object", "required": []string{"module", "series", "version", "why"}, "properties": map[string]any{ + "module": map[string]any{"type": "string", "description": "the module"}, + "series": map[string]any{"type": "string", "description": "its MAJOR.MINOR"}, + "version": map[string]any{"type": "string", "description": "the MAJOR.MINOR.PATCH the reservation stands at, as builder_reserved shows it: a newer one is never dropped"}, + "why": map[string]any{"type": "string", "description": "why, in plain words"}}}, Run: func(args map[string]any) (any, error) { - key, value, err := build.NewReservedDrop(str(args, "module"), str(args, "series"), str(args, "why"), stdio.CallerOf(args), now()) + key, value, err := build.NewReservedDrop(str(args, "module"), str(args, "series"), str(args, "version"), str(args, "why"), stdio.CallerOf(args), now()) if err != nil { return nil, err } - if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("dropped the reservation of %s %s by hand", str(args, "module"), str(args, "series")), + if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("dropped the reservation of %s %s by hand", str(args, "module"), str(args, "version")), Why: str(args, "why"), Cause: versions.ReservedDropTool, Verb: "reserved-drop"}); err != nil { return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was dropped: %w", err) } @@ -51,32 +52,5 @@ func reservedTools(rr versions.Reader, ask queueAsker, now func() time.Time, act } return map[string]any{"key": key, "answer": a.Answer}, nil }}, - {Name: versions.ReserveDoneTool, Description: versions.ReserveDoneDescription, - Input: map[string]any{"type": "object", "required": []string{"module", "fp", "why"}, "properties": map[string]any{ - "module": map[string]any{"type": "string", "description": "the module"}, - "fp": map[string]any{"type": "string", "description": "the fingerprint of its done trunk build"}, - "why": map[string]any{"type": "string", "description": "why, in plain words"}}}, - Run: func(args map[string]any) (any, error) { - key, value, err := build.NewReserveDone(str(args, "module"), str(args, "fp"), str(args, "why"), stdio.CallerOf(args), now()) - if err != nil { - return nil, err - } - if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("reserved a version for the done build of %s at %s by hand", str(args, "module"), str(args, "fp")), - Why: str(args, "why"), Cause: versions.ReserveDoneTool, Verb: "reserve-done"}); err != nil { - return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was reserved: %w", err) - } - raw, err := ask(key, value) - if err != nil { - return nil, err - } - a, err := build.DecodeReAsk(raw) - if err != nil { - return nil, err - } - if a.Refused { - return nil, errors.New(a.Answer) - } - return map[string]any{"key": key, "answer": a.Answer}, nil - }}, } } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits.go index 2185b9d7f..20ac75e99 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits.go @@ -23,7 +23,7 @@ func waitsTools(rr versions.Reader, ask queueAsker, now func() time.Time, acts m return []stdio.Tool{ {Name: build.WaitsTool, Description: "The builder's toolchain waits: each entry held because its fingerprint names a toolchain version of its language other than the " + - "agreed one, with its module, fingerprint, what it waits on (toolchain:@) and since when. It ends when the agreed toolchain " + + "agreed one, and each build waiting for a package's blank pin (package:, with its publisher, the catalog revision it holds and until when), with its module, fingerprint, what it waits on (toolchain:@) and since when. It ends when the agreed toolchain " + "names that version (ran) or when " + build.ReleaseTool + " builds it with the running build module (released). Read-only.", Input: map[string]any{"type": "object", "properties": map[string]any{}}, Run: func(map[string]any) (any, error) { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits_test.go index a65a854fa..e782acf23 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/waits_test.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "errors" "strings" "testing" "time" @@ -45,56 +44,3 @@ func TestWaitsToolsListTheWaitsAndReleaseAfterTheHandAct(t *testing.T) { t.Fatalf("release: %v, %d recorded, asked %+v", err, recorded, asked) } } - -// Design 47 G A-455: builder_reserve_done records the hand act first and only then asks the builder through reasks; the builder's -// answer (the version and its queued publish) is the tool's answer, its refusal the tool's error, and an act that was not -// recorded asks nothing. -func TestReserveDoneRecordsTheHandActFirstAndAnswersTheBuilders(t *testing.T) { - var order []string - var asked []build.ReAsk - reply := func(refuse bool) func(string, []byte) (json.RawMessage, error) { - return func(key string, value []byte) (json.RawMessage, error) { - order = append(order, "asked") - a, _ := build.DecodeReAsk(value) - asked = append(asked, a) - a.Answered, a.Answer, a.Refused = time.Now(), "reserved 0.1.13 for node-tools and queued 1 versions to publish: node-tools@0.1.13", refuse - if refuse { - a.Answer = "the build key is not done" - } - return json.Marshal(a) - } - } - record := func(fail bool) meshhandactsclient.Recorder { - return meshhandactsclient.Recorder{Ask: func(string, any) (json.RawMessage, error) { - order = append(order, "recorded") - if fail { - return nil, errors.New("no responders") - } - return json.RawMessage(`{}`), nil - }} - } - run := func(ask func(string, []byte) (json.RawMessage, error), acts meshhandactsclient.Recorder, args map[string]any) (any, error) { - for _, tl := range reservedTools(versions.Reader{}, ask, time.Now, acts) { - if tl.Name == versions.ReserveDoneTool { - return tl.Run(args) - } - } - t.Fatal("the bundle serves no builder_reserve_done") - return nil, nil - } - args := map[string]any{"module": "node-tools", "fp": "src2:7df8", "why": "its build ended done with no version"} - out, err := run(reply(false), record(false), args) - if err != nil || len(order) != 2 || order[0] != "recorded" || order[1] != "asked" || asked[0].Mode != build.ModeReserveDone || asked[0].Name != "node-tools" || asked[0].FP != "src2:7df8" { - t.Fatalf("answer %v, %v; order %v, asked %+v", out, err, order, asked) - } - if ans := out.(map[string]any)["answer"].(string); !strings.Contains(ans, "reserved 0.1.13") || !strings.Contains(ans, "queued 1 versions") { - t.Errorf("the answer %q names no version and queued publish", ans) - } - if _, err := run(reply(true), record(false), args); err == nil || !strings.Contains(err.Error(), "not done") { - t.Errorf("the builder's refusal is not the tool's error: %v", err) - } - order = nil - if _, err := run(reply(false), record(true), args); err == nil || len(order) != 1 || order[0] != "recorded" { - t.Errorf("an unrecorded act was asked of the builder: %v, %v", err, order) - } -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/acted_integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/acted_integration_test.go new file mode 100644 index 000000000..d3bfdbd1a --- /dev/null +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/acted_integration_test.go @@ -0,0 +1,38 @@ +//go:build integration + +package main + +import ( + "errors" + "testing" + "time" + + "github.com/nats-io/nats.go/jetstream" + + "mesh-delivery-builder/internal/versions" +) + +// Design 47 H2 H-A-720 (1), H-A-741: a mark is updated by one publish carrying its lifetime and the expected last sequence of its +// key: the update at the right revision succeeds and the key keeps its lifetime; one at a stale revision is a conflict. +func TestAMarkIsUpdatedWithItsLifetimeInOnePublish(t *testing.T) { + b := startBed(t) + kv, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: "acted-test", LimitMarkerTTL: time.Minute}) + if err != nil { + t.Fatal(err) + } + key := versions.ActedKey("retake:x") + rev, err := kv.Create(b.ctx, key, []byte("1"), jetstream.KeyTTL(time.Hour)) + if err != nil { + t.Fatal(err) + } + next, err := updateWithLifetime(b.ctx, b.js, "acted-test", key, []byte("2"), rev, 2*time.Hour) + if err != nil || next <= rev { + t.Fatalf("update at the key's revision: %d, %v", next, err) + } + if e, err := kv.Get(b.ctx, key); err != nil || string(e.Value()) != "2" || e.Revision() != next { + t.Fatalf("the key holds %v, %v after the update", e, err) + } + if _, err := updateWithLifetime(b.ctx, b.js, "acted-test", key, []byte("3"), rev, time.Hour); !errors.Is(err, versions.ErrConflict) { + t.Fatalf("update at a stale revision: %v, want a conflict", err) + } +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/consumers.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/consumers.go index 3d21bc606..e13cced52 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/consumers.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/consumers.go @@ -14,6 +14,7 @@ import ( // handlers is where a part of the builder registers its handler of the events it hears: the event hub, or agedHub over it. type handlers interface { Handle(pattern string, handle func(jetstream.Msg)) error + HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error } // ledgers are the builder's durable consumers' ledgers, one per consumer as a message's metadata names it (the events consumer @@ -56,7 +57,16 @@ type agedHub struct { } func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error { - return a.hub.Handle(pattern, func(m jetstream.Msg) { + return a.hub.Handle(pattern, a.aged(handle)) +} + +// HandleByKey registers handle held by key, each message noted as Handle's are. +func (a agedHub) HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error { + return a.hub.HandleByKey(pattern, key, a.aged(handle)) +} + +func (a agedHub) aged(handle func(jetstream.Msg)) func(jetstream.Msg) { + return func(m jetstream.Msg) { led := a.ledgers.of(m) if led == nil { handle(m) @@ -64,7 +74,7 @@ func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error { } led.Delivered(m) handle(&agedMsg{Msg: m, ledger: led}) - }) + } } // agedMsg is a message whose acknowledgement or end is noted applied on its consumer's ledger, once. diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/eventtake.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/eventtake.go index 84daae11e..a49ff7ad9 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/eventtake.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/eventtake.go @@ -3,12 +3,12 @@ package main import ( "encoding/json" "errors" - "slices" - "sync" + "strings" "time" "github.com/nats-io/nats.go/jetstream" + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" stdio "git.novox.be/novox/mesh-sdk/go" @@ -60,78 +60,29 @@ func takeEvent(m jetstream.Msg, takers []eventTaker, rest eventTaker, slow time. } } -// eventWorkers hands each event of the builder's durable to a worker of its key (design 47 H2 H-A-514 addenda): the name the -// event carries (a registry seat's outcome's package name, a version-released's module), one shared worker for the events that -// name none. One key's events are handled in the order heard, the keys side by side, so a slow event of one name delays no -// other name's. A worker ends when its queue is empty. The builder holds no timer (ADR 0437 §8), so the events still waiting in -// a queue are said in progress to the bus each time its worker ends a handling, and none waits out the ack wait behind another. -type eventWorkers struct { - handle func(jetstream.Msg) - keyOf func(jetstream.Msg) string - - mu sync.Mutex - queues map[string]*eventQueue -} - -// eventQueue is one key's events not yet handled, the one handled now first. -type eventQueue struct{ msgs []jetstream.Msg } - -// take queues m on its key's worker, starting the worker when none runs. -func (w *eventWorkers) take(m jetstream.Msg) { - key := w.keyOf(m) - w.mu.Lock() - if w.queues == nil { - w.queues = map[string]*eventQueue{} - } - q, running := w.queues[key] - if !running { - q = &eventQueue{} - w.queues[key] = q - } - q.msgs = append(q.msgs, m) - w.mu.Unlock() - if !running { - go w.run(key, q) - } -} - -// run handles key's events in order until its queue is empty, saying those still waiting in progress after each. -func (w *eventWorkers) run(key string, q *eventQueue) { - for { - w.mu.Lock() - if len(q.msgs) == 0 { - delete(w.queues, key) - w.mu.Unlock() - return - } - m := q.msgs[0] - w.mu.Unlock() - w.handle(m) - w.mu.Lock() - q.msgs = q.msgs[1:] - waiting := slices.Clone(q.msgs) - w.mu.Unlock() - for _, m := range waiting { - _ = m.InProgress() - } - } -} - -// eventKey is the worker key of a builder's event (H-A-514 second addendum): a registry seat's outcome's name, a -// version-released's module, else "" (one worker for the events naming none). -func eventKey(m jetstream.Msg) string { - if _, ok := seatEvents[m.Subject()]; ok { +// eventKey is the key the hub holds a builder's event under (design 47 H2 H-A-683 (1), H-A-737 (1)): a registry seat's outcome's +// name, a version-released's module, the node the subject of the seat node-engine's running and manifest-reads-changed names, +// else "" (the events naming none share one key). One key's events are handled one at a time in the order heard, the keys side by +// side, so a slow handling of one node's event holds back no other node's. +func eventKey(subject string, data []byte) string { + if _, ok := seatEvents[subject]; ok { var o versions.Outcome - if json.Unmarshal(m.Data(), &o) == nil { + if json.Unmarshal(data, &o) == nil { return "name " + o.Name } return "" } - if m.Subject() == meshcatalog.SubjectVersionReleased { + if subject == meshcatalog.SubjectVersionReleased { var ev meshcatalog.VersionReleasedEvent - if json.Unmarshal(m.Data(), &ev) == nil { + if json.Unmarshal(data, &ev) == nil { return "module " + ev.Module } + return "" + } + // mesh.seat.node-engine.event.running.. and mesh.seat.node-engine.event.manifest-reads-changed. + if t := strings.Split(subject, "."); len(t) >= 6 && t[2] == "node-engine" && t[3] == "event" && + (t[4] == nodeengine.EventRunning || t[4] == nodeengine.EventManifestReadsChanged) { + return "node " + t[5] } return "" } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go index ebee9999d..b5f98d2ac 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go @@ -19,6 +19,10 @@ import ( // A-29); its `findings-asked` subject is the seat's, from the generated contract (A-17). type heldWriter = views.HeldWriter[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent] +// retiredFindingKinds are kinds no code of the builder raises any more, which its writer clears once at its start (design 47 H2 +// H-A-578 (1), H-A-247 (3)): floor-silent went with the version floor. +var retiredFindingKinds = []views.RetiredKind{{Kind: "floor-silent"}} + // findingWriter is the part of the held writer the builder's findings use; Held answers the findings it holds (design 47 G A-38). type findingWriter interface { Write(ctx context.Context, f mcseat.Finding) error 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 eb446854f..6b189f44f 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 @@ -748,11 +748,26 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7 } } b.awaitSaid(t, "package "+pkg+" has no published version") - goPublished(reserved.Version, pkgDigest) want := "v" + reserved.Version + // Design 47 H2 H-A-707 (3), (4) (B18, whole): the same fingerprint taken in again at a later revision, its entry at a later commit + // naming the version, while the earlier build waits on its blank pin: the build takes that pin, said once, with no published + // heard, and is one build, its key written done once and never failed. + later := b.entry("netcheck", "modules/netcheck", "89abcdef0123456789abcdef0123456789abcdef", fourth, digest, b.manifestOf(t, netcheck), bothToolchains, 0) + later.Packages = map[string]string{pkg: want} + b.catalog.put(t, later) + b.awaitSaid(t, pkg+" takes "+want) if v := b.awaitFP(t, "netcheck", fourth, isState(builds.BuildDone)); v.Packages[pkg] != want { t.Errorf("netcheck built with %v, want %s at %s, its publisher's reservation at the key's origin (H-A-547 (3))", v.Packages, pkg, want) } + goPublished(reserved.Version, pkgDigest) // heard after the build: nothing builds again + if st, err := b.js.Stream(b.ctx, "BUILDER_BUILDS"); err != nil { + t.Fatal(err) + } else if subject := "mesh.stream.mesh-delivery-builder.event." + builds.BuildEndedEventName("netcheck", fourth); true { + info, err := st.Info(b.ctx, jetstream.WithSubjectFilter(subject)) + if err != nil || info.State.Subjects[subject] != 1 { + t.Errorf("netcheck at %s ended %d times (%v), want its one build done, never one failed (H-A-707 (3), (4))", fourth, info.State.Subjects[subject], err) + } + } released, _ := json.Marshal(meshcatalog.VersionReleasedEvent{V: 1, Module: "disk-load", Version: reserved.Version}) msg := nats.NewMsg(meshcatalog.SubjectVersionReleased) msg.Header.Set("x-event-id", "released-disk-load-"+reserved.Version) 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 d4f7a7e95..a5cdbc2c2 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go @@ -99,7 +99,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro // The builder's findings are raised as they happen, so its one finding writer holds them (design 47 G A-29, §689): it // is started once the state is bound, and what is written before is stated at its start. fw, err := views.NewHeldWriter(views.WriterConfig[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent]{ - Module: cred.Module, State: calls.State("findings"), Node: cred.Node, Asked: mcseat.SubjectFindingsAsked, JS: js, Conn: conn, Logf: logger.Printf}) + Module: cred.Module, State: calls.State("findings"), Node: cred.Node, Asked: mcseat.SubjectFindingsAsked, Retired: retiredFindingKinds, JS: js, Conn: conn, Logf: logger.Printf}) if err != nil { return err } @@ -247,6 +247,10 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro b.Reserved = reserved // A take-over of a series' reservation by another fingerprint withdraws the older build (H-A-225). reserved.withdraw = b.Withdraw + reserved.looking = func(module, fp string) bool { + key, err := builds.BuilderBuildKey(module, fp) + return err == nil && b.Looking(key) + } reserved.recordAgain = b.RecordAgain // a done build's digests its end did not record are recorded at the start (H-A-492) // The versions' hand acts (builder_publish_again, builder_reserved_drop) come through reasks, as builder_build_again. acts := versions.Acts{DropReserved: reserved.dropped} @@ -255,13 +259,19 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro actedKV := process.AwaitBucket(ctx, js, conn, own.acted, "no version is published again on an event or by builder_publish_again", logger.Printf) pq := &publishQueue{js: js, logf: logger.Printf, binding: publishesOf(cred.Module)} republish := &versions.Republisher{Reserved: reserved.r, Put: pq.put, - Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk), + Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk, publishUnanswered(ctx, found)), Unreleased: reserved.unreleasedWords, Logf: logger.Printf, Holders: holders, // a registry seat's holder from the seat-holders view, from the start (design 47 G A-416, A-416a) Started: time.Now()} // a build ended from now on is of the live class (H-A-290 (1)) // A number a registry seat already holds is never reserved (H-A-275): read before reserving, through the seats' verb versions. - reserved.r.HeldNumbers = func(ctx context.Context, module, fp string, refs []string) ([]string, error) { - return republish.HeldNumbers(ctx, module, fp, refs, registryVersionsVia(calls.Call)) + reserved.r.HeldRecords = func(ctx context.Context, module, fp string, refs []string) ([]versions.HeldArtifact, error) { + return republish.HeldRecords(ctx, module, fp, refs, registryVersionsVia(calls.Call)) + } + reserved.r.MovedFrom = reserved.movedFrom + republish.Unstored = reserved.unstoredAgain + republish.AsHeld = reserved.sayPublished // an artifact held for this very build is published as held (H-A-738 (1)) + reserved.judge = func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) { + return republish.Held(ctx, v, registryVersionsVia(calls.Call)) } // A done build whose number a registry holds elsewhere is built again at the next free number (H-A-279), on the builder's context. reserved.rebuild = func(_ context.Context, module, fp, why string) error { @@ -279,49 +289,65 @@ 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") } - publishSet, err := publishSettingsOf(getenv) + publishAck, err := numberFile(getenv("MESH_BUILDER_PUBLISH_ACK_FILE"), defaultPublishAckMinutes) if err != nil { return err } - pq.ackWait = publishSet.PauseMax // a sent item unheard is delivered again after the longest pause (H-A-440 (1)) + 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)) + actedDays, err := numberFile(getenv("MESH_BUILDER_ACTED_DAYS_FILE"), versions.DefaultActedDays) + if err != nil { + return err + } + if actedDays > 365 { + return fmt.Errorf("the setting acted-days is %d, at most 365", actedDays) + } releasedKept, err := numberFile(getenv("MESH_BUILDER_RELEASED_KEPT_FILE"), versions.DefaultReleasedKept) if err != nil { return err } reasksKV := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.ReAsksState), "builder_ask_again is not heard; an ask that can no longer be answered is still asked again by itself", logger.Printf) - // A version's publish is the builder's own work until its release is written (design 47 G A-457a): an item of the re-ask state. - items := &publishItems{reasks: reasksKV.KV, set: publishSet, now: time.Now, logf: logger.Printf, + // A version's publish is the builder's own work until its release is written (design 47 G A-457a); a publish dropped by hand is + // kept on its reservation (H-A-746). + items := &publishItems{now: time.Now, logf: logger.Printf, unreleased: republish.Unreleased, + dropMark: func(ctx context.Context, module, version, by, why string) error { + found, err := reserved.r.MarkDropped(ctx, module, version, by, why, time.Now()) + if err == nil && !found { + err = fmt.Errorf("no reservation of %s stands at %s: there is no publish to drop", module, version) + } + return err + }, reserved: func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) { return reserved.r.Of(ctx, module, version) }, - republish: republish.Republish, endedWith: reserved.unreleased, + republish: republish.Republish, // A publish is asked again while the registry's record lacks it (H-A-269 (2), H-A-272; H-A-514 addendum: no backlog count). judge: func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) { return republish.Held(ctx, v, registryVersionsVia(calls.Call)) }, markHeld: reserved.markHeld, moveElsewhere: reserved.movedElsewhere, - allDone: func(ctx context.Context) ([]versions.ReservedVersion, error) { return reserved.r.All(ctx) }, - send: republish.SendQueued, - retired: reserved.r.Retired} // only each module's newest done build is asked at the start (H-A-291 (1)) + send: republish.SendQueued} // A version that never publishes (withdrawn or taken over) has its publish item ended by the queue too (H-A-290 (2)). republish.Ended = items.Ended pq.take = items.take // At the start, a built reservation the catalog holds released is taken in as its version-released would (H-A-484 addendum), // before the publish items of the rest are asked. - reasksKV.Ready(func(jetstream.KeyValue) { + reasksKV.Ready(func(kv jetstream.KeyValue) { + carryDrops(ctx, kv, reserved.r, logger.Printf) // before any event is heard: a drop made before is kept (H-A-749) reserved.releasedAtStart(ctx) - items.AskAllDone(ctx) }) wirePublishItems(reserved, items, awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, releasedKept) acts.Republish = republish.Republish acts.PublishDrop = func(ctx context.Context, module, version, by, why string) (string, error) { return pq.drop(ctx, items, module, version, by, why) } - // builder_reserve_done: a done trunk build that reserved none is given a version, and its publish queued as publish again does. - acts.ReserveDone = reserveDoneAct(b.ReserveDone, republish.Republish, logger.Printf) // The operator is asked once a key's event builds are spent (design 47 G §568): the builder's asker on the seat operator-channel. decided := &decisions{subject: oc.SubjectDecided(cred.Module)} - retakeActed := awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}} + retakeActed := markLifetime{awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, actedDays, js} + actedKV.Ready(func(kv jetstream.KeyValue) { deleteUnknown(ctx, kv, logger.Printf) }) asker := &operatorask.Asker[oc.Warrant]{Module: cred.Module, Call: calls.Call, Record: calls.Ask, Publish: publishVia(ctx, js), Subscribe: decided.hear(logger.Printf), Contract: operatorask.Contract{Seat: oc.Seat, StateAsks: oc.StateAsks}, AskSubject: oc.AcceptSubjectAsk, DecidedSubject: oc.SubjectDecided} @@ -331,6 +357,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro if err := operator.Listen(); err != nil { return fmt.Errorf("hearing the operator's answers: %w", err) } + again := &publishingAgain{a: &versions.Againer{Republisher: republish, Acted: retakeActed, MaxVersions: republishMax, Nodes: branches.SeatHolderNodes(ctx)}} retake := &retaking{rt: &build.Retaker{Builder: b, Acted: retakeActed, Entry: entryVia(calls.Call), Ask: operator.Ask, Logf: logger.Printf}} // What waits on the work queue is pulled, and the old state's items are put on it once (§793). go func() { @@ -469,6 +496,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro takers := []eventTaker{ {"the operator's answer to an ask about a key", decided.heard}, // §568 {"the retake of a key failed on a transport fault", func(m jetstream.Msg) bool { return retake.heard(ctx, m, logger.Printf) }}, // §568 + {"the publish again of reserved versions", func(m jetstream.Msg) bool { return again.heard(ctx, m, logger.Printf) }}, // ADR 0674 §2 {"what a node's engine reads", func(m jetstream.Msg) bool { return reads.heard(m, logger.Printf) }}, // manifest-reads-changed (ADR 0618 §4) {"the toolchains reported", func(m jetstream.Msg) bool { return heardTools.Reported(ctx, m) }}, {"the toolchains running", func(m jetstream.Msg) bool { return heardTools.Running(ctx, m) }}, @@ -476,9 +504,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro {"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }}, } gone := eventTaker{"the artifacts gone", func(m jetstream.Msg) bool { heardGone(ctx, b, m, logger.Printf); return true }} - // Each event goes to a worker of the name it carries, one name's events in order, the names side by side (H-A-514 addenda). - workers := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) }} - events := workers.take + // The hub holds each event under its key (eventKey), one key's events in order, the keys side by side (H-A-683 (1), H-A-737 (1)). + events := func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) } // The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, the indexer's take-in.taken and // manifest-reads-changed and the seat mesh-conditions' condition-cleared: seatEventPatterns); the owners' views events and the // catalog half's catalog-revision and registration-changed and the gate's source-moved are the views reader's (a message has @@ -527,7 +554,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro seatGate.Follow(seatlist.ProcessBus(calls.Call, aged), func() { seatsChanged(ctx); b.SayUnbuildable(ctx) }, logger.Printf) half.holders = func() { seatsChanged(ctx) } for _, pattern := range seatEventPatterns { - if err := aged.Handle(pattern, events); err != nil { + if err := aged.HandleByKey(pattern, eventKey, events); 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 3ab7f6cdc..5caf84658 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 @@ -19,6 +19,7 @@ import ( "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" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry" "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" @@ -46,12 +47,11 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { t.Fatal(err) } // One consumer per holder (H-A-483 and its addenda): the holder's class durables of an earlier release are retired, the item - // one of them held unacknowledged reaches the one consumer; no item is lost; a failed send comes back after its pause, and a - // live item put while it waits is sent before it returns; a dropped item never comes back. + // one of them held unacknowledged reaches the one consumer; no item is lost; a failed send ends its item and is never sent again + // on a timer; a dropped item never comes back. t.Run("one consumer", func(t *testing.T) { - const holder, pause = "paused", 3 * time.Second // the pause is far longer than a send of an item put now + const holder = "paused" bound := testbus.SetupBound(t) - kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} type send struct { module string at time.Time @@ -59,7 +59,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { var mu sync.Mutex published, failed := map[string]bool{}, map[string]bool{} sentCh := make(chan send, 16) - items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: pause, PauseMax: time.Minute, Tries: 5}, + items := &publishItems{dropMark: func(context.Context, string, string, string, string) error { return nil }, now: time.Now, logf: t.Logf, reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) { mu.Lock() @@ -109,22 +109,20 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { } return send{} } - // The two class durables an earlier release made, the live one holding an item given and not acknowledged. - for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} { - if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder) + "-" + class, - FilterSubject: bind.Subject + ".publish." + holder + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Hour}); err != nil { - t.Fatal(err) - } + // The one durable an earlier build made, holding an item given and not acknowledged (H-A-700 (2)). + if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesOneConsumer(holder), + FilterSubject: bind.Subject + ".publish." + holder + ".>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Hour}); err != nil { + t.Fatal(err) } put("given", versions.PublishClassLive) - old, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder)+"-"+versions.PublishClassLive) + old, err := b.js.Consumer(ctx, bind.Stream, publishesOneConsumer(holder)) if err != nil { t.Fatal(err) } if m, err := old.Next(); err != nil { t.Fatal(err) } else if md, _ := m.Metadata(); md.NumDelivered != 1 { - t.Fatalf("the old live durable gave %+v", md) + t.Fatalf("the old durable gave %+v", md) } pq.learn(ctx, holder) stream, err := b.js.Stream(ctx, bind.Stream) @@ -133,38 +131,68 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { } var names []string for n := range stream.ConsumerNames(ctx).Name() { - if strings.HasPrefix(n, publishesConsumer(holder)) { + if strings.HasPrefix(n, publishesOneConsumer(holder)) { names = append(names, n) } } - if !slices.Equal(names, []string{publishesConsumer(holder)}) { - t.Fatalf("the consumers of %s are %v, want only %s: the class durables retired", holder, names, publishesConsumer(holder)) + want := []string{publishesConsumer(holder, versions.PublishClassLive), publishesConsumer(holder, versions.PublishClassStart)} + slices.Sort(names) + slices.Sort(want) + if !slices.Equal(names, want) { + t.Fatalf("the consumers of %s are %v, want %v: the one durable removed", holder, names, want) + } + // H-A-719, H-A-700 (1), H-A-620 (2): each of the two carries the stream's maximum age as its inactive threshold; four live sends + // in flight and one again. + sinfo, err := stream.Info(ctx) + if err != nil { + t.Fatal(err) + } + for class, inflight := range map[string]int{versions.PublishClassLive: 4, versions.PublishClassStart: 1} { + c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder, class)) + if err != nil { + t.Fatal(err) + } + info, err := c.Info(ctx) + if err != nil { + t.Fatal(err) + } + if info.Config.InactiveThreshold != sinfo.Config.MaxAge || sinfo.Config.MaxAge == 0 || info.Config.MaxAckPending != inflight { + t.Fatalf("%s: inactive threshold %s (stream max age %s), %d in flight, want the stream's max age and %d", class, info.Config.InactiveThreshold, sinfo.Config.MaxAge, info.Config.MaxAckPending, inflight) + } } if s := next(); s.module != "given" { t.Fatalf("sent %s first, want the item the old durable held unacknowledged", s.module) } put("fail", versions.PublishClassStart) put("dropme", versions.PublishClassStart) - var firstFail time.Time - for range 2 { - if s := next(); s.module == "fail" { - firstFail = s.at - } + for range 2 { // the first send of each fails: its item ends, the version stays reserved, nothing hands it back after a pause (H-A-606) + next() } - put("live", versions.PublishClassLive) // put while both failed items wait out their pause + put("live", versions.PublishClassLive) if s := next(); s.module != "live" { - t.Fatalf("sent %s, want the live item put while the failed ones wait their pause", s.module) + t.Fatalf("sent %s, want the live item put after the failed ones", s.module) + } + // design 47 H2 H-A-654, H-A-703: the consumer deleted under a running dispatch and made again, the dispatch binds again on the + // bus's created advisory and sends the next item. + if err := b.js.DeleteConsumer(ctx, bind.Stream, publishesConsumer(holder, versions.PublishClassLive)); err != nil { + t.Fatal(err) + } + if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder, versions.PublishClassLive), + FilterSubject: bind.Subject + ".publish." + holder + ".live.>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Minute, + MaxAckPending: 4, MaxDeliver: publishesMaxDeliver}); err != nil { + t.Fatal(err) + } + put("rebound", versions.PublishClassLive) + if s := next(); s.module != "rebound" { + t.Fatalf("sent %s, want the item put after the consumer was made again", s.module) } if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil { t.Fatalf("drop: %v", err) } else { t.Log(answer) } - if s := next(); s.module != "fail" || s.at.Sub(firstFail) < pause { - t.Fatalf("sent %s %s after the failed send, want fail again after its pause %s", s.module, s.at.Sub(firstFail), pause) - } // Every item is acknowledged and the dropped one is gone: nothing is left to come back. - c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder)) + c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder, versions.PublishClassLive)) if err != nil { t.Fatal(err) } @@ -197,12 +225,11 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { }) t.Run("the queue, the move, tags and backlog", func(t *testing.T) { - kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} var mu sync.Mutex var sent []string published := map[string]bool{} // the modules whose publish is heard sentCh := make(chan string, 200) - items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: time.Second, PauseMax: time.Minute, Tries: 5}, + items := &publishItems{dropMark: func(context.Context, string, string, string, string) error { return nil }, now: time.Now, logf: t.Logf, reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) { mu.Lock() @@ -248,7 +275,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { if err := pq.learnAll(ctx); err != nil { t.Fatal(err) } - for range 4 { // the items in flight: at most four held unacknowledged, their publish unheard + for range 1 { // the again items in flight: at most one held unacknowledged, its publish unheard (H-A-620 (2)) select { case <-sentCh: case <-time.After(30 * time.Second): @@ -466,4 +493,435 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) { t.Errorf("the health four minutes in = %+v, want healthy", a) } }) + // Design 47 H2 H-A-613 (4), H-A-620 (3), H-A-593 (5), H-A-588 to H-A-590 (whole, against the bus and a fake registry holder): the + // builder's reserving, its publish items and its work queue as main joins them, the publish a kept call through a process + // connection to a holder on the bus, which answers `versions` with each version's digest and kept fingerprint and `publish` as the + // seats do (held, other bytes, a refusal). A publish met by no responders is called again and passes once the holder answers; a + // refused one is ended and waits for the next running; a build whose two of three artifacts a holder holds for its fingerprint + // stores the third and releases the same number; the same with no fingerprint kept withdraws the number, builds again and releases + // the next number, clearing version-held-elsewhere; other bytes of another build end the item at once. + t.Run("a publish is a kept call and a registry's record is read", func(t *testing.T) { + const holder, fpOf = "goreg", "src2:" + reg := &fakeRegistry{held: map[string]map[string]heldRecord{}, away: true, firstAway: make(chan struct{}, 1)} + reg.listen(t, b.js.Conn()) + conn, err := process.Connect(process.Account{URL: b.srvURL, Module: "mesh-delivery-builder", User: "ctl", Password: "pw"}) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + entries := map[string]meshcatalog.CatalogEntry{} + entryOf := func(module, fp string, arts ...string) { + e := meshcatalog.CatalogEntry{Module: module, Fp: fp} + for _, a := range arts { + e.Artifacts = append(e.Artifacts, meshcatalog.Artifact{Ref: module + ":" + a, Kind: versions.KindPackage, Language: "go", + Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "x.example/" + module + "/" + a}}) + } + entries[fp] = e + } + call := func(string, any) (json.RawMessage, error) { + return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) + } + found := &memFindings{vals: map[string][]byte{}} + rv := newReservations(&lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, call, + func() jetstream.KeyValue { return nil }, + &findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, t.Logf) + rv.say = func(context.Context, meshbuilds.PackagePublished) error { return nil } + pq := &publishQueue{js: b.js, ackWait: time.Minute, logf: t.Logf, binding: publishesOf("mesh-delivery-builder")} + republish := &versions.Republisher{Reserved: rv.r, Put: pq.put, Logf: t.Logf, Started: time.Now(), + Entry: func(_ context.Context, fp string) (meshcatalog.CatalogEntry, error) { + if e, ok := entries[fp]; ok { + return e, nil + } + return meshcatalog.CatalogEntry{}, fmt.Errorf("no entry %s", fp) + }, + Send: sendVia(conn.CallKeptAsk, publishUnanswered(ctx, &findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now})), + Unreleased: rv.unreleasedWords, Holders: func(string) []string { return []string{holder} }} + rv.r.HeldRecords = func(ctx context.Context, module, fp string, refs []string) ([]versions.HeldArtifact, error) { + return republish.HeldRecords(ctx, module, fp, refs, registryVersionsVia(conn.Call)) + } + rv.r.MovedFrom = rv.movedFrom + republish.Unstored = rv.unstoredAgain + republish.AsHeld = rv.sayPublished + rv.judge = func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) { + return republish.Held(ctx, v, registryVersionsVia(conn.Call)) + } + rv.r.HeldElsewhere = func(ctx context.Context, module string, skipped []string) { + rv.heldElsewhere(ctx, module, "the registries hold "+strings.Join(skipped, ", ")+", so the reserve skipped them") + } + items := &publishItems{now: time.Now, logf: t.Logf, unreleased: republish.Unreleased, republish: republish.Republish, + dropMark: func(context.Context, string, string, string, string) error { return nil }, + reserved: func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) { + return rv.r.Of(ctx, module, version) + }, + judge: rv.judge, markHeld: rv.markHeld, moveElsewhere: rv.movedElsewhere, send: republish.SendQueued} + republish.Ended = items.Ended + pq.take = items.take + wirePublishItems(rv, items, &lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, versions.DefaultReleasedKept) + // 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() + var refs []string + digests := map[string]string{} + for _, a := range arts { + refs = append(refs, module+":"+a) + digests[module+":"+a] = "sha256:" + built + a + } + res, err := rv.Reserve(ctx, module, "0.1", refs, versions.Source{Fingerprint: fp}) + if err != nil { + t.Fatal(err) + } + if err := rv.Built(ctx, module, res.Version, digests, nil); err != nil { + t.Fatal(err) + } + return res + } + stored := func(module, version, a string) string { return reg.digest("x.example/"+module+"/"+a, version) } + + // H-A-613 (4): the first call finds no responders; the holder answers, and the publish passes, called again by itself. + entryOf("kept", fpOf+"k", "a") + build("kept", fpOf+"k", "k", "a") + select { + case <-reg.firstAway: + case <-time.After(testbus.SetupBound(t)): + t.Fatal("the publish was not called") + } + reg.answer() + reg.await(t, "x.example/kept/a", "0.1.0") + if got := reg.callsOf("x.example/kept/a"); got < 2 { + t.Errorf("the publish was called %d times, want it met by no responders and called again", got) + } + reg.published(t, rv, "x.example/kept/a", "0.1.0") // its publish heard: the item is acknowledged + reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "kept", "0.1.0") }) + + // H-A-613 (4): an answered refusal ends the send; nothing calls again; the next running puts it again and it passes. + entryOf("refused", fpOf+"r", "a") + reg.refuse("x.example/refused/a", "the cap") + build("refused", fpOf+"r", "r", "a") + reg.await(t, "x.example/refused/a", "0.1.0") + reg.settle(t, b.js, bind.Stream, holder, nil) + if got := reg.callsOf("x.example/refused/a"); got != 1 { + 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) + } + 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") }) + + // 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. + entryOf("three", fpOf+"3", "a", "b", "c") + reg.refuse("x.example/three/c", "the cap") + res := build("three", fpOf+"3", "first-", "a", "b", "c") + reg.await(t, "x.example/three/c", res.Version) + reg.settle(t, b.js, bind.Stream, holder, nil) + for _, a := range []string{"a", "b"} { + if got := stored("three", res.Version, a); got != "sha256:first-"+a { + t.Fatalf("%s of three at %s is held at %q, want what the first run stored", a, res.Version, got) + } + } + reg.refuse("x.example/three/c", "") + republish.Started = time.Now().Add(time.Hour) // the build again is of a run before the next: its put is of the start class + again, err := rv.Reserve(ctx, "three", "0.1", []string{"three:a", "three:b", "three:c"}, versions.Source{Fingerprint: fpOf + "3"}) + if err != nil || again.Version != res.Version { + t.Fatalf("the build of three again reserved %q (%v), want the standing %s", again.Version, err, res.Version) + } + rv.MarkRegistryHeld(ctx, again) // before a build module is asked again (H-A-588 (4)) + if err := rv.Built(ctx, "three", res.Version, map[string]string{"three:c": "sha256:again-c"}, nil); err != nil { + t.Fatal(err) + } + reg.await(t, "x.example/three/c", res.Version) + reg.published(t, rv, "x.example/three/c", res.Version) + reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "three", res.Version) }) + cur, ok, _ := rv.r.Of(ctx, "three", "") + if !ok || cur.Version != res.Version || len(cur.Withdrawn) != 0 || len(cur.Missing()) != 0 || cur.Artifacts["three:a"] != "sha256:first-a" || cur.Artifacts["three:c"] != "sha256:again-c" { + t.Errorf("three stands %+v, want %s with every artifact published, the held digests of a and b and the third stored, and no number withdrawn", cur, res.Version) + } + if got := reg.callsOf("x.example/three/a"); got != 1 { + t.Errorf("a of three was published %d times, want once: the second run answered it from the registry's record", got) + } + + // H-A-593 (5): the same with no fingerprint kept withdraws V, builds again and releases the next number, clearing + // version-held-elsewhere at that release. + entryOf("bare", fpOf+"b", "a", "b", "c") + rv.rebuild = func(ctx context.Context, module, fp, _ string) error { + var refs []string + digests := map[string]string{} + for _, a := range []string{"a", "b", "c"} { + refs = append(refs, module+":"+a) + digests[module+":"+a] = "sha256:next-" + a + } + again, err := rv.Reserve(ctx, module, "0.1", refs, versions.Source{Fingerprint: fp, Rebuild: true}) + if err != nil { + return err + } + return rv.Built(ctx, module, again.Version, digests, nil) + } + first := func() versions.ReservedVersion { + res, err := rv.Reserve(ctx, "bare", "0.1", []string{"bare:a", "bare:b", "bare:c"}, versions.Source{Fingerprint: fpOf + "b"}) + if err != nil { + t.Fatal(err) + } + return res + }() + reg.hold("x.example/bare/a", first.Version, "sha256:old-a", "") + reg.hold("x.example/bare/b", first.Version, "sha256:old-b", "") + if err := rv.Built(ctx, "bare", first.Version, map[string]string{"bare:a": "sha256:mine-a", "bare:b": "sha256:mine-b", "bare:c": "sha256:mine-c"}, nil); err != nil { + t.Fatal(err) + } + reg.await(t, "x.example/bare/c", "0.1.1") + raised := func() bool { + for k := range found.vals { + if strings.Contains(k, versions.VersionHeldElsewhere) && strings.Contains(k, "bare") { + return true + } + } + return false + } + if !raised() { + t.Errorf("no version-held-elsewhere raised about bare: %v", found.vals) + } + if got := reg.digest("x.example/bare/a", first.Version); got != "sha256:old-a" { + t.Errorf("a of bare at %s is held at %q, want what the holder held, never overwritten", first.Version, got) + } + for _, a := range []string{"a", "b", "c"} { + reg.published(t, rv, "x.example/bare/"+a, "0.1.1") + } + if err := rv.release(ctx, meshcatalog.VersionReleasedEvent{V: 1, Module: "bare", Version: "0.1.1"}); err != nil { + t.Fatal(err) + } + if raised() { + t.Errorf("version-held-elsewhere still raised about bare after its release: %v", found.vals) + } + reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "bare", "0.1.1") }) + + // H-A-588, H-A-590: a holder answering other bytes of another build ends the item at once, its tries unspent: it is called once. + entryOf("other", fpOf+"o", "a") + res, err = rv.Reserve(ctx, "other", "0.1", []string{"other:a"}, versions.Source{Fingerprint: fpOf + "o"}) + if err != nil { + t.Fatal(err) + } + reg.hold("x.example/other/a", res.Version, "sha256:theirs", fpOf+"another") + reg.hide("x.example/other/a") // the record is not read, so the item is sent and the holder answers other bytes (H-A-729) + if err := rv.Built(ctx, "other", res.Version, map[string]string{"other:a": "sha256:mine"}, nil); err != nil { + t.Fatal(err) + } + reg.await(t, "x.example/other/a", res.Version) + reg.settle(t, b.js, bind.Stream, holder, nil) + if got := reg.callsOf("x.example/other/a"); got != 1 { + t.Errorf("other bytes of another build: called %d times, want once", got) + } + }) +} + +// lockedReserve is the unit tests' reservations store, safe for the pull goroutines of a queue and a test at once. +type lockedReserve struct { + mu sync.Mutex + *memReserve +} + +func (l *lockedReserve) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.memReserve.Get(ctx, key) +} +func (l *lockedReserve) Create(ctx context.Context, key string, v []byte) (uint64, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.memReserve.Create(ctx, key, v) +} +func (l *lockedReserve) Update(ctx context.Context, key string, v []byte, rev uint64) (uint64, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.memReserve.Update(ctx, key, v, rev) +} +func (l *lockedReserve) KeysOf(ctx context.Context, filter string) ([]string, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.memReserve.KeysOf(ctx, filter) +} +func (l *lockedReserve) Delete(ctx context.Context, key string) error { + l.mu.Lock() + defer l.mu.Unlock() + return l.memReserve.Delete(ctx, key) +} + +// heldRecord is what a fake registry holder keeps of one name at one version: its digest and the fingerprint it keeps (none: ""). +type heldRecord struct{ digest, fingerprint string } + +// fakeRegistry is a registry seat's holder on the bus (the seat go-package-registry): it answers `versions` with each version's digest +// and kept fingerprint, and `publish` as the seats do: stored when it holds nothing there, held for the same digest, other bytes +// (with the kept fingerprint) for another digest, or a refusal in words. While away it answers as the bus does when no one is +// listening (a 503 status without data), which the caller meets as no responders. +type fakeRegistry struct { + mu sync.Mutex + held map[string]map[string]heldRecord // name -> version -> record + away bool + firstAway chan struct{} + refused map[string]string // name -> the words it is refused in + hidden map[string]bool + calls map[string]int + answered chan string // " " of each publish answered, not away +} + +func (r *fakeRegistry) listen(t *testing.T, nc *nats.Conn) { + t.Helper() + r.answered = make(chan string, 64) + sub, err := nc.Subscribe("mesh.seat."+versions.SeatGoPackages+".call.>", func(m *nats.Msg) { + reply := func(result any, words string) { + data, _ := json.Marshal(map[string]any{"result": result, "error": words, "node": "ctl"}) + _ = m.Respond(data) + } + switch strings.Split(m.Subject, ".")[4] { + case "versions": + var in struct{ Name string } + _ = json.Unmarshal(m.Data, &in) + r.mu.Lock() + list := []map[string]string{} + if !r.hidden[in.Name] { + for v, rec := range r.held[in.Name] { + list = append(list, map[string]string{"version": v, "digest": rec.digest, "fingerprint": rec.fingerprint}) + } + } + r.mu.Unlock() + reply(map[string]any{"versions": list}, "") + case "publish": + var in gopackageregistry.PublishInput + _ = json.Unmarshal(m.Data, &in) + r.mu.Lock() + if r.calls == nil { + r.calls = map[string]int{} + } + r.calls[in.Name]++ + if r.away { + r.mu.Unlock() + select { + case r.firstAway <- struct{}{}: + default: + } + _ = m.RespondMsg(&nats.Msg{Header: nats.Header{"Status": {"503"}}}) + return + } + var answer gopackageregistry.PublishAnswer + words := r.refused[in.Name] + if rec, ok := r.held[in.Name][in.Version]; words == "" && ok { + if rec.digest == in.Digest { + answer.Held = true + } else { + answer.OtherBytes = &gopackageregistry.PublishAnswerOtherBytes{Digest: rec.digest, Fingerprint: rec.fingerprint} + } + } else if words == "" { + if r.held[in.Name] == nil { + r.held[in.Name] = map[string]heldRecord{} + } + r.held[in.Name][in.Version] = heldRecord{digest: in.Digest, fingerprint: in.Fingerprint} + answer.Transfer = "t" + } + r.mu.Unlock() + reply(answer, words) + r.answered <- in.Name + " " + in.Version + } + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sub.Unsubscribe() }) +} + +func (r *fakeRegistry) answer() { r.mu.Lock(); r.away = false; r.mu.Unlock() } + +func (r *fakeRegistry) refuse(name, words string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.refused == nil { + r.refused = map[string]string{} + } + if words == "" { + delete(r.refused, name) + return + } + r.refused[name] = words +} + +func (r *fakeRegistry) hide(name string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.hidden == nil { + r.hidden = map[string]bool{} + } + r.hidden[name] = true +} + +func (r *fakeRegistry) hold(name, version, digest, fingerprint string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.held[name] == nil { + r.held[name] = map[string]heldRecord{} + } + r.held[name][version] = heldRecord{digest: digest, fingerprint: fingerprint} +} + +func (r *fakeRegistry) digest(name, version string) string { + r.mu.Lock() + defer r.mu.Unlock() + return r.held[name][version].digest +} + +func (r *fakeRegistry) callsOf(name string) int { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls[name] +} + +// await reads the publishes answered until name's at version, within the level's set-up share. +func (r *fakeRegistry) await(t *testing.T, name, version string) { + t.Helper() + bound := time.After(testbus.SetupBound(t)) + for { + select { + case got := <-r.answered: + if got == name+" "+version { + return + } + case <-bound: + t.Fatalf("no publish of %s %s was answered", name, version) + } + } +} + +// settle waits until the holder's queue holds nothing sent and unacknowledged: 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) + } + for deadline := time.Now().Add(testbus.SetupBound(t)); ; { + if each != nil { + each() + } + info, err := c.Info(context.Background()) + if err != nil { + t.Fatal(err) + } + if info.NumAckPending == 0 && info.NumPending == 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("the queue of %s holds %d unacknowledged and %d pending", holder, info.NumAckPending, info.NumPending) + } + time.Sleep(10 * time.Millisecond) + } +} + +// 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() + rv.published(context.Background(), versions.Outcome{Name: name, Version: version, Digest: r.digest(name, version), Kind: versions.KindPackage, Holder: "go-registry"}, nil) } 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 ba8fbea96..ae7b75c39 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem.go @@ -20,44 +20,22 @@ import ( "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/process" - "mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/versions" ) -// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793): each -// reservation of a done build is a publish item in the builder's re-ask state, asked when the build ends and at the builder's -// start; its try puts the publish on the work queue publishes, and each send counts one try in the item and hands a failed one -// back with a longer pause; the release deletes it; after its tries it ends loudly and stays readable in builder_publish_queue. +// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793, H-A-606): the +// ask at a build's end is the first try, and it puts the publish on the work queue publishes; a publish that is refused or fails stays +// reserved, with version-unreleased naming the holder's words, and is put again only on ADR 0674 §2's events (a registry holder's +// running, a returned of its node: versions.Againer) or by builder_publish_again. No timer, pause or count of tries stands on this path. -// publishSettings are the settings publish-pause, publish-pause-max and publish-tries. -type publishSettings struct { - Pause, PauseMax time.Duration - Tries int -} - -// defaultPublishSettings are the settings' defaults: 30 s, 30 min and 5 tries (H-A-446 (2)). -var defaultPublishSettings = publishSettings{Pause: 30 * time.Second, PauseMax: 30 * time.Minute, Tries: 5} - -// pauseAfter is the pause after the try-th try: the setting doubled per try, up to the maximum. -func (s publishSettings) pauseAfter(try int) time.Duration { - d := s.Pause - for i := 1; i < try && d < s.PauseMax; i++ { - d *= 2 - } - return min(d, s.PauseMax) -} - -// publishItems asks, tries and ends the publish items. +// publishItems asks and takes the publishes of reserved versions. type publishItems struct { - reasks func() jetstream.KeyValue // the re-ask state, nil until it is bound + // dropMark records on a version's reservation that its publish was dropped by hand, by whom and why (design 47 H2 H-A-746); nil + // drops none. + dropMark func(ctx context.Context, module, version, by, why string) error + now func() time.Time reserved func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) republish func(ctx context.Context, module, version string) ([]string, error) - endedWith func(ctx context.Context, v versions.ReservedVersion, why string) // raises the finding version-unreleased - // allDone are the reservations, done or not: those whose build is done are asked at the start (builtOf). - allDone func(ctx context.Context) ([]versions.ReservedVersion, error) - // retired are the done builds a newer reservation or release of the same module supersedes, with why (H-A-291 (1)); nil - // retires none. - retired func(ctx context.Context, all []versions.ReservedVersion) (map[string]string, error) // judge is what the registries' own record says of a version's missing artifacts (H-A-272, H-A-274, H-A-275); nil judges none. judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) // markHeld marks the artifacts the registries hold with the built digest published from their record, as their published heard @@ -66,126 +44,32 @@ type publishItems struct { markHeld func(ctx context.Context, v versions.ReservedVersion, held []versions.HeldArtifact) moveElsewhere func(ctx context.Context, v versions.ReservedVersion, j versions.Judged) error // send sends one item pulled from the work queue (Republisher.SendQueued); nil sends none. - send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate - set publishSettings - now func() time.Time - after func(time.Duration) <-chan time.Time - logf func(string, ...any) + send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate + // 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) mu sync.Mutex held map[string][]heldItem // " ": the items sent, their publish not yet heard } -func (p *publishItems) wait(ctx context.Context, d time.Duration) bool { - if d <= 0 { - return ctx.Err() == nil - } - after := p.after - if after == nil { - after = time.After - } - select { - case <-after(d): - return true - case <-ctx.Done(): - return false - } -} - -// Ask writes the publish item of a version whose build is done, when none stands: its first try is now. +// Ask puts the publish of a version whose build is done on the work queue: its first try, at the build's end (A-473). func (p *publishItems) Ask(ctx context.Context, module, version string) error { - kv := p.reasks() - if kv == nil { - return errors.New("the re-ask state is not on the bus yet") - } - raw, err := json.Marshal(build.ReAsk{V: 1, Why: "the build ended with its version unreleased", By: "the builder", At: p.now().UTC(), Mode: build.ModePublish, Module: module, Version: version, NextTry: p.now().UTC()}) + queued, err := p.republish(ctx, module, version) if err != nil { - return err + return fmt.Errorf("the publish of %s %s is not put on the work queue %s: %w", module, version, versions.PublishesLocal, err) } - if _, err := kv.Create(ctx, versions.PublishItemKey(module, version), raw); err != nil && !errors.Is(err, jetstream.ErrKeyExists) { - return fmt.Errorf("the publish item of %s %s cannot be written: %w", module, version, err) + if len(queued) == 0 { + p.logf("%s %s: the publish is not put on the work queue %s: nothing of it is left to queue", module, version, versions.PublishesLocal) } return nil } -// AskAllDone asks the publish item of every reservation whose build is done and that has no release: at the builder's start, so -// what stood before this change moves too, whatever its artifacts. -func (p *publishItems) AskAllDone(ctx context.Context) { - all, err := p.allDone(ctx) - if err != nil { - p.logf("the reservations of done builds are not asked to publish at the start: %v", err) - return - } - var retired map[string]string - if p.retired != nil { - if retired, err = p.retired(ctx, all); err != nil { - p.logf("the superseded builds are not retired at the start: %v", err) - } - } - for _, v := range builtOf(all) { - if why := retired[v.Module+" "+v.Version]; why != "" { // only each module's newest is asked (H-A-291 (1), H-A-275) - p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why) - p.Done(ctx, v.Module, v.Version) - continue - } - if why := versions.NotStanding(v, true); why != "" { // withdrawn: it never publishes (H-A-290 (2)) - p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why) - p.Done(ctx, v.Module, v.Version) - continue - } - if err := p.Ask(ctx, v.Module, v.Version); err != nil { - p.logf("%v", err) - } - } -} - -// Done deletes a version's publish item and acknowledges its held items: its release is written. +// Done acknowledges a version's held items: its release is written. func (p *publishItems) Done(ctx context.Context, module, version string) { for _, h := range p.settle(module, version, func(heldItem) bool { return true }) { _ = h.m.Ack() } - kv := p.reasks() - if kv == nil { - return - } - if err := kv.Delete(ctx, versions.PublishItemKey(module, version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) { - p.logf("the publish item of %s %s is not deleted: %v", module, version, err) - } -} - -// Try waits for the item's next try, then, while the version is still reserved, puts its publish on the work queue publishes -// under its message id (design 47 H2 §793; H-A-448): an item the queue holds already is put once. It counts no try: each send -// does, and hands its item back with the pause (take). A put that queued nothing is put again after the pause. A version no -// longer reserved (released, dropped or taken over) has its item deleted. -func (p *publishItems) Try(ctx context.Context, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk) { - if !p.wait(ctx, r.NextTry.Sub(p.now())) { - return - } - cur, err := kv.Get(ctx, e.Key()) - if err != nil || cur.Revision() != e.Revision() { - return // deleted by the release, or written again - } - v, held, err := p.reserved(ctx, r.Module, r.Version) - if err != nil { - p.logf("%s %s: its reservation cannot be read, the publish item waits: %v", r.Module, r.Version, err) - return - } - if why := versions.NotStanding(v, held); why != "" { // dropped, taken over, released or withdrawn (A-456b, H-A-290 (2)) - p.logf("%s %s: the publish item is ended: %s", r.Module, r.Version, why) - _ = kv.Delete(ctx, e.Key()) - return - } - queued, err := p.republish(ctx, r.Module, r.Version) - if err == nil && len(queued) > 0 { - return - } - r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries)) - p.logf("%s %s: the publish is not on the work queue %s (%v); it is put again after %s", r.Module, r.Version, versions.PublishesLocal, err, p.set.pauseAfter(r.Tries)) - if data, err := json.Marshal(r); err == nil { - if _, err := kv.Update(ctx, e.Key(), data, e.Revision()); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) { - p.logf("%s: the publish item could not be written: %v", e.Key(), err) - } - } } // itemMsg is what take reads of an item pulled from the work queue (jetstream.Msg). @@ -194,14 +78,14 @@ type itemMsg interface { Ack() error NakWithDelay(time.Duration) error Term() error + Metadata() (*jetstream.MsgMetadata, error) } -// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448): an item whose publish item ended (dropped, or -// its tries spent) or whose version never publishes is terminated; one whose artifacts are all published is acknowledged; once -// publish-tries sends are spent it is terminated and version-unreleased said; while a published of it may be unheard it is handed -// back with the pause, and one the registries' record confirms is acknowledged (H-A-274); else it is sent, the try counted in its -// publish item, and a send that fails handed back with the pause as its delay, so the queue delivers it again and nothing is put -// again. A sent item is acknowledged when its publish is heard (heard, Done) and delivered again after the ack wait, unheard. +// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448, H-A-606): an item whose version never publishes is +// terminated; one whose artifacts are all published is acknowledged; one the registries' record confirms is acknowledged (H-A-274); +// else it is sent. A sent item is acknowledged when its publish is heard (heard, Done) and given again after the ack wait, unheard. +// A send that fails or is refused ends the item, the version staying reserved with version-unreleased naming the holder's words +// (said by the send): it is put again only on the next event of ADR 0674 §2 or by builder_publish_again, never on a timer. func (p *publishItems) take(ctx context.Context, m itemMsg) { var q versions.QueuedPublish if err := json.Unmarshal(m.Data(), &q); err != nil || q.Module == "" || q.Version == "" { @@ -209,44 +93,24 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) { _ = m.Term() return } - kv := p.reasks() - if kv == nil { - p.logf("%s %s: the re-ask state is not on the bus yet; the item is handed back", q.Module, q.Version) - _ = m.NakWithDelay(p.set.Pause) - return - } - key := versions.PublishItemKey(q.Module, q.Version) - e, err := kv.Get(ctx, key) - if errors.Is(err, jetstream.ErrKeyNotFound) { // put by builder_publish_again or the move: its tries are counted from now - if err = p.Ask(ctx, q.Module, q.Version); err == nil { - e, err = kv.Get(ctx, key) + if md, err := m.Metadata(); err == nil && md.NumDelivered >= publishesMaxDeliver { + // The delivery where an item reaches the queue's ten ends it, said, never left dead on the queue (design 47 H2 H-A-653, H-A-703). + words := fmt.Sprintf("given up after %d deliveries", publishesMaxDeliver) + p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, words) + if v, found, err := p.reserved(ctx, q.Module, q.Version); err == nil && found && p.unreleased != nil { + p.unreleased(ctx, v, words) } - } - if err != nil { - p.logf("%s %s: its publish item cannot be read (%v); the item is handed back", q.Module, q.Version, err) - _ = m.NakWithDelay(p.set.Pause) - return - } - r, err := build.DecodeReAsk(e.Value()) - if err != nil { - _ = m.Term() - return - } - if r.Answer != "" { - p.logf("%s %s at %s is terminated: its publish item ended: %s", q.Module, q.Version, q.Holder, r.Answer) _ = m.Term() return } v, found, err := p.reserved(ctx, q.Module, q.Version) if err != nil { - p.logf("%s %s: its reservation cannot be read (%v); the item is handed back", q.Module, q.Version, err) - _ = m.NakWithDelay(p.set.pauseAfter(r.Tries)) + p.logf("%s %s: its reservation cannot be read (%v); the item is given again after the ack wait", q.Module, q.Version, err) return } if why := versions.NotStanding(v, found); why != "" { p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, why) _ = m.Term() - _ = kv.Delete(ctx, key) return } if allPublished(v, q) { @@ -254,17 +118,6 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) { _ = m.Ack() return } - if r.Tries >= p.set.Tries { - _ = m.Term() - r.Answer = fmt.Sprintf("the publish of %s %s was tried %d times and the version is not released; builder_publish_again tries it again", r.Module, r.Version, r.Tries) - r.Answered = p.now().UTC() - p.logf("%s: %s", key, r.Answer) - if p.endedWith != nil { - p.endedWith(ctx, v, "the publish ended after "+fmt.Sprint(r.Tries)+" tries") - } - p.write(ctx, kv, key, r, e.Revision()) - return - } if why, gone := p.notAgain(ctx, v); gone { _ = m.Term() // moved to another number, whose own item is asked (H-A-275) return @@ -274,41 +127,33 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) { _ = m.Ack() return } - p.logf("%s %s: the publish is not sent again: %s; handed back for %s", q.Module, q.Version, why, p.set.pauseAfter(r.Tries)) - _ = m.NakWithDelay(p.set.pauseAfter(r.Tries)) + p.logf("%s %s at %s: the publish is not sent: %s; the item is ended, the version stays reserved", q.Module, q.Version, q.Holder, why) + _ = m.Term() return } fate := versions.SendFate{Failed: "this builder sends no publish"} if p.send != nil { fate = p.send(ctx, q) } + 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 + // ack wait, and the queue's tenth delivery ends it loud (design 47 H2 H-A-745, H-A-653). + p.logf("%s %s at %s: sent no publish: %s; the item is left, given again after the ack wait", q.Module, q.Version, q.Holder, fate.Unread) + return + } if fate.Ended != "" { p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, fate.Ended) _ = m.Term() return } - r.Tries++ - r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries)) - p.write(ctx, kv, key, r, e.Revision()) if fate.Failed != "" { - p.logf("%s %s at %s: try %d sent no publish: %s; handed back for %s", q.Module, q.Version, q.Holder, r.Tries, fate.Failed, p.set.pauseAfter(r.Tries)) - _ = m.NakWithDelay(p.set.pauseAfter(r.Tries)) + p.logf("%s %s at %s: sent no publish: %s; the item is ended, the version stays reserved and is put again on the next event of its holder (H-A-606)", q.Module, q.Version, q.Holder, fate.Failed) + _ = m.Term() return } p.hold(q, m) } -// write writes a publish item at its revision; a newer write wins. -func (p *publishItems) write(ctx context.Context, kv jetstream.KeyValue, key string, r build.ReAsk, rev uint64) { - data, err := json.Marshal(r) - if err != nil { - return - } - if _, err := kv.Update(ctx, key, data, rev); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) { - p.logf("%s: the publish item could not be written: %v", key, err) - } -} - // allPublished says none of q's artifacts is missing from v: its publish is heard. func allPublished(v versions.ReservedVersion, q versions.QueuedPublish) bool { missing := map[string]bool{} @@ -421,8 +266,9 @@ func registryVersionsVia(call toolCaller) func(context.Context, string, string) } var a struct { // the four registry seats answer versions alike: each version with its digest Versions []struct { - Version string `json:"version"` - Digest string `json:"digest"` + Version string `json:"version"` + Digest string `json:"digest"` + Fingerprint string `json:"fingerprint"` } `json:"versions"` } if err := json.Unmarshal(raw, &a); err != nil { @@ -430,7 +276,7 @@ func registryVersionsVia(call toolCaller) func(context.Context, string, string) } out := make([]versions.HeldVersion, 0, len(a.Versions)) for _, v := range a.Versions { - out = append(out, versions.HeldVersion{Version: v.Version, Digest: v.Digest}) + out = append(out, versions.HeldVersion{Version: v.Version, Digest: v.Digest, Fingerprint: v.Fingerprint}) } return out, nil } @@ -460,24 +306,6 @@ func numberFile(path string, def int) (int, error) { return n, nil } -// publishSettingsOf reads publish-pause (seconds), publish-pause-max (minutes) and publish-tries from their files. -func publishSettingsOf(getenv func(string) string) (publishSettings, error) { - s := defaultPublishSettings - pause, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_FILE"), int(s.Pause/time.Second)) - if err != nil { - return s, err - } - pmax, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"), int(s.PauseMax/time.Minute)) - if err != nil { - return s, err - } - tries, err := numberFile(getenv("MESH_BUILDER_PUBLISH_TRIES_FILE"), s.Tries) - if err != nil { - return s, err - } - return publishSettings{Pause: time.Duration(pause) * time.Second, PauseMax: time.Duration(pmax) * time.Minute, Tries: tries}, nil -} - // wirePublishItems joins the reservations to the publish items (design 47 G A-457a, A-456a, A-456b, H2 §793): a done build asks its // item, a release ends it and acknowledges its held items, a drop and a takeover end it and terminate them, a published heard // acknowledges those it publishes, and a release is recorded in releases, the last kept of each module. @@ -526,16 +354,29 @@ func publishesOf(module string) func() (publishesStream, error) { return func() (publishesStream, error) { return b, nil } } -// The consumer's numbers (H-A-446 (2)): at most four sends in flight per holder, and ten deliveries, the work queue's largest; -// the builder ends an item at publish-tries anyway. -const ( - publishesMaxAckPending = versions.PublishSendsAtOnce - publishesMaxDeliver = 10 -) +// defaultPublishAckMinutes is the setting publish-ack-minutes' default: G section 369's publish bound (H-A-606 round 3 (3)). +const defaultPublishAckMinutes = 10 -// publishesConsumer is the one durable consumer of holder's items (H-A-483 addendum). -func publishesConsumer(holder string) string { - return versions.PublishesLocal + "-" + holder +// The consumers' numbers (H-A-700 (1), H-A-620 (2)): per holder, at most four `live` sends in flight and one `again` send, and ten +// deliveries, the work queue's largest. +const publishesMaxDeliver = 10 + +// publishesConsumer is the durable consumer of holder's items of a class: `publishes--live` and `publishes--again` +// (H-A-700 (1)). +func publishesConsumer(holder, class string) string { + return versions.PublishesLocal + "-" + holder + "-" + class +} + +// publishesOneConsumer is the one durable of holder's items an earlier build made: its filter overlaps both classes', which a work +// queue refuses, so a pull deletes it before it makes the two (H-A-700 (2)). +func publishesOneConsumer(holder string) string { return versions.PublishesLocal + "-" + holder } + +// inFlight is the sends of a class at once: four `live`, one `again` (ADR 0674 §3, H-A-620 (2)). +func inFlight(class string) int { + if class == versions.PublishClassStart { + return 1 + } + return versions.PublishSendsAtOnce } // subject is the item's subject on the bus. @@ -554,6 +395,18 @@ func (pq *publishQueue) put(ctx context.Context, q versions.QueuedPublish) (bool if err != nil { return false, err } + // No form of a manifest's stream refuses a new message while one is held, so the subject's last message is read first: one held + // there means the version is queued or being sent, and nothing is put (design 47 H2 H-A-620 (1); ADR 0674 §3). + st, err := pq.js.Stream(ctx, b.Stream) + if err != nil { + return false, err + } + if _, err := st.GetLastMsgForSubject(ctx, pq.subject(b, q)); err == nil { + pq.learn(ctx, q.Holder) + return true, nil + } 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))) if err != nil { if w := err.Error(); strings.Contains(w, "maximum bytes") || strings.Contains(w, "maximum messages") || errors.Is(err, jetstream.ErrMaxBytesExceeded) { @@ -614,72 +467,111 @@ func (pq *publishQueue) learn(ctx context.Context, holder string) { } } -// pull makes holder's one consumer and dispatches its items (design 47 H2 §793, H-A-483 and its addenda): first it retires the -// holder's class durables an earlier release made (`-live`, `-again`), whose filters a work queue refuses beside the one; their -// unacknowledged items stay on the queue and reach the one consumer. +// pull makes holder's two consumers and dispatches their items (design 47 H2 §793, H-A-700, H-A-719): first it deletes the one +// consumer `publishes-` an earlier build made, whose filter overlaps both and a work queue refuses overlapping filters, not +// found ignored and a removal said; its unacknowledged items stay on the queue and reach the two. Each of the two takes the bus's +// inactive threshold equal to the stream's own maximum age, so the bus removes the durable of a holder nothing pulled for that long +// and no deleter is built here (H-A-719). func (pq *publishQueue) pull(ctx context.Context, holder string) error { b, err := pq.binding() if err != nil { return err } + st, err := pq.js.Stream(ctx, b.Stream) + if err != nil { + return err + } + info, err := st.Info(ctx) + if err != nil { + return err + } + old := publishesOneConsumer(holder) + switch err := pq.js.DeleteConsumer(ctx, b.Stream, old); { + case err == nil: + pq.logf("the consumer %s of an earlier build is removed: the publishes of %s have two, one per class (H-A-700)", old, holder) + case !errors.Is(err, jetstream.ErrConsumerNotFound): + return fmt.Errorf("the consumer %s of an earlier build is not removed: %w", old, err) + } for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} { - old := publishesConsumer(holder) + "-" + class - err := pq.js.DeleteConsumer(ctx, b.Stream, old) - switch { - case err == nil: - pq.logf("the consumer %s of an earlier release is removed: the publishes of %s have one consumer (H-A-483)", old, holder) - case !errors.Is(err, jetstream.ErrConsumerNotFound): - return fmt.Errorf("the consumer %s of an earlier release is not removed: %w", old, err) + _, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder, class), + FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy, + AckWait: pq.ackWait, MaxAckPending: inFlight(class), MaxDeliver: publishesMaxDeliver, InactiveThreshold: info.Config.MaxAge}) + if err != nil { + return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder, class), err) } } - c, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder), - FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + ".>", AckPolicy: jetstream.AckExplicitPolicy, - AckWait: pq.ackWait, MaxAckPending: publishesMaxAckPending, MaxDeliver: publishesMaxDeliver}) - if err != nil { - return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder), err) - } pq.logf("pulling the publishes of %s", holder) - go pq.dispatch(ctx, holder, c) + for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} { + if err := pq.dispatch(ctx, b.Stream, holder, class); err != nil { + return err + } + } return nil } -// dispatch runs the items of one holder in the order its one consumer gives them, at most four at once (design 47 H2 §793, -// H-A-483): each free slot takes the next item through a pull that waits, so an item put or handed back after its pause is -// received the moment the bus gives it; an item handed back reappears only after its pause, so an item put meanwhile goes -// before it. A pull the bus refuses ends the dispatch, said; the holder is pulled again when an item of it is put. -func (pq *publishQueue) dispatch(ctx context.Context, holder string, c jetstream.Consumer) { - sem := make(chan struct{}, versions.PublishSendsAtOnce) - for { - select { - case sem <- struct{}{}: - case <-ctx.Done(): - return +// dispatch runs the items of one holder's class as the consumer gives them, at most inFlight(class) at once (design 47 H2 §793, +// H-A-483, H-A-700, H-A-654): in the step queue's shape (serveSteps), a Consume bound to the durable, which the bus's advisories of +// the consumer's creation and deletion bind again, so a pull error never ends it. +func (pq *publishQueue) dispatch(ctx context.Context, stream, holder, class string) error { + name := publishesConsumer(holder, class) + var mu sync.Mutex + var pulling jetstream.ConsumeContext + bind := func() bool { + mu.Lock() + defer mu.Unlock() + if pulling != nil || ctx.Err() != nil { + return pulling != nil } - var got jetstream.Msg - b, err := c.Fetch(1) - if err == nil { - for m := range b.Messages() { - got = m - } - err = b.Error() + c, err := pq.js.Consumer(ctx, stream, name) + if err != nil { + return false } - if err != nil && !errors.Is(err, jetstream.ErrNoMessages) && !errors.Is(err, nats.ErrTimeout) && ctx.Err() == nil { - <-sem - pq.logf("the publishes of %s are not pulled: %v; they are pulled when an item of it is put", holder, err) - pq.mu.Lock() - delete(pq.pulling, holder) - pq.mu.Unlock() - return + cc, err := c.Consume(func(m jetstream.Msg) { go pq.take(ctx, m) }, jetstream.PullMaxMessages(inFlight(class)), + jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { + pq.logf("the %s publishes of %s: the pull met %v; it goes on", class, holder, err) + })) + if err != nil { + pq.logf("the %s publishes of %s are not pulled: %v; they are pulled when the bus says the consumer was created", class, holder, err) + return false } - if got == nil { - <-sem - continue - } - go func(m jetstream.Msg) { - defer func() { <-sem }() - pq.take(ctx, m) - }(got) + pulling = cc + return true } + release := func() { + mu.Lock() + defer mu.Unlock() + if pulling == nil { + return + } + pulling.Stop() + pulling = nil + pq.logf("the consumer %s was deleted: its items wait, and it is pulled again when the bus says it was created", name) + } + conn := pq.js.Conn() + created, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.CREATED."+stream+"."+name, func(*nats.Msg) { go bind() }) + if err != nil { + return fmt.Errorf("hearing the creation of the consumer %s: %w", name, err) + } + deleted, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.DELETED."+stream+"."+name, func(*nats.Msg) { + go func() { + release() + bind() // made again before the deletion was heard + }() + }) + if err != nil { + _ = created.Unsubscribe() + return fmt.Errorf("hearing the deletion of the consumer %s: %w", name, err) + } + go func() { + <-ctx.Done() + _ = created.Unsubscribe() + _ = deleted.Unsubscribe() + release() + }() + if !bind() { + return fmt.Errorf("the consumer %s is not bound", name) + } + return nil } // itemsOf are the items the work queue holds of module's version in class (empty for any class), each with its subject. @@ -761,14 +653,17 @@ func (pq *publishQueue) reader(ctx context.Context) versions.Reader { }} } -// drop is builder_publish_drop (§793): the version's publish item is ended with who dropped it and why, so no item of it is ever +// drop is builder_publish_drop (§793): the version's reservation keeps who dropped its publish and why (H-A-746), so no item of it is ever // sent or put again; its items waiting on the work queue are removed, and one held is terminated. func (pq *publishQueue) drop(ctx context.Context, items *publishItems, module, version, by, why string) (string, error) { qs, st, err := pq.itemsOf(ctx, module, version, "") if err != nil { return "", fmt.Errorf("the work queue %s cannot be read: %w", versions.PublishesLocal, err) } - if err := items.endItem(ctx, module, version, fmt.Sprintf("dropped by %s: %s", by, why)); err != nil { + if items.dropMark == nil { + return "", errors.New("this builder keeps no reservations") + } + if err := items.dropMark(ctx, module, version, by, why); err != nil { return "", err } for subj := range qs { @@ -782,48 +677,6 @@ func (pq *publishQueue) drop(ctx context.Context, items *publishItems, module, v return fmt.Sprintf("the publish of %s %s is dropped: %d items terminated, and none is sent or put again", module, version, len(qs)), nil } -// endItem writes the version's publish item ended with answer, made when none stands: Try and take then leave it, and a start -// asks it no more. -func (p *publishItems) endItem(ctx context.Context, module, version, answer string) error { - kv := p.reasks() - if kv == nil { - return errors.New("the re-ask state is not on the bus yet") - } - key := versions.PublishItemKey(module, version) - for range 5 { - r := build.ReAsk{V: 1, Why: "the build ended with its version unreleased", By: "the builder", At: p.now().UTC(), Mode: build.ModePublish, Module: module, Version: version} - e, err := kv.Get(ctx, key) - var rev uint64 - switch { - case errors.Is(err, jetstream.ErrKeyNotFound): - case err != nil: - return err - default: - if r, err = build.DecodeReAsk(e.Value()); err != nil { - return err - } - rev = e.Revision() - } - r.Answer, r.Answered = answer, p.now().UTC() - data, err := json.Marshal(r) - if err != nil { - return err - } - if rev == 0 { - _, err = kv.Create(ctx, key, data) - } else { - _, err = kv.Update(ctx, key, data, rev) - } - if err == nil { - return nil - } - if !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) { - return err - } - } - return errors.New("the publish item of " + module + " " + version + " changed five times while it was ended") -} - // moveOld puts the items of the old state publish-queue on the work queue once at the start (§793): each under its message id, so // a move run twice puts each once within the duplicates window; then the builder, which made that bucket, removes it itself // (H-A-461 (1): the bus module's keeper holds no entry for it, so its drop refuses it). A builder whose bus holds no such 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 c516dff68..91fafe287 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 @@ -5,9 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "maps" - "os" - "path/filepath" "slices" "strings" "sync" @@ -16,9 +13,6 @@ import ( "github.com/nats-io/nats.go/jetstream" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" - "mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/versions" ) @@ -90,15 +84,39 @@ func (k *itemKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOp return nil } +// ListKeys lists the keys the state holds, as the bus's key lister does. +func (k *itemKV) ListKeys(context.Context, ...jetstream.WatchOpt) (jetstream.KeyLister, error) { + k.mu.Lock() + defer k.mu.Unlock() + ch := make(chan string, len(k.vals)) + for key := range k.vals { + ch <- key + } + close(ch) + return itemKeys{ch}, nil +} + +type itemKeys struct{ ch chan string } + +func (l itemKeys) Keys() <-chan string { return l.ch } +func (l itemKeys) Stop() error { return nil } + // itemMsgFake is an item pulled from the work queue: what take settled it with. type itemMsgFake struct { - data []byte - settled []string // ack, term, nak + 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) Metadata() (*jetstream.MsgMetadata, error) { + if m.delivered == 0 { + return nil, errors.New("no metadata") + } + return &jetstream.MsgMetadata{NumDelivered: m.delivered}, nil +} func (m *itemMsgFake) NakWithDelay(d time.Duration) error { m.settled = append(m.settled, "nak "+d.String()) return nil @@ -122,26 +140,19 @@ func decodeItem(t *testing.T, raw []byte) build.ReAsk { return r } -// TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly: design 47 G A-457a, H2 §793 (H-A-440 (2), H-A-448) — a version's publish -// item is asked once; its try puts the publish on the work queue and counts no try; each send counts one and a failed send hands -// the item back with the pause doubled up to its maximum; after the setting's tries the item is terminated and ends with its words, -// raises the condition and stays; an item whose artifacts are published is acknowledged; the release deletes it; a version no -// longer reserved has it deleted. -func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) { +// TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer: design 47 H2 H-A-606 (A-473) — the ask at a build's end puts the publish on the +// work queue once; a send that fails or is refused ends its item, the version stays reserved and nothing hands it back after a pause; +// an item whose artifacts are published is acknowledged; a version no longer reserved is terminated; a publish its drop ended is +// terminated whatever puts it again. +func TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer(t *testing.T) { ctx := context.Background() kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} now := time.Date(2026, 11, 17, 1, 0, 0, 0, time.UTC) - var queued, ended, sent []string + var queued, sent []string reserved := true v := versions.ReservedVersion{Module: "m", Version: "0.1.2", Artifacts: map[string]string{"m:a": "sha256:a"}, BuiltAt: now} - p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: 30 * time.Second, PauseMax: 2 * time.Minute, Tries: 4}, - now: func() time.Time { return now }, logf: t.Logf, - after: func(d time.Duration) <-chan time.Time { - now = now.Add(d) - c := make(chan time.Time, 1) - c <- now - return c - }, + fate := versions.SendFate{Failed: "no holder answers"} + p := &publishItems{now: func() time.Time { return now }, logf: t.Logf, reserved: func(_ context.Context, _, ver string) (versions.ReservedVersion, bool, error) { if ver == "0.3.0" { // every artifact published, its release not written yet return versions.ReservedVersion{Module: "m", Version: ver, Artifacts: map[string]string{"m:a": "sha256:a"}, Published: map[string]bool{"m:a": true}, BuiltAt: now}, true, nil @@ -154,295 +165,93 @@ func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) { }, send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate { sent = append(sent, q.Module+" "+q.Version) - return versions.SendFate{Failed: "no holder answers"} - }, - endedWith: func(_ context.Context, v versions.ReservedVersion, why string) { - ended = append(ended, v.Version+": "+why) + return fate }} - key := versions.PublishItemKey("m", "0.1.2") - if err := p.Ask(ctx, "m", "0.1.2"); err != nil || p.Ask(ctx, "m", "0.1.2") != nil || len(kv.vals) != 1 { - t.Fatalf("asked: %v, %d items, want one item however often it is asked", err, len(kv.vals)) - } - e, _ := kv.Get(ctx, key) - p.Try(ctx, kv, e, decodeItem(t, e.Value())) - if len(queued) != 1 || decodeItem(t, kv.vals[key]).Tries != 0 { - t.Fatalf("the try queued %v, tries %d: want the publish put once, no try counted", queued, decodeItem(t, kv.vals[key]).Tries) - } - var settled []string - for range 5 { - m := queuedMsg(t, "m", "0.1.2") - p.take(ctx, m) - settled = append(settled, m.settled...) - } - got := decodeItem(t, kv.vals[key]) - if len(sent) != 4 || got.Tries != 4 || got.Answer == "" || got.Answered.IsZero() || len(ended) != 1 || !strings.Contains(ended[0], "4 tries") { - t.Fatalf("sent %v, item %+v, ended %v: want four sends, then the end said with its words and the condition", sent, got, ended) - } - if want := "[nak 30s nak 1m0s nak 2m0s nak 2m0s term]"; fmt.Sprint(settled) != want { - t.Errorf("the items were settled %v, want %s (handed back with the pause doubled and capped, then terminated)", settled, want) + if err := p.Ask(ctx, "m", "0.1.2"); err != nil || len(queued) != 1 || len(kv.vals) != 0 { + t.Fatalf("asked: %v, queued %v, %d items: want the publish put once and no item kept", err, queued, len(kv.vals)) } m := queuedMsg(t, "m", "0.1.2") - if p.take(ctx, m); fmt.Sprint(m.settled) != "[term]" || len(sent) != 4 { - t.Errorf("an item of an ended publish item was settled %v, sent %d: want it terminated unsent", m.settled, len(sent)) + p.take(ctx, m) + if len(sent) != 1 || !slices.Equal(m.settled, []string{"term"}) { + t.Fatalf("a failed send: sent %v, settled %v, want one send and the item terminated, never handed back with a pause", sent, m.settled) + } + // design 47 H2 H-A-745: a read of the builder's own state that failed leaves the item unacknowledged, ended nowhere. + fate = versions.SendFate{Unread: "its reservation cannot be read: down"} + m = queuedMsg(t, "m", "0.1.2") + p.take(ctx, m) + if len(sent) != 2 || len(m.settled) != 0 { + t.Fatalf("an unread send: sent %v, settled %v, want it left unacknowledged", sent, m.settled) + } + fate = versions.SendFate{Sent: true} + m = queuedMsg(t, "m", "0.1.2") + p.take(ctx, m) + if len(m.settled) != 0 { + t.Fatalf("a sent item is settled %v, want it held until its publish is heard", m.settled) } - // An item whose artifacts are all published is acknowledged unsent; its publish item stays until its release is written (A-456b). - _ = p.Ask(ctx, "m", "0.3.0") - pk := versions.PublishItemKey("m", "0.3.0") m = queuedMsg(t, "m", "0.3.0") - if p.take(ctx, m); fmt.Sprint(m.settled) != "[ack]" || len(sent) != 4 || !kv.has(pk) { - t.Errorf("an item whose artifacts are published was settled %v, sent %d, kept %v: want it acknowledged unsent, its publish item kept", m.settled, len(sent), kv.has(pk)) + p.take(ctx, m) + if !slices.Equal(m.settled, []string{"ack"}) { + t.Errorf("an item whose artifacts are published settled %v, want ack", m.settled) } - kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{} - // At the start every reservation of a done build with no release is asked, one item each. - kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{} - p.allDone = func(context.Context) ([]versions.ReservedVersion, error) { - published := versions.ReservedVersion{Module: "n", Version: "0.2.0", Artifacts: map[string]string{"n:a": "sha256:a"}, Published: map[string]bool{"n:a": true}, BuiltAt: now} - withdrawn := versions.ReservedVersion{Module: "w", Version: "0.4.0", BuiltAt: now, Withdrawn: map[string]string{"0.4.0": "fp"}} - return builtOf([]versions.ReservedVersion{v, published, withdrawn, {Module: "o", Version: "0.1.0"}}), nil // the last build has not ended - } - _ = p.Ask(ctx, "w", "0.4.0") // asked before its reservation was withdrawn - p.AskAllDone(ctx) - if _, ok := kv.vals[versions.PublishItemKey("w", "0.4.0")]; len(kv.vals) != 2 || ok { - t.Errorf("the start left %d items (withdrawn's kept: %v), want one per done unreleased reservation and none for a withdrawn one (H-A-290 (2))", len(kv.vals), ok) - } - // A start with three unreleased done versions of one module asks only the newest and retires the two (H-A-291 (1), H-A-275). - kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{} - _ = p.Ask(ctx, "s", "0.1.3") // asked in an earlier run - p.allDone = func(context.Context) ([]versions.ReservedVersion, error) { - var out []versions.ReservedVersion - for _, ver := range []string{"0.1.3", "0.1.10", "0.1.2"} { // one series (H-A-293) - out = append(out, versions.ReservedVersion{Module: "s", Version: ver, Artifacts: map[string]string{"s:a": "sha256:a"}, BuiltAt: now}) - } - return out, nil - } - p.retired = (&versions.Reserver{}).Retired - p.AskAllDone(ctx) - if _, ok := kv.vals[versions.PublishItemKey("s", "0.1.10")]; len(kv.vals) != 1 || !ok { - t.Errorf("the start left the items %v, want only the newest, s 0.1.10, asked and the two older retired", slices.Collect(maps.Keys(kv.vals))) - } - kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{} - // A released version's item is deleted; a version no longer reserved has it deleted at its next try. - p.Done(ctx, "m", "0.1.2") - p.Done(ctx, "n", "0.2.0") - if len(kv.vals) != 0 { - t.Errorf("the release left %v", kv.vals) - } - // A withdrawn reservation has its item ended at its try, nothing queued (H-A-290 (2)). - queued = nil - _ = p.Ask(ctx, "m", "0.1.2") - v.Withdrawn = map[string]string{"0.1.2": "fp"} - e, _ = kv.Get(ctx, key) - p.Try(ctx, kv, e, decodeItem(t, e.Value())) - if len(kv.vals) != 0 || len(queued) != 0 { - t.Errorf("a withdrawn reservation left its item %v, queued %v", kv.vals, queued) - } - v.Withdrawn = nil - _ = p.Ask(ctx, "m", "0.1.2") reserved = false - e, _ = kv.Get(ctx, key) - p.Try(ctx, kv, e, decodeItem(t, e.Value())) - if len(kv.vals) != 0 { - t.Errorf("a dropped reservation left its item %v", kv.vals) + m = queuedMsg(t, "m", "0.1.2") + p.take(ctx, m) + if !slices.Equal(m.settled, []string{"term"}) { + t.Errorf("an item of a version no longer reserved settled %v, want term", m.settled) } -} - -// TestThePublishSettingsAreReadFromTheirFiles: design 47 G A-457a, H2 H-A-446 (2) — the three settings, 30 s, 30 min and 5 tries -// unless set, and a -// content that is no number is refused naming its file. -func TestThePublishSettingsAreReadFromTheirFiles(t *testing.T) { - dir := t.TempDir() - write := func(name, v string) string { - p := filepath.Join(dir, name) - if err := os.WriteFile(p, []byte(v), 0o600); err != nil { - t.Fatal(err) - } - return p + reserved = true + // design 47 H2 H-A-746: a publish dropped by hand is kept on the reservation, read as its standing: the item is terminated unsent. + v.Dropped = &versions.PublishDropped{By: "a person", Why: "why", At: now} + before := len(sent) + m = queuedMsg(t, "m", "0.1.2") + p.take(ctx, m) + if !slices.Equal(m.settled, []string{"term"}) || len(sent) != before { + t.Errorf("a dropped publish: settled %v, sent %d more, want it terminated and not sent", m.settled, len(sent)-before) } - env := map[string]string{} - got, err := publishSettingsOf(func(k string) string { return env[k] }) - if err != nil || got != defaultPublishSettings || got.Pause != 30*time.Second || got.PauseMax != 30*time.Minute || got.Tries != 5 { - t.Fatalf("defaults = %+v (%v)", got, err) + v.Dropped = nil + // design 47 H2 H-A-653, H-A-703: the delivery where an item reaches the queue's ten ends it and raises version-unreleased. + var words []string + p.unreleased = func(_ context.Context, _ versions.ReservedVersion, why string) { words = append(words, why) } + before = len(sent) + m = queuedMsg(t, "m", "0.1.2") + m.delivered = publishesMaxDeliver - 1 + p.take(ctx, m) + if len(words) != 0 || len(sent) != before+1 { + t.Errorf("a ninth delivery: said %v, sent %d more, want it sent", words, len(sent)-before) } - env["MESH_BUILDER_PUBLISH_PAUSE_FILE"], env["MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"], env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("p", "5\n"), write("m", "2"), write("t", "3") - if got, err = publishSettingsOf(func(k string) string { return env[k] }); err != nil || got != (publishSettings{5 * time.Second, 2 * time.Minute, 3}) { - t.Errorf("set = %+v (%v)", got, err) + m = queuedMsg(t, "m", "0.1.2") + m.delivered = publishesMaxDeliver + p.take(ctx, m) + if !slices.Equal(m.settled, []string{"term"}) || len(sent) != before+1 || len(words) != 1 || words[0] != "given up after 10 deliveries" { + t.Errorf("a tenth delivery: settled %v, said %v, want it terminated unsent with %q", m.settled, words, "given up after 10 deliveries") } - env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("bad", "many") - if _, err = publishSettingsOf(func(k string) string { return env[k] }); err == nil || !strings.Contains(err.Error(), "bad") { - t.Errorf("a content that is no number: %v", err) - } -} - -// TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch: design 47 G A-457a, A-456b — a mode-publish value of the re-ask state -// reaches the item's try through reAsked; a done build gets an item; the catalog's version-released, a drop and a takeover delete it -// and the release is kept by module. -func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T) { - ctx := context.Background() - kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} - st := &memFindings{vals: map[string][]byte{}} - found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }} - call := func(string, any) (json.RawMessage, error) { - return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"}) - } - rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf) - tried := make(chan string, 4) - items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: time.Now, logf: t.Logf, - reserved: func(ctx context.Context, m, v string) (versions.ReservedVersion, bool, error) { - return rv.r.Of(ctx, m, v) - }, - republish: func(_ context.Context, m, v string) ([]string, error) { tried <- m + " " + v; return nil, nil }} - releases := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}} - wirePublishItems(rv, items, releases, 2) - done := func(fp string) versions.ReservedVersion { - v, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: fp}) + // design 47 H2 H-A-749 (2): at the start an answered publish-drop ask is carried onto its version's reservation as dropped, where + // it stands and holds none; a refused one is not; each record of mode publish is deleted, the drop's own ask staying. + res := &versions.Reserver{Store: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, Now: func() time.Time { return now }, + ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} + for _, m := range []string{"m", "n"} { + rv, err := res.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "src2:" + m}) if err != nil { t.Fatal(err) } - if err := rv.Built(ctx, "m", v.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil { + if _, _, err := res.Built(ctx, m, rv.Version, map[string]string{m + ":a": "sha256:a"}, nil); err != nil { t.Fatal(err) } - return v } - first := done("src2:one") - key := versions.PublishItemKey("m", first.Version) - if !kv.has(key) { - t.Fatalf("a done build has no publish item: %v", kv.vals) + old := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} + put := func(key string, r build.ReAsk) { + raw, _ := json.Marshal(r) + old.vals[key], old.revs[key] = raw, 1 } - // A build whose artifacts are all published still gets its item, until its release is written (A-456b). - if _, _, err := rv.r.Published(ctx, versions.NameOf("m", "a"), first.Version, "sha256:a"); err != nil { - t.Fatal(err) + put("publish-drop.1", build.ReAsk{V: 1, Mode: build.ModePublishDrop, Module: "m", Version: "0.1.0", By: "op@node", Why: "a person's drop", At: now, Answered: now}) + put("publish-drop.2", build.ReAsk{V: 1, Mode: build.ModePublishDrop, Module: "n", Version: "0.1.0", By: "op@node", Why: "refused", At: now, Answered: now, Refused: true}) + put("publish.m.0.1.0", build.ReAsk{V: 1, Mode: "publish", Module: "m", Version: "0.1.0", Answer: "dropped by op@node: a person's drop", Answered: now}) + carryDrops(ctx, old, res, t.Logf) + if m0, _, _ := res.Of(ctx, "m", "0.1.0"); m0.Dropped == nil || m0.Dropped.By != "op@node" || m0.Dropped.Why != "a person's drop" || !m0.Dropped.At.Equal(now) { + t.Errorf("m's reservation reads dropped %+v, want the earlier drop carried onto it", m0.Dropped) } - items.Done(ctx, "m", first.Version) - if err := rv.Built(ctx, "m", first.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil { - t.Fatal(err) - } - if !kv.has(key) { - t.Fatalf("a build with every artifact published has no item: %v", kv.vals) - } - // The watch hands the item to its try, which queues the publish. - e, _ := kv.Get(ctx, key) - reAsked(ctx, nil, versions.Acts{}, items, kv, e, t.Logf) - select { - case got := <-tried: - if got != "m "+first.Version { - t.Errorf("tried %q", got) - } - case <-time.After(10 * time.Second): - t.Fatal("a mode-publish value was not handed to the item's try") - } - // A takeover by another build deletes the older's item and asks the newer's. - second := done("src2:two") - if kv.has(key) { - t.Errorf("the taken-over reservation kept its item") - } - secondKey := versions.PublishItemKey("m", second.Version) - if !kv.has(secondKey) { - t.Fatalf("the newer build has no item: %v", kv.vals) - } - // version-released deletes the item and keeps the release. - msg := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"m","version":"` + second.Version + `","source":1,"artifacts":[]}`)} - if !rv.heard(ctx, msg) || !msg.acked { - t.Fatal("version-released was not taken in") - } - if kv.has(secondKey) { - t.Errorf("a released version kept its publish item") - } - if ok, _ := rv.ReleasedFor(ctx, "m", "src2:two"); !ok { - t.Errorf("the release is not kept by fingerprint") - } - // A drop deletes the item too. - third := done("src2:three") - if _, err := rv.dropped(ctx, "m", "0.1", "op", "never", time.Unix(0, 0)); err != nil { - t.Fatal(err) - } - if kv.has(versions.PublishItemKey("m", third.Version)) { - t.Errorf("a dropped reservation kept its item") - } -} - -// Design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275, and design 47 H2 H-A-514 addendum: a publish is asked again judged from -// what the builder recorded and the registries' record alone, never from how many events its consumer holds unheard: a -// reservation marking every artifact published is acknowledged; a record holding every missing artifact with the built digest -// marks them published from it; a record holding the version at another digest moves the build to the next free number and -// ends this item; a record lacking it is asked again; a skipped try spends no try and is written again with its pause. -func TestAPublishIsAskedAgainFromWhatTheBuilderRecorded(t *testing.T) { - ctx := context.Background() - now := time.Date(2026, 11, 21, 15, 21, 0, 0, time.UTC) - v := versions.ReservedVersion{Module: "node-tools", Version: "0.1.37", Artifacts: map[string]string{"node-tools:program": "sha256:7c9b10"}, BuiltAt: now} - at := versions.HeldArtifact{Ref: "node-tools:program", Seat: versions.SeatArtifacts, Name: "node-tools/program", Version: "0.1.37", Digest: "sha256:7c9b10"} - other := at - other.Digest = "sha256:83bec1" - for _, c := range []struct { - name string - published bool - judged versions.Judged - wantAsked, wantMark, wantMov bool - }{ - {name: "its reservation marks it published: acknowledged, no ask", published: true}, - {name: "the registry holds it: marked from its record, no ask", judged: versions.Judged{All: true, Held: []versions.HeldArtifact{at}}, wantMark: true}, - {name: "the registry holds the number at another digest: moved, no ask", judged: versions.Judged{Elsewhere: []versions.HeldArtifact{other}}, wantMov: true}, - {name: "the registry lacks it: asked, whatever the events consumer holds", judged: versions.Judged{Lacks: "none"}, wantAsked: true}, - } { - t.Run(c.name, func(t *testing.T) { - kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}} - asked, judged, marked, moved := 0, 0, 0, 0 - p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: func() time.Time { return now }, logf: t.Logf, - reserved: func(context.Context, string, string) (versions.ReservedVersion, bool, error) { - if c.published { - w := v - w.Published = map[string]bool{"node-tools:program": true} - return w, true, nil - } - return v, true, nil - }, - send: func(context.Context, versions.QueuedPublish) versions.SendFate { - asked++ - return versions.SendFate{Sent: true} - }, - judge: func(context.Context, versions.ReservedVersion) (versions.Judged, error) { - judged++ - return c.judged, nil - }, - markHeld: func(_ context.Context, _ versions.ReservedVersion, h []versions.HeldArtifact) { - if len(h) == 1 && h[0].Digest == "sha256:7c9b10" { - marked++ - } - }, - moveElsewhere: func(context.Context, versions.ReservedVersion, versions.Judged) error { - moved++ - delete(kv.vals, versions.PublishItemKey(v.Module, v.Version)) // the takeover ends the old item - return nil - }} - if err := p.Ask(ctx, v.Module, v.Version); err != nil { - t.Fatal(err) - } - key := versions.PublishItemKey(v.Module, v.Version) - m := queuedMsg(t, v.Module, v.Version) - m.data = []byte(strings.ReplaceAll(string(m.data), `"node-tools:a"`, `"node-tools:program"`)) - p.take(ctx, m) - if (asked == 1) != c.wantAsked || (marked == 1) != c.wantMark || (moved == 1) != c.wantMov { - t.Fatalf("asked %d, marked %d, moved %d; want asked %v, marked %v, moved %v", asked, marked, moved, c.wantAsked, c.wantMark, c.wantMov) - } - if c.published { - if fmt.Sprint(m.settled) != "[ack]" || judged != 0 { - t.Errorf("a version its reservation marks published settled %v, the registry read %d times; want acknowledged, none read", m.settled, judged) - } - return - } - if c.wantMov { - if _, ok := kv.vals[key]; ok || fmt.Sprint(m.settled) != "[term]" { - t.Errorf("the moved version's old item is written again, or its item settled %v, not terminated", m.settled) - } - return - } - got := decodeItem(t, kv.vals[key]) - if got.Tries != map[bool]int{true: 1, false: 0}[c.wantAsked] || (c.wantAsked && !got.NextTry.After(now)) { - t.Errorf("tries %d, next try %s: want a try spent only when sent, the item written with its pause", got.Tries, got.NextTry) - } - if !c.wantAsked && fmt.Sprint(m.settled) != "[nak 30s]" { - t.Errorf("an item not sent was settled %v, want it handed back with the pause and no try spent", m.settled) - } - }) + if n0, _, _ := res.Of(ctx, "n", "0.1.0"); n0.Dropped != nil || old.has("publish.m.0.1.0") || !old.has("publish-drop.1") || !old.has("publish-drop.2") { + t.Errorf("n dropped %+v, publish record left %v: want a refused drop not carried, the record gone and the asks kept", n0.Dropped, old.has("publish.m.0.1.0")) } } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go index e3951c9a6..bf9d5cdbc 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go @@ -45,13 +45,6 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi if r.Answer != "" { return } - if r.Mode == build.ModePublish { - // A version's publish item (design 47 G A-457a): its try waits for its pause, so it is made beside the watch. - if items != nil { - go items.Try(ctx, kv, e, r) - } - return - } if r.Mode == build.ModeBuild { // The answer comes when the claim and the asks are written, so it is made beside the watch, not in it. go builtAgain(ctx, b, kv, e, r, logf) @@ -65,7 +58,7 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi released(ctx, b, kv, e, r, logf) return } - if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone { + if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop { // A version's hand act (design 51 *Tools of the builder*) may build again, so it is answered beside the watch. go versionActed(ctx, acts, kv, e, r, logf) return @@ -196,7 +189,7 @@ func emitBuildEnded(ctx context.Context, js jetstream.JetStream, cred process.Ac return nil } -// versionActed answers a reasks value of builder_publish_again, builder_publish_drop, builder_reserve_done, builder_reserved_drop or builder_old_form's drop, a hand act said in the log. +// versionActed answers a reasks value of builder_publish_again, builder_publish_drop, builder_reserved_drop or builder_old_form's drop, a hand act said in the log. func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk, logf func(string, ...any)) { var err error if r.Mode == build.ModeRepublish { @@ -215,17 +208,11 @@ func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue } else { r.Answer, err = act(ctx, r.Module, r.Version, r.By, r.Why) } - } else if r.Mode == build.ModeReserveDone { - if acts.ReserveDone == nil { - err = errors.New("this builder keeps no reservations") - } else { - r.Answer, err = acts.ReserveDone(ctx, r.Name, r.FP, r.By, r.Why, r.At) - } } else if r.Mode == build.ModeReservedDrop { if acts.DropReserved == nil { err = errors.New("this builder keeps no reservations") } else { - r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.By, r.Why, r.At) + r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.Version, r.By, r.Why, r.At) } } else if acts.DropOldForm == nil { err = errors.New("this builder keeps no old-form window") diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go index c53d57d9b..ee11565bd 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go @@ -566,4 +566,8 @@ func TestTheBuildersFindingsAreObservedByItsCredentialsModule(t *testing.T) { if err != nil || got.Observer != "acme-builder" { t.Fatalf("the finding = %+v, %v; want the observer acme-builder", got, err) } + // H2 H-A-578 (1): floor-silent, which no code of the builder raises any more, is cleared at the writer's start + if !slices.ContainsFunc(retiredFindingKinds, func(r views.RetiredKind) bool { return r.Kind == "floor-silent" && len(r.IDs) == 0 }) || slices.ContainsFunc(retiredFindingKinds, func(r views.RetiredKind) bool { return r.Kind == BuildFailed }) { + t.Error("the writer's retired kinds are not floor-silent alone") + } } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish.go index f53a17617..9c6e4acf8 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish.go @@ -8,9 +8,11 @@ import ( "fmt" "time" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry" "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/process" "mesh-delivery-builder/internal/versions" @@ -47,9 +49,15 @@ func publishAskID(p versions.Publish) string { // artifact store, addressed by digest. The four seats' publish take one wire form; an answer that lacks parts, or a fault of // the call, is the holder's refusal, said in its words (not stored when the holder lacks the bytes). The publish is a kept // call carrying its ask id (design 47 H2 §775), made again through transport faults at the kept-call pace within ctx's bound. -func sendVia(call keptCaller) func(ctx context.Context, p versions.Publish) error { +// +// said is told when the call has waited five minutes unanswered and once at its answer (busretry.WaitSaid; design 47 H2 H-A-613 (4), +// H-A-620 (3): call-unanswered written after five minutes, ADR 0668 §3); nil is told nothing. +func sendVia(call keptCaller, said func(p versions.Publish, w busretry.Waited)) func(ctx context.Context, p versions.Publish) error { return func(ctx context.Context, p versions.Publish) error { ask := process.KeptAsk{ID: publishAskID(p)} + if said != nil { + ask.Hook = func(w busretry.Waited) { said(p, w) } + } if d, ok := ctx.Deadline(); ok { ask.Bound = time.Until(d) } @@ -62,6 +70,11 @@ func sendVia(call keptCaller) func(ctx context.Context, p versions.Publish) erro if err := json.Unmarshal(raw, &a); err != nil { return fmt.Errorf("%s answered what is no publish answer: %w", p.Seat, err) } + // A version held with other bytes is answered, never failed (design 47 H2 H-A-729); it is read before the transfer, which is + // absent exactly then (H-A-732). + if a.OtherBytes != nil { + return &versions.OtherBytes{Seat: p.Seat, Name: p.Name, Version: p.Version, Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint} + } if len(a.Lacks) > 0 { return fmt.Errorf("%s%s holds %d of the parts of %s %s", versions.NotStoredWords, p.Seat, len(a.Lacks), p.Name, p.Version) } @@ -96,3 +109,18 @@ func callWithin(ctx context.Context, call toolCaller, key string, body any) (jso func publishBody(p versions.Publish) gopackageregistry.PublishInput { return gopackageregistry.PublishInput{Commit: p.Commit, Digest: p.Digest, Fingerprint: p.Fingerprint, Kind: p.Kind, Name: p.Name, Transfer: p.Transfer, Version: p.Version} } + +// publishUnanswered is what a publish's kept call tells when it has waited five minutes and at its answer (design 47 H2 H-A-613 (4), +// H-A-620 (3); ADR 0668 §3): the finding call-unanswered about the publish's ask id is raised at the first and cleared at the second. +func publishUnanswered(ctx context.Context, f *findings) func(versions.Publish, busretry.Waited) { + return func(p versions.Publish, w busretry.Waited) { + id := publishAskID(p) + if w.Answered { + f.clear(ctx, meshconditionsclient.KindCallUnanswered, meshconditionsclient.ScopeCall, id) + return + } + o := callUnanswered(id, "seat:"+p.Seat+"."+versions.VerbPublish+" of "+p.Name+" "+p.Version, "", w.Last, "builder."+meshconditionsclient.KindCallUnanswered, w.Since) + o.needs = "the call is made again by itself until the holder answers; builder_publish_queue shows the item." + f.raise(ctx, o) + } +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish_test.go index 7a22acdb7..11f4223d0 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/republish_test.go @@ -15,6 +15,9 @@ import ( "git.novox.be/novox/mesh-sdk/go/process" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" + "git.novox.be/novox/mesh-sdk/go/busretry" "mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/versions" ) @@ -54,7 +57,7 @@ func TestRepublishSend(t *testing.T) { send := sendVia(func(ask process.KeptAsk, key string, body any) (json.RawMessage, error) { asked, id = key, ask.ID return json.RawMessage(c.answer), c.err - }) + }, nil) err := send(context.Background(), p) // design 47 H2 §775: the publish carries its ask id, the same for the same publish if asked != "seat:oci-artifact-registry.publish" || id != publishAskID(p) || strings.Contains(id, ".") || (c.want == "") != (err == nil) || (err != nil && !strings.Contains(err.Error(), c.want)) { @@ -73,7 +76,7 @@ func TestRepublishSend(t *testing.T) { } for name, call := range map[string]func(context.Context) error{ "the publish": func(ctx context.Context) error { - return sendVia(func(_ process.KeptAsk, k string, b any) (json.RawMessage, error) { return slow(k, b) })(ctx, p) + return sendVia(func(_ process.KeptAsk, k string, b any) (json.RawMessage, error) { return slow(k, b) }, nil)(ctx, p) }, "the entry": func(ctx context.Context) error { _, err := entryVia(slow)(ctx, "fp"); return err }, } { @@ -89,3 +92,29 @@ func TestRepublishSend(t *testing.T) { } func versionsNow() time.Time { return time.Unix(1, 0) } + +// Design 47 H2 H-A-613 (4), H-A-620 (3): a publish's kept call that has waited five minutes raises call-unanswered about its ask id, +// and its answer clears it; the call carries the hook that says so. +func TestAPublishWaitedFiveMinutesIsCallUnanswered(t *testing.T) { + p := versions.Publish{Seat: versions.SeatArtifacts, Kind: "bundle", Name: "m/prog", Version: "0.1.3", Digest: "sha256:aa"} + st := &memFindings{vals: map[string][]byte{}} + f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }} + said := publishUnanswered(context.Background(), f) + var hook func(busretry.Waited) + _ = sendVia(func(ask process.KeptAsk, _ string, _ any) (json.RawMessage, error) { + hook = ask.Hook + return json.RawMessage(`{"held":true}`), nil + }, said)(context.Background(), p) + if hook == nil { + t.Fatal("the publish's kept call carries no hook") + } + key := meshconditionsclient.Key(meshconditionsclient.ScopeCall, publishAskID(p), meshconditionsclient.KindCallUnanswered) + hook(busretry.Waited{Since: time.Unix(0, 0), Last: "no responders"}) + if got, err := decodeFinding(st.vals[key]); err != nil || got.Kind != meshconditionsclient.KindCallUnanswered || !strings.Contains(got.Summary, "m/prog 0.1.3") { + t.Fatalf("the call waited: finding %+v, %v", got, err) + } + hook(busretry.Waited{Answered: true}) + if st.vals[key] != nil { + t.Error("the call answered: the finding stands") + } +} 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 16d5eff87..c3ab95aed 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go @@ -7,6 +7,7 @@ import ( "fmt" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "slices" + "sort" "strings" "time" @@ -58,6 +59,10 @@ type reservations struct { recordAgain func(ctx context.Context, module, fp, when string) (string, error) // rebuild builds a done key of module at fp again (the build-again path, A-490; H-A-279); nil builds none. rebuild func(ctx context.Context, module, fp, why string) error + // looking says a look of the builder holds the build key of module at fp now (builder_reserved_drop refuses it); nil says none. + looking func(module, fp string) bool + // judge reads the registries' record of a reservation's artifacts at its version (the republisher's Held); nil reads none. + judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) // say says package-published on the seat mesh-builds; nil says none. say func(context.Context, meshbuilds.PackagePublished) error // names is each package's name as its series key names it (for Go, its module path), and sayReserved says version-reserved on @@ -186,9 +191,9 @@ func (rv *reservations) TakenOver(ctx context.Context, module, fingerprint strin return rv.r.TakenOver(ctx, module, fingerprint) } -// VersionAt is the version module's artifact is published at from the source revision of branch (H-A-547 (3), H-A-551). -func (rv *reservations) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) { - return rv.r.VersionAt(ctx, module, artifact, branch, source) +// PublishedOf answers the seat mesh-builds' published rule for the build's pins (H-A-328, design 47 H2 H-A-707 (4)). +func (rv *reservations) PublishedOf(ctx context.Context, module, artifact, fingerprint string) (meshbuilds.PublishedAnswer, error) { + return rv.r.PublishedOf(ctx, module, artifact, fingerprint) } func (rv *reservations) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) { @@ -501,22 +506,55 @@ func (rv *reservations) sayPublished(ctx context.Context, m versions.Marked, dig } } -// dropped is builder_reserved_drop: the reservation is deleted and its bound ended. -func (rv *reservations) dropped(ctx context.Context, module, series, by, why string, at time.Time) (string, error) { - cur, held, _ := rv.r.At(ctx, versions.ReservedKey(module, series)) +// dropped is builder_reserved_drop (design 47 H2 H-A-592): it names its version, and the reservation of the series is deleted whole +// only when it stands at that version and its fingerprint is not building; the publish item and the version-unreleased go with it, +// the bound ends, and the answer names what was forgotten. +func (rv *reservations) dropped(ctx context.Context, module, series, version, by, why string, at time.Time) (string, error) { + cur, held, err := rv.r.At(ctx, versions.ReservedKey(module, series)) + if err != nil { + return "", err + } + if !held { + return "", fmt.Errorf("%s holds no reservation of %s", module, series) + } + if cur.Version != version { + return "", fmt.Errorf("%s's reservation of %s stands at %s, not %s: a reservation a newer build took is never dropped", module, series, cur.Version, version) + } + if rv.looking != nil && rv.looking(module, cur.Fingerprint) { + return "", fmt.Errorf("the build of %s at %s, which holds %s, is building: drop it when that build ends or its ask is dropped (builder_stuck reads it)", module, cur.Fingerprint, version) + } + atRegistries := "the registries' record was not read" + if rv.judge != nil { + if j, jerr := rv.judge(ctx, cur); jerr == nil { + var names []string + for _, h := range append(append([]versions.HeldArtifact{}, j.Held...), j.Elsewhere...) { + names = append(names, h.Seat+" "+h.Name) + } + atRegistries = "the registries keep " + strings.Join(names, ", ") + " at it, a gap the next reserve skips" + if len(names) == 0 { + atRegistries = "no registry holds an artifact at it" + } + } + } ok, err := rv.r.Drop(ctx, module, series) if err != nil { return "", err } - if ok && held && rv.itemEnded != nil { - rv.itemEnded(ctx, module, cur.Version) // its publish item goes with its reservation (A-456b), its items terminated (§793) - } if !ok { return "", fmt.Errorf("%s holds no reservation of %s", module, series) } + if rv.itemEnded != nil { + rv.itemEnded(ctx, module, cur.Version) // its publish item goes with its reservation (A-456b), its items terminated (§793) + } rv.dropBound(ctx, versions.ReservedKey(module, series)) rv.found.clear(ctx, versions.VersionUnreleased, meshconditionsclient.ScopeModule, module) - return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s)", module, series, by, why), nil + withdrawn := make([]string, 0, len(cur.Withdrawn)) + for v := range cur.Withdrawn { + withdrawn = append(withdrawn, v) + } + sort.Strings(withdrawn) + return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s): forgot version %s of fingerprint %s, %d recorded digests, withdrawn numbers %v and its publish item and version-unreleased; %s", + module, series, by, why, cur.Version, cur.Fingerprint, len(cur.Artifacts), withdrawn, atRegistries), nil } // noMark says why a published marked nothing, from the reservations the published read (design 47 H H-A-280: no second read): @@ -544,35 +582,49 @@ func (rv *reservations) noMark(ctx context.Context, o versions.Outcome, read []v return strings.Join(out, "; ") + " (" + standing + "; a published heard before the build recorded its digests is kept until it does)" } -// reserveDoneAct is builder_reserve_done's act (design 47 G A-455): the next version of the series is reserved for a done trunk build -// that reserved none, and its publish is queued as builder_publish_again queues it. Its answer says the version and the queued -// publishes; a reservation whose publish could not be queued is said so, with the tool that queues it. -func reserveDoneAct(reserve func(ctx context.Context, module, fp string) (versions.ReservedVersion, error), - republish func(ctx context.Context, module, version string) ([]string, error), logf func(string, ...any)) func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) { - return func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) { - res, err := reserve(ctx, module, fp) - if err != nil { - return "", err - } - logf("%s at %s: version %s is reserved by hand (%s, %s) for the done build", module, fp, res.Version, by, why) - queued, err := republish(ctx, module, res.Version) - if err != nil { - return "", fmt.Errorf("%s is reserved for %s at %s, but its publish is not queued (builder_publish_again queues it): %w", res.Version, module, fp, err) - } - return fmt.Sprintf("reserved %s for %s at %s and queued %d versions to publish: %s; builder_publish_queue shows them", res.Version, module, fp, len(queued), strings.Join(queued, ", ")), nil - } -} - // ReleasedFor says whether a version was released for the build of fingerprint (design 47 G A-456a). func (rv *reservations) ReleasedFor(ctx context.Context, module, fingerprint string) (bool, error) { return rv.r.ReleasedFor(ctx, module, fingerprint) } +// MarkRegistryHeld reads the registries' record of v's artifacts and writes the held digest of each artifact a registry holds at v's version +// for the build's fingerprint on the reservation, marked published, and says package-published of each once (design 47 H2 H-A-588 +// (4)); what the registries do not hold loses its recorded digest (H-A-664). A read that does not answer is said and nothing is +// written, so the build goes on. +func (rv *reservations) MarkRegistryHeld(ctx context.Context, v versions.ReservedVersion) { + if rv.judge == nil { + return + } + j, err := rv.judge(ctx, v) + if err != nil { + rv.logf("%s %s: the registries' record of its artifacts is not read before the build module is asked again, so none is marked held: %v", v.Module, v.Version, err) + return + } + marked, _, err := rv.r.MarkHeld(ctx, v.Module, v.Version, j.Held) + if err != nil { + rv.logf("%s %s: what the registries hold is not written on the reservation: %v", v.Module, v.Version, err) + return + } + for _, m := range marked { + var held versions.HeldArtifact + for _, h := range j.Held { + if h.Ref == m.Artifact { + held = h + } + } + rv.logf("%s %s: %s holds %s %s at %s for this build: marked published from its record before the build is asked again", v.Module, v.Version, held.Seat, held.Name, held.Version, held.Digest) + rv.sayPublished(ctx, m, held.Digest) + } +} + // markHeld marks the artifacts the registries' record holds at their version with the built digest published, as their published // heard would, and says package-published of each (design 47 H H-A-274): a published heard and lost never leaves the publish // asked for ever. The version's release follows from the catalog as for any published. func (rv *reservations) markHeld(ctx context.Context, v versions.ReservedVersion, held []versions.HeldArtifact) { for _, h := range held { + if v.Published[h.Ref] { + continue // marked already: its package-published was said (design 47 H2 H-A-588 (4): once) + } rv.logf("%s %s: %s holds %s %s with the built digest %s: marked published from its record", v.Module, v.Version, h.Seat, h.Name, h.Version, h.Digest) rv.published(ctx, versions.Outcome{Name: h.Name, Version: h.Version, Digest: h.Digest, Holder: h.Seat}, nil) } @@ -605,11 +657,40 @@ func (rv *reservations) movedElsewhere(ctx context.Context, v versions.ReservedV } return err } - var at []string - for _, h := range j.Elsewhere { - at = append(at, fmt.Sprintf("%s holds %s %s at %s, built %s", h.Seat, h.Name, h.Version, h.Digest, v.Artifacts[h.Ref])) - } - why := fmt.Sprintf("%s is withdrawn and the build of %s is built again at the next free number: %s", v.Version, v.Fingerprint, strings.Join(at, "; ")) + why := elsewhereWords(v, j.Elsewhere) rv.heldElsewhere(ctx, v.Module, why) return rv.rebuild(ctx, v.Module, v.Fingerprint, why) } + +// elsewhereWords says what withdrew v's number: each artifact a registry holds there for another build, with the seat, both digests and +// the fingerprint the registry keeps for it when one is kept (design 47 H2 H-A-590 (1), H-A-279). +func elsewhereWords(v versions.ReservedVersion, elsewhere []versions.HeldArtifact) string { + var at []string + for _, h := range elsewhere { + w := fmt.Sprintf("%s holds %s %s at %s, built %s", h.Seat, h.Name, h.Version, h.Digest, v.Artifacts[h.Ref]) + if h.Fingerprint != "" { + w += ", for fingerprint " + h.Fingerprint + } + at = append(at, w) + } + return fmt.Sprintf("%s is withdrawn and the build of %s is built again at the next free number: %s", v.Version, v.Fingerprint, strings.Join(at, "; ")) +} + +// unstoredAgain builds a key again whose reservation's first artifact a holder refused as not stored (design 47 H2 H-A-662): the +// build under its standing version completes what the registries lack, as the person's builder_build_again would. A key the +// build again refuses (not a first branch's trunk build, or released) is said and left to the person's tool. +func (rv *reservations) unstoredAgain(ctx context.Context, v versions.ReservedVersion, ref, words string) { + if rv.rebuild == nil { + return + } + why := fmt.Sprintf("%s refused by its holder as not stored (%s): the build of %s is built again under %s", ref, words, v.Fingerprint, v.Version) + if err := rv.rebuild(ctx, v.Module, v.Fingerprint, why); err != nil { + rv.logf("%s %s: the build again is not started: %v; builder_build_again builds it", v.Module, v.Version, err) + } +} + +// movedFrom is told by the reserver a standing number it withdrew at a build again (design 47 H2 H-A-590 (1)): the finding is raised; +// the reserve itself takes the next number no registry holds. +func (rv *reservations) movedFrom(ctx context.Context, v versions.ReservedVersion, elsewhere []versions.HeldArtifact) { + rv.heldElsewhere(ctx, v.Module, elsewhereWords(v, elsewhere)) +} 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 456d21c62..45b8e01f8 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 @@ -7,7 +7,6 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" "slices" "strings" - "sync/atomic" "testing" "time" @@ -19,8 +18,8 @@ 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" 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" ) @@ -143,13 +142,14 @@ func TestTheCatalogsWordsMoveTheReservations(t *testing.T) { if all, _ := rv.r.All(ctx); len(all) != 0 || bounds.keys[boundKey] || len(st.vals) != 0 { t.Errorf("after version-released: reservations %v, bounds %v, findings %v; want none", all, bounds.keys, st.vals) } - if _, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}); err != nil { + again, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}) + if err != nil { t.Fatal(err) } - if answer, err := rv.dropped(ctx, "m", "1.4", "op", "never released", time.Unix(0, 0)); err != nil || !strings.Contains(answer, "dropped") { + if answer, err := rv.dropped(ctx, "m", "1.4", again.Version, "op", "never released", time.Unix(0, 0)); err != nil || !strings.Contains(answer, "dropped") { t.Errorf("builder_reserved_drop: %q (%v)", answer, err) } - if _, err := rv.dropped(ctx, "m", "1.4", "op", "again", time.Unix(0, 0)); err == nil { + if _, err := rv.dropped(ctx, "m", "1.4", again.Version, "op", "again", time.Unix(0, 0)); err == nil { t.Error("a reservation that is gone was dropped again") } } @@ -666,62 +666,6 @@ func (e ansEntry) Revision() uint64 { return 1 } func (e ansEntry) Value() []byte { return e.value } func (e ansEntry) Operation() jetstream.KeyValueOp { return jetstream.KeyValuePut } -// TestAReserveDoneIsAnsweredWithTheVersionAndItsQueuedPublish: design 47 G A-455 — the reasks value of builder_reserve_done reaches -// the act, which reserves for the done build and queues the publish as publish again does, and its answer names both; a -// refusal of the reserving queues nothing and is the answer; a publish that cannot be queued says the version is reserved. -func TestAReserveDoneIsAnsweredWithTheVersionAndItsQueuedPublish(t *testing.T) { - ctx := context.Background() - var queued []string - var logged []string - logf := func(f string, a ...any) { logged = append(logged, fmt.Sprintf(f, a...)) } - reserve := func(_ context.Context, module, fp string) (versions.ReservedVersion, error) { - if fp == "refused" { - return versions.ReservedVersion{}, fmt.Errorf("the build key of %s at %s is not done", module, fp) - } - return versions.ReservedVersion{Module: module, Version: "0.1.13", Fingerprint: fp}, nil - } - republish := func(_ context.Context, module, version string) ([]string, error) { - if module == "nope" { - return nil, fmt.Errorf("the queue is full") - } - queued = append(queued, module+"@"+version) - return []string{module + "@" + version}, nil - } - acts := versions.Acts{ReserveDone: reserveDoneAct(reserve, republish, logf)} - for _, c := range []struct { - module, fp, want string - refused bool - }{ - {"node-tools", "src2:7df8", "reserved 0.1.13 for node-tools at src2:7df8 and queued 1 versions to publish: node-tools@0.1.13", false}, - {"node-tools", "refused", "not done", true}, - {"nope", "src2:1", "0.1.13 is reserved for nope at src2:1, but its publish is not queued", true}, - } { - value, err := json.Marshal(build.ReAsk{V: 1, Why: "w", By: "me", Mode: build.ModeReserveDone, Name: c.module, FP: c.fp}) - if err != nil { - t.Fatal(err) - } - kv := &ansKV{wrote: make(chan []byte, 1)} - // reAsked sends a reserve-done to the version acts (b is not asked), and the answer is written back to the key. - reAsked(ctx, nil, acts, nil, kv, ansEntry{key: "reserve-done." + c.module, value: value}, logf) - var wrote []byte - select { - case wrote = <-kv.wrote: - case <-time.After(10 * time.Second): - t.Fatalf("%s at %s: no answer was written to the key", c.module, c.fp) - } - var got build.ReAsk - if err := json.Unmarshal(wrote, &got); err != nil || got.Refused != c.refused || !strings.Contains(got.Answer, c.want) || got.Answered.IsZero() { - t.Errorf("%s at %s: written %s (%v), want refused=%v containing %q", c.module, c.fp, wrote, err, c.refused, c.want) - } - } - if !slices.Equal(queued, []string{"node-tools@0.1.13"}) { - t.Errorf("queued %v, want only node-tools@0.1.13", queued) - } - if !slices.ContainsFunc(logged, func(l string) bool { return strings.Contains(l, "0.1.13 is reserved by hand") }) { - t.Errorf("the reserving by hand is not said in the log: %q", logged) - } -} - // 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 @@ -742,7 +686,13 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) { rv.released = func(_ context.Context, m, v string) { ended = append(ended, m+" "+v) } rv.itemEnded = rv.released // a build withdrawn or superseded ends its publish item too (§793) registry := []string{"0.1.37"} - rv.r.HeldNumbers = func(context.Context, string, string, []string) ([]string, error) { return registry, nil } + rv.r.HeldRecords = func(context.Context, string, string, []string) ([]versions.HeldArtifact, error) { + var out []versions.HeldArtifact + for _, v := range registry { + out = append(out, versions.HeldArtifact{Version: v}) + } + return out, nil + } res, err := rv.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, versions.Source{Fingerprint: "fp1"}) if err != nil || res.Version != "0.1.0" { t.Fatalf("reserved %q (%v)", res.Version, err) @@ -925,62 +875,35 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) { }) } -// Design 47 H2 H-A-514 addenda: each event goes to the worker of the name it carries, so a slow handling of one name holds -// no other name's events, one name's events are handled in the order heard, and an event waiting in its worker's queue is -// said in progress at each tick, so the bus does not give it again. -func TestEventsAreHandledByAWorkerPerName(t *testing.T) { - pub := func(name, v string) *queuedEvent { - return &queuedEvent{wakeMsg: wakeMsg{subject: gopackageregistry.SubjectPublished, data: []byte(`{"name":"` + name + `","version":"` + v + `","digest":"sha256:aa"}`)}} - } - if got := eventKey(&pub("a", "1").wakeMsg); got != "name a" { - t.Errorf("a published's key is %q, want its name", got) - } - if got := eventKey(&wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"module":"m","version":"0.1.0"}`)}); got != "module m" { - t.Errorf("a version-released's key is %q, want its module", got) - } - if got := eventKey(&wakeMsg{subject: "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", data: []byte(`{}`)}); got != "" { - t.Errorf("an event naming no name has the key %q, want the shared worker's", got) - } - release := make(chan struct{}) - handled := make(chan string, 4) - w := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) { - var o versions.Outcome - _ = json.Unmarshal(m.Data(), &o) - if o.Name == "a" && o.Version == "1" { - <-release +// Design 47 H2 H-A-683 (1), H-A-737 (1): the builder gives the hub each pattern's key: a registry seat's outcome by its name, +// version-released by its module, the seat node-engine's running and manifest-reads-changed by the node their subject names; +// the hub holds one key's events in order and the keys side by side (mesh-sdk's tests). +func TestEventsAreHeldByTheKeyTheyName(t *testing.T) { + for _, c := range []struct { + name, subject, body, want string + }{ + {"a registry seat's outcome by its name", gopackageregistry.SubjectPublished, `{"name":"a","version":"1","digest":"sha256:aa"}`, "name a"}, + {"a version-released by its module", meshcatalog.SubjectVersionReleased, `{"module":"m","version":"0.1.0"}`, "module m"}, + {"a running by its node", "mesh.seat.node-engine.event.running.ace.mod", `{}`, "node ace"}, + {"a manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.g14", `{}`, "node g14"}, + {"another node's manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.ace", `{}`, "node ace"}, + {"another event of the seat node-engine shares", "mesh.seat.node-engine.event.composed.ace", `{}`, ""}, + {"an event naming none shares", "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", `{}`, ""}, + } { + if got := eventKey(c.subject, []byte(c.body)); got != c.want { + t.Errorf("%s: the key is %q, want %q", c.name, got, c.want) } - handled <- o.Name + "@" + o.Version - }} - a1, a2, a3, b1 := pub("a", "1"), pub("a", "2"), pub("a", "3"), pub("b", "1") - w.take(a1) - w.take(a2) - w.take(a3) - w.take(b1) - if got := <-handled; got != "b@1" { - t.Fatalf("handled %s first, want b's event while a's first one is slow", got) - } - close(release) - if got := []string{<-handled, <-handled, <-handled}; !slices.Equal(got, []string{"a@1", "a@2", "a@3"}) { - t.Errorf("a's events handled %v, want in the order heard", got) - } - // a's worker said its waiting events in progress at each end: a2 and a3 after a1, a3 again after a2. - if a1.progressed.Load() != 0 || a2.progressed.Load() != 1 || a3.progressed.Load() != 2 { - t.Errorf("in progress said %d, %d and %d times of a's events, want 0, 1 and 2", a1.progressed.Load(), a2.progressed.Load(), a3.progressed.Load()) } } -// queuedEvent is an event of the builder's durable that counts its in-progress. -type queuedEvent struct { - wakeMsg - progressed atomic.Int32 -} - -func (m *queuedEvent) InProgress() error { m.progressed.Add(1); return nil } - // oneHandler is an event hub with one handler. type oneHandler struct{ handle func(jetstream.Msg) } func (h *oneHandler) Handle(_ string, f func(jetstream.Msg)) error { h.handle = f; return nil } +func (h *oneHandler) HandleByKey(_ string, _ process.EventKey, f func(jetstream.Msg)) error { + h.handle = f + return nil +} // agedTestMsg is a message of the builder's events consumer, with the metadata a ledger reads. type agedTestMsg struct { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/retake.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/retake.go index 5163558e2..95644b4ed 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/retake.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/retake.go @@ -8,6 +8,7 @@ import ( "github.com/nats-io/nats.go/jetstream" "mesh-delivery-builder/internal/build" + "mesh-delivery-builder/internal/versions" ) // The builder's retake of a key failed on a transport fault, on the node-engine seat's events (design 47 G §568, ADR 0673): the @@ -87,3 +88,26 @@ func (d *decisions) heard(m jetstream.Msg) bool { d.handle(m) return true } + +// publishingAgain is the builder's publish again on ADR 0674 §2's events (design 47 H2 H-A-606): the wiring of versions.Againer to the +// events consumer. +type publishingAgain struct{ a *versions.Againer } + +// heard hands a message of the events consumer to the publish again: one whose state cannot take it is left for the bus to give +// again (Nak); every message goes on to the other parts. +func (g *publishingAgain) heard(ctx context.Context, m jetstream.Msg, logf func(string, ...any)) (stop bool) { + meta, err := m.Metadata() + if err != nil { + return false + } + handled, err := g.a.Heard(ctx, m.Subject(), m.Data(), meta.Sequence.Stream) + if handled && err != nil { + logf("%v; heard again", err) + if nakErr := m.Nak(); nakErr != nil { + logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr) + } + givenUp(m, "its event", err, logf) + return true + } + return false +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go index 0ac59ccad..cf1a2bc98 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" "errors" + "fmt" + "slices" + "strconv" "time" "github.com/nats-io/nats.go" @@ -11,6 +14,7 @@ import ( "git.novox.be/novox/mesh-sdk/go/process" + "mesh-delivery-builder/internal/build" "mesh-delivery-builder/internal/versions" ) @@ -123,3 +127,144 @@ func emitSeatEvent(ctx context.Context, js jetstream.JetStream, cred process.Acc _, err = js.PublishMsg(pub, msg, jetstream.WithMsgID(id)) return err } + +// markLifetime writes the marks of the state acted with the bus's per-message lifetime of the setting acted-days, each write giving +// it again (design 47 H2 H-A-720 (1)); the release record and every other key it writes with none (H-A-720 (2)). An update is the +// one publish carrying the lifetime and the expected last sequence of the key (H-A-741). +type markLifetime struct { + awaitedReserved + days int + js jetstream.JetStream +} + +func (s markLifetime) life(key string) (time.Duration, bool) { + if mark, _ := versions.ActedFormOf(key); mark { + return time.Duration(s.days) * 24 * time.Hour, true + } + return 0, false +} + +func (s markLifetime) Create(ctx context.Context, key string, value []byte) (uint64, error) { + ttl, ok := s.life(key) + if !ok { + return s.awaitedReserved.Create(ctx, key, value) + } + kv, err := s.kv() + if err != nil { + return 0, err + } + rev, err := kv.Create(ctx, key, value, jetstream.KeyTTL(ttl)) + return rev, versionsConflict(err) +} + +func (s markLifetime) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) { + ttl, ok := s.life(key) + if !ok { + return s.awaitedReserved.Update(ctx, key, value, revision) + } + kv, err := s.kv() + if err != nil { + return 0, err + } + _ = kv + return updateWithLifetime(ctx, s.js, s.bucket, key, value, revision, ttl) +} + +// updateWithLifetime is one publish to the key's subject carrying the per-message lifetime and the expected last sequence of the +// key: the compare-and-set update that gives the lifetime again (design 47 H2 H-A-741). +func updateWithLifetime(ctx context.Context, js jetstream.JetStream, bucket, key string, value []byte, revision uint64, ttl time.Duration) (uint64, error) { + msg := nats.NewMsg("$KV." + bucket + "." + key) + msg.Data = value + msg.Header.Set("Nats-TTL", fmt.Sprintf("%ds", int64(ttl/time.Second))) + msg.Header.Set("Nats-Expected-Last-Subject-Sequence", strconv.FormatUint(revision, 10)) + ack, err := js.PublishMsg(ctx, msg) + if err != nil { + var apiErr *jetstream.APIError + if errors.As(err, &apiErr) && apiErr.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequence { + return 0, versions.ErrConflict + } + return 0, err + } + return ack.Sequence, nil +} + +// deleteUnknown deletes each key of the state acted of a form the builder does not write (design 47 H2 H-A-720 (3)) and says the +// count once. +func deleteUnknown(ctx context.Context, kv jetstream.KeyValue, logf func(string, ...any)) { + l, err := kv.ListKeys(ctx) + if err != nil { + logf("the keys of the state %s are not listed, so none of no form is deleted: %v", versions.ActedState, err) + return + } + var gone []string + for k := range l.Keys() { + if _, known := versions.ActedFormOf(k); !known { + gone = append(gone, k) + } + } + _ = l.Stop() + n := 0 + for _, k := range gone { + if err := kv.Delete(ctx, k); err != nil { + logf("the key %s of the state %s, of no form the builder writes, is not deleted: %v", k, versions.ActedState, err) + continue + } + n++ + } + if len(gone) > 0 { + logf("the state %s: %d keys of no form the builder writes were deleted at the start", versions.ActedState, n) + } +} + +// carryDrops is the builder's start of the re-ask state (design 47 H2 H-A-749 (2)): each answered publish-drop ask is carried onto +// its version's reservation as dropped (the ask's by, why and at) where the reservation stands and holds none, so a drop made before +// is kept; then each record of mode publish, whose readers are gone, is deleted. It says the counts once. +func carryDrops(ctx context.Context, kv jetstream.KeyValue, r *versions.Reserver, logf func(string, ...any)) { + l, err := kv.ListKeys(ctx) + if err != nil { + logf("the keys of the state %s are not listed, so no earlier drop is carried and no publish record deleted: %v", build.ReAsksState, err) + return + } + var keys []string + for k := range l.Keys() { + keys = append(keys, k) + } + _ = l.Stop() + slices.Sort(keys) + var carried, deleted int + var records []string + for _, k := range keys { + e, err := kv.Get(ctx, k) + if err != nil { + continue + } + ask, err := build.DecodeReAsk(e.Value()) + if err != nil { + continue + } + switch { + case ask.Mode == "publish": // the record of a version's publish item, written before H-A-746 + records = append(records, k) + case ask.Mode == build.ModePublishDrop && !ask.Answered.IsZero() && !ask.Refused: + v, found, err := r.Of(ctx, ask.Module, ask.Version) + if err != nil || !found || v.Dropped != nil { + continue + } + if ok, err := r.MarkDropped(ctx, ask.Module, ask.Version, ask.By, ask.Why, ask.At); err != nil { + logf("the drop of %s %s by %s is not carried onto its reservation: %v", ask.Module, ask.Version, ask.By, err) + } else if ok { + carried++ + } + } + } + for _, k := range records { + if err := kv.Delete(ctx, k); err != nil { + logf("the publish record %s of the state %s is not deleted: %v", k, build.ReAsksState, err) + continue + } + deleted++ + } + if carried > 0 || deleted > 0 { + logf("the state %s at the start: %d earlier drops carried onto their reservations as dropped, %d publish records deleted", build.ReAsksState, carried, deleted) + } +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits.go index e3781b5d9..21a047804 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits.go @@ -27,9 +27,16 @@ type waitBody struct { Since time.Time `json:"since"` Bound string `json:"bound,omitempty"` How string `json:"how,omitempty"` + // Publisher, Revision and Until are a pin wait's (design 47 H2 H-A-707 (5), DQ-53). + Publisher string `json:"publisher,omitempty"` + Revision int64 `json:"revision,omitempty"` + Until time.Time `json:"until,omitzero"` } -const waitStepBuilding = "building" +const ( + waitStepBuilding = "building" + waitStepBuild = "build" +) // waitsKept keeps the builder's toolchain waits in its old state waits, one key . (design 47 G §672), // and says wait-held and wait-ended on its old stream waits; at its start it says wait-held again for every key. @@ -48,7 +55,24 @@ func newWaitsKept(kv *process.AwaitedBucket, say func(context.Context, string, s } func (w *waitsKept) body(t build.ToolchainWait, how string) waitBody { - return waitBody{Step: waitStepBuilding, On: t.On(), Part: t.Package, Module: t.Module, Fingerprint: t.Fingerprint, Since: t.Since, Bound: w.bound.String(), How: how} + b := waitBody{Step: waitStepBuilding, On: t.On(), Part: t.Package, Module: t.Module, Fingerprint: t.Fingerprint, Since: t.Since, Bound: w.bound.String(), How: how, + Publisher: t.Publisher, Until: t.Until} + if !t.Until.IsZero() { // a pin wait says the bound of `package-wait-minutes`, which it carries, and the revision it holds + b.Bound, b.Revision = t.Bound, t.Revision + } + if t.IsRevision() { // a step ask's wait for its revision: `step` build, its own bound (design 47 H2 H-A-577 (1)) + b.Step, b.Bound = waitStepBuild, t.Bound + } + return b +} + +// slotOf is the part of a wait's key and subject after `.`: a revision wait keeps its own, so it is told apart +// from that key's toolchain wait. +func slotOf(t build.ToolchainWait) string { + if t.IsRevision() { + return ".revision" + } + return "" } // start reads the state whole and says wait-held again for each key. @@ -76,26 +100,33 @@ func (w *waitsKept) start(ctx context.Context, kv jetstream.KeyValue) { } func (w *waitsKept) said(ctx context.Context, event string, t build.ToolchainWait, how string) { - if err := w.say(ctx, event+"."+t.Module+"."+t.Fingerprint, event+"-"+t.Module+"-"+t.Fingerprint+"-"+t.Since.UTC().Format(time.RFC3339Nano)+how, w.body(t, how)); err != nil { + if err := w.say(ctx, event+"."+t.Module+"."+t.Fingerprint+slotOf(t), event+"-"+t.Module+"-"+t.Fingerprint+slotOf(t)+"-"+t.Since.UTC().Format(time.RFC3339Nano)+how, w.body(t, how)); err != nil { w.logf("saying %s of %s at %s: %v", event, t.Module, t.Fingerprint, err) } } -// Hold keeps the wait and says wait-held, once. +// Hold keeps the wait and says wait-held, once. A key holds the build's one current wait (design 47 H2 H-A-723 (1)): a Hold over a +// standing wait of another kind or other fields ends that wait, said wait-ended with how replaced, and holds the new one; a Hold equal +// to the standing wait changes nothing. func (w *waitsKept) Hold(ctx context.Context, t build.ToolchainWait) { key, err := builds.BuilderBuildKey(t.Module, t.Fingerprint) if err != nil { w.logf("a wait of %s at %s has no key: %v", t.Module, t.Fingerprint, err) return } + key += slotOf(t) w.mu.Lock() - if _, had := w.held[key]; had { + old, had := w.held[key] + if had && old.SameWait(t) { w.mu.Unlock() return } w.held[key] = t w.mu.Unlock() - if kv := w.kv.KV(); kv != nil { + if had { + w.said(ctx, "wait-ended", old, build.WaitReplaced) + } + if kv := w.bucket(); kv != nil { data, _ := json.Marshal(t) if _, err := kv.Put(ctx, key, data); err != nil { w.logf("%s.%s could not be written, so the wait is kept in memory only: %v", build.WaitsState, key, err) @@ -106,14 +137,25 @@ func (w *waitsKept) Hold(ctx context.Context, t build.ToolchainWait) { // End deletes the wait and says wait-ended with how; it answers whether one was held. func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool { + return w.end(ctx, module, fp, "", how) +} + +// EndRevision ends the revision wait of module's fingerprint, kept under its own key. +func (w *waitsKept) EndRevision(ctx context.Context, module, fp, how string) bool { + return w.end(ctx, module, fp, ".revision", how) +} + +func (w *waitsKept) end(ctx context.Context, module, fp, slot, how string) bool { key, err := builds.BuilderBuildKey(module, fp) if err != nil { return false } + key += slot w.mu.Lock() t, had := w.held[key] - // A key queued behind a package ends only when it is published, and a toolchain wait never by that (design 47 G A-192). - if had && (t.Package != "") != (how == build.WaitPublished) { + // A key queued behind a package ends only when it is published, and a toolchain wait never by that (design 47 G A-192); a wait + // ended failed is ended whatever its kind (design 47 H2 H-A-723 (2)). + if had && slot == "" && how != build.WaitFailed && (t.Package != "") != (how == build.WaitPublished) { had = false } if had { @@ -123,7 +165,7 @@ func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool { if !had { return false } - if kv := w.kv.KV(); kv != nil { + if kv := w.bucket(); kv != nil { if err := kv.Delete(ctx, key); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) { w.logf("%s.%s could not be deleted: %v", build.WaitsState, key, err) } @@ -131,3 +173,11 @@ func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool { w.said(ctx, "wait-ended", t, how) return true } + +// bucket is the state waits once it is on the bus; none before, and none for a form kept in memory alone. +func (w *waitsKept) bucket() jetstream.KeyValue { + if w.kv == nil { + return nil + } + return w.kv.KV() +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits_test.go index b21a290fb..dd5f2086f 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/waits_test.go @@ -1,6 +1,9 @@ package main import ( + "context" + "slices" + "strings" "testing" "time" @@ -18,4 +21,50 @@ func TestAWaitBodyNamesItsPart(t *testing.T) { if tc := w.body(build.ToolchainWait{Module: "m", Fingerprint: "src2:f", Language: "go", Version: "go1.26.0"}, ""); tc.Part != "" || tc.On != "toolchain:go@go1.26.0" { t.Errorf("a toolchain wait says %+v", tc) } + // H2 H-A-577 (1): a revision wait says `step` build, `on` revision: and its own bound, under the subject token `.revision` + rev := build.ToolchainWait{Module: "m", Fingerprint: "src2:f", Kind: build.WaitKindRevision, Revision: 7, Bound: "2m0s"} + if rv := w.body(rev, ""); rv.Step != "build" || rv.On != "revision:7" || rv.Bound != "2m0s" || slotOf(rev) != ".revision" || slotOf(build.ToolchainWait{}) != "" { + t.Errorf("a revision wait says %+v, slot %q", rv, slotOf(rev)) + } } + +// Design 47 H2 H-A-723, H-A-707 (5), DQ-53 (H-A-717): a key holds one wait. A pin wait held over a toolchain wait ends it as `replaced` +// and stands; an equal Hold writes nothing; a pin wait ended `failed` is deleted; its body says `package-wait-minutes` as its bound +// and carries publisher, revision and until, the package its path alone. +func TestAKeyHoldsTheBuildsOneWait(t *testing.T) { + var said []string + var bodies []waitBody + w := newWaitsKept(nil, func(_ context.Context, event, _ string, body any) error { + said = append(said, strings.SplitN(event, ".", 2)[0]) + bodies = append(bodies, body.(waitBody)) + return nil + }, time.Hour, t.Logf) + ctx := context.Background() + since := time.Unix(100, 0) + tc := build.ToolchainWait{Module: "m", Fingerprint: fpw, Language: "go", Version: "go1.26.0", Since: since} + pin := build.ToolchainWait{Module: "m", Fingerprint: fpw, Package: "git.x/y/sdk", Publisher: "sdk@src2:p", Revision: 7, Bound: "10m0s", Since: since, Until: since.Add(10 * time.Minute)} + w.Hold(ctx, tc) + w.Hold(ctx, tc) + if !slices.Equal(said, []string{"wait-held"}) { + t.Fatalf("a toolchain wait held twice said %v, want one wait-held", said) + } + w.Hold(ctx, pin) + if !slices.Equal(said, []string{"wait-held", "wait-ended", "wait-held"}) || bodies[1].How != build.WaitReplaced || bodies[1].On != "toolchain:go@go1.26.0" { + t.Fatalf("a pin wait over a toolchain wait said %v, %+v, want the toolchain wait ended replaced", said, bodies) + } + if p := bodies[2]; p.Bound != "10m0s" || p.Publisher != "sdk@src2:p" || p.Revision != 7 || !p.Until.Equal(pin.Until) || p.Part != "git.x/y/sdk" || p.On != "package:git.x/y/sdk" { + t.Errorf("the pin wait says %+v", p) + } + w.Hold(ctx, pin) + if len(said) != 3 { + t.Errorf("a Hold equal to the standing wait said %v, want nothing", said[3:]) + } + if w.End(ctx, "m", fpw, build.WaitRan) { + t.Error("a pin wait ended ran") + } + if !w.End(ctx, "m", fpw, build.WaitFailed) || len(w.held) != 0 || bodies[len(bodies)-1].How != build.WaitFailed { + t.Errorf("a pin wait ended failed: held %v, said %v", w.held, said) + } +} + +var fpw = "src2:" + strings.Repeat("a", 64) diff --git a/modules/mesh-delivery-builder/internal/build/buildread_test.go b/modules/mesh-delivery-builder/internal/build/buildread_test.go index 5602a5874..3eb6cf544 100644 --- a/modules/mesh-delivery-builder/internal/build/buildread_test.go +++ b/modules/mesh-delivery-builder/internal/build/buildread_test.go @@ -106,4 +106,13 @@ func TestBuilderStuckAnswersTheFingerprintWhole(t *testing.T) { if len(rows) != 1 || rows[0].FP != fp1 { t.Fatalf("stuck = %+v, want the fingerprint %s whole", rows, fp1) } + // design 47 H2 H-A-707 (5): a key building with no ask names the wait the state waits holds for it + pin, _ := json.Marshal(ToolchainWait{Module: "m", Fingerprint: fp1, Package: "git.x/y/sdk", Publisher: "sdk@src2:p", Revision: 7}) + out, err = StuckReader{Builds: stateOf(map[string][]byte{k: building}), Waits: stateOf(map[string][]byte{k: pin})}.Stuck("m") + if err != nil { + t.Fatal(err) + } + if rows = out["stuck"].([]Stuck); len(rows) != 1 || len(rows[0].Waits) != 1 || rows[0].Waits[0].Publisher != "sdk@src2:p" || rows[0].Waits[0].Package != "git.x/y/sdk" { + t.Errorf("a key building with no ask: stuck = %+v, want its pin wait", rows) + } } diff --git a/modules/mesh-delivery-builder/internal/build/faulted.go b/modules/mesh-delivery-builder/internal/build/faulted.go new file mode 100644 index 000000000..20659cb01 --- /dev/null +++ b/modules/mesh-delivery-builder/internal/build/faulted.go @@ -0,0 +1,113 @@ +package build + +import ( + "context" + "sort" + "sync" + + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" +) + +// Faulted is the set of build keys whose newest revision failed on a transport fault, with the seat and node the fault names +// (design 47 H2 H-A-683 (2), H-A-696): filled by the start sweep (Builder.Sweep) and kept by every write of a build (the store +// Builder.init wraps), held in memory so that an event retakes only the keys whose seat or node it names, and lists no key of the +// bucket. An event heard before the sweep has filled the set waits (WaitFilled) until it has. +type Faulted struct { + mu sync.Mutex + revs map[string]uint64 // the newest revision noted of each key, so that an older read never replaces a newer write + faults map[string]fault + filled chan struct{} + once sync.Once +} + +type fault struct{ seat, node string } + +func newFaulted() *Faulted { + return &Faulted{revs: map[string]uint64{}, faults: map[string]fault{}, filled: make(chan struct{})} +} + +// note keeps what key holds at revision rev: in the set when it failed on a transport fault, else out of it. +func (f *Faulted) note(key string, value []byte, rev uint64) { + var fl fault + in := false + if v, err := builds.DecodeBuilderBuild(value); err == nil && v.State == builds.BuildFailed { + _, seat, node, _, ok := builds.TransportFaultOf(v.Error) + fl, in = fault{seat, node}, ok + } + f.mu.Lock() + defer f.mu.Unlock() + if rev < f.revs[key] { + return + } + f.revs[key] = rev + if in { + f.faults[key] = fl + } else { + delete(f.faults, key) + } +} + +// Fill says the start sweep has read every key, and returns how many keys the set holds. +func (f *Faulted) Fill() int { + f.once.Do(func() { close(f.filled) }) + return f.Len() +} + +// Len is how many keys the set holds. +func (f *Faulted) Len() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.faults) +} + +// WaitFilled returns once the start sweep has filled the set, or ctx ends. +func (f *Faulted) WaitFilled(ctx context.Context) error { + select { + case <-f.filled: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// Matching are the keys of the set whose seat and node want says passed, in order. +func (f *Faulted) Matching(want func(seat, node string) bool) []string { + f.mu.Lock() + defer f.mu.Unlock() + var out []string + for k, fl := range f.faults { + if want(fl.seat, fl.node) { + out = append(out, k) + } + } + sort.Strings(out) + return out +} + +// faultNoting is the builds store that notes every write in the set. +type faultNoting struct { + Store + set *Faulted +} + +func (s faultNoting) Create(ctx context.Context, key string, value []byte) (uint64, error) { + rev, err := s.Store.Create(ctx, key, value) + if err == nil { + s.set.note(key, value, rev) + } + return rev, err +} + +func (s faultNoting) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) { + rev, err := s.Store.Update(ctx, key, value, revision) + if err == nil { + s.set.note(key, value, rev) + } + return rev, err +} + +// WaitFaults returns once the start sweep has filled the set of faulted keys, or ctx ends. +func (b *Builder) WaitFaults(ctx context.Context) error { + b.init() + return b.Faults.WaitFilled(ctx) +} diff --git a/modules/mesh-delivery-builder/internal/build/numbers.go b/modules/mesh-delivery-builder/internal/build/numbers.go index 81ab181ab..01ea7b7ca 100644 --- a/modules/mesh-delivery-builder/internal/build/numbers.go +++ b/modules/mesh-delivery-builder/internal/build/numbers.go @@ -2,7 +2,6 @@ package build import ( "context" - "errors" "fmt" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" "git.novox.be/novox/mesh-sdk/go/catalogue" @@ -133,9 +132,13 @@ type Reservations interface { // TakenOver is the reservation of module's series that took the series over from the build of fingerprint, whose number // it keeps withdrawn (design 47 H H-A-226), and whether one does (H-A-244). TakenOver(ctx context.Context, module, fingerprint string) (versions.ReservedVersion, bool, error) - // VersionAt is the version module's artifact is published at from the source revision of branch: its reservation of that - // origin with the artifact published, else its release recorded at that source revision (design 47 H2 H-A-547 (3), H-A-551). - VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) + // MarkRegistryHeld reads the registries' record of v's artifacts at its version and writes on the reservation the held digest of each + // artifact a registry holds there for the build's fingerprint, marking it published, before a build module is asked for the + // fingerprint again (design 47 H2 H-A-588 (4)). A read that does not answer is said and the build goes on. + MarkRegistryHeld(ctx context.Context, v versions.ReservedVersion) + // PublishedOf is the seat mesh-builds' published rule (design 47 H-A-328): whether artifact of module built at fingerprint is + // published, and its version; the pin a blank package takes is the publisher's build in the build's revision (H2 H-A-707 (4)). + PublishedOf(ctx context.Context, module, artifact, fingerprint string) (meshbuilds.PublishedAnswer, error) } // reserves says whether a look at a trunk build is one that reserves: the build has a series of the form MAJOR.MINOR @@ -178,67 +181,3 @@ func (b *Builder) reserve(ctx context.Context, module string, m meshcatalog.Modu b.logf("%s: version %s is reserved for this build", module, res.Version) return res, true } - -// ReserveDone is builder_reserve_done (design 47 G A-455): a done trunk build of the first watched branch that reserved no -// version (its key is done, so a look never reserves for it, and a done key cannot be built again) reserves the next version of -// its series now, with the digests the done key holds, as a build that started would, and its build ends with every digest -// recorded. It answers the reserved version; the caller queues its publish (versions.Republisher). A fingerprint whose key is not -// done, whose entry no watched branch carries now, that is no first branch's, or that holds a reservation already is refused, saying which. -func (b *Builder) ReserveDone(ctx context.Context, module, fp string) (versions.ReservedVersion, error) { - b.init() - if b.Reserved == nil { - return versions.ReservedVersion{}, errors.New("this builder reserves no versions") - } - key, err := builds.BuilderBuildKey(module, fp) - if err != nil { - return versions.ReservedVersion{}, err - } - b.mu.Lock() - var m meshcatalog.ModulesByModuleValue - found := false - for hk, v := range b.heard { - if strings.HasSuffix(hk, "\x00"+module) && v.Fp2 == fp { - m, found = v, true - } - } - trunk, first := b.trunkFP[key], b.origin[key].First - b.mu.Unlock() - switch { - case !found: - return versions.ReservedVersion{}, fmt.Errorf("no watched branch carries an entry of %s at %s now, so there is nothing to reserve it from", module, fp) - case !trunk || !first: - return versions.ReservedVersion{}, fmt.Errorf("%s at %s is not the first watched branch's build: only that one reserves a version (§371)", module, fp) - } - digests := b.doneDigests(ctx, module, fp) - if digests == nil { - return versions.ReservedVersion{}, fmt.Errorf("the build key of %s at %s is not done", module, fp) - } - plan, planErr, _ := b.planOf(ctx, m.Manifest) - switch { - case planErr != nil: - return versions.ReservedVersion{}, fmt.Errorf("the plan of %s at %s cannot be read: %w", module, fp, planErr) - case len(plan.Tasks) == 0 || strings.Count(plan.Series, ".") != 1: - return versions.ReservedVersion{}, fmt.Errorf("%s at %s builds nothing or has no MAJOR.MINOR series (%q): it reserves no version", module, fp, plan.Series) - } - if cur, ok, err := b.Reserved.ReservedFor(ctx, module, fp); err != nil { - return versions.ReservedVersion{}, err - } else if ok { - return versions.ReservedVersion{}, fmt.Errorf("%s at %s holds the reservation of %s already", module, fp, cur.Version) - } - res, ok := b.reserve(ctx, module, m, plan, b.originOf(key), false) - if !ok { - return versions.ReservedVersion{}, fmt.Errorf("no version could be reserved for %s at %s (the builder's journal says why)", module, fp) - } - refs := map[string]string{} - for _, t := range plan.Tasks { - d, have := digests[t.Artifact] - if !have { - return res, fmt.Errorf("%s is reserved for %s at %s, but the done key holds no digest of %s", res.Version, module, fp, t.Artifact) - } - refs[module+":"+t.Artifact] = d - } - if err := b.Reserved.Built(ctx, module, res.Version, refs, nil); err != nil { - return res, fmt.Errorf("%s is reserved for %s at %s, but its digests are not recorded: %w", res.Version, module, fp, err) - } - return res, nil -} diff --git a/modules/mesh-delivery-builder/internal/build/reserve_test.go b/modules/mesh-delivery-builder/internal/build/reserve_test.go index 9492e6f48..0a648ab9d 100644 --- a/modules/mesh-delivery-builder/internal/build/reserve_test.go +++ b/modules/mesh-delivery-builder/internal/build/reserve_test.go @@ -34,25 +34,35 @@ type fakeReservations struct { tookBy map[string]versions.ReservedVersion // by fingerprint, the reservation that took its series over (H-A-244) held map[string]versions.ReservedVersion // by fingerprint, the reservation ReservedFor answers as it stands (H-A-492) lost error // the record of the digests fails, as a store refusing it would + marks []string // the versions MarkRegistryHeld was told, with the asks the build module had by then (H-A-588 (4)) + asked func() int atMu sync.Mutex - at map[string]string // by ":@.", the version VersionAt answers (H-A-547 (3)) + at map[string]string // by ":@", the version PublishedOf answers (H2 H-A-707 (4)) } -func (f *fakeReservations) VersionAt(_ context.Context, module, artifact, branch string, source int64) (string, bool, error) { +func (f *fakeReservations) PublishedOf(_ context.Context, module, artifact, fingerprint string) (meshbuilds.PublishedAnswer, error) { f.atMu.Lock() defer f.atMu.Unlock() - v, ok := f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)] - return v, ok, nil + v, ok := f.at[fmt.Sprintf("%s@%s", artifact, fingerprint)] + return meshbuilds.PublishedAnswer{Published: ok, Version: v}, nil } -// publishAt makes VersionAt answer version for module's artifact at the origin branch and source. -func (f *fakeReservations) publishAt(module, artifact, branch string, source int64, version string) { +// publishAt makes PublishedOf answer version for module's artifact built at fingerprint (design 47 H2 H-A-707 (4)). +func (f *fakeReservations) publishAt(module, artifact, fingerprint, version string) { f.atMu.Lock() defer f.atMu.Unlock() if f.at == nil { f.at = map[string]string{} } - f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)] = version + f.at[fmt.Sprintf("%s:%s@%s", module, artifact, fingerprint)] = version +} + +func (f *fakeReservations) MarkRegistryHeld(_ context.Context, v versions.ReservedVersion) { + n := 0 + if f.asked != nil { + n = f.asked() + } + f.marks = append(f.marks, fmt.Sprintf("%s@%d asks", v.Version, n)) } func (f *fakeReservations) TakenOver(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) { @@ -270,15 +280,16 @@ func (unreadable) Get(context.Context, string) ([]byte, uint64, bool, error) { // reasks, under a key of the reservation (never a build key), refusing a module with no MAJOR.MINOR or no why. func TestADropOfAReservationIsAReasksValueOfItsOwnKey(t *testing.T) { at := time.Unix(0, 0) - key, data, err := NewReservedDrop("m", "1.4", "never released", "op@x", at) + key, data, err := NewReservedDrop("m", "1.4", "1.4.3", "never released", "op@x", at) if err != nil || key != "reserved."+versions.ReservedKey("m", "1.4") { t.Fatalf("key %q (%v)", key, err) } - if r, err := DecodeReAsk(data); err != nil || r.Mode != ModeReservedDrop || r.Name != "m" || r.FP != "1.4" || r.By != "op@x" { + if r, err := DecodeReAsk(data); err != nil || r.Mode != ModeReservedDrop || r.Name != "m" || r.FP != "1.4" || r.Version != "1.4.3" || r.By != "op@x" { t.Errorf("value = %+v (%v)", r, err) } - for name, args := range map[string][3]string{"no module": {"", "1.4", "why"}, "no series": {"m", "1", "why"}, "three numbers": {"m", "1.4.2", "why"}, "no why": {"m", "1.4", " "}} { - if _, _, err := NewReservedDrop(args[0], args[1], args[2], "op", at); err == nil { + for name, args := range map[string][4]string{"no module": {"", "1.4", "1.4.3", "why"}, "no series": {"m", "1", "1.4.3", "why"}, "three numbers": {"m", "1.4.2", "1.4.3", "why"}, "no why": {"m", "1.4", "1.4.3", " "}, + "no version": {"m", "1.4", "", "why"}, "another series": {"m", "1.4", "1.5.3", "why"}} { + if _, _, err := NewReservedDrop(args[0], args[1], args[2], args[3], "op", at); err == nil { t.Errorf("%s: a drop was made", name) } } @@ -429,6 +440,7 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) { } r.b.Reserved = res asked := len(r.asks.Asks()) + res.asked = func() int { return len(r.asks.Asks()) - asked } got := r.b.BuildAgain(context.Background(), "m", fp1, "its publish was refused", "shanks.lead", 2*time.Second) r.b.Wait() if c.refuse != "" { @@ -447,6 +459,10 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) { if _, ok := res.built[want]; !ok || len(res.reserved) != 1 { t.Fatalf("built %v after %d reservations; want the digests recorded under the freshly reserved %s so the build's end asks its publish", res.built, len(res.reserved), want) } + // H2 H-A-588 (4): what the registries hold is marked once the version is reserved and before the build module is asked + if len(res.marks) != 1 || res.marks[0] != want+"@0 asks" { + t.Errorf("MarkRegistryHeld was told %v; want %s once, before any ask of the build module", res.marks, want) + } }) } } @@ -457,6 +473,7 @@ type realReserve struct { reservations map[string][]byte } +func (r *realReserve) MarkRegistryHeld(context.Context, versions.ReservedVersion) {} func (r *realReserve) ReleasedFor(context.Context, string, string) (bool, error) { return false, nil } diff --git a/modules/mesh-delivery-builder/internal/build/reservedone_test.go b/modules/mesh-delivery-builder/internal/build/reservedone_test.go deleted file mode 100644 index 96e611e8a..000000000 --- a/modules/mesh-delivery-builder/internal/build/reservedone_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package build - -import ( - "context" - "slices" - "strings" - "testing" - "time" - - "git.novox.be/novox/mesh-sdk/go/catalogue" - - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" -) - -// TestADoneTrunkBuildThatReservedNoneIsGivenAVersionByHand: design 47 G A-455 — builder_reserve_done reserves the series' next -// version for a done key that reserved none, with the digests the key holds; a key not done, a fingerprint no entry carries and -// a build that holds a reservation already are refused; the value it writes is a reasks value of its own key. -func TestADoneTrunkBuildThatReservedNoneIsGivenAVersionByHand(t *testing.T) { - ctx := context.Background() - r := newRig(t, goBundle) - r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} - res := &fakeReservations{} - r.b.Reserved = res - if _, err := r.b.ReserveDone(ctx, "m", fp1); err == nil { - t.Fatal("a version was reserved for a key that is not built") - } - // The build ran while the builder reserved nothing (as the live key did): done, with no reservation. - r.b.Reserved = nil - if v := r.consider(t, "modules/m"); v.State != builds.BuildDone { - t.Fatalf("build = %+v, want done", v) - } - r.b.Reserved = res - if _, err := r.b.ReserveDone(ctx, "m", "src2:"+strings.Repeat("9", 64)); err == nil || !strings.Contains(err.Error(), "no watched branch carries") { - t.Errorf("a fingerprint no entry carries: %v", err) - } - got, err := r.b.ReserveDone(ctx, "m", fp1) - if err != nil || got.Version != "0.1.5" || !slices.Equal(res.series, []string{"0.1"}) || !slices.Equal(res.reserved[0], []string{"m:tool"}) { - t.Fatalf("reserved %+v (%v) in %v for %v, want 0.1.5 of m:tool in 0.1", got, err, res.series, res.reserved) - } - if res.built["m:tool"] != digest || res.sources[0].Fingerprint != fp1 { - t.Errorf("recorded %v from %+v, want the done key's digest for the entry %s", res.built, res.sources, fp1) - } - if _, err := r.b.ReserveDone(ctx, "m", fp1); err == nil || !strings.Contains(err.Error(), "reservation") { - t.Errorf("a build that holds a reservation was given another: %v", err) - } - at := time.Unix(0, 0) - key, _, err := NewReserveDone("m", fp1, "why", "op", at) - if err != nil || !strings.HasPrefix(key, "reserve-done.") { - t.Errorf("key %q (%v)", key, err) - } - for _, args := range [][3]string{{"", fp1, "why"}, {"m", "", "why"}, {"m", fp1, " "}} { - if _, _, err := NewReserveDone(args[0], args[1], args[2], "op", at); err == nil { - t.Errorf("%q made a value", args) - } - } -} diff --git a/modules/mesh-delivery-builder/internal/build/retake.go b/modules/mesh-delivery-builder/internal/build/retake.go index e27865d2d..740769c10 100644 --- a/modules/mesh-delivery-builder/internal/build/retake.go +++ b/modules/mesh-delivery-builder/internal/build/retake.go @@ -104,6 +104,10 @@ func (r *Retaker) Heard(ctx context.Context, subject string, data []byte, seq ui return true, nil } } + // An event heard before the start sweep has filled the set of faulted keys waits for it (H-A-696), held under its node's key. + if err := r.Builder.WaitFaults(ctx); err != nil { + return true, err + } var want func(seat, node string) bool if running { want, err = r.runningWant(ctx, data) @@ -135,7 +139,7 @@ func (r *Retaker) runningWant(ctx context.Context, data []byte) (func(seat, node r.logf("a running that does not read is not acted on: %v", err) return nil, nil } - if ev.Stopped || ev.Fingerprint == "" { + if ev.Stopped || ev.Fingerprint == "" || r.Builder.Faults.Len() == 0 { // no key to retake: no call (H-A-683 (2)) return nil, nil } e, err := r.Entry(ctx, ev.Fingerprint) @@ -167,25 +171,9 @@ func (r *Retaker) returnedWant(data []byte) (func(seat, node string) bool, error return func(_, node string) bool { return node == ev.Node }, nil } -// retakeAll builds again every key failed on a transport fault whose seat and node want says passed. +// retakeAll builds again every key of the set of faulted keys whose seat and node want says passed; it lists no key of the bucket. func (r *Retaker) retakeAll(ctx context.Context, want func(seat, node string) bool) error { - keys, err := r.Builder.Claimer.Store.Keys(ctx) - if err != nil { - return fmt.Errorf("the build keys cannot be listed: %w", err) - } - for _, key := range keys { - raw, _, found, err := r.Builder.Claimer.Store.Get(ctx, key) - if err != nil || !found { - continue - } - v, err := builds.DecodeBuilderBuild(raw) - if err != nil || v.State != builds.BuildFailed { - continue - } - _, seat, node, _, ok := builds.TransportFaultOf(v.Error) - if !ok || !want(seat, node) { - continue - } + for _, key := range r.Builder.Faults.Matching(want) { started, ask, cur, rev, err := r.Builder.Retake(ctx, key) if err != nil { return err diff --git a/modules/mesh-delivery-builder/internal/build/retake_test.go b/modules/mesh-delivery-builder/internal/build/retake_test.go index 3d8ee4a9b..f113f7652 100644 --- a/modules/mesh-delivery-builder/internal/build/retake_test.go +++ b/modules/mesh-delivery-builder/internal/build/retake_test.go @@ -5,7 +5,9 @@ import ( "encoding/json" "fmt" "sync" + "sync/atomic" "testing" + "time" "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" @@ -52,6 +54,9 @@ func TestRetakeOnAnEvent(t *testing.T) { if v := r.consider(t, "modules/m"); !builds.FailedOnTransportFault(v.Error) { t.Fatalf("the key = %+v, want failed on a transport fault", v) } + if err := r.b.Sweep(context.Background()); err != nil { // the start sweep fills the set of faulted keys (H-A-696) + t.Fatal(err) + } var asked []string rt := &Retaker{Builder: r.b, Acted: &actedStore{}, Entry: func(context.Context, string) (meshcatalog.CatalogEntry, error) { @@ -113,6 +118,9 @@ func TestRetakeOnANodeReturned(t *testing.T) { r.consider(t, "modules/m") seed(t, r.st, builds.BuilderBuild{State: builds.BuildFailed, By: "novox.builder", Manifest: mdigest('a'), Error: "transport fault: connection, node-build-go ace, dial tcp: connection refused"}) + if err := r.b.Sweep(context.Background()); err != nil { + t.Fatal(err) + } rt := &Retaker{Builder: r.b, Acted: &actedStore{}} for seq, c := range []struct { node, why string @@ -128,3 +136,45 @@ func TestRetakeOnANodeReturned(t *testing.T) { } } } + +// Design 47 H2 H-A-683 (2), H-A-696: a running heard before the start sweep has filled the set of faulted keys waits for it, then +// retakes the keys its node names; one heard after, with the set empty, reads no entry and starts nothing. +func TestRetakeWaitsForTheStartSweep(t *testing.T) { + r := newRig(t, goBundle) + r.consider(t, "modules/m") + seed(t, r.st, builds.BuilderBuild{State: builds.BuildFailed, By: "novox.builder", Manifest: mdigest('a'), + Error: "transport fault: connection, node-build-go ace, dial tcp: connection refused"}) + var entries atomic.Int32 + rt := &Retaker{Builder: r.b, Acted: &actedStore{}, Entry: func(context.Context, string) (meshcatalog.CatalogEntry, error) { + entries.Add(1) + return meshcatalog.CatalogEntry{Serves: []string{"node-build-go.steps"}}, nil + }} + running, _ := json.Marshal(nodeengine.Running{Module: "mesh-build-go", Node: "ace", Fingerprint: "f1"}) + done := make(chan error, 1) + go func() { + _, err := rt.Heard(context.Background(), "mesh.seat.node-engine.event.running.ace.mesh-build-go", running, 1) + done <- err + }() + select { + case err := <-done: + t.Fatalf("a running heard before the sweep ended returned (%v), want it waiting", err) + case <-time.After(50 * time.Millisecond): + } + if err := r.b.Sweep(context.Background()); err != nil { + t.Fatal(err) + } + if err := <-done; err != nil { + t.Fatal(err) + } + r.b.Wait() + if v := valueOf(t, r.st, r.key); v.State != builds.BuildDone || entries.Load() != 1 { + t.Fatalf("after the sweep: the key = %+v, entries read %d, want built and one entry read", v, entries.Load()) + } + // The set is empty now: another running reads no entry. + if _, err := rt.Heard(context.Background(), "mesh.seat.node-engine.event.running.ace.mesh-build-go", running, 2); err != nil { + t.Fatal(err) + } + if entries.Load() != 1 { + t.Fatalf("a running with the set empty read %d entries, want none more", entries.Load()-1) + } +} diff --git a/modules/mesh-delivery-builder/internal/build/retakeask_test.go b/modules/mesh-delivery-builder/internal/build/retakeask_test.go index b30b3c0fd..e0467d1ce 100644 --- a/modules/mesh-delivery-builder/internal/build/retakeask_test.go +++ b/modules/mesh-delivery-builder/internal/build/retakeask_test.go @@ -54,6 +54,9 @@ func theOperatorAnswers(t *testing.T, option string) { r.consider(t, "modules/m") seed(t, r.st, builds.BuilderBuild{State: builds.BuildFailed, By: "novox.builder", Manifest: mdigest('a'), EventBuilds: 3, Error: "transport fault: connection, node-build-go ace, dial tcp: connection refused"}) + if err := r.b.Sweep(context.Background()); err != nil { + t.Fatal(err) + } var published []oc.Ask acted := &actedStore{} asker := &OperatorAsk{Builder: r.b, Acted: acted, Ctx: context.Background(), Now: askedAt, diff --git a/modules/mesh-delivery-builder/internal/build/revisionwait.go b/modules/mesh-delivery-builder/internal/build/revisionwait.go index 417f92c43..233a2c966 100644 --- a/modules/mesh-delivery-builder/internal/build/revisionwait.go +++ b/modules/mesh-delivery-builder/internal/build/revisionwait.go @@ -2,6 +2,7 @@ package build import ( "context" + "errors" "fmt" "maps" "slices" @@ -163,26 +164,71 @@ func (b *Builder) awaitRevision(ctx context.Context, run meshbuilds.StepRun) (ou wait, stop := context.WithTimeout(ctx, bound) // a context's bound, no timer (ADR 0437 §8) defer stop() told := false + var keys []string + // Each entry of the ask is a wait said on the builder's stream waits (design 47 H2 H-A-577 (1)): `wait-held` while the picture + // does not hold the revision, `wait-ended` with how it ended: ran, failed at the bound, released by builder_release. + endWaits := func(how string) { + for _, e := range run.Entries { + if b.Waits != nil { + b.Waits.EndRevision(context.WithoutCancel(ctx), e.Module, e.Fingerprint, how) + } + } + b.mu.Lock() + for _, k := range keys { + delete(b.revisionWaiting, k) + delete(b.revisionReleased, k) + } + b.mu.Unlock() + } for { b.mu.Lock() moved := b.moved + released := false + for _, k := range keys { + released = released || b.revisionReleased[k] + } b.mu.Unlock() if b.holdsRevision(run.Branch, run.Source, run.Entries) { if told { b.logf("%s: revision %d of %s is in the builder's picture: the build goes on", run.Pipeline, run.Source, run.Branch) + endWaits(WaitRan) } return "", "" } + if released { + endWaits(WaitReleased) + b.logf("%s: %s: the wait was released by hand, the step fails, nothing is built", run.Pipeline, notHeld) + return meshbuilds.StepEndedOutcomeFailed, notHeld + ": the wait was released by hand, and a build with no version is never made" + } if !told { b.logf("%s: %s yet: the ask waits for it, at most %s", run.Pipeline, notHeld, bound) told = true + since := b.now() + for _, e := range run.Entries { + if run.Revision <= 0 { + break // an ask naming no revision has no `revision:` to say + } + k, err := builds.BuilderBuildKey(e.Module, e.Fingerprint) + if err != nil { + continue + } + keys = append(keys, k) + b.mu.Lock() + b.revisionWaiting[k] = true + b.mu.Unlock() + if b.Waits != nil { + b.Waits.Hold(ctx, ToolchainWait{Module: e.Module, Fingerprint: e.Fingerprint, Since: since, Kind: WaitKindRevision, Revision: run.Revision, Bound: bound.String()}) + } + } } select { case <-moved: case <-wait.Done(): if ctx.Err() != nil { + endWaits(WaitFailed) return meshbuilds.StepEndedOutcomeCouldNotRun, notHeld + ": the builder stopped before it was" } + endWaits(WaitFailed) b.logf("%s: %s within %s: the step fails, nothing is built", run.Pipeline, notHeld, bound) return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notHeld, bound) } @@ -217,36 +263,92 @@ func (b *Builder) PackagePublished(name, version string) { b.pictureMoved() } -// versionAtOrigin is the version, as Go names it, the module that publishes the package holds at the source revision of the -// key's origin (H-A-547 (3), H-A-551), and words saying why there is none. -func (b *Builder) versionAtOrigin(ctx context.Context, key, pkg string) (version, none string) { - if b.Members == nil || b.Reserved == nil { - return "", "no module that publishes it can be read" - } - module, artifact, found, err := b.Members(ctx, pkg) - if err != nil || !found { - if err != nil { - return "", fmt.Sprintf("the module that publishes it cannot be read: %v", err) - } - return "", "no entry names the module that publishes it" - } +// pinOf is the version of package pkg for the build of module at fp, which holds origin, and what it waited for when there is none +// (design 47 H2 H-A-707 (3), (4)). First the entry the picture holds for the module on the branch of origin, when it is of fp and +// names a version for the package: a newer entry of the key's fingerprint has the pin its earlier entry lacked, and an entry of +// another branch is never read. Else the version of the publisher's build in the build's revision: the module that publishes the +// package (Members), its fingerprint in the catalog revision origin names (the picture while it holds that revision, else the +// revision read by number, once), and the version the seat mesh-builds' published rule answers (Reserver.PublishedOf, H-A-328). +// publisher is `@` of that build, empty where no module publishes the package. +func (b *Builder) pinOf(ctx context.Context, module, fp, pkg string, origin Origin) (version, publisher, none string) { + hk := origin.Branch + "\x00" + module b.mu.Lock() - o := b.origin[key] + h, heard := b.heard[hk] + at := b.heardAt[hk] b.mu.Unlock() - v, found, err := b.Reserved.VersionAt(ctx, module, artifact, o.Branch, o.Source) + if heard && h.Fp2 == fp && h.Packages[pkg] != "" { + if _, told := b.pinTold.LoadOrStore(module+"@"+fp+" "+pkg, true); !told { + b.logf("%s at %s: %s takes %s, the pin of the entry of revision %d, heard while the build from revision %d waited", module, fp, pkg, h.Packages[pkg], at.Revision, origin.Revision) + } + return h.Packages[pkg], "", "" + } + if b.Members == nil || b.Reserved == nil { + return "", "", "no module that publishes it can be read" + } + pubModule, artifact, found, err := b.Members(ctx, pkg) if err != nil { - return "", fmt.Sprintf("the version %s holds at source revision %d cannot be read: %v", module, o.Source, err) + return "", "", fmt.Sprintf("the module that publishes it cannot be read: %v", err) } if !found { - return "", fmt.Sprintf("%s publishes no version of it at source revision %d of %s", module, o.Source, o.Branch) + return "", "", fmt.Sprintf("no module of revision %d publishes it", origin.Revision) } - return "v" + strings.TrimPrefix(v, "v"), "" + pubFP, err := b.fingerprintAt(ctx, origin, pubModule) + if err != nil { + return "", pubModule + "@", fmt.Sprintf("%s's fingerprint in revision %d cannot be read: %v", pubModule, origin.Revision, err) + } + publisher = pubModule + "@" + pubFP + if pubFP == "" { + return "", publisher, fmt.Sprintf("%s has no entry in revision %d of %s", pubModule, origin.Revision, origin.Branch) + } + a, err := b.Reserved.PublishedOf(ctx, pubModule, pubModule+":"+artifact, pubFP) // the reservation keeps an artifact by its ref + if err != nil { + return "", publisher, fmt.Sprintf("the version %s holds at %s cannot be read: %v", pubModule, pubFP, err) + } + if !a.Published { + return "", publisher, fmt.Sprintf("%s at %s (revision %d) is not published", pubModule, pubFP, origin.Revision) + } + return "v" + strings.TrimPrefix(a.Version, "v"), publisher, "" } -// awaitPublished fills each package of packages with no pin from the version its publisher holds at the key's origin -// (versionAtOrigin), waiting for one (H-A-521, H-A-165). It answers the packages with every pin, or an outcome and its words: -// failed past the bound naming the package, could not run when the builder stops. -func (b *Builder) awaitPublished(ctx context.Context, module, fp string, packages map[string]string) (map[string]string, string, string) { +// fingerprintAt is module's fingerprint in the catalog revision origin names: in the picture of the branch while the picture holds +// that revision (or the origin names none), else in the revision read by number through the seat mesh-catalog, kept once read. +func (b *Builder) fingerprintAt(ctx context.Context, origin Origin, module string) (string, error) { + hk := origin.Branch + "\x00" + module + b.mu.Lock() + h, heard := b.heard[hk] + at := b.heardAt[hk] + b.mu.Unlock() + if heard && (origin.Revision <= 0 || at.Revision == origin.Revision) { + return h.Fp2, nil + } + if b.KeptRevision == nil || origin.Revision <= 0 { + return "", errors.New("the picture does not hold the revision and none can be read by its number") + } + rk := fmt.Sprintf("%s\x00%d", origin.Branch, origin.Revision) + b.mu.Lock() + fps, ok := b.keptFPs[rk] + b.mu.Unlock() + if !ok { + _, read, err := b.KeptRevision(ctx, origin.Branch, origin.Revision) + if err != nil { + return "", err + } + fps = read + b.mu.Lock() + if b.keptFPs == nil { + b.keptFPs = map[string]map[string]string{} + } + b.keptFPs[rk] = fps + b.mu.Unlock() + } + return fps[module], nil +} + +// awaitPublished fills each package of packages with no pin (pinOf), waiting for one (H-A-521, H-A-165). The wait is kept in the +// state waits in the one wait form, held under the build's key with the package's path, the publisher, the catalog revision and the +// time it ends, ended published or failed (H-A-707 (5)). It answers the packages with every pin, or an outcome and its words: failed +// past the bound naming the publisher and its fingerprint, could not run when the builder stops. +func (b *Builder) awaitPublished(ctx context.Context, module, fp string, packages map[string]string, origin Origin) (map[string]string, string, string) { var unpinned []string for p, v := range packages { if v == "" { @@ -257,25 +359,30 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp string, package return packages, "", "" } slices.Sort(unpinned) - key, err := builds.BuilderBuildKey(module, fp) - if err != nil { + if _, err := builds.BuilderBuildKey(module, fp); err != nil { return nil, meshbuilds.StepEndedOutcomeCouldNotRun, err.Error() } bound := b.packageWait() wait, stop := context.WithTimeout(ctx, bound) // a context's bound, no timer (ADR 0437 §8) defer stop() told := false + since := b.now() + endWait := func(how string) { + if told && b.Waits != nil { + b.Waits.End(ctx, module, fp, how) + } + } for { b.mu.Lock() moved := b.moved b.mu.Unlock() pins := map[string]string{} - missing, why := "", "" + missing, why, publisher := "", "", "" for _, p := range unpinned { - v, none := b.versionAtOrigin(wait, key, p) + v, pub, none := b.pinOf(wait, module, fp, p, origin) pins[p] = v if v == "" && missing == "" { - missing, why = p, none + missing, why, publisher = p, none, pub } } if missing == "" { @@ -283,6 +390,7 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp string, package maps.Copy(out, pins) if told { b.logf("%s at %s: every package it names is published: built with %v", module, fp, pins) + endWait(WaitPublished) } return out, "", "" } @@ -291,6 +399,10 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp string, package b.logf("%s at %s: %s yet: the build waits for its publish, at most %s", module, fp, notPublished, bound) told = true } + if b.Waits != nil { + b.Waits.Hold(ctx, ToolchainWait{Module: module, Fingerprint: fp, Since: since, Package: missing, Publisher: publisher, + Revision: origin.Revision, Bound: bound.String(), Until: since.Add(bound)}) + } select { case <-moved: case <-wait.Done(): @@ -298,6 +410,7 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp string, package return nil, meshbuilds.StepEndedOutcomeCouldNotRun, notPublished + ": the builder stopped before it was" } b.logf("%s at %s: %s within %s: the build fails, nothing is built", module, fp, notPublished, bound) + endWait(WaitFailed) return nil, meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notPublished, bound) } } diff --git a/modules/mesh-delivery-builder/internal/build/run.go b/modules/mesh-delivery-builder/internal/build/run.go index cb4cd5f2b..d475474fb 100644 --- a/modules/mesh-delivery-builder/internal/build/run.go +++ b/modules/mesh-delivery-builder/internal/build/run.go @@ -133,10 +133,16 @@ type Builder struct { // its single reference, and its needs. Nil: no node states anything, and the first forms are kept. Forms func() (present, counted map[string][]string) - once sync.Once - sem chan struct{} - wg sync.WaitGroup - mu sync.Mutex + once sync.Once + // Faults are the keys whose newest revision failed on a transport fault (H-A-683 (2)), filled by Sweep and kept by every write. + Faults *Faulted + sem chan struct{} + wg sync.WaitGroup + mu sync.Mutex + // pinTold are the pins taken from a newer entry, said once each; keptFPs the fingerprints of a kept catalog revision, by branch and + // revision, read once (design 47 H2 H-A-707 (3), (4)). + pinTold sync.Map + keptFPs map[string]map[string]string known map[string]meshcatalog.ModulesByModuleValue // by modules key: the first watched branch's heard map[string]meshcatalog.ModulesByModuleValue // by branch and module (take): what supersedes what heardAt map[string]Origin // by branch and module (take): the revision the heard entry came from (H-A-557) @@ -165,6 +171,9 @@ type Builder struct { events map[string]bool // released are the keys builder_release is building now, whatever toolchain their fingerprint names (§276, §672). released map[string]bool + // revisionWaiting are the keys whose step ask waits for its revision now, revisionReleased those builder_release ended + // (design 47 H2 H-A-577 (1)). + revisionWaiting, revisionReleased map[string]bool // builds are the ends that withdraw the asks of a key's build in flight, by build key (ADR 0664 §4): a newer fingerprint of // the module takes its older one's build out, and the asker drops that build's asks. builds map[string]context.CancelCauseFunc @@ -191,6 +200,8 @@ func (b *Builder) Looking(key string) bool { func (b *Builder) init() { b.once.Do(func() { + b.Faults = newFaulted() + b.Claimer.Store = faultNoting{Store: b.Claimer.Store, set: b.Faults} limit := b.Limit if limit <= 0 { limit = 256 @@ -205,6 +216,7 @@ func (b *Builder) init() { b.hands, b.events = map[string]*handWatch{}, map[string]bool{} b.builds = map[string]context.CancelCauseFunc{} b.moved = make(chan struct{}) + b.revisionWaiting, b.revisionReleased = map[string]bool{}, map[string]bool{} }) } @@ -307,7 +319,11 @@ func (b *Builder) take(ctx context.Context, o Origin, key string, m meshcatalog. if bk, err := builds.BuilderBuildKey(key, m.Fp2); err == nil && m.Fp2 != "" { // A fingerprint a watched branch carries is built from that branch's commit, whoever asked for it first. b.trunkFP[bk] = true - b.origin[bk] = o + // The key's origin is never moved back (design 47 H2 H-A-707 (2)): an entry of an older revision with the same fingerprint + // leaves the origin of the newer one as it was. + if cur, held := b.origin[bk]; !held || !originNewer(cur, o) { + b.origin[bk] = o + } b.edges[bk] = e } b.mu.Unlock() @@ -335,7 +351,7 @@ const withdrawnPrefix = "withdrawn: " // supersededBy is the fingerprint that supersedes fp, a fingerprint of module whose build key is key, when fp is of its // registration's first watched branch and is no longer the newest entry heard on that branch (H-A-489); "" otherwise. A key no -// entry named is of the first branch, as originOf has it. +// entry named is of the first branch, as originLocked has it. func (b *Builder) supersededBy(module, key, fp string) string { b.mu.Lock() defer b.mu.Unlock() @@ -429,17 +445,38 @@ func everyArtifactNamesPaths(e meshcatalog.CatalogEntry) bool { return true } -// originOf is the catalog revision the entry of a build key came from; a key no entry named is of the first branch, as a build -// of the trunk's value was before branches were watched. -func (b *Builder) originOf(key string) Origin { - b.mu.Lock() - defer b.mu.Unlock() +// originLocked is the catalog revision the entry of a build key came from; a key no entry named is of the first branch, as a build +// of the trunk's value was before branches were watched. It is read under the lock the caller holds. +func (b *Builder) originLocked(key string) Origin { if o, ok := b.origin[key]; ok { return o } return Origin{First: true} } +// originNewer says whether the origin cur is of a newer module graph revision than o: known by their revisions, else their sources. +func originNewer(cur, o Origin) bool { + newer, known := newerRevision(cur, o) + return known && newer +} + +// entryAndOrigin is what a build holds from its start (design 47 H2 H-A-707 (1)): the entry its picture holds for the module on the +// branch of the key's origin when that entry is of the key's fingerprint, with the origin it was heard at, else the entry that woke it +// with the key's origin. Taken under one lock, it is read by the build's reservation, pins and revision wait, never the key's origin +// as it stands later. +func (b *Builder) entryAndOrigin(module, key string, woke meshcatalog.ModulesByModuleValue) (meshcatalog.ModulesByModuleValue, Origin) { + b.mu.Lock() + defer b.mu.Unlock() + o := b.originLocked(key) + if h, ok := b.heard[o.Branch+"\x00"+module]; ok && h.Fp2 == woke.Fp2 { + if at, ok := b.heardAt[o.Branch+"\x00"+module]; ok { + return h, at + } + return h, o + } + return woke, o +} + // NodesChanged is Reconsider after a toolchain moved, so a build that waited for the nodes to agree on one may go on. func (b *Builder) NodesChanged(ctx context.Context) { b.Reconsider(ctx) } @@ -481,6 +518,7 @@ func (b *Builder) Sweep(ctx context.Context, pictured ...string) error { if err != nil || !found { continue } + b.Faults.note(key, value, rev) cur, err := builds.DecodeBuilderBuild(value) if err != nil { continue @@ -500,6 +538,7 @@ func (b *Builder) Sweep(ctx context.Context, pictured ...string) error { } b.logf("%s: closed, left building by %s for a fingerprint the module no longer has", key, cur.By) } + b.logf("the start sweep read %d keys and put %d in the set of keys failed on a transport fault", len(keys), b.Faults.Fill()) if newly { // A key read before the scan may wait for a package the scan found published (ADR 0500 clause 6). b.Reconsider(ctx) @@ -700,6 +739,7 @@ func (b *Builder) startOnce(ctx context.Context, key, module string, m meshcatal // building by this builder: it takes it again when it starts (ADR 0478 clause 5). func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue) { key, _ := builds.BuilderBuildKey(module, m.Fp2) + m, origin := b.entryAndOrigin(module, key, m) // the build holds one entry and its origin (design 47 H2 H-A-707 (1)) whyEnded := "" defer func() { b.handEnded(key, whyEnded) }() defer b.unrelease(key) @@ -748,8 +788,8 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB delete(b.events, key) b.mu.Unlock() // Only a build of the registration's first watched branch reserves and releases a version (design 47 G §371). - reserving := trunk && b.originOf(key).First && planErr == nil && !nothing && b.reserves(ctx, module, m, plan) - if trunk && b.originOf(key).First && planErr == nil && !nothing && !reserving { + reserving := trunk && origin.First && planErr == nil && !nothing && b.reserves(ctx, module, m, plan) + if trunk && origin.First && planErr == nil && !nothing && !reserving { // A done build whose digests its end did not record is recorded at the next look (design 47 H2 H-A-492). if _, err := b.RecordAgain(ctx, module, m.Fp2, "at a look"); err != nil { b.logf("%v", err) @@ -803,14 +843,20 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB // Reserved as A-490b amended by H-A-225 has it: this fingerprint's standing reservation is kept while it is unreleased // and above the highest the catalog's versions answers, else the next above that highest is taken (A-455); the build's // own publish then runs. - reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), true) + reserved, hasReserved = b.reserve(ctx, module, m, plan, origin, true) reserving = true } else if reserving && cl.Build.State != builds.BuildDone { // Looked at again just before it reserves (H-A-489): a newer entry heard since the claim is not taken over. if supersededNow = b.supersededBy(module, key, m.Fp2); supersededNow == "" { - reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), false) + reserved, hasReserved = b.reserve(ctx, module, m, plan, origin, false) } } + if hasReserved && supersededNow == "" && cl.Build.State != builds.BuildDone { + // Before a build module is asked for the fingerprint again, what a registry holds of it at its version is on the reservation + // and marked published, so a version a failed build left partly published is completed, never built whole again over a + // refusal (design 47 H2 H-A-588 (4), H-A-666: between the reserve and the build). + b.Reserved.MarkRegistryHeld(ctx, reserved) + } var result builds.BuilderBuild if supersededNow != "" { // Ended as the newer entry's take-in withdraws a build in flight: final for this fingerprint. @@ -828,7 +874,7 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB b.mu.Lock() b.builds[key] = withdraw b.mu.Unlock() - result = b.build(run, module, m, plan, planErr, prior, only, b.notes(cl), reserved.Version) + result = b.build(run, module, m, plan, planErr, prior, only, b.notes(cl, origin), reserved.Version) b.mu.Lock() delete(b.builds, key) b.mu.Unlock() @@ -1167,10 +1213,12 @@ type askNotes struct { resumed map[string]string // step is the step words of a key taken over at start: an ask asked again says its asking there (askingOf). step string + // origin is the origin the build holds from its start (design 47 H2 H-A-707 (1)), which its pins are read at. + origin Origin } -func (b *Builder) notes(cl *Claim) *askNotes { - n := &askNotes{b: b, cl: cl} +func (b *Builder) notes(cl *Claim, origin Origin) *askNotes { + n := &askNotes{b: b, cl: cl, origin: origin} if cl.Build.State == builds.BuildBuilding && len(cl.Build.Asks) > 0 { n.resumed, n.step = maps.Clone(cl.Build.Asks), cl.Build.Step } @@ -1239,7 +1287,7 @@ func (b *Builder) runLane(ctx context.Context, l *lane, repository string, m mes // them into the workspace, whatever the repository's go.mod names. A package the entry names with no pin waits for // its publish and is built with the version its publisher holds at the key's origin; past the bound the lane fails // naming it, and no ask is put (H-A-521, H-A-547 (3), H-A-165). - pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Packages) + pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Packages, asked.origin) if outcome != "" { l.err = errors.New(said) return diff --git a/modules/mesh-delivery-builder/internal/build/step.go b/modules/mesh-delivery-builder/internal/build/step.go index 6b2031979..148498587 100644 --- a/modules/mesh-delivery-builder/internal/build/step.go +++ b/modules/mesh-delivery-builder/internal/build/step.go @@ -32,6 +32,11 @@ func (b *Builder) BuildStep(ctx context.Context, ask string, run meshbuilds.Step if d := DroppedOf(ctx); d != nil { outcome, said = meshbuilds.StepEndedOutcomeCouldNotRun, d.Error() } + // A superseded end names the revision of the entry that supersedes it (H-A-561); where the builder heard none, it ends the + // step could-not-run itself, naming that, never superseded with a zero revision (design 47 H2 H-A-650). + if outcome == meshbuilds.StepEndedOutcomeSuperseded && end.Revision <= 0 { + outcome, said = meshbuilds.StepEndedOutcomeCouldNotRun, "superseded by a newer entry, but the builder heard no superseding revision for it to name: "+said + } at := b.now() end.Ended, end.Outcome, end.Said = &at, outcome, said if outcome != meshbuilds.StepEndedOutcomeSuperseded { @@ -148,7 +153,10 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds. } // A package the entry names with no pin is built against its publisher's version at the key's origin, waited for // (H-A-521, H-A-547 (3), H-A-165). - pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, entry.Packages) + b.mu.Lock() + origin := b.originLocked(func() string { k, _ := builds.BuilderBuildKey(entry.Module, entry.Fp); return k }()) + b.mu.Unlock() + pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, entry.Packages, origin) if outcome != "" { return outcome, said } @@ -207,7 +215,7 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds. // passedWithItsVersion is the verdict of a build that ended done (design 47 G A-456): a build that reserves a version (a build // of the first watched branch's trunk, with a MAJOR.MINOR series and artifacts) passes only when a version is reserved for its -// fingerprint; one that ended done with none fails loudly, naming builder_reserve_done, so no pipeline says passed for a build +// fingerprint; one that ended done with none fails loudly, naming builder_build_again, so no pipeline says passed for a build // that can never be released, and one whose series another fingerprint took over fails saying it is stale, naming that // fingerprint and its version (design 47 H H-A-244). A build that reserves none (a candidate's, a series of before G) passes as it did. func (b *Builder) passedWithItsVersion(ctx context.Context, entry meshcatalog.CatalogEntry) (outcome, said string) { @@ -252,7 +260,7 @@ func (b *Builder) passedWithItsVersion(ctx context.Context, entry meshcatalog.Ca // H-A-244 (2): the series was taken over by a newer fingerprint, whose number it carries now: the build is stale. return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s: built at %s but its series moved to %s %s: stale", entry.Module, entry.Fp, by.Fingerprint, by.Version) } - return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s: built at %s, but no version is reserved for it; builder_reserve_done reserves one for the done build", entry.Module, entry.Fp) + return meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s: built at %s, but no version is reserved for it; builder_build_again builds it again under a reserved one", entry.Module, entry.Fp) } return meshbuilds.StepEndedOutcomePassed, "" } diff --git a/modules/mesh-delivery-builder/internal/build/step_test.go b/modules/mesh-delivery-builder/internal/build/step_test.go index 4294b85cd..a1a82064f 100644 --- a/modules/mesh-delivery-builder/internal/build/step_test.go +++ b/modules/mesh-delivery-builder/internal/build/step_test.go @@ -121,7 +121,7 @@ func TestAStepAskIsWokenByItsBuildsEnd(t *testing.T) { } // A build step passes a build that reserves a version only when a version is reserved for its fingerprint (design 47 G A-456): -// a trunk build that ended done with none fails naming builder_reserve_done, and passes once one is reserved for it; a build +// a trunk build that ended done with none fails naming builder_build_again, and passes once one is reserved for it; a build // that reserves none (a manifest of before G, version "1") passes as it did. func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T) { for _, c := range []struct { @@ -158,7 +158,7 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T) if err != nil { t.Fatal(err) } - r.b.Module(t.Context(), "m", newer) + hearAtRevision(t, r.b, "m", newer, 9) r.b.Wait() } r.b.Reserved = res @@ -169,7 +169,8 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T) return meshcatalog.CatalogEntry{Module: "m", Repository: "novox/m", Commit: "c1", Fp: fp1, ManifestDigest: digestOf(c.unreadable), Path: "modules/m"}, nil } end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.1.m", Step: meshbuilds.StepRunStepBuild, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) - if end.Outcome != c.want || !strings.Contains(end.Said, c.said) || (c.want == meshbuilds.StepEndedOutcomeFailed && strings.Contains(end.Said, "builder_reserve_done") == c.takenOver) { + // H2 H-A-665: the failure words of a build with no version name builder_build_again, the person's tool + if end.Outcome != c.want || !strings.Contains(end.Said, c.said) || (c.want == meshbuilds.StepEndedOutcomeFailed && strings.Contains(end.Said, "builder_build_again") == c.takenOver) { t.Errorf("end = %+v, want %s saying %q", end, c.want, c.said) } // The verdict of a build that ended done, as a build ended now is judged, says the same (H-A-508: the newest entry first). @@ -182,6 +183,8 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T) }) } t.Run("H-A-508: built now, superseded: a newer entry heard while the build runs ends the step superseded", aNewerEntryWhileTheBuildRunsSupersedesTheStep) + t.Run("H-A-650: a superseded end the builder knows no revision for is could-not-run, never superseded with a zero", aSupersededEndWithNoRevisionIsCouldNotRun) + t.Run("H-A-707 (1) (2): a build holds the newest entry of its fingerprint and its origin, which an older entry never moves back", aBuildHoldsItsNewestEntryAndOrigin) t.Run("H-A-155: an ask waits for the picture to take its revision in, then builds with its version reserved", aStepAskWaitsForItsRevision) t.Run("H-A-155: past the bound the ask fails naming its revision, and nothing is built", aStepAskPastItsRevisionBoundFails) t.Run("H-A-205: an ask of a revision below the picture's newest is read by number and built", anOlderKeptRevisionIsReadByNumber) @@ -191,6 +194,7 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T) t.Run("H-A-547 (3): a package with no pin waits for its publisher's version at the key's origin and is built with it", aPackageWithNoPinWaitsForItsRelease) t.Run("H-A-165: past its bound a package with no version at the origin fails the step", aPackageWithNoReleaseFailsPastItsBound) t.Run("H-A-547 (3): a lane waits for an unpinned package's version at its origin and fails past its bound", aLaneWaitsForAnUnpinnedPackage) + t.Run("H-A-707 (3) (5): a newer entry of the branch names the pin and ends the wait, never one of another branch", aNewerEntrysPinEndsTheWait) } // unpinnedRig is a rig whose step entry m names the package x with no version, x published by the artifact x of the module xm, @@ -207,6 +211,8 @@ func unpinnedRig(t *testing.T) (*rig, *fakeReservations, meshcatalog.CatalogEntr r.b.init() r.b.mu.Lock() r.b.origin[r.key] = Origin{Branch: "main", Source: 41, First: true} + // the publisher's entry of the build's revision the picture holds (H2 H-A-707 (4)) + r.b.heard["main\x00xm"], r.b.heardAt["main\x00xm"] = meshcatalog.ModulesByModuleValue{Fp2: fpX}, Origin{Branch: "main", Source: 41, First: true} r.b.mu.Unlock() waiting := make(chan struct{}, 1) r.b.Logf = func(format string, args ...any) { @@ -221,6 +227,11 @@ func unpinnedRig(t *testing.T) (*rig, *fakeReservations, meshcatalog.CatalogEntr return r, res, entry, waiting } +var ( + fpX = "src2:" + strings.Repeat("c", 64) // the publisher xm's fingerprint in the build's revision + fpXOld = "src2:" + strings.Repeat("d", 64) +) + const unpinnedX = "git.novox.be/novox/mesh-contracts/go/seats/x" // awaitWaiting fails the test unless the build started its wait before ended said anything. @@ -251,8 +262,8 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) { mu.Unlock() } } - res.publishAt("xm", "x", "main", 40, "0.1.2") // another source revision than the key's origin: no pin - r.b.PackagePublished(unpinnedX, "v0.1.9") // the newest heard: no pin (H-A-547 (3)) + res.publishAt("xm", "x", fpXOld, "0.1.2") // another fingerprint of the publisher than its build in the revision: no pin + r.b.PackagePublished(unpinnedX, "v0.1.9") // the newest heard: no pin (H-A-547 (3)) ended := make(chan meshbuilds.StepEnded, 1) go func() { ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, @@ -262,7 +273,7 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) { if _, ok := r.st.vals[r.key]; ok { t.Fatal("the build was made before the package was published") } - res.publishAt("xm", "x", "main", 41, "0.1.3") + res.publishAt("xm", "x", fpX, "0.1.3") r.b.PackagePublished(unpinnedX, "v0.1.3") var end meshbuilds.StepEnded select { @@ -281,7 +292,7 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) { t.Errorf("the end reports the pins %v; want the ones it was built with", end.Packages) } // A done key reports the pins it keeps it was built with, never a newer one published now (H-A-207). - res.publishAt("xm", "x", "main", 41, "0.1.5") + res.publishAt("xm", "x", fpX, "0.1.5") again := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) if again.Outcome != meshbuilds.StepEndedOutcomePassed || again.Packages[unpinnedX] != "v0.1.3" { @@ -317,11 +328,11 @@ func aPackageWithNoReleaseFailsPastItsBound(t *testing.T) { Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) r.b.Wait() if _, built := r.st.vals[r.key]; end.Outcome != meshbuilds.StepEndedOutcomeFailed || built || - !strings.Contains(end.Said, "package "+unpinnedX+" has no published version: xm publishes no version of it at source revision 41 of main") { + !strings.Contains(end.Said, "package "+unpinnedX+" has no published version: xm at "+fpX+" (revision 0) is not published") { t.Errorf("end = %+v, built %v; want failed naming the package, nothing built", end, built) } // A version its publisher holds at the origin gives the pin at once. - res.publishAt("xm", "x", "main", 41, "0.1.2") + res.publishAt("xm", "x", fpX, "0.1.2") if end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}); strings.Contains(end.Said, "no published version") { t.Errorf("a version at the origin did not pin the package: %+v", end) @@ -342,7 +353,7 @@ func aLaneWaitsForAnUnpinnedPackage(t *testing.T) { if asks := r.asks.Asks(); len(asks) != 0 { t.Fatalf("a build was asked without the package's pin: %+v", asks) } - res.publishAt("xm", "x", "main", 41, "0.1.5") + res.publishAt("xm", "x", fpX, "0.1.5") r.b.PackagePublished(unpinnedX, "0.1.5") select { case <-done: @@ -417,6 +428,8 @@ func aStepAskWaitsForItsRevision(t *testing.T) { held.Store(40) asked := make(chan struct{}, 1) r, res, entry := revisionRig(t, &held, asked) + rw := &memWaits{} + r.b.Waits = rw var keptReads atomic.Int64 // H-A-205, H-A-222: a revision above the newest is read by number once; not answered, it is waited for r.b.KeptRevision = func(context.Context, string, int64) (int64, map[string]string, error) { keptReads.Add(1) @@ -449,6 +462,11 @@ func aStepAskWaitsForItsRevision(t *testing.T) { if end.Outcome != meshbuilds.StepEndedOutcomePassed || len(res.sources) != 1 || res.sources[0].Revision != 41 || keptReads.Load() != 1 { t.Errorf("end = %+v, reserved from %+v, kept revisions read %d; want passed with one version reserved from revision 41, read by number once", end, res.sources, keptReads.Load()) } + // H-A-577 (1): the wait is held `revision:7` while the picture lacks it and ended `ran` once it holds it + if rw.mu.Lock(); !slices.Equal(rw.ons, []string{"revision:7"}) || !slices.Equal(rw.ended, []string{"revision:ran"}) || len(rw.held) != 0 { + t.Errorf("the revision wait: held %v, ended %v, standing %v; want one revision:7 ended ran", rw.ons, rw.ended, rw.held) + } + rw.mu.Unlock() } @@ -488,7 +506,7 @@ func anOlderKeptRevisionIsReadByNumber(t *testing.T) { return 45, map[string]string{"m": fp1}, nil } entryn.Fp = fp2 - rn.b.Entry(context.Background(), Origin{Branch: "main", Source: 46, First: true}, entryn) + rn.b.Entry(context.Background(), Origin{Branch: "main", Source: 46, Revision: 48, First: true}, entryn) rn.b.Wait() if endn := rn.b.BuildStep(t.Context(), "a1", run); endn.Outcome != meshbuilds.StepEndedOutcomeSuperseded || !strings.Contains(endn.Said, "superseded by "+fp2) { t.Errorf("the older ask after the newer entry: end = %+v; want superseded by %s", endn, fp2) @@ -643,12 +661,19 @@ func aStepAskPastItsRevisionBoundFails(t *testing.T) { held.Store(40) r, res, _ := revisionRig(t, &held, make(chan struct{}, 1)) r.b.RevisionWait = time.Nanosecond + rw := &memWaits{} + r.b.Waits = rw end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.7.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Revision: 7, Source: 41, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) r.b.Wait() if _, built := r.st.vals[r.key]; end.Outcome != meshbuilds.StepEndedOutcomeFailed || !strings.Contains(end.Said, "revision 41 of main not in the builder's picture") || built || len(res.sources) != 0 { t.Errorf("end = %+v, built %v, reserved %+v; want failed naming revision 41 of main, nothing built", end, built, res.sources) } + // H-A-577 (1): the wait is held and ended `failed` at its bound + if rw.mu.Lock(); !slices.Equal(rw.ended, []string{"revision:failed"}) || len(rw.held) != 0 { + t.Errorf("the revision wait: ended %v, standing %v; want one ended failed", rw.ended, rw.held) + } + rw.mu.Unlock() // A step ask with no source (a run on request) does not wait (H-A-156). end = r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "run.1.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) if strings.Contains(end.Said, "not in the builder's picture") { @@ -710,7 +735,7 @@ func aNewerEntryWhileTheBuildRunsSupersedesTheStep(t *testing.T) { if err != nil { t.Fatal(err) } - r.b.Module(t.Context(), "m", newer) + hearAtRevision(t, r.b, "m", newer, 9) var end meshbuilds.StepEnded select { case end = <-ended: @@ -725,3 +750,130 @@ func aNewerEntryWhileTheBuildRunsSupersedesTheStep(t *testing.T) { t.Errorf("end = %+v, want superseded by %s", end, fp2) } } + +// hearAtRevision takes a module's value in as the picture hears an entry of catalog revision rev on the first branch, so a step it +// supersedes names that revision (design 47 H H-A-561; H2 H-A-650: none heard is no superseded end). +func hearAtRevision(t *testing.T, b *Builder, module string, value []byte, rev int64) { + t.Helper() + m, err := meshcatalogclient.DecodeModule(value) + if err != nil { + t.Fatal(err) + } + b.init() + b.take(t.Context(), Origin{First: true, Revision: rev}, module, m, nil) + b.Wait() +} + +func aSupersededEndWithNoRevisionIsCouldNotRun(t *testing.T) { + r := newRig(t, goBundle) + r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}} + if v := r.consider(t, "modules/m"); v.State != builds.BuildDone { + t.Fatalf("build = %+v, want done", v) + } + newer, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", + Fp2: fp2, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)}) + if err != nil { + t.Fatal(err) + } + r.b.Module(t.Context(), "m", newer) // heard with no catalog revision + r.b.Wait() + r.b.Reserved = &fakeReservations{} + r.b.StepEntry = func(context.Context, string) (meshcatalog.CatalogEntry, error) { + return meshcatalog.CatalogEntry{Module: "m", Repository: "novox/m", Commit: "c1", Fp: fp1, ManifestDigest: digestOf(false), Path: "modules/m"}, nil + } + end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.1.m", Step: meshbuilds.StepRunStepBuild, Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) + if end.Outcome != meshbuilds.StepEndedOutcomeCouldNotRun || end.Revision != 0 || !strings.Contains(end.Said, "no superseding revision") { + t.Errorf("end = %+v, want could not run naming that no superseding revision was heard", end) + } +} + +func aBuildHoldsItsNewestEntryAndOrigin(t *testing.T) { + var held atomic.Int64 + r, _, entry := revisionRig(t, &held, make(chan struct{}, 1)) + key, _ := builds.BuilderBuildKey("m", fp1) + val := func(commit string) meshcatalog.ModulesByModuleValue { + v, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: commit, Fp2: fp1, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)}) + if err != nil { + t.Fatal(err) + } + m, _ := meshcatalogclient.DecodeModule(v) + return m + } + _ = entry + r.b.init() + o511 := Origin{Branch: "main", Source: 155, Revision: 511, First: true} + o510 := Origin{Branch: "main", Source: 154, Revision: 510, First: true} + r.b.take(t.Context(), o511, "m", val("7a74cee83f88e6585a5511c3cc53bdf0f5303d20"), nil) + r.b.Wait() + r.b.take(t.Context(), o510, "m", val("1111111111111111111111111111111111111111"), nil) // the same fingerprint, an older revision's entry + r.b.Wait() + r.b.mu.Lock() + got := r.b.origin[key] + r.b.mu.Unlock() + if got != o511 { + t.Errorf("the key's origin is %+v after an older revision's entry was taken; want revision 511's %+v as it was", got, o511) + } + // a build woken by revision 510's value takes the entry its picture holds, revision 511's, with its origin + m, o := r.b.entryAndOrigin("m", key, val("1111111111111111111111111111111111111111")) + if o != o511 || m.Commit != "7a74cee83f88e6585a5511c3cc53bdf0f5303d20" { + t.Errorf("the build woken by revision 510's value holds %+v at %+v; want revision 511's entry and origin", m.Commit, o) + } +} + +// H-A-707 (3), (5): while a build waits for a blank pin its wait stands in the state waits with the package's path, the publisher and its +// fingerprint, the revision and its end; an entry of another branch with the pin changes nothing, and a newer entry of the key's +// branch and fingerprint that names it ends the wait published and the build is made with it; one never published fails past the bound +// naming the publisher and its fingerprint, its wait ended failed. +func aNewerEntrysPinEndsTheWait(t *testing.T) { + r, _, _, waiting := unpinnedRig(t) + w := &memWaits{} + r.b.Waits = w + ended := make(chan meshbuilds.StepEnded, 1) + go func() { + ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, + Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) + }() + awaitWaiting(t, waiting, ended) + w.mu.Lock() + held := w.held["m."+fp1] + w.mu.Unlock() + if held.Package != unpinnedX || held.Publisher != "xm@"+fpX || held.Until.IsZero() || held.Bound == "" { + t.Fatalf("the pin wait held is %+v, want the package's path, xm@%s, its end and bound", held, fpX) + } + pin := func(branch string) { + r.b.mu.Lock() + r.b.heard[branch+"\x00m"], r.b.heardAt[branch+"\x00m"] = meshcatalog.ModulesByModuleValue{Fp2: fp1, Manifest: mdigest('a'), Path: "modules/m", Repository: "novox/m", Commit: "3333333333333333333333333333333333333333", Toolchains: CatalogToolchains(agreedToolchains), Packages: map[string]string{unpinnedX: "v0.1.8"}}, Origin{Branch: branch, Source: 42, First: true} + r.b.mu.Unlock() + r.b.pictureMoved() + } + pin("feature") + select { + case end := <-ended: + t.Fatalf("an entry of another branch ended the wait: %+v", end) + case <-time.After(100 * time.Millisecond): + } + pin("main") + var end meshbuilds.StepEnded + select { + case end = <-ended: + case <-time.After(5 * time.Second): + t.Fatal("a newer entry's pin did not end the wait") + } + r.b.Wait() + asks := r.asks.Asks() + w.mu.Lock() + endedWaits := slices.Clone(w.ended) + w.mu.Unlock() + if end.Outcome != meshbuilds.StepEndedOutcomePassed || len(asks) == 0 || asks[0].Packages[unpinnedX] != "v0.1.8" || !slices.Equal(endedWaits, []string{WaitPublished}) { + t.Errorf("end %+v, asks %+v, waits ended %v; want passed, built with v0.1.8, the wait ended published", end, asks, endedWaits) + } + // Never published: past the bound the key fails naming the publisher and its fingerprint, and the wait ends failed. + r2, _, _, _ := unpinnedRig(t) + w2 := &memWaits{} + r2.b.Waits, r2.b.PackageWait = w2, time.Nanosecond + end = r2.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41, + Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}) + if end.Outcome != meshbuilds.StepEndedOutcomeFailed || !strings.Contains(end.Said, "xm at "+fpX+" (revision 0) is not published within") || !slices.Equal(w2.ended, []string{WaitFailed}) { + t.Errorf("end %+v, waits ended %v; want failed naming xm and its fingerprint, the wait ended failed", end, w2.ended) + } +} diff --git a/modules/mesh-delivery-builder/internal/build/stuck.go b/modules/mesh-delivery-builder/internal/build/stuck.go index a2c8173db..7486ff238 100644 --- a/modules/mesh-delivery-builder/internal/build/stuck.go +++ b/modules/mesh-delivery-builder/internal/build/stuck.go @@ -61,15 +61,8 @@ type ReAsk struct { Name string `json:"name,omitempty"` Version string `json:"version,omitempty"` Queued []string `json:"queued,omitempty"` - // Tries and NextTry are a ModePublish value's (design 47 G A-457a): the publishes tried so far, and when the next is. - Tries int `json:"tries,omitempty"` - NextTry time.Time `json:"next-try,omitzero"` } -// ModePublish is the Mode of a reasks value that is a version's publish item (design 47 G A-457a): Module and Version name it, -// Tries and NextTry say where it stands; it is written by the builder itself, when a build ends and at its start. -const ModePublish = "publish" - // ModeRepublish is the Mode of a reasks value of builder_publish_again (design 47 G §588): Module and Version, each // optional, name what to publish again; the builder answers with the versions it queued (Queued). const ModeRepublish = "republish" @@ -129,9 +122,10 @@ func NewOldFormDrop(node, why, by string, at time.Time) (string, []byte, error) const ModeReservedDrop = "reserved-drop" // NewReservedDrop is the value builder_reserved_drop writes: the key `reserved..` (never a build key) -// and the value. -func NewReservedDrop(module, series, why, by string, at time.Time) (string, []byte, error) { - module, series = strings.TrimSpace(module), strings.TrimSpace(series) +// and the value, which names the version to drop (design 47 H2 H-A-592 (1)): a reservation a newer build took after it was read +// is never dropped. +func NewReservedDrop(module, series, version, why, by string, at time.Time) (string, []byte, error) { + module, series, version = strings.TrimSpace(module), strings.TrimSpace(series), strings.TrimSpace(version) if module == "" { return "", nil, errors.New("module is required") } @@ -141,28 +135,13 @@ func NewReservedDrop(module, series, why, by string, at time.Time) (string, []by if strings.TrimSpace(why) == "" { return "", nil, errors.New("say why the reservation is dropped (why)") } - data, err := json.Marshal(ReAsk{V: 1, Why: strings.TrimSpace(why), By: by, At: at.UTC(), Mode: ModeReservedDrop, Name: module, FP: series}) + if s, _, err := versions.SplitVersion(version); err != nil || s != series { + return "", nil, fmt.Errorf("version %q is not a MAJOR.MINOR.PATCH of the series %s (version is required)", version, series) + } + data, err := json.Marshal(ReAsk{V: 1, Why: strings.TrimSpace(why), By: by, At: at.UTC(), Mode: ModeReservedDrop, Name: module, FP: series, Version: version}) return "reserved." + versions.ReservedKey(module, series), data, err } -// ModeReserveDone is the Mode of a reasks value of builder_reserve_done (design 47 G A-455): Name is the module and FP the -// fingerprint of a done trunk build that reserved no version. -const ModeReserveDone = "reserve-done" - -// NewReserveDone is the value builder_reserve_done writes: the key `reserve-done..` (never a build key) and -// the value. -func NewReserveDone(module, fp, why, by string, at time.Time) (string, []byte, error) { - module, fp = strings.TrimSpace(module), strings.TrimSpace(fp) - if module == "" || fp == "" { - return "", nil, errors.New("module and fp are required") - } - if strings.TrimSpace(why) == "" { - return "", nil, errors.New("say why a version is reserved for the done build (why)") - } - data, err := json.Marshal(ReAsk{V: 1, Why: strings.TrimSpace(why), By: by, At: at.UTC(), Mode: ModeReserveDone, Name: module, FP: fp}) - return "reserve-done." + versions.EscapeToken(module) + "." + versions.EscapeToken(fp), data, err -} - // ModeBuild is the Mode of a reasks value that asks the key to be built again, not its waiting asks to be asked again. const ModeBuild = "build" @@ -243,24 +222,28 @@ type StuckAsk struct { // Stuck is one build key that waits on an ask. type Stuck struct { - Key string `json:"key"` - Module string `json:"module"` - FP string `json:"fp"` - State string `json:"state"` - Step string `json:"step"` - By string `json:"by"` - Since time.Time `json:"since,omitzero"` - Age string `json:"age,omitempty"` - Asks []StuckAsk `json:"asks"` - ReAsk *ReAsk `json:"reask,omitempty"` - Unasked bool `json:"unasked,omitempty"` - NoneStep int `json:"asks_with_no_step"` + Key string `json:"key"` + Module string `json:"module"` + FP string `json:"fp"` + State string `json:"state"` + Step string `json:"step"` + By string `json:"by"` + Since time.Time `json:"since,omitzero"` + Age string `json:"age,omitempty"` + Asks []StuckAsk `json:"asks"` + ReAsk *ReAsk `json:"reask,omitempty"` + // Waits is the wait a key building with no ask holds in the state waits, so a key waiting for a pin is told apart from one stuck. + Waits []ToolchainWait `json:"waits,omitempty"` + Unasked bool `json:"unasked,omitempty"` + NoneStep int `json:"asks_with_no_step"` } // StuckReader reads what builder_stuck answers. type StuckReader struct { Builds StateRead ReAsks StateRead + // Waits is the builder's state waits: a key building with no ask gains the wait it holds, read from it (design 47 H2 H-A-707 (5)). + Waits StateRead // Steps are the build seats' steps states (`.steps`, design 47 G A-82), by build seat. Steps map[string]StateRead // StepsOf, when set, reads the steps state of a build seat the seat list names (`.steps`), instead of Steps: the seats @@ -418,6 +401,15 @@ func (r StuckReader) Stuck(module string) (map[string]any, error) { } sort.Slice(s.Asks, func(i, j int) bool { return s.Asks[i].Language < s.Asks[j].Language }) s.Unasked = v.State == builds.BuildBuilding && len(v.Asks) == 0 + if s.Unasked && r.Waits.Get != nil { + reads++ + if raw, _, err := r.Waits.Get(key); err == nil && raw != nil { + var w ToolchainWait + if json.Unmarshal(raw, &w) == nil && w.Module != "" { + s.Waits = append(s.Waits, w) + } + } + } if r.ReAsks.Get != nil { reads++ if raw, _, err := r.ReAsks.Get(key); err == nil && raw != nil { diff --git a/modules/mesh-delivery-builder/internal/build/waits.go b/modules/mesh-delivery-builder/internal/build/waits.go index e51f0b14d..0fdd22a12 100644 --- a/modules/mesh-delivery-builder/internal/build/waits.go +++ b/modules/mesh-delivery-builder/internal/build/waits.go @@ -29,6 +29,12 @@ const ( // WaitPublished ends the wait of a key queued behind a package, when the key is claimed (the package is published). WaitPublished = "published" WaitReleased = "released" + // WaitFailed ends a revision wait at its bound (design 47 H2 H-A-577 (1)). + WaitFailed = "failed" + // WaitReplaced ends a wait a build's next wait took the key from (design 47 H2 H-A-723 (1)). + WaitReplaced = "replaced" + // WaitKindRevision is the Kind of a revision wait. + WaitKindRevision = "revision" ) // ToolchainWait is one wait: the entry's module and fingerprint, and the toolchain it waits for. @@ -41,13 +47,36 @@ type ToolchainWait struct { // Package is the package version a key queued behind it waits for, `@` (ADR 0603 §8; design 47 G A-192): the wait is the // package's, not a toolchain's, and Language and Version are empty. Package string `json:"package,omitempty"` + // Kind is "revision" on a step ask's wait for its revision; Revision is then the module graph revision the ask names (design + // 47 H2 H-A-577 (1)); Bound is that wait's own bound, said as `bound` (the toolchain wait's is the builder's). + Kind string `json:"kind,omitempty"` + Revision int64 `json:"revision,omitempty"` + Bound string `json:"bound,omitempty"` + // Publisher (`@`) and Until are the pin wait's: a build waiting for a blank pin's version holds Package, the + // package's path alone, Publisher the build it waits for, Revision the catalog revision the build holds and Until its start plus + // `package-wait-minutes` (design 47 H2 H-A-707 (5), DQ-53, H-A-717). + Publisher string `json:"publisher,omitempty"` + Until time.Time `json:"until,omitzero"` } +// SameWait says w and o are one wait: every field but when it began and when it ends, so a Hold of the wait that stands changes +// nothing (design 47 H2 H-A-723 (1)). +func (w ToolchainWait) SameWait(o ToolchainWait) bool { + w.Since, w.Until, o.Since, o.Until = time.Time{}, time.Time{}, time.Time{}, time.Time{} + return w == o +} + +// IsRevision says whether the wait is a step ask's wait for its revision, kept under `..revision`. +func (w ToolchainWait) IsRevision() bool { return w.Kind == WaitKindRevision } + // On is what the wait waits for, as the wait's `on` says it. func (w ToolchainWait) On() string { if w.Package != "" { return "package:" + w.Package } + if w.IsRevision() { + return fmt.Sprintf("revision:%d", w.Revision) + } return "toolchain:" + w.Language + "@" + w.Version } @@ -56,6 +85,9 @@ func (w ToolchainWait) On() string { type Waits interface { Hold(ctx context.Context, w ToolchainWait) End(ctx context.Context, module, fp, how string) bool + // EndRevision ends the revision wait of module's fingerprint, saying how (ran, failed or released), and answers whether + // one was held (design 47 H2 H-A-577 (1)). + EndRevision(ctx context.Context, module, fp, how string) bool } // toolchainWait is the toolchain wait of a module's fingerprint, or false when no language of its plan names a version @@ -100,7 +132,18 @@ func (b *Builder) Release(ctx context.Context, module, fp, why, by string) strin if !b.Waits.End(ctx, module, fp, WaitReleased) { b.mu.Lock() delete(b.released, key) + revision := b.revisionWaiting[key] b.mu.Unlock() + // A step ask's wait for its revision ends as its bound does (design 47 H2 H-A-577 (1)): the ask fails, since a build + // with no version is never made (H-A-155). + if revision { + b.mu.Lock() + b.revisionReleased[key] = true + b.mu.Unlock() + b.pictureMoved() + b.logf("%s: the revision wait is released by %s (%s): the ask fails, nothing is built", key, by, why) + return "" + } return fmt.Sprintf("%s holds no toolchain wait: %s builds a failed key again", key, BuildAgainTool) } b.logf("%s: released by %s (%s): built with the running build module", key, by, why) diff --git a/modules/mesh-delivery-builder/internal/build/waits_test.go b/modules/mesh-delivery-builder/internal/build/waits_test.go index 180b24a46..f6090f717 100644 --- a/modules/mesh-delivery-builder/internal/build/waits_test.go +++ b/modules/mesh-delivery-builder/internal/build/waits_test.go @@ -13,6 +13,7 @@ type memWaits struct { mu sync.Mutex held map[string]ToolchainWait ended []string + ons []string // what each wait held waited on, in the order held } func (w *memWaits) Hold(_ context.Context, t ToolchainWait) { @@ -21,7 +22,20 @@ func (w *memWaits) Hold(_ context.Context, t ToolchainWait) { if w.held == nil { w.held = map[string]ToolchainWait{} } - w.held[t.Module+"."+t.Fingerprint] = t + w.ons = append(w.ons, t.On()) + w.held[t.Module+"."+t.Fingerprint+map[bool]string{true: ".revision"}[t.IsRevision()]] = t +} + +func (w *memWaits) EndRevision(_ context.Context, module, fp, how string) bool { + w.mu.Lock() + defer w.mu.Unlock() + k := module + "." + fp + ".revision" + if _, ok := w.held[k]; !ok { + return false + } + delete(w.held, k) + w.ended = append(w.ended, "revision:"+how) + return true } func (w *memWaits) End(_ context.Context, module, fp, how string) bool { @@ -29,7 +43,7 @@ func (w *memWaits) End(_ context.Context, module, fp, how string) bool { defer w.mu.Unlock() k := module + "." + fp t, ok := w.held[k] - if !ok || (t.Package != "") != (how == WaitPublished) { // as the builder's waitsKept ends them: a package wait by its publishing alone + if !ok || (how != WaitFailed && (t.Package != "") != (how == WaitPublished)) { // as the builder's waitsKept ends them: a package wait by its publishing alone return false } delete(w.held, k) diff --git a/modules/mesh-delivery-builder/internal/versions/again.go b/modules/mesh-delivery-builder/internal/versions/again.go index 3010c1bbe..130d90733 100644 --- a/modules/mesh-delivery-builder/internal/versions/again.go +++ b/modules/mesh-delivery-builder/internal/versions/again.go @@ -11,11 +11,8 @@ type Acts struct { Republish func(ctx context.Context, module, version string) ([]string, error) // DropOldForm drops a retired node from the old form's count by hand (builder_old_form): its answer, or why not. DropOldForm func(ctx context.Context, node, by, why string, at time.Time) (string, error) - // ReserveDone reserves the next version for a done trunk build that reserved none and queues its publish (builder_reserve_done): - // its answer, or why not. - ReserveDone func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) // DropReserved drops a module's reservation of one MAJOR.MINOR by hand (builder_reserved_drop): its answer, or why not. - DropReserved func(ctx context.Context, module, series, by, why string, at time.Time) (string, error) + DropReserved func(ctx context.Context, module, series, version, by, why string, at time.Time) (string, error) // PublishDrop terminates one publish item (builder_publish_drop, design 47 H2 §793): the answer, or why not. PublishDrop func(ctx context.Context, module, version, by, why string) (string, error) } diff --git a/modules/mesh-delivery-builder/internal/versions/publishagain.go b/modules/mesh-delivery-builder/internal/versions/publishagain.go new file mode 100644 index 000000000..8469514e2 --- /dev/null +++ b/modules/mesh-delivery-builder/internal/versions/publishagain.go @@ -0,0 +1,179 @@ +package versions + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + "git.novox.be/novox/mesh-sdk/go/seatlist" +) + +// DefaultRepublishMaxVersions is the setting republish-max-versions' default: the most versions one event queues (design 47 G §633). +const DefaultRepublishMaxVersions = 50 + +// Againer puts the publish of every reserved version again on the events of ADR 0674 §2 (design 47 H2 H-A-606, G §588): the node-engine +// seat's `running` of a module whose catalog entry claims a registry seat, and its `manifest-reads-changed` with `why` `returned` of a +// node a registry seat's holder runs on. Each message is acted on once, by its stream sequence (state `acted`, key `publish:`), +// and queues at most MaxVersions versions per event, newest first, at that holder only; what the work queue holds already is not queued +// again (ADR 0674 §3). +type Againer struct { + Republisher *Republisher + // Acted is the state acted, written with the lifetime of acted-days. + Acted ReserveStore + // Nodes answers each holder of a registry seat with its node, from the seat-holders view (seatlist.HolderNodesIn); nil answers none. + Nodes func(seat string) []seatlist.HolderNode + // MaxVersions is the setting republish-max-versions; zero is DefaultRepublishMaxVersions. + MaxVersions int +} + +func (a *Againer) logf(f string, args ...any) { a.Republisher.logf(f, args...) } + +func againKey(subject string) string { return ActedKey("publish:" + subject) } + +// Heard takes one message of the node-engine seat's running or manifest-reads-changed in, at stream sequence seq, and acts on it once: +// handled is false for a subject that is neither. An error leaves it not acted on, so it is read again. +func (a *Againer) Heard(ctx context.Context, subject string, data []byte, seq uint64) (handled bool, err error) { + running := strings.HasPrefix(subject, strings.TrimSuffix(nodeengine.SubjectRunningAll, "*.*")) + changed := strings.HasPrefix(subject, "mesh.seat.node-engine.event."+nodeengine.EventManifestReadsChanged+".") + if !running && !changed { + return false, nil + } + key := againKey(subject) + raw, rev, found, err := a.Acted.Get(ctx, key) + if err != nil { + return true, fmt.Errorf("the acted sequence of %s cannot be read: %w", subject, err) + } + if found { + var done Acted + if json.Unmarshal(raw, &done) == nil && done.Sequence >= seq { + return true, nil + } + } + var holders func(seat string) []string + if running { + holders = a.runningHolders(ctx, data) + } else { + holders = a.returnedHolders(data) + } + if holders != nil { + if err := a.again(ctx, holders); err != nil { + return true, err + } + } + val, _ := json.Marshal(Acted{Sequence: seq}) + if found { + _, err = a.Acted.Update(ctx, key, val, rev) + } else { + _, err = a.Acted.Create(ctx, key, val) + } + if err != nil && !errors.Is(err, ErrConflict) { + return true, fmt.Errorf("the acted sequence of %s cannot be kept: %w", subject, err) + } + return true, nil +} + +// runningHolders is the holder function of a running: the module that is running holds each registry seat its catalog entry claims. +// nil when it holds none, or when no version waits (no call is made then). +func (a *Againer) runningHolders(ctx context.Context, data []byte) func(seat string) []string { + var ev nodeengine.Running + if err := json.Unmarshal(data, &ev); err != nil || ev.Module == "" { + a.logf("a running that does not read is not acted on: %v", err) + return nil + } + if ev.Stopped || ev.Fingerprint == "" { + return nil + } + if vs, err := a.unreleased(ctx); err != nil || len(vs) == 0 { + return nil + } + e, err := a.Republisher.Entry(ctx, ev.Fingerprint) + if err != nil { + a.logf("the catalog entry %s of %s cannot be read, so no publish is put again for it: %v", ev.Fingerprint, ev.Module, err) + return nil + } + var claimed []string + for _, s := range e.Serves { + if seat, _, _ := strings.Cut(s, "."); slices.Contains(RegistrySeats, seat) && !slices.Contains(claimed, seat) { + claimed = append(claimed, seat) + } + } + if len(claimed) == 0 { + return nil + } + return func(seat string) []string { + if slices.Contains(claimed, seat) { + return []string{ev.Module} + } + return nil + } +} + +// returnedHolders is the holder function of a manifest-reads-changed with why returned: the holders of each registry seat that run on +// the node it names. nil for another why, or when none runs there. +func (a *Againer) returnedHolders(data []byte) func(seat string) []string { + var ev nodeengine.ManifestReadsChanged + if err := json.Unmarshal(data, &ev); err != nil || ev.Node == "" { + a.logf("a manifest-reads-changed that does not read is not acted on: %v", err) + return nil + } + if ev.Why != nodeengine.ManifestReadsChangedWhyReturned || a.Nodes == nil { + return nil + } + on := map[string]string{} + for _, seat := range RegistrySeats { + for _, h := range a.Nodes(seat) { + if h.Node == ev.Node { + on[seat] = h.Module + break + } + } + } + if len(on) == 0 { + return nil + } + return func(seat string) []string { + if m, ok := on[seat]; ok { + return []string{m} + } + return nil + } +} + +// unreleased are the reserved versions whose build is done and with an artifact unpublished. +func (a *Againer) unreleased(ctx context.Context) ([]ReservedVersion, error) { + all, err := a.Republisher.Reserved.All(ctx) + if err != nil { + return nil, err + } + var out []ReservedVersion + for _, v := range all { + if !v.BuiltAt.IsZero() && len(v.Missing()) > 0 { + out = append(out, v) + } + } + return out, nil +} + +// 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 { + vs, err := a.unreleased(ctx) + if err != nil { + return fmt.Errorf("the reserved versions cannot be read: %w", err) + } + if len(vs) == 0 { + return nil + } + max := a.MaxVersions + if max <= 0 { + max = DefaultRepublishMaxVersions + } + queued, err := a.Republisher.queue(ctx, vs, holdersOf, max) + if len(queued) > 0 { + a.logf("publish again on an event: %d versions put on the work queue: %s", len(queued), strings.Join(queued, ", ")) + } + return err +} diff --git a/modules/mesh-delivery-builder/internal/versions/republish.go b/modules/mesh-delivery-builder/internal/versions/republish.go index d2ab90a8f..4e16fb134 100644 --- a/modules/mesh-delivery-builder/internal/versions/republish.go +++ b/modules/mesh-delivery-builder/internal/versions/republish.go @@ -32,7 +32,7 @@ const ( PublishesLocal = "publishes" // ActedState holds, one key per subject, the last stream sequence the builder acted on; capped at ActedMiB. ActedState = "acted" - ActedMiB = 1 + ActedMiB = 4 // PublishQueueTool is builder_publish_queue. PublishQueueTool = "builder_publish_queue" // QueueFull is what version-unreleased says of a version the work queue's cap refused. @@ -137,6 +137,21 @@ type Acted struct { Sequence uint64 `json:"sequence"` } +// OtherBytes is a holder's answer to a publish of a version it holds with other bytes (design 47 H2 H-A-589 (1), H-A-729): the +// digest, and the fingerprint it keeps for the version, empty where none is kept. It is an error of Send, which the publish item +// ends at, never as a refusal asked again: the build again of the fingerprint then takes the next free number (H-A-590 (1)). +type OtherBytes struct { + Seat, Name, Version, Digest, Fingerprint string +} + +func (o *OtherBytes) Error() string { + w := fmt.Sprintf("%s holds %s %s with other bytes: digest %s", o.Seat, o.Name, o.Version, o.Digest) + if o.Fingerprint != "" { + w += ", fingerprint " + o.Fingerprint + } + return w +} + // Publish is one artifact's publish again: what the registry seat's publish takes, without parts. type Publish struct { Seat, Kind, Name, Version, Digest, Fingerprint, Commit, Transfer string @@ -162,6 +177,12 @@ type Republisher struct { // Started is when this run of the builder started: a version whose build ended at or after it is of the live class, one // that ended before it of the start's (H-A-290 (1)). Zero makes every version live. Started time.Time + // Unstored is told the first artifact of a reservation a holder refused as not stored, with the reservation as it stood: the + // builder builds the key again itself (design 47 H2 H-A-662); nil is told none. + Unstored func(ctx context.Context, v ReservedVersion, ref, words string) + // AsHeld is told each artifact a holder answered `other-bytes` for the publish's own fingerprint, newly marked published with the held + // digest (design 47 H2 H-A-738 (1)): the builder says package-published of it; nil says none. + AsHeld func(ctx context.Context, m Marked, digest string) // 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) @@ -215,6 +236,8 @@ func NotStanding(v ReservedVersion, found bool) string { return "its reservation stands no more at the version (released, dropped or taken over)" case hasKey(v.Withdrawn, v.Version): return "its reservation was withdrawn" + case v.Dropped != nil: + return "its publish was dropped by " + v.Dropped.By + ": " + v.Dropped.Why } return "" } @@ -310,6 +333,23 @@ func (r *Republisher) end(ctx context.Context, module, version, why string) { } } +// The forms of the keys of the state acted (design 47 H2 H-A-720): the marks of an event or an ask acted on, each written with the +// lifetime of the setting acted-days, and the release record `released.`, written with none. A key of no form is deleted at +// the start. +const DefaultActedDays = 30 + +var actedMarkForms = []string{EscapeToken("retake:"), EscapeToken("retake-asked:"), EscapeToken("retake-ask:"), EscapeToken("publish:")} + +// ActedFormOf says whether key is a mark (known, with a lifetime) or the release record (known, with none), or of no form. +func ActedFormOf(key string) (mark, known bool) { + for _, f := range actedMarkForms { + if strings.HasPrefix(key, f) { + return true, true + } + } + return false, strings.HasPrefix(key, ReleasedKey("")) +} + // ActedKey is the acted key of a subject. func ActedKey(subject string) string { return EscapeToken(subject) } @@ -351,6 +391,7 @@ func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf errs = append(errs, fmt.Errorf("the catalog entry %s of %s %s cannot be read: %w", v.Fingerprint, v.Module, v.Version, err)) continue } + v = r.fillUpstream(ctx, v, e) byHolder := map[string]map[string]string{} for _, ref := range v.Missing() { if _, no := v.Unstored[ref]; no { @@ -440,6 +481,16 @@ func (r *Republisher) Republish(ctx context.Context, module, version string) ([] vs = append(vs, v) } } + // builder_publish_again asks a dropped publish anew: the drop is cleared in the write before its put (H-A-746). + for i := range vs { + if vs[i].Dropped == nil { + continue + } + if _, err := r.Reserved.ClearDropped(ctx, vs[i].Module, vs[i].Version); err != nil { + return nil, err + } + vs[i].Dropped = nil + } if len(vs) == 0 { return nil, fmt.Errorf("%s holds no reserved version%s with an artifact unpublished", module, map[bool]string{true: " " + version, false: ""}[version != ""]) } @@ -449,7 +500,7 @@ func (r *Republisher) Republish(ctx context.Context, module, version string) ([] // Queued is builder_publish_queue's answer, small at any size of the queue (design 47 H H-A-290 (5)): the queued versions' // count per holder and class with the oldest and newest queue time, the first PublishQueueListCap of them in the order they are -// sent (each with its class), the acted keys with their sequences, and the publish items, counted and capped alike. +// sent (each with its class) and the acted keys with their sequences, counted and capped alike. type Queued struct { Total int `json:"total"` Counts []QueueCount `json:"counts"` @@ -459,10 +510,6 @@ type Queued struct { // Listed says how many of Total the answer lists. Listed int `json:"listed"` Acted map[string]uint64 `json:"acted"` - // ItemCount is how many publish items stand; Items the first of them by their next try (design 47 G A-457a), each with its - // tries and its next try; an item that ended says why. - ItemCount int `json:"item-count"` - Items []PublishItem `json:"items"` // Capped says a state held more than the one page read of it (H-A-293); Read names each such state, the keys read and its // size. Every count above is then of the keys read. Capped bool `json:"capped,omitempty"` @@ -486,27 +533,6 @@ type QueueCount struct { Newest time.Time `json:"newest"` } -// PublishItemKeyPrefix opens the key of a publish item in the builder's re-ask state. -const PublishItemKeyPrefix = "publish." - -// PublishItem is the builder's own record of a version's publish (design 47 G A-457a): a value of the re-ask state, its tries and -// its next try. It is asked when the build ends and at the builder's start, rewritten with one more try and a longer pause after -// each, and deleted when the version is released; after the setting's number of tries it ends, saying so (Answer), and stays. -type PublishItem struct { - Module string `json:"module"` - Version string `json:"version"` - Tries int `json:"tries"` - NextTry time.Time `json:"next-try"` - Why string `json:"why,omitempty"` - Answer string `json:"answer,omitempty"` - Answered time.Time `json:"answered,omitzero"` -} - -// PublishItemKey is the key of module's version's publish item. -func PublishItemKey(module, version string) string { - return PublishItemKeyPrefix + EscapeToken(module) + "." + EscapeToken(version) -} - // PublishQueueOf is the seat mesh-builds' verb publish-queue (design 47 H2 §793; H-A-454): the builder's read of its own work queue // publishes (queue, its items read in bulk, capped past its bound), small at any size of the queue (H-A-290 (5)): the items' count // per holder and class with the oldest and newest queue time, and the first PublishQueueListCap in stream order, the order the @@ -574,10 +600,10 @@ func PublishQueueOf(queue Reader, module, version string) (meshbuilds.PublishQue return out, nil } -// AnswerQueue is builder_publish_queue: the seat mesh-builds' publish-queue answer the builder gave (q, §793, H-A-454) and the two -// states as the tools bundle reads them (H-A-290 (5)), each read in bulk (Reader.All), capped at PublishQueueListCap. -func AnswerQueue(q meshbuilds.PublishQueueAnswer, acted, reasks Reader) (Queued, error) { - out := Queued{Total: int(q.Total), Counts: []QueueCount{}, Queue: []QueuedPublish{}, Listed: int(q.Listed), Acted: map[string]uint64{}, Items: []PublishItem{}} +// AnswerQueue is builder_publish_queue: the seat mesh-builds' publish-queue answer the builder gave (q, §793, H-A-454) and the state +// acted as the tools bundle reads it (H-A-290 (5)), read in bulk (Reader.All), capped at PublishQueueListCap. +func AnswerQueue(q meshbuilds.PublishQueueAnswer, acted Reader) (Queued, error) { + out := Queued{Total: int(q.Total), Counts: []QueueCount{}, Queue: []QueuedPublish{}, Listed: int(q.Listed), Acted: map[string]uint64{}} if q.Capped { out.capped(&StateCapped{State: PublishesLocal, KeysRead: int(q.ItemsRead), StateKeys: uint64(q.QueueItems), StateBytes: uint64(q.QueueBytes)}) } @@ -598,25 +624,6 @@ func AnswerQueue(q meshbuilds.PublishQueueAnswer, acted, reasks Reader) (Queued, out.Acted[k] = a.Sequence } } - rvals, c, err := reasks.values("reasks") - out.capped(c) - if err != nil { - return out, fmt.Errorf("the re-ask state cannot be read: %w", err) - } - for k, raw := range rvals { - if !strings.HasPrefix(k, PublishItemKeyPrefix) { - continue - } - var it PublishItem - if json.Unmarshal(raw, &it) == nil { - out.Items = append(out.Items, it) - } - } - out.ItemCount = len(out.Items) - sort.SliceStable(out.Items, func(i, j int) bool { return out.Items[i].NextTry.Before(out.Items[j].NextTry) }) - if len(out.Items) > PublishQueueListCap { - out.Items = out.Items[:PublishQueueListCap] - } return out, nil } @@ -625,13 +632,12 @@ const PublishQueueDescription = "The versions the builder will publish again (it "how many each registry seat holder's items hold per class (live, a build a pipeline's step waits on, or again, asked again at a start) " + "with the oldest and newest queue time; the first 50 in stream order, the order each holder's one consumer pulls them, each with its class, its artifacts' digests and when it was " + "queued (module, and version, list only that module's, so one item's class can be read); the keys of the state " + ActedState + ", the last stream " + - "sequence the builder acted on for each subject; and the publish items (design 47 G A-457a), counted, the first 50 by next try, each version's " + - "tries and next try, and why one ended (its tries spent, or dropped). A read past its pages is answered capped, naming the items read and the " + + "sequence the builder acted on for each subject. A read past its pages is answered capped, naming the items read and the " + "queue's size (H-A-293). Read-only." // PublishDropDescription is builder_publish_drop's (§793). const PublishDropDescription = "Drop one version's publish (design 47 H2 section 793): its items on the work queue " + PublishesLocal + " are " + - "terminated at every holder, and its publish item ended with who dropped it and why, so it is never sent or put again; builder_publish_again " + + "terminated at every holder, and its reservation says who dropped it and why, so it is never sent or put again (design 47 H2 H-A-746); builder_publish_again " + "asks it anew. A hand act, recorded in the hand-act log first." // PublishAgainDescription is builder_publish_again's description. @@ -687,10 +693,11 @@ 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 handed back with the pause). +// (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). type SendFate struct { - Sent bool - Ended, Failed string + 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, @@ -700,8 +707,8 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate defer cancel() all, err := r.Reserved.All(bound) if err != nil { - r.logf("publish again: %s %s is not sent to %s: its reservation cannot be read: %v; it is handed back", q.Module, q.Version, q.Holder, err) - return SendFate{Failed: "its reservation cannot be read: " + err.Error()} + r.logf("publish again: %s %s is not sent to %s: its reservation cannot be read: %v; it is given again after the ack wait", q.Module, q.Version, q.Holder, err) + return SendFate{Unread: "its reservation cannot be read: " + err.Error()} } var v ReservedVersion found := false @@ -729,9 +736,10 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate e, err := r.Entry(bound, v.Fingerprint) if err != nil { words := fmt.Sprintf("the catalog entry %s cannot be read: %v", v.Fingerprint, err) - r.say(ctx, v, words) - return SendFate{Failed: words} + r.logf("publish again: %s %s is not sent to %s: %s; it is given again after the ack wait", q.Module, q.Version, q.Holder, words) + return SendFate{Unread: words} } + v = r.fillUpstream(ctx, v, e) missing := map[string]bool{} for _, ref := range v.Missing() { missing[ref] = true @@ -748,7 +756,7 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate return SendFate{Ended: "none of its artifacts is left to send: each is published or refused as not stored"} } var failed []string - sent := 0 + sent, held, again := 0, 0, false for _, ref := range refs { seat, name, kind, ok := publishTarget(e, q.Module, ref) if !ok { @@ -762,6 +770,34 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate sent++ continue } + var other *OtherBytes + if errors.As(err, &other) && other.Fingerprint != "" && other.Fingerprint == v.Fingerprint { + // The holder keeps this very build at the version, with the digest of an earlier run of it: the publish is answered as + // published with the held digest, nothing stored (H-A-738 (1)). + marked, _, merr := r.Reserved.MarkHeld(bound, q.Module, v.Version, []HeldArtifact{{Ref: ref, Seat: other.Seat, Name: other.Name, + Version: other.Version, Digest: other.Digest, Fingerprint: other.Fingerprint}}) + if merr != nil { + r.say(ctx, v, ref+": "+merr.Error()) + failed = append(failed, ref+": "+merr.Error()) + continue + } + r.say(ctx, v, fmt.Sprintf("%s %s: %s holds it for this build with the digest %s, built %s: published as held, nothing stored", ref, q.Version, other.Seat, other.Digest, q.Artifacts[ref])) + for _, m := range marked { + if r.AsHeld != nil { + r.AsHeld(ctx, m, other.Digest) + } + } + held++ + continue + } + if errors.As(err, &other) { + // A version the holder holds with other bytes is never published as it stands (ADR 0605 §4): the item ends at once, spending + // no try; the next build of the fingerprint withdraws the number and takes the next free one (H-A-590 (1), H-A-729). + words := fmt.Sprintf("%s %s: %s; built %s, so the number is held for another build and is not published again", ref, q.Version, other, q.Artifacts[ref]) + r.say(ctx, v, words) + r.end(ctx, q.Module, q.Version, words) + return SendFate{Ended: words} + } 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, ": ")) { @@ -769,6 +805,12 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate r.logf("%s %s: the unstored %s is not kept: %v", q.Module, q.Version, ref, merr) } else if ok { r.say(ctx, v, ref+" "+NotStoredWords+words) + // The first of the reservation's artifacts refused as not stored starts the build again, once per reservation: one + // the kept `unstored` already holds starts none (design 47 H2 H-A-662, H-A-703). + if len(v.Unstored) == 0 && !again && r.Unstored != nil { + again = true + r.Unstored(ctx, v, ref, words) + } } continue } @@ -778,12 +820,39 @@ func (r *Republisher) SendQueued(ctx context.Context, q QueuedPublish) SendFate switch { case len(failed) > 0: return SendFate{Failed: strings.Join(failed, "; ")} + case sent == 0 && held > 0: + return SendFate{Ended: "each artifact left is published as the holder holds it for this build"} case sent == 0: return SendFate{Ended: "each artifact left was refused as not stored"} } return SendFate{Sent: true} } +// fillUpstream fills the reservation's `upstream` from the catalog entry at its fingerprint, once, by compare-and-set, so every reader +// of the reservation agrees which of its artifacts a registry never publishes (design 47 H2 H-A-656, amending H-A-486's addendum); +// the reservation as it stands is answered, and a write that fails is said and v answered as it was read. +func (r *Republisher) fillUpstream(ctx context.Context, v ReservedVersion, e meshcatalog.CatalogEntry) ReservedVersion { + if len(v.Upstream) > 0 { + return v + } + var refs []string + for _, a := range e.Artifacts { + if _, in := v.Artifacts[a.Ref]; in && a.Kind == "upstream" { + refs = append(refs, a.Ref) + } + } + if len(refs) == 0 { + return v + } + got, err := r.Reserved.FillUpstream(ctx, v.Module, v.Version, refs) + if err != nil { + r.logf("%s %s: its upstream artifacts %v are not written on the reservation: %v", v.Module, v.Version, refs, err) + v.Upstream = refs + return v + } + return got +} + // publishTarget is the registry seat, the name and the kind module's artifact ref is published as, from its catalog entry; ok is // false when the entry names no registry seat for it. func publishTarget(e meshcatalog.CatalogEntry, module, ref string) (seat, name, kind string, ok bool) { @@ -843,43 +912,102 @@ func (r *Reserver) MarkUnstored(ctx context.Context, module, version, artifact, } } +// MarkDropped records on module's reserved version that its publish was dropped by hand, by whom, why and when, written by compare-and-set +// (design 47 H2 H-A-746). It answers whether the reservation stands at the version; a version not reserved is no publish to drop. +func (r *Reserver) MarkDropped(ctx context.Context, module, version, by, why string, at time.Time) (bool, error) { + return r.setDropped(ctx, module, version, &PublishDropped{By: by, Why: why, At: at.UTC()}) +} + +// ClearDropped clears the drop of module's version: builder_publish_again asks it anew (H-A-746). It answers whether one was cleared. +func (r *Reserver) ClearDropped(ctx context.Context, module, version string) (bool, error) { + return r.setDropped(ctx, module, version, nil) +} + +func (r *Reserver) setDropped(ctx context.Context, module, version string, d *PublishDropped) (bool, error) { + series, _, err := SplitVersion(version) + if err != nil { + return false, err + } + key := ReservedKey(module, series) + for { + cur, rev, found, err := r.get(ctx, key) + if err != nil || !found || cur.Version != version { + return false, err + } + if d == nil && cur.Dropped == nil { + return false, nil + } + cur.Dropped = d + raw, _ := json.Marshal(cur) + if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) { + continue + } else if err != nil { + return false, fmt.Errorf("%s cannot be written: %w", key, err) + } + return true, nil + } +} + // HeldVersion is one version a registry seat's verb versions answers of a name, with its digest. type HeldVersion struct { Version, Digest string + // Fingerprint is the fingerprint the holder keeps for the version (design 47 H2 H-A-589 (3)); empty where none is kept. + Fingerprint string } // HeldArtifact is an artifact of a reservation as a registry seat's record holds it at the reservation's version: its reference, // the seat and the name it is published as, the version and the digest the seat holds. type HeldArtifact struct { Ref, Seat, Name, Version, Digest string + // Fingerprint is the fingerprint the registry keeps for the version, empty where none is kept (design 47 H2 H-A-589 (3)). + Fingerprint string } -// Judged is what the registries' record says of a reserved version's missing artifacts (design 47 H H-A-272, H-A-274, H-A-275): -// those held at the version with the built digest (Held), those held at the version with another digest (Elsewhere), and, when an -// artifact is held at neither, the first one lacking (Lacks). All says every missing artifact is held with its built digest. +// Judged is what the registries' record says of a reserved version's artifacts (design 47 H H-A-272, H-A-274, H-A-275; H2 H-A-588 +// (4), H-A-616, H-A-663): those held at the version for the reservation's fingerprint (Held, with the digest the registry holds), +// those held at the version for another fingerprint or with another digest (Elsewhere), and, when an artifact is held at neither, +// the first one lacking (Lacks). All says every artifact is held for the fingerprint. type Judged struct { Held, Elsewhere []HeldArtifact Lacks string All bool } -// Held judges v's missing artifacts against the registries' record (design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275): each -// artifact's registry seat and name as a publish again sends them, its record read through the seat's verb versions (versionsOf). -// A version with no missing artifact is All. +// heldFor says whether the registry's record h of an artifact at v's version is held for v's fingerprint (design 47 H2 H-A-616, +// H-A-663): a holder that keeps a fingerprint says it, and it is the reservation's or another's; one that keeps none holds it for +// the reservation's fingerprint when its digest is the one the reservation records for the artifact (a kept published is such a +// record), and elsewhere when the reservation records another digest or none. +func heldFor(v ReservedVersion, ref string, h HeldVersion) bool { + if h.Fingerprint != "" { + return h.Fingerprint == v.Fingerprint + } + return v.Artifacts[ref] != "" && h.Digest == v.Artifacts[ref] +} + +// Held judges every artifact of v against the registries' record (design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275; H2 H-A-588 +// (4), H-A-663: an artifact already marked published counts as held when its registry still answers it): each artifact's registry +// seat and name as a publish again sends them, its record read through the seat's verb versions (versionsOf). An upstream artifact +// is never read. A version with no missing artifact is All. func (r *Republisher) Held(ctx context.Context, v ReservedVersion, versionsOf func(ctx context.Context, seat, name string) ([]HeldVersion, error)) (Judged, error) { - missing := v.Missing() - if len(missing) == 0 { + if len(v.Missing()) == 0 { return Judged{All: true}, nil } e, err := r.Entry(ctx, v.Fingerprint) if err != nil { return Judged{}, fmt.Errorf("the catalog entry %s of %s %s cannot be read: %w", v.Fingerprint, v.Module, v.Version, err) } + refs := make([]string, 0, len(v.Artifacts)) + for ref := range v.Artifacts { + if !slices.Contains(v.Upstream, ref) { + refs = append(refs, ref) + } + } + sort.Strings(refs) var out Judged - for _, ref := range missing { + for _, ref := range refs { seat, name, _, ok := publishTarget(e, v.Module, ref) if !ok { - if out.Lacks == "" { + if out.Lacks == "" && !v.Published[ref] { out.Lacks = ref + ": the catalog entry names no registry seat for it" } continue @@ -888,13 +1016,13 @@ func (r *Republisher) Held(ctx context.Context, v ReservedVersion, versionsOf fu if err != nil { return Judged{}, fmt.Errorf("%s's versions of %s cannot be read: %w", seat, name, err) } - at, found := HeldArtifact{}, false + at, found, forF := HeldArtifact{}, false, false for _, h := range held { if strings.TrimPrefix(h.Version, "v") != v.Version { continue } - at, found = HeldArtifact{Ref: ref, Seat: seat, Name: name, Version: h.Version, Digest: h.Digest}, true - if h.Digest == v.Artifacts[ref] { + at, found, forF = HeldArtifact{Ref: ref, Seat: seat, Name: name, Version: h.Version, Digest: h.Digest}, true, heldFor(v, ref, h) + if forF { break } } @@ -903,25 +1031,26 @@ func (r *Republisher) Held(ctx context.Context, v ReservedVersion, versionsOf fu if out.Lacks == "" { out.Lacks = fmt.Sprintf("%s holds no %s %s", seat, name, v.Version) } - case at.Digest == v.Artifacts[ref]: + case forF: out.Held = append(out.Held, at) default: out.Elsewhere = append(out.Elsewhere, at) } } - out.All = len(out.Held) == len(missing) + out.All = out.Lacks == "" && len(out.Elsewhere) == 0 && len(out.Held) > 0 return out, nil } -// HeldNumbers are the versions (MAJOR.MINOR.PATCH) a registry seat's record holds of any of module's artifacts refs, as the catalog -// entry of fingerprint names their seats and names (design 47 H H-A-275): a number one holds is never reserved. An artifact the -// entry names no registry seat for is read nowhere. -func (r *Republisher) HeldNumbers(ctx context.Context, module, fingerprint string, refs []string, versionsOf func(ctx context.Context, seat, name string) ([]HeldVersion, error)) ([]string, error) { +// HeldRecords are the versions (MAJOR.MINOR.PATCH) a registry seat's record holds of any of module's artifacts refs, as the catalog +// entry of fingerprint names their seats and names (design 47 H H-A-275), one record per artifact and version with the digest and the +// fingerprint the registry keeps (H2 H-A-590 (1)): a number one holds is never reserved. An artifact the entry names no registry seat +// for is read nowhere. +func (r *Republisher) HeldRecords(ctx context.Context, module, fingerprint string, refs []string, versionsOf func(ctx context.Context, seat, name string) ([]HeldVersion, error)) ([]HeldArtifact, error) { e, err := r.Entry(ctx, fingerprint) if err != nil { return nil, fmt.Errorf("the catalog entry %s of %s cannot be read: %w", fingerprint, module, err) } - var out []string + var out []HeldArtifact for _, ref := range refs { seat, name, _, ok := publishTarget(e, module, ref) if !ok { @@ -932,8 +1061,8 @@ func (r *Republisher) HeldNumbers(ctx context.Context, module, fingerprint strin return out, fmt.Errorf("%s's versions of %s cannot be read: %w", seat, name, err) } for _, h := range held { - if v := strings.TrimPrefix(h.Version, "v"); v != "" && !slices.Contains(out, v) { - out = append(out, v) + if v := strings.TrimPrefix(h.Version, "v"); v != "" { + out = append(out, HeldArtifact{Ref: ref, Seat: seat, Name: name, Version: v, Digest: h.Digest, Fingerprint: h.Fingerprint}) } } } diff --git a/modules/mesh-delivery-builder/internal/versions/republish_test.go b/modules/mesh-delivery-builder/internal/versions/republish_test.go index 0f78961f4..926eff578 100644 --- a/modules/mesh-delivery-builder/internal/versions/republish_test.go +++ b/modules/mesh-delivery-builder/internal/versions/republish_test.go @@ -13,8 +13,10 @@ import ( "testing" "time" + "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/seatlist" ) // republishBed is a Republisher over memory states: reservations of module m (a bundle by the oci seat and a Go package by @@ -29,7 +31,8 @@ type republishBed struct { sent []Publish said []string ended []string - refuse string // the words Send fails with, empty for none + refuse string // the words Send fails with, empty for none + other *OtherBytes // the holder's answer of a version held with other bytes (H-A-729) // holders are the registry seats' holders the seat-holders view names (design 47 G A-416). holders map[string][]string // puts are the items the work queue took; window deduplicates by message id; full refuses every put; held keeps the puts @@ -58,6 +61,9 @@ func newRepublishBed(t *testing.T) *republishBed { b.mu.Lock() defer b.mu.Unlock() b.sent = append(b.sent, p) + if b.other != nil { + return b.other + } if b.refuse != "" { return errors.New(b.refuse) } @@ -163,6 +169,66 @@ func TestRepublish(t *testing.T) { t.Errorf("sent %d, said %v: want one try and one saying of not stored", len(b.sent), b.said) } }) + t.Run("a reservation with no upstream gets it from the entry once", func(t *testing.T) { + // design 47 H2 H-A-656: the republisher's read of the entry fills the reservation's upstream by compare-and-set, so the + // artifact a registry never publishes is no missing one and no entry "names no registry seat" for it + b := newRepublishBed(t) + v := b.reserve(t, "m") + entry := b.Entry + b.Entry = func(ctx context.Context, fp string) (meshcatalog.CatalogEntry, error) { + e, err := entry(ctx, fp) + e.Artifacts = append(e.Artifacts, meshcatalog.Artifact{Ref: "m:up", Kind: "upstream"}) + return e, err + } + if _, _, err := b.Reserved.Built(ctx, "m", v.Version, map[string]string{"m:up": "sha256:cc"}, nil); err != nil { + t.Fatal(err) + } + b.holders = map[string][]string{SeatArtifacts: {"oci"}} + b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)) + cur, _, _ := b.Reserved.At(ctx, ReservedKey("m", "0.1")) + if !slices.Equal(cur.Upstream, []string{"m:up"}) || slices.Contains(cur.Missing(), "m:up") { + t.Errorf("the reservation's upstream is %v, missing %v; want m:up filled once and not missing", cur.Upstream, cur.Missing()) + } + }) + t.Run("a version held with other bytes ends the item at once, no try spent", func(t *testing.T) { + // design 47 H2 H-A-590 (2), H-A-729: never asked again as it stands; the next build of the fingerprint takes another number + b := newRepublishBed(t) + v := b.reserve(t, "m") + b.other = &OtherBytes{Seat: SeatArtifacts, Name: "m/prog", Version: v.Version, Digest: "sha256:zz", Fingerprint: "src2:other"} + f := b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)) + if f.Ended == "" || f.Failed != "" || f.Sent || len(b.sent) != 1 || fmt.Sprint(b.ended) != "[m "+v.Version+"]" || !strings.Contains(f.Ended, "sha256:zz") { + t.Errorf("%+v, sent %d, ended %v: want the item ended at once naming the other digest, and no failure to try again", f, len(b.sent), b.ended) + } + }) + t.Run("a version held with other bytes for the publish's own fingerprint ends as published with the held digest", func(t *testing.T) { + // design 47 H2 H-A-738 (1): equal fingerprints answer as published, nothing stored, the held digest on the reservation + b := newRepublishBed(t) + v := b.reserve(t, "m") + var said []string + b.AsHeld = func(_ context.Context, m Marked, digest string) { said = append(said, m.Artifact+" "+digest) } + b.other = &OtherBytes{Seat: SeatArtifacts, Name: "m/prog", Version: v.Version, Digest: "sha256:zz", Fingerprint: v.Fingerprint} + f := b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)) + cur, _, _ := b.Reserved.At(ctx, ReservedKey("m", "0.1")) + if f.Ended == "" || f.Failed != "" || f.Sent || len(b.ended) != 0 || !cur.Published["m:prog"] || cur.Artifacts["m:prog"] != "sha256:zz" || fmt.Sprint(said) != "[m:prog sha256:zz]" { + t.Errorf("%+v, ended %v, published %v, digest %q, said %v: want published with the held digest, said once, no refusal", f, b.ended, cur.Published, cur.Artifacts["m:prog"], said) + } + }) + t.Run("the first artifact refused as not stored starts the build again once", func(t *testing.T) { + // design 47 H2 H-A-662, H-A-703: one start per reservation, whatever number of its artifacts are refused + b := newRepublishBed(t) + v := b.reserve(t, "m") + var started []string + b.Unstored = func(_ context.Context, v ReservedVersion, ref, _ string) { + started = append(started, v.Version+" "+ref) + } + b.refuse = "oci-artifact-registry's publish of m/prog: not stored: no blob sha256:aa" + b.holders = map[string][]string{SeatArtifacts: {"oci"}} + b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)) + b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)) + if len(started) != 1 || started[0] != v.Version+" m:prog" { + t.Errorf("the build again was started %v, want once for %s", started, v.Version) + } + }) t.Run("a refusal in other words is said each time", func(t *testing.T) { b := newRepublishBed(t) b.reserve(t, "m") @@ -234,15 +300,6 @@ func TestRepublish(t *testing.T) { } b.holders = map[string][]string{SeatArtifacts: {"oci"}} _, _ = b.Republish(ctx, "", "") - items := Reader{Keys: func() ([]string, error) { return []string{"publish.m.0.1.0", "reserve-done.m.x"}, nil }, - Get: func(k string) (json.RawMessage, bool, error) { - return json.RawMessage(`{"mode":"publish","module":"m","version":"0.1.0","tries":3,"next-try":"2026-11-17T01:00:00Z","why":"w"}`), true, nil - }} - none := Reader{Keys: func() ([]string, error) { return nil, nil }} - answer, err := answerOf(none, none, items, "", "") - if err != nil || len(answer.Items) != 1 || answer.Items[0].Tries != 3 || answer.Items[0].Version != "0.1.0" { - t.Errorf("builder_publish_queue items = %+v (%v), want the one publish item with its tries", answer.Items, err) - } }) } @@ -262,6 +319,11 @@ func TestTheRegistriesRecordSaysWhetherAVersionIsHeld(t *testing.T) { {name: "held in the Go form with the built digest", holds: []HeldVersion{{Version: "v0.1.36", Digest: "sha256:z"}, {Version: "v0.1.37", Digest: "sha256:a"}}, all: true}, {name: "another digest at the version", holds: []HeldVersion{{Version: "0.1.37", Digest: "sha256:b"}}, elsewhere: true}, {name: "the version lacked", holds: []HeldVersion{{Version: "0.1.36", Digest: "sha256:a"}}, lacks: true}, + // H2 H-A-616: no fingerprint kept: held for F when the digest is the reserved one, elsewhere with another + {name: "no fingerprint kept, the reserved digest", holds: []HeldVersion{{Version: "0.1.37", Digest: "sha256:a"}}, all: true}, + // H2 H-A-589 (3): a holder that keeps a fingerprint says whose it is, whatever the digest + {name: "the fingerprint kept is F's", holds: []HeldVersion{{Version: "0.1.37", Digest: "sha256:b", Fingerprint: "fp"}}, all: true}, + {name: "the fingerprint kept is another's", holds: []HeldVersion{{Version: "0.1.37", Digest: "sha256:a", Fingerprint: "other"}}, elsewhere: true}, } { t.Run(c.name, func(t *testing.T) { var seat, name string @@ -273,7 +335,7 @@ func TestTheRegistriesRecordSaysWhetherAVersionIsHeld(t *testing.T) { if c.lacks && !strings.Contains(j.Lacks, "0.1.37") { t.Errorf("what the registry lacks is said as %q", j.Lacks) } - nums, err := r.HeldNumbers(ctx, "m", "fp", []string{"m:lib"}, versionsOf) + nums, err := r.HeldRecords(ctx, "m", "fp", []string{"m:lib"}, versionsOf) if err != nil || len(nums) != len(c.holds) { t.Errorf("the held numbers are %v (%v), want one per version the seat holds", nums, err) } @@ -283,6 +345,20 @@ func TestTheRegistriesRecordSaysWhetherAVersionIsHeld(t *testing.T) { if j, err := r.Held(ctx, v, nil); err != nil || !j.All { t.Errorf("a version with no missing artifact is judged %+v (%v), want all held without a read", j, err) } + // H2 H-A-663: a kept published counts as held while its registry answers it at the version, and no longer when it does not + v.Published, v.Artifacts = map[string]bool{"m:lib": true, "m:other": true}, map[string]string{"m:lib": "sha256:a", "m:other": "sha256:o"} + v.Upstream = nil + entry.Artifacts = append(entry.Artifacts, meshcatalog.Artifact{Ref: "m:other", Kind: "package", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "git.example/o"}}) + v.Published["m:other"] = false + both := func(_ context.Context, _, n string) ([]HeldVersion, error) { + if n == "git.example/o" { + return nil, nil + } + return []HeldVersion{{Version: "0.1.37", Digest: "sha256:a"}}, nil + } + if j, err := r.Held(ctx, v, both); err != nil || j.All || len(j.Held) != 1 || j.Held[0].Ref != "m:lib" || !strings.Contains(j.Lacks, "git.example/o") { + t.Errorf("a kept published its registry answers is judged %+v (%v), want it held and the other lacking", j, err) + } } // queueAt writes a queued version of module m at holder oci directly, as a start finds it. @@ -381,12 +457,51 @@ func TestAQueuedItemIsSentWhileItsBuildStands(t *testing.T) { if f := b.SendQueued(ctx, b.queueAt(w, PublishClassLive, b.now)); f.Failed == "" || f.Sent { t.Errorf("a refusal in other words answered %+v, want it failed, handed back", f) } + // design 47 H2 H-A-745: a read of the builder's own state that fails is no answer of a holder: nothing is sent or said and the + // item is left to be given again, while an answered failure above ended it. + x := b.reserve(t, "x") + sent, said := len(b.sent), len(b.said) + entry := b.Entry + b.Entry = func(context.Context, string) (meshcatalog.CatalogEntry, error) { + return meshcatalog.CatalogEntry{}, errors.New("the catalog is down") + } + if f := b.SendQueued(ctx, b.queueAt(x, PublishClassLive, b.now)); f.Unread == "" || f.Failed != "" || f.Ended != "" || f.Sent || len(b.sent) != sent || len(b.said) != said { + t.Errorf("an unreadable entry answered %+v, sent %d more, said %d more: want it unread, nothing sent or said", f, len(b.sent)-sent, len(b.said)-said) + } + b.Entry = entry + b.reserved.mem.down = errors.New("the state is down") + if f := b.SendQueued(ctx, b.queueAt(x, PublishClassLive, b.now)); f.Unread == "" || f.Failed != "" || f.Ended != "" || f.Sent || len(b.sent) != sent { + t.Errorf("an unreadable reservation answered %+v: want it unread", 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) { + b := newRepublishBed(t) + v := b.reserve(t, "d") + b.held = true + b.holders = map[string][]string{SeatArtifacts: {"oci"}} + if found, err := b.Reserved.MarkDropped(ctx, "d", v.Version, "op@node", "a test drops it", b.now); err != nil || !found { + t.Fatalf("drop: %v %v", found, err) + } + if _, err := b.Republish(ctx, "", ""); err != nil || len(b.puts) != 0 { + t.Errorf("an event put %d items (%v), want the dropped version passed over", len(b.puts), err) + } + if f := b.SendQueued(ctx, b.queueAt(v, PublishClassLive, b.now)); f.Ended == "" || !strings.Contains(f.Ended, "op@node") || len(b.sent) != 0 { + t.Errorf("a send of the dropped version answered %+v, sent %d: want it ended unsent, naming who dropped it", f, len(b.sent)) + } + if _, err := b.Republish(ctx, "d", v.Version); err != nil || len(b.puts) != 1 { + t.Errorf("builder_publish_again put %d items (%v), want the one", len(b.puts), err) + } + if cur, ok, err := b.Reserved.Of(ctx, "d", v.Version); err != nil || !ok || cur.Dropped != nil { + t.Errorf("after builder_publish_again the reservation is %+v (%v), want its drop cleared", cur, err) + } }) } // answerOf is builder_publish_queue whole: the builder's verb publish-queue over its work queue (queue), then the tool over the -// verb's answer and the two states (design 47 H2 §793, H-A-454). -func answerOf(queue, acted, reasks Reader, module, version string) (Queued, error) { +// verb's answer and the state (design 47 H2 §793, H-A-454). +func answerOf(queue, acted Reader, module, version string) (Queued, error) { q, err := PublishQueueOf(queue, module, version) if err != nil { return Queued{}, err @@ -399,7 +514,7 @@ func answerOf(queue, acted, reasks Reader, module, version string) (Queued, erro if err := json.Unmarshal(raw, &heard); err != nil { return Queued{}, err } - return AnswerQueue(heard, acted, reasks) + return AnswerQueue(heard, acted) } // TestThePublishQueueToolAnswersAtAnySize: design 47 H H-A-290 (5) — builder_publish_queue over two thousand queued versions answers @@ -426,7 +541,7 @@ func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) { Get: func(k string) (json.RawMessage, bool, error) { gets++; v, ok := vals[k]; return v, ok, nil }} none := Reader{Keys: func() ([]string, error) { return nil, nil }} start := time.Now() - a, err := answerOf(queue, none, none, "", "") + a, err := answerOf(queue, none, "", "") took := time.Since(start) raw, _ := json.Marshal(a) if err != nil || took > time.Second || a.Total != 2000 || len(a.Queue) != PublishQueueListCap || a.Listed != PublishQueueListCap || len(raw) > 64<<10 || gets != 0 { @@ -440,7 +555,7 @@ func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) { t.Fatalf("the list holds %s at %d, want m%d: the items in stream order, whatever their holder or class", q.Module, i, i) } } - one, err := answerOf(queue, none, none, "m1995", "") + one, err := answerOf(queue, none, "m1995", "") if err != nil || len(one.Queue) != 1 || one.Queue[0].Class != PublishClassLive || one.Total != 2000 { t.Errorf("one module's answer %+v (%v), want its item with its class", one.Queue, err) } @@ -448,12 +563,98 @@ func TestThePublishQueueToolAnswersAtAnySize(t *testing.T) { t.Errorf("a state one page holds is answered capped: %+v", a.Read) } queue.All = func() (StatePage, error) { return StatePage{Values: vals, More: true, Keys: 5000, Bytes: 3 << 20}, nil } - if c, err := answerOf(queue, none, none, "", ""); err != nil || !c.Capped || len(c.Read) != 1 || c.Read[0].State != PublishesLocal || + if c, err := answerOf(queue, none, "", ""); err != nil || !c.Capped || len(c.Read) != 1 || c.Read[0].State != PublishesLocal || c.Read[0].KeysRead != 2000 || c.Read[0].StateKeys != 5000 || c.Read[0].StateBytes != 3<<20 || c.Total != 2000 { t.Errorf("a state past its one page answered capped %v, read %+v (%v): want capped, 2000 keys read of 5000, its size said (H-A-293)", c.Capped, c.Read, err) } queue.All = func() (StatePage, error) { return StatePage{}, errors.ErrUnsupported } - if b, err := answerOf(queue, none, none, "", ""); err != nil || b.Total != 2000 || gets != 2000 { + if b, err := answerOf(queue, none, "", ""); err != nil || b.Total != 2000 || gets != 2000 { t.Errorf("a reader with no bulk read answered %d (%v) with %d single reads, want every key read one by one", b.Total, err, gets) } } + +// Design 47 H2 H-A-720: the forms of the keys of the state acted: marks take a lifetime, the release record none, any other key of no +// form is deleted at the start. +func TestActedKeysHaveForms(t *testing.T) { + for _, c := range []struct { + key string + mark, known bool + }{ + {ActedKey("retake:mesh.seat.node-engine.event.running.ace.m"), true, true}, + {ActedKey("retake-asked:m\x00abc"), true, true}, + {ActedKey("retake-ask:ask-1"), true, true}, + {ReleasedKey("m"), false, true}, + {"junk", false, false}, + {ActedKey("publish:mesh.seat.node-engine.event.running.ace.oci"), true, true}, + } { + if mark, known := ActedFormOf(c.key); mark != c.mark || known != c.known { + t.Errorf("%q: mark %v, known %v, want %v, %v", c.key, mark, known, c.mark, c.known) + } + } +} + +// TestAPublishIsPutAgainOnAHoldersEventsOnceBySequence: design 47 H2 H-A-606 (ADR 0674 §2, §3) — a registry holder's running and a +// returned of its node put each unreleased version again, at that holder, once per stream sequence, at most the bound per event, newest +// first; a module that holds no registry seat, a stopped running and another node's returned put nothing; a mark is kept for each. +func TestAPublishIsPutAgainOnAHoldersEventsOnceBySequence(t *testing.T) { + ctx := context.Background() + b := newRepublishBed(t) + b.window = true + b.reserve(t, "m1") + b.reserve(t, "m2") + b.reserve(t, "m3") + acted := &reserveMem{mem: newMem()} + a := &Againer{Republisher: b.Republisher, Acted: acted, MaxVersions: 2, + Nodes: func(seat string) []seatlist.HolderNode { + if seat == SeatArtifacts { + return []seatlist.HolderNode{{Module: "holder", Node: "ace"}} + } + return nil + }} + running := func(module, fp string, stopped bool) []byte { + raw, _ := json.Marshal(nodeengine.Running{Module: module, Node: "ace", Fingerprint: fp, Stopped: stopped}) + return raw + } + sub := "mesh.seat.node-engine.event.running.ace." + puts := func() []string { + var out []string + for _, q := range b.puts { + out = append(out, q.Holder+" "+q.Module) + } + return out + } + if handled, err := a.Heard(ctx, "mesh.seat.node-engine.event.other.ace", nil, 1); handled || err != nil { + t.Fatalf("another subject: handled %v, %v", handled, err) + } + for _, c := range []struct { + name, subject string + data []byte + seq uint64 + want []string + }{ + {"a module that holds no registry seat", sub + "m1", running("m1", "src2:m1", false), 2, nil}, + {"a stopped holder", sub + "holder", running("holder", "src2:holder", true), 3, nil}, + {"the holder's running, two of three versions, newest first", sub + "holder", running("holder", "src2:holder", false), 4, []string{"holder m3", "holder m2"}}, + {"the same sequence heard again", sub + "holder", running("holder", "src2:holder", false), 4, nil}, + {"another node's return", "mesh.seat.node-engine.event.manifest-reads-changed.bee", mustJSON(nodeengine.ManifestReadsChanged{Node: "bee", Why: nodeengine.ManifestReadsChangedWhyReturned}), 5, nil}, + {"a change that is no return", "mesh.seat.node-engine.event.manifest-reads-changed.ace", mustJSON(nodeengine.ManifestReadsChanged{Node: "ace", Why: "changed"}), 6, nil}, + {"the holder's node returned", "mesh.seat.node-engine.event.manifest-reads-changed.ace", mustJSON(nodeengine.ManifestReadsChanged{Node: "ace", Why: nodeengine.ManifestReadsChangedWhyReturned}), 7, []string{"holder m3", "holder m2"}}, + } { + b.puts, b.ids = nil, map[string]bool{} + handled, err := a.Heard(ctx, c.subject, c.data, c.seq) + 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) + } + } + if _, _, found, _ := acted.Get(ctx, againKey(sub+"holder")); !found { + t.Error("the running's mark is not kept in the state acted") + } +} + +func mustJSON(v any) []byte { + raw, err := json.Marshal(v) + if err != nil { + panic(err) + } + return raw +} diff --git a/modules/mesh-delivery-builder/internal/versions/reserve.go b/modules/mesh-delivery-builder/internal/versions/reserve.go index a6a3a55e9..800f42199 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve.go @@ -31,8 +31,6 @@ const ( // ReservedTool is builder_reserved, ReservedDropTool builder_reserved_drop. ReservedTool = "builder_reserved" ReservedDropTool = "builder_reserved_drop" - // ReserveDoneTool is builder_reserve_done (design 47 G A-455). - ReserveDoneTool = "builder_reserve_done" // 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 @@ -77,6 +75,9 @@ type ReservedVersion struct { // Unstored are the artifacts a holder refused as not stored, with its words: said once, and not published again on // events (design 47 G §588); builder_build_again builds the key again, which reserves anew. Unstored map[string]string `json:"unstored,omitempty"` + // Dropped is who dropped the version's publish by hand (builder_publish_drop), why and when: a fate of the version, read as the + // rest of its standing (NotStanding), so no event, item or send passes it; builder_publish_again clears it (design 47 H2 H-A-746). + Dropped *PublishDropped `json:"dropped,omitempty"` // Branch and Source are the watched branch and the source revision of the catalog revision whose entry the build came from // (design 47 G §371, A-57): what `package-published` says of the publication. Branch string `json:"branch,omitempty"` @@ -95,6 +96,13 @@ type ReservedVersion struct { Withdrawn map[string]string `json:"withdrawn,omitempty"` } +// PublishDropped is a publish dropped by hand: who, why and when (design 47 H2 H-A-746). +type PublishDropped struct { + By string `json:"by"` + Why string `json:"why"` + At time.Time `json:"at"` +} + // markPublished marks artifact a published at at, the moment the builder heard or confirmed its publish (H-A-331). func (v *ReservedVersion) markPublished(a string, at time.Time) { if v.Published == nil { @@ -161,28 +169,46 @@ type Reserver struct { // Logf says an index write that failed (H-A-269 (1)): the reservation stands, and Reindex writes its index at the next // start. Nil says nothing. Logf func(string, ...any) - // HeldNumbers are the versions a registry seat's record holds of any of module's artifacts (design 47 H H-A-275), read before a - // number is reserved: a number one holds is skipped. Nil reads none; a read that fails is said and the reserve proceeds. - HeldNumbers func(ctx context.Context, module, fingerprint string, refs []string) ([]string, error) + // HeldRecords are the versions a registry seat's record holds of any of module's artifacts (design 47 H H-A-275), each with the + // digest and the fingerprint the registry keeps, read before a number is reserved: a number one holds is skipped, and a + // standing reservation whose number one holds for another build is withdrawn (design 47 H2 H-A-590 (1)). Nil reads none; a + // read that fails is said and the reserve proceeds. + HeldRecords func(ctx context.Context, module, fingerprint string, refs []string) ([]HeldArtifact, error) // HeldElsewhere is told the numbers of module a reserve skipped because a registry holds them (H-A-275); nil is told none. HeldElsewhere func(ctx context.Context, module string, skipped []string) + // MovedFrom is told a standing reservation a reserve withdrew because a registry holds an artifact at its number for another + // build, with those artifacts (H-A-590 (1), H-A-279); nil is told none. + MovedFrom func(ctx context.Context, v ReservedVersion, elsewhere []HeldArtifact) } -// heldNumbers are the patches of series a registry holds of module's artifacts (H-A-275); a read that fails is said, and none. -func (r *Reserver) heldNumbers(ctx context.Context, module, series, fingerprint string, refs []string) map[int]bool { - if r.HeldNumbers == nil { - return nil +// heldNumbers are the patches of series a registry holds of module's artifacts (H-A-275), and the records they come from; a read +// that fails is said, and none. +func (r *Reserver) heldNumbers(ctx context.Context, module, series, fingerprint string, refs []string) (map[int]bool, []HeldArtifact) { + if r.HeldRecords == nil { + return nil, nil } - vs, err := r.HeldNumbers(ctx, module, fingerprint, refs) + recs, err := r.HeldRecords(ctx, module, fingerprint, refs) if err != nil { r.said(fmt.Errorf("%s: the registries' versions are not read before reserving, so a number they hold is not skipped: %w", module, err)) } out := map[int]bool{} - for _, v := range vs { - if s, p, err := SplitVersion(v); err == nil && s == series { + for _, h := range recs { + if s, p, err := SplitVersion(strings.TrimPrefix(h.Version, "v")); err == nil && s == series { out[p] = true } } + return out, recs +} + +// heldElsewhereAt are the records of recs at v's number held for another build (design 47 H2 H-A-590 (1), H-A-616): the registry +// keeps another fingerprint, or none and the reservation records another digest or none for the artifact. +func heldElsewhereAt(v ReservedVersion, recs []HeldArtifact) []HeldArtifact { + var out []HeldArtifact + for _, h := range recs { + if strings.TrimPrefix(h.Version, "v") == v.Version && !heldFor(v, h.Ref, HeldVersion{Version: h.Version, Digest: h.Digest, Fingerprint: h.Fingerprint}) { + out = append(out, h) + } + } return out } @@ -243,13 +269,22 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts } } key := ReservedKey(module, series) - held := r.heldNumbers(ctx, module, series, src.Fingerprint, artifacts) + held, records := r.heldNumbers(ctx, module, series, src.Fingerprint, artifacts) for { cur, rev, found, err := r.get(ctx, key) if err != nil { return ReservedVersion{}, err } withdrawn := found && hasKey(cur.Withdrawn, cur.Version) // a number a registry holds elsewhere (H-A-279) + // A standing reservation of this fingerprint whose number a registry holds for another build, or for none the reservation + // records, is withdrawn now, as the done build's path withdraws it (design 47 H2 H-A-590 (1)); the next number no registry holds + // is taken. A read that did not answer left no record: the standing number is kept. + var elsewhere []HeldArtifact + if found && !withdrawn && cur.Fingerprint == src.Fingerprint && cur.Fingerprint != "" { + if elsewhere = heldElsewhereAt(cur, records); len(elsewhere) > 0 { + withdrawn = true + } + } if found && !withdrawn && cur.Fingerprint == src.Fingerprint && cur.Fingerprint != "" && !slices.Contains(released, cur.Version) { if _, p, err := SplitVersion(cur.Version); err == nil && p > high { return cur, nil // kept until released (H-A-225); one at or below the catalog's highest can never be released @@ -270,7 +305,7 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts out.Upstream = slices.Clone(src.Upstream) if found { out.Withdrawn = maps.Clone(cur.Withdrawn) - if cur.Fingerprint != src.Fingerprint { + if cur.Fingerprint != src.Fingerprint || len(elsewhere) > 0 { if out.Withdrawn == nil { out.Withdrawn = map[string]string{} } @@ -301,6 +336,9 @@ func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts if len(skipped) > 0 && r.HeldElsewhere != nil { r.HeldElsewhere(ctx, module, skipped) } + if len(elsewhere) > 0 && r.MovedFrom != nil { + r.MovedFrom(ctx, cur, elsewhere) + } if found && r.Took != nil { r.Took(ctx, cur, out) } @@ -416,6 +454,91 @@ func allSet(m map[string]string) bool { return true } +// MarkHeld writes on module's reservation of version each artifact a registry holds at the version for the reservation's +// fingerprint, with the held digest, and marks it published when it was not, in one compare-and-set; in the same write each +// artifact that is neither held nor marked published loses its recorded digest and the reservation its built-at, since what +// the registries do not hold is built again (design 47 H2 H-A-588 (4), H-A-664; unstored is kept). It answers the artifacts it +// newly marked, and false when the reservation stands at another version. +func (r *Reserver) MarkHeld(ctx context.Context, module, version string, held []HeldArtifact) ([]Marked, bool, error) { + series, _, err := SplitVersion(version) + if err != nil { + return nil, false, err + } + key := ReservedKey(module, series) + for { + cur, rev, found, err := r.get(ctx, key) + if err != nil || !found || cur.Version != version { + return nil, false, err + } + was := cur + was.Artifacts, was.Published, was.PublishedAt = maps.Clone(cur.Artifacts), maps.Clone(cur.Published), maps.Clone(cur.PublishedAt) + var marked []Marked + changed := false + if cur.Artifacts == nil { + cur.Artifacts = map[string]string{} + } + isHeld := map[string]bool{} + for _, h := range held { + isHeld[h.Ref] = true + if cur.Artifacts[h.Ref] != h.Digest { + cur.Artifacts[h.Ref], changed = h.Digest, true + } + if !cur.Published[h.Ref] { + cur.markPublished(h.Ref, r.now()) + marked, changed = append(marked, Marked{Artifact: h.Ref}), true + } + } + for ref, d := range cur.Artifacts { + if d != "" && !isHeld[ref] && !cur.Published[ref] && !slices.Contains(cur.Upstream, ref) { + cur.Artifacts[ref], changed = "", true + } + } + if !cur.BuiltAt.IsZero() && !allSet(cur.Artifacts) { + cur.BuiltAt, changed = time.Time{}, true + } + if !changed { + return nil, true, nil + } + raw, _ := json.Marshal(cur) + if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) { + continue + } else if err != nil { + return nil, false, fmt.Errorf("%s cannot be written: %w", key, err) + } + r.said(r.reindex(ctx, key, was, cur)) + for i := range marked { + marked[i].Reserved = cur + } + return marked, true, nil + } +} + +// FillUpstream writes the artifacts of kind upstream on module's reservation of version when it names none, once, by +// compare-and-set (design 47 H2 H-A-656); it answers the reservation as it stands (one that names some, or stands at another +// version, is answered unchanged). +func (r *Reserver) FillUpstream(ctx context.Context, module, version string, refs []string) (ReservedVersion, error) { + series, _, err := SplitVersion(version) + if err != nil { + return ReservedVersion{}, err + } + key := ReservedKey(module, series) + for { + cur, rev, found, err := r.get(ctx, key) + if err != nil || !found || cur.Version != version || len(cur.Upstream) > 0 { + return cur, err + } + cur.Upstream = slices.Clone(refs) + sort.Strings(cur.Upstream) + raw, _ := json.Marshal(cur) + if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) { + continue + } else if err != nil { + return ReservedVersion{}, fmt.Errorf("%s cannot be written: %w", key, err) + } + return cur, nil + } +} + // DefaultReleasedKept is the setting released-kept unless set (design 47 G A-456b). const DefaultReleasedKept = 16 @@ -510,47 +633,6 @@ func (r *Reserver) PublishedOf(ctx context.Context, module, artifact, fingerprin return meshbuilds.PublishedAnswer{Published: false}, nil } -// VersionAt answers the version artifact of module is published at from the source revision of branch (design 47 H2 H-A-547 -// (3), H-A-551): the standing reservation of that branch and source revision whose artifact a registry seat said published, its -// number not withdrawn, first; else the module's release recorded at that branch and source revision (H-A-558 (2)), the newest such. A reservation of -// that origin not yet published answers none, so the importer's build waits for the publish (H-A-521). -func (r *Reserver) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) { - if module == "" || artifact == "" || source <= 0 { - return "", false, nil - } - ref := module + ":" + artifact - keys, err := r.Store.KeysOf(ctx, NameFilter(module)) - if err != nil { - return "", false, fmt.Errorf("the reservations of %s cannot be listed: %w", module, err) - } - sort.Strings(keys) - for _, k := range keys { - cur, _, found, err := r.get(ctx, k) - if err != nil { - return "", false, err - } - if found && cur.Module == module && cur.Branch == branch && cur.Source == source && cur.Published[ref] && !hasKey(cur.Withdrawn, cur.Version) { - return cur.Version, true, nil - } - } - if r.Releases == nil { - return "", false, nil - } - raw, _, found, err := r.Releases.Get(ctx, ReleasedKey(module)) - if err != nil { - return "", false, fmt.Errorf("the releases of %s cannot be read: %w", module, err) - } - var rec ReleasedRecord - if found && json.Unmarshal(raw, &rec) == nil { - for i := len(rec.Kept) - 1; i >= 0; i-- { - if rec.Kept[i].Branch == branch && rec.Kept[i].Source == source { - return rec.Kept[i].Version, true, nil - } - } - } - return "", false, nil -} - // keepRelease adds a release to the module's record, dropping the oldest past ReleasedKept. func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version string, digests, withdrawn map[string]string, branch string, source int64) error { n := r.ReleasedKept @@ -767,7 +849,7 @@ type Marked struct { func (m Marked) PackagePublished(digest string, at time.Time) meshbuilds.PackagePublished { at = at.UTC() return meshbuilds.PackagePublished{V: 1, Artifact: m.Artifact, At: &at, Branch: m.Reserved.Branch, Source: m.Reserved.Source, Revision: m.Reserved.Revision, Module: m.Reserved.Module, - Version: m.Reserved.Version, Digest: digest, Dependencies: m.Reserved.Dependencies[m.Artifact]} + Version: m.Reserved.Version, Digest: digest, Fingerprint: m.Reserved.Fingerprint, Dependencies: m.Reserved.Dependencies[m.Artifact]} } // Published takes a registry seat's published in, as PublishedRead does, answering the artifacts newly marked and the keys it is @@ -1128,11 +1210,10 @@ const ( "the version its build reserved at its start, each artifact's digest once built, when the build ended and which artifacts a registry " + "seat said published. With module, that module's only. A key goes when the catalog says version-released for it. Read-only." ReservedDropDescription = "Drop a module's reservation of one MAJOR.MINOR by hand (design 47 G section 369), when its version will never be " + - "released; the next build takes the next after the highest released. A hand act: it is recorded in the hand-act log." - ReserveDoneDescription = "Reserve a version for a done trunk build that reserved none (design 47 G A-455): given module and fp, the next version " + - "of the series is reserved for that fingerprint with the digests of the build's artifacts, and its publish is queued as builder_publish_again " + - "queues it; builds nothing. For a done key that cannot be built again. Refused when the key is not done, is no first watched branch's, or " + - "holds a reservation already. A hand act: it is recorded in the hand-act log." + "released; given module, series and the version it stands at (version, as builder_reserved shows it). Refused when the key holds another version " + + "(it names the one that stands) and while the reservation's fingerprint is building. It forgets the key whole (the version, its fingerprint, the " + + "artifacts' recorded digests, its withdrawn numbers), its publish item and its version-unreleased, and the answer names what it forgot; what the " + + "registries hold at the version stays, a gap the next reserve skips. A hand act: it is recorded in the hand-act log." // ReservedVerb is the seat mesh-builds' verb served as a tool of the same name. ReservedVerb = meshbuilds.VerbReserved ) diff --git a/modules/mesh-delivery-builder/internal/versions/reserve_test.go b/modules/mesh-delivery-builder/internal/versions/reserve_test.go index 46616f5ed..41bb62e44 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve_test.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve_test.go @@ -112,7 +112,7 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) { ctx := context.Background() store := &reserveMem{mem: newMem()} r := &Reserver{Store: store, ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"1.4.2"}, nil }} - v, err := r.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, Source{Branch: "main", Revision: 41, CatalogRevision: 44}) + v, err := r.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, Source{Branch: "main", Revision: 41, CatalogRevision: 44, Fingerprint: "src2:f"}) if err != nil || v.Version != "1.4.3" { t.Fatalf("reserved %q (%v), want 1.4.3", v.Version, err) } @@ -146,7 +146,7 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) { at := time.Unix(100, 0) said := marked[0].PackagePublished("sha256:aa", at) atUTC := at.UTC() - if wantSaid := (meshbuilds.PackagePublished{V: 1, Artifact: "m:a", At: &atUTC, Branch: "main", Source: 41, Revision: 44, Module: "m", Version: "1.4.3", Digest: "sha256:aa", Dependencies: deps}); !reflect.DeepEqual(said, wantSaid) { + if wantSaid := (meshbuilds.PackagePublished{V: 1, Artifact: "m:a", At: &atUTC, Branch: "main", Source: 41, Revision: 44, Module: "m", Version: "1.4.3", Digest: "sha256:aa", Fingerprint: "src2:f", Dependencies: deps}); !reflect.DeepEqual(said, wantSaid) { t.Errorf("package-published = %+v, want %+v", said, wantSaid) } if marked, _, _ := r.Published(ctx, "m-a", "1.4.3", "sha256:other"); len(marked) != 0 { @@ -174,6 +174,36 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) { if key, ok := ReservedBoundOf(ReservedBoundKey("m", "1.4")); !ok || key != ReservedKey("m", "1.4") || ReservedBoundFor(key) != ReservedBoundKey("m", "1.4") { t.Errorf("the bound key does not name the reservation back: %q %v", key, ok) } + // Design 47 H2 H-A-588 (4): MarkHeld writes the digest a registry holds on the reservation and marks the artifact published, once. + held := []HeldArtifact{{Ref: "m:b", Digest: "sha256:held"}} + markedHeld, ok, err := r.MarkHeld(ctx, "m", "1.4.3", held) + cur, _, _ = r.At(ctx, ReservedKey("m", "1.4")) + if err != nil || !ok || len(markedHeld) != 1 || cur.Artifacts["m:b"] != "sha256:held" || !cur.Published["m:b"] || cur.Artifacts["m:a"] != "sha256:aa" || cur.PublishedAt["m:b"].IsZero() { + t.Fatalf("marked %v (%v, %v), reservation %+v: want m:b with the held digest, published, m:a as it was", markedHeld, ok, err, cur) + } + if again, ok, err := r.MarkHeld(ctx, "m", "1.4.3", held); err != nil || !ok || len(again) != 0 { + t.Errorf("a second marking marked %v (%v, %v), want none: package-published is said once", again, ok, err) + } + if _, ok, _ := r.MarkHeld(ctx, "m", "1.4.99", held); ok { + t.Error("a reservation at another version was marked") + } + // H-A-664: in the same write what no registry holds loses its recorded digest and the reservation its built-at; unstored is kept + nv, err := r.Reserve(ctx, "n", "0.1", []string{"n:a", "n:b"}, Source{Fingerprint: "fpn"}) + if err != nil { + t.Fatal(err) + } + if _, _, err := r.Built(ctx, "n", nv.Version, map[string]string{"n:a": "sha256:a", "n:b": "sha256:b"}, nil); err != nil { + t.Fatal(err) + } + if _, err := r.MarkUnstored(ctx, "n", nv.Version, "n:b", "not stored: no blob"); err != nil { + t.Fatal(err) + } + if _, _, err := r.MarkHeld(ctx, "n", nv.Version, []HeldArtifact{{Ref: "n:a", Digest: "sha256:a"}}); err != nil { + t.Fatal(err) + } + if cur, _, _ = r.At(ctx, ReservedKey("n", "0.1")); cur.Artifacts["n:b"] != "" || cur.Artifacts["n:a"] != "sha256:a" || !cur.BuiltAt.IsZero() || cur.Unstored["n:b"] == "" || !cur.Published["n:a"] { + t.Errorf("after the marking %+v: want n:b's digest and the built-at cleared, n:a held, unstored kept", cur) + } } // TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes: design 47 G A-456a — the version-released of a version records @@ -202,44 +232,19 @@ func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) { if all, _ := r.All(ctx); len(all) != 0 { t.Errorf("reservations left: %v", all) } - // Design 47 H2 H-A-547 (3), H-A-551: an importer's version at the source revision of its key's origin is the standing - // reservation of that origin once its artifact is published, then the release recorded at that source revision. w, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:cc", Branch: "main", Revision: 41}) if err != nil { t.Fatal(err) } - at := func(branch string, source int64) string { - v, found, err := r.VersionAt(ctx, "m", "a", branch, source) - if err != nil || found != (v != "") { - t.Fatalf("VersionAt %s.%d: %q %v %v", branch, source, v, found, err) - } - return v - } - if v := at("main", 41); v != "" { - t.Errorf("a reservation not yet published answers %q, want none", v) - } if _, _, err := r.Built(ctx, "m", w.Version, map[string]string{"m:a": "sha256:cc"}, nil); err != nil { t.Fatal(err) } if _, _, err := r.Published(ctx, "m/a", w.Version, "sha256:cc"); err != nil { t.Fatal(err) } - if v := at("main", 41); v != w.Version { - t.Errorf("the published reservation at main.41 answers %q, want %s", v, w.Version) - } - if v, v2 := at("main", 40), at("feat", 41); v != "" || v2 != "" { - t.Errorf("another source revision or branch answers %q %q, want none", v, v2) - } if _, err := r.Released(ctx, "m", w.Version); err != nil { t.Fatal(err) } - if v := at("main", 41); v != w.Version { - t.Errorf("once released, main.41 answers %q, want %s from the release's record", v, w.Version) - } - // H-A-558 (2): the record keeps the origin's branch with its source revision, so another branch's equal number never meets it. - if v := at("feat", 41); v != "" { - t.Errorf("once released, feat.41 answers %q, want none", v) - } // One key per module holds the last releases, the oldest dropped (A-456b). for _, fp := range []string{"src2:b1", "src2:b2"} { n, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp}) @@ -451,11 +456,15 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) { var readErr error var skipped []string r := &Reserver{Store: store, ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.36"}, nil }, - HeldNumbers: func(_ context.Context, module, fp string, refs []string) ([]string, error) { + HeldRecords: func(_ context.Context, module, fp string, refs []string) ([]HeldArtifact, error) { if module != "node-tools" || fp != "fp1" || len(refs) != 1 { t.Errorf("the registries are read for %s %s %v", module, fp, refs) } - return held, readErr + var out []HeldArtifact + for _, v := range held { + out = append(out, HeldArtifact{Ref: "node-tools:program", Version: v}) + } + return out, readErr }, HeldElsewhere: func(_ context.Context, _ string, s []string) { skipped = append(skipped, s...) }} v, err := r.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, Source{Fingerprint: "fp1", Repository: "o/r", Commit: "c1"}) @@ -487,4 +496,37 @@ func TestANumberARegistryHoldsIsNeverReserved(t *testing.T) { if v, err := r.Reserve(ctx, "node-tools", "0.2", []string{"node-tools:program"}, Source{Fingerprint: "fp1"}); err != nil || v.Version != "0.2.1" { t.Errorf("with the registry down reserved %q (%v), want 0.2.1 (what it answered still skipped)", v.Version, err) } + // H2 H-A-590 (1), H-A-616: a build again of F keeps F's standing number unless a registry holds an artifact at it for another + // build: the registry keeps another fingerprint, or none and another digest; one with the reserved digest, or F's own + // fingerprint, keeps it. + for _, c := range []struct { + name string + held HeldArtifact + wantMoved bool + }{ + {name: "another fingerprint kept", held: HeldArtifact{Digest: "sha256:mine", Fingerprint: "other"}, wantMoved: true}, + {name: "no fingerprint, another digest", held: HeldArtifact{Digest: "sha256:theirs"}, wantMoved: true}, + {name: "no fingerprint, the reserved digest", held: HeldArtifact{Digest: "sha256:mine"}}, + {name: "F's own fingerprint", held: HeldArtifact{Digest: "sha256:mine", Fingerprint: "fp9"}}, + } { + st := &reserveMem{mem: newMem()} + var told []HeldArtifact + rr := &Reserver{Store: st, ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }} + first, err := rr.Reserve(ctx, "m", "0.3", []string{"m:a"}, Source{Fingerprint: "fp9"}) + if err != nil { + t.Fatal(err) + } + if _, _, err := rr.Built(ctx, "m", first.Version, map[string]string{"m:a": "sha256:mine"}, nil); err != nil { + t.Fatal(err) + } + c.held.Ref, c.held.Version, c.held.Seat = "m:a", first.Version, SeatArtifacts + rr.HeldRecords = func(context.Context, string, string, []string) ([]HeldArtifact, error) { + return []HeldArtifact{c.held}, nil + } + rr.MovedFrom = func(_ context.Context, _ ReservedVersion, e []HeldArtifact) { told = e } + again, err := rr.Reserve(ctx, "m", "0.3", []string{"m:a"}, Source{Fingerprint: "fp9", Rebuild: true}) + if err != nil || (again.Version != first.Version) != c.wantMoved || (again.Withdrawn[first.Version] == "fp9") != c.wantMoved || (len(told) == 1) != c.wantMoved { + t.Errorf("%s: the build again reserved %+v (%v), told %v; want the number %s %s", c.name, again, err, told, first.Version, map[bool]string{true: "withdrawn and the next taken", false: "kept"}[c.wantMoved]) + } + } } diff --git a/modules/mesh-delivery-builder/manifest_test.go b/modules/mesh-delivery-builder/manifest_test.go index e1114fb86..6540eedad 100644 --- a/modules/mesh-delivery-builder/manifest_test.go +++ b/modules/mesh-delivery-builder/manifest_test.go @@ -122,7 +122,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1 if m.Module != "mesh-delivery-builder" { t.Errorf("module = %q", m.Module) } - if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, MaxMiB: 1}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814) + if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, KeyTTL: true, MaxMiB: 4}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814) t.Errorf("state = %+v, want %+v", m.State, want) } // 1887/A4c: the builder chooses no node, so it reads neither presence nor have, invokes no build module's tool and @@ -184,7 +184,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1 } // 1945: the builder's tools (builder_seat_queue: note 62), served by its tools bundle, and the event it says when it asks an ask again. if want := []string{"build_current", "builder_announce_again", "builder_ask_again", "builder_ask_drop", "builder_asks", "builder_bounds", "builder_build", "builder_build_again", "builder_builds_since", "builder_engine_reads", "builder_first_view_again", "builder_first_views", - "builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserve_done", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) { + "builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) { t.Errorf("tools = %v, want %v", m.Tools, want) } // Design 47 G §672: the toolchain waits' stream, kept 7 days within 16 MiB, and the bound's setting, 60 minutes. @@ -198,7 +198,8 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1 m.Streams[3].Duplicates != 24 || m.Streams[3].MaxDeliveries != 10 || m.Streams[3].MaxAgeDays != 7 || m.Streams[3].MaxMiB != 64 { t.Errorf("streams = %+v, want waits with wait-held.** and wait-ended.**, 7 days, 16 MiB, the builds' stream (build.ended.**, 7 days, kept last per subject: design 47 G A-181) and the findings' stream", m.Streams) } - if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 13 || + if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 13 || m.Config["acted-days"].Default != float64(30) || m.Config["acted-days"].Maximum != 365 || // H-A-720 (1) + // design 47 H2 §775, H-A-381 (2): the kept-call pace and the taken key's bound, read by the process m.Config["kept-call-pace-first"].Default != "1s" || m.Config["kept-call-pace-max"].Default != "30s" || m.Config["ask-taken-bound"].Default != "10m" || !m.Config["kept-call-pace-first"].Runtime || !m.Config["kept-call-pace-max"].Runtime || !m.Config["ask-taken-bound"].Runtime || @@ -207,8 +208,9 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1 m.Config["revision-wait-minutes"].Default != float64(2) || m.Config["package-wait-minutes"].Default != float64(10) || // H-A-492: the record of a version's digests runs under the builder's own bound, a setting of 60 s by default m.Config["record-bound-seconds"].Default != float64(60) || - m.Config["publish-pause"].Default != float64(30) || m.Config["publish-pause-max"].Default != float64(30) || m.Config["publish-tries"].Default != float64(5) || m.Config["publish-tries"].Maximum != 10 { - t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), record-bound-seconds of 60 (H-A-492), the publish settings 30 s, 30 min and 5 tries, at most 10 (design 47 G §588, §633, A-457a; H2 H-A-446 (2))", m.Config) + m.Config["republish-max-versions"].Default != float64(50) || m.Config["publish-ack-minutes"].Default != float64(10) || // H-A-606: no pause, maximum or tries of a publish + m.Config["publish-pause"].Default != nil || m.Config["publish-pause-max"].Default != nil || m.Config["publish-tries"].Default != nil { + t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), record-bound-seconds of 60 (H-A-492), republish-max-versions of 50 and publish-ack-minutes of 10, and no pause, maximum or tries of a publish (design 47 G §588, §633; H2 H-A-606, H-A-613 (3))", m.Config) } // Design 47 G §349: version.numbered is no longer said; old-form-closed on the family version, apart from the builds' ends. if want := []string{"build.asked-again", "version.old-form-closed"}; !reflect.DeepEqual(m.Emits, want) { @@ -267,7 +269,7 @@ func TestManifestProcess(t *testing.T) { // 1607/AC1 t.Errorf("health = %v, want kind unit alone", p["health"]) } env, _ := p["env"].(map[string]any) - if len(env) != 9 || env["MESH_BUILDER_RECORD_BOUND_FILE"] != "${dir:state}/record-bound-seconds" || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_TRIES_FILE"] != "${dir:state}/publish-tries" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" { + if len(env) != 9 || env["MESH_BUILDER_RECORD_BOUND_FILE"] != "${dir:state}/record-bound-seconds" || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_ACK_FILE"] != "${dir:state}/publish-ack-minutes" || env["MESH_BUILDER_REPUBLISH_MAX_FILE"] != "${dir:state}/republish-max-versions" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" { t.Errorf("env = %v, want the broker file and the path of the toolchain wait's file, never the setting itself (design 47 G §672, A-71)", p["env"]) } for k, v := range env { @@ -350,6 +352,11 @@ func TestServesNoRequestSubjectAndHoldsNoTicker(t *testing.T) { // 1607/AC6 (ADR if (f == "Subscribe(" || f == "time.NewTicker") && filepath.ToSlash(path) == "cmd/mesh-delivery-builder/stepqueue.go" { continue } + // 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. + if f == "Subscribe(" && filepath.ToSlash(path) == "cmd/mesh-delivery-builder/publishitem.go" { + continue + } if strings.Contains(string(src), f) { t.Errorf("%s holds %s: the builder serves no request subject but its seat's verbs and accepted kinds (A-107) and holds no timer", path, f) } diff --git a/modules/mesh-delivery-builder/module.json b/modules/mesh-delivery-builder/module.json index 75156b103..53a3605b5 100644 --- a/modules/mesh-delivery-builder/module.json +++ b/modules/mesh-delivery-builder/module.json @@ -31,7 +31,6 @@ "builder_reserved", "builder_release", "builder_reserved_drop", - "builder_reserve_done", "builder_seat_queue", "builder_stuck", "builder_toolchains", @@ -136,7 +135,7 @@ { "name": "toolchains-heard", "history": 1, "max-mib": 8 }, { "name": "waits", "history": 1, "max-mib": 4 }, { "name": "reserved", "history": 1, "max-mib": 8 }, - { "name": "acted", "history": 1, "max-mib": 1 }, + { "name": "acted", "history": 1, "key-ttl": true, "max-mib": 4 }, { "name": "asked", "history": 1, "max-mib": 8 }, { "name": "reasks", "history": 1, "max-mib": 8 }, { "name": "first-views", "history": 1, "max-mib": 8 }, @@ -217,19 +216,11 @@ "default": "5m", "runtime": true }, - "publish-pause": { + "acted-days": { "type": "number", - "description": "seconds before a version's second publish try, doubled per try up to publish-pause-max (design 47 G A-457a).", + "description": "how many days a mark of an event or an ask acted on (state acted) is kept after its last write; the mark outlives every delivery of its event by far (design 47 H2 H-A-720).", "minimum": 1, - "maximum": 3600, - "trusted": false, - "default": 30 - }, - "publish-pause-max": { - "type": "number", - "description": "minutes, the most a pause between a version's publish tries grows to (design 47 G A-457a).", - "minimum": 1, - "maximum": 1440, + "maximum": 365, "trusted": false, "default": 30 }, @@ -241,13 +232,21 @@ "trusted": false, "default": 16 }, - "publish-tries": { + "republish-max-versions": { "type": "number", - "description": "how many times the builder tries a done build's publish before it ends loudly (log and condition) and leaves it readable in builder_publish_queue, at most 10, the work queue publishes' max-deliveries (design 47 G A-457a; H2 H-A-446 (2)).", + "description": "the most versions one event of a registry seat's holder (its running, or the return of its node) puts on the work queue publishes, newest first (design 47 G section 633, H2 H-A-606).", "minimum": 1, - "maximum": 10, + "maximum": 10000, "trusted": false, - "default": 5 + "default": 50 + }, + "publish-ack-minutes": { + "type": "number", + "description": "minutes a sent publish waits for its published before the work queue gives it again, the publish bound (design 47 G section 369, H2 H-A-613 (3)).", + "minimum": 1, + "maximum": 1440, + "trusted": false, + "default": 10 } }, "logs": [ @@ -318,20 +317,12 @@ "content": "${config:record-bound-seconds}" }, { - "id": "publish-pause", + "id": "acted-days", "type": "file", - "path": "${dir:state}/publish-pause", + "path": "${dir:state}/acted-days", "owner": "mesh-delivery-builder", "mode": "0600", - "content": "${config:publish-pause}" - }, - { - "id": "publish-pause-max", - "type": "file", - "path": "${dir:state}/publish-pause-max", - "owner": "mesh-delivery-builder", - "mode": "0600", - "content": "${config:publish-pause-max}" + "content": "${config:acted-days}" }, { "id": "released-kept", @@ -342,12 +333,20 @@ "content": "${config:released-kept}" }, { - "id": "publish-tries", + "id": "republish-max", "type": "file", - "path": "${dir:state}/publish-tries", + "path": "${dir:state}/republish-max-versions", "owner": "mesh-delivery-builder", "mode": "0600", - "content": "${config:publish-tries}" + "content": "${config:republish-max-versions}" + }, + { + "id": "publish-ack", + "type": "file", + "path": "${dir:state}/publish-ack-minutes", + "owner": "mesh-delivery-builder", + "mode": "0600", + "content": "${config:publish-ack-minutes}" }, { "id": "builder", @@ -369,9 +368,9 @@ "MESH_BUILDER_REVISION_WAIT_FILE": "${dir:state}/revision-wait-minutes", "MESH_BUILDER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes", "MESH_BUILDER_RECORD_BOUND_FILE": "${dir:state}/record-bound-seconds", - "MESH_BUILDER_PUBLISH_PAUSE_FILE": "${dir:state}/publish-pause", - "MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE": "${dir:state}/publish-pause-max", - "MESH_BUILDER_PUBLISH_TRIES_FILE": "${dir:state}/publish-tries", + "MESH_BUILDER_REPUBLISH_MAX_FILE": "${dir:state}/republish-max-versions", + "MESH_BUILDER_PUBLISH_ACK_FILE": "${dir:state}/publish-ack-minutes", + "MESH_BUILDER_ACTED_DAYS_FILE": "${dir:state}/acted-days", "MESH_BUILDER_RELEASED_KEPT_FILE": "${dir:state}/released-kept" }, "user": "mesh-delivery-builder", diff --git a/modules/mesh-delivery-contracts/go/clients/meshcatalogclient/catalog.go b/modules/mesh-delivery-contracts/go/clients/meshcatalogclient/catalog.go index 27fe86aab..d70b0543b 100644 --- a/modules/mesh-delivery-contracts/go/clients/meshcatalogclient/catalog.go +++ b/modules/mesh-delivery-contracts/go/clients/meshcatalogclient/catalog.go @@ -108,13 +108,15 @@ func WireCatalog(r *views.Reader, call Call, branch string, changed func(module // WireCatalogProcess is WireCatalog for a process's views.ProcessReader: its picture // (`mesh-catalog_catalog-revisions.`) reads the half as a read-only bucket, and the seat's event catalog-revision -// on the module's durable consumer goes to Hear. -func WireCatalogProcess(r *views.ProcessReader, call Call, branch string, changed func(module string, entry json.RawMessage, deleted bool, at time.Time)) (*Catalog, *views.Picture, error) { +// on the module's durable consumer goes to Hear. held is told each revision the view takes in whole, whether or not an entry +// changed, as Catalog.Held is (design 47 H2 H-A-747); it is set before the first ask. A nil held tells nothing. +func WireCatalogProcess(r *views.ProcessReader, call Call, branch string, changed func(module string, entry json.RawMessage, deleted bool, at time.Time), held func(seat.CatalogRevision)) (*Catalog, *views.Picture, error) { c, err := NewCatalog(call, branch) if err != nil { return nil, nil, err } c.Follower.Changed = changed + c.Held = held p, err := r.Adopt(c.Follower, seat.Seat, seat.EventCatalogRevision, c.Hear) if err != nil { return nil, nil, err diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main.go index 6404b644a..dc0a3cd59 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main.go @@ -25,6 +25,15 @@ type kept struct{ s stdio.KeptState } func (k kept) Keys() ([]string, error) { return k.s.Keys() } +// Revision is the revision of key's record, for the cursor of show (design 47 H2 H-A-709 (2)). +func (k kept) Revision(key string) (uint64, error) { + e, err := k.s.Get(key) + if err != nil || e == nil { + return 0, err + } + return e.Revision, nil +} + func (k kept) Value(key string) (json.RawMessage, error) { e, err := k.s.Get(key) if err != nil || e == nil { @@ -54,7 +63,11 @@ func Tools(r pipeline.Reads) []stdio.Tool { if err != nil { return nil, err } - return r.Show(in) + ans, err := r.Show(in) + if err == nil && ans.Capped && in.Bound == 0 && in.Next == "" && r.SaidCapped != nil { + r.SaidCapped(stdio.CallerOf(a), seat.VerbShow, ans.Total) + } + return ans, err }, seat.VerbList: func(a map[string]any) (any, error) { in, err := as[seat.ListInput](a) @@ -63,7 +76,17 @@ func Tools(r pipeline.Reads) []stdio.Tool { } return r.List(in) }, - seat.VerbStands: func(map[string]any) (any, error) { return r.Stands() }, + seat.VerbStands: func(a map[string]any) (any, error) { + in, err := as[seat.StandsInput](a) + if err != nil { + return nil, err + } + ans, err := r.Stands(in) + if err == nil && ans.Capped && in.Bound == 0 && in.Next == "" && r.SaidCapped != nil { + r.SaidCapped(stdio.CallerOf(a), seat.VerbStands, ans.Total) + } + return ans, err + }, seat.VerbWhyCarried: func(a map[string]any) (any, error) { in, err := as[seat.WhyCarriedInput](a) if err != nil { @@ -174,9 +197,24 @@ func main() { fmt.Fprintf(os.Stderr, "[mesh-delivery-pipeline-tools] %v\n", err) os.Exit(1) } + answerBound, err := pipeline.AnswerBound(stdio.Setting) + if err != nil { + fmt.Fprintf(os.Stderr, "[mesh-delivery-pipeline-tools] %v\n", err) + os.Exit(1) + } + var saidMu sync.Mutex + said := map[string]bool{} fill := StoresFill(func(n string) (*stdio.StateInfo, error) { return stdio.State(n).Info() }, func(n string) (*stdio.LogInfo, error) { return stdio.Log(n).Info() }, time.Now) - r := pipeline.Reads{Pipelines: kept{stdio.State(seat.StatePipelines)}, Kept: kept{stdio.State(seat.StateKept)}, Fill: fill} + r := pipeline.Reads{Pipelines: kept{stdio.State(seat.StatePipelines)}, Kept: kept{stdio.State(seat.StateKept)}, Fill: fill, StalledBound: stalledBound, AnswerBound: answerBound, + SaidCapped: func(caller, verb string, total int64) { + saidMu.Lock() + defer saidMu.Unlock() + if !said[caller] { + said[caller] = true + fmt.Fprintf(os.Stderr, "[mesh-delivery-pipeline-tools] %s answered %s a capped page of %d, as it named no bound and no next: it reads the rest from next, or names a bound up to %d (H-A-709 (2))\n", verb, caller, total, pipeline.MaxAnswer) + } + }} tools := append(Tools(r), FirstViewTools(os.Getenv(stdio.ServedAs), stdio.State(views.StatusState), meshhandactsclient.Recorder{Ask: stdio.Ask}, time.Now)...) tools = append(tools, UnloggedTools(stdio.State(seat.StatePipelines), stdio.Log(seat.StateStepLog), meshhandactsclient.Recorder{Ask: stdio.Ask}, func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-pipeline-tools] "+f+"\n", a...) })...) diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main_test.go index c8392a828..b35ce4f37 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/main_test.go @@ -97,7 +97,7 @@ func TestTools(t *testing.T) { } // design 47 H2 §786: runner_unfinished reads each key and its entry; runner_unfinished_drop names why, drops nothing when // its hand act is not recorded, and drops the key once it is. - if got, err := tools[0].Run(nil); err != nil || fmt.Sprint(got) != "[{main.app {src2:aa 4 main.4 failed}}]" { + if got, err := tools[0].Run(nil); err != nil || fmt.Sprint(got) != "[{main.app {src2:aa 4 main.4 failed []}}]" { t.Errorf("runner_unfinished = %v (%v)", got, err) } for _, c := range []struct { diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/show.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/show.go index 07a332f1a..3e0de3952 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/show.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/show.go @@ -16,13 +16,14 @@ func ShowTools(r pipeline.Reads) []stdio.Tool { return []stdio.Tool{ {Name: Prefix + "_show", Description: "One pipeline in parts: its record with the steps the filters hold (a mover, a step kind, a step's " + - "outcome), at most 768 KB with capped, the filters' total and next, the cursor of the next page.", + "outcome), at most the bound's bytes (default the setting answer-bound, 32 KB) with capped, the filters' total and next, the cursor of the next page, moved when the record was written between two pages.", Input: map[string]any{"type": "object", "properties": map[string]any{ "pipeline": map[string]any{"type": "string", "description": "the pipeline's key"}, "mover": map[string]any{"type": "string", "description": "only this mover's steps"}, "step": map[string]any{"type": "string", "description": "only the steps of this kind (build, lint, unit, integration, validate, composition, review, approval)"}, "state": map[string]any{"type": "string", "description": "only the steps whose outcome is this (passed, failed, running, could not run, ...)"}, "next": map[string]any{"type": "string", "description": "the cursor the previous page answered"}, + "bound": map[string]any{"type": "number", "description": "the most bytes the answer holds, 4096 to 786432; absent, the setting answer-bound"}, }, "required": []string{"pipeline"}}, Run: func(a map[string]any) (any, error) { in, err := as[seat.ShowInput](a) diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/unfinished.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/unfinished.go index a91071c13..5b2710ac6 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/unfinished.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline-tools/unfinished.go @@ -37,7 +37,7 @@ func UnfinishedTools(st UnfinishedState, acts views.HandActs) []stdio.Tool { str := map[string]any{"type": "string"} return []stdio.Tool{ {Name: Prefix + "_unfinished", - Description: "The movers a pipeline's end left unfinished (design 47 H2 §786): each key . with its fingerprint, the catalog revision and the pipeline it was left in, and that pipeline's outcome. Each is put in the pipeline of its branch's next catalog revision; runner_unfinished_place puts one in a pipeline of its own now, runner_unfinished_drop drops one.", + Description: "The movers a pipeline's end left unfinished (design 47 H2 §786): each key . with its fingerprint, the catalog revision and the pipeline it was left in, and that pipeline's outcome. Each is put in the pipeline of its branch's next catalog revision; runner_unfinished_place puts the closed group of one key, or of every key with all, in a pipeline now, runner_unfinished_drop drops one.", Input: map[string]any{"type": "object", "properties": map[string]any{}}, Run: func(map[string]any) (any, error) { return unfinishedOf(st) }}, {Name: Prefix + "_unfinished_drop", 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 c1f3c4d8c..97580ccc2 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 @@ -19,7 +19,7 @@ func VerbTools(ask func(key string, body any) (json.RawMessage, error)) []stdio. } return []stdio.Tool{ verbTool[seat.StartInput](ask, "start", seat.VerbStart, - "Start by hand the delivering pipeline of the head of a watched branch for a module, by the seat verb start: the branch, the module and why. A head whose pipeline is written already is refused by the verb, naming it. With modules instead of module, the named modules whose newest entry has no passed pipeline (a failed, cut or superseded one) are started again at the head, keyed ..again.; a module whose newest entry passed is refused by name (design 47 H2 H-A-479).", + "Start by hand, by the seat verb start, the module or the modules at the head of a watched branch: the branch, exactly one of module or modules, and why. Each module follows one rule: a head with no pipeline is started with them; the head's pipeline that waits or runs takes the ones it does not move as movers, said by mover-added with the caller; once it ended, start never refuses: a module it does not move is added to it as a mover, one whose own step failed or whose steps are unfinished reopens it with its closed group, as runner_rerun and runner_unfinished_place do, and one it delivered is answered by it with nothing started. No other pipeline is keyed (design 47 H2 H-A-571, H-A-643).", obj([]string{"branch", "why"}, map[string]any{"branch": str, "module": str, "modules": map[string]any{"type": "array", "items": str}, "why": str}), func(in seat.StartInput) string { if in.Branch == "" || (in.Module == "") == (len(in.Modules) == 0) { @@ -64,11 +64,11 @@ func VerbTools(ask func(key string, body any) (json.RawMessage, error)) []stdio. return whyOf(in.Why) }), verbTool[seat.PlaceUnfinishedInput](ask, "unfinished_place", seat.VerbPlaceUnfinished, - "Put a mover kept in the state unfinished in a pipeline of its own at once, by the seat verb place-unfinished (design 47 H2 §786): the entry's key . (runner_unfinished lists them) and why; written in the hand-act log. The answer names the pipeline, keyed ..unfinished..", - obj([]string{"key", "why"}, map[string]any{"key": str, "why": str}), + "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 == "" { - return "place-unfinished names the unfinished entry's key" + if (in.Key == "") == !in.All { + return "place-unfinished names the unfinished entry's key or all, exactly one" } 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 8f6329ebc..73b03c924 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 @@ -43,7 +43,11 @@ func TestVerbTools(t *testing.T) { // design 47 H2 §786, H-A-398: runner_unfinished_place asks the verb place-unfinished with the entry's key and why. {"unfinished place", "runner_unfinished_place", "seat:mesh-pipeline-runner.place-unfinished", "", map[string]any{"key": "main.app", "why": "now"}, seat.PlaceUnfinishedInput{Key: "main.app", Why: "now"}}, - {"unfinished place no key", "runner_unfinished_place", "", "entry's key", map[string]any{"why": "now"}, nil}, + {"unfinished place no key", "runner_unfinished_place", "", "exactly one", map[string]any{"why": "now"}, nil}, + // 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}, {"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/main.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go index e8418b4e8..3b8407d5e 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/main.go @@ -105,7 +105,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro var resumer atomic.Pointer[func(string)] var advancer atomic.Pointer[func(string)] var placer atomic.Pointer[func(catalog.CatalogRevisionEvent) error] - var registrar atomic.Pointer[func(catalog.Registration)] + var registrar atomic.Pointer[func(catalog.Registration, bool)] var reviser atomic.Pointer[func(catalog.CatalogRevisionEvent) (int, error)] rv, err := startViews(ctx, js, conn, cred, hub, calls.State("findings"), calls.Call, func(branch string) { if f := resumer.Load(); f != nil { @@ -120,9 +120,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro return (*f)(ev) } return fmt.Errorf("the candidate %s's revision %d is heard before the runner can place it", ev.Group, ev.Revision) - }, func(reg catalog.Registration) { + }, func(reg catalog.Registration, gone bool) { if f := registrar.Load(); f != nil { - (*f)(reg) + (*f)(reg, gone) } }, func(ev catalog.CatalogRevisionEvent) (int, error) { if f := reviser.Load(); f != nil { @@ -160,7 +160,14 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro hearer.Widens = widener.Reads hearer.LogLast = stepLog{ctx: ctx, js: js, module: cred.Module}.Last hearer.Where = routerRecordOf(cred.Module, calls.Call, calls.Ask) - hearer.Failures = &pipeline.Failures{Findings: rv.Findings, Observer: cred.Module, Author: commitAuthor(calls.Call), Logf: logger.Printf} + hearer.Failures = &pipeline.Failures{Findings: rv.Findings, Observer: cred.Module, Author: commitAuthor(calls.Call), Logf: logger.Printf, + Behind: func(p seat.Pipeline, module string) []string { + half, err := widener.Revision(p.Branch, p.Revision) + if err != nil { + return nil + } + return pipeline.HeldBehind(p, module, half.Entries) + }} // Every ask but a test run's is bounded until its holder's first word (H-A-235, H-A-238), its bounds keys of the state // bounds. A step's ask is put as a kept call within the same bound (design 47 H2 §775). askBound, err := askUnansweredBound(getenv) @@ -172,6 +179,13 @@ 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)) + // 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 { + return err + } + logger.Printf("reads: show and stands answer at most %d bytes unless a call names a bound (%s)", answerBound, pipeline.AnswerBoundSetting) logger.Printf("health: a running pipeline with nothing open and nothing newly placed, or a step whose ask is untaken, is named after %s (%s)", stalledBound, pipeline.StalledBoundSetting) // Its asking half (§22, §24): a pipeline's steps are placed from the module's registration and each build seat is asked // for its step. @@ -249,7 +263,11 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro // A registration-changed places the steps of its module's pipelines started before it, from it (A-327), and binds the // takeins durable when its bind failed at the start (H-A-500 fifth addendum). var bindTakeInsAgain atomic.Pointer[func()] - register := func(reg catalog.Registration) { + register := func(reg catalog.Registration, gone bool) { + if gone { + hearer.Failures.ModuleGone(reg.Module) + return + } if f := bindTakeInsAgain.Load(); f != nil { (*f)() } @@ -263,6 +281,21 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro revise := func(ev catalog.CatalogRevisionEvent) (int, error) { return starter.Revised(ev, widener.Revision) } reviser.Store(&revise) starter.Store = store + // The movers a failed pipeline leaves are carried in closed groups (design 47 H2 H-A-594, H-A-607): their edges are read at + // the pipeline's revision, their ties end with the failed module's registration, and a group joins the head's pipeline. + unfinished.Entries = func(branch string, revision int64) (map[string]catalog.CatalogEntry, bool) { + half, err := widener.Revision(branch, revision) + return half.Entries, err == nil + } + unfinished.Pipeline = func(key string) (seat.Pipeline, bool) { p, _, err := store.Get(key); return p, err == nil } + 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) + if !ok { + return "", false + } + return starter.CarryToHead(from, group, half.Entries, rv.Catalog.View) + } // The queue (design 47 H §748): at most pipelines-at-once pipelines have their steps asked, the others wait in order in // the state queue, placed at the start from it and on every end. atOnce, waitingCap, err := queueSettings(getenv) 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 5fda4dab6..28195f2d5 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 @@ -309,15 +309,11 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { t.Fatal(err) } outcome("main.4", seat.PipelineOutcomeCancelled) - // design 47 H2 §786: the cancel leaves main.4's lib unfinished; dropped here, as runner_unfinished_drop does, so the - // next take-ins move only what they name. - unfinished, err := js.KeyValue(ctx, module+"_"+pipeline.StateUnfinished) - if err != nil { - t.Fatal(err) - } - waitFor(t, ctx, logs, func() bool { _, err := unfinished.Get(ctx, "main.lib"); return err == nil }) - if err := unfinished.Delete(ctx, "main.lib"); err != nil { - t.Fatal(err) + // design 47 H2 §786, H-A-607 (2), H-A-750 (1): the cancel leaves main.4's lib, which joins the head's pipeline main.7 though + // that waits, said by mover-added with the pipeline it came from. + waitFor(t, ctx, logs, func() bool { return wasSaid("mover-added.main.7") }) + if p := get("main.7"); !slices.ContainsFunc(p.Movers, func(m seat.Mover) bool { return m.Module == "lib" }) { + t.Fatalf("main.7 moves %+v, want lib joined from the cancelled main.4", p.Movers) } outcome("main.6", seat.PipelineOutcomeRunning) waitFor(t, ctx, logs, func() bool { _, ok := finding(pipeline.QueueFullKind); return !ok }) @@ -331,6 +327,7 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { outcome("main.7", seat.PipelineOutcomeRunning) take(8, "gated") built("main.7", "tool") + built("main.7", "lib") // the lib that joined main.7 is built too, so main.7 ends and main.8 runs outcome("main.8", seat.PipelineOutcomeRunning) take(9, "lib") built("main.8", "gated") @@ -384,7 +381,10 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { t.Fatal(err) } before := pipelineKeys(t, ctx, pipelines) + heardBefore := takeInsLines(logs) stopRunner = start() + // The restarted runner is waited for by what it says it did, its own take-ins line, never by a clock (H-A-637's kind). + takeInsHeardMore(t, ctx, logs, heardBefore) outcome("main.10", seat.PipelineOutcomeRunning) waitFor(t, ctx, logs, func() bool { return wasSaid("wait-ended.main.10") && slices.Equal(running(), []string{"main.10"}) }) waitFor(t, ctx, logs, func() bool { _, ok := finding(pipeline.PipelinesStalledKind); return !ok }) @@ -417,8 +417,10 @@ func testTheQueueRunsPipelinesInTurn(t *testing.T) { restarted := time.Now() stopRunner = start() outcome("main.10", seat.PipelineOutcomeFailed) - if e := stepFor(get("main.10"), "app", seat.StepResultStepBuild).Ended; e == nil || e.Sub(restarted) >= 3*time.Second { - t.Fatalf("main.10's build ended %v, the runner restarted at %v; want its missed bound taken at the start", e, restarted) + // The missed bound is taken by the restarted runner: the step ends after the restart and the journal says so below; no + // clock between the restart and the end is asserted, which a loaded machine stretches (H-A-637's kind). + if e := stepFor(get("main.10"), "app", seat.StepResultStepBuild).Ended; e == nil || e.Before(restarted) { + t.Fatalf("main.10's build ended %v, the runner restarted at %v; want its missed bound taken by the restarted runner", e, restarted) } if !strings.Contains(logs.String(), "expired while the runner was away: taken now") { t.Fatal("the start did not say the bound it took") diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/testruns_integration_test.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/testruns_integration_test.go index 4f20a0fbe..5d58a6a63 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/testruns_integration_test.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/testruns_integration_test.go @@ -147,8 +147,12 @@ func TestTestRunsAreAskedOncePerLevelAndMoveEveryReader(t *testing.T) { } var revision atomic.Int64 revision.Store(1) + var late atomic.Pointer[chan struct{}] // a view's ask of revision 2 answered once this channel is closed if _, err := nc.Subscribe("mesh.seat.mesh-catalog.call.revision.*", func(m *nats.Msg) { r := revision.Load() + if h := late.Load(); h != nil && r == 2 { + <-*h + } raw, _ := json.Marshal(map[string]any{"result": catalog.RevisionAnswer{Revision: &catalog.CatalogRevision{Revision: r, Kind: "trunk", Branch: "main", Source: 2 + r}, Entries: entries}}) _ = m.Respond(raw) }); err != nil { @@ -545,10 +549,16 @@ func TestTestRunsAreAskedOncePerLevelAndMoveEveryReader(t *testing.T) { } // A second revision with the same digests asks its own runs, so a failed test runs again (§724). + // design 47 H2 H-A-747 (DQ-56): the view's ask of revision 2, whose entries equal revision 1's, is answered late, after the + // take-in made main.2 with no step: no entry changes, and the view holding revision 2 alone places it. revision.Store(2) + answered := make(chan struct{}) + late.Store(&answered) publish(catalog.SubjectCatalogRevision("main"), catalog.CatalogRevisionEvent{V: 1, Revision: 2, Kind: "trunk", Branch: "main", Source: 4}) const p4 = "main.2" takeIn("app", "c1", "src2:aa", 4, 2) + waitFor(t, ctx, logs, func() bool { return strings.Contains(logs.String(), "main.2 starts with no step") }) + close(answered) placed(p4) run4, r4 := runOfStep(p4, "app:program", "integration") if !strings.HasPrefix(run4, "main.2.") || r4.Ask == integ.Ask { 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 5abc6df67..80cfcaf55 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 @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "slices" + "strings" "sync/atomic" "testing" "time" @@ -140,4 +141,45 @@ func TestAMoverLeftUnfinishedIsPutInTheNextPipelineAndWanted(t *testing.T) { if _, err := unfinished.Get(ctx, "main.app"); err == nil { t.Error("main.app is still unfinished after main.2 passed") } + + // design 47 H2 H-A-609 (1), H-A-644, H-A-725 (AC-P5a, AC-P5d), whole: lib fails again in main.3, leaving app unfinished; + // place-unfinished with all puts app in one hand act by reopening main.3 for app alone, so main.3 ends again passed (its + // second end, the end count one higher) and no third end follows, lib staying a failed mover outside the group. + newest.Store(3) + rev, _ = json.Marshal(catalog.CatalogRevisionEvent{V: 1, Revision: 3, Kind: "trunk", Branch: "main", Source: 5, CallKind: catalog.CatalogRevisionEventCallKindTakeIn}) + if _, err := w.js.Publish(ctx, catalog.SubjectCatalogRevision("main"), rev); err != nil { + t.Fatal(err) + } + takeIn(5, 3, catalog.TakeInEntry{Module: "app", Commit: "c1", Fingerprint: "src2:aa"}, catalog.TakeInEntry{Module: "lib", Commit: "l1", Fingerprint: "src2:l1"}) + waitFor(t, ctx, w.logs, answer("main.3", true)) + if pe := endOf(); pe.Pipeline != "main.3" || pe.Outcome != seat.PipelineEndedOutcomeFailed || !slices.Equal(pe.Unfinished, []string{"app"}) { + t.Fatalf("pipeline-ended = %s %s unfinished %v, want main.3 failed leaving app unfinished\n%s", pe.Pipeline, pe.Outcome, pe.Unfinished, w.logs.String()) + } + var placed seat.PlaceUnfinishedAnswer + waitFor(t, ctx, w.logs, func() bool { + raw, _ := json.Marshal(seat.PlaceUnfinishedInput{All: true, 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 all: %s", reply.Error) + } + return json.Unmarshal(reply.Result, &placed) == nil + }) + if len(placed.Placed) != 1 || placed.Placed[0].Key != "main.app" || placed.Placed[0].Pipeline != "main.3" || len(placed.Failed) != 0 { + t.Fatalf("place-unfinished all = %+v, want main.app placed in main.3", placed) + } + waitFor(t, ctx, w.logs, answer("main.3", false)) + if pe := endOf(); pe.Pipeline != "main.3" || pe.Outcome != seat.PipelineEndedOutcomePassed || len(pe.Unfinished) != 0 { + t.Fatalf("main.3 ended again %s unfinished %v, want passed for app alone\n%s", pe.Outcome, pe.Unfinished, w.logs.String()) + } + var third seat.Pipeline + 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)) + } } diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/views.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/views.go index 2c30941fc..a27356016 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/views.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/views.go @@ -115,7 +115,7 @@ func (h *holderView) Nodes(seats []string) ([]string, bool) { // after, then start hub once. func startViews(ctx context.Context, js jetstream.JetStream, conn *nats.Conn, cred process.Account, hub *process.EventHub, findingsState process.State, call meshcatalogclient.Call, onReady, onAdvance func(branch string), candidate func(ctx context.Context, ev catalog.CatalogRevisionEvent) error, - registered func(reg catalog.Registration), revised func(ev catalog.CatalogRevisionEvent) (int, error), logf func(string, ...any)) (*runnerViews, error) { + registered func(reg catalog.Registration, gone bool), revised func(ev catalog.CatalogRevisionEvent) (int, error), logf func(string, ...any)) (*runnerViews, error) { findings, err := findingWriter(ctx, cred, conn, js, findingsState, logf) if err != nil { return nil, err @@ -132,7 +132,9 @@ func startViews(ctx context.Context, js jetstream.JetStream, conn *nats.Conn, cr // is picked up as readiness is: its pipelines started with no steps are placed then (A-327, A-336). var wired atomic.Pointer[meshcatalogclient.Catalog] var ready pipeline.Readiness - c, _, err := meshcatalogclient.WireCatalogProcess(reader, call, branch, func(string, json.RawMessage, bool, time.Time) { + // A newer revision whose entries equal the one before changes no key, so the follower's Changed never tells it: the view + // holding it is told by Held as well (design 47 H2 H-A-747, DQ-56). + observe := func() { c := wired.Load() if c == nil || onReady == nil { return @@ -148,7 +150,9 @@ func startViews(ctx context.Context, js jetstream.JetStream, conn *nats.Conn, cr go onAdvance(branch) } } - }) + } + c, _, err := meshcatalogclient.WireCatalogProcess(reader, call, branch, func(string, json.RawMessage, bool, time.Time) { observe() }, + func(catalog.CatalogRevision) { observe() }) if err != nil { return nil, err } @@ -158,9 +162,10 @@ func startViews(ctx context.Context, js jetstream.JetStream, conn *nats.Conn, cr regs, _, err := meshcatalogclient.WireRegistrationsProcess(reader, call, func(reg catalog.Registration, gone bool) { if !gone { cv.Registered(reg) - // A pipeline of the module started before this registration gets its steps from it (A-327). - registered(reg) } + // A pipeline of the module started before this registration gets its steps from it (A-327); a module the view no + // longer names has its finding pipeline-failed cleared (design 47 H2 H-A-605 (2)). + registered(reg, gone) }) if err != nil { return nil, err @@ -191,5 +196,5 @@ func (v catalogView) View() (pipeline.Half, bool) { if !ok { return pipeline.Half{}, false } - return pipeline.Half{Revision: h.Revision.Revision, Source: h.Revision.Source, Entries: h.Entries}, true + return pipeline.Half{Revision: h.Revision.Revision, Source: h.Revision.Source, Base: h.Revision.Base, Entries: h.Entries}, true } diff --git a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/widens.go b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/widens.go index eb509c08f..8447568cd 100644 --- a/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/widens.go +++ b/modules/mesh-delivery-pipeline/cmd/mesh-delivery-pipeline/widens.go @@ -175,7 +175,7 @@ func catalogRevision(call func(string, any) (json.RawMessage, error), kept *revi if h, ok := kept.get(branch, a.Revision.Revision); ok { return h, nil } - half = pipeline.Half{Revision: a.Revision.Revision, Source: a.Revision.Source, Entries: map[string]catalog.CatalogEntry{}, + half = pipeline.Half{Revision: a.Revision.Revision, Source: a.Revision.Source, Base: a.Revision.Base, Entries: map[string]catalog.CatalogEntry{}, Call: a.Revision.Call, Movers: a.Revision.Movers} in.Revision = a.Revision.Revision // the pages of one revision, though a newer one is said between them } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/carry.go b/modules/mesh-delivery-pipeline/internal/pipeline/carry.go new file mode 100644 index 000000000..3325b1d32 --- /dev/null +++ b/modules/mesh-delivery-pipeline/internal/pipeline/carry.go @@ -0,0 +1,177 @@ +package pipeline + +import ( + "errors" + "fmt" + "slices" + + 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). +type AddedFrom struct { + // From is the key of the pipeline the mover came from. + From string + // Caller is the caller of start, as the runtime proved it. + Caller string + // TakeIn is the source revision of the take-in whose entries were added to a pipeline held already. + TakeIn int64 +} + +// openPipeline says whether p waits or runs: a delivering pipeline that has not ended. +func openPipeline(p seat.Pipeline) bool { + return p.Run == "" && (p.Outcome == seat.PipelineOutcomeRunning || p.Outcome == seat.PipelineOutcomeWaiting) && p.Ended == nil +} + +// AddMovers adds to the pipeline key, which waits or runs, each of movers it does not move yet, tiers them with the rest from +// entries, says one mover-added per mover added with the origin (H-A-594 (3), (4), H-A-609 (3)), and places their steps from +// the branch's view. It answers the modules added. +func (s *Starter) AddMovers(key string, movers []seat.Mover, entries map[string]catalog.CatalogEntry, from AddedFrom, view func(branch string) (Half, bool)) ([]string, error) { + if s.Store == nil { + return nil, errors.New("the runner reads no pipeline") + } + var p seat.Pipeline + var added []seat.Mover + for { + cur, rev, err := s.Store.Get(key) + if err != nil { + return nil, fmt.Errorf("the pipeline %s is not read: %w", key, err) + } + if !openPipeline(cur) { + return nil, fmt.Errorf("the pipeline %s neither waits nor runs: no mover is added", key) + } + added = added[:0] + for _, m := range movers { + if !Moves(cur, m.Module) { + added = append(added, m) + } + } + if len(added) == 0 { + return nil, nil + } + cur.Movers = Tiers(append(slices.Clone(cur.Movers), added...), entries, s.logf) + if _, err := s.Store.Update(key, cur, rev); errors.Is(err, ErrChanged) { + continue + } else if err != nil { + return nil, fmt.Errorf("the pipeline %s is not written: %w", key, err) + } + p = cur + break + } + var names []string + for _, m := range added { + names = append(names, m.Module) + s.sayMoverAdded(p, m, from) + } + s.logf("%s: %v added (%s)", key, names, from.describe()) + if view != nil { + if _, err := s.Waiting(s.Store, p.Branch, view); err != nil { + return names, err + } + } + return names, nil +} + +// sayMoverAdded says mover-added for m of pipeline p with its origin (design 47 H2 H-A-645). +func (s *Starter) sayMoverAdded(p seat.Pipeline, m seat.Mover, from AddedFrom) { + if s.Say == nil { + return + } + ev := seat.MoverAdded{Pipeline: p.Pipeline, Revision: p.Revision, Module: m.Module, Fingerprint: m.Fingerprint, From: from.From, Caller: from.Caller, TakeIn: from.TakeIn} + if err := s.Say(runnerclient.RevisionSubject(seat.EventMoverAdded, p.Branch, subjectRevision(p)), ev); err != nil { + s.logf("mover-added of %s in %s is not said: %v", m.Module, p.Pipeline, err) + } +} + +func (f AddedFrom) describe() string { + switch { + case f.From != "": + return "carried from " + f.From + case f.Caller != "": + return "started by " + f.Caller + } + 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 +} + +// CarryToHead adds the closed group of movers pipeline from left to the head's pipeline of its branch 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) { + return "", false + } + if _, err := s.AddMovers(head.Pipeline, group, entries, AddedFrom{From: from.Pipeline}, view); err != nil { + s.logf("the movers %v of %s are not added to %s: %v", moduleNames(group), from.Pipeline, head.Pipeline, err) + return "", false + } + for { + cur, rev, err := s.Store.Get(from.Pipeline) + if err != nil { + return head.Pipeline, true + } + cur.Movers = slices.DeleteFunc(slices.Clone(cur.Movers), func(m seat.Mover) bool { + return slices.ContainsFunc(group, func(g seat.Mover) bool { return g.Module == m.Module }) + }) + if _, err := s.Store.Update(from.Pipeline, cur, rev); errors.Is(err, ErrChanged) { + continue + } else if err != nil { + s.logf("%s's movers %v are not taken out after their carry: %v", from.Pipeline, moduleNames(group), err) + } + return head.Pipeline, true + } +} + +func moduleNames(movers []seat.Mover) []string { + var out []string + for _, m := range movers { + out = append(out, m.Module) + } + return out +} + +// HeldBehind are the movers of p, sorted, that the failed mover module holds back: those whose own steps held and that await +// it, directly or through others, or sit in the tier group of one that does (H-A-625 (2)). +func HeldBehind(p seat.Pipeline, module string, entries map[string]catalog.CatalogEntry) []string { + failed := failedMovers(p) + var left []string + for _, m := range p.Movers { + if !slices.Contains(failed, m.Module) && ownStepsHeld(p, m.Module) { + left = append(left, m.Module) + } + } + var out []string + for m, by := range tiedTo(p, left, failed, entries) { + if slices.Contains(by, module) { + out = append(out, m) + } + } + slices.Sort(out) + return out +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/carry_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/carry_test.go new file mode 100644 index 000000000..63de02f3c --- /dev/null +++ b/modules/mesh-delivery-pipeline/internal/pipeline/carry_test.go @@ -0,0 +1,9 @@ +package pipeline + +import catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + +func edgeInto(entries map[string]catalog.CatalogEntry, to, from string, kind int64) { + e := entries[to] + e.Edges = append(e.Edges, catalog.Edge{From: catalog.ArtifactRef(from + ":x"), Kind: kind}) + entries[to] = e +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/ended_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/ended_test.go index 1080f9715..74efa466d 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/ended_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/ended_test.go @@ -134,10 +134,9 @@ func (m memUnfinished) Get(k string) ([]byte, error) { func (m memUnfinished) Put(k string, v []byte) error { m[k] = string(v); return nil } func (m memUnfinished) Delete(k string) error { delete(m, k); return nil } func (m memUnfinished) Keys(filter string) ([]string, error) { - prefix := strings.TrimSuffix(filter, "*") var out []string for k := range m { - if strings.HasPrefix(k, prefix) { + if ok, _ := matchKey(filter, k); ok { out = append(out, k) } } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go index 1c07f6844..e0b5f7a97 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/endopen_test.go @@ -78,7 +78,7 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { bs := stepSeatOf(t, builds.Seat) end := StepEnded{ID: "x1", Node: "n1", Pipeline: "main.117", Module: "a", Commit: "c1", Fingerprint: "src2:a1", Step: "build", Outcome: builds.StepEndedOutcomeSuperseded, Said: "a at src2:a1 is superseded by src2:a2, the newest entry heard on its first branch"} - if _, err := h.OnStepEnded(bs, bs.Prefix+"n1", end); err != nil { + if _, err := h.OnStepEndedRevised(bs, bs.Prefix+"n1", end, nil, nil, 120); err != nil { // the end names its superseding revision (H-A-601) t.Fatal(err) } p, _, _ := h.Store.Get("main.117") @@ -123,7 +123,7 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { store.refused["main.118"], store.refused["main.119"] = true, true grants, revisions := 0, 0 w := &Widener{ - Revision: func(string, int64) (Half, error) { revisions++; return Half{}, nil }, + Revision: func(string, int64) (Half, error) { revisions++; return Half{Base: 4}, nil }, Holder: func(s string) (string, error) { return s, nil }, GrantsFor: func(string, int64) (meshgrants.GrantsFor, error) { grants++ @@ -172,8 +172,8 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { h := &Hearer{Store: store, Say: func(string, any) error { return nil }, Now: func() time.Time { return t0 }, Release: func(key string) { released = append(released, key) }, View: newerView} bs := stepSeatOf(t, builds.Seat) - got, err := h.OnStepEnded(bs, bs.Prefix+"n1", StepEnded{ID: "x1", Node: "n1", Pipeline: "main.117", Module: "a", Commit: "c1", Fingerprint: "src2:a1", - Step: "build", Outcome: builds.StepEndedOutcomeSuperseded, Said: "a at src2:a1 is superseded by src2:a2"}) + got, err := h.OnStepEndedRevised(bs, bs.Prefix+"n1", StepEnded{ID: "x1", Node: "n1", Pipeline: "main.117", Module: "a", Commit: "c1", Fingerprint: "src2:a1", + Step: "build", Outcome: builds.StepEndedOutcomeSuperseded, Said: "a at src2:a1 is superseded by src2:a2"}, nil, nil, 120) if err != nil { t.Fatal(err) } @@ -197,7 +197,7 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { view int64 want string // left, again or held }{ - {"an end naming no revision (H-A-508 as before)", 0, 116, "left"}, + {"an end naming no revision (H-A-601: could not run)", 0, 116, "could-not-run"}, {"an older revision's entry", 116, 117, "again"}, {"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"}, @@ -208,19 +208,25 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { Movers: slices.Clone(movers[:2]), Steps: []seat.StepResult{step("a", seat.StepResultOutcomeRunning, "x1"), step("b", seat.StepResultOutcomeRunning, "x2")}}, rev: 1}} 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 started []seat.StepEvent view := r.view say := func(subject string, body any) error { + if ev, ok := body.(seat.StepEvent); ok && strings.Contains(subject, seat.EventStepStarted) { + started = append(started, ev) + } if w, ok := body.(seat.Wait); ok { ev := seat.EventWaitHeld if strings.Contains(subject, seat.EventWaitEnded) { ev = seat.EventWaitEnded } + waitBodies = append(waitBodies, w) waits = append(waits, ev+" "+w.Step+" "+w.On+" "+w.Module) } return nil } - h := &Hearer{Store: store, Say: say, Now: func() time.Time { return t0 }, + h := &Hearer{Store: store, Say: say, Now: func() time.Time { return t0 }, Name: "mesh-delivery-pipeline", StalledBound: time.Minute, View: func(string) (Half, bool) { return Half{Revision: view, Source: view, Entries: map[string]catalog.CatalogEntry{"a": {Module: "a", Fp: "src2:a2"}}}, true }, @@ -239,6 +245,11 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { return slices.Equal(p.Superseded, []string{"a"}) && p.Steps[0].Outcome == seat.StepResultOutcomeSuperseded && len(put) == 0 } switch r.want { + case "could-not-run": + // H2 H-A-601: no revision, no judging: the step ends could-not-run naming the builder and the words, the mover stays + if s := p.Steps[0]; len(p.Superseded) != 0 || s.Outcome != seat.StepResultOutcomeCouldNotRun || !strings.Contains(s.Why, "a superseded end without its revision") || len(put) != 0 { + t.Errorf("superseded %v, a's build %+v, put %+v; want the step could-not-run with the words, the mover staying", p.Superseded, s, put) + } case "left": if !left(p) { t.Errorf("superseded %v, a's build %+v, put %+v; want a left, its build superseded, nothing asked again", p.Superseded, p.Steps[0], put) @@ -248,6 +259,14 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { len(put) != 1 || put[0].ID != "x1again" || p.Outcome != seat.PipelineOutcomeRunning { t.Errorf("superseded %v, a's build %+v, put %+v, pipeline %s; want nothing left, the build asked again as x1again", p.Superseded, p.Steps[0], put, p.Outcome) } + // H2 H-A-577 (3): the passed-over end is said as a step-started with rerun and the runner as the caller + if len(started) != 1 || !started[0].Result.Rerun || started[0].Result.By != "mesh-delivery-pipeline" || started[0].Result.Ask != "x1again" { + t.Errorf("step-started said %+v, want one rerun by the runner of x1again", started) + } + // H-A-743: the step log's entry of the step asked again names the pipeline's own revision and the passed-over end's. + if len(p.Unlogged) != 1 || p.Unlogged[0].Revision == 0 || p.Unlogged[0].PassedOver == 0 || p.Unlogged[0].PassedOver >= p.Unlogged[0].Revision || p.Unlogged[0].What != seat.LogEntryWhatStarted { + t.Errorf("the step log's entries %+v, want one started entry naming the pipeline's revision and the older passed-over one", p.Unlogged) + } 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) } @@ -256,6 +275,9 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { len(put) != 0 || p.Outcome != seat.PipelineOutcomeRunning { t.Fatalf("superseded %v, a's build %+v, put %+v; want the build waiting on the revision view for revision 120, nothing asked", p.Superseded, s, put) } + if s := p.Steps[0]; s.HeldAt == nil || !s.HeldAt.Equal(t0) { + t.Errorf("the held step keeps held-at %v, want %v", s.HeldAt, t0) + } if want := []string{seat.EventWaitHeld + " build revision view a"}; !slices.Equal(waits, want) { t.Errorf("waits said %q, want %q", waits, want) } @@ -268,12 +290,18 @@ func TestAPipelineWithNothingOpenEndsAtOnce(t *testing.T) { if moved := h.RevisionHeld("main"); !slices.Equal(moved, []string{"main.117"}) { t.Errorf("at revision 120 the view moved %v, want main.117", moved) } - if p, _, _ := store.Get("main.117"); !left(p) || p.Steps[0].On != "" || p.Outcome != seat.PipelineOutcomeRunning { + if p, _, _ := store.Get("main.117"); !left(p) || p.Steps[0].On != "" || p.Steps[0].HeldAt != nil || p.Outcome != seat.PipelineOutcomeRunning { t.Errorf("after the view held 120: superseded %v, a's build %+v, pipeline %s; want a left, b still running", p.Superseded, p.Steps[0], p.Outcome) } 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) } + // 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) { + t.Errorf("a wait said with bound %q and clock-from %v, want 1m0s and %v", w.Bound, w.ClockFrom, t0) + } + } } }) } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/failed.go b/modules/mesh-delivery-pipeline/internal/pipeline/failed.go index 313264edf..10417b3e1 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/failed.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/failed.go @@ -38,6 +38,8 @@ type Failures struct { Author func(repository, commit string) (string, error) Now func() time.Time Logf func(string, ...any) + // Behind names the movers of p that a failed mover holds back, for the finding's words (H-A-625 (2)); nil names none. + Behind func(p seat.Pipeline, module string) []string } func (f *Failures) logf(format string, args ...any) { @@ -126,6 +128,11 @@ func (f *Failures) write(ctx context.Context, p seat.Pipeline, m seat.Mover) { if why != "" { explanation += " " + why } + if f.Behind != nil { + if held := f.Behind(p, m.Module); len(held) > 0 { + explanation += fmt.Sprintf(" The movers %s are held behind it, in the state unfinished; runner_unfinished_place places them.", strings.Join(held, ", ")) + } + } id := findingID(m.Module, p.Branch) err := f.Findings.Write(ctx, condseat.Finding{Scope: mcc.ScopeDelivery, ID: id, Kind: PipelineFailedKind, Severity: condseat.FindingSeverityWarning, Summary: fmt.Sprintf("%s on %s in %s: %s", m.Module, p.Branch, p.Pipeline, strings.Join(names, ", ")), @@ -154,3 +161,20 @@ func (f *Failures) author(m seat.Mover) (string, string) { } return "forge:" + account, "" } + +// ModuleGone clears every finding pipeline-failed of module, on any branch, when the registrations view no longer names the +// module, as the indexer frees its failed record (design 47 H2 H-A-605 (2)). +func (f *Failures) ModuleGone(module string) { + if f == nil || f.Findings == nil { + return + } + prefix := findingID(module, "") + for _, h := range f.Findings.Held() { + if h.Scope != mcc.ScopeDelivery || h.Kind != PipelineFailedKind || !strings.HasPrefix(h.ID, prefix) { + continue + } + if err := f.Findings.Clear(context.Background(), mcc.ScopeDelivery, h.ID, PipelineFailedKind, module+" is no longer registered"); err != nil { + f.logf("the finding %s %s is not cleared: %v", PipelineFailedKind, h.ID, err) + } + } +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/failed_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/failed_test.go index 6b3c04d4c..760e7e857 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/failed_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/failed_test.go @@ -7,6 +7,7 @@ import ( "testing" condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" + 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" nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" ) @@ -156,4 +157,29 @@ func TestEachFailingMoverIsAFindingAndItsNextPassedPipelineClearsIt(t *testing.T if _, stands := f.held["delivery.app.main.pipeline-failed"]; !stands || len(f.held) != 1 { t.Fatalf("findings %v, want app's alone after lib's pipeline passed", f.held) } + // design 47 H2 H-A-605 (2), H-A-625 (2) (AC-P7, AC-P7b): a module the registrations view no longer names has its finding + // pipeline-failed cleared, on any branch; the finding names the movers held behind the failed one and runner_unfinished_place. + t.Run("TestAFailedFindingNamesTheMoversHeldBehindAndGoesWithTheRegistration", func(t *testing.T) { + f := newHeld() + entries := map[string]catalog.CatalogEntry{} + edgeInto(entries, "gitea", "engine", 1) + p := seat.Pipeline{Pipeline: "main.5", Branch: "main", Revision: 5, + Movers: []seat.Mover{{Module: "engine", Commit: "c1"}, {Module: "gitea"}}, + Steps: []seat.StepResult{{Module: "engine", Step: seat.StepResultStepLint, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeFailed}, + {Module: "gitea", Step: seat.StepResultStepLint, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeNotAsked}}} + fl := &Failures{Findings: f, Observer: "runner", Behind: func(p seat.Pipeline, m string) []string { return HeldBehind(p, m, entries) }} + fl.StepEnded(nil, p, p.Steps[0]) + got := f.held["delivery.engine.main.pipeline-failed"] + if !strings.Contains(got.Explanation, "gitea are held behind it") || !strings.Contains(got.Explanation, "runner_unfinished_place") { + t.Fatalf("the finding says %q, want gitea held behind it and runner_unfinished_place", got.Explanation) + } + fl.Findings.(*heldFindings).held["delivery.engineer.main.pipeline-failed"] = condseat.Finding{Scope: "delivery", ID: "engineer.main", Kind: PipelineFailedKind} + fl.ModuleGone("engine") + if _, ok := f.held["delivery.engine.main.pipeline-failed"]; ok { + t.Errorf("engine left the registrations and its finding is held") + } + if _, ok := f.held["delivery.engineer.main.pipeline-failed"]; !ok { + t.Errorf("the finding of engineer, another module, was cleared") + } + }) } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go b/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go new file mode 100644 index 000000000..f707ebbf5 --- /dev/null +++ b/modules/mesh-delivery-pipeline/internal/pipeline/handplace.go @@ -0,0 +1,441 @@ +package pipeline + +import ( + "errors" + "fmt" + "slices" + "strings" + + 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" +) + +// Start starts by hand the named modules at the head of a watched branch the runner's catalog half holds, recorded in the hand-act +// log first (design 47 H2 H-A-571, H-A-607 (3), H-A-643): exactly one of module or modules. Each module follows one rule: the +// head's pipeline `.` takes it as a mover while that pipeline waits or runs, said by mover-added with the +// caller; a head with no pipeline is started with the modules named; once the head's pipeline has ended, start never refuses (H-A-750 +// (2), H-A-751): a module it does not move reopens it as a mover, one whose own step failed or whose steps are unfinished reopens +// it with its closed group as rerun and place-unfinished do, and one it delivered is answered by it. No other pipeline is keyed. +func (v Verbs) Start(caller string, in seat.StartInput) (seat.StartAnswer, error) { + if in.Module != "" && len(in.Modules) > 0 { + return seat.StartAnswer{}, errors.New("start names the module or the modules, not both: nothing was started") + } + modules := in.Modules + if in.Module != "" { + modules = []string{in.Module} + } + if in.Branch == "" || len(modules) == 0 { + return seat.StartAnswer{}, errors.New("start names the watched branch and the module or the modules") + } + s := v.Starter + if s == nil || s.Store == nil || v.View == nil { + return seat.StartAnswer{}, errors.New("the runner cannot start a pipeline: it holds no starter or no catalog half") + } + half, ok := v.View(in.Branch) + if !ok || half.Source <= 0 { + return seat.StartAnswer{}, fmt.Errorf("the catalog half of %s is not held at a source revision yet: nothing was started", in.Branch) + } + var movers []seat.Mover + var absent []string + for _, m := range modules { + e, ok := half.Entries[m] + switch { + case !ok: + absent = append(absent, m) + case !slices.ContainsFunc(movers, func(x seat.Mover) bool { return x.Module == m }): + movers = append(movers, seat.Mover{Module: m, Commit: e.Commit, Fingerprint: e.Fp, Repository: e.Repository}) + } + } + 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) + if err != nil { + return seat.StartAnswer{}, fmt.Errorf("the pipeline %s is not looked for: nothing was started: %w", key, 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) + } + } + 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: + if err := v.record(seat.VerbStart, what, in.Why); err != nil { + return seat.StartAnswer{}, err + } + movers = Tiers(movers, half.Entries, s.logf) + started, err := s.Start(Begin{Branch: in.Branch, Source: half.Source, Revision: half.Revision, Entries: half.Entries, Movers: movers}) + if err != nil { + return seat.StartAnswer{}, err + } + if !started { + return seat.StartAnswer{}, fmt.Errorf("the pipeline %s is started already: nothing was started", key) + } + return seat.StartAnswer{Pipeline: key}, nil + case openPipeline(head): + var add []seat.Mover + for _, m := range movers { + if !Moves(head, m.Module) { + add = append(add, m) + } + } + if len(add) == 0 { + return seat.StartAnswer{}, fmt.Errorf("the pipeline %s moves %s already: a step of it is asked again by rerun: nothing was started", key, strings.Join(names, ", ")) + } + if err := v.record(seat.VerbStart, what, in.Why); err != nil { + return seat.StartAnswer{}, err + } + if _, err := s.AddMovers(key, add, half.Entries, AddedFrom{Caller: caller}, v.View); err != nil { + return seat.StartAnswer{}, err + } + return seat.StartAnswer{Pipeline: key}, nil + } + // The head's pipeline has ended and start never refuses (design 47 H2 H-A-750 (2), H-A-751): a module it does not move is added + // to it as a mover; one it moves whose own step failed, or whose required steps did not all pass, reopens it with its closed + // group, as rerun and place-unfinished do; one it moved and whose steps passed is delivered by it, nothing to start. + entries := half.Entries + var group []string + var add []seat.Mover + for _, m := range movers { + switch { + case !Moves(head, m.Module): + add = append(add, m) + case len(failedSteps(head, m.Module)) > 0 || !allPassed(head, m.Module): + group = appendNew(group, v.closedGroup(head, m.Module, entries)...) + } + } + if len(group) == 0 && len(add) == 0 { + return seat.StartAnswer{Pipeline: key}, nil + } + if err := v.record(seat.VerbStart, what, in.Why); err != nil { + return seat.StartAnswer{}, err + } + if err := v.reopenGroup(caller, head, group, add, entries, in.Why); err != nil { + return seat.StartAnswer{}, err + } + s.markCarriedKeys(head, group, head.Pipeline) + return seat.StartAnswer{Pipeline: key}, 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 { + has := false + for _, st := range p.Steps { + if st.Module != module || st.Status != seat.StepResultStatusRequired { + continue + } + if has = true; !stepPassed(st) { + return false + } + } + return has +} + +func appendNew(into []string, add ...string) []string { + for _, a := range add { + if !slices.Contains(into, a) { + into = append(into, a) + } + } + return into +} + +// closedGroup is the group of movers of p that go with module: closed under the tier edges and under every awaited edge from a +// mover that left unfinished or failed, so a mover goes only with every mover it has an edge from (design 47 H2 H-A-594 (2), +// H-A-646). A passed mover is never in it. +func (v Verbs) closedGroup(p seat.Pipeline, module string, entries map[string]catalog.CatalogEntry) []string { + left := unfinishedOf(p) + universe := appendNew(slices.Clone(left), failedMovers(p)...) + group := []string{module} + for changed := true; changed; { + changed = false + for _, g := range tierGroups(universe, entries) { + if slices.ContainsFunc(g, func(m string) bool { return slices.Contains(group, m) }) { + for _, m := range g { + if !slices.Contains(group, m) { + group, changed = append(group, m), true + } + } + } + } + for _, m := range slices.Clone(group) { + for _, x := range awaited(p, m, entries) { + if from := moduleOf(x.From); slices.Contains(universe, from) && !slices.Contains(group, from) { + group, changed = append(group, from), true + } + } + } + } + slices.Sort(group) + return group +} + +// markCarriedKeys names carrier as the carrier of the unfinished keys of group's modules of p's branch. +func (s *Starter) markCarriedKeys(p seat.Pipeline, group []string, carrier string) { + if s.Unfinished != nil { + s.Unfinished.markCarried(p.Branch, group, carrier) + } +} + +// reopenGroup reopens the ended pipeline from for group alone (design 47 H2 H-A-607 (3), H-A-609 (1), H-A-623): the movers outside +// the group that left unfinished or failed leave its movers, so its next end judges the group; a group mover with a failed step +// asks it again as rerun asks it, and one with none has its steps placed again, its passed packages carried by their kept +// results. The group's hand act is the caller's. +func (v Verbs) reopenGroup(caller string, from seat.Pipeline, group []string, add []seat.Mover, entries map[string]catalog.CatalogEntry, why string) error { + reopens, err := v.reopeningFor(from.Pipeline, true) + if err != nil { + return err + } + if !reopens { + return fmt.Errorf("the pipeline %s is %s and cannot be reopened: nothing was placed", from.Pipeline, from.Outcome) + } + s := v.Starter + var failed []seat.StepResult + for _, m := range group { + failed = append(failed, failedSteps(from, m)...) + } + for { + cur, rev, err := s.Store.Get(from.Pipeline) + if err != nil { + return fmt.Errorf("the pipeline %s is not read: %w", from.Pipeline, err) + } + outside := appendNew(unfinishedOf(cur), failedMovers(cur)...) + cur.Movers = slices.DeleteFunc(slices.Clone(cur.Movers), func(m seat.Mover) bool { + return slices.Contains(outside, m.Module) && !slices.Contains(group, m.Module) + }) + // The modules start adds come after the movers outside the group left, and are tiered with the rest (H-A-750 (2)). + if len(add) > 0 { + cur.Movers = Tiers(append(cur.Movers, add...), entries, s.logf) + } + for _, m := range group { + if len(failedSteps(cur, m)) == 0 { + cur.Steps = slices.DeleteFunc(slices.Clone(cur.Steps), func(st seat.StepResult) bool { return st.Module == m }) + // The steps placed again take ask ids of their own: an id is made from the pipeline's start and its end count, which the + // reopen's next end raises (H-A-753); the pipeline's start stays its first (H-A-750 (4)). + } + } + if len(failed) == 0 || cur.Outcome == seat.PipelineOutcomeCancelled { + cur.Outcome, cur.Why, cur.Ended = seat.PipelineOutcomeRunning, "", nil + } + if _, err := s.Store.Update(from.Pipeline, cur, rev); errors.Is(err, ErrChanged) { + continue + } else if err != nil { + return fmt.Errorf("the pipeline %s is not written: %w", from.Pipeline, err) + } + break + } + w := v + w.noRecord = true + for i, st := range failed { + if _, err := w.rerun(caller, seat.RerunInput{Pipeline: from.Pipeline, Module: st.Module, Step: st.Step, Artifact: st.Artifact, Why: why}, reopens && i == 0); err != nil { + return fmt.Errorf("the %s step of %s in %s is not asked again: %w", st.Step, st.Module, from.Pipeline, err) + } + } + // Only a module start adds to a pipeline that did not move it is said by mover-added with the caller (H-A-750 (2), H-A-755); a + // group reopened in its own pipeline adds none. + p, _, err := s.Store.Get(from.Pipeline) + if err != nil { + return fmt.Errorf("the pipeline %s is not read: %w", from.Pipeline, err) + } + for _, m := range add { + s.sayMoverAdded(p, m, AddedFrom{Caller: caller}) + } + if len(failed) == 0 || len(add) > 0 { + if len(failed) == 0 { + v.sayReopened(p, true) + } + if _, err := s.Waiting(s.Store, p.Branch, v.View); err != nil { + return err + } + } + s.logf("%s reopened by hand for %s (H-A-607 (3))", from.Pipeline, strings.Join(group, ", ")) + return nil +} + +// handPlan is one group place-unfinished puts: the keys of its movers in the state unfinished, the pipeline they left and the +// movers that go. +type handPlan struct { + keys []string + from seat.Pipeline + group []string + movers []seat.Mover + // entries are the entries a carry tiers its movers from. + entries map[string]catalog.CatalogEntry +} + +// planUnfinished is the group key belongs to (design 47 H2 H-A-607 (3)): refused, naming why, a key the state does not hold, one a +// pipeline that waits or runs carries, one whose pipeline no longer moves it, or one whose entry holds another fingerprint. +func (v Verbs) planUnfinished(key string) (handPlan, error) { + s := v.Starter + e, held, err := s.Unfinished.Entry(key) + if err != nil { + return handPlan{}, fmt.Errorf("the unfinished entry %s is not read: %w", key, err) + } + if !held { + return handPlan{}, fmt.Errorf("the state unfinished holds no %s", key) + } + b, m, _ := strings.Cut(key, ".") + branch, berr := keys.UnescapeName(b) + module, merr := keys.UnescapeName(m) + if berr != nil || merr != nil || branch == "" || module == "" { + return handPlan{}, fmt.Errorf("%s is no key .", key) + } + if e.CarriedBy != "" { + if c, _, err := s.Store.Get(e.CarriedBy); err == nil && openPipeline(c) { + return handPlan{}, fmt.Errorf("%s carries it and waits or runs", e.CarriedBy) + } + } + from, _, err := s.Store.Get(e.Pipeline) + 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: + 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) + } + group := v.closedGroup(from, module, half.Entries) + plan := handPlan{from: from, group: group, entries: half.Entries} + if head, ok := v.View(branch); ok && head.Entries != nil { + plan.entries = head.Entries + } + for _, g := range group { + mv, _ := MoverOf(from, g) + plan.movers = append(plan.movers, mv) + if k := UnfinishedKey(branch, g); slices.ContainsFunc(unfinishedOf(from), func(x string) bool { return x == g }) { + if _, ok, _ := s.Unfinished.Entry(k); ok { + plan.keys = append(plan.keys, k) + } + } + } + return plan, nil +} + +// PlaceUnfinished puts the closed group of a mover kept in the state unfinished in a pipeline at once, recorded in the hand-act log +// once for the call (design 47 H2 §786, H-A-607 (3), H-A-644, H-A-725): with `key` the one key's group, with `all` every key whose +// carrier neither waits nor runs. 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 and revision, a failed mover asked again as +// rerun asks it. With `all` the answer lists each key placed and each key not, with its words. +func (v Verbs) PlaceUnfinished(caller string, in seat.PlaceUnfinishedInput) (seat.PlaceUnfinishedAnswer, error) { + s := v.Starter + one := strings.TrimSpace(in.Key) + if (one == "") == !in.All { + return seat.PlaceUnfinishedAnswer{}, errors.New("place-unfinished names the unfinished entry's key or all, exactly one: nothing was placed") + } + if s == nil || s.Unfinished == nil || s.Store == nil { + return seat.PlaceUnfinishedAnswer{}, errors.New("the runner keeps no state unfinished: nothing was placed") + } + todo := []string{one} + if in.All { + var err error + if todo, err = s.Unfinished.Store.Keys("*.*"); err != nil { + return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the state unfinished is not listed: nothing was placed: %w", err) + } + slices.Sort(todo) + } + ans := seat.PlaceUnfinishedAnswer{Placed: []seat.PlaceUnfinishedAnswerPlacedItem{}, Failed: []seat.PlaceUnfinishedAnswerFailedItem{}} + type unit struct { + plan handPlan + keys []string + } + var units []unit + done := map[string]bool{} + for _, k := range todo { + if done[k] { + continue + } + plan, err := v.planUnfinished(k) + if err != nil { + if !in.All { + return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("%v: nothing was placed", err) + } + if e, held, _ := s.Unfinished.Entry(k); held && e.CarriedBy != "" && strings.Contains(err.Error(), "waits or runs") { + continue // carried already: nothing to place + } + ans.Failed = append(ans.Failed, seat.PlaceUnfinishedAnswerFailedItem{Key: k, Words: err.Error()}) + continue + } + for _, pk := range plan.keys { + done[pk] = true + } + units = append(units, unit{plan: plan, keys: plan.keys}) + } + var all []string + for _, u := range units { + all = append(all, u.keys...) + } + for _, f := range ans.Failed { + all = append(all, f.Key) + } + if len(all) == 0 { + if in.All { + ans.Said = "the state unfinished holds no key to place" + } + return ans, nil + } + if err := v.record(seat.VerbPlaceUnfinished, "put the unfinished movers "+strings.Join(all, ", ")+" in a pipeline by hand", in.Why); err != nil { + return seat.PlaceUnfinishedAnswer{}, err + } + w := v + w.noRecord = true + for _, u := range units { + pipe, err := w.placeGroup(caller, u.plan, in.Why) + if err != nil { + if !in.All { + return seat.PlaceUnfinishedAnswer{}, err + } + for _, k := range u.keys { + ans.Failed = append(ans.Failed, seat.PlaceUnfinishedAnswerFailedItem{Key: k, Words: err.Error()}) + } + continue + } + ans.Pipeline = pipe + for _, k := range u.keys { + ans.Placed = append(ans.Placed, seat.PlaceUnfinishedAnswerPlacedItem{Key: k, Pipeline: pipe}) + } + } + if in.All { + ans.Pipeline = "" + } + return ans, nil +} + +// placeGroup puts one group (PlaceUnfinished): in the head's pipeline when none of its movers failed and that waits or runs, +// otherwise by reopening the pipeline it left. It answers the pipeline that carries the group now. +func (v Verbs) placeGroup(caller string, plan handPlan, why string) (string, error) { + s := v.Starter + failed := false + for _, m := range plan.group { + failed = failed || len(failedSteps(plan.from, m)) > 0 + } + if !failed { + if carrier, ok := s.CarryToHead(plan.from, plan.movers, plan.entries, v.View); ok { + s.markCarriedKeys(plan.from, plan.group, carrier) + s.logf("%s puts %s in the head's pipeline %s by hand (H-A-607 (3))", plan.from.Pipeline, strings.Join(plan.group, ", "), carrier) + return carrier, nil + } + } + if err := v.reopenGroup(caller, plan.from, plan.group, nil, plan.entries, why); err != nil { + return "", err + } + s.markCarriedKeys(plan.from, plan.group, plan.from.Pipeline) + return plan.from.Pipeline, nil +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/place.go b/modules/mesh-delivery-pipeline/internal/pipeline/place.go index 6d8002604..80f1446b8 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/place.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/place.go @@ -78,10 +78,12 @@ func keptAskID(started time.Time, pipeline, module, artifact, step string, kept return strconv.FormatInt(started.UnixMilli(), 36) + hex.EncodeToString(sum[:3]) } -// startOf is a pipeline's start time, the time its step ask ids open with (A-297); now for a pipeline that records none. +// startOf is the time a pipeline's step ask ids open with (A-297): its start with its end count added as milliseconds, so a +// pipeline never ended keeps every id it has and each reopen gives every later ask an id of its own, the same again at a restart +// (design 47 H2 H-A-753); now for a pipeline that records no start. func startOf(p seat.Pipeline, now time.Time) time.Time { if p.Started != nil { - return *p.Started + return p.Started.Add(time.Duration(p.EndCount) * time.Millisecond) } return now } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/place_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/place_test.go index af5316902..57f62eb88 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/place_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/place_test.go @@ -97,6 +97,18 @@ func TestStartPlacesTheStepsThePolicyNamesAndAsksEachBuildSeat(t *testing.T) { t.Errorf("ask %d's id %q is not the usual form opened by the pipeline's start: %v", i, id, err) } } + // H-A-753: a pipeline of end count 0 asks with the ids it has; one reopened after an end (count 1) asks the steps placed again + // with ids of their own, the same on every computation, its start unchanged. + m0 := p.Movers[0] + same, sameAsks := Place(p, m0, reg, entries, *p.Started, "the-runner") + p.EndCount = 1 + again, againAsks := Place(p, m0, reg, entries, *p.Started, "the-runner") + again2, _ := Place(p, m0, reg, entries, p.Started.Add(time.Hour), "the-runner") + if len(sameAsks) != len(asks.ids) || len(againAsks) != len(asks.ids) || same[0].Ask != asks.ids[0] || again[0].Ask == same[0].Ask || again[0].Ask != again2[0].Ask || + !strings.HasPrefix(again[0].Ask, strconv.FormatInt(p.Started.UnixMilli()+1, 36)) { + t.Errorf("ids at end count 0 %q, at 1 %q and %q; want today's ids at 0, others at 1 that a later computation repeats", same[0].Ask, again[0].Ask, again2[0].Ask) + } + p.EndCount = 0 // H-A-516: the build step's record carries its asked-at, as a test step's does. if p.Steps[0].AskedAt == nil || !p.Steps[0].AskedAt.Equal(*p.Steps[0].Started) { t.Errorf("the build step's asked-at = %v, want the time it was asked", p.Steps[0].AskedAt) diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/read.go b/modules/mesh-delivery-pipeline/internal/pipeline/read.go index 584ed38b4..b59dd32f8 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/read.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/read.go @@ -29,6 +29,69 @@ type Reads struct { // Fill is each of the runner's stores' fill now, pipelines, kept and step-log, read through the bundle's calls // (the state's `mesh/state.info`, the object store's and the log's fill; design 47 G §366, §623, A-214); nil says none. Fill func() ([]seat.Fill, error) + // StalledBound is the runner's setting stalled-bound, the bound of a held step's wait (H-A-599, H-A-738 (2)). + StalledBound time.Duration + // AnswerBound is the runner's setting answer-bound, the most bytes show and stands answer when a call names no bound; + // zero reads as DefaultAnswerBound (design 47 H2 H-A-709 (2)). + AnswerBound int64 + // SaidCapped says, for the journal, that a caller named no bound and no next and was answered a capped page of verb with + // total rows or waits in all; the caller of it says it once per caller (design 47 H2 H-A-709 (2)). + SaidCapped func(caller, verb string, total int64) +} + +// Revised is a Kept that tells the revision of a key's record: the cursor of show holds it (design 47 H2 H-A-709 (2)). +type Revised interface { + Revision(key string) (uint64, error) +} + +// DefaultAnswerBound is the setting answer-bound's default, AnswerBoundSetting its name (design 47 H2 H-A-709 (2), §781): the +// runner's process and its tools program read it alike. MinAnswer is the least a call's bound may name. +const ( + DefaultAnswerBound = 32768 + AnswerBoundSetting = "answer-bound" + MinAnswer = 4096 +) + +// AnswerBound is the setting answer-bound as the runner's process and its tools program read it through setting (the runtime's +// word for a setting): a whole number of bytes from MinAnswer to MaxAnswer, DefaultAnswerBound when none is set. +func AnswerBound(setting func(key string) (string, bool)) (int64, error) { + v, ok := setting(AnswerBoundSetting) + if !ok || strings.TrimSpace(v) == "" { + return DefaultAnswerBound, nil + } + n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64) + if err != nil || n < MinAnswer || n > MaxAnswer { + return 0, fmt.Errorf("the setting %s is %q: it is a whole number of bytes from %d to %d", AnswerBoundSetting, v, MinAnswer, MaxAnswer) + } + return n, nil +} + +// cappedReserve is what a capped answer adds to its size: its capped flag and its cursor, so the bound holds the answer whole. +const cappedReserve = 96 + +// bound is the most bytes an answer holds: the call's, else the setting's, else the default; one outside MinAnswer to MaxAnswer +// is refused. +func (r Reads) bound(asked int64) (int, error) { + b := asked + if b == 0 { + b = r.AnswerBound + } + if b == 0 { + b = DefaultAnswerBound + } + if b < MinAnswer || b > MaxAnswer { + return 0, fmt.Errorf("the bound %d is outside %d to %d bytes: nothing was answered", b, MinAnswer, MaxAnswer) + } + return int(b), nil +} + +// revisionOf is the revision of key's record in the state pipelines, zero when the state tells none. +func (r Reads) revisionOf(key string) uint64 { + if rv, ok := r.Pipelines.(Revised); ok { + n, _ := rv.Revision(key) + return n + } + return 0 } // fills is the stores' fill, or an error saying it could not be read: an answer never leaves it out unsaid. @@ -61,10 +124,15 @@ func (r Reads) Show(in seat.ShowInput) (seat.ShowAnswer, error) { if err != nil { return seat.ShowAnswer{}, err } - from, err := pageFrom(in.Next) + bound, err := r.bound(in.Bound) if err != nil { return seat.ShowAnswer{}, err } + from, cursorRev, err := pageFrom(in.Next) + if err != nil { + return seat.ShowAnswer{}, err + } + rev := r.revisionOf(in.Pipeline) // Named, a mover is answered by its steps alone (H-A-187): one mover's of a pipeline of a hundred movers. m := strings.TrimSpace(in.Mover) if m != "" && !Moves(p, m) { @@ -74,13 +142,15 @@ func (r Reads) Show(in seat.ShowInput) (seat.ShowAnswer, error) { // Naming neither a mover nor a filter, show answers each mover's row, never every step of every mover (design 47 H2 // H-A-376), in pages as the steps are. rows := MoverRows(p) - p.Steps = []seat.StepResult{} - a := seat.ShowAnswer{Pipeline: p, Fill: fills, Total: int64(len(rows)), Movers: []seat.MoverRow{}} - size := sizeOf(a) + moverCount, stepCount := int64(len(p.Movers)), int64(len(p.Steps)) + p.Steps, p.Movers, p.Unlogged = []seat.StepResult{}, []seat.Mover{}, nil // the page's mover rows name each mover (design 47 H2 H-A-709 (1)) + p.MoverCount, p.StepCount = moverCount, stepCount + a := seat.ShowAnswer{Pipeline: p, Fill: fills, Total: int64(len(rows)), Movers: []seat.MoverRow{}, Moved: in.Next != "" && cursorRev != rev} + size := sizeOf(a) + cappedReserve for i := from; i < len(rows); i++ { n := sizeOf(rows[i]) + 1 - if size+n > MaxAnswer && len(a.Movers) > 0 { - a.Capped, a.Next = true, pageCursor(i) + if size+n > bound && len(a.Movers) > 0 { + a.Capped, a.Next = true, pageCursor(i, rev) break } size += n @@ -88,46 +158,74 @@ func (r Reads) Show(in seat.ShowInput) (seat.ShowAnswer, error) { } return a, nil } + p0steps := len(p.Steps) held := []seat.StepResult{} for _, s := range p.Steps { if (m == "" || s.Module == m) && (in.Step == "" || s.Step == in.Step) && (in.State == "" || s.Outcome == in.State) { held = append(held, s) } } - p.Steps = []seat.StepResult{} - a := seat.ShowAnswer{Pipeline: p, Fill: fills, Total: int64(len(held))} - size := sizeOf(a) + // The answer names only the movers its page holds: the named mover, or those whose steps the page holds (design 47 H2 H-A-709 (1)). + all := p.Movers + p.Steps, p.Movers, p.Unlogged = []seat.StepResult{}, []seat.Mover{}, nil + p.MoverCount, p.StepCount = int64(len(all)), int64(p0steps) + a := seat.ShowAnswer{Pipeline: p, Fill: fills, Total: int64(len(held)), Moved: in.Next != "" && cursorRev != rev} + size := sizeOf(a) + cappedReserve + named := map[string]bool{} for i := from; i < len(held); i++ { n := sizeOf(held[i]) + 1 - if size+n > MaxAnswer && len(a.Pipeline.Steps) > 0 { - a.Capped, a.Next = true, pageCursor(i) + if !named[held[i].Module] { // the mover the page's step belongs to is on the page too + named[held[i].Module] = true + for _, mv := range all { + if mv.Module == held[i].Module { + n += sizeOf(mv) + 1 + } + } + } + if size+n > bound && len(a.Pipeline.Steps) > 0 { + a.Capped, a.Next = true, pageCursor(i, rev) break } size += n a.Pipeline.Steps = append(a.Pipeline.Steps, held[i]) } + for _, mv := range all { + if mv.Module == m || slices.ContainsFunc(a.Pipeline.Steps, func(s seat.StepResult) bool { return s.Module == mv.Module }) { + a.Pipeline.Movers = append(a.Pipeline.Movers, mv) + } + } return a, nil } -// pageCursor is the opaque cursor of a page starting at the i-th step the filters hold (§779): the caller hands it back. -func pageCursor(i int) string { - return base64.RawURLEncoding.EncodeToString([]byte("step:" + strconv.Itoa(i))) +// pageCursor is the opaque cursor of a page starting at the i-th row or step the filters hold, in the record at revision rev +// (design 47 H2 §779, H-A-709 (2)): the caller hands it back. +func pageCursor(i int, rev uint64) string { + return base64.RawURLEncoding.EncodeToString([]byte("page:" + strconv.Itoa(i) + ":" + strconv.FormatUint(rev, 10))) } -// pageFrom is the step a cursor starts at, 0 for none; a cursor this reader did not give is refused. -func pageFrom(next string) (int, error) { +// errCursor refuses a cursor the runner cannot read as its own, saying that a page is read again from the start (H-A-717 DQ-57). +func errCursor(next string) error { + return fmt.Errorf("the cursor %q is not one this runner answered: a page is read again from the start, with no next", next) +} + +// pageFrom is the place a cursor starts at, 0 for none, and the revision of the record it was given at; a cursor this reader +// did not give is refused. +func pageFrom(next string) (int, uint64, error) { if next = strings.TrimSpace(next); next == "" { - return 0, nil + return 0, 0, nil } raw, err := base64.RawURLEncoding.DecodeString(next) if err == nil { - if n, ok := strings.CutPrefix(string(raw), "step:"); ok { - if i, err := strconv.Atoi(n); err == nil && i >= 0 { - return i, nil + if n, ok := strings.CutPrefix(string(raw), "page:"); ok { + at, rv, _ := strings.Cut(n, ":") + i, e1 := strconv.Atoi(at) + r, e2 := strconv.ParseUint(rv, 10, 64) + if e1 == nil && e2 == nil && i >= 0 { + return i, r, nil } } } - return 0, fmt.Errorf("the cursor %q is not one show answered", next) + return 0, 0, errCursor(next) } // sizeOf is v's size as JSON. @@ -223,7 +321,7 @@ func MoverRows(p seat.Pipeline) []seat.MoverRow { out := make([]seat.MoverRow, 0, len(p.Movers)) for _, m := range p.Movers { steps := stepsOf(p, m.Module) - row := seat.MoverRow{Module: m.Module, Outcome: seat.MoverRowOutcomePassed, Failed: firstFailed(steps)} + row := seat.MoverRow{Module: m.Module, Outcome: seat.MoverRowOutcomePassed, Failed: firstFailed(steps), Fingerprint: m.Fingerprint, Version: m.Version, Tier: m.Tier} running, failed := false, false for _, s := range steps { switch { @@ -309,13 +407,32 @@ func stepCounts(steps []seat.StepResult) map[string]int64 { } // Stands is every step that has started and not ended, with what it waits on and since when (§75, §83): the watchman -// seeds its open waits from it. -func (r Reads) Stands() (seat.StandsAnswer, error) { - all, err := r.pipelines() +// seeds its open waits from it. It answers the waits of the pipeline and the module it names, in the order of their since, +// then their pipeline, module, step and artifact, at most the bound's bytes with capped, the filters' total and a next that +// holds the last wait answered: the next page answers the waits after it, so a wait standing across both pages is answered +// once, one ended between them is gone, and one held since comes later (design 47 H2 H-A-709 (2)). +func (r Reads) Stands(in seat.StandsInput) (seat.StandsAnswer, error) { + bound, err := r.bound(in.Bound) if err != nil { return seat.StandsAnswer{}, err } - out := []seat.Wait{} + after, err := standsFrom(in.Next) + if err != nil { + return seat.StandsAnswer{}, err + } + var all []seat.Pipeline + if in.Pipeline != "" { + p, ok, err := r.pipeline(in.Pipeline) + if err != nil { + return seat.StandsAnswer{}, err + } + if ok { + all = []seat.Pipeline{p} + } + } else if all, err = r.pipelines(); err != nil { + return seat.StandsAnswer{}, err + } + var held []seat.Wait for _, p := range all { for _, s := range p.Steps { if s.Ended != nil || s.Started == nil { @@ -325,13 +442,63 @@ func (r Reads) Stands() (seat.StandsAnswer, error) { continue } m, _ := MoverOf(p, s.Module) - out = append(out, seat.Wait{Pipeline: p.Pipeline, Module: m.Module, Branch: p.Branch, Commit: m.Commit, + if in.Module != "" && m.Module != in.Module { + continue + } + w := seat.Wait{Pipeline: p.Pipeline, Module: m.Module, Branch: p.Branch, Commit: m.Commit, Run: p.Run, Source: p.Source, Revision: p.Revision, Fingerprint: m.Fingerprint, Step: s.Step, - Artifact: s.Artifact, On: s.On, Since: *s.Started, V: 1, Ask: askOfWait(s), Shared: sharedOfWait(s)}) + Artifact: s.Artifact, On: s.On, Since: *s.Started, V: 1, Ask: askOfWait(s), Shared: sharedOfWait(s)} + if s.On == seat.WaitOnRevisionView && s.HeldAt != nil { // the held step's wait is timed from its hold (H-A-599, H-A-738 (2)) + w.Bound, w.ClockFrom = boundOf(r.StalledBound), s.HeldAt + } + held = append(held, w) } } - sort.SliceStable(out, func(i, j int) bool { return out[i].Since.Before(out[j].Since) }) - return seat.StandsAnswer{Stands: out}, nil + sort.SliceStable(held, func(i, j int) bool { return waitLess(held[i], held[j]) }) + a := seat.StandsAnswer{Stands: []seat.Wait{}, Total: int64(len(held))} + size := sizeOf(a) + cappedReserve + for _, w := range held { + if after != nil && !waitLess(*after, w) { + continue + } + n := sizeOf(w) + 1 + if size+n > bound && len(a.Stands) > 0 { + a.Capped, a.Next = true, standsCursor(a.Stands[len(a.Stands)-1]) + break + } + size += n + a.Stands = append(a.Stands, w) + } + return a, nil +} + +// waitLess orders waits by their since, then their pipeline, module, step and artifact (design 47 H2 H-A-709 (2)). +func waitLess(a, b seat.Wait) bool { + if !a.Since.Equal(b.Since) { + return a.Since.Before(b.Since) + } + return strings.Join([]string{a.Pipeline, a.Module, a.Step, a.Artifact}, "\x00") < strings.Join([]string{b.Pipeline, b.Module, b.Step, b.Artifact}, "\x00") +} + +// standsCursor is the cursor after wait w: its place in the order, by the fields the order reads. +func standsCursor(w seat.Wait) string { + return base64.RawURLEncoding.EncodeToString([]byte(strings.Join([]string{"wait", strconv.FormatInt(w.Since.UnixNano(), 10), w.Pipeline, w.Module, w.Step, w.Artifact}, "\x00"))) +} + +// standsFrom is the wait a cursor follows, nil for none; one this reader did not give is refused. +func standsFrom(next string) (*seat.Wait, error) { + if next = strings.TrimSpace(next); next == "" { + return nil, nil + } + raw, err := base64.RawURLEncoding.DecodeString(next) + if err == nil { + if f := strings.Split(string(raw), "\x00"); len(f) == 6 && f[0] == "wait" { + if ns, err := strconv.ParseInt(f[1], 10, 64); err == nil { + return &seat.Wait{Since: time.Unix(0, ns), Pipeline: f[2], Module: f[3], Step: f[4], Artifact: f[5]}, nil + } + } + } + return nil, errCursor(next) } // WhyCarried is where a step's result was carried from (§25, §83): the pipeline it names. diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/read_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/read_test.go index 430eeb04d..40fd4ac01 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/read_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/read_test.go @@ -14,6 +14,14 @@ import ( type memKept map[string]json.RawMessage +// revKept is a memKept that tells every record's revision as the number rev points to (H-A-709 (2)). +type revKept struct { + memKept + rev *uint64 +} + +func (k revKept) Revision(string) (uint64, error) { return *k.rev, nil } + func (m memKept) Keys() ([]string, error) { var out []string for k := range m { @@ -46,7 +54,7 @@ func TestReads(t *testing.T) { {Module: "alpha", Step: seat.StepResultStepUnit, Artifact: "alpha:program", Status: "required", Outcome: seat.StepResultOutcomeCarried, CarriedFrom: "main.6.alpha"}, {Module: "alpha", Step: seat.StepResultStepApproval, Status: "required", Outcome: seat.StepResultOutcomeWaiting, On: seat.WaitOnPerson, - Started: &t1}}, Movers: []seat.Mover{{Module: "alpha", Commit: "c7"}}}) + Started: &t1}}, Movers: []seat.Mover{{Module: "alpha", Commit: "c7", Tier: 2}}}) put(t, pipes, "beta.3.alpha", seat.Pipeline{Pipeline: "beta.3.alpha", Branch: "beta", Outcome: seat.PipelineOutcomePassed, Started: &t2, Movers: []seat.Mover{{Module: "alpha", Commit: "b3"}}}) put(t, pipes, "main.7.gamma", seat.Pipeline{Pipeline: "main.7.gamma", Branch: "main", @@ -90,8 +98,10 @@ func TestReads(t *testing.T) { // Design 47 H2 H-A-376: naming no mover, show answers each mover's row and never its steps. {"show naming no mover answers each mover's row", func() (string, error) { a, err := r.Show(seat.ShowInput{Pipeline: "main.7.alpha"}) - return fmt.Sprint(a.Pipeline.Movers[0].Module, " ", len(a.Pipeline.Steps), " ", a.Movers, " ", a.Total), err - }, "alpha 0 [{ alpha running}] 1"}, + // design 47 H2 H-A-709 (1): the answer's pipeline names no mover of its own, the rows do, each with its fingerprint, version and + // tier; mover-count and step-count count the record's + return fmt.Sprint(len(a.Pipeline.Movers), " ", len(a.Pipeline.Steps), " ", a.Movers, " ", a.Total, " ", a.Pipeline.MoverCount, " ", a.Pipeline.StepCount), err + }, "0 0 [{ alpha running 2 }] 1 1 3"}, {"show's row of a mover names its first failed step", func() (string, error) { a, err := r.Show(seat.ShowInput{Pipeline: "gone.2"}) return fmt.Sprint(a.Movers[0].Outcome, " ", *a.Movers[0].Failed), err @@ -124,7 +134,7 @@ func TestReads(t *testing.T) { s = append(s, st.Module+" "+st.Step) } return fmt.Sprintf("%s, %d movers", strings.Join(s, ", "), len(a.Pipeline.Movers)), err - }, "epsilon build, 2 movers"}, + }, "epsilon build, 1 movers"}, {"show refuses a mover the pipeline does not move", func() (string, error) { _, err := r.Show(seat.ShowInput{Pipeline: "next.8", Mover: "alpha"}) return "", err @@ -186,7 +196,7 @@ func TestReads(t *testing.T) { return fmt.Sprint(len(a.Rows), " ", a.Rows[0].Pipeline, " ", a.Rows[19].Pipeline), err }, "20 main.24 main.5"}, {"stands names a waiting step and since when", func() (string, error) { - a, err := r.Stands() + a, err := r.Stands(seat.StandsInput{}) var s []string for _, w := range a.Stands { s = append(s, w.Pipeline+" "+w.Step+" "+w.On+" "+w.Since.Format("15:04")) @@ -274,7 +284,7 @@ func TestStandsAndStepStartedNameWhatAReadingStepWaitsOn(t *testing.T) { } pipes := memKept{} put(t, pipes, p.Pipeline, f.pipeline(p)) - a, err := Reads{Pipelines: pipes, Kept: memKept{}}.Stands() + a, err := Reads{Pipelines: pipes, Kept: memKept{}}.Stands(seat.StandsInput{}) if err != nil { t.Fatal(err) } @@ -302,6 +312,34 @@ func TestStandsAndStepStartedNameWhatAReadingStepWaitsOn(t *testing.T) { if len(f.said) == n { t.Error("resume said no step-started") } + // Design 47 H2 H-A-599, H-A-738 (2): a held step stands with the runner's stalled-bound and the time it was held, so the watchman's + // seed from stands times it as the wait-held did, also after a restart. + t.Run("TestStandsNamesTheBoundAndClockOfAHeldStep", func(t *testing.T) { + f := newRunFixture() + p := f.start(t, 4, 9) + held := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + pl := f.pipeline(p) + for i := range pl.Steps { + if pl.Steps[i].Step == "unit" && pl.Steps[i].Artifact == "app:program" { + pl.Steps[i].Outcome, pl.Steps[i].On, pl.Steps[i].Revision, pl.Steps[i].HeldAt = seat.StepResultOutcomeWaiting, seat.WaitOnRevisionView, 12, &held + } + } + pipes := memKept{} + put(t, pipes, p.Pipeline, pl) + a, err := Reads{Pipelines: pipes, Kept: memKept{}, StalledBound: time.Minute}.Stands(seat.StandsInput{}) + if err != nil { + t.Fatal(err) + } + for _, w := range a.Stands { + if w.Artifact == "app:program" && w.Step == "unit" { + if w.Bound != "1m0s" || w.ClockFrom == nil || !w.ClockFrom.Equal(held) { + t.Errorf("the held step stands with bound %q and clock-from %v, want 1m0s and %v", w.Bound, w.ClockFrom, held) + } + return + } + } + t.Error("the held step does not stand") + }) } // TestAPipelineIsReadInParts holds show and runner_movers to design 47 H2 §789: one mover's steps of a record of 129 movers @@ -336,15 +374,22 @@ func TestAPipelineIsReadInParts(t *testing.T) { if raw, _ := json.Marshal(a); err != nil || len(raw) >= 64<<10 || len(a.Pipeline.Steps) != 6 || a.Total != 6 || a.Capped { t.Fatalf("one mover of 129: %d bytes, %d steps, total %d, capped %v, %v", len(raw), len(a.Pipeline.Steps), a.Total, a.Capped, err) } + if len(a.Pipeline.Movers) != 1 || a.Pipeline.Movers[0].Module != "module-0042" || a.Pipeline.MoverCount != 129 || a.Pipeline.StepCount != 129*6 { + t.Fatalf("one mover named: the answer's movers %d, counts %d and %d; want that mover alone and the record's counts", len(a.Pipeline.Movers), a.Pipeline.MoverCount, a.Pipeline.StepCount) + } a, err = r.Show(seat.ShowInput{Pipeline: "main.9", Step: seat.StepResultStepUnit, State: seat.StepResultOutcomeFailed}) if err != nil || a.Total != 13 || len(a.Pipeline.Steps) != 13 || a.Pipeline.Steps[0].Module != "module-0003" { t.Fatalf("the failed unit steps: total %d, %d steps, %v", a.Total, len(a.Pipeline.Steps), err) } + // H2 H-A-709 (1): with step and state the movers are those whose steps the page holds, 13 of 129 + if len(a.Pipeline.Movers) != 13 || a.Pipeline.Movers[0].Module != "module-0003" { + t.Fatalf("the filters' answer names %d movers, want the 13 whose steps the page holds", len(a.Pipeline.Movers)) + } // The steps a filter holds are larger than one answer: they are read in pages, each under 768 KB, every step once. big := Reads{Pipelines: record(1000), Kept: memKept{}} seen, pages, next := 0, 0, "" for { - a, err := big.Show(seat.ShowInput{Pipeline: "main.9", State: seat.StepResultOutcomePassed, Next: next}) + a, err := big.Show(seat.ShowInput{Pipeline: "main.9", State: seat.StepResultOutcomePassed, Next: next, Bound: MaxAnswer}) raw, _ := json.Marshal(a) if err != nil || len(raw) > MaxAnswer || a.Total != 5900 { t.Fatalf("page %d: %d bytes, total %d, %v", pages, len(raw), a.Total, err) @@ -359,13 +404,72 @@ func TestAPipelineIsReadInParts(t *testing.T) { t.Fatalf("pages %d read %d steps, want every one of 5900 over more than one page", pages, seen) } // Design 47 H2 H-A-376: naming no mover and no filter, show answers 1,000 movers' rows in one answer and no step. - if a, err := big.Show(seat.ShowInput{Pipeline: "main.9"}); err != nil || len(a.Movers) != 1000 || len(a.Pipeline.Steps) != 0 || a.Capped || + if a, err := big.Show(seat.ShowInput{Pipeline: "main.9", Bound: MaxAnswer}); err != nil || len(a.Movers) != 1000 || len(a.Pipeline.Steps) != 0 || a.Capped || a.Movers[3].Outcome != seat.MoverRowOutcomeFailed || a.Movers[3].Failed == nil || a.Movers[3].Failed.Step != seat.StepResultStepUnit { t.Fatalf("the movers' rows: %d rows, %d steps, capped %v, %v", len(a.Movers), len(a.Pipeline.Steps), a.Capped, err) } if _, err := big.Show(seat.ShowInput{Pipeline: "main.9", Next: "not-a-cursor"}); err == nil { t.Fatal("a cursor show never answered is refused") } + // design 47 H2 H-A-709 (2), H-A-717 (DQ-57) (AC-P10): a call naming no bound is answered at the setting's 32,768 bytes and + // capped with a next that reads the rest; a bound outside 4,096 to 786,432 and a cursor of no page are refused. + def, err := big.Show(seat.ShowInput{Pipeline: "main.9", State: seat.StepResultOutcomePassed}) + if raw, _ := json.Marshal(def); err != nil || !def.Capped || def.Next == "" || len(raw) > DefaultAnswerBound || def.Moved { + t.Errorf("show at the default bound: %d bytes, capped %v, next %q, moved %v, %v", len(raw), def.Capped, def.Next, def.Moved, err) + } + if few, _ := (Reads{Pipelines: record(1000), Kept: memKept{}, AnswerBound: 8192}).Show(seat.ShowInput{Pipeline: "main.9", State: seat.StepResultOutcomePassed}); len(few.Pipeline.Steps) >= len(def.Pipeline.Steps) { + t.Errorf("the setting 8192 answered %d steps, want fewer than the default's %d", len(few.Pipeline.Steps), len(def.Pipeline.Steps)) + } + for _, in := range []seat.ShowInput{{Pipeline: "main.9", Bound: 100}, {Pipeline: "main.9", Bound: MaxAnswer + 1}, {Pipeline: "main.9", Next: "step:3"}} { + if _, err := big.Show(in); err == nil || (in.Next != "" && !strings.Contains(err.Error(), "read again from the start")) { + t.Errorf("show %+v = %v, want refused", in, err) + } + } + // A record written between two pages: the second answers from the place and says moved. + rev := uint64(3) + moving := Reads{Pipelines: revKept{record(129), &rev}, Kept: memKept{}} + first, _ := moving.Show(seat.ShowInput{Pipeline: "main.9", Step: seat.StepResultStepUnit, Bound: MinAnswer}) + same, _ := moving.Show(seat.ShowInput{Pipeline: "main.9", Step: seat.StepResultStepUnit, Bound: MinAnswer, Next: first.Next}) + rev = 4 + later, _ := moving.Show(seat.ShowInput{Pipeline: "main.9", Step: seat.StepResultStepUnit, Bound: MinAnswer, Next: first.Next}) + if !first.Capped || first.Moved || same.Moved || !later.Moved || len(later.Pipeline.Steps) == 0 || later.Pipeline.Steps[0].Module != same.Pipeline.Steps[0].Module { + t.Errorf("pages: first capped %v moved %v, same revision moved %v, a record written between: moved %v", first.Capped, first.Moved, same.Moved, later.Moved) + } + // stands pages its waits in the order of their since, each once, by pipeline and module when it names them. + waits := memKept{} + for _, key := range []string{"main.9", "main.10"} { + wp := seat.Pipeline{Pipeline: key, Branch: "main", Source: 9, Outcome: seat.PipelineOutcomeRunning, Started: &t0} + for i := 0; i < 40; i++ { + at := t0.Add(time.Duration(i) * time.Minute) + m := fmt.Sprintf("module-%02d", i) + wp.Movers = append(wp.Movers, seat.Mover{Module: m}) + wp.Steps = append(wp.Steps, seat.StepResult{Module: m, Step: seat.StepResultStepApproval, Artifact: m + ":program", Outcome: seat.StepResultOutcomeWaiting, Started: &at, On: seat.WaitOnPerson}) + } + put(t, waits, key, wp) + } + var standing []string + for next, pages := "", 0; ; pages++ { + a, err := (Reads{Pipelines: waits, Kept: memKept{}}).Stands(seat.StandsInput{Bound: MinAnswer, Next: next}) + if err != nil || a.Total != 80 || (a.Capped && a.Next == "") || pages > 80 { + t.Fatalf("stands page %d: total %d, capped %v, %v", pages, a.Total, a.Capped, err) + } + if raw, _ := json.Marshal(a); len(raw) > MinAnswer { + t.Errorf("a stands page of %d bytes at bound %d", len(raw), MinAnswer) + } + for _, w := range a.Stands { + standing = append(standing, w.Pipeline+" "+w.Module) + } + if !a.Capped { + break + } + next = a.Next + } + if len(standing) != 80 || standing[0] != "main.10 module-00" || standing[1] != "main.9 module-00" { + t.Errorf("stands pages answered %d waits, the first %v, want 80 in the order of since, then pipeline", len(standing), standing[:2]) + } + if a, err := (Reads{Pipelines: waits, Kept: memKept{}}).Stands(seat.StandsInput{Pipeline: "main.9", Module: "module-07"}); err != nil || len(a.Stands) != 1 || a.Total != 1 || a.Capped { + t.Errorf("stands of one pipeline and module = %+v (%v), want its one wait", a, err) + } m, err := big.Movers("main.9") raw, _ := json.Marshal(m) if err != nil || len(raw) >= MaxAnswer || len(m.Movers) != 1000 { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/registrations.go b/modules/mesh-delivery-pipeline/internal/pipeline/registrations.go index 1f0cc57ab..b2233cc37 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/registrations.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/registrations.go @@ -98,7 +98,9 @@ type readyView interface{ Ready() <-chan struct{} } type Half struct { Revision int64 Source int64 - Entries map[string]catalog.CatalogEntry + // Base is the revision's base, the newest kept revision of its branch below it (H-A-151); 0 on the branch's first take-in. + Base int64 + Entries map[string]catalog.CatalogEntry // Call and Movers are the revision's own, as the revision verb answers them (H-A-213): what made it and its movers; // a view's half names none. Call string diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/repin_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/repin_test.go index 3ac122550..5938011b7 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/repin_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/repin_test.go @@ -290,7 +290,7 @@ func TestAKeptMoverWaitingOnItsRevisionSaysSo(t *testing.T) { said++ } } - shown, err := Reads{Pipelines: rawKept{store.Raw.(*memRaw)}, Kept: memKept{}}.Show(seat.ShowInput{Pipeline: key}) + shown, err := Reads{Pipelines: rawKept{store.Raw.(*memRaw)}, Kept: memKept{}}.Show(seat.ShowInput{Pipeline: key, Mover: "app"}) // the mover named: the answer holds that mover alone (H-A-709 (1)) if err != nil || said != 1 || shown.Pipeline.Movers[0].Unplaced != seat.MoverUnplacedKeptRevisionUnread || shown.Pipeline.Movers[0].Revision != 11 { t.Fatalf("said %d times, show %+v (%v)", said, shown.Pipeline.Movers, err) } diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/start.go b/modules/mesh-delivery-pipeline/internal/pipeline/start.go index e2429dd7d..ba2795075 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/start.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/start.go @@ -446,8 +446,14 @@ func (s *Starter) create(key string, p seat.Pipeline) error { // started is a pipeline's pipeline-started (§746): its key, branch, source, call, revision and movers, and kept, every // catalog revision its movers are kept at (design 47 H2 H-A-496), so the indexer pins each while the pipeline runs. func started(p seat.Pipeline, at time.Time, kept []int64) seat.PipelineStarted { + // Each mover carries what the readers of pipeline-started read, and no more (design 47 H2 H-A-709 (3)): published, widens, tests, + // unplaced, revision and over-budget stay in the pipeline's record, read by show. + movers := make([]seat.StartedMover, 0, len(p.Movers)) + for _, m := range p.Movers { + movers = append(movers, seat.StartedMover{Module: m.Module, Commit: m.Commit, Fingerprint: m.Fingerprint, Repository: m.Repository, Tier: m.Tier, Version: m.Version}) + } return seat.PipelineStarted{V: 1, At: &at, Pipeline: p.Pipeline, Branch: p.Branch, Source: p.Source, Call: p.Call, - Revision: p.Revision, Movers: p.Movers, Published: p.Published, Run: p.Run, Kept: kept} + Revision: p.Revision, Movers: movers, Published: p.Published, Run: p.Run, Kept: kept} } // keptList is every distinct revision of kept-revisions, in order (H-A-496). @@ -1152,12 +1158,27 @@ func (s *Starter) TakenIn(ev catalog.TakeInTaken, view func(branch string) (Half s.logf("the take-in of %s source %d names no entries: it starts no pipeline", ev.Branch, ev.Source) return 0, nil } + // A take-in whose pipeline key is held already by a pipeline that waits or runs adds its entries to it as movers, one + // mover-added each with the take-in (H-A-594 (1), H-A-609 (3)). + if held && s.Store != nil && ev.Revision > 0 { + key := Key(ev.Branch, ev.Revision) + if cur, _, gerr := s.Store.Get(key); gerr == nil && openPipeline(cur) { + var entries []seat.Mover + for _, m := range movers { + entries = append(entries, m) + } + names, err := s.AddMovers(key, entries, half.Entries, AddedFrom{TakeIn: ev.Source}, view) + s.markCarried(ev.Branch, names, key) + return 0, err + } + } movers = Tiers(movers, half.Entries, s.logf) ok, err := s.Start(Begin{Branch: ev.Branch, Source: ev.Source, Call: ev.Call, Revision: ev.Revision, Movers: movers, Entries: half.Entries, unheld: !held}) started := 0 if ok { started = 1 + s.markCarried(ev.Branch, moduleNames(movers), Key(ev.Branch, keyRevision(Begin{Revision: ev.Revision, Source: ev.Source}))) } // The view was read before the start wrote: when the pipeline was held back for it and it has reached the revision since, // it is placed now, not left for an advance that already came (A-448, §200). @@ -1226,6 +1247,24 @@ func (s *Starter) heardPublished(ev builds.PackagePublished, view func(branch st if !ok { return seat.Pipeline{}, false, nil } + p, held, err := s.markPublished(key, ev, view) + if !held { + return p, false, err + } + // The same publish reaches every other running pipeline of the branch that moves the publishing module at the fingerprint it + // names, so a pipeline sharing the build releases its waiting movers too (design 47 H2 H-A-707 (6)). + if ev.Fingerprint != "" { + if serr := s.markSharing(ev, key, view); serr != nil { + s.logf("a package-published of %s at %s did not reach every pipeline sharing the build: %v", ev.Artifact, ev.Fingerprint, serr) + err = errors.Join(err, serr) + } + } + return p, true, err +} + +// markPublished writes ev into the publishing mover's published of the running pipeline key and releases the movers that waited for +// it; it answers that pipeline, read, and whether one is held. +func (s *Starter) markPublished(key string, ev builds.PackagePublished, view func(branch string) (Half, bool)) (seat.Pipeline, bool, error) { for { p, rev, err := s.Store.Get(key) if err != nil { @@ -1249,6 +1288,32 @@ func (s *Starter) heardPublished(ev builds.PackagePublished, view func(branch st } } +// markSharing marks ev in every running pipeline of its branch, but except, whose mover of the publishing module is at the +// fingerprint the publish names (design 47 H2 H-A-707 (6)). +func (s *Starter) markSharing(ev builds.PackagePublished, except string, view func(branch string) (Half, bool)) error { + pkeys, err := s.Store.Keys(keys.EscapeName(ev.Branch) + ".*") + if err != nil { + return fmt.Errorf("the pipelines of %s are not listed: %w", ev.Branch, err) + } + var errs []error + for _, k := range pkeys { + if k == except { + continue + } + p, _, err := s.Store.Get(k) + if err != nil || p.Branch != ev.Branch || p.Run != "" || p.Outcome != seat.PipelineOutcomeRunning { + continue + } + if i := slices.IndexFunc(p.Movers, func(m seat.Mover) bool { return m.Module == ev.Module }); i < 0 || p.Movers[i].Fingerprint != ev.Fingerprint { + continue + } + if _, _, err := s.markPublished(k, ev, view); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + // sourcePipeline is the key of branch's pipeline of the lowest-numbered revision of source, the take-in's (H-A-213 (4), // H-A-218): a pipeline is keyed by its revision, so one of a source is found by the source it names, never by its key. func (s *Starter) sourcePipeline(branch string, source int64) (string, bool) { @@ -1337,3 +1402,10 @@ func (s *Starter) Revised(ev catalog.CatalogRevisionEvent, read func(branch stri } return 0, err } + +// markCarried names the pipeline key as the carrier of the unfinished keys of modules it carries (H-A-594 (4)). +func (s *Starter) markCarried(branch string, modules []string, key string) { + if s.Unfinished != nil { + s.Unfinished.markCarried(branch, modules, key) + } +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go index 8746e391b..49232dffa 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/start_test.go @@ -1,6 +1,7 @@ package pipeline import ( + "bytes" "encoding/json" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "slices" "strings" "testing" + "time" 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" @@ -30,7 +32,13 @@ func (c created) Create(key string, value []byte) error { // refused. func TestStarts(t *testing.T) { store := created{} - s := &Starter{Pipelines: store, Say: func(string, any) error { return nil }} + var said []seat.PipelineStarted + s := &Starter{Pipelines: store, Say: func(_ string, body any) error { + if ev, ok := body.(seat.PipelineStarted); ok { + said = append(said, ev) + } + return nil + }} key := Key("main", 41) if ok, err := s.Start(Begin{Branch: "main", Source: 41, Movers: []seat.Mover{{Module: "app", Commit: "c1"}}}); !ok || err != nil { t.Fatalf("start = %v, %v", ok, err) @@ -51,6 +59,20 @@ func TestStarts(t *testing.T) { if _, err := s.Start(Begin{Branch: "main", Source: 6}); err == nil { t.Error("a start with no mover is refused") } + // H2 H-A-709 (3): pipeline-started of 100 movers carries StartedMover's fields alone and stays under 32 KB + many := make([]seat.Mover, 100) + for i := range many { + many[i] = seat.Mover{Module: fmt.Sprintf("module-%03d", i), Commit: strings.Repeat("c", 40), Fingerprint: "src2:" + strings.Repeat("f", 64), Repository: "novox/mesh-delivery", Tier: 3, + Published: []string{"module:artifact", "module:other"}, Widens: []seat.Widening{{}}, OverBudget: true, Unplaced: seat.MoverUnplacedKeptRevisionUnread, Revision: 9} + } + said = nil + if _, err := s.Start(Begin{Branch: "main", Source: 44, Movers: many}); err != nil || len(said) != 1 { + t.Fatalf("100 movers started %d events (%v)", len(said), err) + } + raw, _ := json.Marshal(said[0]) + if len(said[0].Movers) != 100 || len(raw) > 32*1024 || bytes.Contains(raw, []byte("over-budget")) || bytes.Contains(raw, []byte("widens")) || bytes.Contains(raw, []byte("unplaced")) || bytes.Contains(raw, []byte(`"published":["`)) { + t.Errorf("pipeline-started of 100 movers is %d bytes: %.200s; want 100 StartedMovers under 32 KB without published, widens, unplaced or over-budget", len(raw), raw) + } s.Pipelines = failing{} if _, err := s.Start(Begin{Branch: "main", Source: 5, Movers: []seat.Mover{{Module: "app"}}}); err == nil { t.Error("a write the bus refuses is an error") @@ -449,33 +471,69 @@ func TestTakenInStartsOnlyItsEntries(t *testing.T) { if p, _, _ := mem.Get("main.13"); len(p.Movers) != 2 || !Moves(p, "moved") || !Moves(p, "batched") { t.Errorf("main.13 moves %+v, want moved and the unfinished batched", p.Movers) } - if u.String() != `dev.batched={"fingerprint":"src2:bb"} main.batched={"fingerprint":"src2:bb","revision":11}` { + if u.String() != `dev.batched={"fingerprint":"src2:bb"} main.batched={"fingerprint":"src2:bb","revision":11,"pipeline":"","outcome":"","carried-by":"main.13"}` { t.Errorf("the state unfinished = %s, want main.moved (moved at src2:aa) and main.gone (no entry) gone", u.String()) } if !strings.Contains(strings.Join(journal, "\n"), "revision 13 of main puts batched in a pipeline again") { t.Errorf("the journal says %q, want batched put in a pipeline again", journal) } half.Revision = 14 + // The key's carrier main.13 runs: the carry skips it (H-A-594 (4)); once the carrier ends otherwise, it names no carrier. + if n, err := s.TakenIn(catalog.TakeInTaken{Branch: "main", Source: 11, Revision: 14}, view); err != nil || n != 0 { + t.Fatalf("a take-in moving nothing started %d (%v) while the carrier runs, want none", n, err) + } + u["main.batched"] = `{"fingerprint":"src2:bb","revision":11}` if n, err := s.TakenIn(catalog.TakeInTaken{Branch: "main", Source: 11, Revision: 14}, view); err != nil || n != 1 { t.Fatalf("a take-in moving nothing started %d (%v), want one pipeline for the unfinished", n, err) } if p, _, _ := mem.Get("main.14"); len(p.Movers) != 1 || !Moves(p, "batched") { t.Errorf("main.14 moves %+v, want batched alone", p.Movers) } - half.Revision = 11 + delete(u, "dev.batched") acts := &actLog{} - v := Verbs{Starter: s, View: view, Acts: acts} - if a, err := v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{Key: "main.batched", Why: "now"}); err != nil || a.Pipeline != "main.11.unfinished.batched" || len(*acts) != 1 { - t.Errorf("place-unfinished = %+v (%v), %d hand acts", a, err, len(*acts)) - } - if p, _, _ := mem.Get("main.11.unfinished.batched"); len(p.Movers) != 1 || !Moves(p, "batched") { - t.Errorf("main.11.unfinished.batched moves %+v, want batched", p.Movers) - } - for _, in := range []seat.PlaceUnfinishedInput{{Key: "main.batched", Why: "again"}, {Key: "main.none", Why: "x"}, {Key: "dev.batched"}} { + v := Verbs{Starter: s, View: view, Acts: acts, Hearer: &Hearer{Store: mem}} + // design 47 H2 H-A-607 (3), H-A-644, H-A-725: a key a pipeline that runs carries is refused, and `all` over it answers two empty lists + // and says so; exactly one of key and all is given. + for _, in := range []seat.PlaceUnfinishedInput{{Key: "main.batched", Why: "now"}, {Why: "x"}, {Key: "main.batched", All: true, Why: "x"}, {Key: "main.none", Why: "x"}} { if _, err := v.PlaceUnfinished("agent.dev", in); err == nil { t.Errorf("place-unfinished %+v is refused", in) } } + if a, err := v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{All: true, Why: "now"}); err != nil || a.Said == "" || len(a.Placed) != 0 || len(a.Failed) != 0 || len(*acts) != 0 { + t.Errorf("place-unfinished all over a carried key = %+v (%v), %d hand acts", a, err, len(*acts)) + } + // The carrier ended failed, leaving batched: `all` reopens it for the group and answers it placed; a key whose entry holds + // another fingerprint is answered failed with its words, and the other is placed. + end := time.Unix(5, 0) + 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":14,"pipeline":"main.14","outcome":"failed"}` + u["main.odd"] = `{"fingerprint":"src2:zz","revision":14,"pipeline":"main.14","outcome":"failed"}` + half.Revision = 14 + a, err := v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{All: true, Why: "now"}) + if err != nil || len(a.Placed) != 1 || a.Placed[0] != (seat.PlaceUnfinishedAnswerPlacedItem{Key: "main.batched", Pipeline: "main.14"}) || + len(a.Failed) != 1 || a.Failed[0].Key != "main.odd" || a.Failed[0].Words == "" || len(*acts) != 1 || !strings.Contains((*acts)[0], "main.odd") { + t.Errorf("place-unfinished all = %+v (%v), hand acts %v", a, err, *acts) + } + if p, _, _ := mem.Get("main.14"); p.Outcome != seat.PipelineOutcomeRunning || p.Ended != nil || !strings.Contains(u["main.batched"], `"carried-by":"main.14"`) { + t.Errorf("main.14 is %s ended %v, batched = %s: want reopened and carried by it", p.Outcome, p.Ended, u["main.batched"]) + } + // H-A-750 (3): a key whose pipeline ended cancelled reopens it as a failed one is. + c, rev, _ = mem.Get("main.14") + c.Outcome, c.Ended = seat.PipelineOutcomeCancelled, &end + if _, err := mem.Update("main.14", c, rev); err != nil { + t.Fatal(err) + } + u["main.batched"] = `{"fingerprint":"src2:bb","revision":14,"pipeline":"main.14","outcome":"cancelled"}` + if a, err = v.PlaceUnfinished("agent.dev", seat.PlaceUnfinishedInput{Key: "main.batched", Why: "again"}); err != nil || len(a.Placed) != 1 { + t.Fatalf("place-unfinished of a key of a cancelled pipeline = %+v (%v), want it placed", a, err) + } + 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) + } } // 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 @@ -496,12 +554,16 @@ func testATakeInOfTheOldFormIsRefused(t *testing.T) { // older builder) into its source's lowest-numbered revision, the take-in's. func TestAPublishIsTakenIntoThePipelineOfItsRevision(t *testing.T) { mem := memStore{} - for _, r := range []int64{7, 8} { + for _, r := range []int64{7, 8, 9} { + fp := "src2:a" // the pipelines of revisions 7 and 8 move mesh-sdk at one fingerprint, revision 9's at another (H-A-707 (6)) + if r == 9 { + fp = "src2:b" + } mem[Key("main", r)] = struct { p seat.Pipeline rev uint64 }{seat.Pipeline{Pipeline: Key("main", r), Branch: "main", Source: 4, Revision: r, Outcome: seat.PipelineOutcomeRunning, - Movers: []seat.Mover{{Module: "mesh-sdk"}}}, 1} + Movers: []seat.Mover{{Module: "mesh-sdk", Fingerprint: fp}}}, 1} } s := &Starter{Pipelines: memCreated{mem}, Store: mem, Say: func(string, any) error { return nil }} view := func(string) (Half, bool) { return Half{Revision: 8}, true } @@ -514,6 +576,112 @@ func TestAPublishIsTakenIntoThePipelineOfItsRevision(t *testing.T) { if err := s.Published(ev, view); err != nil || len(published("main.7")) != 1 || len(published("main.8")) != 1 { t.Errorf("a publish naming no revision (%v): main.7 %v, main.8 %v; want main.7's, the source's lowest", err, published("main.7"), published("main.8")) } + // H2 H-A-707 (6): a publish naming the fingerprint reaches every running pipeline of the branch that moves the module at it + ev = builds.PackagePublished{Artifact: "mesh-sdk:py", Module: "mesh-sdk", Branch: "main", Source: 4, Revision: 8, Version: "0.1.18", Fingerprint: "src2:a"} + if err := s.Published(ev, view); err != nil || len(published("main.8")) != 2 || len(published("main.7")) != 2 || len(published("main.9")) != 0 { + t.Errorf("a publish at src2:a (%v): main.8 %v, main.7 %v, main.9 %v; want both pipelines moving it marked and revision 9's not", err, published("main.8"), published("main.7"), published("main.9")) + } + // design 47 H2 H-A-594 (3), (4), H-A-607 (2), H-A-609 (3): a group left joins the head's pipeline when that waits or runs, said by + // mover-added with from, its key naming the carrier and leaving the failed pipeline's movers; a take-in whose key is held adds + // its entries, one mover-added each with take-in; a carrier that ends otherwise leaves its key naming that pipeline. + t.Run("TestAClosedGroupJoinsTheHeadPipelineAndIsSaid", func(t *testing.T) { + mem := memStore{} + failed := seat.Pipeline{Pipeline: "main.5", Branch: "main", Revision: 5, Outcome: seat.PipelineOutcomeFailed, + Movers: []seat.Mover{{Module: "engine", Fingerprint: "f1"}, {Module: "gitea", Fingerprint: "f2"}, {Module: "free", Fingerprint: "f3"}}, + Steps: []seat.StepResult{{Module: "engine", Step: seat.StepResultStepUnit, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeFailed}, + {Module: "gitea", Step: seat.StepResultStepUnit, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeNotAsked}, + {Module: "free", Step: seat.StepResultStepUnit, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeNotAsked}}} + head := seat.Pipeline{Pipeline: "main.6", Branch: "main", Revision: 6, Outcome: seat.PipelineOutcomeRunning, Movers: []seat.Mover{{Module: "other", Fingerprint: "f9"}}} + mem["main.5"] = struct { + p seat.Pipeline + rev uint64 + }{failed, 1} + mem["main.6"] = struct { + p seat.Pipeline + rev uint64 + }{head, 1} + entries := map[string]catalog.CatalogEntry{} + edgeInto(entries, "gitea", "engine", 1) + type said struct { + subject string + ev seat.MoverAdded + } + var out []said + s := &Starter{Store: mem, Say: func(subject string, body any) error { + if ev, ok := body.(seat.MoverAdded); ok { + out = append(out, said{subject, ev}) + } + return nil + }} + st := memUnfinished{} + 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) + }} + 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") { + t.Fatalf("mover-added = %+v, want free added to main.6 from main.5 alone: gitea is tied to engine", out) + } + if p, _, _ := mem.Get("main.6"); !Moves(p, "free") || !Moves(p, "other") { + t.Errorf("main.6 moves %+v, want other and free", p.Movers) + } + if p, _, _ := mem.Get("main.5"); Moves(p, "free") || !Moves(p, "gitea") { + t.Errorf("main.5 moves %+v, want free gone and the tied gitea kept", p.Movers) + } + var e UnfinishedEntry + _ = json.Unmarshal([]byte(st["main.free"]), &e) + if e.CarriedBy != "main.6" { + t.Errorf("free's key = %s, want carried by main.6", st["main.free"]) + } + // The carrier ends failed: the key stays, naming that pipeline, with no carrier. + ended := seat.Pipeline{Pipeline: "main.6", Branch: "main", Revision: 6, Outcome: seat.PipelineOutcomeFailed, + Movers: []seat.Mover{{Module: "free", Fingerprint: "f3"}}, + Steps: []seat.StepResult{{Module: "free", Step: seat.StepResultStepUnit, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomeFailed}}} + u.Ended(ended) + e = UnfinishedEntry{} + _ = json.Unmarshal([]byte(st["main.free"]), &e) + if e.CarriedBy != "" || e.Pipeline != "main.6" { + t.Errorf("free's key = %s, want pipeline main.6 and no carrier", st["main.free"]) + } + // A take-in whose key is held adds its entries, one mover-added each, with take-in. + out = nil + half := Half{Revision: 6, Source: 9, Entries: map[string]catalog.CatalogEntry{"late": {Commit: "c", Fp: "f7"}}} + s.Unfinished = u + n, err := s.TakenIn(catalog.TakeInTaken{Branch: "main", Source: 9, Revision: 6, Entries: []catalog.TakeInEntry{{Module: "late", Commit: "c", Fingerprint: "f7"}}}, + func(string) (Half, bool) { return half, true }) + if err != nil || n != 0 || len(out) != 1 || out[0].ev.TakeIn != 9 || out[0].ev.From != "" || out[0].ev.Module != "late" { + t.Errorf("a take-in of a held key = %d (%v), said %+v, want late added with take-in 9", n, err, out) + } + // design 47 H2 H-A-594 (2), H-A-646 (AC-P3b): a mover awaiting a failed one's package (kind 1) or build step (kind 3), directly or + // through another, is tied; one with only a tier edge is not; the tied group is closed under the tier kinds. + t.Run("TestTiedMoversAreThoseAwaitingAFailedOne", func(t *testing.T) { + p := seat.Pipeline{Pipeline: "main.5", Branch: "main", Outcome: seat.PipelineOutcomeFailed} + for _, m := range []string{"engine", "gitea", "far", "tieronly", "mate", "free"} { + p.Movers = append(p.Movers, seat.Mover{Module: m}) + } + entries := map[string]catalog.CatalogEntry{} + edgeInto(entries, "gitea", "engine", 1) // kind 1: awaits engine's package + edgeInto(entries, "far", "gitea", 3) // kind 3 through gitea + edgeInto(entries, "tieronly", "engine", 2) // delivery order only + edgeInto(entries, "mate", "far", 4) // tier edge to a tied mover: the group goes together + tied := tiedTo(p, []string{"gitea", "far", "tieronly", "mate", "free"}, []string{"engine"}, entries) + for _, m := range []string{"gitea", "far", "mate"} { + if !slices.Equal(tied[m], []string{"engine"}) { + t.Errorf("%s is tied to %v, want engine", m, tied[m]) + } + } + for _, m := range []string{"tieronly", "free"} { + if len(tied[m]) != 0 { + t.Errorf("%s is tied to %v, want none", m, tied[m]) + } + } + groups := tierGroups([]string{"tieronly", "free"}, entries) + if len(groups) != 2 { + t.Errorf("groups = %v, want each alone", groups) + } + }) + }) } // racingStore is memStore whose first Update is preceded by before, a write another part makes between a read and its write. diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/steps.go b/modules/mesh-delivery-pipeline/internal/pipeline/steps.go index ec3d1201d..99e2a56e2 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/steps.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/steps.go @@ -157,6 +157,8 @@ type Hearer struct { // Asker publishes an approval step's ask (§37); Name is the runner's own name, the asker a warrant names. Asker Asker Name string + // StalledBound is the runner's setting stalled-bound (§790): the bound of a held step's wait, given at the start (H-A-738 (2)). + StalledBound time.Duration // Where reads the router's record of one of the runner's asks, as operatorchannelclient.Client.Where does: its state and // its warrant (design 47 G A-89, §700). Where func(ask string) (string, *oc.Warrant, error) @@ -368,6 +370,10 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s old := s.Ask a, why := h.supersededAgain(&p, i, ev, passed, now) if a != nil { + // The step log's entry of the step asked again names the pipeline's own revision and the one the passed-over end + // named (design 47 H2 H-A-577 (3), H-A-743). + p.Unlogged = append(p.Unlogged, seat.LogEntry{Pipeline: ev.Pipeline, Module: s.Module, Step: s.Step, Artifact: s.Artifact, + What: seat.LogEntryWhatStarted, Outcome: seat.LogEntryOutcomeRunning, Revision: own, PassedOver: superseding, At: now}) if _, err := h.Store.Update(ev.Pipeline, p, rev); errors.Is(err, ErrChanged) { continue } else if err != nil { @@ -379,6 +385,11 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s if err := h.PutAgain(ev.Pipeline, *a); err != nil { h.logf("%s: the build of %s asked again as %s is written and not put, put again at the next start: %v", ev.Pipeline, s.Module, a.ID, err) } + // The passed-over end is said as an event, not only in the journal (design 47 H2 H-A-577 (3)): step-started with rerun + // and the runner as the caller. + if err := h.say(seat.EventStepStarted, p, s); err != nil { + h.logf("%s: the step-started of %s asked again is not said: %v", ev.Pipeline, s.Module, err) + } return p, nil } h.logf("%s: %s's build ended superseded (%s), passed over: %s; %s (H-A-555, H-A-561)", ev.Pipeline, s.Module, ev.Said, passed, why) @@ -386,6 +397,8 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s case superseding > own && !h.viewHolds(p.Branch, superseding): old := s.Ask s.Outcome, s.On, s.Revision, s.Node, s.Why = seat.StepResultOutcomeWaiting, seat.WaitOnRevisionView, superseding, node, ev.Said + held := h.now() + s.HeldAt = &held // when the step was held: the clock of its wait (H-A-599, H-A-738 (2)) if _, err := h.Store.Update(ev.Pipeline, p, rev); errors.Is(err, ErrChanged) { continue } else if err != nil { @@ -399,8 +412,14 @@ func (h *Hearer) OnStepEndedRevised(bs StepSeat, subject string, ev StepEnded, s } return p, nil } + } else if supersededBuild(*s, ev.Outcome) { + // A superseded end naming no revision is no end the runner can judge (design 47 H2 H-A-601, H-A-650): the step ends could-not-run, + // naming the builder, and a rerun asks it again. + h.logf("%s: %s's build ended superseded (%s) with no revision: the step ends could-not-run (H-A-601)", ev.Pipeline, s.Module, ev.Said) + ev.Outcome, ev.Said = nodebuildgo.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the builder on %s ended it superseded: a superseded end without its revision (%s)", node, ev.Said) } s.Outcome, s.Node, s.Why, s.Rerun, s.By, s.Ended = ev.Outcome, node, ev.Said, ev.Rerun, ev.By, &now + s.HeldAt = nil // the hold ends with the step (H-A-738 (2)) if len(shared) > 0 { s.Shared = shared } @@ -751,6 +770,7 @@ func (h *Hearer) say(event string, p seat.Pipeline, step *seat.StepResult) error 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) @@ -901,6 +921,8 @@ func (h *Hearer) supersededAgain(p *seat.Pipeline, i int, ev StepEnded, passed s return nil, fmt.Sprintf("its build ended superseded (%s), though %s, and it cannot be asked again: %v", ev.Said, passed, err) } s.Ask, s.AskedAt, s.TakenAt, s.Node = a.ID, &now, nil, "" + // The step asked again is a rerun by the runner itself, said as such by its step-started (design 47 H2 H-A-577 (3)). + s.Rerun, s.By = true, h.Name return a, "" } @@ -1013,6 +1035,9 @@ func endPipeline(p *seat.Pipeline, now time.Time, unplaced func(seat.Pipeline, s switch { case slices.Contains(p.Superseded, s.Module): continue + case s.Module != "" && len(p.Movers) > 0 && !Moves(*p, s.Module): + // A mover a carry or a reopening took out of the pipeline is judged where it went (H-A-609 (1)). + continue case s.Step == seat.StepResultStepApproval && s.Outcome == seat.StepResultOutcomeWaiting: notAsked = append(notAsked, i) continue @@ -1067,7 +1092,10 @@ func (h *Hearer) endPipeline(p *seat.Pipeline, now time.Time, wr func(seat.Pipel } if wr != nil { for i := range p.Movers { - p.Movers[i].Widens = wr(*p, p.Movers[i].Module) + // A carried or reopened mover says the widens its first pipeline computed and never computes it again (H-A-595). + if len(p.Movers[i].Widens) == 0 { + p.Movers[i].Widens = wr(*p, p.Movers[i].Module) + } } } return true @@ -1116,3 +1144,11 @@ func sameValidate(p *seat.Pipeline, i int, now time.Time) []int { } return out } + +// boundOf is a bound as a wait names it, a Go duration such as 5m0s; empty for none. +func boundOf(d time.Duration) string { + if d <= 0 { + return "" + } + return d.String() +} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go b/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go index f2c7858e9..de358ce92 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/supersede.go @@ -214,6 +214,7 @@ func supersedeStep(p *seat.Pipeline, st *seat.StepResult, why string, now time.T drop = append(drop, *st) // its own ask on a build node: the seat's drop cancels it } st.Outcome, st.Why, st.Ended = seat.StepResultOutcomeSuperseded, why, &now + st.HeldAt = nil p.Unlogged = append(p.Unlogged, endEntry(p.Pipeline, *st, now)) return leave, drop } @@ -405,7 +406,7 @@ func (h *Hearer) revisionHeldOne(key string, held int64) bool { 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 = "", 0 + st.On, st.Revision, st.HeldAt = "", 0, nil l, d := supersedeStep(&p, st, why, now) leave, drop = append(leave, l...), append(drop, d...) ended = append(ended, i) diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go b/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go index dfc20deb6..8746e02d3 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/unfinished.go @@ -28,6 +28,12 @@ type UnfinishedEntry struct { Revision int64 `json:"revision"` Pipeline string `json:"pipeline"` Outcome string `json:"outcome"` + // CarriedBy is the pipeline that carries the mover now, cleared when it ends otherwise than passed (design 47 H2 H-A-594 + // (4)); the carry skips a key whose carrier is held. + CarriedBy string `json:"carried-by,omitempty"` + // Widens is what the mover's change widens in its first pipeline, kept so a carried or reopened pipeline says the same + // (H-A-595). + Widens []seat.Widening `json:"widens,omitempty"` } // UnfinishedStore is the state unfinished: a key's value (nil when it has none), a put, a delete and the keys matching a @@ -96,6 +102,14 @@ func ownStepsHeld(p seat.Pipeline, module string) bool { type Unfinished struct { Store UnfinishedStore Logf func(string, ...any) + // Entries are the entries of a branch's catalog revision, whose edges say which movers a failed one holds back (H-A-646); + // Pipeline reads a pipeline of the state pipelines; Registered says whether a module is registered still (H-A-610); Add + // puts a closed group of movers a pipeline left in the head's pipeline while that waits or runs, and answers its key + // (H-A-607 (2)). Nil hooks carry nothing at an end and tie nothing. + Entries func(branch string, revision int64) (map[string]catalog.CatalogEntry, bool) + Pipeline func(key string) (seat.Pipeline, bool) + Registered func(module string) bool + Add func(from seat.Pipeline, group []seat.Mover) (string, bool) } func (u *Unfinished) logf(format string, args ...any) { @@ -117,9 +131,106 @@ func (u *Unfinished) read(key string) (UnfinishedEntry, bool, error) { return e, true, nil } +// failedMovers are the movers of p with a required step that failed or could not run: each counts as failed (H-A-566, +// H-A-649). +func failedMovers(p seat.Pipeline) []string { + var out []string + for _, m := range p.Movers { + if len(failedSteps(p, m.Module)) > 0 { + out = append(out, m.Module) + } + } + return out +} + +// tiedTo are the modules in failed that left, of p, holds back: left has an awaited edge from them (kind 1, the package +// published, or kind 3, the build step passed), directly or through others (H-A-646), and so has every mover of its tier +// component, the group being closed under the tier kinds. The answer maps each tied mover to the failed modules it waits on. +func tiedTo(p seat.Pipeline, left, failed []string, entries map[string]catalog.CatalogEntry) map[string][]string { + root := map[string][]string{} + for changed := true; changed; { + changed = false + for _, m := range left { + for _, x := range awaited(p, m, entries) { + from := moduleOf(x.From) + var by []string + if slices.Contains(failed, from) { + by = []string{from} + } else { + by = root[from] + } + for _, f := range by { + if !slices.Contains(root[m], f) { + root[m], changed = append(root[m], f), true + } + } + } + } + } + for _, g := range tierGroups(left, entries) { + var by []string + for _, m := range g { + for _, f := range root[m] { + if !slices.Contains(by, f) { + by = append(by, f) + } + } + } + for _, m := range g { + if len(by) > 0 { + slices.Sort(by) + root[m] = by + } + } + } + return root +} + +// tierGroups are the connected components of modules under the delivery (tier) edges of their entries: the groups a carry +// keeps together (H-A-594 (2)). Each is sorted, the groups in the order of their first module. +func tierGroups(modules []string, entries map[string]catalog.CatalogEntry) [][]string { + parent := map[string]string{} + for _, m := range modules { + parent[m] = m + } + var find func(string) string + find = func(m string) string { + if parent[m] != m { + parent[m] = find(parent[m]) + } + return parent[m] + } + for _, m := range modules { + for _, x := range entries[m].Edges { + if from := moduleOf(x.From); tierKinds[x.Kind] && from != m && slices.Contains(modules, from) { + parent[find(from)] = find(m) + } + } + } + byRoot := map[string][]string{} + var order []string + for _, m := range modules { + r := find(m) + if _, ok := byRoot[r]; !ok { + order = append(order, r) + } + byRoot[r] = append(byRoot[r], m) + } + var out [][]string + for _, r := range order { + slices.Sort(byRoot[r]) + out = append(out, byRoot[r]) + } + slices.SortFunc(out, func(a, b []string) int { return strings.Compare(a[0], b[0]) }) + return out +} + // Ended takes a pipeline's end into the state unfinished (§786): a mover p leaves unfinished is kept under its key; a mover // whose pipeline ended passed, or whose own required step did not pass (it waits for its fingerprint to move), has its key -// deleted when the key names its fingerprint. A run on request's pipeline, and one every mover left, change nothing. +// deleted when the key names its fingerprint. A run on request's pipeline, and one every mover left, change nothing. A key a +// pipeline carried whose carrier ends otherwise than passed names that pipeline and no carrier (H-A-594 (4)). At an end +// failed, cancelled or could-not-run, the groups of the movers it leaves that no failed mover holds back are added at once +// to the head's pipeline when that waits or runs (H-A-607 (2)). func (u *Unfinished) Ended(p seat.Pipeline) { if u == nil || p.Run != "" { return @@ -136,7 +247,7 @@ func (u *Unfinished) Ended(p seat.Pipeline) { } key := UnfinishedKey(p.Branch, m.Module) if slices.Contains(left, m.Module) { - raw, _ := json.Marshal(UnfinishedEntry{Fingerprint: m.Fingerprint, Revision: p.Revision, Pipeline: p.Pipeline, Outcome: p.Outcome}) + raw, _ := json.Marshal(UnfinishedEntry{Fingerprint: m.Fingerprint, Revision: p.Revision, Pipeline: p.Pipeline, Outcome: p.Outcome, Widens: m.Widens}) if err := u.Store.Put(key, raw); err != nil { u.logf("%s ended %s and leaves %s unfinished, but it is not kept in the state unfinished: %v", p.Pipeline, p.Outcome, m.Module, err) continue @@ -152,18 +263,132 @@ func (u *Unfinished) Ended(p seat.Pipeline) { if !held || e.Fingerprint != m.Fingerprint { continue } + if p.Outcome != seat.PipelineOutcomePassed && e.CarriedBy == p.Pipeline { + e.CarriedBy, e.Pipeline, e.Outcome, e.Revision = "", p.Pipeline, p.Outcome, p.Revision + raw, _ := json.Marshal(e) + if err := u.Store.Put(key, raw); err != nil { + u.logf("%s: the unfinished entry of %s is not written: %v", p.Pipeline, m.Module, err) + } + continue + } if err := u.Store.Delete(key); err != nil { u.logf("%s: the unfinished entry of %s is not deleted: %v", p.Pipeline, m.Module, err) continue } u.logf("%s ended %s: %s is no longer unfinished", p.Pipeline, p.Outcome, m.Module) } + u.carryAtEnd(p, left) +} + +// carryAtEnd adds each closed group of the movers left to the head's pipeline (H-A-594 (2), (3), H-A-607 (2)), and names that +// pipeline as the carrier of each of its movers' keys. +func (u *Unfinished) carryAtEnd(p seat.Pipeline, left []string) { + if len(left) == 0 || u.Add == nil || u.Entries == nil { + return + } + entries, ok := u.Entries(p.Branch, p.Revision) + if !ok { + u.logf("%s: revision %d of %s is not read, so the movers it left are carried at the next take-in", p.Pipeline, p.Revision, p.Branch) + return + } + tied := tiedTo(p, left, failedMovers(p), entries) + var free []string + for _, m := range left { + if len(tied[m]) == 0 { + free = append(free, m) + } + } + for _, g := range tierGroups(free, entries) { + var group []seat.Mover + for _, name := range g { + m, _ := MoverOf(p, name) + group = append(group, m) + } + carrier, ok := u.Add(p, group) + if !ok { + continue + } + u.markCarried(p.Branch, g, carrier) + } +} + +// markCarried names carrier as the carrier of the keys of modules (H-A-594 (4)). +func (u *Unfinished) markCarried(branch string, modules []string, carrier string) { + for _, module := range modules { + key := UnfinishedKey(branch, module) + e, held, err := u.read(key) + if err != nil || !held { + continue + } + e.CarriedBy = carrier + raw, _ := json.Marshal(e) + if err := u.Store.Put(key, raw); err != nil { + u.logf("the unfinished entry of %s is not written: %v", module, err) + } + } +} + +// heldBack are the failed modules a mover's key is tied to: the failed movers of its pipeline that the mover awaits at that +// pipeline's revision, directly or through others, and that are registered still (H-A-610, H-A-646). None when the hooks that +// read them are not set. +func (u *Unfinished) heldBack(branch, module string, e UnfinishedEntry) []string { + if u.Pipeline == nil || u.Entries == nil { + return nil + } + p, ok := u.Pipeline(e.Pipeline) + if !ok { + return nil + } + entries, ok := u.Entries(branch, p.Revision) + if !ok { + return nil + } + var left []string + for _, m := range p.Movers { + if _, held, _ := u.read(UnfinishedKey(branch, m.Module)); held && !slices.Contains(failedMovers(p), m.Module) { + left = append(left, m.Module) + } + } + var out []string + for _, f := range tiedTo(p, left, failedMovers(p), entries)[module] { + if u.Registered == nil || u.Registered(f) { + out = append(out, f) + } + } + return out +} + +// HeldBehind are the modules whose unfinished key of branch is tied to module (H-A-625 (2)): the movers a failed module holds +// back, said by its finding pipeline-failed. +func (u *Unfinished) HeldBehind(branch, module string) []string { + if u == nil { + return nil + } + ukeys, err := u.Store.Keys(keys.EscapeName(branch) + ".*") + if err != nil { + return nil + } + slices.Sort(ukeys) + var out []string + for _, key := range ukeys { + _, name, _ := strings.Cut(key, ".") + m, err := keys.UnescapeName(name) + if err != nil { + continue + } + if e, held, _ := u.read(key); held && slices.Contains(u.heldBack(branch, m, e), module) { + out = append(out, m) + } + } + return out } // Carry adds to the movers of a catalog revision of branch each unfinished mover whose fingerprint is still its entry's in // entries, the revision's entries, with one journal line per mover added again (§786). An unfinished mover the revision // moves at a newer fingerprint, or whose entry holds another fingerprint or none, has its key deleted; one it moves at its -// own fingerprint is carried by the revision already. It answers movers with the added ones after them. +// own fingerprint is carried by the revision already. A key whose carrier waits or runs is skipped (H-A-594 (4)); one tied to +// a failed mover the revision does not move is kept, tied, until that mover passes or leaves the registrations (H-A-594 (2), +// H-A-610). It answers movers with the added ones after them. func (u *Unfinished) Carry(branch string, revision int64, entries map[string]catalog.CatalogEntry, movers []seat.Mover) []seat.Mover { if u == nil { return movers @@ -187,6 +412,9 @@ func (u *Unfinished) Carry(branch string, revision int64, entries map[string]cat } continue } + if e.CarriedBy != "" { + continue + } 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)) @@ -198,7 +426,13 @@ func (u *Unfinished) Carry(branch string, revision int64, entries map[string]cat u.dropMoved(key, module, fmt.Sprintf("revision %d of %s holds it at %q", revision, branch, entry.Fp)) continue } - movers = append(movers, seat.Mover{Module: module, Commit: entry.Commit, Fingerprint: entry.Fp, Repository: entry.Repository}) + if by := u.heldBack(branch, module, e); len(by) > 0 && !slices.ContainsFunc(by, func(f string) bool { + return slices.ContainsFunc(movers, func(m seat.Mover) bool { return m.Module == f }) + }) { + u.logf("revision %d of %s does not carry %s: it is tied to %v, which it does not move (H-A-594 (2))", revision, branch, module, by) + continue + } + movers = append(movers, seat.Mover{Module: module, Commit: entry.Commit, Fingerprint: entry.Fp, Repository: entry.Repository, Widens: e.Widens}) u.logf("revision %d of %s puts %s in a pipeline again: %s left it unfinished (%s) at fingerprint %s (§786)", revision, branch, module, e.Pipeline, e.Outcome, e.Fingerprint) } return movers diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go b/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go index fcc689246..c64e89328 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/verbs.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "slices" - "strconv" "strings" "time" @@ -34,6 +33,9 @@ type Verbs struct { // at the time of the ask: nil when it is, an error wrapping ErrRevisionGone when it is removed (design 47 H2 H-A-479 // addendum (2)). RevisionHeld func(branch string, revision int64) error + // noRecord says the call records no hand act: a verb that is one hand act and asks other verbs' acts inside it (design 47 + // H2 H-A-607 (3), H-A-644). + noRecord bool } // ErrRevisionGone is a catalog revision the catalog no longer keeps (H-A-479 addendum (2)). @@ -42,6 +44,9 @@ var ErrRevisionGone = errors.New("the catalog revision is gone") func (v Verbs) now() time.Time { return v.Hearer.now() } func (v Verbs) record(verb, what, why string) error { + if v.noRecord { + return nil + } if v.Acts == nil { return errors.New("no way to record a hand act is given: nothing was done") } @@ -306,11 +311,16 @@ func (v Verbs) sayReopened(p seat.Pipeline, reopens bool) { } // reopening says whether a rerun of pipeline key reopens an ended delivering pipeline, refusing it when its revision is -// gone (H-A-479 addendum (2)). A pipeline not read, a run's, or one the rerun refuses anyway is left to the rerun. -func (v Verbs) reopening(key string) (bool, error) { +// gone (H-A-479 addendum (2)). A pipeline not read, a run's, or one the rerun refuses anyway is left to the rerun. With hand +// set, a pipeline that ended cancelled is reopened too: a key of unfinished reopens the pipeline it names whatever its end +// (design 47 H2 H-A-750 (3)). +func (v Verbs) reopening(key string) (bool, error) { return v.reopeningFor(key, false) } + +// reopeningFor is reopening, a pipeline that ended cancelled reopened too when hand is set. +func (v Verbs) reopeningFor(key string, hand bool) (bool, error) { p, _, err := v.Hearer.Store.Get(key) - if err != nil || p.Ended == nil || p.Run != "" || p.Revision <= 0 || - p.Outcome == seat.PipelineOutcomeCancelled || p.Outcome == seat.PipelineOutcomeSuperseded { + if err != nil || p.Ended == nil || p.Run != "" || p.Revision <= 0 || p.Outcome == seat.PipelineOutcomeSuperseded || + (p.Outcome == seat.PipelineOutcomeCancelled && !hand) { return false, nil } // A reopening never builds beside an open pipeline carrying one of its movers at the same revision (H-A-479 third @@ -735,158 +745,6 @@ func (v Verbs) Run(caller string, in seat.RunInput) (seat.RunAnswer, error) { return v.Starter.Run(caller, in, NewRunID, v.View) } -// Start starts by hand a delivering pipeline for the head of a watched branch the runner's catalog half holds, recorded in -// the hand-act log first (§306, §394): the pipeline of that branch's source revision and the module, as a take-in would -// start it. A head whose pipeline is written already starts nothing and is refused, naming the pipeline. With modules it -// starts the named modules again at the head instead (startAgain, H-A-479); exactly one of module or modules is given. -func (v Verbs) Start(_ string, in seat.StartInput) (seat.StartAnswer, error) { - if in.Module != "" && len(in.Modules) > 0 { - return seat.StartAnswer{}, errors.New("start names the module or the modules, not both: nothing was started") - } - if in.Branch != "" && len(in.Modules) > 0 { - return v.startAgain(in) - } - if in.Branch == "" || in.Module == "" { - return seat.StartAnswer{}, errors.New("start names the watched branch and the module or the modules") - } - if v.Starter == nil || v.View == nil { - return seat.StartAnswer{}, errors.New("the runner cannot start a pipeline: it holds no starter or no catalog half") - } - half, ok := v.View(in.Branch) - if !ok { - return seat.StartAnswer{}, fmt.Errorf("the catalog half of %s is not held yet: nothing was started", in.Branch) - } - e, ok := half.Entries[in.Module] - if !ok || half.Source <= 0 { - return seat.StartAnswer{}, fmt.Errorf("the catalog half of %s holds no entry of %s at a source revision: nothing was started", in.Branch, in.Module) - } - key := Key(in.Branch, keyRevision(Begin{Revision: half.Revision, Source: half.Source})) - if err := v.record(seat.VerbStart, "started the pipeline "+key+" by hand", in.Why); err != nil { - return seat.StartAnswer{}, err - } - // A hand start keys the newest revision's . with the module as its one mover (H-A-52, H-A-213 (4)). - started, err := v.Starter.Start(Begin{Branch: in.Branch, Source: half.Source, Revision: half.Revision, Entries: half.Entries, - Movers: []seat.Mover{{Module: in.Module, Commit: e.Commit, Fingerprint: e.Fp, Repository: e.Repository, Tier: 1}}}) - if err != nil { - return seat.StartAnswer{}, err - } - if !started { - return seat.StartAnswer{}, fmt.Errorf("the pipeline %s of the head is started already: a step of it is asked again by rerun", key) - } - return seat.StartAnswer{Pipeline: key}, nil -} - -// startAgain starts by hand, recorded in the hand-act log first, a pipeline at the head of a watched branch carrying the -// named modules whose newest entry, the head's, has no passed pipeline (a failed, cut or superseded one), with the head's -// revision as its candidate and the take-in's tiers (design 47 H2 H-A-479): keyed `..again.`, n from 1, -// taken by writing on absence (addendum (1)). Its pipeline-started pins the head's revision as a take-in's does, and its -// versions are reserved at its build steps as a take-in's are. A module the head holds no entry of, or whose newest entry -// passed in a pipeline, is refused by name, nothing started. -func (v Verbs) startAgain(in seat.StartInput) (seat.StartAnswer, error) { - if v.Starter == nil || v.View == nil || v.Hearer == nil || v.Hearer.Store == nil { - return seat.StartAnswer{}, errors.New("the runner cannot start a pipeline again: it holds no starter, no catalog half or no state pipelines") - } - half, ok := v.View(in.Branch) - if !ok || half.Source <= 0 { - return seat.StartAnswer{}, fmt.Errorf("the catalog half of %s is not held at a source revision yet: nothing was started", in.Branch) - } - movers := make([]seat.Mover, 0, len(in.Modules)) - var absent []string - for _, m := range in.Modules { - e, ok := half.Entries[m] - if !ok { - absent = append(absent, m) - continue - } - if slices.ContainsFunc(movers, func(x seat.Mover) bool { return x.Module == m }) { - continue - } - movers = append(movers, seat.Mover{Module: m, Commit: e.Commit, Fingerprint: e.Fp, Repository: e.Repository}) - } - 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, ", ")) - } - passed, running, err := v.heldEntries(in.Branch, movers) - if err != nil { - return seat.StartAnswer{}, err - } - if len(passed) > 0 { - return seat.StartAnswer{}, fmt.Errorf("the newest entry of %s passed already: nothing was started", strings.Join(passed, ", ")) - } - if len(running) > 0 { - return seat.StartAnswer{}, fmt.Errorf("the newest entry of %s: nothing was started", strings.Join(running, ", ")) - } - movers = Tiers(movers, half.Entries, v.Starter.logf) - names := make([]string, 0, len(movers)) - for _, m := range movers { - names = append(names, m.Module) - } - prefix := AgainPipelineKey(in.Branch, half.Revision, 0) - prefix = prefix[:len(prefix)-1] - held, err := v.Hearer.Store.Keys(prefix + "*") - if err != nil { - return seat.StartAnswer{}, fmt.Errorf("the pipelines started again at revision %d of %s are not listed: nothing was started: %w", half.Revision, in.Branch, err) - } - n := 1 - for _, k := range held { - if i, err := strconv.Atoi(strings.TrimPrefix(k, prefix)); err == nil && i >= n { - n = i + 1 - } - } - if err := v.record(seat.VerbStart, fmt.Sprintf("started %s again at the head of %s by hand", strings.Join(names, ", "), in.Branch), in.Why); err != nil { - return seat.StartAnswer{}, err - } - // The next n is taken without a bound: each refusal means the key exists (H-A-479 second addendum). - for ; ; n++ { - key := AgainPipelineKey(in.Branch, half.Revision, n) - started, err := v.Starter.Start(Begin{Branch: in.Branch, Source: half.Source, Revision: half.Revision, Entries: half.Entries, - Key: key, Movers: movers}) - if err != nil { - return seat.StartAnswer{}, err - } - if started { - v.Starter.logf("%s starts %s again at the head by hand (H-A-479)", key, strings.Join(names, ", ")) - return seat.StartAnswer{Pipeline: key}, nil - } - } -} - -// heldEntries are the movers whose module, at the mover's fingerprint, a delivering pipeline of branch carries and did not -// leave: passed, those a passed pipeline holds (a newest entry that passed is not started again, H-A-479); running, those a -// pipeline not ended holds, each said ": its pipeline is running", so two pipelines never build one entry side -// by side (H-A-479 second addendum). -func (v Verbs) heldEntries(branch string, movers []seat.Mover) (passed, running []string, err error) { - pkeys, err := branchKeys(v.Hearer.Store, branch) - if err != nil { - return nil, nil, fmt.Errorf("the pipelines of %s are not listed, so nothing was started: %w", branch, err) - } - seen := map[string]bool{} - for _, key := range pkeys { - p, _, err := v.Hearer.Store.Get(key) - if err != nil { - return nil, nil, fmt.Errorf("the pipeline %s is not read, so nothing was started: %w", key, err) - } - open := p.Ended == nil && (p.Outcome == seat.PipelineOutcomeRunning || p.Outcome == seat.PipelineOutcomeWaiting) - if p.Run != "" || (p.Outcome != seat.PipelineOutcomePassed && !open) { - continue - } - for _, m := range movers { - if seen[m.Module] || slices.Contains(p.Superseded, m.Module) { - continue - } - if pm, ok := MoverOf(p, m.Module); ok && pm.Fingerprint == m.Fingerprint { - seen[m.Module] = true - if open { - running = append(running, m.Module+": its pipeline "+key+" is running") - } else { - passed = append(passed, m.Module+" (in "+key+")") - } - } - } - } - return passed, running, nil -} - // AskAgain asks a declined approval step once more (§306, §36), recorded in the hand-act log first: the step waits again, // marked asked again by the caller the bus proved, and is asked at once when the pipeline's every other required step // passed, under an ask of its own (the earlier ask's decision ended it). @@ -948,63 +806,3 @@ func (v Verbs) Place(caller string, in seat.PlaceInput) (seat.PlaceAnswer, error p, _, err = s.Store.Get(in.Pipeline) return seat.PlaceAnswer{Pipeline: p}, err } - -// PlaceUnfinished puts a mover kept in the state unfinished in a pipeline of its own at once, recorded in the hand-act log -// first (design 47 H2 §786, H-A-398): keyed `..unfinished.`, its steps placed from the entries of -// the catalog revision the entry names, the mover at the entry's fingerprint. The key stays until that pipeline ends passed. -// A key the state does not hold, a revision whose entry holds another fingerprint, or a pipeline written already is refused, -// nothing done. -func (v Verbs) PlaceUnfinished(_ string, in seat.PlaceUnfinishedInput) (seat.PlaceUnfinishedAnswer, error) { - s := v.Starter - if strings.TrimSpace(in.Key) == "" { - return seat.PlaceUnfinishedAnswer{}, errors.New("place-unfinished names the unfinished entry's key") - } - if s == nil || s.Unfinished == nil { - return seat.PlaceUnfinishedAnswer{}, errors.New("the runner keeps no state unfinished: nothing was placed") - } - e, held, err := s.Unfinished.Entry(in.Key) - if err != nil { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the unfinished entry %s is not read: %w", in.Key, err) - } - if !held { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the state unfinished holds no %s: nothing was placed", in.Key) - } - b, m, _ := strings.Cut(in.Key, ".") - branch, berr := keys.UnescapeName(b) - module, merr := keys.UnescapeName(m) - if berr != nil || merr != nil || branch == "" || module == "" { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("%s is no key .: nothing was placed", in.Key) - } - var half Half - switch { - case s.Revision != nil: - if half, err = s.Revision(branch, e.Revision); err != nil { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the revision %d of %s is not read: nothing was placed: %w", e.Revision, branch, err) - } - case v.View != nil: - var ok bool - if half, ok = v.View(branch); !ok || half.Revision != e.Revision { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the revision %d of %s is not held: nothing was placed", e.Revision, branch) - } - default: - return seat.PlaceUnfinishedAnswer{}, errors.New("the runner reads no catalog revision: nothing was placed") - } - entry, ok := half.Entries[module] - if !ok || entry.Fp != e.Fingerprint || half.Source <= 0 { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the revision %d of %s holds %s at %q, not its unfinished fingerprint %s: nothing was placed", e.Revision, branch, module, entry.Fp, e.Fingerprint) - } - key := UnfinishedPipelineKey(branch, e.Revision, module) - if err := v.record(seat.VerbPlaceUnfinished, "put the unfinished mover "+module+" of "+branch+" in the pipeline "+key+" by hand", in.Why); err != nil { - return seat.PlaceUnfinishedAnswer{}, err - } - started, err := s.Start(Begin{Branch: branch, Source: half.Source, Revision: e.Revision, Entries: half.Entries, Key: key, - Movers: []seat.Mover{{Module: module, Commit: entry.Commit, Fingerprint: entry.Fp, Repository: entry.Repository, Tier: 1}}}) - if err != nil { - return seat.PlaceUnfinishedAnswer{}, err - } - if !started { - return seat.PlaceUnfinishedAnswer{}, fmt.Errorf("the pipeline %s is started already: nothing was placed", key) - } - s.logf("%s puts the unfinished mover %s in a pipeline of its own by hand (§786)", key, module) - return seat.PlaceUnfinishedAnswer{Pipeline: key}, nil -} diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go index 2fb55c882..89734ab92 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/verbs_test.go @@ -373,7 +373,7 @@ func (failingActs) RecordHandAct(views.HandAct) error { return errors.New("no ho func TestStartAndAskAgain(t *testing.T) { v, store, _, _, acts, _ := verbsFixture() made := created{} - v.Starter.Pipelines, v.Starter.Say = made, func(string, any) error { return nil } + v.Starter.Pipelines, v.Starter.Say, v.Starter.Store = made, func(string, any) error { return nil }, store _, entries := placeFixture() v.View = func(string) (Half, bool) { return Half{Source: 7, Revision: 3, Entries: entries}, true } a, err := v.Start("operator", seat.StartInput{Branch: "main", Module: "app", Why: "no pipeline for the head"}) @@ -472,17 +472,18 @@ func TestAValidateRerunMovesEveryMoversValidateAndReopensItsCompositions(t *test } } -// H-A-479: start with modules starts a pipeline at the head keyed ..again. carrying the named modules -// whose newest entry has no passed pipeline, at the take-in's tiers; a module whose newest entry passed is refused by name, -// nothing started; exactly one of module or modules is given; a second start takes the next n. -func TestStartWithModulesStartsAFailedMoverAgainAtTheHead(t *testing.T) { - v, store, _, _, acts, _ := verbsFixture() +// H-A-571, H-A-607 (3), H-A-643 (design 47 H2): start with modules follows one rule per module: a head with no pipeline is started +// with the modules named, the head's pipeline that runs takes the modules it does not move as movers said by mover-added with +// the caller, and an ended one reopens for a module whose own step failed; no `.again.` pipeline is ever keyed, and a module +// whose head pipeline passed or does not move it is refused by name; exactly one of module or modules is given. +func TestStartWithModulesJoinsTheHeadsPipelineOrReopensIt(t *testing.T) { + v, store, _, asks, acts, _ := verbsFixture() made := created{} - var started []seat.PipelineStarted - v.Starter.Pipelines = made + var added []seat.MoverAdded + v.Starter.Pipelines, v.Starter.Store = made, store v.Starter.Say = func(_ string, body any) error { - if ps, ok := body.(seat.PipelineStarted); ok { - started = append(started, ps) + if ev, ok := body.(seat.MoverAdded); ok { + added = append(added, ev) } return nil } @@ -491,76 +492,97 @@ func TestStartWithModulesStartsAFailedMoverAgainAtTheHead(t *testing.T) { app.Fp, app.Commit, app.Repository = "src2:aa", "c1", "o/app" entries["app"] = app entries["lib"] = catalog.CatalogEntry{Module: "lib", Fp: "src2:bb", Commit: "c2", Repository: "o/lib"} - v.View = func(string) (Half, bool) { return Half{Source: 7, Revision: 9, Entries: entries}, true } - // The fixture's main.5 moves app at src2:aa and failed; lib's newest entry passed in main.8. - e := store[pkey] - e.p.Outcome = seat.PipelineOutcomeFailed - store[pkey] = e - store["main.8"] = struct { - p seat.Pipeline - rev uint64 - }{seat.Pipeline{Pipeline: "main.8", Branch: "main", Source: 6, Revision: 8, Outcome: seat.PipelineOutcomePassed, - Movers: []seat.Mover{{Module: "lib", Fingerprint: "src2:bb"}, {Module: "app", Fingerprint: "src2:aa"}}, Superseded: []string{"app"}}, 1} - + revision := int64(9) + v.View = func(string) (Half, bool) { return Half{Source: 7, Revision: revision, Entries: entries}, true } if _, err := v.Start("operator", seat.StartInput{Branch: "main", Module: "app", Modules: []string{"app"}, Why: "x"}); err == nil { t.Error("a start naming both module and modules was taken") } - // A pipeline still running at app's head entry refuses the start: two pipelines never build one entry side by side. - store["main.7"] = struct { - p seat.Pipeline - rev uint64 - }{seat.Pipeline{Pipeline: "main.7", Branch: "main", Source: 6, Revision: 7, Outcome: seat.PipelineOutcomeRunning, - Movers: []seat.Mover{{Module: "app", Fingerprint: "src2:aa"}}}, 1} - if _, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "x"}); err == nil || !strings.Contains(err.Error(), "its pipeline main.7 is running") { - t.Errorf("a start of app while main.7 runs it = %v; want refused naming main.7", err) - } - delete(store, "main.7") - if _, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app", "lib"}, Why: "x"}); err == nil || !strings.Contains(err.Error(), "lib") { - t.Errorf("a start naming lib, whose newest entry passed, = %v; want refused naming lib", err) - } - if len(made) != 0 { - t.Fatalf("a refused start wrote %d pipelines", len(made)) - } - a, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "its pipeline failed at an unchanged entry"}) - if err != nil || a.Pipeline != "main.9.again.1" || made["main.9.again.1"] == nil { + // A head with no pipeline starts one with both modules, keyed by the revision. + a, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app", "lib"}, Why: "no pipeline for the head"}) + if err != nil || a.Pipeline != "main.9" || made["main.9"] == nil { t.Fatalf("start with modules = %+v, %v; written %v", a, err, len(made)) } var p seat.Pipeline - if err := json.Unmarshal(made["main.9.again.1"], &p); err != nil { - t.Fatal(err) + if err := json.Unmarshal(made["main.9"], &p); err != nil || len(p.Movers) != 2 { + t.Fatalf("the pipeline = %+v (%v), want app and lib", p, err) } - if p.Revision != 9 || p.Source != 7 || len(p.Movers) != 1 || p.Movers[0].Module != "app" || p.Movers[0].Fingerprint != "src2:aa" || p.Movers[0].Tier != 1 { - t.Errorf("the pipeline = %+v, want app at src2:aa, tier 1, at revision 9 of source 7", p) - } - if len(started) != 1 || started[0].Pipeline != "main.9.again.1" || started[0].Revision != 9 { - t.Errorf("pipeline-started = %+v, want main.9.again.1 at revision 9 (its revision pinned)", started) - } - // The next start at the same head, once main.9.again.1 failed, takes the next n. - at := time.Unix(3, 0) - p.Outcome, p.Ended = seat.PipelineOutcomeFailed, &at - store["main.9.again.1"] = struct { + // The head's pipeline waits (H-A-750 (1)) and moves app alone: start of both adds lib, said with the caller; one it moves + // already is refused. + p.Movers, p.Outcome = p.Movers[:1], seat.PipelineOutcomeWaiting + store["main.9"] = struct { p seat.Pipeline rev uint64 }{p, 1} - if a, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "again"}); err != nil || a.Pipeline != "main.9.again.2" { - t.Errorf("a second start with modules = %+v, %v; want main.9.again.2", a, err) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app", "lib"}, Why: "lib joins"}); err != nil || a.Pipeline != "main.9" { + t.Fatalf("start of lib while main.9 runs = %+v, %v", a, err) } - if len(*acts) != 2 { - t.Errorf("hand acts %v, want the two starts recorded", *acts) + if got, _, _ := store.Get("main.9"); !Moves(got, "lib") || len(got.Movers) != 2 || len(added) != 1 || added[0].Module != "lib" || added[0].Caller != "operator" || added[0].Pipeline != "main.9" { + t.Errorf("main.9 moves %+v, mover-added %+v, want lib added by the caller", got.Movers, added) } - // main.9.again.1 passed: its version is written into it as into any pipeline of its source, and a further start of app is - // refused naming it, read through the branch's key forms. - p.Outcome = seat.PipelineOutcomePassed - store["main.9.again.1"] = struct { + if _, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "x"}); err == nil || !strings.Contains(err.Error(), "main.9") { + t.Errorf("a start of app, which main.9 moves, = %v; want refused naming main.9", err) + } + // The head's pipeline ended and start never refuses (H-A-750 (2)): app, which it moved and whose steps passed, is answered + // delivered by it, no act written and nothing said. + got, _, _ := store.Get("main.9") + end := time.Unix(3, 0) + got.Outcome, got.Ended, got.Why = seat.PipelineOutcomePassed, &end, "" + got.Steps = []seat.StepResult{{Module: "app", Step: seat.StepResultStepBuild, Status: seat.StepResultStatusRequired, Outcome: seat.StepResultOutcomePassed}} + set := func(p seat.Pipeline) { + e := store["main.9"] + e.p = p + store["main.9"] = e + } + set(got) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "x"}); err != nil || a.Pipeline != "main.9" || len(*acts) != 2 || len(added) != 1 { + t.Errorf("a start of app, delivered by main.9, = %+v, %v with %d acts and %d mover-added; want main.9, no act, nothing said", a, err, len(*acts), len(added)) + } + // lib, which the ended head does not move, reopens it as a mover said by mover-added with the caller. + got.Movers = got.Movers[:1] + set(got) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"lib"}, Why: "lib reopens main.9"}); err != nil || a.Pipeline != "main.9" { + t.Fatalf("start of lib, which ended main.9 does not move, = %+v, %v", a, err) + } + if got, _, _ = store.Get("main.9"); got.Outcome != seat.PipelineOutcomeRunning || got.Ended != nil || !Moves(got, "lib") || len(added) != 2 || added[1].Module != "lib" || added[1].Caller != "operator" { + t.Errorf("main.9 is %s ended %v moving %+v, mover-added %+v; want it reopened with lib added by the caller", got.Outcome, got.Ended, got.Movers, added) + } + // A head that ended cancelled and left app unfinished (H-A-751): start of app reopens it with its group as place-unfinished + // does, said by mover-added with the caller. + first := time.Unix(1, 0) + got.Outcome, got.Ended, got.Steps, got.Started = seat.PipelineOutcomeCancelled, &end, nil, &first + set(got) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "app left unfinished"}); err != nil || a.Pipeline != "main.9" { + t.Fatalf("start of app, which cancelled main.9 left unfinished, = %+v, %v", a, err) + } + if got, _, _ = store.Get("main.9"); got.Outcome != seat.PipelineOutcomeRunning || got.Ended != nil || len(added) != 2 || Moves(got, "lib") || got.Started == nil || !got.Started.Equal(first) { + t.Errorf("main.9 is %s ended %v, mover-added %+v; want it reopened and no mover-added said for the reopen of a group already among its movers (H-A-755)", got.Outcome, got.Ended, added) + } + 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, p5.Revision = seat.PipelineOutcomeFailed, &end, 5 + store[pkey] = struct { p seat.Pipeline rev uint64 - }{p, 1} - if wrote, err := v.Hearer.Released(catalog.VersionReleasedEvent{Module: "app", Version: "0.1.2", Source: 7}, "main"); err != nil || wrote != 1 || - store["main.9.again.1"].p.Movers[0].Version != "0.1.2" { - t.Errorf("the release of app 0.1.2 wrote %d (%v), the again pipeline's mover %+v; want its version written", wrote, err, store["main.9.again.1"].p.Movers) + }{p5, 2} + revision = 5 + asked := len(asks.asks) + if a, err = v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "its lint failed"}); err != nil || a.Pipeline != pkey { + t.Fatalf("start of app whose step failed in %s = %+v, %v", pkey, a, err) } - if _, err := v.Start("operator", seat.StartInput{Branch: "main", Modules: []string{"app"}, Why: "x"}); err == nil || !strings.Contains(err.Error(), "main.9.again.1") { - t.Errorf("a start of app after main.9.again.1 passed = %v; want refused naming it", err) + 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) + } + for k := range made { + if strings.Contains(k, ".again.") { + t.Errorf("a start keyed %s", k) + } + } + if len(*acts) != 5 { + t.Errorf("hand acts %v, want the five starts that did something recorded", *acts) } 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/widens.go b/modules/mesh-delivery-pipeline/internal/pipeline/widens.go index 4f73cb0ae..7bf7a4725 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/widens.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/widens.go @@ -105,9 +105,13 @@ func (r *endReads) widens(p seat.Pipeline, module string) []seat.Widening { if err != nil { return could("mesh-catalog", fmt.Sprintf("the candidate's revision %d is not read: %v", p.Revision, err)) } - newest, err := r.revision(p.Branch, 0) - if err != nil { - return could("mesh-catalog", fmt.Sprintf("the branch's newest revision is not read: %v", 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 + 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)) + } } var out []seat.Widening for _, s := range servingSeats(p) { diff --git a/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go b/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go index b146b7aac..b04caf628 100644 --- a/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go +++ b/modules/mesh-delivery-pipeline/internal/pipeline/widens_test.go @@ -27,7 +27,7 @@ func halfOf(rev int64, es ...catalog.CatalogEntry) Half { // (the runner, the catalog, each step's seat, the node-engine) by fingerprint, an acting rule gained or matching more, a // credential named that was not, and the grants the grants part adds; each is said by name, a grants part that does not answer says // `could not run` and nothing is refused (design 47 G §71, §275, §441, A-207, A-215, A-220). -func TestWidensIsTheCandidateAgainstTheNewest(t *testing.T) { +func TestWidensIsTheCandidateAgainstItsBase(t *testing.T) { p := seat.Pipeline{Pipeline: "main.8.app", Branch: "main", Source: 31, Revision: 8, Steps: []seat.StepResult{{Module: "app", Step: "unit", Seat: "node-build-go"}, {Module: "app", Step: "lint", Seat: "node-build-go"}, {Module: "app", Step: "approval"}}, Movers: []seat.Mover{{Module: "app"}}} holders := map[string]string{seat.Seat: "runner", catalog.Seat: "indexer", "node-build-go": "build-go", "node-engine": "host"} @@ -65,13 +65,16 @@ func TestWidensIsTheCandidateAgainstTheNewest(t *testing.T) { for _, c := range cases { w := &Widener{ Revision: func(_ string, rev int64) (Half, error) { - if rev == 0 { + // The base of revision 8 is revision 9 here (design 47 H2 H-A-582): never the branch's newest, revision 0. + if rev == 9 { return newest, nil } if rev != 8 { - t.Errorf("%s: the candidate asked as revision %d", c.name, rev) + t.Errorf("%s: revision %d asked, want the candidate 8 or its base 9", c.name, rev) } - return c.cand, nil + cand := c.cand + cand.Base = 9 + return cand, nil }, Holder: func(s string) (string, error) { return holders[s], nil }, GrantsFor: func(string, int64) (meshgrants.GrantsFor, error) { return c.grants, c.grantsErr }, @@ -98,6 +101,12 @@ func TestAnEndKeepsEachMoversWidens(t *testing.T) { if !h.endPipeline(&p, time.Unix(1, 0), h.widensReads()) || len(p.Movers[0].Widens) != 1 || p.Movers[0].Widens[0].Name != "app s v" || p.Movers[1].Widens[0].Name != "lib s v" { t.Errorf("the ended movers = %+v", p.Movers) } + // design 47 H2 H-A-595 (AC-P6b): a carried mover says its first pipeline's widens, never computed again. + c := seat.Pipeline{Outcome: seat.PipelineOutcomeRunning, Movers: []seat.Mover{{Module: "app", Widens: []seat.Widening{{What: seat.WideningWhatGrant, Name: "first"}}}}, + Steps: []seat.StepResult{{Module: "app", Step: "build", Outcome: "passed"}}} + 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.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 { diff --git a/modules/mesh-delivery-pipeline/manifest_test.go b/modules/mesh-delivery-pipeline/manifest_test.go index b8b2d835f..d9af51e88 100644 --- a/modules/mesh-delivery-pipeline/manifest_test.go +++ b/modules/mesh-delivery-pipeline/manifest_test.go @@ -234,7 +234,7 @@ func runSettingsOf(raw []byte) bool { // program alike, from the words the node-engine composes: no file of its own. // design 47 H2 §775: the kept-call form's pace, read by mesh-sdk at the process's and the bundle's start; §777: // ask-silent-bound goes. - words := map[string]string{"stalled-bound": "5m", "kept-call-pace-first": "1s", "kept-call-pace-max": "30s"} + words := map[string]string{"stalled-bound": "5m", "answer-bound": "32768", "kept-call-pace-first": "1s", "kept-call-pace-max": "30s"} for key, def := range words { if m.Config[key]["type"] != "string" || m.Config[key]["default"] != def || m.Config[key]["runtime"] != true { return false diff --git a/modules/mesh-delivery-pipeline/module.json b/modules/mesh-delivery-pipeline/module.json index 5a1801ced..2066abfbd 100644 --- a/modules/mesh-delivery-pipeline/module.json +++ b/modules/mesh-delivery-pipeline/module.json @@ -169,10 +169,17 @@ }, "ask-unanswered-bound": { "type": "string", - "description": "how long an ask the runner puts on a seat, but a test run's, may go without its holder's first word (an ask-taken, a step progress or the step's end) before it is asked once more, and as long again before its step ends could not run, a Go duration such as 10m (design 47 H H-A-235, H-A-238).", + "description": "how long an ask the runner puts on a seat, but a test run's, may go without its holder's first word (an ask-taken, a step progress or the step's end) before it is asked once more, and as long again before its step ends could not run, a Go duration such as 10m (design 47 H H-A-235, H-A-238). The assigner's setting reads-bound is kept below it, so a run's step ends with the assigner's words; one set above it has the runner's bound end the step with its own (design 47 H2 H-A-708 (3)).", "trusted": false, "default": "10m" }, + "answer-bound": { + "type": "string", + "description": "the most bytes the runner's show and stands answer when a call names no bound, a whole number from 4096 to 786432; a longer answer is capped, answers next and is read from it (design 47 H2 H-A-709 (2), section 781).", + "trusted": false, + "runtime": true, + "default": "32768" + }, "stalled-bound": { "type": "string", "description": "how long a running pipeline may have nothing open and nothing newly placed, or a step's ask stay untaken, before the runner's health names it, a Go duration such as 5m (design 47 H2 sections 778, 790).",