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)
This commit is contained in:
2026-11-25 17:09:15 +01:00
parent b4f9429115
commit f0bc6a3ceb
11 changed files with 294 additions and 6 deletions
+24
View File
@@ -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"}
+17 -2
View File
@@ -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
}
+33
View File
@@ -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)
}
}
+6
View File
@@ -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
+53
View File
@@ -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
}
+20
View File
@@ -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 <time>" until Ready closes, nil after. A handler asks it before
// it reads, so a call made while the first view is not in is answered `away` at once; Get and Values keep answering what the
// picture holds, an empty one before the first view (design 47 H2 H-A-708 (2)).
func (f *Follower) Unread() error {
f.mu.Lock()
f.init()
ready, since := f.ready, f.born
f.mu.Unlock()
select {
case <-ready:
return nil
default:
}
return &busretry.Away{Part: f.Tool, Words: "not read yet since " + since.UTC().Format("15:04:05")}
}
// Values is a copy of the picture.
func (f *Follower) Values() map[string]json.RawMessage {
f.mu.Lock()
+41
View File
@@ -77,6 +77,8 @@ type ProcessReader struct {
unheard int
lastUnheard string
startedAt time.Time
// phase is the phase the holder's start is in, nil while none runs (BeginPhase).
phase *StartPhase
// hooked is the hub the count of unhandled events is wired on, so a second Start counts no event twice.
hooked *process.EventHub
}
@@ -939,6 +941,7 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
if status != nil {
status.Ready(func(kv jetstream.KeyValue) {
KeepOwnBuild(ctx, kv, process.OwnBuild(), r.logf)
r.keepPhase()
if err := hearAgain(ctx, kv, r.Followers, r.logf); err != nil {
r.logf("views: the hand asks of %s's first views are not heard (%v) until it starts again", r.Module, err)
}
@@ -952,6 +955,44 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
r.Ask(ctx, said)
}
// BeginPhase says the holder's start is in the phase name since now, ending the one before: it is said in the journal and
// kept at StartPhaseKey of the state `first-views`, which the part's first-views tool answers beside the views, so a call
// that meets `away` while the holder starts says what the start is doing (design 47 H2 H-A-708 (1), H-A-717 DQ-54). EndPhase
// ends it.
func (r *ProcessReader) BeginPhase(name string) {
r.mu.Lock()
r.phase = &StartPhase{Name: name, Since: r.now().UTC()}
r.mu.Unlock()
r.logf("views: %s's start is in the phase %s", r.Module, name)
r.keepPhase()
}
// EndPhase says the holder's start is in no phase.
func (r *ProcessReader) EndPhase() {
r.mu.Lock()
ended := r.phase
r.phase = nil
r.mu.Unlock()
if ended != nil {
r.logf("views: %s's start ends the phase %s", r.Module, ended.Name)
}
r.keepPhase()
}
// keepPhase writes the phase now at StartPhaseKey, once the state is there (a bucket not yet opened keeps it for then).
func (r *ProcessReader) keepPhase() {
r.mu.Lock()
status, phase := r.status, r.phase
r.mu.Unlock()
if status == nil {
return
}
data, _ := json.Marshal(phase)
if _, err := status.Put(context.Background(), StartPhaseKey, data); err != nil {
r.logf("views: the start phase is not kept in %s: %v", StatusState, err)
}
}
// handleEvent registers handle on the hub for a seat's event on its bare subject and on every further part after it
// (`<subject>.>`): one handler, both forms, as the seat's contract says the event on either (design 47 H, H-A-166; one
// subscription per event, design 47 G §532). The two patterns do not overlap, so a message reaches the handler once.
@@ -58,8 +58,35 @@ func subAReaderHearsAnOwnersChangesAsOrdinaryEvents(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// H-A-708 (1), H-A-717 DQ-54: the phase the start is in, set before the state is there, is kept in it once it is, and
// ended with null.
r.BeginPhase("take-in")
r.Start(ctx, js, cred, process.AwaitBucket(ctx, js, nil, "reader_first-views", "", t.Logf))
<-r.Ready()
phases, err := statusKV.Watch(ctx, views.StartPhaseKey)
if err != nil {
t.Fatal(err)
}
phaseNow := func() string {
for e := range phases.Updates() {
if e != nil {
var p *views.StartPhase
_ = json.Unmarshal(e.Value(), &p)
if p == nil {
return "none"
}
return p.Name
}
}
return "closed"
}
if got := phaseNow(); got != "take-in" {
t.Fatalf("the start's phase is %s", got)
}
r.EndPhase()
if got := phaseNow(); got != "none" {
t.Fatalf("the start's phase after it ended is %s", got)
}
pic, err := r.KeyValue(ctx, "o_modules")
if err != nil {
t.Fatal(err)
+16 -2
View File
@@ -19,6 +19,16 @@ import (
// process serves no tool (ADR 0436), so its read and re-read tools, in its tools bundle, meet it here.
const StatusState = "first-views"
// StartPhaseKey is where a process keeps the phase its start is in (design 47 H2 H-A-708 (1), H-A-717 DQ-54), in its state
// `first-views`: a StartPhase, or null while no phase runs. The read tool answers it beside the views, under this name.
const StartPhaseKey = "start-phase"
// StartPhase is the phase a holder's start is in: its name and since when.
type StartPhase struct {
Name string `json:"name"`
Since time.Time `json:"since"`
}
// StatusKey is where a reader keeps its first view of owner's state.
func StatusKey(owner, state string) string { return owner + "." + state }
@@ -125,7 +135,7 @@ func StatusTools(reader, read, again string, st keptStatus, acts HandActs, now f
}
out := []Status{}
for _, k := range keys {
if strings.HasPrefix(k, "again.") || k == OwnBuildKey {
if strings.HasPrefix(k, "again.") || k == OwnBuildKey || k == StartPhaseKey {
continue
}
e, err := st.Get(k)
@@ -144,7 +154,11 @@ func StatusTools(reader, read, again string, st keptStatus, acts HandActs, now f
own = w
}
}
return map[string]any{"first-views": out, OwnBuildKey: own}, nil
var phase *StartPhase
if e, err := st.Get(StartPhaseKey); err == nil && e != nil {
_ = json.Unmarshal(e.Value, &phase)
}
return map[string]any{"first-views": out, OwnBuildKey: own, StartPhaseKey: phase}, nil
}},
{Name: again,
Description: fmt.Sprintf("Ask %s's first view of an owner's state again now, by hand (a hand act, its caller and why kept in "+
+28
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/busretry"
"maps"
"reflect"
"runtime"
@@ -1534,3 +1535,30 @@ func TestFirstViewsSayTheOwnBuild(t *testing.T) {
t.Errorf("nothing kept: %v", read)
}
}
// Design 47 H2 H-A-708 (1) (2), H-A-717 DQ-54: a first view not yet answered says `away` naming its owner's verb and since when,
// at once, and nothing after Ready; the status tool answers the phase the start is in beside the views.
func TestAFirstViewIsUnreadUntilItsAnswerIsIn(t *testing.T) {
now := time.Date(2026, 11, 25, 23, 35, 40, 0, time.UTC)
f := &Follower{Owner: "mesh-catalog", Tool: "mesh-catalog.seat-definitions", State: "seat-definitions", Now: func() time.Time { return now },
Ask: func(context.Context, string) (Answer, error) { return Answer{}, nil }}
var away *busretry.Away
if err := f.Unread(); !errors.As(err, &away) || away.Part != "mesh-catalog.seat-definitions" || away.Words != "not read yet since 23:35:40" {
t.Fatalf("before the first view: %v", err)
}
if err := f.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := f.Unread(); err != nil {
t.Fatalf("after the first view: %v", err)
}
st := statusWith{StartPhaseKey: []byte(`{"name":"take-in","since":"2026-11-25T23:35:40Z"}`)}
read, _ := StatusTools("m", "m_first_views", "m_first_view_again", st, nil, time.Now)[0].Run(nil)
if p, ok := read.(map[string]any)[StartPhaseKey].(*StartPhase); !ok || p == nil || p.Name != "take-in" || !p.Since.Equal(now) {
t.Fatalf("the status tool says %v", read)
}
none, _ := StatusTools("m", "r", "a", statusWith{}, nil, time.Now)[0].Run(nil)
if p := none.(map[string]any)[StartPhaseKey].(*StartPhase); p != nil {
t.Fatalf("no phase kept: %v", none)
}
}
+29 -2
View File
@@ -2,6 +2,7 @@ package stdio
import (
"fmt"
"git.novox.be/novox/mesh-sdk/go/busretry"
"sort"
"sync"
"time"
@@ -22,12 +23,15 @@ type WatchedStates struct {
// once holds each value read with Once, by state and key, for the process's life: a few kilobytes per manifest
// digest. Past onceAtMost keys it is emptied, which costs only a read again.
once map[string][]byte
// born is when the copy was made: a state not yet asked for is unread since then (Unread).
born time.Time
}
// onceAtMost bounds the values Once keeps.
const onceAtMost = 4096
type watchedState struct {
asked time.Time // when its watch began (Unread)
ready chan struct{} // closed once the watch's current values are all in the copy, or it was refused
err error
@@ -60,7 +64,7 @@ func NewWatchedStates() *WatchedStates {
// every current value and returns once they are handled, then hands every change; get reads one key.
func WatchedStatesOver(watch func(state string, handle func(StateChange) error) error,
get func(state, key string) ([]byte, bool, error)) *WatchedStates {
return &WatchedStates{watch: watch, get: get, states: map[string]*watchedState{}, once: map[string][]byte{}}
return &WatchedStates{watch: watch, get: get, states: map[string]*watchedState{}, once: map[string][]byte{}, born: time.Now()}
}
// watched is the state's copy, its watch started now when it has none, the caller waiting until its current values
@@ -81,7 +85,7 @@ func (w *WatchedStates) watched(state string, then func(StateChange) error) (*wa
}
return s, nil
}
s = &watchedState{ready: make(chan struct{}), values: map[string][]byte{}, revs: map[string]uint64{}}
s = &watchedState{asked: time.Now(), ready: make(chan struct{}), values: map[string][]byte{}, revs: map[string]uint64{}}
if then != nil {
s.then = []func(StateChange) error{then}
}
@@ -130,6 +134,29 @@ func (w *WatchedStates) watched(state string, then func(StateChange) error) (*wa
return s, nil
}
// Unread says whether the copy of state has not taken in its current values yet: the fault `away` (busretry.Away, design
// 47 H2 §776) with `part` naming the state and `words` "not read yet since <time>", while the state's watch has not
// handed them all over (or was never asked for, since the copy was made); nil once it has, and nothing after. A handler
// asks it before it reads, so a call made while the module starts is answered `away` at once; a read itself still waits
// (watched) for the module's own start (design 47 H2 H-A-708 (2)).
func (w *WatchedStates) Unread(state string) error {
w.mu.Lock()
s, ok := w.states[state]
w.mu.Unlock()
since := w.born
if ok {
select {
case <-s.ready:
if s.err == nil {
return nil
}
default:
}
since = s.asked
}
return &busretry.Away{Part: "the state " + state, Words: "not read yet since " + since.UTC().Format("15:04:05")}
}
// join adds then to a state already watched (a read started its watch first) and runs it over the copy's current values
// before any later change, so no change that landed before it joined is lost to it (review of ADR 0580 §2: a read
// beat the follower to the watch at start-up). Under thenMu, so a later change waits for these; a change the copy took