I4: a release re-pins once, at its reservation

The builder's version-reserved writes the series' numbered version with the
contents of the module's entry commit, so acceptedSeries and releasedPins pin
it; the indexer keeps each reservation in heard (reserved.<revision>.<module>,
reserved-keep) and gathers a revision's reservations until its pipeline's
start, its first step-ended or the expiry of settling.<revision>
(reserved-settle), then keeps one re-pin revision of that branch. The release's
package-published moves no fingerprint; a pipeline-ended not passed withdraws
its reservations to the newest released version.

Builds: design 47 H2 §805; H-A-418, H-A-420, H-A-424, H-A-436
This commit is contained in:
2026-11-22 01:35:56 +01:00
parent 7ed668fa53
commit 40c2870a71
12 changed files with 669 additions and 17 deletions
@@ -92,6 +92,16 @@ func (s awaitedStore) Create(ctx context.Context, key string, value []byte) erro
return st.Create(ctx, key, value)
}
// CreateTTL creates key living ttl: the state is declared key-ttl (index.TTLStore, design 47 H2 §805).
func (s awaitedStore) CreateTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error {
st, err := s.store()
if err != nil {
return err
}
_, err = st.kv.Create(ctx, key, value, jetstream.KeyTTL(ttl))
return conflict(err)
}
func (s awaitedStore) Update(ctx context.Context, key string, value []byte, revision uint64) error {
st, err := s.store()
if err != nil {
@@ -346,6 +356,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
Named: namedVia(calls.Call), Trunk: trunkVia(calls.Call), BranchHead: branchHeadVia(calls.Call), Contains: containsVia(calls.Call), Read: readVia(calls.Call),
Packages: awaitedStore{b: packages, js: js, name: index.Bucket(cred.Module, index.PackagesState)}, Files: filesVia(calls.Call), GoSum: goSumVia(calls.Call), GoMod: goModVia(calls.Call),
Heard: heardStore, Runs: awaitedStore{b: runs}, Graph: graph,
// How long a reservation is kept and how long its gathering waits at most (design 47 H2 §805, H-A-424).
ReservedKeep: reservedSetting("reserved-keep", index.DefaultReservedKeep, logger.Printf),
ReservedSettle: reservedSetting("reserved-settle", index.DefaultReservedSettle, logger.Printf),
SeatDefinitions: awaitedStore{b: seatDefs}, ReadFile: readFileVia(calls.Call), SaySeatDefinition: saySeats,
Revisions: revisions, EntryIndex: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.EntryIndexState), "no entry is found by its fingerprint", logger.Printf)}, // Message a kept call: a read, called again through a transport fault (ADR 0668 §1)
// Each catalog revision may bring another holder of a build seat: the build modules are found again (buildmodules.go).
@@ -571,6 +584,36 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
if err := hub.Handle(meshbuilds.SubjectPackagePublished, func(m jetstream.Msg) { heardPackagePublished(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
// A release re-pins once, at its reservation (design 47 H2 §805): the builder's version-reserved, and the step-ended of
// a pipeline whose reservations settle then.
if err := hub.Handle(meshbuilds.SubjectVersionReserved, func(m jetstream.Msg) { heardVersionReserved(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
if err := hub.Handle(meshbuilds.SubjectStepEndedAll, func(m jetstream.Msg) { heardBuildStepEnded(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
// A gathering's key settling.<revision> settles it when its time to live ends: the watch of heard hands the bus's
// expiry marker over (H-A-436); a gathering a restart cut settles once heard is bound.
heardStore.b.Ready(func(kv jetstream.KeyValue) {
eachHeard := func(e jetstream.KeyValueEntry) {
if e.Operation() != jetstream.KeyValuePurge {
return
}
if err := ix.Expired(ctx, e.Key()); err != nil {
logger.Printf("versions: %s expired and its reservations are not re-pinned: %v", e.Key(), err)
}
}
if hw, err := settle(ctx, kv, eachHeard); err != nil {
process.NotWatched(logger.Printf, index.Bucket(cred.Module, index.HeardState), err, "no gathering of reservations settles at its bound until the indexer starts again")
} else {
go func() { errs <- follow(ctx, hw, eachHeard) }()
}
go func() {
if err := ix.GatherKept(ctx); err != nil {
logger.Printf("versions: the reservations kept before the start are not settled again: %v", err)
}
}()
})
if err := hub.Handle(meshbuilds.SubjectToolchainAgreed, func(m jetstream.Msg) { heardToolchainAgreed(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
@@ -641,3 +684,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return err
}
}
// reservedSetting is the setting key read as a duration (stdio.SettingDuration); one that does not read is said and takes def.
func reservedSetting(key string, def time.Duration, logf func(string, ...any)) time.Duration {
d, err := stdio.SettingDuration(key, def)
if err != nil {
logf("%v: %s is taken", err, def)
return def
}
return d
}
@@ -98,6 +98,38 @@ func heardPackagePublished(ctx context.Context, ix *index.Indexer, m jetstream.M
_ = m.Ack()
}
// heardVersionReserved takes one version-reserved of the seat mesh-builds in (design 47 H2 §805): one that does not decode
// is said and acknowledged; one that cannot be kept is left, so the bus gives it again.
func heardVersionReserved(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e meshbuilds.VersionReservedEvent
if err := json.Unmarshal(m.Data(), &e); err != nil {
logf("%s holds what is no version-reserved, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.HearVersionReserved(ctx, e); err != nil {
logf("versions: the version-reserved of %s %s could not be kept, so the bus gives it again: %v", e.Artifact, e.Version, err)
leftForBus(m, fmt.Sprintf("the version-reserved of %s %s", e.Artifact, e.Version), err, logf)
return
}
_ = m.Ack()
}
// heardBuildStepEnded settles the reservations of the step's pipeline, if they gather (design 47 H2 §805, H-A-424 (1)):
// the builder reserves every mover before it asks the first build. A settle that fails is said; its bound settles again.
func heardBuildStepEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e meshbuilds.StepEnded
if err := json.Unmarshal(m.Data(), &e); err != nil {
logf("%s holds what is no step-ended, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.Settle(ctx, e.Pipeline); err != nil {
logf("versions: the reservations of %s are not re-pinned at its step-ended: %v", e.Pipeline, err)
}
_ = m.Ack()
}
// heardToolchainAgreed keeps the newest toolchain-agreed of its language (A-68); one that does not decode is said and
// acknowledged, one that cannot be kept is left, so the bus gives it again.
func heardToolchainAgreed(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
@@ -192,6 +192,10 @@ type Indexer struct {
runMu sync.Mutex // one run event at a time (runcandidates.go)
heldFull atomic.Bool // a take-in is held because the catalog store is full: room is said when it has room again (RoomAgain)
pendingMu sync.Mutex // one take-in step at a time: a merge, a group's end, the start and a hand act (pending.go)
// ReservedKeep is how long a reservation is kept in the state heard, and ReservedSettle how long after a revision's
// first reservation its gathering settles at the latest: the settings reserved-keep and reserved-settle (design 47 H2
// §805, H-A-424); zero takes the default.
ReservedKeep, ReservedSettle time.Duration
}
func (ix *Indexer) logf(format string, args ...any) {
@@ -178,3 +178,12 @@ func contentsOfPublished(p meshcatalog.PackagesByModuleValue) *meshcatalog.Packa
}
return c
}
// publishedOfNumbered is a series' numbered version's contents as the value of a per-module packages key (the same fields).
func publishedOfNumbered(c meshcatalog.PackagesByPackageSeriesValueNumberedContents) meshcatalog.PackagesByModuleValue {
p := meshcatalog.PackagesByModuleValue{At: c.At, Commit: c.Commit, Dir: c.Dir, Module: c.Module, Repository: c.Repository, Requires: c.Requires, V: c.V}
for _, d := range c.Packages {
p.Packages = append(p.Packages, meshcatalog.PackagesByModuleValuePackagesItem{Package: d.Package, Digest: d.Digest})
}
return p
}
@@ -83,7 +83,14 @@ func (ix *Indexer) HeardPins(ctx context.Context, started *runner.PipelineStarte
}
switch {
case started != nil && started.Revision > 0 && started.Pipeline != "":
return ix.pin(ctx, PinKey(started.Branch, started.Revision), PipelineRecord(started.Pipeline))
if err := ix.pin(ctx, PinKey(started.Branch, started.Revision), PipelineRecord(started.Pipeline)); err != nil {
return err
}
// The reservations of the pipeline's revision settle at its start, if they gather (design 47 H2 §805, H-A-424 (1)).
if err := ix.Settle(ctx, BranchObject(started.Branch, started.Revision)); err != nil {
ix.logf("versions: the reservations of %s are not re-pinned at its pipeline-started: %v", BranchObject(started.Branch, started.Revision), err)
}
return nil
case ended != nil && ended.Revision > 0 && ended.Pipeline != "":
// A passed pipeline's release pins the revision its movers' entries live in, before the pipeline's own pin is freed,
// one record per mover that released a version in it (H-A-168, H-A-170, H-A-173); a mover that released none, and a run
@@ -98,6 +105,12 @@ func (ix *Indexer) HeardPins(ctx context.Context, started *runner.PipelineStarte
}
}
}
// A pipeline that did not pass withdraws the reservations its revision holds (design 47 H2 §805, H-A-418 (1)).
if ended.Outcome != runner.PipelineEndedOutcomePassed {
if err := ix.Withdraw(ctx, ended.Branch, ended.Revision); err != nil {
return fmt.Errorf("the reservations of %s are not withdrawn: %w", BranchObject(ended.Branch, ended.Revision), err)
}
}
record := PipelineRecord(ended.Pipeline)
if err := ix.unpin(ctx, PinKey(ended.Branch, ended.Revision), record); err != nil {
return err
@@ -2,11 +2,13 @@ package index
import (
"context"
"fmt"
"slices"
"strings"
"testing"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"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"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-sdk/go/catalogue"
@@ -97,4 +99,65 @@ func TestAReleaseRepinsAnEntryNamingItsPackageWithNoPin(t *testing.T) {
said[0].CallKind != meshcatalog.CatalogRevisionEventCallKindRelease || said[1].Module != "mesh-sdk" || said[1].Version != "0.1.27" {
t.Errorf("said %+v, want catalog-revision of each branch with the release's call", said)
}
// Design 47 H2 §805, H-A-418, H-A-420, H-A-424, H-A-436: a pipeline reserving twenty packages of mesh-sdk in main's
// revision 2 keeps one re-pin revision of main when its gathering settles, at its first step-ended; its release then
// keeps none on main, and a pipeline that did not pass withdraws its reservations back to the newest released version.
ix.Files = func(_ context.Context, _, _ string, dirs []string) (map[string]map[string]string, error) {
out := map[string]map[string]string{}
for _, d := range dirs {
out[d] = map[string]string{"go.mod": strings.Repeat("d", 40), "sdk.go": strings.Repeat("e", 40)}
}
return out, nil
}
heard := newMem()
ix.Heard = heard
revision := BranchObject("main", 2)
newest := func() int64 {
rev, _, _, err := readNewestOf(ctx, ix.Revisions, "main")
if err != nil {
t.Fatal(err)
}
return rev.Revision
}
for i := range 20 {
e := meshbuilds.VersionReservedEvent{Module: "mesh-sdk", Artifact: fmt.Sprintf("mesh-sdk:p%d", i), Path: "mesh-sdk/go", Version: "0.1.28", Revision: revision}
if err := ix.HearVersionReserved(ctx, e); err != nil {
t.Fatal(err)
}
}
if _, _, open, _ := heard.Get(ctx, SettlingKey(revision)); !open || newest() != 2 {
t.Fatalf("twenty reservations: gathering open %v, main's newest %d, want open and no revision kept before it settles", open, newest())
}
if err := ix.Settle(ctx, revision); err != nil || newest() != 3 {
t.Fatalf("the gathering settled (%v) keeping main's newest %d, want one re-pin revision, 3", err, newest())
}
if now, _ := moduleOf(t, mods, "g"); now.Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.28" {
t.Errorf("g after the reservations is pinned %v, want v0.1.28", now.Packages)
}
if err := ix.Settle(ctx, revision); err != nil || newest() != 3 {
t.Errorf("a second step-ended settled (%v) keeping main's newest %d, want still 3", err, newest())
}
if _, err := ix.HearVersion(ctx, HeardVersion{Package: "mesh-sdk/go", GoModule: "git.novox.be/novox/mesh-sdk/go", Version: "0.1.28", Commit: strings.Repeat("1", 40), Published: true}); err != nil {
t.Fatal(err)
}
if _, err := ix.Repin(ctx, "mesh-sdk", "0.1.28"); err != nil || newest() != 3 {
t.Errorf("the release of the reserved 0.1.28 re-pinned (%v) keeping main's newest %d, want no revision more", err, newest())
}
next := BranchObject("main", 3)
if err := ix.HearVersionReserved(ctx, meshbuilds.VersionReservedEvent{Module: "mesh-sdk", Artifact: "mesh-sdk:p0", Path: "mesh-sdk/go", Version: "0.1.29", Revision: next}); err != nil {
t.Fatal(err)
}
if err := ix.Settle(ctx, next); err != nil || newest() != 4 {
t.Fatalf("the reservation of 0.1.29 settled (%v) keeping main's newest %d, want 4", err, newest())
}
if err := ix.Withdraw(ctx, "main", 3); err != nil || newest() != 5 {
t.Fatalf("the withdrawal (%v) kept main's newest %d, want 5", err, newest())
}
if now, _ := moduleOf(t, mods, "g"); now.Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.28" {
t.Errorf("g after the withdrawal is pinned %v, want the newest released v0.1.28", now.Packages)
}
if _, _, kept, _ := heard.Get(ctx, ReservedKey(next, "mesh-sdk")); kept {
t.Errorf("the withdrawn reservation is still kept")
}
}
@@ -0,0 +1,432 @@
package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
"time"
"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/keys"
)
// A release re-pins once, at its reservation (design 47 H2 §805; H-A-418, H-A-420, H-A-424). The builder says
// version-reserved when it reserves a package's number, naming the revision `<branch>.<n>` its pipeline runs. The indexer
// writes the series' numbered version with the contents read at the commit of the module's entry in that revision, so
// acceptedSeries and releasedPins pin it, and keeps the reservation in its state heard under
// `reserved.<revision>.<module>`, each key living reserved-keep. It gathers a pipeline's reservations per revision and
// writes one re-pin revision of that revision's branch when the gathering settles: at the first pipeline-started or
// step-ended of that pipeline heard after them, or at the expiry of the key settling.<revision>, written reserved-settle
// after the first. The release's package-published then
// moves no fingerprint. A pipeline-ended not passed whose revision holds reservations withdraws them: the series'
// numbered goes back to its newest released version and the importers are re-pinned to it.
// ReservedPrefix begins every key of the state heard holding a revision's reservations of one module.
const ReservedPrefix = "reserved."
// The defaults of the settings reserved-keep and reserved-settle (H-A-424 (1), (2)).
const (
DefaultReservedKeep = 24 * time.Hour
DefaultReservedSettle = 30 * time.Second
)
// ReservedKey is the key of module's reservations in revision, `reserved.<revision>.<module>`, the module escaped as a
// key's name is.
func ReservedKey(revision, module string) string {
return ReservedPrefix + revision + "." + keys.EscapeName(module)
}
// Reservation is one version-reserved as the indexer keeps it.
type Reservation struct {
Artifact string `json:"artifact"`
Path string `json:"path"`
Version string `json:"version"`
Fingerprint string `json:"fingerprint,omitempty"`
}
// Reserved is the value of a reserved key: a module's reservations in one revision.
type Reserved struct {
V int `json:"v"`
Revision string `json:"revision"`
Module string `json:"module"`
Reservations []Reservation `json:"reservations"`
At time.Time `json:"at"`
}
// TTLStore is a Store that writes a new key with its own time to live (a state declared `key-ttl`).
type TTLStore interface {
CreateTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error
}
// SettlingPrefix begins the key of the state heard that holds a revision's gathering open, `settling.<revision>`, written
// with the key-ttl reserved-settle at its first reservation: its expiry, heard through the indexer's watch of heard
// (Expired), settles the gathering; the indexer holds no timer (ADR 0437 §8; H-A-436).
const SettlingPrefix = "settling."
// SettlingKey is the key holding revision's gathering open.
func SettlingKey(revision string) string { return SettlingPrefix + revision }
// HearVersionReserved takes one version-reserved in: the series' numbered version, the reservation kept and the revision's
// gathering begun. An error leaves the event for the bus to give again.
func (ix *Indexer) HearVersionReserved(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
if ix.Heard == nil {
return errors.New("the indexer keeps no state " + HeardState)
}
_, ok, err := ix.branchOfRevision(ctx, e.Revision)
if err != nil {
return err
}
if !ok {
ix.logf("versions: the version-reserved of %s %s names the revision %q, which is of no watched branch: left", e.Artifact, e.Version, e.Revision)
return nil
}
if err := ix.keepNumbered(ctx, e); err != nil {
return err
}
if err := ix.keepReservation(ctx, e); err != nil {
return err
}
ix.logf("versions: %s reserved %s %s in %s; its importers are re-pinned once the pipeline's reservations settle", e.Module, e.Path, e.Version, e.Revision)
return ix.gather(ctx, e.Revision)
}
// branchOfRevision is the watched branch (the trunk among them) whose revision name is revision, `<branch>.<n>`.
func (ix *Indexer) branchOfRevision(ctx context.Context, revision string) (string, bool, error) {
branches, err := ix.watchedBranches(ctx)
if err != nil {
return "", false, err
}
if !slices.Contains(branches, TrunkBranch) {
branches = append(branches, TrunkBranch)
}
for _, b := range branches {
if _, ok := BranchRevisionOf(b, revision); ok {
return b, true, nil
}
}
return "", false, nil
}
// seriesOfPath is the series key and value of the package path names in series: the key whose name or Go module is path.
func (ix *Indexer) seriesOfPath(ctx context.Context, path, series string) (string, SeriesPackage, bool) {
all := ix.SeriesAll(ctx)
for _, key := range slices.Sorted(maps.Keys(all)) {
if s := all[key]; s.Series == series && (s.Name == path || s.GoModule == path) {
return key, s, true
}
}
return SeriesKey(path, series), SeriesPackage{}, false
}
// keepNumbered writes the reserved version as its series' numbered one, with the contents read at the commit of the
// module's entry in the event's revision (H-A-418 (2)); an older version than the numbered held changes nothing.
func (ix *Indexer) keepNumbered(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
series, ok := SeriesOf(e.Version)
if ix.Packages == nil || e.Path == "" || !ok {
return nil
}
key, s, _ := ix.seriesOfPath(ctx, e.Path, series)
v := SeriesVersion{Version: strings.TrimPrefix(e.Version, "v"), Fingerprint: e.Fingerprint}
if ix.Revisions != nil {
_, entries, err := ReadRevision(ctx, ix.Revisions, e.Revision)
if err != nil {
return fmt.Errorf("the revision %s of %s's reservation: %w", e.Revision, e.Module, err)
}
if i := slices.IndexFunc(entries, func(x meshcatalog.CatalogEntry) bool { return x.Module == e.Module }); i >= 0 {
v.Commit = entries[i].Commit
if s.GoModule != "" && v.Commit != "" && ix.Files != nil {
got, err := ix.packagesAt(ctx, entries[i].Repository, v.Commit, []string{s.GoModule}, nil)
switch p, found := got[s.GoModule]; {
case err != nil:
ix.logf("versions: %s %s's contents at %.12s are not read, so its importers are not pinned to it before its publish: %v", e.Path, e.Version, v.Commit, err)
case !found:
ix.logf("versions: the forge's listing at %.12s holds no Go module %s, so %s's importers are not pinned to it before its publish", v.Commit, s.GoModule, e.Version)
default:
p.At = ptr(ix.now().UTC())
v.Contents = contentsOfPublished(p)
}
}
} else {
ix.logf("versions: the revision %s holds no entry of %s, so %s %s is numbered with no contents", e.Revision, e.Module, e.Path, e.Version)
}
}
return write(ctx, ix.Packages, key, func(value []byte, found bool) ([]byte, bool, error) {
held := SeriesPackage{V: keys.Version, Name: e.Path, Series: series}
if found {
if err := json.Unmarshal(value, &held); err != nil {
return nil, false, err
}
}
if n := held.Numbered; n != nil && (CompareVersions("v"+n.Version, "v"+v.Version) > 0 || n.Version == v.Version && n.Contents != nil) {
return nil, false, nil
}
held.Numbered = numberedOf(v)
held.At = ptr(ix.now())
next, err := json.Marshal(held)
return next, false, err
})
}
// keepReservation keeps e under its revision and module in the state heard, the key living reserved-keep: a module's
// further reservation in the revision is added to its key, which is written again with its time to live.
func (ix *Indexer) keepReservation(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
key := ReservedKey(e.Revision, e.Module)
r := Reservation{Artifact: e.Artifact, Path: e.Path, Version: e.Version, Fingerprint: e.Fingerprint}
for range writeTries {
value, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil {
return err
}
held := Reserved{V: keys.Version, Revision: e.Revision, Module: e.Module, At: ix.now().UTC()}
if found {
if err := json.Unmarshal(value, &held); err != nil {
return fmt.Errorf("heard.%s: %w", key, err)
}
if slices.Contains(held.Reservations, r) {
return nil
}
}
held.Reservations = append(held.Reservations, r)
data, err := json.Marshal(held)
if err != nil {
return err
}
if found {
if err := ix.Heard.Delete(ctx, key, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return err
}
}
err = ix.createTTL(ctx, key, data)
if errors.Is(err, ErrConflict) {
continue
}
return err
}
return fmt.Errorf("heard.%s: %w", key, ErrConflict)
}
// createTTL creates key in the state heard living reserved-keep (createTTLFor).
func (ix *Indexer) createTTL(ctx context.Context, key string, data []byte) error {
keep := ix.ReservedKeep
if keep <= 0 {
keep = DefaultReservedKeep
}
return ix.createTTLFor(ctx, key, data, keep)
}
// createTTLFor creates key in the state heard living ttl; a store that keeps no time to live per key keeps it with none,
// said.
func (ix *Indexer) createTTLFor(ctx context.Context, key string, data []byte, ttl time.Duration) error {
if st, ok := ix.Heard.(TTLStore); ok {
return st.CreateTTL(ctx, key, data, ttl)
}
ix.logf("versions: the state %s keeps no time to live per key here, so %s is kept with none", HeardState, key)
return ix.Heard.Create(ctx, key, data)
}
// reservedOf are the reservations revision holds, by module.
func (ix *Indexer) reservedOf(ctx context.Context, revision string) (map[string]Reserved, map[string]uint64, error) {
if ix.Heard == nil {
return nil, nil, nil
}
all, err := ix.Heard.Keys(ctx)
if err != nil {
return nil, nil, err
}
out, revs := map[string]Reserved{}, map[string]uint64{}
prefix := ReservedPrefix + revision + "."
for _, key := range all {
if !strings.HasPrefix(key, prefix) {
continue
}
value, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil {
return nil, nil, err
}
var r Reserved
if !found || json.Unmarshal(value, &r) != nil || r.Revision != revision {
continue
}
out[key], revs[key] = r, rev
}
return out, revs, nil
}
// gather begins revision's gathering, if none is open: the key settling.<revision>, living reserved-settle.
func (ix *Indexer) gather(ctx context.Context, revision string) error {
settle := ix.ReservedSettle
if settle <= 0 {
settle = DefaultReservedSettle
}
data, err := json.Marshal(map[string]any{"revision": revision, "at": ix.now().UTC()})
if err != nil {
return err
}
err = ix.createTTLFor(ctx, SettlingKey(revision), data, settle)
if errors.Is(err, ErrConflict) {
return nil // a gathering is open already
}
return err
}
// GatherKept settles, at the start, every revision the state heard holds reservations of whose gathering is not open any
// more: a settle cut by a restart is made then (one that moves nothing keeps no revision). An open one settles at its
// expiry or its pipeline's next word.
func (ix *Indexer) GatherKept(ctx context.Context) error {
if ix.Heard == nil {
return nil
}
all, err := ix.Heard.Keys(ctx)
if err != nil {
return err
}
revisions := map[string]bool{}
for _, key := range all {
if !strings.HasPrefix(key, ReservedPrefix) {
continue
}
value, _, found, err := ix.Heard.Get(ctx, key)
var r Reserved
if err != nil || !found || json.Unmarshal(value, &r) != nil || slices.Contains(all, SettlingKey(r.Revision)) {
continue
}
revisions[r.Revision] = true
}
var errs []error
for _, revision := range slices.Sorted(maps.Keys(revisions)) {
errs = append(errs, ix.settleNow(ctx, revision))
}
return errors.Join(errs...)
}
// Settle settles revision's gathering, if one is open (a pipeline-started or step-ended of its pipeline): its key goes, and
// every importer of the modules it reserved is re-pinned in one revision of its branch. None open settles nothing.
func (ix *Indexer) Settle(ctx context.Context, revision string) error {
if ix.Heard == nil {
return nil
}
key := SettlingKey(revision)
_, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil || !found {
return err
}
if err := ix.Heard.Delete(ctx, key, rev); errors.Is(err, ErrConflict) {
return nil // settled by another word, or by its expiry
} else if err != nil {
return err
}
return ix.settleNow(ctx, revision)
}
// Expired takes in a key of the state heard that its time to live ended, as the watch of heard hands it over: a
// gathering's key settles that gathering (H-A-436); any other key is passed over.
func (ix *Indexer) Expired(ctx context.Context, key string) error {
revision, ok := strings.CutPrefix(key, SettlingPrefix)
if !ok {
return nil
}
return ix.settleNow(ctx, revision)
}
// settleNow re-pins every importer of the modules revision reserved in one revision of its branch.
func (ix *Indexer) settleNow(ctx context.Context, revision string) error {
held, _, err := ix.reservedOf(ctx, revision)
if err != nil || len(held) == 0 {
return err
}
branch, ok, err := ix.branchOfRevision(ctx, revision)
if err != nil || !ok {
return err
}
modules := modulesOf(held)
_, err = ix.repinModules(ctx, branch, modules, reservedCall(revision, len(modules), false))
return err
}
// Withdraw takes a pipeline-ended not passed of branch's revision in: each reservation the revision holds is withdrawn, its
// series' numbered set back to the newest released version, its importers re-pinned to that, and its key deleted.
func (ix *Indexer) Withdraw(ctx context.Context, branch string, revision int64) error {
if ix.Heard == nil {
return nil
}
name := BranchObject(branch, revision)
if _, rev, found, err := ix.Heard.Get(ctx, SettlingKey(name)); err == nil && found {
_ = ix.Heard.Delete(ctx, SettlingKey(name), rev) // the gathering is withdrawn with it
}
held, revs, err := ix.reservedOf(ctx, name)
if err != nil || len(held) == 0 {
return err
}
for _, r := range held {
for _, one := range r.Reservations {
if err := ix.withdrawNumbered(ctx, one); err != nil {
return err
}
}
}
modules := modulesOf(held)
if _, err := ix.repinModules(ctx, branch, modules, reservedCall(name, len(modules), true)); err != nil {
return err
}
for key, rev := range revs {
if err := ix.Heard.Delete(ctx, key, rev); err != nil && !errors.Is(err, ErrConflict) {
return err
}
}
ix.logf("versions: the %d reservations of %s are withdrawn, their importers re-pinned to the newest released versions", len(held), name)
return nil
}
// withdrawNumbered sets the series' numbered version back to its newest released one while it is the version r reserved.
func (ix *Indexer) withdrawNumbered(ctx context.Context, r Reservation) error {
series, ok := SeriesOf(r.Version)
if ix.Packages == nil || !ok {
return nil
}
key, _, found := ix.seriesOfPath(ctx, r.Path, series)
if !found {
return nil
}
return write(ctx, ix.Packages, key, func(value []byte, found bool) ([]byte, bool, error) {
var s SeriesPackage
if !found || json.Unmarshal(value, &s) != nil || s.Numbered == nil || s.Numbered.Version != strings.TrimPrefix(r.Version, "v") {
return nil, false, nil
}
s.Numbered = nil
if s.Newest != nil {
s.Numbered = numberedOf(*s.Newest)
}
s.At = ptr(ix.now())
next, err := json.Marshal(s)
return next, false, err
})
}
// modulesOf are the modules of a revision's reservations, sorted.
func modulesOf(held map[string]Reserved) []string {
var out []string
for _, r := range held {
if !slices.Contains(out, r.Module) {
out = append(out, r.Module)
}
}
slices.Sort(out)
return out
}
// reservedCall is the call of the re-pin revision of a revision's reservations: a release's re-pin, made at its reservation
// (§805), or at their withdrawal.
func reservedCall(revision string, modules int, withdrawn bool) revisionCall {
call := fmt.Sprintf("release of %s's %d reserved modules", revision, modules)
if withdrawn {
call = fmt.Sprintf("release of %s's %d reserved modules withdrawn", revision, modules)
}
return revisionCall{Call: call, Kind: meshcatalog.CatalogRevisionCallKindRelease}
}
@@ -177,7 +177,8 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
var pins sdkstep.PackageVersions
for _, key := range slices.Sorted(maps.Keys(series)) {
s := series[key]
if s.GoModule == "" || s.Newest == nil || s.Newest.Contents == nil || m.AcceptedSeries(s.Name) != s.Series {
pinned := pinnedVersion(s)
if s.GoModule == "" || pinned == nil || pinned.Contents == nil || m.AcceptedSeries(s.Name) != s.Series {
continue
}
if repo, _, ok := trunk.PackageRepository(s.GoModule); !ok || trunk.SameRepository(repo, repository) {
@@ -186,8 +187,8 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
if out == nil {
out, pins = maps.Clone(published), sdkstep.PackageVersions{}
}
p := publishedOfContents(*s.Newest.Contents)
version := "v" + s.Newest.Version
p := publishedOfContents(*pinned.Contents)
version := "v" + pinned.Version
p.Commit = version
out[s.GoModule], pins[s.GoModule] = p, version
}
@@ -197,6 +198,17 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
return out, pins
}
// pinnedVersion is the version of a series its users are pinned to: its numbered one when a reservation wrote it with its
// contents and it is newer than the newest released (design 47 H2 §805, H-A-418 (2), H-A-424 (4)), else the newest; nil
// for none.
func pinnedVersion(s SeriesPackage) *SeriesVersion {
if n := s.Numbered; n != nil && n.Contents != nil && (s.Newest == nil || CompareVersions("v"+s.Newest.Version, "v"+n.Version) < 0) {
p := publishedOfNumbered(*n.Contents)
return &SeriesVersion{Version: n.Version, Commit: n.Commit, Digest: n.Digest, Fingerprint: n.Fingerprint, Contents: contentsOfPublished(p)}
}
return s.Newest
}
// KeepPackageNames writes, at a trunk merge, each package artifact's name in its own ecosystem into its series key
// (design 32): a Go package's module path from the go.mod under its paths at the merge commit, a TypeScript package's
// package.json name, each read through the forge. The key keeps what it held and gains the name and the module and
@@ -645,10 +645,16 @@ func (ix *Indexer) Repin(ctx context.Context, module, version string) (int, erro
return named, nil
}
// repinBranch re-pins branch's importers of module at version: the trunk in place, another branch as a dry run over its
// revision view, whose scratch goes once it is kept (design 47 H2 §804). It answers how many modules it named.
// repinBranch re-pins branch's importers of module at version (repinModules).
func (ix *Indexer) repinBranch(ctx context.Context, branch, module, version string) (int, error) {
x, call := ix, releaseCall(module, version)
return ix.repinModules(ctx, branch, []string{module}, releaseCall(module, version))
}
// repinModules re-pins branch's importers of modules in one revision kept with call: the trunk in place, another branch
// as a dry run over its revision view, whose scratch goes once it is kept (design 47 H2 §804, §805). It answers how many
// modules it named.
func (ix *Indexer) repinModules(ctx context.Context, branch string, modules []string, call revisionCall) (int, error) {
x := ix
if !isTrunkBranch(branch) {
view, nodes, _, err := BranchView(ctx, ix.Revisions, branch)
if err != nil {
@@ -660,12 +666,19 @@ func (ix *Indexer) repinBranch(ctx context.Context, branch, module, version stri
d.ix.Logf = func(format string, args ...any) { ix.logf("re-pin of "+branch+": "+format, args...) }
x = d.ix
}
only, err := x.repinned(ctx, module)
if err != nil || len(only) == 0 {
return 0, err
only := map[string]bool{}
for _, module := range modules {
some, err := x.repinned(ctx, module)
if err != nil {
return 0, err
}
maps.Copy(only, some)
}
if len(only) == 0 {
return 0, nil
}
x.recompute.Lock()
err = x.recomputeLocked(ctx, nil, nil, "", only)
err := x.recomputeLocked(ctx, nil, nil, "", only)
x.recompute.Unlock()
if err != nil {
return len(only), err
@@ -395,10 +395,11 @@ func releasedPins(versions sdkstep.PackageVersions, series map[string]SeriesPack
}
out[p] = ""
for _, s := range series {
if s.GoModule != p || s.Newest == nil || s.Series != m.AcceptedSeries(s.Name) {
pinned := pinnedVersion(s)
if s.GoModule != p || pinned == nil || s.Series != m.AcceptedSeries(s.Name) {
continue
}
v := strings.TrimPrefix(s.Newest.Version, "v")
v := strings.TrimPrefix(pinned.Version, "v")
if _, ok := versionParts(v); ok && (out[p] == "" || compareVersions(v, strings.TrimPrefix(out[p], "v")) > 0) {
out[p] = "v" + v
}
@@ -72,6 +72,7 @@ type manifest struct {
Scope string `json:"scope"`
Serves []string `json:"serves"`
} `json:"claims"`
Config map[string]any `json:"config"` // the settings (design 47 H2 §805)
Tools []string `json:"tools"`
Emits []string `json:"emits"`
Consumes []string `json:"consumes"`
@@ -133,8 +134,9 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
if !slices.Equal(m.Uses, []string{"operator-channel"}) || !slices.Contains(m.Invokes, "seat:mesh-module-assigner.assignments") || !slices.Contains(m.Invokes, "seat:mesh-module-assigner.placement") {
t.Errorf("uses = %v, invokes = %v, want the seat operator-channel used and seat:mesh-module-assigner.assignments invoked", m.Uses, m.Invokes)
}
// 1126 note 76: heard keeps the last 64 FORGE messages the indexer handled, for indexer_heard.
if want := []state{{Name: "candidates", History: 10}, {Name: "heard", History: 64}, {Name: "manifests", History: 1}, {Name: "predefined", History: 5}, {Name: "taken", History: 1}, {Name: "takeins", History: 1}, {Name: "oldsections", History: 1}, {Name: index.RunsState, History: 1}, {Name: index.PackagesState, History: index.PackagesHistory},
// 1126 note 76: heard keeps the last 64 FORGE messages the indexer handled, for indexer_heard; 8 MiB, each reservation
// and each gathering of them a key of its own time to live (design 47 H2 §805, H-A-420 (3), H-A-436).
if want := []state{{Name: "candidates", History: 10}, {Name: "heard", History: 64, MaxMiB: 8, KeyTTL: true}, {Name: "manifests", History: 1}, {Name: "predefined", History: 5}, {Name: "taken", History: 1}, {Name: "takeins", History: 1}, {Name: "oldsections", History: 1}, {Name: index.RunsState, History: 1}, {Name: index.PackagesState, History: index.PackagesHistory},
{Name: views.MarksState, History: 1}, {Name: index.FindingsState, History: 5}, {Name: views.StatusState, History: 1},
{Name: index.RequirementsState, History: 5}, {Name: index.SeatDefinitionsState, History: 5},
{Name: index.EntryIndexState, History: 1, MaxMiB: 8}, {Name: index.NamedState, History: 1, MaxMiB: 4}, // design 47 G §695
@@ -173,7 +175,7 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
// "Reads FORGE" is a consumes of the indexer's stream: the broker grants only buckets by reads (mesh-control
// internal/broker/state.go:62-93).
// The registry seats' published fill each (§413: no consume of version.numbered) package's series (DLV-I5, design 51 *The versions*).
if want := []string{"go-package-registry.published", "mesh-build-go.toolchain.reported", "mesh-build-node.toolchain.reported", "mesh-builds.package-published", "mesh-builds.toolchain-agreed", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.room", "mesh-conditions.findings-asked",
if want := []string{"go-package-registry.published", "mesh-build-go.toolchain.reported", "mesh-build-node.toolchain.reported", "mesh-builds.package-published", "mesh-builds.step-ended", "mesh-builds.toolchain-agreed", "mesh-builds.version-reserved", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.room", "mesh-conditions.findings-asked",
"mesh-delivery.source-moved", "mesh-pipeline-runner.pipeline-ended", "mesh-pipeline-runner.pipeline-started", "mesh-pipeline-runner.run-started", "mesh-wants.pipeline-wanted", "mesh-wants.wait-ended", "mesh-wants.wanted", "node-build-go.step-ended", "node-engine.running", "npm-package-registry.published", "operator-channel.decided", "seat:mesh-module-assigner.views.assignments", "seat:mesh-module-assigner.views.seat-holders"}; !reflect.DeepEqual(sorted(m.Consumes), want) {
t.Errorf("consumes = %v, want %v", m.Consumes, want)
}
+19 -1
View File
@@ -82,6 +82,8 @@
"seat:mesh-module-assigner.views.assignments",
"seat:mesh-module-assigner.views.seat-holders",
"mesh-builds.package-published",
"mesh-builds.version-reserved",
"mesh-builds.step-ended",
"mesh-builds.toolchain-agreed",
"node-build-go.step-ended",
"mesh-wants.wait-ended",
@@ -98,9 +100,25 @@
"operator-channel.decided",
"npm-package-registry.published"
],
"config": {
"reserved-keep": {
"type": "string",
"description": "how long the indexer keeps a pipeline's reservation of a package's version in its state heard (reserved.<revision>.<module>), a Go duration (design 47 H2 §805, H-A-424 (2)).",
"trusted": false,
"default": "24h",
"runtime": true
},
"reserved-settle": {
"type": "string",
"description": "how long after a revision's first reservation its importers are re-pinned at the latest, when no pipeline-started or step-ended of its pipeline came first, a Go duration (design 47 H2 §805, H-A-424 (1), H-A-436).",
"trusted": false,
"default": "30s",
"runtime": true
}
},
"state": [
{ "name": "candidates", "history": 10 },
{ "name": "heard", "history": 64 },
{ "name": "heard", "history": 64, "max-mib": 8, "key-ttl": true },
{ "name": "manifests", "history": 1 },
{ "name": "predefined", "history": 5 },
{ "name": "taken", "history": 1 },