node-tools: an integration test's wait on the bus takes the test's own deadline, never a few fixed seconds (issue 1754) #92

Merged
mesh-tools merged 2 commits from fix/1754-node-tools-waits into main 2026-11-23 19:19:08 +00:00
24 changed files with 370 additions and 80 deletions
@@ -138,8 +138,8 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
if err != nil {
t.Errorf("serve ended with %v", err)
}
case <-time.After(30 * time.Second):
t.Error("the tool runner did not stop within 30s")
case <-time.After(mt.Bound(t)):
t.Errorf("the tool runner did not stop within %s", mt.Bound(t))
}
})
}
@@ -167,7 +167,7 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
if _, err := ask("seat:node-desk.slow@anchor"); err == nil {
t.Error("the verb that answers after three seconds was answered within its timeout of one second")
}
if took := time.Since(began); took < time.Second || took > 2500*time.Millisecond {
if took := time.Since(began); took < time.Second || took > bus.RequestTimeout/2 { // 1754/AC4
t.Errorf("the verb of a timeout of one second was waited %s, want about one second, not the runner's own %s", took, bus.RequestTimeout)
}
@@ -199,7 +199,7 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
}
readPage := func(cursor string) paged {
t.Helper()
answered, err := asker.AskWithin("ledger.page", map[string]any{"cursor": cursor}, "", 30*time.Second)
answered, err := asker.AskWithin("ledger.page", map[string]any{"cursor": cursor}, "", mt.Bound(t))
var p paged
if err != nil || json.Unmarshal(answered.Result, &p) != nil || p.Error != nil {
t.Fatalf("the page after %q was answered %.300s, %v", cursor, answered.Result, err)
+14 -10
View File
@@ -35,7 +35,7 @@ func grantedBus(t *testing.T, publish map[string][]string) string {
t.Fatal(err)
}
go s.Start()
if !s.ReadyForConnections(10 * time.Second) {
if !s.ReadyForConnections(mt.Bound(t)) {
t.Fatal("the bus did not come up")
}
t.Cleanup(s.Shutdown)
@@ -92,7 +92,7 @@ func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testin
if err != nil {
t.Fatal(err)
}
if took := time.Since(began); took > 2*time.Second {
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after the caller-named call's timeout
t.Errorf("the fall-back took %s", took)
}
if got := h.all(); len(got) != 1 || got[0] != "" || !strings.Contains(string(answered.Result), `"caller":""`) {
@@ -129,7 +129,7 @@ func TestACallerTheBusRefusesTheCallerNamedSubjectFallsBackAtOnce(t *testing.T)
t.Errorf("the refusal was not said: %v", said)
}
mu.Unlock()
if took := time.Since(began); took > 3*time.Second {
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after RequestTimeout
t.Errorf("the refused caller-named call held the caller %s", took)
}
if got := h.all(); len(got) != 1 || got[0] != "" {
@@ -173,7 +173,7 @@ func TestAGrantedCallerIsHeardAsItselfAndCannotNameAnother(t *testing.T) {
if !errors.Is(err, nats.ErrPermissionViolation) {
t.Errorf("the bus said %v, want a permissions violation", err)
}
case <-time.After(3 * time.Second):
case <-time.After(mt.Bound(t)):
t.Error("the bus did not refuse a call naming another caller")
}
if got := h.all(); len(got) != 1 || got[0] != "shanks.node-tools" {
@@ -248,6 +248,10 @@ func TestACallWaitsTheBoundItsVerbNamesAndTimesOutThere(t *testing.T) {
// 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.
// 1754/AC3: its order is held (StopAnswering returns once the bus holds the unsubscriptions), so it needs no clock of its
// own: each call and the held call's arrival wait meshtest.Bound(t), and "at once" is the bus's word, no responders, where a
// subscription left behind would end the call at its bound in a timeout. It failed on a loaded build node (main.505)
// while it asked 1 s of two round trips and 5 s and 10 s of its waits.
func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T) {
url := mt.URL(t)
server := dial(t, url, "ledger", "anchor", "")
@@ -267,18 +271,18 @@ func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
held := make(chan error, 1)
go func() {
_, err := asker.AskWithin("ledger.who", map[string]any{"held": true}, "", 10*time.Second)
_, err := asker.AskWithin("ledger.who", map[string]any{"held": true}, "", mt.Bound(t))
held <- err
}()
select {
case <-began:
case <-time.After(10 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("the call to hold never reached the runner")
}
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 {
at, within := time.Now(), mt.Bound(t)
answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", within)
if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > within/2 {
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) {
@@ -300,7 +304,7 @@ func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T
}); 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) {
if answered, err := asker.AskWithin("ledger.raced", map[string]any{}, "", mt.Bound(t)); !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)
}
}
+1 -1
View File
@@ -137,7 +137,7 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
for n := 0; n < 3; n++ { // three more intervals pass, counted by the loop's own tick
select {
case <-ticks:
case <-time.After(10 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("the heartbeat loop handled no more intervals")
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ func TestAnAnswerLargerThanOneMessage(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "more than the bus carries") {
t.Fatalf("a module's answer too large for one message read as %v", err)
}
if took := time.Since(asked); took > 5*time.Second {
if took := time.Since(asked); took > bus.RequestTimeout/2 { // 1754/AC4: said at once, not at the call's timeout
t.Fatalf("it took %s to say", took)
}
}
+2 -2
View File
@@ -145,7 +145,7 @@ func TestTheHolderTakesItsWorkOnceAndAFailureComesBack(t *testing.T) {
t.Fatal(err)
}
defer stop()
deadline := time.Now().Add(15 * time.Second)
deadline := time.Now().Add(mt.Bound(t))
for {
mu.Lock()
n := len(got)
@@ -212,7 +212,7 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
t.Fatal(err)
}
}
if first, err := replies.NextMsg(30 * time.Second); err != nil || string(first.Data) != `{"linked":true}` {
if first, err := replies.NextMsg(mt.Bound(t)); err != nil || string(first.Data) != `{"linked":true}` {
t.Fatalf("a proof cut at the stop was answered, or the whole one not: %v %v", first, err)
}
if _, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.desktop", json.RawMessage(`{}`)); err == nil {
@@ -117,7 +117,7 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
}
return nil
}
bound := time.After(30 * time.Second)
bound := time.After(mt.Bound(t))
for err := missing(); err != nil; err = missing() {
select {
case <-heard:
+2 -2
View File
@@ -140,7 +140,7 @@ func TestAWatchHoldsWhileItsCurrentValuesKeepArriving(t *testing.T) {
}
select {
case <-first:
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("the bundle was handed no change")
}
stop()
@@ -180,7 +180,7 @@ func TestAWatchIsRefusedWhenNoCurrentValueIsTakenWithinTheBound(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "did not arrive in") {
t.Fatalf("a watch whose first value was never taken: want refused, got %v", err)
}
if took := time.Since(began); took > 3*time.Second {
if took := time.Since(began); took > was/2 { // 1754/AC4: at the bound it was set, half the default StateTimeout it replaced
t.Fatalf("the refusal took %s, far past the bound", took)
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ func TestAnEventADeclaredStreamCarriesIsPublishedOnItsSubjectAlone(t *testing.T)
if got != "mesh.stream.mail.event.mail.home.message.added" {
t.Errorf("published on %s", got)
}
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("the event did not land on its stream's subject")
}
if err := conn.PublishAs("mail", bus.Envelope{Key: "status", Body: json.RawMessage(`{}`)}); err != nil {
+7 -6
View File
@@ -29,7 +29,7 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
t.Fatal(err)
}
go s.Start()
if !s.ReadyForConnections(10 * time.Second) {
if !s.ReadyForConnections(mt.Bound(t)) {
t.Fatal("the bus did not come up")
}
t.Cleanup(s.Shutdown)
@@ -38,7 +38,8 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
// Every subscription refused: answered after the timeout, never at once, in §16's words.
start := time.Now()
_, ok, refused, err := c.HearFirst(context.Background(), []string{other}, 300*time.Millisecond, nil)
if took := time.Since(start); took < 300*time.Millisecond || took > 3*time.Second {
// 1754/AC4: after its timeout, never at once; a wait that never ended would meet the test's own deadline
if took := time.Since(start); took < 300*time.Millisecond {
t.Errorf("a wait refused whole answered after %s, want its timeout of 300ms", took)
}
if ok || err == nil || !strings.Contains(err.Error(), "the bus refused this account a subscription on "+other) ||
@@ -62,7 +63,7 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
}
done := make(chan result, 1)
go func() {
h, ok, refused, err := c.HearFirst(context.Background(), []string{other, granted}, 5*time.Second, nil)
h, ok, refused, err := c.HearFirst(context.Background(), []string{other, granted}, mt.Bound(t), nil)
if !ok && err == nil {
err = errors.New("timed out")
}
@@ -103,12 +104,12 @@ func TestAWaitEndsWhenItsCallerIsGone(t *testing.T) {
before := c.Subscriptions()
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(200*time.Millisecond, cancel)
start := time.Now()
_, ok, _, err := c.HearFirst(ctx, []string{"mesh.mod.mesh-knowledge.event.reviewed"}, time.Minute, nil)
start, within := time.Now(), mt.Bound(t)
_, ok, _, err := c.HearFirst(ctx, []string{"mesh.mod.mesh-knowledge.event.reviewed"}, within, nil)
if ok || !errors.Is(err, context.Canceled) {
t.Errorf("a cancelled wait answered %v, %v", ok, err)
}
if took := time.Since(start); took > 2*time.Second {
if took := time.Since(start); took > within/2 { // 1754/AC4: at the cancel, not at its own timeout
t.Errorf("a cancelled wait ended after %s", took)
}
if after := c.Subscriptions(); after != before {
+1 -1
View File
@@ -210,7 +210,7 @@ func TestTheMeshsToolsAreFoundByAddress(t *testing.T) {
}
defer stopLate()
var found string
for i := 0; i < 30; i++ {
for deadline := time.Now().Add(mt.Bound(t)); time.Now().Before(deadline); {
found, _ = call(t, endpoint, "mesh_search", map[string]any{"query": "gamma given"})
if strings.Contains(found, "desk/gamma.given") {
break
+18 -19
View File
@@ -124,14 +124,14 @@ func TestMeshWaitAnswersTheFirstMatchingEvent(t *testing.T) {
var got answer
select {
case got = <-done:
case <-time.After(10 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("mesh_wait did not answer the matching event")
}
if got.isErr {
t.Fatalf("mesh_wait failed: %s", got.text)
}
if got.at.Sub(published) > time.Second {
t.Errorf("answered %s after the event was published, want within a second", got.at.Sub(published))
if got.at.Sub(published) > 10*time.Second { // 1754/AC4: half its timeout of 20 s, on the event and not at its timeout
t.Errorf("answered %s after the event was published, want on the event, not at its timeout", got.at.Sub(published))
}
var heard heardAnswer
if err := json.Unmarshal([]byte(got.text), &heard); err != nil {
@@ -161,7 +161,7 @@ func TestMeshWaitAnswersTheFirstMatchingEvent(t *testing.T) {
h.Published != nil || !strings.Contains(heard.Read, "claude_code_answer") {
t.Errorf("the asker's decided: %s", got.text)
}
case <-time.After(10 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("mesh_wait did not answer the asker's decided")
}
}
@@ -172,7 +172,7 @@ func TestMeshWaitSaysItTimedOutAndKeepsNothing(t *testing.T) {
before := s.conn.Subscriptions()
start := time.Now()
text, isErr := callWait(s, map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "timeout": 1})
if took := time.Since(start); took < time.Second || took > 3*time.Second {
if took := time.Since(start); took < time.Second || took > WaitDefault/2 { // 1754/AC4: at its timeout, not WaitDefault's
t.Errorf("a one-second wait took %s", took)
}
// Before the catalog half is read, names are not checked, and the answer says so (design 34 every-event §14).
@@ -219,13 +219,12 @@ func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
{map[string]any{"subjects": []any{}}, "at least one event"},
{map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "from": "bench"}, "seat, module or stream"},
} {
c.args["timeout"] = 1
start := time.Now()
start := time.Now() // no timeout: the wait's would be WaitDefault
text, isErr := callWait(s, c.args)
if !isErr || !strings.Contains(text, c.says) || strings.Contains(text, "manifest") {
t.Errorf("%v: %s, want refused saying %q", c.args, text, c.says)
}
if took := time.Since(start); took > 500*time.Millisecond {
if took := time.Since(start); took > WaitDefault/2 { // 1754/AC4: half the wait's timeout, refused before any wait
t.Errorf("%v was refused after %s, want at once", c.args, took)
}
}
@@ -268,7 +267,7 @@ func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
t.Fatal(err)
}
go b.Start()
if !b.ReadyForConnections(10 * time.Second) {
if !b.ReadyForConnections(mt.Bound(t)) {
t.Fatal("the bus did not come up")
}
t.Cleanup(b.Shutdown)
@@ -280,7 +279,7 @@ func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
t.Cleanup(conn.Close)
start := time.Now()
text, isErr := callWait(NewSurface(conn, nil, "desk.node-tools"), map[string]any{"subjects": []any{"mesh-delivery-view.delivered"}, "timeout": 1})
if took := time.Since(start); took < time.Second || took > 3*time.Second {
if took := time.Since(start); took < time.Second || took > WaitDefault/2 { // 1754/AC4: at its timeout, not WaitDefault's
t.Errorf("a wait the bus refused whole answered after %s, want its timeout of 1s", took)
}
if !isErr || !strings.Contains(text, "the bus refused this account a subscription on mesh.seat.mesh-delivery-view.event.delivered") ||
@@ -369,7 +368,7 @@ func markedWaitsOnAWarrant(t *testing.T, s *Surface, mesh *mt.Mesh) {
if !strings.Contains(got, "make this wait again within 30 minutes") {
t.Errorf("a long wait chosen while it waits: %s", got)
}
case <-time.After(10 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("a long marked wait was not answered at the choice")
}
before := g.conn.Subscriptions()
@@ -644,12 +643,10 @@ func TestMeshWaitEndsWhenItsClientHangsUp(t *testing.T) {
return nil
})
cancel()
start := time.Now()
for s.conn.Subscriptions() > before {
if time.Since(start) > 3*time.Second {
t.Fatalf("%d subscriptions 3s after the client hung up, %d before the wait", s.conn.Subscriptions(), before)
for deadline := time.Now().Add(mt.Bound(t)); s.conn.Subscriptions() > before; time.Sleep(20 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatalf("%d subscriptions at the test's bound after the client hung up, %d before the wait", s.conn.Subscriptions(), before)
}
time.Sleep(20 * time.Millisecond)
}
}
@@ -676,11 +673,13 @@ func TestMeshWaitEndsWhenTheConsoleCloses(t *testing.T) {
go func() { closed <- up.Close() }()
select {
case <-closed:
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatal("closing the console waited on a mesh_wait in flight")
}
if took := time.Since(start); took > 3*time.Second {
t.Errorf("closing took %s", took)
// 1754/AC4: half the bound it tells apart, the console's own backstop ShutdownWithin, which ends a close whose waits
// were never cancelled
if took := time.Since(start); took > ShutdownWithin/2 {
t.Errorf("closing took %s, want the waits cancelled at once, not ended by the backstop of %s", took, ShutdownWithin)
}
mt.Until(t, func() error {
if s.conn.Subscriptions() > before {
+43 -8
View File
@@ -57,9 +57,9 @@ func URL(t *testing.T) string {
t.Fatalf("a bus for this test could not be made: %v", err)
}
go s.Start()
if !s.ReadyForConnections(30 * time.Second) {
if !s.ReadyForConnections(Bound(t)) {
s.Shutdown()
t.Fatal("a bus for this test did not come up within 30s")
t.Fatal("a bus for this test did not come up within its bound")
}
url := s.ClientURL()
buses.Store(t, url)
@@ -260,17 +260,52 @@ func Fixture(name string) string {
return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name)
}
// Until retries while the bus answers "no responders" — something not yet served. Its bound only ends a wait that never
// hears what it waits for: 30 s, which a loaded machine stays within, where the earlier 5 s did not (design 47 H,
// H-A-363; fix-a-bug-met-twice: a fixed bound a loaded machine overruns, fixed for every package that waits here).
// Bound is how long, from now, a test waits for what the bus is to carry (an event, an answer, a watch's change, a key's
// expiry, a bus coming up) before it fails: the test's own deadline, go test's -timeout that the build step sets, less
// cleanupMargin for the test's cleanup, never a few seconds written into a test (issue 1754: a 1 s key's expire not heard
// in 5 s on a loaded build node; the lead's answers on the issue of 2026-11-23 20:00 and of round 2, principles 11 and 7;
// 1754/AC1). It only ends a wait that never hears what it waits for: a wait that hears ends then, so a passing test is no
// longer for it. With less than the margin left it answers what is left, at least a millisecond, so a cleanup's wait runs
// to the deadline and go test's own timeout names the test (principle 3).
func Bound(t *testing.T) time.Duration {
deadline, ok := t.Deadline()
if !ok {
deadline = started.Add(goTestTimeout)
}
return boundOf(time.Until(deadline))
}
// boundOf is Bound for what is left until the deadline.
func boundOf(left time.Duration) time.Duration {
if left > cleanupMargin {
return left - cleanupMargin
}
return max(left, time.Millisecond)
}
// cleanupMargin is what Bound leaves of a test's deadline for its cleanup: 30 s, the longest bound these tests used
// (Until's), which covers their cleanups (the lead's answer on issue 1754, round 2).
const cleanupMargin = 30 * time.Second
// goTestTimeout is go test's own default -timeout, the deadline of a run that names none, from the run's start.
const goTestTimeout = 10 * time.Minute
// started is when this test binary began.
var started = time.Now()
// Until retries while the bus answers "no responders" — something not yet served — until the test's Bound has passed: a
// deadline, so a try that itself waits does not multiply it (fix-a-bug-met-twice: a fixed bound a loaded machine overruns,
// fixed for every package that waits here).
func Until(t *testing.T, try func() error) {
t.Helper()
var err error
for i := 0; i < 300; i++ {
for deadline := time.Now().Add(Bound(t)); ; time.Sleep(100 * time.Millisecond) {
if err = try(); err == nil {
return
}
time.Sleep(100 * time.Millisecond)
if time.Now().After(deadline) {
break
}
}
t.Fatal(err)
}
@@ -381,7 +416,7 @@ func (m *Mesh) BucketKeyTTL(t *testing.T, name string) {
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), Bound(t))
defer cancel()
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1, MaxValueSize: 256 * 1024,
LimitMarkerTTL: time.Minute}); err != nil {
+252
View File
@@ -0,0 +1,252 @@
package meshtest
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
// 1754/AC1: a wait's bound is the test's deadline less the cleanup margin, and what is left once less than the margin is,
// never zero or less (the lead's answer on issue 1754, round 2).
func TestABoundIsTheTestsDeadlineLessItsCleanupMargin(t *testing.T) {
for _, row := range []struct{ left, want time.Duration }{
{10 * time.Minute, 10*time.Minute - cleanupMargin},
{cleanupMargin + time.Second, time.Second},
{cleanupMargin, cleanupMargin},
{time.Second, time.Second},
{0, time.Millisecond},
{-time.Minute, time.Millisecond},
} {
if got := boundOf(row.left); got != row.want {
t.Errorf("with %s left the bound is %s, want %s", row.left, got, row.want)
}
}
deadline, ok := t.Deadline()
if !ok {
deadline = started.Add(goTestTimeout)
}
left := time.Until(deadline)
if b := Bound(t); b <= 0 || b > left-cleanupMargin {
t.Errorf("this test's bound is %s, with %s left until its deadline", b, left)
}
}
// waitBound is, for each call that waits, which argument is its bound.
var waitBound = map[string]int{
"After": 0, "NewTimer": 0, "WithTimeout": 1, "NextMsg": 0, "ReadyForConnections": 0, "Request": 2, "RequestMsg": 1,
"AskWithin": 3, "HearFirst": 2, "MaxWait": 0,
}
// 1754/AC1: no test that starts a bus (a test file importing this package, and this package itself) waits for what the
// bus carries with a fixed bound of a second or more: each such wait takes the test's own deadline, Bound(t). A few
// seconds is what a loaded build node overran (issue 1754: state_counter_test.go's 5 s for a 1 s key's expire, failed on
// a build node); a bound under a second is the bound under test or the window an absence is given, and is not this guard's.
func TestNoWaitOnTheBusHasAFixedBound(t *testing.T) {
root := moduleRoot()
var found []string
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if path != root && (d.Name() == "node_modules" || strings.HasPrefix(d.Name(), ".")) {
return filepath.SkipDir
}
return nil
}
dir := filepath.Dir(path)
ours := filepath.Base(dir) == "meshtest" && filepath.Base(filepath.Dir(dir)) == "internal"
if !strings.HasSuffix(path, ".go") || !ours && !strings.HasSuffix(path, "_test.go") {
return nil
}
found = append(found, fixedWaits(t, path, ours)...)
return nil
})
if err != nil {
t.Fatal(err)
}
if len(found) > 0 {
t.Errorf("waits on the bus with a fixed bound, which a loaded build node overruns: give each the test's own, meshtest.Bound(t)\n%s",
strings.Join(found, "\n"))
}
}
// fixedWaits are the waits of one file that starts a bus whose bound is a constant of a second or more.
func fixedWaits(t *testing.T, path string, ours bool) []string {
t.Helper()
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
t.Fatal(err)
}
if !ours && !importsMeshtest(f) {
return nil
}
consts := packageConsts(t, filepath.Dir(path))
var found []string
flag := func(what string, bound ast.Expr) {
if d, ok := duration(bound, consts); ok && d >= time.Second {
rel, _ := filepath.Rel(moduleRoot(), fset.Position(bound.Pos()).Filename)
found = append(found, rel+":"+strconv.Itoa(fset.Position(bound.Pos()).Line)+": "+what+" "+d.String())
}
}
ast.Inspect(f, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.CallExpr:
name := ""
switch fn := n.Fun.(type) {
case *ast.SelectorExpr:
name = fn.Sel.Name
case *ast.Ident:
name = fn.Name
}
if i, ok := waitBound[name]; ok && i < len(n.Args) {
flag(name, n.Args[i])
}
case *ast.AssignStmt:
// a deadline kept in a name, for a loop that polls until it passes
for _, v := range n.Rhs {
if bound, ok := nowAdd(v); ok {
flag("a deadline", bound)
}
}
case *ast.ValueSpec:
for _, v := range n.Values {
if bound, ok := nowAdd(v); ok {
flag("a deadline", bound)
}
}
}
return true
})
return found
}
func importsMeshtest(f *ast.File) bool {
for _, i := range f.Imports {
if strings.HasSuffix(strings.Trim(i.Path.Value, `"`), "/internal/meshtest") {
return true
}
}
return false
}
// nowAdd is d of time.Now().Add(d).
func nowAdd(e ast.Expr) (ast.Expr, bool) {
call, ok := e.(*ast.CallExpr)
if !ok || len(call.Args) != 1 {
return nil, false
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != "Add" {
return nil, false
}
now, ok := sel.X.(*ast.CallExpr)
if !ok {
return nil, false
}
if s, ok := now.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "Now" && isIdent(s.X, "time") {
return call.Args[0], true
}
return nil, false
}
func isIdent(e ast.Expr, name string) bool {
id, ok := e.(*ast.Ident)
return ok && id.Name == name
}
// packageConsts are the constants a package's files declare at their top, by name, unevaluated.
func packageConsts(t *testing.T, dir string) map[string]ast.Expr {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
consts := map[string]ast.Expr{}
for _, e := range entries {
if !strings.HasSuffix(e.Name(), ".go") {
continue
}
f, err := parser.ParseFile(token.NewFileSet(), filepath.Join(dir, e.Name()), nil, 0)
if err != nil {
t.Fatal(err)
}
for _, d := range f.Decls {
g, ok := d.(*ast.GenDecl)
if !ok || g.Tok != token.CONST {
continue
}
for _, s := range g.Specs {
v := s.(*ast.ValueSpec)
for i, n := range v.Names {
if i < len(v.Values) {
consts[n.Name] = v.Values[i]
}
}
}
}
}
return consts
}
// duration is the value of a constant duration written as the tests write one: a number, time's units, a constant of
// the package, and their products and sums. Anything else (a variable, Bound(t), another package's bound) is not constant.
func duration(e ast.Expr, consts map[string]ast.Expr) (time.Duration, bool) {
switch e := e.(type) {
case *ast.ParenExpr:
return duration(e.X, consts)
case *ast.BasicLit:
if e.Kind == token.INT {
n, err := strconv.ParseInt(e.Value, 0, 64)
return time.Duration(n), err == nil
}
if e.Kind == token.FLOAT {
f, err := strconv.ParseFloat(e.Value, 64)
return time.Duration(f), err == nil
}
case *ast.SelectorExpr:
if isIdent(e.X, "time") {
unit, ok := map[string]time.Duration{"Nanosecond": time.Nanosecond, "Microsecond": time.Microsecond,
"Millisecond": time.Millisecond, "Second": time.Second, "Minute": time.Minute, "Hour": time.Hour}[e.Sel.Name]
return unit, ok
}
case *ast.Ident:
if v, ok := consts[e.Name]; ok {
delete(consts, e.Name) // a constant read once, so none refers to itself
d, ok := duration(v, consts)
consts[e.Name] = v
return d, ok
}
case *ast.UnaryExpr:
if d, ok := duration(e.X, consts); ok && e.Op == token.SUB {
return -d, true
}
case *ast.BinaryExpr:
a, okA := duration(e.X, consts)
b, okB := duration(e.Y, consts)
if !okA || !okB {
return 0, false
}
switch e.Op {
case token.MUL:
return a * b, true
case token.ADD:
return a + b, true
case token.SUB:
return a - b, true
case token.QUO:
if b != 0 {
return a / b, true
}
}
}
return 0, false
}
+4 -4
View File
@@ -44,7 +44,7 @@ func TestTheRuntimeAnnouncesWhatItServesInTheServicesProtocol(t *testing.T) {
defer nc.Close()
info := func() micro.Info {
t.Helper()
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, 2*time.Second)
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, mt.Bound(t))
if err != nil {
t.Fatal(err)
}
@@ -102,13 +102,13 @@ func TestTheRuntimeAnnouncesWhatItServesInTheServicesProtocol(t *testing.T) {
}
// PING answers with the same identity, and a request for another service is not answered.
if msg, err := nc.Request("$SRV.PING", nil, 2*time.Second); err != nil || !strings.Contains(string(msg.Data), micro.PingResponseType) {
if msg, err := nc.Request("$SRV.PING", nil, mt.Bound(t)); err != nil || !strings.Contains(string(msg.Data), micro.PingResponseType) {
t.Errorf("ping: %v %v", msg, err)
}
// alpha is re-issued a plain subject: the announcement says so, and says it is interchangeable.
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", true, nil))
var after string
for i := 0; i < 40; i++ {
for deadline := time.Now().Add(mt.Bound(t)); time.Now().Before(deadline); {
after = subjects(info())
if strings.Contains(after, "mesh.mod.alpha.tool.one|serve.alpha|tool|alpha|||true") {
break
@@ -139,7 +139,7 @@ func TestTheRunnerStatesTheCapabilitiesOfItsCallsInItsPing(t *testing.T) {
t.Fatal(err)
}
defer nc.Close()
msg, err := nc.Request("$SRV.PING.node-tools.anchor", nil, 2*time.Second)
msg, err := nc.Request("$SRV.PING.node-tools.anchor", nil, mt.Bound(t))
if err != nil {
t.Fatalf("ping of the instance: %v", err)
}
+3 -3
View File
@@ -89,7 +89,7 @@ func TestACallOnTheCallerNamedSubjectReachesTheModuleWithItsCaller(t *testing.T)
Result saidCaller `json:"result"`
}
mt.Until(t, func() error {
answer, err := raw.RequestMsg(msg, 5*time.Second)
answer, err := raw.RequestMsg(msg, mt.Bound(t))
if err == nil {
err = json.Unmarshal(answer.Data, &reply)
}
@@ -131,7 +131,7 @@ func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
Error string `json:"error"`
}
mt.Until(t, func() error {
msg, err := old.Request(subject, body, 5*time.Second)
msg, err := old.Request(subject, body, mt.Bound(t))
if err == nil {
err = json.Unmarshal(msg.Data, &reply)
}
@@ -254,7 +254,7 @@ func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
for i := 0; i < 3; i++ {
go func() { got, err := c.chunkedAsked("seat:mesh-wants.input"); done <- got && err == nil }()
}
for deadline := time.Now().Add(5 * time.Second); c.rereadWaiting() < 2; runtime.Gosched() {
for deadline := time.Now().Add(mt.Bound(t)); c.rereadWaiting() < 2; runtime.Gosched() {
if time.Now().After(deadline) {
t.Fatal("two asks never joined the read running")
}
+1 -1
View File
@@ -96,7 +96,7 @@ func TestTheRuntimeHandsAModulesEventsToItsBundleAndAcknowledgesThemOnlyWhenTake
// The bundle dies on the first offer: not acknowledged, the bundle is started again and the
// event is offered again once its ack wait has passed.
mesh.Emit(t, "mesh.mod.alpha.event.happened", map[string]any{"n": 3, "die": true})
deadline := time.Now().Add(20 * time.Second)
deadline := time.Now().Add(mt.Bound(t))
for time.Now().Before(deadline) {
if countLines(t, log, "handled 2") == 1 && countLines(t, log, "handled 3") == 1 {
break
@@ -7,7 +7,6 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/buscompose"
@@ -42,7 +41,7 @@ func TestALedgerIsWrittenOnlyOnItsModulesLedgerConnection(t *testing.T) {
t.Fatal(err)
}
go s.Start()
if !s.ReadyForConnections(30 * time.Second) {
if !s.ReadyForConnections(mt.Bound(t)) {
t.Fatal("the bus did not come up")
}
t.Cleanup(s.Shutdown)
+2 -2
View File
@@ -39,7 +39,7 @@ func TestTheLedgerRepairsAreToolsOfEveryLedgerOwner(t *testing.T) {
defer stop()
asker := connect(t, "console", "workstation")
listed := func(module string) (string, error) {
answered, err := asker.AskWithin(module+"."+ToolsVerb, map[string]any{}, "", callWithin)
answered, err := asker.AskWithin(module+"."+ToolsVerb, map[string]any{}, "", mt.Bound(t))
if err != nil {
return "", err
}
@@ -75,7 +75,7 @@ func TestTheLedgerRepairsAreToolsOfEveryLedgerOwner(t *testing.T) {
plain.Bindings = owner.Bindings
}
mesh.Issue(t, plain)
if _, err := asker.AskWithin("plain.who@anchor", map[string]any{}, "", callWithin); err != nil {
if _, err := asker.AskWithin("plain.who@anchor", map[string]any{}, "", mt.Bound(t)); err != nil {
t.Fatalf("binding change %d: the first call of plain.who failed: %v — dropped while its tools were served again", round, err)
}
}
+1 -1
View File
@@ -247,7 +247,7 @@ func TestALogAnswersEachVerbOnTheBus(t *testing.T) {
if e.Sequence != want || e.Key != "12" {
t.Fatalf("the watch handed %d %s, want %d", e.Sequence, e.Key, want)
}
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatalf("the watch did not hand entry %d", want)
}
}
@@ -143,7 +143,7 @@ func TestABundlesWatchIsHandedTheValueAndEachChange(t *testing.T) {
select {
case c := <-handed:
return c
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatalf("nothing handed: %s", what)
}
return ProvisionChange{}
+1 -1
View File
@@ -201,7 +201,7 @@ func announced(t *testing.T) string {
t.Fatal(err)
}
defer nc.Close()
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, 2*time.Second)
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, mt.Bound(t))
if err != nil {
t.Fatal(err)
}
+5 -6
View File
@@ -26,13 +26,12 @@ func connect(t *testing.T, module, node string) *bus.Conn {
return c
}
// callWithin is the tests' own bound on a call (principle 11, design 47 H, H-A-158): a call that is never answered
// fails the try it is part of within it, never after the tool runner's own 30 s.
const callWithin = 2 * time.Second
// call waits the test's own bound, meshtest.Bound(t), where 2 s were what a loaded build node overran (1754/AC1; the lead's
// answer on issue 1754 of 2026-11-23 20:00): a call that is never answered fails there, and Until, a deadline of the same
// bound, does not try it again past it.
func call(t *testing.T, asker *bus.Conn, key string, args any) (string, error) {
t.Helper()
got, err := asker.AskWithin(key, args, "", callWithin)
got, err := asker.AskWithin(key, args, "", mt.Bound(t))
return string(got.Result), err
}
@@ -119,7 +118,7 @@ func TestTheNodesRuntimeServesFiveModulesAndFollowsAReissuedMembership(t *testin
if subject != "mesh.mod.alpha.event.happened" {
t.Errorf("the event landed on %s", subject)
}
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Error("the event never landed")
}
@@ -93,7 +93,7 @@ func TestABundlesSeatTrafficGoesThroughItsModulesBus(t *testing.T) {
t.Fatal(err)
}
}
deadline := time.Now().Add(10 * time.Second)
deadline := time.Now().Add(mt.Bound(t))
for {
mu.Lock()
n := len(taken)
@@ -140,7 +140,8 @@ func TestTwoWritersIncrementingOneCounterOnTheBusLoseNoUpdate(t *testing.T) {
// revision it read, never zero.
// A key's own time to live (issue 1952, mesh-sdk process.State.CreateTTL and RenewTTL): created once, renewed whole by a
// put, its end heard by a watch as an expiry; refused, writing nothing, on a bucket that takes none, under a second, and
// on an update.
// on an update. 1754/AC2: each change the watch is to hear is waited meshtest.Bound(t), the test's own deadline:
// the 5 s it was given for a 1 s key's expire were overrun on a loaded build node (main.505).
func TestAStaleWriteIsRefusedAndWritesNothing(t *testing.T) {
b := counterBus(t)
state := func(verb string, extra map[string]any) (uint64, error) {
@@ -265,7 +266,7 @@ func TestAStaleWriteIsRefusedAndWritesNothing(t *testing.T) {
if c.Op == "put" && len(ops) == 3 && string(c.Value) != "3" {
t.Fatalf("the renewed key holds %s", c.Value)
}
case <-time.After(5 * time.Second):
case <-time.After(mt.Bound(t)):
t.Fatalf("the watch heard %q, want %q", strings.Join(ops, " "), want)
}
}