diff --git a/cmd/mesh-host/engineseat.go b/cmd/mesh-host/engineseat.go index b806028b..02d5ef00 100644 --- a/cmd/mesh-host/engineseat.go +++ b/cmd/mesh-host/engineseat.go @@ -428,8 +428,9 @@ func packagesFrom(node string, session *link.Session, composer *atomic.Pointer[s // nec.AnswerBound, selfcompose candidateWithin). The answer is // the seat's shape (nodeengine.ComposeCandidateAnswer), checked as it is encoded; a node whose shadow does not run yet // answers unready, which the checker takes as no answer. -func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) { - return func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) { +// An ask carrying an id is taken once by it (design 47 H2 §775, H-A-364). +func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) { + return func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) { ask := nodeengine.ComposeCandidateInput{Candidate: candidate, Input: input, Call: call} if _, err := nec.EncodeAsk(ask); err != nil { return nil, err @@ -442,7 +443,7 @@ func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow } else { ctx, cancel := context.WithTimeout(context.Background(), nec.AnswerBound) defer cancel() - a = s.ComposeCandidate(ctx, ask) + a = s.ComposeCandidate(ctx, ask, askID) } return answerComposeCandidate(a, candidate, input, call, line) } diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 92c0b224..7c77f6b2 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -1241,6 +1241,8 @@ func composerEnv(session *link.Session, node string, say func(string), hooks com return session.AskSeat(ctx, nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, nodepacketfilter.AllowedInput{}, within) } env.ComposeAskBound = composeAskBound() + // And the state taken, where an ask of the seat's verbs is taken once by its id (design 47 H2 §775, H-A-364). + env.Taken = session.TakeOnce return env } diff --git a/cmd/mesh-host/nodeagent_integration_test.go b/cmd/mesh-host/nodeagent_integration_test.go index 067c13c6..9ec999b9 100644 --- a/cmd/mesh-host/nodeagent_integration_test.go +++ b/cmd/mesh-host/nodeagent_integration_test.go @@ -866,7 +866,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) { before, _ := b.composed.Status() // A-237c: asked with input and no call token (the checker's, until G removes it, G-6 §321) an input past what one answer carries // is refused; asked with a token it is sent in chunks through the engine's call, whatever its size (A-237b). - if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", nil); err != nil { + if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", "", nil); err != nil { t.Fatal(err) } else if a, err := nec.DecodeAnswer(over.(json.RawMessage)); err != nil || a.Verdict != nec.Refused || !strings.Contains(a.Refused, "an answer on the bus carries") || a.Input != nil { t.Errorf("an input over the inline bound asked with no token answered %+v (%v)", a, err) @@ -900,7 +900,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) { if len(file) <= 900<<10 || !json.Valid(file) { t.Errorf("the chunks held %d bytes, want a JSON input over 900 KiB", len(file)) } - got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", nil) + got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", "", nil) if err != nil { t.Fatal(err) } diff --git a/cmd/mesh-host/recovery_integration_test.go b/cmd/mesh-host/recovery_integration_test.go index c9def26a..70956784 100644 --- a/cmd/mesh-host/recovery_integration_test.go +++ b/cmd/mesh-host/recovery_integration_test.go @@ -36,9 +36,9 @@ import ( // says the events; the grants part composes the node's subjects from the manifest, so the test adds them to the node's grant. func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) { perms := nodegrant.For(itNode) - perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "mesh.seat.mesh-recovery.call.*.node~"+itNode, + perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "mesh.seat.mesh-recovery.call.*.node~"+itNode, "mesh.mod.db.tool.rebuild."+itNode) - perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>") + perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>") b := newItBedAs(t, perms) ctx := context.Background() @@ -52,8 +52,10 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) if err != nil { t.Fatal(err) } - if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: link.BoundsBucket, History: 1, LimitMarkerTTL: time.Second}); err != nil { - t.Fatal(err) + for _, bucket := range []string{link.BoundsBucket, link.TakenBucket} { + if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: bucket, History: 1, LimitMarkerTTL: time.Second}); err != nil { + t.Fatal(err) + } } say := func(act, outcome string) { raw, _ := json.Marshal(meshrecovery.RestoredEvent{Act: act, Module: "db", Kept: "cache", Outcome: outcome, At: time.Now().UTC()}) @@ -133,6 +135,13 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) say("old", meshrecovery.RestoredEventOutcomeFailed) // said before anyone listens: the last message of the subject session := b.startSession() r := recoveryEnv(session, nil) + // Design 47 H2 §775, H-A-364: over the same session, an ask of the seat is taken once in the state taken: the first time, + // and never again within its bound. + for i, want := range []bool{true, false} { + if took, err := session.TakeOnce(nodeengine.Seat, "ask-1", time.Minute); err != nil || took != want { + t.Fatalf("take %d of ask-1: %v, %v; want %v", i+1, took, err, want) + } + } events, stop, err := r.Hear(ctx, "restored", "db", "cache") if err != nil { diff --git a/internal/link/engineseat.go b/internal/link/engineseat.go index 5551322f..2f110b91 100644 --- a/internal/link/engineseat.go +++ b/internal/link/engineseat.go @@ -57,6 +57,9 @@ type EngineCall struct { // Line is the link's bus connection, which a verb marked chunks sends its answer's file on (buscalls.SeatChunks.Send); nil // where the call did not come over a live link. Line buscalls.ChunkLine + // Ask is the id of the ask the call carried in the header stdio.AskHeader, by which the verb takes it once (design 47 H2 + // §775, H-A-351, H-A-364); empty when it carried none. + Ask string } // EngineFunc answers one call: its result, or why it is refused. @@ -75,8 +78,9 @@ func CallerOfSubject(subject, verb, node string) string { // MaxEngineCall bounds a call's arguments: a path, an access and a few words. const MaxEngineCall = 16 << 10 -// AnswerEngineCall is the envelope one call is answered with: the verb's result, or its refusal in words. -func AnswerEngineCall(handle EngineFunc, verb, node, subject string, body []byte) []byte { +// AnswerEngineCall is the envelope one call is answered with: the verb's result, or its refusal in words. ask is the id +// the call carried in the header stdio.AskHeader. +func AnswerEngineCall(handle EngineFunc, verb, node, subject, ask string, body []byte) []byte { envelope := map[string]any{"node": node} say := func() []byte { raw, err := json.Marshal(envelope) @@ -99,7 +103,7 @@ func AnswerEngineCall(handle EngineFunc, verb, node, subject string, body []byte return say() } } - result, err := handle(EngineCall{Verb: verb, Caller: CallerOfSubject(subject, verb, node), Args: args}) + result, err := handle(EngineCall{Verb: verb, Caller: CallerOfSubject(subject, verb, node), Args: args, Ask: ask}) if err != nil { envelope["error"] = err.Error() } else { @@ -200,7 +204,7 @@ const apartAtOnce = 4 func EngineAnswer(handle EngineFunc, verb, node string, apart chan struct{}) micro.HandlerFunc { return func(r micro.Request) { if !answeredApart[verb] { - _ = r.Respond(AnswerEngineCall(handle, verb, node, r.Subject(), r.Data())) + _ = r.Respond(AnswerEngineCall(handle, verb, node, r.Subject(), r.Headers().Get(stdio.AskHeader), r.Data())) return } select { @@ -211,10 +215,10 @@ func EngineAnswer(handle EngineFunc, verb, node string, apart chan struct{}) mic _ = r.Respond(raw) return } - subject, data := r.Subject(), r.Data() + subject, ask, data := r.Subject(), r.Headers().Get(stdio.AskHeader), r.Data() go func() { defer func() { <-apart }() - _ = r.Respond(AnswerEngineCall(handle, verb, node, subject, data)) + _ = r.Respond(AnswerEngineCall(handle, verb, node, subject, ask, data)) }() } } diff --git a/internal/link/handacts.go b/internal/link/handacts.go index cbea5eb1..18a44c91 100644 --- a/internal/link/handacts.go +++ b/internal/link/handacts.go @@ -192,7 +192,8 @@ type HandActs struct { // module, applying and writing nothing; with input, also the composition input it composed from (the verb // compose-candidate, ADR 0593 §7). // call is the caller's token for the chunks the input is sent in (A-237b) and line the connection they go on; with no token the input is inline. - ComposeCandidate func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) + // ask is the id of the ask, taken once (design 47 H2 §775, H-A-364). + ComposeCandidate func(candidate string, input bool, call, ask string, line buscalls.ChunkLine) (any, error) // ManifestReads is what this engine states it reads of a manifest and when its record last carried them (the verb // manifest-reads, novox/hq ADR 0618 §3). ManifestReads func() ([]string, time.Time) @@ -330,7 +331,7 @@ func (h *HandActs) Call(c EngineCall) (any, error) { if b, ok := c.Args["input"].(bool); ok { input = b } - return h.ComposeCandidate(arg("candidate"), input, arg("call"), c.Line) + return h.ComposeCandidate(arg("candidate"), input, arg("call"), c.Ask, c.Line) case ActManifestReads: if h.ManifestReads == nil { return nil, errors.New("this engine states no manifest reads yet: its node agent has not started") diff --git a/internal/link/handover_test.go b/internal/link/handover_test.go index 3b502ed8..1ca0b771 100644 --- a/internal/link/handover_test.go +++ b/internal/link/handover_test.go @@ -343,7 +343,7 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { if !ok { body = `{}` } - if got := string(AnswerEngineCall(h.Call, row.verb, "n1", subject, []byte(body))); !strings.Contains(got, row.want) || + if got := string(AnswerEngineCall(h.Call, row.verb, "n1", subject, "", []byte(body))); !strings.Contains(got, row.want) || !strings.Contains(got, `"node":"n1"`) { t.Errorf("%s on %s: %s", row.verb, row.subject, got) } @@ -360,8 +360,10 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { t.Run("two asks of compose-candidate at once are answered side by side", func(t *testing.T) { var mu sync.Mutex arrived, both := 0, make(chan struct{}) + var asks []string handle := func(c EngineCall) (any, error) { mu.Lock() + asks = append(asks, c.Ask) if arrived++; arrived == 2 { close(both) } @@ -376,13 +378,18 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { answered := make(chan string, 2) answer := EngineAnswer(handle, ActComposeCandidate, "n1", make(chan struct{}, 4)) for range 2 { - answer(fakeRequest{subject: EngineToolSubject(ActComposeCandidate, "n1"), answered: answered}) + answer(fakeRequest{subject: EngineToolSubject(ActComposeCandidate, "n1"), answered: answered, ask: "ask-1"}) } for range 2 { if got := <-answered; !strings.Contains(got, `"result":"together"`) { t.Errorf("an ask answered %s; want both answered side by side", got) } } + // Design 47 H2 §775, H-A-364: the ask id the call carried in its header reaches the verb, to take it once by. + if mu.Lock(); strings.Join(asks, ",") != "ask-1,ask-1" { + t.Errorf("the verb was handed the asks %v; want the header's ask-1 each time", asks) + } + mu.Unlock() full := make(chan struct{}, 1) full <- struct{}{} EngineAnswer(handle, ActComposeCandidate, "n1", full)(fakeRequest{subject: "s", answered: answered}) @@ -396,6 +403,7 @@ func TestALinkThatHearsHandOversIsGivenTheQueues(t *testing.T) { type fakeRequest struct { subject string answered chan string + ask string // the header stdio.AskHeader } func (r fakeRequest) Respond(b []byte, _ ...micro.RespondOpt) error { @@ -407,7 +415,9 @@ func (r fakeRequest) Error(string, string, []byte, ...micro.RespondOpt) error { return nil } func (r fakeRequest) Data() []byte { return []byte(`{}`) } -func (r fakeRequest) Headers() micro.Headers { return nil } +func (r fakeRequest) Headers() micro.Headers { + return micro.Headers{stdio.AskHeader: []string{r.ask}} +} func (r fakeRequest) Subject() string { return r.subject } func (r fakeRequest) Reply() string { return "_INBOX.x" } diff --git a/internal/link/taken.go b/internal/link/taken.go new file mode 100644 index 00000000..ec2e8975 --- /dev/null +++ b/internal/link/taken.go @@ -0,0 +1,65 @@ +package link + +import ( + "context" + "fmt" + "time" + + "git.novox.be/novox/mesh-sdk/go/process" + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" +) + +// The node-engine takes an ask once by its id (design 47 H2 §775, §820; H-A-364 (a)): the ids it took are kept in its own +// state taken, under `.`, each for the ask's bound, bound over the link it serves its seat on. + +// TakenBucket is the node-engine's state `taken`, named by its holder as every state is. +const TakenBucket = "mesh-host_" + process.TakenState + +// TakenBus is a link that binds the node-engine's state taken. +type TakenBus interface { + TakenKV(ctx context.Context) (jetstream.KeyValue, error) +} + +func takenKV(ctx context.Context, conn *nats.Conn) (jetstream.KeyValue, error) { + js, err := jetstream.New(conn) + if err != nil { + return nil, err + } + kv, err := js.KeyValue(ctx, TakenBucket) + if err != nil { + return nil, fmt.Errorf("the state %s cannot be bound: %w", TakenBucket, err) + } + return kv, nil +} + +func (l *natsLink) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, l.conn) } +func (b OverNATS) TakenKV(ctx context.Context) (jetstream.KeyValue, error) { return takenKV(ctx, b.Conn) } + +var ( + _ TakenBus = (*natsLink)(nil) + _ TakenBus = OverNATS{} +) + +// takenWithin bounds binding the state taken. +const takenWithin = 5 * time.Second + +// TakeOnce takes the ask ask of seat once, in the state taken for bound (process.State.TakeOnce): true the first time it +// is given, false when it was taken within its bound. ErrNoLink when no link is held. +func (q *Session) TakeOnce(seat, ask string, bound time.Duration) (bool, error) { + q.init() + q.mu.Lock() + bus := q.bus + q.mu.Unlock() + t, ok := bus.(TakenBus) + if bus == nil || !ok { + return false, ErrNoLink + } + ctx, cancel := context.WithTimeout(context.Background(), takenWithin) + defer cancel() + kv, err := t.TakenKV(ctx) + if err != nil { + return false, err + } + return process.StateOver("mesh-host", process.TakenState, kv).TakeOnce(seat, ask, bound) +} diff --git a/internal/selfcompose/candidate.go b/internal/selfcompose/candidate.go index 15cbdac5..0badb931 100644 --- a/internal/selfcompose/candidate.go +++ b/internal/selfcompose/candidate.go @@ -98,10 +98,87 @@ func (r *candidateRun) said(now time.Time) (waits string, on string) { return waits, on } -// ComposeCandidate is the node's answer to ask, within candidateWithin (or ctx's deadline, if sooner). Each answer is -// said in one line, with what it waited on and for how long (issue 1126: ace, g14 and shanks answered nothing for a -// minute while nothing said why). An answer not composed within the bound is unready, naming what the node waits on. -func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCandidateInput) nodeengine.ComposeCandidateAnswer { +// askRuns are the compose-candidate runs going now, by their ask's id (design 47 H2 §775, H-A-364 (b)): compose-candidate +// is a read, so a repeat of an ask while its run goes joins that run and gets the answer it composes once, and a repeat +// after the run ended is composed again. No answer is kept. +type askRuns struct { + mu sync.Mutex + runs map[string]*askRun +} + +// askRun is one ask's run: done is closed once a holds its answer; joined counts the repeats that joined it, under the +// runs' lock. +type askRun struct { + done chan struct{} + a nodeengine.ComposeCandidateAnswer + joined int +} + +// once answers the ask id by compose, run once for every repeat of id that comes while it runs; joined says this call +// joined a run another started. A joiner whose ctx ends first answers ended's answer. +func (r *askRuns) once(ctx context.Context, id string, compose func() nodeengine.ComposeCandidateAnswer, ended func() nodeengine.ComposeCandidateAnswer) (a nodeengine.ComposeCandidateAnswer, joined bool) { + r.mu.Lock() + if run, ok := r.runs[id]; ok { + run.joined++ + r.mu.Unlock() + select { + case <-run.done: + return run.a, true + case <-ctx.Done(): + return ended(), true + } + } + if r.runs == nil { + r.runs = map[string]*askRun{} + } + run := &askRun{done: make(chan struct{})} + r.runs[id] = run + r.mu.Unlock() + defer func() { + r.mu.Lock() + delete(r.runs, id) + r.mu.Unlock() + close(run.done) + }() + run.a = compose() + return run.a, false +} + +// ComposeCandidate is the node's answer to ask, carried with the ask id id, within candidateWithin (or ctx's deadline, if +// sooner). An ask with an id is taken once (design 47 H2 §775, H-A-364): kept in the state taken for compose-ask-bound, and +// a repeat while its run goes joins that run (askRuns); an ask with none is composed as it comes. Each answer is said in one +// line, with what it waited on and for how long (issue 1126: ace, g14 and shanks answered nothing for a minute while +// nothing said why). An answer not composed within the bound is unready, naming what the node waits on. +func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCandidateInput, id string) nodeengine.ComposeCandidateAnswer { + if id == "" { + return s.composeCandidateNow(ctx, ask, "") + } + s.mu.Lock() + c := s.c + s.mu.Unlock() + a, joined := s.asked.once(ctx, id, func() nodeengine.ComposeCandidateAnswer { + took := "" + if c.env.Taken != nil { + switch first, err := c.env.Taken(nodeengine.Seat, id, c.composeAskBound()); { + case err != nil: + took = fmt.Sprintf(", not kept in taken: %v", err) + case !first: + took = ", taken before and its run ended, so composed again" + } + } + return s.composeCandidateNow(ctx, ask, " (ask "+id+took+")") + }, func() nodeengine.ComposeCandidateAnswer { + return nodeengine.ComposeCandidateAnswer{Node: c.env.Node, Candidate: ask.Candidate, Verdict: nec.Unready, + Refused: "the run of ask " + id + " this repeat joined did not end within the ask's bound"} + }) + if joined { + c.env.Say(fmt.Sprintf("compose-candidate %s (ask %s again) joined its run and answered %s", ask.Candidate, id, a.Verdict)) + } + return a +} + +// composeCandidateNow composes ask, its journal line naming its ask in about. +func (s *Shadow) composeCandidateNow(ctx context.Context, ask nodeengine.ComposeCandidateInput, about string) nodeengine.ComposeCandidateAnswer { s.mu.Lock() c := s.c s.mu.Unlock() @@ -125,7 +202,7 @@ func (s *Shadow) ComposeCandidate(ctx context.Context, ask nodeengine.ComposeCan if a.Refused != "" { words = ": " + a.Refused } - c.env.Say(fmt.Sprintf("compose-candidate %s answered %s in %s (%s)%s", ask.Candidate, a.Verdict, + c.env.Say(fmt.Sprintf("compose-candidate %s%s answered %s in %s (%s)%s", ask.Candidate, about, a.Verdict, (time.Duration(a.Took) * time.Millisecond).String(), waits, words)) return a } diff --git a/internal/selfcompose/candidate_test.go b/internal/selfcompose/candidate_test.go index 0216f65b..ba0d54eb 100644 --- a/internal/selfcompose/candidate_test.go +++ b/internal/selfcompose/candidate_test.go @@ -3,6 +3,7 @@ package selfcompose import ( "context" "encoding/json" + "runtime" "strings" "sync/atomic" "testing" @@ -84,12 +85,21 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { } return json.Marshal(meshcatalog.EntryAnswer{Entry: entry}) }) + // Design 47 H2 §775, H-A-364: an ask with an id is taken once in the state taken, for compose-ask-bound. + var takes []string + taken := map[string]bool{} + env.Taken = func(seat, ask string, bound time.Duration) (bool, error) { + takes = append(takes, seat+"."+ask+" "+bound.String()) + first := !taken[ask] + taken[ask] = true + return first, nil + } var handed atomic.Int64 s := NewShadow(env, func(context.Context, map[string]nodeengine.CandidateAnswer) { handed.Add(1) }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { _ = s.Run(ctx) }() - if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}); a.Verdict != nec.Unready || a.Refused == "" { + if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, ""); a.Verdict != nec.Unready || a.Refused == "" { t.Errorf("a shadow not ready answered %+v", a) } place := assignedValues(t, meshmoduleassigner.Assignments{Node: "n1", Decided: meshmoduleassigner.NodeDecided{Hub: true, Address: "10.77.0.1"}, @@ -111,7 +121,7 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { time.Sleep(5 * time.Millisecond) } - a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}) + a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, "") if _, err := nec.EncodeAnswer(a); err != nil { t.Fatalf("the answer does not fit the seat's shape: %v (%+v)", err, a) } @@ -120,9 +130,20 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { a.Own.Module != nec.NodeWord || a.Took > nec.AnswerBound.Milliseconds() { t.Errorf("an accepted candidate answered %+v", a) } + // Design 47 H2 §775, H-A-364 (b): an ask with an id is taken once; given again after its run ended it is composed again, + // to the same answer, and nothing of the answer is kept. + for range 2 { + if a := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted}, "ask-1"); a.Verdict != nec.Composed || + len(a.Modules) != 1 || a.Modules[0].Fp != fpNew { + t.Errorf("an ask with an id answered %+v", a) + } + } + if strings.Join(takes, ",") != "node-engine.ask-1 10s,node-engine.ask-1 10s" { + t.Errorf("the asks with an id were taken as %v; want node-engine.ask-1 for compose-ask-bound, each time", takes) + } // Issue 774: the input it sends the sandbox says how it composed the node (the builds), so the sandbox composes it // through the same path. - sent := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted, Input: true}) + sent := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: accepted, Input: true}, "") var in compose.Input raw, _ := json.Marshal(sent.Input) if err := json.Unmarshal(raw, &in); err != nil || in.ComposedHow == nil || in.ComposedHow.Node != "n1" || @@ -132,43 +153,83 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { // A-226b: a branch pipeline's revision composes as the candidate, each module at the revision's build; one the catalog does // not hold, and a run on request's key, are refused in words. revKey, _ := nec.RevisionKey("main", 362) - rv := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: revKey}) + rv := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: revKey}, "") if rv.Verdict != nec.Composed || len(rv.Modules) != 1 || rv.Modules[0].Fp != fpNew || !rv.Modules[0].Changed { t.Errorf("a catalog revision answered %+v", rv) } noRev, _ := nec.RevisionKey("main", 999) - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRev}); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no revision 999") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRev}, ""); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no revision 999") { t.Errorf("a revision the catalog does not hold answered %+v", m) } // A-226c: a run's key reads the indexer's candidates.run- by its group, with no heads compared; one it holds none of is refused. candidateOf("run-r1", digest2) runKey, _ := nec.RunKey("r1") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: runKey}); m.Verdict != nec.Composed || len(m.Modules) != 1 || m.Modules[0].Fp != fpNew || !m.Modules[0].Changed { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: runKey}, ""); m.Verdict != nec.Composed || len(m.Modules) != 1 || m.Modules[0].Fp != fpNew || !m.Modules[0].Changed { t.Errorf("a run's key answered %+v", m) } noRun, _ := nec.RunKey("r2") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRun}); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no candidate") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: noRun}, ""); m.Verdict != nec.Refused || !strings.Contains(m.Refused, "holds no candidate") { t.Errorf("a run the indexer holds none of answered %+v", m) } missing, _ := nec.CompositionKey("novox/x#8", "0123456789ab") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: missing}); !strings.Contains(m.Refused, "holds no candidate") { + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: missing}, ""); !strings.Contains(m.Refused, "holds no candidate") { t.Errorf("a candidate the indexer does not hold answered %+v", m) } // The group's candidate moved to other heads since the ask: the node composes not the one asked, and answers // unready (no answer), naming the heads it holds. moved, _ := nec.CompositionKey("fix/940-no-retire-on-partial-read", "0123456789ab") - if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: moved}); m.Verdict != nec.Unready || + if m := s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: moved}, ""); m.Verdict != nec.Unready || !strings.Contains(m.Refused, "heads") { t.Errorf("a candidate at other heads answered %+v", m) } ended, end := context.WithCancel(ctx) end() - if e := s.ComposeCandidate(ended, nodeengine.ComposeCandidateInput{Candidate: accepted}); e.Verdict != nec.Unready { + if e := s.ComposeCandidate(ended, nodeengine.ComposeCandidateInput{Candidate: accepted}, ""); e.Verdict != nec.Unready { t.Errorf("an ended bound answered %+v", e) } if len(state.written()) != 0 || applied.Load() != 0 || handed.Load() != 0 { t.Errorf("composing candidates wrote %v, marked %d have(s), handed %d answer(s); want nothing", state.written(), applied.Load(), handed.Load()) } + // H-A-364 (b): a repeat of an ask while its run goes joins that run and gets the answer it composes once; one whose + // bound ends first answers unready; a repeat after the run ended composes again. + t.Run("a repeat of an ask joins the run it started", func(t *testing.T) { + var runs askRuns + var composed atomic.Int64 + release, started := make(chan struct{}), make(chan struct{}) + compose := func() nodeengine.ComposeCandidateAnswer { + if composed.Add(1) == 1 { + close(started) + <-release + } + return nodeengine.ComposeCandidateAnswer{Verdict: nec.Composed} + } + ended := func() nodeengine.ComposeCandidateAnswer { return nodeengine.ComposeCandidateAnswer{Verdict: nec.Unready} } + first := make(chan bool, 1) + go func() { _, joined := runs.once(ctx, "a", compose, ended); first <- joined }() + <-started + gone, cut := context.WithCancel(ctx) + cut() + if a, joined := runs.once(gone, "a", compose, ended); !joined || a.Verdict != nec.Unready { + t.Errorf("a repeat whose bound ended answered %+v (joined %v)", a, joined) + } + again := make(chan nodeengine.ComposeCandidateAnswer, 1) + go func() { a, _ := runs.once(ctx, "a", compose, ended); again <- a }() + for joined := 0; joined < 2; runtime.Gosched() { // the cut repeat, then this one + runs.mu.Lock() + joined = runs.runs["a"].joined + runs.mu.Unlock() + } + close(release) + if joined := <-first; joined { + t.Error("the first ask joined a run") + } + if a := <-again; a.Verdict != nec.Composed || composed.Load() != 1 { + t.Errorf("a repeat while the run went answered %+v after %d composition(s); want the one", a, composed.Load()) + } + if _, joined := runs.once(ctx, "a", compose, ended); joined || composed.Load() != 2 { + t.Errorf("a repeat after the run ended joined %v, %d composition(s); want composed again", joined, composed.Load()) + } + }) // Issue 1126, 2026-11-03: off the control-node an ask of compose-candidate was not answered within a minute, and said // nothing of why. Each of its two compositions read every manifest in the mesh one by one, on copies of the shadow // that kept nothing, so every ask read them all twice again. Each manifest is now read once, before either @@ -269,7 +330,7 @@ func TestTheNodeComposesACandidateOnAsk(t *testing.T) { } var a nodeengine.ComposeCandidateAnswer for range tc.asks { - a = s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: key}) + a = s.ComposeCandidate(ctx, nodeengine.ComposeCandidateInput{Candidate: key}, "") } if a.Verdict != tc.verdict || !strings.Contains(a.Refused, tc.words) { t.Errorf("answered %s %q; want %s with %q", a.Verdict, a.Refused, tc.verdict, tc.words) diff --git a/internal/selfcompose/selfcompose.go b/internal/selfcompose/selfcompose.go index 7b12cccb..0850f3a3 100644 --- a/internal/selfcompose/selfcompose.go +++ b/internal/selfcompose/selfcompose.go @@ -153,6 +153,9 @@ type Env struct { // ComposeAskBound is the setting `compose-ask-bound`: how long a compose waits for allowed; DefaultComposeAskBound when 0 // (design 08 control-verbs §1, H-A-314 (5)). ComposeAskBound time.Duration + // Taken takes an ask of the seat seat once by its id (design 47 H2 §775, H-A-364 (a)): kept in the node-engine's state + // `taken` under `.` for bound; false when it was taken before. Nil keeps nothing. + Taken func(seat, ask string, bound time.Duration) (bool, error) // Registry asks the registry seats' verb versions (oci-artifact-registry, container-image-registry) in the engine's own // name: a want naming its version is resolved to its artifacts' digests through it (design 47 G A-430a). Registry meshcatalogclient.Call diff --git a/internal/selfcompose/shadow.go b/internal/selfcompose/shadow.go index 506efd1b..2eae3305 100644 --- a/internal/selfcompose/shadow.go +++ b/internal/selfcompose/shadow.go @@ -68,6 +68,8 @@ type Shadow struct { entryMoved chan struct{} // ready says this run read every input once: the verb compose-candidate composes only then (ComposeCandidate). ready atomic.Bool + // asked are the compose-candidate runs going now, by their ask's id (H-A-364 (b)). + asked askRuns } // answeredAt is what one proposal's answer was composed at: its keys' revisions, by node, and the changes of each input. diff --git a/module.json b/module.json index 8f6929b1..52b30be5 100644 --- a/module.json +++ b/module.json @@ -93,6 +93,12 @@ "name": "bounds", "history": 1, "key-ttl": true + }, + { + "name": "taken", + "history": 1, + "key-ttl": true, + "max-mib": 8 } ], "config": { diff --git a/packaging/bounds_state_test.go b/packaging/bounds_state_test.go deleted file mode 100644 index d92beab9..00000000 --- a/packaging/bounds_state_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package packaging_test - -import ( - "os" - "testing" - - "git.novox.be/novox/mesh-sdk/go/catalogue" -) - -// The node-engine's waits run against bound keys with their own time to live, in its old section as its other states are -// (design 47 G A-92, §560, §627): the manifest declares the state bounds with a lifetime per key. -func TestTheManifestDeclaresTheBoundsStateWithAKeyLifetime(t *testing.T) { - raw, err := os.ReadFile("../module.json") - if err != nil { - t.Fatal(err) - } - m, err := catalogue.Decode(raw) - if err != nil { - t.Fatalf("the manifest no longer parses: %v", err) - } - for _, s := range m.State { - if s.Name == "bounds" { - if !s.KeyTTL || s.History != 1 { - t.Fatalf("the state bounds is %+v: one value a key, each key with its own lifetime", s) - } - return - } - } - t.Fatal("the manifest declares no state bounds") -} diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index b29841a8..f13e9455 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -128,11 +128,13 @@ func TestTheManifestConsumesTheBackupEvent(t *testing.T) { // ADR 0565 clause 6: and the state packages, one key per node, its compositions' declared packages, read by pacman. // ADR 0564 §2, ADR 0636 §1: and the state findings, the node's finding that it waits for the seat list (no TTL: the // finding stays until the first full read deletes its key). - // Design 47 G A-92: and the state bounds, each key a wait's bound with its own lifetime (packaging/bounds_state_test.go). - if len(parsed.State) != 5 || parsed.State[0].Name != "health" || parsed.State[0].TTLSeconds != 0 || + // Design 47 G A-92: and the state bounds, each key a wait's bound with its own lifetime, one value a key. + // Design 47 H2 §775, §820, H-A-364: and the state taken, the asks taken once, each key for its ask's bound, 8 MiB. + if len(parsed.State) != 6 || parsed.State[0].Name != "health" || parsed.State[0].TTLSeconds != 0 || parsed.State[1].Name != "findings" || parsed.State[1].TTLSeconds != 0 || parsed.State[2].Name != "data" || parsed.State[2].TTLSeconds != 0 || parsed.State[3].Name != "packages" || - parsed.State[3].TTLSeconds != 0 || parsed.State[4].Name != "bounds" { + parsed.State[3].TTLSeconds != 0 || parsed.State[4].Name != "bounds" || !parsed.State[4].KeyTTL || parsed.State[4].History != 1 || + parsed.State[5].Name != "taken" || !parsed.State[5].KeyTTL || parsed.State[5].History != 1 || parsed.State[5].MaxMiB != 8 { t.Fatalf("the manifest declares the state %+v", parsed.State) } }