Join: merge feat/47-H2-i into feat/47-H2

No conflicts; the mesh-catalog seat's form 5 is -i's (feat/47-H2 left it at 3),
and its contract is regenerated with seatgen so the seat-list verb's description
follows the merged seat.json (seatgen -check clean).

Builds: design 47 H2 (join of the develop step, playbook 07)
This commit is contained in:
2026-11-22 02:33:37 +01:00
296 changed files with 9461 additions and 1476 deletions
@@ -14,13 +14,13 @@ const Seat = "mesh-catalog"
// Form is the form of the seat's values, events and answers this contract was generated at (design 47 H2 §780):
// a reader of a value of another form says "form N, this reader knows M".
const Form = 3
const Form = 5
// The forms and the digest of the fields this contract was generated from: the generator's compare fails a definition
// whose fields changed while its forms did not (design 47 H2 §780).
const (
generatedForms = "3"
generatedFieldsDigest = "ActingRule=8a83ce7e0457 Artifact=78b05c1a9ec3 ArtifactPackage=2a3a660a934d ArtifactRef=a2f06147f4b6 BuildEdge=76f0684e254a BuildEdges=d2b95000259e BuildEdgesByModuleBranchValue=4fdf7cc1e723 CandidatesByGroupValue=9ea8c6c580d2 CandidatesByGroupValuePullsItem=90fb03643258 CandidatesByGroupValuePullsItemFpsValue=4c6783201aa3 CatalogEntry=c0a4ea25d523 CatalogRevision=d1ecaaa484af CatalogRevisionDefinitionsItem=77fcff620d48 CatalogRevisionEvent=710cbc5bfff1 CatalogRevisionsByBranchRevisionValue=17e54f635d35 CatalogRevisionsByCandidateGroupHeadsValue=17e54f635d35 CatalogRevisionsByEntryDigestValue=8755036a3051 DependentsAnswer=7538f2f5e68e Edge=7242732afaef EntryAnswer=805c2ff28e1c EntryInputs=76a7f8690dd2 EntryRef=ff109e5089e1 Fill=80f442916429 FillingEvent=5bd4df78ed84 FingerprintInputs=99a6df7f991f FullEvent=5bd4df78ed84 Head=774b4bf88ba4 InputAnswer=cd41ee65565d InputsByTimeDigestValue=a2f06147f4b6 ManifestsByDigestValue=51b3822b29c6 ModuleAnswer=499a03ce9b27 ModuleAnswerModule=c0f679e09f08 ModulesAnswer=6d119571c69e ModulesAnswerModulesItem=a70f39c60b67 ModulesByModuleValue=fc7530ba893a ModulesByModuleValueInputs2=99a6df7f991f Outdated=e820214f66bc OutdatedAnswer=275fb25266b9 OutdatedDependency=dc35dca1b683 PackagesByModuleValue=2b62574b709f PackagesByModuleValuePackagesItem=a7d30558470d PackagesByPackageSeriesValue=07421d8d3411 PackagesByPackageSeriesValueNewest=aba144994370 PackagesByPackageSeriesValueNewestContents=eca2ccf56913 PackagesByPackageSeriesValueNewestContentsPackagesItem=a7d30558470d PackagesByPackageSeriesValueNumbered=c8ffc628599c PackagesByPackageSeriesValueNumberedContents=0def6c0794ee PackagesByPackageSeriesValueNumberedContentsPackagesItem=a7d30558470d Policy=719e2f460c6f PolicyAnswer=46cdf8430557 PredefinedByListValue=ec8e3febe8ac ProvidesAnswer=7538f2f5e68e RegisterAnswer=46cdf8430557 Registration=ef03d1b2e73f RegistrationAsked=55adba349c24 RegistrationChangedEvent=99a3268edf41 RegistrationHistoryByModuleVersionValue=0999b5bb7dc7 RegistrationHistoryBySourceOwnerNameVersionValue=0999b5bb7dc7 RegistrationsAnswer=8849ef618cf3 RegistrationsByModuleValue=0999b5bb7dc7 RegistrationsBySourceOwnerNameValue=0999b5bb7dc7 RevisionAnswer=258ea5124931 RoomEvent=5bd4df78ed84 SeatDefinitionChangedEvent=e271d24d58f7 SeatDefinitionRemovedEvent=f7d6171111e6 SeatDefinitionsAnswer=0fd6a59fec59 SeatDefinitionsAnswerEntry=d006f68d2be5 SeatDefinitionsAnswerSeatsItem=e271d24d58f7 SeatListAnswer=912c0cebcf0a SourceCheck=d1ed7cbbd579 StepStatuses=4f50aa633e61 TakeInEntry=545ec1528499 ToolchainUsed=43b6d42376fb UnwatchAnswer=46cdf8430557 VersionArtifact=438c49a392b0 VersionEdge=b0f80e83f4dc VersionEntry=33f5b00dbda9 VersionReleasedEvent=4ccf1ea90e7f VersionsAnswer=b59e6e057e7b VersionsByModuleVersionValue=e546dfadb913 VersionsFilledEvent=4cc437912dc3 WatchAnswer=46cdf8430557"
generatedForms = "5"
generatedFieldsDigest = "ActingRule=8a83ce7e0457 Artifact=78b05c1a9ec3 ArtifactPackage=2a3a660a934d ArtifactRef=a2f06147f4b6 BuildEdge=76f0684e254a BuildEdges=d2b95000259e BuildEdgesByModuleBranchValue=4fdf7cc1e723 CandidatesByGroupValue=9ea8c6c580d2 CandidatesByGroupValuePullsItem=90fb03643258 CandidatesByGroupValuePullsItemFpsValue=4c6783201aa3 CatalogEntry=c0a4ea25d523 CatalogRevision=d1ecaaa484af CatalogRevisionDefinitionsItem=77fcff620d48 CatalogRevisionEvent=710cbc5bfff1 CatalogRevisionsByBranchRevisionValue=17e54f635d35 CatalogRevisionsByCandidateGroupHeadsValue=17e54f635d35 CatalogRevisionsByEntryDigestValue=8755036a3051 DependentsAnswer=7538f2f5e68e Edge=7242732afaef EntryAnswer=805c2ff28e1c EntryInputs=76a7f8690dd2 EntryRef=ff109e5089e1 Fill=80f442916429 FillingEvent=5bd4df78ed84 FingerprintInputs=99a6df7f991f FullEvent=5bd4df78ed84 Head=774b4bf88ba4 InputAnswer=cd41ee65565d InputsByTimeDigestValue=a2f06147f4b6 ManifestsByDigestValue=51b3822b29c6 ModuleAnswer=499a03ce9b27 ModuleAnswerModule=c0f679e09f08 ModulesAnswer=6d119571c69e ModulesAnswerModulesItem=a70f39c60b67 ModulesByModuleValue=fc7530ba893a ModulesByModuleValueInputs2=99a6df7f991f Outdated=e820214f66bc OutdatedAnswer=275fb25266b9 OutdatedDependency=dc35dca1b683 PackagesByModuleValue=2b62574b709f PackagesByModuleValuePackagesItem=a7d30558470d PackagesByPackageSeriesValue=07421d8d3411 PackagesByPackageSeriesValueNewest=aba144994370 PackagesByPackageSeriesValueNewestContents=eca2ccf56913 PackagesByPackageSeriesValueNewestContentsPackagesItem=a7d30558470d PackagesByPackageSeriesValueNumbered=c8ffc628599c PackagesByPackageSeriesValueNumberedContents=0def6c0794ee PackagesByPackageSeriesValueNumberedContentsPackagesItem=a7d30558470d Policy=719e2f460c6f PolicyAnswer=46cdf8430557 PredefinedByListValue=ec8e3febe8ac ProvidesAnswer=7538f2f5e68e RegisterAnswer=46cdf8430557 Registration=ef03d1b2e73f RegistrationAsked=b529a0e1c5ca RegistrationChangedEvent=99a3268edf41 RegistrationHistoryByModuleVersionValue=0999b5bb7dc7 RegistrationHistoryBySourceOwnerNameVersionValue=0999b5bb7dc7 RegistrationsAnswer=8849ef618cf3 RegistrationsByModuleValue=0999b5bb7dc7 RegistrationsBySourceOwnerNameValue=0999b5bb7dc7 RevisionAnswer=258ea5124931 RoomEvent=5bd4df78ed84 SeatDefinitionChangedEvent=e271d24d58f7 SeatDefinitionRemovedEvent=f7d6171111e6 SeatDefinitionsAnswer=0fd6a59fec59 SeatDefinitionsAnswerEntry=d006f68d2be5 SeatDefinitionsAnswerSeatsItem=e271d24d58f7 SeatListAnswer=04477a8044b1 SourceCheck=d1ed7cbbd579 StepStatuses=4f50aa633e61 TakeInEntry=545ec1528499 ToolchainUsed=43b6d42376fb UnwatchAnswer=46cdf8430557 VersionArtifact=438c49a392b0 VersionEdge=b0f80e83f4dc VersionEntry=33f5b00dbda9 VersionReleasedEvent=4ccf1ea90e7f VersionsAnswer=b59e6e057e7b VersionsByModuleVersionValue=e546dfadb913 VersionsFilledEvent=4cc437912dc3 WatchAnswer=46cdf8430557"
)
const (
@@ -74,7 +74,7 @@ func VerbDescription(verb string) string {
case VerbSeatDefinitions:
return "The seat list (ADR 0636 §4): with no seat, every trunk seat with its digest and the revision of the list; with a seat, that trunk definition resolved with the parts it includes. Reads only."
case VerbSeatList:
return "The seat list the mesh holds, as one object in the holder's objects seat-lists, one object per digest (design 47 H2 §814): the manifest validator program takes it by address, so a run by hand reads what the live validate reads. Reads only."
return "The trunk's seat list as the mesh holds it, the object of the holder's objects seat-lists of that digest (design 47 H2 §814, §820; H-A-441, H-A-443): its digest and size, then its bytes (the definitions resolved, a JSON array in the form of a composer request's seats, sorted by seat) in chunks of at most 512 KiB on the chunk subject of the call, each acknowledged by the caller on the ack subject within 30 seconds. A validate run's asker fills the request's seats from these bytes. Reads only."
case VerbRevision:
return "The catalog half of the revision view (ADR 0656 §6): one catalog graph revision with its entries whole, the trunk heads, the seat definitions by digest, and each manifest's verdict and fingerprint; the trunk's newest when no revision and no candidate is named, or a candidate's for its group and heads. Answered by the holder from what it holds, in its own runtime (ADR 0663), in pages of entries. Reads only. A watched branch with no revision yet answers {none-yet: true} alone (design 47 G section 530)."
case VerbRegistrations:
@@ -964,7 +964,7 @@ type RegistrationAsked struct {
// every value the change moves, as the ask names it ("nats:program unit: required -> bypass")
Lines []string `json:"lines,omitempty"`
Module string `json:"module"`
// why no ask was raised
// why no ask was raised; holds-manifest: a source-only registration whose repository holds a module.json at its root or under modules/ at the branch's head (design 47 H2 §815; H-A-450)
Refused string `json:"refused,omitempty"`
// the refusal in words, naming the branch, the step or the module
Words string `json:"words,omitempty"`
@@ -978,6 +978,7 @@ const (
RegistrationAskedRefusedReviewRequired = "review required"
RegistrationAskedRefusedUnknownModule = "unknown module"
RegistrationAskedRefusedNothingMoves = "nothing moves"
RegistrationAskedRefusedHoldsManifest = "holds-manifest"
)
// SourceCheck is the check of a source-only registration: a build seat and a step kind, run at the repository's root, never a free command (design 47 H2 §815).
@@ -1272,17 +1273,19 @@ type SeatDefinitionsAnswer struct {
// SeatListInput is what seat-list takes.
type SeatListInput struct {
// 128 random bits the caller chooses: the subject token of this send's chunks and acknowledgements
Call string `json:"call"`
}
// SeatListAnswer is what seat-list answers.
type SeatListAnswer struct {
// the seat list's digest
// how many chunks are sent
Chunks int64 `json:"chunks"`
// the seat list's sha256, the object's name in seat-lists
Digest string `json:"digest"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// the object's name in seat-lists
Object string `json:"object"`
// the object's size in bytes
// the seat list's size in bytes
Size int64 `json:"size"`
}
@@ -185,7 +185,9 @@ func TestFixtures(t *testing.T) {
decode: func(b []byte) (any, error) { var v RegistrationsInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "registrations answers a capped page with a source-only registration and the next cursor", subject: "", given: "{\"capped\":true,\"next\":\"c-121\",\"registrations\":[{\"at\":\"2026-11-22T00:10:00Z\",\"branches\":[\"main\"],\"by\":\"operator@workstation\",\"check\":{\"seat\":\"node-build-go\",\"step\":\"unit\"},\"origin\":\"novox/hq\",\"policy\":{\"steps\":{\"approval\":\"bypass\",\"review\":\"optional\",\"unit\":\"required\"}},\"v\":1,\"version\":1,\"warrant\":\"ask-m2kx9a1b3c4d6a\"}],\"total\":118}", wire: "{\"capped\":true,\"next\":\"c-121\",\"registrations\":[{\"at\":\"2026-11-22T00:10:00Z\",\"branches\":[\"main\"],\"by\":\"operator@workstation\",\"check\":{\"seat\":\"node-build-go\",\"step\":\"unit\"},\"origin\":\"novox/hq\",\"policy\":{\"steps\":{\"approval\":\"bypass\",\"review\":\"optional\",\"unit\":\"required\"}},\"v\":1,\"version\":1,\"warrant\":\"ask-m2kx9a1b3c4d6a\"}],\"total\":118}",
decode: func(b []byte) (any, error) { var v RegistrationsAnswer; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "seat-list answers the seat list's object by its digest", subject: "", given: "{\"digest\":\"sha256:eeee\",\"object\":\"sha256-eeee\",\"size\":412345}", wire: "{\"digest\":\"sha256:eeee\",\"object\":\"sha256-eeee\",\"size\":412345}",
{name: "seat-list asks the seat list's bytes on a call's chunks", subject: "", given: "{\"call\":\"0123456789abcdef0123456789abcdef\"}", wire: "{\"call\":\"0123456789abcdef0123456789abcdef\"}",
decode: func(b []byte) (any, error) { var v SeatListInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "seat-list answers the seat list's digest, size and how many chunks carry its bytes", subject: "", given: "{\"chunks\":1,\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"size\":412345}", wire: "{\"chunks\":1,\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"size\":412345}",
decode: func(b []byte) (any, error) { var v SeatListAnswer; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
}
for _, c := range cases {
@@ -485,12 +485,19 @@
}
},
{
"name": "seat-list answers the seat list's object by its digest",
"name": "seat-list asks the seat list's bytes on a call's chunks",
"of": "verb:seat-list.input",
"given": {
"call": "0123456789abcdef0123456789abcdef"
}
},
{
"name": "seat-list answers the seat list's digest, size and how many chunks carry its bytes",
"of": "verb:seat-list.answer",
"given": {
"digest": "sha256:eeee",
"size": 412345,
"object": "sha256-eeee"
"chunks": 1,
"digest": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"size": 412345
}
}
]
@@ -256,34 +256,45 @@
{
"name": "seat-list",
"class": "read",
"description": "The seat list the mesh holds, as one object in the holder's objects seat-lists, one object per digest (design 47 H2 §814): the manifest validator program takes it by address, so a run by hand reads what the live validate reads. Reads only.",
"description": "The trunk's seat list as the mesh holds it, the object of the holder's objects seat-lists of that digest (design 47 H2 §814, §820; H-A-441, H-A-443): its digest and size, then its bytes (the definitions resolved, a JSON array in the form of a composer request's seats, sorted by seat) in chunks of at most 512 KiB on the chunk subject of the call, each acknowledged by the caller on the ack subject within 30 seconds. A validate run's asker fills the request's seats from these bytes. Reads only.",
"input": {
"type": "object",
"properties": {}
"properties": {
"call": {
"type": "string",
"description": "128 random bits the caller chooses: the subject token of this send's chunks and acknowledgements",
"minLength": 1
}
},
"required": [
"call"
]
},
"answer": {
"type": "object",
"properties": {
"digest": {
"type": "string",
"description": "the seat list's digest"
"description": "the seat list's sha256, the object's name in seat-lists"
},
"size": {
"type": "integer",
"minimum": 0,
"description": "the object's size in bytes"
"description": "the seat list's size in bytes"
},
"object": {
"type": "string",
"description": "the object's name in seat-lists"
"chunks": {
"type": "integer",
"minimum": 0,
"description": "how many chunks are sent"
}
},
"required": [
"digest",
"size",
"object"
"chunks"
]
}
},
"chunks": true
},
{
"name": "revision",
@@ -2286,9 +2297,10 @@
"placed",
"review required",
"unknown module",
"nothing moves"
"nothing moves",
"holds-manifest"
],
"description": "why no ask was raised"
"description": "why no ask was raised; holds-manifest: a source-only registration whose repository holds a module.json at its root or under modules/ at the branch's head (design 47 H2 §815; H-A-450)"
},
"words": {
"type": "string",
@@ -2725,5 +2737,5 @@
]
}
},
"form": 3
"form": 5
}
@@ -469,8 +469,8 @@ export interface RegistrationAsked {
/** every value the change moves, as the ask names it ("nats:program unit: required -> bypass") */
"lines"?: string[];
"module": string;
/** why no ask was raised */
"refused"?: "unprotected branch" | "reserved branch name" | "placed" | "review required" | "unknown module" | "nothing moves";
/** why no ask was raised; holds-manifest: a source-only registration whose repository holds a module.json at its root or under modules/ at the branch's head (design 47 H2 §815; H-A-450) */
"refused"?: "unprotected branch" | "reserved branch name" | "placed" | "review required" | "unknown module" | "nothing moves" | "holds-manifest";
/** the refusal in words, naming the branch, the step or the module */
"words"?: string;
}
@@ -699,17 +699,19 @@ export interface SeatDefinitionsAnswer {
/** is what seat-list takes. */
export interface SeatListInput {
/** 128 random bits the caller chooses: the subject token of this send's chunks and acknowledgements */
"call": string;
}
/** is what seat-list answers. */
export interface SeatListAnswer {
/** the seat list's digest */
/** how many chunks are sent */
"chunks": number;
/** the seat list's sha256, the object's name in seat-lists */
"digest": string;
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** the object's name in seat-lists */
"object": string;
/** the object's size in bytes */
/** the seat list's size in bytes */
"size": number;
}
@@ -156,6 +156,11 @@ func (k keptRead) Get(_ context.Context, key string) ([]byte, uint64, bool, erro
func (k keptRead) Keys(context.Context) ([]string, error) { return k.s.Keys() }
// Page reads the state a page at a time from the bus's cursor (design 47 H2 §779): the registrations are read so (§806).
func (k keptRead) Page(cursor string, maxBytes int, budget time.Duration) (stdio.StatePage, error) {
return k.s.Page(cursor, maxBytes, budget)
}
func (keptRead) Create(context.Context, string, []byte) error { return errReadOnly }
func (keptRead) Update(context.Context, string, []byte, uint64) error { return errReadOnly }
@@ -208,10 +213,11 @@ func main() {
_, err := acts.Record(meshhandactsclient.Request{What: what, Why: why, Cause: index.PinDropTool, Verb: "pin-drop"})
return err
})...)
tools = append(tools, index.HeldTools(keptRead{stdio.State(index.HeldState)}, asks, time.Now, func(what, why string) error {
tools = append(tools, index.HeldTools(keptRead{stdio.State(index.HeldState)}, keptRead{stdio.State(index.TakeInsState)}, asks, time.Now, func(what, why string) error {
_, err := acts.Record(meshhandactsclient.Request{What: what, Why: why, Cause: index.TakeInSkipTool, Verb: "take-in-skip"})
return err
})...)
tools = append(tools, index.DryRunsTools(keptRead{stdio.State(index.DryRunsState)})...)
tools = append(tools, index.RunsTools(keptRead{stdio.State(index.RunsState)}, keptRead{stdio.State(index.CandidatesState)}, asks, time.Now, func(what, why string) error {
_, err := acts.Record(meshhandactsclient.Request{What: what, Why: why, Cause: index.RunDropTool, Verb: "run-drop"})
return err
@@ -363,6 +363,10 @@ func startIndexerRun(t *testing.T, put func(context.Context, buildLog), before .
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: index.Bucket(testIndexer, index.ManifestsState), History: index.ManifestsHistory}); err != nil {
t.Fatal(err)
}
// The dry runs' scratch, made by the grants part from the manifest's state entry dry-runs (design 47 H2 §804, §820).
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: index.Bucket(testIndexer, index.DryRunsState), History: 1, TTL: time.Hour, MaxBytes: 16 << 20}); err != nil {
t.Fatal(err)
}
// The builder's module log, as the runtime raises it (ADR 0297), filled by put before the indexer starts.
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: buscompose.LogStreamName(builds.BuilderModule, builds.BuilderLog),
Subjects: []string{buscompose.LogSubject(builds.BuilderModule, builds.BuilderLog) + ".>"}, AllowDirect: true}); err != nil {
@@ -518,7 +522,7 @@ func seedBuildModules(t *testing.T, ctx context.Context, js jetstream.JetStream,
if _, err := defs.Put(ctx, b.seat+".trunk", entry); err != nil {
t.Fatal(err)
}
manifest := `{"module":"` + b.module + `","version":"1","claims":[{"name":"` + b.seat + `","scope":"node","serves":["current","drop","pause","resume"]}],` +
manifest := `{"module":"` + b.module + `","version":"1","class":"core","claims":[{"name":"` + b.seat + `","scope":"node","serves":["current","drop","pause","resume"]}],` +
`"streams":[{"name":"` + b.stream + `","events":["toolchain.**"]}]}`
digest := meshcatalogclient.ManifestDigest([]byte(manifest))
mkey, err := meshcatalogclient.ManifestsKey(digest)
@@ -560,7 +564,7 @@ func seedClaimant(t *testing.T, ctx context.Context, js jetstream.JetStream, man
}
}
seedAssignerSeat(t, ctx, js)
manifest := `{"module":"` + assignerHolderModule + `","version":"1","claims":[{"name":"` + meshmoduleassigner.Seat + `","scope":"mesh"}]}`
manifest := `{"module":"` + assignerHolderModule + `","version":"1","class":"core","claims":[{"name":"` + meshmoduleassigner.Seat + `","scope":"mesh"}]}`
digest := meshcatalogclient.ManifestDigest([]byte(manifest))
mkey, err := meshcatalogclient.ManifestsKey(digest)
if err != nil {
@@ -92,6 +92,16 @@ func (s awaitedStore) Create(ctx context.Context, key string, value []byte) erro
return st.Create(ctx, key, value)
}
// CreateTTL creates key living ttl: the state is declared key-ttl (index.TTLStore, design 47 H2 §805).
func (s awaitedStore) CreateTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error {
st, err := s.store()
if err != nil {
return err
}
_, err = st.kv.Create(ctx, key, value, jetstream.KeyTTL(ttl))
return conflict(err)
}
func (s awaitedStore) Update(ctx context.Context, key string, value []byte, revision uint64) error {
st, err := s.store()
if err != nil {
@@ -308,14 +318,18 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
seatDefs := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.SeatDefinitionsState), "no seat definition is kept", logger.Printf)
marks := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, views.MarksState), "no change is said on the views family, so every reader waits on its first view", logger.Printf)
seatBus := &seatBus{defs: awaitedSource{ctx, seatDefs}, marks: awaitedSource{ctx, marks}}
// The seat lists, one object per digest (design 47 H2 §814, §820; H-A-441, H-A-443), kept at each trunk definition's move
// and handed by the verb seat-list.
seatLists := newBusObjects(js, cred, index.SeatListsObjects)
// The build modules are found again at every change of the seat list (buildmodules.go), once the indexer is made.
var buildFollow atomic.Pointer[buildModulesFollow]
seatReader, saySeats := followSeatList(seatBus, saySeatDefinition(js, cred), logger.Printf, func() {
if b := buildFollow.Load(); b != nil {
go b.refresh() // never inside the reader's change: the refresh reads the reader's definitions
}
})
}, seatLists)
readWhenBound(seatReader, seatDefs, marks)
keepSeatListAtStart(ctx, seatDefs, seatBus.defs, seatLists, logger.Printf)
var fillFollow atomic.Pointer[versionsFill]
// Kept while named (design 47 G §675): the want and the running build that name a fingerprint, heard below.
named := index.NewNamed(awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.NamedState), "no entry is kept for a want or a running build that names it", logger.Printf)}, logger.Printf)
@@ -326,16 +340,30 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
inputsStore := awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.InputsState), "no input of a run ask is kept, so the verb input answers none", logger.Printf)}
inObjects := &inputObjects{js: js, module: cred.Module}
stopInput, err := calls.AnswerSeat(meshcatalog.Seat, seatlist.Definition(seatReader.Reader, meshcatalog.Seat), map[string]process.SeatHandler{
meshcatalog.VerbInput: index.InputVerb(inputsStore, inObjects, conn, buscalls.SeatAckWithin, logger.Printf)})
meshcatalog.VerbInput: index.InputVerb(inputsStore, inObjects, conn, buscalls.SeatAckWithin, logger.Printf),
meshcatalog.VerbSeatList: index.SeatListVerb(seatBus.defs, seatLists, conn, buscalls.SeatAckWithin, logger.Printf)})
if err != nil {
return fmt.Errorf("answering the verb input: %w", err)
return fmt.Errorf("answering the verbs input and seat-list: %w", err)
}
defer stopInput()
ix := &index.Indexer{Module: cred.Module, NamedSets: named, Findings: writer, OldSections: awaitedStore{b: oldSections}, Requirements: awaitedStore{b: requirements}, Store: kvStore{candidates}, Modules: modules, Manifests: kvStore{manifests}, Taken: awaitedStore{b: taken}, Builds: known,
// The state takeins: hand acts ask there (watched below), and a running take-in keeps what it waits on (H2 §803, H-A-409).
takeIns := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.TakeInsState), "no hand act of the indexer is answered", logger.Printf)
// The state dry-runs, a dry run's scratch of the packages it writes (H2 §804): every key it holds goes at this start, before
// any dry run, so no dry run outlives a start.
dryRuns := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.DryRunsState), "no dry run is computed: a branch's take-in, a run's candidate and a branch's re-pin wait for it", logger.Printf)
dryRuns.Ready(func(kv jetstream.KeyValue) {
if err := index.ClearDryRuns(ctx, kvStore{kv}); err != nil {
logger.Printf("the state %s is not cleared at this start: %v", index.DryRunsState, err)
}
})
ix := &index.Indexer{Module: cred.Module, TakeIns: awaitedStore{b: takeIns}, DryRuns: awaitedStore{b: dryRuns}, NamedSets: named, Findings: writer, OldSections: awaitedStore{b: oldSections}, Requirements: awaitedStore{b: requirements}, Store: kvStore{candidates}, Modules: modules, Manifests: kvStore{manifests}, Taken: awaitedStore{b: taken}, Builds: known,
Predefined: awaitedStore{b: predefined}, Logf: logger.Printf,
Named: namedVia(calls.Call), Trunk: trunkVia(calls.Call), BranchHead: branchHeadVia(calls.Call), Contains: containsVia(calls.Call), Read: readVia(calls.Call),
Packages: awaitedStore{b: packages, js: js, name: index.Bucket(cred.Module, index.PackagesState)}, Files: filesVia(calls.Call), GoSum: goSumVia(calls.Call), GoMod: goModVia(calls.Call),
Heard: heardStore, Runs: awaitedStore{b: runs}, Graph: graph,
// How long a reservation is kept and how long its gathering waits at most (design 47 H2 §805, H-A-424).
ReservedKeep: reservedSetting("reserved-keep", index.DefaultReservedKeep, logger.Printf),
ReservedSettle: reservedSetting("reserved-settle", index.DefaultReservedSettle, logger.Printf),
SeatDefinitions: awaitedStore{b: seatDefs}, ReadFile: readFileVia(calls.Call), SaySeatDefinition: saySeats,
Revisions: revisions, EntryIndex: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.EntryIndexState), "no entry is found by its fingerprint", logger.Printf)}, // Message a kept call: a read, called again through a transport fault (ADR 0668 §1)
// Each catalog revision may bring another holder of a build seat: the build modules are found again (buildmodules.go).
@@ -502,7 +530,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
done()
// A person's hand act writes the takeins state (issue 1945): watched, as every other input.
// A state not on the bus yet at this start is watched once it appears (issue 1790).
process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.TakeInsState), "no hand act of the indexer is answered", logger.Printf).Ready(func(kv jetstream.KeyValue) {
takeIns.Ready(func(kv jetstream.KeyValue) {
eachTakeIn := func(e jetstream.KeyValueEntry) { takenIn(ctx, actor{ix, sources}, kv, e, logger.Printf) }
if tw, err := settle(ctx, kv, eachTakeIn); err != nil {
process.NotWatched(logger.Printf, index.Bucket(cred.Module, index.TakeInsState), err, "no hand act of the indexer is answered until the indexer starts again")
@@ -561,6 +589,36 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
if err := hub.Handle(meshbuilds.SubjectPackagePublished, func(m jetstream.Msg) { heardPackagePublished(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
// A release re-pins once, at its reservation (design 47 H2 §805): the builder's version-reserved, and the step-ended of
// a pipeline whose reservations settle then.
if err := hub.Handle(meshbuilds.SubjectVersionReserved, func(m jetstream.Msg) { heardVersionReserved(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
if err := hub.Handle(meshbuilds.SubjectStepEndedAll, func(m jetstream.Msg) { heardBuildStepEnded(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
// A gathering's key settling.<revision> settles it when its time to live ends: the watch of heard hands the bus's
// expiry marker over (H-A-436); a gathering a restart cut settles once heard is bound.
heardStore.b.Ready(func(kv jetstream.KeyValue) {
eachHeard := func(e jetstream.KeyValueEntry) {
if e.Operation() != jetstream.KeyValuePurge {
return
}
if err := ix.Expired(ctx, e.Key()); err != nil {
logger.Printf("versions: %s expired and its reservations are not re-pinned: %v", e.Key(), err)
}
}
if hw, err := settle(ctx, kv, eachHeard); err != nil {
process.NotWatched(logger.Printf, index.Bucket(cred.Module, index.HeardState), err, "no gathering of reservations settles at its bound until the indexer starts again")
} else {
go func() { errs <- follow(ctx, hw, eachHeard) }()
}
go func() {
if err := ix.GatherKept(ctx); err != nil {
logger.Printf("versions: the reservations kept before the start are not settled again: %v", err)
}
}()
})
if err := hub.Handle(meshbuilds.SubjectToolchainAgreed, func(m jetstream.Msg) { heardToolchainAgreed(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
@@ -631,3 +689,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return err
}
}
// reservedSetting is the setting key read as a duration (stdio.SettingDuration); one that does not read is said and takes def.
func reservedSetting(key string, def time.Duration, logf func(string, ...any)) time.Duration {
d, err := stdio.SettingDuration(key, def)
if err != nil {
logf("%v: %s is taken", err, def)
return def
}
return d
}
@@ -14,6 +14,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/views"
@@ -109,6 +110,28 @@ func (b *busObjects) Names(ctx context.Context) ([]string, error) {
return names, nil
}
// List is every object the store holds, a deleted one left out (index.SeatLists).
func (b *busObjects) List(ctx context.Context) ([]buscalls.ObjectInfo, error) {
o, err := b.open(ctx)
if err != nil {
return nil, err
}
infos, err := o.List(ctx)
if errors.Is(err, jetstream.ErrNoObjectsFound) {
return []buscalls.ObjectInfo{}, nil
}
if err != nil {
return nil, err
}
out := make([]buscalls.ObjectInfo, 0, len(infos))
for _, i := range infos {
if !i.Deleted {
out = append(out, buscalls.ObjectInfo{Name: i.Name, Size: i.Size, Chunks: i.Chunks, Digest: i.Digest, Modified: i.ModTime})
}
}
return out, nil
}
func (b *busObjects) Fill(ctx context.Context) (int64, int64, error) {
o, err := b.open(ctx)
if err != nil {
@@ -5,7 +5,9 @@ package main
import (
"context"
"encoding/json"
"errors"
"os"
"reflect"
"slices"
"strconv"
"strings"
@@ -62,14 +64,17 @@ func untilModule(t *testing.T, ctx context.Context, js jetstream.JetStream, name
// go.sum line names it, ADR 0573 §2; design 47 H-A-157), and plain, which requires
// nothing of it, are taken in with mesh-sdk as main's first source revision. A source revision moving mesh-sdk to a commit
// changing its buildstep package is taken in as one revision whose movers are mesh-sdk and importer, of another repository,
// and not plain; the packages key of mesh-sdk/go names that commit with a digest per package.
// and not plain; the packages key of mesh-sdk/go names that commit with a digest per package. Design 47 H2 §804: a key a dry
// run left in the state dry-runs is gone at the start, and the take-in of a branch moving mesh-sdk again, a dry run, leaves
// the trunk's packages state byte for byte as before and no key in dry-runs once it answered.
func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
const (
sdkGo = "git.novox.be/novox/mesh-sdk/go"
m1, m2 = "1111111111111111111111111111111111111111", "2222222222222222222222222222222222222222"
m1, m2, m3 = "1111111111111111111111111111111111111111", "2222222222222222222222222222222222222222", "4444444444444444444444444444444444444444"
catalogMerge = "3333333333333333333333333333333333333333"
goModContent = "module importer\n\nrequire git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000\n"
sdkRoot1, sdk2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
sdk3 = "cccccccccccccccccccccccccccccccccccccccc"
)
avahi, err := os.ReadFile("../../internal/index/testdata/catalogue-a67f0196-avahi.module.json")
if err != nil {
@@ -92,7 +97,7 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
"package.json": "3333333333333333333333333333333333333333", "package-lock.json": "4444444444444444444444444444444444444444",
"tsconfig.json": "5555555555555555555555555555555555555555"}}}
}
var packages jetstream.KeyValue
var packages, dryRuns jetstream.KeyValue
var heard *takeIns
js, ctx, _, _ := startIndexer(t, func(context.Context, buildLog) {}, func(ctx context.Context, js jetstream.JetStream) {
var err error
@@ -118,6 +123,14 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
forge := serveCommits(t, js.Conn())
forge.put(m1, sdkAt(sdkRoot1, "f5", "6666666666666666666666666666666666666666"))
forge.put(m2, sdkAt(sdk2, "f6", "7777777777777777777777777777777777777777"))
forge.put(m3, sdkAt(sdk3, "f7", "8888888888888888888888888888888888888888"))
// A dry run's key left by an indexer that stopped mid-run (§804).
if dryRuns, err = js.KeyValue(ctx, index.Bucket(testIndexer, index.DryRunsState)); err != nil {
t.Fatal(err)
}
if _, err := dryRuns.Put(ctx, index.DryRunPrefix("beta", "0123")+index.PackagesState+".left", []byte(`{"value":"e30="}`)); err != nil {
t.Fatal(err)
}
forge.put(catalogMerge, repoAt{trees: map[string]string{"modules/importer": "t1", "modules/plain": "t2"},
files: map[string]string{"modules/importer/module.json": named("importer"), "modules/plain/module.json": named("plain"),
"modules/importer/go.mod": goModContent, "modules/importer/go.sum": "golang.org/x/sys v0.1.0 h1:x=\n",
@@ -125,7 +138,7 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
regs := registerAvahi(t, ctx, js, "main")
for _, r := range []meshcatalog.Registration{{V: 1, Module: "importer", Origin: "novox/mesh-catalog", Path: "modules/importer", Branches: []string{"main"}},
{V: 1, Module: "plain", Origin: "novox/mesh-catalog", Path: "modules/plain", Branches: []string{"main"}},
{V: 1, Module: "mesh-sdk", Origin: "novox/mesh-sdk", Path: ".", Branches: []string{"main"}}} {
{V: 1, Module: "mesh-sdk", Origin: "novox/mesh-sdk", Path: ".", Branches: []string{"main", "beta"}}} {
raw, _ := json.Marshal(r)
if _, err := regs.Put(ctx, index.RegistrationKey(r.Module), raw); err != nil {
t.Fatal(err)
@@ -134,16 +147,40 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
seedBuildModules(t, ctx, js, nil)
heard = hearTakeIns(t, js.Conn())
})
say := func(source int64, start bool, heads ...meshdelivery.SourceMovedEventHeadsItem) {
sayOn := func(branch string, source int64, start bool, heads ...meshdelivery.SourceMovedEventHeadsItem) {
t.Helper()
raw, _ := json.Marshal(meshdelivery.SourceMovedEvent{V: 1, Branch: "main", Source: source, Call: "0123456789abcdef", Start: start, Heads: heads})
if _, err := js.Publish(ctx, meshdelivery.SubjectSourceMoved("main", strconv.FormatInt(source, 10)), raw); err != nil {
raw, _ := json.Marshal(meshdelivery.SourceMovedEvent{V: 1, Branch: branch, Source: source, Call: "0123456789abcdef", Start: start, Heads: heads})
if _, err := js.Publish(ctx, meshdelivery.SubjectSourceMoved(branch, strconv.FormatInt(source, 10)), raw); err != nil {
t.Fatal(err)
}
}
say := func(source int64, start bool, heads ...meshdelivery.SourceMovedEventHeadsItem) {
t.Helper()
sayOn("main", source, start, heads...)
}
// every is each key of kv with its value.
every := func(kv jetstream.KeyValue) map[string]string {
t.Helper()
out := map[string]string{}
ks, err := kv.Keys(ctx)
if err != nil && !errors.Is(err, jetstream.ErrNoKeysFound) {
t.Fatal(err)
}
for _, k := range ks {
e, err := kv.Get(ctx, k)
if err != nil {
t.Fatal(err)
}
out[k] = string(e.Value())
}
return out
}
say(10, true, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-sdk", Commit: m1}, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-catalog", Commit: catalogMerge})
heard.next(t, "main", 10)
heard.acked(t, "main")
if left := every(dryRuns); len(left) != 0 {
t.Errorf("dry-runs holds %v after the start, want every key gone (§804)", left)
}
// mesh-sdk has released no version: importer keeps the package for its kind-1 edge, with no pin (H-A-161).
untilModule(t, ctx, js, "importer", func(m meshcatalog.ModulesByModuleValue) bool {
pin, kept := m.Packages[sdkGo]
@@ -169,4 +206,18 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
pub, err := index.DecodePublishedPackages(v)
return v != nil && err == nil && pub.Commit == m2 && len(pub.Packages) == 3
})
// A branch's take-in moving mesh-sdk to m3 is a dry run: its packages stay in dry-runs while it runs, the trunk's are
// untouched, and its keys go once it answered (§804).
heard.acked(t, "main")
before := every(packages)
sayOn("beta", 1, true, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-catalog", Commit: catalogMerge}, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-sdk", Commit: m3})
heard.next(t, "beta", 1)
heard.acked(t, "beta")
if after := every(packages); !reflect.DeepEqual(after, before) {
t.Errorf("the branch's take-in changed the trunk's packages state:\n%v\nwant\n%v", after, before)
}
if left := every(dryRuns); len(left) != 0 {
t.Errorf("dry-runs holds %v once the branch's take-in answered, want none", left)
}
}
@@ -57,7 +57,9 @@ func newRegistry(js jetstream.JetStream, conn *nats.Conn, cred process.Account,
if err != nil {
return err
}
_, err = js.Publish(ctx, historySubject(cred.Module, r.Module), data, jetstream.WithMsgID(fmt.Sprintf("%s.%d", r.Module, r.Version)))
// A source-only registration's versions are kept under its key source.<owner>.<name> (design 47 H2 §815).
name := index.RegistrationName(r)
_, err = js.Publish(ctx, historySubject(cred.Module, name), data, jetstream.WithMsgID(fmt.Sprintf("%s.%d", name, r.Version)))
if err == nil {
// Past 80 % full the stream's fill is a finding (design 47 G §704); read within a second, and said when it cannot be.
fctx, cancel := context.WithTimeout(ctx, time.Second)
@@ -105,6 +107,10 @@ func newRegistry(js jetstream.JetStream, conn *nats.Conn, cred process.Account,
Say: func(_ context.Context, e meshcatalog.RegistrationChangedEvent) error {
return publishAs(conn, cred, seatEventSubject(meshcatalog.EventRegistrationChanged), fmt.Sprintf("%s-%s-%d", meshcatalog.EventRegistrationChanged, e.Module, e.Version), e)
},
// The directories of a commit that hold a module.json, the seat git's trees (design 47 H2 §815; H-A-450).
ModuleDirs: func(repository, commit string) ([]string, error) {
return trunkVia(call)(context.Background(), repository, commit)
},
Placement: func(module string) ([]mma.ModulePlacement, error) {
raw, err := call("seat:"+mma.Seat+"."+mma.VerbPlacement, mma.PlacementInput{Module: module})
if err != nil {
@@ -110,18 +110,26 @@ func (b *seatBus) said(c index.SeatDefinitionChanged) {
// seatlist.Part, novox/hq ADR 0636 §7), which gives catalogue what it holds at every change, and wraps say so that each move
// the indexer says is also heard by the reader. Its two tools are not served: the indexer's process serves no request
// subject (ADR 0437 §4), and its list is its own state seat-definitions, which indexer_seat_definition and the seat's verb
// seat-definitions read. It returns the part, whose status the indexer's health can show.
func followSeatList(bus *seatBus, say func(context.Context, index.SeatDefinitionChanged) error, logf func(string, ...any), changed func()) (*seatlist.Part, func(context.Context, index.SeatDefinitionChanged) error) {
// seat-definitions read. It returns the part, whose status the indexer's health can show. At each trunk definition's move,
// said or not, the seat list is kept as one object in lists, the objects seat-lists (design 47 H2 §814, §820, H-A-441), a
// failure said in logf.
func followSeatList(bus *seatBus, say func(context.Context, index.SeatDefinitionChanged) error, logf func(string, ...any), changed func(), lists index.SeatLists) (*seatlist.Part, func(context.Context, index.SeatDefinitionChanged) error) {
part := seatlist.NewPart(toolPrefix)
part.Follow(bus, changed, logf)
return part, func(ctx context.Context, c index.SeatDefinitionChanged) error {
if err := say(ctx, c); err != nil {
return err
if c.Source != index.SourceTrunk { // only a trunk's definition is the seat list's
return say(ctx, c)
}
if c.Source == index.SourceTrunk { // only a trunk's definition is the seat list's
err := say(ctx, c)
if err == nil {
bus.said(c)
}
return nil
if lists != nil {
if _, kerr := index.KeepSeatList(ctx, bus.defs, lists, logf); kerr != nil {
logf("the seat list is not kept in %s after %s moved: %v", index.SeatListsObjects, c.Seat, kerr)
}
}
return err
}
}
@@ -139,5 +147,16 @@ func readWhenBound(part *seatlist.Part, states ...bucket) {
}
}
// keepSeatListAtStart keeps the seat list in lists once the seat definitions' state is bound at the indexer's start, so the
// verb seat-list answers from the first delivery and not only after a trunk definition's move (design 47 H2 §814; H-A-447).
// A list that cannot be kept is said in logf.
func keepSeatListAtStart(ctx context.Context, state bucket, defs views.Source, lists index.SeatLists, logf func(string, ...any)) {
state.Ready(func(jetstream.KeyValue) {
if _, err := index.KeepSeatList(ctx, defs, lists, logf); err != nil {
logf("the seat list is not kept in %s at the start: %v", index.SeatListsObjects, err)
}
})
}
// toolPrefix is the prefix of the indexer's tools, its manifest's slug.
const toolPrefix = "indexer"
@@ -1,7 +1,10 @@
package main
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
@@ -10,6 +13,8 @@ import (
"git.novox.be/novox/mesh-sdk/go/seatlist"
"git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-indexer/internal/index"
)
type unboundSource struct {
@@ -44,7 +49,17 @@ func (b *awaitedFake) Ready(f func(jetstream.KeyValue)) { b.ready = append(b.rea
func TestTheSeatListIsReadAgainWhenItsStatesAreBound(t *testing.T) {
src := &unboundSource{}
bus := &seatBus{defs: src, marks: src}
part, _ := followSeatList(bus, nil, t.Logf, nil)
var mu sync.Mutex
var unkept []string
logf := func(f string, a ...any) {
t.Logf(f, a...)
if strings.HasPrefix(f, "the seat list is not kept in %s after") {
mu.Lock()
unkept = append(unkept, fmt.Sprintf(f, a...))
mu.Unlock()
}
}
part, say := followSeatList(bus, func(context.Context, index.SeatDefinitionChanged) error { return nil }, logf, nil, &busObjects{})
reader := part.Reader()
<-reader.Ready()
if reader.Status().Heard {
@@ -76,5 +91,24 @@ func TestTheSeatListIsReadAgainWhenItsStatesAreBound(t *testing.T) {
if _, ok := seatlist.Definition(part.Reader, "no-such-seat")(); ok {
t.Error("a seat the list does not hold is answered a definition")
}
// Design 47 H2 §814 (H-A-441): a trunk definition's move keeps the seat list in seat-lists, a pull request's does not; here
// the list holds no definition, so the keeping is refused and said.
_ = say(context.Background(), index.SeatDefinitionChanged{Seat: "a", Source: "pull-7", Digest: "d"})
_ = say(context.Background(), index.SeatDefinitionChanged{Seat: "a", Source: index.SourceTrunk, Digest: "d"})
mu.Lock()
defer mu.Unlock()
if len(unkept) != 1 || !strings.Contains(unkept[0], "holds no trunk definition") {
t.Errorf("the moves kept the seat list as %q, want one try, for the trunk's", unkept)
}
// H-A-447: and once the state is bound at the start, with no move.
started, atStart := &awaitedFake{}, ""
keepSeatListAtStart(context.Background(), started, src, &busObjects{}, func(f string, a ...any) { atStart = fmt.Sprintf(f, a...) })
if atStart != "" || len(started.ready) != 1 {
t.Fatalf("the seat list was kept before its state was bound: %q", atStart)
}
started.ready[0](nil)
if !strings.Contains(atStart, "at the start") || !strings.Contains(atStart, "holds no trunk definition") {
t.Errorf("the start kept the seat list as %q, want one try", atStart)
}
var _ seatlist.Bus = bus
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"strings"
"time"
"github.com/nats-io/nats.go/jetstream"
@@ -32,8 +33,8 @@ type takerIn interface {
// written back, by compare-and-set at its revision, with what the indexer stored or why not. A value
// answered already (this indexer's own write) or deleted is left.
func takenIn(ctx context.Context, ix takerIn, kv jetstream.KeyValue, e jetstream.KeyValueEntry, logf func(string, ...any)) {
if e.Operation() != jetstream.KeyValuePut {
return
if e.Operation() != jetstream.KeyValuePut || strings.HasPrefix(e.Key(), index.RunningPrefix) {
return // a running take-in's waiting-on is the indexer's own record, no ask (H-A-409)
}
a, err := index.DecodeTakeIn(e.Value())
if err != nil {
@@ -592,7 +592,7 @@ func TestIndexerWhole(t *testing.T) {
t.Errorf("main 14 at main 13's head said %+v, want no mover", next)
}
var log []string
tools := index.HeldTools(kvStore{held}, askVia(t, ctx, takeinsKV), time.Now, func(what, why string) error {
tools := index.HeldTools(kvStore{held}, kvStore{takeinsKV}, askVia(t, ctx, takeinsKV), time.Now, func(what, why string) error {
log = append(log, what+": "+why)
return nil
})
@@ -625,6 +625,30 @@ func TestIndexerWhole(t *testing.T) {
if _, _, err := index.ReadRevision(ctx, objects, "gamma.1"); err != nil {
t.Errorf("gamma.1 is not kept: %v", err)
}
// Design 47 H2 §815: a source-only registration, kept under source.<owner>.<name>, watches its branch as any registration
// does, and a move of that branch by its repository, which holds no manifest, is taken in with no movers.
const hqCommit = "4444444444444444444444444444444444444444"
forge.put(hqCommit, repoAt{trees: map[string]string{}})
watchBranch(t, ctx, js, "delta")
source, _ := json.Marshal(meshcatalog.Registration{V: 1, Origin: "novox/hq", Branches: []string{"delta"},
Check: &meshcatalog.SourceCheck{Seat: meshcatalog.SourceCheckSeatNodeBuildGo, Step: meshcatalog.SourceCheckStepUnit}})
if _, err := regs.Put(ctx, meshcatalog.RegistrationsBySourceOwnerNameKey("novox", "hq"), source); err != nil {
t.Fatal(err)
}
if _, err := js.Publish(ctx, meshcatalog.SubjectRegistrationChanged, []byte(`{"module":"source.novox.hq"}`)); err != nil {
t.Fatal(err)
}
sayMoved(t, ctx, js, "delta", 1, c10, true)
heard.next(t, "delta", 1)
moved, _ := json.Marshal(meshdelivery.SourceMovedEvent{V: 1, Branch: "delta", Source: 2, Call: "00112233445566aa",
Heads: []meshdelivery.SourceMovedEventHeadsItem{{Repository: "novox/hq", Commit: hqCommit}}})
if _, err := js.Publish(ctx, meshdelivery.SubjectSourceMoved("delta", "2"), moved); err != nil {
t.Fatal(err)
}
if hq := heard.next(t, "delta", 2); len(hq.Entries) != 0 || hq.Revision != 2 {
t.Errorf("the move of novox/hq on delta said %+v, want revision 2 with no movers", hq)
}
}
// toolNamed is the tool of that name.
@@ -92,7 +92,7 @@ func TestEveryHandToolsAskIsReadAndActedOn(t *testing.T) {
}
record := func(string, string) error { return nil }
tools := map[string]func(map[string]any) (any, error){}
for _, tl := range slices.Concat(index.HeldTools(nil, ask, time.Now, record), index.PinsTools(nil, nil, ask, time.Now, record),
for _, tl := range slices.Concat(index.HeldTools(nil, nil, ask, time.Now, record), index.PinsTools(nil, nil, ask, time.Now, record),
index.RunsTools(nil, nil, ask, time.Now, record), index.NamedTools(ask, time.Now, record),
index.FingerprintsTools(ask, time.Now, record, time.Minute), index.CatalogRevisionTools(nil, ask, time.Now, record),
index.RegistrationTools(nil, nil, ask, time.Now, func(string, string, string, string) error { return nil })) {
@@ -98,6 +98,38 @@ func heardPackagePublished(ctx context.Context, ix *index.Indexer, m jetstream.M
_ = m.Ack()
}
// heardVersionReserved takes one version-reserved of the seat mesh-builds in (design 47 H2 §805): one that does not decode
// is said and acknowledged; one that cannot be kept is left, so the bus gives it again.
func heardVersionReserved(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e meshbuilds.VersionReservedEvent
if err := json.Unmarshal(m.Data(), &e); err != nil {
logf("%s holds what is no version-reserved, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.HearVersionReserved(ctx, e); err != nil {
logf("versions: the version-reserved of %s %s could not be kept, so the bus gives it again: %v", e.Artifact, e.Version, err)
leftForBus(m, fmt.Sprintf("the version-reserved of %s %s", e.Artifact, e.Version), err, logf)
return
}
_ = m.Ack()
}
// heardBuildStepEnded settles the reservations of the step's pipeline, if they gather (design 47 H2 §805, H-A-424 (1)):
// the builder reserves every mover before it asks the first build. A settle that fails is said; its bound settles again.
func heardBuildStepEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e meshbuilds.StepEnded
if err := json.Unmarshal(m.Data(), &e); err != nil {
logf("%s holds what is no step-ended, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.Settle(ctx, e.Pipeline); err != nil {
logf("versions: the reservations of %s are not re-pinned at its step-ended: %v", e.Pipeline, err)
}
_ = m.Ack()
}
// heardToolchainAgreed keeps the newest toolchain-agreed of its language (A-68); one that does not decode is said and
// acknowledged, one that cannot be kept is left, so the bus gives it again.
func heardToolchainAgreed(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
@@ -21,8 +21,9 @@
// read mesh-sdk and mesh-catalog. None reads mesh-controller, which ended by its unassignment (novox/hq
// ADR 0590). In a mesh where either module has no source repository nothing is
// cloned, and these tests fail loudly with "not beside this check": a cause in the setup, not in the
// change. And in a delivery group that holds a mesh-catalog pull request, these tests read the
// catalogue's main, not the group's head.
// change. In a delivery group that holds a mesh-catalog member, these tests read that member's head, the
// sibling the group's check places in MESH_CHECK_BESIDE, and the catalogue's main only when the catalogue is
// not in the group: a group is judged against its own heads (ADR 0573 §2; design 47 H2 §814, H-A-428).
// - Anywhere else, the test judges against the copy captured in this repository's testdata/beside, at the
// commit testdata/beside/CAPTURED names. Never against a developer's own checkout: to judge one, set
// MESH_CHECK_BESIDE to the directory holding it, as the check does.
@@ -229,8 +229,10 @@ func ReplacedSiblings(goMod []byte, repository string) []string {
// VersionLine is the version line's value of each package (Inputs.Packages) of a module of repository: a mesh Go
// module of another repository by its version (versions), and one of repository itself, replaced by its directory
// (ReplacedSiblings), by the content its directory publishes, `content:` and the hex sha256 of its requirements' digest
// and each package's digest (empty while it is not published, which gives no fingerprint until it is, as a version
// none publishes does).
// and each package's digest. A package of another repository with no version is empty, which gives no fingerprint until
// it is published (NoPackageVersion); one of repository that is not published yet has no line: it enters by its
// directory's tree, which the module's tree input carries (its own directory, or a derived directory of H-A-202), never by
// a commit (design 47 H2 §802, H-A-349 DQ-8).
func VersionLine(repository string, packages []string, versions sdkstep.PackageVersions, published map[string]meshcatalog.PackagesByModuleValue) map[string]string {
if len(packages) == 0 {
return nil
@@ -244,7 +246,6 @@ func VersionLine(repository string, packages []string, versions sdkstep.PackageV
}
pub, held := published[p]
if !held {
out[p] = ""
continue
}
lines := []string{"requires " + pub.Requires}
@@ -62,8 +62,17 @@ func versionLineTakesASiblingDirectoryByItsContent(t *testing.T) {
if a, b := line("d1"), line("d2"); a == b {
t.Error("a change of the sibling directory alone left the importer's fingerprint where it was")
}
if got := VersionLine(repo, []string{buildrun}, nil, nil)[buildrun]; got != "" {
t.Errorf("an unpublished sibling is taken as %q, want none (no fingerprint until it is published)", got)
// An unpublished sibling has no line: it enters by its directory's tree, which the tree input carries (design 47 H2
// §802, H-A-349 DQ-8); one of another repository with no version still gives no fingerprint.
if got, ok := VersionLine(repo, []string{buildrun}, nil, nil)[buildrun]; ok {
t.Errorf("an unpublished sibling is taken as %q, want no line (it enters by its directory's tree)", got)
}
in := base()
if in.Packages = VersionLine(repo, []string{sdk}, nil, nil); in.Packages[sdk] != "" {
t.Fatalf("a package of another repository with no version is taken as %q", in.Packages[sdk])
}
if fp, none := Of(in); fp != "" || !strings.HasPrefix(none, NoPackageVersion) {
t.Errorf("a package of another repository with no version gives %q (%q), want none naming it", fp, none)
}
}
@@ -126,8 +126,16 @@ type Indexer struct {
// content; nil reads none.
GoMod func(ctx context.Context, repository, sha, dir string) ([]byte, error)
// Now is the clock of a taken value; nil is time.Now.
Now func() time.Time
Builds *Builds
Now func() time.Time
// Bound bounds a running take-in's wait (takein_waiting.go), a context's bound and no timer (ADR 0437 §8); nil is
// context.WithTimeout.
Bound func(context.Context, time.Duration) (context.Context, context.CancelFunc)
// TakeIns is the state takeins, where a running take-in keeps what it waits on (design 47 H2 §803, H-A-409); nil keeps none.
TakeIns Store
// DryRuns is the state dry-runs, a dry run's scratch of the packages it writes (dryrun.go; design 47 H2 §804); nil keeps
// a dry run's packages in memory.
DryRuns Store
Builds *Builds
// Named asks the forge for the git object of each named path of the module directories given, at a commit
// (the seat git's trees with paths; novox/hq ADR 0499 clauses 2 and 3): the indexer is the one reader of a
// manifest's paths (ADR 0495 clause 1, the lead's decision L8 of R4e). Nil asks nothing, and a module naming paths
@@ -156,7 +164,7 @@ type Indexer struct {
filling atomic.Bool // a FillTaken runs in the background (KickFill)
fillAgain atomic.Bool // a kick arrived while it ran
underSeats bool // a dry run inside judge.WithSeats: its judge passes do not hold the seat list (verdicts.go)
isDry bool // a dry run (dryrun.go): it shares the live packages state, so it drops no kept package key (packages.go)
isDry bool // a dry run (dryrun.go): its packages are a working copy over the live state, and it drops no kept package key (packages.go)
judgeMu sync.Mutex // one judge pass at a time (verdicts.go)
keepMu sync.Mutex // one catalog graph revision kept at a time (keepEntries)
// Pins is the state pins (pins.go); nil keeps none. PinsPending says how many messages the indexer's durable consumer of the
@@ -184,6 +192,10 @@ type Indexer struct {
runMu sync.Mutex // one run event at a time (runcandidates.go)
heldFull atomic.Bool // a take-in is held because the catalog store is full: room is said when it has room again (RoomAgain)
pendingMu sync.Mutex // one take-in step at a time: a merge, a group's end, the start and a hand act (pending.go)
// ReservedKeep is how long a reservation is kept in the state heard, and ReservedSettle how long after a revision's
// first reservation its gathering settles at the latest: the settings reserved-keep and reserved-settle (design 47 H2
// §805, H-A-424); zero takes the default.
ReservedKeep, ReservedSettle time.Duration
}
func (ix *Indexer) logf(format string, args ...any) {
@@ -27,13 +27,14 @@ const CatalogEntryLayout = 1
// CatalogEntryOf is the catalog graph entry of one module: the module graph's node of it as a recompute computed it
// (its build, provision and verb edges, the verb edges left out on a cycle, ADR 0614), with where the trunk holds it,
// its manifest's digest and verdict, the main package its process runs (MainOf), the package versions it builds against
// and what the indexer computes its next revision from (Inputs: the lead's ruling on milestone 47/G finding 1), so that
// and what the indexer computes its next revision from (Inputs: the lead's ruling on milestone 47/G finding 1), and its
// manifest's class, core or leaf, absent for none (design 47 H2 §810, H-A-394 (1): the gate reads it), so that
// ModuleValueOf gives the module's value back from the entry alone. The acting rules are the revision's to add.
func CatalogEntryOf(module string, cur meshcatalog.ModulesByModuleValue, m catalogue.Manifest, raw string, n graph.Node) meshcatalog.CatalogEntry {
e := meshcatalog.CatalogEntry{V: CatalogEntryLayout, Module: module, Repository: cur.Repository, Path: cur.Path,
Commit: cur.Commit, Manifest: manifestWhole(raw), ManifestDigest: meshcatalogclient.EntryManifestDigest(cur.Manifest), Verdict: cur.Verdict, Fp: n.FP, None: n.None, Bases: n.Bases,
Packages: maps.Clone(cur.Packages), Provides: n.Provides, Requires: n.Requires, Awaits: n.Awaits, Invokes: n.Invokes,
Serves: n.Serves, LeftOut: n.LeftOut, Main: MainOf(m), Contributes: contributesOf(m)}
Serves: n.Serves, LeftOut: n.LeftOut, Main: MainOf(m), Contributes: contributesOf(m), Class: m.Class}
// requires names every requirement as catalogue.Manifest.Wants lists them, optional ones and those only contributes names
// included, since contributing to a requirement is requiring it (design 47 G §709, A-229).
for _, r := range m.Wants() {
@@ -106,7 +106,11 @@ func TestAnEntryNamesWhatItContributesToAndEveryRequirement(t *testing.T) {
if n := graph.NodeOf(e); !reflect.DeepEqual(n.Requires, []string{"database", graph.BusState, "route"}) {
t.Errorf("the node's requires = %v, want the optional cache left out", n.Requires)
}
if e := CatalogEntryOf("kv", meshcatalog.ModulesByModuleValue{}, catalogue.Manifest{}, "", graph.Node{}); e.Contributes != nil {
t.Errorf("an entry of a manifest contributing nothing carries contributes %v", e.Contributes)
if e := CatalogEntryOf("kv", meshcatalog.ModulesByModuleValue{}, catalogue.Manifest{}, "", graph.Node{}); e.Contributes != nil || e.Class != "" {
t.Errorf("an entry of a manifest contributing nothing and naming no class carries contributes %v, class %q", e.Contributes, e.Class)
}
// Design 47 H2 §810, H-A-394 (1): the entry carries its manifest's class, which the gate reads.
if e := CatalogEntryOf("kv", meshcatalog.ModulesByModuleValue{}, catalogue.Manifest{Class: catalogue.ClassCore}, "", graph.Node{}); e.Class != catalogue.ClassCore {
t.Errorf("the entry of a core manifest carries the class %q, want core", e.Class)
}
}
@@ -1,12 +1,20 @@
package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"strings"
"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/nodebuildgo"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
)
type dryRun struct {
@@ -14,12 +22,20 @@ type dryRun struct {
modules, graph *overlayStore
candidates, taken, predefined *overlayStore
oldSections *overlayStore
// scratch is the state dry-runs this dry run's packages are written to, under prefix (§804); nil when the indexer keeps
// none, and the packages then stay in memory.
scratch Store
prefix string
logf func(string, ...any)
}
// dry is an indexer over overlays of this one's states (overlay.go), for a run on request's candidate (runcandidates.go): what
// it computes stays in memory and nothing reaches the bus but the manifests and the packages, which clause 1 writes all the
// same. It says no event, kicks nothing in the background, and knows what this one knows of the source and the toolchains. Every field of Indexer is named here (TestDryNamesEveryField holds it so).
func (ix *Indexer) dry() *dryRun {
// dry is an indexer over overlays of this one's states (overlay.go), for a run on request's candidate (runcandidates.go), a
// branch's take-in or re-pin: what it computes stays in memory but the packages it writes, kept in the state dry-runs under
// the branch and call given (scratchStore; design 47 H2 §804, H-A-413), so the trunk's packages state is left untouched; its
// manifests are written create-once by digest as every take-in's (H-A-413's addendum). The caller ends it (end) once it
// answered. It says no event, kicks nothing in the background, and knows what this one knows of the source and the
// toolchains. Every field of Indexer is named here.
func (ix *Indexer) dry(branch, call string) *dryRun {
over := func(st Store) (Store, *overlayStore) {
if st == nil {
return nil, nil
@@ -27,9 +43,17 @@ func (ix *Indexer) dry() *dryRun {
o := newOverlay(st)
return o, o
}
d := &dryRun{}
x := &Indexer{Module: ix.Module, Manifests: ix.Manifests, Packages: ix.Packages, JudgeID: ix.JudgeID, Files: ix.Files, GoSum: ix.GoSum,
GoMod: ix.GoMod, Now: ix.Now, Builds: ix.Builds, Named: ix.Named, Trunk: ix.Trunk, BranchHead: ix.BranchHead, Read: ix.Read, Contains: ix.Contains,
d := &dryRun{scratch: ix.DryRuns, prefix: DryRunPrefix(branch, call), logf: ix.logf}
packages := ix.Packages
if packages != nil && d.scratch != nil {
packages = &scratchStore{under: ix.Packages, scratch: d.scratch, prefix: d.prefix + PackagesState + "."}
} else if packages != nil {
packages = newOverlay(ix.Packages)
}
x := &Indexer{Module: ix.Module, Manifests: ix.Manifests, Packages: packages, DryRuns: nil, JudgeID: ix.JudgeID, Files: ix.Files, GoSum: ix.GoSum,
GoMod: ix.GoMod, Now: ix.Now, Bound: ix.Bound,
// A dry run keeps no waiting-on: the take-in it computes for says its waits through the live indexer (H-A-409).
TakeIns: nil, Builds: ix.Builds, Named: ix.Named, Trunk: ix.Trunk, BranchHead: ix.BranchHead, Read: ix.Read, Contains: ix.Contains,
SayTakeIn: nil,
// The registry milestone's fields: what a take-in would write on the bus stays out of a dry run, so the states of the
// requirements, findings, seat definitions, holds and their bounds are not overlaid, nothing is said, and no hold is
@@ -83,3 +107,236 @@ func (ix *Indexer) refuseDisagreement(c meshcatalog.CandidatesByGroupValue) erro
}
return nil
}
// DryRunsState is the indexer's state dry-runs (design 47 H2 §804, §820; H-A-413): a dry run's scratch, the overlay of the
// packages state a dry run writes, keyed <branch>.<call>.<kind>.<name> (DryRunPrefix, the kind the overlaid state's name and
// the name its key), so a dry run leaves the trunk's packages state untouched. The indexer deletes a dry run's keys when it
// answers, and every key at its start; each lives an hour at most (the state's TTL). indexer_dry_runs reads it.
const (
DryRunsState = "dry-runs"
DryRunsTool = "indexer_dry_runs"
)
// DryRunPrefix is the prefix of a dry run's keys in the state dry-runs: its branch, escaped as a key's name is, and its call.
func DryRunPrefix(branch, call string) string {
return keys.EscapeName(branch) + "." + keys.EscapeName(call) + "."
}
// scratchRevision lifts a revision of the state dry-runs above every revision of the state it overlays, as overlayStore does.
const scratchRevision = 1 << 62
// scratched is a value of the state dry-runs: the value a dry run wrote over its key, or that it deleted it.
type scratched struct {
Value []byte `json:"value,omitempty"`
Deleted bool `json:"deleted,omitempty"`
}
// scratchStore is a store whose writes go to the state dry-runs under its prefix, over the store it reads through: a key
// it wrote reads as written, a key it deleted as absent, every other as the store under it holds it. Its compare-and-set
// holds against what it reads, a key it wrote carrying the dry-runs revision lifted by scratchRevision.
type scratchStore struct {
under, scratch Store
prefix string
}
func (s *scratchStore) held(ctx context.Context, key string) (scratched, uint64, bool, error) {
raw, rev, found, err := s.scratch.Get(ctx, s.prefix+key)
if err != nil || !found {
return scratched{}, 0, false, err
}
var v scratched
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, false, fmt.Errorf("%s.%s%s: %w", DryRunsState, s.prefix, key, err)
}
return v, rev, true, nil
}
func (s *scratchStore) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
v, rev, found, err := s.held(ctx, key)
if err != nil {
return nil, 0, false, err
}
if found {
if v.Deleted {
return nil, rev + scratchRevision, false, nil
}
return v.Value, rev + scratchRevision, true, nil
}
if s.under == nil {
return nil, 0, false, nil
}
return s.under.Get(ctx, key)
}
// put checks the revision read against what the key reads as now and writes it into the state dry-runs.
func (s *scratchStore) put(ctx context.Context, key string, value []byte, revision uint64, create, del bool) error {
_, own, mine, err := s.held(ctx, key)
if err != nil {
return err
}
_, rev, found, err := s.Get(ctx, key)
if err != nil {
return err
}
if create && found || !create && (!found || rev != revision) {
return ErrConflict
}
data, err := json.Marshal(scratched{Value: value, Deleted: del})
if err != nil {
return err
}
if mine {
return s.scratch.Update(ctx, s.prefix+key, data, own)
}
return s.scratch.Create(ctx, s.prefix+key, data)
}
func (s *scratchStore) Create(ctx context.Context, key string, value []byte) error {
return s.put(ctx, key, value, 0, true, false)
}
func (s *scratchStore) Update(ctx context.Context, key string, value []byte, revision uint64) error {
return s.put(ctx, key, value, revision, false, false)
}
func (s *scratchStore) Delete(ctx context.Context, key string, revision uint64) error {
return s.put(ctx, key, nil, revision, false, true)
}
func (s *scratchStore) Keys(ctx context.Context) ([]string, error) {
var out []string
if s.under != nil {
var err error
if out, err = s.under.Keys(ctx); err != nil {
return nil, err
}
}
all, err := s.scratch.Keys(ctx)
if err != nil {
return nil, err
}
mine := map[string]bool{}
for _, k := range all {
if !strings.HasPrefix(k, s.prefix) {
continue
}
key := strings.TrimPrefix(k, s.prefix)
v, _, found, err := s.held(ctx, key)
if err != nil {
return nil, err
}
if found {
mine[key] = !v.Deleted
}
}
out = slices.DeleteFunc(out, func(k string) bool { _, ok := mine[k]; return ok })
for k, live := range mine {
if live {
out = append(out, k)
}
}
slices.Sort(out)
return out, nil
}
// end deletes the dry run's keys from the state dry-runs, once it answered (§804); a key it cannot delete is said, and goes
// with the state's TTL or at the indexer's next start.
func (d *dryRun) end(ctx context.Context) {
if d == nil || d.scratch == nil {
return
}
if err := dropPrefixed(ctx, d.scratch, d.prefix); err != nil {
d.logf("the dry run's keys %s* are not all deleted from %s: %v", d.prefix, DryRunsState, err)
}
}
// ClearDryRuns deletes every key of the state dry-runs, at the indexer's start (§804): no dry run outlives a start.
func ClearDryRuns(ctx context.Context, st Store) error { return dropPrefixed(ctx, st, "") }
func dropPrefixed(ctx context.Context, st Store, prefix string) error {
all, err := st.Keys(ctx)
if err != nil {
return err
}
var errs []error
for _, k := range all {
if !strings.HasPrefix(k, prefix) {
continue
}
_, rev, found, err := st.Get(ctx, k)
if err == nil && found {
err = st.Delete(ctx, k, rev)
}
if err != nil && !errors.Is(err, ErrConflict) {
errs = append(errs, fmt.Errorf("%s: %w", k, err))
}
}
return errors.Join(errs...)
}
// DryRunKey is one key of the state dry-runs as indexer_dry_runs answers it: the key, the value the dry run wrote (none when
// it deleted the key) and whether it deleted it.
type DryRunKey struct {
Key string `json:"key"`
Value json.RawMessage `json:"value,omitempty"`
Deleted bool `json:"deleted,omitempty"`
}
// DryRunsAnswer is indexer_dry_runs' answer: the keys in key order up to views.PageBytes, capped when more are held, and
// how many the state holds in all.
type DryRunsAnswer struct {
Keys []DryRunKey `json:"keys"`
Capped bool `json:"capped,omitempty"`
Total int `json:"total"`
}
// ReadDryRuns is what the state dry-runs holds now, at most views.PageBytes of values (§804, §811).
func ReadDryRuns(ctx context.Context, st Store) (DryRunsAnswer, error) {
out := DryRunsAnswer{Keys: []DryRunKey{}}
if st == nil {
return out, nil
}
all, err := st.Keys(ctx)
if err != nil {
return out, err
}
slices.Sort(all)
out.Total = len(all)
size := 0
for _, k := range all {
raw, _, found, err := st.Get(ctx, k)
if err != nil {
return out, err
}
if !found {
continue
}
var v scratched
if err := json.Unmarshal(raw, &v); err != nil {
return out, fmt.Errorf("%s.%s: %w", DryRunsState, k, err)
}
if size += len(k) + len(v.Value); size > views.PageBytes && len(out.Keys) > 0 {
out.Capped = true
break
}
e := DryRunKey{Key: k, Deleted: v.Deleted}
if !v.Deleted {
e.Value = v.Value
}
out.Keys = append(out.Keys, e)
}
return out, nil
}
// DryRunsTools are the dry runs' tools: indexer_dry_runs reads the state dry-runs (§804).
func DryRunsTools(st Store) []stdio.Tool {
return []stdio.Tool{{Name: DryRunsTool,
Description: "The dry runs' scratch state dry-runs (design 47 H2 §804): the packages a branch's take-in, a run's candidate " +
"or a branch's re-pin computes, kept as <branch>.<call>.packages.<name> while it runs, so the trunk's packages state " +
"is left untouched; a dry run's keys go when it answers and every key at the indexer's start. Each key with the " +
"value it wrote or deleted, up to 768 KB (capped) and the total held.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) {
return ReadDryRuns(context.Background(), st)
}}}
}
@@ -22,7 +22,7 @@ const CallUnansweredKind = "indexer-call-unanswered"
// H-A-242, H-A-247): its own, the process reader's event-unhandled and the family-not-heard of the heard writer it is handed
// (H-A-247 (1)); a views reader's and the emitter's (views.ViewKinds) are always the writer's besides. The tool runner's
// writer over the same state `findings` owns its own. TestFindingKindsHoldEveryKindTheCodeRaises holds the code to this list.
var FindingKinds = []string{PinMissingKind, OutOfStepKind, PackagesNotPublishedKind, HistoryFillingKind, SeedWaitsKind,
var FindingKinds = []string{TakeInWaitingKind, PinMissingKind, OutOfStepKind, PackagesNotPublishedKind, HistoryFillingKind, SeedWaitsKind,
SeedLeftOutKind, SeatDefinitionUnparsedKind, SeatDefinedTwiceKind, SeatOutsideItsDomainKind, CallUnansweredKind,
views.EventUnhandledKind, heard.Kind}
@@ -7,7 +7,6 @@ import (
"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"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"mesh-delivery-indexer/internal/fingerprint"
)
@@ -39,14 +38,15 @@ type form struct {
// another repository its go.mod requires, at any version (design 47 H-A-157), read as the indexer always read it
// (fingerprint.HeldVersionsOf), and the content of each mesh Go module of its own repository its go.mod replaces by a
// directory (fingerprint.VersionLine), so a change of that directory alone moves it (review finding 2). Its versions are the other repositories' alone.
// A package of another repository none of them publishes takes the commit the gate's source names for its repository
// (heads, design 47 G A-365).
// A package of another repository none of them publishes leaves the module without a fingerprint until one does
// (fingerprint.NoPackageVersion), and one of its own repository none publishes enters by its directory's tree alone,
// never by a commit: the same source, the same fingerprint (design 47 H2 §802, H-A-349 DQ-8).
// - **An accepted series** (DLV-I6): published and pins come from acceptedSeries, so a mesh Go module of another
// repository whose series the module accepts enters, in either form, by its series' newest published version and the
// digests of that version's commit.
//
// It sets kept.ImportForm when it writes the import form.
func formOf(module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, toolchains map[string]meshcatalogclient.Toolchain2, prev meshcatalog.ModulesByModuleValue, held map[string]meshcatalog.ModulesByModuleValue, published map[string]meshcatalog.PackagesByModuleValue, pins sdkstep.PackageVersions, heads map[string]string, logf func(string, ...any)) form {
func formOf(module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, toolchains map[string]meshcatalogclient.Toolchain2, prev meshcatalog.ModulesByModuleValue, held map[string]meshcatalog.ModulesByModuleValue, published map[string]meshcatalog.PackagesByModuleValue, pins sdkstep.PackageVersions, logf func(string, ...any)) form {
in := inputsFrom(module, *kept, toolchains)
if len(kept.Imports) > 0 {
r := fingerprint.Resolve(repository, kept.Imports, published)
@@ -58,11 +58,11 @@ func formOf(module, repository string, kept *meshcatalog.ModulesByModuleValueInp
return form{none: none}
case kept.ImportForm == fp && prev.Fp2 != "":
// The build that reported the imports stands, and so do its versions.
return form{fp: prev.Fp2, versions: refined(sdkstep.PackageVersions(prev.Packages), r.Versions, module, repository, kept, held, pins, heads),
return form{fp: prev.Fp2, versions: refined(sdkstep.PackageVersions(prev.Packages), r.Versions, module, repository, kept, held, pins),
stands: true, raw: fp, built: prev.Packages}
}
kept.ImportForm = fp
return form{fp: fp, versions: refined(r.Versions, nil, module, repository, kept, held, pins, heads)}
return form{fp: fp, versions: refined(r.Versions, nil, module, repository, kept, held, pins)}
}
if logf != nil {
logf("%s: no published package holds %s, so its fingerprint takes the version line", module, strings.Join(r.Missing, ", "))
@@ -71,7 +71,7 @@ func formOf(module, repository string, kept *meshcatalog.ModulesByModuleValueInp
// The fingerprint written here is the version line's, not the import form's: no import form is held for the inputs it was
// computed from, so a later pass whose import form computes the same does not take this one for the build's (issue 1966).
kept.ImportForm = ""
versions := lineVersions(module, repository, kept, held, pins, heads, logf)
versions := lineVersions(module, repository, kept, held, pins, logf)
in.Packages = fingerprint.VersionLine(repository, kept.Packages, versions, published)
fp, none := fingerprint.Of(in)
if fp == "" {
@@ -83,22 +83,22 @@ func formOf(module, repository string, kept *meshcatalog.ModulesByModuleValueInp
// refined are an import form's versions: the first of sets that names a package, else, while the module's go.mod
// requires a mesh package of another repository (kept.Packages), the version line's, so a build's reported imports
// refine the go.mod's set and never empty it (design 47 H-A-157); nil when nothing names one.
func refined(versions, then sdkstep.PackageVersions, module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, held map[string]meshcatalog.ModulesByModuleValue, pins sdkstep.PackageVersions, heads map[string]string) sdkstep.PackageVersions {
func refined(versions, then sdkstep.PackageVersions, module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, held map[string]meshcatalog.ModulesByModuleValue, pins sdkstep.PackageVersions) sdkstep.PackageVersions {
switch {
case len(versions) > 0:
return versions
case len(then) > 0:
return then
case len(fingerprint.OtherPackages(kept.Packages, repository)) > 0:
return lineVersions(module, repository, kept, held, pins, heads, nil)
return lineVersions(module, repository, kept, held, pins, nil)
}
return versions
}
// lineVersions are the version line's versions of the mesh Go modules of other repositories the module's go.mod requires
// (kept.Packages): each as the indexer has always read it, an accepted series' pin over it, else the commit the gate's
// source names for its repository.
func lineVersions(module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, held map[string]meshcatalog.ModulesByModuleValue, pins sdkstep.PackageVersions, heads map[string]string, logf func(string, ...any)) sdkstep.PackageVersions {
// (kept.Packages): each as the indexer has always read it, an accepted series' pin over it; one neither gives has no
// version, so the module has no fingerprint until it is published (design 47 H2 §802).
func lineVersions(module, repository string, kept *meshcatalog.ModulesByModuleValueInputs2, held map[string]meshcatalog.ModulesByModuleValue, pins sdkstep.PackageVersions, logf func(string, ...any)) sdkstep.PackageVersions {
others := fingerprint.OtherPackages(kept.Packages, repository)
versions, unpublished := fingerprint.HeldVersionsOf(others, held)
for p, v := range pins { // an accepted series' newest published version (acceptedSeries, DLV-I6)
@@ -110,19 +110,6 @@ func lineVersions(module, repository string, kept *meshcatalog.ModulesByModuleVa
unpublished = slices.DeleteFunc(unpublished, func(u string) bool { return u == p })
}
}
// A mesh Go package no module the indexer holds publishes is built at the commit the gate's source names for its
// repository, as an import of the same repository is; once a version is published, the version applies (design 47 G A-365).
for _, p := range slices.Clone(unpublished) {
if repo, _, ok := trunk.PackageRepository(p); ok {
if head := heads[repo]; len(head) == 40 {
if versions == nil {
versions = sdkstep.PackageVersions{}
}
versions[p] = head
unpublished = slices.DeleteFunc(unpublished, func(u string) bool { return u == p })
}
}
}
if len(unpublished) > 0 && logf != nil {
logf("%s: no module the indexer holds publishes %s, so its fingerprint takes no version of it", module, strings.Join(unpublished, ", "))
}
@@ -49,6 +49,8 @@ func (h HeldTakeIn) Event() meshdelivery.SourceMovedEvent {
// PendingAnswer is indexer_pending's answer (H-A-102): every branch's held take-ins, in the state held's form (since in RFC 3339).
type PendingAnswer struct {
Held []HeldTakeIn `json:"held"`
// Running are the take-ins that run, each with what it waits on (design 47 H2 §803, H-A-409).
Running []RunningTakeIn `json:"running,omitempty"`
}
// ErrHeldUnwritten says a source-moved that could not be taken in is not written into the state held either: its message
@@ -224,20 +226,25 @@ func ReadHeld(ctx context.Context, st Store) ([]HeldTakeIn, error) {
return out, nil
}
// HeldTools are the held take-in's tools (§744): indexer_pending reads the state held; indexer_take_in_pending takes a branch's
// HeldTools are the held take-in's tools (§744): indexer_pending reads the state held and the running take-ins' waiting-on in
// the state takeins (H2 §803, H-A-409); indexer_take_in_pending takes a branch's
// held source-moved again now and indexer_take_in_skip acknowledges it unwritten, each an ask in the state takeins the indexer
// acts on (H-A-97), the skip a hand act recorded through mesh-hand-acts before it is asked.
func HeldTools(held Store, ask func(key string, value []byte) (TakeInAsk, error), now func() time.Time, record func(what, why string) error) []stdio.Tool {
func HeldTools(held, takeIns Store, ask func(key string, value []byte) (TakeInAsk, error), now func() time.Time, record func(what, why string) error) []stdio.Tool {
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
return []stdio.Tool{
{Name: PendingTool,
Description: "Each watched branch's held take-in (design 47 H §744): the source revision of the gate's source-moved the indexer " +
"could not take in (the catalog store full, a read of the forge unanswered), why and since when, in order, each kept here once " +
"acknowledged and taken in again on the indexer's room and at its start. indexer_take_in_pending takes it again now, indexer_take_in_skip ends it unwritten.",
"acknowledged and taken in again on the indexer's room and at its start; and each running take-in that waits over a minute on another part, its waiting-on (part, verb, since). indexer_take_in_pending takes it again now, indexer_take_in_skip ends it unwritten.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) {
h, err := ReadHeld(context.Background(), held)
return PendingAnswer{Held: h}, err
if err != nil {
return PendingAnswer{Held: h}, err
}
r, err := ReadRunning(context.Background(), takeIns)
return PendingAnswer{Held: h, Running: r}, err
}},
{Name: TakeInPendingTool,
Description: "Take a watched branch's held source-moved in again now (design 47 H §744), as the indexer's room would: " +
@@ -26,7 +26,7 @@ func TestTheHeldAndPinToolsAskWhatTheIndexerReads(t *testing.T) {
}
record := func(what, _ string) error { recorded = append(recorded, what); return nil }
tools := map[string]stdio.Tool{}
for _, tl := range append(HeldTools(newMem(), ask, time.Now, record), PinsTools(newMem(), newMemObjects(0), ask, time.Now, record)...) {
for _, tl := range append(HeldTools(newMem(), nil, ask, time.Now, record), PinsTools(newMem(), newMemObjects(0), ask, time.Now, record)...) {
tools[tl.Name] = tl
}
for _, c := range []struct {
@@ -56,7 +56,7 @@ func TestTheHeldAndPinToolsAskWhatTheIndexerReads(t *testing.T) {
held := newMem()
ix := &Indexer{Held: held}
ix.hold(t.Context(), meshdelivery.SourceMovedEvent{Branch: "main", Source: 4, Call: "0123456789abcdef"}, "the catalog store is full")
got, err := HeldTools(held, ask, time.Now, record)[0].Run(map[string]any{})
got, err := HeldTools(held, nil, ask, time.Now, record)[0].Run(map[string]any{})
data, _ := json.Marshal(got)
var answer struct {
Held []struct {
@@ -11,6 +11,8 @@ import (
"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-sdk/go/process"
"mesh-delivery-indexer/internal/fingerprint"
)
const meshSDK = "git.novox.be/novox/mesh-sdk/go"
@@ -402,41 +404,44 @@ func anUnreadPackagesStateWritesNoFingerprintAndFingerprintsAreComputedAgain(t *
t.Fatalf("fingerprints again of a module not held answered stored: %+v", r)
}
})
t.Run("formOf builds a package no module publishes at the source's commit of its repository", func(t *testing.T) { // design 47 G A-365
head := strings.Repeat("c", 40)
t.Run("formOf takes a package by what is published, never by a commit of its repository", func(t *testing.T) { // design 47 H2 §802, H-A-349 DQ-8
contracts := "git.novox.be/novox/mesh-contracts/go/seats/findings"
held := map[string]meshcatalog.ModulesByModuleValue{"other": {Repository: "novox/mesh-sdk", Commit: strings.Repeat("d", 40), Path: "go"}}
// A build's imports of its own repository alone (design 47 H-A-157): they refine the go.mod's set and never empty it.
own := "git.novox.be/novox/mesh-catalog/modules/avahi/lib"
published := map[string]meshcatalog.PackagesByModuleValue{own: {Module: own, Repository: "novox/mesh-catalog", Commit: head, Requires: "r1",
published := map[string]meshcatalog.PackagesByModuleValue{own: {Module: own, Repository: "novox/mesh-catalog", Commit: strings.Repeat("c", 40), Requires: "r1",
Packages: []meshcatalog.PackagesByModuleValuePackagesItem{{Package: own, Digest: "d1"}}}}
for _, c := range []struct {
name string
heads map[string]string
held map[string]meshcatalog.ModulesByModuleValue
imports []string
want string
}{
{"the source names its repository", map[string]string{"novox/mesh-contracts": head}, held, nil, head},
{"the source names another repository only", map[string]string{"novox/mesh-sdk": head}, held, nil, ""},
{"a module the indexer holds publishes it", map[string]string{"novox/mesh-contracts": head},
map[string]meshcatalog.ModulesByModuleValue{"c": {Repository: "novox/mesh-contracts", Commit: strings.Repeat("e", 40), Path: "go/seats/findings"}}, nil, strings.Repeat("e", 40)},
{"a build's imports naming none of another repository keep the go.mod's", map[string]string{"novox/mesh-contracts": head}, held, []string{own}, head},
{"a package of another repository none publishes", held, nil, ""},
{"a module the indexer holds publishes it", map[string]meshcatalog.ModulesByModuleValue{"c": {Repository: "novox/mesh-contracts", Commit: strings.Repeat("e", 40), Path: "go/seats/findings"}}, nil, strings.Repeat("e", 40)},
{"a build's imports naming none of another repository, which none publishes", held, []string{own}, ""},
} {
kept := meshcatalog.ModulesByModuleValueInputs2{Tree: "t", Packages: []string{contracts}, Imports: c.imports}
f := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, c.held, published, nil, c.heads, nil)
f := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, c.held, published, nil, nil)
if got := f.versions[contracts]; got != c.want {
t.Errorf("%s: version of %s = %q, want %q", c.name, contracts, got, c.want)
}
if c.imports == nil {
continue
}
// The build that reported them stands, its held versions empty (a version line read from go.sum).
f = formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{Fp2: "src2:" + strings.Repeat("b", 64)}, c.held, published, nil, c.heads, nil)
if got := f.versions[contracts]; got != c.want || f.fp != "src2:"+strings.Repeat("b", 64) {
t.Errorf("%s, the build standing: version of %s = %q (fp %q), want %q", c.name, contracts, got, f.fp, c.want)
if c.want == "" && c.imports == nil && (f.fp != "" || !strings.HasPrefix(f.none, fingerprint.NoPackageVersion)) {
t.Errorf("%s: fingerprint %q (none %q), want none naming %s", c.name, f.fp, f.none, fingerprint.NoPackageVersion)
}
}
// A package of the module's own repository no module has published enters by its directory's tree (the tree input),
// so the module has a fingerprint, and the same tree gives the same one whatever commit names it.
sibling := "git.novox.be/novox/mesh-catalog/modules/sibling"
kept := meshcatalog.ModulesByModuleValueInputs2{Tree: "t\nderived modules/sibling o1", Packages: []string{sibling}}
f := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, nil, nil, nil, nil)
if f.fp == "" {
t.Fatalf("an unpublished package of the same repository: none %q, want a fingerprint by its directory's tree", f.none)
}
kept.Tree = "t\nderived modules/sibling o2"
if g := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, nil, nil, nil, nil); g.fp == "" || g.fp == f.fp {
t.Errorf("the sibling's directory changed: fingerprint %q, was %q; want a new one", g.fp, f.fp)
}
})
t.Run("formOf clears the import form when it writes the version line", func(t *testing.T) {
for _, c := range []struct {
@@ -444,7 +449,7 @@ func anUnreadPackagesStateWritesNoFingerprintAndFingerprintsAreComputedAgain(t *
imports []string
}{{"an import no package holds", []string{meshSDK + "/announce"}}, {"no import reported", nil}} {
kept := meshcatalog.ModulesByModuleValueInputs2{Tree: "t", Imports: c.imports, ImportForm: "src2:" + strings.Repeat("a", 64)}
f := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, nil, nil, nil, nil, nil)
f := formOf("avahi", "novox/mesh-catalog", &kept, nil, meshcatalog.ModulesByModuleValue{}, nil, nil, nil, nil)
if kept.ImportForm != "" {
t.Errorf("%s: kept import form %q after the version line %q", c.name, kept.ImportForm, f.fp)
}
@@ -160,7 +160,9 @@ func TestAContextIsNotPinned(t *testing.T) { // 1450 (the rule 1444 keeps: conte
// build-agent's manifest from mesh-controller at f2d7bc94 has an image artifact built from a context in another repository.
// Its claim of the retired seat node-build-agent is read as a claim of a build seat: the parser refuses a retired seat
// since R4g (mesh-sdk A9a), and the claim is not what this test is about.
// It names no class, which a seat-claiming manifest names since design 47 H2 §814: given here.
raw := strings.ReplaceAll(fixture(t, "controller-f2d7bc94-build-agent"), `"node-build-agent"`, `"node-build-go"`)
raw = strings.Replace(raw, `"claims"`, `"class": "core", "claims"`, 1)
in := inputsOf("build-agent", raw, "t", nil, noBases)
if in.Kept == nil || in.None2 != None2Context {
t.Errorf("kept %+v none2 %q, want none2 %q", in.Kept, in.None2, None2Context)
@@ -9,7 +9,8 @@ import (
)
// The manifests these tests carry are real files, copied unchanged into testdata: the module.json of modules of
// mesh-catalog at its main commit a67f01963f0d9ef0913a63720b89e573ca7a16ef (testdata/catalogue-a67f0196-<module>.module.json)
// mesh-catalog at its main commit a67f01963f0d9ef0913a63720b89e573ca7a16ef (testdata/catalogue-a67f0196-<module>.module.json),
// at 30a3e665e0070ae5b0ebfede985da5759af8affd for those that claim a seat (testdata/catalogue-30a3e665-<module>.module.json)
// and of build-agent from mesh-controller at its main commit f2d7bc94 (testdata/controller-f2d7bc94-build-agent.module.json).
func fixture(t *testing.T, name string) string {
t.Helper()
@@ -20,8 +21,14 @@ func fixture(t *testing.T, name string) string {
return string(b)
}
// catalogueManifest is a module's captured module.json of mesh-catalog: ca-trust's at 30a3e665, the group's catalogue head
// of design 47 H2 (it claims a seat, so it names its class, §810, §814; H-A-430 (3)), every other at a67f0196.
func catalogueManifest(t *testing.T, module string) string {
return fixture(t, "catalogue-a67f0196-"+module)
at := "a67f0196"
if module == "ca-trust" {
at = "30a3e665"
}
return fixture(t, "catalogue-"+at+"-"+module)
}
// avahiGoSum is the sha256 of modules/avahi/go.sum in mesh-catalog at a67f0196 (sha256sum of that file).
@@ -227,7 +227,7 @@ func (ix *Indexer) namedObjects(ctx context.Context, f whole) (map[string]map[st
if len(need) == 0 || ix.Named == nil {
return objects, nil
}
got, err := ix.Named(ctx, f.Repository, f.Merge, need)
got, err := waited(ctx, "git", "trees", func() (map[string]map[string]string, error) { return ix.Named(ctx, f.Repository, f.Merge, need) })
if err != nil {
words := map[string]string{}
for dir := range need {
@@ -320,7 +320,7 @@ func (ix *Indexer) reconcile(ctx context.Context) error {
if len(mine) == 0 {
continue
}
dirs, err := ix.Trunk(ctx, repository, heads[repository])
dirs, err := waited(ctx, "git", "trees", func() ([]string, error) { return ix.Trunk(ctx, repository, heads[repository]) })
if err != nil {
ix.logf("%s at %s: the modules of the trunk cannot be read, so none is dropped: %v", repository, heads[repository], err)
continue
@@ -346,7 +346,7 @@ func (ix *Indexer) reconcile(ctx context.Context) error {
if m.Commit == "" || ix.Contains == nil {
return true
}
in, err := ix.Contains(ctx, repository, m.Commit, head)
in, err := waited(ctx, "git", "contains", func() (bool, error) { return ix.Contains(ctx, repository, m.Commit, head) })
if err != nil {
ix.logf("%s: whether %s is in %s cannot be read, so the module at %s is kept: %v", repository, m.Commit, head, m.Path, err)
return true
@@ -421,7 +421,7 @@ func (ix *Indexer) goModOf(ctx context.Context, f whole, dir string) ([]byte, bo
if ix.GoMod == nil {
return nil, false
}
raw, err := ix.GoMod(ctx, f.Repository, f.Merge, dir)
raw, err := waited(ctx, "git", "file", func() ([]byte, error) { return ix.GoMod(ctx, f.Repository, f.Merge, dir) })
if err != nil {
ix.logf("%s at %s: the go.mod of %q cannot be read, so its module keeps the packages it held: %v", f.Repository, f.Merge, dir, err)
return nil, false
@@ -444,7 +444,7 @@ func (ix *Indexer) requirementsOf(ctx context.Context, f whole, dir string, cur
}
}
}
raw, err := ix.GoSum(ctx, f.Repository, f.Merge, dir)
raw, err := waited(ctx, "git", "file", func() ([]byte, error) { return ix.GoSum(ctx, f.Repository, f.Merge, dir) })
if err != nil {
ix.logf("%s at %s: the go.sum of %q cannot be read, so what it requires is not kept: %v", f.Repository, f.Merge, dir, err)
return
@@ -26,7 +26,7 @@ func (ix *Indexer) heldByAnotherTrunk(ctx context.Context, module, repository st
if head == "" || trunk.SameRepository(other, repository) {
continue
}
dirs, err := ix.Trunk(ctx, other, head)
dirs, err := waited(ctx, "git", "trees", func() ([]string, error) { return ix.Trunk(ctx, other, head) })
if err != nil {
ix.logf("%s at %s: the modules of the trunk cannot be read, so %s is not looked for there: %v", other, head, module, err)
continue
@@ -36,7 +36,7 @@ func (ix *Indexer) heldByAnotherTrunk(ctx context.Context, module, repository st
if nameOfDirectory(dir) != module {
continue
}
read, err := ix.Read(ctx, other, head, dir)
read, err := waited(ctx, "git", "trees", func() (RepoRead, error) { return ix.Read(ctx, other, head, dir) })
if err != nil {
ix.logf("%s at %s: %q cannot be read, so %s is not handed over from it: %v", other, head, dir, module, err)
continue
@@ -67,7 +67,7 @@ func (ix *Indexer) older(ctx context.Context, repository, commit, later string)
if ix.Contains == nil || commit == "" || later == "" || commit == later {
return false, nil
}
in, err := ix.Contains(ctx, repository, commit, later)
in, err := waited(ctx, "git", "contains", func() (bool, error) { return ix.Contains(ctx, repository, commit, later) })
if notFound(err) {
ix.logf("%s: the forge does not have %.12s or %.12s (a rewritten history?), so %.12s is not known to be older and is written: %v", repository, commit, later, commit, err)
return false, nil
@@ -36,7 +36,7 @@ func (t *goModTree) goMod(dir string) []byte {
var raw []byte
if t.ix.GoMod != nil {
var err error
if raw, err = t.ix.GoMod(t.ctx, t.f.Repository, t.f.Merge, dir); err != nil {
if raw, err = waited(t.ctx, "git", "file", func() ([]byte, error) { return t.ix.GoMod(t.ctx, t.f.Repository, t.f.Merge, dir) }); err != nil {
t.ix.logf("%s at %s: the go.mod of %q cannot be read, so no module of the tree is found there: %v", t.f.Repository, t.f.Merge, dir, err)
raw = nil
}
@@ -167,7 +167,9 @@ func (ix *Indexer) derivedTree(ctx context.Context, f whole, t *goModTree, m cat
if ix.Named == nil {
return "", "the forge cannot be asked the git objects of the derived directories " + strings.Join(dirs, ", ")
}
got, err := ix.Named(ctx, f.Repository, f.Merge, map[string][]string{"": dirs})
got, err := waited(ctx, "git", "trees", func() (map[string]map[string]string, error) {
return ix.Named(ctx, f.Repository, f.Merge, map[string][]string{"": dirs})
})
if err != nil {
return "", fmt.Sprintf("the git objects of the derived directories %s: %v", strings.Join(dirs, ", "), err)
}
@@ -174,7 +174,7 @@ func (ix *Indexer) packagesIn(ctx context.Context, repository, commit string, mo
if len(ask) == 0 {
return nil
}
got, err := ix.Files(ctx, repository, commit, ask)
got, err := waited(ctx, "git", "trees", func() (map[string]map[string]string, error) { return ix.Files(ctx, repository, commit, ask) })
if err != nil {
return fmt.Errorf("the forge's listing of %s at %s (%s): %w", repository, commit, strings.Join(ask, ", "), err)
}
@@ -231,7 +231,7 @@ func (ix *Indexer) packagesIn(ctx context.Context, repository, commit string, mo
if ix.Trunk == nil {
return nil, nil, whole
}
if _, err := ix.Trunk(ctx, repository, commit); err != nil {
if _, err := waited(ctx, "git", "trees", func() ([]string, error) { return ix.Trunk(ctx, repository, commit) }); err != nil {
return nil, nil, fmt.Errorf("%w (and the commit's trees: %v)", whole, err)
}
ix.logf("%s at %s: the commit holds a tree, so every directory asked (%s) is gone", repository, commit, strings.Join(dirs, ", "))
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"time"
@@ -115,18 +116,26 @@ func TestARepositorysPackagesAreThoseInTheMergesTree(t *testing.T) {
})
for _, row := range []struct {
name string
dry bool
branch string
name string
dry, scratch bool
branch string
}{
{"a branch's take-in keeps the key: only the trunk's merge says a directory is gone", false, "feat/x"},
{"a dry run keeps the key: it shares the live packages state", true, TrunkBranch},
{"a branch's take-in keeps the key: only the trunk's merge says a directory is gone", false, false, "feat/x"},
{"a dry run keeps the key: its packages are a working copy over the live state", true, false, TrunkBranch},
// Design 47 H2 §804: over the state dry-runs, a dry run's packages are kept there alone, under its branch and call,
// read by indexer_dry_runs and gone at its end; the live packages state is left as it was.
{"a dry run over the state dry-runs writes its packages there alone and drops them at its end", true, true, TrunkBranch},
} {
t.Run(row.name, func(t *testing.T) {
s := newSetup(t, live, gone)
ix := s.ix
if row.scratch {
s.ix.DryRuns = newMem()
}
before := s.ix.publishedAll(ctx)
ix, d := s.ix, (*dryRun)(nil)
if row.dry {
ix = s.ix.dry().ix
d = s.ix.dry("beta", "t")
ix = d.ix
}
if err := ix.publish(ctx, catalogueRepo, merge, reaching(live), false, row.branch); err != nil {
t.Fatal(err)
@@ -134,6 +143,24 @@ func TestARepositorysPackagesAreThoseInTheMergesTree(t *testing.T) {
if _, kept := s.ix.publishedAll(ctx)[gone]; !kept {
t.Errorf("the kept key of %s was dropped", gone)
}
if !row.scratch {
return
}
if got := s.ix.publishedAll(ctx); !reflect.DeepEqual(got, before) {
t.Errorf("the live packages state is %+v after the dry run, want %+v as before", got, before)
}
if mine := ix.publishedAll(ctx); mine[live].Commit != merge {
t.Errorf("the dry run reads %s at %q, want its own write at %s", live, mine[live].Commit, merge)
}
read, err := DryRunsTools(s.ix.DryRuns)[0].Run(map[string]any{})
a, _ := read.(DryRunsAnswer)
if err != nil || a.Total == 0 || len(a.Keys) != a.Total || !strings.HasPrefix(a.Keys[0].Key, DryRunPrefix("beta", "t")+PackagesState+".") {
t.Errorf("indexer_dry_runs = %+v (%v), want the dry run's packages under beta.t.packages.", read, err)
}
d.end(ctx)
if a, err := ReadDryRuns(ctx, s.ix.DryRuns); err != nil || a.Total != 0 {
t.Errorf("dry-runs holds %+v (%v) after the dry run's end, want none", a, err)
}
})
}
@@ -178,3 +178,12 @@ func contentsOfPublished(p meshcatalog.PackagesByModuleValue) *meshcatalog.Packa
}
return c
}
// publishedOfNumbered is a series' numbered version's contents as the value of a per-module packages key (the same fields).
func publishedOfNumbered(c meshcatalog.PackagesByPackageSeriesValueNumberedContents) meshcatalog.PackagesByModuleValue {
p := meshcatalog.PackagesByModuleValue{At: c.At, Commit: c.Commit, Dir: c.Dir, Module: c.Module, Repository: c.Repository, Requires: c.Requires, V: c.V}
for _, d := range c.Packages {
p.Packages = append(p.Packages, meshcatalog.PackagesByModuleValuePackagesItem{Package: d.Package, Digest: d.Digest})
}
return p
}
@@ -83,7 +83,14 @@ func (ix *Indexer) HeardPins(ctx context.Context, started *runner.PipelineStarte
}
switch {
case started != nil && started.Revision > 0 && started.Pipeline != "":
return ix.pin(ctx, PinKey(started.Branch, started.Revision), PipelineRecord(started.Pipeline))
if err := ix.pin(ctx, PinKey(started.Branch, started.Revision), PipelineRecord(started.Pipeline)); err != nil {
return err
}
// The reservations of the pipeline's revision settle at its start, if they gather (design 47 H2 §805, H-A-424 (1)).
if err := ix.Settle(ctx, BranchObject(started.Branch, started.Revision)); err != nil {
ix.logf("versions: the reservations of %s are not re-pinned at its pipeline-started: %v", BranchObject(started.Branch, started.Revision), err)
}
return nil
case ended != nil && ended.Revision > 0 && ended.Pipeline != "":
// A passed pipeline's release pins the revision its movers' entries live in, before the pipeline's own pin is freed,
// one record per mover that released a version in it (H-A-168, H-A-170, H-A-173); a mover that released none, and a run
@@ -98,6 +105,12 @@ func (ix *Indexer) HeardPins(ctx context.Context, started *runner.PipelineStarte
}
}
}
// A pipeline that did not pass withdraws the reservations its revision holds (design 47 H2 §805, H-A-418 (1)).
if ended.Outcome != runner.PipelineEndedOutcomePassed {
if err := ix.Withdraw(ctx, ended.Branch, ended.Revision); err != nil {
return fmt.Errorf("the reservations of %s are not withdrawn: %w", BranchObject(ended.Branch, ended.Revision), err)
}
}
record := PipelineRecord(ended.Pipeline)
if err := ix.unpin(ctx, PinKey(ended.Branch, ended.Revision), record); err != nil {
return err
@@ -7,10 +7,10 @@ import (
// Issue 1751: a manifest whose config value falls back to a predefined key (novox/hq ADR 0348) is read by the indexer, so
// the module gets its new-form inputs. The manifests are claude-code's, dunst's and xterm's module.json from mesh-catalog
// at 835bf22b.
// at 30a3e665.
func TestAManifestFallingBackToAPredefinedKeyIsRead(t *testing.T) { // 1751
for _, module := range []string{"claude-code", "dunst", "xterm"} {
raw := fixture(t, "catalogue-835bf22b-"+module)
raw := fixture(t, "catalogue-30a3e665-"+module)
if !strings.Contains(raw, `"predefined"`) {
t.Fatalf("%s: the fixture names no predefined key", module)
}
@@ -20,7 +20,7 @@ func TestAManifestFallingBackToAPredefinedKeyIsRead(t *testing.T) { // 1751
}
}
// A predefined key of another type than its value is still refused: the read judges what it can.
raw := strings.Replace(fixture(t, "catalogue-835bf22b-xterm"), `"predefined": "font-size"`, `"predefined": "font-size", "trusted": "yes"`, 1)
raw := strings.Replace(fixture(t, "catalogue-30a3e665-xterm"), `"predefined": "font-size"`, `"predefined": "font-size", "trusted": "yes"`, 1)
if in := inputsOf("xterm", raw, "newtree", nil, func(string) (string, string) { return "", "none" }); in.Kept != nil {
t.Errorf("inputs = %+v, want a manifest the catalogue refuses still refused", in)
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"path"
"slices"
"sort"
"strings"
@@ -16,7 +17,10 @@ import (
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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
)
// A module's registration, and the trusted change of one (design 47 G §2 to §4, §10, §342, §343, §667): the indexer keeps each
@@ -104,8 +108,68 @@ func ProposalKey(verb, module, branch string) string {
return k
}
// RegistrationKey is a module's key in registrations.
func RegistrationKey(module string) string { return keys.EscapeName(module) }
// RegistrationKey is a registration's key in registrations: a module's name escaped as a key's name is, and a source-only
// registration's name, its key source.<owner>.<name>, as it stands (design 47 H2 §815; H-A-349 DQ-9).
func RegistrationKey(module string) string {
if isSourceMember(module) {
return module
}
return keys.EscapeName(module)
}
// RegistrationName is the name a registration is kept, asked and said under: its module, or for a source-only registration
// (a check and no module) its key source.<owner>.<name> from its origin (design 47 H2 §815; H-A-438). Empty when a
// source-only registration's origin is not <owner>/<name>.
func RegistrationName(reg meshcatalog.Registration) string {
if reg.Check == nil || reg.Module != "" {
return reg.Module
}
owner, name, ok := strings.Cut(trunk.RepositoryName(reg.Origin), "/")
if !ok || owner == "" || name == "" || strings.ContainsAny(owner+name, "./") {
return ""
}
return meshcatalog.RegistrationsBySourceOwnerNameKey(owner, name)
}
// sourceForm refuses a source-only registration that is not of its form (design 47 H2 §815): it names no module and no
// path, one branch at most (none takes the default branch), and a check of a build seat and a step kind the seat names.
func sourceForm(reg meshcatalog.Registration) error {
if reg.Module != "" || reg.Path != "" {
return errors.New("a source-only registration (check) names no module and no path: a module registers with its manifest's path instead")
}
if len(reg.Branches) > 1 {
return fmt.Errorf("a source-only registration watches one branch, not %d", len(reg.Branches))
}
if !slices.Contains([]string{meshcatalog.SourceCheckSeatNodeBuildGo, meshcatalog.SourceCheckSeatNodeBuildNode, meshcatalog.SourceCheckSeatNodeBuildImage}, reg.Check.Seat) {
return fmt.Errorf("the check's seat %q is no build seat (node-build-go, node-build-node or node-build-image)", reg.Check.Seat)
}
if !slices.Contains([]string{meshcatalog.SourceCheckStepLint, meshcatalog.SourceCheckStepUnit, meshcatalog.SourceCheckStepIntegration}, reg.Check.Step) {
return fmt.Errorf("the check's step %q is no step kind (lint, unit or integration)", reg.Check.Step)
}
if RegistrationName(reg) == "" {
return fmt.Errorf("a source-only registration's origin is its repository as <owner>/<name>, not %q", reg.Origin)
}
return nil
}
// holdsManifest is the manifest a repository holds at a commit, read through the seat git's trees (design 47 H2 §815;
// H-A-450): a module.json at the tree's root or under modules/; empty when it holds none.
func (r *Registry) holdsManifest(repository, commit string) (string, error) {
if r.ModuleDirs == nil {
return "", errors.New("the trees of a repository are not asked of the seat git, so no source-only registration is judged")
}
dirs, err := r.ModuleDirs(repository, commit)
if err != nil {
return "", fmt.Errorf("the seat git does not answer the trees of %s at %.12s: %w", repository, commit, err)
}
slices.Sort(dirs)
for _, d := range dirs {
if d == "" || d == "." || strings.HasPrefix(d, "modules/") {
return path.Join(d, ModuleManifest), nil
}
}
return "", nil
}
// Registry is the registrations and the trusted changes of them. Its parts are the indexer's: the two states, the history
// stream, the event, the seat git's branch, the seat operator-channel's ask.
@@ -125,6 +189,9 @@ type Registry struct {
Pruned func(ctx context.Context, module string, watched []string) error
// Branch reads a branch through the seat git; an empty branch asks the repository's default branch.
Branch func(repository, branch string) (gitseat.BranchAnswer, error)
// ModuleDirs reads the directories of a commit that hold a module.json through the seat git's trees, the root as "": a
// source-only registration whose repository holds a manifest is refused (design 47 H2 §815; H-A-450).
ModuleDirs func(repository, commit string) ([]string, error)
// Placement reads a module's placements through the seat mesh-module-assigner's verb placement: one per watched branch a row
// of its assignments names, with the nodes that run the module from it (design 47 G §704, A-62).
Placement func(module string) ([]mma.ModulePlacement, error)
@@ -169,15 +236,34 @@ func (r *Registry) Registration(ctx context.Context, module string) (meshcatalog
return reg, true, nil
}
// Registrations is the verb registrations (§4): every registration, or one module's, with its history.
// RegistrationsTool is the indexer's tool of the registrations (design 47 H2 §806): the verb registrations' answer, by hand.
const RegistrationsTool = "indexer_registrations"
// StatePager reads a state a page at a time, in the order the bus wrote it, after an opaque cursor (mesh-sdk
// KeptState.Page, design 47 H2 §779).
type StatePager interface {
Page(cursor string, maxBytes int, budget time.Duration) (stdio.StatePage, error)
}
// keyCursor is the cursor of a store read by its keys (a store that pages none): after this key, in key order.
const keyCursor = "key:"
// RegistrationsAnswer is the verb registrations and the tool indexer_registrations (§4; design 47 H2 §806, §811): every
// registration, or one module's with its history, filtered by module and repository while it reads, at most views.PageBytes
// a page, capped with the cursor next when more is held; a store that pages (StatePager) is read from the bus's cursor,
// any other by its keys in order. total is how many the filters hold, said when one page holds the whole read.
func (r *Registry) RegistrationsAnswer(ctx context.Context, in meshcatalog.RegistrationsInput) (meshcatalog.RegistrationsAnswer, error) {
out := meshcatalog.RegistrationsAnswer{Registrations: []meshcatalog.Registration{}}
repository := trunk.RepositoryName(strings.TrimSpace(in.Repository))
keep := func(reg meshcatalog.Registration) bool {
return (in.Module == "" || RegistrationName(reg) == in.Module) && (repository == "" || trunk.SameRepository(reg.Origin, repository))
}
if in.Module != "" {
reg, found, err := r.Registration(ctx, in.Module)
if err != nil {
return out, err
}
if found {
if found && keep(reg) {
out.Registrations = append(out.Registrations, reg)
}
if in.History && r.HistoryOf != nil {
@@ -185,22 +271,53 @@ func (r *Registry) RegistrationsAnswer(ctx context.Context, in meshcatalog.Regis
return out, fmt.Errorf("the history of %s cannot be read: %w", in.Module, err)
}
}
out.Total = int64(len(out.Registrations))
return out, nil
}
all, err := r.Registrations.Keys(ctx)
if err != nil {
return out, err
match := func(value []byte) (meshcatalog.Registration, bool) {
var reg meshcatalog.Registration
return reg, json.Unmarshal(value, &reg) == nil && keep(reg)
}
slices.Sort(all)
for _, k := range all {
v, _, found, err := r.Registrations.Get(ctx, k)
if p, ok := r.Registrations.(StatePager); ok {
page, err := p.Page(in.Next, views.PageBytes, views.PageBudget)
if err != nil {
return out, err
}
var reg meshcatalog.Registration
if found && json.Unmarshal(v, &reg) == nil {
out.Registrations = append(out.Registrations, reg)
// A page holds at most views.PageBytes, so what the filters keep of it always fits one answer.
for _, e := range page.Entries {
if reg, ok := match(e.Value); ok {
out.Registrations = append(out.Registrations, reg)
}
}
out.Next, out.Capped = page.Next, page.Next != ""
} else {
all, err := r.Registrations.Keys(ctx)
if err != nil {
return out, err
}
slices.Sort(all)
after, size := strings.TrimPrefix(in.Next, keyCursor), 0
for _, k := range all {
if in.Next != "" && k <= after {
continue
}
v, _, found, err := r.Registrations.Get(ctx, k)
if err != nil {
return out, err
}
reg, ok := match(v)
if !found || !ok {
continue
}
if size += len(k) + len(v); size > views.PageBytes && len(out.Registrations) > 0 {
out.Capped, out.Next = true, keyCursor+after
return out, nil
}
out.Registrations, after = append(out.Registrations, reg), k
}
}
if in.Next == "" && !out.Capped {
out.Total = int64(len(out.Registrations))
}
return out, nil
}
@@ -282,30 +399,37 @@ func compose(verb string, cur meshcatalog.Registration, found bool, change json.
}
next := in.Registration
next.Version, next.Warrant, next.By, next.At = 0, "", "", nil
name := RegistrationName(next)
var lines []string
if !found {
lines = append(lines, fmt.Sprintf("%s: registered from %s, watching %s", next.Module, next.Origin, strings.Join(next.Branches, ", ")))
lines = append(lines, stepLines(next.Module+" ", meshcatalog.StepStatuses{}, next.Policy.Steps)...)
lines = append(lines, fmt.Sprintf("%s: registered from %s, watching %s", name, next.Origin, strings.Join(next.Branches, ", ")))
if next.Check != nil {
lines = append(lines, fmt.Sprintf("%s: checked by the step %s on the seat %s", name, next.Check.Step, next.Check.Seat))
}
lines = append(lines, stepLines(name+" ", meshcatalog.StepStatuses{}, next.Policy.Steps)...)
return next, lines, nil
}
if cur.Origin != next.Origin {
lines = append(lines, fmt.Sprintf("%s: origin %s -> %s", next.Module, cur.Origin, next.Origin))
lines = append(lines, fmt.Sprintf("%s: origin %s -> %s", name, cur.Origin, next.Origin))
}
if cur.Path != next.Path {
lines = append(lines, fmt.Sprintf("%s: manifest path %s -> %s", next.Module, cur.Path, next.Path))
lines = append(lines, fmt.Sprintf("%s: manifest path %s -> %s", name, cur.Path, next.Path))
}
if was, now := checkWords(cur.Check), checkWords(next.Check); was != now {
lines = append(lines, fmt.Sprintf("%s: check %s -> %s", name, was, now))
}
for _, b := range next.Branches {
if !slices.Contains(cur.Branches, b) {
lines = append(lines, fmt.Sprintf("%s: watches %s", next.Module, b))
lines = append(lines, fmt.Sprintf("%s: watches %s", name, b))
}
}
for _, b := range cur.Branches {
if !slices.Contains(next.Branches, b) {
lines = append(lines, fmt.Sprintf("%s: stops watching %s", next.Module, b))
lines = append(lines, fmt.Sprintf("%s: stops watching %s", name, b))
}
}
lines = append(lines, stepLines(next.Module+" ", cur.Policy.Steps, next.Policy.Steps)...)
lines = append(lines, artifactLines(next.Module, cur.Policy, next.Policy)...)
lines = append(lines, stepLines(name+" ", cur.Policy.Steps, next.Policy.Steps)...)
lines = append(lines, artifactLines(name, cur.Policy, next.Policy)...)
return next, lines, nil
case verbPolicy:
var in meshcatalog.PolicyInput
@@ -349,6 +473,14 @@ func compose(verb string, cur meshcatalog.Registration, found bool, change json.
return cur, nil, fmt.Errorf("%q is no change of a registration", verb)
}
// checkWords says a source-only registration's check as a line names it: none for a module's.
func checkWords(c *meshcatalog.SourceCheck) string {
if c == nil {
return "none"
}
return c.Step + " on " + c.Seat
}
func artifactLines(module string, old, next meshcatalog.Policy) []string {
names := map[string]bool{}
for k := range old.Artifacts {
@@ -380,7 +512,12 @@ func (r *Registry) Propose(ctx context.Context, verb, caller string, change json
if err := json.Unmarshal(change, &in); err != nil {
return meshcatalog.RegistrationAsked{}, fmt.Errorf("register takes a registration: %w", err)
}
module, why = in.Registration.Module, in.Why
if in.Registration.Check != nil {
if err := sourceForm(in.Registration); err != nil {
return meshcatalog.RegistrationAsked{}, err
}
}
module, why = RegistrationName(in.Registration), in.Why
case verbPolicy:
var in meshcatalog.PolicyInput
if err := json.Unmarshal(change, &in); err != nil {
@@ -411,6 +548,10 @@ func (r *Registry) Propose(ctx context.Context, verb, caller string, change json
if verb != verbRegister && !found {
return refused(module, meshcatalog.RegistrationAskedRefusedUnknownModule, module+" is not registered: register it first"), nil
}
// A source-only registration watches one branch (design 47 H2 §815).
if verb == verbWatch && cur.Check != nil && !slices.Contains(cur.Branches, branch) && len(cur.Branches) > 0 {
return meshcatalog.RegistrationAsked{}, fmt.Errorf("%s is a source-only registration, which watches one branch (%s)", module, strings.Join(cur.Branches, ", "))
}
// An unwatch of a branch a placement names is refused, naming the placement (§704, A-62).
if verb == verbUnwatch {
if r.Placement == nil {
@@ -431,9 +572,10 @@ func (r *Registry) Propose(ctx context.Context, verb, caller string, change json
if verb == verbRegister {
var in meshcatalog.RegisterInput
_ = json.Unmarshal(change, &in)
if in.Registration.Origin == "" || in.Registration.Path == "" {
if in.Registration.Origin == "" || (in.Registration.Path == "" && in.Registration.Check == nil) {
return meshcatalog.RegistrationAsked{}, errors.New("name the registration's origin and the path of its manifest")
}
head := ""
if len(in.Registration.Branches) == 0 {
a, err := r.Branch(in.Registration.Origin, "")
if err != nil {
@@ -442,11 +584,34 @@ func (r *Registry) Propose(ctx context.Context, verb, caller string, change json
if a.Error != "" || a.Branch == "" {
return meshcatalog.RegistrationAsked{}, fmt.Errorf("the default branch of %s is not read: %s", in.Registration.Origin, a.Error)
}
in.Registration.Branches = []string{a.Branch}
in.Registration.Branches, head = []string{a.Branch}, a.Head
if change, err = json.Marshal(in); err != nil {
return meshcatalog.RegistrationAsked{}, err
}
}
// A source-only registration of a repository that holds a manifest is refused: its module registers instead
// (design 47 H2 §815; H-A-450), judged from the tree at the branch's head through the seat git.
if in.Registration.Check != nil {
branch := in.Registration.Branches[0]
if head == "" {
a, err := r.Branch(in.Registration.Origin, branch)
if err != nil {
return meshcatalog.RegistrationAsked{}, fmt.Errorf("the seat git does not answer the branch %s of %s: %w", branch, in.Registration.Origin, err)
}
if a.Error != "" || a.Head == "" {
return meshcatalog.RegistrationAsked{}, fmt.Errorf("the head of the branch %s of %s is not read: %s", branch, in.Registration.Origin, a.Error)
}
head = a.Head
}
held, err := r.holdsManifest(in.Registration.Origin, head)
if err != nil {
return meshcatalog.RegistrationAsked{}, err
}
if held != "" {
return refused(module, meshcatalog.RegistrationAskedRefusedHoldsManifest,
fmt.Sprintf("%s holds %s at %.12s of %s: a repository with a manifest registers its module, not a source alone", in.Registration.Origin, held, head, branch)), nil
}
}
}
steps := []meshcatalog.StepStatuses{}
switch verb {
@@ -784,14 +949,16 @@ func (r *Registry) apply(ctx context.Context, key string, p Proposal, w oc.Warra
func (r *Registry) write(ctx context.Context, key string, p Proposal, next meshcatalog.Registration, w oc.Warrant) error {
at := r.now()
next.V, next.Version, next.Warrant, next.By, next.At = 1, p.Was+1, w.Ask, p.Caller, &at
// A source-only registration is kept, said and pruned under its key source.<owner>.<name> (§815; H-A-438).
name := RegistrationName(next)
began := time.Now()
step := func(what string) {
r.logf("registration %s version %d: %s (%s since its start)", next.Module, next.Version, what, time.Since(began).Round(time.Millisecond))
r.logf("registration %s version %d: %s (%s since its start)", name, next.Version, what, time.Since(began).Round(time.Millisecond))
}
step("writing")
if r.History != nil {
if err := r.History(ctx, next); err != nil {
return fmt.Errorf("the version %d of %s is not kept on %s, so it is not written: %w", next.Version, next.Module, RegistrationHistoryStream, err)
return fmt.Errorf("the version %d of %s is not kept on %s, so it is not written: %w", next.Version, name, RegistrationHistoryStream, err)
}
step("kept on " + RegistrationHistoryStream)
}
@@ -799,10 +966,10 @@ func (r *Registry) write(ctx context.Context, key string, p Proposal, next meshc
if err != nil {
return err
}
err = write(ctx, r.Registrations, RegistrationKey(next.Module), func(old []byte, found bool) ([]byte, bool, error) {
err = write(ctx, r.Registrations, RegistrationKey(name), func(old []byte, found bool) ([]byte, bool, error) {
var cur meshcatalog.Registration
if found && json.Unmarshal(old, &cur) == nil && cur.Version != p.Was {
return nil, false, fmt.Errorf("the registration of %s is at version %d, not %d", next.Module, cur.Version, p.Was)
return nil, false, fmt.Errorf("the registration of %s is at version %d, not %d", name, cur.Version, p.Was)
}
return data, false, nil
})
@@ -812,21 +979,21 @@ func (r *Registry) write(ctx context.Context, key string, p Proposal, next meshc
step("written")
if r.Say != nil {
defer step("registration-changed said")
if err := r.Say(ctx, meshcatalog.RegistrationChangedEvent{V: 1, Module: next.Module, Version: next.Version, Moved: p.Lines, By: p.Caller, Warrant: w.Ask, At: &at}); err != nil {
r.logf("registration-changed of %s %d is not said: %v", next.Module, next.Version, err)
if err := r.Say(ctx, meshcatalog.RegistrationChangedEvent{V: 1, Module: name, Version: next.Version, Moved: p.Lines, By: p.Caller, Warrant: w.Ask, At: &at}); err != nil {
r.logf("registration-changed of %s %d is not said: %v", name, next.Version, err)
}
}
// A first registration watched no branch before, so no branch's builds are to be pruned.
if r.Pruned != nil && p.Was > 0 {
defer step("builds of unwatched branches pruned")
if err := r.Pruned(ctx, next.Module, next.Branches); err != nil {
r.logf("the builds of %s on the branches it no longer watches are not pruned: %v", next.Module, err)
if err := r.Pruned(ctx, name, next.Branches); err != nil {
r.logf("the builds of %s on the branches it no longer watches are not pruned: %v", name, err)
}
}
if key == "" {
return nil // a write of the seed's: no proposal key of its own to end
}
return r.endKey(ctx, key, p, ProposalApplied, fmt.Sprintf("applied as version %d of %s on %s", next.Version, next.Module, occ.Says(w)))
return r.endKey(ctx, key, p, ProposalApplied, fmt.Sprintf("applied as version %d of %s on %s", next.Version, name, occ.Says(w)))
}
// Restart reads each open key at the indexer's start (§667 A restart): a decided ask is applied or ended, an open one waited on,
@@ -189,6 +189,71 @@ func TestRegistrationsAreWrittenOnTheirWarrantOnly(t *testing.T) {
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)
}
})
}
func mustJSON(v any) json.RawMessage { b, _ := json.Marshal(v); return b }
@@ -43,27 +43,37 @@ func RegistrationTools(registrations, proposals Store, ask func(key string, valu
// in, never queued behind a running take-in (design 47 G A-370). Only a module's history is read from the stream the
// indexer keeps, so that is still asked of the indexer.
viaIndexer := act(ActRegistrations, true)
read := func(args map[string]any) (any, error) {
var in meshcatalog.RegistrationsInput
clean := map[string]any{}
for k, v := range args {
if k != "caller" && !strings.HasPrefix(k, "_") {
clean[k] = v
}
}
raw, err := json.Marshal(clean)
if err == nil {
err = json.Unmarshal(raw, &in)
}
if err != nil {
return nil, err
}
if in.History {
return viaIndexer(args)
}
return (&Registry{Registrations: registrations}).RegistrationsAnswer(context.Background(), in)
}
return []stdio.Tool{
{Name: meshcatalog.Seat + "." + meshcatalog.VerbRegistrations, Run: func(args map[string]any) (any, error) {
var in meshcatalog.RegistrationsInput
clean := map[string]any{}
for k, v := range args {
if k != "caller" && !strings.HasPrefix(k, "_") {
clean[k] = v
}
}
raw, err := json.Marshal(clean)
if err == nil {
err = json.Unmarshal(raw, &in)
}
if err != nil {
return nil, err
}
if in.History {
return viaIndexer(args)
}
return (&Registry{Registrations: registrations}).RegistrationsAnswer(context.Background(), in)
}},
{Name: meshcatalog.Seat + "." + meshcatalog.VerbRegistrations, Run: read},
{Name: RegistrationsTool, Description: "The registrations (design 47 H2 §806), as the seat mesh-catalog's verb registrations answers them: " +
"every module's and every source-only one, filtered by module or repository (owner/name) while it reads, at most 768 KB a page " +
"(capped), the rest read from the cursor next; one module's with every version (history).",
Input: map[string]any{"type": "object", "properties": map[string]any{
"module": map[string]any{"type": "string", "description": "one module; absent, every registration"},
"repository": map[string]any{"type": "string", "description": "only the registrations of this repository, owner/name"},
"history": map[string]any{"type": "boolean", "description": "with every version of the one module"},
"next": map[string]any{"type": "string", "description": "the cursor the previous page answered"}}},
Run: read},
{Name: meshcatalog.Seat + "." + meshcatalog.VerbRegister, Run: act(verbRegister, true)},
{Name: meshcatalog.Seat + "." + meshcatalog.VerbPolicy, Run: act(verbPolicy, true)},
{Name: meshcatalog.Seat + "." + meshcatalog.VerbWatch, Run: act(verbWatch, true)},
@@ -4,12 +4,28 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// pagedStore is a store whose Page answers the pages given, by cursor, and records the cursors asked.
type pagedStore struct {
Store
pages map[string]stdio.StatePage
asked []string
}
func (p *pagedStore) Page(cursor string, _ int, _ time.Duration) (stdio.StatePage, error) {
p.asked = append(p.asked, cursor)
return p.pages[cursor], nil
}
// Design 47 G A-370: the verb registrations answers from the state at once; it never asks the indexer (whose take-in may be
// running), but for a module's history, which the indexer reads from its stream.
func TestTheRegistrationsVerbIsAnsweredFromItsStateNotAskedOfTheIndexer(t *testing.T) {
@@ -41,4 +57,72 @@ func TestTheRegistrationsVerbIsAnsweredFromItsStateNotAskedOfTheIndexer(t *testi
if _, err := tool(map[string]any{"module": "a", "history": true}); err == nil || asked != 1 {
t.Errorf("a history is asked of the indexer: err %v, asked %d", err, asked)
}
// Design 47 H2 §806: indexer_registrations answers as the verb, filtered by module and repository while it reads, at most
// 768 KB a page, capped with the cursor next; a state that pages is read from the bus's cursor.
t.Run("filtered and paged", func(t *testing.T) {
ctx := context.Background()
big := MemoryStore()
var want []string
for i := range 12 {
origin := "novox/mesh-catalog"
if i%3 == 0 {
origin = "novox/mesh-sdk"
}
module := fmt.Sprintf("m%02d", i)
data, _ := json.Marshal(meshcatalog.Registration{Module: module, Origin: origin, Path: strings.Repeat("p", 100<<10)})
if err := big.Create(ctx, RegistrationKey(module), data); err != nil {
t.Fatal(err)
}
if origin == "novox/mesh-catalog" {
want = append(want, module)
}
}
named := func(tools []stdio.Tool) func(map[string]any) (any, error) {
for _, tl := range tools {
if tl.Name == RegistrationsTool {
return tl.Run
}
}
t.Fatalf("no tool %s", RegistrationsTool)
return nil
}
run := named(RegistrationTools(big, MemoryStore(), ask, time.Now, nil))
var got []string
pages := 0
for next := ""; ; pages++ {
raw, err := run(map[string]any{"repository": "novox/mesh-catalog", "next": next})
a, _ := raw.(meshcatalog.RegistrationsAnswer)
if err != nil || a.Capped != (a.Next != "") {
t.Fatalf("page %d = %+v (%v), want capped exactly when a cursor follows", pages, a, err)
}
for _, r := range a.Registrations {
got = append(got, r.Module)
}
if next = a.Next; next == "" {
break
}
}
if !slices.Equal(got, want) || pages == 0 {
t.Errorf("the pages hold %v in %d pages after the first, want %v over more than one page", got, pages, want)
}
if a, _ := run(map[string]any{"module": "m00", "repository": "novox/mesh-catalog"}); len(a.(meshcatalog.RegistrationsAnswer).Registrations) != 0 {
t.Errorf("m00 of novox/mesh-sdk answered for the repository novox/mesh-catalog: %+v", a)
}
reg := func(module, origin string) stdio.StateEntry {
data, _ := json.Marshal(meshcatalog.Registration{Module: module, Origin: origin})
return stdio.StateEntry{Key: RegistrationKey(module), Value: data}
}
pager := &pagedStore{Store: MemoryStore(), pages: map[string]stdio.StatePage{
"": {Entries: []stdio.StateEntry{reg("a", "novox/x"), reg("b", "novox/y")}, Next: "c1"},
"c1": {Entries: []stdio.StateEntry{reg("c", "novox/x")}}}}
run = named(RegistrationTools(pager, MemoryStore(), ask, time.Now, nil))
first, _ := run(map[string]any{"repository": "novox/x"})
second, _ := run(map[string]any{"repository": "novox/x", "next": "c1"})
f, g := first.(meshcatalog.RegistrationsAnswer), second.(meshcatalog.RegistrationsAnswer)
if len(f.Registrations) != 1 || f.Registrations[0].Module != "a" || f.Next != "c1" || !f.Capped ||
len(g.Registrations) != 1 || g.Registrations[0].Module != "c" || g.Next != "" || !slices.Equal(pager.asked, []string{"", "c1"}) {
t.Errorf("the paged read answered %+v then %+v, asking %v, want a then c of novox/x by the bus's cursor", f, g, pager.asked)
}
})
}
@@ -2,11 +2,13 @@ package index
import (
"context"
"fmt"
"slices"
"strings"
"testing"
"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/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-sdk/go/catalogue"
@@ -97,4 +99,65 @@ func TestAReleaseRepinsAnEntryNamingItsPackageWithNoPin(t *testing.T) {
said[0].CallKind != meshcatalog.CatalogRevisionEventCallKindRelease || said[1].Module != "mesh-sdk" || said[1].Version != "0.1.27" {
t.Errorf("said %+v, want catalog-revision of each branch with the release's call", said)
}
// Design 47 H2 §805, H-A-418, H-A-420, H-A-424, H-A-436: a pipeline reserving twenty packages of mesh-sdk in main's
// revision 2 keeps one re-pin revision of main when its gathering settles, at its first step-ended; its release then
// keeps none on main, and a pipeline that did not pass withdraws its reservations back to the newest released version.
ix.Files = func(_ context.Context, _, _ string, dirs []string) (map[string]map[string]string, error) {
out := map[string]map[string]string{}
for _, d := range dirs {
out[d] = map[string]string{"go.mod": strings.Repeat("d", 40), "sdk.go": strings.Repeat("e", 40)}
}
return out, nil
}
heard := newMem()
ix.Heard = heard
revision := BranchObject("main", 2)
newest := func() int64 {
rev, _, _, err := readNewestOf(ctx, ix.Revisions, "main")
if err != nil {
t.Fatal(err)
}
return rev.Revision
}
for i := range 20 {
e := meshbuilds.VersionReservedEvent{Module: "mesh-sdk", Artifact: fmt.Sprintf("mesh-sdk:p%d", i), Path: "mesh-sdk/go", Version: "0.1.28", Revision: revision}
if err := ix.HearVersionReserved(ctx, e); err != nil {
t.Fatal(err)
}
}
if _, _, open, _ := heard.Get(ctx, SettlingKey(revision)); !open || newest() != 2 {
t.Fatalf("twenty reservations: gathering open %v, main's newest %d, want open and no revision kept before it settles", open, newest())
}
if err := ix.Settle(ctx, revision); err != nil || newest() != 3 {
t.Fatalf("the gathering settled (%v) keeping main's newest %d, want one re-pin revision, 3", err, newest())
}
if now, _ := moduleOf(t, mods, "g"); now.Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.28" {
t.Errorf("g after the reservations is pinned %v, want v0.1.28", now.Packages)
}
if err := ix.Settle(ctx, revision); err != nil || newest() != 3 {
t.Errorf("a second step-ended settled (%v) keeping main's newest %d, want still 3", err, newest())
}
if _, err := ix.HearVersion(ctx, HeardVersion{Package: "mesh-sdk/go", GoModule: "git.novox.be/novox/mesh-sdk/go", Version: "0.1.28", Commit: strings.Repeat("1", 40), Published: true}); err != nil {
t.Fatal(err)
}
if _, err := ix.Repin(ctx, "mesh-sdk", "0.1.28"); err != nil || newest() != 3 {
t.Errorf("the release of the reserved 0.1.28 re-pinned (%v) keeping main's newest %d, want no revision more", err, newest())
}
next := BranchObject("main", 3)
if err := ix.HearVersionReserved(ctx, meshbuilds.VersionReservedEvent{Module: "mesh-sdk", Artifact: "mesh-sdk:p0", Path: "mesh-sdk/go", Version: "0.1.29", Revision: next}); err != nil {
t.Fatal(err)
}
if err := ix.Settle(ctx, next); err != nil || newest() != 4 {
t.Fatalf("the reservation of 0.1.29 settled (%v) keeping main's newest %d, want 4", err, newest())
}
if err := ix.Withdraw(ctx, "main", 3); err != nil || newest() != 5 {
t.Fatalf("the withdrawal (%v) kept main's newest %d, want 5", err, newest())
}
if now, _ := moduleOf(t, mods, "g"); now.Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.28" {
t.Errorf("g after the withdrawal is pinned %v, want the newest released v0.1.28", now.Packages)
}
if _, _, kept, _ := heard.Get(ctx, ReservedKey(next, "mesh-sdk")); kept {
t.Errorf("the withdrawn reservation is still kept")
}
}
@@ -0,0 +1,432 @@
package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// A release re-pins once, at its reservation (design 47 H2 §805; H-A-418, H-A-420, H-A-424). The builder says
// version-reserved when it reserves a package's number, naming the revision `<branch>.<n>` its pipeline runs. The indexer
// writes the series' numbered version with the contents read at the commit of the module's entry in that revision, so
// acceptedSeries and releasedPins pin it, and keeps the reservation in its state heard under
// `reserved.<revision>.<module>`, each key living reserved-keep. It gathers a pipeline's reservations per revision and
// writes one re-pin revision of that revision's branch when the gathering settles: at the first pipeline-started or
// step-ended of that pipeline heard after them, or at the expiry of the key settling.<revision>, written reserved-settle
// after the first. The release's package-published then
// moves no fingerprint. A pipeline-ended not passed whose revision holds reservations withdraws them: the series'
// numbered goes back to its newest released version and the importers are re-pinned to it.
// ReservedPrefix begins every key of the state heard holding a revision's reservations of one module.
const ReservedPrefix = "reserved."
// The defaults of the settings reserved-keep and reserved-settle (H-A-424 (1), (2)).
const (
DefaultReservedKeep = 24 * time.Hour
DefaultReservedSettle = 30 * time.Second
)
// ReservedKey is the key of module's reservations in revision, `reserved.<revision>.<module>`, the module escaped as a
// key's name is.
func ReservedKey(revision, module string) string {
return ReservedPrefix + revision + "." + keys.EscapeName(module)
}
// Reservation is one version-reserved as the indexer keeps it.
type Reservation struct {
Artifact string `json:"artifact"`
Path string `json:"path"`
Version string `json:"version"`
Fingerprint string `json:"fingerprint,omitempty"`
}
// Reserved is the value of a reserved key: a module's reservations in one revision.
type Reserved struct {
V int `json:"v"`
Revision string `json:"revision"`
Module string `json:"module"`
Reservations []Reservation `json:"reservations"`
At time.Time `json:"at"`
}
// TTLStore is a Store that writes a new key with its own time to live (a state declared `key-ttl`).
type TTLStore interface {
CreateTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error
}
// SettlingPrefix begins the key of the state heard that holds a revision's gathering open, `settling.<revision>`, written
// with the key-ttl reserved-settle at its first reservation: its expiry, heard through the indexer's watch of heard
// (Expired), settles the gathering; the indexer holds no timer (ADR 0437 §8; H-A-436).
const SettlingPrefix = "settling."
// SettlingKey is the key holding revision's gathering open.
func SettlingKey(revision string) string { return SettlingPrefix + revision }
// HearVersionReserved takes one version-reserved in: the series' numbered version, the reservation kept and the revision's
// gathering begun. An error leaves the event for the bus to give again.
func (ix *Indexer) HearVersionReserved(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
if ix.Heard == nil {
return errors.New("the indexer keeps no state " + HeardState)
}
_, ok, err := ix.branchOfRevision(ctx, e.Revision)
if err != nil {
return err
}
if !ok {
ix.logf("versions: the version-reserved of %s %s names the revision %q, which is of no watched branch: left", e.Artifact, e.Version, e.Revision)
return nil
}
if err := ix.keepNumbered(ctx, e); err != nil {
return err
}
if err := ix.keepReservation(ctx, e); err != nil {
return err
}
ix.logf("versions: %s reserved %s %s in %s; its importers are re-pinned once the pipeline's reservations settle", e.Module, e.Path, e.Version, e.Revision)
return ix.gather(ctx, e.Revision)
}
// branchOfRevision is the watched branch (the trunk among them) whose revision name is revision, `<branch>.<n>`.
func (ix *Indexer) branchOfRevision(ctx context.Context, revision string) (string, bool, error) {
branches, err := ix.watchedBranches(ctx)
if err != nil {
return "", false, err
}
if !slices.Contains(branches, TrunkBranch) {
branches = append(branches, TrunkBranch)
}
for _, b := range branches {
if _, ok := BranchRevisionOf(b, revision); ok {
return b, true, nil
}
}
return "", false, nil
}
// seriesOfPath is the series key and value of the package path names in series: the key whose name or Go module is path.
func (ix *Indexer) seriesOfPath(ctx context.Context, path, series string) (string, SeriesPackage, bool) {
all := ix.SeriesAll(ctx)
for _, key := range slices.Sorted(maps.Keys(all)) {
if s := all[key]; s.Series == series && (s.Name == path || s.GoModule == path) {
return key, s, true
}
}
return SeriesKey(path, series), SeriesPackage{}, false
}
// keepNumbered writes the reserved version as its series' numbered one, with the contents read at the commit of the
// module's entry in the event's revision (H-A-418 (2)); an older version than the numbered held changes nothing.
func (ix *Indexer) keepNumbered(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
series, ok := SeriesOf(e.Version)
if ix.Packages == nil || e.Path == "" || !ok {
return nil
}
key, s, _ := ix.seriesOfPath(ctx, e.Path, series)
v := SeriesVersion{Version: strings.TrimPrefix(e.Version, "v"), Fingerprint: e.Fingerprint}
if ix.Revisions != nil {
_, entries, err := ReadRevision(ctx, ix.Revisions, e.Revision)
if err != nil {
return fmt.Errorf("the revision %s of %s's reservation: %w", e.Revision, e.Module, err)
}
if i := slices.IndexFunc(entries, func(x meshcatalog.CatalogEntry) bool { return x.Module == e.Module }); i >= 0 {
v.Commit = entries[i].Commit
if s.GoModule != "" && v.Commit != "" && ix.Files != nil {
got, err := ix.packagesAt(ctx, entries[i].Repository, v.Commit, []string{s.GoModule}, nil)
switch p, found := got[s.GoModule]; {
case err != nil:
ix.logf("versions: %s %s's contents at %.12s are not read, so its importers are not pinned to it before its publish: %v", e.Path, e.Version, v.Commit, err)
case !found:
ix.logf("versions: the forge's listing at %.12s holds no Go module %s, so %s's importers are not pinned to it before its publish", v.Commit, s.GoModule, e.Version)
default:
p.At = ptr(ix.now().UTC())
v.Contents = contentsOfPublished(p)
}
}
} else {
ix.logf("versions: the revision %s holds no entry of %s, so %s %s is numbered with no contents", e.Revision, e.Module, e.Path, e.Version)
}
}
return write(ctx, ix.Packages, key, func(value []byte, found bool) ([]byte, bool, error) {
held := SeriesPackage{V: keys.Version, Name: e.Path, Series: series}
if found {
if err := json.Unmarshal(value, &held); err != nil {
return nil, false, err
}
}
if n := held.Numbered; n != nil && (CompareVersions("v"+n.Version, "v"+v.Version) > 0 || n.Version == v.Version && n.Contents != nil) {
return nil, false, nil
}
held.Numbered = numberedOf(v)
held.At = ptr(ix.now())
next, err := json.Marshal(held)
return next, false, err
})
}
// keepReservation keeps e under its revision and module in the state heard, the key living reserved-keep: a module's
// further reservation in the revision is added to its key, which is written again with its time to live.
func (ix *Indexer) keepReservation(ctx context.Context, e meshbuilds.VersionReservedEvent) error {
key := ReservedKey(e.Revision, e.Module)
r := Reservation{Artifact: e.Artifact, Path: e.Path, Version: e.Version, Fingerprint: e.Fingerprint}
for range writeTries {
value, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil {
return err
}
held := Reserved{V: keys.Version, Revision: e.Revision, Module: e.Module, At: ix.now().UTC()}
if found {
if err := json.Unmarshal(value, &held); err != nil {
return fmt.Errorf("heard.%s: %w", key, err)
}
if slices.Contains(held.Reservations, r) {
return nil
}
}
held.Reservations = append(held.Reservations, r)
data, err := json.Marshal(held)
if err != nil {
return err
}
if found {
if err := ix.Heard.Delete(ctx, key, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return err
}
}
err = ix.createTTL(ctx, key, data)
if errors.Is(err, ErrConflict) {
continue
}
return err
}
return fmt.Errorf("heard.%s: %w", key, ErrConflict)
}
// createTTL creates key in the state heard living reserved-keep (createTTLFor).
func (ix *Indexer) createTTL(ctx context.Context, key string, data []byte) error {
keep := ix.ReservedKeep
if keep <= 0 {
keep = DefaultReservedKeep
}
return ix.createTTLFor(ctx, key, data, keep)
}
// createTTLFor creates key in the state heard living ttl; a store that keeps no time to live per key keeps it with none,
// said.
func (ix *Indexer) createTTLFor(ctx context.Context, key string, data []byte, ttl time.Duration) error {
if st, ok := ix.Heard.(TTLStore); ok {
return st.CreateTTL(ctx, key, data, ttl)
}
ix.logf("versions: the state %s keeps no time to live per key here, so %s is kept with none", HeardState, key)
return ix.Heard.Create(ctx, key, data)
}
// reservedOf are the reservations revision holds, by module.
func (ix *Indexer) reservedOf(ctx context.Context, revision string) (map[string]Reserved, map[string]uint64, error) {
if ix.Heard == nil {
return nil, nil, nil
}
all, err := ix.Heard.Keys(ctx)
if err != nil {
return nil, nil, err
}
out, revs := map[string]Reserved{}, map[string]uint64{}
prefix := ReservedPrefix + revision + "."
for _, key := range all {
if !strings.HasPrefix(key, prefix) {
continue
}
value, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil {
return nil, nil, err
}
var r Reserved
if !found || json.Unmarshal(value, &r) != nil || r.Revision != revision {
continue
}
out[key], revs[key] = r, rev
}
return out, revs, nil
}
// gather begins revision's gathering, if none is open: the key settling.<revision>, living reserved-settle.
func (ix *Indexer) gather(ctx context.Context, revision string) error {
settle := ix.ReservedSettle
if settle <= 0 {
settle = DefaultReservedSettle
}
data, err := json.Marshal(map[string]any{"revision": revision, "at": ix.now().UTC()})
if err != nil {
return err
}
err = ix.createTTLFor(ctx, SettlingKey(revision), data, settle)
if errors.Is(err, ErrConflict) {
return nil // a gathering is open already
}
return err
}
// GatherKept settles, at the start, every revision the state heard holds reservations of whose gathering is not open any
// more: a settle cut by a restart is made then (one that moves nothing keeps no revision). An open one settles at its
// expiry or its pipeline's next word.
func (ix *Indexer) GatherKept(ctx context.Context) error {
if ix.Heard == nil {
return nil
}
all, err := ix.Heard.Keys(ctx)
if err != nil {
return err
}
revisions := map[string]bool{}
for _, key := range all {
if !strings.HasPrefix(key, ReservedPrefix) {
continue
}
value, _, found, err := ix.Heard.Get(ctx, key)
var r Reserved
if err != nil || !found || json.Unmarshal(value, &r) != nil || slices.Contains(all, SettlingKey(r.Revision)) {
continue
}
revisions[r.Revision] = true
}
var errs []error
for _, revision := range slices.Sorted(maps.Keys(revisions)) {
errs = append(errs, ix.settleNow(ctx, revision))
}
return errors.Join(errs...)
}
// Settle settles revision's gathering, if one is open (a pipeline-started or step-ended of its pipeline): its key goes, and
// every importer of the modules it reserved is re-pinned in one revision of its branch. None open settles nothing.
func (ix *Indexer) Settle(ctx context.Context, revision string) error {
if ix.Heard == nil {
return nil
}
key := SettlingKey(revision)
_, rev, found, err := ix.Heard.Get(ctx, key)
if err != nil || !found {
return err
}
if err := ix.Heard.Delete(ctx, key, rev); errors.Is(err, ErrConflict) {
return nil // settled by another word, or by its expiry
} else if err != nil {
return err
}
return ix.settleNow(ctx, revision)
}
// Expired takes in a key of the state heard that its time to live ended, as the watch of heard hands it over: a
// gathering's key settles that gathering (H-A-436); any other key is passed over.
func (ix *Indexer) Expired(ctx context.Context, key string) error {
revision, ok := strings.CutPrefix(key, SettlingPrefix)
if !ok {
return nil
}
return ix.settleNow(ctx, revision)
}
// settleNow re-pins every importer of the modules revision reserved in one revision of its branch.
func (ix *Indexer) settleNow(ctx context.Context, revision string) error {
held, _, err := ix.reservedOf(ctx, revision)
if err != nil || len(held) == 0 {
return err
}
branch, ok, err := ix.branchOfRevision(ctx, revision)
if err != nil || !ok {
return err
}
modules := modulesOf(held)
_, err = ix.repinModules(ctx, branch, modules, reservedCall(revision, len(modules), false))
return err
}
// Withdraw takes a pipeline-ended not passed of branch's revision in: each reservation the revision holds is withdrawn, its
// series' numbered set back to the newest released version, its importers re-pinned to that, and its key deleted.
func (ix *Indexer) Withdraw(ctx context.Context, branch string, revision int64) error {
if ix.Heard == nil {
return nil
}
name := BranchObject(branch, revision)
if _, rev, found, err := ix.Heard.Get(ctx, SettlingKey(name)); err == nil && found {
_ = ix.Heard.Delete(ctx, SettlingKey(name), rev) // the gathering is withdrawn with it
}
held, revs, err := ix.reservedOf(ctx, name)
if err != nil || len(held) == 0 {
return err
}
for _, r := range held {
for _, one := range r.Reservations {
if err := ix.withdrawNumbered(ctx, one); err != nil {
return err
}
}
}
modules := modulesOf(held)
if _, err := ix.repinModules(ctx, branch, modules, reservedCall(name, len(modules), true)); err != nil {
return err
}
for key, rev := range revs {
if err := ix.Heard.Delete(ctx, key, rev); err != nil && !errors.Is(err, ErrConflict) {
return err
}
}
ix.logf("versions: the %d reservations of %s are withdrawn, their importers re-pinned to the newest released versions", len(held), name)
return nil
}
// withdrawNumbered sets the series' numbered version back to its newest released one while it is the version r reserved.
func (ix *Indexer) withdrawNumbered(ctx context.Context, r Reservation) error {
series, ok := SeriesOf(r.Version)
if ix.Packages == nil || !ok {
return nil
}
key, _, found := ix.seriesOfPath(ctx, r.Path, series)
if !found {
return nil
}
return write(ctx, ix.Packages, key, func(value []byte, found bool) ([]byte, bool, error) {
var s SeriesPackage
if !found || json.Unmarshal(value, &s) != nil || s.Numbered == nil || s.Numbered.Version != strings.TrimPrefix(r.Version, "v") {
return nil, false, nil
}
s.Numbered = nil
if s.Newest != nil {
s.Numbered = numberedOf(*s.Newest)
}
s.At = ptr(ix.now())
next, err := json.Marshal(s)
return next, false, err
})
}
// modulesOf are the modules of a revision's reservations, sorted.
func modulesOf(held map[string]Reserved) []string {
var out []string
for _, r := range held {
if !slices.Contains(out, r.Module) {
out = append(out, r.Module)
}
}
slices.Sort(out)
return out
}
// reservedCall is the call of the re-pin revision of a revision's reservations: a release's re-pin, made at its reservation
// (§805), or at their withdrawal.
func reservedCall(revision string, modules int, withdrawn bool) revisionCall {
call := fmt.Sprintf("release of %s's %d reserved modules", revision, modules)
if withdrawn {
call = fmt.Sprintf("release of %s's %d reserved modules withdrawn", revision, modules)
}
return revisionCall{Call: call, Kind: meshcatalog.CatalogRevisionCallKindRelease}
}
@@ -67,7 +67,9 @@ func (r Run) done() bool {
}
// StartRun takes a run on request in, as the runner said it started: its members are kept in the state runs and its
// candidate is written; a run every member of which has ended already (its ends heard first) is dropped instead.
// candidate is written; a run every member of which has ended already (its ends heard first) is dropped instead. A member
// that is a source-only registration (its module the key source.<owner>.<name>) gets no candidate: the runner runs its check
// as one step (design 47 H2 §815; H-A-442), so a run of such members alone keeps and writes nothing.
func (ix *Indexer) StartRun(ctx context.Context, e meshpipelinerunner.RunStarted) error {
group, err := RunGroup(e.Run)
if err != nil {
@@ -76,9 +78,13 @@ func (ix *Indexer) StartRun(ctx context.Context, e meshpipelinerunner.RunStarted
if len(e.Members) == 0 {
return fmt.Errorf("%w: the run %s names no member", ErrUnreadable, e.Run)
}
members := slices.DeleteFunc(slices.Clone(e.Members), func(m meshpipelinerunner.Member) bool { return isSourceMember(m.Module) })
if len(members) == 0 {
return nil // a source-only check: no candidate, no run kept
}
ix.runMu.Lock()
defer ix.runMu.Unlock()
r, err := ix.updateRun(ctx, group, func(r *Run) { r.Members = slices.Clone(e.Members) })
r, err := ix.updateRun(ctx, group, func(r *Run) { r.Members = members })
if err != nil {
return err
}
@@ -88,11 +94,18 @@ func (ix *Indexer) StartRun(ctx context.Context, e meshpipelinerunner.RunStarted
return ix.writeRunCandidate(ctx, group, r.Members)
}
// isSourceMember says a run's member or mover is a source-only registration, named by its key source.<owner>.<name>
// (design 47 H2 §815; H-A-438).
func isSourceMember(module string) bool {
_, _, source := meshcatalog.ParseRegistrationsBySourceOwnerNameKey(module)
return source
}
// EndRunPipeline takes one pipeline-ended in: of a run's pipeline, its module is kept as ended, and once every member's has
// ended the candidate and the run's key are removed. A pipeline of no run is none of this.
func (ix *Indexer) EndRunPipeline(ctx context.Context, e meshpipelinerunner.PipelineEnded) error {
if e.Run == "" {
return nil
if e.Run == "" || !slices.ContainsFunc(e.Movers, func(m meshpipelinerunner.MoverEnded) bool { return !isSourceMember(m.Module) }) {
return nil // no run, or a source-only check's, which keeps no run (StartRun)
}
group, err := RunGroup(e.Run)
if err != nil {
@@ -211,6 +224,11 @@ func (ix *Indexer) writeRunCandidate(ctx context.Context, group string, members
pulls := make([]meshcatalog.CandidatesByGroupValuePullsItem, len(placed))
// One take-in per base branch: the members on one base are taken in together, so one member sees another's.
bases := map[string]*dryRun{}
defer func() {
for _, d := range bases {
d.end(ctx) // the run's scratch goes once it answered (design 47 H2 §804)
}
}()
for i, m := range placed {
d, ok := bases[m.base]
if !ok {
@@ -218,7 +236,7 @@ func (ix *Indexer) writeRunCandidate(ctx context.Context, group string, members
if err != nil {
return fmt.Errorf("the run %s: the revision view of %s: %w", group, m.base, err)
}
d = ix.dry()
d = ix.dry(m.base, group)
d.ix.Modules, d.ix.Graph, d.ix.Taken = view, nodes, newOverlay(nil)
d.ix.Logf = func(format string, args ...any) {
ix.logf("the run "+group+", computed and not written: "+format, args...)
@@ -114,6 +114,25 @@ func TestARunsCandidateIsBuiltOnItsStartAndDroppedWhenEveryMembersPipelineEnded(
t.Errorf("candidates %v, want none", k)
}
})
// Design 47 H2 §815 (H-A-438, H-A-442): a source-only check's member is its registration's key; the runner runs it as one
// step, so the indexer builds it no candidate and keeps no run, at its start or its end.
t.Run("a source-only check gets no candidate and no run", func(t *testing.T) {
ix, cands, runs, _ := bed(t)
source := started
source.Members = []meshpipelinerunner.Member{{Module: "source.novox.hq", Commit: c1}}
if err := ix.StartRun(ctx, source); err != nil {
t.Errorf("a source-only check's start: %v", err)
}
if err := ix.EndRunPipeline(ctx, ended("source.novox.hq")); err != nil {
t.Error(err)
}
if k, _ := cands.Keys(ctx); len(k) != 0 {
t.Errorf("candidates %v, want none", k)
}
if k, _ := runs.Keys(ctx); len(k) != 0 {
t.Errorf("runs %v, want none", k)
}
})
t.Run("a member's take-in starts from its own branch only when its registration watches it", func(t *testing.T) {
reg := meshcatalog.Registration{Branches: []string{"main", "beta"}}
for branch, want := range map[string]string{"beta": "beta", "main": TrunkBranch, "feature/1966-x": TrunkBranch, "": TrunkBranch} {
@@ -0,0 +1,163 @@
package index
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/views"
)
// The seat list as one object (design 47 H2 §814, §820; H-A-441): the trunk's seat definitions, resolved with their
// includes, as one JSON array in composer.Request.Seats' form sorted by seat, kept in the indexer's objects seat-lists
// under its digest (the sha256 of those bytes), written at the indexer's start (H-A-447) and at each trunk
// seat-definition-changed or -removed; every object
// but the newest two is deleted at each new list. The seat mesh-catalog's verb seat-list hands its digest, size and bytes, and
// a validate run's asker fills its request's seats from them, so every run of one seat list judges the same bytes.
// SeatListsObjects is the indexer's objects store of seat lists, in its old objects section (a foundation part, ADR 0619
// §2): 64 MiB, one object per digest.
const SeatListsObjects = "seat-lists"
// seatListsKept is how many seat lists the objects keep: the newest two.
const seatListsKept = 2
// SeatLists is the objects seat-lists as the indexer's process reaches them, to write, prune and hand out.
type SeatLists interface {
// Put stores data whole under name, replacing one of that name.
Put(ctx context.Context, name string, data []byte) error
// Get is the object's bytes; ErrNoObject when it holds none of that name.
Get(ctx context.Context, name string) ([]byte, error)
// Delete removes the object; one it does not hold is no error.
Delete(ctx context.Context, name string) error
// List is every object the store holds, a deleted one left out.
List(ctx context.Context) ([]buscalls.ObjectInfo, error)
}
// SeatListOf is the trunk's seat list as the object holds it, and its digest: each trunk definition resolved, in the
// order of its seat's name. A list with no seat is an error: no validator judges by an empty list.
func SeatListOf(defs views.Source) ([]byte, string, error) {
keys, err := defs.Keys()
if err != nil {
return nil, "", fmt.Errorf("the %s state cannot be listed: %w", SeatDefinitionsState, err)
}
type seatDef struct {
seat string
def json.RawMessage
}
var seats []seatDef
for _, key := range keys {
seat, ok := strings.CutSuffix(key, "."+SourceTrunk)
if !ok || strings.HasPrefix(key, outOfStepPrefix) {
continue
}
v, ok, err := defs.Get(key)
if err != nil {
return nil, "", fmt.Errorf("%s.%s cannot be read: %w", SeatDefinitionsState, key, err)
}
if !ok || v == nil {
continue
}
var e SeatDefinitionEntry
if err := json.Unmarshal(v.Value, &e); err != nil || e.Digest == "" || len(e.Definition) == 0 {
continue // an entry that holds no definition is no seat of the list
}
seats = append(seats, seatDef{seat, e.Definition})
}
slices.SortFunc(seats, func(a, b seatDef) int { return strings.Compare(a.seat, b.seat) })
list := make([]json.RawMessage, 0, len(seats))
for _, s := range seats {
list = append(list, s.def)
}
if len(list) == 0 {
return nil, "", fmt.Errorf("the %s state holds no trunk definition, so there is no seat list", SeatDefinitionsState)
}
raw, err := json.Marshal(list)
if err != nil {
return nil, "", err
}
sum := sha256.Sum256(raw)
return raw, hex.EncodeToString(sum[:]), nil
}
// KeepSeatList writes the trunk's seat list into seat-lists under its digest when the objects do not hold it, then deletes
// every object but the newest two, never the list just kept. It answers the list's digest; each write and each delete is
// one line in logf.
func KeepSeatList(ctx context.Context, defs views.Source, o SeatLists, logf func(string, ...any)) (string, error) {
raw, digest, err := SeatListOf(defs)
if err != nil {
return "", err
}
held, err := o.List(ctx)
if err != nil {
return "", fmt.Errorf("the objects %s cannot be listed: %w", SeatListsObjects, err)
}
if !slices.ContainsFunc(held, func(i buscalls.ObjectInfo) bool { return i.Name == digest }) {
if err := o.Put(ctx, digest, raw); err != nil {
return "", fmt.Errorf("the seat list %s cannot be kept in %s: %w", digest, SeatListsObjects, err)
}
logf("seat list %s kept in %s (%d bytes)", digest, SeatListsObjects, len(raw))
if held, err = o.List(ctx); err != nil {
return digest, fmt.Errorf("the objects %s cannot be listed: %w", SeatListsObjects, err)
}
}
slices.SortFunc(held, func(a, b buscalls.ObjectInfo) int { return b.Modified.Compare(a.Modified) }) // newest first
kept := 0
for _, i := range held {
if i.Name == digest || kept < seatListsKept {
kept++
continue
}
if err := o.Delete(ctx, i.Name); err != nil {
return digest, fmt.Errorf("the seat list %s cannot be deleted from %s: %w", i.Name, SeatListsObjects, err)
}
logf("seat list %s deleted from %s: only the newest %d are kept", i.Name, SeatListsObjects, seatListsKept)
}
return digest, nil
}
// SeatListVerb is the seat mesh-catalog's verb seat-list, served by the indexer's process (H-A-443: the owner hands its
// objects, ADR 0596): the trunk's seat list's digest and size, then the bytes of its object in seat-lists in chunks of at
// most buscalls.SeatChunkBytes on the call's chunk subjects, each acknowledged before the next. A list the objects do not
// hold yet is refused naming it, never answered with other bytes. A caller that does not acknowledge within within ends
// the send, said in logf.
func SeatListVerb(defs views.Source, o SeatLists, line buscalls.ChunkLine, within time.Duration, logf func(string, ...any)) func(caller string, body json.RawMessage) (any, error) {
return func(_ string, raw json.RawMessage) (any, error) {
var in meshcatalog.SeatListInput
if err := json.Unmarshal(raw, &in); err != nil {
return nil, fmt.Errorf("the arguments are not JSON: %w", err)
}
if !callToken.MatchString(in.Call) {
return nil, errors.New("call is one token of 16 to 64 letters, digits, - or _: 128 random bits the caller chooses")
}
ctx := context.Background()
_, digest, err := SeatListOf(defs)
if err != nil {
return nil, err
}
body, err := o.Get(ctx, digest)
if errors.Is(err, ErrNoObject) {
return nil, fmt.Errorf("the seat list %s is not kept in %s yet: it is written at the indexer's start and at each trunk seat-definition move", digest, SeatListsObjects)
}
if err != nil {
return nil, fmt.Errorf("the seat list %s cannot be read from %s: %w", digest, SeatListsObjects, err)
}
send := buscalls.SeatChunks{Seat: meshcatalog.Seat, Verb: meshcatalog.VerbSeatList, Call: in.Call}
total := int64((len(body) + buscalls.SeatChunkBytes - 1) / buscalls.SeatChunkBytes)
go func() { // the send subscribes to the acknowledgements itself and ends when every chunk is sent or one is not acknowledged
if err := send.Send(line, body, within, logf); err != nil {
logf("the send %s of the seat list %s: %v", in.Call, digest, err)
}
}()
return meshcatalog.SeatListAnswer{Digest: digest, Size: int64(len(body)), Chunks: total}, nil
}
}
@@ -0,0 +1,123 @@
package index
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"slices"
"strings"
"testing"
"time"
"github.com/nats-io/nats.go"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/views"
)
// memSeatLists is seat-lists in memory; each put is a second newer than the last.
type memSeatLists struct {
objects map[string][]byte
at map[string]time.Time
clock time.Time
}
func (m *memSeatLists) Put(_ context.Context, name string, data []byte) error {
m.clock = m.clock.Add(time.Second)
m.objects[name], m.at[name] = data, m.clock
return nil
}
func (m *memSeatLists) Get(_ context.Context, name string) ([]byte, error) {
d, ok := m.objects[name]
if !ok {
return nil, ErrNoObject
}
return d, nil
}
func (m *memSeatLists) Delete(_ context.Context, name string) error {
delete(m.objects, name)
return nil
}
func (m *memSeatLists) List(context.Context) ([]buscalls.ObjectInfo, error) {
out := []buscalls.ObjectInfo{}
for n, d := range m.objects {
out = append(out, buscalls.ObjectInfo{Name: n, Size: uint64(len(d)), Modified: m.at[n]})
}
return out, nil
}
func (m *memSeatLists) names() []string {
var out []string
for n := range m.objects {
out = append(out, n)
}
slices.Sort(out)
return out
}
// noLine is a chunk line that hears nothing, so a send ends at once, said.
type noLine struct{}
func (noLine) Publish(string, []byte) error { return nil }
func (noLine) Subscribe(string, nats.MsgHandler) (*nats.Subscription, error) {
return nil, errors.New("no bus in this test")
}
// Design 47 H2 §814, §820 (H-A-441, H-A-443): the trunk's seat list is one object of seat-lists named by its sha256, in the
// order of its seats, kept at each new list with the newest two, and handed by the verb seat-list.
func TestTheSeatListIsOneObjectByItsDigest(t *testing.T) {
entry := func(seat, source, def string) *views.Entry {
raw, _ := json.Marshal(SeatDefinitionEntry{Seat: seat, Source: source, Digest: "d-" + seat, Definition: json.RawMessage(def)})
return &views.Entry{Value: raw}
}
defs := memSource{
SeatDefinitionKey("a-b"): entry("a-b", SourceTrunk, `{"seat":"a-b"}`),
SeatDefinitionKey("a"): entry("a", SourceTrunk, `{"seat":"a"}`),
"a.pull-7": entry("a", "pull-7", `{"seat":"a","pull":7}`),
outOfStepPrefix + "c." + SourceTrunk: entry("c", SourceTrunk, `{"seat":"c"}`),
}
want := `[{"seat":"a"},{"seat":"a-b"}]` // by seat, not by key: "a-b.trunk" sorts before "a.trunk"
sum := sha256.Sum256([]byte(want))
digest := hex.EncodeToString(sum[:])
raw, got, err := SeatListOf(defs)
if err != nil || string(raw) != want || got != digest {
t.Fatalf("SeatListOf = %s %s (%v), want %s %s", raw, got, err, want, digest)
}
if _, _, err := SeatListOf(memSource{}); err == nil {
t.Error("an empty seat list was given a digest")
}
lists := &memSeatLists{objects: map[string][]byte{}, at: map[string]time.Time{}}
verb := SeatListVerb(defs, lists, noLine{}, time.Second, t.Logf)
if _, err := verb("", json.RawMessage(`{"call":"0123456789abcdef0123456789abcdef"}`)); err == nil || !strings.Contains(err.Error(), "not kept in seat-lists yet") {
t.Errorf("a list not kept yet was answered: %v", err)
}
for _, old := range []string{"old-1", "old-2", "old-3"} {
_ = lists.Put(context.Background(), old, []byte("[]"))
}
if d, err := KeepSeatList(context.Background(), defs, lists, t.Logf); err != nil || d != digest {
t.Fatalf("KeepSeatList = %s (%v), want %s", d, err, digest)
}
if names := lists.names(); !slices.Equal(names, []string{digest, "old-3"}) || string(lists.objects[digest]) != want {
t.Errorf("seat-lists holds %v, want the list kept and the newest other", names)
}
before := lists.at[digest]
if _, err := KeepSeatList(context.Background(), defs, lists, t.Logf); err != nil || !lists.at[digest].Equal(before) || len(lists.objects) != 2 {
t.Errorf("the same list kept again was written again, or another deleted: %v %v", lists.names(), err)
}
if _, err := verb("", json.RawMessage(`{"call":"x"}`)); err == nil || !strings.Contains(err.Error(), "128 random bits") {
t.Errorf("a call that is no token was taken: %v", err)
}
a, err := verb("", json.RawMessage(`{"call":"0123456789abcdef0123456789abcdef"}`))
if err != nil || a != (meshcatalog.SeatListAnswer{Digest: digest, Size: int64(len(want)), Chunks: 1}) {
t.Errorf("seat-list = %+v (%v), want its digest, size and one chunk", a, err)
}
}
@@ -177,7 +177,8 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
var pins sdkstep.PackageVersions
for _, key := range slices.Sorted(maps.Keys(series)) {
s := series[key]
if s.GoModule == "" || s.Newest == nil || s.Newest.Contents == nil || m.AcceptedSeries(s.Name) != s.Series {
pinned := pinnedVersion(s)
if s.GoModule == "" || pinned == nil || pinned.Contents == nil || m.AcceptedSeries(s.Name) != s.Series {
continue
}
if repo, _, ok := trunk.PackageRepository(s.GoModule); !ok || trunk.SameRepository(repo, repository) {
@@ -186,8 +187,8 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
if out == nil {
out, pins = maps.Clone(published), sdkstep.PackageVersions{}
}
p := publishedOfContents(*s.Newest.Contents)
version := "v" + s.Newest.Version
p := publishedOfContents(*pinned.Contents)
version := "v" + pinned.Version
p.Commit = version
out[s.GoModule], pins[s.GoModule] = p, version
}
@@ -197,6 +198,17 @@ func acceptedSeries(series map[string]SeriesPackage, m catalogue.Manifest, repos
return out, pins
}
// pinnedVersion is the version of a series its users are pinned to: its numbered one when a reservation wrote it with its
// contents and it is newer than the newest released (design 47 H2 §805, H-A-418 (2), H-A-424 (4)), else the newest; nil
// for none.
func pinnedVersion(s SeriesPackage) *SeriesVersion {
if n := s.Numbered; n != nil && n.Contents != nil && (s.Newest == nil || CompareVersions("v"+s.Newest.Version, "v"+n.Version) < 0) {
p := publishedOfNumbered(*n.Contents)
return &SeriesVersion{Version: n.Version, Commit: n.Commit, Digest: n.Digest, Fingerprint: n.Fingerprint, Contents: contentsOfPublished(p)}
}
return s.Newest
}
// KeepPackageNames writes, at a trunk merge, each package artifact's name in its own ecosystem into its series key
// (design 32): a Go package's module path from the go.mod under its paths at the merge commit, a TypeScript package's
// package.json name, each read through the forge. The key keeps what it held and gains the name and the module and
@@ -24,13 +24,6 @@ type sourceNow struct {
heads map[string]string
}
// sourceHeads is the head the latest source seen names for each repository (a copy), nil while none has been seen.
func (ix *Indexer) sourceHeads() map[string]string {
ix.mu.Lock()
defer ix.mu.Unlock()
return maps.Clone(ix.source.heads)
}
// wholeAt reads repository's trees at the commit head through the seat git (design 47 H §743): every module directory's manifest,
// templates' needs, lock files and packages, and the catalogue's predefined list where the repository is the catalogue's (§769).
func (ix *Indexer) wholeAt(ctx context.Context, repository, head string) (whole, error) {
@@ -39,9 +32,9 @@ func (ix *Indexer) wholeAt(ctx context.Context, repository, head string) (whole,
if ix.ReadFile == nil {
return nil, errors.New("the indexer reads no file of the forge")
}
return ix.ReadFile(ctx, repository, head, p)
return waited(ctx, "git", "file", func() ([]byte, error) { return ix.ReadFile(ctx, repository, head, p) })
}
first, err := ix.Read(ctx, repository, head, "")
first, err := waited(ctx, "git", "trees", func() (RepoRead, error) { return ix.Read(ctx, repository, head, "") })
if err != nil {
return f, fmt.Errorf("the seat git could not read %s at %.12s: %w", repository, head, err)
}
@@ -49,7 +42,7 @@ func (ix *Indexer) wholeAt(ctx context.Context, repository, head string) (whole,
for _, dir := range slices.Sorted(maps.Keys(first.Trees)) {
read := first
if dir != "" {
if read, err = ix.Read(ctx, repository, head, dir); err != nil {
if read, err = waited(ctx, "git", "trees", func() (RepoRead, error) { return ix.Read(ctx, repository, head, dir) }); err != nil {
return f, fmt.Errorf("the seat git could not read %q of %s at %.12s: %w", dir, repository, head, err)
}
}
@@ -38,7 +38,8 @@ func TakenID(branch string, source int64) string {
// ErrObjectsFull waits for the indexer's own room, any other is the failed read or write it says; ErrOldForm is never taken in
// and said as no take-in.
func (ix *Indexer) TakeInSource(ctx context.Context, e meshdelivery.SourceMovedEvent) (meshcatalog.TakeInTaken, error) {
taken, err := ix.takeInSource(ctx, e)
taken, err := ix.takeInSource(ix.withTakeIn(ctx, e.Branch, e.Source), e)
ix.endTakeIn(ctx, e.Source)
switch {
case err == nil:
ix.unhold(ctx, e.Branch, e.Source)
@@ -78,7 +79,8 @@ func (ix *Indexer) takeInSource(ctx context.Context, e meshdelivery.SourceMovedE
if err != nil {
return taken, err
}
d := ix.dry()
d := ix.dry(e.Branch, e.Call)
defer d.end(ctx)
d.ix.Modules, d.ix.Graph, d.ix.Taken = view, nodes, newOverlay(nil)
d.ix.Logf = func(format string, args ...any) { ix.logf("take-in of "+e.Branch+": "+format, args...) }
x = d.ix
@@ -6,7 +6,14 @@ import (
"errors"
"fmt"
"reflect"
"slices"
"strings"
"sync"
"testing"
"time"
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"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/meshdelivery"
@@ -98,6 +105,125 @@ func TestASourceRevisionIsTakenInAsOneRevision(t *testing.T) {
if _, err := ix.TakeInSource(ctx, old); !errors.Is(err, ErrOldForm) {
t.Errorf("a source-moved with no call answered %v, want ErrOldForm", err)
}
// Design 47 H2 §815: a move of a source-only registration's branch (a repository with no manifest) is taken in as a
// take-in with no movers.
read := ix.Read
ix.Read = func(ctx context.Context, repository, sha, dir string) (RepoRead, error) {
if repository == "novox/hq" {
return RepoRead{Root: "1111111111111111111111111111111111111111", Trees: map[string]string{}, Manifests: map[string]string{}}, nil
}
return read(ctx, repository, sha, dir)
}
hq := meshdelivery.SourceMovedEvent{V: 1, Branch: "main", Source: 9, Call: "00112233445566aa",
Heads: []meshdelivery.SourceMovedEventHeadsItem{{Repository: "novox/hq", Commit: "2222222222222222222222222222222222222222"}}}
if src, err := ix.TakeInSource(ctx, hq); err != nil || len(src.Entries) != 0 || src.Revision != 3 || src.Source != 9 {
t.Errorf("a source-only repository's move said %+v (%v), want revision 3 of source 9 with no movers", src, err)
}
ix.Read = read
// Design 47 H2 §803, H-A-409: a take-in says what it waits on, in the journal, in takeins and past five minutes as a finding.
t.Run("a take-in says what it waits on", func(t *testing.T) {
running := newMem()
ix.TakeIns = running
ix.Findings = newFindings()
// The take-in's end removes its waiting-on.
if err := running.Create(ctx, RunningKey(10), []byte(`{"source":10}`)); err != nil {
t.Fatal(err)
}
next := moved
next.Source, next.Call = 10, "00112233445566ff"
if _, err := ix.TakeInSource(ctx, next); err != nil {
t.Fatal(err)
}
if _, _, found, _ := running.Get(ctx, RunningKey(10)); found {
t.Error("the take-in's end left its waiting-on in takeins")
}
start := time.Date(2026, 11, 22, 1, 0, 0, 0, time.UTC)
now := start
timers := make(chan context.CancelFunc)
var mu sync.Mutex
var lines []string
wrote := make(chan struct{}, 1)
findings := newFindings()
w := &Indexer{Module: testSelf, TakeIns: running, Findings: findings, Now: func() time.Time { mu.Lock(); defer mu.Unlock(); return now },
Bound: func(parent context.Context, _ time.Duration) (context.Context, context.CancelFunc) {
b, cancel := context.WithCancel(parent)
timers <- cancel
return b, cancel
},
Logf: func(format string, args ...any) {
mu.Lock()
defer mu.Unlock()
lines = append(lines, fmt.Sprintf(format, args...))
}}
w.Findings = findingsSignal{findings, wrote}
listing := func(answerAfter time.Duration) {
t.Helper()
mu.Lock()
now, lines = start, nil
mu.Unlock()
release, res := make(chan struct{}), make(chan error)
go func() {
_, err := waited(w.withTakeIn(ctx, "main", 9), "git", "trees", func() (int, error) { <-release; return 1, nil })
res <- err
}()
first := <-timers
if answerAfter < WaitingLineAfter {
close(release)
<-res
return
}
mu.Lock()
now = start.Add(70 * time.Second)
mu.Unlock()
first()
second := <-timers // asked once the line is said and the waiting-on written
if answerAfter >= WaitingFindingAfter {
second()
<-wrote
if h := findings.Held(); len(h) != 1 || h[0].Kind != TakeInWaitingKind || h[0].Scope != mcc.ScopeMerge || h[0].ID != "9" {
t.Errorf("after %s: findings %+v, want take-in-waiting of merge 9", answerAfter, h)
}
}
close(release)
if err := <-res; err != nil {
t.Fatal(err)
}
}
for _, c := range []struct {
after time.Duration
lines int
finding bool
}{{30 * time.Second, 0, false}, {70 * time.Second, 1, false}, {6 * time.Minute, 1, false}} {
listing(c.after)
mu.Lock()
got := slices.Clone(lines)
mu.Unlock()
if len(got) != c.lines || (c.lines == 1 && !strings.Contains(got[0], "waits on git trees since 2026-11-22T01:00:00Z")) {
t.Errorf("answered after %s: lines %q, want %d naming git trees and since when", c.after, got, c.lines)
}
r, err := ReadRunning(ctx, running)
want := c.lines == 1
if err != nil || want != (len(r) == 1) || (want && (r[0].Source != 9 || r[0].Branch != "main" || r[0].WaitingOn != WaitingOn{Part: "git", Verb: "trees", Since: start})) {
t.Errorf("answered after %s: running %+v (%v), want waiting-on git trees since %s: %v", c.after, r, err, start, want)
}
if len(findings.Held()) != 0 {
t.Errorf("answered after %s: take-in-waiting still raised: %+v", c.after, findings.Held())
}
w.endTakeIn(ctx, 9)
}
})
}
// findingsSignal is a finding writer that says each write it passes on.
type findingsSignal struct {
*memFindings
wrote chan struct{}
}
func (f findingsSignal) Write(ctx context.Context, x mcseat.Finding) error {
err := f.memFindings.Write(ctx, x)
f.wrote <- struct{}{}
return err
}
// Design 47 H §768, §743, H-A-19: a branch's first source revision (start true) is taken in with no mover, says take-in.taken
@@ -0,0 +1,194 @@
package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
)
// A take-in says what it waits on (design 47 H2 §803, H-A-409): a source-moved take-in that waits longer than
// WaitingLineAfter on another part (the seat git's listing or a file, a package's versions, a registry) writes one journal
// line naming the part, the verb and since when, and keeps its waiting-on in the state takeins under the key
// RunningPrefix and the source revision, rewritten at each new wait and removed at the take-in's end; past
// WaitingFindingAfter it raises the finding take-in-waiting (scope merge, id the source revision), cleared when the wait
// ends. indexer_pending answers it beside the held take-ins.
const (
TakeInWaitingKind = "take-in-waiting"
RunningPrefix = "running."
WaitingLineAfter = time.Minute
WaitingFindingAfter = 5 * time.Minute
)
// WaitingOn is what a running take-in waits on: the part, its verb and since when.
type WaitingOn struct {
Part string `json:"part"`
Verb string `json:"verb"`
Since time.Time `json:"since"`
}
// RunningTakeIn is the value of a running take-in in the state takeins (H-A-409).
type RunningTakeIn struct {
Branch string `json:"branch"`
Source int64 `json:"source"`
WaitingOn WaitingOn `json:"waiting-on"`
}
// RunningKey is the takeins key of the running take-in of a source revision.
func RunningKey(source int64) string { return RunningPrefix + strconv.FormatInt(source, 10) }
type takeInRunKey struct{}
// takeInRun is the running take-in a context carries, and the live indexer that says its waits (a branch's take-in
// computes on a dry copy, which writes nothing).
type takeInRun struct {
ix *Indexer
branch string
source int64
}
// withTakeIn is ctx carrying the running take-in of the source revision of branch.
func (ix *Indexer) withTakeIn(ctx context.Context, branch string, source int64) context.Context {
return context.WithValue(ctx, takeInRunKey{}, &takeInRun{ix: ix, branch: branch, source: source})
}
// endTakeIn removes the running take-in's value from the state takeins, when one was written.
func (ix *Indexer) endTakeIn(ctx context.Context, source int64) {
if ix.TakeIns == nil {
return
}
key := RunningKey(source)
_, rev, found, err := ix.TakeIns.Get(ctx, key)
if err == nil && found {
err = ix.TakeIns.Delete(ctx, key, rev)
}
if err != nil && !errors.Is(err, ErrConflict) {
ix.logf("take-in: source revision %d: its waiting-on is not removed from %s: %v", source, TakeInsState, err)
}
}
// bound is ctx bounded by d, a context's bound and no timer (ADR 0437 §8, as fingerprints.go bounds its wait); Bound
// when set.
func (ix *Indexer) bound(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
if ix.Bound != nil {
return ix.Bound(ctx, d)
}
return context.WithTimeout(ctx, d)
}
// passed is whether the wait outlasted the bound b: false once it ended (done) or the take-in's own context ended.
func passed(ctx, b context.Context, done <-chan struct{}) bool {
select {
case <-done:
return false
case <-b.Done():
}
select {
case <-done:
return false
default:
}
return ctx.Err() == nil
}
// waited is f, a call on part's verb: within a running take-in (ctx), a wait past WaitingLineAfter is said and kept, one
// past WaitingFindingAfter raises take-in-waiting until it ends. Outside a take-in it is f alone.
func waited[T any](ctx context.Context, part, verb string, f func() (T, error)) (T, error) {
run, ok := ctx.Value(takeInRunKey{}).(*takeInRun)
if !ok {
return f()
}
done, finished := make(chan struct{}), make(chan struct{})
go func() {
defer close(finished)
run.ix.watchWait(ctx, run, part, verb, done)
}()
v, err := f()
close(done)
<-finished
return v, err
}
func (ix *Indexer) watchWait(ctx context.Context, run *takeInRun, part, verb string, done <-chan struct{}) {
since := ix.now().UTC()
line, cancel := ix.bound(ctx, WaitingLineAfter)
defer cancel()
if !passed(ctx, line, done) {
return
}
ix.logf("take-in: source revision %d of %s waits on %s %s since %s", run.source, run.branch, part, verb, since.Format(time.RFC3339))
ix.writeWaiting(ctx, RunningTakeIn{Branch: run.branch, Source: run.source, WaitingOn: WaitingOn{Part: part, Verb: verb, Since: since}})
id := strconv.FormatInt(run.source, 10)
finding, cancelFinding := ix.bound(ctx, WaitingFindingAfter-WaitingLineAfter)
defer cancelFinding()
if !passed(ctx, finding, done) {
return
}
if ix.Findings != nil {
f := ix.observed(mcc.ScopeMerge, id, TakeInWaitingKind,
fmt.Sprintf("the take-in of source revision %d of %s waits on %s %s", run.source, run.branch, part, verb),
"A take-in waits on another part",
fmt.Sprintf("The take-in of source revision %d of %s has waited on %s's %s since %s, so the revision is not taken in.", run.source, run.branch, part, verb, since.Format(time.RFC3339)),
"indexer."+TakeInWaitingKind)
if err := ix.Findings.Write(ctx, f); err != nil {
ix.logf("take-in: the finding %s is not written: %v", TakeInWaitingKind, err)
}
}
<-done
if ix.Findings != nil {
if err := ix.clearFinding(context.WithoutCancel(ctx), mcc.ScopeMerge, id, TakeInWaitingKind, part+" "+verb+" answered"); err != nil {
ix.logf("take-in: the finding %s is not cleared: %v", TakeInWaitingKind, err)
}
}
}
// writeWaiting writes the running take-in's value in the state takeins, over the one it holds.
func (ix *Indexer) writeWaiting(ctx context.Context, v RunningTakeIn) {
if ix.TakeIns == nil {
return
}
raw, _ := json.Marshal(v)
key := RunningKey(v.Source)
_, rev, found, err := ix.TakeIns.Get(ctx, key)
switch {
case err != nil:
case found:
err = ix.TakeIns.Update(ctx, key, raw, rev)
default:
err = ix.TakeIns.Create(ctx, key, raw)
}
if err != nil {
ix.logf("take-in: source revision %d: its waiting-on is not written in %s: %v", v.Source, TakeInsState, err)
}
}
// ReadRunning is every running take-in's value of the state takeins (indexer_pending's running part); none for no state.
func ReadRunning(ctx context.Context, st Store) ([]RunningTakeIn, error) {
if st == nil {
return nil, nil
}
keys, err := st.Keys(ctx)
if err != nil {
return nil, err
}
var out []RunningTakeIn
for _, k := range keys {
if len(k) <= len(RunningPrefix) || k[:len(RunningPrefix)] != RunningPrefix {
continue
}
raw, _, found, err := st.Get(ctx, k)
if err != nil {
return nil, err
}
var r RunningTakeIn
if !found || json.Unmarshal(raw, &r) != nil {
continue
}
out = append(out, r)
}
return out, nil
}
@@ -43,7 +43,7 @@ func (ix *Indexer) writeTakenKnown(ctx context.Context, f whole, notOlder string
return nil, false, nil
}
if ix.Contains != nil && cur.Merge != notOlder {
later, err := ix.Contains(ctx, f.Repository, f.Merge, cur.Merge)
later, err := waited(ctx, "git", "contains", func() (bool, error) { return ix.Contains(ctx, f.Repository, f.Merge, cur.Merge) })
if err != nil {
ix.logf("%s: whether %s is in %s cannot be read, so taken.%s stays at %s: %v", f.Repository, f.Merge, cur.Merge, key, cur.Merge, err)
return nil, false, nil
@@ -1,6 +1,7 @@
{
"module": "ca-trust",
"version": "1",
"version": "0.1",
"class": "core",
"slug": "catrust",
"capabilities": [
"service-manager"
@@ -1,6 +1,7 @@
{
"module": "claude-code",
"version": "1",
"version": "0.1",
"class": "leaf",
"moved": true,
"slug": "agent",
"capabilities": [
@@ -11,6 +12,25 @@
{
"name": "gitea-read",
"optional": true
},
{
"name": "finding-events",
"storage": "stream",
"template": "events",
"options": {
"events": [
"finding-written.*",
"finding-cleared.*",
"findings-stated.*"
],
"max-age-days": 7,
"max-mib": 8
}
},
{
"name": "findings",
"storage": "key-value",
"template": "state"
}
],
"binds": {
@@ -22,6 +42,31 @@
"uses": [
"operator-channel"
],
"invokes": [
"seat:mesh-hand-acts.warranted",
"seat:mesh-hand-acts.hand-act",
"seat:mesh-catalog.seat-definitions",
"seat:mesh-catalog.revision",
"seat:mesh-catalog.registrations",
"seat:mesh-delivery.source",
"mesh-delivery-assigner.assigner_read_assignments",
"seat:anthropic-licence-manager.bindings",
"seat:anthropic-licence-manager.current",
"seat:mesh-vault.get",
"seat:operator-channel.notify"
],
"consumes": [
"mesh-catalog.catalog-revision",
"mesh-catalog.registration-changed",
"mesh-delivery.source-moved",
"mesh-delivery-assigner.views.assignments",
"mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed",
"mesh-conditions.findings-asked",
"claude-licence-manager.holdings.asked",
"claude-licence-manager.binding.changed.*",
"mesh-vault.secret-changed"
],
"state": [
"servers",
"holdings",
@@ -31,13 +76,13 @@
"memory",
"waits"
],
"reads": [
"claude-licence-manager.bindings"
"emits": [
"judged",
"holdings-changed"
],
"tools": [
"claude_code_status",
"claude_code_render",
"claude_code_guard",
"claude_code_pull",
"claude_code_grant",
"claude_code_add_api_key",
@@ -83,7 +128,11 @@
"claude_code_home_removed",
"claude_code_home_restore",
"claude_code_judge",
"claude_code_judged"
"claude_code_judged",
"claude_code_first_views",
"claude_code_first_view_again",
"claude_code_seat_list",
"claude_code_seat_list_again"
],
"data": {
"own": [
@@ -210,7 +259,16 @@
"path": "${dir:state}/settings.json",
"mode": "0600",
"owner": "${machine:account}",
"takes-config": ["role", "mcp_servers", "managed_settings", "instructions", "output_styles", "skills", "commands", "agents"],
"takes-config": [
"role",
"mcp_servers",
"managed_settings",
"instructions",
"output_styles",
"skills",
"commands",
"agents"
],
"merge": "json",
"template": "files/settings.json"
}
@@ -236,7 +294,8 @@
"env": {
"MESH_CLAUDE_CODE_STATE": "${dir:state}",
"MESH_CLAUDE_CODE_FACTS": "${dir:state}/facts.json",
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json"
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json",
"MESH_CLAUDE_CODE_FORGE": "${dir:state}/gitea-read.secret"
}
},
{
@@ -1,6 +1,7 @@
{
"module": "dunst",
"version": "1",
"version": "0.1",
"class": "core",
"moved": true,
"capabilities": [
"package-manager"
@@ -1,6 +1,7 @@
{
"module": "xterm",
"version": "1",
"version": "0.1",
"class": "core",
"moved": true,
"capabilities": [
"package-manager"
@@ -303,11 +303,11 @@ func (ix *Indexer) recomputeLocked(ctx context.Context, overlay map[string]meshc
r.none = strings.Join(missing, "; ")
case noToolchain != "":
r.none = noToolchain
if fp, pkgs, ok := stillComputed(module, kept, k, toolchains, held, pub, pins, ix.sourceHeads(), series); ok {
if fp, pkgs, ok := stillComputed(module, kept, k, toolchains, held, pub, pins, series); ok {
r = result{fp: fp, tcs: k.held.Toolchains, pkgs: pkgs}
}
default:
f := formOf(module, k.cur.Repository, &kept, toolchains, k.held, held, pub, pins, ix.sourceHeads(), ix.logf)
f := formOf(module, k.cur.Repository, &kept, toolchains, k.held, held, pub, pins, ix.logf)
r.fp, r.none = f.fp, f.none
if r.fp != "" {
// a pin is a released version, never a commit (H-A-161), and the version line's fingerprint takes it (H-A-167)
@@ -510,7 +510,7 @@ func hasContext(m catalogue.Manifest) bool {
// with the toolchains it was computed with in place of the languages agreed on none, give it again, in its form. Any
// other input that moved (a merge, a base, an agreed toolchain, an imported package) gives another fingerprint, and the
// module has none until they agree.
func stillComputed(module string, kept meshcatalog.ModulesByModuleValueInputs2, k *known, agreed map[string]meshcatalogclient.Toolchain2, held map[string]meshcatalog.ModulesByModuleValue, published map[string]meshcatalog.PackagesByModuleValue, pins sdkstep.PackageVersions, heads map[string]string, series map[string]SeriesPackage) (string, sdkstep.PackageVersions, bool) {
func stillComputed(module string, kept meshcatalog.ModulesByModuleValueInputs2, k *known, agreed map[string]meshcatalogclient.Toolchain2, held map[string]meshcatalog.ModulesByModuleValue, published map[string]meshcatalog.PackagesByModuleValue, pins sdkstep.PackageVersions, series map[string]SeriesPackage) (string, sdkstep.PackageVersions, bool) {
if k.held.Fp2 == "" {
return "", nil, false
}
@@ -526,7 +526,7 @@ func stillComputed(module string, kept meshcatalog.ModulesByModuleValueInputs2,
}
toolchains[artifact] = meshcatalogclient.Toolchain2{Language: language, Version: used.Version, Recipe: used.Recipe}
}
f := formOf(module, k.held.Repository, &kept, toolchains, k.held, held, published, pins, heads, nil)
f := formOf(module, k.held.Repository, &kept, toolchains, k.held, held, published, pins, nil)
if f.none != "" || f.fp == "" {
return "", nil, false
}
@@ -636,38 +636,56 @@ func (ix *Indexer) Repin(ctx context.Context, module, version string) (int, erro
}
named := 0
for _, branch := range branches {
x := ix
if !isTrunkBranch(branch) {
view, nodes, _, err := BranchView(ctx, ix.Revisions, branch)
if err != nil {
return named, err
}
d := ix.dry()
d.ix.Modules, d.ix.Graph, d.ix.Taken = view, nodes, newOverlay(nil)
d.ix.Logf = func(format string, args ...any) { ix.logf("re-pin of "+branch+": "+format, args...) }
x = d.ix
}
only, err := x.repinned(ctx, module)
n, err := ix.repinBranch(ctx, branch, module, version)
named += n
if err != nil {
return named, err
}
if len(only) == 0 {
continue
}
named += len(only)
x.recompute.Lock()
err = x.recomputeLocked(ctx, nil, nil, "", only)
x.recompute.Unlock()
if err != nil {
return named, err
}
if err := ix.keepRepinned(ctx, x, branch, releaseCall(module, version), only); err != nil {
return named, err
}
}
return named, nil
}
// repinBranch re-pins branch's importers of module at version (repinModules).
func (ix *Indexer) repinBranch(ctx context.Context, branch, module, version string) (int, error) {
return ix.repinModules(ctx, branch, []string{module}, releaseCall(module, version))
}
// repinModules re-pins branch's importers of modules in one revision kept with call: the trunk in place, another branch
// as a dry run over its revision view, whose scratch goes once it is kept (design 47 H2 §804, §805). It answers how many
// modules it named.
func (ix *Indexer) repinModules(ctx context.Context, branch string, modules []string, call revisionCall) (int, error) {
x := ix
if !isTrunkBranch(branch) {
view, nodes, _, err := BranchView(ctx, ix.Revisions, branch)
if err != nil {
return 0, err
}
d := ix.dry(branch, call.Call)
defer d.end(ctx)
d.ix.Modules, d.ix.Graph, d.ix.Taken = view, nodes, newOverlay(nil)
d.ix.Logf = func(format string, args ...any) { ix.logf("re-pin of "+branch+": "+format, args...) }
x = d.ix
}
only := map[string]bool{}
for _, module := range modules {
some, err := x.repinned(ctx, module)
if err != nil {
return 0, err
}
maps.Copy(only, some)
}
if len(only) == 0 {
return 0, nil
}
x.recompute.Lock()
err := x.recomputeLocked(ctx, nil, nil, "", only)
x.recompute.Unlock()
if err != nil {
return len(only), err
}
return len(only), ix.keepRepinned(ctx, x, branch, call, only)
}
// repinned are the modules the indexer's modules state holds whose packages name a package of module: by their pins, and
// by their kept requirements, which name a package they hold no pin of yet (design 47 H-A-204, H-A-165, H-A-167).
func (ix *Indexer) repinned(ctx context.Context, module string) (map[string]bool, error) {
@@ -208,7 +208,7 @@ func theBuildModuleOfALanguageIsTheHolderOfItsBuildSeat(t *testing.T) {
t.Errorf("two seats building go and two holders of node-build-node: %+v %q, want none, both said", by, problems)
}
// The indexer finds them among the manifests it holds, and a report of a module that holds no build seat is left out.
builder := `{"module":"go-builds","version":"1","claims":[{"name":"node-build-go"}],"streams":[{"name":"toolchains-go","events":["toolchain.**"]}]}`
builder := `{"module":"go-builds","version":"1","class":"core","claims":[{"name":"node-build-go"}],"streams":[{"name":"toolchains-go","events":["toolchain.**"]}]}`
ix, _ := newFormIndexer(t, mod{"avahi", catalogueManifest(t, "avahi")}, mod{"go-builds", builder})
ix.UseBuildModules(nil)
got, err := ix.BuildModulesNow(context.Background(), defs)
@@ -395,10 +395,11 @@ func releasedPins(versions sdkstep.PackageVersions, series map[string]SeriesPack
}
out[p] = ""
for _, s := range series {
if s.GoModule != p || s.Newest == nil || s.Series != m.AcceptedSeries(s.Name) {
pinned := pinnedVersion(s)
if s.GoModule != p || pinned == nil || s.Series != m.AcceptedSeries(s.Name) {
continue
}
v := strings.TrimPrefix(s.Newest.Version, "v")
v := strings.TrimPrefix(pinned.Version, "v")
if _, ok := versionParts(v); ok && (out[p] == "" || compareVersions(v, strings.TrimPrefix(out[p], "v")) > 0) {
out[p] = "v" + v
}
@@ -87,10 +87,12 @@ var busTemplates = map[string]busTemplate{
},
catalogue.TemplateObjects: {
storage: catalogue.StorageObjectStore,
fixed: "what happens when full (a new object is refused) and that objects are kept for good",
fixed: "what happens when full (a new object is refused)",
// max-age-days is how long the bus keeps an object; absent, objects are kept for good (design 47 H2 §820; H-A-434).
options: map[string]optionRule{
catalogue.OptionCapMiB: {kind: optionInt, least: catalogue.ObjectsLeastMiB, most: catalogue.ObjectsMostMiB, required: true},
catalogue.OptionGrant: {kind: optionText},
catalogue.OptionCapMiB: {kind: optionInt, least: catalogue.ObjectsLeastMiB, most: catalogue.ObjectsMostMiB, required: true},
catalogue.OptionAgeDays: {kind: optionInt, least: 1, most: 3650},
catalogue.OptionGrant: {kind: optionText},
},
},
catalogue.TemplateLedger: {
@@ -27,7 +27,7 @@ func TestBusStateIsJudgedOnce(t *testing.T) {
// 1966/AC8: a state, a log, objects and a ledger within bounds
{"within bounds", manifest(`{"name":"cache","storage":"key-value","template":"state","options":{"history":8,"key-ttl":true}},` +
`{"name":"audit","storage":"stream","template":"log","options":{"max-mib":64,"max-age-days":365}},` +
`{"name":"files","storage":"object-store","template":"objects","options":{"max-mib":2048}},` + ledger), nil},
`{"name":"files","storage":"object-store","template":"objects","options":{"max-mib":2048,"max-age-days":7}},` + ledger), nil},
// Design 47: every kept data may say its form and its catch-up tool, in an old section and in `requires` by template,
// and is accepted as read; one saying neither reads as before.
{"a form and a catch-up tool on every kept kind", `{"module":"a","version":"1.0","tools":["a_take_in"],` +
@@ -60,6 +60,7 @@ func TestBusStateIsJudgedOnce(t *testing.T) {
{"deliveries 11", manifest(`{"name":"x","storage":"stream","template":"work-queue","options":{"events":["job"],"max-deliveries":11}}`), []string{"\"x\"", "\"max-deliveries\" is 11", "1 to 10"}},
{"duplicates past the age", manifest(`{"name":"x","storage":"stream","template":"work-queue","options":{"events":["job"],"max-age-days":1,"duplicates":86401}}`), []string{"\"x\"", "\"duplicates\"", "longer than the queue's age of 1 days"}},
{"log age 3651", manifest(`{"name":"x","storage":"stream","template":"log","options":{"max-age-days":3651}}`), []string{"\"x\"", "\"max-age-days\" is 3651"}},
{"objects age 3651 (H2 §820)", manifest(`{"name":"x","storage":"object-store","template":"objects","options":{"max-mib":64,"max-age-days":3651}}`), []string{"\"x\"", "\"max-age-days\" is 3651"}},
{"objects without a cap", manifest(`{"name":"x","storage":"object-store","template":"objects"}`), []string{"\"x\"", "\"max-mib\" is missing"}},
{"when full given as an option", manifest(`{"name":"x","storage":"stream","template":"log","options":{"when-full":"drop-oldest"}}`), []string{"\"x\"", "\"when-full\"", "fixed"}},
// A-277: a state's max-mib is an option of its template; an approvals state is §677's (key-ttl, 48 hours, at most 64 MiB).
@@ -2,6 +2,7 @@ package judge
import (
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"regexp"
"strings"
"testing"
@@ -9,6 +10,9 @@ import (
// Design 47 G §368, §386, §387, §89: the manifest validator reads the manifests' new words before any manifest uses them.
func TestTheJudgeReadsMilestoneGsWords(t *testing.T) {
was := deliverySeats.Load()
useDeliverySeats([]seatdef.Definition{{Seat: "thing", Domain: deliveryDomain}})
t.Cleanup(func() { deliverySeats.Store(was) })
for _, row := range []struct {
name string
raw string
@@ -33,12 +37,24 @@ func TestTheJudgeReadsMilestoneGsWords(t *testing.T) {
`"streams":[{"name":"a-findings","events":["finding-written"],"retention":"history"}],"consumes":["mesh-conditions.findings-asked"]}`, want: "old sections"},
{name: "another part's findings in its requires (§529)", raw: `{"module":"a","version":"1.0","consumes":["mesh-conditions.findings-asked"],"requires":[` +
`{"name":"findings","storage":"key-value","template":"state"},` +
`{"name":"finding-events","storage":"stream","template":"events","options":{"events":["finding-written.*","finding-cleared.*","findings-stated.*"],"max-age-days":7,"max-mib":16}}]}`},
`{"name":"finding-events","storage":"stream","template":"events","options":{"events":["finding-written.*","finding-cleared.*","findings-stated.*"],"max-age-days":7,"max-mib":8}}]}`},
{name: "another part's findings without the finding events (§529)", raw: `{"module":"a","version":"1.0","consumes":["mesh-conditions.findings-asked"],"requires":[` +
`{"name":"findings","storage":"key-value","template":"state"}]}`, want: "finding-events"},
{name: "another part's finding events not kept 7 days (§529)", raw: `{"module":"a","version":"1.0","consumes":["mesh-conditions.findings-asked"],"requires":[` +
`{"name":"findings","storage":"key-value","template":"state"},` +
`{"name":"finding-events","storage":"stream","template":"events","options":{"events":["finding-written.*","finding-cleared.*","findings-stated.*"],"max-age-days":30,"max-mib":16}}]}`, want: "max-age-days"},
`{"name":"finding-events","storage":"stream","template":"events","options":{"events":["finding-written.*","finding-cleared.*","findings-stated.*"],"max-age-days":30,"max-mib":8}}]}`, want: "max-age-days"},
{name: "another part's finding events of 16 MiB (H2 §820, H-A-411 (1))", raw: `{"module":"a","version":"1.0","consumes":["mesh-conditions.findings-asked"],"requires":[` +
`{"name":"findings","storage":"key-value","template":"state"},` +
`{"name":"finding-events","storage":"stream","template":"events","options":{"events":["finding-written.*","finding-cleared.*","findings-stated.*"],"max-age-days":7,"max-mib":16}}]}`, want: "max-mib"},
{name: "a delivery module's uncapped old-section state (H2 §814)", raw: `{"module":"d","version":"1.0","class":"core","claims":[{"name":"thing","scope":"mesh"}],"state":["s"]}`, want: `state "s" in its old section names none`},
{name: "a delivery module's uncapped state in requires (H2 §814)", raw: `{"module":"d","version":"1.0","class":"core","claims":[{"name":"thing","scope":"mesh"}],` +
`"requires":[{"name":"s","storage":"key-value","template":"state"}]}`, want: `state "s" in ` + "`requires`"},
{name: "a delivery module's uncapped objects (H2 §814)", raw: `{"module":"d","version":"1.0","class":"core","claims":[{"name":"thing","scope":"mesh"}],"objects":[{"name":"o"}]}`, want: `objects "o"`},
{name: "a foundation part's capped old-section state (H2 §814)", raw: `{"module":"mesh-delivery-builder","version":"1.0","class":"core","claims":[{"name":"thing","scope":"mesh"}],"state":[{"name":"s","max-mib":8}]}`},
{name: "an uncapped state of a module claiming no delivery seat (H2 §814)", raw: `{"module":"a","version":"1.0","state":["s"]}`},
{name: "a seat-claiming manifest with no class (H2 §810, §814)", raw: `{"module":"d","version":"1.0","claims":[{"name":"thing","scope":"mesh"}]}`, want: "no `class`"},
{name: "a seat-claiming manifest of another class (H2 §810, §814)", raw: `{"module":"d","version":"1.0","class":"middle","claims":[{"name":"thing","scope":"mesh"}]}`, want: `class "middle"`},
{name: "a seat-claiming leaf (H2 §810)", raw: `{"module":"d","version":"1.0","class":"leaf","claims":[{"name":"thing","scope":"mesh"}]}`},
} {
module := "a"
if m := regexp.MustCompile(`"module":"([a-z-]+)"`).FindStringSubmatch(row.raw); m != nil {
@@ -88,7 +88,8 @@ func gWordsProblems(m catalogue.Manifest) []string {
}
// findingEventsProblems judges the entry `finding-events` of a part that is no foundation part: it lists the three finding
// events in its option `events` and keeps them 7 days and 16 MiB (design 47 G §529).
// events in its option `events` and keeps them 7 days and 8 MiB (design 47 G §529, H2 §820; H-A-411 (1)); the template
// `events` drops the oldest when full.
func findingEventsProblems(module string, e catalogue.BusStateEntry) []string {
var problems []string
var listed []string
@@ -100,9 +101,9 @@ func findingEventsProblems(module string, e catalogue.BusStateEntry) []string {
problems = append(problems, fmt.Sprintf("%s's %s does not list the event %q in its `events` (design 47 G §529)", module, FindingEventsEntry, want))
}
}
for option, want := range map[string]string{"max-age-days": "7", "max-mib": "16"} {
for option, want := range map[string]string{"max-age-days": "7", "max-mib": "8"} {
if got := strings.TrimSpace(string(e.Options[option])); got != want {
problems = append(problems, fmt.Sprintf("%s's %s sets %s to %q, not %s (design 47 G §529)", module, FindingEventsEntry, option, got, want))
problems = append(problems, fmt.Sprintf("%s's %s sets %s to %q, not %s (design 47 G §529, H2 §820)", module, FindingEventsEntry, option, got, want))
}
}
slices.Sort(problems)
@@ -290,6 +290,7 @@ func UseSeatList(defs []seatdef.Definition) {
seatsMu.Lock() // not while a pass judges with seats put over the list (WithSeats)
defer seatsMu.Unlock()
catalogue.UseSeats(catalogue.SeatsFromDefinitions(defs))
useDeliverySeats(defs)
}
// TrunkCase is the case of a request holding the catalogue as the trunk holds it (the checker's JudgeTrunk).
@@ -43,7 +43,7 @@ func TestTheJudge(t *testing.T) {
{name: "a claimed seat's module with tools of its own",
raws: map[string]string{
"def": `{"module":"def","version":"1.0","seats":[{"name":"enrolment","scope":"mesh","serves":["issue","again"]}]}`,
"enrolment": `{"module":"enrolment","version":"1.0","claims":[{"name":"enrolment","scope":"mesh","serves":["issue","again"]}],` +
"enrolment": `{"module":"enrolment","version":"1.0","class":"core","claims":[{"name":"enrolment","scope":"mesh","serves":["issue","again"]}],` +
`"tools":["enrolment_first_views","enrolment_first_view_again"]}`}},
} {
raws := map[string][]byte{"node-engine": []byte(engineManifest("node-engine"))} // a revision has one claim of the seat node-engine (§527)
@@ -185,7 +185,7 @@ func engineManifest(module string) string {
for _, v := range seat.Serves {
verbs = append(verbs, `"`+v.Name+`"`)
}
return `{"module":"` + module + `","version":"1.0","claims":[{"name":"node-engine","scope":"node","serves":[` + strings.Join(verbs, ",") + `]}]}`
return `{"module":"` + module + `","version":"1.0","class":"core","claims":[{"name":"node-engine","scope":"node","serves":[` + strings.Join(verbs, ",") + `]}]}`
}
// Design 47 G §508, §527: one module of a revision claims the seat node-engine; a second is refused naming both, and none
@@ -2599,6 +2599,8 @@ func parseManifest(raw []byte, predefined catalogue.PredefinedList) (catalogue.M
m.SetPredefined(predefined)
problems := gWordsProblems(m)
problems = append(problems, deliveryStoreProblems(m)...)
problems = append(problems, classProblems(m)...)
if !name.MatchString(m.Module) {
problems = append(problems, fmt.Sprintf(
"%q is not a usable module name: lower-case letters, digits, dashes and dots", m.Module))
@@ -261,7 +261,7 @@ func caseAClaimOnASeatAnotherModuleDeclaresIsAccepted(t *testing.T) {
// would say it where no consumer hears it, so the manifest is refused, naming the seat's subject; the seat's
// holder saying nothing of its own is accepted.
holder := func(emits string) []byte {
return []byte(`{"module":"mesh-self-check","version":"1.0","emits":` + emits + `,"claims":[{"name":"mesh-self-check","scope":"mesh","serves":["doctor","probes"]}]}`)
return []byte(`{"module":"mesh-self-check","version":"1.0","emits":` + emits + `,"class":"core","claims":[{"name":"mesh-self-check","scope":"mesh","serves":["doctor","probes"]}]}`)
}
if _, err := ParseManifest(holder(`["checked"]`)); err == nil || !strings.Contains(err.Error(), "mesh.seat.mesh-self-check.event.checked") {
t.Errorf("a seat's event listed as the module's own: %v", err)
@@ -383,7 +383,7 @@ func caseAContributionPlaceholderOutsideTheHolderIsRefused(t *testing.T) {
if _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), "laptop does not claim node-hotkeys") {
t.Errorf("a placeholder outside the holder was accepted: %v", err)
}
raw = `{"module":"triggerhappy","claims":[{"name":"node-hotkeys"}],"resources":[{"id":"t","type":"file","path":"/etc/t","content":"${contribution:node-hotkeys:keys}"}]}`
raw = `{"module":"triggerhappy","class":"core","claims":[{"name":"node-hotkeys"}],"resources":[{"id":"t","type":"file","path":"/etc/t","content":"${contribution:node-hotkeys:keys}"}]}`
if _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), "it receives trigger") {
t.Errorf("a placeholder for a kind the seat does not receive was accepted: %v", err)
}
@@ -508,7 +508,7 @@ func caseADeliveringSeatIsOnlyHeldByAModuleThatProvides(t *testing.T) {
// would be the answer anyway, and every consumer would be sent to it.
// And refused at registration, where the seat set is the store's: what a seat delivers is
// data, so a compiled copy of it may not be what refuses a build (novox/hq ADR 0122).
raw := []byte(`{"module":"thing","version":"1.0","claims":[{"name":"git","scope":"mesh"}]}`)
raw := []byte(`{"module":"thing","version":"1.0","class":"core","claims":[{"name":"git","scope":"mesh"}]}`)
m, err := ParseManifest(raw)
if err != nil {
t.Fatalf("the parser judged what a seat delivers: %v", err)
@@ -723,7 +723,7 @@ func caseAHolderOfNodeFilesDeclaringRunsAsIsRefused(t *testing.T) {
// carry — as the operator's account — is refused at parse.
func caseAHolderOfNodeReadsWithoutAnAccountOfItsOwnIsRefused(t *testing.T) {
_, err := ParseManifest([]byte(`{"module": "reads", "version":"1.0",
"claims": [{"name": "node-reads", "scope": "node"}]}`))
"class":"core","claims":[{"name": "node-reads", "scope": "node"}]}`))
if err == nil || !strings.Contains(err.Error(), "runs-as") || !strings.Contains(err.Error(), "0310") {
t.Errorf("a holder of node-reads without runs-as was not refused for it: %v", err)
}
@@ -745,7 +745,7 @@ func caseAHolderPlacesEveryCombinationOnceWithATemplateThatRendersEveryExample(t
if template != "" {
renders = `,"renders":{"block":` + string(tb) + `}`
}
return `{"module":"a-bar","claims":[{"name":"node-bar"` + renders + `}],"resources":[` + strings.Join(res, ",") + `]}`
return `{"module":"a-bar","class":"core","claims":[{"name":"node-bar"` + renders + `}],"resources":[` + strings.Join(res, ",") + `]}`
}
all := "${contribution:node-bar:block:bar=bottom,place=resources}${contribution:node-bar:block:bar=bottom,place=status}" +
"${contribution:node-bar:block:bar=top,place=resources}${contribution:node-bar:block:bar=top,place=status}"
@@ -1304,7 +1304,7 @@ func caseAModuleDeclaresItsOwnSeatAndHoldsIt(t *testing.T) {
// what it means (novox/hq ADR 0121). But it may not define one in the mesh's own namespace.
func caseAModuleDefinesAndClaimsItsOwnSeat(t *testing.T) {
ok := []byte(`{"module":"showcase","version":"1.0","seats":[{"name":"the-showcase","scope":"node"}],` +
`"claims":[{"name":"the-showcase","scope":"node"}]}`)
`"class":"core","claims":[{"name":"the-showcase","scope":"node"}]}`)
if _, err := ParseManifest(ok); err != nil {
t.Fatalf("a module could not define and claim its own seat: %v", err)
}
@@ -1321,7 +1321,7 @@ func caseAModuleDefinesAndClaimsItsOwnSeat(t *testing.T) {
}
// A module may not carve its seat out of the mesh's own namespace.
bad := []byte(`{"module":"x","version":"1.0","seats":[{"name":"node-mine","scope":"node"}],` +
`"claims":[{"name":"node-mine","scope":"node"}]}`)
`"class":"core","claims":[{"name":"node-mine","scope":"node"}]}`)
if _, err := ParseManifest(bad); err == nil || !strings.Contains(err.Error(), "own namespace") {
t.Fatalf("a module defined a seat in the mesh's namespace and was not refused: %v", err)
}
@@ -2266,14 +2266,14 @@ func caseAnUnknownPlaceholderKeyIsRefused(t *testing.T) {
{"${shell:tcsh:first}", "names ${shell:tcsh:first}; shell code is ${shell:<shell>:<slot>}"},
{"${shell:zsh}", "names ${shell:zsh}; shell code is ${shell:<shell>:<slot>}"},
} {
raw := `{"module":"holder","claims":[{"name":"node-environment","scope":"node"},{"name":"node-login-shell","scope":"node"}],` +
raw := `{"module":"holder","class":"core","claims":[{"name":"node-environment","scope":"node"},{"name":"node-login-shell","scope":"node"}],` +
`"resources":[{"id":"rc","type":"file","path":"/etc/rc","content":"` + c.content + `"}]}`
if _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s was accepted: %v", c.content, err)
}
}
// And outside a file's content, where nothing could be placed.
raw := `{"module":"holder","claims":[{"name":"node-environment","scope":"node"}],` +
raw := `{"module":"holder","class":"core","claims":[{"name":"node-environment","scope":"node"}],` +
`"resources":[{"id":"rc","type":"file","path":"/etc/${environment:posix}","content":"x"}]}`
if _, err := ParseManifest([]byte(raw)); err == nil ||
!strings.Contains(err.Error(), "names ${environment:posix} in its path; the environment and the shell's code are placed only in a file's content") {
@@ -2408,7 +2408,7 @@ func caseAPackageParsesLikeABundleAndNeedsALanguage(t *testing.T) {
} {
raw := `{"module":"a","version":"1.0","build":{"artifacts":[` + c.artifact + `]}}`
if before, ok := strings.CutSuffix(c.artifact, claims); ok {
raw = `{"module":"a","version":"1.0","claims":[{"name":"mesh-vault","scope":"mesh"}],"build":{"artifacts":[` + before + `]}}`
raw = `{"module":"a","version":"1.0","class":"core","claims":[{"name":"mesh-vault","scope":"mesh"}],"build":{"artifacts":[` + before + `]}}`
}
_, err := ParseManifest([]byte(raw))
switch {
@@ -2560,7 +2560,7 @@ func caseAProcessBusNamesOnlyTheModulesOwn(t *testing.T) {
func caseAProcessBusNeverServesOrHoldsASeat(t *testing.T) {
for name, c := range map[string]struct{ bus, says string }{
"holds": {`{"emits":["mail.send.sent"],"holds":["mail-sender"]}`, "holds"},
"claims": {`{"emits":["mail.send.sent"],"claims":["mail-sender"]}`, "claims"},
"claims": {`{"emits":["mail.send.sent"],"class":"core","claims":["mail-sender"]}`, "claims"},
"seat": {`{"emits":["mail.send.sent"],"seat":"mail-sender"}`, "seat"},
} {
_, err := ParseManifest([]byte(mailSenderProcessManifest(t, c.bus)))
@@ -2610,7 +2610,7 @@ func caseAProcessDeclaresItsBusAndIsAccepted(t *testing.T) {
// process's, named after its binary and kept through resolution; a removal is from the closed set, alone, and the
// bus module's (mesh-broker) alone.
toolsIn := func(claims, bus, mode, where string) string {
return `{"module":"nats","version":"1.0","claims":` + claims + `,"own-secrets":{"broker":"${dir:mesh-state}/broker",` +
return `{"module":"nats","version":"1.0","class":"core","claims":` + claims + `,"own-secrets":{"broker":"${dir:mesh-state}/broker",` +
`"broker-nats-tools":"${dir:tools-secret}/broker-nats-tools"},"resources":[{"id":"mesh-state","type":"directory",` +
`"mode":"0700","place":"mesh","unknown":"program"},{"id":"tools-secret","type":"directory","mode":"` + mode +
`","path":"` + where + `","unknown":"program"}],"build":{"artifacts":[{"name":"tools","kind":"bundle",` +
@@ -3276,10 +3276,10 @@ func caseAManifestCarryingWaitsIsAFieldNotKnown(t *testing.T) {
func caseAMarkNothingEnforcesIsRefused(t *testing.T) {
const bundle = `"build":{"artifacts":[{"name":"tools","kind":"bundle","language":"typescript","entrypoints":["tools/index.js"]}]}`
const oc = `"uses":["operator-channel"]`
shell := `{"module":"zsh","claims":[{"name":"node-login-shell","scope":"node","serves":["execute"]}],"tools":["zsh_config"],` + bundle
shell := `{"module":"zsh","class":"core","claims":[{"name":"node-login-shell","scope":"node","serves":["execute"]}],"tools":["zsh_config"],` + bundle
for _, row := range []struct{ name, manifest, want string }{
{"a tool its tools do not list", `{"module":"shop","tools":["sell"],"needs-approval":["refund"],` + oc + `,` + bundle + `}`, "its tools do not list"},
{"a verb its claims do not serve", `{"module":"shop","claims":[{"name":"shop-till","serves":["price"]}],"tools":["price"],"needs-approval":["shop-till.refund"],` + oc + `,` + bundle + `}`, "does not serve"},
{"a verb its claims do not serve", `{"module":"shop","class":"core","claims":[{"name":"shop-till","serves":["price"]}],"tools":["price"],"needs-approval":["shop-till.refund"],` + oc + `,` + bundle + `}`, "does not serve"},
{"a marked tool without operator-channel", `{"module":"shop","tools":["sell"],"needs-approval":["sell"],` + bundle + `}`, "without operator-channel"},
{"a held seat verb its seat marks without operator-channel", shell + `}`, "without operator-channel"},
{"every bundle run by its own process", `{"module":"shop","tools":["sell"],"needs-approval":["sell"],` + oc + `,` + bundle +
@@ -4130,7 +4130,7 @@ func caseNodeBuildAgentIsRetiredForTheBuildSeats(t *testing.T) {
t.Errorf("the mesh still defines %s", gone)
}
}
_, err := ParseManifest([]byte(`{"module":"build-agent","version":"1.0","claims":[{"name":"node-build-agent","scope":"node"}]}`))
_, err := ParseManifest([]byte(`{"module":"build-agent","version":"1.0","class":"core","claims":[{"name":"node-build-agent","scope":"node"}]}`))
if err == nil || !strings.Contains(err.Error(), `"node-build-agent", which is retired`) || !strings.Contains(err.Error(), "node-build-go") {
t.Fatalf("the claim is not refused naming its replacement: %v", err)
}
@@ -4147,12 +4147,16 @@ func caseNodeBuildAgentIsRetiredForTheBuildSeats(t *testing.T) {
if !s.Yields {
t.Errorf("%s does not yield (ADR 0553)", name)
}
// The seat's definition is the catalogue's (mesh-contracts'), and it serves more than these since (drop,
// kept-artifact, steps, output, answer): the retirement holds current, pause and resume among them.
var verbs []string
for _, v := range s.Serves {
verbs = append(verbs, v.Name)
}
if strings.Join(verbs, ",") != "current,pause,resume" {
t.Errorf("%s serves %v", name, verbs)
for _, want := range []string{"current", "pause", "resume"} {
if !slices.Contains(verbs, want) {
t.Errorf("%s serves %v, without %s", name, verbs, want)
}
}
}
// The build seats are the seats that yield, and no other (ADR 0553 §1).
@@ -4193,7 +4197,7 @@ func caseNoModuleMayDeclareTheLoginShell(t *testing.T) {
}
// And a shell module claiming the mesh's seat, serving execute, is what the seat is for.
m, err := ParseManifest([]byte(`{"module":"zsh","tools":["execute"],"uses":["operator-channel"],` +
`"claims":[{"name":"node-login-shell","scope":"node"}]}`))
`"class":"core","claims":[{"name":"node-login-shell","scope":"node"}]}`))
if err != nil {
t.Fatal(err)
}
@@ -4302,13 +4306,13 @@ func caseOnlyChannelAndIntakeAreKinded(t *testing.T) {
}
// The indexer and the builder hold no published list of predefined keys; a manifest whose config values fall back to
// one (claude-code, dunst, xterm at mesh-catalog 835bf22b) is still read for its build's and fingerprint's inputs
// one (claude-code, dunst, xterm at mesh-catalog 30a3e665) is still read for its build's and fingerprint's inputs
// (issue 1751).
func caseParseManifestForInputsReadsAValueFallingBackToAPredefinedKey(t *testing.T) { // issue 1751
was := catalogue.ReplacePublished(nil) // the indexer's and the builder's case: no published list
defer catalogue.ReplacePublished(was)
for _, module := range []string{"claude-code", "dunst", "xterm"} {
raw, err := os.ReadFile("testdata/catalogue-835bf22b-" + module + ".module.json")
raw, err := os.ReadFile("testdata/catalogue-30a3e665-" + module + ".module.json")
if err != nil {
t.Fatal(err)
}
@@ -4506,7 +4510,7 @@ func caseAStoreHolderThatBuildsIsNotRefusedByItsManifest(t *testing.T) {
// nothing, so it is refused at the parser rather than silently dropped.
func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
raw := []byte(`{"module":"bus","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh"}],
"claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"emits":["something.happened"]}`)
_, err := ParseManifest(raw)
if err == nil || !strings.Contains(err.Error(), "granted the bus's snapshot API and nothing else") {
@@ -4514,7 +4518,7 @@ func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
}
// Nor what it invokes, with no bundle for the runtime to ask on its behalf.
unbundledInvoke := []byte(`{"module":"bus","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh"}],
"claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"invokes":["seat:mesh-hand-acts.hand-act"]}`)
if _, err := ParseManifest(unbundledInvoke); err == nil || !strings.Contains(err.Error(), "its invokes would be granted nothing") {
t.Fatalf("a bus module with no bundle declaring what it invokes was not refused, or not for the reason: %v", err)
@@ -4525,7 +4529,7 @@ func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
// ships one may declare them. The shape of mesh-catalog's modules/nats/module.json at fc5b849d, cut to the
// parts the rule reads, was refused and held every bus user list from 2026-11-02 01:35.
nats := []byte(`{"module":"nats","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh","credential":{"form":"none"}}],
"claims":[{"name":"mesh-broker","scope":"mesh"}],
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}],
"own-secrets":{"broker":"/run/broker","broker-nats-tools":"${dir:tools-secret}/broker-nats-tools"},
"resources":[{"id":"tools-secret","type":"directory","path":"/var/lib/mesh/nats-tools","mode":"0711","unknown":"program"}],
"emits":["consumer-removed","bucket-keys-removed","stream-removed","bucket-expiry-set"],
@@ -4551,7 +4555,7 @@ func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
// Its tools bundle says what it emits (novox/hq ADR 0357): the node's runtime carries the bundle and is
// granted the module's events, so a bus module that ships one may declare them.
bundled := []byte(`{"module":"bus","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh"}],
"claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"emits":["bus.slow-consumer"],"tools":["bus_streams"],
"build":{"artifacts":[{"name":"tools","kind":"bundle","language":"go","system":"arch","from":"cmd/t","binary":"t"}]}}`)
m, err := ParseManifest(bundled)
@@ -4577,7 +4581,7 @@ func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
// parts the rule reads.
keeper := func(bus string, more string) []byte {
return []byte(`{"module":"nats","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh"}],
"claims":[{"name":"mesh-broker","scope":"mesh","serves":["list"]}],"own-secrets":{"broker":"/run/broker"},
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh","serves":["list"]}],"own-secrets":{"broker":"/run/broker"},
"tools":["nats_server"],"consumes":["mesh-catalog.manifest-accepted"],"uses":["operator-channel"],
"state":[{"name":"requests","history":5}],"streams":[{"name":"broker-events","events":["created"]}],
"emits":["consumer-removed"],
@@ -4621,7 +4625,7 @@ func caseTheBussAccountSaysNothingOnTheBus(t *testing.T) {
}
quiet := []byte(`{"module":"bus","version":"1.0","provides":[{"name":"mesh-bus","scope":"mesh"}],
"claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}],"own-secrets":{"broker":"/run/broker"},
"tools":["bus_streams"]}`)
m, err = ParseManifest(quiet)
if err != nil {
@@ -4974,7 +4978,7 @@ func caseTheParserDoesNotJudgeWhatOnlyTheStoreKnows(t *testing.T) {
catalogue.UseSeats([]catalogue.Seat{{Name: "mesh-broker", Scope: catalogue.ScopeMesh, Delivers: "mesh-bus", Decision: "test"}})
raw := []byte(`{"module":"a-bus","version":"1.0",` +
`"provides":[{"name":"mesh-bus","scope":"mesh","credential":{"form":"none"}}],` +
`"claims":[{"name":"mesh-broker","scope":"mesh"}]}`)
`"class":"core","claims":[{"name":"mesh-broker","scope":"mesh"}]}`)
m, err := ParseManifest(raw)
if err != nil {
@@ -5185,13 +5189,13 @@ func caseTheSessionsFilesArePlacedByTheDisplayServersHolderAlone(t *testing.T) {
{`{"name":"node-display-server"}`, "${shell:zsh:normal}", "does not claim node-login-shell"},
{`{"name":"node-display-server"}`, "${shell:xsession:normal}", "the session's file one of xinitrc, xresources"},
} {
raw := `{"module":"holder","claims":[` + c.claims + `],"resources":[{"id":"rc","type":"file","path":"/etc/rc","content":"` +
raw := `{"module":"holder","class":"core","claims":[` + c.claims + `],"resources":[{"id":"rc","type":"file","path":"/etc/rc","content":"` +
c.content + `"}]}`
if _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s with claims [%s]: want %q, got %v", c.content, c.claims, c.want, err)
}
}
if _, err := ParseManifest([]byte(`{"module":"xorg","claims":[{"name":"node-display-server"}],` +
if _, err := ParseManifest([]byte(`{"module":"xorg","class":"core","claims":[{"name":"node-display-server"}],` +
`"resources":[{"id":"rc","type":"file","path":"/home/op/.xinitrc","content":"${shell:xinitrc:last}"}]}`)); err != nil {
t.Errorf("the display server's holder could not place the session's slots: %v", err)
}
@@ -5259,7 +5263,7 @@ func caseTheUplinkIsANodeSeatThatDeliversNothing(t *testing.T) {
t.Fatalf("the uplink is %+v, not a node seat delivering nothing by ADR 0117", seat)
}
// And a manager's module can hold it without providing anything.
raw := []byte(`{"module":"networkmanager","version":"1.0","claims":[{"name":"node-uplink","scope":"node"}]}`)
raw := []byte(`{"module":"networkmanager","version":"1.0","class":"core","claims":[{"name":"node-uplink","scope":"node"}]}`)
if _, err := ParseManifest(raw); err != nil {
t.Fatalf("a network manager's module could not hold the uplink: %v", err)
}
@@ -5573,7 +5577,7 @@ func problemsFor(t *testing.T, shelf catalogue.Shelf) string {
}
func claimed(claims string) []byte {
return []byte(`{"module":"thing","version":"1.0","provides":[{"name":"npm-package-registry","scope":"mesh","credential":{"form":"none"}}],"claims":` + claims + `}`)
return []byte(`{"module":"thing","version":"1.0","provides":[{"name":"npm-package-registry","scope":"mesh","credential":{"form":"none"}}],"class":"core","claims":` + claims + `}`)
}
func hostnameSeat(t *testing.T) catalogue.Seat {
@@ -6098,7 +6102,7 @@ func mod(name string, provides, requires, capabilities []string, claims ...catal
}
const collectorZsh = `{"module":"zsh","version":"1.0","moved":true,
"claims":[{"name":"node-login-shell","scope":"node"}],
"class":"core","claims":[{"name":"node-login-shell","scope":"node"}],
"collections":[{"name":"widgets","comment":"#"}],
"build":{"artifacts":[{"name":"files","kind":"archive","from":"files"}]},
"resources":[{"id":"rc","type":"file","path":"${machine:account-home}/.zshrc","owner":"${machine:account}",
@@ -6660,7 +6664,7 @@ func caseOneModuleClaimsTheNodeEnginesSeat(t *testing.T) {
t.Cleanup(func() { catalogue.UseSeats(was) })
catalogue.UseSeats([]catalogue.Seat{{Name: NodeEngineSeat, Scope: catalogue.ScopeNode, Decision: "test", HeldByTheEngine: true}})
engine := func(module string) []byte {
return []byte(`{"module":"` + module + `","version":"1.0","claims":[{"name":"node-engine","scope":"node"}]}`)
return []byte(`{"module":"` + module + `","version":"1.0","class":"core","claims":[{"name":"node-engine","scope":"node"}]}`)
}
for _, row := range []struct {
name string
@@ -0,0 +1,79 @@
package judge
import (
"fmt"
"slices"
"sync/atomic"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// The manifest check of design 47 H2 §814 and §810: every kept store of a delivery module names its cap (§812), and a
// module that claims a seat names its class (H-A-394 (1), H-A-411 (4)).
// deliveryDomain is the glossary domain of the delivery system's seats, as a seat definition names it (seatdef.Domains).
const deliveryDomain = "Delivery"
// deliverySeats are the seats of the seat list the judge judges against whose definition is of the delivery system,
// by name: set with the list (UseSeatList), read by deliveryStoreProblems.
var deliverySeats atomic.Pointer[map[string]bool]
// useDeliverySeats keeps the delivery system's seats of defs (deliverySeats).
func useDeliverySeats(defs []seatdef.Definition) {
seats := map[string]bool{}
for _, d := range defs {
if d.Domain == deliveryDomain {
seats[d.Seat] = true
}
}
deliverySeats.Store(&seats)
}
// deliverySeatOf is the first seat of the delivery system m claims, by the seat list's definitions; "" for none.
func deliverySeatOf(m catalogue.Manifest) string {
seats := deliverySeats.Load()
if seats == nil {
return ""
}
for _, c := range m.Claims {
if (*seats)[c.Name] {
return c.Name
}
}
return ""
}
// deliveryStoreProblems refuses each state, log and objects entry of a delivery module (one whose manifest claims a seat
// of the delivery system) that names no cap, in its old section or in `requires` alike (design 47 H2 §812, §814): a
// foundation part's old-section entry names its cap in that section.
func deliveryStoreProblems(m catalogue.Manifest) []string {
seat := deliverySeatOf(m)
if seat == "" {
return nil
}
var problems []string
for _, u := range m.UncappedStores() {
where := "in `requires`"
if u.OldSection {
where = "in its old section"
}
problems = append(problems, fmt.Sprintf("%s claims the seat %s of the delivery system, so every store it keeps names its cap; "+
"its %s %q %s names none (design 47 H2 §812, §814)", m.Module, seat, u.Kind, u.Name, where))
}
return problems
}
// classProblems refuses a manifest that claims a seat and names no class, or a class that is neither core nor leaf
// (design 47 H2 §810, §814; H-A-394 (1)).
func classProblems(m catalogue.Manifest) []string {
if len(m.Claims) == 0 || slices.Contains([]string{catalogue.ClassCore, catalogue.ClassLeaf}, m.Class) {
return nil
}
if m.Class == "" {
return []string{fmt.Sprintf("%s claims a seat and names no `class`; a module that claims a seat names `class` %s or %s "+
"(design 47 H2 §810, §814)", m.Module, catalogue.ClassCore, catalogue.ClassLeaf)}
}
return []string{fmt.Sprintf("%s names the class %q; a class is %s or %s (design 47 H2 §810, §814)", m.Module, m.Class,
catalogue.ClassCore, catalogue.ClassLeaf)}
}
@@ -1,6 +1,7 @@
{
"module": "claude-code",
"version": "1",
"version": "0.1",
"class": "leaf",
"moved": true,
"slug": "agent",
"capabilities": [
@@ -11,6 +12,25 @@
{
"name": "gitea-read",
"optional": true
},
{
"name": "finding-events",
"storage": "stream",
"template": "events",
"options": {
"events": [
"finding-written.*",
"finding-cleared.*",
"findings-stated.*"
],
"max-age-days": 7,
"max-mib": 8
}
},
{
"name": "findings",
"storage": "key-value",
"template": "state"
}
],
"binds": {
@@ -22,6 +42,31 @@
"uses": [
"operator-channel"
],
"invokes": [
"seat:mesh-hand-acts.warranted",
"seat:mesh-hand-acts.hand-act",
"seat:mesh-catalog.seat-definitions",
"seat:mesh-catalog.revision",
"seat:mesh-catalog.registrations",
"seat:mesh-delivery.source",
"mesh-delivery-assigner.assigner_read_assignments",
"seat:anthropic-licence-manager.bindings",
"seat:anthropic-licence-manager.current",
"seat:mesh-vault.get",
"seat:operator-channel.notify"
],
"consumes": [
"mesh-catalog.catalog-revision",
"mesh-catalog.registration-changed",
"mesh-delivery.source-moved",
"mesh-delivery-assigner.views.assignments",
"mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed",
"mesh-conditions.findings-asked",
"claude-licence-manager.holdings.asked",
"claude-licence-manager.binding.changed.*",
"mesh-vault.secret-changed"
],
"state": [
"servers",
"holdings",
@@ -31,13 +76,13 @@
"memory",
"waits"
],
"reads": [
"claude-licence-manager.bindings"
"emits": [
"judged",
"holdings-changed"
],
"tools": [
"claude_code_status",
"claude_code_render",
"claude_code_guard",
"claude_code_pull",
"claude_code_grant",
"claude_code_add_api_key",
@@ -83,7 +128,11 @@
"claude_code_home_removed",
"claude_code_home_restore",
"claude_code_judge",
"claude_code_judged"
"claude_code_judged",
"claude_code_first_views",
"claude_code_first_view_again",
"claude_code_seat_list",
"claude_code_seat_list_again"
],
"data": {
"own": [
@@ -210,7 +259,16 @@
"path": "${dir:state}/settings.json",
"mode": "0600",
"owner": "${machine:account}",
"takes-config": ["role", "mcp_servers", "managed_settings", "instructions", "output_styles", "skills", "commands", "agents"],
"takes-config": [
"role",
"mcp_servers",
"managed_settings",
"instructions",
"output_styles",
"skills",
"commands",
"agents"
],
"merge": "json",
"template": "files/settings.json"
}
@@ -236,7 +294,8 @@
"env": {
"MESH_CLAUDE_CODE_STATE": "${dir:state}",
"MESH_CLAUDE_CODE_FACTS": "${dir:state}/facts.json",
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json"
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json",
"MESH_CLAUDE_CODE_FORGE": "${dir:state}/gitea-read.secret"
}
},
{
@@ -1,6 +1,7 @@
{
"module": "dunst",
"version": "1",
"version": "0.1",
"class": "core",
"moved": true,
"capabilities": [
"package-manager"
@@ -1,6 +1,7 @@
{
"module": "xterm",
"version": "1",
"version": "0.1",
"class": "core",
"moved": true,
"capabilities": [
"package-manager"
+38 -16
View File
@@ -14,6 +14,7 @@ import (
"testing"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein"
"git.novox.be/novox/mesh-sdk/go/busretry"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/views"
@@ -31,6 +32,7 @@ type state struct {
History int `json:"history,omitempty"`
KeyTTL bool `json:"key-ttl,omitempty"`
MaxMiB int `json:"max-mib,omitempty"`
TTL int `json:"ttl-seconds,omitempty"`
}
type artifact struct {
@@ -57,6 +59,7 @@ type stream struct {
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Class string `json:"class"` // core, as it claims a seat (design 47 H2 §810, §814; H-A-394 (1))
Slug string `json:"slug"`
RunsAs string `json:"runs-as"`
Streams []stream `json:"streams"`
@@ -71,6 +74,7 @@ type manifest struct {
Scope string `json:"scope"`
Serves []string `json:"serves"`
} `json:"claims"`
Config map[string]any `json:"config"` // the settings (design 47 H2 §805)
Tools []string `json:"tools"`
Emits []string `json:"emits"`
Consumes []string `json:"consumes"`
@@ -132,22 +136,29 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
if !slices.Equal(m.Uses, []string{"operator-channel"}) || !slices.Contains(m.Invokes, "seat:mesh-module-assigner.assignments") || !slices.Contains(m.Invokes, "seat:mesh-module-assigner.placement") {
t.Errorf("uses = %v, invokes = %v, want the seat operator-channel used and seat:mesh-module-assigner.assignments invoked", m.Uses, m.Invokes)
}
// 1126 note 76: heard keeps the last 64 FORGE messages the indexer handled, for indexer_heard.
if want := []state{{Name: "candidates", History: 10}, {Name: "heard", History: 64}, {Name: "manifests", History: 1}, {Name: "predefined", History: 5}, {Name: "taken", History: 1}, {Name: "takeins", History: 1}, {Name: "oldsections", History: 1}, {Name: index.RunsState, History: 1}, {Name: index.PackagesState, History: index.PackagesHistory},
{Name: views.MarksState, History: 1}, {Name: index.FindingsState, History: 5}, {Name: views.StatusState, History: 1},
{Name: index.RequirementsState, History: 5}, {Name: index.SeatDefinitionsState, History: 5},
// 1126 note 76: heard keeps the last 64 FORGE messages the indexer handled, for indexer_heard; 8 MiB, each reservation
// and each gathering of them a key of its own time to live (design 47 H2 §805, H-A-420 (3), H-A-436).
// Design 47 H2 §814, §820 (H-A-411 (2), H-A-437): every state names its cap, 8 MiB where the live fill (novox, 2026-11-22)
// is a quarter of it or less, else the smallest power of two above four times the fill: candidates 3.78 MiB at 16,
// manifests 5.21 MiB and seat-definitions 4.19 MiB at 32.
if want := []state{{Name: "candidates", History: 10, MaxMiB: 16}, {Name: "heard", History: 64, MaxMiB: 8, KeyTTL: true}, {Name: "manifests", History: 1, MaxMiB: 32}, {Name: "predefined", History: 5, MaxMiB: 8}, {Name: "taken", History: 1, MaxMiB: 8}, {Name: "takeins", History: 1, MaxMiB: 8}, {Name: "oldsections", History: 1, MaxMiB: 8}, {Name: index.RunsState, History: 1, MaxMiB: 8}, {Name: index.PackagesState, History: index.PackagesHistory, MaxMiB: 8},
{Name: views.MarksState, History: 1, MaxMiB: 8}, {Name: index.FindingsState, History: 5, MaxMiB: 8}, {Name: views.StatusState, History: 1, MaxMiB: 8},
{Name: index.RequirementsState, History: 5, MaxMiB: 8}, {Name: index.SeatDefinitionsState, History: 5, MaxMiB: 32},
{Name: index.EntryIndexState, History: 1, MaxMiB: 8}, {Name: index.NamedState, History: 1, MaxMiB: 4}, // design 47 G §695
{Name: index.RegistrationsState, History: 1}, {Name: index.ProposalsState, History: 1, MaxMiB: 4},
{Name: index.VersionsState, History: 1, MaxMiB: 64}, {Name: index.BuildEdgesState, History: 1}, {Name: index.InputsState, History: 1}, {Name: index.PinsState, History: 1, MaxMiB: index.PinsCapMiB}, {Name: index.HeldState, History: 1}}; !reflect.DeepEqual(m.State, want) { // DLV-I7, DLV-I17
{Name: index.RegistrationsState, History: 1, MaxMiB: 8}, {Name: index.ProposalsState, History: 1, MaxMiB: 4},
{Name: index.VersionsState, History: 1, MaxMiB: 64}, {Name: index.BuildEdgesState, History: 1, MaxMiB: 8}, {Name: index.InputsState, History: 1, MaxMiB: 8}, {Name: index.PinsState, History: 1, MaxMiB: index.PinsCapMiB}, {Name: index.HeldState, History: 1, MaxMiB: 8},
{Name: index.DryRunsState, History: 1, TTL: 3600, MaxMiB: 16}}; !reflect.DeepEqual(m.State, want) { // DLV-I7, DLV-I17; design 47 H2 §804, §820
t.Errorf("state = %+v, want %+v", m.State, want)
}
// Milestone 47/G W4.2 (design 47, Two graphs; ADR 0619 §2): the catalog graph revisions are objects in the old section,
// capped at 512 MiB, under the local name the indexer opens. W4.14 (design 47, Reverted): their form is 1. Design 47 H
// §742 (H-A-105): no catch-up tool of the indexer's follows a restore, indexer_take_in having gone with the builder-log
// index; the gate's gate_head_take is the one hand take of a head.
if len(m.Objects) != 1 || m.Objects[0].Name != index.CatalogRevisionsObjects || m.Objects[0].MaxMiB != 512 ||
m.Objects[0].Form != 1 || m.Objects[0].CatchUp != "" {
t.Errorf("objects = %+v, want %s capped at 512 MiB, form 1, no catch-up tool", m.Objects, index.CatalogRevisionsObjects)
// Design 47 H2 §814, §820 (H-A-441): the seat lists, one object per digest, 64 MiB, in the old section too.
if len(m.Objects) != 2 || m.Objects[0].Name != index.CatalogRevisionsObjects || m.Objects[0].MaxMiB != 512 ||
m.Objects[0].Form != 1 || m.Objects[0].CatchUp != "" || m.Objects[1].Name != index.SeatListsObjects || m.Objects[1].MaxMiB != 64 {
t.Errorf("objects = %+v, want %s capped at 512 MiB, form 1, no catch-up tool, and %s at 64 MiB", m.Objects,
index.CatalogRevisionsObjects, index.SeatListsObjects)
}
// D-11 (ADR 0634 §1): the holders and buckets the indexer names (internal/index/names.go) are its manifest's: its own
// name and states with their revisions, and the states it reads, each as `<holder>.<state>`.
@@ -171,7 +182,7 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
// "Reads FORGE" is a consumes of the indexer's stream: the broker grants only buckets by reads (mesh-control
// internal/broker/state.go:62-93).
// The registry seats' published fill each (§413: no consume of version.numbered) package's series (DLV-I5, design 51 *The versions*).
if want := []string{"go-package-registry.published", "mesh-build-go.toolchain.reported", "mesh-build-node.toolchain.reported", "mesh-builds.package-published", "mesh-builds.toolchain-agreed", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.room", "mesh-conditions.findings-asked",
if want := []string{"go-package-registry.published", "mesh-build-go.toolchain.reported", "mesh-build-node.toolchain.reported", "mesh-builds.package-published", "mesh-builds.step-ended", "mesh-builds.toolchain-agreed", "mesh-builds.version-reserved", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.room", "mesh-conditions.findings-asked",
"mesh-delivery.source-moved", "mesh-pipeline-runner.pipeline-ended", "mesh-pipeline-runner.pipeline-started", "mesh-pipeline-runner.run-started", "mesh-wants.pipeline-wanted", "mesh-wants.wait-ended", "mesh-wants.wanted", "node-build-go.step-ended", "node-engine.running", "npm-package-registry.published", "operator-channel.decided", "seat:mesh-module-assigner.views.assignments", "seat:mesh-module-assigner.views.seat-holders"}; !reflect.DeepEqual(sorted(m.Consumes), want) {
t.Errorf("consumes = %v, want %v", m.Consumes, want)
}
@@ -206,14 +217,25 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
// milestone 47/G W4.12 (design 47, the indexer's tools): the catalog graph revisions read and steered.
index.CatalogRevisionTool, index.CatalogRevisionsTool, index.CandidateGraphsTool, index.RecomputeTool, index.DropCandidateGraphTool,
index.EntryIndexTool, index.EntryPinsTool, index.NamedDropTool, // design 47 G §675, H-A-204
index.ProposalsTool, index.ProposalDropTool, index.SeedAgainTool, index.InputsTool, index.PinsTool, index.PinDropTool, index.PendingTool, index.TakeInPendingTool, index.TakeInAgainTool, index.TakeInSkipTool, index.RunsTool, index.RunDropTool) // design 47 G §667, §8, §579, §64 (A-194)
if !reflect.DeepEqual(m.Tools, want) || len(want) != 44 || !slices.Contains(m.Tools, "modules") {
index.ProposalsTool, index.ProposalDropTool, index.SeedAgainTool, index.InputsTool, index.PinsTool, index.PinDropTool, index.PendingTool, index.TakeInPendingTool, index.TakeInAgainTool, index.TakeInSkipTool, index.RunsTool, index.RunDropTool, // design 47 G §667, §8, §579, §64 (A-194)
index.DryRunsTool, index.RegistrationsTool) // design 47 H2 §804, §806
if !reflect.DeepEqual(m.Tools, want) || len(want) != 46 || !slices.Contains(m.Tools, "modules") {
t.Errorf("tools = %v, want %v", m.Tools, want)
}
// Design 47 G §2, §9: every version of every registration is kept with no age limit, 64 MiB, on the old streams section.
if len(m.Streams) != 2 || m.Streams[0].Name != index.RegistrationHistoryStream || m.Streams[0].Retention != "history" || m.Streams[0].MaxMiB != 64 ||
m.Streams[1].Name != m.Module+"-findings" || m.Streams[1].MaxAgeDays != 7 || m.Streams[1].MaxMiB != 16 {
t.Errorf("streams = %+v, want registration-history keeping its history, 64 MiB, and the findings stream (§387)", m.Streams)
m.Streams[1].Name != m.Module+"-findings" || m.Streams[1].MaxAgeDays != 7 || m.Streams[1].MaxMiB != 8 {
t.Errorf("streams = %+v, want registration-history keeping its history, 64 MiB, and the findings stream at 8 MiB (§387, H2 §783)", m.Streams)
}
// Design 47 H2 §810, §814 (H-A-394 (1)): it claims a seat, so its class is core. §775: it makes kept calls, so it declares
// the kept-call pace, 1 s to 30 s, read while it runs.
if m.Class != "core" {
t.Errorf("class = %q, want core", m.Class)
}
for key, def := range map[string]string{busretry.PaceFirstSetting: "1s", busretry.PaceMaxSetting: "30s"} {
if c, _ := m.Config[key].(map[string]any); c["default"] != def || c["runtime"] != true || c["type"] != "string" {
t.Errorf("config %s = %v, want a runtime string setting defaulting to %s", key, m.Config[key], def)
}
}
// Design 47 G §368: version is MAJOR.MINOR (0.1 while none is published, §368); §295, §299: the catalog revisions' form and
// the catch-up tool beside it (checked above).
@@ -301,8 +323,8 @@ func TestManifestDeclarations(t *testing.T) { // 1238/AC1, 1444 (reads the build
// ADR 0604 §2, ADR 0636 §4: it holds the seat mesh-catalog, serving its four verbs and seat-definitions from its tools
// bundle (which stays without a request subject); ADR 0663 §1: and revision, in the same runtime of its own.
if len(m.Claims) != 1 || m.Claims[0].Name != index.CatalogSeat || m.Claims[0].Scope != catalogue.ScopeMesh ||
!slices.Equal(m.Claims[0].Serves, []string{"modules", "module", "provides", "dependents", index.SeatDefinitionsVerb, "revision", "entry", "registrations", "register", "policy", "watch", "unwatch", "versions", "outdated", "input"}) {
t.Errorf("claims = %+v, want mesh-catalog with its seven verbs (entry: design 47 G §675)", m.Claims)
!slices.Equal(m.Claims[0].Serves, []string{"modules", "module", "provides", "dependents", index.SeatDefinitionsVerb, "seat-list", "revision", "entry", "registrations", "register", "policy", "watch", "unwatch", "versions", "outdated", "input"}) {
t.Errorf("claims = %+v, want mesh-catalog with its verbs (entry: design 47 G §675; seat-list: H2 §814)", m.Claims)
}
for _, e := range []string{index.SeatDefinitionChangedEvent, index.SeatDefinitionRemovedEvent} {
if slices.Contains(m.Emits, e) {
+59 -21
View File
@@ -1,6 +1,7 @@
{
"module": "mesh-delivery-indexer",
"version": "0.1",
"class": "core",
"slug": "indexer",
"runs-as": "mesh-delivery-indexer",
"claims": [
@@ -13,6 +14,7 @@
"provides",
"dependents",
"seat-definitions",
"seat-list",
"revision",
"entry",
"registrations",
@@ -70,7 +72,9 @@
"indexer_take_in_again",
"indexer_take_in_skip",
"indexer_runs",
"indexer_run_drop"
"indexer_run_drop",
"indexer_dry_runs",
"indexer_registrations"
],
"consumes": [
"go-package-registry.published",
@@ -80,6 +84,8 @@
"seat:mesh-module-assigner.views.assignments",
"seat:mesh-module-assigner.views.seat-holders",
"mesh-builds.package-published",
"mesh-builds.version-reserved",
"mesh-builds.step-ended",
"mesh-builds.toolchain-agreed",
"node-build-go.step-ended",
"mesh-wants.wait-ended",
@@ -96,37 +102,69 @@
"operator-channel.decided",
"npm-package-registry.published"
],
"config": {
"kept-call-pace-first": {
"type": "string",
"description": "the first wait before a kept call is made again after a transport fault, doubling to kept-call-pace-max, a Go duration (design 47 H2 §775).",
"trusted": false,
"default": "1s",
"runtime": true
},
"kept-call-pace-max": {
"type": "string",
"description": "the longest wait between two tries of a kept call after a transport fault, a Go duration (design 47 H2 §775).",
"trusted": false,
"default": "30s",
"runtime": true
},
"reserved-keep": {
"type": "string",
"description": "how long the indexer keeps a pipeline's reservation of a package's version in its state heard (reserved.<revision>.<module>), a Go duration (design 47 H2 §805, H-A-424 (2)).",
"trusted": false,
"default": "24h",
"runtime": true
},
"reserved-settle": {
"type": "string",
"description": "how long after a revision's first reservation its importers are re-pinned at the latest, when no pipeline-started or step-ended of its pipeline came first, a Go duration (design 47 H2 §805, H-A-424 (1), H-A-436).",
"trusted": false,
"default": "30s",
"runtime": true
}
},
"state": [
{ "name": "candidates", "history": 10 },
{ "name": "heard", "history": 64 },
{ "name": "manifests", "history": 1 },
{ "name": "predefined", "history": 5 },
{ "name": "taken", "history": 1 },
{ "name": "takeins", "history": 1 },
{ "name": "oldsections", "history": 1 },
{ "name": "runs", "history": 1 },
{ "name": "packages", "history": 5 },
{ "name": "view-marks", "history": 1 },
{ "name": "findings", "history": 5 },
{ "name": "first-views", "history": 1 },
{ "name": "requirements", "history": 5 },
{ "name": "seat-definitions", "history": 5 },
{ "name": "candidates", "history": 10, "max-mib": 16 },
{ "name": "heard", "history": 64, "max-mib": 8, "key-ttl": true },
{ "name": "manifests", "history": 1, "max-mib": 32 },
{ "name": "predefined", "history": 5, "max-mib": 8 },
{ "name": "taken", "history": 1, "max-mib": 8 },
{ "name": "takeins", "history": 1, "max-mib": 8 },
{ "name": "oldsections", "history": 1, "max-mib": 8 },
{ "name": "runs", "history": 1, "max-mib": 8 },
{ "name": "packages", "history": 5, "max-mib": 8 },
{ "name": "view-marks", "history": 1, "max-mib": 8 },
{ "name": "findings", "history": 5, "max-mib": 8 },
{ "name": "first-views", "history": 1, "max-mib": 8 },
{ "name": "requirements", "history": 5, "max-mib": 8 },
{ "name": "seat-definitions", "history": 5, "max-mib": 32 },
{ "name": "entry-index", "history": 1, "max-mib": 8 },
{ "name": "named", "history": 1, "max-mib": 4 },
{ "name": "registrations", "history": 1 },
{ "name": "registrations", "history": 1, "max-mib": 8 },
{ "name": "proposals", "history": 1, "max-mib": 4 },
{ "name": "versions", "history": 1, "max-mib": 64 },
{ "name": "build-edges", "history": 1 },
{ "name": "inputs", "history": 1 },
{ "name": "build-edges", "history": 1, "max-mib": 8 },
{ "name": "inputs", "history": 1, "max-mib": 8 },
{ "name": "pins", "history": 1, "max-mib": 4 },
{ "name": "held", "history": 1 }
{ "name": "held", "history": 1, "max-mib": 8 },
{ "name": "dry-runs", "history": 1, "ttl-seconds": 3600, "max-mib": 16 }
],
"streams": [
{ "name": "registration-history", "events": ["registration.*"], "retention": "history", "max-mib": 64 },
{ "name": "mesh-delivery-indexer-findings", "events": ["finding-written.*", "finding-cleared.*", "findings-stated.*"], "max-age-days": 7, "max-mib": 16 }
{ "name": "mesh-delivery-indexer-findings", "events": ["finding-written.*", "finding-cleared.*", "findings-stated.*"], "max-age-days": 7, "max-mib": 8 }
],
"objects": [
{ "name": "catalog-revisions", "max-mib": 512, "form": 1 }
{ "name": "catalog-revisions", "max-mib": 512, "form": 1 },
{ "name": "seat-lists", "max-mib": 64 }
],
"emits": [
"take-in.pending",
+3 -6
View File
@@ -8,15 +8,12 @@ private addresses. That is acceptable while mesh-sdk is private; if it ever goes
a second place to clean besides the catalogue itself.
Only what go/catalogue's tests read is captured (R4b, issue 1379), copied here from mesh-sdk with the judge's tests
(issue 1585). mesh-host refreshed 2026-11-01 from its main, the catalogue 2026-10-21 from its main; before that it
(issue 1585). mesh-host refreshed 2026-11-01 from its main, the catalogue 2026-11-22 from its feat/47-H2 (milestone 47/H2's group); before that it
was mesh-controller's copy, which still held two modules that had left the catalogue.
mesh-catalog b5dbfbb784507e211372a7c9640d91f7d6dadd84 modules/*/module.json, modules/*/files/**, modules/*/templates/**, predefined.json
mesh-catalog 30a3e665e0070ae5b0ebfede985da5759af8affd (feat/47-H2, the delivery group's catalogue head; design 47 H2
H-A-428, H-A-430 (3)) modules/*/module.json, modules/*/files/**, modules/*/templates/**, predefined.json
mesh-host 233bb23bbcb1a829ce2a6164a31a5c5cc4f3d950 internal/apply/placement_guard.go
mesh-catalog 2d5358b8 (milestone 47/G's AM-K1) modules/zsh/module.json alone: the login shell uses operator-channel for
its seat's marked execute (design 46 approval mark §21), which the validator requires (§4)
mesh-catalog cd3b8fe8 (restic's secrets-owner, ADR 0680) modules/restic/module.json and modules/restic/files/** alone: its
processes run as the operator account, so the validator (ADR 0680 §3) needs the secrets-owner it names
To move them, from mesh-delivery's modules/mesh-delivery-indexer directory, with the two repositories checked out
beside mesh-delivery:
@@ -1,6 +1,7 @@
{
"module": "adwaita",
"version": "1",
"version": "0.1",
"class": "leaf",
"moved": true,
"capabilities": [
"package-manager"
@@ -0,0 +1 @@
${seat:container-image-registry:reach}
@@ -1,26 +1,64 @@
{
"module": "artifact-store-tools",
"version": "1",
"version": "0.1",
"class": "core",
"packages": {
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds": "0.1"
},
"claims": [
{
"name": "mesh-artifact-sweep",
"scope": "mesh",
"serves": [
"artifacts",
"held",
"collect",
"mirrors",
"images"
]
}
],
"invokes": [
"seat:mesh-controller.artifacts",
"seat:mesh-controller.collect",
"mesh-catalog.catalog_modules",
"mesh-catalog.catalog_module"
"seat:mesh-hand-acts.hand-act",
"seat:mesh-catalog.modules",
"seat:mesh-catalog.module",
"mesh-delivery-assigner.assigner_read_wants",
"mesh-delivery-indexer.indexer_read_manifests",
"seat:oci-artifact-registry.hold",
"seat:oci-artifact-registry.release",
"seat:oci-artifact-registry.remove",
"seat:container-image-registry.hold",
"seat:container-image-registry.release",
"seat:container-image-registry.remove",
"seat:container-image-registry.list",
"seat:oci-artifact-registry.list"
],
"reads": [
"mesh-delivery-builder.builds",
"mesh-delivery-builder.build-log",
"node-engine.have"
],
"consumes": [
"mesh-delivery-assigner.views.wants",
"mesh-delivery-indexer.views.manifests",
"mesh-conditions.findings-asked"
],
"tools": [
"artifact_store_repositories",
"artifact_store_usage",
"artifact_store_references",
"artifact_store_collect"
"artifact_store_collect",
"artifact_store_first_views",
"artifact_store_first_view_again"
],
"config": {
"older-store-names": {
"type": "string",
"description": "The names the artifact store had before, as host names or host:port separated by spaces, or none when it had no other. artifact_store_references reads every definition under these as well as under the store's current name, so an image a definition pins under one is said to be named by a definition (novox/hq issue 323).",
"pattern": "none|[A-Za-z0-9.:-]+( [A-Za-z0-9.:-]+)*",
"default": "none"
}
},
"config": {
"older-store-names": {
"type": "string",
"description": "The names the artifact store had before, as host names or host:port separated by spaces, or none when it had no other. artifact_store_references reads every definition under these as well as under the store's current name, so an image a definition pins under one is said to be named by a definition (novox/hq issue 323).",
"pattern": "none|[A-Za-z0-9.:-]+( [A-Za-z0-9.:-]+)*",
"default": "none"
}
},
"resources": [
{
"id": "state",
@@ -36,6 +74,14 @@
"mode": "0600",
"trusted": false,
"template": "files/store-names"
},
{
"id": "store-address",
"type": "file",
"path": "${dir:state}/store-address",
"mode": "0600",
"trusted": false,
"template": "files/store-address"
}
],
"build": {
@@ -51,8 +97,8 @@
"artifact-store-tools"
],
"env": {
"MESH_ARTIFACT_STORE_CONTAINER": "mesh-registry",
"MESH_ARTIFACT_STORE_NAMES_FILE": "${dir:state}/store-names"
"MESH_ARTIFACT_STORE_NAMES_FILE": "${dir:state}/store-names",
"MESH_ARTIFACT_STORE_ADDRESS_FILE": "${dir:state}/store-address"
}
},
{
@@ -61,5 +107,29 @@
"from": "files"
}
]
}
},
"requires": [
{
"name": "findings",
"storage": "key-value",
"template": "state",
"options": {
"max-mib": 8
}
},
{
"name": "finding-events",
"storage": "stream",
"template": "events",
"options": {
"events": [
"finding-written.*",
"finding-cleared.*",
"findings-stated.*"
],
"max-age-days": 7,
"max-mib": 8
}
}
]
}
@@ -1,6 +1,7 @@
{
"module": "asus-zephyrus-g14",
"version": "1",
"version": "0.1",
"class": "leaf",
"moved": true,
"templates": "templates",
"capabilities": [
@@ -1,6 +1,7 @@
{
"module": "audit-logger",
"version": "1",
"version": "0.1",
"class": "leaf",
"slug": "audit",
"consumes": [
"**"
@@ -1,6 +1,7 @@
{
"module": "avahi",
"version": "1",
"version": "0.1",
"class": "leaf",
"capabilities": [
"package-manager",
"service-manager"
@@ -1,6 +1,7 @@
{
"module": "baserow",
"version": "1",
"version": "0.1",
"class": "leaf",
"capabilities": [
"container-runtime"
],
@@ -1,3 +0,0 @@
{
"accounts": {}
}
@@ -1,10 +0,0 @@
#!/bin/sh
# Betterbird's start, written by the mesh (module betterbird, novox/hq ADR 0316). Replaced at every push.
#
# Before Betterbird starts, the module's tools place its user.js in the profile (the settings prefs, accounts, identities, calendars,
# address-books and tags) and write what Betterbird rewrites itself: the account lists and each declared account's filters. They do
# it only while no Betterbird of this account runs, because Betterbird rewrites its saved preferences when it quits; a
# second start while one runs only hands over to it. What the preparation could not do it says here, and
# betterbird_check says it too. Betterbird starts either way: its configuration never holds the mail back.
/usr/local/lib/mesh-betterbird/betterbird-tools prepare || echo "betterbird: the mesh's preparation did not complete; betterbird_check says why" >&2
exec /opt/betterbird/betterbird "$@"
@@ -1,6 +0,0 @@
{
"identities": {},
"calendars": {},
"address-books": {},
"filters": {}
}
@@ -1,25 +0,0 @@
[Desktop Entry]
Version=1.0
Type=Application
Name=Betterbird
GenericName=Mail Client
Comment=Send and receive mail with Betterbird
Exec=/usr/local/bin/betterbird %u
Icon=/opt/betterbird/chrome/icons/default/default128.png
Terminal=false
Categories=Network;Email;
MimeType=message/rfc822;x-scheme-handler/mailto;application/x-xpinstall;application/x-extension-ics;text/calendar;text/vcard;text/x-vcard;x-scheme-handler/webcal;x-scheme-handler/webcals;x-scheme-handler/mid;
StartupNotify=true
StartupWMClass=eu.betterbird.Betterbird
Keywords=Email;E-mail;Calendar;Thunderbird;
Actions=ComposeMessage;OpenAddressBook;
# Written by the mesh (module betterbird, novox/hq ADR 0316 §3), in place of the community package's entry:
# it starts Betterbird through the module's start, and names the icon in the installation, with no link.
[Desktop Action ComposeMessage]
Name=Write new message
Exec=/usr/local/bin/betterbird -compose
[Desktop Action OpenAddressBook]
Name=Open address book
Exec=/usr/local/bin/betterbird -addressbook
@@ -1,3 +0,0 @@
{
"prefs": {}
}
@@ -1,3 +0,0 @@
{
"tags": {}
}
@@ -1,253 +0,0 @@
{
"module": "betterbird",
"version": "1",
"upgrade": {
"policy": "record",
"why": "a new build may remove the community package betterbird-bin and replaces the installation in /opt/betterbird, which a running Betterbird has open: the switch on each node and every upgrade wait for the operator, who quits Betterbird first and then pushes (novox/hq ADR 0316 §4, §5)"
},
"requires": [
"x11-display"
],
"invokes": [
"seat:mesh-controller.settings",
"seat:mesh-controller.nodes",
"seat:mesh-controller.node",
"betterbird.betterbird_derive"
],
"tools": [
"betterbird_status",
"betterbird_prefs",
"betterbird_config",
"betterbird_config_apply",
"betterbird_user_js",
"betterbird_log",
"betterbird_restart",
"betterbird_check",
"betterbird_accounts",
"betterbird_identities",
"betterbird_calendars",
"betterbird_address_books",
"betterbird_filters",
"betterbird_tags",
"betterbird_derive",
"betterbird_drift",
"betterbird_reminder_test"
],
"config": {
"prefs": {
"type": "object",
"description": "Betterbird's preferences the operator sets, by their own names (mailnews.*, calendar.* and the like), laid into prefs.json; an account's, a server's and a tag's are refused, as accounts, the four kinds and tags own them (novox/hq ADR 0329 §6).",
"trusted": true,
"default": {}
},
"accounts": {
"type": "object",
"description": "The mail accounts Betterbird is set up with, each by a name of the operator's: its address, its sender's name and its incoming and outgoing servers; no password, token or cookie (novox/hq ADR 0329 §2).",
"trusted": true,
"default": {}
},
"identities": {
"type": "object",
"description": "The identities beside an account's own, each by a name of the operator's: the address and name it sends as, its signature as a list of lines, and the profile's key to adopt on a node.",
"trusted": true,
"default": {}
},
"calendars": {
"type": "object",
"description": "The calendars Betterbird shows, each by a name of the operator's: where it is and how it is reached, and the profile's key to adopt on a node.",
"trusted": true,
"default": {}
},
"address-books": {
"type": "object",
"description": "The address books Betterbird uses, each by a name of the operator's: where it is and how it is reached, and the profile's key to adopt on a node.",
"trusted": true,
"default": {}
},
"filters": {
"type": "object",
"description": "The message filters of each account, by account: what each matches and what it does with the mail.",
"trusted": true,
"default": {}
},
"tags": {
"type": "object",
"description": "The tags Betterbird offers, each by its own key: its name, colour and order; trusted since issue 751, so a change to it is the operator's to approve.",
"trusted": true,
"default": {}
}
},
"resources": [
{
"id": "configuration-dir",
"type": "directory",
"path": "${machine:account-home}/.config/betterbird",
"owner": "${machine:account}",
"mode": "0755",
"unknown": "move-out",
"knows": ["accounts-record.json", "configuration-record.json", "kept/"]
},
{
"id": "prefs",
"type": "file",
"path": "${machine:account-home}/.config/betterbird/prefs.json",
"owner": "${machine:account}",
"mode": "0644",
"merge": "json",
"takes-config": [
"prefs"
],
"template": "files/prefs.json",
"trusted": true
},
{
"id": "accounts",
"type": "file",
"path": "${machine:account-home}/.config/betterbird/accounts.json",
"owner": "${machine:account}",
"mode": "0600",
"merge": "json",
"takes-config": [
"accounts"
],
"template": "files/accounts.json",
"trusted": true
},
{
"id": "configuration",
"type": "file",
"path": "${machine:account-home}/.config/betterbird/configuration.json",
"owner": "${machine:account}",
"mode": "0600",
"merge": "json",
"takes-config": [
"identities",
"calendars",
"address-books",
"filters"
],
"template": "files/configuration.json",
"trusted": true
},
{
"id": "tags",
"type": "file",
"path": "${machine:account-home}/.config/betterbird/tags.json",
"owner": "${machine:account}",
"mode": "0644",
"merge": "json",
"takes-config": [
"tags"
],
"template": "files/tags.json",
"trusted": true
},
{
"id": "community-package",
"type": "package",
"package": "betterbird-bin",
"absent": true
},
{
"id": "installation",
"type": "archive",
"path": "/opt/betterbird",
"artifact": "archive",
"unknown": "program"
},
{
"id": "owl",
"type": "archive",
"path": "/opt/betterbird/owl",
"artifact": "owl",
"unknown": "program"
},
{
"id": "policies",
"type": "archive",
"path": "/opt/betterbird/distribution",
"artifact": "distribution",
"unknown": "program"
},
{
"id": "spelling",
"type": "archive",
"path": "/opt/betterbird/defaults/pref",
"artifact": "defaults",
"unknown": "program"
},
{
"id": "preparation",
"type": "archive",
"path": "/usr/local/lib/mesh-betterbird",
"artifact": "tools",
"unknown": "program"
},
{
"id": "start",
"type": "file",
"path": "/usr/local/bin/betterbird",
"mode": "0755",
"template": "files/betterbird"
},
{
"id": "launcher",
"type": "file",
"path": "/usr/local/share/applications/eu.betterbird.Betterbird.desktop",
"mode": "0644",
"template": "files/eu.betterbird.Betterbird.desktop"
}
],
"build": {
"artifacts": [
{
"name": "tools",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/betterbird-tools",
"binary": "betterbird-tools",
"loads": [
"betterbird-tools"
]
},
{
"name": "archive",
"kind": "archive",
"url": "https://www.betterbird.eu/downloads/LinuxArchive/betterbird-153.4.0esr-bb10.en-US.linux-x86_64.tar.xz",
"sha256": "38dd24890a66b4cf9a45bc24e15192e00c26b929e1bb8df7974c16a4539129e2",
"version": "153.4.0esr-bb10",
"within": "betterbird",
"names-on-purpose": {
"www.betterbird.eu": "Betterbird's project publishes its Linux release there; the build seat fetches it once, by its pinned sha256 (novox/hq ADR 0316 §2)"
}
},
{
"name": "owl",
"kind": "archive",
"url": "https://www.beonex.com/owl/owl.xpi",
"sha256": "a54cc3d52113b34f97942ee19190947dee23561e2217f18db3d80ac023991221",
"version": "1.5.6.1",
"file": "owl.xpi",
"names-on-purpose": {
"www.beonex.com": "Owl's vendor publishes its xpi there; the build seat fetches it once, by its pinned sha256 (novox/hq ADR 0316 §6)"
}
},
{
"name": "distribution",
"kind": "archive",
"from": "install/distribution"
},
{
"name": "defaults",
"kind": "archive",
"from": "install/defaults-pref"
},
{
"name": "files",
"kind": "archive",
"from": "files"
}
]
}
}
@@ -1,6 +1,7 @@
{
"module": "blueman",
"version": "1",
"version": "0.1",
"class": "leaf",
"capabilities": [
"package-manager"
],
@@ -1,6 +1,7 @@
{
"module": "bluetooth",
"version": "1",
"version": "0.1",
"class": "leaf",
"capabilities": [
"package-manager",
"service-manager"
@@ -0,0 +1,3 @@
{
"bucket": "${bound:s3-bucket:bucket}"
}
@@ -0,0 +1,3 @@
{
"mesh-range": "${machine:mesh-range}"
}
@@ -1,8 +1,22 @@
{
"module": "brother",
"version": "1",
"version": "0.1",
"class": "core",
"requires": [
"s3-bucket"
{
"name": "s3-bucket",
"shares": [
{
"to": "seat:node-files",
"methods": [
"put"
]
}
]
}
],
"invokes": [
"seat:node-files.upload"
],
"binds": {
"s3-bucket": "${dir:state}/store-binding.json"
@@ -199,6 +213,21 @@
"mode": "0600",
"template": "files/store.json"
},
{
"id": "bucket",
"type": "file",
"path": "${dir:state}/bucket.json",
"mode": "0644",
"template": "files/bucket.json"
},
{
"id": "fetch",
"type": "file",
"path": "${dir:state}/fetch.json",
"owner": "brother-device",
"mode": "0600",
"template": "files/fetch.json"
},
{
"id": "device",
"type": "process",
@@ -213,11 +242,13 @@
"BROTHER_SETTINGS": "${dir:state}/settings.json",
"BROTHER_ADMIN_PASSWORD": "${dir:state}/admin-password.secret",
"BROTHER_BROKER": "${dir:state}/broker-device.secret",
"BROTHER_STORE": "${dir:state}/store.json"
"BROTHER_STORE": "${dir:state}/store.json",
"BROTHER_FETCH": "${dir:state}/fetch.json"
},
"restart-on": [
"settings",
"store"
"store",
"fetch"
],
"bus": {
"queues": [
@@ -228,6 +259,9 @@
],
"emits": [
"scan.added"
],
"invokes": [
"seat:document-converter.convert"
]
},
"health": {
@@ -267,7 +301,8 @@
"brother"
],
"env": {
"BROTHER_SETTINGS": "${dir:state}/settings.json"
"BROTHER_SETTINGS": "${dir:state}/settings.json",
"BROTHER_BUCKET": "${dir:state}/bucket.json"
}
},
{
@@ -0,0 +1,25 @@
{
"module": "buildah",
"version": "0.1",
"class": "leaf",
"capabilities": [
"package-manager",
"user-namespaces"
],
"provides": [
{
"name": "rootless-image-build",
"reach": "machine",
"credential": {
"form": "none"
}
}
],
"resources": [
{
"id": "buildah",
"type": "package",
"package": "buildah"
}
]
}
@@ -1,6 +1,7 @@
{
"module": "ca-trust",
"version": "1",
"version": "0.1",
"class": "core",
"slug": "catrust",
"capabilities": [
"service-manager"
@@ -5,9 +5,5 @@ agent='${machine:agent-account}'
if [ "$(id -un)" = "$agent" ]; then
exec claude "$@"
fi
# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority. The
# operator's override of the guard travels only when it is set in this shell, as it would reach claude.
if [ -n "$MESH_GUARD_OVERRIDE" ]; then
exec sudo -iu "$agent" env MESH_GUARD_OVERRIDE="$MESH_GUARD_OVERRIDE" claude "$@"
fi
# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority.
exec sudo -iu "$agent" claude "$@"

Some files were not shown because too many files have changed in this diff Show More