Merge pull request 'node-engine: every process it runs gets MESH_NODE, a running one at its first pass after the update (issue 1984)' (#258) from fix/mesh-node-composition into main

This commit was merged in pull request #258.
This commit is contained in:
2026-11-25 14:35:24 +00:00
8 changed files with 331 additions and 10 deletions
+64 -1
View File
@@ -1,10 +1,22 @@
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
engcomp "github.com/novox/mesh-host/internal/compositions"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/apply"
engcomp "github.com/novox/mesh-host/internal/compositions"
"github.com/novox/mesh-host/internal/link"
)
// A composition that names a file the provisioner fills without saying it is filled would have this node-engine write
@@ -29,4 +41,55 @@ func TestAFileItCannotProduceIsNeverWrittenEmpty(t *testing.T) {
if d, _ = declarationOf(plain); refuseEmptyWrites(d) != nil {
t.Fatalf("a file with its content was refused: %v", refuseEmptyWrites(d))
}
// 1984/AC15, design 47 G A-342, through the module's apply (applyComposition and declarationOf, not Apply by hand): a process a
// composition places runs with its node's name as MESH_NODE; a composition naming no node, or compositions of two, are
// refused and nothing is applied.
t.Run("AProcessAComposedModulePlacesRunsWithItsNodesName", func(t *testing.T) {
var raw bytes.Buffer
zipped := gzip.NewWriter(&raw)
w := tar.NewWriter(zipped)
_ = w.WriteHeader(&tar.Header{Name: "main.js", Mode: 0o644, Size: 1, Typeflag: tar.TypeReg})
_, _ = w.Write([]byte("1"))
_ = w.Close()
_ = zipped.Close()
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write(raw.Bytes()) }))
t.Cleanup(server.Close)
proc := json.RawMessage(`{"id":"signin.runtime","type":"process","name":"signin","source":"` + server.URL + `/a.tar.gz","digest":"` +
declaration.DigestOf(raw.Bytes()) + `","run":["node","main.js"],"env":{"A":"1"}}`)
units := t.TempDir()
t.Cleanup(apply.ForTests(units, t.TempDir()))
opts := options{state: filepath.Join(t.TempDir(), "state.json"), out: &strings.Builder{},
runner: func(context.Context, string, ...string) (string, error) { return "", nil }}
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "pacman"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
wasBuilt := builtFor
builtFor = "arch"
t.Cleanup(func() { builtFor = wasBuilt })
say := link.Announce(func(string) {})
apply1 := func(c engcomp.Composed) string {
return applyComposition(context.Background(), opts, c, nil, nil, nil, nil, say).Detail
}
if why := apply1(engcomp.Composed{Module: "signin", Resources: []json.RawMessage{proc}}); !strings.Contains(why, "names no node") {
t.Errorf("a composition with no node was not refused: %q", why)
}
if _, err := declarationOf(engcomp.Composed{Node: "ace"}, engcomp.Composed{Node: "g14"}); err == nil {
t.Error("compositions of two nodes were not refused")
}
// Refused loudly means nothing applied: no unit was written by either refusal.
if _, err := os.Stat(filepath.Join(units, "signin.service")); err == nil {
t.Error("a refused composition wrote its unit")
}
res := applyComposition(context.Background(), opts, engcomp.Composed{Node: "ace", Module: "signin", Resources: []json.RawMessage{proc}},
nil, nil, nil, nil, say)
if res.Detail != "" {
t.Fatalf("the apply failed: %s", res.Detail)
}
if b, err := os.ReadFile(filepath.Join(units, "signin.service")); err != nil || !strings.Contains(string(b), `Environment="MESH_NODE=ace"`) {
t.Errorf("the unit does not carry the node's name (%v):\n%s", err, b)
}
})
}
+58 -5
View File
@@ -276,6 +276,49 @@ func awaitBackup(ctx context.Context, events <-chan []byte, node, module string,
}
}
// takenAtStartIn is what the agent does with a module taken as running at this start, with no apply: each record-held
// directory entry of it given its owner and mode where they drifted on disk (H-A-374, H-A-392), and the unit of each of
// its processes written again where it lacks its node's name (H-A-713), one line each.
func takenAtStartIn(opts options, say func(string)) func(module string, runs compositions.Composed) {
return func(module string, runs compositions.Composed) {
for _, line := range convergeDirectories(opts.state, runs) {
say(line)
}
for _, line := range convergeUnits(context.Background(), opts, runs) {
say(line)
}
}
}
// convergeUnits writes again the unit of each process of a module taken as running at this start whose unit as composed
// differs from its applied record's, and restarts a service of them (apply.ConvergeProcessUnits, H-A-713): the module's
// have is unchanged and nothing else of it is written, backed up or run. One line per process, and one when the
// composition or the state does not read.
func convergeUnits(ctx context.Context, opts options, runs compositions.Composed) []string {
d, err := declarationOf(runs)
if err != nil {
return []string{fmt.Sprintf("the units of %s are not judged at this start: its composition does not read: %v", runs.Module, err)}
}
applying.Lock()
defer applying.Unlock()
unlock, err := store.Lock(opts.state, nil)
if err != nil {
return []string{fmt.Sprintf("the units of %s are not judged at this start: %v", runs.Module, err)}
}
defer unlock()
known, err := store.Load(opts.state)
if err != nil {
return []string{fmt.Sprintf("the units of %s are not judged at this start: %v", runs.Module, err)}
}
now, lines := apply.ConvergeProcessUnits(ctx, d, known, opts.run())
if len(lines) > 0 {
if err := store.Save(opts.state, now); err != nil {
lines = append(lines, fmt.Sprintf("the record of the units of %s could not be saved: %v", runs.Module, err))
}
}
return lines
}
// convergeDirectories gives each directory entry of runs that this node's record holds, drifted on disk, its declared
// owner and mode (apply.ConvergeDirectories, H-A-374, H-A-392): one line per directory, and one when the record or the
// composition does not read.
@@ -301,6 +344,16 @@ func convergeDirectories(statePath string, runs compositions.Composed) []string
// ("2 resources declare X") on every node. The node's own copy is left out, and which were left out is said once.
func declarationOf(cs ...compositions.Composed) (*declaration.Declaration, error) {
d := &declaration.Declaration{Version: declaration.Version}
// The declaration is for the node its compositions are of (design 47 G A-342: every process runs with it as MESH_NODE).
// Compositions of one node carry one name; two names, or a name beside an empty one, refuse the declaration whole.
for _, c := range cs {
if c.Node != cs[0].Node {
return nil, fmt.Errorf("the compositions are of different nodes (%q and %q)", cs[0].Node, c.Node)
}
}
if len(cs) > 0 {
d.For = cs[0].Node
}
var modules []compositions.Composed
for _, c := range cs {
if c.Module != "" {
@@ -576,11 +629,7 @@ func nodeAgent(ctx context.Context, opts options, signer ed25519.PublicKey, trus
// again (ace, 2026-10-25 21:17).
// A module taken as running at this start has each record-held directory entry of it given its owner and mode
// where they drifted on disk, one line each (H-A-374, H-A-392).
TakenAtStart: func(module string, runs compositions.Composed) {
for _, line := range convergeDirectories(opts.state, runs) {
say(line)
}
},
TakenAtStart: takenAtStartIn(opts, say),
DirectoryDrift: func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem {
d, err := declarationOf(runs)
if err != nil {
@@ -920,6 +969,10 @@ func applyComposition(ctx context.Context, opts options, c compositions.Composed
if err != nil {
return failedWith(err.Error())
}
if d.For == "" {
// A process placed without its node's name would crash-loop on it (design 47 G A-342): refused, never applied.
return failedWith(fmt.Sprintf("the composition of %s names no node", name))
}
if err := refuseEmptyWrites(d); err != nil {
return failedWith(err.Error())
}
+116
View File
@@ -1,10 +1,21 @@
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/apply"
engcomp "github.com/novox/mesh-host/internal/compositions"
"github.com/novox/mesh-host/internal/system"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/novox/mesh-host/internal/liveness"
@@ -33,6 +44,110 @@ func testACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) {
}
}
// 1984/AC16 (H-A-713): a module taken as running at the start, whose processes a real apply recorded with units written
// without MESH_NODE, has those units written again with it: the service restarted, the run-once step written and not run,
// no other command (no backup is the agent's, never reached here), and nothing at the second pass. The record the
// comparison reads comes from a real apply (apply.Apply with no node, as the engine before the fix).
func testProcessUnitsWithoutTheNodesNameAreWrittenAgainAtTheStart(t *testing.T) {
var raw bytes.Buffer
zipped := gzip.NewWriter(&raw)
w := tar.NewWriter(zipped)
_ = w.WriteHeader(&tar.Header{Name: "main.js", Mode: 0o644, Size: 1, Typeflag: tar.TypeReg})
_, _ = w.Write([]byte("1"))
_ = w.Close()
_ = zipped.Close()
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write(raw.Bytes()) }))
t.Cleanup(server.Close)
one := func(id, name, extra string) json.RawMessage {
return json.RawMessage(`{"id":"` + id + `","type":"process","name":"` + name + `","source":"` + server.URL + `/a.tgz","digest":"` +
declaration.DigestOf(raw.Bytes()) + `","run":["node","main.js"],"env":{"A":"1"}` + extra + `}`)
}
service, step := one("m.service", "m-service", ""), one("m.step", "m-step", `,"run-once":true`)
units := t.TempDir()
t.Cleanup(apply.ForTests(units, t.TempDir()))
var commands []string
run := func(_ context.Context, name string, args ...string) (string, error) {
commands = append(commands, name+" "+strings.Join(args, " "))
return "", nil
}
sys, err := system.For("arch")
if err != nil {
t.Fatal(err)
}
d, err := declaration.Parse([]byte(`{"declaration":1,"resources":[` + string(service) + `,` + string(step) + `]}`))
if err != nil {
t.Fatal(err)
}
_, applied, err := apply.Apply(context.Background(), sys, d, store.State{}, store.OriginDeclared, run, nil, nil)
if err != nil {
t.Fatal(err)
}
state := filepath.Join(t.TempDir(), "state.json")
if err := store.Save(state, applied); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(units, "m-service.service")); strings.Contains(string(b), "MESH_NODE") {
t.Fatalf("the first apply, with no node, wrote the name:\n%s", b)
}
commands = nil
opts := options{state: state, out: &strings.Builder{}, runner: run}
c := engcomp.Composed{Node: "ace", Module: "m", Resources: []json.RawMessage{service, step}}
var said []string
takenAt := takenAtStartIn(opts, func(l string) { said = append(said, l) })
takenAt(c.Module, c)
if len(said) != 2 {
t.Fatalf("the first pass said %v; want one line per process", said)
}
for _, name := range []string{"m-service", "m-step"} {
if b, _ := os.ReadFile(filepath.Join(units, name+".service")); !strings.Contains(string(b), `Environment="MESH_NODE=ace"`) {
t.Errorf("%s was not written again with the node's name:\n%s", name, b)
}
}
if got := strings.Join(commands, "\n"); !strings.Contains(got, "systemctl restart m-service.service") ||
strings.Contains(got, "m-step") || strings.Contains(got, "pacman") {
t.Errorf("the first pass ran:\n%s; want the service restarted, the step not run, nothing else", got)
}
commands = nil
said = nil
takenAt(c.Module, c)
if len(said) != 0 || len(commands) != 0 {
t.Errorf("the second pass said %v and ran %v; want nothing", said, commands)
}
// 1984/AC16 (H-A-714): a process whose record names another bundle is left as it is, with a line naming both; and a
// units reload that fails is said, not skipped.
other := one("m.other", "m-other", `,"env":{"B":"2"}`)
var st store.State
st.Record(store.Applied{ID: "m.other", Type: "process", Target: "m-other", Wrote: "sha256:" + strings.Repeat("1", 64) + " unit"})
st.Record(store.Applied{ID: "m.service", Type: "process", Target: "m-service", Wrote: apply.ProcessWrote(mustProcess(t, service), "")})
if err := store.Save(state, st); err != nil {
t.Fatal(err)
}
say2 := []string{}
commands = nil
opts.runner = func(_ context.Context, name string, args ...string) (string, error) {
commands = append(commands, name+" "+strings.Join(args, " "))
return "", errors.New("no bus to the manager")
}
takenAtStartIn(opts, func(l string) { say2 = append(say2, l) })("m", engcomp.Composed{Node: "ace", Module: "m", Resources: []json.RawMessage{other, service}})
joined := strings.Join(say2, "\n")
if !strings.Contains(joined, "m-other") || !strings.Contains(joined, "sha256:"+strings.Repeat("1", 64)) || !strings.Contains(joined, declaration.DigestOf(raw.Bytes())) ||
!strings.Contains(joined, "units could not be reloaded") || !strings.Contains(joined, "m-service") {
t.Errorf("the lines were:\n%s", joined)
}
if b, _ := os.ReadFile(filepath.Join(units, "m-other.service")); strings.Contains(string(b), "MESH_NODE") {
t.Error("a process whose record names another bundle was written")
}
}
func mustProcess(t *testing.T, raw json.RawMessage) *declaration.Process {
t.Helper()
r, err := declaration.ParseResource(raw)
if err != nil {
t.Fatal(err)
}
return r.(*declaration.Process)
}
// The modules applied again are those with a missing resource, each once; one down but there is not among them.
func testTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) {
t.Run("1957: the machine shows a resource not active", testTheMachineShowsAResourceNotActive)
@@ -97,6 +212,7 @@ func testAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) {
// TestRecorded runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
func TestRecorded(t *testing.T) {
t.Run("ACompositionIsRecordedOnlyWhenEveryResourceIs", testACompositionIsRecordedOnlyWhenEveryResourceIs)
t.Run("ProcessUnitsWithoutTheNodesNameAreWrittenAgainAtTheStart", testProcessUnitsWithoutTheNodesNameAreWrittenAgainAtTheStart)
t.Run("TheModulesAppliedAgainAreThoseWithAMissingResource", testTheModulesAppliedAgainAreThoseWithAMissingResource)
t.Run("OnlyANewlyMissingResourceAppliesItsModuleAgain", testOnlyANewlyMissingResourceAppliesItsModuleAgain)
t.Run("AFilledFileDoesNotMakeItsCompositionUnrecorded", testAFilledFileDoesNotMakeItsCompositionUnrecorded)
+2 -1
View File
@@ -195,7 +195,8 @@ type Env struct {
Settled func(module string)
// TakenAtStart is told, outside the agent's lock, each module taken as running at this start from its have or the
// kept declaration, with no apply, and the composition it runs: the node-engine converges the owner and mode of each
// record-held directory entry of it (H-A-374, H-A-392). Nil tells nothing.
// record-held directory entry of it (H-A-374, H-A-392) and writes again the unit of each process of it whose unit
// lacks its node's name, restarting a service (H-A-713). Nil tells nothing.
TakenAtStart func(module string, runs compositions.Composed)
// DirectoryDrift reads, for the verb composition's diff, each directory entry of runs the mesh made whose owner or
// mode on disk differ (apply.DirectoryDrifts, H-A-392). Nil reads none.
+7
View File
@@ -1083,6 +1083,13 @@ func testADataModuleIsBackedUpFirstAndHeldWhenItFails(t *testing.T) {
if got := r.appliedList(); len(got) != 0 {
t.Fatalf("applied behind a hold with no answer: %v", got)
}
// 1984/AC17 (H-A-713): a held module is not taken as running at the start, so nothing of it is written again.
r.mu.Lock()
taken := len(r.takenAtStart)
r.mu.Unlock()
if taken != 0 {
t.Fatalf("a held module was told as taken at the start: %v", r.takenAtStart)
}
r.wants.put(wk, selfWant(row.later))
eventually(t, "the read tool does not say the answer", func() bool {
v, err := r.ag.Composition(context.Background(), "nats", "", false)
+1 -1
View File
@@ -1629,7 +1629,7 @@ func applyOne(ctx context.Context, sys system.System, r declaration.Resource, ru
if err != nil {
return begin(r), err
}
return applyProcess(ctx, withNode(res, in.node), run, changed, previous, held, in.away)
return applyProcess(ctx, res, in.node, run, changed, previous, held, in.away)
case *declaration.Action:
return applyAction(ctx, res, run)
case *declaration.Network:
+73
View File
@@ -0,0 +1,73 @@
package apply
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/store"
)
// ConvergeProcessUnits writes again the unit of each process of d whose unit as composed (ProcessWrote, with d's node)
// differs from the one its applied record says it wrote, for a module taken as running its want's composition at the
// engine's start (design 47 G A-342, H-A-713): the process then has the node's name in its env. A service is restarted; a
// run-once step's and a scheduled process's unit are written and neither run nor started, and take the name at their next
// run. Nothing else is written or run (no backup, no other resource), and the record takes the new unit, so a second pass
// finds nothing. A process with no record, or whose record holds another bundle than the composition's, is not touched: the
// apply of its new form gives it the name. It answers the changed record state and one line per process.
func ConvergeProcessUnits(ctx context.Context, d *declaration.Declaration, known store.State, run Runner) (store.State, []string) {
var lines []string
if d == nil {
return known, nil
}
for _, res := range d.Resources {
r, ok := res.(*declaration.Process)
if !ok {
continue
}
rec, held := known.Find(r.Identity())
if !held || rec.Type != string(declaration.TypeProcess) {
continue
}
have, same := strings.CutPrefix(rec.Wrote, r.Digest+" ")
want := ProcessWrote(r, d.For)
if !same {
// Another bundle than the composition's (or none) is what the record holds: the apply of the new form gives the
// name (H-A-714). Said, so that the process left as it is can be read from the journal.
named, _, _ := strings.Cut(rec.Wrote, " ")
if named == "" {
named = "none"
}
lines = append(lines, fmt.Sprintf("%s (%s) is left as it is at this start: its record names the bundle %s and the composition names %s",
r.Name, r.ID, named, r.Digest))
continue
}
if have == strings.TrimPrefix(want, r.Digest+" ") {
continue
}
unit := filepath.Join(unitDir, r.Name+".service")
if err := os.WriteFile(unit, []byte(unitFor(withNode(r, d.For))), 0o644); err != nil {
lines = append(lines, fmt.Sprintf("%s (%s) cannot be given its node's name at this start: %v", r.Name, r.ID, err))
continue
}
if _, err := run(ctx, "systemctl", "daemon-reload"); err != nil {
lines = append(lines, fmt.Sprintf("%s (%s) was written with its node's name and the units could not be reloaded: %v", r.Name, r.ID, err))
continue
}
verb := "written again with its node's name at this start"
if !r.RunOnce && r.Schedule == "" {
if _, err := run(ctx, "systemctl", "restart", r.Name+".service"); err != nil {
lines = append(lines, fmt.Sprintf("%s (%s) was written with its node's name and would not restart: %v", r.Name, r.ID, err))
continue
}
verb = "written again with its node's name and restarted at this start"
}
rec.Wrote = want
known.Record(rec)
lines = append(lines, fmt.Sprintf("%s (%s) %s", r.Name, r.ID, verb))
}
return known, lines
}
+10 -2
View File
@@ -42,8 +42,9 @@ var daemonRoot = "/var/lib/mesh/daemons"
// directory of its own.
var unitDir = "/etc/systemd/system"
func applyProcess(ctx context.Context, r *declaration.Process, run Runner,
func applyProcess(ctx context.Context, declared *declaration.Process, node string, run Runner,
changed map[string]bool, previous store.Applied, held []byte, away *storeAway) (Outcome, error) {
r := withNode(declared, node)
out := begin(r)
out.Action = "unchanged"
@@ -67,7 +68,7 @@ func applyProcess(ctx context.Context, r *declaration.Process, run Runner,
// **Its identity is its bytes AND how it is run.** Two processes from one bundle differing
// only in their command are different, and a record tracking the digest alone would call the
// second one unchanged.
want := got + " " + unitFor(r)
want := ProcessWrote(declared, node)
at := filepath.Join(daemonRoot, r.Name)
// **Something it reads changed, so it must be restarted even though it is unchanged.** A
@@ -293,6 +294,13 @@ func withNode(r *declaration.Process, node string) *declaration.Process {
return &p
}
// ProcessWrote is what the engine's record holds as written for a process on node: its bundle's digest and the unit it
// writes for it, with the node's name in its env (design 47 G A-342). The apply builds its record with it, and the start's
// comparison reads it (H-A-713, one function).
func ProcessWrote(r *declaration.Process, node string) string {
return r.Digest + " " + unitFor(withNode(r, node))
}
// drainStopMargin is the seconds a draining process's stop timeout lies above its drain bound: the time it takes to stop
// its children after its drain (H-A-358).
const drainStopMargin = 15