From af36f1a6174d6ffdc97b3630dabf7838072ce920 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:07:17 +0100 Subject: [PATCH 01/13] G14 ledger-lifetimes-planned: a ledger giving ended-days is planned with lifetimes, its snapshot store refuses when full, its binding says ended-days once the bus holds them The bus module plans a ledger whose own configuration gives ended-days with a lifetime per key on its state and index buckets and a lifetime per message on its snapshot store, reads a held stream's lifetime back, plans every ledger's snapshot store to refuse when full, names ended-days in the binding only once every object that asks a lifetime holds one, and says created again when the binding it would say differs from the one it last said (Made.Said). Builds: design 47 H2 H-A-634 (3), H-A-636, H-A-685 (1) (2), H-A-687 (1) (5) --- .../cmd/nats-tools/keeper_integration_test.go | 19 +++++ modules/nats/internal/keeper/jetstream.go | 4 +- modules/nats/internal/keeper/keeper.go | 48 ++++++++++- modules/nats/internal/keeper/keeper_test.go | 81 ++++++++++++++++++- modules/nats/internal/keeper/plan.go | 21 ++++- modules/nats/internal/keeper/requests.go | 8 ++ 6 files changed, 173 insertions(+), 8 deletions(-) diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index 8f9ca6c45..fe0b63972 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -638,6 +638,25 @@ func TestTheBusModuleRunsWhole(t *testing.T) { onBranch("main", "sb", 6, nil) eventually(t, "sb's plan deleted", func() bool { _, _, found, _ := store.Get(keeper.StatePlans, "sb"); return !found }) }) + // Design 47 H2 H-A-634 (3), H-A-687 (1): a ledger giving ended-days is made with a lifetime per key on its state and + // index buckets and a lifetime per message on its snapshot store, which refuses when full. + t.Run("a ledger giving ended-days is made with lifetimes and a snapshot store that refuses when full", func(t *testing.T) { + ending := entry("records", "ledger", "ledger", map[string]string{"max-mib": "4"}) + ending.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("30"), "max-age-days": json.RawMessage("90")} + ending.Types = []catalogue.LedgerType{{Name: "record", EndsWith: "ended", Schema: map[string]catalogue.LedgerField{"ended": {Type: "map"}}, + Operations: []catalogue.LedgerOperation{{Name: "end", Effect: catalogue.EffectSetFields, Fields: []string{"ended"}}}}} + accepted("ld", 9, ending) + eventually(t, "created ld records", saidHas("created ld records")) + if info, ok := held("ld_records_snapshot"); !ok || !info.Config.AllowMsgTTL || info.Config.Discard != jetstream.DiscardNew { + t.Errorf("the snapshot store is %+v: a lifetime per message, refusing when full", info) + } + if info, ok := held("KV_ld_records_state"); !ok || !info.Config.AllowMsgTTL { + t.Errorf("the state bucket is %+v: a lifetime per key", info) + } + if got := k.Held()["ld"].Made["records"].Plan.Binding.EndedDays; got != 30 { + t.Errorf("the binding names ended-days %d, want 30: the bus holds every lifetime", got) + } + }) t.Run("nats_first_view_again asks at once and records the hand act", func(t *testing.T) { raw, _ := json.Marshal(keeper.Request{ID: "r3", Verb: keeper.VerbFirstViewAgain, Why: "a verdict thought missed", Caller: "person.jo"}) _, _ = store.Put(keeper.StateRequests, "r3", raw) diff --git a/modules/nats/internal/keeper/jetstream.go b/modules/nats/internal/keeper/jetstream.go index c5bd4b628..8151c6c7b 100644 --- a/modules/nats/internal/keeper/jetstream.go +++ b/modules/nats/internal/keeper/jetstream.go @@ -80,6 +80,7 @@ func SettingsOf(kind string, c jetstream.StreamConfig) Settings { case KindObjects: s.DuplicatesSeconds = 0 default: + s.KeyTTL = c.AllowMsgTTL if c.MaxMsgsPerSubject > 0 { s.History = c.MaxMsgsPerSubject } @@ -119,7 +120,8 @@ func limitMarker(on bool) time.Duration { func streamConfig(o Object) jetstream.StreamConfig { c := jetstream.StreamConfig{Name: o.Name, Subjects: o.Subjects, Retention: jetstream.LimitsPolicy, MaxBytes: o.Settings.MaxBytes, MaxAge: time.Duration(o.Settings.MaxAgeSeconds) * time.Second, - Discard: jetstream.DiscardOld, Storage: jetstream.FileStorage, Replicas: 1, MaxMsgs: -1, MaxMsgsPerSubject: -1} + Discard: jetstream.DiscardOld, Storage: jetstream.FileStorage, Replicas: 1, MaxMsgs: -1, MaxMsgsPerSubject: -1, + AllowMsgTTL: o.Settings.KeyTTL} if o.Settings.Discard == DiscardNew { c.Discard = jetstream.DiscardNew } diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 41428e100..97e6a4b69 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -174,6 +174,9 @@ type Made struct { Fill int64 `json:"fill,omitempty"` // Orphaned says no manifest asks for it any more: it goes only by drop. Orphaned bool `json:"orphaned,omitempty"` + // Said is the binding its last `created` or `recreated` said (design 47 H2 H-A-685 (2)): a binding the keeper would say + // that differs from it is said again with `created`. Absent where none was kept, which differs from any. + Said *membership.BusBinding `json:"said,omitempty"` } // Status is the keeper's own state, KeyStatus: what its health tool reads. @@ -813,7 +816,11 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { if wasRefused { k.clear(conditionRefused, held.Module, m.Plan.Local) } - if !m.Created || madeLater { + // The binding names ended-days only once the bus holds every object that asks a lifetime with one (design 47 H2 H-A-685 + // (1)); one that differs from the binding last said is said again (H-A-685 (2)), by an entry the keeper creates alone. + m.Plan.Binding = bindingHeld(m.Plan, holds) + changed := create && m.Created && !sameBinding(m.Said, m.Plan.Binding) + if !m.Created || madeLater || changed { // Marked created only once `created` is said whole: the grants part binds on it, so one the bus did not take is // said again on the backoff (Waiting), never marked made and forgotten. if err := k.sayNow(EventCreated, m.Plan, held.Revision, "", asked, holds); err != nil { @@ -821,6 +828,8 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { return } m.Created = true + said := m.Plan.Binding + m.Said = &said } drift := strings.Join(drifts, "; ") switch { @@ -837,6 +846,43 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { } } +// endedDaysOf is the ended-days a ledger entry's own configuration gives, 0 where it gives none. +func endedDaysOf(e catalogue.BusStateEntry) int { + n, err := options{raw: e.Configuration}.int(catalogue.ConfigEndedDays, 0) + if err != nil || n < 1 { + return 0 + } + return int(n) +} + +// bindingHeld is the plan's binding as the keeper says it given what the bus holds: it names ended-days only when the +// ledger's configuration gives it and every object the plan asks a lifetime of, a bucket's key or a stream's message, is held +// with one (design 47 H2 H-A-685 (1)). +func bindingHeld(p Plan, holds map[string]Settings) membership.BusBinding { + b := p.Binding + b.EndedDays = endedDaysOf(p.Entry) + if b.EndedDays == 0 { + return b + } + for _, o := range p.Objects { + if o.Settings.KeyTTL && !holds[o.Name].KeyTTL { + b.EndedDays = 0 + break + } + } + return b +} + +// sameBinding is whether the binding last said is the one the keeper would say; none said differs from any. +func sameBinding(said *membership.BusBinding, b membership.BusBinding) bool { + if said == nil { + return false + } + a, _ := json.Marshal(*said) + c, _ := json.Marshal(b) + return string(a) == string(c) +} + // CheckAll compares every entry the keeper holds with the bus, making what is missing (design 25 § 12.2's check at // start) and making again what waits; it answers what it found, one line per entry. func (k *Keeper) CheckAll() []CheckLine { diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index aaa61f679..3454d66fe 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -332,6 +332,13 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { bigLedger.Types = ledger.Types plainLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, nil) plainLedger.Types = ledger.Types + // A ledger whose own configuration gives ended-days: its state and index buckets with a lifetime per key, its snapshot + // store refusing when full with a lifetime per message (design 47 H2 H-A-634 (3), H-A-687 (1)). + endingLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + endingLedger.Types = ledger.Types + endingLedger.Configuration = map[string]json.RawMessage{"max-age-days": json.RawMessage("90"), "ended-days": json.RawMessage("30")} + badEnding := endingLedger + badEnding.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("3651")} bare := entry("raw", catalogue.StorageStream, "", nil) bare.Configuration = map[string]json.RawMessage{"when-full": json.RawMessage(`"drop-oldest"`), "max-mib": json.RawMessage("8"), "max-age-days": json.RawMessage("3")} forGood := entry("reviews", catalogue.StorageStream, "", nil) @@ -375,20 +382,27 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {16 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {16 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {16 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, {name: "ledger naming max-mib 1024 and past values: its state and index buckets at 1 GiB, no other option reaching them (H-A-636)", entry: bigLedger, objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, {name: "ledger naming no max-mib: its state and index buckets at the state default (H-A-636)", entry: plainLedger, objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {64 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {64 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, + {name: "ledger giving ended-days 30 and max-age-days 90: key-ttl on its state, index and snapshot, its history aged 90 days, the binding naming ended-days (H-A-634 (3), H-A-687)", entry: endingLedger, + objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 7776000, history 0, new, size 262144}; " + + "key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144, key-ttl}; " + + "key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144, key-ttl}; " + + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0, key-ttl}", + binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot, ended-days 30"}, + {name: "a ledger giving ended-days past 3650", entry: badEnding, refused: "not a whole number of days from 1 to 3650"}, {name: "bare stream", entry: bare, objects: "stream mesh-knowledge_raw [mesh.bus.mesh-knowledge.raw.>] {8 MiB, age 259200, history 0, old, size 0}", binding: "stream mesh-knowledge_raw on mesh.bus.mesh-knowledge.raw"}, @@ -428,6 +442,9 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { if s.WorkQueue { w += fmt.Sprintf(", work-queue, duplicates %d", s.DuplicatesSeconds) } + if s.KeyTTL { + w += ", key-ttl" + } objs = append(objs, w+"}") } if got := strings.Join(objs, "; "); got != row.objects { @@ -438,6 +455,9 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { switch { case b.History != "": binding = fmt.Sprintf("history %s on %s, state %s, indexes %v, snapshot %s", b.History, b.Subject, b.State, b.Indexes, b.Snapshot) + if b.EndedDays > 0 { + binding += fmt.Sprintf(", ended-days %d", b.EndedDays) + } case b.Stream != "": binding = fmt.Sprintf("stream %s on %s", b.Stream, b.Subject) case b.Bucket != "": @@ -697,6 +717,61 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("said %v %v: cleared once asked as held", out.events, out.conds) } }}, + // Design 47 H2 H-A-634 (3), H-A-685 (1) (2), H-A-687 (1) (5): a held snapshot store that drops its oldest differs from one + // that refuses; a binding names ended-days only once every object that asks a lifetime holds one, and is said again + // when it differs from the one last said. + {"a ledger's binding names ended-days once its held objects allow lifetimes, and a changed binding is said again (H-A-685)", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + plain := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}) + plain.Types = []catalogue.LedgerType{{Name: "record", Operations: []catalogue.LedgerOperation{{Name: "open"}}}} + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{plain}}) + ending := plain + ending.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("30")} + out.reset() + k.Heard(Accepted{Module: "m", Revision: 2, BusState: []catalogue.BusStateEntry{ending}}) + drift := k.Held()["m"].Made["records"].Drift + if !strings.Contains(drift, "m_records_state: key-ttl asked true, held false") || !strings.Contains(drift, "m_records_snapshot") || + fmt.Sprint(out.events) != "[drifted m records]" || out.bodies[0].Binding.EndedDays != 0 { + t.Fatalf("drift %q, said %v %+v: lifetimes asked of objects that allow none drift, the binding naming no ended-days", drift, out.events, out.bodies) + } + // The bus now allows them (as a recreate in place leaves them): the binding is said again with ended-days. + for _, name := range []string{"KV_m_records_state", "m_records_snapshot"} { + s := bus.held[name] + s.KeyTTL = true + bus.held[name] = s + } + s := bus.held["m_records_snapshot"] + s.Discard = DiscardNew + bus.held["m_records_snapshot"] = s + out.reset() + k.CheckAll() + if fmt.Sprint(out.events) != "[created m records drift-cleared m records]" || out.bodies[0].Binding.EndedDays != 30 { + t.Fatalf("said %v (%q): the drift cleared and created said again naming ended-days 30", out.events, k.Held()["m"].Made["records"].Drift) + } + out.reset() + k.CheckAll() + if len(out.events) != 0 { + t.Errorf("said %v: a binding the same as the one said is said no more", out.events) + } + // A type gaining an operation changes the binding: created again with it, and no recreate. + more := ending + more.Types = []catalogue.LedgerType{{Name: "record", Operations: []catalogue.LedgerOperation{{Name: "open"}, {Name: "end"}}}} + k.Heard(Accepted{Module: "m", Revision: 3, BusState: []catalogue.BusStateEntry{more}}) + if fmt.Sprint(out.events) != "[created m records]" || len(out.bodies[0].Binding.Types[0].Operations) != 2 || len(bus.deleted) != 0 { + t.Errorf("said %v %+v deleted %v: created again with the new operation", out.events, out.bodies, bus.deleted) + } + }}, + {"a held snapshot store that drops its oldest differs from one that refuses when full (H-A-687 (1))", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + s := bus.held["m_records_snapshot"] + s.Discard = DiscardOld + bus.held["m_records_snapshot"] = s + out.reset() + k.CheckAll() + if d := k.Held()["m"].Made["records"].Drift; !strings.Contains(d, "m_records_snapshot: discard asked new, held old") || fmt.Sprint(out.events) != "[drifted m records]" { + t.Errorf("drift %q, said %v: a snapshot store that drops its oldest drifts", d, out.events) + } + }}, {"a plan whose caps pass the account's storage limit is refused, naming the sum and the limit, and the caps made stay (§547)", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { // drafts: 64 MiB state + 16 MiB objects = 80 MiB; log: 1024 MiB. bus.limits = Limits{AccountBytes: 100 * MiB} diff --git a/modules/nats/internal/keeper/plan.go b/modules/nats/internal/keeper/plan.go index c9c8fb2f1..1c794c953 100644 --- a/modules/nats/internal/keeper/plan.go +++ b/modules/nats/internal/keeper/plan.go @@ -37,6 +37,8 @@ const ( ValueMost = 256 << 10 EntryMost = 256 << 10 DefaultCapMiB = 1024 + // EndedDaysMost is the most whole days a ledger's ended-days gives (design 47 H2 H-A-634 (3)). + EndedDaysMost = 3650 EventsDays = 7 ) @@ -83,7 +85,7 @@ type Settings struct { MaxMsgSize int64 `json:"max-msg-size,omitempty"` // DuplicatesSeconds is a work queue's duplicate window. DuplicatesSeconds int64 `json:"duplicates-seconds,omitempty"` - // KeyTTL says a bucket's key may be given a lifetime of its own. + // KeyTTL says a bucket's key, or a stream's message, may be given a lifetime of its own. KeyTTL bool `json:"key-ttl,omitempty"` } @@ -229,6 +231,15 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { return Plan{}, err } history.MaxAgeSeconds = days(age) + // A ledger whose own configuration gives ended-days has its ended instances' keys go by the bus's lifetime per key + // and per message (design 47 H2 H-A-634 (3), ADR 0690 §2): whole days, 1 to 3650. + endedDays, err := conf.int(catalogue.ConfigEndedDays, 0) + if err != nil { + return Plan{}, err + } + if _, given := conf.raw[catalogue.ConfigEndedDays]; given && (endedDays < 1 || endedDays > EndedDaysMost) { + return Plan{}, fmt.Errorf("the configuration %s of %q is %d, not a whole number of days from 1 to %d", catalogue.ConfigEndedDays, e.Name, endedDays, EndedDaysMost) + } // The state bucket and each index bucket take the ledger's own max-mib, as its history and snapshot do, and no // other option of it; with none they keep the state default (design 47 H2's corrections, item 12, H-A-636). stateOpts := options{} @@ -239,12 +250,14 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { if err != nil { return Plan{}, err } + state.KeyTTL = endedDays > 0 subject := buscompose.LedgerHistorySubject(module, e.Name) snapshot := buscompose.LedgerSnapshotSubject(module, e.Name) p.Binding.History, p.Binding.Subject = name, subject p.Binding.State = name + "_state" p.Binding.Snapshot = snapshot p.Binding.Types = e.Types + p.Binding.EndedDays = int(endedDays) p.Objects = []Object{ {Kind: KindStream, Name: name, Subjects: []string{subject + ".>"}, Settings: history}, {Kind: KindBucket, Name: p.Binding.State, Settings: state}, @@ -266,9 +279,11 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { p.Binding.Indexes[ix] = name + "_index-" + ix p.Objects = append(p.Objects, Object{Kind: KindBucket, Name: p.Binding.Indexes[ix], Settings: state}) } - // The snapshot: the latest state per instance, never expiring (ADR 0597 §8), one message per subject. + // The snapshot: the latest state per instance, one message per subject, refusing when full at the ledger's cap (ADR 0595 + // §3, ADR 0597 §8, ADR 0690 §2: a snapshot goes only with its key), with a lifetime per message where the ledger gives + // ended-days (design 47 H2 H-A-634 (3), H-A-687 (1)). p.Objects = append(p.Objects, Object{Kind: KindStream, Name: name + "_snapshot", Subjects: []string{snapshot + ".>"}, - Settings: Settings{MaxBytes: history.MaxBytes, History: 1, Discard: DiscardOld}}) + Settings: Settings{MaxBytes: history.MaxBytes, History: 1, Discard: DiscardNew, KeyTTL: endedDays > 0}}) case e.Storage == catalogue.StorageStream && e.Template == "": // A bare stream: its own configuration, which must give when full, a cap and an age (design 25 § 12.1). var full string diff --git a/modules/nats/internal/keeper/requests.go b/modules/nats/internal/keeper/requests.go index 0f1b08821..692a28ab4 100644 --- a/modules/nats/internal/keeper/requests.go +++ b/modules/nats/internal/keeper/requests.go @@ -281,6 +281,14 @@ func (k *Keeper) act(r *Request) (string, error) { } wasDrift := m.Drift != "" m.Drift = "" + // Every object is as asked again, so its binding names ended-days as the ledger's configuration gives it (H-A-685 (1)). + madeAs := map[string]Settings{} + for _, o := range m.Plan.Objects { + madeAs[o.Name] = o.Settings + } + m.Plan.Binding = bindingHeld(m.Plan, madeAs) + said := m.Plan.Binding + m.Said = &said held.Made[r.Local] = m k.write(held) k.emit(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil) From 436e65f0c4a1b4a9a822aca0c80794a392cd3504 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:10:12 +0100 Subject: [PATCH 02/13] G5 consumer-narrow: the tool nats_consumer_narrow removes some filters of a live consumer, keeping its position It judges the durable's module by name as nats_consumer_remove does, reads the module's trunk fingerprint from the seat mesh-catalog's modules and its entry's consumes, refuses a subject the entry consumes, every filter and a subject not filtered, and records a hand act before the consumer's create-or-update call. Builds: design 47 H2 H-A-600, H-A-615, H-A-621, H-A-657 --- .../cmd/nats-tools/keeper_integration_test.go | 78 +++++++ modules/nats/cmd/nats-tools/main.go | 2 +- modules/nats/cmd/nats-tools/manifest_test.go | 2 +- modules/nats/cmd/nats-tools/removal.go | 195 +++++++++++++++++- modules/nats/cmd/nats-tools/removal_test.go | 4 +- modules/nats/cmd/nats-tools/tools_test.go | 17 +- modules/nats/module.json | 5 +- 7 files changed, 295 insertions(+), 8 deletions(-) diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index fe0b63972..b6ebc4a0a 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -22,6 +22,7 @@ import ( "github.com/nats-io/nats.go/jetstream" "git.novox.be/novox/mesh-contracts/go/seats/meshbroker" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" @@ -657,6 +658,83 @@ func TestTheBusModuleRunsWhole(t *testing.T) { t.Errorf("the binding names ended-days %d, want 30: the bus holds every lifetime", got) } }) + // Design 47 H2 H-A-600, H-A-615, H-A-621: nats_consumer_narrow on the real bus keeps the consumer's delivery position, delivers it + // no message of a removed subject, and refuses every filter, a subject not filtered and one the module's entry consumes. + t.Run("nats_consumer_narrow keeps a consumer's position and delivers none of a removed subject", func(t *testing.T) { + if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "NARROW", Subjects: []string{"narrow.>"}}); err != nil { + t.Fatal(err) + } + cons, err := js.CreateOrUpdateConsumer(ctx, "NARROW", jetstream.ConsumerConfig{Durable: "ace_nw", AckPolicy: jetstream.AckExplicitPolicy, + FilterSubjects: []string{"narrow.a", "narrow.b", "narrow.c"}}) + if err != nil { + t.Fatal(err) + } + for _, subject := range []string{"narrow.a", "narrow.c", "narrow.b"} { + if _, err := js.Publish(ctx, subject, []byte(subject)); err != nil { + t.Fatal(err) + } + } + first, err := cons.Fetch(2, jetstream.FetchMaxWait(2*time.Second)) + if err != nil { + t.Fatal(err) + } + for m := range first.Messages() { + _ = m.Ack() + } + before, _ := cons.Info(ctx) + bus := func(context.Context) (jetstream.JetStream, func(), error) { return js, func() {}, nil } + accepted := func() (map[string]keeper.Planned, error) { return map[string]keeper.Planned{"nw": {Module: "nw"}}, nil } + consumes := func(context.Context, string) ([]string, error) { return []string{"narrow.a"}, nil } + var handActs []meshhandactsclient.Request + record := func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil } + call := func(remove ...any) (any, error) { + return NarrowConsumer(ctx, bus, accepted, consumes, record, map[string]any{"stream": "NARROW", "durable": "ace_nw", "remove": remove, "why": "its module no longer consumes them"}) + } + for what, c := range map[string]struct { + remove []any + want string + }{ + "a subject the entry still consumes": {[]any{"narrow.a"}, "still consumes narrow.a"}, + "a subject it does not filter": {[]any{"narrow.b", "narrow.d"}, "does not filter narrow.d"}, + } { + if _, err := call(c.remove...); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: %v, want a refusal saying %q", what, err, c.want) + } + } + consumes = func(context.Context, string) ([]string, error) { return nil, nil } + if _, err := call("narrow.a", "narrow.b", "narrow.c"); err == nil || !strings.Contains(err.Error(), "takes every filter") { + t.Errorf("removing every filter: %v, want a refusal", err) + } + if len(handActs) != 0 { + t.Errorf("a refused narrowing recorded hand acts %v", handActs) + } + got, err := call("narrow.c") + if err != nil { + t.Fatal(err) + } + after, _ := cons.Info(ctx) + if n := got.(ConsumerNarrowed); fmt.Sprint(n.After) != "[narrow.a narrow.b]" || len(handActs) != 1 || handActs[0].Cause != "consumer-narrow" { + t.Errorf("narrowed %+v with hand acts %v", n, handActs) + } + if after.Delivered.Stream != before.Delivered.Stream || after.Delivered.Consumer != before.Delivered.Consumer || after.Config.AckWait != before.Config.AckWait || fmt.Sprint(after.Config.FilterSubjects) != "[narrow.a narrow.b]" { + t.Errorf("the consumer after is %+v, before %+v: its position and its other settings kept, its filters narrowed", after, before) + } + if _, err := js.Publish(ctx, "narrow.c", []byte("late")); err != nil { + t.Fatal(err) + } + next, err := cons.Fetch(5, jetstream.FetchMaxWait(time.Second)) + if err != nil { + t.Fatal(err) + } + var delivered []string + for m := range next.Messages() { + delivered = append(delivered, m.Subject()) + _ = m.Ack() + } + if fmt.Sprint(delivered) != "[narrow.b]" { + t.Errorf("delivered %v after the narrowing: the one narrow.b still owed, and none of narrow.c", delivered) + } + }) t.Run("nats_first_view_again asks at once and records the hand act", func(t *testing.T) { raw, _ := json.Marshal(keeper.Request{ID: "r3", Verb: keeper.VerbFirstViewAgain, Why: "a verdict thought missed", Caller: "person.jo"}) _, _ = store.Put(keeper.StateRequests, "r3", raw) diff --git a/modules/nats/cmd/nats-tools/main.go b/modules/nats/cmd/nats-tools/main.go index fc35315a5..7e963be2d 100644 --- a/modules/nats/cmd/nats-tools/main.go +++ b/modules/nats/cmd/nats-tools/main.go @@ -191,7 +191,7 @@ func allTools() []stdio.Tool { defer cancel() return monitor(ctx, heldJsz) } - out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState, PlansInState, RecordedBySeat, bundleTwinCurrent)...) + out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState, PlansInState, RecordedBySeat, bundleTwinCurrent, ConsumesBySeat)...) out = append(out, expiryTools(LiveBus(), SaidByTheRuntime, RecordedBySeat)...) out = append(out, brokerTools(HeldInState, StatusInState, jsz, StreamHistory(LiveBus()))...) out = append(out, keeperHealthTool(StatusInState, HeldInState, jsz)) diff --git a/modules/nats/cmd/nats-tools/manifest_test.go b/modules/nats/cmd/nats-tools/manifest_test.go index 4c0790563..1d533b2b9 100644 --- a/modules/nats/cmd/nats-tools/manifest_test.go +++ b/modules/nats/cmd/nats-tools/manifest_test.go @@ -140,7 +140,7 @@ func TestTheBussManifestMountsItsProgramsIntoTheUpstreamImage(t *testing.T) { } // The tools that change the bus (issue 1952 N1-N3): listed, their audit events declared, and the credential // they dial with the module's own secret `broker`. - for _, want := range []string{"nats_consumer_remove", "nats_bucket_remove", "nats_stream_remove", "nats_bucket_expiry"} { + for _, want := range []string{"nats_consumer_remove", "nats_consumer_narrow", "nats_bucket_remove", "nats_stream_remove", "nats_bucket_expiry"} { if !slices.Contains(m.Tools, want) { t.Errorf("tools do not list %s", want) } diff --git a/modules/nats/cmd/nats-tools/removal.go b/modules/nats/cmd/nats-tools/removal.go index df6c982dc..6f3f1bdad 100644 --- a/modules/nats/cmd/nats-tools/removal.go +++ b/modules/nats/cmd/nats-tools/removal.go @@ -17,11 +17,13 @@ import ( "errors" "fmt" "regexp" + "slices" "sort" "strings" "time" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" stdio "git.novox.be/novox/mesh-sdk/go" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" @@ -348,7 +350,7 @@ func RemoveStream(ctx context.Context, bus Bus, said Said, a map[string]any) (an // every module it heard as accepted, its state plans, one key per module of a watched branch's newest revision whether // it asks for kept data or not, design 47 G §538) is refused, on any stream; every other durable is an orphan and goes, `why` its warrant, at once, and its removal is // recorded as a hand act through mesh-hand-acts, as nats_bucket_expiry's change is. -func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration) []stdio.Tool { +func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration, consumes Consumes) []stdio.Tool { removeConsumer := func(a map[string]any) (any, error) { within := DefaultTwinCurrentHours * time.Hour if twinWithin != nil { @@ -401,6 +403,14 @@ func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModu Input: map[string]any{"stream": str("the stream, e.g. SEAT_NODE_BUILD_GO"), "below": num("the first sequence kept: every message below it is purged"), "why": str("why they are purged, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "read the stream, purge nothing"}}, Run: run(PurgeStream)}, + {Name: "nats_consumer_narrow", + Description: "Narrows one live JetStream consumer: removes some of its filter subjects (`remove`) and keeps the others, its other settings and its delivery position, by the consumer's create-or-update call (design 47 H2, H-A-600), e.g. the subjects a module's durable no longer consumes after a change of its manifest, so the bus delivers it none of them. Refuses to remove every filter of the consumer and a subject the consumer does not filter; judges the durable's module by name as nats_consumer_remove does (_ or __..., against the keeper's accepted set) and refuses a subject that module's accepted manifest still consumes, read as the `consumes` of its entry in the seat mesh-catalog (its trunk fingerprint from `modules`, then `entry`), naming the subject (H-A-615, H-A-621, H-A-657). Needs `why`, its warrant, recorded as a hand act through mesh-hand-acts before the consumer is changed (ADR 0640 §3); reads the consumer first and answers its filters before and after.", + Input: map[string]any{"stream": str("the stream the consumer is on, e.g. EVENTS"), "durable": str("the durable consumer's name, e.g. novox_mesh-delivery-indexer"), + "remove": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "the filter subjects to remove, each one the consumer filters"}, + "why": str("why they are removed, for the audit trail (required)")}, + Run: func(a map[string]any) (any, error) { + return NarrowConsumer(context.Background(), bus, accepted, consumes, record, a) + }}, {Name: "nats_bucket_remove", Description: "Removes (purges) keys from a key-value bucket: one node's keys (`node`, the keys starting `.`) or the keys under a `prefix`, e.g. a full acts bucket of the node-engine. Needs `why`, kept in the audit trail; never the whole bucket. Counts the keys first and lists them (`dry_run` only counts; `expect` refuses when the count differs); removes only those keys, and their history. See the buckets and their keys with nats_buckets. The bus refuses any bucket the module's credential is not granted.", Input: map[string]any{"bucket": str("the bucket as nats_buckets lists it, e.g. mesh-host_acts"), "node": str("a node whose keys (`.`) go"), "prefix": str("key prefix instead of node"), @@ -409,6 +419,189 @@ func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModu } } +// Consumes reads the subjects the accepted manifest of a module consumes, as the seat mesh-catalog's entry of the module +// at trunk carries them (design 47 H2, H-A-621, H-A-657). +type Consumes func(ctx context.Context, module string) ([]string, error) + +// ConsumesBySeat asks the seat mesh-catalog's `modules` for the module's trunk fingerprint and its `entry` with it, and +// answers that entry's `consumes` (design 47 H2, H-A-657): an entry that cannot be read refuses, since what the module +// consumes is then not known. +func ConsumesBySeat(_ context.Context, module string) ([]string, error) { + raw, err := stdio.Ask("seat:mesh-catalog.modules", map[string]any{}) + if err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's modules cannot be read: %w", err) + } + var mods meshcatalog.ModulesAnswer + if err := json.Unmarshal(raw, &mods); err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's modules answered what cannot be read: %w", err) + } + for _, m := range mods.Modules { + if m.Module != module { + continue + } + if m.Fp == "" { + return nil, fmt.Errorf("the trunk holds %s with no fingerprint (%s)", module, m.None) + } + raw, err := stdio.Ask("seat:mesh-catalog.entry", meshcatalog.EntryInput{Fingerprint: m.Fp}) + if err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's entry %s of %s cannot be read: %w", m.Fp, module, err) + } + var e meshcatalog.EntryAnswer + if err := json.Unmarshal(raw, &e); err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's entry of %s answered what cannot be read: %w", module, err) + } + return e.Entry.Consumes, nil + } + return nil, fmt.Errorf("the trunk holds no module %s", module) +} + +// ConsumerNarrowed is what nats_consumer_narrow answers. +type ConsumerNarrowed struct { + Stream string `json:"stream"` + Durable string `json:"durable"` + Why string `json:"why"` + Module string `json:"module,omitempty"` + Before []string `json:"filters_before"` + After []string `json:"filters_after"` + Removed []string `json:"removed"` + At time.Time `json:"at"` +} + +// moduleOfDurable is the module of the keeper's accepted set a durable _ or __... belongs to, +// as refuseAcceptedDurable judges it (design 47 H, H-A-127, H-A-128); "" for a durable of none. +func moduleOfDurable(held map[string]keeper.Planned, durable string) string { + _, module, ok := strings.Cut(durable, "_") + if !ok || module == "" { + return "" + } + best := "" + for m := range held { + if (module == m || strings.HasPrefix(module, m+"_")) && len(m) > len(best) { + best = m + } + } + return best +} + +// filtersOf are the filter subjects of a consumer, whether it names one or many. +func filtersOf(c jetstream.ConsumerConfig) []string { + if len(c.FilterSubjects) > 0 { + return slices.Clone(c.FilterSubjects) + } + if c.FilterSubject != "" { + return []string{c.FilterSubject} + } + return nil +} + +// NarrowConsumer removes some filter subjects of one live consumer by its create-or-update call, keeping its other +// settings and its delivery position (design 47 H2, H-A-600). It refuses with nothing changed: no `why`, no hand-act log, +// a subject to remove that the consumer does not filter, every filter, and a subject the entry of the durable's module in +// the seat mesh-catalog still consumes (H-A-615, H-A-621); a module whose consumption cannot be read is refused too. +func NarrowConsumer(ctx context.Context, bus Bus, accepted acceptedModules, consumes Consumes, record Recorded, a map[string]any) (any, error) { + w, err := why(a) + if err != nil { + return nil, err + } + stream, durable := arg(a, "stream"), arg(a, "durable") + if !name.MatchString(stream) || !name.MatchString(durable) { + return nil, errors.New("stream and durable are required, each one name (letters, digits, - and _): nothing was narrowed") + } + var remove []string + if list, ok := a["remove"].([]any); ok { + for _, v := range list { + subject, ok := v.(string) + if !ok || strings.TrimSpace(subject) == "" || strings.ContainsAny(subject, " \t") { + return nil, errors.New("remove is a list of filter subjects, each one text without spaces: nothing was narrowed") + } + remove = append(remove, subject) + } + } + if len(remove) == 0 { + return nil, errors.New("remove is required, the filter subjects to remove: nothing was narrowed") + } + module := "" + if accepted != nil { + held, err := accepted() + if err != nil { + return nil, fmt.Errorf("whether %s is the durable of a module of an accepted manifest cannot be read (%v), so nothing was narrowed", durable, err) + } + module = moduleOfDurable(held, durable) + } + if module != "" { + if consumes == nil { + return nil, fmt.Errorf("what %s consumes cannot be read here, so nothing was narrowed", module) + } + still, err := consumes(ctx, module) + if err != nil { + return nil, fmt.Errorf("what %s consumes cannot be read (%v), so nothing was narrowed", module, err) + } + for _, subject := range remove { + if slices.Contains(still, subject) { + return nil, fmt.Errorf("%s still consumes %s, its accepted manifest says so: it is not removed from %s; nothing was narrowed", module, subject, durable) + } + } + } + js, closeBus, err := bus(ctx) + if err != nil { + return nil, err + } + defer closeBus() + sctx, cancel := step(ctx) + info, err := readConsumer(sctx, js, stream, durable) + cancel() + if err != nil { + if errors.Is(err, jetstream.ErrConsumerNotFound) || errors.Is(err, jetstream.ErrStreamNotFound) { + return nil, fmt.Errorf("%s has no consumer %s (%v): nothing was narrowed", stream, durable, err) + } + return nil, unanswered(err, fmt.Sprintf("the consumer %s of %s could not be read, so it was not narrowed", durable, stream)) + } + before := filtersOf(info.Config) + for _, subject := range remove { + if !slices.Contains(before, subject) { + return nil, fmt.Errorf("%s does not filter %s (it filters %v): nothing was narrowed", durable, subject, before) + } + } + var kept []string + for _, f := range before { + if !slices.Contains(remove, f) { + kept = append(kept, f) + } + } + if len(kept) == 0 { + return nil, fmt.Errorf("removing %v takes every filter of %s: a consumer is narrowed, never left with none; nothing was narrowed", remove, durable) + } + what := fmt.Sprintf("narrowed the consumer %s of the stream %s: removed the filter subjects %s, kept %s", durable, stream, strings.Join(remove, ", "), strings.Join(kept, ", ")) + if record == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was narrowed") + } + if err := record(meshhandactsclient.Request{What: what, Why: w, Cause: "consumer-narrow"}); err != nil { + return nil, fmt.Errorf("the hand act could not be recorded, so nothing was narrowed: %w", err) + } + cfg := info.Config + cfg.FilterSubject, cfg.FilterSubjects = "", kept + sctx, cancel = step(ctx) + _, err = js.CreateOrUpdateConsumer(sctx, stream, cfg) + cancel() + if err != nil { + return nil, unanswered(err, fmt.Sprintf("consumer %s of %s was not narrowed (its hand act was recorded)", durable, stream)) + } + sctx, cancel = step(ctx) + after, err := readConsumer(sctx, js, stream, durable) + cancel() + if err != nil { + return nil, unanswered(err, fmt.Sprintf("the narrowing of consumer %s of %s was accepted but could not be confirmed", durable, stream)) + } + got := filtersOf(after.Config) + slices.Sort(got) + want := slices.Clone(kept) + slices.Sort(want) + if !slices.Equal(got, want) { + return nil, fmt.Errorf("consumer %s of %s filters %v after the narrowing was accepted, not %v", durable, stream, got, kept) + } + return ConsumerNarrowed{Stream: stream, Durable: durable, Why: w, Module: module, Before: before, After: kept, Removed: remove, At: time.Now().UTC()}, nil +} + // refuseAcceptedDurable refuses a durable named _, or beginning __, for a module of the // keeper's accepted set, on any node (design 47 H, H-A-127, H-A-128): every module it heard as accepted, read from its // state plans (design 47 G §538), never from its state asked, which holds only a module that asks for kept data (a diff --git a/modules/nats/cmd/nats-tools/removal_test.go b/modules/nats/cmd/nats-tools/removal_test.go index 257431722..e6301ac9a 100644 --- a/modules/nats/cmd/nats-tools/removal_test.go +++ b/modules/nats/cmd/nats-tools/removal_test.go @@ -197,7 +197,7 @@ accounts { MESH { jetstream: enabled, users: [ // Through the tool, `why` its warrant: each removal is recorded as a hand act (design 47 H, H-A-127). var handActs []meshhandactsclient.Request var removeConsumer func(map[string]any) (any, error) - for _, tl := range removalTools(bus, say, nil, nil, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + for _, tl := range removalTools(bus, say, nil, nil, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil, nil) { if tl.Name == "nats_consumer_remove" { removeConsumer = tl.Run } @@ -279,7 +279,7 @@ accounts { MESH { jetstream: enabled, users: [ } } handActs = nil - for _, tl := range removalTools(adminBus, say, nil, accepted, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + for _, tl := range removalTools(adminBus, say, nil, accepted, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil, nil) { if tl.Name == "nats_consumer_remove" { removeConsumer = tl.Run } diff --git a/modules/nats/cmd/nats-tools/tools_test.go b/modules/nats/cmd/nats-tools/tools_test.go index 1bc0b8eb4..7a27549a7 100644 --- a/modules/nats/cmd/nats-tools/tools_test.go +++ b/modules/nats/cmd/nats-tools/tools_test.go @@ -277,9 +277,22 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { // H-A-472 (1): a twin that cannot be read keeps the durable refused, saying so. {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_m", "why": "x"}, "its twin novox_m_tools on EVENTS cannot be read"}, {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_quiet_tools", "why": "x"}, "its twin novox_quiet on EVENTS cannot be read"}, + // Design 47 H2 H-A-600, H-A-615, H-A-621: a narrowing needs its warrant, a stream, a durable and subjects to remove, and + // refuses a subject the durable's module still consumes (the entry's `consumes`) before the bus is reached. + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "remove": []any{"a.b"}}, "why is required"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "why": "x"}, "remove is required"}, + {"nats_consumer_narrow", map[string]any{"stream": "A.B", "durable": "d", "remove": []any{"a"}, "why": "x"}, "stream and durable are required"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "remove": []any{"mesh.m.still.>"}, "why": "x"}, "m still consumes mesh.m.still.>"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m_tools", "remove": []any{"mesh.m.still.>"}, "why": "x"}, "m still consumes mesh.m.still.>"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_quiet", "remove": []any{"a"}, "why": "x"}, "what quiet consumes cannot be read"}, } { var run func(map[string]any) (any, error) - for _, tl := range removalTools(bus, said, newForm, accepted, nil, nil) { + for _, tl := range removalTools(bus, said, newForm, accepted, nil, nil, func(_ context.Context, module string) ([]string, error) { + if module == "m" { + return []string{"mesh.m.still.>"}, nil + } + return nil, errors.New("the entry is not read") + }) { if tl.Name == c.tool { run = tl.Run } @@ -339,7 +352,7 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { unreachable := func(context.Context) (jetstream.JetStream, func(), error) { return nil, nil, errors.New("the bus is not reached here") } - for _, tl := range removalTools(unreachable, said, newForm, accepted, nil, nil) { + for _, tl := range removalTools(unreachable, said, newForm, accepted, nil, nil, nil) { if tl.Name != "nats_consumer_remove" { continue } diff --git a/modules/nats/module.json b/modules/nats/module.json index 57b75d50d..8fada932a 100644 --- a/modules/nats/module.json +++ b/modules/nats/module.json @@ -67,7 +67,9 @@ "seat:mesh-catalog.revision", "seat:mesh-catalog.registrations", "seat:mesh-delivery.source", - "seat:mesh-catalog.seat-definitions" + "seat:mesh-catalog.seat-definitions", + "seat:mesh-catalog.modules", + "seat:mesh-catalog.entry" ], "consumes": [ "mesh-catalog.catalog-revision", @@ -178,6 +180,7 @@ "nats_user_can", "nats_snapshot_verify", "nats_consumer_remove", + "nats_consumer_narrow", "nats_bucket_remove", "nats_stream_remove", "nats_stream_purge", From 2bf3426efb14b014e911e592d76489a5b03fefac Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 15:47:02 +0100 Subject: [PATCH 03/13] mesh-delivery-gate: apply a running heard after its record ended to that record, so its delivery time is kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The gate hears the assigner's pipeline-wanted and the node-engine seat's running on consumers no ordering joins, so a record can end before the last running of its movers is applied, and that delivery's time was lost: an ended record took no running (H-A-585, issue 721 note 11). - StepConsumer.apply applies a running that names a mover of an ended record to it (the mover marked running on that machine), and Records.RanAfterEnd writes ended and, for a record that ended with every mover running, delivery-time again from it when it is later than the end, keeping the class the movers' entries kept when they opened. record-ended is not said again; one journal line names the record, the module, the machine and both times. A running offered again after that write was refused writes it then. - TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied gains the row "pipeline-wanted before the running", its end's write refused once; TestAGateWhole's record of 126 movers, ended with none running, takes a running after its end with its delivery time and the journal line. Both fail without the change. Fixes: issue 721 note 11 Builds: design 47 H2 H-A-585, §810, H-A-394 (3); G §144 --- .../cmd/mesh-delivery-gate/bus_test.go | 35 ++++- .../cmd/mesh-delivery-gate/consumer.go | 20 ++- .../mesh-delivery-gate/mergecall_bus_test.go | 15 +++ .../cmd/mesh-delivery-gate/recordevents.go | 47 +++++++ .../mesh-delivery-gate/recordpipeline_test.go | 120 +++++++++++++----- 5 files changed, 198 insertions(+), 39 deletions(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go index 65e5fce31..ec23fe56c 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go @@ -134,6 +134,24 @@ type runtime struct { operatorCancels []string // owedSaid are the subjects of the seat events owed the gate said, in order (W11.17). owedSaid []string + // logs is what the bundle said in its journal. + logs *testLog +} + +// journalHas is whether the bundle said a line in its journal holding every one of words. +func (r *runtime) journalHas(words ...string) bool { + r.logs.mu.Lock() + defer r.logs.mu.Unlock() + for _, l := range r.logs.said { + all := true + for _, w := range words { + all = all && strings.Contains(l, w) + } + if all { + return true + } + } + return false } type askedOfMesh struct { @@ -154,19 +172,28 @@ func (b *testBus) start(t *testing.T) *runtime { if err != nil { t.Fatal(err) } - cmd.Stderr = testLog{t} + logs := &testLog{t: t} + cmd.Stderr = logs if err := cmd.Start(); err != nil { t.Fatal(err) } - r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64)} + r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64), logs: logs} go r.read(out) t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() }) return r } -type testLog struct{ t *testing.T } +// testLog is the bundle's journal: said in the test's log, and kept for journalHas. +type testLog struct { + t *testing.T + mu sync.Mutex + said []string +} -func (w testLog) Write(p []byte) (int, error) { +func (w *testLog) Write(p []byte) (int, error) { + w.mu.Lock() + w.said = append(w.said, string(p)) + w.mu.Unlock() defer func() { _ = recover() }() // the bundle may speak after the test ended w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n")) // Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go index f61195ae0..799f85f7b 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go @@ -247,9 +247,11 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string { return "" } -// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one +// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, one // that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown -// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)). +// away), or one that ended before a running of its movers was heard (H-A-585: the running is applied to it, and its end +// written again from it, Records.RanAfterEnd). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, +// H-A-89 (4)). func (c *StepConsumer) apply(o StepOutcome, event string) error { records, err := c.Records.Kept() if err != nil { @@ -258,12 +260,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error { for _, r := range records { _, fromAway := r.Away[o.Node] fromAway = fromAway && o.Node != "" - if (r.Ended != nil && !fromAway) || !holds(r, o) { + ranAfter := r.Ended != nil && o.Step == StepRunning && o.Outcome == OutcomeRunning + if (r.Ended != nil && !fromAway && !ranAfter) || !holds(r, o) { continue } ro := RecordOutcome{Module: o.Module, Fingerprint: o.Fingerprint, Node: o.Node, Step: o.Step, Outcome: o.Outcome, Why: o.Why, At: o.At, Event: event} - if _, err := c.Records.Outcome(r, ro); err != nil { + applied, err := c.Records.Outcome(r, ro) + if err != nil { return err } if fromAway { @@ -271,6 +275,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error { return err } } + if ranAfter { + // The running as the record keeps it, applied now or by an event offered again after its end could not be + // written. + kept := r.Outcomes[OutcomeKey(o.Module, o.Fingerprint, o.Node, o.Step)] + if err := c.Records.RanAfterEnd(r, kept, applied); err != nil { + return err + } + } } return nil } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go index c21674dd2..6d05ed956 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go @@ -179,6 +179,21 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) { b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".2", map[string]any{"v": 1, "branch": branch, "source": 2, "pipeline": recordMilestone(branch, 2), "outcome": "running"}) rt.until("record-too-large cleared at the record's end", eventWithin, func() bool { return !findingHeld(ctx, b, RecordTooLarge, "") }) + // H-A-585: the record ended on pipeline-wanted before any of its movers' running was applied, with no delivery time; a + // running of one of them heard after takes it, its ended and delivery-time written again, and says so in the journal. + late := taken[1].(map[string]any) + b.publish(t, "mesh.seat.node-engine.event.running.test."+late["module"].(string), map[string]any{"v": 1, "module": late["module"], + "node": "test", "fingerprint": late["fingerprint"], "at": time.Now().UTC().Format(time.RFC3339)}) + var ended2 Record + rt.until("the ended record's delivery time written from a running heard after its end", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + ended2 = Record{} + return json.Unmarshal(b.ledger.states[instance2], &ended2) == nil && ended2.Ended != nil && ended2.DeliveryTime != "" + }) + rt.until("the journal line naming the record, the mover on test and both times", eventWithin, func() bool { + return rt.journalHas(instance2, late["module"].(string)+" on test", "after it ended") + }) // The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing. seeded := strings.Repeat("5", 40) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index 5d5bc3640..f97e61290 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -172,6 +172,53 @@ func (rs *Records) end(r *Record, why, by string) error { return nil } +// RanAfterEnd writes a record's end again from a running of one of its movers kept after the record ended (H-A-585): when +// that running is later than the record's ended, ended takes its time and, for a record that ended with every mover running, +// delivery-time runs to it, with the class its movers' entries kept when they opened (H2 §810, H-A-394 (3)). record-ended is +// not said a second time; the journal says the record, the module, the machine and both times. Applied says the running was +// applied now; one applied before and not later than the end (its end written from it already) changes and says nothing. +func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error { + if r.Ended == nil { + return nil + } + was := r.Ended.At + if !applied && !o.At.After(was) { + return nil + } + if o.At.After(was) { + e := *r.Ended + e.At = o.At + body := map[string]any{"ended": e} + next := *r + next.Ended = &e + var took time.Duration + class := r.Class + if e.Why == WhyAllRun { + var kept string + if took, kept = timesAtEnd(r); took > 0 { + class = firstOf(class, kept) + body["delivery-time"], body["class"] = took.String(), class + next.DeliveryTime, next.Class = took.String(), class + } + } + seq, err := rs.write(r, r.Instance, OpEnd, body, next.head()) + if err != nil { + return err + } + r.Ended, r.Sequence = &e, seq + if took > 0 { + r.DeliveryTime, r.Class = took.String(), class + } + rs.keep(r) + } + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q", + r.Instance, o.Module, o.Node, o.At.UTC().Format(time.RFC3339Nano), was.UTC().Format(time.RFC3339Nano), + r.Ended.At.UTC().Format(time.RFC3339Nano), r.DeliveryTime) + } + return nil +} + func (rs *Records) sayEnded(r *Record) error { if r.Ended == nil { return nil diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go index 89d4e6b71..959af1390 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go @@ -122,39 +122,50 @@ func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, erro return seq, err } -// 721/AC1 (issue 721 note 11; design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so -// one can be heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits -// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it -// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer -// taken before the next event writes the record. +// heardBed is what the gate said while a row of TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied ran. +type heardBed struct { + ended int // the record-ended said + journal []string // the lines the records said in the journal +} + +// Issue 721 note 11 (design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so one can be +// heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits until the running +// is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it ended the record +// with neither, the delivery time lost), and the call show answers the record with the running, its answer taken before the +// next event writes the record. A pipeline-wanted heard before the running (H-A-585) ends the record, and the running heard +// after is applied to it: ended and delivery-time are written again from it, the class kept, record-ended said once and the +// journal told, also when that end could first not be written and the running is offered again. func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { running := func(node string) stdio.Envelope { return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage( `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"` + node + `","fingerprint":"f","healthy":true}`)} } + pipelineWanted := func(h *Holder) (any, error) { + return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage( + `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)}) + } for _, tc := range []struct { - name string - heard func(h *Holder) (any, error) - check func(t *testing.T, h *Holder, answer any) + name string + // before hears it before the running, a minute earlier; else it is heard as the running's write lands. + before bool + heard func(h *Holder) (any, error) + check func(t *testing.T, h *Holder, answer any, said *heardBed) }{ - {"pipeline-wanted", func(h *Holder) (any, error) { - return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage( - `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)}) - }, func(t *testing.T, h *Holder, _ any) { + {"pipeline-wanted", false, pipelineWanted, func(t *testing.T, h *Holder, _ any, said *heardBed) { r, err := h.Records.ByKey("main", 1) - if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore { - t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q (%v); want 5m0s and core", r.Ended, - r.DeliveryTime, r.Class, err) + if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore || said.ended != 1 { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, said %d times (%v); want 5m0s and core, once", + r.Ended, r.DeliveryTime, r.Class, said.ended, err) } }}, - {"the call show", func(h *Holder) (any, error) { + {"the call show", false, func(h *Holder) (any, error) { for _, tool := range tools(h, &listening{}) { if tool.Name == Seat+".show" { return tool.Run(map[string]any{"id": "main.1"}) } } return nil, fmt.Errorf("the gate serves no %s.show", Seat) - }, func(t *testing.T, h *Holder, answer any) { + }, func(t *testing.T, h *Holder, answer any, _ *heardBed) { if err := take(h, running("g14")); err != nil { t.Fatal(err) } @@ -173,12 +184,46 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { t.Fatal(err) } }}, + {"pipeline-wanted before the running (H-A-585)", true, pipelineWanted, func(t *testing.T, h *Holder, _ any, said *heardBed) { + r, err := h.Records.ByKey("main", 1) + ran := time.Date(2026, 11, 20, 3, 6, 0, 0, time.UTC) + if err != nil || r == nil || r.Ended == nil || !r.Ended.At.Equal(ran) || r.Ended.Why != WhyAllRun || r.DeliveryTime != "6m0s" || + r.Class != catalogue.ClassCore || said.ended != 1 { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, said %d times (%v); want ended at the "+ + "running, 6m0s and core, said once", r.Ended, r.DeliveryTime, r.Class, said.ended, err) + } + if o := r.Outcomes[OutcomeKey("app", "f", "ace", StepRunning)]; o.Outcome != OutcomeRunning { + t.Fatalf("the running after the end is %+v", o) + } + var lines []string + for _, l := range said.journal { + if strings.Contains(l, "after it ended") { + lines = append(lines, l) + } + } + if len(lines) != 1 || !strings.Contains(lines[0], r.Instance) || !strings.Contains(lines[0], "app on ace") || + !strings.Contains(lines[0], "03:05:00Z") || !strings.Contains(lines[0], "03:06:00Z") { + t.Fatalf("the journal says %q: want one line naming the record, the module, the machine and both times", said.journal) + } + // The ledger holds what memory does. + back, err := h.Records.Read(r.Instance) + if err != nil || back.Ended == nil || !back.Ended.At.Equal(ran) || back.DeliveryTime != "6m0s" || back.Class != catalogue.ClassCore { + t.Fatalf("the ledger keeps %+v, %q, %q (%v)", back.Ended, back.DeliveryTime, back.Class, err) + } + }}, } { t.Run(tc.name, func(t *testing.T) { now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + said := &heardBed{} h := &Holder{Now: func() time.Time { return now }} ledger := &hookedLedger{ledgerFake: newLedgerFake(t)} - h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }} + h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }, + Say: func(subject string, _ any, _ string) error { + if strings.Contains(subject, "record-ended") { + said.ended++ + } + return nil + }, Logf: func(format string, a ...any) { said.journal = append(said.journal, fmt.Sprintf(format, a...)) }} h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { t.Fatal(err) @@ -196,20 +241,33 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { err error } heard := make(chan heardOut, 1) - ledger.after = func(_, operation string, body any) { - if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning { - return + if tc.before { + answer, err := tc.heard(h) + heard <- heardOut{answer, err} + now = now.Add(time.Minute) + // The end written again from the running is refused at first: the running is offered again (the take below), + // and the end is written then. + ledger.failOn = OpEnd + if err := take(h, running("ace")); err == nil { + t.Fatal("a running whose end could not be written again is taken") } - ledger.after = nil - // Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's - // goroutines allow, else on a goroutine of its own, as the runtime hands it. - hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} } - if h.applying.TryLock() { - h.applying.Unlock() - hear() - return + ledger.failOn = "" + } else { + ledger.after = func(_, operation string, body any) { + if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning { + return + } + ledger.after = nil + // Heard as the running's write lands: taken there and then when nothing holds the records, as the + // runtime's goroutines allow, else on a goroutine of its own, as the runtime hands it. + hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} } + if h.applying.TryLock() { + h.applying.Unlock() + hear() + return + } + go hear() } - go hear() } if err := take(h, running("ace")); err != nil { t.Fatal(err) @@ -218,7 +276,7 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { if out.err != nil { t.Fatal(out.err) } - tc.check(t, h, out.answer) + tc.check(t, h, out.answer, said) }) } } From c6f478aee9373e8dae88957c77ffa2984bf75013 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:15:18 +0100 Subject: [PATCH 04/13] G4 late-running: a late running moves a record's end only from a machine present at it, a record says its end count, a mover-added is counted and a higher pipeline end reopens the record On fa345c83's RanAfterEnd: a running from a machine away at the end, or a repeated one, moves nothing; a first running from a present machine moves ended and delivery-time and says record-ended again with ends one higher (an id of its own). The record head gains ends and pipeline-ends (the end operation's fields); a pipeline-ended of a count above 1 and higher than pipeline-ends reopens the record; the gate consumes mover-added and counts the mover in the record its pipeline key names. Builds: design 47 H2 H-A-585, H-A-597, H-A-609 (2), H-A-617, H-A-645, H-A-648, H-A-728 --- .../cmd/mesh-delivery-gate/consumer.go | 1 + .../cmd/mesh-delivery-gate/manifest_test.go | 2 +- .../cmd/mesh-delivery-gate/record.go | 5 + .../cmd/mesh-delivery-gate/recordevents.go | 110 +++++++++++------ .../cmd/mesh-delivery-gate/recordpipeline.go | 68 +++++++++- .../mesh-delivery-gate/recordpipeline_test.go | 116 +++++++++++++++++- modules/mesh-delivery-gate/module.json | 11 +- 7 files changed, 267 insertions(+), 46 deletions(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go index 799f85f7b..ba22da41c 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go @@ -63,6 +63,7 @@ var stepFamilies = []stepFamily{ // runner's pipeline-started, pipeline-ended, wait-held and wait-ended on ., the assigner's wanted on // . and pipeline-wanted on ., and the node-engine seat's running on .. seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted), + seatFamily(runner.EventMoverAdded, 2, false, decodeMoverAdded), seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded), seatFamily(runner.EventWaitHeld, 2, false, decodeWait), seatFamily(runner.EventWaitEnded, 2, false, decodeWait), diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go index 304fee87e..ea99aa79e 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go @@ -117,7 +117,7 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { } // The names move (milestone 47/G): the families heard from another module are its manifest's consumes, and no Go // source of the gate names those modules. - if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 8 { + if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 9 { t.Fatalf("owed.ended is %q and the step families %+v, not the manifest's consumes %v", owedEndedEvent, stepFamilies, m.Consumes) } for _, f := range stepFamilies { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index b7f4804ee..d572411af 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -99,6 +99,11 @@ type Record struct { // entry of its own, joined when read, never on the head entry (design 47 H2 §809, H-A-455 (1)). Acts map[string]RecordAct `json:"acts,omitempty"` Ended *RecordEnded `json:"ended,omitempty"` + // Ends is the record's end count, one higher at each end and said by record-ended; PipelineEnds the highest + // pipeline-ended end count the record heard: a pipeline-ended of a higher count reopens it. Both absent read as 0, and a + // reopening empties neither (design 47 H2 H-A-728, H-A-597, H-A-609 (2), H-A-617). + Ends int `json:"ends,omitempty"` + PipelineEnds int `json:"pipeline-ends,omitempty"` // Recovery marks the merge its author named a recovery by the seat's verb recovery (design 47 G §81, A-23). Recovery *RecordRecovery `json:"recovery,omitempty"` // MoverCount is the count of its movers, each with an entry of its own (design 47 H2 §809); Entries and Outcomes above diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index f97e61290..4fd8a6f02 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -8,6 +8,7 @@ package main import ( "fmt" "sort" + "strconv" "strings" "time" @@ -150,8 +151,10 @@ func (rs *Records) end(r *Record, why, by string) error { body["delivery-time"], body["class"] = took.String(), class } } + // The end count one higher, and the highest pipeline end count the record heard (H-A-728). + body["ends"], body["pipeline-ends"] = r.Ends+1, r.PipelineEnds next := *r - next.Ended = &e + next.Ended, next.Ends = &e, r.Ends+1 if took > 0 { next.DeliveryTime, next.Class = took.String(), class } @@ -159,7 +162,7 @@ func (rs *Records) end(r *Record, why, by string) error { if err != nil { return err } - r.Ended, r.Sequence = &e, seq + r.Ended, r.Sequence, r.Ends = &e, seq, r.Ends+1 if took > 0 { r.DeliveryTime, r.Class = took.String(), class } @@ -172,49 +175,78 @@ func (rs *Records) end(r *Record, why, by string) error { return nil } -// RanAfterEnd writes a record's end again from a running of one of its movers kept after the record ended (H-A-585): when -// that running is later than the record's ended, ended takes its time and, for a record that ended with every mover running, -// delivery-time runs to it, with the class its movers' entries kept when they opened (H2 §810, H-A-394 (3)). record-ended is -// not said a second time; the journal says the record, the module, the machine and both times. Applied says the running was -// applied now; one applied before and not later than the end (its end written from it already) changes and says nothing. +// RanAfterEnd writes a record's end again from a running of one of its movers kept after the record ended (H-A-585, H-A-597, +// H-A-617): when that running is the first of its mover's version from a machine present at the end and later than the +// record's ended, ended takes its time and, for a record that ended with every mover running, delivery-time runs to it, with +// the class its movers' entries kept when they opened (H2 §810, H-A-394 (3)); the end count goes one higher and +// record-ended is said again with it. A running from a machine that was away at the end (a machine back, ADR 0603 §7), or +// a repeated one, marks the mover's entry (the caller applied it) and changes neither time nor count. The journal says the +// record, the module, the machine and both times when the time moved. Applied says the running was applied now; one applied +// before and not later than the end (its end written from it already) changes and says nothing. func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error { if r.Ended == nil { return nil } + for _, a := range r.Ended.Away { + if a.Node == o.Node { + return nil + } + } was := r.Ended.At - if !applied && !o.At.After(was) { + if !o.At.After(was) { return nil } - if o.At.After(was) { - e := *r.Ended - e.At = o.At - body := map[string]any{"ended": e} - next := *r - next.Ended = &e - var took time.Duration - class := r.Class - if e.Why == WhyAllRun { - var kept string - if took, kept = timesAtEnd(r); took > 0 { - class = firstOf(class, kept) - body["delivery-time"], body["class"] = took.String(), class - next.DeliveryTime, next.Class = took.String(), class - } + e := *r.Ended + e.At = o.At + ends := r.Ends + 1 + body := map[string]any{"ended": e, "ends": ends} + next := *r + next.Ended, next.Ends = &e, ends + var took time.Duration + class := r.Class + if e.Why == WhyAllRun { + var kept string + if took, kept = timesAtEnd(r); took > 0 { + class = firstOf(class, kept) + body["delivery-time"], body["class"] = took.String(), class + next.DeliveryTime, next.Class = took.String(), class } - seq, err := rs.write(r, r.Instance, OpEnd, body, next.head()) - if err != nil { - return err - } - r.Ended, r.Sequence = &e, seq - if took > 0 { - r.DeliveryTime, r.Class = took.String(), class - } - rs.keep(r) } + seq, err := rs.write(r, r.Instance, OpEnd, body, next.head()) + if err != nil { + return err + } + r.Ended, r.Sequence, r.Ends = &e, seq, ends + if took > 0 { + r.DeliveryTime, r.Class = took.String(), class + } + rs.keep(r) if rs.Logf != nil { - rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q", + rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q, end %d", r.Instance, o.Module, o.Node, o.At.UTC().Format(time.RFC3339Nano), was.UTC().Format(time.RFC3339Nano), - r.Ended.At.UTC().Format(time.RFC3339Nano), r.DeliveryTime) + r.Ended.At.UTC().Format(time.RFC3339Nano), r.DeliveryTime, ends) + } + return rs.sayEnded(r) +} + +// Reopen reopens an ended record whose pipeline ended again with a higher end count (H-A-609 (2), H-A-728): its `ended` is +// emptied and pipeline-ends takes the count, its own end count staying; the next end says ends one higher. +func (rs *Records) Reopen(r *Record, pipelineEnds int) error { + if r.Ended == nil { + return nil + } + next := *r + next.Ended, next.PipelineEnds = nil, pipelineEnds + seq, err := rs.write(r, r.Instance, OpEnd, map[string]any{"ended": nil, "pipeline-ends": pipelineEnds}, next.head()) + if err != nil { + return err + } + was := r.Ended.At + r.Ended, r.PipelineEnds, r.Sequence = nil, pipelineEnds, seq + rs.keep(r) + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s, ended at %s, is open again: its pipeline ended again, end %d", r.Instance, + was.UTC().Format(time.RFC3339Nano), pipelineEnds) } return nil } @@ -224,10 +256,16 @@ func (rs *Records) sayEnded(r *Record) error { return nil } at := r.Ended.At - e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at} + e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at, + Ends: int64(r.Ends)} for _, a := range r.Ended.Away { since := a.Since e.Away = append(e.Away, meshdelivery.RecordEndedEventAwayItem{Node: a.Node, Since: &since}) } - return rs.say(meshdelivery.SubjectRecordEnded, e, "record-ended."+r.Instance) + // Each end is said under an id of its own, so an end said again is kept once and the next end is said (H-A-597, H-A-617). + id := "record-ended." + r.Instance + if r.Ends > 1 { + id += "." + strconv.Itoa(r.Ends) + } + return rs.say(meshdelivery.SubjectRecordEnded, e, id) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go index aec852ae0..3564fc753 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go @@ -55,6 +55,28 @@ func decodePipelineStarted(body json.RawMessage, _ time.Time) ([]StepOutcome, er return nil, namesSource(p.Branch, p.Source, p.Run) } +// decodeMoverAdded reads a mover-added with the contract's decoder, and refuses one naming none or two of from, caller and +// take-in (design 47 H2 H-A-645). +func decodeMoverAdded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + m, _, err := runner.DecodeMoverAddedEvent(body) + if err != nil { + return nil, err + } + named := 0 + for _, given := range []bool{m.From != "", m.Caller != "", m.TakeIn != 0} { + if given { + named++ + } + } + if named != 1 { + return nil, fmt.Errorf("a mover-added names exactly one of from, caller and take-in, and this names %d", named) + } + if m.Module == "" || m.Pipeline == "" { + return nil, fmt.Errorf("a mover-added names no module or pipeline") + } + return nil, nil +} + func decodePipelineEnded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { var p runner.PipelineEndedEvent if err := strictly(body, &p); err != nil { @@ -134,6 +156,12 @@ func (h *Holder) Follow(event string, body json.RawMessage) error { return nil } return h.pipelineStarted(p) + case runner.EventMoverAdded: + var m runner.MoverAddedEvent + if err := json.Unmarshal(body, &m); err != nil { + return nil + } + return h.moverAdded(m) case runner.EventPipelineEnded: var p runner.PipelineEndedEvent if err := json.Unmarshal(body, &p); err != nil || p.Run != "" { @@ -193,11 +221,45 @@ func (h *Holder) pipelineStarted(p runner.PipelineStartedEvent) error { return nil } -func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error { - r, err := h.openRecord(p.Branch, p.Source) - if err != nil || r == nil { +// moverAdded counts a mover added to a pipeline in the record that pipeline's key names, as wantWritten finds it (G §144, +// design 47 H2 H-A-609 (2), H-A-645): a mover carried into a pipeline whose record ended is counted there too, and the +// pipeline's next end with a higher end count reopens the record. +func (h *Holder) moverAdded(m runner.MoverAddedEvent) error { + milestone, _, _ := strings.Cut(m.Pipeline, ".published.") + r, err := h.Records.ByMilestone(milestone) + if err != nil { + return fmt.Errorf("the record of the pipeline %s cannot be read: %w", m.Pipeline, err) + } + if r == nil { + return nil + } + if err := h.Records.AddEntry(r, RecordEntry{Module: m.Module, Fingerprint: m.Fingerprint}); err != nil { return err } + return h.Records.SetMover(r, m.Module, m.Fingerprint, m.Pipeline, "") +} + +func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error { + r, err := h.Records.ByKey(p.Branch, p.Source) + if err != nil { + return fmt.Errorf("the record of %s at %d cannot be read: %w", p.Branch, p.Source, err) + } + if r == nil { + return nil + } + count := int(p.EndCount) + if r.Ended != nil { + // A pipeline that ended again, with an end count higher than the record heard, reopens its record; its first end + // reopens nothing (H-A-609 (2), H-A-728). + if count < 2 || count <= r.PipelineEnds { + return nil + } + if err := h.Records.Reopen(r, count); err != nil { + return err + } + } else if count > r.PipelineEnds { + r.PipelineEnds = count + } at := h.Now().UTC() if p.Ended != nil { at = p.Ended.UTC() diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go index 959af1390..aee6ed2a7 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -188,9 +189,9 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { r, err := h.Records.ByKey("main", 1) ran := time.Date(2026, 11, 20, 3, 6, 0, 0, time.UTC) if err != nil || r == nil || r.Ended == nil || !r.Ended.At.Equal(ran) || r.Ended.Why != WhyAllRun || r.DeliveryTime != "6m0s" || - r.Class != catalogue.ClassCore || said.ended != 1 { - t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, said %d times (%v); want ended at the "+ - "running, 6m0s and core, said once", r.Ended, r.DeliveryTime, r.Class, said.ended, err) + r.Class != catalogue.ClassCore || said.ended != 2 || r.Ends != 2 { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, end %d, said %d times (%v); want ended at the "+ + "running, 6m0s and core, said at its end and again at the late running (H-A-597)", r.Ended, r.DeliveryTime, r.Class, r.Ends, said.ended, err) } if o := r.Outcomes[OutcomeKey("app", "f", "ace", StepRunning)]; o.Outcome != OutcomeRunning { t.Fatalf("the running after the end is %+v", o) @@ -207,8 +208,8 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { } // The ledger holds what memory does. back, err := h.Records.Read(r.Instance) - if err != nil || back.Ended == nil || !back.Ended.At.Equal(ran) || back.DeliveryTime != "6m0s" || back.Class != catalogue.ClassCore { - t.Fatalf("the ledger keeps %+v, %q, %q (%v)", back.Ended, back.DeliveryTime, back.Class, err) + if err != nil || back.Ended == nil || !back.Ended.At.Equal(ran) || back.DeliveryTime != "6m0s" || back.Class != catalogue.ClassCore || back.Ends != 2 { + t.Fatalf("the ledger keeps %+v, %q, %q, end %d (%v)", back.Ended, back.DeliveryTime, back.Class, back.Ends, err) } }}, } { @@ -281,6 +282,111 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { } } +// Design 47 H2 H-A-597, H-A-609 (2), H-A-617, H-A-645, H-A-728: a first end says ends 1; a late running from a machine present +// at the end moves the end and says record-ended again with ends 2, one from a machine that was away and a repeated one +// move nothing; a pipeline-ended of a first end, or of a count not higher than the record heard, reopens nothing and a +// higher one reopens it, its next end saying ends one higher; a mover-added counts its mover in the record its pipeline +// names, and one naming none or two of from, caller and take-in is refused. +func TestARecordsEndCountIsSaidAtEachEndAndAHigherPipelineEndReopensIt(t *testing.T) { + now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + var said []meshdelivery.RecordEndedEvent + var ids []string + h := &Holder{Now: func() time.Time { return now }} + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now, Say: func(subject string, body any, id string) error { + if e, ok := body.(meshdelivery.RecordEndedEvent); ok { + said, ids = append(said, e), append(ids, id) + } + return nil + }} + if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { + t.Fatal(err) + } + if _, err := h.Records.Kept(); err != nil { + t.Fatal(err) + } + r, _ := h.Records.ByKey("main", 1) + c := &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`) + for _, node := range []string{"ace", "g14"} { + hear(t, c, "mesh-wants.wanted.x.app", "", `{"v":1,"node":"`+node+`","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12}`) + } + if err := h.Records.NodeAway(r, "g14", now); err != nil { + t.Fatal(err) + } + running := func(node string) { + hear(t, c, "node-engine.running."+node+".app", node, `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"`+node+`","fingerprint":"f","healthy":true}`) + } + pipelineWanted := func() { + hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`) + } + pipelineEnded := func(count int) { + hear(t, c, "mesh-pipeline-runner.pipeline-ended.main.1", "", fmt.Sprintf( + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"passed","end-count":%d,"movers":[]}`, count)) + } + // The first end, with ace not heard running yet and g14 away: ends 1. + now = now.Add(time.Minute) + pipelineWanted() + if r.Ended == nil || r.Ends != 1 || len(said) != 1 || said[0].Ends != 1 || ids[0] != "record-ended."+r.Instance { + t.Fatalf("the record ended %+v at end %d, said %+v under %v: want the first end, ends 1", r.Ended, r.Ends, said, ids) + } + endedAt := r.Ended.At + // A running from the machine that was away at the end moves nothing; a late one from ace, present at the end, moves it. + now = now.Add(time.Minute) + running("g14") + if !r.Ended.At.Equal(endedAt) || r.Ends != 1 || len(said) != 1 { + t.Fatalf("a machine back moved the end to %v, end %d, said %d times", r.Ended.At, r.Ends, len(said)) + } + now = now.Add(time.Minute) + running("ace") + if !r.Ended.At.Equal(now) || r.Ends != 2 || len(said) != 2 || said[1].Ends != 2 || ids[1] != "record-ended."+r.Instance+".2" { + t.Fatalf("a late running left the end at %v, end %d, said %+v under %v: want it moved, ends 2, said again under an id of its own", r.Ended.At, r.Ends, said, ids) + } + now = now.Add(time.Minute) + running("ace") + if r.Ends != 2 || len(said) != 2 { + t.Fatalf("a repeated running changed the end to %d, said %d times", r.Ends, len(said)) + } + back, err := h.Records.Read(r.Instance) + if err != nil || back.Ends != 2 || back.PipelineEnds != 0 { + t.Fatalf("the ledger keeps end %d and pipeline end %d (%v): the late running leaves the pipeline's count unchanged", back.Ends, back.PipelineEnds, err) + } + // A pipeline's first end, and a count not higher than the record heard, reopen nothing; a higher one reopens it. + pipelineEnded(1) + if r.Ended == nil { + t.Fatal("a first pipeline end reopened the record") + } + pipelineEnded(2) + if r.Ended != nil || r.PipelineEnds != 2 || r.Ends != 2 { + t.Fatalf("a pipeline ended again left the record ended %+v, pipeline end %d, end %d: want it open, both counts kept", r.Ended, r.PipelineEnds, r.Ends) + } + pipelineWanted() + if r.Ended == nil || r.Ends != 3 || len(said) != 3 || said[2].Ends != 3 || ids[2] != "record-ended."+r.Instance+".3" { + t.Fatalf("the reopened record ended %+v at end %d, said %+v: want ends 3", r.Ended, r.Ends, said) + } + pipelineEnded(2) + if r.Ended == nil || r.Ends != 3 { + t.Fatalf("a pipeline end not higher than the record heard reopened it: %+v, end %d", r.Ended, r.Ends) + } + if back, err = h.Records.Read(r.Instance); err != nil || back.Ended == nil || back.Ends != 3 || back.PipelineEnds != 2 { + t.Fatalf("the ledger keeps %+v, end %d, pipeline end %d (%v)", back.Ended, back.Ends, back.PipelineEnds, err) + } + // A mover-added counts its mover in the record its pipeline's key names; one naming none or two of its sources is refused. + hear(t, c, "mesh-pipeline-runner.mover-added.main.1", "", `{"v":1,"pipeline":"main.1","revision":4,"module":"extra","fingerprint":"x","from":"main.1.again.1"}`) + for _, bad := range []string{ + `{"v":1,"pipeline":"main.1","revision":4,"module":"never","fingerprint":"y"}`, + `{"v":1,"pipeline":"main.1","revision":4,"module":"never","fingerprint":"y","from":"a","take-in":3}`, + } { + hear(t, c, "mesh-pipeline-runner.mover-added.main.1", "", bad) + } + if _, ok := r.Entries[EntryKey("extra", "x", "")]; !ok { + t.Errorf("a mover-added counted no mover: %v", r.Entries) + } + if _, ok := r.Entries[EntryKey("never", "y", "")]; ok { + t.Errorf("a mover-added naming none or two of its sources counted a mover: %v", r.Entries) + } +} + // GATE-5/AC (design 47 H §738, §751; H-A-75, H-A-89 (3), (4)): a pipeline-ended not passed ends the record failed naming // the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running. func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) { diff --git a/modules/mesh-delivery-gate/module.json b/modules/mesh-delivery-gate/module.json index a6cb5797e..360d43dd2 100644 --- a/modules/mesh-delivery-gate/module.json +++ b/modules/mesh-delivery-gate/module.json @@ -22,6 +22,7 @@ "mesh-delivery-forge-bridge.forge.*.*.*.head-moved", "mesh-delivery-indexer.take-in.taken", "mesh-pipeline-runner.pipeline-started.*.*", + "mesh-pipeline-runner.mover-added.*.*", "mesh-pipeline-runner.pipeline-ended.*.*", "mesh-pipeline-runner.wait-held.*.*", "mesh-pipeline-runner.wait-ended.*.*", @@ -120,6 +121,12 @@ }, "phases": { "type": "object" + }, + "ends": { + "type": "integer" + }, + "pipeline-ends": { + "type": "integer" } }, "operations": [ @@ -193,7 +200,9 @@ "fields": [ "ended", "delivery-time", - "class" + "class", + "ends", + "pipeline-ends" ], "sequence": true } From b1b7940f4f24b12a5e23a031f9b72182ac91b94a Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:17:34 +0100 Subject: [PATCH 05/13] G10 records-end-with-their-record: an end writes each mover's and act's end after the head's, the ledger gives its own ended-days, record-retention goes The ledger records asks max-mib 3072 and its own configuration max-age-days 90 and ended-days 30; record, mover and act name ends-with ended, mover and act gain the field ended and the operation end. A record's end writes the head's end first, then each mover's and act's with the head's ended; a reopening empties theirs first, then the head's; a late running moves every one's end alike. The setting record-retention leaves the manifest, its settings file and its code; the words of room name ended-days. Builds: design 47 H2 H-A-634 (2), H-A-688, H-A-691, H-A-721 --- .../cmd/mesh-delivery-gate/main.go | 2 +- .../cmd/mesh-delivery-gate/movers.go | 7 +- .../cmd/mesh-delivery-gate/owedended.go | 4 +- .../cmd/mesh-delivery-gate/record_test.go | 109 ++++++++++++------ .../cmd/mesh-delivery-gate/recordevents.go | 62 ++++++++++ .../cmd/mesh-delivery-gate/recordfill.go | 2 +- .../cmd/mesh-delivery-gate/settings.go | 27 +---- .../mesh-delivery-gate/files/settings.json | 1 - modules/mesh-delivery-gate/module.json | 40 +++++-- 9 files changed, 179 insertions(+), 75 deletions(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index a8658de1f..2f6b37b66 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -61,7 +61,7 @@ func main() { } h.init() h.SaySeat = stdio.SeatPublish - h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, + h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, Class: seatCatalog{ask: stdio.Ask}.Class} h.Records.Changed = h.recordChanged h.Forge = seatGit{ask: stdio.Ask} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go index 8e3ca90ea..80649aaca 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go @@ -29,11 +29,12 @@ const MoversIndex = "movers" // The operations of a mover's entry; the manifest's type mover declares exactly these (record_test.go). const ( OpMover = "mover" // set-fields: its record's key, its module, its class, its pipeline and its version - // OpEntry and OpOutcome write its entries and outcomes as they did on the whole record. + // OpEntry and OpOutcome write its entries and outcomes as they did on the whole record; OpEnd (record.go) gives it the + // head's ended, its type's ends-with (design 47 H2 H-A-634 (2)). ) // MoverOperations are a mover's operations, in the order the manifest's type allows them. -var MoverOperations = []string{OpMover, OpEntry, OpOutcome} +var MoverOperations = []string{OpMover, OpEntry, OpOutcome, OpEnd} // OpMovers is the head entry's count of its movers (set-fields movers). const OpMovers = "movers" @@ -59,6 +60,8 @@ type Mover struct { Class string `json:"class,omitempty"` Entries map[string]RecordEntry `json:"entries,omitempty"` Outcomes map[string]RecordOutcome `json:"outcomes,omitempty"` + // Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)). + Ended *RecordEnded `json:"ended,omitempty"` } // Running are the machines the mover runs healthy on, each with when it was first said. diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go index d8e6e6319..858423576 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go @@ -71,6 +71,8 @@ type RecordAct struct { Words string `json:"words,omitempty"` At time.Time `json:"at"` Owed seat.Owed `json:"owed"` + // Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)). + Ended *RecordEnded `json:"ended,omitempty"` } // TypeAct is the ledger type of an act's entry, and ActsIndex the ledger's index of the acts' entries on their record's key @@ -81,7 +83,7 @@ const ( ) // ActOperations are an act's operations, in the order the manifest's type act allows them. -var ActOperations = []string{OpAct} +var ActOperations = []string{OpAct, OpEnd} // ActInstance is the entry of a record's act: `act/`, escaped as a name. func ActInstance(milestone, id string) (string, error) { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index 513150b59..c82e6b350 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -274,6 +274,50 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T } }) + // Design 47 H2 H-A-634 (2): a record's end writes the head's end first, then an end on each of its movers and acts with the + // head's ended; a reopening empties theirs first, then the head's; an end written again moves every one's alike. + t.Run("an end writes the head, then each mover and act with its ended; a reopening empties theirs first", func(t *testing.T) { + l := newLedgerFake(t) + rs := &Records{Ledger: l, Now: func() time.Time { return at }} + r, _, err := rs.Open(opening("main", 91, heads)) + if err != nil { + t.Fatal(err) + } + for _, module := range []string{"mod-b", "mod-a"} { + if err := rs.AddEntry(r, RecordEntry{Module: module, Fingerprint: "src2:f" + module}); err != nil { + t.Fatal(err) + } + } + if err := rs.Act(r, RecordAct{ID: "view@1.a", Act: "view", Repository: "novox/app", Number: 3, Head: heads["novox/app@3"]}); err != nil { + t.Fatal(err) + } + l.history = nil + if err := rs.End(r, "by hand", "person"); err != nil { + t.Fatal(err) + } + if len(l.history) != 4 || !strings.HasPrefix(l.history[0], "record/") || !strings.HasPrefix(l.history[3], "act/") || + !strings.Contains(l.history[1], "mod-a") || !strings.Contains(l.history[2], "mod-b") { + t.Fatalf("an end wrote %v: the head's first, then each mover's by module, then each act's", l.history) + } + for _, inst := range l.history[1:3] { + inst = strings.TrimSuffix(inst, " end") + if !strings.Contains(string(l.states[inst]), `"ended":{"at":`) || !strings.Contains(string(l.states[inst]), `"why":"by hand"`) { + t.Errorf("%s holds %s: the head's ended copied", inst, l.states[inst]) + } + } + l.history = nil + if err := rs.Reopen(r, 2); err != nil { + t.Fatal(err) + } + if len(l.history) != 4 || l.history[3] != r.Instance+" end" { + t.Fatalf("a reopening wrote %v: the movers' and acts' ended first, the head's last", l.history) + } + if inst := strings.TrimSuffix(l.history[0], " end"); !strings.HasPrefix(inst, "mover/") || strings.Contains(string(l.states[inst]), `"at"`) || + r.Ended != nil || r.Movers()["mod-a"].Ended != nil { + t.Errorf("a reopened record's mover holds %s, the record ended %+v", l.states[inst], r.Ended) + } + }) + // A record keeps its delivery time and class; gate_times judges them against the budgets (design 47 H2 §810; H-A-394). t.Run("a core record ended 11 minutes after merge-called is over its budget", func(t *testing.T) { now := at @@ -442,37 +486,6 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T t.Fatalf("list %+v", list) } }) - - t.Run("the setting record-retention, in days", func(t *testing.T) { - dir := t.TempDir() - for _, c := range []struct { - file string - want time.Duration - bad bool - }{ - {`{}`, DefaultRecordRetention, false}, - {`{"record-retention": 30}`, 30 * 24 * time.Hour, false}, - {`{"record-retention": 0}`, 0, true}, - {`{"record-retention": 1.5}`, 0, true}, - {`{"record-retention": "90"}`, 0, true}, - } { - p := filepath.Join(dir, "settings.json") - if err := os.WriteFile(p, []byte(c.file), 0o600); err != nil { - t.Fatal(err) - } - s, err := readSettings(p) - if (err != nil) != c.bad { - t.Fatalf("%s: %v", c.file, err) - } - if c.bad { - continue - } - h := &Holder{Settings: func() Settings { return s }} - if got := h.recordRetention(); got != c.want { - t.Fatalf("%s: %s, wanted %s", c.file, got, c.want) - } - } - }) } // W11.1: the manifest's ledger types allow exactly the operations the gate applies, and the ledger is capped at 768 MiB. @@ -488,9 +501,39 @@ func TestTheManifestsLedgerTypesAreTheRecordsOperations(t *testing.T) { t.Errorf("the type %s allows %v, the gate applies %v", name, got, want) } } + // The records ledger's cap and its own configuration (design 47 H2 H-A-688, H-A-634 (2)): 3 GiB, its history kept 90 days, + // an ended instance's keys 30 days (7 or more, the judge's floor for a record a person may still read), and the ending + // types; the month lists' operations stay declared for the replay of the history and are applied by no part (H-A-691, + // H-A-721: no forget). + var manifest struct { + Requires []catalogue.BusStateEntry `json:"requires"` + Config map[string]json.RawMessage `json:"config"` + } raw, _ := os.ReadFile(filepath.Join("..", "..", "module.json")) - if !strings.Contains(string(raw), `"max-mib": 1024`) { - t.Error("the records ledger is not capped at 1 GiB (design 47 H2 §809)") + if err := json.Unmarshal(raw, &manifest); err != nil { + t.Fatal(err) + } + for _, e := range manifest.Requires { + if e.Name != RecordsLedger { + continue + } + var days, kept int + _ = json.Unmarshal(e.Configuration[catalogue.ConfigEndedDays], &days) + _ = json.Unmarshal(e.Configuration[catalogue.OptionAgeDays], &kept) + if string(e.Options[catalogue.OptionCapMiB]) != "3072" || days < 7 || days > 30 || kept != 90 { + t.Errorf("the records ledger asks %v and %v: want max-mib 3072, ended-days from 7 to 30 and max-age-days 90", e.Options, e.Configuration) + } + for _, ty := range e.Types { + if (ty.Name == TypeRecord || ty.Name == TypeMover || ty.Name == TypeAct) != (ty.EndsWith == "ended") { + t.Errorf("the type %s ends with %q: record, mover and act end with ended, held with nothing", ty.Name, ty.EndsWith) + } + if _, has := ty.Schema["ended"]; ty.EndsWith != "" && !has { + t.Errorf("the type %s ends with a field its schema lacks", ty.Name) + } + } + } + if _, kept := manifest.Config["record-retention"]; kept || strings.Contains(string(raw), "forget") { + t.Error("the manifest keeps the setting record-retention or a forget: the bus ends a record's keys by ended-days (H-A-634 (2), H-A-721)") } if ix := l.types[TypeMover].Indexes; len(ix) != 1 || ix[0].Name != MoversIndex || !slices.Equal(ix[0].On, []string{"record"}) { t.Errorf("the type mover's indexes are %+v, not one %s on its record's key", ix, MoversIndex) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index 4fd8a6f02..bfe6a8d94 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -167,6 +167,7 @@ func (rs *Records) end(r *Record, why, by string) error { r.DeliveryTime, r.Class = took.String(), class } rs.keep(r) + rs.endEntries(r, &e) if rs.Changed != nil { rs.Changed(r, RecordChange{What: "ended", Why: why, Ended: true}) } @@ -221,6 +222,7 @@ func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error { r.DeliveryTime, r.Class = took.String(), class } rs.keep(r) + rs.endEntries(r, &e) if rs.Logf != nil { rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q, end %d", r.Instance, o.Module, o.Node, o.At.UTC().Format(time.RFC3339Nano), was.UTC().Format(time.RFC3339Nano), @@ -229,12 +231,72 @@ func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error { return rs.sayEnded(r) } +// endEntries writes the head's ended, or none (nil, a reopening), on each of the record's movers and acts by their `end`, so +// an ended record's entries all take the lifetime of its end and an open one's none (design 47 H2 H-A-634 (2)). A write that +// fails is said in the journal, the record, the instance and the error, and the record's end stands. +func (rs *Records) endEntries(r *Record, e *RecordEnded) { + var value any + if e != nil { + value = *e + } + say := func(instance string, err error) { + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s: the end of its entry %s is not written: %v", r.Instance, instance, err) + } + } + modules := make([]string, 0, len(r.movers)) + for module := range r.movers { + modules = append(modules, module) + } + sort.Strings(modules) + for _, module := range modules { + m := r.movers[module] + next := *m + next.Ended = copyEnded(e) + seq, err := rs.write(r, m.Instance, OpEnd, map[string]any{"ended": value}, next) + if err != nil { + say(m.Instance, err) + continue + } + m.Ended, m.Sequence = next.Ended, seq + } + ids := make([]string, 0, len(r.Acts)) + for id := range r.Acts { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + inst, err := ActInstance(r.Milestone, id) + if err != nil { + say(id, err) + continue + } + a := r.Acts[id] + a.Ended = copyEnded(e) + if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, a); err != nil { + say(inst, err) + continue + } + r.Acts[id] = a + } +} + +func copyEnded(e *RecordEnded) *RecordEnded { + if e == nil { + return nil + } + c := *e + return &c +} + // Reopen reopens an ended record whose pipeline ended again with a higher end count (H-A-609 (2), H-A-728): its `ended` is // emptied and pipeline-ends takes the count, its own end count staying; the next end says ends one higher. func (rs *Records) Reopen(r *Record, pipelineEnds int) error { if r.Ended == nil { return nil } + // Its movers' and acts' ended first, then the head's, so no open head has an entry whose key is ageing (H-A-634 (2)). + rs.endEntries(r, nil) next := *r next.Ended, next.PipelineEnds = nil, pipelineEnds seq, err := rs.write(r, r.Instance, OpEnd, map[string]any{"ended": nil, "pipeline-ends": pipelineEnds}, next.head()) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go index 00a9bd0b1..0fa96d4c8 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go @@ -95,7 +95,7 @@ func (rs *Records) refuseFull(milestone, inst string) (before buscalls.Fill, rea rs.sayFill(meshdelivery.SubjectFull, "full-"+inst, before, "the next record, "+inst+" of "+milestone+"; its merge is held until room is said") return before, true, fmt.Errorf("%w (%d of %d bytes): the record %s of %s is not opened, and its merge is held until "+ - "room is said: the setting record-retention or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone) + "room is said: ended-days of the ledger's own configuration or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone) } // sayFilling says filling when the record just opened took the ledger past FillingPercent of its cap. diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go index becf0c8f7..bf9cef69d 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go @@ -14,9 +14,6 @@ import ( // Settings are the operator's values for this module. type Settings struct { - // RecordRetentionDays is how many days a delivery record is kept from when it opened (design 47 *The delivery - // record*); nil keeps DefaultRecordRetention. - RecordRetentionDays *int `json:"record-retention"` // UntakenBoundMinutes is how many minutes a head may stand untaken before head-untaken is raised (design 47 H §740); nil // keeps DefaultUntakenBound. UntakenBoundMinutes *int `json:"untaken-bound"` @@ -25,7 +22,7 @@ type Settings struct { // DefaultUntakenBound is untaken-bound when the setting gives none (§740). const DefaultUntakenBound = 10 * time.Minute -// readSettings reads the settings file; a value that is not a whole number of days, from 1 to 3650, is refused. +// readSettings reads the settings file; a value that is not a whole number of minutes, at least 1, is refused. func readSettings(path string) (Settings, error) { var s Settings if path == "" { @@ -39,17 +36,6 @@ func readSettings(path string) (Settings, error) { if err := json.Unmarshal(raw, &loose); err != nil { return s, fmt.Errorf("the settings file is not JSON: %v", err) } - switch v := loose["record-retention"].(type) { - case nil: - case float64: - n := int(v) - if v < 1 || v > 3650 || v != float64(n) { - return Settings{}, errors.New("record-retention is not a whole number of days, from 1 to 3650") - } - s.RecordRetentionDays = &n - default: - return Settings{}, errors.New("record-retention is not a number") - } switch v := loose["untaken-bound"].(type) { case nil: case float64: @@ -63,14 +49,3 @@ func readSettings(path string) (Settings, error) { } return s, nil } - -// recordRetention is how long a delivery record is kept from when it opened. -func (h *Holder) recordRetention() time.Duration { - if h.Settings == nil { - return DefaultRecordRetention - } - if n := h.Settings().RecordRetentionDays; n != nil { - return time.Duration(*n) * 24 * time.Hour - } - return DefaultRecordRetention -} diff --git a/modules/mesh-delivery-gate/files/settings.json b/modules/mesh-delivery-gate/files/settings.json index 63414735c..b3b492a24 100644 --- a/modules/mesh-delivery-gate/files/settings.json +++ b/modules/mesh-delivery-gate/files/settings.json @@ -1,4 +1,3 @@ { - "record-retention": 90, "untaken-bound": 10 } diff --git a/modules/mesh-delivery-gate/module.json b/modules/mesh-delivery-gate/module.json index 360d43dd2..3784c9e0c 100644 --- a/modules/mesh-delivery-gate/module.json +++ b/modules/mesh-delivery-gate/module.json @@ -38,11 +38,16 @@ "storage": "ledger", "template": "ledger", "options": { - "max-mib": 1024 + "max-mib": 3072 + }, + "configuration": { + "max-age-days": 90, + "ended-days": 30 }, "types": [ { "name": "record", + "ends-with": "ended", "schema": { "milestone": { "type": "string" @@ -210,6 +215,7 @@ }, { "name": "mover", + "ends-with": "ended", "schema": { "record": { "type": "string" @@ -249,6 +255,9 @@ }, "class": { "type": "string" + }, + "ended": { + "type": "object" } }, "operations": [ @@ -294,6 +303,14 @@ "into": "outcomes", "key": "key", "sequence": true + }, + { + "name": "end", + "effect": "set-fields", + "fields": [ + "ended" + ], + "sequence": true } ], "indexes": [ @@ -307,6 +324,7 @@ }, { "name": "act", + "ends-with": "ended", "schema": { "record": { "type": "string" @@ -337,6 +355,9 @@ }, "owed": { "type": "object" + }, + "ended": { + "type": "object" } }, "operations": [ @@ -356,6 +377,14 @@ "owed" ], "sequence": true + }, + { + "name": "end", + "effect": "set-fields", + "fields": [ + "ended" + ], + "sequence": true } ], "indexes": [ @@ -470,14 +499,6 @@ "mesh-delivery-gate_state_prune_now" ], "config": { - "record-retention": { - "type": "number", - "description": "days a delivery record is kept from when it opened (design 47 *The delivery record*): ninety covers every trace asked of a past delivery so far; when a record is removed at its retention, the gate says freed for each graph revision it pinned. Nothing else is removed to make room.", - "minimum": 1, - "maximum": 3650, - "trusted": false, - "default": 90 - }, "untaken-bound": { "type": "number", "description": "minutes a watched branch's head may stand that no merge call delivered before the gate raises head-untaken (design 47 H §740); the gate keeps one deadline timer for the earliest.", @@ -532,7 +553,6 @@ "path": "${dir:state}/settings.json", "mode": "0600", "takes-config": [ - "record-retention", "untaken-bound" ], "merge": "json", From c055c82bd839d131560391d1be90f9cab9579eea Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:20:29 +0100 Subject: [PATCH 06/13] G11 records-listed-by-watch: the gate lists its records from a watch of its ledger, writes no month list, sweeps nothing, and removes the month lists standing at its start The gate keeps the key and opening of every record from a watch of its ledger's record/> (stdio.WatchLedger): the current states at its start, then each change; a key gone is dropped from every list, and an event for it is said in the journal and changes nothing. An open writes no month list and sweeps and refuses nothing; List, months, heldIn, Sweep, Retention and DefaultRecordRetention go; a month list a watch of held/> hands with a state at the start is removed with mesh/ledger.remove, and no forget is applied (H-A-721). Builds: design 47 H2 H-A-634 (2), (5), (6), H-A-706 (DMC-13), H-A-712 (1), H-A-721 --- .../cmd/mesh-delivery-gate/bus_test.go | 20 +- .../cmd/mesh-delivery-gate/record.go | 294 +++++++++--------- .../cmd/mesh-delivery-gate/record_test.go | 100 +++++- .../cmd/mesh-delivery-gate/recordfill.go | 9 +- .../cmd/mesh-delivery-gate/recordtools.go | 8 +- 5 files changed, 251 insertions(+), 180 deletions(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go index ec23fe56c..cacda2f09 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go @@ -427,13 +427,31 @@ func (r *runtime) answer(m rpcMessage) { return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key) } switch m.Method { - case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove: + case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove, buscalls.LedgerWatch: // The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory. r.b.mu.Lock() defer r.b.mu.Unlock() if r.b.ledger == nil { r.b.ledger = newLedgerFake(r.t) } + if m.Method == buscalls.LedgerWatch { + // The tool runner's ledger watch (design 47 H2 H-A-706): the current states first, each handed to the bundle as a + // `mesh/ledger` call named by the watch's id, then each change the ledger makes; answered once the current are sent. + var in buscalls.LedgerWatchRequest + if err := json.Unmarshal(m.Params, &in); err != nil { + return nil, err + } + err := r.b.ledger.Watch(in.Instances, func(instance string, state json.RawMessage) error { + r.mu.Lock() + n := r.next + r.next++ + r.mu.Unlock() + r.say(map[string]any{"id": fmt.Sprintf("ledger-%d", n), "method": buscalls.LedgerWatched, + "params": buscalls.InstanceChange{Watch: in.Watch, Instance: instance, State: state}}) + return nil + }) + return map[string]any{}, err + } if m.Method == buscalls.LedgerQuery { var in buscalls.QueryRequest if err := json.Unmarshal(m.Params, &in); err != nil { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index d572411af..ffda8c243 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -64,10 +64,6 @@ var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpMovers, OpPhases, Op // HeldOperations are the month's list's operations. var HeldOperations = []string{OpHold, OpDrop} -// DefaultRecordRetention is how long a record is kept when the setting record-retention gives none (design 47: 90 days -// covers every trace the operator has asked of a past delivery so far). -const DefaultRecordRetention = 90 * 24 * time.Hour - // Record is a delivery record's state, as apply derives it from its operations. type Record struct { // Instance is the record's path in the ledger; not in the state. @@ -228,16 +224,6 @@ type RecordEnded struct { Away []NodeAway `json:"away,omitempty"` } -// heldList is a month's list of records: each record opened that month, by instance. -type heldList struct { - Records map[string]heldEntry `json:"records,omitempty"` -} - -type heldEntry struct { - Instance string `json:"instance"` - Opened time.Time `json:"opened"` -} - // segmentRe is what one part of an instance's path may hold (the tool runner's rule). var segmentRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) @@ -275,9 +261,6 @@ func RecordInstance(milestone string) (string, error) { return inst, nil } -// heldInstance is the list of the records opened in a month: `held/2026-11`. -func heldInstance(t time.Time) string { return TypeHeld + "/" + t.UTC().Format("2006-01") } - // RecordLedger is the gate's ledger: an operation applied to one instance, and one instance's state read. type RecordLedger interface { Apply(instance, operation string, body any) (uint64, error) @@ -287,6 +270,10 @@ type RecordLedger interface { Remove(instance string) error // Query is the instances a declared index names under key (`>` for the rest). Query(index, key string) ([]string, error) + // Watch hands handle the current state of each instance `instances` names (an instance, `*` for one name, `>` for the + // rest), then each change, in the order it came: the instance and its state, null once its key has gone (ADR 0597 §10, + // design 47 H2 H-A-634 (5)); it answers once the current states are handled. + Watch(instances string, handle func(instance string, state json.RawMessage) error) error } // sdkLedger is the gate's ledger through the runtime: the tool runner's ledger calls, on the gate's own ledger only @@ -352,6 +339,11 @@ func (sdkLedger) Query(index, key string) ([]string, error) { return insts, nil } +// Watch is the tool runner's watch of the gate's own ledger (mesh-sdk's stdio.WatchLedger), the current states first. +func (sdkLedger) Watch(instances string, handle func(string, json.RawMessage) error) error { + return stdio.WatchLedger(RecordsLedger, instances, func(c buscalls.InstanceChange) error { return handle(c.Instance, c.State) }) +} + func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) if err != nil { @@ -371,8 +363,6 @@ func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { type Records struct { Ledger RecordLedger Now func() time.Time - // Retention is how long a record is kept; nil keeps DefaultRecordRetention. - Retention func() time.Duration // Say says the seat mesh-delivery's events of the records: pinned, freed, record-ended (recordevents.go), filling, // full and room (recordfill.go); nil says none. Say SeatSay @@ -388,11 +378,15 @@ type Records struct { // finding's subject (§809; H-A-460); an empty instance clears every one held of the record (its end). nil raises none. TooLarge func(record, instance string, bytes int, raised bool) - // held are the records kept, by instance, read once from the ledger (Current) and kept as the gate writes them: the - // gate is their one writer. - mu sync.Mutex - held map[string]*Record - loaded bool + // held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read, + // then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in + // gone so an event for it is said and changes nothing (design 47 H2 H-A-634 (2), (5)). + mu sync.Mutex + held map[string]*Record + gone map[string]bool + pending map[string]struct{} + watching bool + loaded bool } // Current is every record kept and not ended, oldest first: read from the ledger at the first call, then as the gate @@ -428,41 +422,134 @@ func (rs *Records) Kept() ([]*Record, error) { return out, nil } +// load starts the gate's watch of its ledger's `record/>` once, at the first read: the key and opening of every record the +// ledger holds come as current states, each read as today, then each change; and the month lists `held/` the +// earlier gate wrote, a watch of `held/>` hands with a state, are removed through the ledger's removal (H-A-721). A record +// that could not be read is read again at the next call. func (rs *Records) load() error { rs.mu.Lock() - loaded := rs.loaded - rs.mu.Unlock() - if loaded { + if rs.loaded { + rs.mu.Unlock() return nil } - list, err := rs.List() + started := rs.watching + rs.watching = true + rs.mu.Unlock() + if !started { + if err := rs.Ledger.Watch(TypeRecord+"/>", rs.heardRecord); err != nil { + rs.mu.Lock() + rs.watching = false + rs.mu.Unlock() + return fmt.Errorf("the delivery records cannot be watched: %w", err) + } + if err := rs.Ledger.Watch(TypeHeld+"/>", rs.removeMonthList); err != nil { + rs.log("the month lists of the records cannot be watched, so none is removed: %v", err) + } + } + rs.mu.Lock() + var pending []string + for inst := range rs.pending { + pending = append(pending, inst) + } + rs.mu.Unlock() + for _, inst := range pending { + if err := rs.heardRecord(inst, json.RawMessage("true")); err != nil { + return err + } + } + rs.mu.Lock() + defer rs.mu.Unlock() + if rs.held == nil { + rs.held = map[string]*Record{} + } + rs.loaded = true + return nil +} + +// heardRecord takes one record's state from the watch: null drops the record, as a key gone by its lifetime; a record the +// gate holds is current already, being the one writer; any other is read and kept. A record that cannot be read stays pending. +func (rs *Records) heardRecord(instance string, state json.RawMessage) error { + if string(state) == "null" || len(state) == 0 { + rs.mu.Lock() + delete(rs.held, instance) + delete(rs.pending, instance) + if rs.gone == nil { + rs.gone = map[string]bool{} + } + known := rs.gone[instance] + rs.gone[instance] = true + rs.mu.Unlock() + if !known { + rs.log("the record %s's key has gone: it is no longer read", instance) + } + return nil + } + rs.mu.Lock() + _, have := rs.held[instance] + rs.mu.Unlock() + if have { + return nil + } + r, err := rs.Read(instance) if err != nil { + rs.mu.Lock() + if rs.pending == nil { + rs.pending = map[string]struct{}{} + } + rs.pending[instance] = struct{}{} + rs.mu.Unlock() return err } rs.mu.Lock() defer rs.mu.Unlock() - if !rs.loaded { - rs.held = map[string]*Record{} - for _, r := range list { - rs.held[r.Instance] = r - } - rs.loaded = true + delete(rs.pending, instance) + if r == nil { + return nil } + if rs.held == nil { + rs.held = map[string]*Record{} + } + if _, have := rs.held[instance]; !have { + rs.held[instance] = r + } + delete(rs.gone, instance) return nil } -func (rs *Records) keep(r *Record) { - rs.mu.Lock() - defer rs.mu.Unlock() - if rs.loaded { - rs.held[r.Instance] = r +// removeMonthList removes a month list the earlier gate wrote, through the ledger's removal, which ends the instance whole +// (design 47 H2 H-A-721): its operations, its snapshot, its key and its index keys. +func (rs *Records) removeMonthList(instance string, state json.RawMessage) error { + if string(state) == "null" || len(state) == 0 { + return nil + } + if err := rs.Ledger.Remove(instance); err != nil { + rs.log("the month list %s is not removed: %v", instance, err) + return err + } + rs.log("the month list %s is removed: the gate lists its records from a watch of the ledger", instance) + return nil +} + +func (rs *Records) log(format string, a ...any) { + if rs.Logf != nil { + rs.Logf("[mesh-delivery] "+format, a...) } } -func (rs *Records) forget(instance string) { +// keep holds a record the gate writes once it keeps its records, and answers the one held under its instance: the record +// a watch handed first stays the one every reader writes through. +func (rs *Records) keep(r *Record) *Record { rs.mu.Lock() defer rs.mu.Unlock() - delete(rs.held, instance) + if !rs.loaded { + return r + } + if held, ok := rs.held[r.Instance]; ok && held != r { + return held + } + rs.held[r.Instance] = r + delete(rs.gone, r.Instance) + return r } func (rs *Records) now() time.Time { @@ -472,16 +559,6 @@ func (rs *Records) now() time.Time { return rs.Now().UTC() } -func (rs *Records) retention() time.Duration { - if rs.Retention == nil { - return DefaultRecordRetention - } - if d := rs.Retention(); d > 0 { - return d - } - return DefaultRecordRetention -} - // Read is one record, or nil when the ledger holds none at that instance (or one removed). func (rs *Records) Read(instance string) (*Record, error) { raw, seq, err := rs.Ledger.Get(instance) @@ -521,8 +598,8 @@ type RecordOpening struct { } // Open opens the record of a source revision, unless one is there already, which is left as it is (a merge call heard -// again opens no second record and says nothing new). Opened says it was opened now. Each open removes the records past -// their retention first (the retention needs no timer: records open as deliveries do). +// again opens no second record and says nothing new). Opened says it was opened now. An open writes no month list and +// removes nothing: the bus ends an ended record's keys by the ledger's ended-days (design 47 H2 H-A-634 (2), (5), (6)). func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if o.Branch == "" || o.Source < 1 || o.Call == "" { return nil, false, fmt.Errorf("a delivery record names its branch, its source revision and its merge call (%q, %d, %q)", o.Branch, o.Source, o.Call) @@ -548,9 +625,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { return r, false, nil } now := rs.now() - if err := rs.Sweep(now); err != nil { - return nil, false, fmt.Errorf("the records past their retention cannot be removed, so no record is opened: %w", err) - } before, read, err := rs.refuseFull(milestone, inst) if err != nil { return nil, false, err @@ -564,9 +638,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if _, err := rs.write(&Record{Milestone: milestone}, inst, OpOpen, body, body); err != nil { return nil, false, err } - if _, err := rs.Ledger.Apply(heldInstance(now), OpHold, heldEntry{Instance: inst, Opened: now}); err != nil { - return nil, false, fmt.Errorf("the record %s is opened but not listed: %w", inst, err) - } if read { rs.sayFilling(inst, before) } @@ -576,7 +647,7 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if err := rs.SetTrace(r, o.Trace); err != nil { return r, true, fmt.Errorf("the record %s is opened and its trace is not written: %w", inst, err) } - rs.keep(r) + r = rs.keep(r) rs.sayOpened(r) return r, true, nil } @@ -602,7 +673,14 @@ func (rs *Records) ByMilestone(milestone string) (*Record, error) { } r, err := rs.Read(inst) if r != nil { - rs.keep(r) + r = rs.keep(r) + } else if err == nil { + rs.mu.Lock() + gone := rs.gone[inst] + rs.mu.Unlock() + if gone { + rs.log("the record %s's key has gone: an event for it changes nothing", inst) + } } return r, err } @@ -617,100 +695,6 @@ func (rs *Records) sayOpened(r *Record) { } } -// List is every record kept, opened within the retention and a month more, oldest first. -func (rs *Records) List() ([]*Record, error) { - now := rs.now() - var out []*Record - for _, m := range rs.months(now) { - list, err := rs.heldIn(m) - if err != nil { - return nil, err - } - for _, e := range list { - r, err := rs.Read(e.Instance) - if err != nil { - return nil, err - } - if r != nil { - out = append(out, r) - } - } - } - sort.SliceStable(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) }) - return out, nil -} - -// months are the months' lists a record within the retention can be in, oldest first, one more at each end. -func (rs *Records) months(now time.Time) []string { - from := now.Add(-rs.retention()).AddDate(0, -1, 0) - var out []string - for m := time.Date(from.Year(), from.Month(), 1, 0, 0, 0, 0, time.UTC); !m.After(now); m = m.AddDate(0, 1, 0) { - out = append(out, heldInstance(m)) - } - return out -} - -func (rs *Records) heldIn(month string) ([]heldEntry, error) { - raw, _, err := rs.Ledger.Get(month) - if err != nil || raw == nil { - return nil, err - } - var l heldList - if err := json.Unmarshal(raw, &l); err != nil { - return nil, fmt.Errorf("the list of records %s is not readable: %w", month, err) - } - out := make([]heldEntry, 0, len(l.Records)) - for _, e := range l.Records { - out = append(out, e) - } - sort.Slice(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) }) - return out, nil -} - -// Sweep removes every record opened longer ago than the retention. Nothing else is removed to make room. -func (rs *Records) Sweep(now time.Time) error { - cut := now.Add(-rs.retention()) - for _, m := range rs.months(now) { - list, err := rs.heldIn(m) - if err != nil { - return err - } - for _, e := range list { - if !e.Opened.Before(cut) { - continue - } - r, err := rs.Read(e.Instance) - if err != nil { - return err - } - if r != nil { - for _, m := range r.movers { - if err := rs.Ledger.Remove(m.Instance); err != nil { - return err - } - } - for id := range r.Acts { - inst, err := ActInstance(r.Milestone, id) - if err != nil { - return err - } - if err := rs.Ledger.Remove(inst); err != nil { - return err - } - } - if err := rs.Ledger.Remove(e.Instance); err != nil { - return err - } - rs.forget(e.Instance) - } - if _, err := rs.Ledger.Apply(m, OpDrop, map[string]any{"instance": e.Instance}); err != nil { - return err - } - } - } - return nil -} - // SetGroup writes the record's group state, unless it holds that state already. func (rs *Records) SetGroup(r *Record, g RecordGroup) error { if r.Group != nil && reflect.DeepEqual(*r.Group, g) { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index c82e6b350..969f71897 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -34,6 +34,46 @@ type ledgerFake struct { failOn string // fill is what Fill answers; nil, the ledger says no fill. fill *buscalls.Fill + // watchers are the watches the gate started, each told of every change to an instance its pattern names. + watchers []ledgerWatch +} + +// ledgerWatch is one watch of the fake ledger: the instances it names (an instance path, or a type's `/>`) and its handler. +type ledgerWatch struct { + instances string + handle func(instance string, state json.RawMessage) error +} + +func (w ledgerWatch) names(instance string) bool { + return w.instances == instance || strings.HasSuffix(w.instances, ">") && strings.HasPrefix(instance, strings.TrimSuffix(w.instances, ">")) +} + +// Watch hands the current state of each instance the pattern names, in order, and keeps the handler for change. +func (f *ledgerFake) Watch(instances string, handle func(string, json.RawMessage) error) error { + w := ledgerWatch{instances: instances, handle: handle} + f.watchers = append(f.watchers, w) + var names []string + for inst, raw := range f.states { + if w.names(inst) && string(raw) != "null" { + names = append(names, inst) + } + } + sort.Strings(names) + for _, inst := range names { + if err := handle(inst, f.states[inst]); err != nil { + return err + } + } + return nil +} + +// change hands an instance's state, null once its key has gone, to every watch that names it. +func (f *ledgerFake) change(instance string) { + for _, w := range f.watchers { + if w.names(instance) { + _ = w.handle(instance, f.states[instance]) + } + } } func (f *ledgerFake) Fill() (buscalls.Fill, error) { @@ -151,6 +191,7 @@ func (f *ledgerFake) Remove(instance string) error { f.seq[instance]++ f.states[instance] = json.RawMessage("null") f.history = append(f.history, instance+" remove") + f.change(instance) return nil } @@ -423,7 +464,7 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T if byKey, err := rs.ByKey("main", 47); err != nil || byKey == nil || byKey.Instance != r.Instance { t.Fatalf("read by its key: %+v %v", byKey, err) } - list, err := rs.List() + list, err := rs.Kept() if err != nil || len(list) != 1 || list[0].Instance != r.Instance { t.Fatalf("list %+v %v", list, err) } @@ -464,26 +505,57 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T } }) - t.Run("a record past its retention is removed at the next open", func(t *testing.T) { + // Design 47 H2 H-A-634 (2), (5), H-A-721: the gate lists its records from a watch of its ledger's `record/>`; an open + // writes no month list and removes nothing; a month list standing at the start is removed through the ledger's removal and no + // forget is applied; a key gone drops the record from every list, and an event for it changes nothing and is said. + t.Run("the records are listed from a watch: a month list standing is removed at the start, a gone key drops its record and an event for it changes nothing", func(t *testing.T) { l := newLedgerFake(t) now := at - rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }} - old, _, _ := rs.Open(opening("main", 46, heads)) + var journal []string + logf := func(format string, a ...any) { journal = append(journal, fmt.Sprintf(format, a...)) } + before := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf} + old, _, _ := before.Open(opening("main", 46, heads)) now = at.Add(89 * 24 * time.Hour) - kept, _, _ := rs.Open(opening("main", 47, heads)) - if r, _ := rs.Read(old.Instance); r == nil { - t.Fatal("a record within its retention is removed") + kept, _, _ := before.Open(opening("main", 47, heads)) + for _, op := range l.history { + if strings.HasPrefix(op, TypeHeld+"/") { + t.Fatalf("an open wrote %s: no month list is written", op) + } } - now = at.Add(91 * 24 * time.Hour) - if _, _, err := rs.Open(opening("main", 48, heads)); err != nil { + // A month list the gate before H2 wrote, standing at the start. + if _, err := l.Apply("held/2026-11", OpHold, map[string]any{"instance": old.Instance, "opened": at}); err != nil { t.Fatal(err) } - if r, _ := rs.Read(old.Instance); r != nil { - t.Fatal("a record past its retention is kept") + l.history = nil + rs := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf} + list, err := rs.Kept() + if err != nil || len(list) != 2 || list[0].Instance != old.Instance || list[1].Instance != kept.Instance { + t.Fatalf("the records listed from the watch are %+v (%v): the two, oldest first", list, err) } - list, _ := rs.List() - if len(list) != 2 || list[0].Instance != kept.Instance { - t.Fatalf("list %+v", list) + if string(l.states["held/2026-11"]) != "null" || !slices.Contains(l.history, "held/2026-11 remove") { + t.Fatalf("the month list holds %s after %v: removed through the ledger's removal", l.states["held/2026-11"], l.history) + } + for _, op := range l.history { + if strings.HasSuffix(op, " forget") || strings.HasSuffix(op, " "+OpDrop) || strings.HasSuffix(op, " "+OpHold) { + t.Errorf("the gate applied %s: no month list is applied", op) + } + } + // The key of the older record goes by its lifetime: the bus hands it removed. + l.states[old.Instance] = json.RawMessage("null") + l.change(old.Instance) + if list, _ := rs.Kept(); len(list) != 1 || list[0].Instance != kept.Instance { + t.Fatalf("after its key went the records are %+v: one", list) + } + if cur, _ := rs.Current(); len(cur) != 1 { + t.Fatalf("after its key went the open records are %+v: one", cur) + } + n := len(l.history) + journal = nil + if r, err := rs.ByKey("main", 46); err != nil || r != nil { + t.Fatalf("an event's record is %+v (%v): none, its key has gone", r, err) + } + if len(l.history) != n || !strings.Contains(strings.Join(journal, "\n"), "key has gone: an event for it changes nothing") { + t.Fatalf("the ledger took %v and the journal says %q: nothing written, said once", l.history[n:], journal) } }) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go index 0fa96d4c8..e8bec47ed 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go @@ -4,7 +4,7 @@ package main // full"): the gate reads its ledger's fill through the tool runner (mesh-sdk buscalls.LedgerFill), says `filling` of the // seat mesh-delivery when a record it opens takes the ledger past 80 % of its cap, refuses the next record when the // ledger has no room for one and says `full`, and holds that record's merge until the ledger is below 80 % again, when -// it says `room` and hands the merge. Nothing is dropped to make room: only the retention removes a record. The fill +// it says `room` and hands the merge. Nothing is dropped to make room: the bus ends an ended record's keys by the ledger's ended-days. The fill // is read from the bus at each judgement, and which merges wait for room is kept on their deliveries (Ready.HeldFull), // so a restarted gate judges as the one before it. @@ -109,12 +109,9 @@ func (rs *Records) sayFilling(inst string, before buscalls.Fill) { } } -// RoomAgain is whether a merge held for a full ledger since then may be handed now: the records past their retention -// removed first, the ledger below FillingPercent of its cap, said once as room. A fill it cannot read gives no room. +// RoomAgain is whether a merge held for a full ledger since then may be handed now: the ledger below FillingPercent of its +// cap, said once as room. A fill it cannot read gives no room. func (rs *Records) RoomAgain(since time.Time) (bool, error) { - if err := rs.Sweep(rs.now()); err != nil { - return false, err - } f, err := rs.Fill() if err != nil { return false, err diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go index c8ab68e22..31f294c02 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go @@ -51,7 +51,7 @@ func (rs *Records) RecordOf(instance, milestone string) ([]recordView, error) { if milestone == "" { return nil, errors.New("name a record's instance or a milestone") } - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } @@ -84,7 +84,7 @@ type recordLine struct { // Lines are every record kept, oldest first, each with its fill against the value limit. func (rs *Records) Lines() (map[string]any, error) { - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } @@ -102,7 +102,7 @@ func (rs *Records) Lines() (map[string]any, error) { } lines = append(lines, l) } - return map[string]any{"records": lines, "open": open, "kept": len(lines), "retention-days": int(rs.retention().Hours() / 24), + return map[string]any{"records": lines, "open": open, "kept": len(lines), "fill": rs.fillLine()}, nil } @@ -143,7 +143,7 @@ func (rs *Records) EndAllByHand(why, by string, acts handActs) (map[string]any, if strings.TrimSpace(why) == "" { return nil, errors.New("say why every open record is ended by hand, such as the clean state") } - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } From cdae0e03391a56ae5a443e60c94795c9e079463d Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:20:47 +0100 Subject: [PATCH 07/13] G19 started-decoded-by-contract: the gate reads pipeline-started with the contract's decoder A pipeline-started of the earlier form, whose movers carry fields the new StartedMover leaves out, is taken as the new form is: a field this reader does not know is left unread, never refused. Builds: design 47 H2 H-A-709 (3) --- .../cmd/mesh-delivery-gate/recordpipeline.go | 7 +++++-- .../cmd/mesh-delivery-gate/recordpipeline_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go index 3564fc753..c9b4840f0 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go @@ -47,9 +47,12 @@ func strictly(body json.RawMessage, into any) error { return dec.Decode(into) } +// decodePipelineStarted reads a pipeline-started with the contract's decoder, so a field of the runner's other form that this +// reader does not know is left unread and the movers of the earlier form and of the new are taken alike (design 47 H2 +// H-A-709 (3)). func decodePipelineStarted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { - var p runner.PipelineStartedEvent - if err := strictly(body, &p); err != nil { + p, _, err := runner.DecodePipelineStartedEvent(body) + if err != nil { return nil, err } return nil, namesSource(p.Branch, p.Source, p.Run) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go index aee6ed2a7..33b3367fc 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go @@ -62,6 +62,14 @@ func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) { if _, ok := r.Entries[EntryKey("app", "f", "")]; !ok || len(r.Entries) != 1 { t.Fatalf("entries %v: the mover is one, a run's none", r.Entries) } + // Design 47 H2 H-A-709 (3): a pipeline-started of the earlier form, whose movers carry fields the new form's StartedMover + // leaves out, is taken as the new form is: its movers are entries. + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"older","commit":"c","fingerprint":"o","repository":"novox/older","tier":1,"published":true,"widens":["x"],"tests":{"passed":3},"over-budget":false}]}`) + if _, ok := r.Entries[EntryKey("older", "o", "")]; !ok || len(r.Entries) != 2 { + t.Fatalf("entries %v: the earlier form's mover is one too", r.Entries) + } + delete(r.Entries, EntryKey("older", "o", "")) hear(t, c, "mesh-pipeline-runner.wait-held.main.1", "", `{"v":1,"branch":"main","source":1,"pipeline":"main.1","module":"app","fingerprint":"f","step":"approval","on":"person","who":"the operator","since":"2026-11-20T03:01:00Z"}`) held := r.Outcomes[OutcomeKey("app", "f", "", "approval")] From e580f54a4be20f2e0a0aecd10276241b52c946c6 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:22:15 +0100 Subject: [PATCH 08/13] G16 fill-names-object: full and full-cleared carry the fill of the object judged and its part, and show answers each object The fill pass keeps the object of an entry with the highest share and says full and full-cleared (the body's v 2) with a fill naming that object, its part (history, state, index or snapshot of a ledger), its messages, bytes and cap; their why and the condition's text name it. mesh-broker.show's fill keeps the sum and gains objects, one item of the definition ObjectFill each. Builds: design 47 H2 H-A-634 (9), H-A-636, H-A-687 (3), H-A-706 (DQ-41), H-A-717 (DQ-50) --- modules/nats/cmd/nats-tools/broker.go | 11 +++-- modules/nats/cmd/nats-tools/broker_test.go | 3 ++ modules/nats/internal/keeper/fill.go | 20 +++++++-- modules/nats/internal/keeper/keeper.go | 20 ++++++--- modules/nats/internal/keeper/keeper_test.go | 49 +++++++++++++++++++++ modules/nats/internal/keeper/plan.go | 23 ++++++++++ 6 files changed, 115 insertions(+), 11 deletions(-) diff --git a/modules/nats/cmd/nats-tools/broker.go b/modules/nats/cmd/nats-tools/broker.go index 86421c683..c691fc721 100644 --- a/modules/nats/cmd/nats-tools/broker.go +++ b/modules/nats/cmd/nats-tools/broker.go @@ -96,7 +96,7 @@ func streamsHeld(jsz []byte) (map[string]busStream, error) { // heldOf is one entry as the seat's list, show and orphans answer it (mesh-contracts meshbroker.Held): its bus name, its // template, its options or configuration as the manifest asked them, the settings the bus holds of each of its objects // by stream, and its fill summed over them against their caps. -func heldOf(module, local string, m keeper.Made, held map[string]busStream) meshbroker.Held { +func heldOf(module, local string, m keeper.Made, held map[string]busStream, objects bool) meshbroker.Held { h := meshbroker.Held{BusName: keeper.BusName(module, local), Module: module, LocalName: local, StorageType: m.Plan.Storage, Template: m.Plan.Template, Options: anyOf(m.Plan.Entry.Options), Configuration: anyOf(m.Plan.Entry.Configuration)} settings := map[string]any{} @@ -110,6 +110,11 @@ func heldOf(module, local string, m keeper.Made, held map[string]busStream) mesh fill.Bytes += int64(s.State.Bytes) fill.Count += int64(s.State.Messages) fill.Cap += s.Config.MaxBytes + if objects { + // show's fill keeps the entry's sum and gains one item per object (design 47 H2 H-A-634 (9), H-A-687 (3)). + fill.Objects = append(fill.Objects, meshbroker.ObjectFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: int64(s.State.Messages), + Bytes: int64(s.State.Bytes), Cap: s.Config.MaxBytes}) + } } if len(settings) > 0 { h.Settings, h.Fill = settings, &fill @@ -189,7 +194,7 @@ func brokerTools(read heldEntries, status func() (keeper.Status, error), jsz fun for _, module := range sortedNames(entries) { for _, local := range sortedNames(entries[module].Made) { if m := entries[module].Made[local]; keep(m) { - out = append(out, heldOf(module, local, m, held)) + out = append(out, heldOf(module, local, m, held, false)) } } } @@ -227,7 +232,7 @@ func brokerTools(read heldEntries, status func() (keeper.Status, error), jsz fun if !ok { return nil, fmt.Errorf("the bus module made no entry %q of %q", local, module) } - return heldOf(module, local, m, held), nil + return heldOf(module, local, m, held, true), nil }}, {Name: "mesh-broker.check", Description: "What the bus holds against what was asked, entry by entry: each object missing, or differing from its manifest's settings, with both. A difference that only grows is applied by the bus module itself; any other is a drift, raised to the operator.", diff --git a/modules/nats/cmd/nats-tools/broker_test.go b/modules/nats/cmd/nats-tools/broker_test.go index 348b7b4eb..21bb3636b 100644 --- a/modules/nats/cmd/nats-tools/broker_test.go +++ b/modules/nats/cmd/nats-tools/broker_test.go @@ -67,6 +67,9 @@ func TestTheSeatsReadingVerbsAnswerFromTheKeeperAndTheBus(t *testing.T) { {"mesh-broker.list", nil, []string{`"caps":{"account-limit-mib":2048,"server-limit-mib":4096,"sum-mib":1376`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "log"}, []string{`"bus-name":"m_log"`, `"template":"log"`, `"m_log":{"max-bytes":33554432`}, ""}, + // show's fill keeps the entry's sum and gains one item per object (design 47 H2 H-A-634 (9), H-A-687 (3)). + {"mesh-broker.show", map[string]any{"module": "m", "local-name": "drafts"}, []string{`"fill":{"bytes":1048576,"cap":83886080,"count":3,"objects":[{"bytes":1048576,"cap":67108864,"count":3,"object":"KV_m_drafts"}`, + `{"bytes":0,"cap":16777216,"count":0,"object":"OBJ_m_drafts-objects"}]}`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "later"}, []string{`"local-name":"later"`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "none"}, nil, `made no entry "none" of "m"`}, {"mesh-broker.check", nil, []string{`{"differences":[{`, `"local-name":"log"`, `"asked":{"m_log":{"max-bytes":16777216`, diff --git a/modules/nats/internal/keeper/fill.go b/modules/nats/internal/keeper/fill.go index 87a9de1e7..75a9e0173 100644 --- a/modules/nats/internal/keeper/fill.go +++ b/modules/nats/internal/keeper/fill.go @@ -38,6 +38,7 @@ func (k *Keeper) FillPass() { continue } var most int64 = -1 + var judged *EventFill for _, o := range m.Plan.Objects { if !o.Settings.Refuses() || o.Settings.MaxBytes <= 0 { continue @@ -48,6 +49,7 @@ func (k *Keeper) FillPass() { } if p := int64(f.Bytes) * 100 / o.Settings.MaxBytes; p > most { most = p + judged = &EventFill{Count: f.Messages, Bytes: f.Bytes, Cap: o.Settings.MaxBytes, Object: o.Stream(), Part: m.Plan.PartOf(o)} } } if most < 0 { @@ -58,13 +60,13 @@ func (k *Keeper) FillPass() { switch { case !m.Full && most >= raise: m.Full = true - k.emit(EventFull, m.Plan, held.Revision, fmt.Sprintf("%d%% of its cap, past the raise mark %d%%", most, raise), nil, nil) + k.emitFill(EventFull, m.Plan, held.Revision, fmt.Sprintf("%s holds %d%% of its cap, past the raise mark %d%%", nameOf(judged), most, raise), nil, nil, judged) k.raise(conditionFull, module, local, occ.SeverityWarning, "Kept data is filling up", "a larger cap in the module's manifest, or data removed", - fmt.Sprintf("%s of %s holds %d%% of its cap and refuses new data when full; it is cleared below %d%%", local, module, most, clear)) + fmt.Sprintf("%s of %s of %s holds %d%% of its cap and refuses new data when full; it is cleared below %d%%", nameOf(judged), local, module, most, clear)) case m.Full && most < clear: m.Full = false - k.emit(EventFullCleared, m.Plan, held.Revision, fmt.Sprintf("%d%% of its cap, below the clear mark %d%%", most, clear), nil, nil) + k.emitFill(EventFullCleared, m.Plan, held.Revision, fmt.Sprintf("%s holds %d%% of its cap, below the clear mark %d%%", nameOf(judged), most, clear), nil, nil, judged) k.clear(conditionFull, module, local) } if m.Fill != was.Fill || m.Full != was.Full { @@ -77,3 +79,15 @@ func (k *Keeper) FillPass() { } k.setStatus(func(s *Status) { s.Pass = k.now() }) } + +// nameOf names the object a fill is of in words: its part and its bus name for a ledger, its bus name alone for an entry of +// one object (design 47 H2 H-A-634 (9): the state `KV_mesh-delivery-gate_records_state`). +func nameOf(f *EventFill) string { + if f == nil { + return "it" + } + if f.Part == "" { + return "`" + f.Object + "`" + } + return "the " + f.Part + " `" + f.Object + "`" +} diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 97e6a4b69..031d6c6f8 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -76,11 +76,15 @@ type Event struct { Revision uint64 `json:"revision"` } -// EventFill is an entry's fill as an event says it: its messages, its bytes and its cap. +// EventFill is the fill an event says: the object it is of, its messages, its bytes and its cap; Object is its name on the +// bus and Part the place it has in the entry's binding (history, state, `index ` or snapshot of a ledger), absent for an +// entry of one object (design 47 H2 H-A-634 (9), H-A-687 (3)). type EventFill struct { - Count uint64 `json:"count"` - Bytes uint64 `json:"bytes"` - Cap int64 `json:"cap"` + Count uint64 `json:"count"` + Bytes uint64 `json:"bytes"` + Cap int64 `json:"cap"` + Object string `json:"object,omitempty"` + Part string `json:"part,omitempty"` } // Accepted is one module's entry as the catalog half's watched branches give it (design 47 G §344, §433, §532): the @@ -1040,10 +1044,16 @@ func (k *Keeper) SayUnsaid() { // emit says one event; one the bus did not take whole is kept in the keeper's status and said again, on the subjects // left, at the next fill pass. func (k *Keeper) emit(event string, p Plan, revision uint64, why string, asked, held map[string]Settings) { + k.emitFill(event, p, revision, why, asked, held, nil) +} + +// emitFill is emit with the fill of the object judged, which full and full-cleared carry (design 47 H2 H-A-634 (9)). +func (k *Keeper) emitFill(event string, p Plan, revision uint64, why string, asked, held map[string]Settings, fill *EventFill) { if k.Emit == nil { return } s := k.saying(event, p, revision, why, asked, held) + s.Body.Fill = fill if err := k.Emit(&s); err != nil { s.Error = err.Error() k.setStatus(func(st *Status) { st.Unsaid = append(st.Unsaid, s) }) @@ -1074,7 +1084,7 @@ func (k *Keeper) sayNow(event string, p Plan, revision uint64, why string, asked } func (k *Keeper) saying(event string, p Plan, revision uint64, why string, asked, held map[string]Settings) Saying { - body := Event{V: 1, Module: p.Module, Local: p.Local, Storage: p.Storage, Template: p.Template, Options: p.Entry.Options, + body := Event{V: 2, Module: p.Module, Local: p.Local, Storage: p.Storage, Template: p.Template, Options: p.Entry.Options, Configuration: p.Entry.Configuration, BusName: BusName(p.Module, p.Local), Binding: p.Binding, Asked: asked, Held: held, Why: why, Revision: revision} if event == EventDropped { diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index 3454d66fe..7bbb09720 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "os" + "slices" "sort" "strings" "sync" @@ -772,6 +773,54 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("drift %q, said %v: a snapshot store that drops its oldest drifts", d, out.events) } }}, + // Design 47 H2 H-A-634 (9), H-A-636, H-A-687 (3): full and full-cleared carry the fill of the object judged, naming it and its + // part; a ledger whose state holds 100 MiB under its cap of 1 GiB says none, at 75% its state is named, and a snapshot store + // at 75% is named with the part snapshot. + {"a ledger's full names the object it judged and its part", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + out.reset() + bus.fill["KV_m_records_state"] = 100 * uint64(MiB) + bus.fill["m_records"] = 200 * uint64(MiB) + k.FillPass() + if len(out.events) != 0 { + t.Fatalf("said %v: a state at 100 MiB of 1 GiB and a history at 20%% are not full (H-A-636)", out.events) + } + bus.fill["KV_m_records_state"] = 768 * uint64(MiB) + k.FillPass() + if fmt.Sprint(out.events) != "[full m records]" || out.bodies[0].V != 2 { + t.Fatalf("said %v", out.events) + } + if f := out.bodies[0].Fill; f == nil || f.Object != "KV_m_records_state" || f.Part != "state" || f.Bytes != 768*uint64(MiB) || f.Cap != 1024*MiB || + !strings.Contains(out.bodies[0].Why, "the state `KV_m_records_state` holds 75%") { + t.Fatalf("full carries %+v and says %q: the state, at 75%% of 1 GiB", f, out.bodies[0].Why) + } + if !slices.ContainsFunc(out.conds, func(c string) bool { return strings.HasPrefix(c, "raised") }) { + t.Fatalf("conditions %v", out.conds) + } + bus.fill["KV_m_records_state"] = 0 + bus.fill["m_records_snapshot"] = 768 * uint64(MiB) + k.FillPass() + k.FillPass() + if len(out.events) != 1 { + t.Fatalf("said %v: the entry stays full while any object holds past the clear mark", out.events) + } + bus.fill["m_records_snapshot"] = 10 * uint64(MiB) + k.FillPass() + if cleared := out.bodies[len(out.bodies)-1]; fmt.Sprint(out.events) != "[full m records full-cleared m records]" || cleared.Fill == nil || cleared.Fill.Part != "history" { + t.Fatalf("said %v", out.events) + } + }}, + {"a ledger's snapshot store at 75% says full with the part snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + out.reset() + bus.fill["m_records_snapshot"] = 768 * uint64(MiB) + k.FillPass() + if f := out.bodies[0].Fill; fmt.Sprint(out.events) != "[full m records]" || f == nil || f.Object != "m_records_snapshot" || f.Part != "snapshot" { + t.Fatalf("said %v: full naming the snapshot store %+v", out.events, f) + } + }}, {"a plan whose caps pass the account's storage limit is refused, naming the sum and the limit, and the caps made stay (§547)", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { // drafts: 64 MiB state + 16 MiB objects = 80 MiB; log: 1024 MiB. bus.limits = Limits{AccountBytes: 100 * MiB} diff --git a/modules/nats/internal/keeper/plan.go b/modules/nats/internal/keeper/plan.go index 1c794c953..63574870e 100644 --- a/modules/nats/internal/keeper/plan.go +++ b/modules/nats/internal/keeper/plan.go @@ -129,6 +129,29 @@ type Plan struct { Entry catalogue.BusStateEntry `json:"entry"` } +// PartOf is the place an object has in its entry's binding, for a ledger: `history`, `state`, `index ` or `snapshot`; +// empty for an entry of one object (design 47 H2 H-A-634 (9), H-A-687 (3)). +func (p Plan) PartOf(o Object) string { + if p.Storage != catalogue.StorageLedger { + return "" + } + b := p.Binding + switch { + case o.Name == b.History && b.History != "": + return "history" + case o.Name == b.State && b.State != "": + return "state" + case b.History != "" && o.Name == b.History+"_snapshot": + return "snapshot" + } + for name, bucket := range b.Indexes { + if o.Name == bucket { + return "index " + name + } + } + return "" +} + // BusName is `_`, the name the mesh gives an entry on the bus (design 25 § 12.1). func BusName(module, local string) string { return module + Separator + local } From aa1a59c6bc289526fef114a4d62e473cf4e29b5e Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:27:17 +0100 Subject: [PATCH 09/13] G12 records-tools: gate_records_expiring and gate_records_follow_ends, gate_records says the ledger's ended-days, keeping days and soonest expires Builds: design 47 H2 H-A-634 (7), H-A-689 (2) (hq 999e6525, 95cf2052) --- .../cmd/mesh-delivery-gate/main.go | 7 + .../cmd/mesh-delivery-gate/record.go | 19 ++ .../cmd/mesh-delivery-gate/record_test.go | 121 +++++++ .../cmd/mesh-delivery-gate/recordends.go | 295 ++++++++++++++++++ .../cmd/mesh-delivery-gate/recordtools.go | 33 +- modules/mesh-delivery-gate/manifest.go | 23 ++ modules/mesh-delivery-gate/module.json | 2 + 7 files changed, 498 insertions(+), 2 deletions(-) create mode 100644 modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index 2f6b37b66..1dce628c6 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -16,6 +16,8 @@ import ( "sync" "time" + ownmanifest "mesh-delivery-gate" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -64,6 +66,11 @@ func main() { h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, Class: seatCatalog{ask: stdio.Ask}.Class} h.Records.Changed = h.recordChanged + var daysErr error + if h.Records.KeepingDays, h.Records.EndedDays, daysErr = ownmanifest.RecordsDays(); daysErr != nil { + logf("%v", daysErr) + os.Exit(1) + } h.Forge = seatGit{ask: stdio.Ask} h.Catalog = seatCatalog{ask: stdio.Ask} h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn, diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index ffda8c243..56c1aab04 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -266,6 +266,9 @@ type RecordLedger interface { Apply(instance, operation string, body any) (uint64, error) // Get is the instance's state and the sequence of its last operation; a nil state when it has none. Get(instance string) (json.RawMessage, uint64, error) + // Expires is when the bus ends the instance's state key, as `get` reads it from the bus (its time and the lifetime it + // carries); nil while the instance has not ended (design 47 H2 H-A-689 (2)). + Expires(instance string) (*time.Time, error) // Remove removes a record with its operations and its snapshot through the tool runner's ledger removal. Remove(instance string) error // Query is the instances a declared index names under key (`>` for the rest). @@ -344,6 +347,19 @@ func (sdkLedger) Watch(instances string, handle func(string, json.RawMessage) er return stdio.WatchLedger(RecordsLedger, instances, func(c buscalls.InstanceChange) error { return handle(c.Instance, c.State) }) } +// Expires is the `expires` the tool runner's `get` answers for the instance. +func (sdkLedger) Expires(instance string) (*time.Time, error) { + out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) + if err != nil { + return nil, err + } + var got buscalls.InstanceState + if err := json.Unmarshal(out, &got); err != nil { + return nil, fmt.Errorf("the ledger's state of %s is not readable: %w", instance, err) + } + return got.Expires, nil +} + func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) if err != nil { @@ -377,6 +393,9 @@ type Records struct { // TooLarge raises (raised) or clears record-too-large for an entry of the record named by its head's instance, the // finding's subject (§809; H-A-460); an empty instance clears every one held of the record (its end). nil raises none. TooLarge func(record, instance string, bytes int, raised bool) + // KeepingDays and EndedDays are the ledger's `max-age-days` and `ended-days` its manifest gives, said by the read tools + // (design 47 H2 H-A-634 (7)); zero says none. + KeepingDays, EndedDays int // held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read, // then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index 969f71897..22aa011d7 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -12,6 +12,8 @@ import ( "testing" "time" + ownmanifest "mesh-delivery-gate" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" @@ -222,6 +224,25 @@ func (f *ledgerFake) Query(index, key string) ([]string, error) { return out, nil } +// Expires is the end of the instance plus the manifest's ended-days, as `get` answers it; nil while it has no end. +func (f *ledgerFake) Expires(instance string) (*time.Time, error) { + if f.failOn == "expires" { + return nil, errors.New("the ledger is away") + } + var st struct { + Ended *RecordEnded `json:"ended"` + } + if raw := f.states[instance]; raw != nil { + _ = json.Unmarshal(raw, &st) + } + if st.Ended == nil { + return nil, nil + } + _, days, _ := ownmanifest.RecordsDays() + at := st.Ended.At.AddDate(0, 0, days) + return &at, nil +} + func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) { s := f.states[instance] if s == nil || string(s) == "null" { @@ -970,6 +991,106 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { t.Fatalf("with none open: %+v %v, log %d", again, err, len(log.took)) } }) + // H-A-634 (7), H-A-689 (2): gate_records_expiring names what the bus ends when, read from the bus, and no open record. + t.Run("gate_records_expiring names an ended record's expires thirty days after its end, and no open record", func(t *testing.T) { + rs, r, _ := setup(t) + rs.EndedDays, rs.KeepingDays = 30, 90 + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)})) + if err != nil { + t.Fatal(err) + } + if err := rs.End(r, "done", "jochen@shanks"); err != nil { + t.Fatal(err) + } + got, err := rs.Expiring(0, "") + lines, _ := got["records"].([]expiringLine) + want := at.AddDate(0, 0, 30).UTC().Format(time.RFC3339) + if err != nil || len(lines) != 1 || lines[0].Instance != r.Instance || lines[0].Expires != want || got["open"] != 1 || + lines[0].Movers != (counts{Counted: 1, Indexed: 1}) || got["capped"] != false { + t.Fatalf("%+v %v", got, err) + } + for _, l := range lines { + if l.Instance == open.Instance { + t.Fatal("an open record is named") + } + } + if short, _ := rs.Expiring(1, ""); short["total"] != 0 { + t.Fatalf("within one day: %+v", short) + } + if _, err := rs.Expiring(3651, ""); err == nil { + t.Fatal("within 3651 days was taken") + } + if _, err := rs.Expiring(0, "not-a-cursor"); err == nil { + t.Fatal("a cursor this tool never answered was taken") + } + if lines, _ := rs.Lines(); lines["soonest-expires"] != want || lines["ended-days"] != 30 || lines["keeping-days"] != 90 { + t.Fatalf("gate_records says %v, %v, %v", lines["soonest-expires"], lines["ended-days"], lines["keeping-days"]) + } + rs.Ledger.(*ledgerFake).failOn = "expires" + if got, _ := rs.Expiring(0, ""); got["unread"] == nil { + t.Fatalf("an expires that could not be read is not said: %+v", got) + } + }) + // H-A-634 (7): gate_records_follow_ends gives an ended record's movers and acts its end and takes it from an open one's, once + // the hand-act log took it. + t.Run("gate_records_follow_ends gives an ended record's entries its end and takes it from an open record's", func(t *testing.T) { + rs, r, _ := setup(t) + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + if err := rs.Act(r, RecordAct{ID: "a1", Act: "merge", Repository: "novox/app", Number: 1, At: at}); err != nil { + t.Fatal(err) + } + open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)})) + if err != nil { + t.Fatal(err) + } + if err := rs.SetMover(open, "mesh-y", "src2:f2", "main.48", "0.1.0"); err != nil { + t.Fatal(err) + } + if err := rs.End(r, "done", "jochen@shanks"); err != nil { + t.Fatal(err) + } + l := rs.Ledger.(*ledgerFake) + moverX, _ := MoverInstance(r.Milestone, "mesh-x") + actA, _ := ActInstance(r.Milestone, "a1") + moverY, _ := MoverInstance(open.Milestone, "mesh-y") + // The earlier gate left the entries as the end found them: the ended record's with none, the open one's with an end. + for inst, ended := range map[string]any{moverX: nil, actA: nil, moverY: RecordEnded{At: at, Why: "stale"}} { + if _, err := l.Apply(inst, OpEnd, map[string]any{"ended": ended}); err != nil { + t.Fatal(err) + } + } + log := &handActsFake{refuse: errors.New("no responders")} + if _, err := rs.FollowEnds("", log); err == nil { + t.Fatal("followed with no reason") + } + if _, err := rs.FollowEnds("the indexes were rebuilt", log); err == nil || len(l.history) == 0 || strings.HasSuffix(l.history[len(l.history)-1], moverX+" end") { + t.Fatalf("followed though the hand-act log refused it: %v", err) + } + endedOf := func(inst string) any { + var st map[string]any + _ = json.Unmarshal(l.states[inst], &st) + return st["ended"] + } + if endedOf(moverX) != nil || endedOf(moverY) == nil { + t.Fatal("an entry was written while no hand act was recorded") + } + log.refuse = nil + got, err := rs.FollowEnds("the indexes were rebuilt", log) + if err != nil || got["written"] != 3 || len(log.took) != 1 { + t.Fatalf("%+v %v (log %+v)", got, err, log.took) + } + if endedOf(moverX) == nil || endedOf(actA) == nil || endedOf(moverY) != nil { + t.Fatalf("the ends: %v %v %v", endedOf(moverX), endedOf(actA), endedOf(moverY)) + } + if again, err := rs.FollowEnds("again", log); err != nil || again["written"] != 0 { + t.Fatalf("a second pass wrote: %+v %v", again, err) + } + }) t.Run("gate_record_repair asks the owners for the outcomes an entry lacks, applies what they answer, and ends the record", func(t *testing.T) { rs, r, said := setup(t) owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go new file mode 100644 index 000000000..a8defac04 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go @@ -0,0 +1,295 @@ +package main + +// What the ledger's lifetimes make of the records, read and mended by hand (design 47 H2 H-A-634 (7), H-A-689): when an ended +// record's key goes (gate_records_expiring) and the end each of its movers and acts holds (gate_records_follow_ends), found +// through the ledger's indexes `movers` and `acts`. + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "strings" + "time" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + "git.novox.be/novox/mesh-sdk/go/views" +) + +// expiry is one ended record with the time the bus ends its key. +type expiry struct { + r *Record + expires time.Time +} + +// expiries are the ended records of list whose key the bus ends, each with its `expires` as the ledger's `get` reads it from the +// bus, the soonest first; a record whose `expires` cannot be read is named in unread with the error. +func (rs *Records) expiries(list []*Record) (out []expiry, unread []string) { + for _, r := range list { + if r.Ended == nil { + continue + } + at, err := rs.Ledger.Expires(r.Instance) + if err != nil { + unread = append(unread, r.Instance+": "+err.Error()) + continue + } + if at == nil { + continue + } + out = append(out, expiry{r: r, expires: at.UTC()}) + } + sort.SliceStable(out, func(i, j int) bool { + if !out[i].expires.Equal(out[j].expires) { + return out[i].expires.Before(out[j].expires) + } + return out[i].r.Instance < out[j].r.Instance + }) + return out, unread +} + +// expiringLine is one ended record as gate_records_expiring lists it: its movers and acts as the head counts them and as the +// ledger's indexes name them. +type expiringLine struct { + Instance string `json:"instance"` + Opened string `json:"opened"` + Ended string `json:"ended"` + Expires string `json:"expires"` + Movers counts `json:"movers"` + Acts counts `json:"acts"` +} + +type counts struct { + Counted int `json:"counted"` + Indexed int `json:"indexed"` +} + +// MaxWithinDays is the most days gate_records_expiring looks ahead. +const MaxWithinDays = 3650 + +// Expiring reads what goes when, removing nothing: every ended record whose key expires within `within` days (the ledger's +// ended-days when 0), the soonest first, and how many open records are kept whatever their age, at most views.PageBytes a page +// with capped, total and the cursor (design 47 H2 §811, H-A-634 (7), H-A-689 (2)). +func (rs *Records) Expiring(within int, next string) (map[string]any, error) { + if within == 0 { + within = rs.EndedDays + } + if within < 1 || within > MaxWithinDays { + return nil, fmt.Errorf("within is a number of days from 1 to %d", MaxWithinDays) + } + list, err := rs.Kept() + if err != nil { + return nil, err + } + open := 0 + for _, r := range list { + if r.Ended == nil { + open++ + } + } + until := rs.now().Add(time.Duration(within) * 24 * time.Hour) + var all []expiry + got, unread := rs.expiries(list) + for _, e := range got { + if !e.expires.After(until) { + all = append(all, e) + } + } + page, size, capped, cursor := []expiringLine{}, 0, false, "" + for _, e := range all { + if next != "" { + at, err := beforeExpiry(e, next) + if err != nil { + return nil, err + } + if at { + continue + } + } + line, err := rs.expiringLine(e) + if err != nil { + return nil, err + } + raw, _ := json.Marshal(line) + if size+len(raw) > views.PageBytes && len(page) > 0 { + capped = true + break + } + size += len(raw) + page, cursor = append(page, line), expiryCursor(e) + } + out := map[string]any{"within-days": within, "ended-days": rs.EndedDays, "records": page, "total": len(all), "open": open, + "capped": capped} + if capped { + out["next"] = cursor + } else { + out["next"] = "" + } + if len(unread) > 0 { + out["unread"] = unread + } + return out, nil +} + +func (rs *Records) expiringLine(e expiry) (expiringLine, error) { + ms, err := rs.Ledger.Query(MoversIndex, moversKey(e.r.Milestone)) + if err != nil { + return expiringLine{}, fmt.Errorf("the movers of the record %s cannot be read: %w", e.r.Instance, err) + } + as, err := rs.Ledger.Query(ActsIndex, moversKey(e.r.Milestone)) + if err != nil { + return expiringLine{}, fmt.Errorf("the acts of the record %s cannot be read: %w", e.r.Instance, err) + } + return expiringLine{Instance: e.r.Instance, Opened: timeText(&e.r.Opened), Ended: timeText(&e.r.Ended.At), + Expires: timeText(&e.expires), Movers: counts{Counted: e.r.MoverCount, Indexed: len(ms)}, + Acts: counts{Counted: len(e.r.Acts), Indexed: len(as)}}, nil +} + +// expiryCursor is the opaque cursor of a page of gate_records_expiring: the place of the last record it answered. +func expiryCursor(e expiry) string { + return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d|%s", e.expires.UnixNano(), e.r.Instance))) +} + +// beforeExpiry is whether e comes at or before the place the cursor names. +func beforeExpiry(e expiry, cursor string) (bool, error) { + raw, err := base64.RawURLEncoding.DecodeString(cursor) + at, inst, ok := strings.Cut(string(raw), "|") + n, perr := strconv.ParseInt(at, 10, 64) + if err != nil || !ok || perr != nil { + return false, fmt.Errorf("gate_records_expiring: %q is no cursor this tool answered", cursor) + } + if e.expires.UnixNano() != n { + return e.expires.UnixNano() < n, nil + } + return e.r.Instance <= inst, nil +} + +// soonest is the earliest `expires` among the ended records, "" when none ends or none could be read. +func (rs *Records) soonest(list []*Record) string { + got, _ := rs.expiries(list) + if len(got) == 0 { + return "" + } + return timeText(&got[0].expires) +} + +// sameEnded is whether two ends are one: the time, the reason, who and the nodes away. +func sameEnded(a, b *RecordEnded) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if !a.At.Equal(b.At) || a.Why != b.Why || a.By != b.By || len(a.Away) != len(b.Away) { + return false + } + for i := range a.Away { + if a.Away[i].Node != b.Away[i].Node || !a.Away[i].Since.Equal(b.Away[i].Since) { + return false + } + } + return true +} + +// followRecord gives every mover and act of the record, found through the indexes `movers` and `acts`, the record's end where +// they hold another, and takes it from those of an open record, by their `end` (H-A-634 (2), (7)): the instances it wrote. It +// stops at the first write that fails, naming it. +func (rs *Records) followRecord(r *Record) ([]string, error) { + var written []string + for _, index := range []string{MoversIndex, ActsIndex} { + insts, err := rs.Ledger.Query(index, moversKey(r.Milestone)) + if err != nil { + return written, fmt.Errorf("the %s of the record %s cannot be read: %w", index, r.Instance, err) + } + sort.Strings(insts) + for _, inst := range insts { + raw, _, err := rs.Ledger.Get(inst) + if err != nil { + return written, err + } + if raw == nil { + continue + } + var m Mover + var a RecordAct + var held, state any + var heldEnded *RecordEnded + if index == MoversIndex { + if err := json.Unmarshal(raw, &m); err != nil { + return written, fmt.Errorf("the mover %s is not readable: %w", inst, err) + } + heldEnded = m.Ended + m.Ended = copyEnded(r.Ended) + held, state = m.Ended, m + } else { + if err := json.Unmarshal(raw, &a); err != nil { + return written, fmt.Errorf("the act %s is not readable: %w", inst, err) + } + heldEnded = a.Ended + a.Ended = copyEnded(r.Ended) + held, state = a.Ended, a + } + if sameEnded(heldEnded, r.Ended) { + continue + } + var value any + if r.Ended != nil { + value = *held.(*RecordEnded) + } + if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, state); err != nil { + return written, fmt.Errorf("the end of %s is not written: %w", inst, err) + } + written = append(written, inst) + } + } + return written, nil +} + +// FollowEnds does by hand the pass the gate makes at its start: every record's movers and acts take the record's end, or none +// while it is open, read through the indexes. Recorded first in the hand-act log of the seat mesh-hand-acts: nothing is written +// when the log did not take it. It answers each record and the instances it wrote; a record whose pass failed is named with +// the error and the rest go on. +func (rs *Records) FollowEnds(why string, acts handActs) (map[string]any, error) { + if strings.TrimSpace(why) == "" { + return nil, errors.New("say why the ends are followed by hand, such as the indexes were rebuilt") + } + if acts == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was written") + } + list, err := rs.Kept() + if err != nil { + return nil, err + } + if _, err := acts.Record(meshhandactsclient.Request{What: "gave the movers and acts of every delivery record its end by hand", + Why: why, Cause: "gate_records_follow_ends", Verb: "follow-ends"}); err != nil { + return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was written: %w", err) + } + type line struct { + Record string `json:"record"` + Ended bool `json:"ended"` + Written []string `json:"written"` + Failed string `json:"failed,omitempty"` + } + lines, total, failed := []line{}, 0, 0 + for _, r := range list { + w, err := rs.followRecord(r) + if len(w) == 0 && err == nil { + continue + } + l := line{Record: r.Instance, Ended: r.Ended != nil, Written: w} + if l.Written == nil { + l.Written = []string{} + } + if err != nil { + l.Failed = err.Error() + failed++ + } + total += len(w) + lines = append(lines, l) + } + out := map[string]any{"records": lines, "read": len(list), "written": total, "failed": failed} + if failed > 0 { + return out, fmt.Errorf("the ends of %d records were not followed in full", failed) + } + return out, nil +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go index 31f294c02..9568424aa 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go @@ -102,8 +102,8 @@ func (rs *Records) Lines() (map[string]any, error) { } lines = append(lines, l) } - return map[string]any{"records": lines, "open": open, "kept": len(lines), - "fill": rs.fillLine()}, nil + return map[string]any{"records": lines, "open": open, "kept": len(lines), "ended-days": rs.EndedDays, + "keeping-days": rs.KeepingDays, "soonest-expires": rs.soonest(list), "fill": rs.fillLine()}, nil } // EndByHand ends one open record by hand, with the reason, recorded in the hand-act log first: nothing is ended when the @@ -216,6 +216,35 @@ func recordTools(h *Holder, acts handActs) []stdio.Tool { } return h.Records.Lines() }}, + {Name: "gate_records_expiring", + Description: "What the ledger's lifetimes take, removing nothing (design 47 H2 H-A-634 (7)): every ended delivery record whose " + + "key the bus ends within within days (1 to 3650, default the ledger's ended-days), the soonest first, with its key, " + + "when it opened and ended, its expires as the bus holds it, and its movers and acts as the head counts them and as the " + + "indexes name them; and how many open records are kept, whatever their age. At most 768 KB a page, with capped, total " + + "and the next page's cursor.", + Input: map[string]any{"type": "object", "properties": map[string]any{ + "within": map[string]any{"type": "integer", "description": "days from now, 1 to 3650; the ledger's ended-days when absent"}, + "next": str("the cursor the previous page answered")}}, + Run: func(a map[string]any) (any, error) { + if h.Records == nil { + return none() + } + within, _ := a["within"].(float64) + return h.Records.Expiring(int(within), strArg(a, "next")) + }}, + {Name: "gate_records_follow_ends", + Description: "Do by hand the pass the gate makes at its start (design 47 H2 H-A-634 (7)): give every mover and act of an ended " + + "delivery record that record's end where they hold another, and take it from those of an open record, found through " + + "the ledger's indexes movers and acts; answers each record and the instances it wrote. Recorded in the hand-act log " + + "of the seat mesh-hand-acts first.", + Input: map[string]any{"type": "object", "properties": map[string]any{ + "why": str("why the ends are followed by hand, in plain words")}, "required": []string{"why"}}, + Run: func(a map[string]any) (any, error) { + if h.Records == nil { + return none() + } + return h.Records.FollowEnds(strArg(a, "why"), acts) + }}, {Name: "gate_consumer", Description: "The delivery record's consumer of the step events: per family the events applied and refused " + "since the gate started, the last applied, and why the last was refused.", diff --git a/modules/mesh-delivery-gate/manifest.go b/modules/mesh-delivery-gate/manifest.go index a6214ed30..a20fab017 100644 --- a/modules/mesh-delivery-gate/manifest.go +++ b/modules/mesh-delivery-gate/manifest.go @@ -21,3 +21,26 @@ func Consumes() ([]string, error) { } return m.Consumes, nil } + +// RecordsDays are the days the manifest's ledger `records` keeps its history (`max-age-days`) and an ended instance's state +// (`ended-days`), as its `configuration` says them (design 47 H2 H-A-634 (7)); the gate's read tools say them beside the records. +func RecordsDays() (keeping, ended int, err error) { + var m struct { + Requires []struct { + Name string `json:"name"` + Configuration map[string]any `json:"configuration"` + } `json:"requires"` + } + if err := json.Unmarshal(manifest, &m); err != nil { + return 0, 0, fmt.Errorf("the gate's own manifest is not readable: %w", err) + } + for _, r := range m.Requires { + if r.Name != "records" { + continue + } + k, _ := r.Configuration["max-age-days"].(float64) + e, _ := r.Configuration["ended-days"].(float64) + return int(k), int(e), nil + } + return 0, 0, fmt.Errorf("the gate's own manifest asks for no ledger records") +} diff --git a/modules/mesh-delivery-gate/module.json b/modules/mesh-delivery-gate/module.json index 3784c9e0c..82a713dcb 100644 --- a/modules/mesh-delivery-gate/module.json +++ b/modules/mesh-delivery-gate/module.json @@ -490,6 +490,8 @@ "gate_record_end", "gate_record_repair", "gate_records", + "gate_records_expiring", + "gate_records_follow_ends", "gate_source", "gate_source_again", "gate_source_seed", From 5de68de0a09691ba1e4a7ba6cf5eda0efcff1de1 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:29:28 +0100 Subject: [PATCH 10/13] G13 indexes-kept: the gate keeps its ledger indexes by a watcher, builds an index behind again at its start before the pass of the ends, and raises index-behind and record-end-unwritten Builds: design 47 H2 H-A-690 (2) (3) (4), H-A-634 (2) (hq 95cf2052, 999e6525); H-A-706 (DMC-13) (hq 543e6963) --- .../cmd/mesh-delivery-gate/findings.go | 74 ++++++++- .../cmd/mesh-delivery-gate/main.go | 12 ++ .../cmd/mesh-delivery-gate/record.go | 46 ++++++ .../cmd/mesh-delivery-gate/record_test.go | 151 ++++++++++++++++++ .../cmd/mesh-delivery-gate/recordends.go | 11 ++ .../cmd/mesh-delivery-gate/recordevents.go | 3 + .../cmd/mesh-delivery-gate/recordindexes.go | 110 +++++++++++++ 7 files changed, 406 insertions(+), 1 deletion(-) create mode 100644 modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go index e9c5afe16..ef18861c1 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go @@ -29,7 +29,7 @@ type FindingWriter interface { // generated contract of the seat that defines it (A-17). It is started once the runtime serves (A-40). func NewFindingWriter() (*views.HeldWriter[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent], error) { return views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ - Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge}}) + Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge, IndexBehind, RecordEndUnwritten}}) } // recordTooLarge raises record-too-large for a delivery record's entry the gate refused over EntryLimit, its subject the @@ -69,3 +69,75 @@ func (h *Holder) recordTooLarge(record, instance string, bytes int, raised bool) h.Logf("[mesh-delivery] record-too-large of %s (%s) is not said: %v", instance, record, err) } } + +// The findings of the gate's ledger indexes and of an end not written (design 47 H2 H-A-690 (3), (4)). +const ( + // IndexBehind has the ledger index for its id: a call that keeps it failed, or `lag` still names it behind after its whole + // reindex; cleared at the next `lag` that names it not behind. + IndexBehind = "index-behind" + // RecordEndUnwritten has the record's instance for its id: the end of a mover or an act, or its emptying at a reopening, + // was not written; cleared when the pass for the record writes it. + RecordEndUnwritten = "record-end-unwritten" +) + +// indexBehind raises index-behind for a ledger index with why, or clears it (Records.IndexBehind). +func (h *Holder) indexBehind(index, why string, behind bool) { + if h.Findings == nil { + return + } + var err error + if behind { + now := h.Now().UTC() + err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: index, Kind: IndexBehind, + Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now, + Summary: fmt.Sprintf("the index %s of the delivery records is behind its history: %s", index, why), + Headline: "A delivery record index is behind", Subject: meshconditions.Subject{Scope: FindingScope, ID: index}, + Explanation: "The gate keeps the index by a call of the tool runner's repair reindex at each change; it clears at the " + + "next lag that names the index not behind (the gate's next start, or after ledger_reindex by hand)."}) + } else if h.heldFinding(IndexBehind, index) { + err = h.Findings.Clear(context.Background(), FindingScope, index, IndexBehind, "lag names the index not behind") + } + if err != nil && h.Logf != nil { + h.Logf("[mesh-delivery] index-behind of %s is not said: %v", index, err) + } +} + +// endUnwritten raises record-end-unwritten for a record, naming the instance and the error, or clears it +// (Records.EndUnwritten). +func (h *Holder) endUnwritten(record, instance string, cause error, raised bool) { + if h.Findings == nil { + return + } + var err error + if raised { + now := h.Now().UTC() + what := record + if instance != "" { + what = instance + } + err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: record, Kind: RecordEndUnwritten, + Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now, + Summary: fmt.Sprintf("the end of %s of the record %s is not written: %v", what, record, cause), + Headline: "A delivery record's end is not written to all its entries", Subject: meshconditions.Subject{Scope: FindingScope, ID: record}, + Explanation: "A mover or an act of the record does not hold the record's end, so its key does not take the lifetime of the " + + "end. The gate writes it at the record's next event, or at its next start, and the finding clears when it is written."}) + } else if h.heldFinding(RecordEndUnwritten, record) { + err = h.Findings.Clear(context.Background(), FindingScope, record, RecordEndUnwritten, "the end is written to every entry") + } + if err != nil && h.Logf != nil { + h.Logf("[mesh-delivery] record-end-unwritten of %s is not said: %v", record, err) + } +} + +// heldFinding is whether the writer holds the finding of the kind under the id. +func (h *Holder) heldFinding(kind, id string) bool { + if h.Findings == nil { + return false + } + for _, f := range h.Findings.Held() { + if f.Scope == FindingScope && f.Kind == kind && f.ID == id { + return true + } + } + return false +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index 1dce628c6..7a49b57f2 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -66,6 +66,8 @@ func main() { h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, Class: seatCatalog{ask: stdio.Ask}.Class} h.Records.Changed = h.recordChanged + h.Records.IndexBehind, h.Records.EndUnwritten = h.indexBehind, h.endUnwritten + h.Records.EndPending = func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) } var daysErr error if h.Records.KeepingDays, h.Records.EndedDays, daysErr = ownmanifest.RecordsDays(); daysErr != nil { logf("%v", daysErr) @@ -105,6 +107,16 @@ func main() { // tick, no forge poll, no reconcile loop. Each step is retried, each failure said, never given up on quietly. func run(h *Holder, l *listening) { <-stdio.Served() // Serve first: the state is reached through it, and an event is heard from as soon as it serves + // The indexes first: built again where behind, each record's movers and acts given its end, then watched (H-A-690 (2)). + for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { + err := h.Records.KeepIndexes() + if err == nil { + break + } + l.set("not yet: " + err.Error()) + logf("[mesh-delivery] the record indexes are not kept yet (%v); asking again in %s", err, wait) + time.Sleep(wait) + } go h.Work() for _, pattern := range followed { pattern := pattern diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index 56c1aab04..58a428756 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -271,6 +271,11 @@ type RecordLedger interface { Expires(instance string) (*time.Time, error) // Remove removes a record with its operations and its snapshot through the tool runner's ledger removal. Remove(instance string) error + // Reindex builds a declared index again from the history: of the one instance only, or whole when instance is empty + // (buscalls.LedgerReindex, design 47 H2 H-A-690 (1)); the entries it wrote. + Reindex(index, instance string) (int, error) + // Lag is every instance and index behind its history (buscalls.LedgerLag). + Lag() (buscalls.Lagged, error) // Query is the instances a declared index names under key (`>` for the rest). Query(index, key string) ([]string, error) // Watch hands handle the current state of each instance `instances` names (an instance, `*` for one name, `>` for the @@ -326,6 +331,32 @@ func (sdkLedger) Remove(instance string) error { return nil } +// Reindex is the tool runner's repair `reindex` of the gate's own ledger. +func (sdkLedger) Reindex(index, instance string) (int, error) { + out, err := ledgerCall(buscalls.LedgerReindex, buscalls.ReindexRequest{Ledger: RecordsLedger, Index: index, Instance: instance}) + if err != nil { + return 0, err + } + var got buscalls.Repaired + if err := json.Unmarshal(out, &got); err != nil { + return 0, fmt.Errorf("the ledger's answer to the reindex of %s is not readable: %w", index, err) + } + return got.Written, nil +} + +// Lag is the tool runner's `lag` of the gate's own ledger. +func (sdkLedger) Lag() (buscalls.Lagged, error) { + var got buscalls.Lagged + out, err := ledgerCall(buscalls.LedgerLag, buscalls.LedgerRequest{Ledger: RecordsLedger}) + if err != nil { + return got, err + } + if err := json.Unmarshal(out, &got); err != nil { + return got, fmt.Errorf("the ledger's answer to lag is not readable: %w", err) + } + return got, nil +} + func (sdkLedger) Query(index, key string) ([]string, error) { out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key}) if err != nil { @@ -396,6 +427,12 @@ type Records struct { // KeepingDays and EndedDays are the ledger's `max-age-days` and `ended-days` its manifest gives, said by the read tools // (design 47 H2 H-A-634 (7)); zero says none. KeepingDays, EndedDays int + // IndexBehind raises (behind) or clears the finding index-behind for a ledger index, with why (design 47 H2 H-A-690 (3)); + // nil says none. EndUnwritten raises (raised) or clears record-end-unwritten for a record, naming the instance and the + // error (H-A-690 (4)); EndPending says whether the record holds one, so its next event finishes it; nil: none held. + IndexBehind func(index, why string, behind bool) + EndUnwritten func(record, instance string, err error, raised bool) + EndPending func(record string) bool // held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read, // then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in @@ -680,6 +717,15 @@ func (rs *Records) ByKey(branch string, source int64) (*Record, error) { // the gate keeps as it writes it when it holds it, so a write through it is seen by every reader, else read from the // ledger; nil when none is kept. func (rs *Records) ByMilestone(milestone string) (*Record, error) { + r, err := rs.byMilestone(milestone) + if r != nil && err == nil && rs.EndPending != nil && rs.EndPending(r.Instance) { + // The next event of a record whose end was not written in full finishes it, by the pass for it alone (H-A-690 (4)). + _, _ = rs.followRecord(r) + } + return r, err +} + +func (rs *Records) byMilestone(milestone string) (*Record, error) { inst, err := RecordInstance(milestone) if err != nil { return nil, err diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index 22aa011d7..bdfb449c3 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -36,6 +36,13 @@ type ledgerFake struct { failOn string // fill is what Fill answers; nil, the ledger says no fill. fill *buscalls.Fill + // lagged is what Lag answers; a whole Reindex of an index takes it out unless stuck names it. calls is every reindex and every + // `end` applied, in order; reindexErr fails every Reindex; endErr fails the `end` of an instance. + lagged buscalls.Lagged + stuck string + calls []string + reindexErr error + endErr string // watchers are the watches the gate started, each told of every change to an instance its pattern names. watchers []ledgerWatch } @@ -112,10 +119,36 @@ func newLedgerFake(t *testing.T) *ledgerFake { return f } +// Reindex records the call; a whole one makes the index not behind, unless it is stuck. +func (f *ledgerFake) Reindex(index, instance string) (int, error) { + f.calls = append(f.calls, "reindex "+index+" "+instance) + if f.reindexErr != nil { + return 0, f.reindexErr + } + if instance == "" && index != f.stuck { + var keep []buscalls.IndexLag + for _, l := range f.lagged.Indexes { + if l.Index != index { + keep = append(keep, l) + } + } + f.lagged.Indexes = keep + } + return 3, nil +} + +func (f *ledgerFake) Lag() (buscalls.Lagged, error) { return f.lagged, nil } + func (f *ledgerFake) Apply(instance, operation string, body any) (uint64, error) { if f.failOn == operation { return 0, fmt.Errorf("the ledger is away") } + if operation == OpEnd { + f.calls = append(f.calls, "end "+instance) + if f.endErr == instance { + return 0, fmt.Errorf("the ledger did not take the end of %s", instance) + } + } ty, ok := f.types[strings.SplitN(instance, "/", 2)[0]] if !ok { return 0, fmt.Errorf("no type for %s", instance) @@ -1319,3 +1352,121 @@ func opening(branch string, source int64, heads map[string]string) RecordOpening } func ptrTime(t time.Time) *time.Time { return &t } + +// H-A-690 (2) to (4): the gate keeps its ledger's indexes by a watcher, builds an index behind again whole at its start before the +// pass of the ends, says what fails as index-behind and record-end-unwritten, and finishes an end at the record's next event. +func TestTheGateKeepsItsLedgerIndexesByAWatcher(t *testing.T) { + at := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + heads := map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)} + setup := func(t *testing.T) (*Records, *Holder, *ledgerFake, *Record, string) { + l := newLedgerFake(t) + h := &Holder{Findings: &findingsFake{held: map[string]meshconditions.Finding{}}, Now: func() time.Time { return at }} + rs := &Records{Ledger: l, Now: func() time.Time { return at }, IndexBehind: h.indexBehind, EndUnwritten: h.endUnwritten, + EndPending: func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) }} + r, _, err := rs.Open(opening("main", 47, heads)) + if err != nil { + t.Fatal(err) + } + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + inst, _ := MoverInstance(r.Milestone, "mesh-x") + return rs, h, l, r, inst + } + count := func(l *ledgerFake, call string) (n int) { + for _, c := range l.calls { + if c == call { + n++ + } + } + return n + } + t.Run("a change the watch hands makes one reindex naming it, and the current states none", func(t *testing.T) { + rs, _, l, r, mover := setup(t) + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if len(l.calls) != 0 { + t.Fatalf("the start called %v", l.calls) + } + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.48", "0.1.1"); err != nil { + t.Fatal(err) + } + l.change(mover) + if got := count(l, "reindex movers "+mover); got != 1 || len(l.calls) != 1 { + t.Fatalf("calls %v", l.calls) + } + l.states[mover] = json.RawMessage("null") + l.change(mover) // a key gone by its lifetime needs no call + if len(l.calls) != 1 { + t.Fatalf("a key gone called %v", l.calls) + } + }) + t.Run("an index behind is built again whole before the pass of the ends, and still behind it is raised", func(t *testing.T) { + rs, h, l, r, mover := setup(t) + if err := rs.End(r, "done", "x"); err != nil { + t.Fatal(err) + } + if _, err := l.Apply(mover, OpEnd, map[string]any{"ended": nil}); err != nil { // the mover lost its end + t.Fatal(err) + } + l.calls = nil + l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}} + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if len(l.calls) < 2 || l.calls[0] != "reindex movers " || l.calls[1] != "end "+mover { + t.Fatalf("the start called %v", l.calls) + } + if h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("an index built again is still raised") + } + l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}} + l.stuck = MoversIndex + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if !h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("an index still behind after its whole reindex is not raised") + } + l.stuck, l.lagged = "", buscalls.Lagged{} + if err := rs.KeepIndexes(); err != nil || h.heldFinding(IndexBehind, MoversIndex) { + t.Fatalf("lag naming it not behind did not clear it: %v", err) + } + }) + t.Run("a failed call raises index-behind and is made again at the instance's next change", func(t *testing.T) { + rs, h, l, _, mover := setup(t) + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + l.reindexErr = errors.New("the tool runner is away") + l.change(mover) + if !h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("a failed reindex is not raised") + } + l.reindexErr = nil + l.change(mover) + if got := count(l, "reindex movers "+mover); got != 2 { + t.Fatalf("calls %v", l.calls) + } + }) + t.Run("a failed end raises record-end-unwritten, and the record's next event writes it and clears it", func(t *testing.T) { + rs, h, l, r, mover := setup(t) + l.endErr = mover + if err := rs.End(r, "done", "x"); err != nil { + t.Fatal(err) // the record's end stands + } + if !h.heldFinding(RecordEndUnwritten, r.Instance) || r.Ended == nil { + t.Fatal("a failed end of an entry is not raised") + } + l.endErr = "" + if got, err := rs.ByMilestone(r.Milestone); err != nil || got == nil { + t.Fatalf("%v %v", got, err) + } + var st struct{ Ended *RecordEnded } + _ = json.Unmarshal(l.states[mover], &st) + if st.Ended == nil || h.heldFinding(RecordEndUnwritten, r.Instance) { + t.Fatalf("the next event did not write the end (%v) or clear the finding", st.Ended) + } + }) +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go index a8defac04..8d3570152 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go @@ -195,6 +195,17 @@ func sameEnded(a, b *RecordEnded) bool { // they hold another, and takes it from those of an open record, by their `end` (H-A-634 (2), (7)): the instances it wrote. It // stops at the first write that fails, naming it. func (rs *Records) followRecord(r *Record) ([]string, error) { + written, err := rs.followEnds(r) + if rs.EndUnwritten != nil { + rs.EndUnwritten(r.Instance, "", err, err != nil) + } + if err != nil { + rs.log("the record %s: its movers and acts do not all hold its end: %v", r.Instance, err) + } + return written, err +} + +func (rs *Records) followEnds(r *Record) ([]string, error) { var written []string for _, index := range []string{MoversIndex, ActsIndex} { insts, err := rs.Ledger.Query(index, moversKey(r.Milestone)) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index bfe6a8d94..3818199b4 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -243,6 +243,9 @@ func (rs *Records) endEntries(r *Record, e *RecordEnded) { if rs.Logf != nil { rs.Logf("[mesh-delivery] the record %s: the end of its entry %s is not written: %v", r.Instance, instance, err) } + if rs.EndUnwritten != nil { + rs.EndUnwritten(r.Instance, instance, err, true) + } } modules := make([]string, 0, len(r.movers)) for module := range r.movers { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go new file mode 100644 index 000000000..29d553034 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go @@ -0,0 +1,110 @@ +package main + +// The gate keeps the ledger's indexes `movers` and `acts` by a watcher of its own process (design 47 H2 H-A-690 (2) to (4); ADR +// 0597 §4): the tool runner stays the one writer of index keys, the gate asks it, by the repair `reindex`, for each instance +// that changed; at its start it reads `lag`, builds again whole each index behind, and gives every record's movers and acts its +// end before it follows the changes. + +import ( + "encoding/json" + "fmt" + "sync/atomic" + + "git.novox.be/novox/mesh-sdk/go/buscalls" +) + +// KeepIndexes is the gate's start of its indexes: `lag`, a whole `reindex` of each index it names behind (said with the count +// written), the finding index-behind for an index still behind after it and its clearing for one not, the pass of the ends over +// every record, then a watch of the ledger's `mover/>` and `act/>` that makes one `reindex` naming each instance a change +// hands after the current states. What fails is said and made again at the next change or the next start, never given up. +func (rs *Records) KeepIndexes() error { + rs.reindexBehind() + list, err := rs.Kept() + if err != nil { + return err + } + for _, r := range list { + if _, err := rs.followRecord(r); err != nil { + continue // said, and the finding raised, by the pass + } + } + var caught atomic.Bool + watch := func(index string) func(string, json.RawMessage) error { + return func(instance string, state json.RawMessage) error { + // The current states are not changes; a key gone by its lifetime (or removed) has no index key left to write. + if !caught.Load() || len(state) == 0 || string(state) == "null" { + return nil + } + rs.reindexInstance(index, instance) + return nil + } + } + for _, w := range []struct{ prefix, index string }{{TypeMover + "/>", MoversIndex}, {TypeAct + "/>", ActsIndex}} { + if err := rs.Ledger.Watch(w.prefix, watch(w.index)); err != nil { + return fmt.Errorf("the ledger's %s cannot be watched: %w", w.prefix, err) + } + } + caught.Store(true) + return nil +} + +// reindexInstance asks the tool runner to write one instance's entries of an index again; a call that fails is said and +// raises index-behind, and is made again at that instance's next change (H-A-690 (2), (3)). +func (rs *Records) reindexInstance(index, instance string) { + if _, err := rs.Ledger.Reindex(index, instance); err != nil { + rs.log("the index %s is not kept for %s: %v", index, instance, err) + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("the reindex of %s failed: %v", instance, err), true) + } + } +} + +// reindexBehind reads `lag` and builds again whole each index it names behind; an index still behind after it is raised as +// index-behind, one `lag` does not name is cleared (H-A-690 (2), (3)). +func (rs *Records) reindexBehind() { + lag, err := rs.Ledger.Lag() + if err != nil { + rs.log("the ledger's lag cannot be read, so no index is built again at this start: %v", err) + return + } + for _, index := range []string{MoversIndex, ActsIndex} { + if !behind(lag, index) { + if rs.IndexBehind != nil { + rs.IndexBehind(index, "", false) + } + continue + } + n, err := rs.Ledger.Reindex(index, "") + if err != nil { + rs.log("the index %s is behind and its reindex failed: %v", index, err) + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("the whole reindex failed: %v", err), true) + } + continue + } + rs.log("the index %s was behind its history and is built again: %d entries written", index, n) + again, err := rs.Ledger.Lag() + switch { + case err != nil: + rs.log("the ledger's lag cannot be read after the reindex of %s: %v", index, err) + case behind(again, index): + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("still behind its history after a whole reindex (%d entries written)", n), true) + } + default: + if rs.IndexBehind != nil { + rs.IndexBehind(index, "", false) + } + } + } +} + +// behind is whether lag names the index behind its history. +func behind(l buscalls.Lagged, index string) bool { + for _, i := range l.Indexes { + if i.Index == index && i.Behind > 0 { + return true + } + } + return false +} From 8aef19934ed03ca6f7ba780a877d6995bd76d0e1 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:33:19 +0100 Subject: [PATCH 11/13] G15 recreate-in-place: a recreate reads the account's room first, changes each object in place where the bus takes it, makes empty only a retention that changes, stops at a refused change; the ask names each object Builds: design 47 H2 H-A-686 (1) (2) (3), H-A-634 (3), H-A-706 (DQ-42) (hq 95cf2052, 999e6525, 543e6963) --- modules/nats/cmd/nats-tools/broker.go | 5 +- .../cmd/nats-tools/keeper_integration_test.go | 70 +++++++++- modules/nats/cmd/nats-tools/main.go | 11 ++ modules/nats/cmd/nats-tools/recreateask.go | 127 ++++++++++++++++++ modules/nats/cmd/nats-tools/requests.go | 17 ++- modules/nats/cmd/nats-tools/requests_test.go | 39 +++++- modules/nats/internal/keeper/jetstream.go | 12 ++ modules/nats/internal/keeper/keeper.go | 2 +- modules/nats/internal/keeper/keeper_test.go | 73 +++++++++- modules/nats/internal/keeper/plan.go | 13 +- modules/nats/internal/keeper/requests.go | 84 ++++++++++-- 11 files changed, 427 insertions(+), 26 deletions(-) create mode 100644 modules/nats/cmd/nats-tools/recreateask.go diff --git a/modules/nats/cmd/nats-tools/broker.go b/modules/nats/cmd/nats-tools/broker.go index c691fc721..14f4c9f36 100644 --- a/modules/nats/cmd/nats-tools/broker.go +++ b/modules/nats/cmd/nats-tools/broker.go @@ -66,8 +66,9 @@ func capsOf(all map[string]keeper.Asked, status func() (keeper.Status, error)) * type busStream struct { Config jetstream.StreamConfig `json:"config"` State struct { - Messages uint64 `json:"messages"` - Bytes uint64 `json:"bytes"` + Messages uint64 `json:"messages"` + Bytes uint64 `json:"bytes"` + FirstTS time.Time `json:"first_ts"` } `json:"state"` } diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index b6ebc4a0a..3e689c7cd 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -401,7 +401,7 @@ func TestTheBusModuleRunsWhole(t *testing.T) { put(keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused"}) eventually(t, "the drop with no ask refused", func() bool { return strings.Contains(get("r1").Error, "operator's warrant") }) r := keeper.Request{ID: "r2", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused", At: time.Now(), AskExpires: time.Now().Add(keeper.AskLasts)} - a, _ := askFor(r) + a, _ := askFor(r, "") r.Ask = a.ID record := func(w *oc.Warrant) { raw, _ := json.Marshal(map[string]any{"asker": keeper.Module, "ask": a, "state": "open", "warrant": w}) @@ -757,3 +757,71 @@ func entry(name, storage, template string, options map[string]string) catalogue. } return e } + +// Design 47 H2 H-A-686: the change the bus takes in place keeps what the object holds. On the real bus, a stream holding +// messages is changed to a shorter age, a lifetime per message and a refusal when full, keeps its messages, and takes a lifetime +// on its next write; a bucket changed to a lifetime per key keeps its keys. +func TestTheBusTakesARecreatesChangeInPlace(t *testing.T) { + s, err := server.NewServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir(), NoLog: true, NoSigs: true}) + if err != nil { + t.Fatal(err) + } + go s.Start() + if !s.ReadyForConnections(5 * time.Second) { + t.Fatal("the server did not start") + } + defer s.Shutdown() + nc, err := nats.Connect(s.ClientURL()) + if err != nil { + t.Fatal(err) + } + defer nc.Close() + js, _ := jetstream.New(nc) + ctx := context.Background() + bus := keeper.JetStream{JS: js} + stream := keeper.Object{Kind: keeper.KindStream, Name: "m_events", Subjects: []string{"m.events.>"}, + Settings: keeper.Settings{MaxBytes: 4 << 20, MaxAgeSeconds: 0, Discard: keeper.DiscardOld}} + bucket := keeper.Object{Kind: keeper.KindBucket, Name: "m_state", Settings: keeper.Settings{MaxBytes: 4 << 20, History: 1, Discard: keeper.DiscardNew}} + for _, o := range []keeper.Object{stream, bucket} { + if err := bus.Create(ctx, o); err != nil { + t.Fatal(err) + } + } + for i := range 5 { + if _, err := js.Publish(ctx, fmt.Sprintf("m.events.%d", i), []byte("x")); err != nil { + t.Fatal(err) + } + } + kv, _ := js.KeyValue(ctx, "m_state") + for _, k := range []string{"a", "b"} { + if _, err := kv.Put(ctx, k, []byte("v")); err != nil { + t.Fatal(err) + } + } + stream.Settings = keeper.Settings{MaxBytes: 4 << 20, MaxAgeSeconds: 3600, Discard: keeper.DiscardNew, KeyTTL: true} + bucket.Settings.KeyTTL = true + for _, o := range []keeper.Object{stream, bucket} { + if err := bus.Update(ctx, o); err != nil { + t.Fatalf("%s: %v", o.Stream(), err) + } + } + held, fill, _, err := bus.Held(ctx, stream) + if err != nil || fill.Messages != 5 || held.MaxAgeSeconds != 3600 || held.Discard != keeper.DiscardNew || !held.KeyTTL { + t.Fatalf("the stream holds %+v, %+v (%v): it keeps its messages and takes the settings", held, fill, err) + } + msg := &nats.Msg{Subject: "m.events.9", Data: []byte("x"), Header: nats.Header{"Nats-TTL": []string{"60s"}}} + if _, err := js.PublishMsg(ctx, msg); err != nil { + t.Fatalf("a message with a lifetime of its own is refused after the change: %v", err) + } + if _, fill, _, _ := bus.Held(ctx, bucket); fill.Messages != 2 { + t.Fatalf("the bucket holds %d keys, want 2", fill.Messages) + } + if _, err := kv.Create(ctx, "c", []byte("v"), jetstream.KeyTTL(time.Minute)); err != nil { + t.Fatalf("a key with a lifetime of its own is refused after the change: %v", err) + } + // A held lifetime is never turned off by an Update: the bus would refuse it, and the keeper's comparison matches it. + stream.Settings.KeyTTL = false + if err := bus.Update(ctx, stream); err != nil { + t.Fatalf("an ask of no lifetime over a held one: %v", err) + } +} diff --git a/modules/nats/cmd/nats-tools/main.go b/modules/nats/cmd/nats-tools/main.go index 7e963be2d..9bd48ae92 100644 --- a/modules/nats/cmd/nats-tools/main.go +++ b/modules/nats/cmd/nats-tools/main.go @@ -197,6 +197,17 @@ func allTools() []stdio.Tool { out = append(out, keeperHealthTool(StatusInState, HeldInState, jsz)) out = append(out, readTools(jsz, LiveMsgGet(LiveBus()))...) rs := RequestsInState() + rs.Explain = func(r keeper.Request) (string, error) { + held, err := HeldInState() + if err != nil { + return "", err + } + raw, err := jsz() + if err != nil { + return "", err + } + return recreateWords(held, StatusInState, raw, time.Now(), LiveOlderThan(LiveBus()), r.Module, r.Local) + } out = append(out, snapshotListTool(rs, bundleKeepDays)...) out = append(out, plansTool(PlansInState)) return append(out, requestTools(rs)...) diff --git a/modules/nats/cmd/nats-tools/recreateask.go b/modules/nats/cmd/nats-tools/recreateask.go new file mode 100644 index 000000000..681a873cd --- /dev/null +++ b/modules/nats/cmd/nats-tools/recreateask.go @@ -0,0 +1,127 @@ +package main + +// What the operator's ask for a recreate names (design 47 H2 H-A-686 (3), H-A-706 on DQ-42): per object whether it is changed in +// place or made again empty, its held and asked settings, the messages, bytes and oldest message's time it holds, read when +// the ask is raised, and what the change removes; and the room the caps it asks need on the bus's account. + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/nats-io/nats.go/jetstream" + + "nats-tools/internal/keeper" +) + +// olderThan counts the messages of a stream stored before a time. +type olderThan func(stream string, before time.Time) (uint64, error) + +// LiveOlderThan counts them on the bus by an ordered consumer that starts at the time: the messages before it are those the +// stream holds less the ones the consumer has pending. +func LiveOlderThan(bus Bus) olderThan { + return func(stream string, before time.Time) (uint64, error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + js, closeBus, err := bus(ctx) + if err != nil { + return 0, err + } + defer closeBus() + s, err := js.Stream(ctx, stream) + if err != nil { + return 0, err + } + info, err := s.Info(ctx) + if err != nil { + return 0, err + } + c, err := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{DeliverPolicy: jetstream.DeliverByStartTimePolicy, + OptStartTime: &before, AckPolicy: jetstream.AckNonePolicy, InactiveThreshold: time.Minute}) + if err != nil { + return 0, err + } + ci, err := c.Info(ctx) + if err != nil { + return 0, err + } + _ = s.DeleteConsumer(ctx, ci.Name) + if info.State.Msgs < ci.NumPending { + return 0, nil + } + return info.State.Msgs - ci.NumPending, nil + } +} + +func settingsWords(s keeper.Settings) string { + age := "no age" + if s.MaxAgeSeconds > 0 { + age = "age " + (time.Duration(s.MaxAgeSeconds) * time.Second).String() + } + return fmt.Sprintf("cap %d MiB, %s, history %d, discard %s, lifetime %v", s.MaxBytes/keeper.MiB, age, s.History, s.Discard, s.KeyTTL) +} + +// recreateWords says, for each object of the entry, what the rebuild does and removes, read from the entry the keeper made and +// the bus's streams as the monitoring endpoint answers them; and the room its caps need. +func recreateWords(held map[string]keeper.Asked, status func() (keeper.Status, error), jsz []byte, now time.Time, older olderThan, + module, local string) (string, error) { + m, ok := held[module].Made[local] + if !ok || !m.Created { + return "", fmt.Errorf("the bus module made no %s of %s", local, module) + } + streams, err := streamsHeld(jsz) + if err != nil { + return "", err + } + var lines []string + var caps int64 + for _, o := range m.Plan.Objects { + caps += o.Settings.MaxBytes + s, found := streams[o.Stream()] + if !found { + lines = append(lines, fmt.Sprintf("%s: the bus holds none, so it is made, holding nothing to remove", o.Stream())) + continue + } + have := keeper.SettingsOf(o.Kind, s.Config) + inPlace := have.WorkQueue == o.Settings.WorkQueue + oldest := "none" + if !s.State.FirstTS.IsZero() && s.State.Messages > 0 { + oldest = s.State.FirstTS.UTC().Format(time.RFC3339) + } + how, removes := "changed in place", []string{} + if !inPlace { + how, removes = "made again empty, its retention changes", []string{fmt.Sprintf("every message (%d)", s.State.Messages)} + } else { + if over := int64(s.State.Bytes) - o.Settings.MaxBytes; over > 0 { + removes = append(removes, fmt.Sprintf("the oldest messages beyond the cap, %d bytes over it", over)) + } + if age := o.Settings.MaxAgeSeconds; age > 0 && (have.MaxAgeSeconds == 0 || age < have.MaxAgeSeconds) && s.State.Messages > 0 { + cutoff := now.Add(-time.Duration(age) * time.Second) + switch { + case !s.State.FirstTS.Before(cutoff): + removes = append(removes, "no message older than the age") + case older == nil: + removes = append(removes, "the messages older than the age, not counted here") + default: + n, err := older(o.Stream(), cutoff) + if err != nil { + return "", fmt.Errorf("the messages of %s older than the age cannot be counted: %w", o.Stream(), err) + } + removes = append(removes, fmt.Sprintf("%d messages older than the age", n)) + } + } + } + if len(removes) == 0 { + removes = []string{"nothing"} + } + lines = append(lines, fmt.Sprintf("%s %s; held {%s}, asked {%s}; it holds %d messages, %d bytes, the oldest from %s; the change removes: %s", + o.Stream(), how, settingsWords(have), settingsWords(o.Settings), s.State.Messages, s.State.Bytes, oldest, strings.Join(removes, ", "))) + } + room := fmt.Sprintf("The caps it asks sum to %d MiB", caps/keeper.MiB) + if st, err := status(); err == nil && st.Limits.AccountBytes > 0 { + need := caps + keeper.CapSum(held, module, local) + st.OldBytes + room += fmt.Sprintf(", %d MiB with every other cap of the bus, against the account's storage limit of %d MiB", need/keeper.MiB, st.Limits.AccountBytes/keeper.MiB) + } + return room + ". Per object: " + strings.Join(lines, " | "), nil +} diff --git a/modules/nats/cmd/nats-tools/requests.go b/modules/nats/cmd/nats-tools/requests.go index b0902d809..0c01270c7 100644 --- a/modules/nats/cmd/nats-tools/requests.go +++ b/modules/nats/cmd/nats-tools/requests.go @@ -43,6 +43,9 @@ type requestStore struct { // Standing reads the router's record of one of this module's asks, by its id, or nil while it holds none (design 47 // H-A-237, H-A-239). Standing func(askID string) (*stdio.StateEntry, error) + // Explain says what a recreate of the request's entry does to each of its objects and removes, and the room its caps need, + // read when the ask is raised (design 47 H2 H-A-686 (3), H-A-706); nil says none. + Explain func(r keeper.Request) (string, error) } // RequestsInState is the store through the runtime that launched this bundle: one watch of the state requests for the @@ -175,7 +178,7 @@ func askExpiry(a map[string]any) (time.Duration, error) { // the approve level until a channel carries a destroy answer, ending at the request's AskExpires, the caller's (design // 47 H-A-237); the bend ends with the research effort that designs the channel carrying the destroy proof (design 47 H2 // §813 (11)). -func askFor(r keeper.Request) (oc.Ask, error) { +func askFor(r keeper.Request, explained string) (oc.Ask, error) { binds, err := occ.ActDigest(r.Act()) if err != nil { return oc.Ask{}, err @@ -187,7 +190,7 @@ func askFor(r keeper.Request) (oc.Ask, error) { About: keeper.ConditionKey(map[string]string{keeper.VerbDrop: "orphaned", keeper.VerbRecreate: "drifted"}[r.Verb], r.Module, r.Local), Headline: fmt.Sprintf("%s's kept data %s: %s it?", r.Module, r.Local, what), Explanation: fmt.Sprintf("%s asks to %s %s on the bus, %s. A snapshot of it is taken first; its data is lost from the bus.", - r.Caller, what, name, r.Why), + r.Caller, what, name, r.Why) + explained, Options: []oc.Option{ {ID: "go", Label: strings.ToUpper(what[:1]) + what[1:], Does: fmt.Sprintf("%s %s after a snapshot", what, name), Level: occ.Approve, Binds: binds}, {ID: "keep", Label: "Keep it", Does: "nothing is removed", Level: occ.Acknowledge}, @@ -289,7 +292,15 @@ func requestTools(rs requestStore) []stdio.Tool { return nil, err } r.AskExpires = r.At.Add(lasts) - ask, err := askFor(r) + var explained string + if verb == keeper.VerbRecreate && rs.Explain != nil { + words, err := rs.Explain(r) + if err != nil { + return nil, fmt.Errorf("the ask cannot name what the rebuild changes and removes, so nothing is asked: %w", err) + } + explained = " " + words + } + ask, err := askFor(r, explained) if err != nil { return nil, err } diff --git a/modules/nats/cmd/nats-tools/requests_test.go b/modules/nats/cmd/nats-tools/requests_test.go index b7c380fbb..264af8faa 100644 --- a/modules/nats/cmd/nats-tools/requests_test.go +++ b/modules/nats/cmd/nats-tools/requests_test.go @@ -156,7 +156,7 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) { func TestTheAskLastsTheCallersExpiryAndTheToolSaysTheRoutersStanding(t *testing.T) { now := time.Now() r := keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Why: "unused", Caller: "person.jo", AskExpires: now.Add(1430 * time.Minute)} - a, err := askFor(r) + a, err := askFor(r, "") if err != nil { t.Fatal(err) } @@ -200,3 +200,40 @@ func TestTheAskLastsTheCallersExpiryAndTheToolSaysTheRoutersStanding(t *testing. } } } + +// Design 47 H2 H-A-686 (3), H-A-706 (DQ-42): the ask of a recreate names, per object, in place or made empty, what it holds and +// what the change removes (a shorter age's older messages, a smaller cap's bytes over it, every message of a retention change), +// and the room the caps need. +func TestTheAskOfARecreateNamesEachObjectAndWhatItRemoves(t *testing.T) { + now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + hist := keeper.Object{Kind: keeper.KindStream, Name: "m_records", Settings: keeper.Settings{MaxBytes: 4 * keeper.MiB, MaxAgeSeconds: 3600, Discard: keeper.DiscardNew}} + state := keeper.Object{Kind: keeper.KindBucket, Name: "m_records_state", Settings: keeper.Settings{MaxBytes: 8 * keeper.MiB, History: 1, Discard: keeper.DiscardNew}} + queue := keeper.Object{Kind: keeper.KindStream, Name: "m_queue", Settings: keeper.Settings{MaxBytes: 8 * keeper.MiB, Discard: keeper.DiscardNew, WorkQueue: true}} + held := map[string]keeper.Asked{"m": {Module: "m", Made: map[string]keeper.Made{"records": {Created: true, + Plan: keeper.Plan{Module: "m", Local: "records", Objects: []keeper.Object{hist, state, queue}}}}}} + old := now.Add(-3 * time.Hour).Format(time.RFC3339) + jsz := []byte(`{"account_details":[{"stream_detail":[ + {"name":"m_records","config":{"name":"m_records","max_bytes":16777216,"max_age":0,"discard":"new"},"state":{"messages":50,"bytes":1048576,"first_ts":"` + old + `"}}, + {"name":"KV_m_records_state","config":{"name":"KV_m_records_state","max_bytes":33554432,"max_msgs_per_subject":1,"discard":"new"},"state":{"messages":9,"bytes":12582912,"first_ts":"` + old + `"}}, + {"name":"m_queue","config":{"name":"m_queue","max_bytes":8388608,"retention":"limits","discard":"new"},"state":{"messages":7,"bytes":100,"first_ts":"` + old + `"}}]}]}`) + var asked time.Time + words, err := recreateWords(held, func() (keeper.Status, error) { + return keeper.Status{Limits: keeper.Limits{AccountBytes: 100 * keeper.MiB}}, nil + }, jsz, now, func(stream string, before time.Time) (uint64, error) { asked = before; return 42, nil }, "m", "records") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"m_records changed in place", "42 messages older than the age", "50 messages, 1048576 bytes", + "KV_m_records_state changed in place", "4194304 bytes over it", "m_queue made again empty", "every message (7)", "against the account's storage limit of 100 MiB"} { + if !strings.Contains(words, want) { + t.Errorf("the ask does not say %q:\n%s", want, words) + } + } + if !asked.Equal(now.Add(-time.Hour)) { + t.Errorf("the messages were counted before %v", asked) + } + ask, err := askFor(keeper.Request{Verb: keeper.VerbRecreate, Module: "m", Local: "records", Why: "w", Caller: "c", AskExpires: now}, " "+words) + if err != nil || !strings.Contains(ask.Explanation, "42 messages older than the age") { + t.Fatalf("the ask %+v %v", ask, err) + } +} diff --git a/modules/nats/internal/keeper/jetstream.go b/modules/nats/internal/keeper/jetstream.go index 8151c6c7b..8e487f121 100644 --- a/modules/nats/internal/keeper/jetstream.go +++ b/modules/nats/internal/keeper/jetstream.go @@ -154,6 +154,18 @@ func (b JetStream) Update(ctx context.Context, o Object) error { if o.Settings.History > 0 { c.MaxMsgsPerSubject = o.Settings.History } + // The discard, and a lifetime per key or per message turned on; a held one is never turned off, which the bus refuses + // (design 47 H2 H-A-686); a bucket's key lifetime brings its limit marker, as the bucket is made with it. + c.Discard = jetstream.DiscardOld + if o.Settings.Discard == DiscardNew { + c.Discard = jetstream.DiscardNew + } + if o.Settings.KeyTTL { + c.AllowMsgTTL = true + if o.Kind == KindBucket && c.SubjectDeleteMarkerTTL == 0 { + c.SubjectDeleteMarkerTTL = limitMarker(true) + } + } _, err = b.JS.UpdateStream(ctx, c) return retryable(err) } diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 031d6c6f8..104be20ce 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -312,7 +312,7 @@ func (k *Keeper) capRoom(ctx context.Context, held *Asked, m *Made) error { sum += o.Settings.MaxBytes } if sum > lim.AccountBytes { - return fmt.Errorf("the plan takes the sum of the bus's caps to %d MiB, past the account's storage limit of %d MiB", sum/MiB, lim.AccountBytes/MiB) + return fmt.Errorf("the plan takes the sum of the bus's caps to %d MiB, past the account's storage limit of %d MiB, short by %d MiB", sum/MiB, lim.AccountBytes/MiB, (sum-lim.AccountBytes+MiB-1)/MiB) } return nil } diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index 7bbb09720..0b02c5e6c 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -110,6 +110,9 @@ func (b *fakeBus) Create(_ context.Context, o Object) error { func (b *fakeBus) Update(_ context.Context, o Object) error { b.mu.Lock() defer b.mu.Unlock() + if err := b.refuse["update "+o.Stream()]; err != nil { + return err + } b.held[o.Stream()] = o.Settings b.updated = append(b.updated, o.Stream()) return nil @@ -1356,8 +1359,8 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { raw, _ := json.Marshal(Request{ID: "r8", Verb: VerbRecreate, Module: "m", Local: "findings", Ask: "bus-8"}) _, _ = store.Put(StateRequests, "r8", raw) k.ActOnRequests() - if fmt.Sprint(bus.deleted) != "[KV_m_findings]" || bus.held["OBJ_m_findings-objects"].MaxBytes != 8*MiB { - t.Errorf("deleted %v, store held %+v: the recreate rebuilds the bucket alone", bus.deleted, bus.held["OBJ_m_findings-objects"]) + if fmt.Sprint(bus.updated) != "[KV_m_findings]" || len(bus.deleted) != 0 || bus.held["OBJ_m_findings-objects"].MaxBytes != 8*MiB { + t.Errorf("updated %v, deleted %v, store held %+v: the recreate changes the bucket alone, in place", bus.updated, bus.deleted, bus.held["OBJ_m_findings-objects"]) } }}, {"a recreate rebuilds a drifted entry after a snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { @@ -1378,6 +1381,72 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("held %+v, said %v %v: rebuilt as asked, the drift cleared", bus.held["m_log"], out.events, out.conds) } }}, + // Design 47 H2 H-A-686, H-A-706 (DQ-42): a held lifetime matches an ask with none; a recreate changes each object in place + // and stops at the bus's refusal, empties nothing and says no recreated; short of room it changes nothing and takes no + // snapshot, the warrant spent. + {"a recreate changes a ledger in place, stops at a refused change, and stops short of room", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + if Differs(Settings{MaxBytes: 8, Discard: DiscardNew}, Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}) != "" || + !Grows(Settings{MaxBytes: 16, Discard: DiscardNew}, Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}) || + Differs(Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}, Settings{MaxBytes: 8, Discard: DiscardNew}) == "" { + t.Fatal("a held lifetime does not match an ask with none, or an asked one matches a held none") + } + store := k.Store.(*memStore) + big, small := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}), + entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "8"}) + big.Types = []catalogue.LedgerType{{Name: "decision", Indexes: []catalogue.LedgerIndex{{Name: "by-topic", On: []string{"topic"}}}}} + small.Types = big.Types + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{big}}) + k.Heard(Accepted{Module: "m", Revision: 2, BusState: []catalogue.BusStateEntry{small}}) + if k.Held()["m"].Made["records"].Drift == "" { + t.Fatal("a smaller cap is no drift") + } + objects := k.Held()["m"].Made["records"].Plan.Objects + recreate := func(id string) Request { + ask := oc.Ask{ID: "bus-" + id, Who: occ.Operator, Expires: occ.FormatTime(k.now().Add(time.Hour)), Options: []oc.Option{{ID: "go", Label: "Rebuild", Level: occ.Destroy, + Binds: func() string { + b, _ := occ.ActDigest(occ.Act{"verb": "recreate", "module": "m", "local": "records"}) + return b + }()}}} + w := &oc.Warrant{Ask: ask.ID, Asker: Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, + Option: "go", Label: "Rebuild", Level: occ.Destroy, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)} + k.Warrant = func(string) (*oc.Ask, *oc.Warrant, error) { return &ask, w, nil } + raw, _ := json.Marshal(Request{ID: id, Verb: VerbRecreate, Module: "m", Local: "records", Ask: ask.ID}) + _, _ = store.Put(StateRequests, id, raw) + k.ActOnRequests() + raw, _, _, _ = store.Get(StateRequests, id) + var got Request + _ = json.Unmarshal(raw, &got) + return got + } + // Short of room: the account holds less than the caps ask. + bus.limits = Limits{AccountBytes: 4 * MiB} + out.reset() + snaps := len(bus.snaps) + if got := recreate("r1"); !strings.Contains(got.Error, "short by") || len(bus.updated) != 0 || len(bus.deleted) != 0 || len(bus.snaps) != snaps || + len(out.events) != 0 { + t.Fatalf("short of room: %q, updated %v, deleted %v, snapshots %d, said %v", got.Error, bus.updated, bus.deleted, len(bus.snaps)-snaps, out.events) + } + if _, _, spent, _ := store.Get(StateSpent, "bus-r1"); !spent { + t.Error("the warrant of a recreate short of room is not spent") + } + // A refused change in place stops it: the first object changed, the second refused, none emptied or changed after. + bus.limits = Limits{} + bus.refuse["update "+objects[1].Stream()] = errors.New("the bus refuses this change") + out.reset() + got := recreate("r2") + if !strings.Contains(got.Error, objects[1].Stream()) || len(bus.deleted) != 0 || fmt.Sprint(bus.updated) != "["+objects[0].Stream()+"]" || + len(out.events) != 0 || k.Held()["m"].Made["records"].Drift == "" { + t.Fatalf("a refused change: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events) + } + // Without the refusal, a new warrant changes every object in place, keeping what they keep, and says what it held. + delete(bus.refuse, "update "+objects[1].Stream()) + out.reset() + bus.updated = nil + if got := recreate("r3"); got.Error != "" || len(bus.deleted) != 0 || len(bus.updated) != len(objects) || + fmt.Sprint(out.events) != "[recreated m records]" || k.Held()["m"].Made["records"].Drift != "" { + t.Fatalf("the change in place: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events) + } + }}, // Review round 1 (security F2; design 25 § 12.3): a warrant acts once, spent by compare-and-set before anything is // deleted; a second request naming the same ask is refused and deletes nothing. {"a warrant acts once", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { diff --git a/modules/nats/internal/keeper/plan.go b/modules/nats/internal/keeper/plan.go index 63574870e..2fd614c3f 100644 --- a/modules/nats/internal/keeper/plan.go +++ b/modules/nats/internal/keeper/plan.go @@ -440,12 +440,19 @@ func (o options) bool(name string) (bool, error) { // settings grow by nothing and are no difference (Differs). func Grows(asked, held Settings) bool { if asked.Discard != held.Discard || asked.WorkQueue != held.WorkQueue || asked.MaxMsgSize != held.MaxMsgSize || - asked.DuplicatesSeconds != held.DuplicatesSeconds || asked.KeyTTL != held.KeyTTL { + asked.DuplicatesSeconds != held.DuplicatesSeconds || !lifetimeMatches(asked, held) { return false } return asked.MaxBytes >= held.MaxBytes && longer(asked.MaxAgeSeconds, held.MaxAgeSeconds) && asked.History >= held.History } +// lifetimeMatches is whether a held lifetime per key (a bucket's) or per message (a stream's) matches the asked one: equal, +// or held while the ask gives none, since allowing a lifetime is no setting a write must use and the bus refuses to turn it +// off in place (design 47 H2 H-A-686 (1)). +func lifetimeMatches(asked, held Settings) bool { + return asked.KeyTTL == held.KeyTTL || held.KeyTTL && !asked.KeyTTL +} + // longer is whether age a keeps at least as long as b, 0 being for ever. func longer(a, b int64) bool { if a == 0 { @@ -469,7 +476,9 @@ func Differs(asked, held Settings) string { add("work-queue", asked.WorkQueue, held.WorkQueue) add("max-msg-size", asked.MaxMsgSize, held.MaxMsgSize) add("duplicates-seconds", asked.DuplicatesSeconds, held.DuplicatesSeconds) - add("key-ttl", asked.KeyTTL, held.KeyTTL) + if !lifetimeMatches(asked, held) { + add("key-ttl", asked.KeyTTL, held.KeyTTL) + } return strings.Join(out, "; ") } diff --git a/modules/nats/internal/keeper/requests.go b/modules/nats/internal/keeper/requests.go index 692a28ab4..fb43f86a6 100644 --- a/modules/nats/internal/keeper/requests.go +++ b/modules/nats/internal/keeper/requests.go @@ -241,6 +241,29 @@ func (k *Keeper) act(r *Request) (string, error) { } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() + // A recreate reads each object before anything is changed: whether the bus takes its asked settings in place (all but a + // retention that changes, which it refuses to change), and what it holds now (design 47 H2 H-A-686, H-A-634 (3)). + var steps []rebuild + if r.Verb == VerbRecreate { + for _, o := range m.Plan.Objects { + st, fill, found, err := k.Bus.Held(ctx, o) + if err != nil { + return "nothing done", fmt.Errorf("%s cannot be read, so nothing was changed: %w", o.Stream(), err) + } + steps = append(steps, rebuild{o: o, found: found, inPlace: found && st.WorkQueue == o.Settings.WorkQueue, before: fill}) + } + // Short of room for the caps it asks, no object is changed and no snapshot taken; the warrant is spent (H-A-706, DQ-42). + if err := k.capRoom(ctx, &held, &m); err != nil { + if errors.Is(err, ErrRetry) { + return "nothing done", err + } + if serr := k.spend(r); serr != nil { + return "nothing done", serr + } + k.record(r, fmt.Sprintf("recreate of %s of %s refused: %v", r.Local, r.Module, err)) + return "nothing done", fmt.Errorf("%s of %s was not rebuilt, no snapshot was taken and no object was changed: %w", r.Local, r.Module, err) + } + } var streams []string for _, o := range m.Plan.Objects { streams = append(streams, o.Stream()) @@ -258,12 +281,12 @@ func (k *Keeper) act(r *Request) (string, error) { if err := k.spend(r); err != nil { return "nothing done", err } - for _, o := range m.Plan.Objects { - if err := k.Bus.Delete(ctx, o); err != nil { - return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err) - } - } if r.Verb == VerbDrop { + for _, o := range m.Plan.Objects { + if err := k.Bus.Delete(ctx, o); err != nil { + return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err) + } + } delete(held.Made, r.Local) k.write(held) k.emit(EventDropped, m.Plan, held.Revision, r.Why, nil, nil) @@ -271,13 +294,38 @@ func (k *Keeper) act(r *Request) (string, error) { k.record(r, fmt.Sprintf("dropped %s of %s on the operator's warrant (snapshot %s)", r.Local, r.Module, path)) return fmt.Sprintf("dropped %s, its snapshot at %s", BusName(r.Module, r.Local), path), nil } - for _, o := range m.Plan.Objects { - if err := k.Bus.Create(ctx, o); err != nil { - m.Created, m.Refused = false, fmt.Sprintf("%s: %v", o.Stream(), err) - held.Made[r.Local] = m - k.write(held) - return "partly done", fmt.Errorf("%s was removed and could not be made again (its snapshot at %s): %w", o.Stream(), path, err) + // Each object changed in place where the bus takes the asked settings, keeping what they keep; made again empty only one + // whose retention changes. A change the bus refuses stops it: no object made empty, none changed after, the refusal naming + // the object, no recreated, drifted left naming what differs (H-A-686 (2)). + var words []string + for i, st := range steps { + o := st.o + switch { + case st.inPlace: + if err := k.Bus.Update(ctx, o); err != nil { + return "partly done", fmt.Errorf("%s was refused its change in place: %w; the rebuild stopped there: no object was made empty, "+ + "none after it was changed, the drift stays, and its snapshot is at %s (%d of %d objects were changed before it)", o.Stream(), err, path, i, len(steps)) + } + default: + if st.found { + if err := k.Bus.Delete(ctx, o); err != nil { + return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err) + } + } + if err := k.Bus.Create(ctx, o); err != nil { + m.Created, m.Refused = false, fmt.Sprintf("%s: %v", o.Stream(), err) + held.Made[r.Local] = m + k.write(held) + return "partly done", fmt.Errorf("%s was removed and could not be made again (its snapshot at %s): %w", o.Stream(), path, err) + } } + _, after, _, _ := k.Bus.Held(ctx, o) + how := "changed in place" + if !st.inPlace { + how = "made again empty" + } + words = append(words, fmt.Sprintf("%s %s: held %d messages, %d bytes before, %d messages, %d bytes after", o.Stream(), how, + st.before.Messages, st.before.Bytes, after.Messages, after.Bytes)) } wasDrift := m.Drift != "" m.Drift = "" @@ -291,12 +339,20 @@ func (k *Keeper) act(r *Request) (string, error) { m.Said = &said held.Made[r.Local] = m k.write(held) - k.emit(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil) + k.emit(EventRecreated, m.Plan, held.Revision, r.Why+" ("+strings.Join(words, "; ")+")", nil, nil) if wasDrift { k.clear(conditionDrifted, r.Module, r.Local) } - k.record(r, fmt.Sprintf("recreated %s of %s on the operator's warrant (snapshot %s)", r.Local, r.Module, path)) - return fmt.Sprintf("recreated %s as asked, its old data's snapshot at %s", BusName(r.Module, r.Local), path), nil + k.record(r, fmt.Sprintf("recreated %s of %s on the operator's warrant (snapshot %s): %s", r.Local, r.Module, path, strings.Join(words, "; "))) + return fmt.Sprintf("recreated %s as asked, its old data's snapshot at %s: %s", BusName(r.Module, r.Local), path, strings.Join(words, "; ")), nil +} + +// rebuild is one object of a recreate: whether it was found, whether the bus takes its asked settings in place, and what it +// held before. +type rebuild struct { + o Object + found, inPlace bool + before Fill } // warranted holds a recreate or a drop to the operator's warrant on the ask its tool raised: chosen by the operator, From 82abaa03acceaf807e64addcf1ee53c1880cb473 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:34:25 +0100 Subject: [PATCH 12/13] G18 unanswered-said-at-start: the gate says again every act owed with no outcome at its start and when it hears the forge bridge's module running MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds: design 47 G §165, H-A-712 (3) (hq 7c5c3860), H-A-717 (DMC-15, DQ-51) (hq eed55e62) --- .../cmd/mesh-delivery-gate/main.go | 12 +++- .../cmd/mesh-delivery-gate/owedacts.go | 58 +++++++++++++++++++ .../cmd/mesh-delivery-gate/owedacts_test.go | 45 ++++++++++++++ 3 files changed, 114 insertions(+), 1 deletion(-) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index 7a49b57f2..c2c1d608f 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -117,6 +117,10 @@ func run(h *Holder, l *listening) { logf("[mesh-delivery] the record indexes are not kept yet (%v); asking again in %s", err, wait) time.Sleep(wait) } + // The acts owed to the forge that have no outcome are said again, once the records are read after the indexes (G §165). + h.applying.Lock() + h.sayUnanswered("the gate's start") + h.applying.Unlock() go h.Work() for _, pattern := range followed { pattern := pattern @@ -173,7 +177,13 @@ func take(h *Holder, e stdio.Envelope) error { h.applying.Lock() defer h.applying.Unlock() if h.Consumer != nil && h.Consumer.Takes(e.Key) { - return h.Consumer.Hear(e) + err := h.Consumer.Hear(e) + if err == nil && bridgeRunning(e.Key) { + // The forge bridge runs (again): its answer to an act owed is heard whichever of it and the gate was delivered + // first (H-A-717, DQ-51). + h.sayUnanswered("the forge bridge runs") + } + return err } if stdio.TopicMatches(headMovedEvent, e.Key) { return h.HeadMoved(e) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go index b297ff9dc..8bcedd25d 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" + nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" ) @@ -114,3 +115,60 @@ func endedFailedOrHeld(r *Record) string { sort.Strings(lines) return fmt.Sprintf("The delivery record %s ended (%s), with outcomes failed or held:\n%s", r.Instance, r.Ended.Why, strings.Join(lines, "\n")) } + +// sayUnanswered says again, under each act's id and first said time, every act of every record kept that has no outcome yet +// (design 47 G §165, H-A-712 (3), H-A-717 on DMC-15), with one journal line naming the count and why: the owner of the act +// answers one it performed already by its kept outcome. An act that cannot be said is counted and shown as refused; the +// others go on. The caller holds the gate's applying lock where events may be heard. +func (h *Holder) sayUnanswered(why string) { + if h.Owed == nil || h.Records == nil { + return + } + kept, err := h.Records.Kept() + if err != nil { + h.Refuse(fmt.Errorf("the acts owed to the forge are not said again (%s): the records are not read: %w", why, err)) + return + } + said, failed := 0, 0 + for _, r := range kept { + ids := make([]string, 0, len(r.Acts)) + for id, a := range r.Acts { + if a.Outcome == "" { + ids = append(ids, id) + } + } + sort.Strings(ids) + for _, id := range ids { + a := r.Acts[id] + o := a.Owed + o.Record = r.Milestone + if o.ID == "" { + o.ID = a.ID + } + if o.Said == nil { + at := a.At + o.Said = &at + } + if err := h.Owed.Say(o); err != nil { + failed++ + h.Refuse(fmt.Errorf("the %s owed on %s#%d for the record %s is not said again: %w", a.Act, a.Repository, a.Number, r.Instance, err)) + continue + } + said++ + } + } + if h.Logf != nil { + h.Logf("[mesh-delivery] %s: %d acts owed to the forge without an outcome said again, %d not said", why, said, failed) + } +} + +// bridgeRunning is whether the key is the node-engine seat's running of the module that owns the event owed.ended, the forge +// bridge, found from the manifest's consumes (the gate names no other module in code): `.running..`. +func bridgeRunning(key string) bool { + owner, _, ok := strings.Cut(owedEndedEvent, ".") + if !ok || owner == "" { + return false + } + parts := strings.Split(key, ".") + return len(parts) == 4 && parts[1] == nodeengine.EventRunning && parts[3] == owner +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go index 30c7c83b0..b5d478df8 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "fmt" "strings" "testing" "time" @@ -179,3 +180,47 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. } }) } + +// Design 47 G §165, H-A-712 (3), H-A-717 (DMC-15, DQ-51): the gate says again, at its start and when it hears the forge bridge's +// module running, every act owed that has no outcome, under its id and first said time, with one journal line naming the count. +func TestTheGateSaysItsUnansweredActsAgain(t *testing.T) { + at := time.Date(2026, 11, 25, 17, 0, 0, 0, time.UTC) + head := strings.Repeat("1", 40) + var journal []string + rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }} + first := &sayerFake{} + h := &Holder{Now: func() time.Time { return at }, Owed: first, Records: rs, Logf: func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }} + rs.Changed = h.recordChanged + r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@7": head})) + if err != nil { + t.Fatal(err) + } + if err := rs.AddEntry(r, RecordEntry{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace"}); err != nil { + t.Fatal(err) + } + if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt}); err != nil || len(first.said) != 2 { + t.Fatalf("%v, said %d", err, len(first.said)) + } + // One act is answered: it is not said again. + answered := first.said[0] + body, err := forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, ID: answered.ID, Of: seat.Seat, Outcome: forgemsg.OwedNotNeeded, Words: "closed", At: at}) + if err != nil { + t.Fatal(err) + } + if err := h.OwedEnded(body); err != nil { + t.Fatal(err) + } + again := &sayerFake{} + h.Owed = again + h.sayUnanswered("the gate's start") + if len(again.said) != 1 || again.said[0].ID != first.said[1].ID || again.said[0].Said == nil || !again.said[0].Said.Equal(*first.said[1].Said) || + len(journal) != 1 || !strings.Contains(journal[0], "1 acts owed to the forge without an outcome said again") { + t.Fatalf("said %+v, journal %v", again.said, journal) + } + for key, want := range map[string]bool{"node-engine.running.ace.mesh-delivery-forge-bridge": true, "node-engine.running.ace.mesh-x": false, + "node-engine.wait-held.ace.mesh-delivery-forge-bridge": false} { + if got := bridgeRunning(key); got != want { + t.Errorf("bridgeRunning(%s) is %v", key, got) + } + } +} From feb0120330c1734c0c40f03130f5258e1cfbc9cf Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:37:29 +0100 Subject: [PATCH 13/13] G15b recreated-before-after: the event recreated says what each object held before and after, its why a sentence Builds: design 47 H2 H-A-740, H-A-686 (3) --- modules/nats/internal/keeper/keeper.go | 17 +++++++++++++---- modules/nats/internal/keeper/keeper_test.go | 4 +++- modules/nats/internal/keeper/requests.go | 9 ++++++--- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 104be20ce..733532246 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -71,9 +71,13 @@ type Event struct { Asked map[string]Settings `json:"asked,omitempty"` Held map[string]Settings `json:"held,omitempty"` Fill *EventFill `json:"fill,omitempty"` - Snapshot string `json:"snapshot,omitempty"` - Why string `json:"why,omitempty"` - Revision uint64 `json:"revision"` + // Before and After are what each object of a recreated entry held before and after it, said by `recreated` (design 47 H2 + // H-A-740). + Before []EventFill `json:"before,omitempty"` + After []EventFill `json:"after,omitempty"` + Snapshot string `json:"snapshot,omitempty"` + Why string `json:"why,omitempty"` + Revision uint64 `json:"revision"` } // EventFill is the fill an event says: the object it is of, its messages, its bytes and its cap; Object is its name on the @@ -1049,11 +1053,16 @@ func (k *Keeper) emit(event string, p Plan, revision uint64, why string, asked, // emitFill is emit with the fill of the object judged, which full and full-cleared carry (design 47 H2 H-A-634 (9)). func (k *Keeper) emitFill(event string, p Plan, revision uint64, why string, asked, held map[string]Settings, fill *EventFill) { + k.emitBody(event, p, revision, why, asked, held, func(b *Event) { b.Fill = fill }) +} + +// emitBody is emit with the body changed before it is said. +func (k *Keeper) emitBody(event string, p Plan, revision uint64, why string, asked, held map[string]Settings, change func(*Event)) { if k.Emit == nil { return } s := k.saying(event, p, revision, why, asked, held) - s.Body.Fill = fill + change(&s.Body) if err := k.Emit(&s); err != nil { s.Error = err.Error() k.setStatus(func(st *Status) { st.Unsaid = append(st.Unsaid, s) }) diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index 0b02c5e6c..f11f4ebb3 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -1443,7 +1443,9 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { out.reset() bus.updated = nil if got := recreate("r3"); got.Error != "" || len(bus.deleted) != 0 || len(bus.updated) != len(objects) || - fmt.Sprint(out.events) != "[recreated m records]" || k.Held()["m"].Made["records"].Drift != "" { + fmt.Sprint(out.events) != "[recreated m records]" || k.Held()["m"].Made["records"].Drift != "" || + len(out.bodies) == 0 || len(out.bodies[len(out.bodies)-1].Before) != len(objects) || len(out.bodies[len(out.bodies)-1].After) != len(objects) || + out.bodies[len(out.bodies)-1].Why != "" { t.Fatalf("the change in place: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events) } }}, diff --git a/modules/nats/internal/keeper/requests.go b/modules/nats/internal/keeper/requests.go index fb43f86a6..9af8329ab 100644 --- a/modules/nats/internal/keeper/requests.go +++ b/modules/nats/internal/keeper/requests.go @@ -298,6 +298,7 @@ func (k *Keeper) act(r *Request) (string, error) { // whose retention changes. A change the bus refuses stops it: no object made empty, none changed after, the refusal naming // the object, no recreated, drifted left naming what differs (H-A-686 (2)). var words []string + var before, after []EventFill for i, st := range steps { o := st.o switch { @@ -319,13 +320,15 @@ func (k *Keeper) act(r *Request) (string, error) { return "partly done", fmt.Errorf("%s was removed and could not be made again (its snapshot at %s): %w", o.Stream(), path, err) } } - _, after, _, _ := k.Bus.Held(ctx, o) + _, now, _, _ := k.Bus.Held(ctx, o) + before = append(before, EventFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: st.before.Messages, Bytes: st.before.Bytes, Cap: o.Settings.MaxBytes}) + after = append(after, EventFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: now.Messages, Bytes: now.Bytes, Cap: o.Settings.MaxBytes}) how := "changed in place" if !st.inPlace { how = "made again empty" } words = append(words, fmt.Sprintf("%s %s: held %d messages, %d bytes before, %d messages, %d bytes after", o.Stream(), how, - st.before.Messages, st.before.Bytes, after.Messages, after.Bytes)) + st.before.Messages, st.before.Bytes, now.Messages, now.Bytes)) } wasDrift := m.Drift != "" m.Drift = "" @@ -339,7 +342,7 @@ func (k *Keeper) act(r *Request) (string, error) { m.Said = &said held.Made[r.Local] = m k.write(held) - k.emit(EventRecreated, m.Plan, held.Revision, r.Why+" ("+strings.Join(words, "; ")+")", nil, nil) + k.emitBody(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil, func(b *Event) { b.Before, b.After = before, after }) if wasDrift { k.clear(conditionDrifted, r.Module, r.Local) }