The node-engine held 1,707 top-level unit tests against the budget of 500 a module. Each unit test file with two or more tests now runs them as subtests of one test named for the file, each named as its function was, in the same order: every check is kept, and the check counts 383. Files with a TestMain, a re-run of a test by its name, or the integration tag are left. Four files of this branch's earlier commits are formatted. Builds: design 47 H2 §819; H-A-349 DQ-14
1082 lines
50 KiB
Go
1082 lines
50 KiB
Go
package link
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
|
|
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
|
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
|
sdkkeys "git.novox.be/novox/mesh-sdk/go/keys"
|
|
"github.com/novox/mesh-host/internal/compositions"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.novox.be/novox/mesh-sdk/go/busretry"
|
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
|
"github.com/nats-io/nats.go"
|
|
)
|
|
|
|
// What the node-engine writes beside its report: a module's have, and the node's own facts (novox/hq ADR 0429 §4,
|
|
// issue 1132).
|
|
|
|
// haveLink is a link with a bucket behind it that keeps each key's revision as the bus does.
|
|
type haveLink struct {
|
|
*quietLink
|
|
hmu sync.Mutex
|
|
kv map[string]haveEntry
|
|
sets []string // keys written, in order
|
|
events []string // "have <key>", in the order they happened
|
|
failing bool
|
|
binds int
|
|
setTries int
|
|
bindFails, bindStuck bool
|
|
// bindNoResponders fails that many binds with the bus's no responders, as while it reloads its accounts.
|
|
bindNoResponders int
|
|
// stated is what the tool runner's PING says of itself (Stater); statedErr is the runner not answering.
|
|
stated map[string]string
|
|
statedErr error
|
|
// readsSaid are the node seat's manifest-reads-changed events said on the link (ADR 0618 §4).
|
|
readsSaid []nodeengine.ManifestReadsChangedEvent
|
|
// sayFails fails that many of the node seat's says, as a publish past the bus's retry bound; said is every event said.
|
|
sayFails int
|
|
// sayFault is what a failed say answers; a bus answering a refusal when nil.
|
|
sayFault error
|
|
said []string
|
|
// onSaid are the events said on a subject of their own (running), by subject, in order.
|
|
onSaid []string
|
|
// asked are the subjects asked of the bus, records the router's records read as bucket and key.
|
|
asked, records []string
|
|
}
|
|
|
|
func (l *haveLink) SayEngineOn(subject string, body any) error {
|
|
raw, _ := json.Marshal(body)
|
|
l.hmu.Lock()
|
|
l.onSaid = append(l.onSaid, subject+" "+string(raw))
|
|
l.hmu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// saidOn is the events said on a subject, as the bus would carry them.
|
|
func (l *haveLink) saidOn(prefix string) []string {
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
var out []string
|
|
for _, e := range l.onSaid {
|
|
if strings.HasPrefix(e, prefix) {
|
|
out = append(out, e)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (l *haveLink) SayEngine(event string, body any) error {
|
|
l.hmu.Lock()
|
|
if l.sayFails > 0 {
|
|
l.sayFails--
|
|
fault := l.sayFault
|
|
l.hmu.Unlock()
|
|
if fault != nil {
|
|
return fault
|
|
}
|
|
return errors.New("nats: timeout")
|
|
}
|
|
l.said = append(l.said, event)
|
|
l.hmu.Unlock()
|
|
if e, ok := body.(nodeengine.ManifestReadsChangedEvent); ok && event == nodeengine.EventManifestReadsChanged {
|
|
l.hmu.Lock()
|
|
l.readsSaid = append(l.readsSaid, e)
|
|
l.hmu.Unlock()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (l *haveLink) Stated(context.Context, string, string) (map[string]string, error) {
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
return l.stated, l.statedErr
|
|
}
|
|
|
|
type haveEntry struct {
|
|
value []byte
|
|
rev uint64
|
|
}
|
|
|
|
// The link as the operator's asker and a tool bus: the seat list answers the holder of the seat operator-channel, and the
|
|
// router's records are read from the bucket named for it (design 47 G A-101).
|
|
func (l *haveLink) Ask(_ context.Context, subject string, _ []byte) ([]byte, error) {
|
|
l.hmu.Lock()
|
|
l.asked = append(l.asked, subject)
|
|
l.hmu.Unlock()
|
|
return []byte(`{"result":{"seats":[{"seat":"operator-channel","holders":[{"module":"the-router"}]}]}}`), nil
|
|
}
|
|
func (l *haveLink) PublishAsk(string, any, string) error { return nil }
|
|
func (l *haveLink) HearWarrants(string, func(oc.Warrant)) error { return nil }
|
|
func (l *haveLink) RouterRecord(bucket, key string) (*stdio.StateEntry, error) {
|
|
l.hmu.Lock()
|
|
l.records = append(l.records, bucket+" "+key)
|
|
l.hmu.Unlock()
|
|
return nil, nil
|
|
}
|
|
|
|
func newHaveLink() *haveLink { return &haveLink{quietLink: newQuietLink(), kv: map[string]haveEntry{}} }
|
|
|
|
func (l *haveLink) Health(context.Context, string, []byte) error { return nil }
|
|
|
|
func (l *haveLink) HaveBind(ctx context.Context) (HaveBucket, error) {
|
|
l.hmu.Lock()
|
|
l.binds++
|
|
stuck, refuse := l.bindStuck, l.bindFails
|
|
reloading := l.bindNoResponders > 0
|
|
if reloading {
|
|
l.bindNoResponders--
|
|
}
|
|
l.hmu.Unlock()
|
|
if reloading {
|
|
return nil, fmt.Errorf("binding node-engine_have: %w", nats.ErrNoResponders)
|
|
}
|
|
if stuck {
|
|
<-ctx.Done()
|
|
return nil, ctx.Err()
|
|
}
|
|
if refuse {
|
|
return nil, errors.New("no grant for the have bucket")
|
|
}
|
|
return l, nil
|
|
}
|
|
|
|
func (l *haveLink) Get(_ context.Context, key string) ([]byte, uint64, error) {
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
e, ok := l.kv[key]
|
|
if !ok {
|
|
return nil, 0, ErrHaveAbsent
|
|
}
|
|
return e.value, e.rev, nil
|
|
}
|
|
|
|
func (l *haveLink) Set(_ context.Context, key string, value []byte, revision uint64) error {
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
l.setTries++
|
|
if l.failing {
|
|
return errors.New("the bucket refused")
|
|
}
|
|
e, ok := l.kv[key]
|
|
if (revision == 0) == ok || (ok && e.rev != revision) {
|
|
return errors.New("wrong last sequence")
|
|
}
|
|
l.kv[key] = haveEntry{value: value, rev: e.rev + 1}
|
|
l.sets = append(l.sets, key)
|
|
l.events = append(l.events, "have "+key)
|
|
return nil
|
|
}
|
|
|
|
func (l *haveLink) have(t *testing.T, key string) nodeengine.HaveByNodeModuleValue {
|
|
t.Helper()
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
h, err := nodeengineclient.DecodeHave(l.kv[key].value)
|
|
if err != nil {
|
|
t.Fatalf("%s holds no have: %v", key, err)
|
|
}
|
|
return h
|
|
}
|
|
|
|
func (l *haveLink) setCount() int {
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
return len(l.sets)
|
|
}
|
|
|
|
func (l *haveLink) put(t *testing.T, key string, h nodeengine.HaveByNodeModuleValue) {
|
|
t.Helper()
|
|
raw, err := nodeengineclient.EncodeHave(h)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
l.hmu.Lock()
|
|
defer l.hmu.Unlock()
|
|
l.kv[key] = haveEntry{value: raw, rev: l.kv[key].rev + 1}
|
|
}
|
|
|
|
func healthOf(states map[string]string) *Health {
|
|
h := &Health{Contract: LivenessContract, At: time.Now().UTC()}
|
|
for module, state := range states {
|
|
h.Resources = append(h.Resources, ResourceHealth{Module: module, Resource: module + ".server", State: state})
|
|
}
|
|
return h
|
|
}
|
|
|
|
func appliedModules() Report {
|
|
return Report{Applied: []string{"a.x", "b.x"},
|
|
Modules: []ModuleFact{{Module: "a", Build: "b-1"}, {Module: "b", Build: "b-2", Failed: true, Detail: "b.x failed: no space"}},
|
|
Health: healthOf(map[string]string{"a": StateHealthy, "b": StateUnhealthy})}
|
|
}
|
|
|
|
func aHaveQueue(l *haveLink) (*Session, *[]string) {
|
|
var said []string
|
|
var mu sync.Mutex
|
|
q := &Session{Membership: Membership{Node: "n1"}, Timeout: time.Second, Say: func(s string) {
|
|
mu.Lock()
|
|
said = append(said, s)
|
|
mu.Unlock()
|
|
}}
|
|
q.Attach(context.Background(), l)
|
|
return q, &said
|
|
}
|
|
|
|
// 1132/AC3, AC5: a module that applied is running with its build and a module that failed is failed with the detail;
|
|
// the key does not exist yet, so it is created.
|
|
func testAnAppliedModuleIsWrittenRunningAndAFailedOneFailed(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
// Design 47 G A-197: each have as written is told to the node-engine's findings of itself, the failed one with its detail.
|
|
told := map[string]nodeengine.HaveByNodeModuleValue{}
|
|
q.SetHaveSaid(func(m string, h nodeengine.HaveByNodeModuleValue) { told[m] = h }, nil)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if told["b"].Phase != nodeengineclient.PhaseFailed || !strings.Contains(told["b"].Detail, "no space") || told["a"].Phase != nodeengineclient.PhaseRunning {
|
|
t.Errorf("the haves told were %+v", told)
|
|
}
|
|
a, b := l.have(t, "n1.a"), l.have(t, "n1.b")
|
|
if a.Phase != nodeengineclient.PhaseRunning || a.Build != "b-1" || a.Health != nodeengineclient.HealthOK {
|
|
t.Errorf("a: %+v", a)
|
|
}
|
|
if b.Phase != nodeengineclient.PhaseFailed || b.Build != "b-2" || !strings.Contains(b.Detail, "no space") ||
|
|
b.Health != nodeengineclient.HealthFailed {
|
|
t.Errorf("b: %+v", b)
|
|
}
|
|
if l.kv["n1.a"].rev != 1 {
|
|
t.Errorf("a was created at revision %d", l.kv["n1.a"].rev)
|
|
}
|
|
}
|
|
|
|
// 1132/AC5: a have equal to the bucket's value is not written; a different one is written over the last revision. Each
|
|
// is written at the seat's form (H-A-388).
|
|
func testAHaveIsWrittenOnlyWhenItDiffers(t *testing.T) {
|
|
l := newHaveLink()
|
|
l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
|
l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-0", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
|
q, _ := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if l.kv["n1.a"].rev != 1 {
|
|
t.Errorf("a equal to the bucket was written again, to revision %d", l.kv["n1.a"].rev)
|
|
}
|
|
if l.kv["n1.b"].rev != 2 || l.have(t, "n1.b").Phase != nodeengineclient.PhaseFailed {
|
|
t.Errorf("b was not updated over its last revision: %+v at %d", l.have(t, "n1.b"), l.kv["n1.b"].rev)
|
|
}
|
|
before := l.setCount()
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if l.setCount() != before {
|
|
t.Errorf("an apply that changed nothing wrote %d keys", l.setCount()-before)
|
|
}
|
|
}
|
|
|
|
// 1132/AC4: a look's health reaches the module's have: ok, failed, waits or unknown, and only a change is written.
|
|
func testAModulesHealthFollowsTheLook(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
rep := Report{Modules: []ModuleFact{{Module: "a", Build: "b"}, {Module: "b", Build: "b"},
|
|
{Module: "c", Build: "b"}, {Module: "d", Build: "b"}, {Module: "e", Build: "b"}}}
|
|
q.SayFacts(context.Background(), rep)
|
|
for _, m := range []string{"a", "b", "c", "d", "e"} {
|
|
if h := l.have(t, "n1."+m).Health; h != nodeengineclient.HealthUnknown {
|
|
t.Errorf("%s with no look is %s, want unknown", m, h)
|
|
}
|
|
}
|
|
h := healthOf(map[string]string{"a": StateHealthy, "b": StateUnhealthy, "c": StateStarting})
|
|
h.Resources[slicesIndex(h.Resources, "b.server")].Reason = ReasonRestarting
|
|
// 1496: a directory used as found is not the module's health (e runs healthy beside one); a failed or waiting module's
|
|
// have says the words of the resource that made it so.
|
|
h.Resources = append(h.Resources, ResourceHealth{Module: "a", Resource: "a.two", State: StateWaiting},
|
|
ResourceHealth{Module: "b", Resource: "b.two", State: StateHealthy}, ResourceHealth{Module: "d", Resource: "d.x", State: StateUnknown},
|
|
ResourceHealth{Module: "e", Resource: "e.server", State: StateHealthy},
|
|
ResourceHealth{Module: "e", Resource: "e.cache", Kind: KindDirectory, State: StateUnhealthy, Reason: ReasonUsedAsFound + " owned by 1:1"})
|
|
if !q.SayHealth(context.Background(), *h) {
|
|
t.Fatal("not said")
|
|
}
|
|
for m, want := range map[string]string{"a": nodeengineclient.HealthWaits, "b": nodeengineclient.HealthFailed,
|
|
"c": nodeengineclient.HealthWaits, "d": nodeengineclient.HealthUnknown, "e": nodeengineclient.HealthOK} {
|
|
if got := l.have(t, "n1."+m).Health; got != want {
|
|
t.Errorf("%s is %s, want %s", m, got, want)
|
|
}
|
|
}
|
|
for m, want := range map[string]string{"a": "a.two waiting", "b": "b.server unhealthy: restarting", "d": "", "e": ""} {
|
|
if got := l.have(t, "n1."+m).Detail; got != want {
|
|
t.Errorf("%s says %q, want %q", m, got, want)
|
|
}
|
|
}
|
|
before := l.setCount()
|
|
h2 := *h
|
|
q.SayHealth(context.Background(), h2)
|
|
if l.setCount() != before {
|
|
t.Errorf("the same look wrote %d keys", l.setCount()-before)
|
|
}
|
|
h2.Resources = []ResourceHealth{{Module: "a", Resource: "a.server", State: StateHealthy}}
|
|
q.SayHealth(context.Background(), h2)
|
|
if got := l.have(t, "n1.a"); got.Health != nodeengineclient.HealthOK || got.Detail != "" {
|
|
t.Errorf("a after a healthy look is %s, saying %q", got.Health, got.Detail)
|
|
}
|
|
}
|
|
|
|
// 1132/AC6: the node's key holds its windows, busy, strays, filters and profile.
|
|
func testTheNodeKeyCarriesTheNodesFacts(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, journal := aHaveQueue(l)
|
|
rep := appliedModules()
|
|
rep.Windows = []Window{{Step: "backup", Holds: []string{"db"}}}
|
|
rep.Busy = []Busy{{ID: "x", Container: "x", State: "waiting"}}
|
|
rep.Strays = []Stray{{Kind: "container", Name: "old"}}
|
|
rep.Filters = []Filter{{Where: "inet mesh", Owner: "mesh"}}
|
|
rep.Profile = map[string]any{"cores": 8}
|
|
q.SayFacts(context.Background(), rep)
|
|
got, err := nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
enc := func(v any) []map[string]any {
|
|
var out []map[string]any
|
|
b, _ := json.Marshal(v)
|
|
_ = json.Unmarshal(b, &out)
|
|
return out
|
|
}
|
|
want := nodeengine.HaveByNodeNodeValue{V: sdkkeys.Version, Windows: enc(rep.Windows), Busy: enc(rep.Busy), Strays: enc(rep.Strays),
|
|
Filters: enc(rep.Filters), Profile: rep.Profile}
|
|
if !nodeengineclient.SameHaveNode(got, want) {
|
|
t.Errorf("the node key holds %+v, want %+v", got, want)
|
|
}
|
|
|
|
// 1126 (ADR 0555 §3): with its keys, the node key carries the node's record: the profile's present capabilities and
|
|
// networks, the outward links, the health's contract and the public keys; a report that changes none of it writes
|
|
// nothing, a changed fact writes the key once, and a report without a profile or health leaves them standing.
|
|
keys := RecordKeys{TunnelKey: "tk", SealingKey: "sk", ServingKey: "pk", Certificate: "cert",
|
|
Trusts: []string{"controller key sha256:aa", "vault key sha256:bb"}} // and what it trusts (L3 s6, ADR 0550 §2)
|
|
q.Keys = func() RecordKeys { return keys }
|
|
l.stated = map[string]string{CapabilitiesKey: "ledger-calls, bus-state-calls", // the tool runner's calls (ENG-2)
|
|
FingerprintKey: "sha256:runner"} // and the runner that stated them (design 46 approval mark §6)
|
|
rep.Profile = map[string]any{"capabilities": []any{map[string]any{"name": "systemd", "present": true},
|
|
map[string]any{"name": "docker", "present": false}, map[string]any{"name": "apt", "present": true}},
|
|
"machine": map[string]any{"networks": []any{map[string]any{"link": "eth0", "network": "192.0.2.0/24"}}}}
|
|
rep.Outward = []string{"eth0"}
|
|
rep.Health = &Health{Contract: NodeKeyContract}
|
|
q.SayFacts(context.Background(), rep)
|
|
if got, err = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); err != nil || got.Record == nil {
|
|
t.Fatalf("the node key holds no record: %+v, %v", got, err)
|
|
}
|
|
wantRecord := nodeengine.NodeRecord{V: sdkkeys.Version, Node: "n1", TunnelKey: "tk", SealingKey: "sk", ServingKey: "pk",
|
|
Certificate: "cert", Trusts: keys.Trusts, Capabilities: []string{"apt", "bus-state-calls", "ledger-calls", "systemd"}, OutwardLinks: []string{"eth0"}, NetworksSaid: true,
|
|
Networks: []nodeengine.AttachedNetwork{{Link: "eth0", Network: "192.0.2.0/24"}}, Contract: NodeKeyContract,
|
|
ManifestReads: statedReads(), // what it reads of a manifest: its contract's (ADR 0614 §4) and that it reads a want by version (H §772)
|
|
RunnerCapabilities: []string{"bus-state-calls", "ledger-calls"}, RunnerFingerprint: "sha256:runner"}
|
|
if !nodeengineclient.SameNodeRecord(*got.Record, wantRecord) {
|
|
t.Errorf("record = %+v, want %+v", *got.Record, wantRecord)
|
|
}
|
|
// A node-engine of H1 reads a want by its version alone and says so in its manifest-reads, not in its capabilities (H §772, §764).
|
|
if !slices.Contains(got.Record.ManifestReads, nodeengine.ManifestReadWordWantVersion) || slices.Contains(got.Record.Capabilities, "want-parts") {
|
|
t.Errorf("the record states reads %v and capabilities %v, want the word want:version and no want-parts", got.Record.ManifestReads, got.Record.Capabilities)
|
|
}
|
|
// Among them, that it fills a seat's reach from the seat holder's listen (ADR 0632 §1).
|
|
// And the words and forms it builds (design 42 zfs-owns-zfs §4, answer A-13).
|
|
for _, read := range []string{catalogue.ReadForm + catalogue.ReferenceFormSeatReach, "word:resources.if-config",
|
|
"form:config-lines", "form:config-json"} {
|
|
if !slices.Contains(got.Record.ManifestReads, read) {
|
|
t.Errorf("the engine does not state it reads %s: %v", read, got.Record.ManifestReads)
|
|
}
|
|
}
|
|
at := l.kv["n1.node"].rev
|
|
q.SayFacts(context.Background(), rep)
|
|
if l.kv["n1.node"].rev != at {
|
|
t.Errorf("a report changing nothing wrote the node key again")
|
|
}
|
|
// Design 47 G §590: the node's capabilities are said by the event manifest-reads-changed alone; no capabilities-changed.
|
|
if got := l.saidOn("mesh.seat.node-engine.event.capabilities-changed."); len(got) != 0 {
|
|
t.Errorf("capabilities-changed said %v, want none (G §590)", got)
|
|
}
|
|
// A runner that does not answer states what it stated before; one answering without any states none (an older runner).
|
|
l.statedErr = fmt.Errorf("%w: nothing answered", ErrNoAnswer)
|
|
l.stated = nil
|
|
q.SayFacts(context.Background(), rep)
|
|
if l.kv["n1.node"].rev != at {
|
|
t.Errorf("a runner that did not answer changed the record")
|
|
}
|
|
l.statedErr, l.stated = nil, map[string]string{}
|
|
q.SayFacts(context.Background(), rep)
|
|
if got, _ = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); l.kv["n1.node"].rev != at+1 || !slices.Equal(got.Record.Capabilities, []string{"apt", "systemd"}) {
|
|
t.Errorf("a runner stating no calls: revision %d (was %d), capabilities %v", l.kv["n1.node"].rev, at, got.Record.Capabilities)
|
|
}
|
|
at++
|
|
l.stated = map[string]string{CapabilitiesKey: "ledger-calls,bus-state-calls"}
|
|
q.SayFacts(context.Background(), rep)
|
|
at++
|
|
keys.Certificate = "cert-2"
|
|
q.SayFacts(context.Background(), rep)
|
|
if got, _ = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); l.kv["n1.node"].rev != at+1 || got.Record.Certificate != "cert-2" {
|
|
t.Errorf("a new certificate: revision %d (was %d), record %+v", l.kv["n1.node"].rev, at, got.Record)
|
|
}
|
|
bare := rep
|
|
bare.Health = nil
|
|
q.SayFacts(context.Background(), bare)
|
|
if got, _ = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); got.Record.Contract != NodeKeyContract {
|
|
t.Errorf("a report without a health statement dropped the contract: %+v", got.Record)
|
|
}
|
|
|
|
// Issue 1966 (ADR 0618 §4): the seats the engine states are those of the seat list it holds now. A change of the list
|
|
// writes the record once and says manifest-reads-changed with the new statement; a restatement that changes nothing
|
|
// writes and says nothing; the verb answers the statement and when it was made.
|
|
all := catalogue.Seats()
|
|
defer catalogue.UseSeats(all)
|
|
q.RestateReads(context.Background()) // the statement as the list stands, whatever an earlier test left
|
|
_, before := q.StatedReads()
|
|
at, saidBefore := l.kv["n1.node"].rev, len(l.readsSaid)
|
|
catalogue.UseSeats(slices.DeleteFunc(slices.Clone(all), func(s catalogue.Seat) bool { return s.Name == "mesh-vault" }))
|
|
q.RestateReads(context.Background())
|
|
got, _ = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value)
|
|
if l.kv["n1.node"].rev != at+1 || slices.Contains(got.Record.ManifestReads, "seat:mesh-vault") ||
|
|
!slices.Contains(got.Record.ManifestReads, "seat:mesh-catalog") || !slices.Contains(got.Record.ManifestReads, "word:claims") {
|
|
t.Errorf("a seat list without mesh-vault: revision %d (was %d), the record states %v", l.kv["n1.node"].rev, at, got.Record.ManifestReads)
|
|
}
|
|
if said := l.readsSaid[saidBefore:]; len(said) != 1 || said[0].Why != ReadsStarted || !slices.Equal(said[0].ManifestReads, got.Record.ManifestReads) {
|
|
t.Errorf("a changed statement said %+v, want one manifest-reads-changed carrying the record's", said)
|
|
}
|
|
if reads, made := q.StatedReads(); !slices.Equal(reads, got.Record.ManifestReads) || made.Before(before) {
|
|
t.Errorf("the verb answers %v made at %v (was %v), want the record's", reads, made, before)
|
|
}
|
|
q.RestateReads(context.Background())
|
|
if l.kv["n1.node"].rev != at+1 || len(l.readsSaid) != saidBefore+1 {
|
|
t.Errorf("an unchanged statement wrote the record or said it again")
|
|
}
|
|
catalogue.UseSeats(all)
|
|
q.RestateReads(context.Background())
|
|
if got, _ = nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); !slices.Equal(got.Record.ManifestReads, statedReads()) {
|
|
t.Errorf("the list back whole: the record states %v, want its contract's", got.Record.ManifestReads)
|
|
}
|
|
|
|
// Issue 1966 note 155, ADR 0668 §4: a seat list read while no link is open is said at the link's opening with what
|
|
// the engine states then; and an event whose publish failed past the bus's retry bound is kept and said there too,
|
|
// never only a line in the log.
|
|
q.Detach(l)
|
|
saidBefore = len(l.readsSaid)
|
|
catalogue.UseSeats(slices.DeleteFunc(slices.Clone(all), func(s catalogue.Seat) bool { return s.Name == "mesh-vault" }))
|
|
q.RestateReads(context.Background())
|
|
if len(l.readsSaid) != saidBefore {
|
|
t.Errorf("a statement made with no link open was said on none")
|
|
}
|
|
q.Attach(context.Background(), l)
|
|
l.sayFails = 1
|
|
q.SayEngine("running", map[string]string{"module": "m"})
|
|
q.SayReads()
|
|
if said := l.readsSaid[saidBefore:]; len(said) != 1 || slices.Contains(said[0].ManifestReads, "seat:mesh-vault") ||
|
|
!slices.Contains(said[0].ManifestReads, "seat:mesh-catalog") {
|
|
t.Errorf("at the link's opening said %+v, want the statement made while no link was open", said)
|
|
}
|
|
if !slices.Contains(l.said, "running") {
|
|
t.Errorf("an event whose publish failed was not said at the next link: said %v", l.said)
|
|
}
|
|
catalogue.UseSeats(all)
|
|
q.RestateReads(context.Background())
|
|
|
|
// A-292 (§590, issue 1975): a restatement the bus did not take, past its retry bound, is said again on the same link
|
|
// until the bus takes it, never held for the next link, and each failed attempt is in the engine's journal by name.
|
|
saidBefore = len(l.readsSaid)
|
|
l.hmu.Lock()
|
|
l.sayFails, l.sayFault = 2, fmt.Errorf("saying: %w", nats.ErrTimeout)
|
|
l.hmu.Unlock()
|
|
catalogue.UseSeats(slices.DeleteFunc(slices.Clone(all), func(s catalogue.Seat) bool { return s.Name == "mesh-vault" }))
|
|
q.RestateReads(context.Background())
|
|
q.retrying.Wait()
|
|
l.hmu.Lock()
|
|
again := slices.Clone(l.readsSaid[saidBefore:])
|
|
l.sayFault = nil
|
|
l.hmu.Unlock()
|
|
if len(again) != 1 || slices.Contains(again[0].ManifestReads, "seat:mesh-vault") {
|
|
t.Errorf("a restatement the bus did not take, said on this link: %+v, want it said once with the new statement", again)
|
|
}
|
|
failed := 0
|
|
for _, line := range *journal {
|
|
if strings.Contains(line, "could not say the node seat's "+nodeengine.EventManifestReadsChanged) &&
|
|
strings.Contains(line, "on this link") {
|
|
failed++
|
|
}
|
|
}
|
|
if failed != 2 {
|
|
t.Errorf("the journal names %d failed attempts of %s, want 2: %q", failed, nodeengine.EventManifestReadsChanged, *journal)
|
|
}
|
|
q.reads.Lock()
|
|
_, held := q.reads.unsaid[nodeengine.EventManifestReadsChanged]
|
|
q.reads.Unlock()
|
|
if held {
|
|
t.Errorf("a restatement said on this link is also held for the next link")
|
|
}
|
|
catalogue.UseSeats(all)
|
|
q.RestateReads(context.Background())
|
|
|
|
// And the publish itself (sayOnce): through no responders, as the old JetStream client says it, and a deadline it is published again under one message id,
|
|
// so the stream takes it once.
|
|
t.Cleanup(busretry.Waits(10*time.Second, time.Millisecond, 2*time.Millisecond))
|
|
var ids []string
|
|
faults := []error{nats.ErrNoStreamResponse, context.DeadlineExceeded, nil}
|
|
if err := sayOnce(func(id string) error { ids = append(ids, id); return faults[len(ids)-1] }, "s", []byte("{}")); err != nil ||
|
|
len(ids) != 3 || ids[0] != ids[2] || ids[0] == "" {
|
|
t.Errorf("a publish through two faults: %v, ids %q", err, ids)
|
|
}
|
|
}
|
|
|
|
// 1132/AC7: a write the bucket refuses is said in the log, and the next apply writes again.
|
|
func testAFailedHaveWriteIsSaidAndWrittenAgain(t *testing.T) {
|
|
l := newHaveLink()
|
|
l.failing = true
|
|
q, said := aHaveQueue(l)
|
|
if !q.SayFacts(context.Background(), appliedModules()) {
|
|
t.Fatal("the facts were not said with a link open")
|
|
}
|
|
if !strings.Contains(strings.Join(*said, "\n"), "n1.a") || !strings.Contains(strings.Join(*said, "\n"), "refused") {
|
|
t.Errorf("the failure is not in the log: %v", *said)
|
|
}
|
|
l.hmu.Lock()
|
|
l.failing = false
|
|
l.hmu.Unlock()
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if l.have(t, "n1.a").Phase != nodeengineclient.PhaseRunning {
|
|
t.Error("the next apply did not write again")
|
|
}
|
|
}
|
|
|
|
// A link without a bucket, and a report with no module facts (a refusal), write nothing and say nothing wrong.
|
|
func testNoBucketAndNoFactsWriteNothing(t *testing.T) {
|
|
plain := newQuietLink()
|
|
q := &Session{Membership: Membership{Node: "n1"}, Timeout: time.Second}
|
|
q.Attach(context.Background(), plain)
|
|
if !q.SayFacts(context.Background(), appliedModules()) {
|
|
t.Fatal("the report did not go out")
|
|
}
|
|
l := newHaveLink()
|
|
q2, _ := aHaveQueue(l)
|
|
q2.SayFacts(context.Background(), Report{Refused: "no"})
|
|
if l.setCount() != 0 {
|
|
t.Errorf("a refusal wrote %d keys", l.setCount())
|
|
}
|
|
}
|
|
|
|
// 1132/AC7: a bind that fails, or never answers, writes nothing and returns within the queue's timeout; a write that
|
|
// fails ends the pass, and is said once.
|
|
func testAFailedBindOrWriteEndsThePassAndReturnsInTime(t *testing.T) {
|
|
for name, set := range map[string]func(*haveLink){
|
|
"a bind refused": func(l *haveLink) { l.bindFails = true },
|
|
"a bind that never answers": func(l *haveLink) { l.bindStuck = true },
|
|
} {
|
|
l := newHaveLink()
|
|
set(l)
|
|
q, said := aHaveQueue(l)
|
|
q.Timeout = 100 * time.Millisecond
|
|
start := time.Now()
|
|
if !q.SayFacts(context.Background(), appliedModules()) {
|
|
t.Fatalf("%s: the report did not go out", name)
|
|
}
|
|
if took := time.Since(start); took > time.Second {
|
|
t.Errorf("%s: the pass took %s", name, took)
|
|
}
|
|
if l.binds != 1 || l.setTries != 0 || len(*said) != 1 {
|
|
t.Errorf("%s: binds %d, writes tried %d, said %v; want one bind, no write, one line", name, l.binds, l.setTries, *said)
|
|
}
|
|
}
|
|
l := newHaveLink()
|
|
l.failing = true
|
|
q, said := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if l.binds != 1 || l.setTries != 1 || len(*said) != 1 {
|
|
t.Errorf("a failed write: binds %d, writes tried %d, said %v; want one of each and one line", l.binds, l.setTries, *said)
|
|
}
|
|
// A bind that meets no responders while the bus reloads its accounts (2026-10-25 23:04:24, four in one second on the
|
|
// bus node) is written again after a backoff, with no apply or look to come.
|
|
defer func(was func(int) time.Duration) { haveBackoff = was }(haveBackoff)
|
|
haveBackoff = func(int) time.Duration { return time.Millisecond }
|
|
l = newHaveLink()
|
|
l.bindNoResponders = 1
|
|
q, _ = aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
deadline := time.Now().Add(3 * time.Second)
|
|
for l.setCount() == 0 && time.Now().Before(deadline) {
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
if l.setCount() == 0 {
|
|
t.Fatal("a bind that met no responders was not written again")
|
|
}
|
|
if l.have(t, "n1.a").Phase != nodeengineclient.PhaseRunning {
|
|
t.Error("the have written again does not say running")
|
|
}
|
|
}
|
|
|
|
func onlyA() Report {
|
|
return Report{Applied: []string{"a.x"}, Modules: []ModuleFact{{Module: "a", Build: "b-1"}},
|
|
Health: healthOf(map[string]string{"a": StateHealthy})}
|
|
}
|
|
|
|
// 1369/AC1: after a declaration with a and b, one with a only writes n1.b with the phase removed, over the revision
|
|
// read, and leaves a as it was; the key is not deleted.
|
|
func testAModuleLeavingTheDeclarationIsWrittenRemoved(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
var gone []string
|
|
q.SetHaveSaid(nil, func(m string) { gone = append(gone, m) })
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
revA, revB := l.kv["n1.a"].rev, l.kv["n1.b"].rev
|
|
q.SayFacts(context.Background(), onlyA())
|
|
if len(gone) != 1 || gone[0] != "b" { // design 47 G A-197: a module that left ends its findings
|
|
t.Errorf("the modules told gone were %v, want b", gone)
|
|
}
|
|
b := l.have(t, "n1.b")
|
|
if b.Phase != nodeengineclient.PhaseRemoved || b.Build != "b-2" {
|
|
t.Errorf("b: %+v", b)
|
|
}
|
|
if l.kv["n1.b"].rev != revB+1 {
|
|
t.Errorf("b was written at revision %d, want one over %d", l.kv["n1.b"].rev, revB)
|
|
}
|
|
// Design 47 G §365: a module the have no longer holds says running stopped, with no fingerprint, once, on its own subject.
|
|
if got := l.saidOn("mesh.seat.node-engine.event.running.n1.b "); len(got) != 1 || !strings.Contains(got[0], `"stopped":true`) || strings.Contains(got[0], `"fingerprint"`) {
|
|
t.Errorf("running said %v for b, want one stopped with no fingerprint", got)
|
|
}
|
|
if l.kv["n1.a"].rev != revA || l.have(t, "n1.a").Phase != nodeengineclient.PhaseRunning {
|
|
t.Errorf("a changed: %+v at %d", l.have(t, "n1.a"), l.kv["n1.a"].rev)
|
|
}
|
|
before := l.setCount()
|
|
q.SayFacts(context.Background(), onlyA())
|
|
if l.setCount() != before {
|
|
t.Errorf("a second apply without b wrote %d keys, removed is written once", l.setCount()-before)
|
|
}
|
|
}
|
|
|
|
// 1369/AC2: a module removed and later added back is written with its new phase.
|
|
func testARemovedModuleAddedBackIsWrittenWithItsNewPhase(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
q.SayFacts(context.Background(), onlyA())
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if b := l.have(t, "n1.b"); b.Phase != nodeengineclient.PhaseFailed || b.Build != "b-2" {
|
|
t.Errorf("b after it came back: %+v", b)
|
|
}
|
|
q.SayFacts(context.Background(), onlyA())
|
|
if b := l.have(t, "n1.b"); b.Phase != nodeengineclient.PhaseRemoved {
|
|
t.Errorf("b removed again: %+v", b)
|
|
}
|
|
}
|
|
|
|
// 1369/AC3: a module this node-engine never wrote a have key for is not written, and a key that is gone from the
|
|
// bucket is not created again.
|
|
func testAModuleNeverWrittenIsNotWrittenRemoved(t *testing.T) {
|
|
l := newHaveLink()
|
|
l.put(t, "n1.c", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "b-9", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
|
q, _ := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
q.SayFacts(context.Background(), onlyA())
|
|
if c := l.have(t, "n1.c"); c.Phase != nodeengineclient.PhaseRunning || l.kv["n1.c"].rev != 1 {
|
|
t.Errorf("c, which this node-engine never wrote, changed: %+v at %d", c, l.kv["n1.c"].rev)
|
|
}
|
|
// a key that vanished from the bucket is not created by the removal
|
|
l2 := newHaveLink()
|
|
q2, _ := aHaveQueue(l2)
|
|
q2.SayFacts(context.Background(), appliedModules())
|
|
l2.hmu.Lock()
|
|
delete(l2.kv, "n1.b")
|
|
l2.hmu.Unlock()
|
|
q2.SayFacts(context.Background(), onlyA())
|
|
if _, there := l2.kv["n1.b"]; there {
|
|
t.Error("the removal created a key that was not there")
|
|
}
|
|
}
|
|
|
|
// A removal the bucket refused is written by the next pass.
|
|
func testARefusedRemovalIsWrittenByTheNextPass(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
l.hmu.Lock()
|
|
l.failing = true
|
|
l.hmu.Unlock()
|
|
q.SayFacts(context.Background(), onlyA())
|
|
l.hmu.Lock()
|
|
l.failing = false
|
|
l.hmu.Unlock()
|
|
q.SayFacts(context.Background(), onlyA())
|
|
if b := l.have(t, "n1.b"); b.Phase != nodeengineclient.PhaseRemoved {
|
|
t.Errorf("b: %+v", b)
|
|
}
|
|
}
|
|
|
|
// 1369/F1: a node-engine that started since wrote nothing, and the report names the modules the kept declaration held
|
|
// before: one of them the new declaration lacks is written removed, one that is not in the bucket is not created.
|
|
func testARestartedNodeEngineWritesTheRemovalFromTheReportsBefore(t *testing.T) {
|
|
l := newHaveLink()
|
|
l.put(t, "n1.a", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
|
l.put(t, "n1.b", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Form: nodeengine.Form, Build: "b-2", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
|
q, _ := aHaveQueue(l) // fresh: nothing written by this process
|
|
r := onlyA()
|
|
r.Before = []string{"a", "b", "c"}
|
|
q.SayFacts(context.Background(), r)
|
|
if b := l.have(t, "n1.b"); b.Phase != nodeengineclient.PhaseRemoved {
|
|
t.Errorf("b: %+v", b)
|
|
}
|
|
if _, there := l.kv["n1.c"]; there {
|
|
t.Error("c, which has no key, was created")
|
|
}
|
|
if l.kv["n1.a"].rev != 1 {
|
|
t.Errorf("a was written, revision %d", l.kv["n1.a"].rev)
|
|
}
|
|
}
|
|
|
|
// R6-A AC7: the first have this node-engine writes — or finds already saying what it would write — is told to the
|
|
// proof, which proves a node-engine on trial to its launcher (novox/hq ADR 0539 §9); a write the bucket refuses is not.
|
|
func testTheFirstHaveWrittenIsToldToTheProof(t *testing.T) {
|
|
l := newHaveLink()
|
|
l.failing = true
|
|
q, _ := aHaveQueue(l)
|
|
var told int
|
|
q.HaveWritten = func() { told++ }
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if told != 0 {
|
|
t.Fatalf("a refused write proved the build %d time(s)", told)
|
|
}
|
|
l.hmu.Lock()
|
|
l.failing = false
|
|
l.hmu.Unlock()
|
|
q.SayFacts(context.Background(), appliedModules())
|
|
if told == 0 {
|
|
t.Fatal("a have written under this build was not told")
|
|
}
|
|
|
|
// The bucket already holds what this node-engine would write: a restart with nothing changed still proves it.
|
|
same := newHaveLink()
|
|
q2, _ := aHaveQueue(same)
|
|
q2.SayFacts(context.Background(), appliedModules())
|
|
again, _ := aHaveQueue(same)
|
|
told = 0
|
|
again.HaveWritten = func() { told++ }
|
|
again.SayFacts(context.Background(), appliedModules())
|
|
if told == 0 {
|
|
t.Fatal("a have already saying the same was not told")
|
|
}
|
|
}
|
|
|
|
// R6-A AC6: an applied module's have names its fingerprint and the digest of the composition applied; a health check that
|
|
// fails after the module's start window gives health failed, and the have keeps both.
|
|
func testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
fp := "src2:" + strings.Repeat("a", 64)
|
|
dig := "sha256:" + strings.Repeat("b", 64)
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig})
|
|
h := l.have(t, "n1.web")
|
|
if h.Fp != fp || h.Composed != dig || h.Phase != nodeengineclient.PhaseRunning || h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("the have after the apply: %+v", h)
|
|
}
|
|
// Design 47, *What each step says*: running is said once, when the build is healthy and its manifest is known, on
|
|
// running.<node>.<module>, with the module, the fingerprint and the manifest's digest; never while it is unknown.
|
|
q.SetManifestOf(func(module, f string) string {
|
|
if module == "web" && f == fp {
|
|
return "sha256:" + strings.Repeat("c", 64)
|
|
}
|
|
return ""
|
|
})
|
|
q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateHealthy}))
|
|
q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateHealthy}))
|
|
if got := l.saidOn("mesh.seat.node-engine.event.running.n1.web "); len(got) != 1 ||
|
|
!strings.Contains(got[0], `"healthy":true`) || !strings.Contains(got[0], `"fingerprint":"`+fp+`"`) || !strings.Contains(got[0], `"manifest":"sha256:`+strings.Repeat("c", 64)+`"`) {
|
|
t.Fatalf("running said %v, want one for the healthy build", got)
|
|
}
|
|
// A have with a wait says wait-held once on wait-held.<node>.<module>, and wait-ended when the wait is gone (design 47 G §541, A-113).
|
|
hold := &nodeengine.Wait{Owner: nodeengine.Seat, Step: nodeengine.WaitStepCompose, Reason: "restore point missing", Since: time.Now().UTC(), Words: "w"}
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Wait: hold})
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Wait: hold})
|
|
if got := l.saidOn("mesh.seat.node-engine.event.wait-held.n1.web "); len(got) != 1 || !strings.Contains(got[0], `"reason":"restore point missing"`) || !strings.Contains(got[0], `"clock-from"`) {
|
|
t.Fatalf("wait-held said %v, want one", got)
|
|
}
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig})
|
|
if got := l.saidOn("mesh.seat.node-engine.event.wait-ended.n1.web "); len(got) != 1 {
|
|
t.Fatalf("wait-ended said %v, want one", got)
|
|
}
|
|
// The router's record of an ask is read from the bucket of the seat's holder on the seat list (design 47 G A-101).
|
|
if _, err := q.RouterRecord("engine.a1"); err != nil || !slices.Equal(l.records, []string{"the-router_asks engine.a1"}) ||
|
|
!strings.Contains(strings.Join(l.asked, " "), "assignments") {
|
|
t.Fatalf("the router's record read as %v after asking %v: %v", l.records, l.asked, err)
|
|
}
|
|
// Starting: it waits. Past its start window the check fails: failed.
|
|
q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateStarting}))
|
|
if got := l.have(t, "n1.web"); got.Health != nodeengineclient.HealthWaits || got.Fp != fp || got.Composed != dig {
|
|
t.Fatalf("while it starts: %+v", got)
|
|
}
|
|
q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateUnhealthy}))
|
|
if got := l.have(t, "n1.web"); got.Health != nodeengineclient.HealthFailed || got.Fp != fp || got.Composed != dig {
|
|
t.Fatalf("a failing check after the start window: %+v", got)
|
|
}
|
|
// §520: running is said again when healthy changes, now false, and the stream's newest says it.
|
|
if got := l.saidOn("mesh.seat.node-engine.event.running.n1.web "); len(got) != 2 || !strings.Contains(got[1], `"healthy":false`) {
|
|
t.Fatalf("running said %v after the check failed, want a second with healthy false", got)
|
|
}
|
|
|
|
// The bus's user list written alone rides on the module's have, and an apply after it keeps it (ADR 0547 §8).
|
|
w := nodeengine.UserListWritten{Source: "n1.web." + fp, Revision: 4, Wanted: dig, Digest: dig, Users: 3,
|
|
At: time.Date(2026, 10, 25, 21, 0, 0, 0, time.UTC)}
|
|
q.NoteUserList(context.Background(), "web", w)
|
|
if got := l.have(t, "n1.web"); got.UserList == nil || got.UserList.Revision != 4 || got.Fp != fp {
|
|
t.Fatalf("the user list is not in the have: %+v", got)
|
|
}
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig})
|
|
if got := l.have(t, "n1.web"); got.UserList == nil || got.UserList.Users != 3 {
|
|
t.Fatalf("an apply lost the user list: %+v", got)
|
|
}
|
|
|
|
// A failed apply waiting on a store's holder carries the pull it waits on in its have (ENG-9, read by node_haves).
|
|
wait := &nodeengine.PullWait{Image: "reg/x@sha256:1", Seat: "container-image-registry", Holder: "distribution",
|
|
Began: time.Date(2026, 11, 4, 14, 0, 0, 0, time.UTC), Retried: "distribution settled"}
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Failed: true, Detail: "the pull failed", PullWait: wait})
|
|
if got := l.have(t, "n1.web"); got.Phase != nodeengineclient.PhaseFailed || got.PullWait == nil || got.PullWait.Holder != "distribution" {
|
|
t.Fatalf("the failed have does not say the pull it waits on: %+v", got)
|
|
}
|
|
|
|
// A module held for a failed backup says so and what it keeps running; removed is written once, over its key.
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "web", FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseHeld), Detail: "the repository is locked"})
|
|
if got := l.have(t, "n1.web"); got.Phase != nodeengineclient.PhaseHeld || got.Detail == "" {
|
|
t.Fatalf("held: %+v", got)
|
|
}
|
|
q.NoteRemoved(context.Background(), "web", "")
|
|
if got := l.have(t, "n1.web"); got.Phase != nodeengineclient.PhaseRemoved {
|
|
t.Fatalf("removed: %+v", got)
|
|
}
|
|
q.NoteNode(context.Background(), dig, compositions.Seals{"core-box#sealed": "core"})
|
|
if n, err := nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); err != nil || n.Composed != dig || len(n.SealedAt) != 1 || n.SealedAt["core-box#sealed"] != "core" {
|
|
t.Fatalf("the node key, with its own composition's sealed values by slot: %+v %v", n, err)
|
|
}
|
|
if n, ok := q.ReadNodeHave(context.Background()); !ok || n.Composed != dig || len(n.SealedAt) != 1 {
|
|
t.Fatalf("the node key read back: %+v %v", n, ok)
|
|
}
|
|
// The node's answers to assignment candidates ride in the same key (ADR 0559 §4), and go when no group is answered.
|
|
answers := map[string]nodeengine.CandidateAnswer{"p-1": {Proposal: "p-1", Revision: 1, Verdict: nodeengine.CandidateAnswerVerdictSame, Same: []string{"web"}}}
|
|
q.NoteCandidates(context.Background(), answers)
|
|
if n, err := nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); err != nil || n.Candidates["p-1"].Proposal != "p-1" || n.Composed != dig {
|
|
t.Fatalf("the node key with its answers: %+v %v", n, err)
|
|
}
|
|
q.NoteCandidates(context.Background(), nil)
|
|
if n, _ := nodeengineclient.DecodeHaveNode(l.kv["n1.node"].value); n.Candidates != nil {
|
|
t.Fatalf("an answer left after its group went: %+v", n.Candidates)
|
|
}
|
|
}
|
|
|
|
// A module applied and running that has nothing long-running to judge is ok once the engine has looked: there is nothing
|
|
// of it that could be down. Unknown kept it from ever being healthy, so the assigner's canary rule held every other node
|
|
// of mesh-host back for good (issue 1945, live on 2026-10-25: ace's have of mesh-host said unknown, and novox and shanks
|
|
// never got the new node-engine). A failed one stays failed, and before any look it is unknown.
|
|
func testAModuleWithNothingToJudgeIsOkOnceLookedAt(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
q.SayFacts(context.Background(), Report{Modules: []ModuleFact{{Module: "mesh-host", Build: "b"}, {Module: "web", Build: "b"},
|
|
{Module: "broken", Build: "b", Failed: true, Detail: "x"}}})
|
|
if h := l.have(t, "n1.mesh-host").Health; h != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("before any look: %s", h)
|
|
}
|
|
if !q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateHealthy})) {
|
|
t.Fatal("not said")
|
|
}
|
|
if h := l.have(t, "n1.mesh-host").Health; h != nodeengineclient.HealthOK {
|
|
t.Fatalf("a running module with nothing to judge after a look: %s", h)
|
|
}
|
|
if h := l.have(t, "n1.broken").Health; h == nodeengineclient.HealthOK {
|
|
t.Fatalf("a failed module was said ok")
|
|
}
|
|
}
|
|
|
|
// A have an older engine left unknown is written over with this engine's health once the module is said again, as the
|
|
// node agent says a module it finds running on its own have: a packages-only module (xorg, nothing long-running) is ok
|
|
// after a look, so the assigner no longer holds back what requires its provision (2026-10-25, g14 and shanks).
|
|
func testAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth(t *testing.T) {
|
|
l := newHaveLink()
|
|
fp := "src2:" + strings.Repeat("a", 64)
|
|
dig := "sha256:" + strings.Repeat("b", 64)
|
|
l.put(t, "n1.xorg", nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Fp: fp, Composed: dig, Phase: nodeengineclient.PhaseRunning,
|
|
Health: nodeengineclient.HealthUnknown})
|
|
q, _ := aHaveQueue(l)
|
|
if !q.SayHealth(context.Background(), *healthOf(map[string]string{"web": StateHealthy})) {
|
|
t.Fatal("not said")
|
|
}
|
|
if h := l.have(t, "n1.xorg"); h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("a module the session does not hold was written: %+v", h)
|
|
}
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "xorg", FP: fp, Composed: dig})
|
|
if h := l.have(t, "n1.xorg"); h.Health != nodeengineclient.HealthOK || h.Fp != fp || h.Composed != dig || h.Phase != nodeengineclient.PhaseRunning {
|
|
t.Fatalf("said again after a look: %+v", h)
|
|
}
|
|
}
|
|
|
|
// A module's health is not yet judged (unknown) while its change is under way and until a look after it, never failed
|
|
// from a look at what was being replaced: on 2026-10-25 15:27:36 the controller's canary on novox was held on a have
|
|
// saying applying and failed, two seconds before its launch said healthy.
|
|
func testAHealthIsNotJudgedWhileAModuleIsApplied(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
ctx := context.Background()
|
|
old := ModuleFact{Module: "ctl", FP: "src2:" + strings.Repeat("a", 64), Composed: "sha256:" + strings.Repeat("1", 64)}
|
|
q.NoteModule(ctx, old)
|
|
q.SayHealth(ctx, *healthOf(map[string]string{"ctl": StateUnhealthy}))
|
|
if h := l.have(t, "n1.ctl"); h.Health != nodeengineclient.HealthFailed {
|
|
t.Fatalf("the running module's failed look was not said: %+v", h)
|
|
}
|
|
next := ModuleFact{Module: "ctl", FP: "src2:" + strings.Repeat("b", 64), Composed: "sha256:" + strings.Repeat("2", 64)}
|
|
applying := next
|
|
applying.Phase = string(nodeengineclient.PhaseApplying)
|
|
q.NoteModule(ctx, applying)
|
|
if h := l.have(t, "n1.ctl"); h.Phase != nodeengineclient.PhaseApplying || h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("applying carried the last look's health: %+v", h)
|
|
}
|
|
q.SayHealth(ctx, *healthOf(map[string]string{"ctl": StateUnhealthy}))
|
|
if h := l.have(t, "n1.ctl"); h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("a look during the apply judged it: %+v", h)
|
|
}
|
|
q.NoteModule(ctx, next)
|
|
if h := l.have(t, "n1.ctl"); h.Phase != nodeengineclient.PhaseRunning || h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("running before a look after the apply: %+v", h)
|
|
}
|
|
q.SayHealth(ctx, *healthOf(map[string]string{"ctl": StateHealthy}))
|
|
if h := l.have(t, "n1.ctl"); h.Health != nodeengineclient.HealthOK {
|
|
t.Fatalf("the look after the apply was not taken: %+v", h)
|
|
}
|
|
}
|
|
|
|
// A fact naming another composition than the one looked at, with no apply phase between, is not judged by the old look.
|
|
func testAHealthIsNotCarriedOverToAnotherComposition(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
ctx := context.Background()
|
|
q.NoteModule(ctx, ModuleFact{Module: "ctl", FP: "src2:" + strings.Repeat("a", 64)})
|
|
q.SayHealth(ctx, *healthOf(map[string]string{"ctl": StateUnhealthy}))
|
|
q.NoteModule(ctx, ModuleFact{Module: "ctl", FP: "src2:" + strings.Repeat("b", 64)})
|
|
if h := l.have(t, "n1.ctl"); h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("the old composition's look judged the new one: %+v", h)
|
|
}
|
|
}
|
|
|
|
// A declaration's report naming another composition of a module, with no health of its own, does not carry the old
|
|
// look's health over; and a module removed leaves nothing marked unjudged behind.
|
|
func testADeclarationReportMovesAHealthAndARemovalForgetsIt(t *testing.T) {
|
|
l := newHaveLink()
|
|
q, _ := aHaveQueue(l)
|
|
ctx := context.Background()
|
|
q.SayFacts(ctx, Report{Applied: []string{"a.x"}, Modules: []ModuleFact{{Module: "a", Build: "b-1"}},
|
|
Health: healthOf(map[string]string{"a": StateUnhealthy})})
|
|
if h := l.have(t, "n1.a"); h.Health != nodeengineclient.HealthFailed {
|
|
t.Fatalf("the failed look was not said: %+v", h)
|
|
}
|
|
q.SayFacts(ctx, Report{Applied: []string{"a.x"}, Modules: []ModuleFact{{Module: "a", Build: "b-1", FP: "src2:" + strings.Repeat("c", 64)}}})
|
|
if h := l.have(t, "n1.a"); h.Health != nodeengineclient.HealthUnknown {
|
|
t.Fatalf("the old composition's look judged the new one: %+v", h)
|
|
}
|
|
select {
|
|
case <-q.HealthOwed():
|
|
default:
|
|
t.Fatal("a module out of motion and unjudged owed no look")
|
|
}
|
|
q.NoteRemoved(ctx, "a", "")
|
|
q.haves.mu.Lock()
|
|
left := q.haves.unjudged["a"]
|
|
q.haves.mu.Unlock()
|
|
if left {
|
|
t.Fatal("a removed module is still marked unjudged")
|
|
}
|
|
}
|
|
|
|
// ADR 0547 §8, 2026-10-26 on the bus node: the bus's user list of a module this engine says no have of (no want, and no
|
|
// longer in the declaration) still reaches the module's key, merged into what the key says, every other field kept; a
|
|
// key that does not exist is not made up and is said once; a writer that drops the list again is written over.
|
|
func testAUserListReachesTheHaveOfAModuleNoApplyHereSays(t *testing.T) {
|
|
l := newHaveLink()
|
|
older := nodeengine.HaveByNodeModuleValue{V: sdkkeys.Version, Build: "build-1", Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK}
|
|
l.put(t, "n1.nats", older)
|
|
q, said := aHaveQueue(l)
|
|
dig := "sha256:" + strings.Repeat("c", 64)
|
|
w := nodeengine.UserListWritten{Source: "n1.nats", Revision: 7, Wanted: dig, Digest: dig, Users: 58,
|
|
At: time.Date(2026, 10, 26, 12, 26, 51, 0, time.UTC)}
|
|
q.NoteUserList(context.Background(), "nats", w)
|
|
got := l.have(t, "n1.nats")
|
|
if got.UserList == nil || got.UserList.Users != 58 || got.UserList.Digest != dig {
|
|
t.Fatalf("the user list is not in the have: %+v", got)
|
|
}
|
|
if got.Build != "build-1" || got.Phase != nodeengineclient.PhaseRunning || got.Health != nodeengineclient.HealthOK {
|
|
t.Fatalf("the merge lost the key's own fields: %+v", got)
|
|
}
|
|
rev := l.kv["n1.nats"].rev
|
|
q.NoteUserList(context.Background(), "nats", w)
|
|
if l.kv["n1.nats"].rev != rev {
|
|
t.Errorf("the same list was written again, to revision %d", l.kv["n1.nats"].rev)
|
|
}
|
|
|
|
// Another writer replaces the value without the list: the next pass merges it back.
|
|
l.put(t, "n1.nats", older)
|
|
q.SayFacts(context.Background(), Report{})
|
|
if got := l.have(t, "n1.nats"); got.UserList == nil || got.Build != "build-1" {
|
|
t.Fatalf("a value written without the list kept it out: %+v", got)
|
|
}
|
|
|
|
// No key at all: nothing is created, said once; the module's first have carries the list.
|
|
q.NoteUserList(context.Background(), "other", w)
|
|
q.NoteUserList(context.Background(), "other", w)
|
|
if _, ok := l.kv["n1.other"]; ok {
|
|
t.Fatalf("a have was made up for a module no apply says")
|
|
}
|
|
n := 0
|
|
for _, s := range *said {
|
|
if strings.Contains(s, "is in no have") {
|
|
n++
|
|
}
|
|
}
|
|
if n != 1 {
|
|
t.Errorf("the missing key was said %d times: %q", n, *said)
|
|
}
|
|
fp := "src2:" + strings.Repeat("a", 64)
|
|
q.NoteModule(context.Background(), ModuleFact{Module: "other", FP: fp, Composed: dig})
|
|
if got := l.have(t, "n1.other"); got.UserList == nil || got.Fp != fp {
|
|
t.Fatalf("the first have of the module lost the list: %+v", got)
|
|
}
|
|
}
|
|
|
|
// slicesIndex is the index of the resource with id in rs, or -1.
|
|
func slicesIndex(rs []ResourceHealth, id string) int {
|
|
for i, r := range rs {
|
|
if r.Resource == id {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// statedReads is the contract's reads with the word that the engine reads a want by its version (design 47 H §772).
|
|
func statedReads() []string {
|
|
return slices.Sorted(slices.Values(append(catalogue.ManifestReads(), nodeengine.ManifestReadWordWantVersion)))
|
|
}
|
|
|
|
// TestHave runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
|
func TestHave(t *testing.T) {
|
|
t.Run("AnAppliedModuleIsWrittenRunningAndAFailedOneFailed", testAnAppliedModuleIsWrittenRunningAndAFailedOneFailed)
|
|
t.Run("AHaveIsWrittenOnlyWhenItDiffers", testAHaveIsWrittenOnlyWhenItDiffers)
|
|
t.Run("AModulesHealthFollowsTheLook", testAModulesHealthFollowsTheLook)
|
|
t.Run("TheNodeKeyCarriesTheNodesFacts", testTheNodeKeyCarriesTheNodesFacts)
|
|
t.Run("AFailedHaveWriteIsSaidAndWrittenAgain", testAFailedHaveWriteIsSaidAndWrittenAgain)
|
|
t.Run("NoBucketAndNoFactsWriteNothing", testNoBucketAndNoFactsWriteNothing)
|
|
t.Run("AFailedBindOrWriteEndsThePassAndReturnsInTime", testAFailedBindOrWriteEndsThePassAndReturnsInTime)
|
|
t.Run("AModuleLeavingTheDeclarationIsWrittenRemoved", testAModuleLeavingTheDeclarationIsWrittenRemoved)
|
|
t.Run("ARemovedModuleAddedBackIsWrittenWithItsNewPhase", testARemovedModuleAddedBackIsWrittenWithItsNewPhase)
|
|
t.Run("AModuleNeverWrittenIsNotWrittenRemoved", testAModuleNeverWrittenIsNotWrittenRemoved)
|
|
t.Run("ARefusedRemovalIsWrittenByTheNextPass", testARefusedRemovalIsWrittenByTheNextPass)
|
|
t.Run("ARestartedNodeEngineWritesTheRemovalFromTheReportsBefore", testARestartedNodeEngineWritesTheRemovalFromTheReportsBefore)
|
|
t.Run("TheFirstHaveWrittenIsToldToTheProof", testTheFirstHaveWrittenIsToldToTheProof)
|
|
t.Run("AnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth", testAnAppliedModulesHaveNamesTheFingerprintAndTheDigestAndFollowsItsHealth)
|
|
t.Run("AModuleWithNothingToJudgeIsOkOnceLookedAt", testAModuleWithNothingToJudgeIsOkOnceLookedAt)
|
|
t.Run("AModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth", testAModuleSaidAgainOverAnOlderEnginesUnknownIsWrittenWithThisEnginesHealth)
|
|
t.Run("AHealthIsNotJudgedWhileAModuleIsApplied", testAHealthIsNotJudgedWhileAModuleIsApplied)
|
|
t.Run("AHealthIsNotCarriedOverToAnotherComposition", testAHealthIsNotCarriedOverToAnotherComposition)
|
|
t.Run("ADeclarationReportMovesAHealthAndARemovalForgetsIt", testADeclarationReportMovesAHealthAndARemovalForgetsIt)
|
|
t.Run("AUserListReachesTheHaveOfAModuleNoApplyHereSays", testAUserListReachesTheHaveOfAModuleNoApplyHereSays)
|
|
}
|