Files
mesh-catalog/modules/mesh-build-go/cmd/mesh-build-go/digest.go
T
jschoubben 98da0e0b68 M1 check-needs: a package outside every Go artifact's from takes the manifest's own check-needs
The forge module's internal/seatgit whole test needs the Node build seat, and no Go artifact's from holds it, so
nothing named its need and the Go build seat ran it on a node without the Node toolchain. The manifest now says the
need at its top level, read by the Go build module for such packages; gitea declares node-build-node
(review round 1, mesh-catalog, finding on §800; H-A-453 (2)).

Builds: design 47 H2 §800, H-A-453 (2)
2026-11-22 02:27:36 +01:00

646 lines
24 KiB
Go

package main
// The digest step (novox/hq ADR 0445 §5, ADR 0444; issue 1291): for each package of a workspace that has tests at a
// level, one digest of everything those tests read. The checker keys the verdict it keeps by it, so a package whose
// digest is unchanged is not run again. The tool answers in its call (it is short, ADR 0469 §2).
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// DigestVersion is the form of the digest's text: changed whenever what the digest hashes changes in kind.
// 2: no Go version in the text; the toolchain enters a fingerprint as the agreed version (ADR 0477 §3). 3: the siblings'
// commits (the lead's decision L5) and the integration level's tags integration,isolation (the checker's agreement).
// 4: the siblings' commits enter only the digest of a package whose tests reach a file naming MESH_CHECK_BESIDE (ADR 0536 §1).
// 5: a catalogue module's non-Go files enter the digest of its packages (issue 1935).
// 6: a reads-outside marker that lists what its tests read enters the digest with those files' contents (issue 1936).
const DigestVersion = "6"
// besideVariable is the name a file bears when it reads where the siblings lie; a package whose tests reach such a file
// depends on the siblings' commits.
const besideVariable = "MESH_CHECK_BESIDE"
// namesVariable is the same for the mesh's node names: a package whose tests reach a file naming it depends on the node
// list the ask carries, so its digest holds the sorted names and a new node misses a kept verdict (ADR 0567 §15).
const namesVariable = "MESH_NODE_NAMES"
// ReadsOutsideMarker is the name of a file in a package's directory that says its tests read files outside it (a
// repository's documents, a sibling directory), which the Go toolchain does not list (issue 1935). It lists, one per
// line, what those tests read, as paths from the repository's root; a path may be a glob (filepath.Match), and a
// directory it names is read whole (issue 1936). Blank lines and lines starting with # are not read. A line starting
// with ? names a path whose absence is what the tests read (a file that must not be there): it may match nothing.
//
// The digest then hashes, besides what the toolchain lists, every line of the marker, every file it names (under its
// path in the tree, by content) and every file of the package's own directory, Go files included (a file its build tags
// exclude is one go list does not hash). A marker that lists nothing, a line that is not a clean relative path, or a
// line without ? that matches nothing makes the package one that is never kept (its digest a fresh random hex): a list
// nobody can trust keeps nothing. The exact fix, the files a test opened kept
// from the Go test log with each verdict, replaces the lists (issue 1936).
const ReadsOutsideMarker = "reads-outside"
// readNeeds is what a package's integration tests need of the node they run on (issue 890; mesh-delivery-sdk
// steprun.AskNeeds): the seats its module's manifest names in `check-needs` on each Go artifact whose path holds the
// package's directory (design 47 H2 §800; H-A-350 DMC-6, H-A-399 (3)), `node-build-node` for tests that read the Node
// build module's installed toolchain, and for a package none of its Go artifacts holds, the manifest's own top-level
// `check-needs` (H-A-453 (2)). The manifest is the nearest module.json in dir or above it within the tree; nil when
// there is none, or it names no needs for dir. The digest reports it (DigestResult.Needs); a check ask
// leaves such a package untested on a node that lacks it, and the checker asks it again of a node that has it. The unit
// level is never given anything of the node (ADR 0533 §1), so the field binds the integration level alone.
func readNeeds(tree, dir string) ([]string, error) {
for at := dir; within(tree, at); at = filepath.Dir(at) {
raw, err := os.ReadFile(filepath.Join(at, "module.json"))
if errors.Is(err, fs.ErrNotExist) {
if at == tree {
break
}
continue
}
if err != nil {
return nil, err
}
manifest, err := catalogue.Decode(raw)
if err != nil {
return nil, fmt.Errorf("the manifest %s: %w", filepath.Join(at, "module.json"), err)
}
var needs []string
held := false
if manifest.Build != nil {
for _, a := range manifest.Build.Artifacts {
if a.Language != "go" || !within(filepath.Join(at, filepath.FromSlash(a.From)), dir) {
continue
}
held = true
for _, n := range a.CheckNeeds {
if !slices.Contains(needs, n) {
needs = append(needs, n)
}
}
}
}
if !held {
// A package no Go artifact's from holds (the forge module's internal/seatgit) takes the manifest's own
// check-needs (H-A-453 (2)).
needs = slices.Clone(manifest.CheckNeeds)
}
return needs, nil
}
return nil, nil
}
// integrationTags are the build tags of the integration level, its run and its digest alike: integration, and isolation
// for the bubblewrap proofs (mesh-sdk's and the build modules'), which a build node can run.
var integrationTags = []string{"integration", "isolation"}
// goPackage is the part of `go list -json` a digest reads.
type goPackage struct {
ImportPath string
Dir string
ForTest string
Standard bool
DepOnly bool
Deps []string
Module *goModule
// The files a package is built and tested from.
GoFiles, CgoFiles, CFiles, CXXFiles, MFiles, HFiles, FFiles, SFiles, SwigFiles, SwigCXXFiles, SysoFiles []string
TestGoFiles, XTestGoFiles []string
EmbedFiles, TestEmbedFiles, XTestEmbedFiles []string
}
type goModule struct {
Path, Version, Sum string
Main bool
Replace *goModule
Dir string
GoVersion string
}
func (p *goPackage) files() []string {
var all []string
for _, l := range [][]string{p.GoFiles, p.CgoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SwigFiles,
p.SwigCXXFiles, p.SysoFiles, p.TestGoFiles, p.XTestGoFiles, p.EmbedFiles, p.TestEmbedFiles, p.XTestEmbedFiles} {
all = append(all, l...)
}
sort.Strings(all)
return slicesCompact(all)
}
func slicesCompact(s []string) []string {
out := s[:0:0]
for i, v := range s {
if i == 0 || v != s[i-1] {
out = append(out, v)
}
}
return out
}
// hasTests says whether the package has test files at the level go list was asked for.
func (p *goPackage) hasTests() bool { return len(p.TestGoFiles)+len(p.XTestGoFiles) > 0 }
// DigestResult is what a digest step answers: one digest per package that has tests at the level, and the packages
// that have none.
type DigestResult struct {
Level string `json:"level"`
Packages map[string]string `json:"packages"`
// Beside echoes the siblings folded into every digest, "<owner/repo> <commit>" sorted: the checker keeps a verdict
// only when they are the siblings it gave the fetch.
Beside []string `json:"beside,omitempty"`
WithoutTests []string `json:"without_tests,omitempty"`
// ReadsOutside names the packages whose marker lists nothing it can trust (ReadsOutsideMarker): each has a digest
// that no kept verdict can have (a fresh random one), so the check runs it every time.
ReadsOutside []string `json:"reads_outside,omitempty"`
// neverKept is, per package of ReadsOutside, why its marker cannot be trusted; hashedFiles caches the content lines
// of the files markers name, which several packages share (the catalogue's manifests).
neverKept map[string]string
hashedFiles map[string]string
// Needs are the packages whose tests at this level need something of the node, as their module's manifest names them (check-needs).
Needs []sdkstep.PackageNeeds `json:"needs,omitempty"`
// JudgedBy is the program that ran the digest (ADR 0535 §5): "installed", or "candidate <merge commit>" under the
// runner workspace.
JudgedBy string `json:"judged_by,omitempty"`
}
func (m *Module) digestTool() StepTool {
return StepTool{
Name: "build_go_digest",
Description: "One digest per package of a fetched workspace, for one level, of everything that package's tests read: " +
"the files of each package the tests reach in the module's own tree, the version and checksum of each module " +
"outside it, the package's test data and embedded files, the Go version, the build tags and, at the " +
"integration level, the postgres major and nats-server versions. Answers in the call.",
Input: map[string]any{
"type": "object",
"properties": map[string]any{
"workspace": map[string]any{"type": "string", "description": "the workspace id build_go_fetch answered"},
"level": map[string]any{"type": "string", "enum": []string{LevelUnit, LevelIntegration}, "description": "the level"},
"runner": runnerProperty,
sdkstep.NodeNamesArg: map[string]any{"type": "array", "items": map[string]any{"type": "string"},
"description": "optional, the names of the mesh's nodes: a package whose tests read " + sdkstep.NodeNamesEnv + " has them in its digest"},
},
"required": []string{"workspace", "level"},
},
Run: m.digest,
}
}
func (m *Module) digest(ctx context.Context, args map[string]any) (any, error) {
workspace, _ := args["workspace"].(string)
level, _ := args["level"].(string)
runner, err := runnerArg(args["runner"])
if err != nil {
return nil, err
}
names, err := nodeNamesArg(args[sdkstep.NodeNamesArg])
if err != nil {
return nil, err
}
if runner == RunnerWorkspace {
if err := m.workspaceThere(workspace); err != nil {
return nil, err
}
switch level {
case LevelUnit:
case LevelIntegration:
if _, err := m.checkPostgres(ctx); err != nil {
return nil, err // a *steprun.Refusal, as the installed program's digest says it
}
default:
return nil, fmt.Errorf("the level %q is neither unit nor integration", level)
}
a, judged, err := m.asCandidate(ctx, levelSpec{Step: stepDigest, Level: level, Workspace: workspace, NodeNames: names})
if err != nil {
return nil, err
}
if a.Digest == nil {
return nil, fmt.Errorf("the candidate's mesh-build-go answered no digest")
}
a.Digest.JudgedBy = judged
return *a.Digest, nil
}
res, err := m.digestHere(ctx, workspace, level, names)
if err != nil {
return nil, err
}
res.JudgedBy = RunnerInstalled
return res, nil
}
// digestHere is the digest step as this program runs it.
func (m *Module) digestHere(ctx context.Context, workspace, level string, names []string) (DigestResult, error) {
if !workspaceOK.MatchString(workspace) {
return DigestResult{}, fmt.Errorf("%q is not a workspace id", workspace)
}
tree := filepath.Join(m.Work, workspace, "tree")
if _, err := os.Stat(tree); err != nil {
return DigestResult{}, fmt.Errorf("no workspace %s: it was never fetched here, or it is older than a day and was removed", workspace)
}
var tags []string
header := []string{"digest " + DigestVersion, "level " + level}
switch level {
case LevelUnit:
case LevelIntegration:
if _, err := m.checkPostgres(ctx); err != nil {
return DigestResult{}, err
}
tags = integrationTags
header = append(header, "postgres "+strconv.Itoa(m.Recipe.PostgresMajor), "nats-server "+m.Recipe.NatsServer)
default:
return DigestResult{}, fmt.Errorf("the level %q is neither unit nor integration", level)
}
header = append(header, "tags "+strings.Join(tags, ","))
beside, err := m.besideLines(workspace)
if err != nil {
return DigestResult{}, err
}
besideHeader := make([]string, 0, len(beside))
for _, b := range beside {
besideHeader = append(besideHeader, "beside "+b)
}
// The node names, sorted, as a header line for a package that reads them.
sortedNames := append([]string{}, names...)
sort.Strings(sortedNames)
var namesHeader []string
if len(sortedNames) > 0 {
namesHeader = []string{"node-names " + strings.Join(sortedNames, ",")}
}
dirs, err := m.testDirs(ctx, tree)
if err != nil {
return DigestResult{}, err
}
res := DigestResult{Level: level, Packages: map[string]string{}, Beside: beside}
for _, d := range dirs {
pkgs, err := m.listPackages(ctx, workspace, tree, d, tags)
if err != nil {
return DigestResult{}, err
}
if err := digestModule(&res, pkgs, tree, header, besideHeader, namesHeader, level == LevelIntegration); err != nil {
return DigestResult{}, err
}
}
sort.Strings(res.WithoutTests)
sort.Strings(res.ReadsOutside)
sort.Slice(res.Needs, func(i, j int) bool { return res.Needs[i].Package < res.Needs[j].Package })
for _, p := range res.ReadsOutside {
if m.Say != nil {
m.Say("the %s level of %s always runs: its %s %s, so its tests read files outside it that no digest names", level, p, ReadsOutsideMarker, res.neverKept[p])
}
}
return res, nil
}
// listPackages is `go list -test -deps -json` of the directory's packages, by import path.
func (m *Module) listPackages(ctx context.Context, workspace, tree, dir string, tags []string) (map[string]*goPackage, error) {
abs := filepath.Join(tree, dir)
args := []string{"-C", abs, "list", "-test", "-deps", "-json"}
if len(tags) > 0 {
args = append(args, "-tags", strings.Join(tags, ","))
}
args = append(args, "./...")
run, err := m.stepRunner(workspace, false)
if err != nil {
return nil, err
}
r := run(ctx, m.goEnvFor(abs), "go", args...)
if r.Status != 0 || r.Err != "" {
return nil, fmt.Errorf("go list in %s: %s", dir, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
}
return parsePackages(r.Stdout)
}
// parsePackages reads `go list -json`'s stream of objects.
func parsePackages(out string) (map[string]*goPackage, error) {
pkgs := map[string]*goPackage{}
dec := json.NewDecoder(strings.NewReader(out))
for {
var p goPackage
if err := dec.Decode(&p); err == io.EOF {
return pkgs, nil
} else if err != nil {
return nil, fmt.Errorf("go list answered something that is not its JSON: %w", err)
}
pkgs[p.ImportPath] = &p
}
}
// digestModule adds to res the digest of each root package of one go.mod directory. A root is a package of the main
// module that is listed, not only a dependency, and not a variant of another.
func digestModule(res *DigestResult, pkgs map[string]*goPackage, tree string, header, beside, names []string, needs bool) error {
roots := []string{}
for path, p := range pkgs {
if p.ForTest == "" && !p.DepOnly && !p.Standard && !strings.HasSuffix(path, ".test") && p.Module != nil && p.Module.Main {
roots = append(roots, path)
}
}
sort.Strings(roots)
for _, path := range roots {
root := pkgs[path]
if !root.hasTests() {
res.WithoutTests = append(res.WithoutTests, path)
continue
}
testMain := pkgs[path+".test"]
if testMain == nil {
return fmt.Errorf("go list gave no test binary for %s", path)
}
if needs {
n, err := readNeeds(tree, root.Dir)
if err != nil {
return fmt.Errorf("%s: its check-needs: %w", path, err)
}
if len(n) > 0 {
res.Needs = append(res.Needs, sdkstep.PackageNeeds{Package: path, Needs: n})
}
}
declared, why, err := declaredReads(tree, root, res.hashed())
if err != nil {
return fmt.Errorf("%s: its %s: %w", path, ReadsOutsideMarker, err)
}
if why != "" {
// The digest of a package whose reads outside itself are not listed is one nothing can have kept: the key is a
// fresh random hex, so the ask finds no kept verdict and runs it, and what the checker writes under it is never
// read again.
var nonce [32]byte
if _, err := rand.Read(nonce[:]); err != nil {
return err
}
res.Packages[path] = hex.EncodeToString(nonce[:])
res.ReadsOutside = append(res.ReadsOutside, path)
if res.neverKept == nil {
res.neverKept = map[string]string{}
}
res.neverKept[path] = why
continue
}
d, err := packageDigest(root, testMain, pkgs, tree, header, beside, names, declared)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
res.Packages[path] = d
}
return nil
}
// packageDigest is the digest of one package: a hash over a sorted text of the header, the files of every package its
// tests reach in the module's own tree (by their content, under their path in the tree), the version and checksum of
// every module outside it, and the package's own test data. The beside lines (the siblings' commits) join the header
// only when a file the tests reach names MESH_CHECK_BESIDE, and the node names likewise for MESH_NODE_NAMES. A package of the standard library is the Go version's.
// The lines a package's ReadsOutsideMarker declares join them (declaredReads).
func packageDigest(root, testMain *goPackage, pkgs map[string]*goPackage, tree string, header, beside, names, declared []string) (string, error) {
reached := map[string]*goPackage{root.ImportPath: root}
for _, dep := range testMain.Deps {
if p := pkgs[dep]; p != nil {
reached[dep] = p
}
}
lines := append([]string{}, declared...)
readsBeside, readsNames := false, false
for _, p := range reached {
if p.Standard || p.Module == nil {
continue
}
mod := p.Module
if mod.Replace != nil {
mod = mod.Replace
}
// A module outside the tree counts by its version and checksum; a package of the mesh's own forge by the content of
// its files, as a local replacement does, so a new version of a mesh package whose reached files are the same keeps
// every verdict kept for them (ADR 0593 §5, ADR 0444 §3).
if !mod.Main && mod.Version != "" && !strings.HasPrefix(mod.Path, trunk.ForgeModulePrefix) {
lines = append(lines, "module "+mod.Path+"@"+mod.Version+" "+mod.Sum)
continue
}
for _, f := range p.files() {
l, err := fileLine(tree, p, f)
if err != nil {
return "", err
}
lines = append(lines, l)
if !readsBeside || !readsNames {
if raw, err := os.ReadFile(filepath.Join(p.Dir, f)); err == nil {
readsBeside = readsBeside || bytes.Contains(raw, []byte(besideVariable))
readsNames = readsNames || bytes.Contains(raw, []byte(namesVariable))
}
}
}
}
// A catalogue module's tests read its manifest, its README and its files from the package's directory (../../module.json):
// every non-Go file of the module's directory is an input (issue 1935). The module is the nearest ancestor with a module.json.
if modDir := enclosingModule(tree, root.Dir); modDir != "" {
more, err := moduleFileLines(tree, root, modDir)
if err != nil {
return "", err
}
lines = append(lines, more...)
}
data := filepath.Join(root.Dir, "testdata")
if _, err := os.Stat(data); err == nil {
err := filepath.WalkDir(data, func(path string, e fs.DirEntry, err error) error {
if err != nil || e.IsDir() {
return err
}
l, err := contentLine(tree, root, path)
lines = append(lines, l)
return err
})
if err != nil {
return "", err
}
}
sort.Strings(lines)
if readsBeside {
header = append(append([]string{}, header...), beside...)
}
if readsNames {
header = append(append([]string{}, header...), names...)
}
h := sha256.New()
for _, l := range append(append([]string{}, header...), lines...) {
h.Write([]byte(l + "\n"))
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// enclosingModule is the nearest ancestor of dir, inside tree, that holds a module.json, or "" when there is none.
func enclosingModule(tree, dir string) string {
tree = filepath.Clean(tree)
for d := filepath.Clean(dir); d != tree && strings.HasPrefix(d, tree+string(filepath.Separator)); d = filepath.Dir(d) {
if st, err := os.Stat(filepath.Join(d, "module.json")); err == nil && !st.IsDir() {
return d
}
}
return ""
}
// moduleFileLines are the content lines of every file of a module's directory that is not Go source (Go source is the
// packages' own, listed by go list), skipping .git and node_modules.
func moduleFileLines(tree string, p *goPackage, modDir string) ([]string, error) {
var lines []string
err := filepath.WalkDir(modDir, func(path string, e fs.DirEntry, err error) error {
if err != nil {
return err
}
if e.IsDir() {
if n := e.Name(); n == ".git" || n == "node_modules" {
return filepath.SkipDir
}
return nil
}
if strings.HasSuffix(path, ".go") {
return nil
}
l, err := contentLine(tree, p, path)
lines = append(lines, l)
return err
})
return lines, err
}
func fileLine(tree string, p *goPackage, name string) (string, error) {
return contentLine(tree, p, filepath.Join(p.Dir, name))
}
// contentLine is "file <path> <sha256>": the path is the file's in the tree (the import path and the name when it lies
// outside, as a local replacement does), so a digest does not depend on where the workspace is.
func contentLine(tree string, p *goPackage, path string) (string, error) {
label := p.ImportPath + "/" + filepath.Base(path)
if rel, err := filepath.Rel(tree, path); err == nil && !strings.HasPrefix(rel, "..") {
label = filepath.ToSlash(rel)
}
info, err := os.Lstat(path)
if err != nil {
return "", err
}
if info.Mode()&os.ModeSymlink != 0 {
to, _ := os.Readlink(path)
return "link " + label + " " + to, nil
}
raw, err := os.ReadFile(path)
if err != nil {
return "", err
}
sum := sha256.Sum256(raw)
return "file " + label + " " + hex.EncodeToString(sum[:]), nil
}
// hashed is the cache of content lines a digest step shares across its packages.
func (r *DigestResult) hashed() map[string]string {
if r.hashedFiles == nil {
r.hashedFiles = map[string]string{}
}
return r.hashedFiles
}
// declaredReads are the digest lines a package's ReadsOutsideMarker adds: each of its lines, the content line of every
// file it names, and those of every file of the package's own directory. Without a marker it answers nothing. why is
// set, and the lines nil, when the marker cannot be trusted: it lists nothing, a line is not a clean relative path, or
// a line without ? matches nothing.
func declaredReads(tree string, root *goPackage, cache map[string]string) (lines []string, why string, err error) {
raw, err := os.ReadFile(filepath.Join(root.Dir, ReadsOutsideMarker))
if errors.Is(err, fs.ErrNotExist) {
return nil, "", nil
}
if err != nil {
return nil, "", err
}
var patterns []string
for _, l := range strings.Split(string(raw), "\n") {
if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "#") {
patterns = append(patterns, l)
}
}
if len(patterns) == 0 {
return nil, "lists nothing", nil
}
seen := map[string]bool{}
add := func(path string) error {
if seen[path] {
return nil
}
seen[path] = true
l, ok := cache[path]
if !ok {
var err error
if l, err = contentLine(tree, root, path); err != nil {
return err
}
cache[path] = l
}
lines = append(lines, "read "+l)
return nil
}
for _, l := range patterns {
pattern, absent := strings.CutPrefix(l, "?")
if !cleanTreePattern(pattern) {
return nil, fmt.Sprintf("names %q, which is not a clean path from the repository's root", l), nil
}
matches, err := filepath.Glob(filepath.Join(tree, filepath.FromSlash(pattern)))
if err != nil {
return nil, fmt.Sprintf("names %q, which is not a glob", l), nil
}
if len(matches) == 0 && !absent {
return nil, fmt.Sprintf("names %q, which matches nothing (a path whose absence is read starts with ?)", l), nil
}
lines = append(lines, "reads "+l)
for _, match := range matches {
if err := walkFiles(match, add); err != nil {
return nil, "", err
}
}
}
// Every file of the package's own directory: its lists, its marker, and its Go files too, since go list leaves a
// file its build tags exclude (an integration test a unit test globs) out of what the digest hashes. A file the
// toolchain lists is hashed twice, which changes nothing.
err = walkFiles(root.Dir, add)
return lines, "", err
}
// cleanTreePattern says a marker's line is a path from the repository's root that stays inside it.
func cleanTreePattern(p string) bool {
if p == "" || strings.ContainsAny(p, " \t\\") || strings.HasPrefix(p, "/") || path.Clean(p) != p {
return false
}
for _, e := range strings.Split(p, "/") {
if e == ".." || e == "." {
return false
}
}
return true
}
// walkFiles calls each with every file at or under path, skipping .git and node_modules, in lexical order.
func walkFiles(path string, each func(string) error) error {
return filepath.WalkDir(path, func(p string, e fs.DirEntry, err error) error {
if err != nil {
return err
}
if e.IsDir() {
if n := e.Name(); p != path && (n == ".git" || n == "node_modules") {
return filepath.SkipDir
}
return nil
}
return each(p)
})
}