From cedfa71169025869d95b2a9956808dd35466b289 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:02:53 +0100 Subject: [PATCH 01/16] S4 ledger-forms: ends-with, ended-days, expires, a reindex naming an instance Builds: design 47 H2 H-A-634 (3) (4), H-A-685 (1), H-A-690 (1) --- go/buscalls/buscalls.go | 8 ++++++ go/buscalls/buscalls_test.go | 33 ++++++++++++++++++++++ go/catalogue/busstate.go | 8 ++++++ go/catalogue/optional_requirements_test.go | 6 ++-- go/membership/membership.go | 3 ++ go/membership/membership_test.go | 15 ++++++++-- 6 files changed, 68 insertions(+), 5 deletions(-) diff --git a/go/buscalls/buscalls.go b/go/buscalls/buscalls.go index e127c4df..83df3b6b 100644 --- a/go/buscalls/buscalls.go +++ b/go/buscalls/buscalls.go @@ -333,6 +333,9 @@ type InstanceState struct { Instance string `json:"instance"` State json.RawMessage `json:"state"` Sequence uint64 `json:"sequence"` + // Expires is when the instance's state key goes, its end plus the ledger's ended-days; absent while the instance has + // not ended (design 47 H2 H-A-634 (4)). + Expires *time.Time `json:"expires,omitempty"` } // HistoryRequest reads an instance's operations from a sequence on, at most Limit of them. @@ -377,6 +380,8 @@ type InstanceChange struct { State json.RawMessage `json:"state"` Sequence uint64 `json:"sequence"` Current bool `json:"current"` + // Expires is as InstanceState's (design 47 H2 H-A-634 (4)). + Expires *time.Time `json:"expires,omitempty"` } // QueryRequest reads a declared index of a ledger: the entries whose key Key names (a key, with `*` for one name and @@ -449,6 +454,9 @@ type RebuildRequest struct { type ReindexRequest struct { Ledger string `json:"ledger"` Index string `json:"index"` + // Instance, when set, builds only that instance's entries again and deletes the ones the index holds for it that it no + // longer should (design 47 H2 H-A-690 (1)). + Instance string `json:"instance,omitempty"` } // LedgerRequest names a ledger: lag, fill. diff --git a/go/buscalls/buscalls_test.go b/go/buscalls/buscalls_test.go index 01cf18d4..2f5a823d 100644 --- a/go/buscalls/buscalls_test.go +++ b/go/buscalls/buscalls_test.go @@ -3,6 +3,7 @@ package buscalls import ( "encoding/json" "testing" + "time" ) // A-42: stream.publish is a method of its own, beside read and fill, and its request and answer keep their field names. @@ -19,3 +20,35 @@ func TestStreamPublishIsAMethodWithItsShapes(t *testing.T) { t.Errorf("answer %s", a) } } + +// Design 47 H2 H-A-634 (4), H-A-690 (1): an instance's state and a change carry `expires` while it has ended, none +// while it has not; a reindex names an instance only when asked to. +func TestAnInstancesExpiresAndAReindexInstanceKeepTheirNames(t *testing.T) { + at := time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC) + for _, c := range []struct { + name string + v any + want string + }{ + {"state ended", InstanceState{Instance: "record/a", State: json.RawMessage(`{}`), Sequence: 3, Expires: &at}, + `{"instance":"record/a","state":{},"sequence":3,"expires":"2026-12-01T10:00:00Z"}`}, + {"state open", InstanceState{Instance: "record/a", State: json.RawMessage(`{}`), Sequence: 3}, + `{"instance":"record/a","state":{},"sequence":3}`}, + {"change ended", InstanceChange{Watch: "w", Instance: "i", State: json.RawMessage(`{}`), Expires: &at}, + `{"watch":"w","instance":"i","state":{},"sequence":0,"current":false,"expires":"2026-12-01T10:00:00Z"}`}, + {"change open", InstanceChange{Watch: "w", Instance: "i", State: json.RawMessage(`{}`)}, + `{"watch":"w","instance":"i","state":{},"sequence":0,"current":false}`}, + {"reindex one", ReindexRequest{Ledger: "records", Index: "movers", Instance: "mover/x"}, + `{"ledger":"records","index":"movers","instance":"mover/x"}`}, + {"reindex whole", ReindexRequest{Ledger: "records", Index: "movers"}, `{"ledger":"records","index":"movers"}`}, + } { + b, err := json.Marshal(c.v) + if err != nil || string(b) != c.want { + t.Errorf("%s: %s (%v), want %s", c.name, b, err, c.want) + } + } + var back InstanceState + if err := json.Unmarshal([]byte(`{"instance":"i","state":null,"sequence":1,"expires":"2026-12-01T10:00:00Z"}`), &back); err != nil || back.Expires == nil || !back.Expires.Equal(at) { + t.Errorf("expires read back as %+v (%v)", back.Expires, err) + } +} diff --git a/go/catalogue/busstate.go b/go/catalogue/busstate.go index 1e1040b4..d4731262 100644 --- a/go/catalogue/busstate.go +++ b/go/catalogue/busstate.go @@ -61,6 +61,10 @@ const ( OptionDuplicates = "duplicates" ) +// ConfigEndedDays is the configuration name of a ledger that gives its ended instances a lifetime: a whole number of +// days, 1 to 3650, after an instance's end until its state key, snapshot and index keys go (design 47 H2 H-A-634 (3)). +const ConfigEndedDays = "ended-days" + // ConfigWhenFull is what a configuration of its own says a bare stream does when full: WhenFullRefuse or // WhenFullDropOldest. In a template it is fixed, never an option (ADR 0595 §3). const ( @@ -92,6 +96,10 @@ type LedgerType struct { Operations []LedgerOperation `json:"operations"` // Indexes are its declared indexes, each a second key-value bucket kept by a watcher (ADR 0597 §4). Indexes []LedgerIndex `json:"indexes,omitempty"` + // EndsWith names the field of the type's schema whose value ends an instance: an instance has ended while its state + // holds a value there (absent, null, an empty object and an empty text are no value). Absent: its instances never end + // (design 47 H2 H-A-634 (1), (3)). + EndsWith string `json:"ends-with,omitempty"` } // LedgerField is one field of a ledger type's schema. diff --git a/go/catalogue/optional_requirements_test.go b/go/catalogue/optional_requirements_test.go index d98e8db5..53ca1150 100644 --- a/go/catalogue/optional_requirements_test.go +++ b/go/catalogue/optional_requirements_test.go @@ -42,7 +42,7 @@ func TestARequirementsLongForm(t *testing.T) { records := BusStateEntry{Name: "records", Storage: "ledger", Template: "ledger", Options: map[string]json.RawMessage{"max-mib": json.RawMessage(`1024`)}} // A ledger type with each of the four effects. - listing := LedgerType{Name: "listing", + listing := LedgerType{Name: "listing", EndsWith: "sold", Schema: map[string]LedgerField{"price": {Type: "number"}, "seen": {Type: "list"}, "notes": {Type: "map"}, "text": {Type: "text"}, "digest": {Type: "text", DigestOf: "text"}}, Operations: []LedgerOperation{ @@ -53,8 +53,8 @@ func TestARequirementsLongForm(t *testing.T) { }, Indexes: []LedgerIndex{{Name: "cheapest", On: []string{"price"}}}} typeJSON, err := json.Marshal(listing) - if err != nil { - t.Fatal(err) + if err != nil || !strings.Contains(string(typeJSON), `"ends-with":"sold"`) || ConfigEndedDays != "ended-days" { + t.Fatalf("a ledger type's ends-with and the configuration name ended-days (H-A-634 (3)): %s (%v)", typeJSON, err) } ledger := records ledger.Types = []LedgerType{listing} diff --git a/go/membership/membership.go b/go/membership/membership.go index 7fdaab2f..080307f3 100644 --- a/go/membership/membership.go +++ b/go/membership/membership.go @@ -91,6 +91,9 @@ type BusBinding struct { State string `json:"state,omitempty"` Indexes map[string]string `json:"indexes,omitempty"` Snapshot string `json:"snapshot,omitempty"` + // EndedDays is the whole number of days an ended instance's state, snapshot and index keys are kept; absent while the + // held objects allow no lifetime or the ledger names none (design 47 H2 H-A-634 (3), H-A-685 (1)). + EndedDays int `json:"ended-days,omitempty"` // Types are a ledger's types, copied by the grants part from the entry the manifest-accepted event carries, so the // tool runner checks an operation against its type without reading another part's state (ADR 0596, ADR 0597 §1). Types []catalogue.LedgerType `json:"types,omitempty"` diff --git a/go/membership/membership_test.go b/go/membership/membership_test.go index c583f435..e6898710 100644 --- a/go/membership/membership_test.go +++ b/go/membership/membership_test.go @@ -44,8 +44,8 @@ func TestAMembershipRoundTripsAsIssued(t *testing.T) { bound := in bound.Bindings = []BusBinding{{Local: "records", Storage: "ledger", Template: "ledger", History: "forge_records", Subject: "forge_records.>", State: "forge_records_state", Indexes: map[string]string{"search": "forge_records_search"}, - Snapshot: "forge_records_snapshot.>", - Types: []catalogue.LedgerType{{Name: "decision", Schema: map[string]catalogue.LedgerField{"title": {Type: "text"}}, + Snapshot: "forge_records_snapshot.>", EndedDays: 30, + Types: []catalogue.LedgerType{{Name: "decision", EndsWith: "ended", Schema: map[string]catalogue.LedgerField{"title": {Type: "text"}}, Operations: []catalogue.LedgerOperation{{Name: "propose", Effect: catalogue.EffectSetFields, Fields: []string{"title"}}}}}}} boundRaw, err := json.Marshal(bound) if err != nil { @@ -55,6 +55,17 @@ func TestAMembershipRoundTripsAsIssued(t *testing.T) { if err := json.Unmarshal(boundRaw, &boundBack); err != nil || !reflect.DeepEqual(bound, boundBack) { t.Fatalf("a membership with a ledger binding read back as %+v (%v)", boundBack, err) } + // Design 47 H2 H-A-634 (3), H-A-685 (1): ended-days and ends-with are named only when set, so a binding without + // them encodes as before. + if !strings.Contains(string(boundRaw), `"ended-days":30`) || !strings.Contains(string(boundRaw), `"ends-with":"ended"`) { + t.Fatalf("the binding does not name ended-days and ends-with: %s", boundRaw) + } + plain := bound + plain.Bindings = []BusBinding{{Local: "records", Storage: "ledger", Types: []catalogue.LedgerType{{Name: "decision"}}}} + plainRaw, _ := json.Marshal(plain) + if strings.Contains(string(plainRaw), "ended-days") || strings.Contains(string(plainRaw), "ends-with") { + t.Fatalf("an absent ended-days or ends-with is written: %s", plainRaw) + } // Design 47 G §642, §619: a state's binding carries its objects store, the sent store is an entry of its own, and a // foundation part's old `objects` sections map to their stores. withObjects := in From e5b66a77baad6c082b64d3d739c67d2f8efa531c Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:04:25 +0100 Subject: [PATCH 02/16] S2 ask-once-go: Ask calls once; the kind stopping goes Builds: design 47 H2 H-A-570 (2) (3) (4), H-A-624 (3) --- go/busretry/busretry.go | 18 ++--------- go/busretry/busretry_test.go | 7 +++-- go/process/call.go | 24 +++++--------- go/process/call_test.go | 16 +++++++--- go/stdio.go | 61 ++++++++++++++---------------------- go/stdio_test.go | 46 ++++++++++++--------------- 6 files changed, 68 insertions(+), 104 deletions(-) diff --git a/go/busretry/busretry.go b/go/busretry/busretry.go index 2b205d5f..52daccef 100644 --- a/go/busretry/busretry.go +++ b/go/busretry/busretry.go @@ -163,26 +163,12 @@ func (u *Unanswered) Error() string { func (u *Unanswered) Unwrap() error { return u.Last } // Fault says err is a transport fault of a kept call (§775): a request that reached no one, a call's own deadline -// passing, a holder's answer of the kind away (§776), or a stopping tool runner's answer of the kind stopping (design 47 -// H2 H-A-542, H-A-549); a callee's refusal never is. +// passing, or a holder's answer of the kind away (§776); a callee's refusal never is. func Fault(err error) bool { var away *Away - var stopping *Stopping - return TimedOut(err) || Undelivered(err) || errors.As(err, &away) || errors.As(err, &stopping) + return TimedOut(err) || Undelivered(err) || errors.As(err, &away) } -// ErrorKindStopping is the typed fault a stopping tool runner answers each call it does not take with (design 47 H2 -// H-A-542): its reply's `error-kind`. Nothing was done, and the new runner answers the call. -const ErrorKindStopping = "stopping" - -// Stopping is a tool runner's answer of the kind stopping, read as an error: the runner's words. -type Stopping struct{ Words string } - -func (s *Stopping) Error() string { return s.Words } - -// ErrorKind is the typed fault the answer named: stopping. -func (s *Stopping) ErrorKind() string { return ErrorKindStopping } - // ErrorKindAway is the seat error kind a holder answers when a part it depends on is away (design 47 H2 §776): its // answer's `error-kind`, beside `part` (what did not answer) and `words`. A caller reads it as a transport fault. const ErrorKindAway = "away" diff --git a/go/busretry/busretry_test.go b/go/busretry/busretry_test.go index 36a9f2bf..36da3a72 100644 --- a/go/busretry/busretry_test.go +++ b/go/busretry/busretry_test.go @@ -179,9 +179,10 @@ func subAKeptCallIsPaced(t *testing.T) { !strings.Contains(string(raw), `"error-kind":"away"`) { t.Fatalf("%s read as %+v", raw, a) } - // A stopping tool runner's answer is a transport fault too (design 47 H2 H-A-549), wrapped or not. - if !Fault(&Stopping{Words: "not taken"}) || !Fault(fmt.Errorf("asked: %w", &Stopping{Words: "not taken"})) { - t.Fatal("a stopping tool runner's answer is no transport fault") + // Design 47 H2 H-A-570 (3): no responders is the transport fault, wrapped or not; a reply naming the withdrawn kind + // stopping is the callee's answer, no fault. + if !Fault(nats.ErrNoResponders) || !Fault(fmt.Errorf("asked: %w", nats.ErrNoResponders)) || Fault(&Answered{Words: "the tool runner is stopping"}) { + t.Fatal("no responders is no transport fault, or a reply of the kind stopping is one") } if AwayIn([]byte(`{"error":"no","error-kind":"refused"}`)) != nil || AwayIn([]byte(`[1]`)) != nil || Fault(&Answered{Words: "away"}) { t.Fatal("a refusal reads as away") diff --git a/go/process/call.go b/go/process/call.go index 7d790525..1f5721af 100644 --- a/go/process/call.go +++ b/go/process/call.go @@ -189,15 +189,6 @@ func callWith(request func(string, []byte) (json.RawMessage, error), blackout fu return busretry.Do("the call on "+fallback, askBoth(request, called, fallback, data), blackout) } -// replyError is the error a reply naming one is the call's: a stopping tool runner's kind stopping is a transport fault a -// kept call's pacing asks again on, as away is (design 47 H2 H-A-542, H-A-549); any other is the callee's answer. -func replyError(words, kind string) error { - if kind == busretry.ErrorKindStopping { - return &busretry.Stopping{Words: words} - } - return answered(words) -} - // answered is the error a callee answered with: delivered, never asked again (busretry.Answered). func answered(words string) error { return &busretry.Answered{Words: words} } @@ -290,21 +281,20 @@ func (c *Conn) requestAsk(subject string, data []byte, ask string) (json.RawMess return result, nil } -// readReply reads one reply ({result, error, error-kind, node, held}): a reply naming an error is the call's failure, -// of the kind stopping a transport fault a kept call paces on (design 47 H2 H-A-549 (1)); a held call names its hold. +// readReply reads one reply ({result, error, error-kind, node, held}): a reply naming an error is the call's failure; a held +// call names its hold. func readReply(subject string, data []byte) (json.RawMessage, *approval.Held, error) { var r struct { - Result json.RawMessage `json:"result"` - Error string `json:"error"` - ErrorKind string `json:"error-kind"` - Node string `json:"node"` - Held *approval.Held `json:"held"` + Result json.RawMessage `json:"result"` + Error string `json:"error"` + Node string `json:"node"` + Held *approval.Held `json:"held"` } if err := json.Unmarshal(data, &r); err != nil { return nil, nil, fmt.Errorf("%s answered something that is not a seat's answer: %w", subject, err) } if r.Error != "" { - return nil, nil, replyError(r.Error, r.ErrorKind) + return nil, nil, answered(r.Error) } return r.Result, r.Held, nil } diff --git a/go/process/call_test.go b/go/process/call_test.go index 2e7236aa..41bdfca8 100644 --- a/go/process/call_test.go +++ b/go/process/call_test.go @@ -143,8 +143,8 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) { } } // Design 47 H2 §776: a holder's answer of the kind away is a transport fault, called again at the pace; so is a - // stopping tool runner's reply of the kind stopping (H-A-542, H-A-549); a refusal of another kind is the caller's - // answer at once. + // refusal of another kind is the caller's answer at once, and so is a reply of the withdrawn kind stopping + // (H-A-570 (3)). for _, row := range []struct { name string answers []string @@ -153,9 +153,9 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) { want string // the call's answer, where it is not the last answer }{ {"away, then answered", []string{`{"error":"x","error-kind":"away","part":"the forge's store","words":"401"}`, `{"merged":true}`}, 2, false, ""}, - // H-A-549 (1): the runner's reply of the kind stopping, read from its bytes, is paced on until the new runner answers. - {"stopping, then answered by the new runner", []string{`{"error":"git's trees was not taken: the tool runner is stopping","error-kind":"stopping"}`, - `{"result":{"merged":true}}`}, 2, true, `{"merged":true}`}, + // H-A-570 (3): a reply of the kind stopping, read from its bytes, is the callee's answer, asked once. + {"stopping withdrawn: answered at once", []string{`{"error":"git's trees was not taken: the tool runner is stopping","error-kind":"stopping"}`, + `{"result":{"merged":true}}`}, 1, true, ""}, {"refused: answered at once", []string{`{"error":"no","error-kind":"refused"}`}, 1, false, ""}, } { asks := 0 @@ -173,6 +173,12 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) { want = row.answers[len(row.answers)-1] } got, err := callKeptWith(busretry.Kept{Seat: "git", Verb: "merge-pull"}, request, "called", "fallback", nil) + if row.replies && row.want == "" { + if asks != row.asks || err == nil { + t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err) + } + continue + } if asks != row.asks || err != nil || string(got) != want { t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err) } diff --git a/go/stdio.go b/go/stdio.go index d06b6d30..06a6c613 100644 --- a/go/stdio.go +++ b/go/stdio.go @@ -14,6 +14,7 @@ package stdio import ( "bufio" + "context" "crypto/rand" "encoding/hex" "encoding/json" @@ -143,39 +144,39 @@ func (c *channel) askAs(id, method string, params any, timeout time.Duration) (j c.mu.Lock() delete(c.waiting, id) c.mu.Unlock() - return nil, fmt.Errorf("the runtime did not answer %s in %s", method, timeout) + return nil, &noAnswer{method: method, timeout: timeout} } } +// noAnswer is the runtime's silence: its deadline passed with no answer to the request. +type noAnswer struct { + method string + timeout time.Duration +} + +func (n *noAnswer) Error() string { + return fmt.Sprintf("the runtime did not answer %s in %s", n.method, n.timeout) +} + // refused is the runtime's error answer, as opposed to no answer: what it refused, it did not do. type refused struct { message string code int - // kind is the typed fault the answer names, its `error-kind` (ErrorKindStopping), "" for none. + // kind is the typed fault the answer names, its `error-kind`, "" for none. kind string } func (r *refused) Error() string { return r.message } -// Is makes a compare-and-set the runtime refused because another writer was first ErrChanged, and a call a stopping tool -// runner did not take ErrStopping. +// Is makes a compare-and-set the runtime refused because another writer was first ErrChanged. func (r *refused) Is(target error) bool { - return target == ErrChanged && r.code == CodeChanged || target == errors.ErrUnsupported && r.code == CodeNoMethod || - target == ErrStopping && r.kind == ErrorKindStopping + return target == ErrChanged && r.code == CodeChanged || target == errors.ErrUnsupported && r.code == CodeNoMethod } -// ErrorKind is the typed fault the runtime's answer named (ErrorKindStopping), "" for none: a reader that does not import +// ErrorKind is the typed fault the runtime's answer named, "" for none: a reader that does not import // this package tells it by this method, never by the words. func (r *refused) ErrorKind() string { return r.kind } -// ErrorKindStopping is the typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542): -// the answer's `error-kind`. Ask asks again after a pause until the new runner answers or its bound ends. -const ErrorKindStopping = busretry.ErrorKindStopping - -// ErrStopping is a call a stopping tool runner did not take (ErrorKindStopping): nothing was done, and the new runner answers -// it. Told apart by its kind, never by its words. -var ErrStopping = errors.New("the tool runner is stopping") - // CodeNoMethod is the error code the runtime answers a verb it does not have with (JSON-RPC's method not found). const CodeNoMethod = -32601 @@ -603,27 +604,19 @@ func Ask(key string, body any) (json.RawMessage, error) { if err != nil { return nil, err } - // A call a stopping tool runner did not take is asked again after a pause, at the kept-call pace, until the new runner - // answers or Ask's own bound (the setting ask-bound) ends; then its fault is the caller's as such, ErrStopping (design 47 H2 - // H-A-542, H-A-549). + // The call is made once and nothing is asked again here: a call its caller marks safe to repeat is called again by a kept + // call (design 47 H2 §775) through no responders as through every transport fault. At the bound (the setting ask-bound) + // the fault is "no answer within ", a call's own deadline (design 47 H2 H-A-570 (2), (4)). askBound, err := SettingDuration(AskBoundSetting, DefaultAskBound) if err != nil { return nil, err } - start, wait := askNow(), busretry.KeptPace().First - for { - left := askBound - askNow().Sub(start) - answer, err := c.ask("mesh/ask", map[string]any{"key": key, "body": body}, left) - if !errors.Is(err, ErrStopping) { - return answer, err - } - if left = askBound - askNow().Sub(start); wait >= left { - return nil, fmt.Errorf("%s: the tool runner was stopping, asked again until Ask's bound of %s: %w", key, askBound, err) - } - fmt.Fprintf(os.Stderr, "[mesh-sdk] %s: the tool runner is stopping (%v); asked again in %s\n", key, err, wait) - pause(wait) - wait = min(wait*2, busretry.KeptPace().Max) + answer, err := c.ask("mesh/ask", map[string]any{"key": key, "body": body}, askBound) + var timedOut *noAnswer + if errors.As(err, &timedOut) { + return nil, fmt.Errorf("no answer within %s: %w", askBound, context.DeadlineExceeded) } + return answer, err } // AskBoundSetting is the module's setting of how long Ask waits for its answer, asks again included, a duration text; @@ -633,12 +626,6 @@ const ( DefaultAskBound = 60 * time.Second ) -// pause is how Ask waits between two asks and askNow its clock, a test's to replace so nothing sleeps. -var ( - pause = time.Sleep - askNow = time.Now -) - // TopicMatches says whether an event's type matches a pattern: `*` is one dot-separated segment, `#` // (or `**`) any number, as the TypeScript SDK matches; the bus's own `>` as the last token matches one or more // further tokens (design 47 G A-101), so an adopted follower's `..>` hears every event on the seat's event. diff --git a/go/stdio_test.go b/go/stdio_test.go index f366988e..ca906676 100644 --- a/go/stdio_test.go +++ b/go/stdio_test.go @@ -2,6 +2,7 @@ package stdio import ( "bufio" + "context" "encoding/json" "errors" "io" @@ -9,8 +10,6 @@ import ( "sync" "testing" "time" - - "git.novox.be/novox/mesh-sdk/go/busretry" ) // A Go bundle serves as the module the runtime names, answers calls concurrently, and emits through @@ -416,27 +415,21 @@ func subABundleAsksAnAcknowledgedPublishAndASubscriptionForNewMessages(t *testin _ = inW.Close() } -// A call a stopping tool runner did not take reaches the bundle as the typed fault stopping and is asked again after a pause, -// at the kept-call pace, until the new runner answers; past Ask's bound the fault is the caller's as such, ErrStopping; a -// plain refusal, and a bare timeout, are never asked again (design 47 H2 H-A-542). Nothing sleeps: the pause moves a clock. -func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T) { +// Ask makes its call once and asks nothing again itself (design 47 H2 H-A-570 (2)): a call met by no responders returns that fault +// after one ask, a reply of the withdrawn kind stopping is the runtime's refusal like any other, and at the bound (the setting +// ask-bound) the fault is "no answer within ", a call's own deadline. +func TestAskCallsOnceAndFaultsAtItsBound(t *testing.T) { servesAlone(t) t.Setenv(ServedAs, "builder") - clock := time.Unix(0, 0) - var paused []time.Duration - wasPause, wasNow := pause, askNow - t.Cleanup(func() { pause, askNow = wasPause, wasNow }) - pause = func(d time.Duration) { paused = append(paused, d); clock = clock.Add(d) } - askNow = func() time.Time { return clock } - // The bound is the setting ask-bound (H-A-549), here 10 s for its default 60 s. - t.Setenv("MESH_CONFIG_ASK_BOUND", "10s") + // The bound is the setting ask-bound (H-A-570 (4)), here 50 ms for its default 60 s. + t.Setenv("MESH_CONFIG_ASK_BOUND", "50ms") inR, inW := io.Pipe() outR, outW := io.Pipe() go func() { _ = ServeOn("", []Tool{{Name: "publish", Run: func(map[string]any) (any, error) { answer, err := Ask("seat:go-package-registry.publish", map[string]any{}) if err != nil { - return map[string]any{"stopping": errors.Is(err, ErrStopping), "words": err.Error()}, nil + return map[string]any{"deadline": errors.Is(err, context.DeadlineExceeded), "words": err.Error()}, nil } return json.RawMessage(answer), nil }}}, inR, outW) @@ -462,24 +455,28 @@ func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T) send := func(m map[string]any) { b, _ := json.Marshal(m); _, _ = inW.Write(append(b, '\n')) } stopping := map[string]any{"code": -32000, "message": "registry's publish was not taken: the tool runner is stopping", "data": map[string]any{"error-kind": "stopping"}} + noResponders := map[string]any{"code": -32000, "message": "nats: no responders available for request"} for i, row := range []struct { name string answers []map[string]any // the runtime's answers to the asks, in order: an error, or a result asks int want string }{ - {"answered by the new runner after two stoppings", []map[string]any{{"error": stopping}, {"error": stopping}, {"result": "published"}}, 3, - `"published"`}, - {"stopping past the bound", []map[string]any{{"error": stopping}, {"error": stopping}, {"error": stopping}}, 3, - `"stopping":true`}, - {"a plain refusal", []map[string]any{{"error": map[string]any{"code": -32000, "message": "refused"}}}, 1, `"stopping":false`}, - {"a bare timeout", []map[string]any{{"error": map[string]any{"code": -32000, "message": "timeout"}}}, 1, `"words":"timeout"`}, + {"answered", []map[string]any{{"result": "published"}}, 1, `"published"`}, + {"no responders is returned after one ask", []map[string]any{{"error": noResponders}}, 1, `"words":"nats: no responders available for request"`}, + {"a reply of the withdrawn kind stopping is a refusal", []map[string]any{{"error": stopping}}, 1, `"deadline":false`}, + {"no answer within the bound", nil, 1, `"words":"no answer within 50ms: context deadline exceeded"`}, } { t.Run(row.name, func(t *testing.T) { - clock, paused = time.Unix(0, 0), nil - t.Cleanup(busretry.Waits(time.Second, 2*time.Second, 4*time.Second)) send(map[string]any{"jsonrpc": "2.0", "id": 100 + i, "method": "tools/call", "params": map[string]any{"name": "publish"}}) asks := 0 + if row.answers == nil { + m := next() + asks++ + if m["method"] != "mesh/ask" { + t.Fatalf("the bundle said %v, want an ask", m) + } + } for _, a := range row.answers { m := next() if m["method"] != "mesh/ask" { @@ -494,9 +491,6 @@ func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T) if r["id"] != float64(100+i) || asks != row.asks || !strings.Contains(string(text), strings.ReplaceAll(row.want, `"`, `\"`)) { t.Errorf("asked %d times, answered %v; want %d asks and %s", asks, r, row.asks, row.want) } - if want := row.asks - 1; len(paused) != want || (want >= 2 && paused[1] != 2*paused[0]) { - t.Errorf("paused %v, want %d pauses at the kept-call pace", paused, want) - } }) } _ = inW.Close() From a123ebd64388bc6563114e47b9b81596b5efdef8 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:05:11 +0100 Subject: [PATCH 03/16] S3 ask-once-ts: the TypeScript stdio asks once; the kind stopping goes Builds: design 47 H2 H-A-570 (2) (3) (4) --- src/stdio/index.ts | 68 ++++++++++++-------------------- test/fixtures/stdio-ask.mjs | 16 ++++++++ test/fixtures/stdio-stopping.mjs | 24 ----------- test/stdio.test.ts | 24 +++++------ 4 files changed, 53 insertions(+), 79 deletions(-) create mode 100644 test/fixtures/stdio-ask.mjs delete mode 100644 test/fixtures/stdio-stopping.mjs diff --git a/src/stdio/index.ts b/src/stdio/index.ts index f602e979..5e8a92e3 100644 --- a/src/stdio/index.ts +++ b/src/stdio/index.ts @@ -22,27 +22,10 @@ import { runAs } from "../callers/index.js"; /** The protocol version this speaks; the runtime says the same. */ export const PROTOCOL = "2025-03-26"; -/** The typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542): the runtime's - * answer's `error-kind`, kept on the error as `errorKind`. */ -export const ERROR_KIND_STOPPING = "stopping"; - -/** Whether err is a call a stopping tool runner did not take: told by its kind, never by its words (H-A-542). */ -export function isStopping(err: unknown): boolean { - return typeof err === "object" && err !== null && (err as { errorKind?: unknown }).errorKind === ERROR_KIND_STOPPING; -} - -/** The setting of how long a call is asked again while the tool runner is stopping, and its default: the Go stdio Ask's - * (H-A-544, H-A-549). */ +/** The setting of how long a call waits for its answer, and its default: the Go stdio Ask's (design 47 H2 H-A-570 (4)). */ export const ASK_BOUND_SETTING = "ask-bound"; const DEFAULT_ASK_BOUND_MS = 60_000; -/** How a call waits between two asks while the tool runner is stopping, and its clock: a test's to replace, as the Go - * stdio's pause and askNow are, so nothing sleeps. */ -export const askPacing = { - pause: (ms: number): Promise => new Promise((r) => setTimeout(r, ms)), - now: (): number => Date.now(), -}; - /** A duration setting as the node-engine composes it (MESH_CONFIG_, design 47 H2 H-A-370), in milliseconds: Go's * duration text ("1s", "250ms", "1m30s"); an absent setting is its default, one that is no duration is an error naming it. */ function settingMs(key: string, fallback: number): number { @@ -60,31 +43,31 @@ function settingMs(key: string, fallback: number): number { return ms; } -/** Asks once and again, while the answer is the typed fault stopping, after a pause at the kept-call pace (the settings - * kept-call-pace-first and kept-call-pace-max, 1 s doubling to 30 s by default, as the Go stdio's Ask), until the new - * runner answers or the bound (the setting ask-bound, 60 s by default) ends; then the stopping fault is the caller's as such (H-A-542, H-A-544). A plain refusal - * and a bare timeout are never asked again. */ -async function askAgainWhileStopping(key: string, once: () => Promise): Promise { - const start = askPacing.now(); +/** Asks once, as the Go stdio's Ask does, and asks nothing again itself: a call its caller marks safe to repeat is called + * again by a kept call through no responders as through every transport fault. A call met by no responders is the runtime's + * refusal, returned as such; at the bound (the setting ask-bound, 60 s by default) the fault is "no answer within " + * (design 47 H2 H-A-570 (2), (4)). */ +async function askWithinBound(once: () => Promise): Promise { const bound = settingMs(ASK_BOUND_SETTING, DEFAULT_ASK_BOUND_MS); - let wait = settingMs("kept-call-pace-first", 1000); - const most = settingMs("kept-call-pace-max", 30_000); - for (;;) { - try { - return await once(); - } catch (err) { - const left = bound - (askPacing.now() - start); - if (!isStopping(err) || wait >= left) { - if (isStopping(err)) (err as Error).message = `${key}: the tool runner was stopping, asked again until the bound of ${bound}ms: ${(err as Error).message}`; - throw err; - } - process.stderr.write(`[mesh-sdk] ${key}: the tool runner is stopping (${(err as Error).message}); asked again in ${wait}ms\n`); - await askPacing.pause(wait); - wait = Math.min(wait * 2, most); - } + let timer: ReturnType | undefined; + const late = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`no answer within ${boundText(bound)}`)), bound); + }); + try { + return await Promise.race([once(), late]); + } finally { + clearTimeout(timer); } } +/** A bound as Go's duration prints it for the whole milliseconds a setting gives ("50ms", "10s", "1m0s"). */ +function boundText(ms: number): string { + if (ms < 1000) return `${ms}ms`; + const s = ms / 1000; + if (s < 60) return `${s}s`; + return `${Math.floor(s / 60)}m${s % 60}s`; +} + interface Request { jsonrpc: string; id?: number | string | null; @@ -171,10 +154,9 @@ function startSession(): Session { throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`); } }, - // A call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound - // ends, as the Go stdio's Ask does (design 47 H2 H-A-542, H-A-544). + // A call is made once and its fault said at the bound, as the Go stdio's Ask does (design 47 H2 H-A-570 (2), (4)). request: (async (key: string, body: Req): Promise => - (await askAgainWhileStopping(key, () => ask("mesh/ask", { key, body }))) as Res) as Broker["request"], + (await askWithinBound(() => ask("mesh/ask", { key, body }))) as Res) as Broker["request"], handle: (async () => { throw new Error("a launched bundle answers through its tools, not by binding subjects (novox/hq ADR 0193)"); }) as Broker["handle"], @@ -302,7 +284,7 @@ function startSession(): Session { if (reply.method === undefined && typeof reply.id === "string" && awaiting.has(reply.id)) { const waiting = awaiting.get(reply.id)!; awaiting.delete(reply.id); - // A typed fault rides as the error's data `error-kind` (a stopping tool runner's stopping, H-A-542): kept as errorKind. + // A typed fault rides as the error's data `error-kind` (an `away`, §776): kept as errorKind. if (reply.error) waiting.reject(Object.assign(new Error(reply.error.message ?? "the runtime refused"), { code: reply.error.code, errorKind: reply.error.data?.["error-kind"] })); else waiting.resolve(reply.result); diff --git a/test/fixtures/stdio-ask.mjs b/test/fixtures/stdio-ask.mjs new file mode 100644 index 00000000..de943c94 --- /dev/null +++ b/test/fixtures/stdio-ask.mjs @@ -0,0 +1,16 @@ +// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or the +// words of its fault (design 47 H2 H-A-570 (2), (4)). +import { broker } from "../../dist/messaging/index.js"; +import { registerModuleTools } from "../../dist/tools/index.js"; +import { serveRegisteredOverStdio } from "../../dist/stdio/index.js"; + +registerModuleTools("builder", () => [ + { name: "publish", description: "asks the registry", input: {}, run: async () => { + try { + return { answer: await broker().request("seat:go-package-registry.publish", {}) }; + } catch (err) { + return { words: err.message }; + } + } }, +]); +await serveRegisteredOverStdio(); diff --git a/test/fixtures/stdio-stopping.mjs b/test/fixtures/stdio-stopping.mjs deleted file mode 100644 index 84e7b17e..00000000 --- a/test/fixtures/stdio-stopping.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or -// whether its fault was the typed fault stopping, and the pauses between its asks (design 47 H2 H-A-542, H-A-544, -// H-A-549). Its pause moves a clock instead of sleeping. -import { broker } from "../../dist/messaging/index.js"; -import { registerModuleTools } from "../../dist/tools/index.js"; -import { serveRegisteredOverStdio, isStopping, askPacing } from "../../dist/stdio/index.js"; - -let clock = 0; -let paused = []; -askPacing.now = () => clock; -askPacing.pause = async (ms) => { paused.push(ms); clock += ms; }; - -registerModuleTools("builder", () => [ - { name: "publish", description: "asks the registry", input: {}, run: async () => { - clock = 0; - paused = []; - try { - return { answer: await broker().request("seat:go-package-registry.publish", {}), paused }; - } catch (err) { - return { stopping: isStopping(err), words: err.message, paused }; - } - } }, -]); -await serveRegisteredOverStdio(); diff --git a/test/stdio.test.ts b/test/stdio.test.ts index b39f7388..a97f03a8 100644 --- a/test/stdio.test.ts +++ b/test/stdio.test.ts @@ -379,10 +379,10 @@ async function aBundlesFindingWriter(): Promise { } } -test("a call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound ends; a plain refusal and a bare timeout are not (design 47 H2 H-A-542, H-A-544, H-A-549)", async () => { - const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-stopping.mjs", import.meta.url))], +test("a call is made once: no responders is returned after one ask, a reply of the withdrawn kind stopping is a refusal, and at the bound the fault is no answer within (design 47 H2 H-A-570 (2), (4))", async () => { + const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-ask.mjs", import.meta.url))], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, MESH_SERVED_MODULE: "builder", - MESH_CONFIG_KEPT_CALL_PACE_FIRST: "2s", MESH_CONFIG_KEPT_CALL_PACE_MAX: "4s", MESH_CONFIG_ASK_BOUND: "10s" } }); + MESH_CONFIG_ASK_BOUND: "50ms" } }); const seen: any[] = []; let buffered = ""; let said = ""; @@ -404,16 +404,16 @@ test("a call a stopping tool runner did not take is asked again after a pause un try { send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {} } }); await until((m) => m.id === 1); + const noResponders = { code: -32000, message: "nats: no responders available for request" }; for (const row of [ - // The pace and the bound are the settings (2 s doubling to 4 s, a bound of 10 s, H-A-549); the pause moves a clock. - { id: 2, answers: [{ error: stopping }, { error: stopping }, { result: { published: true } }], - want: { answer: { published: true }, paused: [2000, 4000] } }, - { id: 3, answers: [{ error: stopping }, { error: stopping }, { error: stopping }], - want: { stopping: true, words: `seat:go-package-registry.publish: the tool runner was stopping, asked again until the bound of 10000ms: ${stopping.message}`, paused: [2000, 4000] } }, - { id: 4, answers: [{ error: { code: -32000, message: "refused" } }], want: { stopping: false, words: "refused", paused: [] } }, - { id: 5, answers: [{ error: { code: -32000, message: "timeout" } }], want: { stopping: false, words: "timeout", paused: [] } }, + { id: 2, answers: [{ result: { published: true } }], want: { answer: { published: true } } }, + { id: 3, answers: [{ error: noResponders }], want: { words: noResponders.message } }, + { id: 4, answers: [{ error: stopping }], want: { words: stopping.message } }, + { id: 5, answers: [{ error: { code: -32000, message: "refused" } }], want: { words: "refused" } }, + { id: 6, answers: [], want: { words: "no answer within 50ms" } }, ]) { send({ jsonrpc: "2.0", id: row.id, method: "tools/call", params: { name: "publish", arguments: {} } }); + if (row.answers.length === 0) await until((m) => m.method === "mesh/ask" && !m.answered).then((m) => { m.answered = true; }); for (const a of row.answers) { const asked = await until((m) => m.method === "mesh/ask" && !m.answered); assert.ok(asked, `the bundle did not ask again (row ${row.id})`); @@ -422,9 +422,9 @@ test("a call a stopping tool runner did not take is asked again after a pause un } const done = await until((m) => m.id === row.id); assert.deepEqual(JSON.parse(done.result.content[0].text), row.want); - assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${row.answers.length} times`); + assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${Math.max(row.answers.length, 1)} times`); } - assert.match(said, /the tool runner is stopping/); + assert.doesNotMatch(said, /asked again/); } finally { child.kill(); } From e6da0aeb5ffbc1fd4c89ed7078535024797c7a3c Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:06:06 +0100 Subject: [PATCH 04/16] S5 ledger-watch: stdio.WatchLedger and the bundle's mesh/ledger answer Builds: design 47 H2 H-A-706 (DMC-13), H-A-717 (DQ-50) --- go/busstate.go | 35 +++++++++++++++++++ go/stdio.go | 20 ++++++++++- go/stdio_test.go | 87 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 1 deletion(-) diff --git a/go/busstate.go b/go/busstate.go index a77133f6..24f6bb06 100644 --- a/go/busstate.go +++ b/go/busstate.go @@ -2,7 +2,9 @@ package stdio import ( "encoding/json" + "errors" "fmt" + "git.novox.be/novox/mesh-sdk/go/buscalls" "strings" "time" ) @@ -29,3 +31,36 @@ func BusState(method string, params any) (json.RawMessage, error) { } return c.ask(method, params, 60*time.Second) } + +// WatchLedger hands handle every current state of the instances of this bundle's own ledger that instances names (an +// instance, with `*` for one name and `>` for the rest; empty is every instance), and then every change, in the order it +// came, and returns once the current states have all been handled. The watch lasts as long as the process. handle runs +// beside the runtime (follower.go): its time never counts against the runtime's bound on the current states, and an error +// it returns is said on standard error. A watch the runtime refuses is given up, said, and a change the runtime still hands +// to it is refused saying so. A change names the instance's expiry while it has ended (design 47 H2 H-A-706 on DMC-13, +// H-A-717 DQ-50). +func WatchLedger(ledger, instances string, handle func(buscalls.InstanceChange) error) error { + if handle == nil { + return errors.New("a watch needs a handler") + } + c, err := live() + if err != nil { + return err + } + id := c.newID() + f := newFollower("the watch "+id+" of the ledger "+ledger, handle, func(ch buscalls.InstanceChange) string { return ch.Instance }) + c.mu.Lock() + c.ledgerWatches[id] = f + c.mu.Unlock() + if _, err := c.askAs(id, buscalls.LedgerWatch, buscalls.LedgerWatchRequest{Ledger: ledger, Instances: instances, Watch: id}, 60*time.Second); err != nil { + c.mu.Lock() + delete(c.ledgerWatches, id) + c.gaveUp(id, fmt.Sprintf("the ledger %s at %s: %v", ledger, time.Now().Format(time.RFC3339), err)) + c.mu.Unlock() + sayf("the watch %s of the ledger %s is given up: %v", id, ledger, err) + return err + } + // The runtime hands every current state over before it answers the watch: each is in the follower by now. + <-f.handled() + return nil +} diff --git a/go/stdio.go b/go/stdio.go index 06a6c613..bdc6fbb7 100644 --- a/go/stdio.go +++ b/go/stdio.go @@ -20,6 +20,7 @@ import ( "encoding/json" "errors" "fmt" + "git.novox.be/novox/mesh-sdk/go/buscalls" "io" "os" "strconv" @@ -83,6 +84,8 @@ type channel struct { watches map[string]*follower[StateChange] // provisioned are this bundle's watches of its values, by the id each was asked with (provision.go). provisioned map[string]*follower[ProvisionChange] + // ledgerWatches are this bundle's watches of its ledgers, by the id each was asked with (busstate.go). + ledgerWatches map[string]*follower[buscalls.InstanceChange] // givenUp are the watches this bundle gave up, by id, each with why (follower.go). givenUp map[string]string // logWatches are this bundle's watches of a log, by the id each was asked with (log.go). @@ -221,7 +224,7 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error { byName[t.Name] = t } c := &channel{enc: json.NewEncoder(out), waiting: map[string]chan message{}, watches: map[string]*follower[StateChange]{}, - provisioned: map[string]*follower[ProvisionChange]{}, logWatches: map[string]func(LogEntry) error{}, + provisioned: map[string]*follower[ProvisionChange]{}, ledgerWatches: map[string]*follower[buscalls.InstanceChange]{}, logWatches: map[string]func(LogEntry) error{}, takers: map[string]func(Work) error{}, provers: map[string]func(string, json.RawMessage) (any, error){}} currentMu.Lock() current = c @@ -367,6 +370,21 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error { } f.take(*p.Change) go c.say(map[string]any{"id": id, "result": map[string]any{}}) + case buscalls.LedgerWatched: + // One change to an instance of a ledger this bundle watches (WatchLedger), named by the watch's id: taken into the + // watch's follower in the order it came and answered at once, as a state's change is, so a slow handler never counts + // against the runtime's bound on the current states (design 47 H2 H-A-706 on DMC-13). + var change buscalls.InstanceChange + _ = json.Unmarshal(m.Params, &change) + c.mu.Lock() + f := c.ledgerWatches[change.Watch] + c.mu.Unlock() + if f == nil || change.Instance == "" { + c.say(map[string]any{"id": id, "error": map[string]any{"code": -32602, "message": c.noWatch(buscalls.LedgerWatched, change.Watch)}}) + continue + } + f.take(change) + go c.say(map[string]any{"id": id, "result": map[string]any{}}) case "mesh/log": // One entry of a log this bundle watches (log.go), named by the watch's id, answered once its handler has // taken it, in order: the runtime sends the next only after this answer. diff --git a/go/stdio_test.go b/go/stdio_test.go index ca906676..14d331db 100644 --- a/go/stdio_test.go +++ b/go/stdio_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "git.novox.be/novox/mesh-sdk/go/buscalls" "io" "strings" "sync" @@ -495,3 +496,89 @@ func TestAskCallsOnceAndFaultsAtItsBound(t *testing.T) { } _ = inW.Close() } + +// Design 47 H2 H-A-706 on DMC-13: a bundle's ledger watch is asked with `mesh/ledger.watch` under an id it keeps, each +// `mesh/ledger` change naming that id is handed to its handler in the order it came (the current states first, before the +// watch is answered), and a change naming no watch of it is refused as a state's is. +func TestABundlesLedgerWatchIsHandedItsChangesInOrder(t *testing.T) { + servesAlone(t) + t.Setenv(ServedAs, "gate") + inR, inW := io.Pipe() + outR, outW := io.Pipe() + seen := make(chan string, 8) + watched := make(chan error, 1) + go func() { + _ = ServeOn("", []Tool{{Name: "start", Run: func(map[string]any) (any, error) { + go func() { + watched <- WatchLedger("records", "record/>", func(c buscalls.InstanceChange) error { + seen <- c.Instance + return nil + }) + }() + return "started", nil + }}}, inR, outW) + }() + lines := bufio.NewScanner(outR) + next := func() map[string]any { + done := make(chan map[string]any, 1) + go func() { + if lines.Scan() { + var m map[string]any + _ = json.Unmarshal(lines.Bytes(), &m) + done <- m + } + }() + select { + case m := <-done: + return m + case <-time.After(3 * time.Second): + t.Fatal("the bundle said nothing") + return nil + } + } + send := func(m map[string]any) { b, _ := json.Marshal(m); _, _ = inW.Write(append(b, '\n')) } + send(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": map[string]any{"name": "start"}}) + got := map[string]map[string]any{} + for len(got) < 2 { + m := next() + if m["method"] != nil { + got[m["method"].(string)] = m + } else { + got["answer"] = m + } + } + watch := got[buscalls.LedgerWatch] + if p := watch["params"].(map[string]any); p["ledger"] != "records" || p["instances"] != "record/>" || p["watch"] != watch["id"] { + t.Fatalf("asked to watch %v", p) + } + for i, instance := range []string{"record/a", "record/b"} { + send(map[string]any{"jsonrpc": "2.0", "id": 50 + i, "method": buscalls.LedgerWatched, "params": map[string]any{ + "watch": watch["id"], "instance": instance, "state": map[string]any{}, "sequence": 1, "current": true}}) + if r := next(); r["id"] != float64(50+i) || r["error"] != nil { + t.Fatalf("a current state was answered %v", r) + } + } + select { + case err := <-watched: + t.Fatalf("the watch returned before it was answered: %v", err) + default: + } + send(map[string]any{"jsonrpc": "2.0", "id": watch["id"], "result": map[string]any{}}) + if err := <-watched; err != nil { + t.Fatal(err) + } + send(map[string]any{"jsonrpc": "2.0", "id": 60, "method": buscalls.LedgerWatched, "params": map[string]any{ + "watch": watch["id"], "instance": "record/c", "state": map[string]any{}, "sequence": 2}}) + if r := next(); r["id"] != float64(60) || r["error"] != nil { + t.Fatalf("a change was answered %v", r) + } + if order := []string{<-seen, <-seen, <-seen}; strings.Join(order, " ") != "record/a record/b record/c" { + t.Fatalf("handled in the order %v", order) + } + send(map[string]any{"jsonrpc": "2.0", "id": 61, "method": buscalls.LedgerWatched, "params": map[string]any{ + "watch": "bundle-999", "instance": "record/d", "state": map[string]any{}}}) + if r := next(); r["id"] != float64(61) || r["error"] == nil { + t.Fatalf("a change naming no watch of it was answered %v", r) + } + _ = inW.Close() +} From b4f9429115c7e9f2ccc753f34069ef75de342203 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:06:52 +0100 Subject: [PATCH 05/16] S9 kept-call-hook: a kept call's hook at five minutes waited and at its answer Builds: design 47 H2 H-A-708 (4) --- go/busretry/busretry.go | 25 +++++++++++++++++++++++-- go/busretry/busretry_test.go | 22 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/go/busretry/busretry.go b/go/busretry/busretry.go index 52daccef..b166be4a 100644 --- a/go/busretry/busretry.go +++ b/go/busretry/busretry.go @@ -120,13 +120,27 @@ func jittered(w time.Duration) time.Duration { // Kept names one kept call of the paced form (design 47 H2 §775): the seat and the verb it asks (named in the journal // line), the ask's id (named among the asks waiting), the caller's bound (zero is Bound) and the pace (zero is // KeptPace). Open, when given, makes it asked again only while its key is open (DoKept). Logf is the journal; nil -// writes to standard error. +// writes to standard error. Hook, when given, is called when the call has waited WaitSaid, with its last fault and since +// when it waited, and once more when it is answered (design 47 H2 H-A-708 (4)). type Kept struct { Seat, Verb, Ask string Bound time.Duration Pace Pace Open *Open Logf func(format string, args ...any) + Hook func(Waited) +} + +// WaitSaid is how long a kept call waits before its hook says so (design 47 H2 H-A-708 (4)). +const WaitSaid = 5 * time.Minute + +// Waited is what a kept call's hook is told: the call's seat, verb and ask, since when it waited, its last fault's words, +// and whether it is answered (the call ended, by an answer of any kind that is no transport fault). +type Waited struct { + Seat, Verb, Ask string + Since time.Time + Last string + Answered bool } // Try is one call of a kept call that met a transport fault: when it was made and the words it met. @@ -231,7 +245,7 @@ func DoPaced[T any](k Kept, try func() (T, error)) (T, error) { } start, wait := now(), pace.First var tries []Try - waiting := false + waiting, said := false, false defer func() { if waiting { journal.done(k.Seat, k.Ask) @@ -241,9 +255,16 @@ func DoPaced[T any](k Kept, try func() (T, error)) (T, error) { at := now() v, err := try() if !Fault(err) || (k.Open != nil && !k.Open.stillOpen()) { + if said { + k.Hook(Waited{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Since: start, Last: tries[len(tries)-1].Words, Answered: true}) + } return v, err } tries = append(tries, Try{At: at, Words: err.Error()}) + if !said && k.Hook != nil && now().Sub(start) >= WaitSaid { + said = true + k.Hook(Waited{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Since: start, Last: err.Error()}) + } if !waiting { journal.wait(k.Seat, k.Ask) waiting = true diff --git a/go/busretry/busretry_test.go b/go/busretry/busretry_test.go index 36da3a72..1c3f616e 100644 --- a/go/busretry/busretry_test.go +++ b/go/busretry/busretry_test.go @@ -164,6 +164,28 @@ func subAKeptCallIsPaced(t *testing.T) { } } }) + t.Run("the hook is told at five minutes waited, once, and at the answer", func(t *testing.T) { + fakeClock(t) + tries, told := 0, []Waited{} + v, err := DoPaced(Kept{Seat: "mesh-builds", Verb: "build", Ask: "a9", Bound: time.Hour, Logf: func(string, ...any) {}, + Hook: func(w Waited) { told = append(told, w) }}, func() (int, error) { + if tries++; tries <= 40 { + return 0, nats.ErrNoResponders + } + return 3, nil + }) + if v != 3 || err != nil || len(told) != 2 || told[0].Answered || !told[1].Answered || told[0].Seat != "mesh-builds" || + told[0].Verb != "build" || told[0].Last == "" || !told[0].Since.Equal(told[1].Since) { + t.Fatalf("%d, %v, told %+v", v, err, told) + } + // Answered within the five minutes: the hook is never told. + tries, told = 0, nil + _, _ = DoPaced(Kept{Seat: "s", Verb: "v", Logf: func(string, ...any) {}, Hook: func(w Waited) { told = append(told, w) }}, + func() (int, error) { tries++; return 1, map[bool]error{true: nats.ErrNoResponders}[tries < 3] }) + if len(told) != 0 { + t.Fatalf("told %+v for a call answered in time", told) + } + }) t.Run("a refusal returns at once", func(t *testing.T) { slept := fakeClock(t) tries := 0 From f0bc6a3ceb8c67b0c444f7139daf62d2127dbece Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:09:15 +0100 Subject: [PATCH 06/16] S8 unread-away: Unread of a state and a view, the away answers, the start's phase Builds: design 47 H2 H-A-708 (1) (2), H-A-717 (DQ-54, DQ-58) --- go/process/call_test.go | 24 ++++++++++ go/process/serve.go | 19 +++++++- go/state_test.go | 33 +++++++++++++ go/stdio.go | 6 +++ go/stdio_test.go | 53 +++++++++++++++++++++ go/views/follow.go | 20 ++++++++ go/views/process_reader.go | 41 ++++++++++++++++ go/views/process_reader_integration_test.go | 27 +++++++++++ go/views/status.go | 18 ++++++- go/views/views_test.go | 28 +++++++++++ go/watched.go | 31 +++++++++++- 11 files changed, 294 insertions(+), 6 deletions(-) diff --git a/go/process/call_test.go b/go/process/call_test.go index 41bdfca8..2e50f44c 100644 --- a/go/process/call_test.go +++ b/go/process/call_test.go @@ -203,6 +203,30 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) { t.Errorf("the holder read the ask %q, want %q, and none once its handler ended", read, ask) } } + // Design 47 H2 H-A-708 (2): a handler's `away` fault is answered as §776's `away` (error-kind, part, words) and read back + // by the caller as the transport fault; a plain refusal names no kind. + for _, row := range []struct { + err error + kind string + part string + fault bool + }{ + {&busretry.Away{Part: "the trunk's revision 512", Words: "not read yet since 23:35:40"}, "away", "the trunk's revision 512", true}, + {fmt.Errorf("reading: %w", &busretry.Away{Part: "the state seat-definitions", Words: "w"}), "away", "the state seat-definitions", true}, + {errors.New("refused"), "", "", false}, + } { + body := c.answerBody(askMsg("mesh.seat.mesh-catalog.tool.revision", []byte(`{}`), ""), "mesh.seat.mesh-catalog.tool.revision", + func(string, json.RawMessage, bool) (any, *approval.Held, error) { return nil, nil, row.err }) + var got struct{ Kind, Part string } + var raw map[string]any + _ = json.Unmarshal(body, &raw) + got.Kind, _ = raw["error-kind"].(string) + got.Part, _ = raw["part"].(string) + away := busretry.AwayIn(body) + if got.Kind != row.kind || got.Part != row.part || (away != nil) != row.fault || (away != nil && busretry.Fault(away) != true) { + t.Errorf("%v answered %s", row.err, body) + } + } // Design 47 H2 §775, H-A-405: a kept chunked call (CallChunksKept, CallFileKept) asks its verb through the kept-call // form, carries its one ask id on every chunk's acknowledgement, and past its bound ends with the kept call's words. send := buscalls.SeatChunks{Seat: "node-build-go", Verb: "output", Call: "c1"} diff --git a/go/process/serve.go b/go/process/serve.go index 4e2eabf1..0748aedc 100644 --- a/go/process/serve.go +++ b/go/process/serve.go @@ -2,6 +2,7 @@ package process import ( "encoding/json" + "errors" "fmt" "regexp" "sort" @@ -13,6 +14,7 @@ import ( stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/approval" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/calladdress" "git.novox.be/novox/mesh-sdk/go/seatdef" ) @@ -177,6 +179,11 @@ func AskOf(body json.RawMessage) string { // answerCall runs h for one call and replies {result, error, node}; a panic in h is the call's error, never silence. func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) { + _ = msg.Respond(c.answerBody(msg, pattern, h)) +} + +// answerBody is the reply answerCall sends. +func (c *Conn) answerBody(msg *nats.Msg, pattern string, h heldHandler) []byte { caller := "" if strings.HasSuffix(pattern, ".*") { caller = userOfToken(msg.Subject[strings.LastIndex(msg.Subject, ".")+1:]) @@ -184,7 +191,11 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) { var reply struct { Result any `json:"result,omitempty"` Error string `json:"error,omitempty"` - Node string `json:"node,omitempty"` + // ErrorKind, Part and Words are an answer of the kind away (design 47 H2 §776, H-A-708 (2)). + ErrorKind string `json:"error-kind,omitempty"` + Part string `json:"part,omitempty"` + Words string `json:"words,omitempty"` + Node string `json:"node,omitempty"` // Held is a kept call's answer (design 47 G §677; lead answer A-244). Held *approval.Held `json:"held,omitempty"` } @@ -205,6 +216,10 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) { switch { case err != nil: reply.Error = err.Error() + var away *busretry.Away + if errors.As(err, &away) { + reply.ErrorKind, reply.Part, reply.Words = busretry.ErrorKindAway, away.Part, away.Words + } case held != nil: reply.Held = held case result == nil: @@ -218,5 +233,5 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) { if err != nil { body, _ = json.Marshal(map[string]string{"error": "the answer is not JSON: " + err.Error(), "node": c.account.Node}) } - _ = msg.Respond(body) + return body } diff --git a/go/state_test.go b/go/state_test.go index 85a80848..53dcc242 100644 --- a/go/state_test.go +++ b/go/state_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "git.novox.be/novox/mesh-sdk/go/busretry" "io" "sort" "strings" @@ -610,3 +611,35 @@ func strs(v any) []string { } return out } + +// Design 47 H2 H-A-708 (2): Unread says `away`, naming the state and since when, while the state's copy has not taken in its +// current values, whether its watch is not asked for yet or is still handing them over, and nothing once it has. +func TestAWatchedCopyIsUnreadUntilItsCurrentValuesAreIn(t *testing.T) { + release, entered := make(chan struct{}), make(chan struct{}) + w := WatchedStatesOver(func(state string, handle func(StateChange) error) error { + close(entered) + <-release + return handle(StateChange{State: state, Key: "a", Op: OpPut, Value: []byte("1"), Current: true}) + }, nil) + asAway := func() *busretry.Away { + var away *busretry.Away + if !errors.As(w.Unread("placement"), &away) { + return nil + } + return away + } + if a := asAway(); a == nil || a.Part != "the state placement" || !strings.HasPrefix(a.Words, "not read yet since ") { + t.Fatalf("before the watch is asked: %+v", a) + } + done := make(chan struct{}) + go func() { _, _ = w.Keys("placement"); close(done) }() + <-entered + if a := asAway(); a == nil { + t.Fatal("while the watch hands its current values over, the copy is read") + } + close(release) + <-done + if err := w.Unread("placement"); err != nil { + t.Fatalf("after the current values are in: %v", err) + } +} diff --git a/go/stdio.go b/go/stdio.go index bdc6fbb7..86105db7 100644 --- a/go/stdio.go +++ b/go/stdio.go @@ -301,6 +301,12 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error { args = map[string]any{} } result, err := runAs(t, inFlight{caller, call, ask}, args) + // A tool's `away` fault is its result in §776's form, so it reaches the caller whole (design 47 H2 H-A-708 (2), + // H-A-717 DQ-58); any other fault is an error as before. + var away *busretry.Away + if errors.As(err, &away) { + result, err = busretry.AwayAnswer(away.Part, away.Words), nil + } if err != nil { c.say(map[string]any{"id": id, "result": map[string]any{"content": []map[string]any{{"type": "text", "text": err.Error()}}, "isError": true}}) return diff --git a/go/stdio_test.go b/go/stdio_test.go index 14d331db..df7bbdcf 100644 --- a/go/stdio_test.go +++ b/go/stdio_test.go @@ -5,7 +5,9 @@ import ( "context" "encoding/json" "errors" + "fmt" "git.novox.be/novox/mesh-sdk/go/buscalls" + "git.novox.be/novox/mesh-sdk/go/busretry" "io" "strings" "sync" @@ -582,3 +584,54 @@ func TestABundlesLedgerWatchIsHandedItsChangesInOrder(t *testing.T) { } _ = inW.Close() } + +// Design 47 H2 H-A-708 (2), H-A-717 DQ-58: a tool's `away` fault is its result in §776's form (error-kind, part, words), no +// error; a plain refusal stays an error. +func TestAToolsAwayFaultIsItsResultInTheAwayForm(t *testing.T) { + servesAlone(t) + t.Setenv(ServedAs, "indexer") + inR, inW := io.Pipe() + outR, outW := io.Pipe() + go func() { + _ = ServeOn("", []Tool{ + {Name: "revision", Run: func(map[string]any) (any, error) { + return nil, fmt.Errorf("reading: %w", &busretry.Away{Part: "the trunk's revision 512", Words: "not read yet since 23:35:40"}) + }}, + {Name: "refuse", Run: func(map[string]any) (any, error) { return nil, errors.New("refused") }}, + }, inR, outW) + }() + lines := bufio.NewScanner(outR) + for i, row := range []struct { + tool, want string + isError bool + }{ + {"revision", string(mustJSON(t, busretry.AwayAnswer("the trunk's revision 512", "not read yet since 23:35:40"))), false}, + {"refuse", "refused", true}, + } { + b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": map[string]any{"name": row.tool}}) + _, _ = inW.Write(append(b, '\n')) + if !lines.Scan() { + t.Fatal("the bundle said nothing") + } + var m struct { + Result struct { + Content []struct{ Text string } + IsError bool `json:"isError"` + } + } + _ = json.Unmarshal(lines.Bytes(), &m) + if len(m.Result.Content) != 1 || m.Result.Content[0].Text != row.want || m.Result.IsError != row.isError { + t.Errorf("%s answered %s", row.tool, lines.Text()) + } + } + _ = inW.Close() +} + +func mustJSON(t *testing.T, v any) []byte { + t.Helper() + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return b +} diff --git a/go/views/follow.go b/go/views/follow.go index 7fb9f00d..7a8cb8f2 100644 --- a/go/views/follow.go +++ b/go/views/follow.go @@ -14,6 +14,7 @@ import ( "github.com/nats-io/nats.go/jetstream" "git.novox.be/novox/mesh-sdk/go/buscalls" + "git.novox.be/novox/mesh-sdk/go/busretry" ) // Follower is a reader's picture of one state of an owner (ADR 0615 §4 to §6): it asks the owner's first-view tool at @@ -67,6 +68,7 @@ type Follower struct { // catching is set while catchUp runs: one catch-up at a time. catching bool ready chan struct{} + born time.Time // when the follower began (Unread) } // Status is what a reader's read tool says of one first view (design 25 § 12.2): the owner, the tool and the revision @@ -186,6 +188,7 @@ func (f *Follower) init() { f.values = map[string]json.RawMessage{} f.ready = make(chan struct{}) f.st = Status{Owner: f.Owner, Tool: f.Tool, State: f.State} + f.born = f.now() } } @@ -222,6 +225,23 @@ func (f *Follower) Ready() <-chan struct{} { return f.ready } +// Unread says whether the first view was not answered yet: the fault `away` (busretry.Away, design 47 H2 §776) naming the +// view's owner verb (its Tool) and saying "not read yet since