From 662b05ca5ac55e90c874fde8f9754dc79f314d1a Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 16:35:15 +0100 Subject: [PATCH 1/2] node-tools: a stopping tool runner takes its subscriptions down, so callers meet no responders (issue 721) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runner answered each call it did not take once its stop began with the typed fault stopping (#90). Callers built before mesh-sdk read it as the callee's refusal and ended their kept call, and no edge delivered the new answer after its readers. Now, once told to stop, the runner first drains every subscription it answers calls on (a tool's, a seat verb's and a seat proof's) and subscribes none again, then finishes the calls in flight within drain-bound. A call made after the stop meets no responders at once, a transport fault every caller of every mesh-sdk already waits out, until the new runner subscribes. A call that still reached it is answered nothing, as H-A-369 has it. The typed answer goes whole: the reply's error-kind, KindedError, ErrorKindStopping and the bundle's error data. Tests: 721/AC4 in the bus (a call and a proof after the stop meet no responders within a second, the call in flight is answered, a subject served after the stop is refused) and in launch (a call that still reaches the runner gets no answer and no typed fault); the whole test meets no responders while a call is still in flight, before the drain bound. Builds: design 47 H2 H-A-570 (1), (3) (mesh-tools' part), amending §813 (12) as H-A-369 has it --- node-tools/cmd/node-tools/main.go | 3 + .../cmd/node-tools/whole_integration_test.go | 30 ++++--- node-tools/internal/bus/bus.go | 84 ++++++++++++------- node-tools/internal/bus/caller_bus_test.go | 52 +++++++----- node-tools/internal/bus/seat.go | 34 +++++--- node-tools/internal/bus/seat_test.go | 20 +++-- node-tools/internal/launch/drain.go | 22 +++-- node-tools/internal/launch/error_code_test.go | 25 ++---- node-tools/internal/launch/launch.go | 15 +--- 9 files changed, 162 insertions(+), 123 deletions(-) diff --git a/node-tools/cmd/node-tools/main.go b/node-tools/cmd/node-tools/main.go index c4182da..09786dd 100644 --- a/node-tools/cmd/node-tools/main.go +++ b/node-tools/cmd/node-tools/main.go @@ -166,6 +166,9 @@ func serve(ctx context.Context) error { // First of all: the service manager signalled every bundle with this process, and none is started again // (issue 1126). launch.ShutDown() + // Then it unsubscribes from every subject it answers calls on, so a call made from now on meets no responders wherever no + // other tool runner serves it, until the new runner subscribes (design 47 H2 H-A-570 (1)). + conn.StopAnswering() // Then it drains (design 47 H2 §813 (12), H-A-353): no new call is taken, the calls in flight finish within the drain bound // or are cut and said, and only then are the bundles stopped, by the runner itself. launch.Drain(drainBound, log.Printf) diff --git a/node-tools/cmd/node-tools/whole_integration_test.go b/node-tools/cmd/node-tools/whole_integration_test.go index a25d727..1106d30 100644 --- a/node-tools/cmd/node-tools/whole_integration_test.go +++ b/node-tools/cmd/node-tools/whole_integration_test.go @@ -238,8 +238,8 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te } // at its stop the runner drains (design 47 H2 §813 (12), H-A-353; the bound 2 s here for the setting's 30 s): a call of 1 s in - // flight is answered, one of 6 s is cut at the bound, said, and its caller answered nothing; a call after the stop is answered - // the typed fault stopping (H-A-542) + // flight is answered, one of 6 s is cut at the bound, said, and its caller answered nothing; a call after the stop meets no + // responders, since the runner took its subscriptions down first (H-A-570 (1)) type answer struct { got string err error @@ -261,16 +261,24 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te return nil }) stop() - // a call after the stop began is answered the typed fault stopping, never silence, so its caller asks again after a pause and - // meets the new runner (H-A-369 as H-A-542 amends it): until the drain began it is still answered - mt.Until(t, func() error { - answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", 500*time.Millisecond) - var kinded interface{ ErrorKind() string } - if !errors.As(err, &kinded) || kinded.ErrorKind() != "stopping" { - return fmt.Errorf("a call after the stop was answered %s, %v; want the typed fault stopping", answered.Result, err) + // a call after the stop began, of a tool and of a seat verb, meets no responders within a second, a transport fault its + // caller's kept call waits out until the new runner subscribes, never an answer of the old runner's (H-A-570 (1)): until + // the runner took its subscriptions down it is still answered. The runner takes them down before it drains, so its callers + // meet no responders while the call of 6 s is still in flight, before the drain bound cuts it. + for _, key := range []string{"ledger.who", "seat:node-desk.who@anchor"} { + mt.Until(t, func() error { + at := time.Now() + answered, err := asker.AskWithin(key, map[string]any{}, "", 300*time.Millisecond) + if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > time.Second { + return fmt.Errorf("a call of %s after the stop was answered %s, %v in %s; want no responders within a second", key, + answered.Result, err, took) + } + return nil + }) + if journal.has("cut ledger's call hold") { + t.Errorf("a call of %s met no responders only once the drain had ended, want it from the stop on", key) } - return nil - }) + } if got := <-short; got.err != nil || !strings.Contains(got.got, `"held":1`) { t.Errorf("the call of 1 s in flight at the stop was answered %s, %v; want it finished", got.got, got.err) } diff --git a/node-tools/internal/bus/bus.go b/node-tools/internal/bus/bus.go index d112b9a..f905753 100644 --- a/node-tools/internal/bus/bus.go +++ b/node-tools/internal/bus/bus.go @@ -200,6 +200,11 @@ type Conn struct { // answering is every subject this runtime answers on, so a subscription the bus refused can be // asked for again (novox/hq issue 222). answering map[string]*answered + // proofs are the subscriptions that answer a seat's proofs (SeatAnswer), so the stop takes them down with the rest. + proofs map[*nats.Subscription]bool + // answersDown is set once the runner took down every subscription it answers calls on at its stop (StopAnswering): + // from then on it subscribes none again, so every later call meets no responders here (design 47 H2 H-A-570 (1)). + answersDown bool // RetryAfter is how long after a refusal a subscription is asked for again, by attempt; past the // last, it is given up and said. A variable so a test need not wait minutes. RetryAfter []time.Duration @@ -292,7 +297,7 @@ func (c *Conn) refused(err error) { time.AfterFunc(wait, func() { c.mu.Lock() defer c.mu.Unlock() - if a.stopped { + if a.stopped || c.answersDown { return } if a.sub != nil { @@ -688,28 +693,7 @@ func (c *Conn) servedOn(module, tool string) []Served { type reply struct { Result any `json:"result,omitempty"` Error string `json:"error,omitempty"` - // ErrorKind is the typed fault beside Error, when the handler's error names one (ErrorKind() string): a stopping - // tool runner's stopping (design 47 H2 H-A-542). - ErrorKind string `json:"error-kind,omitempty"` - Node string `json:"node,omitempty"` -} - -// KindedError is an answer's error with its typed fault (`error-kind`, design 47 H2 H-A-542): a stopping tool runner's -// stopping. Its words are the answerer's; ErrorKind is told apart by its kind, never by its words. -type KindedError struct{ Words, Kind string } - -func (e *KindedError) Error() string { return e.Words } - -// ErrorKind is the typed fault the answer named. -func (e *KindedError) ErrorKind() string { return e.Kind } - -// errorKindOf is the typed fault err names (ErrorKind() string), "" for none. -func errorKindOf(err error) string { - var kinded interface{ ErrorKind() string } - if errors.As(err, &kinded) { - return kinded.ErrorKind() - } - return "" + Node string `json:"node,omitempty"` } // answerOn answers one subject with one handler, and says which machine answered (ADR 0159). @@ -736,7 +720,7 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e return } if err != nil { - r.Error, r.ErrorKind = err.Error(), errorKindOf(err) + r.Error = err.Error() } else { r.Result = nullable(result) } @@ -749,6 +733,9 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e } }() } + if err := c.answersAreDown(subject); err != nil { + return func() {}, err + } var sub *nats.Subscription var err error if queue != "" { @@ -971,18 +958,13 @@ func (c *Conn) askOnce(subject string, data []byte, within time.Duration) (Answe // answerOf reads one answer. func answerOf(data []byte) (Answered, error) { var r struct { - Result json.RawMessage `json:"result"` - Error string `json:"error"` - ErrorKind string `json:"error-kind"` - Node string `json:"node"` + Result json.RawMessage `json:"result"` + Error string `json:"error"` + Node string `json:"node"` } if err := json.Unmarshal(data, &r); err != nil { return Answered{}, err } - if r.Error != "" && r.ErrorKind != "" { - // A typed fault (a stopping tool runner's stopping, design 47 H2 H-A-542) reaches the caller as such. - return Answered{}, &KindedError{Words: r.Error, Kind: r.ErrorKind} - } if r.Error != "" { return Answered{}, errors.New(r.Error) } @@ -1118,6 +1100,44 @@ func (c *Conn) MaxPayload() int64 { return c.nc.MaxPayload() } // when this returns. func (c *Conn) Flush() { _ = c.nc.Flush() } +// StopAnswering is the runner's first act once told to stop, before it finishes the calls in flight (design 47 H2 H-A-570 +// (1)): it unsubscribes from every subject it answers calls on, a tool's, a seat verb's and a seat proof's, by the bus's +// own drain of each subscription, and subscribes none again, so a call made from now on meets no responders at once +// wherever no other tool runner serves it, until the new runner subscribes. A call already taken is answered as before: +// a reply needs no subscription. It returns once the bus holds the unsubscriptions. +func (c *Conn) StopAnswering() { + c.mu.Lock() + c.answersDown = true + var subs []*nats.Subscription + for _, a := range c.answering { + a.stopped = true + if a.sub != nil { + subs = append(subs, a.sub) + } + } + for s := range c.proofs { + subs = append(subs, s) + } + c.mu.Unlock() + for _, s := range subs { + if err := s.Drain(); err != nil && !errors.Is(err, nats.ErrBadSubscription) { + c.Logf("[mesh-tools] at its stop the tool runner could not take down its subscription to %s: %v", s.Subject, err) + } + } + _ = c.nc.Flush() +} + +// answersAreDown refuses a new subscription that would answer calls once the runner took its subscriptions down at its stop +// (StopAnswering, design 47 H2 H-A-570 (1)). +func (c *Conn) answersAreDown(subject string) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.answersDown { + return fmt.Errorf("%s is not served: at its stop the tool runner took down every subscription it answers calls on", subject) + } + return nil +} + // Close unsubscribes everything and drains, so an in-flight reply is finished rather than dropped. func (c *Conn) Close() { c.mu.Lock() diff --git a/node-tools/internal/bus/caller_bus_test.go b/node-tools/internal/bus/caller_bus_test.go index 76df908..2460a2e 100644 --- a/node-tools/internal/bus/caller_bus_test.go +++ b/node-tools/internal/bus/caller_bus_test.go @@ -244,22 +244,20 @@ func TestACallWaitsTheBoundItsVerbNamesAndTimesOutThere(t *testing.T) { } } -// stoppingFault is the error a stopping tool runner's drain hands for a call it does not take (launch's afterStop). -type stoppingFault struct{} - -func (stoppingFault) Error() string { return "not taken: the tool runner is stopping" } -func (stoppingFault) ErrorKind() string { return "stopping" } - -// A call a stopping tool runner does not take is answered the typed fault stopping, never silence, and its caller is -// handed that kind as such, beside the answerer's words; a plain refusal carries no kind (design 47 H2 H-A-542). -func TestAStoppingRunnersFaultReachesItsCallerByItsKind(t *testing.T) { +// 721/AC4: once told to stop, the tool runner unsubscribes from every subject it answers calls on before it finishes the +// calls in flight (design 47 H2 H-A-570 (1)): a call heard after the stop began gets no answer from it, no typed fault, and its +// caller meets no responders at once; the call in flight at the stop is still answered; a subject served once the stop began +// is not subscribed, and says so. +func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T) { url := mt.URL(t) server := dial(t, url, "ledger", "anchor", "") + began, release := make(chan struct{}, 1), make(chan struct{}) stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.who", func(_, _ string, body json.RawMessage) (any, error) { - if strings.Contains(string(body), "plain") { - return nil, errors.New("ledger keeps no such key") + if strings.Contains(string(body), "held") { + began <- struct{}{} + <-release } - return nil, fmt.Errorf("ledger's who: %w", stoppingFault{}) + return map[string]any{"who": "ledger"}, nil }) if err != nil { t.Fatal(err) @@ -267,13 +265,29 @@ func TestAStoppingRunnersFaultReachesItsCallerByItsKind(t *testing.T) { defer stop() server.Flush() asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools") - _, err = asker.Ask("ledger.who", map[string]any{}, "") - var kinded interface{ ErrorKind() string } - if !errors.As(err, &kinded) || kinded.ErrorKind() != "stopping" || !strings.Contains(err.Error(), "the tool runner is stopping") { - t.Errorf("the call was answered %v, want the typed fault stopping with the answerer's words", err) + held := make(chan error, 1) + go func() { + _, err := asker.AskWithin("ledger.who", map[string]any{"held": true}, "", 10*time.Second) + held <- err + }() + select { + case <-began: + case <-time.After(10 * time.Second): + t.Fatal("the call to hold never reached the runner") } - _, err = asker.Ask("ledger.who", map[string]any{"plain": true}, "") - if err == nil || errors.As(err, &kinded) || err.Error() != "ledger keeps no such key" { - t.Errorf("a plain refusal was answered %v, want its words and no kind", err) + server.StopAnswering() + at := time.Now() + answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", 5*time.Second) + if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > time.Second { + t.Errorf("a call after the stop began was answered %s, %v in %s; want no responders at once", answered.Result, err, took) + } + if _, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.late", func(string, string, json.RawMessage) (any, error) { + return nil, nil + }); err == nil || !strings.Contains(err.Error(), "took down every subscription") { + t.Errorf("a subject served once the stop began was subscribed (%v), want it refused and said", err) + } + close(release) + if err := <-held; err != nil { + t.Errorf("the call in flight at the stop ended %v, want it answered", err) } } diff --git a/node-tools/internal/bus/seat.go b/node-tools/internal/bus/seat.go index b5e9e99..a67febd 100644 --- a/node-tools/internal/bus/seat.go +++ b/node-tools/internal/bus/seat.go @@ -195,8 +195,8 @@ func (c *Conn) SeatProve(module, subject string, body json.RawMessage) (json.Raw } // SeatAnswer answers every proof on a subject the module's seat traffic lists among its answers, with what -// answer returns. A returned error is answered as `{"error": ""}`, with its `error-kind` when it names one (a proof -// after the stop: stopping, design 47 H2 H-A-542), never as silence, but for one that says it is unanswered (cut at the bound). +// answer returns. A returned error is answered as `{"error": ""}`, never as silence, but for one that says it is +// unanswered (a proof after the stop or cut at the bound). The runner's stop takes the subscription down (StopAnswering). func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, body json.RawMessage) (json.RawMessage, error)) (func(), error) { t, err := c.trafficOf(module) if err != nil { @@ -210,6 +210,9 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo return nil, fmt.Errorf("%s does not answer %s: its membership lists %s (novox/hq ADR 0259)", module, subject, strings.Join(t.Answers, ", ")) } + if err := c.answersAreDown(subject); err != nil { + return nil, err + } sub, err := c.nc.Subscribe(subject, func(msg *nats.Msg) { if msg.Reply == "" { return @@ -220,19 +223,14 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo return } out, err := answer(msg.Subject, body) - // A proof cut at the runner's drain bound is answered nothing, as answerCalledOn does (design 47 H2 §813 (12), - // H-A-369); one after the stop is answered stopping below (H-A-542). + // A proof arriving after the runner's stop, or cut at its bound, is answered nothing, as answerCalledOn does + // (design 47 H2 §813 (12), H-A-369). var unanswered interface{ Unanswered() bool } if errors.As(err, &unanswered) && unanswered.Unanswered() { return } if err != nil { - said := map[string]string{"error": err.Error()} - // A typed fault beside the words: a stopping tool runner's stopping (design 47 H2 H-A-542). - if kind := errorKindOf(err); kind != "" { - said["error-kind"] = kind - } - b, _ := json.Marshal(said) + b, _ := json.Marshal(map[string]string{"error": err.Error()}) _ = msg.Respond(b) return } @@ -247,8 +245,22 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo return nil, err } c.track(sub) + // Kept among the proofs the stop takes down (design 47 H2 H-A-570 (1)). + c.mu.Lock() + if c.proofs == nil { + c.proofs = map[*nats.Subscription]bool{} + } + c.proofs[sub] = true + c.mu.Unlock() var once sync.Once - return func() { once.Do(func() { _ = sub.Unsubscribe() }) }, nil + return func() { + once.Do(func() { + c.mu.Lock() + delete(c.proofs, sub) + c.mu.Unlock() + _ = sub.Unsubscribe() + }) + }, nil } // Work is one message a holder took from a seat's work queue. diff --git a/node-tools/internal/bus/seat_test.go b/node-tools/internal/bus/seat_test.go index 5ddfe59..4b06214 100644 --- a/node-tools/internal/bus/seat_test.go +++ b/node-tools/internal/bus/seat_test.go @@ -181,9 +181,6 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) { if string(body) == `{"cut":true}` { return nil, unansweredProof{} } - if string(body) == `{"stopping":true}` { - return nil, stoppingFault{} - } return json.RawMessage(`{"linked":true}`), nil }) if err != nil { @@ -198,11 +195,6 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) { if string(answer) != `{"linked":true}` { t.Fatalf("the proof was answered %s", answer) } - // A proof after the stop is answered the typed fault stopping, never silence (design 47 H2 H-A-542). - if raw, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.telegram", json.RawMessage(`{"stopping":true}`)); err != nil || - !strings.Contains(string(raw), `"error-kind":"stopping"`) { - t.Errorf("a proof after the stop was answered %s, %v; want its error-kind stopping", raw, err) - } // A proof arriving after the stop, or cut at the bound, is answered nothing (design 47 H2 §813 (12), H-A-369): the // answerer handles proofs in order, so the first reply on one inbox after a cut proof and a whole one is the whole one's. raw, err := nats.Connect(mt.URL(t)) @@ -237,6 +229,18 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) { } } } + // 721/AC4: at its stop the runner takes its proofs' subscriptions down with the rest (design 47 H2 H-A-570 (1)): a proof + // after it meets no responders, never an answer of the old runner's, and a proof answered after it is not subscribed. + conn.StopAnswering() + if raw, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.telegram", json.RawMessage(`{"code":"123456"}`)); err == nil || + !strings.Contains(err.Error(), "nothing answers") { + t.Errorf("a proof after the stop was answered %s, %v; want no responders", raw, err) + } + if _, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(string, json.RawMessage) (json.RawMessage, error) { + return nil, nil + }); err == nil { + t.Error("a proof answered after the stop was subscribed") + } } func TestAnAskerReadsItsOwnRecordAndNoOther(t *testing.T) { diff --git a/node-tools/internal/launch/drain.go b/node-tools/internal/launch/drain.go index def11f3..c9cc604 100644 --- a/node-tools/internal/launch/drain.go +++ b/node-tools/internal/launch/drain.go @@ -33,21 +33,18 @@ var asks = struct { ended chan struct{} }{of: map[uint64]*inFlight{}} -// ErrorKindStopping is the typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542, -// amending H-A-369): the answer's `error-kind`, so its caller asks again and meets the new runner; never silence. -const ErrorKindStopping = "stopping" - -// afterStop is an ask made after the stop began: it is not taken, and its caller is answered the typed fault stopping -// (ErrorKind), never silence, so the caller asks again after a pause and meets the new runner (design 47 H2 §813 (12) as -// H-A-369 and H-A-542 amend it). +// afterStop is an ask made after the stop began that still reached the runner: a call the bus handed it before its +// subscriptions were down, or a message a consumer hands on. It is not taken and its caller is answered nothing, never +// refused, so the caller's kept call paces and meets the new runner (design 47 H2 §813 (12) as H-A-369 has it); a call made +// once the subscriptions are down meets no responders instead (H-A-570 (1)). type afterStop struct{ module, verb string } func (e *afterStop) Error() string { - return fmt.Sprintf("%s's %s was not taken: the tool runner is stopping; ask again, the new runner answers it", e.module, e.verb) + return fmt.Sprintf("%s's %s was not taken: the tool runner is stopping, and a call after its stop is answered nothing", e.module, e.verb) } -// ErrorKind is the typed fault the call is answered with: stopping. -func (e *afterStop) ErrorKind() string { return ErrorKindStopping } +// Unanswered says the call is left without an answer, so its kept call asks again and meets the new runner. +func (e *afterStop) Unanswered() bool { return true } // cutCall is a call the drain cut at its bound. Its caller is answered nothing, so it sees a transport fault (§813 (12)): the // bus reads Unanswered and sends no reply. @@ -60,7 +57,7 @@ func (e *cutCall) Error() string { // Unanswered says the call is left without an answer, so its caller sees a transport fault. func (e *cutCall) Unanswered() bool { return true } -// begin records an ask about to be made; once the runner drains it takes none, and its caller is answered stopping. +// begin records an ask about to be made; once the runner drains it takes none, and its caller is answered nothing. func begin(module, verb string) (uint64, *inFlight, error) { asks.mu.Lock() defer asks.mu.Unlock() @@ -86,7 +83,8 @@ func end(id uint64) { } } -// Drain is the runner's stop (design 47 H2 §813 (12), H-A-342 (2), H-A-353): from now on no new ask is made of any bundle, the +// Drain is the runner's stop (design 47 H2 §813 (12), H-A-342 (2), H-A-353), once it took down every subscription it answers +// calls on (the bus's StopAnswering, H-A-570 (1)): from now on no new ask is made of any bundle, the // asks in flight are waited for within bound, and each still in flight at the bound is cut, with a journal line naming the // bundle, the verb and the call's age; its caller is answered nothing. It returns once no ask is in flight or the bound // passed; the runner then stops its bundles itself. diff --git a/node-tools/internal/launch/error_code_test.go b/node-tools/internal/launch/error_code_test.go index d253e28..e72be33 100644 --- a/node-tools/internal/launch/error_code_test.go +++ b/node-tools/internal/launch/error_code_test.go @@ -34,16 +34,6 @@ func TestALostWriteIsAnsweredWithItsOwnCodeAndNothingElseIs(t *testing.T) { if got := errorCode(errors.New("issues keeps no state numbers")); got == CodeChanged || got != -32000 { t.Errorf("a plain refusal is answered %d", got) } - // A typed fault reaches the bundle as its kind in the error's data, wrapped or not (design 47 H2 H-A-542); a plain - // refusal carries none. - for _, err := range []error{&afterStop{module: "registry", verb: "publish"}, fmt.Errorf("asked: %w", &afterStop{module: "registry", verb: "publish"})} { - if data, _ := errorAnswer(err)["data"].(map[string]any); data["error-kind"] != ErrorKindStopping { - t.Errorf("%v is answered %v, want its error-kind stopping", err, errorAnswer(err)) - } - } - if _, has := errorAnswer(errors.New("issues keeps no state numbers"))["data"]; has { - t.Error("a plain refusal is answered an error-kind") - } } // A bundle that answers the handshake and an empty tool list, and notes each start and its pid in $OUT. @@ -65,7 +55,7 @@ done // itself is stopping, none is, by a restart or by a call. // // **The tool runner drains at a stop** (design 47 H2 §813 (12), H-A-342 (2), H-A-353, H-A-369): once it drains, no new call is -// taken and its caller is answered the typed fault stopping (H-A-542), never silence; a call +// taken and its caller is answered nothing (Unanswered), never refused; a call // in flight that ends within the drain bound is answered; one still in flight at the bound is cut, said with its bundle, its verb // and its age, and left unanswered (Unanswered, so the bus sends its caller nothing: a transport fault). func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) { @@ -81,7 +71,7 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) { }{ {"a bundle that dies while the runtime serves", false, 2, 0, false}, {"a bundle signalled with the stopping runtime", true, 1, 0, false}, - {"a call that ends within the drain bound is answered, and a call after the stop is answered stopping", false, 0, 10 * time.Second, true}, + {"a call that ends within the drain bound is answered, and a call after the stop is answered nothing", false, 0, 10 * time.Second, true}, {"a call that outlives the drain bound is cut and said", false, 0, 50 * time.Millisecond, false}, } { t.Run(row.name, func(t *testing.T) { @@ -140,12 +130,13 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) { } } if row.release { - // A call made after the stop is answered the typed fault stopping, never silence (H-A-542). - var kinded interface{ ErrorKind() string } + // 721/AC4: a call that still reaches the runner after its stop began gets no answer from it, no typed fault + // (H-A-570, withdrawing H-A-542's answer): every later one meets no responders on the bus. var unanswered interface{ Unanswered() bool } - if _, err := run("", json.RawMessage(`{}`)); !errors.As(err, &kinded) || kinded.ErrorKind() != ErrorKindStopping || - errors.As(err, &unanswered) { - t.Errorf("a call made after the stop ended %v, want it answered stopping, never silence", err) + var kinded interface{ ErrorKind() string } + if _, err := run("", json.RawMessage(`{}`)); !errors.As(err, &unanswered) || !unanswered.Unanswered() || + errors.As(err, &kinded) { + t.Errorf("a call made after the stop ended %v, want it answered nothing, never refused", err) } f, err := os.OpenFile(hold, os.O_WRONLY, 0) if err != nil { diff --git a/node-tools/internal/launch/launch.go b/node-tools/internal/launch/launch.go index 11ad9b2..22996f0 100644 --- a/node-tools/internal/launch/launch.go +++ b/node-tools/internal/launch/launch.go @@ -634,7 +634,8 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an return } if err != nil { - _ = c.write(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": errorAnswer(err)}) + _ = c.write(map[string]any{"jsonrpc": "2.0", "id": m.ID, + "error": map[string]any{"code": errorCode(err), "message": err.Error()}}) return } _ = c.write(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": result}) @@ -987,18 +988,6 @@ func (c *child) deathReason() error { // stdio.CodeChanged): told by its code, never by its words (novox/hq ADR 0259). const CodeChanged = -32010 -// errorAnswer is the JSON-RPC error a bundle is answered err with: its code and words, and, when err names a typed fault -// (ErrorKind() string: a stopping tool runner's stopping, design 47 H2 H-A-542), that kind as the error's data -// `error-kind`, so mesh-sdk's stdio tells it by its kind, never by its words. -func errorAnswer(err error) map[string]any { - answer := map[string]any{"code": errorCode(err), "message": err.Error()} - var kinded interface{ ErrorKind() string } - if errors.As(err, &kinded) && kinded.ErrorKind() != "" { - answer["data"] = map[string]any{"error-kind": kinded.ErrorKind()} - } - return answer -} - // errorCode is the code an error is answered to a bundle with: a lost compare-and-set's own, else the // general one. func errorCode(err error) int { -- 2.54.0 From 5d87f7d375556ae510fb135bbfc946d981644f14 Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 16:51:00 +0100 Subject: [PATCH 2/2] node-tools: a serve racing the runner's stop is taken down too (issue 721, review round 1) A tool's or a proof's subscription made while the stop took its snapshot was registered after it, so it stayed subscribed until the close and its callers waited out their bound instead of meeting no responders (the review's probe: 4 of 2000 rounds). Now a new answering subscription is kept, and the stop checked again, in one section under the lock the stop takes its subscriptions down under; when the stop began meanwhile, it is drained and the serve refused. Tests: 721/AC4 rows in the bus (a tool's serve and a proof answerer each run the stop between their subscription and its keeping, through a test hook, and are refused; their callers meet no responders), failing without the locked check. Builds: design 47 H2 H-A-570 (1) --- node-tools/internal/bus/bus.go | 46 +++++++++++++++++++--- node-tools/internal/bus/caller_bus_test.go | 13 ++++++ node-tools/internal/bus/export_test.go | 8 ++++ node-tools/internal/bus/seat.go | 17 ++++---- node-tools/internal/bus/seat_test.go | 12 +++++- 5 files changed, 82 insertions(+), 14 deletions(-) diff --git a/node-tools/internal/bus/bus.go b/node-tools/internal/bus/bus.go index f905753..2f8ec67 100644 --- a/node-tools/internal/bus/bus.go +++ b/node-tools/internal/bus/bus.go @@ -205,6 +205,9 @@ type Conn struct { // answersDown is set once the runner took down every subscription it answers calls on at its stop (StopAnswering): // from then on it subscribes none again, so every later call meets no responders here (design 47 H2 H-A-570 (1)). answersDown bool + // subscribedHook, when a test set it (SetSubscribedHook), is called between making an answering subscription and keeping + // it, so a test runs the stop in between (tests only). + subscribedHook func(subject string) // RetryAfter is how long after a refusal a subscription is asked for again, by attempt; past the // last, it is given up and said. A variable so a test need not wait minutes. RetryAfter []time.Duration @@ -746,11 +749,13 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e if err != nil { return func() {}, err } - c.track(sub) + c.subscribed(subject) a := &answered{subject: subject, queue: queue, cb: cb, sub: sub} - c.mu.Lock() - c.answering[answeringKey(subject, queue)] = a - c.mu.Unlock() + // Kept, or taken down, under the one lock the stop takes its subscriptions down under, so a serve racing the stop is + // never missed by it (design 47 H2 H-A-570 (1)). + if err := c.keepAnswering(sub, func() { c.answering[answeringKey(subject, queue)] = a }); err != nil { + return func() {}, err + } return func() { c.mu.Lock() a.stopped = true @@ -1133,11 +1138,42 @@ func (c *Conn) answersAreDown(subject string) error { c.mu.Lock() defer c.mu.Unlock() if c.answersDown { - return fmt.Errorf("%s is not served: at its stop the tool runner took down every subscription it answers calls on", subject) + return answersDownError(subject) } return nil } +func answersDownError(subject string) error { + return fmt.Errorf("%s is not served: at its stop the tool runner took down every subscription it answers calls on", subject) +} + +// keepAnswering keeps a subscription just made that answers calls, with keep registering it, in one section under c.mu, +// the lock StopAnswering takes its subscriptions down under: when the stop began meanwhile, it drains the subscription +// instead and refuses it, so none outlives the stop (design 47 H2 H-A-570 (1)). +func (c *Conn) keepAnswering(sub *nats.Subscription, keep func()) error { + c.mu.Lock() + if c.answersDown { + c.mu.Unlock() + _ = sub.Drain() + return answersDownError(sub.Subject) + } + c.subs = append(c.subs, sub) + keep() + c.mu.Unlock() + return nil +} + +// subscribed calls the connection's subscribedHook, when a test set one, between making an answering subscription and +// keeping it. +func (c *Conn) subscribed(subject string) { + c.mu.Lock() + hook := c.subscribedHook + c.mu.Unlock() + if hook != nil { + hook(subject) + } +} + // Close unsubscribes everything and drains, so an in-flight reply is finished rather than dropped. func (c *Conn) Close() { c.mu.Lock() diff --git a/node-tools/internal/bus/caller_bus_test.go b/node-tools/internal/bus/caller_bus_test.go index 2460a2e..e376bd7 100644 --- a/node-tools/internal/bus/caller_bus_test.go +++ b/node-tools/internal/bus/caller_bus_test.go @@ -290,4 +290,17 @@ func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T if err := <-held; err != nil { t.Errorf("the call in flight at the stop ended %v, want it answered", err) } + // A serve racing the stop (a membership change, a bundle's new tool): the stop begins between its subscription and its + // keeping, and still the subject is not left answered, its subscription taken down and the serve refused. + raced := dial(t, url, "ledger", "anchor", "") + var once sync.Once + bus.SetSubscribedHook(raced, func(string) { once.Do(raced.StopAnswering) }) + if _, err := raced.HandleSubjectCalled("mesh.mod.ledger.tool.raced", func(string, string, json.RawMessage) (any, error) { + return map[string]any{"raced": true}, nil + }); err == nil { + t.Error("a serve that raced the stop was kept, want it refused") + } + if answered, err := asker.AskWithin("ledger.raced", map[string]any{}, "", 5*time.Second); !errors.Is(err, bus.ErrNoResponders) { + t.Errorf("a call of a tool whose serve raced the stop was answered %s, %v; want no responders", answered.Result, err) + } } diff --git a/node-tools/internal/bus/export_test.go b/node-tools/internal/bus/export_test.go index 92420cd..7efd40d 100644 --- a/node-tools/internal/bus/export_test.go +++ b/node-tools/internal/bus/export_test.go @@ -6,3 +6,11 @@ func SetTickHook(f func()) (restore func()) { tickHook = f return func() { tickHook = old } } + +// SetSubscribedHook makes c call f with the subject between making each answering subscription and keeping it, so a test can +// run the stop in between (design 47 H2 H-A-570 (1)). +func SetSubscribedHook(c *Conn, f func(subject string)) { + c.mu.Lock() + c.subscribedHook = f + c.mu.Unlock() +} diff --git a/node-tools/internal/bus/seat.go b/node-tools/internal/bus/seat.go index a67febd..d79a3b5 100644 --- a/node-tools/internal/bus/seat.go +++ b/node-tools/internal/bus/seat.go @@ -244,14 +244,17 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo if err != nil { return nil, err } - c.track(sub) - // Kept among the proofs the stop takes down (design 47 H2 H-A-570 (1)). - c.mu.Lock() - if c.proofs == nil { - c.proofs = map[*nats.Subscription]bool{} + c.subscribed(subject) + // Kept among the proofs the stop takes down, or taken down at once when the stop began meanwhile (design 47 H2 H-A-570 + // (1)). + if err := c.keepAnswering(sub, func() { + if c.proofs == nil { + c.proofs = map[*nats.Subscription]bool{} + } + c.proofs[sub] = true + }); err != nil { + return nil, err } - c.proofs[sub] = true - c.mu.Unlock() var once sync.Once return func() { once.Do(func() { diff --git a/node-tools/internal/bus/seat_test.go b/node-tools/internal/bus/seat_test.go index 4b06214..372ac91 100644 --- a/node-tools/internal/bus/seat_test.go +++ b/node-tools/internal/bus/seat_test.go @@ -230,8 +230,16 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) { } } // 721/AC4: at its stop the runner takes its proofs' subscriptions down with the rest (design 47 H2 H-A-570 (1)): a proof - // after it meets no responders, never an answer of the old runner's, and a proof answered after it is not subscribed. - conn.StopAnswering() + // after it meets no responders, never an answer of the old runner's, and a proof answered after it is not subscribed. The + // stop begins here while a second answerer of the proofs subscribes, between its subscription and its keeping: that one + // is taken down and refused too. + var once sync.Once + bus.SetSubscribedHook(conn, func(string) { once.Do(conn.StopAnswering) }) + if _, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(string, json.RawMessage) (json.RawMessage, error) { + return json.RawMessage(`{"raced":true}`), nil + }); err == nil { + t.Error("a proof answerer that raced the stop was kept, want it refused") + } if raw, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.telegram", json.RawMessage(`{"code":"123456"}`)); err == nil || !strings.Contains(err.Error(), "nothing answers") { t.Errorf("a proof after the stop was answered %s, %v; want no responders", raw, err) -- 2.54.0