Files
mesh-catalog/modules/mesh-build-go/cmd/mesh-build-go/run_test.go
T
jschoubben c91ab3acfa build modules: the checker seat's invoke, its client and its fixtures go; a run's input is asked of the seat mesh-wants
The kinds check and recheck stay in H1 (H-A-117).

Builds: design 47 H §764 (the checker (H1)); lead answers H-A-57, H-A-117

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 04:59:05 +01:00

220 lines
9.8 KiB
Go

package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
const runCommit = "5555555555555555555555555555555555555555"
// runInputVerb is the seat verb a run ask's input is served on, as the ask names it.
const runInputVerb = "seat:mesh-wants.input"
// inputAnswerOf is the seat mesh-wants's answer of the input body as the tool runner hands it over: the digest and
// the whole file.
func inputAnswerOf(body []byte) map[string]any {
sum := sha256.Sum256(body)
return map[string]any{"digest": hex.EncodeToString(sum[:]), "chunks": 1, "file": base64.StdEncoding.EncodeToString(body)}
}
// answersInput is a seat verb serving body by its digest, as the seat mesh-wants' verb input answers.
func answersInput(body string) func(key string, b any) (json.RawMessage, error) {
return func(key string, b any) (json.RawMessage, error) {
ask, _ := b.(meshwants.InputInput)
if sum := sha256.Sum256([]byte(body)); key != runInputVerb || ask.Digest != hex.EncodeToString(sum[:]) {
return nil, fmt.Errorf("the assigner keeps no input %s", ask.Digest)
}
return json.Marshal(inputAnswerOf([]byte(body)))
}
}
func runAskOf(t *testing.T, body string) sdkstep.StepAsk {
t.Helper()
in, err := sdkstep.RunInputOf(runInputVerb, []byte(body))
if err != nil {
t.Fatal(err)
}
return sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner", At: time.Now(),
Run: &sdkstep.RunJob{Program: sdkstep.RunProgram{Repository: "novox/mesh-delivery", Commit: runCommit, Dir: ".", Package: "./cmd/prog"},
Heads: []sdkstep.RunHead{{Repository: "novox/mesh-sdk", Commit: runCommit}, {Repository: "novox/mesh-host", Commit: runCommit}},
Input: in, Args: []string{"-seats"}}}
}
// 1921/C1: a kept checking program is run over the input checked against its digest and the heads laid under
// MESH_RUN_HEADS at <owner>/<name>, and the answer carries its exit and last line; nothing is fetched or built; a
// program that fails, or says no JSON, is an answer; an input that is not the one named is refused; and the program was
// kept under sdkstep.RunKey, so a second ask finds it.
func TestAKeptProgramIsRunOverItsHeadsAndInput(t *testing.T) {
m := composeModule(t)
body := `{"v":1,"case":"x"}`
m.AskInput = answersInput(body)
m.PlaceHead = func(_ context.Context, h sdkstep.RunHead, dir string) error {
return os.MkdirAll(dir, 0o700)
}
a := runAskOf(t, body)
key := sdkstep.RunKey(a.Run.Program, sdkstep.ToolchainUsed{Version: "go1.26.0", Recipe: m.Recipe.Version()}, nil)
exe := m.programPath("programs", key)
os.MkdirAll(filepath.Dir(exe), 0o700)
script := "#!/bin/sh\n" +
`echo "noise"; echo "args $*" >&2; ` +
`printf '{"input":%s,"heads":"%s"}\n' "$(cat "$MESH_RUN_INPUT")" "$(cd "$MESH_RUN_HEADS" && ls -d */* | tr '\n' ' ')"; exit 3` + "\n"
if err := os.WriteFile(exe, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
fetched := 0
fetch := func(context.Context, map[string]any) (any, error) { fetched++; return nil, nil }
out, err := m.run(context.Background(), fetch, a)
if err != nil {
t.Fatal(err)
}
ans := out.(sdkstep.RunAnswer)
if ans.Built || ans.Key != key || fetched != 0 || ans.Exit != 3 || ans.Said != "args -seats" ||
string(ans.Output) != `{"input":{"v":1,"case":"x"},"heads":"novox/mesh-host novox/mesh-sdk "}` {
t.Fatalf("answer = %+v (fetched %d) output %s", ans, fetched, ans.Output)
}
if entries, _ := os.ReadDir(m.Work); len(entries) != 0 {
t.Errorf("the run's workspace was left: %v", entries)
}
// Shut off, the heads are bound read-only after the writable workspace, so a write under MESH_RUN_HEADS fails: a
// read-only bind before the workspace's is covered by it.
m.Inside = false
var argv []string
m.Run = func(_ context.Context, _ []string, _ string, args ...string) forgekey.Ran {
argv = args
return forgekey.Ran{Status: 0, Stdout: "{}"}
}
if _, err := m.run(context.Background(), fetch, a); err != nil {
t.Fatal(err)
}
line, ws, heads := " "+strings.Join(argv, " ")+" ", -1, -1
for i := 0; i+2 < len(argv); i++ {
switch {
case argv[i] == "--bind" && filepath.Dir(argv[i+1]) == m.Work:
ws = i
case argv[i] == "--ro-bind" && filepath.Base(argv[i+1]) == "heads" && argv[i+2] == argv[i+1]:
heads = i
}
}
if ws < 0 || heads < ws || !strings.Contains(line, " "+sdkstep.RunHeadsEnv+" "+argv[heads+1]+" ") {
t.Errorf("the heads are not bound read-only over the workspace: %s", line)
}
m.Inside, m.Run = true, StepRunner(t.TempDir())
// An input other than the one named is refused, naming it; one the verb does not answer fails the step, saying why.
m.AskInput = func(_ string, b any) (json.RawMessage, error) {
return json.Marshal(map[string]any{"digest": b.(meshwants.InputInput).Digest, "chunks": 1, "file": base64.StdEncoding.EncodeToString([]byte(`{"other":1}`))})
}
if _, err := m.run(context.Background(), fetch, a); err == nil || !strings.Contains(err.Error(), "is not the one the ask names") || !errors.As(err, new(*steprun.Refusal)) {
t.Errorf("a wrong input: %v", err)
}
m.AskInput = answersInput(`{"v":2}`)
if _, err := m.run(context.Background(), fetch, a); err == nil || !strings.Contains(err.Error(), "keeps no input") {
t.Errorf("an input the verb does not answer: %v", err)
}
}
// 1921/C2 (F2): a compose ask's seats reach the composer: the module decodes and fills the request and writes it again,
// and used to drop the seats.
func TestAComposeAskKeepsItsSeats(t *testing.T) {
m := composeModule(t)
read, digests := catalogHolds(t, `{"module":"demo","version":"1"}`)
m.ReadEntry = read
a := composeAskOf(t, digests[0])
req := composer.Request{V: composer.Version, Seats: []json.RawMessage{json.RawMessage(`{"seat":"node-x"}`)},
Cases: []composer.Case{{Name: "change", Manifests: map[string]composer.Manifest{"demo": {Digest: digests[0], Fingerprint: fingerprintOf(digests[0])}}}}}
a.Compose.Request, _ = json.Marshal(req)
key := sdkstep.ComposerKey("novox/mesh-sdk", composeCommit, "go", composer.Package, sdkstep.ToolchainUsed{Version: "go1.26.0", Recipe: m.Recipe.Version()}, nil)
exe := m.composerPath(key)
os.MkdirAll(filepath.Dir(exe), 0o700)
script := "#!/bin/sh\n" + `if grep -q '"seats":\[{"seat":"node-x"}\]' "$2"; then S=true; else S=false; fi; ` +
`echo '{"v":1,"sdk":"stand-in","cases":[{"name":"change","manifests":{"demo":{"accepted":'$S'}}}]}'` + "\n"
os.WriteFile(exe, []byte(script), 0o700)
out, err := m.compose(context.Background(), nil, a)
if err != nil {
t.Fatal(err)
}
var v composer.Verdict
if err := json.Unmarshal(out.(sdkstep.ComposeAnswer).Verdict, &v); err != nil || !v.Cases[0].Manifests["demo"].Accepted {
t.Fatalf("the composer did not receive the seats: %+v %v", v, err)
}
}
// Design 47 G §125, §206, §338, §354 (BLD14): a run's input is asked of the verb the ask names, so the indexer's and the
// assigner's runs read their own seat's input, and the manifest invokes both.
func TestARunsInputIsAskedOfTheVerbTheAskNames(t *testing.T) {
for _, verb := range []string{"seat:mesh-catalog.input", "seat:mesh-wants.input", runInputVerb} {
m := composeModule(t)
body := `{"v":1}`
var asked []string
m.AskInput = func(key string, b any) (json.RawMessage, error) {
asked = append(asked, key)
return answersInputOn(verb, body)(key, b)
}
a := runAskOf(t, body)
in, err := sdkstep.RunInputOf(verb, []byte(body))
if err != nil {
t.Fatal(err)
}
a.Run.Input = in
got, err := m.inputOf(a.Run.Input)
if err != nil || string(got) != body || len(asked) != 1 || asked[0] != verb {
t.Errorf("%s: input %q, err %v, asked %v", verb, got, err, asked)
}
}
doc := readManifest(t)
for _, verb := range []string{"seat:mesh-catalog.input", "seat:mesh-wants.input"} {
if !slices.Contains(doc.Invokes, verb) {
t.Errorf("the manifest does not invoke %s: %v", verb, doc.Invokes)
}
}
}
// answersInputOn is answersInput for the seat verb wanted.
func answersInputOn(wanted, body string) func(key string, b any) (json.RawMessage, error) {
return func(key string, b any) (json.RawMessage, error) {
ask, _ := b.(meshwants.InputInput)
if sum := sha256.Sum256([]byte(body)); key != wanted || ask.Digest != hex.EncodeToString(sum[:]) {
return nil, fmt.Errorf("%s keeps no input %s", key, ask.Digest)
}
return json.Marshal(inputAnswerOf([]byte(body)))
}
}
// Design 47 G A-237, A-249: the input of a run is of any size: the mesh-wants seat's verb input, marked chunks, is asked by the
// plain seat call and answers {digest, chunks, file}, the file whole as the tool runner received it; the bytes are checked.
func TestARunsInputOfAnySizeIsTakenFromTheChunkedVerb(t *testing.T) {
body := strings.Repeat("0123456789", 300000) // 3 MB
sum := sha256.Sum256([]byte(body))
in := sdkstep.RunInput{Verb: "seat:mesh-catalog.input", Digest: hex.EncodeToString(sum[:]), Size: len(body)}
m := &Module{AskInput: func(key string, b any) (json.RawMessage, error) {
if ask, _ := b.(meshwants.InputInput); key != in.Verb || ask.Digest != in.Digest {
return nil, fmt.Errorf("%s keeps no input %v", key, b)
}
return json.Marshal(map[string]any{"digest": in.Digest, "chunks": 6, "file": base64.StdEncoding.EncodeToString([]byte(body))})
}}
got, err := m.inputOf(in)
if err != nil || string(got) != body {
t.Fatalf("the input of %d bytes: %d bytes, %v", len(body), len(got), err)
}
in.Size--
if _, err := m.inputOf(in); err == nil || !errors.As(err, new(*steprun.Refusal)) {
t.Errorf("a file of another size than the ask names: %v", err)
}
}