Files
mesh-delivery/modules/mesh-delivery-indexer/internal/index/registrations_test.go
T
jschoubben 7e25aa75f8 Indexer: a warrant given up is answered not applied and said (H-A-470 (2))
The approved registration of source.novox.hq was given up after the bus's
last delivery without a word. On the delivery that reaches the event
deliveries bound heardDecided now gives the warrant up: its key ends refused
"not applied: <reason>" and registration-unwritten (scope module, id the
registration's name) names the ask and the reason, cleared when a later
version is written. The seed's key ends so too and says seed-waits alone.
heardDecided leaves an unapplied warrant for the bus as the other hearers do.

Builds: design 47 H2 H-A-470 (2), H-A-470 addendum (a)-(d), H-A-470 second addendum
2026-11-22 12:44:01 +01:00

413 lines
20 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package index
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
)
// regRig is a Registry on memory states with a fake router: asks it was given, the cancelled ones, the history and the events.
type regRig struct {
r *Registry
asks map[string]oc.Ask
cancelled []string
history []meshcatalog.Registration
events []meshcatalog.RegistrationChangedEvent
now time.Time
whereErr error
chosen map[string]string // ask id -> option the router's record holds
missing map[string]bool
placed map[string][]mma.ModulePlacement // module -> its placements, as the seat mesh-module-assigner's placement answers
}
func newRegRig() *regRig {
g := &regRig{asks: map[string]oc.Ask{}, now: time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC), chosen: map[string]string{}, missing: map[string]bool{}}
g.r = &Registry{Module: testSelf, Registrations: MemoryStore(), Proposals: MemoryStore(),
History: func(_ context.Context, r meshcatalog.Registration) error {
g.history = append(g.history, r)
return nil
},
Say: func(_ context.Context, e meshcatalog.RegistrationChangedEvent) error {
g.events = append(g.events, e)
return nil
},
Branch: func(repo, branch string) (gitseat.BranchAnswer, error) {
if branch == "" {
branch = "main"
}
return gitseat.BranchAnswer{Branch: branch, Repository: repo}, nil
},
Placement: func(module string) ([]mma.ModulePlacement, error) { return g.placed[module], nil },
Ask: func(a oc.Ask) error { g.asks[a.ID] = a; return nil },
Cancel: func(id string) error { g.cancelled = append(g.cancelled, id); return nil },
Where: func(id string) (string, *oc.Warrant, error) {
if g.whereErr != nil {
return "", nil, g.whereErr
}
if g.missing[id] {
return "", nil, nil
}
if opt, ok := g.chosen[id]; ok {
w := g.warrant(id, opt)
return "chosen", &w, nil
}
return "open", nil, nil
},
Now: func() time.Time { return g.now }, Logf: func(string, ...any) {}}
return g
}
// warrant is the warrant of the operator's choice of option on an ask, as the router would say it.
func (g *regRig) warrant(id, option string) oc.Warrant {
a := g.asks[id]
o, _ := occ.OptionOf(a, option)
return oc.Warrant{Ask: id, Asker: testSelf, Outcome: occ.OutcomeChosen, Option: option, Level: o.Level, Label: o.Label,
AskDigest: occ.Digest(a), At: occ.FormatTime(g.now.Add(time.Minute)), By: &oc.Person{Who: occ.Operator, Kind: "telegram", Verified: "user id verified"}}
}
func (g *regRig) decide(t *testing.T, ask, option string) {
t.Helper()
g.chosen[ask] = option
if err := g.r.Heard(context.Background(), g.warrant(ask, option)); err != nil {
t.Fatalf("hearing the warrant of %s: %v", ask, err)
}
}
func reg(module string, steps meshcatalog.StepStatuses, branches ...string) json.RawMessage {
b, _ := json.Marshal(meshcatalog.RegisterInput{Registration: meshcatalog.Registration{Module: module, Origin: "novox/" + module, Path: "module.json", Branches: branches, Policy: meshcatalog.Policy{Steps: steps}}})
return b
}
func pol(module string, s meshcatalog.StepStatuses) json.RawMessage {
b, _ := json.Marshal(meshcatalog.PolicyInput{Module: module, Steps: s})
return b
}
func TestRegistrationsAreWrittenOnTheirWarrantOnly(t *testing.T) {
ctx := context.Background()
g := newRegRig()
// Refusals raise no ask: a code review that is required (§3), a branch named candidate or entry (§343).
for _, c := range []struct {
name, why string
change json.RawMessage
}{
{"review", meshcatalog.RegistrationAskedRefusedReviewRequired, reg("a", meshcatalog.StepStatuses{Review: "required"}, "main")},
{"candidate", meshcatalog.RegistrationAskedRefusedReservedBranchName, reg("a", meshcatalog.StepStatuses{}, "candidate")},
{"entry", meshcatalog.RegistrationAskedRefusedReservedBranchName, reg("a", meshcatalog.StepStatuses{}, "entry")},
} {
got, err := g.r.Propose(ctx, "register", "session@node", c.change)
if err != nil || got.Refused == "" || got.Ask != "" || got.Words == "" || got.Refused != c.why {
t.Fatalf("%s: answer %+v, %v: want a refusal for %q naming why and no ask (design 47 G §704)", c.name, got, err, c.why)
}
}
if len(g.asks) != 0 {
t.Fatalf("a refusal raised %d asks", len(g.asks))
}
// A registration with no branch takes the default branch through the seat git (§342) and asks, naming each value and carrying the digest.
got, err := g.r.Propose(ctx, "register", "session@node", reg("a", meshcatalog.StepStatuses{Unit: "required", Lint: "bypass"}))
if err != nil || got.Ask == "" || len(got.Lines) < 3 {
t.Fatalf("register: %+v, %v", got, err)
}
ask := g.asks[got.Ask]
if !strings.Contains(ask.Explanation, "watching main") || !strings.Contains(ask.Explanation, "sha256:") || ask.About == "" {
t.Fatalf("the ask does not name the values and the digest: %+v", ask)
}
if all, _ := g.r.RegistrationsAnswer(ctx, meshcatalog.RegistrationsInput{}); len(all.Registrations) != 0 {
t.Fatalf("a registration was written before its warrant: %+v", all)
}
g.decide(t, got.Ask, "approve")
one, _ := g.r.RegistrationsAnswer(ctx, meshcatalog.RegistrationsInput{Module: "a"})
if len(one.Registrations) != 1 || one.Registrations[0].Version != 1 || one.Registrations[0].Warrant != got.Ask || one.Registrations[0].By != "session@node" {
t.Fatalf("after the warrant: %+v", one)
}
if len(g.history) != 1 || len(g.events) != 1 || g.events[0].Version != 1 || g.events[0].Warrant != got.Ask {
t.Fatalf("history %d, events %+v", len(g.history), g.events)
}
// A policy from required to bypass asks, showing that line; a decline writes nothing and ends the key declined.
p, err := g.r.Propose(ctx, "policy", "s@n", pol("a", meshcatalog.StepStatuses{Unit: "bypass"}))
if err != nil || len(p.Lines) != 1 || p.Lines[0] != "a unit tests: required -> bypass" {
t.Fatalf("policy: %+v, %v", p, err)
}
g.decide(t, p.Ask, "decline")
if now, _, _ := g.r.Registration(ctx, "a"); now.Version != 1 {
t.Fatalf("a declined change was written: %+v", now)
}
rows, _ := ListProposals(ctx, g.r.Proposals)
if len(rows) != 2 || rows[1].State != ProposalDeclined && rows[0].State != ProposalDeclined {
t.Fatalf("proposals: %+v", rows)
}
// Two changes of one key leave one open ask; the first ask's late warrant writes nothing.
g.now = g.now.Add(time.Hour)
first, _ := g.r.Propose(ctx, "policy", "s@n", pol("a", meshcatalog.StepStatuses{Unit: "bypass"}))
g.now = g.now.Add(time.Hour)
second, _ := g.r.Propose(ctx, "policy", "s@n", pol("a", meshcatalog.StepStatuses{Unit: "optional"}))
if first.Ask == second.Ask {
t.Fatal("a newer change of the key kept the older ask")
}
g.chosen[first.Ask] = "approve"
_ = g.r.Heard(ctx, g.warrant(first.Ask, "approve"))
if now, _, _ := g.r.Registration(ctx, "a"); now.Version != 1 {
t.Fatalf("the replaced ask's warrant wrote: %+v", now)
}
// Where the router's record cannot be read the warrant is left unapplied, said as an error.
g.whereErr = errors.New("no runtime")
if err := g.r.Heard(ctx, g.warrant(second.Ask, "approve")); err == nil {
t.Fatal("a warrant was applied with the router's record unread")
}
g.whereErr = nil
g.decide(t, second.Ask, "approve")
if now, _, _ := g.r.Registration(ctx, "a"); now.Version != 2 || now.Policy.Steps.Unit != "optional" {
t.Fatalf("the second change: %+v", now)
}
// watch adds a branch, its protection never read (I9/AC1, design 47 H §763 corrects G §5); unwatch removes it; each on its warrant.
w, _ := g.r.Propose(ctx, "watch", "s@n", mustJSON(meshcatalog.WatchInput{Module: "a", Branch: "beta"}))
if w.Refused != "" || w.Ask == "" {
t.Fatalf("watch of a branch: %+v; want an ask, no refusal", w)
}
g.decide(t, w.Ask, "approve")
// A branch a placement names is not unwatched: refused as placed, naming the placement, and no ask is raised (§704, A-62).
g.placed = map[string][]mma.ModulePlacement{"a": {{Branch: "beta", Nodes: []string{"n1", "n2"}}}}
if p, err := g.r.Propose(ctx, "unwatch", "s@n", mustJSON(meshcatalog.WatchInput{Module: "a", Branch: "beta"})); err != nil || p.Refused != meshcatalog.RegistrationAskedRefusedPlaced ||
p.Ask != "" || !strings.Contains(p.Words, "beta") || !strings.Contains(p.Words, "n1, n2") {
t.Fatalf("unwatch of a placed branch: %+v, %v; want refused placed naming the placement", p, err)
}
g.placed = nil
u, _ := g.r.Propose(ctx, "unwatch", "s@n", mustJSON(meshcatalog.WatchInput{Module: "a", Branch: "beta"}))
g.decide(t, u.Ask, "approve")
if now, _, _ := g.r.Registration(ctx, "a"); now.Version != 4 || len(now.Branches) != 1 {
t.Fatalf("watch and unwatch: %+v", now)
}
if un, _ := g.r.Propose(ctx, "policy", "s@n", pol("zz", meshcatalog.StepStatuses{Unit: "bypass"})); un.Refused != meshcatalog.RegistrationAskedRefusedUnknownModule {
t.Fatalf("a policy of an unregistered module: %+v", un)
}
// Design 47 H2 §815 (H-A-349 DQ-9, H-A-438, H-A-450): a repository with no module registers as a source alone, kept, kept in
// the history and said under source.<owner>.<name>; one whose tree at the branch's head holds a module.json at its root or
// under modules/ is refused holds-manifest, and a registration not of the source form is an error.
t.Run("a source-only registration", func(t *testing.T) {
g := newRegRig()
const head = "0123456789abcdef0123456789abcdef01234567"
dirs := map[string][]string{"novox/hq": {"tools/x"}, "novox/root": {""}, "novox/mods": {"cmd", "modules/x"}}
var asked []string
g.r.Branch = func(repo, branch string) (gitseat.BranchAnswer, error) {
if branch == "" {
branch = "main"
}
return gitseat.BranchAnswer{Branch: branch, Repository: repo, Head: head}, nil
}
g.r.ModuleDirs = func(repo, commit string) ([]string, error) {
asked = append(asked, repo+"@"+commit)
return dirs[repo], nil
}
check := &meshcatalog.SourceCheck{Seat: meshcatalog.SourceCheckSeatNodeBuildGo, Step: meshcatalog.SourceCheckStepUnit}
source := func(origin string, edit func(*meshcatalog.Registration)) json.RawMessage {
r := meshcatalog.Registration{Origin: origin, Check: check, Policy: meshcatalog.Policy{Steps: meshcatalog.StepStatuses{Unit: "required"}}}
if edit != nil {
edit(&r)
}
return mustJSON(meshcatalog.RegisterInput{Registration: r})
}
for _, origin := range []string{"novox/root", "novox/mods"} {
got, err := g.r.Propose(ctx, "register", "s@n", source(origin, nil))
if err != nil || got.Refused != meshcatalog.RegistrationAskedRefusedHoldsManifest || got.Ask != "" || !strings.Contains(got.Words, "module.json") {
t.Errorf("%s: %+v, %v; want refused holds-manifest naming its module.json and no ask", origin, got, err)
}
}
for name, edit := range map[string]func(*meshcatalog.Registration){
"a module": func(r *meshcatalog.Registration) { r.Module = "hq" },
"a path": func(r *meshcatalog.Registration) { r.Path = "module.json" },
"two branches": func(r *meshcatalog.Registration) { r.Branches = []string{"main", "beta"} },
"a free seat": func(r *meshcatalog.Registration) { r.Check = &meshcatalog.SourceCheck{Seat: "sh", Step: "unit"} },
} {
if got, err := g.r.Propose(ctx, "register", "s@n", source("novox/hq", edit)); err == nil {
t.Errorf("a source-only registration naming %s: %+v, want an error", name, got)
}
}
got, err := g.r.Propose(ctx, "register", "s@n", source("novox/hq", nil))
if err != nil || got.Ask == "" || got.Module != "source.novox.hq" || !strings.Contains(strings.Join(got.Lines, "\n"), "source.novox.hq: checked by the step unit on the seat node-build-go") {
t.Fatalf("register a source: %+v, %v; want an ask of source.novox.hq naming its check", got, err)
}
if len(asked) == 0 || asked[len(asked)-1] != "novox/hq@"+head {
t.Errorf("the trees read %v, want novox/hq at the default branch's head", asked)
}
g.decide(t, got.Ask, "approve")
if v, _, found, _ := g.r.Registrations.Get(ctx, "source.novox.hq"); !found || !strings.Contains(string(v), `"check":{"seat":"node-build-go","step":"unit"}`) || strings.Contains(string(v), `"module"`) {
t.Fatalf("registrations under source.novox.hq: %s (%t), want the source form with no module", v, found)
}
if len(g.history) != 1 || RegistrationName(g.history[0]) != "source.novox.hq" || len(g.events) != 1 || g.events[0].Module != "source.novox.hq" {
t.Fatalf("history %+v, events %+v; want one version and registration-changed of source.novox.hq", g.history, g.events)
}
for _, in := range []meshcatalog.RegistrationsInput{{Module: "source.novox.hq"}, {Repository: "novox/hq"}} {
if a, err := g.r.RegistrationsAnswer(ctx, in); err != nil || len(a.Registrations) != 1 || a.Registrations[0].Branches[0] != "main" {
t.Errorf("registrations %+v: %+v, %v; want the source alone, watching main", in, a, err)
}
}
if w, err := g.r.Propose(ctx, "watch", "s@n", mustJSON(meshcatalog.WatchInput{Module: "source.novox.hq", Branch: "beta"})); err == nil {
t.Errorf("a second branch of a source-only registration: %+v, want an error", w)
}
})
}
// Design 47 H2 H-A-470 (2) and its addenda: a warrant the indexer gives up on (its history write refused, given the last time)
// ends its key refused "not applied: <reason>" and says registration-unwritten of the registration, naming the ask and the
// reason; a later version written clears it; the seed's key ends so too, with no such finding (seed-waits says it).
func TestAWarrantGivenUpIsAnsweredNotAppliedAndSaid(t *testing.T) {
ctx := context.Background()
g := newRegRig()
type said struct {
name, ask, reason string
unwritten bool
}
var findings []said
g.r.Unwritten = func(name, ask, reason string, unwritten bool) {
findings = append(findings, said{name, ask, reason, unwritten})
}
refused := errors.New("nats: no response from stream")
g.r.History = func(context.Context, meshcatalog.Registration) error { return refused }
got, _ := g.r.Propose(ctx, "register", "s@n", reg("a", meshcatalog.StepStatuses{}, "main"))
g.chosen[got.Ask] = "approve"
err := g.r.Heard(ctx, g.warrant(got.Ask, "approve"))
if err == nil {
t.Fatal("a history write refused was applied")
}
if err := g.r.GiveUp(ctx, g.warrant(got.Ask, "approve"), err.Error()); err != nil {
t.Fatal(err)
}
rows, _ := ListProposals(ctx, g.r.Proposals)
if len(rows) != 1 || rows[0].State != ProposalRefused || !strings.HasPrefix(rows[0].Outcome, "not applied: ") || !strings.Contains(rows[0].Outcome, refused.Error()) {
t.Fatalf("the key given up: %+v; want refused, not applied, naming the reason", rows)
}
if len(findings) != 1 || findings[0].name != "a" || findings[0].ask != got.Ask || !strings.Contains(findings[0].reason, refused.Error()) || !findings[0].unwritten {
t.Fatalf("findings said %+v; want registration-unwritten of a naming the ask and the reason", findings)
}
// Given up again (a late redelivery), an ended key says nothing more.
_ = g.r.GiveUp(ctx, g.warrant(got.Ask, "approve"), "again")
if len(findings) != 1 {
t.Fatalf("an ended key said %+v", findings)
}
// Asked again and written, the finding clears.
g.r.History = func(context.Context, meshcatalog.Registration) error { return nil }
again, _ := g.r.Propose(ctx, "register", "s@n", reg("a", meshcatalog.StepStatuses{}, "main"))
g.decide(t, again.Ask, "approve")
if len(findings) != 2 || findings[1].name != "a" || findings[1].unwritten {
t.Fatalf("findings said %+v; want registration-unwritten of a cleared by the version written", findings)
}
// The seed's warrant given up ends its key refused, says seed-waits and no registration-unwritten.
var waits []bool
g.r.SeedWaits = func(_ string, waiting bool) { waits = append(waits, waiting) }
seed, _ := json.Marshal(Proposal{V: 1, Verb: verbSeed, Ask: "ask-seed", State: ProposalOpen})
if err := g.r.Proposals.Create(ctx, SeedKey, seed); err != nil {
t.Fatal(err)
}
if err := g.r.GiveUp(ctx, oc.Warrant{Ask: "ask-seed"}, "the store refused"); err != nil {
t.Fatal(err)
}
p, _, _, _ := g.r.load(ctx, SeedKey)
if p.State != ProposalSeedWaits || p.Outcome != "not applied: the store refused" || len(waits) != 1 || !waits[0] || len(findings) != 2 {
t.Fatalf("the seed given up: %+v, seed-waits %v, findings %+v; want it ended not applied, seed-waits said, no registration-unwritten", p, waits, findings)
}
}
func mustJSON(v any) json.RawMessage { b, _ := json.Marshal(v); return b }
func TestProposalsSurviveARestartAndAreDropped(t *testing.T) {
ctx := context.Background()
g := newRegRig()
a, _ := g.r.Propose(ctx, "register", "s@n", reg("a", meshcatalog.StepStatuses{}, "main"))
b, _ := g.r.Propose(ctx, "register", "s@n", reg("b", meshcatalog.StepStatuses{}, "main"))
c, _ := g.r.Propose(ctx, "register", "s@n", reg("c", meshcatalog.StepStatuses{}, "main"))
// While the indexer was down the operator approved a and the router lost c; b is still open.
g.chosen[a.Ask] = "approve"
g.missing[c.Ask] = true
if err := g.r.Restart(ctx); err != nil {
t.Fatal(err)
}
rows, _ := ListProposals(ctx, g.r.Proposals)
states := map[string]string{}
for _, row := range rows {
states[row.Module] = row.State
}
if states["a"] != ProposalApplied || states["b"] != ProposalOpen || states["c"] != ProposalLost {
t.Fatalf("after a restart: %v", states)
}
// indexer_proposal_drop cancels the open ask and ends the key dropped; it asks why.
if _, err := g.r.Drop(ctx, ProposalKey("register", "b", ""), "", "s@n"); err == nil {
t.Fatal("a drop with no why was taken")
}
if _, err := g.r.Drop(ctx, ProposalKey("register", "b", ""), "not wanted", "s@n"); err != nil {
t.Fatal(err)
}
if len(g.cancelled) != 1 || g.cancelled[0] != b.Ask {
t.Fatalf("cancelled %v", g.cancelled)
}
rows, _ = ListProposals(ctx, g.r.Proposals)
for _, row := range rows {
if row.Module == "b" && row.State != ProposalDropped {
t.Fatalf("a dropped key: %+v", row)
}
}
}
func TestSeedWritesTheModuleGraphWithNoAskAndWaitsForEveryBuildSeat(t *testing.T) {
ctx := context.Background()
g := newRegRig()
mods := []SeedModule{{Module: "a", Origin: "novox/a", Path: "module.json", Artifacts: []SeedArtifact{{Name: "program", Seat: "node-build-go", Answered: false}}}}
if _, err := g.r.ProposeSeed(ctx, mods, false, "indexer"); err == nil || !strings.Contains(err.Error(), "node-build-go") {
t.Fatalf("an unanswered build seat did not hold the seed: %v", err)
}
mods[0].Artifacts[0].Answered, mods[0].Artifacts[0].Steps = true, []string{"unit"}
said, err := g.r.ProposeSeed(ctx, mods, false, "indexer")
if err != nil || !strings.Contains(said, "1 registrations written") {
t.Fatalf("seed: %q, %v", said, err)
}
if len(g.asks) != 0 {
t.Fatalf("the seed asked the operator: %v", g.asks)
}
// A step the seat answers none for is bypass; the statuses the check judged are the rest.
got, _, _ := g.r.Registration(ctx, "a")
if got.Policy.Steps.Validate != "required" { // I7/AC2, design 47 H §745
t.Errorf("the seed wrote validate %q, want required", got.Policy.Steps.Validate)
}
if got.Version != 1 || got.Policy.Steps.Review != "optional" || got.Policy.Steps.Approval != "bypass" || got.Policy.Artifacts["program"].Lint != "bypass" || got.Policy.Artifacts["program"].Integration != "bypass" || got.Policy.Artifacts["program"].Unit != "" {
t.Fatalf("the seeded registration: %+v", got)
}
if _, err := g.r.ProposeSeed(ctx, mods, true, "s@n"); err == nil {
t.Fatal("the seed wrote over registrations the indexer holds")
}
// The seed leaves out no module for its branch's protection, and reads none (I9/AC2, design 47 H §764).
g2 := newRegRig()
reads := 0
branch := g2.r.Branch
g2.r.Branch = func(repo, b string) (gitseat.BranchAnswer, error) {
if b != "" {
reads++
}
return branch(repo, b)
}
seed, err := g2.r.ComposeSeed(mods)
if err != nil || len(seed.Registrations) != 1 || len(seed.Left) != 0 || reads != 0 {
t.Fatalf("seed: %+v, %v, %d reads of a named branch; want one registration, none left out, no protection read", seed, err, reads)
}
}
func TestCanonicalIsRFC8785(t *testing.T) {
got, err := Canonical(map[string]any{"b": []any{1, "x
"}, "a": map[string]any{"z": true, "y": nil}, "é": "<&>"})
if err != nil {
t.Fatal(err)
}
if want := "{\"a\":{\"y\":null,\"z\":true},\"b\":[1,\"x
\"],\"é\":\"<&>\"}"; string(got) != want {
t.Fatalf("canonical = %s, want %s", got, want)
}
if _, err := Canonical(map[string]any{"n": 1.5}); err == nil {
t.Fatal("a fraction has no canonical form here")
}
}