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
This commit is contained in:
2026-11-25 17:10:12 +01:00
parent af36f1a617
commit 436e65f0c4
7 changed files with 295 additions and 8 deletions
@@ -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)
+1 -1
View File
@@ -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))
+1 -1
View File
@@ -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)
}
+194 -1
View File
@@ -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 (<node>_<module> or <node>_<module>_..., 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 `<node>.`) 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 (`<node>.`) 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 <node>_<module> or <node>_<module>_... 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 <node>_<module>, or beginning <node>_<module>_, 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
+2 -2
View File
@@ -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
}
+15 -2
View File
@@ -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
}
+4 -1
View File
@@ -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",