Files
mesh-host/internal/selfcompose/candidate.go
T
jschoubben dc3765bb7c Ask the packet filter's holder allowed at every compose of the filter
The node-engine stays the one renderer of the filter file: at each compose of
a converged node's filter it asks the holder of node-packet-filter its verb
allowed within the setting compose-ask-bound (10 s) and renders the answer.
When allowed does not answer, or answers what is not its answer, no filter file
is composed: the one loaded is kept as it runs, the holder's module is not held
(an old holder must stay replaceable), and the part withheld is said once in
the journal until an answer comes between. The node hears allowances-changed
on its own node's subject and composes again. The manifest invokes
seat:node-packet-filter.allowed and consumes node-packet-filter.allowances-changed.

Builds: design 08 control-verbs §1, §3, §4, §5, §7, §8; ADR 0683; H-A-305, H-A-307 (1), (2), H-A-314 (3), (5), (7), H-A-315 (2), (6), H-A-321
2026-11-21 22:32:36 +01:00

561 lines
22 KiB
Go

package selfcompose
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"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/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/keys"
"github.com/novox/mesh-host/internal/buckets"
engcomp "github.com/novox/mesh-host/internal/compositions"
"maps"
"slices"
"sort"
"strings"
"sync"
"time"
nec "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"github.com/novox/mesh-host/internal/agent"
"github.com/novox/mesh-host/internal/compose/frombus"
"github.com/novox/mesh-host/internal/composer"
)
// **A check's candidate, composed in shadow on a call** (novox/hq ADR 0593 §7): the node seat's verb compose-candidate.
// Given the check's composition key (`<group>.<heads hash>`), it reads the group's candidate from the indexer
// (buckets.Candidates, keyed by the group alone, buckets.CandidateKey) at those heads, and composes itself
// twice from what its shadow holds (assignment, records, the indexer's modules, its config values), with its own sealed
// values: once as it is, and once with the candidate's modules laid over the indexer's (each at the candidate's
// fingerprint, its manifest by digest and the indexer's verdict on it, ADR 0578 §3; a module the candidate removes left
// out). It answers per module placed here composed (its digest, and whether the candidate changes it), refused by the
// candidate, or held without it too, and the verdict of its own composition. It applies nothing and writes nothing: it
// composes on a copy of the shadow's inputs, so neither the shadow's answers nor the node's own composer move.
// errNotReady is a shadow that has not read every input yet.
var errNotReady = errors.New("this node's shadow has not read every input yet")
// candidateWithin is the node's own bound on an answer to compose-candidate: shorter than the checker's
// (nec.AnswerBound), because the bus lets the engine answer an ask only within a minute of it (the grants
// part's allow_responses ttl, mesh-grants ResponseTTL): an answer at the checker's 60 s bound was refused by the bus
// (issue 1126, 2026-11-03 01:17:04 on shanks, "Permissions Violation for Publish to _INBOX..."), so the checker heard
// nothing at all. A node not done by then answers unready, naming what it waits on.
var candidateWithin = nec.AnswerBound - 10*time.Second
// maxSentInput is the most composition input an answer carries: the bus carries 1 MiB in one message (its max_payload),
// and the answer's own fields and envelope come beside it.
const maxSentInput = 900 << 10
// warmAtOnce is how many of the indexer's manifests the shadow reads at once before it composes a candidate.
const warmAtOnce = 8
// candidateRun is what one ask's compositions wait on: each scratch composer it made, the last the one composing now.
type candidateRun struct {
mu sync.Mutex
parts []*Composer
}
func (r *candidateRun) add(c *Composer) *Composer {
r.mu.Lock()
defer r.mu.Unlock()
r.parts = append(r.parts, c)
return c
}
// said is the run's waits in words: how many reads it waited on the bus or the vault for, and the longest; and, while
// one is still running (now), what it waits on and since when.
func (r *candidateRun) said(now time.Time) (waits string, on string) {
r.mu.Lock()
parts := slices.Clone(r.parts)
r.mu.Unlock()
n, longest, longestOn := 0, time.Duration(0), ""
for _, c := range parts {
c.doingMu.Lock()
n += c.waits.n
if c.waits.longest > longest {
longest, longestOn = c.waits.longest, c.waits.longestOn
}
if c.doing != "" {
on = fmt.Sprintf("%s (for %s)", c.doing, now.Sub(c.doingSince).Round(time.Millisecond))
} else if on == "" && c.waits.lastOn != "" {
on = c.waits.lastOn + " (the last read)"
}
c.doingMu.Unlock()
}
waits = fmt.Sprintf("%d read(s) waited on", n)
if longestOn != "" {
waits += fmt.Sprintf(", the longest %s on %s", longest.Round(time.Millisecond), longestOn)
}
if on == "" {
on = "nothing it reads (composing)"
}
return waits, on
}
// ComposeCandidate is the node's answer to ask, within candidateWithin (or ctx's deadline, if sooner). Each answer is
// said in one line, with what it waited on and for how long (issue 1126: ace, g14 and shanks answered nothing for a
// minute while nothing said why). An answer not composed within the bound is unready, naming what the node waits on.
func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCandidateInput) nodeengine.ComposeCandidateAnswer {
s.mu.Lock()
c := s.c
s.mu.Unlock()
began := c.now()
ctx, cancel := context.WithTimeout(ctx, candidateWithin)
defer cancel()
run := &candidateRun{}
done := make(chan nodeengine.ComposeCandidateAnswer, 1)
go func() { done <- s.composeCandidate(ctx, c, ask, began, run) }()
var a nodeengine.ComposeCandidateAnswer
select {
case a = <-done:
case <-ctx.Done():
_, on := run.said(c.now())
a = nodeengine.ComposeCandidateAnswer{Node: c.env.Node, Candidate: ask.Candidate, Verdict: nec.Unready,
Refused: fmt.Sprintf("the node did not compose the candidate within %s: it waits on %s", candidateWithin, on),
Took: c.now().Sub(began).Milliseconds()}
}
waits, _ := run.said(c.now())
words := ""
if a.Refused != "" {
words = ": " + a.Refused
}
c.env.Say(fmt.Sprintf("compose-candidate %s answered %s in %s (%s)%s", ask.Candidate, a.Verdict,
(time.Duration(a.Took) * time.Millisecond).String(), waits, words))
return a
}
// composeCandidate composes ask on scratch copies of c, each added to run as it starts.
func (s *Shadow) composeCandidate(ctx context.Context, c *Composer, ask nodeengine.ComposeCandidateInput, began time.Time, run *candidateRun) nodeengine.ComposeCandidateAnswer {
node := c.env.Node
a := nodeengine.ComposeCandidateAnswer{Node: node, Candidate: ask.Candidate}
refuse := func(why string) nodeengine.ComposeCandidateAnswer {
a.Verdict, a.Refused, a.Modules, a.Own = nec.Refused, why, nil, nodeengine.Module{}
a.Took = c.now().Sub(began).Milliseconds()
return a
}
// A node that cannot compose now (its shadow not ready, a read the bus did not answer, the bound passed) answers
// unready: the checker takes it as no answer (ADR 0593 §9) by the verdict, the words only saying why.
unready := func(why string) nodeengine.ComposeCandidateAnswer {
a = refuse(why)
a.Verdict = nec.Unready
return a
}
key, err := nec.ParseCandidateKey(ask.Candidate)
if err != nil {
return refuse(err.Error())
}
if !s.ready.Load() {
return unready(errNotReady.Error())
}
base := run.add(c.scratch())
var cand meshcatalog.CandidatesByGroupValue
var group, heads string
if key.Kind == nec.CandidateRevision {
// A branch pipeline's catalog graph revision (A-226b): its entries are read through the seat mesh-catalog's verb
// revision and composed as the candidate, each module at the revision's fingerprint.
var answered bool
cand, answered, err = s.revisionCandidate(ctx, base, key)
if err != nil {
return unready(err.Error())
}
if !answered {
return refuse(fmt.Sprintf("the catalog holds no revision %d of the branch %s", key.Revision, key.Branch))
}
} else {
group, heads = key.Group, key.HeadsHash
if key.Kind == nec.CandidateRun {
// A run on request's candidate is the indexer's `candidates.run-<id>`, read by its group as a check's is, with no
// heads to compare: the run is asked for by its id alone (A-226c).
group, heads = "run-"+key.Run, ""
}
// The ask names the check (the composition key, `<group>.<heads hash>`); the indexer keys the group's candidate by
// the group alone (buckets.CandidateKey) and holds its heads hash in the value.
ckey, err := buckets.CandidateKey(group)
if err != nil {
return refuse(err.Error())
}
raw, err := base.get(ctx, buckets.Candidates, ckey)
if err != nil {
return unready(fmt.Sprintf("the indexer's candidate %s cannot be read: %v", ask.Candidate, err))
}
if raw == nil {
return refuse("the indexer holds no candidate " + ask.Candidate)
}
cand, err = meshcatalog.DecodeCandidatesByGroupValue(raw)
if err != nil {
return refuse(fmt.Sprintf("the indexer's candidate %s cannot be read: %v", ask.Candidate, err))
}
if key.Kind == nec.CandidateCheck && cand.Heads != heads {
// The group moved to other heads: the check asked is replaced, and this node composes not a candidate it was
// not asked about. No answer (ADR 0593 §9), never a verdict on the wrong heads.
return unready(fmt.Sprintf("the indexer's candidate of the group %s is at heads %s, not %s: the check asked is replaced", group, cand.Heads, heads))
}
}
// Every module's manifest is read before either composition, several at once, into the shadow's own: a composition
// reads every manifest in the mesh one by one, which off the control-node took about 35 s each (issue 1126).
base.warm(ctx, c, cand)
var running []engcomp.Composed
if c.env.Running != nil {
running = c.env.Running()
}
baseComps, baseHeld, baseErr := base.composeShadow(ctx, running, nil, nil)
// The candidate laid over a copy taken after the composition without it, so what that read is not read again.
laid := run.add(c.scratch())
touched, err := laid.layCandidate(ctx, cand)
if err != nil {
return unready(err.Error())
}
sentSize := 0
laidComps, laidHeld, laidErr := laid.composeShadow(ctx, running, touched, func(scope frombus.Scope, fps map[string]string) {
if !ask.Input {
return
}
// Read as the composition reads it, at the builds it composes at, with how it composes (compose.Input.ComposedHow),
// so the sandbox composes this node through the same path (issue 774).
in, err := frombus.ComposingInput(ctx, reader{c: laid}, laid.env.Mesh, scope, fps)
if err != nil {
return
}
// What the node holds composing without the candidate, a module blamed for a refusal among them, is no refusal of
// the change (review round 1).
in.ComposedHow.HeldBefore = maps.Clone(baseHeld)
// As the sandbox reads it (composer.SentInput, the one shape): this node's own modules as taken in from their
// builds, every other module's manifest left to the cases.
// The seat's contract carries it as a JSON object; its numbers are kept as written (json.Number).
if body, err := json.Marshal(composer.SentInput(in, laid.env.Node)); err == nil {
d := json.NewDecoder(bytes.NewReader(body))
d.UseNumber()
var obj map[string]any
if d.Decode(&obj) == nil {
a.Input, sentSize = obj, len(body)
}
}
})
// An ask with a call token takes the input in chunks, whatever its size (A-237b); one with none is the checker's, answered
// inline until G removes the checker (G-6 §321, A-237c), so past what the bus carries in one answer it is refused.
if sentSize > maxSentInput && ask.Call == "" {
// Past what the bus carries in one answer, the checker would hear nothing: refused, saying so.
size := sentSize
a.Input = nil
return refuse(fmt.Sprintf("the composition input this node composed from is %d bytes, more than the %d an answer on the bus carries", size, maxSentInput))
}
if ctx.Err() != nil {
_, on := run.said(c.now())
return unready(fmt.Sprintf("the node did not compose the candidate within %s: it waits on %s", candidateWithin, on))
}
switch {
case laidErr != nil && BusFailed(laidErr):
return unready("a read on the bus did not answer: " + laidErr.Error())
case laidErr != nil && baseErr != nil:
// The node composes none of its own without the candidate either: the candidate changes nothing of that.
a.Verdict, a.Modules = nec.Composed, []nodeengine.Module{}
a.Own = nodeengine.Module{Module: nec.NodeWord, State: nec.ModuleHeld, Words: laidErr.Error()}
a.Took = c.now().Sub(began).Milliseconds()
return a
case laidErr != nil:
return refuse(laidErr.Error())
}
byModule := func(comps map[string]engcomp.Composed) map[string]engcomp.Composed {
out := map[string]engcomp.Composed{}
for _, comp := range comps {
out[comp.Module] = comp
}
return out
}
was, now := byModule(baseComps), byModule(laidComps)
one := func(module string) (nodeengine.Module, bool) {
m := nodeengine.Module{Module: module}
if module == "" {
m.Module = nec.NodeWord
}
if why, held := laidHeld[module]; held {
m.State, m.Words = nec.ModuleRefused, why
if _, before := baseHeld[module]; before || baseErr != nil {
m.State = nec.ModuleHeld
}
return m, true
}
comp, ok := now[module]
if !ok {
return m, false
}
dig, err := engcomp.DigestOf(comp)
if err != nil {
m.State, m.Words = nec.ModuleRefused, err.Error()
return m, true
}
m.State, m.Fp, m.Digest = nec.ModuleComposed, comp.FP, dig
if before, ok := was[module]; !ok {
m.Changed = true
} else if d, err := engcomp.DigestOf(before); err != nil || d != dig {
m.Changed = true
}
return m, true
}
modules := map[string]bool{}
for m := range now {
modules[m] = m != ""
}
for m := range laidHeld {
modules[m] = m != "" && m != agent.NodeModule
}
names := make([]string, 0, len(modules))
for m, isModule := range modules {
if isModule {
names = append(names, m)
}
}
sort.Strings(names)
a.Modules = []nodeengine.Module{}
refused := false
for _, m := range names {
if mc, ok := one(m); ok {
a.Modules = append(a.Modules, mc)
refused = refused || mc.State == nec.ModuleRefused
}
}
if own, ok := one(""); ok {
a.Own = own
} else {
a.Own = nodeengine.Module{Module: nec.NodeWord, State: nec.ModuleHeld,
Words: "the node composes no composition of its own"}
}
refused = refused || a.Own.State == nec.ModuleRefused
a.Verdict = nec.Composed
if refused {
a.Verdict = nec.Refused
}
a.Took = c.now().Sub(began).Milliseconds()
return a
}
// scratch is a composer over a copy of what c holds of its inputs, for composing in shadow without moving c.
func (c *Composer) scratch() *Composer {
out := New(c.env)
c.mu.Lock()
defer c.mu.Unlock()
out.assignments = maps.Clone(c.assignments)
out.records = maps.Clone(c.records)
out.inOwn = maps.Clone(c.inOwn)
out.modules = maps.Clone(c.modules)
out.values = maps.Clone(c.values)
out.manifests = maps.Clone(c.manifests)
out.archives = maps.Clone(c.archives)
// The entries it holds and the wants that name them give a build (buildOf), as the builder's builds once did.
out.keptEnt = maps.Clone(c.keptEnt)
out.wants = maps.Clone(c.wants)
out.sealedOwn = maps.Clone(c.sealedOwn)
out.ownHanded = maps.Clone(c.ownHanded)
out.certified = c.certified
out.assignmentKeys = c.assignmentKeys
out.origin = c
out.forCandidates = c.forCandidates
return out
}
// warm reads, several at once, each manifest the indexer's modules and the candidate name that the shadow (origin) does
// not hold yet, keeping each in origin and in c; one not read is left to the composition, which reads it and says why.
// Its reads are not noted as the bus failing: the composition that reads again notes its own.
func (c *Composer) warm(ctx context.Context, origin *Composer, cand meshcatalog.CandidatesByGroupValue) {
origin.mu.Lock()
want := map[string]bool{}
for _, m := range origin.modules {
if _, ok := origin.manifests[m.Manifest]; m.Manifest != "" && !ok {
want[m.Manifest] = true
}
}
for _, pull := range cand.Pulls {
for _, cm := range pull.Fps {
if _, ok := origin.manifests[cm.Manifest]; cm.Manifest != "" && !ok {
want[cm.Manifest] = true
}
}
}
origin.mu.Unlock()
if len(want) == 0 {
return
}
defer c.waiting(fmt.Sprintf("%d of the indexer's manifests (%s)", len(want), buckets.Manifests))()
slots := make(chan struct{}, warmAtOnce)
var wg sync.WaitGroup
for digest := range want {
key, err := meshcatalogclient.ManifestsKey(digest)
if err != nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
select {
case slots <- struct{}{}:
case <-ctx.Done():
return
}
defer func() { <-slots }()
value, err := c.env.Get(ctx, buckets.Manifests, key)
if err != nil || value == nil {
return
}
m, err := meshcatalogclient.DecodeManifest(value)
if err != nil {
return
}
c.keepRead(func(k *Composer) { k.manifests[digest] = []byte(m.Manifest) })
}()
}
wg.Wait()
}
// layCandidate lays the candidate's modules over the indexer's: each at its fingerprint, with its manifest's digest and
// a module the candidate removes goes (design 47 H, H-A-79: the seat keeps no verdicts).
// It answers the modules laid.
func (c *Composer) layCandidate(ctx context.Context, cand meshcatalog.CandidatesByGroupValue) (map[string]bool, error) {
touched := map[string]bool{}
for _, pull := range cand.Pulls {
for module, cm := range pull.Fps {
if cm.None2 == candidateNoneNoModule {
c.mu.Lock()
delete(c.modules, module)
c.mu.Unlock()
continue
}
if cm.Fp2 == "" {
continue // no fingerprint at the preview: composed as the trunk holds it
}
m := meshcatalog.ModulesByModuleValue{Fp2: cm.Fp2, Manifest: cm.Manifest, Repository: pull.Repository, Commit: pull.Head}
c.mu.Lock()
c.modules[module] = m
c.mu.Unlock()
touched[module] = true
}
}
return touched, nil
}
// composeShadow composes this node from what c holds, as the shadow composes it (shadowBuilds): each module at the build
// it runs, one placed and not run at the indexer's, and one the candidate laid (laid) at the candidate's. input, when
// given, is handed the scope.
func (c *Composer) composeShadow(ctx context.Context, running []engcomp.Composed, laid map[string]bool, input func(frombus.Scope, map[string]string)) (map[string]engcomp.Composed, map[string]string, error) {
node := c.env.Node
c.mu.Lock()
assignment, placed := c.assignments[node]
modules := maps.Clone(c.modules)
inOwn := c.inOwnOf(assignment)
c.mu.Unlock()
if !placed {
return nil, nil, errors.New("this node's key in the seat's assignment state is gone: it composes nothing of its own")
}
fps := shadowBuilds(running, assignment, modules, inOwn)
// A module the laid candidate changes is composed at the candidate's build, though the node runs another.
for module := range fps {
if mod, ok := modules[module]; ok && laid[module] {
fps[module] = mod.Fp2
}
}
kept := map[string]string{}
for module, fp := range fps {
if mod, ok := modules[module]; ok && mod.Fp2 == fp {
continue
}
kept[module] = fp
}
wants := map[string]meshwants.WantsByWantNodeModuleValue{agent.NodeModule: {}}
for module, fp := range fps {
wants[module] = meshwants.WantsByWantNodeModuleValue{Fp: fp}
}
c.mu.Lock()
c.wants = wants
c.mu.Unlock()
scope := frombus.Scope{Node: node, KeptAt: kept, InOwn: inOwn, Running: running, SameValue: c.sameValue, Heard: c.heardNow(), RunningManifest: c.runningFor(node), Filter: c.lastFilter(node)}
if input != nil {
input(scope, fps)
}
comps, _, held, err := frombus.Compose(ctx, reader{c: c}, c.env.Mesh, scope, fps)
if err != nil {
return nil, nil, err
}
for key, comp := range comps {
comps[key] = c.keepRunning(comp, running)
}
return comps, held, nil
}
// candidateNoneNoModule is the words the indexer writes in a candidate's module that the merge preview names no manifest
// for: the change removes the module. It is the indexer's text, kept here until the catalogue client names it.
const candidateNoneNoModule = "the merge preview names no manifest for the module's directory"
// revisionCandidate reads the catalog graph revision key names, whole, page by page, through the seat mesh-catalog's verb
// revision (the Entry call, the engine's own name), and makes the candidate it composes as: one pull per repository and
// commit with each module's fingerprint and manifest digest, and a module the base holds that the revision does not marked as
// removed. answered is false when the catalog holds no such revision.
func (s *Shadow) revisionCandidate(ctx context.Context, base *Composer, key nec.Candidate) (cand meshcatalog.CandidatesByGroupValue, answered bool, err error) {
call := base.env.Entry
if call == nil {
return cand, false, errors.New("this node's engine cannot ask the catalog for a revision")
}
in := meshcatalog.RevisionInput{Branch: keys.EscapeName(key.Branch), Revision: key.Revision}
type group struct{ repository, commit string }
pulls := map[group]map[string]meshcatalog.CandidatesByGroupValuePullsItemFpsValue{}
seen := map[string]bool{}
for {
raw, err := call(meshcatalogclient.RevisionVerb, in)
if err != nil {
return cand, false, fmt.Errorf("the catalog's revision %d of %s cannot be read: %w", key.Revision, key.Branch, err)
}
body, said, ok := buscalls.Unwrap(raw)
if !ok {
return cand, false, fmt.Errorf("the catalog's revision %d of %s cannot be read: %s", key.Revision, key.Branch, said)
}
var a meshcatalog.RevisionAnswer
if err := json.Unmarshal(body, &a); err != nil {
return cand, false, fmt.Errorf("the catalog's revision %d of %s is not a revision answer: %w", key.Revision, key.Branch, err)
}
if a.NoneYet || a.Revision == nil || a.Revision.Revision != key.Revision {
return cand, false, nil
}
for _, e := range a.Entries {
seen[e.Module] = true
if e.Fp == "" {
continue // no build at the revision: composed as the trunk holds it
}
g := group{e.Repository, e.Commit}
if pulls[g] == nil {
pulls[g] = map[string]meshcatalog.CandidatesByGroupValuePullsItemFpsValue{}
}
// The catalog entry's manifest-digest is the `sha256:`-prefixed form (the seat's definition, entryManifest); a candidate's
// module and the manifests and verdicts keys carry the 64 hex digits alone (ADR 0429 clause 16, meshcatalogclient).
pulls[g][e.Module] = meshcatalog.CandidatesByGroupValuePullsItemFpsValue{Fp2: e.Fp, Manifest: strings.TrimPrefix(e.ManifestDigest, "sha256:")}
}
if a.Next == "" {
break
}
in.After = a.Next
}
removed := map[string]meshcatalog.CandidatesByGroupValuePullsItemFpsValue{}
base.mu.Lock()
for module := range base.modules {
if !seen[module] {
removed[module] = meshcatalog.CandidatesByGroupValuePullsItemFpsValue{None2: candidateNoneNoModule}
}
}
base.mu.Unlock()
cand.Group = key.Branch
for g, fps := range pulls {
cand.Pulls = append(cand.Pulls, meshcatalog.CandidatesByGroupValuePullsItem{Repository: g.repository, Head: g.commit, Fps: fps})
}
sort.Slice(cand.Pulls, func(i, j int) bool {
return cand.Pulls[i].Repository+cand.Pulls[i].Head < cand.Pulls[j].Repository+cand.Pulls[j].Head
})
if len(removed) > 0 {
cand.Pulls = append(cand.Pulls, meshcatalog.CandidatesByGroupValuePullsItem{Fps: removed})
}
return cand, true, nil
}