You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2026/08/09 04:14:27 UTC
(skywalking-banyandb) branch main updated: add cluster schema consistency check in FODC lifecycle endpoint (#1244)
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
The following commit(s) were added to refs/heads/main by this push:
new 3635d42ee add cluster schema consistency check in FODC lifecycle endpoint (#1244)
3635d42ee is described below
commit 3635d42eeb16e0f58b80506950ab14b71ff78a6d
Author: mrproliu <74...@qq.com>
AuthorDate: Sun Aug 9 12:14:22 2026 +0800
add cluster schema consistency check in FODC lifecycle endpoint (#1244)
* add cluster schema consistency check in FODC lifecycle endpoint
---------
Co-authored-by: Gao Hongtao <ha...@gmail.com>
---
CHANGES.md | 1 +
api/proto/banyandb/database/v1/rpc.proto | 101 +++++
api/proto/banyandb/fodc/v1/rpc.proto | 122 ++++++
banyand/measure/metadata.go | 34 +-
banyand/measure/svc_data.go | 5 +
banyand/measure/svc_liaison.go | 6 +-
banyand/measure/svc_standalone.go | 1 +
banyand/measure/write_data_segmentref_test.go | 8 +
banyand/metadata/client.go | 12 +
banyand/metadata/metadata.go | 7 +-
banyand/metadata/schema/collector.go | 77 +++-
banyand/metadata/schema/schema.go | 12 +
banyand/queue/sub/group_lifecycle.go | 4 +
.../queue/sub/group_lifecycle_cold_tier_test.go | 13 +
banyand/queue/sub/group_lifecycle_test.go | 17 +
banyand/queue/sub/node_schema_state.go | 92 +++++
banyand/queue/sub/node_schema_state_test.go | 102 +++++
banyand/queue/sub/server.go | 2 +
banyand/stream/metadata.go | 31 +-
banyand/stream/svc_liaison.go | 4 +-
banyand/stream/svc_standalone.go | 1 +
banyand/stream/write_data_segmentref_test.go | 8 +
banyand/trace/metadata.go | 34 +-
banyand/trace/svc_liaison.go | 6 +-
banyand/trace/svc_standalone.go | 1 +
banyand/trace/write_data_segmentref_test.go | 8 +
docs/api-reference.md | 347 +++++++++++++++++
docs/operation/grafana-fodc-nodes.json | 95 ++++-
fodc/agent/internal/cmd/root.go | 17 +-
fodc/agent/internal/lifecycle/collector.go | 44 ++-
fodc/agent/internal/lifecycle/collector_test.go | 20 +-
fodc/agent/internal/lifecycle/registry.go | 254 +++++++++++++
.../lifecycle/schema_partial_internal_test.go | 87 +++++
fodc/agent/internal/lifecycle/schema_state.go | 255 +++++++++++++
.../lifecycle/schema_state_internal_test.go | 109 ++++++
fodc/agent/internal/proxy/client.go | 283 ++++++++++++--
fodc/agent/internal/proxy/client_test.go | 4 +
.../internal/proxy/schema_registry_chunk_test.go | 95 +++++
fodc/agent/testhelper/flightrecorder.go | 2 +-
fodc/internal/consistency/checker.go | 262 +++++++++++++
fodc/internal/consistency/checker_test.go | 411 +++++++++++++++++++++
fodc/internal/consistency/derive.go | 54 +++
fodc/internal/consistency/derive_test.go | 106 ++++++
fodc/internal/consistency/fingerprint.go | 107 ++++++
fodc/internal/consistency/fingerprint_test.go | 110 ++++++
fodc/internal/consistency/objects.go | 43 +++
.../api/schema_consistency_contract_test.go | 120 ++++++
fodc/proxy/internal/api/server.go | 44 +++
fodc/proxy/internal/api/server_test.go | 5 +
fodc/proxy/internal/grpc/schema_registry_test.go | 217 +++++++++++
fodc/proxy/internal/grpc/service.go | 191 ++++++++++
fodc/proxy/internal/lifecycle/manager.go | 193 ++++++++--
fodc/proxy/internal/lifecycle/manager_test.go | 22 +-
fodc/proxy/internal/lifecycle/schema_check.go | 89 +++++
.../lifecycle/schema_consistency_merge_test.go | 363 ++++++++++++++++++
fodc/proxy/internal/registry/registry.go | 32 ++
fodc/proxy/internal/registry/registry_test.go | 35 ++
pkg/schema/cache.go | 34 +-
pkg/schema/cache_internal_test.go | 145 ++++++++
pkg/schema/schema.go | 4 +
pkg/schema/snapshot_state.go | 194 ++++++++++
pkg/schema/snapshot_state_internal_test.go | 81 ++++
test/e2e-v2/cases/fodc/banyandb-cluster.yaml | 3 +
test/e2e-v2/cases/fodc/check-schema-consistency.sh | 115 ++++++
test/e2e-v2/cases/fodc/e2e.yaml | 5 +
.../cases/fodc/expected/schema-consistency.yml | 16 +
test/e2e-v2/cases/fodc/metrics/documented_gap.txt | 6 +
test/e2e-v2/cases/fodc/metrics/presence.txt | 2 +-
68 files changed, 5234 insertions(+), 96 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 7fa63a795..15f15c120 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -87,6 +87,7 @@ Release Notes.
- Introduce positional parameter binding (`?` placeholders) into BydbQL to eliminate QL injection.
- Add reusable BydbQL binding: Prepare a query once, then Bind it many times without re-parsing or mutating the template. The liaison caches prepared statements on the gRPC query path (LRU bounded by entry count and bytes, on by default; `--bydbql-prepared-cache-size`/`--bydbql-prepared-cache-max-bytes`, `bydbql_prepared_cache_*` metrics) so repeated templates skip parsing. To pinpoint un-cacheable and slow queries without high-cardinality labels, the query access log tags each entry by [...]
- Expire BydbQL top-K entries not seen within their TTL (`--bydbql-topk-slow-ttl` / `--bydbql-topk-reparse-ttl`, default `24h`), and log `last_seen` / `max_latency_at`.
+- Add FODC schema consistency check comparing registry, cache, and runtime fingerprints across all nodes via lifecycle inspect.
- Log the latest slow BydbQL query's bound parameters as `last_params`, redacted per `--bydbql-topk-param-mode` (default `fingerprint`).
### Bug Fixes
diff --git a/api/proto/banyandb/database/v1/rpc.proto b/api/proto/banyandb/database/v1/rpc.proto
index 901e94f8d..6a888bb86 100644
--- a/api/proto/banyandb/database/v1/rpc.proto
+++ b/api/proto/banyandb/database/v1/rpc.proto
@@ -23,6 +23,7 @@ import "banyandb/common/v1/common.proto";
import "banyandb/database/v1/database.proto";
import "banyandb/database/v1/schema.proto";
import "google/api/annotations.proto";
+import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
import "protoc-gen-openapiv2/options/annotations.proto";
@@ -525,6 +526,106 @@ message DataInfo {
int64 data_size_bytes = 3;
}
+// NodeSchemaStateService streams a node's cached and materialized schema bodies
+// for one group. FODC's sidecar agent fingerprints them on receive; the data
+// path itself ships no fingerprints. Every data node and liaison that owns a
+// group cache implements it.
+service NodeSchemaStateService {
+ // StreamGroupSchemaState returns this node's snapshot for one group as a
+ // sequence of ObjectSnapshot events terminated by one SchemaSnapshotTrailer.
+ // The server snapshots its cache under a read lock, then streams from that
+ // consistent view without holding the lock for the network round-trip; the
+ // trailer's object_count lets the agent detect a torn read.
+ //
+ // An empty stream (zero object events, just the trailer) is a normal
+ // termination: the agent reads it as "this node does not cache this group",
+ // never as an error.
+ rpc StreamGroupSchemaState(StreamGroupSchemaStateRequest) returns (stream StreamGroupSchemaStateResponse);
+}
+
+// StreamGroupSchemaStateRequest asks one node for its schema snapshot. An empty group
+// requests every group the node caches (each object and trailer is tagged with
+// its group), so a data-node agent -- which has no group roster of its own --
+// can collect its whole node in one call.
+message StreamGroupSchemaStateRequest {
+ string group = 1;
+}
+
+// StreamGroupSchemaStateResponse is the streaming element. Wire-extensible via the oneof so
+// new event kinds do not break older agents. Per group the server sends one
+// SchemaRuleTable, then that group's ObjectSnapshot events, then one
+// SchemaSnapshotTrailer (clean termination) or a non-EOF status (transport
+// error).
+message StreamGroupSchemaStateResponse {
+ oneof event {
+ ObjectSnapshot object = 1;
+ SchemaSnapshotTrailer trailer = 2;
+ SchemaRuleTable rule_table = 3;
+ }
+}
+
+// SchemaRuleTable carries a slice of a group's content-deduplicated index-rule
+// bodies. Every SchemaBody.bound_index_rule_refs in the group indexes into the
+// full table, so a rule bound to many resources -- and folded into both the
+// cache and runtime layers -- travels the wire once instead of once per
+// (resource, layer). A runtime-stale rule body differs in content from its cache
+// counterpart, so the two occupy distinct entries and the cache-vs-runtime
+// fingerprint divergence stays observable.
+//
+// A group with hundreds of rules would overflow a single gRPC message, so the
+// table is split across multiple SchemaRuleTable events (all preceding the
+// group's object events); the agent concatenates them in arrival order, which
+// preserves every ref's index.
+message SchemaRuleTable {
+ string group = 1;
+ repeated banyandb.database.v1.IndexRule rules = 2;
+}
+
+// SchemaBody is a schema object's proto body plus the index rules it is hashed
+// against. payload holds the object itself as an Any: FODC never discriminates
+// the catalog type -- it only needs GetMetadata() (via interface, to clear the
+// volatile identity fields) and a deterministic marshal -- so a single Any
+// replaces a per-type oneof and keeps the hash algorithm out of the data path.
+// bound_index_rule_refs indexes into the group's SchemaRuleTable, naming the
+// derived rule set the agent hashes with the body without shipping each rule
+// body per resource.
+message SchemaBody {
+ google.protobuf.Any payload = 1;
+ repeated uint32 bound_index_rule_refs = 2;
+}
+
+// ObjectSnapshot carries a schema object as two layers so the agent can compute
+// both fingerprints: cache is what the node stored, runtime is what it has
+// materialized and is actually serving. runtime is omitted when it equals cache
+// (group and indexRule have no derived structure) or when nothing is
+// materialized yet -- the agent then takes the runtime fingerprint from cache.
+message ObjectSnapshot {
+ // group the object belongs to. Always set, so an all-groups stream (empty
+ // request group) is self-describing.
+ string group = 1;
+ string kind = 2;
+ string name = 3;
+ SchemaBody cache = 4;
+ SchemaBody runtime = 5;
+}
+
+// SchemaSnapshotTrailer terminates one group's objects. A single-group stream
+// sends one trailer before EOF; an all-groups stream sends one trailer per group
+// (each following that group's object events), then EOF.
+message SchemaSnapshotTrailer {
+ // group these objects belong to.
+ string group = 1;
+ // node echoes the responding node id so the agent can detect a misrouted
+ // response in a mixed-version cluster.
+ string node = 2;
+ // object_count is the number of object events sent for this group; the agent
+ // verifies it against what it received and retries once on a mismatch.
+ uint32 object_count = 4;
+ // errors are failures observed collecting this group. They surface on
+ // GroupLifecycleInfo.errors but do not fail the stream.
+ repeated string errors = 5;
+}
+
// SegmentInfo contains information about a specific time segment.
message SegmentInfo {
// segment_id is the unique identifier of the segment.
diff --git a/api/proto/banyandb/fodc/v1/rpc.proto b/api/proto/banyandb/fodc/v1/rpc.proto
index a7a7af7ec..7c05bf6dc 100644
--- a/api/proto/banyandb/fodc/v1/rpc.proto
+++ b/api/proto/banyandb/fodc/v1/rpc.proto
@@ -49,6 +49,14 @@ service FODCService {
// profile's bytes); agent replies with StreamPressureProfilesRequest (metadata
// records, or binary chunks).
rpc StreamPressureProfiles(stream StreamPressureProfilesRequest) returns (stream StreamPressureProfilesResponse);
+
+ // Bi-directional stream for the authoritative schema registry fingerprint.
+ // The Proxy picks one schema-serving (liaison) agent by role and drives it via
+ // StreamSchemaRegistryResponse (request_registry); that one agent reads the
+ // authoritative registry from its local node and replies with
+ // StreamSchemaRegistryRequest (the fingerprints). Only the selected agent is
+ // ever asked, so the registry is read once per collection, not once per node.
+ rpc StreamSchemaRegistry(stream StreamSchemaRegistryRequest) returns (stream StreamSchemaRegistryResponse);
}
message RegisterAgentRequest {
@@ -125,6 +133,48 @@ message StreamLifecycleResponse {
bool request_lifecycle = 1;
}
+// StreamSchemaRegistryRequest is one message of the selected agent's streamed
+// reply to a request_registry command. A group's objects are split across
+// messages so no single message carries a whole (potentially large) group; the
+// proxy merges chunks that share a group name. The agent ends the round with a
+// final message that has done set, which is how the proxy knows to stop waiting.
+// A group whose own read failed rides on SchemaRegistryGroup.error; a fatal
+// whole-read failure (e.g. the local registry endpoint was unreachable) is a
+// single group chunk with an empty group name carrying the error.
+message StreamSchemaRegistryRequest {
+ // group carries a chunk of one group's registry fingerprints; unset on the
+ // final message. Chunks that share a group name are merged by the proxy.
+ SchemaRegistryGroup group = 1;
+ // done marks the last message of the round; no group messages follow it.
+ bool done = 2;
+}
+
+message StreamSchemaRegistryResponse {
+ // Proxy asks the selected agent to read and report the registry fingerprints.
+ bool request_registry = 1;
+}
+
+// SchemaRegistryGroup carries one group's authoritative registry fingerprints.
+// The agent computes the fingerprints so the wire carries only uint64 digests,
+// never raw schema bodies; a group's objects may arrive across several chunks
+// that share a group name, which the proxy merges.
+message SchemaRegistryGroup {
+ string group = 1;
+ repeated SchemaObjectFingerprint objects = 2;
+ // error is set when this group's registry read failed; its objects are then
+ // omitted and the group degrades to UNKNOWN with this reason attached. As a
+ // special case, an empty group name with error set is the agent's fatal
+ // whole-read failure, which the proxy surfaces across every group.
+ string error = 3;
+}
+
+message SchemaObjectFingerprint {
+ // kind is schema.Kind.String(), matching ObjectConsistency.kind.
+ string kind = 1;
+ string name = 2;
+ uint64 fingerprint = 3;
+}
+
message LifecycleData {
repeated LifecycleReport reports = 1;
repeated GroupLifecycleInfo groups = 2;
@@ -146,6 +196,78 @@ message GroupLifecycleInfo {
// - data_info non-empty && errors empty -> full success
// - data_info non-empty && errors non-empty -> partial failure
repeated string errors = 5;
+ // schema_consistency is the verdict on whether this group's schema agrees
+ // across the registry, every node's cache, and every node's runtime. Each
+ // node's fingerprints (data and liaison) live in schema_consistency.objects.
+ SchemaConsistency schema_consistency = 6;
+}
+
+// SchemaConsistency is the single, self-contained schema layer: it holds the
+// verdict plus every object's fingerprints across all three layers -- registry
+// truth, and each node's cache and runtime -- so DataInfo/LiaisonInfo carry no
+// schema of their own.
+message SchemaConsistency {
+ ConsistencyStatus status = 1;
+ // objects lists every schema object in the group exactly once, pairing its
+ // registry-truth fingerprint with each node's cache/runtime fingerprints.
+ repeated ObjectConsistency objects = 2;
+ repeated SchemaIssue issues = 3;
+}
+
+// ObjectConsistency is one schema object's fingerprints across all layers: the
+// registry truth plus every node that reported it.
+message ObjectConsistency {
+ // kind is schema.Kind.String().
+ string kind = 1;
+ string name = 2;
+ // registry_fingerprint is the registry truth; zero when the object exists
+ // only on nodes (an orphan) and not in the registry.
+ uint64 registry_fingerprint = 3;
+ repeated NodeFingerprint node_fingerprints = 4;
+}
+
+// NodeFingerprint is one node's cache/runtime fingerprints for a single object.
+// Only the node id is carried; full node info lives in DataInfo/LiaisonInfo.
+message NodeFingerprint {
+ string node = 1;
+ uint64 cache_fingerprint = 2;
+ uint64 runtime_fingerprint = 3;
+}
+
+// SchemaIssue is one object-on-one-node disagreement. Fingerprint values are not
+// repeated here; look them up in SchemaConsistency.objects by kind+name (the
+// registry truth and that node's cache/runtime).
+message SchemaIssue {
+ // kind is schema.Kind.String().
+ string kind = 1;
+ string name = 2;
+ // node is the node id the disagreement was observed on.
+ string node = 3;
+ SchemaIssueType type = 4;
+}
+
+// SchemaIssueType names which layer boundary the disagreement sits on.
+enum SchemaIssueType {
+ SCHEMA_ISSUE_TYPE_UNSPECIFIED = 0;
+ // Registry has it, the node's cache does not. A frequent root cause is the
+ // node silently rejecting the schema; grep the node log for "is ignored".
+ SCHEMA_ISSUE_TYPE_MISSING_IN_CACHE = 1;
+ // The node holds it but the registry does not.
+ SCHEMA_ISSUE_TYPE_ORPHAN = 2;
+ // Registry and cache disagree: the watch is behind.
+ SCHEMA_ISSUE_TYPE_CACHE_STALE = 3;
+ // Cache and runtime disagree: the derived index was never reapplied.
+ SCHEMA_ISSUE_TYPE_RUNTIME_NOT_APPLIED = 4;
+}
+
+// ConsistencyStatus is the group-level rollup.
+enum ConsistencyStatus {
+ CONSISTENCY_STATUS_UNSPECIFIED = 0;
+ CONSISTENCY_STATUS_CONSISTENT = 1;
+ CONSISTENCY_STATUS_INCONSISTENT = 2;
+ // Collection was incomplete, or a disagreement has not yet persisted long
+ // enough to be reported.
+ CONSISTENCY_STATUS_UNKNOWN = 3;
}
message LifecycleReport {
diff --git a/banyand/measure/metadata.go b/banyand/measure/metadata.go
index a21fad2ba..2c196f405 100644
--- a/banyand/measure/metadata.go
+++ b/banyand/measure/metadata.go
@@ -124,12 +124,13 @@ func newSchemaRepo(path string, svc *standalone, nodeLabels map[string]string, n
return sr
}
-func newLiaisonSchemaRepo(path string, svc *liaison, measureDataNodeRegistry grpc.NodeRegistry, pipeline queue.Client) *schemaRepo {
+func newLiaisonSchemaRepo(path string, svc *liaison, measureDataNodeRegistry grpc.NodeRegistry, pipeline queue.Client, nodeID string) *schemaRepo {
ctx, cancel := context.WithCancel(context.Background())
sr := &schemaRepo{
path: path,
l: svc.l,
metadata: svc.metadata,
+ nodeID: nodeID,
pipeline: pipeline,
closingGroups: make(map[string]struct{}),
role: databasev1.Role_ROLE_LIAISON,
@@ -413,7 +414,36 @@ func (sr *schemaRepo) loadQueue(groupName string) (*wqueue.Queue[*tsTable, optio
return db.(*wqueue.Queue[*tsTable, option]), nil
}
-// CollectDataInfo collects data info for a specific group.
+// measureResourceView reaches the runtime view of a measure. IndexListener exposes
+// only OnIndexUpdate, so the assertion must happen here -- the same pattern the
+// resource loader in this package uses.
+func measureResourceView(res resourceSchema.Resource) (resourceSchema.ResourceView, bool) {
+ cached, ok := res.Schema().(*databasev1.Measure)
+ if !ok {
+ return resourceSchema.ResourceView{}, false
+ }
+ view := resourceSchema.ResourceView{Name: cached.GetMetadata().GetName(), Cached: cached}
+ if r, isTyped := res.Delegated().(*measure); isTyped {
+ view.Runtime = r.GetSchema()
+ view.RuntimeRules = r.GetIndexRules()
+ }
+ return view, true
+}
+
+// CollectSchemaSnapshot returns this node's cache/runtime schema bodies for the
+// group so the FODC agent can fingerprint them on receive.
+func (sr *schemaRepo) CollectSchemaSnapshot(group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, error) {
+ return resourceSchema.CollectSchemaSnapshot(sr.Repository, group,
+ schema.KindMeasure.String(), measureResourceView)
+}
+
+// CachedGroups lists the measure groups this node currently caches.
+func (sr *schemaRepo) CachedGroups() []string {
+ return resourceSchema.CachedGroupNames(sr.Repository)
+}
+
+// CollectDataInfo collects data info for a specific group. When includeSchemaState
+// is set it also attaches this node's schema consistency evidence.
func (sr *schemaRepo) CollectDataInfo(ctx context.Context, group string) (*databasev1.DataInfo, error) {
if sr.nodeID == "" {
return nil, nil
diff --git a/banyand/measure/svc_data.go b/banyand/measure/svc_data.go
index f69c19f2b..8cd95ed5c 100644
--- a/banyand/measure/svc_data.go
+++ b/banyand/measure/svc_data.go
@@ -283,6 +283,11 @@ func (s *dataSVC) PreRun(ctx context.Context) error {
}
node := val.(common.Node)
s.schemaRepo = newDataSchemaRepo(s.dataPath, s, node.Labels, node.NodeID)
+ // Register the snapshot collector so this data node serves its local schema
+ // to the co-located FODC agent via NodeSchemaStateService.
+ if metaSvc, ok := s.metadata.(metadata.Service); ok {
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_MEASURE, s.schemaRepo)
+ }
s.cm = newCacheMetrics(s.omr)
obsservice.MetricsCollector.Register("measure_cache", s.collectCacheMetrics)
diff --git a/banyand/measure/svc_liaison.go b/banyand/measure/svc_liaison.go
index 3e5449d8b..7737ee0c7 100644
--- a/banyand/measure/svc_liaison.go
+++ b/banyand/measure/svc_liaison.go
@@ -88,7 +88,8 @@ func (s *liaison) CollectDataInfo(_ context.Context, _ string) (*databasev1.Data
return nil, errors.New("collect data info is not supported on liaison node")
}
-// CollectLiaisonInfo collects liaison node statistics.
+// CollectLiaisonInfo collects liaison node statistics. When includeSchemaState is
+// set it also attaches this node's schema consistency evidence.
func (s *liaison) CollectLiaisonInfo(_ context.Context, group string) (*databasev1.LiaisonInfo, error) {
info := &databasev1.LiaisonInfo{}
pendingWriteCount, writeErr := s.schemaRepo.collectPendingWriteInfo(group)
@@ -202,13 +203,14 @@ func (s *liaison) PreRun(ctx context.Context) error {
}
topNResultPipeline := queue.Local()
measureDataNodeRegistry := grpc.NewClusterNodeRegistry(data.TopicMeasurePartSync, s.option.tire2Client, s.dataNodeSelector)
- s.schemaRepo = newLiaisonSchemaRepo(s.dataPath, s, measureDataNodeRegistry, topNResultPipeline)
+ s.schemaRepo = newLiaisonSchemaRepo(s.dataPath, s, measureDataNodeRegistry, topNResultPipeline, val.(common.Node).NodeID)
writeListener := setUpWriteQueueCallback(s.l, s.schemaRepo, s.maxDiskUsagePercent, s.option.tire2Client)
if err := s.pipeline.Subscribe(data.TopicMeasureWrite, writeListener); err != nil {
return err
}
if metaSvc, ok := s.metadata.(metadata.Service); ok {
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_MEASURE, s)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_MEASURE, s.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_MEASURE, s)
}
diff --git a/banyand/measure/svc_standalone.go b/banyand/measure/svc_standalone.go
index 5787409af..a35d42caa 100644
--- a/banyand/measure/svc_standalone.go
+++ b/banyand/measure/svc_standalone.go
@@ -299,6 +299,7 @@ func (s *standalone) PreRun(ctx context.Context) error {
if metaSvc, ok := s.metadata.(metadata.Service); ok {
metaSvc.RegisterDataCollector(commonv1.Catalog_CATALOG_MEASURE, s.schemaRepo)
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_MEASURE, s)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_MEASURE, s.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_MEASURE, s)
}
diff --git a/banyand/measure/write_data_segmentref_test.go b/banyand/measure/write_data_segmentref_test.go
index c1a36f7eb..af907e5d4 100644
--- a/banyand/measure/write_data_segmentref_test.go
+++ b/banyand/measure/write_data_segmentref_test.go
@@ -30,6 +30,7 @@ import (
"github.com/apache/skywalking-banyandb/api/common"
commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
"github.com/apache/skywalking-banyandb/banyand/internal/storage"
metadataschema "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
"github.com/apache/skywalking-banyandb/banyand/protector"
@@ -236,9 +237,16 @@ func (f *fakeRepository) LoadGroup(name string) (resourceSchema.Group, bool) {
return g, ok
}
func (f *fakeRepository) LoadAllGroups() []resourceSchema.Group { return nil }
+
+func (f *fakeRepository) LatestModRevision() int64 { return 0 }
func (f *fakeRepository) LoadResource(_ *commonv1.Metadata) (resourceSchema.Resource, bool) {
return nil, false
}
+func (f *fakeRepository) LoadAllResources(_ string) []resourceSchema.Resource { return nil }
+func (f *fakeRepository) LoadAllIndexRules(_ string) []*databasev1.IndexRule { return nil }
+func (f *fakeRepository) IndexRules(_ resourceSchema.ResourceSchema) []*databasev1.IndexRule {
+ return nil
+}
func (f *fakeRepository) Close() {}
func (f *fakeRepository) StopCh() <-chan struct{} { return nil }
func (f *fakeRepository) DropGroup(_ string) error { return nil }
diff --git a/banyand/metadata/client.go b/banyand/metadata/client.go
index 9a7b8bb10..2a3d0b6ac 100644
--- a/banyand/metadata/client.go
+++ b/banyand/metadata/client.go
@@ -526,6 +526,18 @@ func (s *clientService) DropGroup(ctx context.Context, catalog commonv1.Catalog,
return s.infoCollectorRegistry.DropGroup(ctx, catalog, group)
}
+func (s *clientService) CollectGroupSchemaSnapshot(ctx context.Context, group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, bool, error) {
+ return s.infoCollectorRegistry.CollectGroupSchemaSnapshot(ctx, group)
+}
+
+func (s *clientService) AllCachedGroups() []string {
+ return s.infoCollectorRegistry.AllCachedGroups()
+}
+
+func (s *clientService) RegisterSchemaSnapshotCollector(catalog commonv1.Catalog, collector schema.SnapshotCollector) {
+ s.infoCollectorRegistry.RegisterSchemaSnapshotCollector(catalog, collector)
+}
+
func (s *clientService) RegisterDataCollector(catalog commonv1.Catalog, collector schema.DataInfoCollector) {
s.infoCollectorRegistry.RegisterDataCollector(catalog, collector)
}
diff --git a/banyand/metadata/metadata.go b/banyand/metadata/metadata.go
index f26631964..fd5127fec 100644
--- a/banyand/metadata/metadata.go
+++ b/banyand/metadata/metadata.go
@@ -53,8 +53,10 @@ type Repo interface {
RegisterHandler(string, schema.Kind, schema.EventHandler)
NodeRegistry() schema.Node
PropertyRegistry() schema.Property
- CollectDataInfo(context.Context, string) ([]*databasev1.DataInfo, []string, error)
- CollectLiaisonInfo(context.Context, string) ([]*databasev1.LiaisonInfo, error)
+ CollectDataInfo(ctx context.Context, group string) ([]*databasev1.DataInfo, []string, error)
+ CollectLiaisonInfo(ctx context.Context, group string) ([]*databasev1.LiaisonInfo, error)
+ CollectGroupSchemaSnapshot(ctx context.Context, group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, bool, error)
+ AllCachedGroups() []string
DropGroup(ctx context.Context, catalog commonv1.Catalog, group string) error
}
@@ -78,5 +80,6 @@ type Service interface {
SetLiaisonBroadcaster(broadcaster bus.Broadcaster)
RegisterDataCollector(catalog commonv1.Catalog, collector schema.DataInfoCollector)
RegisterLiaisonCollector(catalog commonv1.Catalog, collector schema.LiaisonInfoCollector)
+ RegisterSchemaSnapshotCollector(catalog commonv1.Catalog, collector schema.SnapshotCollector)
RegisterGroupDropHandler(catalog commonv1.Catalog, handler schema.GroupDropHandler)
}
diff --git a/banyand/metadata/schema/collector.go b/banyand/metadata/schema/collector.go
index 27d198a71..6ecf54382 100644
--- a/banyand/metadata/schema/collector.go
+++ b/banyand/metadata/schema/collector.go
@@ -68,6 +68,7 @@ type InfoCollectorRegistry struct {
groupGetter GroupGetter
dataCollectors map[commonv1.Catalog]DataInfoCollector
liaisonCollectors map[commonv1.Catalog]LiaisonInfoCollector
+ snapshotCollectors map[commonv1.Catalog]SnapshotCollector
dropHandlers map[commonv1.Catalog]GroupDropHandler
dataBroadcaster bus.Broadcaster
liaisonBroadcaster bus.Broadcaster
@@ -78,11 +79,12 @@ type InfoCollectorRegistry struct {
// NewInfoCollectorRegistry creates a new InfoCollectorRegistry.
func NewInfoCollectorRegistry(l *logger.Logger, groupGetter GroupGetter) *InfoCollectorRegistry {
return &InfoCollectorRegistry{
- groupGetter: groupGetter,
- dataCollectors: make(map[commonv1.Catalog]DataInfoCollector),
- liaisonCollectors: make(map[commonv1.Catalog]LiaisonInfoCollector),
- dropHandlers: make(map[commonv1.Catalog]GroupDropHandler),
- l: l,
+ groupGetter: groupGetter,
+ dataCollectors: make(map[commonv1.Catalog]DataInfoCollector),
+ liaisonCollectors: make(map[commonv1.Catalog]LiaisonInfoCollector),
+ snapshotCollectors: make(map[commonv1.Catalog]SnapshotCollector),
+ dropHandlers: make(map[commonv1.Catalog]GroupDropHandler),
+ l: l,
}
}
@@ -136,7 +138,8 @@ func (icr *InfoCollectorRegistry) CollectDataInfo(ctx context.Context, group str
}
func (icr *InfoCollectorRegistry) broadcastCollectDataInfo(topic bus.Topic, group string) ([]*databasev1.DataInfo, []string) {
- message := bus.NewMessage(bus.MessageID(time.Now().UnixNano()), &databasev1.GroupRegistryServiceInspectRequest{Group: group})
+ message := bus.NewMessage(bus.MessageID(time.Now().UnixNano()),
+ &databasev1.GroupRegistryServiceInspectRequest{Group: group})
futures, broadcastErr := icr.dataBroadcaster.Broadcast(inspectBroadcastTimeout, topic, message)
if broadcastErr != nil {
icr.l.Warn().Err(broadcastErr).Str("group", group).Msg("failed to broadcast collect data info request")
@@ -166,7 +169,9 @@ func (icr *InfoCollectorRegistry) broadcastCollectDataInfo(topic bus.Topic, grou
return dataInfoList, collectionErrors
}
-func (icr *InfoCollectorRegistry) collectDataInfoLocal(ctx context.Context, catalog commonv1.Catalog, group string) (*databasev1.DataInfo, error) {
+func (icr *InfoCollectorRegistry) collectDataInfoLocal(
+ ctx context.Context, catalog commonv1.Catalog, group string,
+) (*databasev1.DataInfo, error) {
icr.mux.RLock()
collector, hasCollector := icr.dataCollectors[catalog]
icr.mux.RUnlock()
@@ -214,12 +219,17 @@ func (icr *InfoCollectorRegistry) CollectLiaisonInfo(ctx context.Context, group
default:
return nil, fmt.Errorf("unsupported catalog type: %v", g.Catalog)
}
+ // Include this node's own liaison info alongside the broadcast. The liaison
+ // collect broadcast targets the pub's registered peers (ActiveRegisteredNodes)
+ // and never loops back to the local node, so the broadcast alone omits the
+ // self-entry -- and in a single-liaison cluster loses it entirely (0 results).
remoteInfo := icr.broadcastCollectLiaisonInfo(topic, group)
return append(localInfoList, remoteInfo...), nil
}
func (icr *InfoCollectorRegistry) broadcastCollectLiaisonInfo(topic bus.Topic, group string) []*databasev1.LiaisonInfo {
- message := bus.NewMessage(bus.MessageID(time.Now().UnixNano()), &databasev1.GroupRegistryServiceInspectRequest{Group: group})
+ message := bus.NewMessage(bus.MessageID(time.Now().UnixNano()),
+ &databasev1.GroupRegistryServiceInspectRequest{Group: group})
futures, broadcastErr := icr.liaisonBroadcaster.Broadcast(inspectBroadcastTimeout, topic, message)
if broadcastErr != nil {
icr.l.Warn().Err(broadcastErr).Str("group", group).Msg("failed to broadcast collect liaison info request")
@@ -246,7 +256,9 @@ func (icr *InfoCollectorRegistry) broadcastCollectLiaisonInfo(topic bus.Topic, g
return liaisonInfoList
}
-func (icr *InfoCollectorRegistry) collectLiaisonInfoLocal(ctx context.Context, catalog commonv1.Catalog, group string) (*databasev1.LiaisonInfo, error) {
+func (icr *InfoCollectorRegistry) collectLiaisonInfoLocal(
+ ctx context.Context, catalog commonv1.Catalog, group string,
+) (*databasev1.LiaisonInfo, error) {
icr.mux.RLock()
collector, hasCollector := icr.liaisonCollectors[catalog]
icr.mux.RUnlock()
@@ -343,6 +355,53 @@ func (icr *InfoCollectorRegistry) RegisterGroupDropHandler(catalog commonv1.Cata
icr.dropHandlers[catalog] = handler
}
+// RegisterSchemaSnapshotCollector registers a schema snapshot collector for a catalog.
+func (icr *InfoCollectorRegistry) RegisterSchemaSnapshotCollector(catalog commonv1.Catalog, collector SnapshotCollector) {
+ icr.mux.Lock()
+ defer icr.mux.Unlock()
+ icr.snapshotCollectors[catalog] = collector
+}
+
+// CollectGroupSchemaSnapshot returns this node's cache/runtime schema bodies for
+// one group plus its deduplicated index-rule table, dispatched to the catalog
+// that owns the group. found is false when the node caches no collector for the
+// group's catalog (it does not serve that group).
+func (icr *InfoCollectorRegistry) CollectGroupSchemaSnapshot(
+ ctx context.Context, group string,
+) (objects []*databasev1.ObjectSnapshot, ruleTable []*databasev1.IndexRule, found bool, err error) {
+ g, getErr := icr.groupGetter.GetGroup(ctx, group)
+ if getErr != nil {
+ return nil, nil, false, getErr
+ }
+ icr.mux.RLock()
+ collector, ok := icr.snapshotCollectors[g.Catalog]
+ icr.mux.RUnlock()
+ if !ok || collector == nil {
+ return nil, nil, false, nil
+ }
+ objs, rules, collectErr := collector.CollectSchemaSnapshot(group)
+ if collectErr != nil {
+ return nil, nil, true, collectErr
+ }
+ return objs, rules, true, nil
+}
+
+// AllCachedGroups returns every group cached across the node's snapshot
+// collectors, for an all-groups snapshot request that carries no roster.
+func (icr *InfoCollectorRegistry) AllCachedGroups() []string {
+ icr.mux.RLock()
+ collectors := make([]SnapshotCollector, 0, len(icr.snapshotCollectors))
+ for _, c := range icr.snapshotCollectors {
+ collectors = append(collectors, c)
+ }
+ icr.mux.RUnlock()
+ var groups []string
+ for _, c := range collectors {
+ groups = append(groups, c.CachedGroups()...)
+ }
+ return groups
+}
+
// SetDataBroadcaster sets the broadcaster for data info collection.
func (icr *InfoCollectorRegistry) SetDataBroadcaster(broadcaster bus.Broadcaster) {
icr.mux.Lock()
diff --git a/banyand/metadata/schema/schema.go b/banyand/metadata/schema/schema.go
index 93a4430b2..bb4b8c535 100644
--- a/banyand/metadata/schema/schema.go
+++ b/banyand/metadata/schema/schema.go
@@ -58,6 +58,18 @@ type LiaisonInfoCollector interface {
CollectLiaisonInfo(ctx context.Context, group string) (*databasev1.LiaisonInfo, error)
}
+// SnapshotCollector streams a node's cached and materialized schema BODIES
+// for a group so the FODC agent can fingerprint them on receive. Registered per
+// catalog by each banyand service; the data path itself computes no fingerprints.
+type SnapshotCollector interface {
+ // CollectSchemaSnapshot returns this node's cache/runtime bodies for the group
+ // plus the group's deduplicated index-rule table that its bodies reference.
+ CollectSchemaSnapshot(group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, error)
+ // CachedGroups lists the groups of this catalog the node currently caches, so
+ // an all-groups request can enumerate without a roster.
+ CachedGroups() []string
+}
+
// UnimplementedOnInitHandler is a placeholder for unimplemented OnInitHandler.
type UnimplementedOnInitHandler struct{}
diff --git a/banyand/queue/sub/group_lifecycle.go b/banyand/queue/sub/group_lifecycle.go
index d8d1f495b..3d8a5388e 100644
--- a/banyand/queue/sub/group_lifecycle.go
+++ b/banyand/queue/sub/group_lifecycle.go
@@ -83,6 +83,10 @@ func (s *server) inspectGroup(ctx context.Context, group *commonv1.Group) *fodcv
// means DataInfo is populated and collectionErrs may carry per-node
// broadcast failures. The two paths never overlap, so the top-level
// branch sets a fresh single-element Errors slice.
+ //
+ // Schema consistency is no longer computed here: each node's schema is
+ // streamed to its co-located FODC agent via NodeSchemaStateService, the agent
+ // fingerprints it, and the proxy runs the checker across the cluster.
dataInfo, collectionErrs, err := s.metadataRepo.CollectDataInfo(ctx, groupName)
if err != nil {
s.log.Warn().Err(err).Str("group", groupName).Msg("Failed to collect data info")
diff --git a/banyand/queue/sub/group_lifecycle_cold_tier_test.go b/banyand/queue/sub/group_lifecycle_cold_tier_test.go
index 11eea1cde..6db67c4ed 100644
--- a/banyand/queue/sub/group_lifecycle_cold_tier_test.go
+++ b/banyand/queue/sub/group_lifecycle_cold_tier_test.go
@@ -104,6 +104,19 @@ func (r *coldTierRepo) CollectDataInfo(_ context.Context, group string) (out []*
return coldTierEmptyDataInfo(), nil, nil
}
+// CollectLiaisonInfo models a cold-tier data node, which serves no liaison
+// schema. inspectGroup now always asks, so the stub must answer rather than
+// fall through to the nil embedded Repo and panic.
+func (r *coldTierRepo) CollectLiaisonInfo(_ context.Context, _ string) ([]*databasev1.LiaisonInfo, error) {
+ return nil, nil
+}
+
+func (r *coldTierRepo) CollectGroupSchemaSnapshot(_ context.Context, _ string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, bool, error) {
+ return nil, nil, false, nil
+}
+
+func (r *coldTierRepo) AllCachedGroups() []string { return nil }
+
// coldTierEmptyDataInfo mirrors the DataInfo shape the fixed schemaRepo
// returns when every selected segment is in the idle-closed residual state
// (s.index = nil): non-nil top-level DataInfo with one SegmentInfo entry whose
diff --git a/banyand/queue/sub/group_lifecycle_test.go b/banyand/queue/sub/group_lifecycle_test.go
index 4f912b323..b4cb17c8d 100644
--- a/banyand/queue/sub/group_lifecycle_test.go
+++ b/banyand/queue/sub/group_lifecycle_test.go
@@ -52,6 +52,10 @@ type mockMetadataRepo struct {
dataInfoErr map[string]error
collectionErrors map[string][]string
slowGroups map[string]time.Duration
+ snapshotObjects []*databasev1.ObjectSnapshot
+ snapshotRules []*databasev1.IndexRule
+ cachedGroups []string
+ snapshotFound bool
collectStarts atomic.Int32
concurrentMax atomic.Int32
concurrentNow atomic.Int32
@@ -92,6 +96,19 @@ func (m *mockMetadataRepo) CollectDataInfo(_ context.Context, group string) ([]*
return dataInfo, collectionErrs, nil
}
+// CollectLiaisonInfo defaults to no liaison schema; inspectGroup always asks, so
+// the base mock must answer rather than fall through to the nil embedded Repo.
+// consistencyRepo overrides this to serve controlled liaison state.
+func (m *mockMetadataRepo) CollectLiaisonInfo(_ context.Context, _ string) ([]*databasev1.LiaisonInfo, error) {
+ return nil, nil
+}
+
+func (m *mockMetadataRepo) CollectGroupSchemaSnapshot(_ context.Context, _ string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, bool, error) {
+ return m.snapshotObjects, m.snapshotRules, m.snapshotFound, nil
+}
+
+func (m *mockMetadataRepo) AllCachedGroups() []string { return m.cachedGroups }
+
func TestCatalogToString(t *testing.T) {
tests := []struct {
name string
diff --git a/banyand/queue/sub/node_schema_state.go b/banyand/queue/sub/node_schema_state.go
new file mode 100644
index 000000000..f7cd6d38b
--- /dev/null
+++ b/banyand/queue/sub/node_schema_state.go
@@ -0,0 +1,92 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package sub
+
+import (
+ grpclib "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+// ruleTableChunkSize bounds how many index rules travel in one SchemaRuleTable
+// event. A group can bind hundreds of rules whose full bodies would overflow a
+// single gRPC message, so the table is split across events; the agent
+// concatenates them in arrival order, which keeps bound_index_rule_refs valid.
+const ruleTableChunkSize = 50
+
+// StreamGroupSchemaState streams this node's cached and materialized schema
+// bodies for a group (or every cached group when the request group is empty).
+// The FODC agent fingerprints them on receive, so the data path ships no
+// fingerprints. Each group's objects are followed by a SchemaSnapshotTrailer;
+// collection errors surface on the trailer rather than failing the stream so a
+// partial snapshot is still useful.
+func (s *server) StreamGroupSchemaState(
+ req *databasev1.StreamGroupSchemaStateRequest,
+ stream grpclib.ServerStreamingServer[databasev1.StreamGroupSchemaStateResponse],
+) error {
+ if s.metadataRepo == nil {
+ return status.Error(codes.Unavailable, "metadata repository not available")
+ }
+ node := s.curNode.GetMetadata().GetName()
+ groups := []string{req.GetGroup()}
+ if req.GetGroup() == "" {
+ groups = s.metadataRepo.AllCachedGroups()
+ }
+ ctx := stream.Context()
+ for _, group := range groups {
+ if group == "" {
+ continue
+ }
+ objects, ruleTable, found, err := s.metadataRepo.CollectGroupSchemaSnapshot(ctx, group)
+ trailer := &databasev1.SchemaSnapshotTrailer{Group: group, Node: node}
+ switch {
+ case err != nil:
+ trailer.Errors = []string{err.Error()}
+ case found:
+ for start := 0; start < len(ruleTable); start += ruleTableChunkSize {
+ end := start + ruleTableChunkSize
+ if end > len(ruleTable) {
+ end = len(ruleTable)
+ }
+ if sendErr := stream.Send(&databasev1.StreamGroupSchemaStateResponse{
+ Event: &databasev1.StreamGroupSchemaStateResponse_RuleTable{
+ RuleTable: &databasev1.SchemaRuleTable{Group: group, Rules: ruleTable[start:end]},
+ },
+ }); sendErr != nil {
+ return sendErr
+ }
+ }
+ for _, obj := range objects {
+ if sendErr := stream.Send(&databasev1.StreamGroupSchemaStateResponse{
+ Event: &databasev1.StreamGroupSchemaStateResponse_Object{Object: obj},
+ }); sendErr != nil {
+ return sendErr
+ }
+ }
+ trailer.ObjectCount = uint32(len(objects))
+ }
+ if sendErr := stream.Send(&databasev1.StreamGroupSchemaStateResponse{
+ Event: &databasev1.StreamGroupSchemaStateResponse_Trailer{Trailer: trailer},
+ }); sendErr != nil {
+ return sendErr
+ }
+ }
+ return nil
+}
diff --git a/banyand/queue/sub/node_schema_state_test.go b/banyand/queue/sub/node_schema_state_test.go
new file mode 100644
index 000000000..18f7cd031
--- /dev/null
+++ b/banyand/queue/sub/node_schema_state_test.go
@@ -0,0 +1,102 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package sub
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ grpclib "google.golang.org/grpc"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+// fakeSchemaStream captures the events StreamGroupSchemaState sends. Only Send
+// and Context are exercised; the rest of the ServerStream surface is never
+// called, so the embedded nil interface is fine.
+type fakeSchemaStream struct {
+ grpclib.ServerStream
+ ctx context.Context
+ events []*databasev1.StreamGroupSchemaStateResponse
+}
+
+func (f *fakeSchemaStream) Send(e *databasev1.StreamGroupSchemaStateResponse) error {
+ f.events = append(f.events, e)
+ return nil
+}
+
+func (f *fakeSchemaStream) Context() context.Context { return f.ctx }
+
+func TestStreamGroupSchemaState_SplitsRuleTableAndPreservesOrder(t *testing.T) {
+ // 120 rules must span ceil(120/50)=3 SchemaRuleTable events, each capped at
+ // the chunk size, and concatenate back in the original order so every
+ // bound_index_rule_ref still resolves.
+ const ruleCount = 120
+ rules := make([]*databasev1.IndexRule, ruleCount)
+ for i := range rules {
+ rules[i] = &databasev1.IndexRule{Metadata: &commonv1.Metadata{Group: "g", Name: fmt.Sprintf("r%d", i)}}
+ }
+ objs := []*databasev1.ObjectSnapshot{
+ {Group: "g", Kind: "stream", Name: "foo"},
+ {Group: "g", Kind: "stream", Name: "bar"},
+ }
+ repo := &mockMetadataRepo{
+ snapshotRules: rules, snapshotObjects: objs, snapshotFound: true, cachedGroups: []string{"g"},
+ }
+ s := &server{metadataRepo: repo, curNode: &databasev1.Node{Metadata: &commonv1.Metadata{Name: "node-1"}}}
+ stream := &fakeSchemaStream{ctx: context.Background()}
+
+ require.NoError(t, s.StreamGroupSchemaState(&databasev1.StreamGroupSchemaStateRequest{}, stream))
+
+ var tableEvents, objectEvents, trailers, lastTableIdx, firstObjectIdx int
+ firstObjectIdx = -1
+ var concatenated []*databasev1.IndexRule
+ var trailer *databasev1.SchemaSnapshotTrailer
+ for i, e := range stream.events {
+ switch ev := e.GetEvent().(type) {
+ case *databasev1.StreamGroupSchemaStateResponse_RuleTable:
+ tableEvents++
+ lastTableIdx = i
+ assert.LessOrEqual(t, len(ev.RuleTable.GetRules()), ruleTableChunkSize, "each chunk is bounded by ruleTableChunkSize")
+ concatenated = append(concatenated, ev.RuleTable.GetRules()...)
+ case *databasev1.StreamGroupSchemaStateResponse_Object:
+ objectEvents++
+ if firstObjectIdx < 0 {
+ firstObjectIdx = i
+ }
+ case *databasev1.StreamGroupSchemaStateResponse_Trailer:
+ trailers++
+ trailer = ev.Trailer
+ }
+ }
+
+ assert.Equal(t, 3, tableEvents, "120 rules at 50/chunk -> 3 rule-table events")
+ assert.Equal(t, len(objs), objectEvents, "objects are still one event each")
+ require.Equal(t, 1, trailers)
+ assert.Equal(t, uint32(len(objs)), trailer.GetObjectCount(), "object_count counts objects, not rule-table chunks")
+ assert.Less(t, lastTableIdx, firstObjectIdx, "all rule-table chunks precede the object events")
+
+ require.Len(t, concatenated, ruleCount, "every rule survives the split")
+ for i, r := range concatenated {
+ assert.Equal(t, fmt.Sprintf("r%d", i), r.GetMetadata().GetName(), "concatenation preserves order across chunks")
+ }
+}
diff --git a/banyand/queue/sub/server.go b/banyand/queue/sub/server.go
index f19236733..d79494c5a 100644
--- a/banyand/queue/sub/server.go
+++ b/banyand/queue/sub/server.go
@@ -82,6 +82,7 @@ type server struct {
databasev1.UnimplementedClusterStateServiceServer
clusterv1.UnimplementedServiceServer
fodcv1.UnimplementedGroupLifecycleServiceServer
+ databasev1.UnimplementedNodeSchemaStateServiceServer
omr observability.MetricsRegistry
creds credentials.TransportCredentials
metadataRepo metadata.Repo
@@ -300,6 +301,7 @@ func (s *server) Serve() run.StopNotify {
tracev1.RegisterTraceServiceServer(s.ser, &traceService{ser: s})
if s.metadataRepo != nil {
fodcv1.RegisterGroupLifecycleServiceServer(s.ser, s)
+ databasev1.RegisterNodeSchemaStateServiceServer(s.ser, s)
}
if s.nodeSchemaStatusRepo != nil {
// The registry is resolved per request (closure) so the service
diff --git a/banyand/stream/metadata.go b/banyand/stream/metadata.go
index b8bb806b4..def88c96e 100644
--- a/banyand/stream/metadata.go
+++ b/banyand/stream/metadata.go
@@ -277,7 +277,36 @@ func (sr *schemaRepo) loadTSDB(groupName string) (storage.TSDB[*tsTable, option]
return db.(storage.TSDB[*tsTable, option]), nil
}
-// CollectDataInfo collects data info for a specific group.
+// CollectSchemaSnapshot returns this node's cache/runtime schema bodies for the
+// group so the FODC agent can fingerprint them on receive.
+func (sr *schemaRepo) CollectSchemaSnapshot(group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, error) {
+ return resourceSchema.CollectSchemaSnapshot(sr.Repository, group,
+ schema.KindStream.String(), streamResourceView)
+}
+
+// CachedGroups lists the stream groups this node currently caches.
+func (sr *schemaRepo) CachedGroups() []string {
+ return resourceSchema.CachedGroupNames(sr.Repository)
+}
+
+// streamResourceView reaches the runtime view of a stream. IndexListener exposes
+// only OnIndexUpdate, so the assertion must happen here -- the same pattern the
+// resource loader in this package uses.
+func streamResourceView(res resourceSchema.Resource) (resourceSchema.ResourceView, bool) {
+ cached, ok := res.Schema().(*databasev1.Stream)
+ if !ok {
+ return resourceSchema.ResourceView{}, false
+ }
+ view := resourceSchema.ResourceView{Name: cached.GetMetadata().GetName(), Cached: cached}
+ if r, isTyped := res.Delegated().(*stream); isTyped {
+ view.Runtime = r.GetSchema()
+ view.RuntimeRules = r.GetIndexRules()
+ }
+ return view, true
+}
+
+// CollectDataInfo collects data info for a specific group. When includeSchemaState
+// is set it also attaches this node's schema consistency evidence.
func (sr *schemaRepo) CollectDataInfo(ctx context.Context, group string) (*databasev1.DataInfo, error) {
if sr.nodeID == "" {
return nil, fmt.Errorf("node ID is empty")
diff --git a/banyand/stream/svc_liaison.go b/banyand/stream/svc_liaison.go
index a9fe96fdc..ce54df3ab 100644
--- a/banyand/stream/svc_liaison.go
+++ b/banyand/stream/svc_liaison.go
@@ -95,7 +95,8 @@ func (s *liaison) CollectDataInfo(_ context.Context, _ string) (*databasev1.Data
return nil, errors.New("collect data info is not supported on liaison node")
}
-// CollectLiaisonInfo collects liaison node info.
+// CollectLiaisonInfo collects liaison node info. When includeSchemaState is set it
+// also attaches this node's schema consistency evidence.
func (s *liaison) CollectLiaisonInfo(_ context.Context, group string) (*databasev1.LiaisonInfo, error) {
info := &databasev1.LiaisonInfo{
PendingWriteDataCount: 0,
@@ -212,6 +213,7 @@ func (s *liaison) PreRun(ctx context.Context) error {
if metaSvc, ok := s.metadata.(metadata.Service); ok {
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_STREAM, s)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_STREAM, &s.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_STREAM, s)
}
diff --git a/banyand/stream/svc_standalone.go b/banyand/stream/svc_standalone.go
index fe8751b3e..eefc851b1 100644
--- a/banyand/stream/svc_standalone.go
+++ b/banyand/stream/svc_standalone.go
@@ -276,6 +276,7 @@ func (s *standalone) PreRun(ctx context.Context) error {
if metaSvc, ok := s.metadata.(metadata.Service); ok {
metaSvc.RegisterDataCollector(commonv1.Catalog_CATALOG_STREAM, &s.schemaRepo)
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_STREAM, s)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_STREAM, &s.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_STREAM, s)
}
if s.pipeline == nil {
diff --git a/banyand/stream/write_data_segmentref_test.go b/banyand/stream/write_data_segmentref_test.go
index 7b6863969..afb167929 100644
--- a/banyand/stream/write_data_segmentref_test.go
+++ b/banyand/stream/write_data_segmentref_test.go
@@ -30,6 +30,7 @@ import (
"github.com/apache/skywalking-banyandb/api/common"
commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
"github.com/apache/skywalking-banyandb/banyand/internal/storage"
metadataschema "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
"github.com/apache/skywalking-banyandb/banyand/protector"
@@ -237,9 +238,16 @@ func (f *fakeRepository) LoadGroup(name string) (resourceSchema.Group, bool) {
return g, ok
}
func (f *fakeRepository) LoadAllGroups() []resourceSchema.Group { return nil }
+
+func (f *fakeRepository) LatestModRevision() int64 { return 0 }
func (f *fakeRepository) LoadResource(_ *commonv1.Metadata) (resourceSchema.Resource, bool) {
return nil, false
}
+func (f *fakeRepository) LoadAllResources(_ string) []resourceSchema.Resource { return nil }
+func (f *fakeRepository) LoadAllIndexRules(_ string) []*databasev1.IndexRule { return nil }
+func (f *fakeRepository) IndexRules(_ resourceSchema.ResourceSchema) []*databasev1.IndexRule {
+ return nil
+}
func (f *fakeRepository) Close() {}
func (f *fakeRepository) StopCh() <-chan struct{} { return nil }
func (f *fakeRepository) DropGroup(_ string) error { return nil }
diff --git a/banyand/trace/metadata.go b/banyand/trace/metadata.go
index 947ca8915..79e5491be 100644
--- a/banyand/trace/metadata.go
+++ b/banyand/trace/metadata.go
@@ -108,12 +108,13 @@ func newSchemaRepo(path string, svc *standalone, nodeLabels map[string]string, n
return sr
}
-func newLiaisonSchemaRepo(path string, svc *liaison, traceDataNodeRegistry grpc.NodeRegistry) schemaRepo {
+func newLiaisonSchemaRepo(path string, svc *liaison, traceDataNodeRegistry grpc.NodeRegistry, nodeID string) schemaRepo {
pipelineFactory := svc.omr.With(pipelineScope)
sr := schemaRepo{
l: svc.l,
path: path,
metadata: svc.metadata,
+ nodeID: nodeID,
role: databasev1.Role_ROLE_LIAISON,
samplerMeter: newSamplerMetrics(pipelineFactory),
pluginTelemetryFactory: pipelineFactory,
@@ -520,7 +521,36 @@ func (sr *schemaRepo) loadTSDB(groupName string) (storage.TSDB[*tsTable, option]
return db.(storage.TSDB[*tsTable, option]), nil
}
-// CollectDataInfo collects data info for a specific group.
+// CollectSchemaSnapshot returns this node's cache/runtime schema bodies for the
+// group so the FODC agent can fingerprint them on receive.
+func (sr *schemaRepo) CollectSchemaSnapshot(group string) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, error) {
+ return resourceSchema.CollectSchemaSnapshot(sr.Repository, group,
+ schema.KindTrace.String(), traceResourceView)
+}
+
+// CachedGroups lists the trace groups this node currently caches.
+func (sr *schemaRepo) CachedGroups() []string {
+ return resourceSchema.CachedGroupNames(sr.Repository)
+}
+
+// traceResourceView reaches the runtime view of a trace. IndexListener exposes
+// only OnIndexUpdate, so the assertion must happen here -- the same pattern the
+// resource loader in this package uses.
+func traceResourceView(res resourceSchema.Resource) (resourceSchema.ResourceView, bool) {
+ cached, ok := res.Schema().(*databasev1.Trace)
+ if !ok {
+ return resourceSchema.ResourceView{}, false
+ }
+ view := resourceSchema.ResourceView{Name: cached.GetMetadata().GetName(), Cached: cached}
+ if r, isTyped := res.Delegated().(*trace); isTyped {
+ view.Runtime = r.GetSchema()
+ view.RuntimeRules = r.GetIndexRules()
+ }
+ return view, true
+}
+
+// CollectDataInfo collects data info for a specific group. When includeSchemaState
+// is set it also attaches this node's schema consistency evidence.
func (sr *schemaRepo) CollectDataInfo(ctx context.Context, group string) (*databasev1.DataInfo, error) {
if sr.nodeID == "" {
return nil, fmt.Errorf("node ID is empty")
diff --git a/banyand/trace/svc_liaison.go b/banyand/trace/svc_liaison.go
index 053c9c657..f4612cd76 100644
--- a/banyand/trace/svc_liaison.go
+++ b/banyand/trace/svc_liaison.go
@@ -272,7 +272,7 @@ func (l *liaison) PreRun(ctx context.Context) error {
Msg("handoff controller initialized")
}
- l.schemaRepo = newLiaisonSchemaRepo(l.dataPath, l, traceDataNodeRegistry)
+ l.schemaRepo = newLiaisonSchemaRepo(l.dataPath, l, traceDataNodeRegistry, val.(common.Node).NodeID)
l.writeListener = setUpWriteQueueCallback(l.l, &l.schemaRepo, l.maxDiskUsagePercent, l.option.tire2Client)
// Register chunked sync handler for trace and sidx data
@@ -284,6 +284,7 @@ func (l *liaison) PreRun(ctx context.Context) error {
if metaSvc, ok := l.metadata.(metadata.Service); ok {
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_TRACE, l)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_TRACE, &l.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_TRACE, l)
}
@@ -338,7 +339,8 @@ func (l *liaison) CollectDataInfo(_ context.Context, _ string) (*databasev1.Data
return nil, errors.New("collect data info is not supported on liaison node")
}
-// CollectLiaisonInfo collects liaison node info.
+// CollectLiaisonInfo collects liaison node info. When includeSchemaState is set it
+// also attaches this node's schema consistency evidence.
func (l *liaison) CollectLiaisonInfo(_ context.Context, group string) (*databasev1.LiaisonInfo, error) {
info := &databasev1.LiaisonInfo{
PendingWriteDataCount: 0,
diff --git a/banyand/trace/svc_standalone.go b/banyand/trace/svc_standalone.go
index 3382a607b..0e9e667b0 100644
--- a/banyand/trace/svc_standalone.go
+++ b/banyand/trace/svc_standalone.go
@@ -188,6 +188,7 @@ func (s *standalone) PreRun(ctx context.Context) error {
if metaSvc, ok := s.metadata.(metadata.Service); ok {
metaSvc.RegisterDataCollector(commonv1.Catalog_CATALOG_TRACE, &s.schemaRepo)
metaSvc.RegisterLiaisonCollector(commonv1.Catalog_CATALOG_TRACE, s)
+ metaSvc.RegisterSchemaSnapshotCollector(commonv1.Catalog_CATALOG_TRACE, &s.schemaRepo)
metaSvc.RegisterGroupDropHandler(commonv1.Catalog_CATALOG_TRACE, s)
}
subErr := s.pipeline.Subscribe(data.TopicTraceCollectDataInfo, &collectDataInfoListener{s: s})
diff --git a/banyand/trace/write_data_segmentref_test.go b/banyand/trace/write_data_segmentref_test.go
index 6770b9c13..f814dfaa3 100644
--- a/banyand/trace/write_data_segmentref_test.go
+++ b/banyand/trace/write_data_segmentref_test.go
@@ -30,6 +30,7 @@ import (
"github.com/apache/skywalking-banyandb/api/common"
commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
"github.com/apache/skywalking-banyandb/banyand/internal/storage"
metadataschema "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
"github.com/apache/skywalking-banyandb/banyand/protector"
@@ -336,9 +337,16 @@ func (f *fakeRepository) LoadGroup(name string) (resourceSchema.Group, bool) {
return g, ok
}
func (f *fakeRepository) LoadAllGroups() []resourceSchema.Group { return nil }
+
+func (f *fakeRepository) LatestModRevision() int64 { return 0 }
func (f *fakeRepository) LoadResource(_ *commonv1.Metadata) (resourceSchema.Resource, bool) {
return nil, false
}
+func (f *fakeRepository) LoadAllResources(_ string) []resourceSchema.Resource { return nil }
+func (f *fakeRepository) LoadAllIndexRules(_ string) []*databasev1.IndexRule { return nil }
+func (f *fakeRepository) IndexRules(_ resourceSchema.ResourceSchema) []*databasev1.IndexRule {
+ return nil
+}
func (f *fakeRepository) Close() {}
func (f *fakeRepository) StopCh() <-chan struct{} { return nil }
func (f *fakeRepository) DropGroup(_ string) error { return nil }
diff --git a/docs/api-reference.md b/docs/api-reference.md
index f4596eaba..a91417c6f 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -265,6 +265,7 @@
- [MeasureRegistryServiceListResponse](#banyandb-database-v1-MeasureRegistryServiceListResponse)
- [MeasureRegistryServiceUpdateRequest](#banyandb-database-v1-MeasureRegistryServiceUpdateRequest)
- [MeasureRegistryServiceUpdateResponse](#banyandb-database-v1-MeasureRegistryServiceUpdateResponse)
+ - [ObjectSnapshot](#banyandb-database-v1-ObjectSnapshot)
- [PropertyRegistryServiceCreateRequest](#banyandb-database-v1-PropertyRegistryServiceCreateRequest)
- [PropertyRegistryServiceCreateResponse](#banyandb-database-v1-PropertyRegistryServiceCreateResponse)
- [PropertyRegistryServiceDeleteRequest](#banyandb-database-v1-PropertyRegistryServiceDeleteRequest)
@@ -279,7 +280,10 @@
- [PropertyRegistryServiceUpdateResponse](#banyandb-database-v1-PropertyRegistryServiceUpdateResponse)
- [RouteTable](#banyandb-database-v1-RouteTable)
- [SIDXInfo](#banyandb-database-v1-SIDXInfo)
+ - [SchemaBody](#banyandb-database-v1-SchemaBody)
- [SchemaInfo](#banyandb-database-v1-SchemaInfo)
+ - [SchemaRuleTable](#banyandb-database-v1-SchemaRuleTable)
+ - [SchemaSnapshotTrailer](#banyandb-database-v1-SchemaSnapshotTrailer)
- [SegmentInfo](#banyandb-database-v1-SegmentInfo)
- [SeriesIndexInfo](#banyandb-database-v1-SeriesIndexInfo)
- [ShardInfo](#banyandb-database-v1-ShardInfo)
@@ -287,6 +291,8 @@
- [SnapshotRequest](#banyandb-database-v1-SnapshotRequest)
- [SnapshotRequest.Group](#banyandb-database-v1-SnapshotRequest-Group)
- [SnapshotResponse](#banyandb-database-v1-SnapshotResponse)
+ - [StreamGroupSchemaStateRequest](#banyandb-database-v1-StreamGroupSchemaStateRequest)
+ - [StreamGroupSchemaStateResponse](#banyandb-database-v1-StreamGroupSchemaStateResponse)
- [StreamRegistryServiceCreateRequest](#banyandb-database-v1-StreamRegistryServiceCreateRequest)
- [StreamRegistryServiceCreateResponse](#banyandb-database-v1-StreamRegistryServiceCreateResponse)
- [StreamRegistryServiceDeleteRequest](#banyandb-database-v1-StreamRegistryServiceDeleteRequest)
@@ -332,6 +338,7 @@
- [IndexRuleRegistryService](#banyandb-database-v1-IndexRuleRegistryService)
- [MeasureRegistryService](#banyandb-database-v1-MeasureRegistryService)
- [NodeQueryService](#banyandb-database-v1-NodeQueryService)
+ - [NodeSchemaStateService](#banyandb-database-v1-NodeSchemaStateService)
- [PropertyRegistryService](#banyandb-database-v1-PropertyRegistryService)
- [SnapshotService](#banyandb-database-v1-SnapshotService)
- [StreamRegistryService](#banyandb-database-v1-StreamRegistryService)
@@ -354,12 +361,18 @@
- [ListProfiles](#banyandb-fodc-v1-ListProfiles)
- [Metric](#banyandb-fodc-v1-Metric)
- [Metric.LabelsEntry](#banyandb-fodc-v1-Metric-LabelsEntry)
+ - [NodeFingerprint](#banyandb-fodc-v1-NodeFingerprint)
+ - [ObjectConsistency](#banyandb-fodc-v1-ObjectConsistency)
- [PressureProfileChunk](#banyandb-fodc-v1-PressureProfileChunk)
- [PressureProfileInfo](#banyandb-fodc-v1-PressureProfileInfo)
- [PressureProfileRecord](#banyandb-fodc-v1-PressureProfileRecord)
- [RegisterAgentRequest](#banyandb-fodc-v1-RegisterAgentRequest)
- [RegisterAgentRequest.LabelsEntry](#banyandb-fodc-v1-RegisterAgentRequest-LabelsEntry)
- [RegisterAgentResponse](#banyandb-fodc-v1-RegisterAgentResponse)
+ - [SchemaConsistency](#banyandb-fodc-v1-SchemaConsistency)
+ - [SchemaIssue](#banyandb-fodc-v1-SchemaIssue)
+ - [SchemaObjectFingerprint](#banyandb-fodc-v1-SchemaObjectFingerprint)
+ - [SchemaRegistryGroup](#banyandb-fodc-v1-SchemaRegistryGroup)
- [StreamClusterTopologyRequest](#banyandb-fodc-v1-StreamClusterTopologyRequest)
- [StreamClusterTopologyResponse](#banyandb-fodc-v1-StreamClusterTopologyResponse)
- [StreamCrashDiagnosticsRequest](#banyandb-fodc-v1-StreamCrashDiagnosticsRequest)
@@ -370,9 +383,13 @@
- [StreamMetricsResponse](#banyandb-fodc-v1-StreamMetricsResponse)
- [StreamPressureProfilesRequest](#banyandb-fodc-v1-StreamPressureProfilesRequest)
- [StreamPressureProfilesResponse](#banyandb-fodc-v1-StreamPressureProfilesResponse)
+ - [StreamSchemaRegistryRequest](#banyandb-fodc-v1-StreamSchemaRegistryRequest)
+ - [StreamSchemaRegistryResponse](#banyandb-fodc-v1-StreamSchemaRegistryResponse)
- [Topology](#banyandb-fodc-v1-Topology)
+ - [ConsistencyStatus](#banyandb-fodc-v1-ConsistencyStatus)
- [MetricType](#banyandb-fodc-v1-MetricType)
+ - [SchemaIssueType](#banyandb-fodc-v1-SchemaIssueType)
- [FODCService](#banyandb-fodc-v1-FODCService)
- [GroupLifecycleService](#banyandb-fodc-v1-GroupLifecycleService)
@@ -4303,6 +4320,29 @@ LiaisonInfo contains information about pending operations in liaison.
+<a name="banyandb-database-v1-ObjectSnapshot"></a>
+
+### ObjectSnapshot
+ObjectSnapshot carries a schema object as two layers so the agent can compute
+both fingerprints: cache is what the node stored, runtime is what it has
+materialized and is actually serving. runtime is omitted when it equals cache
+(group and indexRule have no derived structure) or when nothing is
+materialized yet -- the agent then takes the runtime fingerprint from cache.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [string](#string) | | group the object belongs to. Always set, so an all-groups stream (empty request group) is self-describing. |
+| kind | [string](#string) | | |
+| name | [string](#string) | | |
+| cache | [SchemaBody](#banyandb-database-v1-SchemaBody) | | |
+| runtime | [SchemaBody](#banyandb-database-v1-SchemaBody) | | |
+
+
+
+
+
+
<a name="banyandb-database-v1-PropertyRegistryServiceCreateRequest"></a>
### PropertyRegistryServiceCreateRequest
@@ -4521,6 +4561,29 @@ SIDXInfo contains information about sidx.
+<a name="banyandb-database-v1-SchemaBody"></a>
+
+### SchemaBody
+SchemaBody is a schema object's proto body plus the index rules it is hashed
+against. payload holds the object itself as an Any: FODC never discriminates
+the catalog type -- it only needs GetMetadata() (via interface, to clear the
+volatile identity fields) and a deterministic marshal -- so a single Any
+replaces a per-type oneof and keeps the hash algorithm out of the data path.
+bound_index_rule_refs indexes into the group's SchemaRuleTable, naming the
+derived rule set the agent hashes with the body without shipping each rule
+body per resource.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| payload | [google.protobuf.Any](#google-protobuf-Any) | | |
+| bound_index_rule_refs | [uint32](#uint32) | repeated | |
+
+
+
+
+
+
<a name="banyandb-database-v1-SchemaInfo"></a>
### SchemaInfo
@@ -4542,6 +4605,53 @@ SchemaInfo contains information about all schema objects in a group.
+<a name="banyandb-database-v1-SchemaRuleTable"></a>
+
+### SchemaRuleTable
+SchemaRuleTable carries a slice of a group's content-deduplicated index-rule
+bodies. Every SchemaBody.bound_index_rule_refs in the group indexes into the
+full table, so a rule bound to many resources -- and folded into both the
+cache and runtime layers -- travels the wire once instead of once per
+(resource, layer). A runtime-stale rule body differs in content from its cache
+counterpart, so the two occupy distinct entries and the cache-vs-runtime
+fingerprint divergence stays observable.
+
+A group with hundreds of rules would overflow a single gRPC message, so the
+table is split across multiple SchemaRuleTable events (all preceding the
+group's object events); the agent concatenates them in arrival order, which
+preserves every ref's index.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [string](#string) | | |
+| rules | [IndexRule](#banyandb-database-v1-IndexRule) | repeated | |
+
+
+
+
+
+
+<a name="banyandb-database-v1-SchemaSnapshotTrailer"></a>
+
+### SchemaSnapshotTrailer
+SchemaSnapshotTrailer terminates one group's objects. A single-group stream
+sends one trailer before EOF; an all-groups stream sends one trailer per group
+(each following that group's object events), then EOF.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [string](#string) | | group these objects belong to. |
+| node | [string](#string) | | node echoes the responding node id so the agent can detect a misrouted response in a mixed-version cluster. |
+| object_count | [uint32](#uint32) | | object_count is the number of object events sent for this group; the agent verifies it against what it received and retries once on a mismatch. |
+| errors | [string](#string) | repeated | errors are failures observed collecting this group. They surface on GroupLifecycleInfo.errors but do not fail the stream. |
+
+
+
+
+
+
<a name="banyandb-database-v1-SegmentInfo"></a>
### SegmentInfo
@@ -4661,6 +4771,45 @@ ShardInfo contains information about a specific shard.
+<a name="banyandb-database-v1-StreamGroupSchemaStateRequest"></a>
+
+### StreamGroupSchemaStateRequest
+StreamGroupSchemaStateRequest asks one node for its schema snapshot. An empty group
+requests every group the node caches (each object and trailer is tagged with
+its group), so a data-node agent -- which has no group roster of its own --
+can collect its whole node in one call.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [string](#string) | | |
+
+
+
+
+
+
+<a name="banyandb-database-v1-StreamGroupSchemaStateResponse"></a>
+
+### StreamGroupSchemaStateResponse
+StreamGroupSchemaStateResponse is the streaming element. Wire-extensible via the oneof so
+new event kinds do not break older agents. Per group the server sends one
+SchemaRuleTable, then that group's ObjectSnapshot events, then one
+SchemaSnapshotTrailer (clean termination) or a non-EOF status (transport
+error).
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| object | [ObjectSnapshot](#banyandb-database-v1-ObjectSnapshot) | | |
+| trailer | [SchemaSnapshotTrailer](#banyandb-database-v1-SchemaSnapshotTrailer) | | |
+| rule_table | [SchemaRuleTable](#banyandb-database-v1-SchemaRuleTable) | | |
+
+
+
+
+
+
<a name="banyandb-database-v1-StreamRegistryServiceCreateRequest"></a>
### StreamRegistryServiceCreateRequest
@@ -5313,6 +5462,21 @@ Phase represents the current phase of the deletion task.
| GetCurrentNode | [GetCurrentNodeRequest](#banyandb-database-v1-GetCurrentNodeRequest) | [GetCurrentNodeResponse](#banyandb-database-v1-GetCurrentNodeResponse) | |
+<a name="banyandb-database-v1-NodeSchemaStateService"></a>
+
+### NodeSchemaStateService
+NodeSchemaStateService streams a node's cached and materialized schema bodies
+for one group. FODC's sidecar agent fingerprints them on receive; the data
+path itself ships no fingerprints. Every data node and liaison that owns a
+group cache implements it.
+
+| Method Name | Request Type | Response Type | Description |
+| ----------- | ------------ | ------------- | ------------|
+| StreamGroupSchemaState | [StreamGroupSchemaStateRequest](#banyandb-database-v1-StreamGroupSchemaStateRequest) | [StreamGroupSchemaStateResponse](#banyandb-database-v1-StreamGroupSchemaStateResponse) stream | StreamGroupSchemaState returns this node's snapshot for one group as a sequence of ObjectSnapshot events terminated by one SchemaSnapshotTrailer. The server snapshots its cache under a read lock, then streams from that consistent view without holding the lock for the network ro [...]
+
+An empty stream (zero object events, just the trailer) is a normal termination: the agent reads it as "this node does not cache this group", never as an error. |
+
+
<a name="banyandb-database-v1-PropertyRegistryService"></a>
### PropertyRegistryService
@@ -5512,6 +5676,7 @@ Phase represents the current phase of the deletion task.
| resource_opts | [banyandb.common.v1.ResourceOpts](#banyandb-common-v1-ResourceOpts) | | |
| data_info | [banyandb.database.v1.DataInfo](#banyandb-database-v1-DataInfo) | repeated | |
| errors | [string](#string) | repeated | errors lists every failure observed while collecting data_info for this group: top-level CollectDataInfo failures (GetGroup, missing collector, dial failure -- prefixed "top-level: ") and per-node broadcast failures (prefixed "future error: ", "node error: ", "broadcast failed: "). Combined with len(data_info), consumers can tell the following four states apart: - data_info empty && errors empty -> no no [...]
+| schema_consistency | [SchemaConsistency](#banyandb-fodc-v1-SchemaConsistency) | | schema_consistency is the verdict on whether this group's schema agrees across the registry, every node's cache, and every node's runtime. Each node's fingerprints (data and liaison) live in schema_consistency.objects. |
@@ -5643,6 +5808,43 @@ Proxy -> Agent: stream all capture-event metadata for this request id.
+<a name="banyandb-fodc-v1-NodeFingerprint"></a>
+
+### NodeFingerprint
+NodeFingerprint is one node's cache/runtime fingerprints for a single object.
+Only the node id is carried; full node info lives in DataInfo/LiaisonInfo.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| node | [string](#string) | | |
+| cache_fingerprint | [uint64](#uint64) | | |
+| runtime_fingerprint | [uint64](#uint64) | | |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-ObjectConsistency"></a>
+
+### ObjectConsistency
+ObjectConsistency is one schema object's fingerprints across all layers: the
+registry truth plus every node that reported it.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| kind | [string](#string) | | kind is schema.Kind.String(). |
+| name | [string](#string) | | |
+| registry_fingerprint | [uint64](#uint64) | | registry_fingerprint is the registry truth; zero when the object exists only on nodes (an orphan) and not in the registry. |
+| node_fingerprints | [NodeFingerprint](#banyandb-fodc-v1-NodeFingerprint) | repeated | |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-PressureProfileChunk"></a>
### PressureProfileChunk
@@ -5757,6 +5959,83 @@ the proxy enriches them from the registered AgentIdentity, same as crash.
+<a name="banyandb-fodc-v1-SchemaConsistency"></a>
+
+### SchemaConsistency
+SchemaConsistency is the single, self-contained schema layer: it holds the
+verdict plus every object's fingerprints across all three layers -- registry
+truth, and each node's cache and runtime -- so DataInfo/LiaisonInfo carry no
+schema of their own.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| status | [ConsistencyStatus](#banyandb-fodc-v1-ConsistencyStatus) | | |
+| objects | [ObjectConsistency](#banyandb-fodc-v1-ObjectConsistency) | repeated | objects lists every schema object in the group exactly once, pairing its registry-truth fingerprint with each node's cache/runtime fingerprints. |
+| issues | [SchemaIssue](#banyandb-fodc-v1-SchemaIssue) | repeated | |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-SchemaIssue"></a>
+
+### SchemaIssue
+SchemaIssue is one object-on-one-node disagreement. Fingerprint values are not
+repeated here; look them up in SchemaConsistency.objects by kind+name (the
+registry truth and that node's cache/runtime).
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| kind | [string](#string) | | kind is schema.Kind.String(). |
+| name | [string](#string) | | |
+| node | [string](#string) | | node is the node id the disagreement was observed on. |
+| type | [SchemaIssueType](#banyandb-fodc-v1-SchemaIssueType) | | |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-SchemaObjectFingerprint"></a>
+
+### SchemaObjectFingerprint
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| kind | [string](#string) | | kind is schema.Kind.String(), matching ObjectConsistency.kind. |
+| name | [string](#string) | | |
+| fingerprint | [uint64](#uint64) | | |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-SchemaRegistryGroup"></a>
+
+### SchemaRegistryGroup
+SchemaRegistryGroup carries one group's authoritative registry fingerprints.
+The agent computes the fingerprints so the wire carries only uint64 digests,
+never raw schema bodies; a group's objects may arrive across several chunks
+that share a group name, which the proxy merges.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [string](#string) | | |
+| objects | [SchemaObjectFingerprint](#banyandb-fodc-v1-SchemaObjectFingerprint) | repeated | |
+| error | [string](#string) | | error is set when this group's registry read failed; its objects are then omitted and the group degrades to UNKNOWN with this reason attached. As a special case, an empty group name with error set is the agent's fatal whole-read failure, which the proxy surfaces across every group. |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-StreamClusterTopologyRequest"></a>
### StreamClusterTopologyRequest
@@ -5920,6 +6199,44 @@ Proxy -> Agent: either "stream all your metadata" or "stream one
+<a name="banyandb-fodc-v1-StreamSchemaRegistryRequest"></a>
+
+### StreamSchemaRegistryRequest
+StreamSchemaRegistryRequest is one message of the selected agent's streamed
+reply to a request_registry command. A group's objects are split across
+messages so no single message carries a whole (potentially large) group; the
+proxy merges chunks that share a group name. The agent ends the round with a
+final message that has done set, which is how the proxy knows to stop waiting.
+A group whose own read failed rides on SchemaRegistryGroup.error; a fatal
+whole-read failure (e.g. the local registry endpoint was unreachable) is a
+single group chunk with an empty group name carrying the error.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| group | [SchemaRegistryGroup](#banyandb-fodc-v1-SchemaRegistryGroup) | | group carries a chunk of one group's registry fingerprints; unset on the final message. Chunks that share a group name are merged by the proxy. |
+| done | [bool](#bool) | | done marks the last message of the round; no group messages follow it. |
+
+
+
+
+
+
+<a name="banyandb-fodc-v1-StreamSchemaRegistryResponse"></a>
+
+### StreamSchemaRegistryResponse
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| request_registry | [bool](#bool) | | Proxy asks the selected agent to read and report the registry fingerprints. |
+
+
+
+
+
+
<a name="banyandb-fodc-v1-Topology"></a>
### Topology
@@ -5938,6 +6255,20 @@ Proxy -> Agent: either "stream all your metadata" or "stream one
+<a name="banyandb-fodc-v1-ConsistencyStatus"></a>
+
+### ConsistencyStatus
+ConsistencyStatus is the group-level rollup.
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| CONSISTENCY_STATUS_UNSPECIFIED | 0 | |
+| CONSISTENCY_STATUS_CONSISTENT | 1 | |
+| CONSISTENCY_STATUS_INCONSISTENT | 2 | |
+| CONSISTENCY_STATUS_UNKNOWN | 3 | Collection was incomplete, or a disagreement has not yet persisted long enough to be reported. |
+
+
+
<a name="banyandb-fodc-v1-MetricType"></a>
### MetricType
@@ -5953,6 +6284,21 @@ MetricType represents the Prometheus metric type.
| METRIC_TYPE_UNTYPED | 5 | |
+
+<a name="banyandb-fodc-v1-SchemaIssueType"></a>
+
+### SchemaIssueType
+SchemaIssueType names which layer boundary the disagreement sits on.
+
+| Name | Number | Description |
+| ---- | ------ | ----------- |
+| SCHEMA_ISSUE_TYPE_UNSPECIFIED | 0 | |
+| SCHEMA_ISSUE_TYPE_MISSING_IN_CACHE | 1 | Registry has it, the node's cache does not. A frequent root cause is the node silently rejecting the schema; grep the node log for "is ignored". |
+| SCHEMA_ISSUE_TYPE_ORPHAN | 2 | The node holds it but the registry does not. |
+| SCHEMA_ISSUE_TYPE_CACHE_STALE | 3 | Registry and cache disagree: the watch is behind. |
+| SCHEMA_ISSUE_TYPE_RUNTIME_NOT_APPLIED | 4 | Cache and runtime disagree: the derived index was never reapplied. |
+
+
@@ -5971,6 +6317,7 @@ MetricType represents the Prometheus metric type.
| StreamLifecycle | [StreamLifecycleRequest](#banyandb-fodc-v1-StreamLifecycleRequest) stream | [StreamLifecycleResponse](#banyandb-fodc-v1-StreamLifecycleResponse) stream | Bi-directional stream for lifecycle data |
| StreamCrashDiagnostics | [StreamCrashDiagnosticsRequest](#banyandb-fodc-v1-StreamCrashDiagnosticsRequest) stream | [StreamCrashDiagnosticsResponse](#banyandb-fodc-v1-StreamCrashDiagnosticsResponse) stream | Bi-directional stream for crash diagnostics Agent sends StreamCrashDiagnosticsRequest (panic collections), Proxy sends StreamCrashDiagnosticsResponse (requests) |
| StreamPressureProfiles | [StreamPressureProfilesRequest](#banyandb-fodc-v1-StreamPressureProfilesRequest) stream | [StreamPressureProfilesResponse](#banyandb-fodc-v1-StreamPressureProfilesResponse) stream | Bi-directional stream for memory-pressure pprof profiles. Proxy drives via StreamPressureProfilesResponse (list metadata, or fetch one profile's bytes); agent replies with StreamPressureProfilesRequest (metadata records, or binary chunks). |
+| StreamSchemaRegistry | [StreamSchemaRegistryRequest](#banyandb-fodc-v1-StreamSchemaRegistryRequest) stream | [StreamSchemaRegistryResponse](#banyandb-fodc-v1-StreamSchemaRegistryResponse) stream | Bi-directional stream for the authoritative schema registry fingerprint. The Proxy picks one schema-serving (liaison) agent by role and drives it via StreamSchemaRegistryResponse (request_registry); that one agent reads the authoritative registry from its local node and replies with StreamSch [...]
<a name="banyandb-fodc-v1-GroupLifecycleService"></a>
diff --git a/docs/operation/grafana-fodc-nodes.json b/docs/operation/grafana-fodc-nodes.json
index d80ecc0d5..3b5a5ec8a 100644
--- a/docs/operation/grafana-fodc-nodes.json
+++ b/docs/operation/grafana-fodc-nodes.json
@@ -659,7 +659,7 @@
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
- "description": "Streaming pod-to-pod flows (excludes tier-migration edges; see the Migration Flows panel below for those). Each row is one directed source\u2192target per (group, operation). Pub side is the publisher container; Sub side is the receiver. Units are per-second (rate over $__range). Pub msg/s and Sub msg/s should match side-to-side; a populated Pub cell with an empty Sub cell is signal \u2014 an uninstrumented side or missing scrape target. p99 latencies are histogram- [...]
+ "description": "Streaming pod-to-pod flows (excludes tier-migration edges; see the Migration Flows panel below for those). Each row is one directed source→target per (group, operation). Pub side is the publisher container; Sub side is the receiver. Units are per-second (rate over $__range). Pub msg/s and Sub msg/s should match side-to-side; a populated Pub cell with an empty Sub cell is signal — an uninstrumented side or missing scrape target. p99 latencies are histogram-quantile o [...]
"fieldConfig": {
"defaults": {
"color": {
@@ -2375,6 +2375,95 @@
],
"title": "Heap Next-GC / Alloc Rate",
"type": "timeseries"
+ },
+ {
+ "id": 62,
+ "type": "stat",
+ "title": "Schema Consistency (per group)",
+ "description": "FODC schema consistency verdict per group from the proxy's checker. Value: 1=CONSISTENT, 2=INCONSISTENT, 3=UNKNOWN. Exported at /metrics as banyandb_fodc_schema_consistency_status{group}.",
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 24,
+ "x": 0,
+ "y": 89
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "${DS_PROMETHEUS}"
+ },
+ "editorMode": "code",
+ "expr": "banyandb_fodc_schema_consistency_status",
+ "instant": true,
+ "legendFormat": "{{group}}",
+ "range": false,
+ "refId": "A"
+ }
+ ],
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "justifyMode": "auto",
+ "orientation": "auto",
+ "textMode": "value_and_name",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "fieldConfig": {
+ "defaults": {
+ "color": {
+ "mode": "thresholds"
+ },
+ "unit": "short",
+ "mappings": [
+ {
+ "type": "value",
+ "options": {
+ "1": {
+ "text": "CONSISTENT",
+ "index": 0
+ },
+ "2": {
+ "text": "INCONSISTENT",
+ "index": 1
+ },
+ "3": {
+ "text": "UNKNOWN",
+ "index": 2
+ }
+ }
+ }
+ ],
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "red",
+ "value": 2
+ },
+ {
+ "color": "yellow",
+ "value": 3
+ }
+ ]
+ }
+ },
+ "overrides": []
+ }
}
],
"schemaVersion": 39,
@@ -2477,8 +2566,8 @@
},
"timepicker": {},
"timezone": "browser",
- "title": "BanyanDB Cluster \u2014 Nodes (FODC Proxy)",
+ "title": "BanyanDB Cluster — Nodes (FODC Proxy)",
"uid": "banyandb-fodc-nodes",
"version": 1,
"weekStart": ""
-}
\ No newline at end of file
+}
diff --git a/fodc/agent/internal/cmd/root.go b/fodc/agent/internal/cmd/root.go
index 79a470f0b..57f05cdbb 100644
--- a/fodc/agent/internal/cmd/root.go
+++ b/fodc/agent/internal/cmd/root.go
@@ -90,6 +90,7 @@ var (
crashOutputCfg = panicdiag.NewCrashOutputConfig()
maxFODCDiagnosisMemoryUsagePercent int
lifecyclePort int
+ schemaRegistryPort int
lifecycleReportDir string
lifecycleCacheTTL time.Duration
pressureProfilerEnabled bool
@@ -150,6 +151,8 @@ func init() {
"Maximum percentage of available memory (based on cgroup memory limit) that can be used for storing diagnosis data in the FODC ring buffer. Valid range: 0-100.")
rootCmd.Flags().IntVar(&lifecyclePort, "lifecycle-port", 18912,
"gRPC port for lifecycle InspectAll service. Set to 0 to disable lifecycle collection")
+ rootCmd.Flags().IntVar(&schemaRegistryPort, "schema-registry-port", 17912,
+ "Local liaison client gRPC port serving the authoritative registry, read only when the proxy selects this agent. Set to 0 to disable")
rootCmd.Flags().StringVar(&lifecycleReportDir, "lifecycle-report-dir", lifecycle.DefaultReportDir,
"Directory where lifecycle sidecar writes report files")
rootCmd.Flags().DurationVar(&lifecycleCacheTTL, "lifecycle-cache-ttl", 10*time.Minute,
@@ -501,11 +504,21 @@ func startProxyClient(ctx context.Context, log *logger.Logger, fr *flightrecorde
// IPv6 loopback (::1), which fails with "cannot assign requested address" in pods
// without an IPv6 loopback.
grpcAddr := fmt.Sprintf("127.0.0.1:%d", lifecyclePort)
- lifecycleCollector = lifecycle.NewCollector(log, grpcAddr, lifecycleReportDir, lifecycleCacheTTL)
- log.Info().Str("grpc_addr", grpcAddr).Msg("Lifecycle collector initialized")
+ var registryAddr string
+ if schemaRegistryPort > 0 {
+ registryAddr = fmt.Sprintf("127.0.0.1:%d", schemaRegistryPort)
+ }
+ lifecycleCollector = lifecycle.NewCollector(log, grpcAddr, registryAddr, lifecycleReportDir, lifecycleCacheTTL)
+ log.Info().Str("grpc_addr", grpcAddr).Str("registry_addr", registryAddr).Msg("Lifecycle collector initialized")
}
client := proxy.NewClient(proxyAddr, nodeRole, podName, containerNames, nodeLabels,
heartbeatInterval, reconnectInterval, fr, collector, lifecycleCollector, collectionLister, profileSource, log)
+ if collector != nil {
+ // Keep the registered node_role fresh: it can resolve after startup (e.g. a
+ // liaison whose client gRPC comes up later than the role-resolution budget),
+ // so heartbeats carry the live value and the proxy upgrades the stored role.
+ client.SetNodeRoleProvider(collector.GetNodeInfo)
+ }
panicdiag.GoWithRecovery(ctx, panicdiag.RecoveryOptions{
Component: "fodc-agent-proxy-client",
Logger: log,
diff --git a/fodc/agent/internal/lifecycle/collector.go b/fodc/agent/internal/lifecycle/collector.go
index 1f94636dc..f5a1812c5 100644
--- a/fodc/agent/internal/lifecycle/collector.go
+++ b/fodc/agent/internal/lifecycle/collector.go
@@ -53,23 +53,28 @@ type Collector struct {
nowFunc func() time.Time
currentData *fodcv1.LifecycleData
grpcAddr string
+ registryAddr string
reportDir string
cacheTTL time.Duration
mu sync.RWMutex
grpcUnimplemented atomic.Bool
}
-// NewCollector creates a new lifecycle data collector.
-func NewCollector(log *logger.Logger, grpcAddr, reportDir string, cacheTTL time.Duration) *Collector {
+// NewCollector creates a new lifecycle data collector. grpcAddr is the local
+// node's lifecycle port (InspectAll + NodeSchemaState, the node's cache view);
+// registryAddr is the local liaison client port that serves the authoritative
+// registry, read only when this agent is the one the proxy selects.
+func NewCollector(log *logger.Logger, grpcAddr, registryAddr, reportDir string, cacheTTL time.Duration) *Collector {
if reportDir == "" {
reportDir = DefaultReportDir
}
return &Collector{
- log: log,
- grpcAddr: grpcAddr,
- reportDir: reportDir,
- cacheTTL: cacheTTL,
- nowFunc: time.Now,
+ log: log,
+ grpcAddr: grpcAddr,
+ registryAddr: registryAddr,
+ reportDir: reportDir,
+ cacheTTL: cacheTTL,
+ nowFunc: time.Now,
}
}
@@ -107,7 +112,10 @@ func (c *Collector) Collect(ctx context.Context) (*fodcv1.LifecycleData, error)
return data, nil
}
-// collectGroups invokes InspectAll on the local liaison.
+// collectGroups invokes InspectAll on the local liaison, then attaches this
+// node's cache/runtime schema fingerprints to the returned groups. The registry
+// truth is NOT collected here: the proxy fetches it once from a schema-serving
+// node, so every agent only reports its own node's state.
//
// Return contract:
// - (nil, nil): no RPC was issued (grpcAddr empty, or InspectAll already known to be Unimplemented).
@@ -141,11 +149,23 @@ func (c *Collector) collectGroups(ctx context.Context) ([]*fodcv1.GroupLifecycle
}
return nil, fmt.Errorf("InspectAll on %s: %w", c.grpcAddr, err)
}
- got := resp.GetGroups()
- if got == nil {
- return []*fodcv1.GroupLifecycleInfo{}, nil
+ groups := resp.GetGroups()
+ if groups == nil {
+ groups = []*fodcv1.GroupLifecycleInfo{}
}
- return got, nil
+ states, schemaErr := c.collectNodeSchemaState(ctx)
+ if schemaErr != nil {
+ if c.log != nil {
+ c.log.Warn().Err(schemaErr).Msg("schema state collection failed; reporting lifecycle without it")
+ }
+ // Surface it to the user, not just the log: every group loses this node's
+ // schema evidence this round, so the proxy will report UNKNOWN -- each group
+ // should carry the reason.
+ for _, g := range groups {
+ g.Errors = append(g.Errors, "node schema state: "+schemaErr.Error())
+ }
+ }
+ return applySchemaStates(groups, states), nil
}
func (c *Collector) readReportFiles() []*fodcv1.LifecycleReport {
diff --git a/fodc/agent/internal/lifecycle/collector_test.go b/fodc/agent/internal/lifecycle/collector_test.go
index ab44d5053..33afa784a 100644
--- a/fodc/agent/internal/lifecycle/collector_test.go
+++ b/fodc/agent/internal/lifecycle/collector_test.go
@@ -103,7 +103,7 @@ func startLocalServer(t *testing.T, fake *fakeLifecycleService) string {
func newCollectorForFake(t *testing.T, fake *fakeLifecycleService, cacheTTL time.Duration) *Collector {
t.Helper()
addr := startLocalServer(t, fake)
- return NewCollector(initTestLogger(t), addr, t.TempDir(), cacheTTL)
+ return NewCollector(initTestLogger(t), addr, "", t.TempDir(), cacheTTL)
}
func sampleGroup(name string) *fodcv1.GroupLifecycleInfo {
@@ -112,7 +112,7 @@ func sampleGroup(name string) *fodcv1.GroupLifecycleInfo {
func TestNewCollector(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", "", 10*time.Minute)
+ collector := NewCollector(log, "", "", "", 10*time.Minute)
require.NotNil(t, collector)
assert.Nil(t, collector.currentData)
assert.Equal(t, 10*time.Minute, collector.cacheTTL)
@@ -120,14 +120,14 @@ func TestNewCollector(t *testing.T) {
func TestCollector_ReadReportFiles_EmptyDir(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", t.TempDir(), 0)
+ collector := NewCollector(log, "", "", t.TempDir(), 0)
reports := collector.readReportFiles()
assert.Empty(t, reports)
}
func TestCollector_Collect_NoGRPC(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", "", 0)
+ collector := NewCollector(log, "", "", "", 0)
data, err := collector.Collect(t.Context())
require.NoError(t, err)
require.NotNil(t, data)
@@ -136,7 +136,7 @@ func TestCollector_Collect_NoGRPC(t *testing.T) {
func TestCollector_CacheTTL(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", "", 5*time.Minute)
+ collector := NewCollector(log, "", "", "", 5*time.Minute)
ctx := t.Context()
now := time.Now()
@@ -163,7 +163,7 @@ func TestCollector_CacheTTL(t *testing.T) {
func TestCollector_ZeroTTL_AlwaysRefreshes(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", "", 0)
+ collector := NewCollector(log, "", "", "", 0)
ctx := t.Context()
data1, err := collector.Collect(ctx)
@@ -179,7 +179,7 @@ func TestCollector_ZeroTTL_AlwaysRefreshes(t *testing.T) {
func TestCollector_ReadReportFiles_MaxFiles(t *testing.T) {
log := initTestLogger(t)
dir := t.TempDir()
- collector := NewCollector(log, "", dir, 0)
+ collector := NewCollector(log, "", "", dir, 0)
for idx, name := range []string{
"2026-03-20.json",
@@ -211,7 +211,7 @@ func TestCollector_ReadReportFiles_MaxFiles(t *testing.T) {
func TestCollector_ReadReportFiles_SkipsNonJSON(t *testing.T) {
log := initTestLogger(t)
dir := t.TempDir()
- collector := NewCollector(log, "", dir, 0)
+ collector := NewCollector(log, "", "", dir, 0)
require.NoError(t, os.WriteFile(filepath.Join(dir, "2026-03-26.json"), []byte(`{}`), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(dir, "readme.txt"), []byte("text"), 0o600))
@@ -225,7 +225,7 @@ func TestCollector_ReadReportFiles_SkipsNonJSON(t *testing.T) {
func TestCollector_ReadReportFiles_OversizedFile(t *testing.T) {
log := initTestLogger(t)
dir := t.TempDir()
- collector := NewCollector(log, "", dir, 0)
+ collector := NewCollector(log, "", "", dir, 0)
require.NoError(t, os.WriteFile(filepath.Join(dir, "2026-03-26.json"), []byte(`{"ok":true}`), 0o600))
oversized := make([]byte, maxReportFileSize+1)
@@ -238,7 +238,7 @@ func TestCollector_ReadReportFiles_OversizedFile(t *testing.T) {
func TestCollectGroups_NoGRPCAddrShortCircuits(t *testing.T) {
log := initTestLogger(t)
- collector := NewCollector(log, "", "", 0)
+ collector := NewCollector(log, "", "", "", 0)
groups, err := collector.collectGroups(t.Context())
require.NoError(t, err)
assert.Nil(t, groups)
diff --git a/fodc/agent/internal/lifecycle/registry.go b/fodc/agent/internal/lifecycle/registry.go
new file mode 100644
index 000000000..ff9b9431e
--- /dev/null
+++ b/fodc/agent/internal/lifecycle/registry.go
@@ -0,0 +1,254 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ "context"
+ "fmt"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
+ "github.com/apache/skywalking-banyandb/fodc/internal/timeouts"
+)
+
+// Kind strings match schema.Kind.String(), the same values the node stamps on
+// ObjectSnapshot.kind, so registry and node fingerprints key on the same object.
+const (
+ kindGroup = "group"
+ kindStream = "stream"
+ kindMeasure = "measure"
+ kindTrace = "trace"
+ kindIndexRule = "indexRule"
+)
+
+// registryObjectFP is one registry object's truth fingerprint.
+type registryObjectFP struct {
+ kind string
+ name string
+ fp uint64
+}
+
+// FetchSchemaRegistry reads the authoritative registry from the local liaison
+// client endpoint and returns its per-object fingerprints, one entry per group,
+// which the agent streams to the proxy. Fingerprint compute lives here in the
+// FODC agent, never in the banyandb data path, and it runs only on the one agent
+// the proxy selects, so the authoritative registry is read once per collection
+// cycle. A fatal read failure is returned as an error (the proxy surfaces it
+// rather than silently degrading to UNKNOWN); a group whose own read failed is
+// returned as a group carrying its error and no objects.
+func (c *Collector) FetchSchemaRegistry(ctx context.Context) ([]*fodcv1.SchemaRegistryGroup, error) {
+ if c.registryAddr == "" {
+ return nil, fmt.Errorf("no schema-registry address configured")
+ }
+ byGroup, groupErrs, err := fetchRegistryFingerprints(ctx, c.registryAddr)
+ if err != nil {
+ return nil, err
+ }
+ groups := make([]*fodcv1.SchemaRegistryGroup, 0, len(byGroup)+len(groupErrs))
+ for group, objects := range byGroup {
+ sg := &fodcv1.SchemaRegistryGroup{Group: group, Objects: make([]*fodcv1.SchemaObjectFingerprint, 0, len(objects))}
+ for key, fp := range objects {
+ sg.Objects = append(sg.Objects, &fodcv1.SchemaObjectFingerprint{Kind: key.Kind, Name: key.Name, Fingerprint: fp})
+ }
+ groups = append(groups, sg)
+ }
+ for group, e := range groupErrs {
+ groups = append(groups, &fodcv1.SchemaRegistryGroup{Group: group, Error: e})
+ }
+ return groups, nil
+}
+
+// fetchRegistryFingerprints dials the local schema-serving node and computes the
+// registry-truth fingerprint of every object in every group. It returns the
+// per-group fingerprints; the per-group read errors (a group whose registry read
+// fails is omitted from the map so the checker degrades it to UNKNOWN, but the
+// reason is returned so the caller can surface it); and a fatal error when the
+// node itself is unreachable.
+func fetchRegistryFingerprints(
+ ctx context.Context, address string,
+) (map[string]map[consistency.ObjectKey]uint64, map[string]string, error) {
+ conn, err := grpc.NewClient(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return nil, nil, fmt.Errorf("dial %s: %w", address, err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ reqCtx, cancel := context.WithTimeout(ctx, timeouts.AgentInspectAll)
+ defer cancel()
+ groupClient := databasev1.NewGroupRegistryServiceClient(conn)
+ listResp, err := groupClient.List(reqCtx, &databasev1.GroupRegistryServiceListRequest{})
+ if err != nil {
+ return nil, nil, fmt.Errorf("list groups on %s: %w", address, err)
+ }
+
+ out := make(map[string]map[consistency.ObjectKey]uint64, len(listResp.GetGroup()))
+ groupErrs := make(map[string]string)
+ for _, group := range listResp.GetGroup() {
+ name := group.GetMetadata().GetName()
+ objects, fpErr := registryFingerprintsForGroup(reqCtx, conn, group)
+ if fpErr != nil {
+ groupErrs[name] = fpErr.Error()
+ continue
+ }
+ m := make(map[consistency.ObjectKey]uint64, len(objects))
+ for _, ro := range objects {
+ m[consistency.ObjectKey{Kind: ro.kind, Name: ro.name}] = ro.fp
+ }
+ out[name] = m
+ }
+ return out, groupErrs, nil
+}
+
+// registryFingerprintsForGroup fingerprints every object in one group's registry
+// view (group, index rules, and each resource with its derived bound rules).
+func registryFingerprintsForGroup(
+ ctx context.Context, conn *grpc.ClientConn, group *commonv1.Group,
+) ([]registryObjectFP, error) {
+ groupName := group.GetMetadata().GetName()
+ var objects []registryObjectFP
+
+ groupFP, err := consistency.Fingerprint(group, nil)
+ if err != nil {
+ return nil, fmt.Errorf("fingerprint group %s: %w", groupName, err)
+ }
+ objects = append(objects, registryObjectFP{kind: kindGroup, name: groupName, fp: groupFP})
+
+ ruleClient := databasev1.NewIndexRuleRegistryServiceClient(conn)
+ ruleResp, err := ruleClient.List(ctx, &databasev1.IndexRuleRegistryServiceListRequest{Group: groupName})
+ if err != nil {
+ return nil, fmt.Errorf("list index rules of %s: %w", groupName, err)
+ }
+ ruleIndex := make(map[string]*databasev1.IndexRule, len(ruleResp.GetIndexRule()))
+ for _, rule := range ruleResp.GetIndexRule() {
+ name := rule.GetMetadata().GetName()
+ ruleIndex[groupName+"/"+name] = rule
+ ruleFP, ruleErr := consistency.Fingerprint(rule, nil)
+ if ruleErr != nil {
+ return nil, fmt.Errorf("fingerprint index rule %s: %w", name, ruleErr)
+ }
+ objects = append(objects, registryObjectFP{kind: kindIndexRule, name: name, fp: ruleFP})
+ }
+
+ bindingClient := databasev1.NewIndexRuleBindingRegistryServiceClient(conn)
+ bindingResp, err := bindingClient.List(ctx, &databasev1.IndexRuleBindingRegistryServiceListRequest{Group: groupName})
+ if err != nil {
+ return nil, fmt.Errorf("list index rule bindings of %s: %w", groupName, err)
+ }
+ lookups := registryLookupSet{
+ bindings: registryBindingLookup{bindings: bindingResp.GetIndexRuleBinding(), catalog: group.GetCatalog()},
+ rules: registryRuleLookup{rules: ruleIndex},
+ }
+
+ resources, resErr := registryResourceFingerprints(ctx, conn, group, lookups)
+ if resErr != nil {
+ return nil, resErr
+ }
+ return append(objects, resources...), nil
+}
+
+func registryResourceFingerprints(
+ ctx context.Context, conn *grpc.ClientConn, group *commonv1.Group, lookups registryLookupSet,
+) ([]registryObjectFP, error) {
+ groupName := group.GetMetadata().GetName()
+ var objects []registryObjectFP
+ add := func(kind, name string, fp uint64) {
+ objects = append(objects, registryObjectFP{kind: kind, name: name, fp: fp})
+ }
+ switch group.GetCatalog() {
+ case commonv1.Catalog_CATALOG_STREAM:
+ resp, err := databasev1.NewStreamRegistryServiceClient(conn).List(ctx, &databasev1.StreamRegistryServiceListRequest{Group: groupName})
+ if err != nil {
+ return nil, fmt.Errorf("list streams of %s: %w", groupName, err)
+ }
+ for _, spec := range resp.GetStream() {
+ name := spec.GetMetadata().GetName()
+ fp, fpErr := consistency.Fingerprint(spec, consistency.DeriveBoundRules(groupName, name, lookups.bindings, lookups.rules))
+ if fpErr != nil {
+ return nil, fmt.Errorf("fingerprint stream %s: %w", name, fpErr)
+ }
+ add(kindStream, name, fp)
+ }
+ case commonv1.Catalog_CATALOG_MEASURE:
+ resp, err := databasev1.NewMeasureRegistryServiceClient(conn).List(ctx, &databasev1.MeasureRegistryServiceListRequest{Group: groupName})
+ if err != nil {
+ return nil, fmt.Errorf("list measures of %s: %w", groupName, err)
+ }
+ for _, spec := range resp.GetMeasure() {
+ name := spec.GetMetadata().GetName()
+ fp, fpErr := consistency.Fingerprint(spec, consistency.DeriveBoundRules(groupName, name, lookups.bindings, lookups.rules))
+ if fpErr != nil {
+ return nil, fmt.Errorf("fingerprint measure %s: %w", name, fpErr)
+ }
+ add(kindMeasure, name, fp)
+ }
+ case commonv1.Catalog_CATALOG_TRACE:
+ resp, err := databasev1.NewTraceRegistryServiceClient(conn).List(ctx, &databasev1.TraceRegistryServiceListRequest{Group: groupName})
+ if err != nil {
+ return nil, fmt.Errorf("list traces of %s: %w", groupName, err)
+ }
+ for _, spec := range resp.GetTrace() {
+ name := spec.GetMetadata().GetName()
+ fp, fpErr := consistency.Fingerprint(spec, consistency.DeriveBoundRules(groupName, name, lookups.bindings, lookups.rules))
+ if fpErr != nil {
+ return nil, fmt.Errorf("fingerprint trace %s: %w", name, fpErr)
+ }
+ add(kindTrace, name, fp)
+ }
+ default:
+ // PROPERTY and unspecified groups hold no fingerprintable resources.
+ }
+ return objects, nil
+}
+
+// registryLookupSet pairs the two adapters DeriveBoundRules needs.
+type registryLookupSet struct {
+ rules registryRuleLookup
+ bindings registryBindingLookup
+}
+
+// registryBindingLookup scopes registry bindings to one subject and catalog,
+// matching the node-side cache's catalog-filtered (but not validity-window
+// filtered) binding index.
+type registryBindingLookup struct {
+ bindings []*databasev1.IndexRuleBinding
+ catalog commonv1.Catalog
+}
+
+func (l registryBindingLookup) BindingsOf(_, name string) []*databasev1.IndexRuleBinding {
+ var result []*databasev1.IndexRuleBinding
+ for _, b := range l.bindings {
+ if b.GetSubject().GetName() == name && b.GetSubject().GetCatalog() == l.catalog {
+ result = append(result, b)
+ }
+ }
+ return result
+}
+
+// registryRuleLookup resolves rules from the batch already listed for the group.
+type registryRuleLookup struct {
+ rules map[string]*databasev1.IndexRule
+}
+
+func (l registryRuleLookup) Rule(group, name string) *databasev1.IndexRule {
+ return l.rules[group+"/"+name]
+}
diff --git a/fodc/agent/internal/lifecycle/schema_partial_internal_test.go b/fodc/agent/internal/lifecycle/schema_partial_internal_test.go
new file mode 100644
index 000000000..e066df14a
--- /dev/null
+++ b/fodc/agent/internal/lifecycle/schema_partial_internal_test.go
@@ -0,0 +1,87 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+func TestToSchemaConsistency_EmitsNodeFingerprints(t *testing.T) {
+ st := newGroupSchemaState()
+ st.node = "data-1"
+ o := st.object("stream", "foo")
+ o.cache, o.runtime, o.hasNode = 10, 11, true
+
+ sc := st.toSchemaConsistency()
+
+ require.Len(t, sc.GetObjects(), 1)
+ got := sc.GetObjects()[0]
+ assert.Zero(t, got.GetRegistryFingerprint(), "the agent never sets the registry fingerprint; the proxy fetches it")
+ require.Len(t, got.GetNodeFingerprints(), 1)
+ nf := got.GetNodeFingerprints()[0]
+ assert.Equal(t, "data-1", nf.GetNode())
+ assert.Equal(t, uint64(10), nf.GetCacheFingerprint())
+ assert.Equal(t, uint64(11), nf.GetRuntimeFingerprint())
+}
+
+// When the trailer never arrived the node id is unknown; a node fingerprint
+// stamped with "" would merge into a phantom node at the proxy, so it is dropped.
+func TestToSchemaConsistency_DropsNodeFingerprintWhenNodeUnknown(t *testing.T) {
+ st := newGroupSchemaState()
+ o := st.object("stream", "foo")
+ o.cache, o.runtime, o.hasNode = 10, 10, true
+
+ sc := st.toSchemaConsistency()
+
+ require.Len(t, sc.GetObjects(), 1)
+ assert.Empty(t, sc.GetObjects()[0].GetNodeFingerprints(), "a node fingerprint without a node id is dropped")
+}
+
+func TestApplySchemaStates_AttachesToExistingAndAppendsUnknown(t *testing.T) {
+ groups := []*fodcv1.GroupLifecycleInfo{{Name: "existing"}}
+
+ existing := newGroupSchemaState()
+ existing.node = "n1"
+ existing.object("group", "existing").hasNode = true
+ existing.errors = []string{"collect: boom"}
+
+ unknown := newGroupSchemaState()
+ unknown.node = "n1"
+ unknown.object("group", "unknown").hasNode = true
+
+ out := applySchemaStates(groups, map[string]*groupSchemaState{
+ "existing": existing,
+ "unknown": unknown,
+ })
+
+ byName := make(map[string]*fodcv1.GroupLifecycleInfo, len(out))
+ for _, g := range out {
+ byName[g.GetName()] = g
+ }
+ require.Contains(t, byName, "existing")
+ require.Contains(t, byName, "unknown")
+ assert.NotNil(t, byName["existing"].GetSchemaConsistency(), "schema attaches to the InspectAll group entry")
+ assert.Contains(t, byName["existing"].GetErrors(), "collect: boom", "collection errors ride on the group entry")
+ assert.NotNil(t, byName["unknown"].GetSchemaConsistency(),
+ "a group InspectAll did not return still carries its node's schema evidence")
+}
diff --git a/fodc/agent/internal/lifecycle/schema_state.go b/fodc/agent/internal/lifecycle/schema_state.go
new file mode 100644
index 000000000..0c157f3c7
--- /dev/null
+++ b/fodc/agent/internal/lifecycle/schema_state.go
@@ -0,0 +1,255 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials/insecure"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/proto"
+
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
+ "github.com/apache/skywalking-banyandb/fodc/internal/timeouts"
+)
+
+// groupObjectState is one schema object's cache/runtime fingerprints on the
+// local node. The proxy unions these partials across agents and pairs them with
+// the registry truth it fetches itself.
+type groupObjectState struct {
+ kind string
+ name string
+ cache uint64
+ runtime uint64
+ hasNode bool
+}
+
+// groupSchemaState accumulates one group's per-object evidence, the local node
+// id, and any collection errors.
+type groupSchemaState struct {
+ objects map[consistency.ObjectKey]*groupObjectState
+ node string
+ errors []string
+}
+
+func newGroupSchemaState() *groupSchemaState {
+ return &groupSchemaState{objects: make(map[consistency.ObjectKey]*groupObjectState)}
+}
+
+func (s *groupSchemaState) object(kind, name string) *groupObjectState {
+ key := consistency.ObjectKey{Kind: kind, Name: name}
+ o, ok := s.objects[key]
+ if !ok {
+ o = &groupObjectState{kind: kind, name: name}
+ s.objects[key] = o
+ }
+ return o
+}
+
+// toSchemaConsistency renders this agent's partial view of a group: an
+// object-centric table carrying this node's cache/runtime fingerprints. It sets
+// no registry fingerprint (the proxy fetches the registry truth) and leaves
+// Status UNSPECIFIED -- the proxy assigns the verdict after unioning every
+// agent's partial and comparing against the registry.
+func (s *groupSchemaState) toSchemaConsistency() *fodcv1.SchemaConsistency {
+ objects := make([]*fodcv1.ObjectConsistency, 0, len(s.objects))
+ for _, o := range s.objects {
+ oc := &fodcv1.ObjectConsistency{Kind: o.kind, Name: o.name}
+ // A node fingerprint without a node id (the trailer never arrived) would
+ // merge into a phantom "" node at the proxy; drop it and let the errors
+ // this group also carries drive the UNKNOWN verdict.
+ if o.hasNode && s.node != "" {
+ oc.NodeFingerprints = []*fodcv1.NodeFingerprint{{
+ Node: s.node, CacheFingerprint: o.cache, RuntimeFingerprint: o.runtime,
+ }}
+ }
+ objects = append(objects, oc)
+ }
+ consistency.SortObjectConsistencies(objects)
+ return &fodcv1.SchemaConsistency{Objects: objects}
+}
+
+// applySchemaStates folds each group's schema evidence into the matching
+// GroupLifecycleInfo (its schema_consistency partial and any collection errors),
+// creating a bare entry only for a group InspectAll did not return. The proxy
+// unions these partials across agents and overwrites schema_consistency with the
+// final verdict.
+func applySchemaStates(groups []*fodcv1.GroupLifecycleInfo, states map[string]*groupSchemaState) []*fodcv1.GroupLifecycleInfo {
+ byName := make(map[string]*fodcv1.GroupLifecycleInfo, len(groups))
+ for _, g := range groups {
+ byName[g.GetName()] = g
+ }
+ for name, st := range states {
+ g, ok := byName[name]
+ if !ok {
+ g = &fodcv1.GroupLifecycleInfo{Name: name}
+ byName[name] = g
+ groups = append(groups, g)
+ }
+ g.SchemaConsistency = st.toSchemaConsistency()
+ if len(st.errors) > 0 {
+ g.Errors = append(g.Errors, st.errors...)
+ }
+ }
+ return groups
+}
+
+// collectNodeSchemaState streams the local node's schema bodies and fingerprints
+// them here (not in the data path), producing one groupSchemaState per group.
+// An Unimplemented server (older node, or a role without the service) yields
+// (nil, nil): the agent simply contributes no node schema state. A transport
+// error is propagated so the caller does not cache a torn result.
+func (c *Collector) collectNodeSchemaState(ctx context.Context) (map[string]*groupSchemaState, error) {
+ if c.grpcAddr == "" {
+ return nil, nil
+ }
+ conn, err := grpc.NewClient(c.grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return nil, fmt.Errorf("dial %s: %w", c.grpcAddr, err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ client := databasev1.NewNodeSchemaStateServiceClient(conn)
+ reqCtx, cancel := context.WithTimeout(ctx, timeouts.AgentInspectAll)
+ defer cancel()
+ stream, err := client.StreamGroupSchemaState(reqCtx, &databasev1.StreamGroupSchemaStateRequest{})
+ if err != nil {
+ if status.Code(err) == codes.Unimplemented {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("StreamGroupSchemaState on %s: %w", c.grpcAddr, err)
+ }
+
+ states := make(map[string]*groupSchemaState)
+ received := make(map[string]uint32)
+ tables := make(map[string][]*databasev1.IndexRule)
+ get := func(group string) *groupSchemaState {
+ s, ok := states[group]
+ if !ok {
+ s = newGroupSchemaState()
+ states[group] = s
+ }
+ return s
+ }
+ for {
+ event, recvErr := stream.Recv()
+ if errors.Is(recvErr, io.EOF) {
+ break
+ }
+ if recvErr != nil {
+ if status.Code(recvErr) == codes.Unimplemented {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("recv schema state from %s: %w", c.grpcAddr, recvErr)
+ }
+ switch e := event.GetEvent().(type) {
+ case *databasev1.StreamGroupSchemaStateResponse_RuleTable:
+ // The node may split a group's rule table across several events;
+ // concatenating in arrival order keeps bound_index_rule_refs valid.
+ g := e.RuleTable.GetGroup()
+ tables[g] = append(tables[g], e.RuleTable.GetRules()...)
+ case *databasev1.StreamGroupSchemaStateResponse_Object:
+ obj := e.Object
+ st := get(obj.GetGroup())
+ cacheFP, runtimeFP, fpErr := fingerprintObjectSnapshot(obj, tables[obj.GetGroup()])
+ if fpErr != nil {
+ st.errors = append(st.errors, fpErr.Error())
+ continue
+ }
+ o := st.object(obj.GetKind(), obj.GetName())
+ o.cache, o.runtime, o.hasNode = cacheFP, runtimeFP, true
+ received[obj.GetGroup()]++
+ case *databasev1.StreamGroupSchemaStateResponse_Trailer:
+ t := e.Trailer
+ st := get(t.GetGroup())
+ st.node = t.GetNode()
+ st.errors = append(st.errors, t.GetErrors()...)
+ // A count mismatch means the stream tore mid-flight; flag it so the
+ // proxy checker degrades this node to UNKNOWN rather than reading the
+ // partial set as a real divergence.
+ if received[t.GetGroup()] != t.GetObjectCount() {
+ st.errors = append(st.errors, fmt.Sprintf(
+ "torn stream: received %d objects, trailer reported %d",
+ received[t.GetGroup()], t.GetObjectCount()))
+ }
+ }
+ }
+
+ return states, nil
+}
+
+// fingerprintObjectSnapshot hashes an object's cache and runtime bodies against
+// the group's rule table. Runtime is absent for objects with no derived
+// structure (group, indexRule) or when nothing is materialized yet, in which
+// case the runtime fingerprint equals the cache one -- matching the node-side
+// semantics the checker expects.
+func fingerprintObjectSnapshot(obj *databasev1.ObjectSnapshot, table []*databasev1.IndexRule) (cacheFP, runtimeFP uint64, err error) {
+ cacheBody, cacheRules, err := schemaBodyPayload(obj.GetCache(), table)
+ if err != nil {
+ return 0, 0, fmt.Errorf("resolve cache %s %q: %w", obj.GetKind(), obj.GetName(), err)
+ }
+ cacheFP, err = consistency.Fingerprint(cacheBody, cacheRules)
+ if err != nil {
+ return 0, 0, fmt.Errorf("fingerprint cache %s %q: %w", obj.GetKind(), obj.GetName(), err)
+ }
+ runtimeFP = cacheFP
+ if runtime := obj.GetRuntime(); runtime != nil {
+ runtimeBody, runtimeRules, resolveErr := schemaBodyPayload(runtime, table)
+ if resolveErr != nil {
+ return 0, 0, fmt.Errorf("resolve runtime %s %q: %w", obj.GetKind(), obj.GetName(), resolveErr)
+ }
+ runtimeFP, err = consistency.Fingerprint(runtimeBody, runtimeRules)
+ if err != nil {
+ return 0, 0, fmt.Errorf("fingerprint runtime %s %q: %w", obj.GetKind(), obj.GetName(), err)
+ }
+ }
+ return cacheFP, runtimeFP, nil
+}
+
+// schemaBodyPayload unwraps the Any payload into its concrete proto and resolves
+// its bound_index_rule_refs against the group's rule table. A ref outside the
+// table means the stream tore or the table event was lost; that is an error so
+// the caller degrades the node to UNKNOWN rather than hashing a partial rule set.
+func schemaBodyPayload(body *databasev1.SchemaBody, table []*databasev1.IndexRule) (proto.Message, []*databasev1.IndexRule, error) {
+ if body == nil {
+ return nil, nil, nil
+ }
+ payload, err := body.GetPayload().UnmarshalNew()
+ if err != nil {
+ return nil, nil, fmt.Errorf("unwrap schema body payload: %w", err)
+ }
+ refs := body.GetBoundIndexRuleRefs()
+ if len(refs) == 0 {
+ return payload, nil, nil
+ }
+ rules := make([]*databasev1.IndexRule, 0, len(refs))
+ for _, ref := range refs {
+ if int(ref) >= len(table) {
+ return nil, nil, fmt.Errorf("bound index rule ref %d out of range (table size %d)", ref, len(table))
+ }
+ rules = append(rules, table[ref])
+ }
+ return payload, rules, nil
+}
diff --git a/fodc/agent/internal/lifecycle/schema_state_internal_test.go b/fodc/agent/internal/lifecycle/schema_state_internal_test.go
new file mode 100644
index 000000000..a3e947772
--- /dev/null
+++ b/fodc/agent/internal/lifecycle/schema_state_internal_test.go
@@ -0,0 +1,109 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/anypb"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
+)
+
+func mustAny(t *testing.T, m proto.Message) *anypb.Any {
+ t.Helper()
+ a, err := anypb.New(m)
+ require.NoError(t, err)
+ return a
+}
+
+func streamBody(tag string) *databasev1.Stream {
+ return &databasev1.Stream{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "foo"},
+ Entity: &databasev1.Entity{TagNames: []string{tag}},
+ }
+}
+
+func ruleBody(name, tag string) *databasev1.IndexRule {
+ return &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g", Name: name},
+ Tags: []string{tag},
+ }
+}
+
+// The agent must reconstruct exactly the fingerprint the node would have
+// computed inline: unwrap the Any payload, resolve the refs against the table,
+// and hash. If either step drifts, this equality breaks.
+func TestFingerprintObjectSnapshot_ResolvesRefsMatchingDirectFingerprint(t *testing.T) {
+ r0 := ruleBody("r0", "a")
+ r1 := ruleBody("r1", "b")
+ table := []*databasev1.IndexRule{r0, r1}
+ body := streamBody("service_id")
+
+ obj := &databasev1.ObjectSnapshot{
+ Group: "g", Kind: "measure", Name: "foo",
+ Cache: &databasev1.SchemaBody{Payload: mustAny(t, body), BoundIndexRuleRefs: []uint32{0, 1}},
+ }
+
+ cacheFP, runtimeFP, err := fingerprintObjectSnapshot(obj, table)
+ require.NoError(t, err)
+
+ want, err := consistency.Fingerprint(body, []*databasev1.IndexRule{r0, r1})
+ require.NoError(t, err)
+ assert.Equal(t, want, cacheFP, "resolving refs against the table reproduces the direct fingerprint")
+ assert.Equal(t, cacheFP, runtimeFP, "an object with no runtime body takes its runtime fingerprint from cache")
+}
+
+// This is the invariant that forbids collapsing the table by rule name: the
+// cache and runtime layers reference two table entries that share a name but
+// differ in body, and the two fingerprints must stay distinct so the checker
+// can report RUNTIME_NOT_APPLIED.
+func TestFingerprintObjectSnapshot_RuntimeDivergenceSurvivesInterning(t *testing.T) {
+ table := []*databasev1.IndexRule{ruleBody("r0", "new"), ruleBody("r0", "stale")}
+ body := streamBody("service_id")
+
+ obj := &databasev1.ObjectSnapshot{
+ Group: "g", Kind: "measure", Name: "foo",
+ Cache: &databasev1.SchemaBody{Payload: mustAny(t, body), BoundIndexRuleRefs: []uint32{0}},
+ Runtime: &databasev1.SchemaBody{Payload: mustAny(t, body), BoundIndexRuleRefs: []uint32{1}},
+ }
+
+ cacheFP, runtimeFP, err := fingerprintObjectSnapshot(obj, table)
+ require.NoError(t, err)
+ assert.NotEqual(t, cacheFP, runtimeFP, "a stale runtime rule body must still produce a divergent fingerprint")
+}
+
+// A ref past the end of the table means the table event was lost or the stream
+// tore; the agent must error so the proxy checker degrades the node to UNKNOWN
+// instead of hashing a truncated rule set as if it were real drift.
+func TestFingerprintObjectSnapshot_RefOutOfRangeErrors(t *testing.T) {
+ table := []*databasev1.IndexRule{ruleBody("r0", "a")}
+ obj := &databasev1.ObjectSnapshot{
+ Group: "g", Kind: "measure", Name: "foo",
+ Cache: &databasev1.SchemaBody{Payload: mustAny(t, streamBody("service_id")), BoundIndexRuleRefs: []uint32{5}},
+ }
+
+ _, _, err := fingerprintObjectSnapshot(obj, table)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "out of range")
+}
diff --git a/fodc/agent/internal/proxy/client.go b/fodc/agent/internal/proxy/client.go
index 0328d2ca3..6796217eb 100644
--- a/fodc/agent/internal/proxy/client.go
+++ b/fodc/agent/internal/proxy/client.go
@@ -58,25 +58,27 @@ type MetricsRequestFilter struct {
// Client manages connection and communication with the FODC Proxy.
type Client struct {
- logger *logger.Logger
- heartbeatTicker *time.Ticker
- flightRecorder *flightrecorder.FlightRecorder
- connManager *connManager
- clusterCollector *cluster.Collector
- lifecycleCollector *lifecycle.Collector
- collectionLister crashcollector.CollectionLister
- stopCh chan struct{}
- reconnectCh chan struct{}
- labels map[string]string
- metricsStream fodcv1.FODCService_StreamMetricsClient
- registrationStream fodcv1.FODCService_RegisterAgentClient
- clusterStateStream fodcv1.FODCService_StreamClusterTopologyClient
- lifecycleStream fodcv1.FODCService_StreamLifecycleClient
- crashStream fodcv1.FODCService_StreamCrashDiagnosticsClient
- pressureStream fodcv1.FODCService_StreamPressureProfilesClient
- profileSource ProfileSource
- client fodcv1.FODCServiceClient
- reconnectFn func(context.Context) // overridable in tests; nil means use reconnect
+ logger *logger.Logger
+ heartbeatTicker *time.Ticker
+ flightRecorder *flightrecorder.FlightRecorder
+ connManager *connManager
+ clusterCollector *cluster.Collector
+ lifecycleCollector *lifecycle.Collector
+ collectionLister crashcollector.CollectionLister
+ stopCh chan struct{}
+ reconnectCh chan struct{}
+ labels map[string]string
+ metricsStream fodcv1.FODCService_StreamMetricsClient
+ registrationStream fodcv1.FODCService_RegisterAgentClient
+ clusterStateStream fodcv1.FODCService_StreamClusterTopologyClient
+ lifecycleStream fodcv1.FODCService_StreamLifecycleClient
+ schemaRegistryStream fodcv1.FODCService_StreamSchemaRegistryClient
+ crashStream fodcv1.FODCService_StreamCrashDiagnosticsClient
+ pressureStream fodcv1.FODCService_StreamPressureProfilesClient
+ profileSource ProfileSource
+ client fodcv1.FODCServiceClient
+ reconnectFn func(context.Context) // overridable in tests; nil means use reconnect
+ roleProvider func() (string, map[string]string)
proxyAddr string
nodeRole string
@@ -431,6 +433,176 @@ func (c *Client) sendLifecycleData(ctx context.Context) error {
return nil
}
+// StartSchemaRegistryStream establishes the bi-directional schema registry stream
+// with Proxy. Every agent opens it, but the Proxy only ever drives the one
+// schema-serving agent it selects by role, so all other agents' streams sit idle.
+func (c *Client) StartSchemaRegistryStream(ctx context.Context) error {
+ c.streamsMu.Lock()
+ if c.client == nil {
+ c.streamsMu.Unlock()
+ return fmt.Errorf("client not connected, call Connect() first")
+ }
+ client := c.client
+ agentID := c.agentID
+ c.streamsMu.Unlock()
+
+ if agentID == "" {
+ return fmt.Errorf("agent ID not available, register agent first")
+ }
+
+ md := metadata.New(map[string]string{"agent_id": agentID})
+ ctxWithMetadata := metadata.NewOutgoingContext(ctx, md)
+
+ stream, streamErr := client.StreamSchemaRegistry(ctxWithMetadata)
+ if streamErr != nil {
+ return fmt.Errorf("failed to create schema registry stream: %w", streamErr)
+ }
+
+ c.streamsMu.Lock()
+ c.schemaRegistryStream = stream
+ c.streamsMu.Unlock()
+
+ run.Go(ctx, "fodc.agent.proxy.schema-registry-stream", c.logger, func(ctx context.Context) {
+ c.handleSchemaRegistryStream(ctx, stream)
+ })
+
+ c.logger.Info().
+ Str("agent_id", agentID).
+ Msg("Schema registry stream established with Proxy")
+
+ return nil
+}
+
+// handleSchemaRegistryStream reads the Proxy's request_registry commands and
+// replies with the authoritative registry fingerprints read from the local node.
+func (c *Client) handleSchemaRegistryStream(ctx context.Context, stream fodcv1.FODCService_StreamSchemaRegistryClient) {
+ c.streamsMu.RLock()
+ stopCh := c.stopCh
+ c.streamsMu.RUnlock()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-stopCh:
+ return
+ default:
+ }
+ resp, recvErr := stream.Recv()
+ if errors.Is(recvErr, io.EOF) {
+ c.logger.Warn().Msg("Schema registry stream closed by Proxy, reconnecting...")
+ run.Go(ctx, "fodc.agent.proxy.reconnect", c.logger, func(ctx context.Context) {
+ c.reconnect(ctx)
+ })
+ return
+ }
+ if recvErr != nil {
+ c.streamsMu.RLock()
+ disconnected := c.disconnected
+ c.streamsMu.RUnlock()
+ if disconnected {
+ c.logger.Debug().Err(recvErr).Msg("Schema registry stream closed")
+ return
+ }
+ c.logger.Error().Err(recvErr).Msg("Error receiving from schema registry stream, reconnecting...")
+ run.Go(ctx, "fodc.agent.proxy.reconnect", c.logger, func(ctx context.Context) {
+ c.reconnect(ctx)
+ })
+ return
+ }
+ if resp != nil && resp.RequestRegistry {
+ c.logger.Debug().Msg("Received schema registry request from proxy")
+ if sendErr := c.sendSchemaRegistry(ctx); sendErr != nil {
+ c.logger.Error().Err(sendErr).Msg("Failed to send schema registry to proxy")
+ }
+ }
+ }
+}
+
+// schemaObjectChunkSize bounds how many object fingerprints travel in one schema
+// registry message. A group can hold hundreds of objects (one per index rule);
+// splitting them across messages keeps any single message small, and the proxy
+// merges the chunks by group name.
+const schemaObjectChunkSize = 50
+
+// sendSchemaRegistry reads the authoritative registry from the local node and
+// streams its fingerprints to Proxy, splitting each group's objects into chunks
+// so no single message carries a whole large group, then a final done message
+// that ends the round. The round always ends with a done message (carrying any
+// fatal read error) so the proxy never waits past it.
+func (c *Client) sendSchemaRegistry(ctx context.Context) error {
+ c.streamsMu.RLock()
+ if c.disconnected || c.schemaRegistryStream == nil {
+ c.streamsMu.RUnlock()
+ return fmt.Errorf("schema registry stream not established")
+ }
+ stream := c.schemaRegistryStream
+ collector := c.lifecycleCollector
+ c.streamsMu.RUnlock()
+ if collector == nil {
+ return fmt.Errorf("lifecycle collector is nil, cannot read registry")
+ }
+ groups, fetchErr := collector.FetchSchemaRegistry(ctx)
+ send := func(req *fodcv1.StreamSchemaRegistryRequest) error {
+ c.streamsMu.Lock()
+ defer c.streamsMu.Unlock()
+ if c.schemaRegistryStream != stream {
+ return fmt.Errorf("schema registry stream changed during send")
+ }
+ return stream.Send(req)
+ }
+ if fetchErr != nil {
+ // Fatal whole-read failure: a single chunk with an empty group name carries
+ // the reason, so the proxy surfaces it across every group.
+ if sendErr := send(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Error: fetchErr.Error()}}); sendErr != nil {
+ return fmt.Errorf("failed to send schema registry fatal error: %w", sendErr)
+ }
+ } else {
+ for _, group := range groups {
+ if sendErr := sendSchemaRegistryGroup(group, send); sendErr != nil {
+ return sendErr
+ }
+ }
+ }
+ if sendErr := send(&fodcv1.StreamSchemaRegistryRequest{Done: true}); sendErr != nil {
+ return fmt.Errorf("failed to send schema registry done marker: %w", sendErr)
+ }
+ c.logger.Info().
+ Int("groups_count", len(groups)).
+ Bool("fatal", fetchErr != nil).
+ Msg("Successfully streamed schema registry to proxy")
+ return nil
+}
+
+// sendSchemaRegistryGroup streams one group as one or more chunks. A failed group
+// (carrying an error, no objects) goes as a single message; a group with objects
+// is split into schemaObjectChunkSize-sized messages that share the group name;
+// an empty successful group still goes as one message so the proxy sees it.
+func sendSchemaRegistryGroup(group *fodcv1.SchemaRegistryGroup, send func(*fodcv1.StreamSchemaRegistryRequest) error) error {
+ name := group.GetGroup()
+ if group.GetError() != "" {
+ if sendErr := send(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Group: name, Error: group.GetError()}}); sendErr != nil {
+ return fmt.Errorf("failed to send schema registry group %q error: %w", name, sendErr)
+ }
+ return nil
+ }
+ objects := group.GetObjects()
+ for start := 0; start < len(objects) || start == 0; start += schemaObjectChunkSize {
+ end := start + schemaObjectChunkSize
+ if end > len(objects) {
+ end = len(objects)
+ }
+ if sendErr := send(&fodcv1.StreamSchemaRegistryRequest{
+ Group: &fodcv1.SchemaRegistryGroup{Group: name, Objects: objects[start:end]},
+ }); sendErr != nil {
+ return fmt.Errorf("failed to send schema registry group %q chunk: %w", name, sendErr)
+ }
+ if end == len(objects) {
+ break
+ }
+ }
+ return nil
+}
+
// StartCrashStream establishes bi-directional crash diagnostics stream with Proxy.
func (c *Client) StartCrashStream(ctx context.Context) error {
c.streamsMu.Lock()
@@ -1148,6 +1320,42 @@ func (c *Client) sendFilteredMetrics(
return nil
}
+// SetNodeRoleProvider wires a live source of the node's resolved role (and labels),
+// typically the cluster collector's GetNodeInfo. Heartbeats then carry the current
+// role so the proxy can upgrade a registration made before the role resolved.
+func (c *Client) SetNodeRoleProvider(provider func() (string, map[string]string)) {
+ c.streamsMu.Lock()
+ defer c.streamsMu.Unlock()
+ c.roleProvider = provider
+}
+
+// currentRole returns the role to report on the next heartbeat/registration. When a
+// live provider is wired it prefers the freshly resolved role, updating the cached
+// nodeRole so a later reconnect re-registers with it; a blank or unspecified live
+// role never regresses the last known good value.
+func (c *Client) currentRole() (string, map[string]string) {
+ c.streamsMu.RLock()
+ provider := c.roleProvider
+ role := c.nodeRole
+ labels := c.labels
+ c.streamsMu.RUnlock()
+ if provider == nil {
+ return role, labels
+ }
+ liveRole, liveLabels := provider()
+ if liveRole == "" || liveRole == "ROLE_UNSPECIFIED" || liveRole == role {
+ return role, labels
+ }
+ c.streamsMu.Lock()
+ c.nodeRole = liveRole
+ if liveLabels != nil {
+ c.labels = liveLabels
+ }
+ labels = c.labels
+ c.streamsMu.Unlock()
+ return liveRole, labels
+}
+
// SendHeartbeat sends heartbeat to Proxy. The provided context bounds the wait so that a
// stream whose Send is wedged (for example, after the proxy entered graceful_stop and the
// underlying TCP write queue is no longer being drained) cannot pin the heartbeat goroutine
@@ -1161,9 +1369,13 @@ func (c *Client) SendHeartbeat(ctx context.Context) error {
registrationStream := c.registrationStream
c.streamsMu.RUnlock()
+ // The node role can resolve after the initial registration (e.g. a liaison whose
+ // gRPC came up later than the agent's role-resolution budget), so send the current
+ // value on every heartbeat; the proxy upgrades the stored role from it.
+ role, labels := c.currentRole()
req := &fodcv1.RegisterAgentRequest{
- NodeRole: c.nodeRole,
- Labels: c.labels,
+ NodeRole: role,
+ Labels: labels,
PodName: c.podName,
ContainerNames: c.containerNames,
}
@@ -1249,6 +1461,13 @@ func (c *Client) cleanupStreams() {
c.lifecycleStream = nil
}
+ if c.schemaRegistryStream != nil {
+ if closeErr := c.schemaRegistryStream.CloseSend(); closeErr != nil {
+ c.logger.Warn().Err(closeErr).Msg("Error closing schema registry stream")
+ }
+ c.schemaRegistryStream = nil
+ }
+
if c.crashStream != nil {
if closeErr := c.crashStream.CloseSend(); closeErr != nil {
c.logger.Warn().Err(closeErr).Msg("Error closing crash diagnostics stream")
@@ -1318,6 +1537,13 @@ func (c *Client) Disconnect() error {
c.lifecycleStream = nil
}
+ if c.schemaRegistryStream != nil {
+ if closeErr := c.schemaRegistryStream.CloseSend(); closeErr != nil {
+ c.logger.Warn().Err(closeErr).Msg("Error closing schema registry stream")
+ }
+ c.schemaRegistryStream = nil
+ }
+
if c.crashStream != nil {
if closeErr := c.crashStream.CloseSend(); closeErr != nil {
c.logger.Warn().Err(closeErr).Msg("Error closing crash diagnostics stream")
@@ -1394,6 +1620,12 @@ func (c *Client) Start(ctx context.Context) error {
time.Sleep(c.reconnectInterval)
continue
}
+ if registryErr := c.StartSchemaRegistryStream(ctx); registryErr != nil {
+ c.logger.Error().Err(registryErr).Msg("Failed to start schema registry stream, reconnecting...")
+ c.cleanupStreams()
+ time.Sleep(c.reconnectInterval)
+ continue
+ }
}
if c.collectionLister != nil {
@@ -1576,6 +1808,10 @@ func (c *Client) reconnect(ctx context.Context) {
_ = c.lifecycleStream.CloseSend()
c.lifecycleStream = nil
}
+ if c.schemaRegistryStream != nil {
+ _ = c.schemaRegistryStream.CloseSend()
+ c.schemaRegistryStream = nil
+ }
if c.crashStream != nil {
_ = c.crashStream.CloseSend()
c.crashStream = nil
@@ -1639,6 +1875,11 @@ func (c *Client) reconnect(ctx context.Context) {
c.scheduleReconnect(ctx)
return
}
+ if registryErr := c.StartSchemaRegistryStream(ctx); registryErr != nil {
+ c.logger.Error().Err(registryErr).Msg("Failed to restart schema registry stream; will retry")
+ c.scheduleReconnect(ctx)
+ return
+ }
}
if c.collectionLister != nil {
diff --git a/fodc/agent/internal/proxy/client_test.go b/fodc/agent/internal/proxy/client_test.go
index afb08aeaa..b766fbc68 100644
--- a/fodc/agent/internal/proxy/client_test.go
+++ b/fodc/agent/internal/proxy/client_test.go
@@ -84,6 +84,10 @@ func (m *mockFODCServiceClient) StreamLifecycle(_ context.Context, _ ...grpc.Cal
return nil, errors.New("not implemented")
}
+func (m *mockFODCServiceClient) StreamSchemaRegistry(_ context.Context, _ ...grpc.CallOption) (fodcv1.FODCService_StreamSchemaRegistryClient, error) {
+ return nil, errors.New("not implemented")
+}
+
func (m *mockFODCServiceClient) StreamCrashDiagnostics(_ context.Context, _ ...grpc.CallOption) (fodcv1.FODCService_StreamCrashDiagnosticsClient, error) {
return nil, errors.New("not implemented")
}
diff --git a/fodc/agent/internal/proxy/schema_registry_chunk_test.go b/fodc/agent/internal/proxy/schema_registry_chunk_test.go
new file mode 100644
index 000000000..dc0af6c9d
--- /dev/null
+++ b/fodc/agent/internal/proxy/schema_registry_chunk_test.go
@@ -0,0 +1,95 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package proxy
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+func makeObjects(n int) []*fodcv1.SchemaObjectFingerprint {
+ objs := make([]*fodcv1.SchemaObjectFingerprint, n)
+ for i := range objs {
+ objs[i] = &fodcv1.SchemaObjectFingerprint{Kind: "indexRule", Name: "r", Fingerprint: uint64(i)}
+ }
+ return objs
+}
+
+func collectChunks(t *testing.T, group *fodcv1.SchemaRegistryGroup) []*fodcv1.StreamSchemaRegistryRequest {
+ t.Helper()
+ var sent []*fodcv1.StreamSchemaRegistryRequest
+ require.NoError(t, sendSchemaRegistryGroup(group, func(req *fodcv1.StreamSchemaRegistryRequest) error {
+ sent = append(sent, req)
+ return nil
+ }))
+ return sent
+}
+
+func TestSendSchemaRegistryGroup_ChunksObjectsAndMergesBack(t *testing.T) {
+ // 120 objects with a chunk size of 50 -> 50 + 50 + 20 across three messages,
+ // each carrying the same group name so the proxy can merge them.
+ sent := collectChunks(t, &fodcv1.SchemaRegistryGroup{Group: "g", Objects: makeObjects(120)})
+
+ require.Len(t, sent, 3)
+ // Reassemble in arrival order and assert the exact fingerprints survive, in
+ // order, across the chunk boundaries (makeObjects sets Fingerprint = index).
+ var reassembled []*fodcv1.SchemaObjectFingerprint
+ for _, req := range sent {
+ assert.Equal(t, "g", req.GetGroup().GetGroup())
+ reassembled = append(reassembled, req.GetGroup().GetObjects()...)
+ }
+ require.Len(t, reassembled, 120, "no object is lost across chunks")
+ for i, o := range reassembled {
+ require.Equal(t, uint64(i), o.GetFingerprint(), "fingerprints preserved in order across boundaries")
+ }
+ assert.Len(t, sent[0].GetGroup().GetObjects(), schemaObjectChunkSize)
+ assert.Len(t, sent[2].GetGroup().GetObjects(), 20)
+}
+
+func TestSendSchemaRegistryGroup_ExactMultipleHasNoTrailingEmptyChunk(t *testing.T) {
+ // Exactly schemaObjectChunkSize objects must be ONE chunk, with no extra empty
+ // trailing message -- the classic off-by-one an exact multiple would expose.
+ sent := collectChunks(t, &fodcv1.SchemaRegistryGroup{Group: "g", Objects: makeObjects(schemaObjectChunkSize)})
+ require.Len(t, sent, 1)
+ assert.Len(t, sent[0].GetGroup().GetObjects(), schemaObjectChunkSize)
+}
+
+func TestSendSchemaRegistryGroup_OneOverMultipleSplitsInTwo(t *testing.T) {
+ sent := collectChunks(t, &fodcv1.SchemaRegistryGroup{Group: "g", Objects: makeObjects(schemaObjectChunkSize + 1)})
+ require.Len(t, sent, 2)
+ assert.Len(t, sent[0].GetGroup().GetObjects(), schemaObjectChunkSize)
+ assert.Len(t, sent[1].GetGroup().GetObjects(), 1)
+}
+
+func TestSendSchemaRegistryGroup_EmptyGroupStillSendsOneMessage(t *testing.T) {
+ sent := collectChunks(t, &fodcv1.SchemaRegistryGroup{Group: "empty"})
+ require.Len(t, sent, 1, "an empty successful group is still represented so the proxy sees it")
+ assert.Empty(t, sent[0].GetGroup().GetObjects())
+ assert.Empty(t, sent[0].GetGroup().GetError())
+}
+
+func TestSendSchemaRegistryGroup_FailedGroupSendsErrorOnly(t *testing.T) {
+ sent := collectChunks(t, &fodcv1.SchemaRegistryGroup{Group: "broken", Error: "boom"})
+ require.Len(t, sent, 1)
+ assert.Equal(t, "boom", sent[0].GetGroup().GetError())
+ assert.Empty(t, sent[0].GetGroup().GetObjects())
+}
diff --git a/fodc/agent/testhelper/flightrecorder.go b/fodc/agent/testhelper/flightrecorder.go
index 0f05358d2..1e1455551 100644
--- a/fodc/agent/testhelper/flightrecorder.go
+++ b/fodc/agent/testhelper/flightrecorder.go
@@ -286,7 +286,7 @@ func NewProxyClientWrapper(
return nil
}
clusterCollector := &agentcluster.Collector{}
- lifecycleCollector := agentlifecycle.NewCollector(nil, "", reportDir, 0)
+ lifecycleCollector := agentlifecycle.NewCollector(nil, "", "", reportDir, 0)
client := proxy.NewClient(
proxyAddr,
nodeRole,
diff --git a/fodc/internal/consistency/checker.go b/fodc/internal/consistency/checker.go
new file mode 100644
index 000000000..f8c49b3f8
--- /dev/null
+++ b/fodc/internal/consistency/checker.go
@@ -0,0 +1,262 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "sort"
+ "sync"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+// consecutiveCyclesToReport is how many back-to-back collection rounds a
+// divergence must survive before it is reported. Schema propagation is
+// asynchronous and the node-side sweep is lock-free, so a single round's
+// disagreement is usually in-flight state or a torn read; requiring two rounds
+// removes that class of false positive.
+const consecutiveCyclesToReport = 2
+
+// ObjectKey identifies a schema object inside one group.
+type ObjectKey struct {
+ Kind string
+ Name string
+}
+
+// NodeObjectFP is one object's cache/runtime fingerprints on a node. It is the
+// checker's internal carrier, assembled by the proxy from each agent's partial
+// SchemaConsistency, so the wire format ships no parallel per-node message.
+type NodeObjectFP struct {
+ Kind string
+ Name string
+ Cache uint64
+ Runtime uint64
+}
+
+// NodeObjects is one node's reported schema objects (its cache/runtime layers).
+type NodeObjects struct {
+ Node string
+ Objects []*NodeObjectFP
+}
+
+// issueKey identifies one object's divergence on one node, which is the
+// granularity the suppression counter tracks. It deliberately omits the issue
+// type: any divergence on the same object/node that persists across rounds is
+// suspicious, whatever layer it surfaces in, so the streak is kept per object
+// rather than per type. The reported type is then the latest round's reading.
+type issueKey struct {
+ Group string
+ Node string
+ Kind string
+ Name string
+}
+
+// Checker compares the registry view against what each node reports,
+// suppressing divergences that have not persisted across rounds.
+//
+// It is stateful: the suppression counters live across calls, so one instance
+// must be reused between collection cycles. InspectAll fans groups out
+// concurrently, so all access is mutex-guarded.
+type Checker struct {
+ streaks map[issueKey]int
+ mu sync.Mutex
+}
+
+// NewChecker creates a checker with empty suppression state.
+func NewChecker() *Checker {
+ return &Checker{streaks: make(map[issueKey]int)}
+}
+
+// Check compares registryFingerprints (fetched once from a schema-serving node)
+// against every node's reported cache/runtime. It returns the group-level
+// verdict: an object-centric table pairing each object's registry truth with
+// every node's cache/runtime fingerprints, the surviving issues, and a rollup
+// status.
+//
+// expectedNodes is how many data and liaison nodes are on the roster; a shortfall
+// downgrades the verdict to UNKNOWN rather than letting a silent node pass as
+// consistent.
+func (c *Checker) Check(
+ group string,
+ registryFingerprints map[ObjectKey]uint64,
+ nodes []NodeObjects,
+ expectedNodes int,
+) *fodcv1.SchemaConsistency {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ result := &fodcv1.SchemaConsistency{}
+ live := make(map[issueKey]struct{})
+ suppressed := false
+ objects := newObjectAccumulator(registryFingerprints)
+
+ for _, n := range nodes {
+ reported := make(map[ObjectKey]*NodeObjectFP, len(n.Objects))
+ for _, o := range n.Objects {
+ reported[ObjectKey{Kind: o.Kind, Name: o.Name}] = o
+ objects.addNode(n.Node, o)
+ }
+ // registry has it -> compare against what this node reports.
+ for key, registryFP := range registryFingerprints {
+ issueType := classify(registryFP, reported[key])
+ if issueType == fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_UNSPECIFIED {
+ continue
+ }
+ if c.track(group, n.Node, key, live) < consecutiveCyclesToReport {
+ suppressed = true
+ continue
+ }
+ result.Issues = append(result.Issues, &fodcv1.SchemaIssue{
+ Kind: key.Kind, Name: key.Name, Node: n.Node, Type: issueType,
+ })
+ }
+ // node has it but registry does not -> orphan.
+ for key := range reported {
+ if _, inRegistry := registryFingerprints[key]; inRegistry {
+ continue
+ }
+ if c.track(group, n.Node, key, live) < consecutiveCyclesToReport {
+ suppressed = true
+ continue
+ }
+ result.Issues = append(result.Issues, &fodcv1.SchemaIssue{
+ Kind: key.Kind, Name: key.Name, Node: n.Node,
+ Type: fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_ORPHAN,
+ })
+ }
+ }
+ c.prune(group, live)
+ sortIssues(result.Issues)
+ result.Objects = objects.sorted()
+
+ switch {
+ case len(result.Issues) > 0:
+ result.Status = fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT
+ // No node answered at all: absence of evidence, not evidence of agreement.
+ // Also covers expectedNodes being unknown (roster lookup failed, reported 0).
+ case len(nodes) == 0:
+ result.Status = fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN
+ case suppressed || len(nodes) < expectedNodes:
+ result.Status = fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN
+ default:
+ result.Status = fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT
+ }
+ return result
+}
+
+// objectAccumulator collects every schema object once, pairing the registry
+// truth with each node's cache/runtime fingerprints into the object-centric
+// output.
+type objectAccumulator struct {
+ m map[ObjectKey]*fodcv1.ObjectConsistency
+}
+
+// newObjectAccumulator seeds one entry per registry object with its truth
+// fingerprint; node fingerprints are added as nodes report them.
+func newObjectAccumulator(fps map[ObjectKey]uint64) *objectAccumulator {
+ a := &objectAccumulator{m: make(map[ObjectKey]*fodcv1.ObjectConsistency, len(fps))}
+ for key, fp := range fps {
+ a.m[key] = &fodcv1.ObjectConsistency{Kind: key.Kind, Name: key.Name, RegistryFingerprint: fp}
+ }
+ return a
+}
+
+// addNode records one node's cache/runtime fingerprints for an object, creating
+// the entry (with a zero registry fingerprint) when the object is an orphan the
+// registry does not know.
+func (a *objectAccumulator) addNode(node string, o *NodeObjectFP) {
+ key := ObjectKey{Kind: o.Kind, Name: o.Name}
+ oc, ok := a.m[key]
+ if !ok {
+ oc = &fodcv1.ObjectConsistency{Kind: key.Kind, Name: key.Name}
+ a.m[key] = oc
+ }
+ oc.NodeFingerprints = append(oc.NodeFingerprints, &fodcv1.NodeFingerprint{
+ Node: node, CacheFingerprint: o.Cache, RuntimeFingerprint: o.Runtime,
+ })
+}
+
+// sorted flattens the accumulator and orders it deterministically via the shared
+// sorter, keeping the checker's ordering in lockstep with the proxy merge.
+func (a *objectAccumulator) sorted() []*fodcv1.ObjectConsistency {
+ out := make([]*fodcv1.ObjectConsistency, 0, len(a.m))
+ for _, oc := range a.m {
+ out = append(out, oc)
+ }
+ SortObjectConsistencies(out)
+ return out
+}
+
+func sortIssues(issues []*fodcv1.SchemaIssue) {
+ sort.Slice(issues, func(i, j int) bool {
+ if issues[i].GetKind() != issues[j].GetKind() {
+ return issues[i].GetKind() < issues[j].GetKind()
+ }
+ if issues[i].GetName() != issues[j].GetName() {
+ return issues[i].GetName() < issues[j].GetName()
+ }
+ return issues[i].GetNode() < issues[j].GetNode()
+ })
+}
+
+// classify returns the issue type for one object on one node, or UNSPECIFIED
+// when it agrees across all layers. When both boundaries disagree only the
+// upstream one is reported: the downstream difference is a symptom of the same
+// root cause.
+func classify(registryFP uint64, o *NodeObjectFP) fodcv1.SchemaIssueType {
+ if o == nil {
+ return fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_MISSING_IN_CACHE
+ }
+ switch {
+ case o.Cache != registryFP:
+ return fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_CACHE_STALE
+ case o.Runtime != o.Cache:
+ return fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_RUNTIME_NOT_APPLIED
+ default:
+ return fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_UNSPECIFIED
+ }
+}
+
+// track marks a divergence live and bumps its consecutive-round counter.
+func (c *Checker) track(group, node string, key ObjectKey, live map[issueKey]struct{}) int {
+ ik := issueKey{Group: group, Node: node, Kind: key.Kind, Name: key.Name}
+ live[ik] = struct{}{}
+ c.streaks[ik]++
+ return c.streaks[ik]
+}
+
+// prune drops counters for objects in this group that no longer diverge or no
+// longer exist, keeping the map bounded by the live divergence set rather than
+// by history. Other groups' counters are untouched.
+func (c *Checker) prune(group string, live map[issueKey]struct{}) {
+ for k := range c.streaks {
+ if k.Group != group {
+ continue
+ }
+ if _, stillLive := live[k]; !stillLive {
+ delete(c.streaks, k)
+ }
+ }
+}
+
+// trackedCount reports how many suppression counters are held. Tests use it to
+// assert pruning.
+func (c *Checker) trackedCount() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.streaks)
+}
diff --git a/fodc/internal/consistency/checker_test.go b/fodc/internal/consistency/checker_test.go
new file mode 100644
index 000000000..485d7f82e
--- /dev/null
+++ b/fodc/internal/consistency/checker_test.go
@@ -0,0 +1,411 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+// kindStream mirrors schema.KindStream.String(); the checker treats kinds as
+// opaque strings, so the test hard-codes the value to avoid importing the
+// metadata/schema package (which depends on this one).
+const kindStream = "stream"
+
+func nodeState(nodeID string, objs ...*NodeObjectFP) NodeObjects {
+ return NodeObjects{Node: nodeID, Objects: objs}
+}
+
+// testObjectName is the single object every checker case operates on; the
+// checker's behavior does not depend on the name, only on the fingerprints.
+const testObjectName = "foo"
+
+func obj(cache, runtime uint64) *NodeObjectFP {
+ return &NodeObjectFP{Kind: kindStream, Name: testObjectName, Cache: cache, Runtime: runtime}
+}
+
+func streamKey() ObjectKey {
+ return ObjectKey{Kind: kindStream, Name: testObjectName}
+}
+
+func TestChecker_AllAgreeIsConsistent(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+
+ got := c.Check("g", registry,
+ []NodeObjects{nodeState("data-1", obj(100, 100))}, 1)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, got.GetStatus())
+ assert.Empty(t, got.GetIssues())
+}
+
+func TestChecker_SuppressesFirstOccurrence(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ first := c.Check("g", registry, states, 1)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, first.GetStatus(),
+ "a first-round divergence may still be in-flight propagation")
+ assert.Empty(t, first.GetIssues())
+}
+
+func TestChecker_ReportsOnSecondConsecutiveOccurrence(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ c.Check("g", registry, states, 1)
+ second := c.Check("g", registry, states, 1)
+
+ require.Len(t, second.GetIssues(), 1)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, second.GetStatus())
+ assert.Equal(t, fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_CACHE_STALE, second.GetIssues()[0].GetType())
+ assert.Equal(t, "data-1", second.GetIssues()[0].GetNode())
+}
+
+func TestChecker_RecoveryResetsCounter(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ bad := []NodeObjects{nodeState("data-1", obj(200, 200))}
+ good := []NodeObjects{nodeState("data-1", obj(100, 100))}
+
+ c.Check("g", registry, bad, 1)
+ c.Check("g", registry, good, 1)
+ afterRelapse := c.Check("g", registry, bad, 1)
+
+ assert.Empty(t, afterRelapse.GetIssues(),
+ "recovery must reset the counter so the next divergence starts over")
+}
+
+func TestChecker_MissingInCache(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1")}
+
+ c.Check("g", registry, states, 1)
+ got := c.Check("g", registry, states, 1)
+
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_MISSING_IN_CACHE, got.GetIssues()[0].GetType())
+ // The registry truth lives in the object-centric table now, not on the issue.
+ require.Len(t, got.GetObjects(), 1)
+ assert.Equal(t, uint64(100), got.GetObjects()[0].GetRegistryFingerprint())
+ assert.Empty(t, got.GetObjects()[0].GetNodeFingerprints(),
+ "the node reported nothing, so it contributes no fingerprint")
+}
+
+func TestChecker_ObjectsPairRegistryAndNodeFingerprints(t *testing.T) {
+ // The object-centric table lists each object once, pairing its registry truth
+ // with every node's cache/runtime fingerprints, node fingerprints sorted by id.
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{
+ nodeState("liaison-1", obj(100, 100)),
+ nodeState("data-1", obj(100, 100)),
+ }
+
+ got := c.Check("g", registry, states, 2)
+
+ require.Len(t, got.GetObjects(), 1)
+ o := got.GetObjects()[0]
+ assert.Equal(t, kindStream, o.GetKind())
+ assert.Equal(t, testObjectName, o.GetName())
+ assert.Equal(t, uint64(100), o.GetRegistryFingerprint())
+ require.Len(t, o.GetNodeFingerprints(), 2)
+ assert.Equal(t, "data-1", o.GetNodeFingerprints()[0].GetNode(), "node fingerprints sort by id")
+ assert.Equal(t, uint64(100), o.GetNodeFingerprints()[0].GetCacheFingerprint())
+ assert.Equal(t, uint64(100), o.GetNodeFingerprints()[0].GetRuntimeFingerprint())
+ assert.Equal(t, "liaison-1", o.GetNodeFingerprints()[1].GetNode())
+}
+
+func TestChecker_OrphanObjectHasZeroRegistryFingerprint(t *testing.T) {
+ // An object only the node holds (registry does not) still appears in the
+ // table, with a zero registry fingerprint and the node's fingerprints.
+ c := NewChecker()
+ states := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ got := c.Check("g", map[ObjectKey]uint64{}, states, 1)
+
+ require.Len(t, got.GetObjects(), 1)
+ o := got.GetObjects()[0]
+ assert.Zero(t, o.GetRegistryFingerprint(), "the registry does not know this orphan")
+ require.Len(t, o.GetNodeFingerprints(), 1)
+ assert.Equal(t, uint64(200), o.GetNodeFingerprints()[0].GetCacheFingerprint())
+}
+
+func TestChecker_Orphan(t *testing.T) {
+ c := NewChecker()
+ states := []NodeObjects{nodeState("data-1", obj(100, 100))}
+
+ c.Check("g", map[ObjectKey]uint64{}, states, 1)
+ got := c.Check("g", map[ObjectKey]uint64{}, states, 1)
+
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_ORPHAN, got.GetIssues()[0].GetType())
+}
+
+func TestChecker_RuntimeNotApplied(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(100, 999))}
+
+ c.Check("g", registry, states, 1)
+ got := c.Check("g", registry, states, 1)
+
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_RUNTIME_NOT_APPLIED, got.GetIssues()[0].GetType())
+}
+
+func TestChecker_CacheStaleHidesRuntimeIssue(t *testing.T) {
+ // Both boundaries diverge; only the upstream one is reported so the root
+ // cause is not buried under a derived symptom.
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(200, 999))}
+
+ c.Check("g", registry, states, 1)
+ got := c.Check("g", registry, states, 1)
+
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_CACHE_STALE, got.GetIssues()[0].GetType())
+}
+
+func TestChecker_IncompleteCollectionIsUnknown(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(100, 100))}
+
+ got := c.Check("g", registry, states, 3)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, got.GetStatus(),
+ "only 1 of 3 expected nodes answered")
+}
+
+func TestChecker_PrunesCountersForVanishedObjects(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ bad := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ c.Check("g", registry, bad, 1)
+ // The object disappears from both the registry and the node.
+ c.Check("g", map[ObjectKey]uint64{}, []NodeObjects{nodeState("data-1")}, 1)
+
+ assert.Zero(t, c.trackedCount(), "counters for vanished objects must be pruned")
+}
+
+func TestChecker_PerNodeIndependence(t *testing.T) {
+ // One bad node must not suppress or trigger reporting for a healthy peer.
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{
+ nodeState("data-1", obj(100, 100)),
+ nodeState("data-2", obj(200, 200)),
+ }
+
+ c.Check("g", registry, states, 2)
+ got := c.Check("g", registry, states, 2)
+
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, "data-2", got.GetIssues()[0].GetNode())
+}
+
+func TestChecker_ConcurrentGroupsAreSafe(t *testing.T) {
+ // InspectAll inspects up to maxInspectGroupConcurrency groups in parallel
+ // against one shared checker, so Check must tolerate concurrent callers.
+ // Run with -race to make this meaningful.
+ const groups = 32
+ const rounds = 20
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ var wg sync.WaitGroup
+ for g := 0; g < groups; g++ {
+ wg.Add(1)
+ //panicdiag:allow-rawgo test-only contention driver; a panic here must fail the test loudly rather than be recovered and hidden
+ go func(idx int) {
+ defer wg.Done()
+ group := fmt.Sprintf("g%d", idx)
+ for r := 0; r < rounds; r++ {
+ c.Check(group, registry, states, 1)
+ }
+ }(g)
+ }
+ wg.Wait()
+
+ assert.Equal(t, groups, c.trackedCount(),
+ "each group must keep exactly one live counter, with no cross-group interference")
+}
+
+func TestChecker_NoNodeAnsweredIsUnknown(t *testing.T) {
+ // Zero evidence must never read as agreement. This also covers the roster
+ // lookup failing and reporting zero expected nodes.
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+
+ got := c.Check("g", registry, nil, 0)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, got.GetStatus())
+ assert.Empty(t, got.GetIssues())
+}
+
+func TestChecker_GroupsAreIndependent(t *testing.T) {
+ // Pruning one group's counters must not clear another group's streak.
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ bad := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ c.Check("g1", registry, bad, 1)
+ c.Check("g2", registry, bad, 1)
+ got := c.Check("g1", registry, bad, 1)
+
+ require.Len(t, got.GetIssues(), 1, "g2's round must not reset g1's streak")
+}
+
+// The tests below give each ConsistencyStatus value dedicated coverage.
+
+// TestChecker_StatusConsistentRequiresFullRoster pins that CONSISTENT is only
+// reached when every expected node answered AND nothing diverged; a matching
+// but incomplete roster must stay UNKNOWN even though no issue exists.
+func TestChecker_StatusConsistentRequiresFullRoster(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ agree := []NodeObjects{
+ nodeState("data-1", obj(100, 100)),
+ nodeState("liaison-1", obj(100, 100)),
+ }
+
+ full := c.Check("g", registry, agree, 2)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, full.GetStatus(),
+ "all expected nodes answered and agree")
+
+ short := c.Check("g", registry, agree, 3)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, short.GetStatus(),
+ "one rostered node is silent, so agreement cannot be concluded")
+ assert.Empty(t, short.GetIssues())
+}
+
+// TestChecker_StatusUnknownWhileSuppressing pins that a first-round divergence
+// keeps the whole group UNKNOWN (not CONSISTENT) even though it emits no issue
+// yet: the suppressed divergence is unresolved, not agreement.
+func TestChecker_StatusUnknownWhileSuppressing(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(200, 200))}
+
+ got := c.Check("g", registry, states, 1)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, got.GetStatus())
+ assert.Empty(t, got.GetIssues(), "the divergence is still suppressed on its first round")
+}
+
+// TestChecker_StatusInconsistentThenRecoversToConsistent walks the full status
+// lifecycle for one node: UNKNOWN (suppressed) -> INCONSISTENT (reported) ->
+// CONSISTENT (healed), proving the rollup tracks the latest evidence and does
+// not latch on a past INCONSISTENT verdict.
+func TestChecker_StatusInconsistentThenRecoversToConsistent(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ bad := []NodeObjects{nodeState("data-1", obj(200, 200))}
+ good := []NodeObjects{nodeState("data-1", obj(100, 100))}
+
+ first := c.Check("g", registry, bad, 1)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, first.GetStatus())
+
+ second := c.Check("g", registry, bad, 1)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, second.GetStatus())
+
+ healed := c.Check("g", registry, good, 1)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, healed.GetStatus(),
+ "once the node matches again the group returns to CONSISTENT without latching")
+ assert.Empty(t, healed.GetIssues())
+}
+
+// TestChecker_StatusInconsistentWinsOverSuppressionAndShortfall pins the switch
+// priority: a reported issue makes the group INCONSISTENT even when another
+// node is still suppressing and the roster is short. INCONSISTENT is the most
+// severe verdict and must not be masked by UNKNOWN conditions.
+func TestChecker_StatusInconsistentWinsOverSuppressionAndShortfall(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ // data-1 has diverged for two rounds (will report); data-2 diverges only now
+ // (still suppressed). Expected roster is larger than answered.
+ round1 := []NodeObjects{nodeState("data-1", obj(200, 200))}
+ c.Check("g", registry, round1, 5)
+
+ round2 := []NodeObjects{
+ nodeState("data-1", obj(200, 200)),
+ nodeState("data-2", obj(300, 300)),
+ }
+ got := c.Check("g", registry, round2, 5)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, got.GetStatus(),
+ "a confirmed issue outranks suppression and roster shortfall")
+ require.Len(t, got.GetIssues(), 1)
+ assert.Equal(t, "data-1", got.GetIssues()[0].GetNode())
+}
+
+// TestChecker_StatusUnknownOnRosterShortfallWithoutIssue pins that a healthy but
+// incomplete collection (every answering node agrees, yet fewer answered than
+// the roster) is UNKNOWN, never CONSISTENT: a silent node could be diverging.
+func TestChecker_StatusUnknownOnRosterShortfallWithoutIssue(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ states := []NodeObjects{nodeState("data-1", obj(100, 100))}
+
+ // Two consecutive rounds so suppression is not the reason for UNKNOWN.
+ c.Check("g", registry, states, 2)
+ got := c.Check("g", registry, states, 2)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, got.GetStatus(),
+ "1 of 2 rostered nodes answered; agreement of the one is not agreement of all")
+ assert.Empty(t, got.GetIssues())
+}
+
+// TestChecker_StatusUnspecifiedNeverEscapes pins that the checker never returns
+// the zero-value UNSPECIFIED status: every code path assigns an explicit
+// verdict, so a caller can always trust GetStatus().
+func TestChecker_StatusUnspecifiedNeverEscapes(t *testing.T) {
+ c := NewChecker()
+ registry := map[ObjectKey]uint64{streamKey(): 100}
+ cases := []struct {
+ name string
+ nodes []NodeObjects
+ expectedNodes int
+ }{
+ {"empty", nil, 0},
+ {"agree-full", []NodeObjects{nodeState("data-1", obj(100, 100))}, 1},
+ {"agree-short", []NodeObjects{nodeState("data-1", obj(100, 100))}, 2},
+ {"diverge", []NodeObjects{nodeState("data-1", obj(200, 200))}, 1},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := c.Check(tc.name, registry, tc.nodes, tc.expectedNodes)
+ assert.NotEqual(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNSPECIFIED, got.GetStatus(),
+ "every path must assign an explicit status")
+ })
+ }
+}
diff --git a/fodc/internal/consistency/derive.go b/fodc/internal/consistency/derive.go
new file mode 100644
index 000000000..ce9ae65e5
--- /dev/null
+++ b/fodc/internal/consistency/derive.go
@@ -0,0 +1,54 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package consistency derives and fingerprints schema state so the registry,
+// node-cache and runtime views can be compared with identical semantics.
+package consistency
+
+import (
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+// BindingLookup returns every index rule binding whose subject is the given
+// resource. Implementations are already scoped to one catalog.
+type BindingLookup interface {
+ BindingsOf(group, name string) []*databasev1.IndexRuleBinding
+}
+
+// RuleLookup resolves an index rule by name, returning nil when absent.
+type RuleLookup interface {
+ Rule(group, name string) *databasev1.IndexRule
+}
+
+// DeriveBoundRules returns the index rules bound to the given subject.
+//
+// Semantics deliberately mirror pkg/schema.schemaRepo.indexRules exactly: no
+// sorting, no de-duplication, and no begin_at/expire_at filtering. Keeping the
+// helper behavior-identical lets the production path delegate to it without
+// changing what OnIndexUpdate receives. Determinism required by fingerprints is
+// applied in Fingerprint, not here.
+func DeriveBoundRules(group, name string, bindings BindingLookup, rules RuleLookup) []*databasev1.IndexRule {
+ var result []*databasev1.IndexRule
+ for _, b := range bindings.BindingsOf(group, name) {
+ for _, ruleName := range b.GetRules() {
+ if r := rules.Rule(group, ruleName); r != nil {
+ result = append(result, r)
+ }
+ }
+ }
+ return result
+}
diff --git a/fodc/internal/consistency/derive_test.go b/fodc/internal/consistency/derive_test.go
new file mode 100644
index 000000000..62d5423e2
--- /dev/null
+++ b/fodc/internal/consistency/derive_test.go
@@ -0,0 +1,106 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+type stubBindings struct {
+ m map[string][]*databasev1.IndexRuleBinding
+}
+
+func (s *stubBindings) BindingsOf(group, name string) []*databasev1.IndexRuleBinding {
+ return s.m[group+"/"+name]
+}
+
+type stubRules struct {
+ m map[string]*databasev1.IndexRule
+}
+
+func (s *stubRules) Rule(group, name string) *databasev1.IndexRule {
+ return s.m[group+"/"+name]
+}
+
+const testGroup = "g"
+
+func rule(_, name string) *databasev1.IndexRule {
+ return &databasev1.IndexRule{Metadata: &commonv1.Metadata{Group: testGroup, Name: name}}
+}
+
+// testSubject is the single subject every derivation case binds to; the helper's
+// behavior does not depend on the name.
+const testSubject = "foo"
+
+func binding(name string, rules ...string) *databasev1.IndexRuleBinding {
+ return &databasev1.IndexRuleBinding{
+ Metadata: &commonv1.Metadata{Group: testGroup, Name: name},
+ Subject: &databasev1.Subject{Name: testSubject, Catalog: commonv1.Catalog_CATALOG_STREAM},
+ Rules: rules,
+ }
+}
+
+func TestDeriveBoundRules_CollectsRulesFromAllBindings(t *testing.T) {
+ b := &stubBindings{m: map[string][]*databasev1.IndexRuleBinding{
+ "g/foo": {binding("b1", "r1"), binding("b2", "r2")},
+ }}
+ r := &stubRules{m: map[string]*databasev1.IndexRule{
+ "g/r1": rule("g", "r1"),
+ "g/r2": rule("g", "r2"),
+ }}
+
+ got := DeriveBoundRules("g", "foo", b, r)
+
+ assert.Len(t, got, 2)
+}
+
+func TestDeriveBoundRules_SkipsMissingRule(t *testing.T) {
+ b := &stubBindings{m: map[string][]*databasev1.IndexRuleBinding{
+ "g/foo": {binding("b1", "r1", "absent")},
+ }}
+ r := &stubRules{m: map[string]*databasev1.IndexRule{"g/r1": rule("g", "r1")}}
+
+ got := DeriveBoundRules("g", "foo", b, r)
+
+ assert.Len(t, got, 1, "a rule name with no rule object must be skipped silently")
+}
+
+func TestDeriveBoundRules_KeepsDuplicatesAndOrder(t *testing.T) {
+ // Two bindings referencing the same rule must yield it twice: the helper
+ // deliberately mirrors pkg/schema.schemaRepo.indexRules, which does not
+ // de-duplicate. Determinism is applied by Fingerprint instead.
+ b := &stubBindings{m: map[string][]*databasev1.IndexRuleBinding{
+ "g/foo": {binding("b1", "r1"), binding("b2", "r1")},
+ }}
+ r := &stubRules{m: map[string]*databasev1.IndexRule{"g/r1": rule("g", "r1")}}
+
+ got := DeriveBoundRules("g", "foo", b, r)
+
+ assert.Len(t, got, 2)
+}
+
+func TestDeriveBoundRules_NoBindingsYieldsNil(t *testing.T) {
+ got := DeriveBoundRules("g", "foo", &stubBindings{}, &stubRules{})
+
+ assert.Nil(t, got)
+}
diff --git a/fodc/internal/consistency/fingerprint.go b/fodc/internal/consistency/fingerprint.go
new file mode 100644
index 000000000..fa3a563ca
--- /dev/null
+++ b/fodc/internal/consistency/fingerprint.go
@@ -0,0 +1,107 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "encoding/binary"
+ "fmt"
+ "sort"
+
+ "github.com/cespare/xxhash/v2"
+ "google.golang.org/protobuf/proto"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+// Fingerprint hashes a schema object together with the index rules bound to it.
+//
+// Sorting and de-duplication of rules happen here rather than in
+// DeriveBoundRules so the production derivation keeps its exact behavior while
+// the fingerprint stays deterministic regardless of sync.Map iteration order.
+func Fingerprint(subject proto.Message, rules []*databasev1.IndexRule) (uint64, error) {
+ subjectHash, err := base(subject)
+ if err != nil {
+ return 0, err
+ }
+ ruleHashes := make(map[string]uint64, len(rules))
+ keys := make([]string, 0, len(rules))
+ for _, r := range rules {
+ key := r.GetMetadata().GetGroup() + "/" + r.GetMetadata().GetName()
+ if _, seen := ruleHashes[key]; seen {
+ continue
+ }
+ ruleHash, ruleErr := base(r)
+ if ruleErr != nil {
+ return 0, ruleErr
+ }
+ ruleHashes[key] = ruleHash
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+
+ digest := xxhash.New()
+ var buf [8]byte
+ binary.LittleEndian.PutUint64(buf[:], subjectHash)
+ _, _ = digest.Write(buf[:])
+ for _, key := range keys {
+ binary.LittleEndian.PutUint64(buf[:], ruleHashes[key])
+ _, _ = digest.Write(buf[:])
+ }
+ return digest.Sum64(), nil
+}
+
+// base hashes one schema message after clearing the identity fields that move
+// without any content change. The cleared set matches the IgnoreFields list in
+// banyand/metadata/schema/checker.go.
+//
+// updated_at / created_at are deliberately NOT cleared: all three layers read
+// the same stored value (registry reads and watch notifications share the same
+// ToSchema conversion, and a no-op update never writes), so they cannot cause
+// false positives -- and clearing more than necessary would mask real drift.
+func base(m proto.Message) (uint64, error) {
+ clone := proto.Clone(m)
+ clearVolatile(clone)
+ encoded, err := proto.MarshalOptions{Deterministic: true}.Marshal(clone)
+ if err != nil {
+ return 0, fmt.Errorf("failed to marshal schema for fingerprinting: %w", err)
+ }
+ return xxhash.Sum64(encoded), nil
+}
+
+// clearVolatile zeroes the identity fields on a cloned message. It operates on
+// the clone made by base, never on the caller's live schema. Every BanyanDB
+// schema protobuf (Group, Stream, Measure, Trace, IndexRule, IndexRuleBinding,
+// TopNAggregation) carries a commonv1.Metadata, so the interface assertion
+// covers them all without an exhaustive type switch.
+func clearVolatile(m proto.Message) {
+ type metadataHolder interface {
+ GetMetadata() *commonv1.Metadata
+ }
+ h, ok := m.(metadataHolder)
+ if !ok {
+ return
+ }
+ md := h.GetMetadata()
+ if md == nil {
+ return
+ }
+ md.Id = 0
+ md.CreateRevision = 0
+ md.ModRevision = 0
+}
diff --git a/fodc/internal/consistency/fingerprint_test.go b/fodc/internal/consistency/fingerprint_test.go
new file mode 100644
index 000000000..2a94a2f10
--- /dev/null
+++ b/fodc/internal/consistency/fingerprint_test.go
@@ -0,0 +1,110 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+var fixedUpdatedAt = timestamppb.New(time.Unix(1700000000, 0).UTC())
+
+func streamSpec(modRevision int64, tag string) *databasev1.Stream {
+ return &databasev1.Stream{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "foo", ModRevision: modRevision, Id: 7},
+ TagFamilies: []*databasev1.TagFamilySpec{{
+ Name: "searchable",
+ Tags: []*databasev1.TagSpec{{Name: tag, Type: databasev1.TagType_TAG_TYPE_STRING}},
+ }},
+ Entity: &databasev1.Entity{TagNames: []string{tag}},
+ UpdatedAt: fixedUpdatedAt,
+ }
+}
+
+func TestFingerprint_IgnoresModRevision(t *testing.T) {
+ a, err := Fingerprint(streamSpec(1, "service_id"), nil)
+ require.NoError(t, err)
+ b, err := Fingerprint(streamSpec(999, "service_id"), nil)
+ require.NoError(t, err)
+
+ assert.Equal(t, a, b, "a revision bump with unchanged content must not change the fingerprint")
+}
+
+func TestFingerprint_DetectsContentChange(t *testing.T) {
+ a, err := Fingerprint(streamSpec(1, "service_id"), nil)
+ require.NoError(t, err)
+ b, err := Fingerprint(streamSpec(1, "endpoint_id"), nil)
+ require.NoError(t, err)
+
+ assert.NotEqual(t, a, b)
+}
+
+func TestFingerprint_DetectsBoundRuleChange(t *testing.T) {
+ s := streamSpec(1, "service_id")
+ a, err := Fingerprint(s, []*databasev1.IndexRule{rule("g", "r1")})
+ require.NoError(t, err)
+ b, err := Fingerprint(s, []*databasev1.IndexRule{rule("g", "r2")})
+ require.NoError(t, err)
+
+ assert.NotEqual(t, a, b, "a different bound rule set must change the fingerprint")
+}
+
+func TestFingerprint_RuleOrderAndDuplicatesDoNotMatter(t *testing.T) {
+ s := streamSpec(1, "service_id")
+ r1, r2 := rule("g", "r1"), rule("g", "r2")
+ a, err := Fingerprint(s, []*databasev1.IndexRule{r1, r2})
+ require.NoError(t, err)
+ b, err := Fingerprint(s, []*databasev1.IndexRule{r2, r1, r1})
+ require.NoError(t, err)
+
+ assert.Equal(t, a, b, "sort+dedup happens here so sync.Map iteration order cannot move the fingerprint")
+}
+
+func TestFingerprint_DoesNotMutateInput(t *testing.T) {
+ // Fingerprinting clears identity fields, and doing so on the caller's object
+ // would corrupt the live schema the node is serving.
+ s := streamSpec(42, "service_id")
+
+ _, err := Fingerprint(s, nil)
+ require.NoError(t, err)
+
+ assert.Equal(t, int64(42), s.GetMetadata().GetModRevision())
+ assert.Equal(t, uint32(7), s.GetMetadata().GetId())
+}
+
+func TestFingerprint_RuleContentChangeIsDetected(t *testing.T) {
+ // Same rule name, different rule body: the bound rule set must still differ.
+ s := streamSpec(1, "service_id")
+ plain := rule("g", "r1")
+ modified := rule("g", "r1")
+ modified.Tags = []string{"service_id"}
+
+ a, err := Fingerprint(s, []*databasev1.IndexRule{plain})
+ require.NoError(t, err)
+ b, err := Fingerprint(s, []*databasev1.IndexRule{modified})
+ require.NoError(t, err)
+
+ assert.NotEqual(t, a, b)
+}
diff --git a/fodc/internal/consistency/objects.go b/fodc/internal/consistency/objects.go
new file mode 100644
index 000000000..0ce2931e8
--- /dev/null
+++ b/fodc/internal/consistency/objects.go
@@ -0,0 +1,43 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package consistency
+
+import (
+ "sort"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+// SortObjectConsistencies orders the schema object table deterministically in
+// place: objects by kind then name, and each object's node fingerprints by node
+// id. The checker builds this table and the proxy re-sorts it after merging, so
+// a single sorter keeps the two sides' ordering in lockstep.
+func SortObjectConsistencies(objects []*fodcv1.ObjectConsistency) {
+ for _, oc := range objects {
+ nfs := oc.GetNodeFingerprints()
+ sort.Slice(nfs, func(i, j int) bool {
+ return nfs[i].GetNode() < nfs[j].GetNode()
+ })
+ }
+ sort.Slice(objects, func(i, j int) bool {
+ if objects[i].GetKind() != objects[j].GetKind() {
+ return objects[i].GetKind() < objects[j].GetKind()
+ }
+ return objects[i].GetName() < objects[j].GetName()
+ })
+}
diff --git a/fodc/proxy/internal/api/schema_consistency_contract_test.go b/fodc/proxy/internal/api/schema_consistency_contract_test.go
new file mode 100644
index 000000000..9e73f356d
--- /dev/null
+++ b/fodc/proxy/internal/api/schema_consistency_contract_test.go
@@ -0,0 +1,120 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+// TestLifecycleGroupsJSONContract pins the exact JSON shape of the schema
+// consistency verdict on /cluster/lifecycle.
+//
+// test/e2e-v2/cases/fodc/check-schema-consistency.sh reads this payload with
+// jq. Its queries are string literals, so a rename here (proto field, JSON
+// casing, or enum spelling) would not break compilation -- the script's filters
+// would simply stop matching and every check in it would pass vacuously on a
+// broken cluster. This test is what makes that drift fail loudly instead.
+func TestLifecycleGroupsJSONContract(t *testing.T) {
+ groups := []*fodcv1.GroupLifecycleInfo{{
+ Name: "g",
+ Catalog: "CATALOG_STREAM",
+ SchemaConsistency: &fodcv1.SchemaConsistency{
+ Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT,
+ Objects: []*fodcv1.ObjectConsistency{{
+ Kind: "stream", Name: "foo", RegistryFingerprint: 1,
+ NodeFingerprints: []*fodcv1.NodeFingerprint{{
+ Node: "data-1", CacheFingerprint: 2, RuntimeFingerprint: 3,
+ }},
+ }},
+ Issues: []*fodcv1.SchemaIssue{{
+ Kind: "stream",
+ Name: "foo",
+ Node: "data-1",
+ Type: fodcv1.SchemaIssueType_SCHEMA_ISSUE_TYPE_CACHE_STALE,
+ }},
+ },
+ }}
+
+ raw, err := marshalLifecycleGroups(groups)
+ require.NoError(t, err)
+ require.Len(t, raw, 1)
+
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(raw[0], &decoded))
+
+ // Proto names, not lowerCamelCase: the marshaler sets UseProtoNames.
+ verdictRaw, ok := decoded["schema_consistency"]
+ require.True(t, ok, "the script selects .schema_consistency; lowerCamelCase would silently match nothing")
+ verdict, ok := verdictRaw.(map[string]any)
+ require.True(t, ok)
+
+ assert.Equal(t, "CONSISTENCY_STATUS_CONSISTENT", verdict["status"],
+ "the script compares status against full enum names")
+
+ // objects is the group's single, object-centric schema table: registry truth
+ // plus each node's cache/runtime fingerprints, all in one place.
+ objects, ok := verdict["objects"].([]any)
+ require.True(t, ok, "objects carries the per-object registry and per-node fingerprints")
+ require.Len(t, objects, 1)
+ object, ok := objects[0].(map[string]any)
+ require.True(t, ok)
+ for _, key := range []string{"kind", "name", "registry_fingerprint", "node_fingerprints"} {
+ assert.Contains(t, object, key, "object field %q pins the schema table", key)
+ }
+ nodeFingerprints, ok := object["node_fingerprints"].([]any)
+ require.True(t, ok)
+ require.Len(t, nodeFingerprints, 1)
+ nodeFingerprint, ok := nodeFingerprints[0].(map[string]any)
+ require.True(t, ok)
+ for _, key := range []string{"node", "cache_fingerprint", "runtime_fingerprint"} {
+ assert.Contains(t, nodeFingerprint, key, "node fingerprint field %q pins the per-node layer", key)
+ }
+
+ issues, ok := verdict["issues"].([]any)
+ require.True(t, ok, "the script prints .schema_consistency.issues on failure")
+ require.Len(t, issues, 1)
+ issue, ok := issues[0].(map[string]any)
+ require.True(t, ok)
+
+ assert.Equal(t, "SCHEMA_ISSUE_TYPE_CACHE_STALE", issue["type"])
+ for _, key := range []string{"kind", "name", "node", "type"} {
+ assert.Contains(t, issue, key, "issue field %q is what makes a finding actionable", key)
+ }
+}
+
+// TestConsistencyStatusNamesAreExhaustive pins the status strings the e2e script
+// buckets verdicts into. The script asserts every verdict falls into one of
+// these four; a new enum value added here without updating the script would make
+// that sum check fail rather than let an unrecognized status slip through.
+func TestConsistencyStatusNamesAreExhaustive(t *testing.T) {
+ expected := map[int32]string{
+ 0: "CONSISTENCY_STATUS_UNSPECIFIED",
+ 1: "CONSISTENCY_STATUS_CONSISTENT",
+ 2: "CONSISTENCY_STATUS_INCONSISTENT",
+ 3: "CONSISTENCY_STATUS_UNKNOWN",
+ }
+
+ assert.Equal(t, expected, fodcv1.ConsistencyStatus_name,
+ "check-schema-consistency.sh buckets verdicts by these exact names; update it alongside the enum")
+}
diff --git a/fodc/proxy/internal/api/server.go b/fodc/proxy/internal/api/server.go
index 4194c6bfe..24f2823fa 100644
--- a/fodc/proxy/internal/api/server.go
+++ b/fodc/proxy/internal/api/server.go
@@ -172,6 +172,10 @@ func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
filteredMetrics = append(filteredMetrics, metric)
}
aggregatedMetrics = filteredMetrics
+ } else {
+ // Schema consistency is a cluster-wide, per-group verdict, not a node-scoped
+ // metric, so it only rides on the unfiltered scrape Grafana uses.
+ aggregatedMetrics = append(aggregatedMetrics, s.schemaConsistencyMetrics()...)
}
prometheusText := s.formatPrometheusText(aggregatedMetrics)
@@ -181,6 +185,33 @@ func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(prometheusText))
}
+// schemaConsistencyMetrics turns the cached per-group schema consistency verdict
+// into gauge series for the /metrics scrape so Grafana can chart it. The value is
+// the ConsistencyStatus enum: 1=CONSISTENT, 2=INCONSISTENT, 3=UNKNOWN. It is
+// empty until a lifecycle collection has run.
+func (s *Server) schemaConsistencyMetrics() []*metrics.AggregatedMetric {
+ if s.lifecycleManager == nil {
+ return nil
+ }
+ snapshot := s.lifecycleManager.SchemaConsistencySnapshot()
+ if len(snapshot) == 0 {
+ return nil
+ }
+ now := time.Now()
+ out := make([]*metrics.AggregatedMetric, 0, len(snapshot))
+ for group, status := range snapshot {
+ out = append(out, &metrics.AggregatedMetric{
+ Name: "banyandb_fodc_schema_consistency_status",
+ Type: "gauge",
+ Description: "Schema consistency verdict per group (1=CONSISTENT, 2=INCONSISTENT, 3=UNKNOWN).",
+ Labels: map[string]string{"group": group},
+ Value: float64(status),
+ Timestamp: now,
+ })
+ }
+ return out
+}
+
// handleMetricsWindows handles GET /metrics-windows endpoint.
func (s *Server) handleMetricsWindows(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
@@ -628,6 +659,19 @@ func (s *Server) handleClusterLifecycle(w http.ResponseWriter, r *http.Request)
http.Error(w, "Lifecycle manager not available", http.StatusServiceUnavailable)
return
}
+
+ // CollectLifecycle blocks until the slowest agent answers or times out, which
+ // is far longer than the server-wide WriteTimeout and, crucially, not bounded
+ // by any fixed value we can predict here. If a fixed deadline is too small the
+ // whole response is dropped with "i/o timeout" even though most agents replied.
+ // Clear the write deadline entirely for this handler (the pressure-profile
+ // download below does the same); other endpoints keep the server-wide timeout.
+ controller := http.NewResponseController(w)
+ if deadlineErr := controller.SetWriteDeadline(time.Time{}); deadlineErr != nil {
+ s.logger.Warn().Err(deadlineErr).
+ Msg("Failed to lift write deadline for lifecycle; a slow agent may truncate the response")
+ }
+
lifecycleData, agentSummary := s.lifecycleManager.CollectLifecycle(r.Context())
groupsJSON, err := marshalLifecycleGroups(lifecycleData.Groups)
diff --git a/fodc/proxy/internal/api/server_test.go b/fodc/proxy/internal/api/server_test.go
index 954b89cf3..f7f7843bf 100644
--- a/fodc/proxy/internal/api/server_test.go
+++ b/fodc/proxy/internal/api/server_test.go
@@ -20,6 +20,7 @@ package api
import (
"context"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"net/url"
@@ -701,6 +702,10 @@ func (m *mockLifecycleDataRequester) RequestLifecycleData(agentID string) error
return nil
}
+func (m *mockLifecycleDataRequester) FetchSchemaRegistry(_ context.Context, _ string) ([]*fodcv1.SchemaRegistryGroup, error) {
+ return nil, fmt.Errorf("no schema registry configured")
+}
+
func TestFormatPrometheusText_SortedMetrics(t *testing.T) {
server := newTestServerOnly(t)
diff --git a/fodc/proxy/internal/grpc/schema_registry_test.go b/fodc/proxy/internal/grpc/schema_registry_test.go
new file mode 100644
index 000000000..19921aac5
--- /dev/null
+++ b/fodc/proxy/internal/grpc/schema_registry_test.go
@@ -0,0 +1,217 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package grpc
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc/metadata"
+
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+)
+
+// mockSchemaRegistryServer captures the request_registry command the proxy sends.
+type mockSchemaRegistryServer struct {
+ ctx context.Context
+ sent chan *fodcv1.StreamSchemaRegistryResponse
+}
+
+func (m *mockSchemaRegistryServer) Send(resp *fodcv1.StreamSchemaRegistryResponse) error {
+ m.sent <- resp
+ return nil
+}
+func (m *mockSchemaRegistryServer) Recv() (*fodcv1.StreamSchemaRegistryRequest, error) { select {} }
+func (m *mockSchemaRegistryServer) Context() context.Context { return m.ctx }
+func (m *mockSchemaRegistryServer) SendMsg(_ interface{}) error { return nil }
+func (m *mockSchemaRegistryServer) RecvMsg(_ interface{}) error { return nil }
+func (m *mockSchemaRegistryServer) SetHeader(_ metadata.MD) error { return nil }
+func (m *mockSchemaRegistryServer) SendHeader(_ metadata.MD) error { return nil }
+func (m *mockSchemaRegistryServer) SetTrailer(_ metadata.MD) {}
+
+func objFP(kind, name string, fp uint64) *fodcv1.SchemaObjectFingerprint {
+ return &fodcv1.SchemaObjectFingerprint{Kind: kind, Name: name, Fingerprint: fp}
+}
+
+func TestFetchSchemaRegistry_MergesChunksAndEndsOnDone(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ go func() {
+ // Wait until the request_registry command was sent (channel is set up).
+ <-srv.sent
+ // Group "g" streams its objects across two chunks that must be merged.
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{
+ Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{objFP("group", "g", 1)},
+ }})
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{
+ Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{objFP("stream", "foo", 100)},
+ }})
+ // A failed group carries an error and no objects.
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{
+ Group: "broken", Error: "list streams of broken: boom",
+ }})
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Done: true})
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ groups, err := ac.fetchSchemaRegistry(ctx)
+
+ require.NoError(t, err)
+ require.Len(t, groups, 2)
+ byName := map[string]*fodcv1.SchemaRegistryGroup{}
+ for _, g := range groups {
+ byName[g.GetGroup()] = g
+ }
+ require.Contains(t, byName, "g")
+ // Assert the merged objects' identity (kind/name/fingerprint), not just the
+ // count -- a lose-then-pad or reorder merge bug would pass a length-only check.
+ gObjs := map[string]uint64{}
+ for _, o := range byName["g"].GetObjects() {
+ gObjs[o.GetKind()+"/"+o.GetName()] = o.GetFingerprint()
+ }
+ assert.Equal(t, map[string]uint64{"group/g": 1, "stream/foo": 100}, gObjs, "both chunks' exact fingerprints are merged")
+ assert.Equal(t, "list streams of broken: boom", byName["broken"].GetError())
+ assert.Empty(t, byName["broken"].GetObjects())
+}
+
+func TestFetchSchemaRegistry_ObjectChunkThenErrorChunkSetsError(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ go func() {
+ <-srv.sent
+ // A group that streamed some objects and then reports an error on a later chunk.
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{
+ Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{objFP("group", "g", 1)},
+ }})
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Group: "g", Error: "late boom"}})
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Done: true})
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ groups, err := ac.fetchSchemaRegistry(ctx)
+
+ require.NoError(t, err)
+ require.Len(t, groups, 1)
+ assert.Equal(t, "late boom", groups[0].GetError(), "a later error chunk is recorded on the merged group")
+}
+
+func TestDeliverSchemaRegistry_AfterFetchGaveUpDoesNotBlock(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ // Run a fetch that never gets a done marker; it returns on its ctx timeout and
+ // clears its channel in the deferred cleanup.
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ _, err := ac.fetchSchemaRegistry(ctx)
+ require.Error(t, err, "the round times out with no done marker")
+
+ // A chunk arriving after the round is over must return promptly, never block.
+ done := make(chan struct{})
+ go func() {
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Group: "late"}})
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("deliverSchemaRegistry blocked after the fetch gave up")
+ }
+}
+
+func TestFetchSchemaRegistry_FatalErrorOnDone(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ go func() {
+ <-srv.sent
+ // The fatal whole-read failure is an empty-name group chunk carrying the reason.
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Error: "dial 127.0.0.1:17912: connection refused"}})
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Done: true})
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ groups, err := ac.fetchSchemaRegistry(ctx)
+
+ require.Error(t, err, "the empty-name error sentinel becomes a Go error")
+ assert.Contains(t, err.Error(), "connection refused")
+ assert.Nil(t, groups)
+}
+
+func TestFetchSchemaRegistry_TimesOutWithoutDone(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ go func() {
+ <-srv.sent
+ // One chunk, then silence: the round never gets a done marker.
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{Group: &fodcv1.SchemaRegistryGroup{Group: "g"}})
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ _, err := ac.fetchSchemaRegistry(ctx)
+
+ require.Error(t, err, "a round with no done marker ends on the collection deadline, never hangs")
+}
+
+func TestFetchSchemaRegistry_NoStreamIsError(t *testing.T) {
+ ac := &agentConnection{agentID: "liaison-0"}
+ _, err := ac.fetchSchemaRegistry(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "not established")
+}
+
+func TestCancelSchemaRegistryFetch_WakesInflightFetchImmediately(t *testing.T) {
+ srv := &mockSchemaRegistryServer{ctx: context.Background(), sent: make(chan *fodcv1.StreamSchemaRegistryResponse, 1)}
+ ac := &agentConnection{agentID: "liaison-0", schemaRegistryStream: srv}
+
+ go func() {
+ <-srv.sent // the fetch has sent its request and is now waiting
+ ac.cancelSchemaRegistryFetch()
+ }()
+
+ // ctx far longer than the assertion window, so completing proves the cancel
+ // woke the fetch rather than the deadline firing. Reads happen-after fetchDone.
+ var gotGroups []*fodcv1.SchemaRegistryGroup
+ var gotErr error
+ fetchDone := make(chan struct{})
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ go func() {
+ gotGroups, gotErr = ac.fetchSchemaRegistry(ctx)
+ close(fetchDone)
+ }()
+
+ select {
+ case <-fetchDone:
+ require.Error(t, gotErr, "a mid-fetch disconnect wakes the fetch with a fatal error")
+ assert.Contains(t, gotErr.Error(), "disconnected")
+ assert.Nil(t, gotGroups)
+ case <-time.After(3 * time.Second):
+ t.Fatal("fetch was not woken by cancelSchemaRegistryFetch; it waited on ctx instead")
+ }
+}
diff --git a/fodc/proxy/internal/grpc/service.go b/fodc/proxy/internal/grpc/service.go
index 47acd8a19..09ea4c5d1 100644
--- a/fodc/proxy/internal/grpc/service.go
+++ b/fodc/proxy/internal/grpc/service.go
@@ -50,6 +50,9 @@ type agentConnection struct {
lifecycleStream fodcv1.FODCService_StreamLifecycleServer
crashDiagnosticsStream fodcv1.FODCService_StreamCrashDiagnosticsServer
pressureProfilesStream fodcv1.FODCService_StreamPressureProfilesServer
+ schemaRegistryStream fodcv1.FODCService_StreamSchemaRegistryServer
+ schemaRegistryCh chan *fodcv1.StreamSchemaRegistryRequest
+ schemaRegistryDone chan struct{}
pendingFetches map[string]*fetchWaiter
lastActivity time.Time
agentID string
@@ -166,6 +169,122 @@ func (ac *agentConnection) sendLifecycleDataRequest() error {
return nil
}
+// setSchemaRegistryStream sets the schema registry stream.
+func (ac *agentConnection) setSchemaRegistryStream(stream fodcv1.FODCService_StreamSchemaRegistryServer) {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ ac.schemaRegistryStream = stream
+}
+
+// schemaRegistryChanBuffer bounds the in-flight chunk backlog between the stream
+// receive loop and the fetch consumer; the consumer drains far faster than the
+// network delivers, so this is headroom, not a hard limit.
+const schemaRegistryChanBuffer = 16
+
+// fetchSchemaRegistry asks this agent to read the authoritative registry and
+// reassembles its streamed reply into a single result. Each group's objects
+// arrive across one or more chunks that share a group name; they are merged here.
+// fetchMu (shared with pressure-profile downloads) serializes fetches so the
+// response channel is unambiguous. The wait ends on the done marker in the normal
+// case and on ctx (the caller's collection deadline) otherwise, so a stalled or
+// disconnected agent cannot hang the collection.
+func (ac *agentConnection) fetchSchemaRegistry(ctx context.Context) ([]*fodcv1.SchemaRegistryGroup, error) {
+ ac.fetchMu.Lock()
+ defer ac.fetchMu.Unlock()
+
+ ch := make(chan *fodcv1.StreamSchemaRegistryRequest, schemaRegistryChanBuffer)
+ done := make(chan struct{})
+ ac.mu.Lock()
+ stream := ac.schemaRegistryStream
+ if stream == nil {
+ ac.mu.Unlock()
+ return nil, fmt.Errorf("schema registry stream not established for agent ID: %s", ac.agentID)
+ }
+ ac.schemaRegistryCh = ch
+ ac.schemaRegistryDone = done
+ ac.mu.Unlock()
+ defer func() {
+ ac.mu.Lock()
+ ac.schemaRegistryCh = nil
+ ac.schemaRegistryDone = nil
+ close(done)
+ ac.mu.Unlock()
+ }()
+
+ if sendErr := stream.Send(&fodcv1.StreamSchemaRegistryResponse{RequestRegistry: true}); sendErr != nil {
+ return nil, fmt.Errorf("failed to send schema registry request: %w", sendErr)
+ }
+
+ groups := make(map[string]*fodcv1.SchemaRegistryGroup)
+ order := make([]string, 0)
+ fatalErr := ""
+ for {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case msg := <-ch:
+ if chunk := msg.GetGroup(); chunk != nil {
+ name := chunk.GetGroup()
+ switch {
+ case name == "" && chunk.GetError() != "":
+ // Sentinel: the agent's fatal whole-read failure.
+ fatalErr = chunk.GetError()
+ case groups[name] == nil:
+ groups[name] = &fodcv1.SchemaRegistryGroup{Group: name, Objects: chunk.GetObjects(), Error: chunk.GetError()}
+ order = append(order, name)
+ default:
+ existing := groups[name]
+ existing.Objects = append(existing.Objects, chunk.GetObjects()...)
+ if chunk.GetError() != "" {
+ existing.Error = chunk.GetError()
+ }
+ }
+ }
+ if msg.GetDone() {
+ if fatalErr != "" {
+ return nil, fmt.Errorf("agent %s registry read failed: %s", ac.agentID, fatalErr)
+ }
+ result := make([]*fodcv1.SchemaRegistryGroup, 0, len(order))
+ for _, name := range order {
+ result = append(result, groups[name])
+ }
+ return result, nil
+ }
+ }
+ }
+}
+
+// deliverSchemaRegistry routes one received registry chunk to the waiting fetch.
+// It blocks until the consumer takes the chunk (so a full buffer never drops a
+// group and silently loses fingerprints) but abandons delivery once the fetch is
+// over, so a chunk arriving after a timed-out round cannot stall the stream's
+// receive loop.
+func (ac *agentConnection) deliverSchemaRegistry(msg *fodcv1.StreamSchemaRegistryRequest) {
+ ac.mu.RLock()
+ ch := ac.schemaRegistryCh
+ done := ac.schemaRegistryDone
+ ac.mu.RUnlock()
+ if ch == nil {
+ return
+ }
+ select {
+ case ch <- msg:
+ case <-done:
+ }
+}
+
+// cancelSchemaRegistryFetch wakes an in-flight schema registry fetch on agent
+// disconnect by delivering a fatal terminal, so the collection fails over to the
+// next liaison immediately instead of waiting out its deadline -- the schema
+// registry counterpart to cancelPendingFetches for pressure-profile downloads. It
+// is a no-op when no fetch is in flight.
+func (ac *agentConnection) cancelSchemaRegistryFetch() {
+ ac.deliverSchemaRegistry(&fodcv1.StreamSchemaRegistryRequest{
+ Group: &fodcv1.SchemaRegistryGroup{Error: "agent disconnected during registry read"},
+ Done: true,
+ })
+}
+
// setCrashDiagnosticsStream sets the crash diagnostics stream.
func (ac *agentConnection) setCrashDiagnosticsStream(stream fodcv1.FODCService_StreamCrashDiagnosticsServer) {
ac.mu.Lock()
@@ -478,6 +597,10 @@ func (s *FODCService) RegisterAgent(stream fodcv1.FODCService_RegisterAgentServe
s.logger.Error().Err(updateErr).Str("agent_id", agentID).Msg("Failed to update heartbeat")
return updateErr
}
+ // The heartbeat carries the agent's current node_role, which can resolve
+ // after the initial registration (e.g. a liaison whose gRPC came up late),
+ // so upgrade the stored role from it.
+ s.registry.UpdateAgentRole(agentID, req.GetNodeRole(), req.GetLabels())
if agentConn != nil {
agentConn.updateActivity()
@@ -603,6 +726,7 @@ func (s *FODCService) cleanupConnection(agentID string) {
if conn != nil {
conn.cancelPendingFetches()
+ conn.cancelSchemaRegistryFetch()
}
s.ackDepartedAgent(agentID)
if s.pressureAggregator != nil {
@@ -811,6 +935,73 @@ func (s *FODCService) RequestLifecycleData(agentID string) error {
return agentConn.sendLifecycleDataRequest()
}
+// StreamSchemaRegistry handles the bi-directional schema registry stream. The
+// agent opens it and blocks; the proxy drives only the one agent it selects,
+// which replies with the authoritative registry fingerprints.
+func (s *FODCService) StreamSchemaRegistry(stream fodcv1.FODCService_StreamSchemaRegistryServer) error {
+ ctx := stream.Context()
+ agentID := s.getAgentIDFromContext(ctx)
+ if agentID == "" {
+ agentID = s.getAgentIDFromPeer(ctx)
+ if agentID != "" {
+ s.logger.Warn().
+ Str("agent_id", agentID).
+ Msg("Agent ID not found in metadata, using peer address fallback (this may be unreliable)")
+ }
+ }
+ if agentID == "" {
+ s.logger.Error().Msg("Agent ID not found in context metadata or peer address for schema registry stream")
+ return status.Errorf(codes.Unauthenticated, "agent ID not found in context or peer address")
+ }
+
+ s.connectionsMu.Lock()
+ agentConn, exists := s.connections[agentID]
+ if exists {
+ agentConn.setSchemaRegistryStream(stream)
+ agentConn.updateActivity()
+ } else {
+ agentConn = &agentConnection{
+ agentID: agentID,
+ schemaRegistryStream: stream,
+ lastActivity: time.Now(),
+ }
+ s.connections[agentID] = agentConn
+ }
+ s.connectionsMu.Unlock()
+
+ for {
+ req, err := stream.Recv()
+ if errors.Is(err, io.EOF) {
+ s.logger.Debug().Str("agent_id", agentID).Msg("Schema registry stream closed by agent")
+ return nil
+ }
+ if err != nil {
+ if st, ok := status.FromError(err); ok && (st.Code() == codes.Canceled || st.Code() == codes.DeadlineExceeded) {
+ s.logger.Debug().Err(err).Str("agent_id", agentID).Msg("Schema registry stream closed")
+ } else if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ s.logger.Debug().Err(err).Str("agent_id", agentID).Msg("Schema registry stream closed")
+ } else {
+ s.logger.Error().Err(err).Str("agent_id", agentID).Msg("Error receiving schema registry data")
+ }
+ return err
+ }
+ agentConn.deliverSchemaRegistry(req)
+ }
+}
+
+// FetchSchemaRegistry asks the given agent to read the authoritative registry and
+// returns its per-group fingerprints. The lifecycle manager calls it on the one
+// agent it selects by role, so the registry is read once per collection cycle.
+func (s *FODCService) FetchSchemaRegistry(ctx context.Context, agentID string) ([]*fodcv1.SchemaRegistryGroup, error) {
+ s.connectionsMu.RLock()
+ agentConn, exists := s.connections[agentID]
+ s.connectionsMu.RUnlock()
+ if !exists {
+ return nil, fmt.Errorf("agent connection not found for agent ID: %s", agentID)
+ }
+ return agentConn.fetchSchemaRegistry(ctx)
+}
+
// HasCrashDiagnosticsStream reports whether the given agent has a crash diagnostics stream.
func (s *FODCService) HasCrashDiagnosticsStream(agentID string) bool {
s.connectionsMu.RLock()
diff --git a/fodc/proxy/internal/lifecycle/manager.go b/fodc/proxy/internal/lifecycle/manager.go
index e223ff17a..cbda7bf94 100644
--- a/fodc/proxy/internal/lifecycle/manager.go
+++ b/fodc/proxy/internal/lifecycle/manager.go
@@ -20,11 +20,14 @@ package lifecycle
import (
"context"
+ "errors"
"fmt"
"sort"
"sync"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
"github.com/apache/skywalking-banyandb/fodc/internal/timeouts"
"github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
"github.com/apache/skywalking-banyandb/pkg/logger"
@@ -75,17 +78,22 @@ type agentLifecycleData struct {
PodName string
}
-// RequestSender is an interface for sending lifecycle data requests to agents.
+// RequestSender is an interface for sending requests to agents. Beyond driving
+// the lifecycle stream, it reads the authoritative registry from a single
+// schema-serving agent the manager selects by role.
type RequestSender interface {
RequestLifecycleData(agentID string) error
+ FetchSchemaRegistry(ctx context.Context, agentID string) ([]*fodcv1.SchemaRegistryGroup, error)
}
// Manager manages lifecycle data from multiple agents.
type Manager struct {
+ grpcService RequestSender
log *logger.Logger
registry *registry.AgentRegistry
- grpcService RequestSender
collecting map[string]chan *agentLifecycleData
+ checker *consistency.Checker
+ schemaStatus map[string]fodcv1.ConsistencyStatus
mu sync.RWMutex
collectingMu sync.RWMutex
collectingOp sync.Mutex
@@ -94,11 +102,40 @@ type Manager struct {
// NewManager creates a new lifecycle manager.
func NewManager(registry *registry.AgentRegistry, grpcService RequestSender, log *logger.Logger) *Manager {
return &Manager{
- registry: registry,
- grpcService: grpcService,
- log: log,
- collecting: make(map[string]chan *agentLifecycleData),
+ registry: registry,
+ grpcService: grpcService,
+ log: log,
+ collecting: make(map[string]chan *agentLifecycleData),
+ checker: consistency.NewChecker(),
+ schemaStatus: make(map[string]fodcv1.ConsistencyStatus),
+ }
+}
+
+// SchemaConsistencySnapshot returns the per-group schema consistency status from
+// the most recent collection, for the proxy to export as a Prometheus gauge. It
+// reflects whatever cadence CollectLifecycle is driven at (the checker needs
+// regular collections anyway for its two-round suppression).
+func (m *Manager) SchemaConsistencySnapshot() map[string]fodcv1.ConsistencyStatus {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ out := make(map[string]fodcv1.ConsistencyStatus, len(m.schemaStatus))
+ for group, status := range m.schemaStatus {
+ out[group] = status
+ }
+ return out
+}
+
+// cacheSchemaStatus records the per-group verdict of a completed collection.
+func (m *Manager) cacheSchemaStatus(groups []*fodcv1.GroupLifecycleInfo) {
+ status := make(map[string]fodcv1.ConsistencyStatus, len(groups))
+ for _, g := range groups {
+ if sc := g.GetSchemaConsistency(); sc != nil {
+ status[g.GetName()] = sc.GetStatus()
+ }
}
+ m.mu.Lock()
+ m.schemaStatus = status
+ m.mu.Unlock()
}
// SetGRPCService sets the gRPC service for sending lifecycle data requests.
@@ -191,7 +228,9 @@ func (m *Manager) CollectLifecycle(ctx context.Context) (*InspectionResult, Agen
m.log.Info().Int("responses_with_data", len(allData)).
Msg("CollectLifecycle: all responses collected, aggregating")
- return m.buildInspectionResult(allData), summary
+ result := m.buildInspectionResult(ctx, allData, summary.NotResponded > 0)
+ m.cacheSchemaStatus(result.Groups)
+ return result, summary
}
func (m *Manager) requestAllAgents(ctx context.Context, agents []*registry.AgentInfo,
@@ -259,14 +298,106 @@ func (m *Manager) cleanupSessions(collectChs map[string]chan *agentLifecycleData
m.collectingMu.Unlock()
}
-func (m *Manager) buildInspectionResult(allData []*agentLifecycleData) *InspectionResult {
+func (m *Manager) buildInspectionResult(ctx context.Context, allData []*agentLifecycleData, shortfall bool) *InspectionResult {
+ registryByGroup, registryGroupErrs, registryErr := m.fetchRegistry(ctx)
+ verdicts := assembleSchemaConsistency(allData, m.checker, shortfall, registryByGroup)
+ schemaErrors := m.registrySchemaErrors(verdicts, registryGroupErrs, registryErr)
return &InspectionResult{
- Groups: m.mergeGroups(allData),
+ Groups: m.mergeGroups(allData, verdicts, schemaErrors),
LifecycleStatuses: m.aggregateLifecycle(allData),
}
}
-func (m *Manager) mergeGroups(allData []*agentLifecycleData) []*fodcv1.GroupLifecycleInfo {
+// registrySchemaErrors turns the registry-fetch failures into per-group error
+// strings so mergeGroups surfaces them on GroupLifecycleInfo.errors -- the same
+// channel the user already reads -- instead of the reason living only in a log
+// line. A fatal fetch failure is attached to every group the checker had to
+// downgrade, so each UNKNOWN carries its cause; per-group read failures attach to
+// just their group.
+func (m *Manager) registrySchemaErrors(
+ verdicts map[string]*fodcv1.SchemaConsistency, registryGroupErrs map[string]string, registryErr error,
+) map[string][]string {
+ schemaErrors := make(map[string][]string)
+ for group, e := range registryGroupErrs {
+ schemaErrors[group] = append(schemaErrors[group], "registry read failed: "+e)
+ }
+ if registryErr != nil {
+ m.log.Warn().Err(registryErr).Msg("schema registry fetch failed; schema consistency degrades to UNKNOWN")
+ for group := range verdicts {
+ schemaErrors[group] = append(schemaErrors[group], "registry unavailable: "+registryErr.Error())
+ }
+ }
+ return schemaErrors
+}
+
+// fetchRegistry reads the authoritative registry truth once per collection by
+// asking a single schema-serving agent, selected by its ROLE_LIAISON node role,
+// to read its local registry and report the fingerprints. It tries each liaison
+// agent in a deterministic order until one succeeds, so a single unhealthy
+// liaison does not blank the schema check. It returns the per-group fingerprints,
+// per-group read errors, and a fatal error when no liaison could be reached; the
+// caller surfaces these on the groups so the user learns why rather than only
+// seeing a log line.
+func (m *Manager) fetchRegistry(
+ ctx context.Context,
+) (map[string]map[consistency.ObjectKey]uint64, map[string]string, error) {
+ m.mu.RLock()
+ reg := m.registry
+ svc := m.grpcService
+ m.mu.RUnlock()
+ if reg == nil || svc == nil {
+ return nil, nil, errors.New("registry or grpc service not available for schema registry read")
+ }
+ liaisons := reg.ListAgentsByRole(databasev1.Role_ROLE_LIAISON.String())
+ if len(liaisons) == 0 {
+ return nil, nil, errors.New("no schema-serving (liaison) agent available to read the registry")
+ }
+ sort.Slice(liaisons, func(i, j int) bool { return liaisons[i].AgentID < liaisons[j].AgentID })
+ var lastErr error
+ for _, agentInfo := range liaisons {
+ // Bound each read so a liaison that dies mid-stream (never sending its done
+ // marker) cannot hang the collection past this deadline.
+ fetchCtx, cancel := context.WithTimeout(ctx, defaultCollectionTimeout)
+ groups, err := svc.FetchSchemaRegistry(fetchCtx, agentInfo.AgentID)
+ cancel()
+ if err != nil {
+ lastErr = err
+ continue
+ }
+ registryByGroup, groupErrs := schemaRegistryToFingerprints(groups)
+ return registryByGroup, groupErrs, nil
+ }
+ return nil, nil, fmt.Errorf("schema registry read failed on all %d liaison agent(s): %w", len(liaisons), lastErr)
+}
+
+// schemaRegistryToFingerprints converts the agent's reported registry message
+// into the per-group object fingerprint map the checker consumes, splitting out
+// per-group read errors (a group whose read failed carries no objects and its
+// reason is returned so the caller can surface it).
+func schemaRegistryToFingerprints(
+ groups []*fodcv1.SchemaRegistryGroup,
+) (map[string]map[consistency.ObjectKey]uint64, map[string]string) {
+ byGroup := make(map[string]map[consistency.ObjectKey]uint64, len(groups))
+ groupErrs := make(map[string]string)
+ for _, g := range groups {
+ if e := g.GetError(); e != "" {
+ groupErrs[g.GetGroup()] = e
+ continue
+ }
+ objects := make(map[consistency.ObjectKey]uint64, len(g.GetObjects()))
+ for _, o := range g.GetObjects() {
+ objects[consistency.ObjectKey{Kind: o.GetKind(), Name: o.GetName()}] = o.GetFingerprint()
+ }
+ byGroup[g.GetGroup()] = objects
+ }
+ return byGroup, groupErrs
+}
+
+func (m *Manager) mergeGroups(
+ allData []*agentLifecycleData,
+ verdicts map[string]*fodcv1.SchemaConsistency,
+ schemaErrors map[string][]string,
+) []*fodcv1.GroupLifecycleInfo {
groupMap := make(map[string]*fodcv1.GroupLifecycleInfo)
// Errors are unioned across agents because each agent may observe a
// different subset of per-node failures (e.g. liaison-0 sees cold-0
@@ -274,27 +405,43 @@ func (m *Manager) mergeGroups(allData []*agentLifecycleData) []*fodcv1.GroupLife
// of the GroupLifecycleInfo is fine -- name/catalog/resource_opts are
// agent-invariant -- but errors must be the deduped union.
mergedErrors := make(map[string]map[string]struct{})
+ addErr := func(group string, errs ...string) {
+ if len(errs) == 0 {
+ return
+ }
+ set, ok := mergedErrors[group]
+ if !ok {
+ set = make(map[string]struct{})
+ mergedErrors[group] = set
+ }
+ for _, e := range errs {
+ set[e] = struct{}{}
+ }
+ }
for _, ad := range allData {
if ad == nil || ad.Data == nil {
continue
}
for _, g := range ad.Data.Groups {
groupMap[g.Name] = g
- if len(g.Errors) == 0 {
- continue
- }
- set, ok := mergedErrors[g.Name]
- if !ok {
- set = make(map[string]struct{})
- mergedErrors[g.Name] = set
- }
- for _, e := range g.Errors {
- set[e] = struct{}{}
- }
+ // g.Errors already carries this agent's schema collection errors (the
+ // agent folds them in before sending), so the union covers them too.
+ addErr(g.Name, g.Errors...)
}
}
+ // The proxy's own registry-fetch failures (fatal or per-group) surface here so
+ // each affected group tells the user why its verdict is UNKNOWN.
+ for group, errs := range schemaErrors {
+ addErr(group, errs...)
+ }
groups := make([]*fodcv1.GroupLifecycleInfo, 0, len(groupMap))
for name, g := range groupMap {
+ // g is this round's freshly received data: the gRPC stream re-unmarshals
+ // every LifecycleData on arrival and nothing caches it, so overwriting the
+ // two merged fields in place cannot leak into a later round. This keeps
+ // every other field (and any future field) without a copy that must be
+ // kept in lockstep with the message definition.
+ g.SchemaConsistency = verdicts[name]
if set := mergedErrors[name]; len(set) > 0 {
errs := make([]string, 0, len(set))
for e := range set {
@@ -305,6 +452,10 @@ func (m *Manager) mergeGroups(allData []*agentLifecycleData) []*fodcv1.GroupLife
}
groups = append(groups, g)
}
+ // Range over groupMap is nondeterministic; sort so the payload order is
+ // stable across requests (the checker sorts its own slices for the same
+ // reason).
+ sort.Slice(groups, func(i, j int) bool { return groups[i].GetName() < groups[j].GetName() })
return groups
}
diff --git a/fodc/proxy/internal/lifecycle/manager_test.go b/fodc/proxy/internal/lifecycle/manager_test.go
index 3f1117705..ca070e6ab 100644
--- a/fodc/proxy/internal/lifecycle/manager_test.go
+++ b/fodc/proxy/internal/lifecycle/manager_test.go
@@ -34,7 +34,11 @@ import (
type mockRequestSender struct {
requestErrors map[string]error
+ schemaRegErr error
+ failAgents map[string]error
+ schemaRegistry []*fodcv1.SchemaRegistryGroup
requestedAgents []string
+ schemaFetchedBy []string
mu sync.Mutex
}
@@ -45,6 +49,22 @@ func newMockRequestSender() *mockRequestSender {
}
}
+func (m *mockRequestSender) FetchSchemaRegistry(_ context.Context, agentID string) ([]*fodcv1.SchemaRegistryGroup, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.schemaFetchedBy = append(m.schemaFetchedBy, agentID)
+ if err, ok := m.failAgents[agentID]; ok {
+ return nil, err
+ }
+ if m.schemaRegErr != nil {
+ return nil, m.schemaRegErr
+ }
+ if m.schemaRegistry != nil {
+ return m.schemaRegistry, nil
+ }
+ return nil, fmt.Errorf("no schema registry configured")
+}
+
func (m *mockRequestSender) RequestLifecycleData(agentID string) error {
m.mu.Lock()
defer m.mu.Unlock()
@@ -442,7 +462,7 @@ func TestManager_MergeGroups_UnionsErrorsAcrossAgents(t *testing.T) {
},
}
- merged := mgr.mergeGroups([]*agentLifecycleData{agentA, agentB, agentC})
+ merged := mgr.mergeGroups([]*agentLifecycleData{agentA, agentB, agentC}, nil, nil)
require.Len(t, merged, 1)
g := merged[0]
assert.Equal(t, groupName, g.Name)
diff --git a/fodc/proxy/internal/lifecycle/schema_check.go b/fodc/proxy/internal/lifecycle/schema_check.go
new file mode 100644
index 000000000..56c2978fa
--- /dev/null
+++ b/fodc/proxy/internal/lifecycle/schema_check.go
@@ -0,0 +1,89 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
+)
+
+// assembleSchemaConsistency unions the per-agent SchemaConsistency partials
+// (each agent's local node cache/runtime fingerprints) and compares them against
+// registryByGroup -- the registry truth the proxy fetched once from a
+// schema-serving node -- running the checker once per group. Fingerprint compute
+// happened in the agents and (for the registry) in the proxy's fetch; the
+// checker only compares. It returns the per-group verdict, which the caller
+// writes back onto the merged GroupLifecycleInfo (per-group collection errors
+// already ride on GroupLifecycleInfo.errors and are unioned by the group merge).
+//
+// shortfall is set when an agent that should have reported did not, so the
+// checker degrades affected groups to UNKNOWN rather than concluding CONSISTENT
+// from a partial node set. A group with no registry truth (registry fetch failed
+// or omitted it) is also UNKNOWN rather than treating every node object as an
+// orphan.
+func assembleSchemaConsistency(
+ allData []*agentLifecycleData, checker *consistency.Checker, shortfall bool,
+ registryByGroup map[string]map[consistency.ObjectKey]uint64,
+) map[string]*fodcv1.SchemaConsistency {
+ nodesByGroup := make(map[string]map[string][]*consistency.NodeObjectFP)
+ for _, ad := range allData {
+ if ad == nil || ad.Data == nil {
+ continue
+ }
+ for _, g := range ad.Data.GetGroups() {
+ sc := g.GetSchemaConsistency()
+ if sc == nil {
+ continue
+ }
+ nodes, ok := nodesByGroup[g.GetName()]
+ if !ok {
+ nodes = make(map[string][]*consistency.NodeObjectFP)
+ nodesByGroup[g.GetName()] = nodes
+ }
+ for _, oc := range sc.GetObjects() {
+ for _, nf := range oc.GetNodeFingerprints() {
+ nodes[nf.GetNode()] = append(nodes[nf.GetNode()], &consistency.NodeObjectFP{
+ Kind: oc.GetKind(), Name: oc.GetName(),
+ Cache: nf.GetCacheFingerprint(), Runtime: nf.GetRuntimeFingerprint(),
+ })
+ }
+ }
+ }
+ }
+
+ verdicts := make(map[string]*fodcv1.SchemaConsistency, len(nodesByGroup))
+ for group, nodeMap := range nodesByGroup {
+ registry := registryByGroup[group]
+ if len(registry) == 0 {
+ verdicts[group] = &fodcv1.SchemaConsistency{
+ Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN,
+ }
+ continue
+ }
+ nodes := make([]consistency.NodeObjects, 0, len(nodeMap))
+ for node, objects := range nodeMap {
+ nodes = append(nodes, consistency.NodeObjects{Node: node, Objects: objects})
+ }
+ expected := len(nodes)
+ if shortfall {
+ expected = len(nodes) + 1
+ }
+ verdicts[group] = checker.Check(group, registry, nodes, expected)
+ }
+ return verdicts
+}
diff --git a/fodc/proxy/internal/lifecycle/schema_consistency_merge_test.go b/fodc/proxy/internal/lifecycle/schema_consistency_merge_test.go
new file mode 100644
index 000000000..24aab2105
--- /dev/null
+++ b/fodc/proxy/internal/lifecycle/schema_consistency_merge_test.go
@@ -0,0 +1,363 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package lifecycle
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1"
+ "github.com/apache/skywalking-banyandb/fodc/internal/consistency"
+ "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+// testGroup is the single group the assembly cases operate on.
+const testGroup = "g"
+
+// nodeObj is one object carrying a single node's cache/runtime fingerprints, as
+// that node's agent reports it.
+func nodeObj(kind, name, node string, cache, runtime uint64) *fodcv1.ObjectConsistency {
+ return &fodcv1.ObjectConsistency{
+ Kind: kind, Name: name,
+ NodeFingerprints: []*fodcv1.NodeFingerprint{{Node: node, CacheFingerprint: cache, RuntimeFingerprint: runtime}},
+ }
+}
+
+// agentData is one agent's LifecycleData with a single group whose
+// schema_consistency partial carries the given objects.
+func agentData(objs ...*fodcv1.ObjectConsistency) *agentLifecycleData {
+ return &agentLifecycleData{Data: &fodcv1.LifecycleData{Groups: []*fodcv1.GroupLifecycleInfo{
+ {Name: testGroup, SchemaConsistency: &fodcv1.SchemaConsistency{Objects: objs}},
+ }}}
+}
+
+// registryTruth is what the proxy fetches once from a schema-serving node: the
+// group object plus the stream object, both at their canonical fingerprints. A
+// node whose stream fingerprint differs from 100 is diverging.
+func registryTruth() map[string]map[consistency.ObjectKey]uint64 {
+ return map[string]map[consistency.ObjectKey]uint64{
+ testGroup: {
+ {Kind: "group", Name: testGroup}: 1,
+ {Kind: "stream", Name: "foo"}: 100,
+ },
+ }
+}
+
+// nodeContribution is one node's fingerprints for the group and stream objects.
+func nodeContribution(node string, cacheFP, runtimeFP uint64) *agentLifecycleData {
+ return agentData(
+ nodeObj("group", testGroup, node, 1, 1),
+ nodeObj("stream", "foo", node, cacheFP, runtimeFP),
+ )
+}
+
+func TestAssembleSchemaConsistency_AgreementIsConsistent(t *testing.T) {
+ data := []*agentLifecycleData{nodeContribution("data-1", 100, 100)}
+
+ verdicts := assembleSchemaConsistency(data, consistency.NewChecker(), false, registryTruth())
+
+ require.Contains(t, verdicts, "g")
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, verdicts["g"].GetStatus())
+}
+
+func TestAssembleSchemaConsistency_DivergenceReportedAfterTwoRounds(t *testing.T) {
+ // The node's cache (200) disagrees with the registry (100). The checker
+ // suppresses the first round, then reports on the second.
+ checker := consistency.NewChecker()
+ data := []*agentLifecycleData{nodeContribution("data-1", 200, 200)}
+
+ first := assembleSchemaConsistency(data, checker, false, registryTruth())
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, first["g"].GetStatus(),
+ "a first-round divergence may still be in-flight propagation")
+
+ second := assembleSchemaConsistency(data, checker, false, registryTruth())
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, second["g"].GetStatus())
+ require.Len(t, second["g"].GetIssues(), 1)
+ assert.Equal(t, "data-1", second["g"].GetIssues()[0].GetNode())
+}
+
+func TestAssembleSchemaConsistency_NoRegistryIsUnknown(t *testing.T) {
+ // A node reported, but the proxy fetched no registry truth for the group
+ // (fetch failed or omitted it), so the objects cannot be verified.
+ data := []*agentLifecycleData{nodeContribution("data-1", 100, 100)}
+
+ verdicts := assembleSchemaConsistency(data, consistency.NewChecker(), false, nil)
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, verdicts["g"].GetStatus())
+}
+
+func TestAssembleSchemaConsistency_ShortfallForcesUnknown(t *testing.T) {
+ // Every answering node agrees, but an agent went silent this round, so a node
+ // could be silently diverging -> UNKNOWN, never CONSISTENT.
+ data := []*agentLifecycleData{nodeContribution("data-1", 100, 100)}
+
+ verdicts := assembleSchemaConsistency(data, consistency.NewChecker(), true, registryTruth())
+
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN, verdicts["g"].GetStatus())
+}
+
+func TestAssembleSchemaConsistency_UnionsNodeFingerprints(t *testing.T) {
+ // Each node's fingerprints come from its own agent; the proxy pairs them with
+ // the single registry truth it fetched.
+ data := []*agentLifecycleData{
+ nodeContribution("data-1", 100, 100),
+ nodeContribution("liaison-1", 100, 100),
+ }
+
+ verdicts := assembleSchemaConsistency(data, consistency.NewChecker(), false, registryTruth())
+
+ objs := verdicts["g"].GetObjects()
+ var stream *fodcv1.ObjectConsistency
+ for _, o := range objs {
+ if o.GetKind() == "stream" {
+ stream = o
+ }
+ }
+ require.NotNil(t, stream)
+ assert.Equal(t, uint64(100), stream.GetRegistryFingerprint())
+ require.Len(t, stream.GetNodeFingerprints(), 2, "both nodes' fingerprints appear")
+ assert.Equal(t, "data-1", stream.GetNodeFingerprints()[0].GetNode(), "sorted by node id")
+ assert.Equal(t, "liaison-1", stream.GetNodeFingerprints()[1].GetNode())
+}
+
+func TestMergeGroups_AppliesVerdictAndUnionsErrors(t *testing.T) {
+ // Two agents each observe the group with a different error; the merge unions
+ // them and stamps on the proxy's verdict.
+ mgr := NewManager(nil, nil, logger.GetLogger("test-merge"))
+ data := []*agentLifecycleData{
+ {Data: &fodcv1.LifecycleData{Groups: []*fodcv1.GroupLifecycleInfo{{Name: "g", Errors: []string{"collect: boom"}}}}},
+ {Data: &fodcv1.LifecycleData{Groups: []*fodcv1.GroupLifecycleInfo{{Name: "g", Errors: []string{"schema: registry unavailable"}}}}},
+ }
+ verdicts := map[string]*fodcv1.SchemaConsistency{
+ "g": {Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT},
+ }
+
+ got := mgr.mergeGroups(data, verdicts, nil)
+
+ require.Len(t, got, 1)
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, got[0].GetSchemaConsistency().GetStatus())
+ assert.ElementsMatch(t, []string{"collect: boom", "schema: registry unavailable"}, got[0].GetErrors(),
+ "collection and schema errors are unioned across agents")
+}
+
+func TestMergeGroups_NoVerdictStaysNil(t *testing.T) {
+ // A group with no schema reports (e.g. a property group) gets no verdict.
+ mgr := NewManager(nil, nil, logger.GetLogger("test-merge"))
+ data := []*agentLifecycleData{{Data: &fodcv1.LifecycleData{
+ Groups: []*fodcv1.GroupLifecycleInfo{{Name: "g"}},
+ }}}
+
+ got := mgr.mergeGroups(data, map[string]*fodcv1.SchemaConsistency{}, nil)
+
+ require.Len(t, got, 1)
+ assert.Nil(t, got[0].GetSchemaConsistency())
+}
+
+func TestMergeGroups_IsolatesDistinctGroups(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-merge"))
+ data := []*agentLifecycleData{{Data: &fodcv1.LifecycleData{Groups: []*fodcv1.GroupLifecycleInfo{
+ {Name: "a"}, {Name: "b"},
+ }}}}
+ verdicts := map[string]*fodcv1.SchemaConsistency{
+ "a": {Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT},
+ "b": {Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT},
+ }
+
+ got := mgr.mergeGroups(data, verdicts, nil)
+
+ require.Len(t, got, 2)
+ byName := map[string]*fodcv1.GroupLifecycleInfo{got[0].GetName(): got[0], got[1].GetName(): got[1]}
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, byName["a"].GetSchemaConsistency().GetStatus())
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, byName["b"].GetSchemaConsistency().GetStatus())
+}
+
+func TestRegistrySchemaErrors_FatalAttachesToEveryVerdictGroup(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-reg-err"))
+ verdicts := map[string]*fodcv1.SchemaConsistency{"a": {}, "b": {}}
+
+ got := mgr.registrySchemaErrors(verdicts, map[string]string{"a": "boom-a"}, errors.New("unreachable"))
+
+ assert.Contains(t, got["a"], "registry read failed: boom-a", "a per-group read error attaches to its group")
+ assert.Contains(t, got["a"], "registry unavailable: unreachable", "the fatal error also attaches to a")
+ assert.Contains(t, got["b"], "registry unavailable: unreachable", "the fatal error reaches every downgraded group")
+ assert.NotContains(t, got["b"], "registry read failed: boom-a", "a per-group error does not bleed into other groups")
+}
+
+func TestRegistrySchemaErrors_NoErrorIsEmpty(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-reg-err"))
+
+ got := mgr.registrySchemaErrors(map[string]*fodcv1.SchemaConsistency{"a": {}}, nil, nil)
+
+ assert.Empty(t, got["a"], "a clean fetch surfaces no schema errors")
+}
+
+func TestMergeGroups_SurfacesRegistryErrors(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-merge-reg"))
+ data := []*agentLifecycleData{{Data: &fodcv1.LifecycleData{
+ Groups: []*fodcv1.GroupLifecycleInfo{{Name: "g", Errors: []string{"collect: boom"}}},
+ }}}
+
+ got := mgr.mergeGroups(data, map[string]*fodcv1.SchemaConsistency{}, map[string][]string{"g": {"registry unavailable: down"}})
+
+ require.Len(t, got, 1)
+ assert.ElementsMatch(t, []string{"collect: boom", "registry unavailable: down"}, got[0].GetErrors(),
+ "registry errors are unioned onto the group alongside the agent's own errors")
+}
+
+func TestSchemaConsistencySnapshot_CachesVerdictExcludingNilAndCopies(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-snap"))
+ assert.Empty(t, mgr.SchemaConsistencySnapshot(), "no collection yet -> empty")
+
+ mgr.cacheSchemaStatus([]*fodcv1.GroupLifecycleInfo{
+ {Name: "a", SchemaConsistency: &fodcv1.SchemaConsistency{Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT}},
+ {Name: "b", SchemaConsistency: &fodcv1.SchemaConsistency{Status: fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT}},
+ {Name: "prop", SchemaConsistency: nil}, // property group: no verdict -> excluded
+ })
+
+ snap := mgr.SchemaConsistencySnapshot()
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, snap["a"])
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_INCONSISTENT, snap["b"])
+ assert.NotContains(t, snap, "prop", "a group without a verdict exports no metric")
+
+ // The returned map is a copy: mutating it must not corrupt the cache.
+ snap["a"] = fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_UNKNOWN
+ assert.Equal(t, fodcv1.ConsistencyStatus_CONSISTENCY_STATUS_CONSISTENT, mgr.SchemaConsistencySnapshot()["a"])
+}
+
+func TestFetchRegistry_NoRegistryOrServiceIsError(t *testing.T) {
+ mgr := NewManager(nil, nil, logger.GetLogger("test-fetch"))
+ _, _, err := mgr.fetchRegistry(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "not available")
+}
+
+func TestFetchRegistry_NoLiaisonAgentIsError(t *testing.T) {
+ log := logger.GetLogger("test-fetch")
+ reg := registry.NewAgentRegistry(log, 5*time.Second, 10*time.Second, 100)
+ defer reg.Stop()
+ // Only a data agent is registered: none can serve the registry.
+ _, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_DATA.String(), PodName: "data-0"})
+ require.NoError(t, err)
+
+ mgr := NewManager(reg, newMockRequestSender(), log)
+ _, _, err = mgr.fetchRegistry(context.Background())
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "no schema-serving (liaison) agent")
+}
+
+func TestFetchRegistry_SelectsLiaisonAndConverts(t *testing.T) {
+ log := logger.GetLogger("test-fetch")
+ reg := registry.NewAgentRegistry(log, 5*time.Second, 10*time.Second, 100)
+ defer reg.Stop()
+ _, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_LIAISON.String(), PodName: "liaison-0"})
+ require.NoError(t, err)
+
+ sender := newMockRequestSender()
+ sender.schemaRegistry = []*fodcv1.SchemaRegistryGroup{
+ {Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{
+ {Kind: "group", Name: "g", Fingerprint: 1},
+ {Kind: "stream", Name: "foo", Fingerprint: 100},
+ }},
+ {Group: "broken", Error: "list streams of broken: boom"},
+ }
+ mgr := NewManager(reg, sender, log)
+
+ byGroup, groupErrs, err := mgr.fetchRegistry(context.Background())
+
+ require.NoError(t, err)
+ assert.Equal(t, uint64(100), byGroup["g"][consistency.ObjectKey{Kind: "stream", Name: "foo"}])
+ assert.Equal(t, uint64(1), byGroup["g"][consistency.ObjectKey{Kind: "group", Name: "g"}])
+ assert.Contains(t, groupErrs["broken"], "boom", "a per-group read error is surfaced, not the objects")
+ assert.NotContains(t, byGroup, "broken")
+}
+
+func TestFetchRegistry_FatalFromSelectedAgentIsError(t *testing.T) {
+ log := logger.GetLogger("test-fetch")
+ reg := registry.NewAgentRegistry(log, 5*time.Second, 10*time.Second, 100)
+ defer reg.Stop()
+ _, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_LIAISON.String(), PodName: "liaison-0"})
+ require.NoError(t, err)
+
+ sender := newMockRequestSender()
+ // The agent read failed wholesale (e.g. its local registry endpoint was down).
+ sender.schemaRegErr = errors.New("dial 127.0.0.1:17912: connection refused")
+ mgr := NewManager(reg, sender, log)
+
+ _, _, err = mgr.fetchRegistry(context.Background())
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "connection refused")
+}
+
+func TestFetchRegistry_NeverSelectsDataAgent(t *testing.T) {
+ log := logger.GetLogger("test-fetch")
+ reg := registry.NewAgentRegistry(log, 5*time.Second, 10*time.Second, 100)
+ defer reg.Stop()
+ liaisonID, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_LIAISON.String(), PodName: "liaison-0"})
+ require.NoError(t, err)
+ dataID, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_DATA.String(), PodName: "data-0"})
+ require.NoError(t, err)
+
+ sender := newMockRequestSender()
+ sender.schemaRegistry = []*fodcv1.SchemaRegistryGroup{
+ {Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{{Kind: "group", Name: "g", Fingerprint: 1}}},
+ }
+ mgr := NewManager(reg, sender, log)
+
+ _, _, ferr := mgr.fetchRegistry(context.Background())
+
+ require.NoError(t, ferr)
+ assert.Equal(t, []string{liaisonID}, sender.schemaFetchedBy, "only the liaison agent is asked to read the registry")
+ assert.NotContains(t, sender.schemaFetchedBy, dataID, "the data agent is never selected")
+}
+
+func TestFetchRegistry_RetriesNextLiaisonOnFailure(t *testing.T) {
+ log := logger.GetLogger("test-fetch")
+ reg := registry.NewAgentRegistry(log, 5*time.Second, 10*time.Second, 100)
+ defer reg.Stop()
+ idA, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_LIAISON.String(), PodName: "liaison-a"})
+ require.NoError(t, err)
+ idB, err := reg.RegisterAgent(context.Background(), registry.AgentIdentity{Role: databasev1.Role_ROLE_LIAISON.String(), PodName: "liaison-b"})
+ require.NoError(t, err)
+
+ // The manager tries liaisons sorted by AgentID; fail the first so it must fall through.
+ first, second := idA, idB
+ if second < first {
+ first, second = second, first
+ }
+ sender := newMockRequestSender()
+ sender.failAgents = map[string]error{first: errors.New("liaison down")}
+ sender.schemaRegistry = []*fodcv1.SchemaRegistryGroup{
+ {Group: "g", Objects: []*fodcv1.SchemaObjectFingerprint{{Kind: "group", Name: "g", Fingerprint: 1}}},
+ }
+ mgr := NewManager(reg, sender, log)
+
+ byGroup, _, ferr := mgr.fetchRegistry(context.Background())
+
+ require.NoError(t, ferr, "the second liaison succeeds after the first fails")
+ assert.Contains(t, byGroup, "g")
+ assert.Equal(t, []string{first, second}, sender.schemaFetchedBy, "tried in sorted order: first (failed) then second")
+}
diff --git a/fodc/proxy/internal/registry/registry.go b/fodc/proxy/internal/registry/registry.go
index 8483cfc86..b5ac843af 100644
--- a/fodc/proxy/internal/registry/registry.go
+++ b/fodc/proxy/internal/registry/registry.go
@@ -166,6 +166,38 @@ func (ar *AgentRegistry) UpdateHeartbeat(agentID string) error {
return nil
}
+// roleUnspecified is the node-role string an agent reports before its node role
+// has resolved; it must never overwrite an already-resolved role.
+const roleUnspecified = "ROLE_UNSPECIFIED"
+
+// UpdateAgentRole refreshes an agent's node role (and labels) from a heartbeat.
+// The node_role can resolve only after the initial registration -- e.g. a liaison
+// whose client gRPC comes up later than the agent's role-resolution budget, so the
+// agent first registers as ROLE_UNSPECIFIED -- and every heartbeat carries the
+// agent's current value. A blank or unspecified incoming role never overwrites an
+// already-resolved one, so a transient resolution failure cannot regress the role.
+func (ar *AgentRegistry) UpdateAgentRole(agentID, role string, labels map[string]string) {
+ if role == "" || role == roleUnspecified {
+ return
+ }
+ ar.mu.Lock()
+ defer ar.mu.Unlock()
+ agentInfo, exists := ar.agents[agentID]
+ if !exists || agentInfo.AgentIdentity.Role == role {
+ return
+ }
+ ar.logger.Info().
+ Str("agent_id", agentID).
+ Str("old_role", agentInfo.AgentIdentity.Role).
+ Str("new_role", role).
+ Msg("Agent role refreshed from heartbeat")
+ agentInfo.AgentIdentity.Role = role
+ if labels != nil {
+ agentInfo.AgentIdentity.Labels = labels
+ agentInfo.Labels = labels
+ }
+}
+
// GetAgent retrieves agent information by primary containerNames + role + labels.
func (ar *AgentRegistry) GetAgent(podName string, role string, labels map[string]string) (*AgentInfo, error) {
ar.mu.RLock()
diff --git a/fodc/proxy/internal/registry/registry_test.go b/fodc/proxy/internal/registry/registry_test.go
index 32ae788c4..0e0e0c9e8 100644
--- a/fodc/proxy/internal/registry/registry_test.go
+++ b/fodc/proxy/internal/registry/registry_test.go
@@ -648,3 +648,38 @@ func TestConcurrentUpdateHeartbeat(t *testing.T) {
require.NoError(t, getErr)
assert.Equal(t, AgentStatusOnline, agentInfo.Status)
}
+
+func TestUpdateAgentRole_UpgradesFromUnspecified(t *testing.T) {
+ ar := newTestRegistry(t, time.Minute, 2*time.Minute, 10)
+ defer ar.Stop()
+ id, err := ar.RegisterAgent(context.Background(), AgentIdentity{Role: roleUnspecified, PodName: "liaison-0"})
+ require.NoError(t, err)
+ require.Empty(t, ar.ListAgentsByRole("ROLE_LIAISON"), "an unresolved role is not yet a liaison")
+
+ // A later heartbeat carries the resolved role.
+ ar.UpdateAgentRole(id, "ROLE_LIAISON", map[string]string{"k": "v"})
+
+ liaisons := ar.ListAgentsByRole("ROLE_LIAISON")
+ require.Len(t, liaisons, 1, "the resolved role is picked up from the heartbeat")
+ assert.Equal(t, id, liaisons[0].AgentID)
+ assert.Equal(t, "v", liaisons[0].AgentIdentity.Labels["k"])
+}
+
+func TestUpdateAgentRole_BlankOrUnspecifiedNeverRegresses(t *testing.T) {
+ ar := newTestRegistry(t, time.Minute, 2*time.Minute, 10)
+ defer ar.Stop()
+ id, err := ar.RegisterAgent(context.Background(), AgentIdentity{Role: "ROLE_LIAISON", PodName: "liaison-0"})
+ require.NoError(t, err)
+
+ ar.UpdateAgentRole(id, "", nil) // blank: ignored
+ ar.UpdateAgentRole(id, roleUnspecified, nil) // unspecified: ignored
+
+ assert.Len(t, ar.ListAgentsByRole("ROLE_LIAISON"), 1,
+ "a resolved role is never regressed by a transient blank/unspecified heartbeat")
+}
+
+func TestUpdateAgentRole_UnknownAgentIsNoop(t *testing.T) {
+ ar := newTestRegistry(t, time.Minute, 2*time.Minute, 10)
+ defer ar.Stop()
+ ar.UpdateAgentRole("missing-agent", "ROLE_LIAISON", nil) // must not panic
+}
diff --git a/pkg/schema/cache.go b/pkg/schema/cache.go
index 60ac65f98..430e52b4e 100644
--- a/pkg/schema/cache.go
+++ b/pkg/schema/cache.go
@@ -469,6 +469,32 @@ func (sr *schemaRepo) LoadResource(metadata *commonv1.Metadata) (Resource, bool)
return s.(Resource), true
}
+// LoadAllResources returns every cached resource belonging to the group.
+// The schema consistency collector needs to enumerate a group's resources;
+// LoadResource only answers for a name the caller already knows.
+func (sr *schemaRepo) LoadAllResources(group string) []Resource {
+ var result []Resource
+ sr.resourceMap.Range(func(key, value any) bool {
+ if path.Dir(key.(string)) == group {
+ result = append(result, value.(Resource))
+ }
+ return true
+ })
+ return result
+}
+
+// LoadAllIndexRules returns every cached index rule belonging to the group.
+func (sr *schemaRepo) LoadAllIndexRules(group string) []*databasev1.IndexRule {
+ var result []*databasev1.IndexRule
+ sr.indexRuleMap.Range(func(key, value any) bool {
+ if path.Dir(key.(string)) == group {
+ result = append(result, value.(*databasev1.IndexRule))
+ }
+ return true
+ })
+ return result
+}
+
func (sr *schemaRepo) storeResource(resourceSchema ResourceSchema) error {
sr.resourceMutex.Lock()
defer sr.resourceMutex.Unlock()
@@ -488,7 +514,7 @@ func (sr *schemaRepo) storeResource(resourceSchema ResourceSchema) error {
if err != nil {
return errors.WithMessage(err, "fails to open the resource")
}
- sm.OnIndexUpdate(sr.indexRules(resourceSchema))
+ sm.OnIndexUpdate(sr.IndexRules(resourceSchema))
resource.delegated = sm
sr.resourceMap.Store(key, resource)
sr.updateLatestModRevision(resourceSchema.GetMetadata().GetModRevision())
@@ -567,11 +593,13 @@ func (sr *schemaRepo) updateIndex(binding *databasev1.IndexRuleBinding) {
Name: binding.Subject.GetName(),
Group: binding.GetMetadata().GetGroup(),
}); ok {
- r.Delegated().OnIndexUpdate(sr.indexRules(r.Schema()))
+ r.Delegated().OnIndexUpdate(sr.IndexRules(r.Schema()))
}
}
-func (sr *schemaRepo) indexRules(schema ResourceSchema) []*databasev1.IndexRule {
+// IndexRules derives the index rules bound to a resource -- exactly what the
+// runtime is fed on OnIndexUpdate and what the consistency collector fingerprints.
+func (sr *schemaRepo) IndexRules(schema ResourceSchema) []*databasev1.IndexRule {
n := schema.GetMetadata().GetName()
g := schema.GetMetadata().GetGroup()
col, _ := sr.bindingForwardMap.Load(getKey(&commonv1.Metadata{
diff --git a/pkg/schema/cache_internal_test.go b/pkg/schema/cache_internal_test.go
new file mode 100644
index 000000000..21bba532e
--- /dev/null
+++ b/pkg/schema/cache_internal_test.go
@@ -0,0 +1,145 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package schema
+
+import (
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+// TestIndexRules_BehaviourContract locks the exact semantics indexRules must
+// keep across the DeriveBoundRules refactor: duplicates preserved, missing rules
+// skipped silently.
+func TestIndexRules_BehaviourContract(t *testing.T) {
+ sr := &schemaRepo{}
+
+ bindings := &sync.Map{}
+ bindings.Store("g/b1", &databasev1.IndexRuleBinding{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "b1"},
+ Subject: &databasev1.Subject{Name: "foo", Catalog: commonv1.Catalog_CATALOG_STREAM},
+ Rules: []string{"r1", "absent"},
+ })
+ bindings.Store("g/b2", &databasev1.IndexRuleBinding{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "b2"},
+ Subject: &databasev1.Subject{Name: "foo", Catalog: commonv1.Catalog_CATALOG_STREAM},
+ Rules: []string{"r1"},
+ })
+ sr.bindingForwardMap.Store("g/foo", bindings)
+ sr.indexRuleMap.Store("g/r1", &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "r1"},
+ })
+
+ got := sr.IndexRules(&databasev1.Stream{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "foo"},
+ })
+
+ assert.Len(t, got, 2, "r1 must appear once per binding; the absent rule must be skipped")
+ for _, r := range got {
+ assert.Equal(t, "r1", r.GetMetadata().GetName())
+ }
+}
+
+// TestIndexRules_IgnoresBindingValidityWindow pins the current (unfiltered)
+// semantics. The registry-side helper in banyand/metadata/client.go DOES filter
+// begin_at/expire_at; matching that here would change production behavior and
+// turn every expired binding into a permanent false positive in the consistency
+// check.
+func TestIndexRules_IgnoresBindingValidityWindow(t *testing.T) {
+ sr := &schemaRepo{}
+ bindings := &sync.Map{}
+ bindings.Store("g/expired", &databasev1.IndexRuleBinding{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "expired"},
+ Subject: &databasev1.Subject{Name: "foo", Catalog: commonv1.Catalog_CATALOG_STREAM},
+ Rules: []string{"r1"},
+ // begin_at / expire_at left unset: an unset expire_at reads as "already
+ // expired" under the registry-side filter, yet must still be applied here.
+ })
+ sr.bindingForwardMap.Store("g/foo", bindings)
+ sr.indexRuleMap.Store("g/r1", &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "r1"},
+ })
+
+ got := sr.IndexRules(&databasev1.Stream{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "foo"},
+ })
+
+ assert.Len(t, got, 1, "cache-side derivation must not filter by the binding validity window")
+}
+
+// TestIndexRules_NoBindingsYieldsNil pins the empty case.
+func TestIndexRules_NoBindingsYieldsNil(t *testing.T) {
+ sr := &schemaRepo{}
+
+ got := sr.IndexRules(&databasev1.Stream{
+ Metadata: &commonv1.Metadata{Group: "g", Name: "foo"},
+ })
+
+ assert.Nil(t, got)
+}
+
+func TestLoadAllResources_FiltersByGroup(t *testing.T) {
+ sr := &schemaRepo{}
+ sr.resourceMap.Store("g1/a", &resourceSpec{
+ schema: &databasev1.Stream{Metadata: &commonv1.Metadata{Group: "g1", Name: "a"}},
+ })
+ sr.resourceMap.Store("g2/b", &resourceSpec{
+ schema: &databasev1.Stream{Metadata: &commonv1.Metadata{Group: "g2", Name: "b"}},
+ })
+
+ got := sr.LoadAllResources("g1")
+
+ assert.Len(t, got, 1)
+ assert.Equal(t, "a", got[0].Schema().GetMetadata().GetName())
+}
+
+// TestLoadAllResources_DoesNotMatchGroupPrefix guards against a naive prefix
+// match leaking "g1x/..." into group "g1".
+func TestLoadAllResources_DoesNotMatchGroupPrefix(t *testing.T) {
+ sr := &schemaRepo{}
+ sr.resourceMap.Store("g1/a", &resourceSpec{
+ schema: &databasev1.Stream{Metadata: &commonv1.Metadata{Group: "g1", Name: "a"}},
+ })
+ sr.resourceMap.Store("g1x/b", &resourceSpec{
+ schema: &databasev1.Stream{Metadata: &commonv1.Metadata{Group: "g1x", Name: "b"}},
+ })
+
+ got := sr.LoadAllResources("g1")
+
+ assert.Len(t, got, 1)
+ assert.Equal(t, "g1", got[0].Schema().GetMetadata().GetGroup())
+}
+
+func TestLoadAllIndexRules_FiltersByGroup(t *testing.T) {
+ sr := &schemaRepo{}
+ sr.indexRuleMap.Store("g1/r1", &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g1", Name: "r1"},
+ })
+ sr.indexRuleMap.Store("g2/r2", &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g2", Name: "r2"},
+ })
+
+ got := sr.LoadAllIndexRules("g1")
+
+ assert.Len(t, got, 1)
+ assert.Equal(t, "r1", got[0].GetMetadata().GetName())
+}
diff --git a/pkg/schema/schema.go b/pkg/schema/schema.go
index 05b738328..b95a089ea 100644
--- a/pkg/schema/schema.go
+++ b/pkg/schema/schema.go
@@ -115,6 +115,10 @@ type Repository interface {
LoadGroup(name string) (Group, bool)
LoadAllGroups() []Group
LoadResource(metadata *commonv1.Metadata) (Resource, bool)
+ LoadAllResources(group string) []Resource
+ LoadAllIndexRules(group string) []*databasev1.IndexRule
+ IndexRules(resourceSchema ResourceSchema) []*databasev1.IndexRule
+ LatestModRevision() int64
Close()
StopCh() <-chan struct{}
DropGroup(groupName string) error
diff --git a/pkg/schema/snapshot_state.go b/pkg/schema/snapshot_state.go
new file mode 100644
index 000000000..f82456598
--- /dev/null
+++ b/pkg/schema/snapshot_state.go
@@ -0,0 +1,194 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package schema
+
+import (
+ "fmt"
+
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/anypb"
+
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
+)
+
+// ResourceView is one resource's cache and runtime views. Runtime is nil when
+// the resource is not materialized.
+type ResourceView struct {
+ Cached proto.Message
+ Runtime proto.Message
+ Name string
+ RuntimeRules []*databasev1.IndexRule
+}
+
+// ResourceViewer extracts the snapshot views of a resource. It returns false
+// when the resource is not of the caller's catalog type. This is the only
+// catalog-specific part of snapshot collection: IndexListener exposes only
+// OnIndexUpdate, so reaching the runtime view needs a type assertion that only
+// the owning package can make.
+type ResourceViewer func(Resource) (ResourceView, bool)
+
+// CollectSchemaSnapshot returns a node's cache and runtime schema BODIES for
+// every object it holds in the group, as ObjectSnapshots. Unlike
+// CollectSchemaState it ships no fingerprints: the FODC agent hashes the bodies
+// on receive, keeping the hash algorithm and suppression policy out of the data
+// path.
+//
+// The same lock-free rationale as CollectSchemaState applies: the maps are read
+// without the write path's mutex, so a concurrent watch event can tear the read;
+// the agent's two-round suppression absorbs it. Callers that need a consistent
+// view snapshot the resource list under a read lock before calling.
+func CollectSchemaSnapshot(
+ repo Repository,
+ group, resourceKind string,
+ view ResourceViewer,
+) ([]*databasev1.ObjectSnapshot, []*databasev1.IndexRule, error) {
+ tb := newRuleTable()
+ var objects []*databasev1.ObjectSnapshot
+ if g, ok := repo.LoadGroup(group); ok {
+ if gs := g.GetSchema(); gs != nil {
+ obj, err := selfConsistentSnapshot(tb, group, schema.KindGroup.String(), group, gs)
+ if err != nil {
+ return nil, nil, err
+ }
+ objects = append(objects, obj)
+ }
+ }
+ for _, rule := range repo.LoadAllIndexRules(group) {
+ obj, err := selfConsistentSnapshot(tb, group, schema.KindIndexRule.String(), rule.GetMetadata().GetName(), rule)
+ if err != nil {
+ return nil, nil, err
+ }
+ objects = append(objects, obj)
+ }
+ for _, res := range repo.LoadAllResources(group) {
+ v, ok := view(res)
+ if !ok {
+ continue
+ }
+ cache, err := newSchemaBody(tb, v.Cached, repo.IndexRules(res.Schema()))
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to build cache body for %s %q: %w", resourceKind, v.Name, err)
+ }
+ obj := &databasev1.ObjectSnapshot{
+ Group: group,
+ Kind: resourceKind,
+ Name: v.Name,
+ Cache: cache,
+ }
+ if v.Runtime != nil {
+ runtime, runtimeErr := newSchemaBody(tb, v.Runtime, v.RuntimeRules)
+ if runtimeErr != nil {
+ return nil, nil, fmt.Errorf("failed to build runtime body for %s %q: %w", resourceKind, v.Name, runtimeErr)
+ }
+ obj.Runtime = runtime
+ }
+ objects = append(objects, obj)
+ }
+ return objects, tb.rules, nil
+}
+
+// ruleTable interns index-rule bodies for wire deduplication only (never for
+// consistency matching -- the checker keys objects by kind+name). The key is the
+// deterministic marshal of the WHOLE rule, i.e. its exact content.
+//
+// Do NOT key this by rule name or id. A rule's cache body (current) and its
+// runtime body (possibly a stale copy) share the same name and id but differ in
+// content; that difference is exactly the RUNTIME_NOT_APPLIED signal. A
+// content key keeps the two in separate entries so cacheFP != runtimeFP still
+// fires; a name/id key would merge them, the runtime ref would resolve to the
+// cache body, and the drift would be silently masked. Deterministic marshal
+// guarantees "same content -> same key", so identical rules always dedup and
+// differing rules never collide -- a miss only ever wastes a table slot, it
+// cannot misroute a ref. See TestRuleTable_InternKeepsDivergentBodiesDistinct.
+type ruleTable struct {
+ index map[string]uint32
+ rules []*databasev1.IndexRule
+}
+
+func newRuleTable() *ruleTable {
+ return &ruleTable{index: make(map[string]uint32)}
+}
+
+// intern returns the table indexes of the given rules, appending any not yet
+// seen. Order is preserved so the agent's derived rule set matches the node's.
+// The key must stay content-based (see ruleTable): never switch it to name/id.
+func (t *ruleTable) intern(rules []*databasev1.IndexRule) ([]uint32, error) {
+ if len(rules) == 0 {
+ return nil, nil
+ }
+ refs := make([]uint32, 0, len(rules))
+ for _, rule := range rules {
+ key, err := proto.MarshalOptions{Deterministic: true}.Marshal(rule)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal index rule %q for interning: %w", rule.GetMetadata().GetName(), err)
+ }
+ idx, ok := t.index[string(key)]
+ if !ok {
+ idx = uint32(len(t.rules))
+ t.rules = append(t.rules, rule)
+ t.index[string(key)] = idx
+ }
+ refs = append(refs, idx)
+ }
+ return refs, nil
+}
+
+// CachedGroupNames lists the names of every group the repository currently
+// caches, so an all-groups snapshot request can enumerate without a roster.
+func CachedGroupNames(repo Repository) []string {
+ groups := repo.LoadAllGroups()
+ names := make([]string, 0, len(groups))
+ for _, g := range groups {
+ if gs := g.GetSchema(); gs != nil {
+ names = append(names, gs.GetMetadata().GetName())
+ }
+ }
+ return names
+}
+
+// selfConsistentSnapshot builds a snapshot for an object with no derived
+// structure (group, indexRule): its cache and runtime bodies are the same, so
+// runtime is left unset and the agent takes the runtime fingerprint from cache.
+func selfConsistentSnapshot(tb *ruleTable, group, kind, name string, spec proto.Message) (*databasev1.ObjectSnapshot, error) {
+ cache, err := newSchemaBody(tb, spec, nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to build body for %s %q: %w", kind, name, err)
+ }
+ return &databasev1.ObjectSnapshot{
+ Group: group,
+ Kind: kind,
+ Name: name,
+ Cache: cache,
+ }, nil
+}
+
+// newSchemaBody wraps a schema proto as an Any and interns its bound index rules
+// into tb, storing only the resulting table refs. FODC needs no per-type
+// knowledge, so a single Any replaces the former per-catalog oneof.
+func newSchemaBody(tb *ruleTable, payload proto.Message, boundRules []*databasev1.IndexRule) (*databasev1.SchemaBody, error) {
+ body, err := anypb.New(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to wrap schema body of type %T: %w", payload, err)
+ }
+ refs, err := tb.intern(boundRules)
+ if err != nil {
+ return nil, err
+ }
+ return &databasev1.SchemaBody{Payload: body, BoundIndexRuleRefs: refs}, nil
+}
diff --git a/pkg/schema/snapshot_state_internal_test.go b/pkg/schema/snapshot_state_internal_test.go
new file mode 100644
index 000000000..62b2cddb0
--- /dev/null
+++ b/pkg/schema/snapshot_state_internal_test.go
@@ -0,0 +1,81 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package schema
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+)
+
+func indexRuleFixture(name string, tags ...string) *databasev1.IndexRule {
+ return &databasev1.IndexRule{
+ Metadata: &commonv1.Metadata{Group: "g", Name: name},
+ Tags: tags,
+ }
+}
+
+func TestRuleTable_InternDedupsIdenticalContent(t *testing.T) {
+ tb := newRuleTable()
+
+ // Two resources bind the same pair of rules -- distinct proto objects with
+ // identical content. Each body must be stored once, so the second resource's
+ // refs reuse the first's indexes.
+ first, err := tb.intern([]*databasev1.IndexRule{indexRuleFixture("r1", "a"), indexRuleFixture("r2", "b")})
+ require.NoError(t, err)
+ second, err := tb.intern([]*databasev1.IndexRule{indexRuleFixture("r1", "a"), indexRuleFixture("r2", "b")})
+ require.NoError(t, err)
+
+ assert.Equal(t, []uint32{0, 1}, first)
+ assert.Equal(t, []uint32{0, 1}, second, "identical bodies resolve to the already-stored indexes")
+ assert.Len(t, tb.rules, 2, "each distinct body is stored once regardless of how many resources bind it")
+}
+
+func TestRuleTable_InternKeepsDivergentBodiesDistinct(t *testing.T) {
+ tb := newRuleTable()
+
+ // The cache holds the new rule body; a resource's runtime layer still holds
+ // the stale one under the same name. They differ in content, so they must
+ // occupy distinct entries -- otherwise the agent's cache-vs-runtime
+ // fingerprint comparison could never surface RUNTIME_NOT_APPLIED.
+ cacheRefs, err := tb.intern([]*databasev1.IndexRule{indexRuleFixture("r1", "new")})
+ require.NoError(t, err)
+ runtimeRefs, err := tb.intern([]*databasev1.IndexRule{indexRuleFixture("r1", "stale")})
+ require.NoError(t, err)
+
+ assert.NotEqual(t, cacheRefs, runtimeRefs, "a stale runtime body must not collapse onto its cache counterpart")
+ assert.Len(t, tb.rules, 2)
+}
+
+func TestRuleTable_InternPreservesOrderAndHandlesEmpty(t *testing.T) {
+ tb := newRuleTable()
+
+ empty, err := tb.intern(nil)
+ require.NoError(t, err)
+ assert.Nil(t, empty, "an empty rule set yields no refs")
+
+ refs, err := tb.intern([]*databasev1.IndexRule{
+ indexRuleFixture("r2", "b"), indexRuleFixture("r1", "a"), indexRuleFixture("r2", "b"),
+ })
+ require.NoError(t, err)
+ assert.Equal(t, []uint32{0, 1, 0}, refs, "refs follow input order and reuse the first index for repeats")
+}
diff --git a/test/e2e-v2/cases/fodc/banyandb-cluster.yaml b/test/e2e-v2/cases/fodc/banyandb-cluster.yaml
index 8c6e2f983..9650dba45 100644
--- a/test/e2e-v2/cases/fodc/banyandb-cluster.yaml
+++ b/test/e2e-v2/cases/fodc/banyandb-cluster.yaml
@@ -137,6 +137,7 @@ spec:
- --prometheus-listen-addr=:9090
- --heartbeat-interval=5s
- --pod-name=$(POD_NAME)
+ - --lifecycle-port=17912
env:
- name: POD_NAME
valueFrom:
@@ -219,6 +220,8 @@ spec:
- --prometheus-listen-addr=:9090
- --heartbeat-interval=5s
- --pod-name=$(POD_NAME)
+ - --lifecycle-port=18912
+ - --schema-registry-port=17912
env:
- name: POD_NAME
valueFrom:
diff --git a/test/e2e-v2/cases/fodc/check-schema-consistency.sh b/test/e2e-v2/cases/fodc/check-schema-consistency.sh
new file mode 100755
index 000000000..7f14f7b4d
--- /dev/null
+++ b/test/e2e-v2/cases/fodc/check-schema-consistency.sh
@@ -0,0 +1,115 @@
+#!/usr/bin/env bash
+
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# check-schema-consistency.sh asserts that a HEALTHY cluster reports no schema
+# inconsistency. This is the steady-state guard for the schema consistency
+# checker: on this cluster the registry, every node's cache and every node's
+# runtime genuinely agree, so any INCONSISTENT verdict here is a false positive
+# in the checker itself -- exactly the regression class that unit tests, which
+# feed hand-built fingerprints, cannot catch.
+#
+# It also gives /cluster/lifecycle its first e2e coverage.
+#
+# The skywalking-infra-e2e verify retry loop drives the waiting: this script
+# does ONE fetch and exits. The single status line on STDOUT is matched against
+# expected/schema-consistency.yml; all diagnostics go to STDERR.
+#
+# UNKNOWN is tolerated: a group whose divergence has not yet survived the
+# checker's consecutive-cycle suppression, or whose nodes have not all answered
+# yet, is still converging and is not a failure.
+
+set -euo pipefail
+
+NAMESPACE="${NAMESPACE:-default}"
+PROXY_DEPLOY="${PROXY_DEPLOY:-deployment/fodc-proxy}"
+PROXY_CONTAINER="${PROXY_CONTAINER:-fodc-proxy}"
+PROXY_LIFECYCLE_URL="${PROXY_LIFECYCLE_URL:-http://127.0.0.1:17913/cluster/lifecycle}"
+STATUS_KEY="fodc_schema_consistency_status"
+
+RESPONSE_FILE="$(mktemp)"
+trap 'rm -f "${RESPONSE_FILE}"' EXIT
+
+log() { echo "$@" >&2; }
+kx() { kubectl -n "${NAMESPACE}" "$@"; }
+emit() { echo "${STATUS_KEY}: $1"; }
+
+fail() {
+ log "FAIL: $*"
+ log "---- /cluster/lifecycle response ----"
+ cat "${RESPONSE_FILE}" >&2 || true
+ emit "FAIL"
+ exit 1
+}
+
+kx exec "${PROXY_DEPLOY}" -c "${PROXY_CONTAINER}" -- \
+ wget -qO- "${PROXY_LIFECYCLE_URL}" > "${RESPONSE_FILE}" 2>/dev/null || true
+
+[ -s "${RESPONSE_FILE}" ] || fail "empty response from ${PROXY_LIFECYCLE_URL}"
+
+# Field names are proto names: the proxy marshals groups with
+# protojson.MarshalOptions{UseProtoNames: true}, so the key is
+# schema_consistency (snake_case), never schemaConsistency. Enum values are
+# emitted as their full name strings. fodc/proxy/internal/api's
+# TestLifecycleGroupsJSONContract pins both, so this script cannot silently rot.
+count_status() {
+ jq -r --arg s "$1" \
+ '[.groups[]? | select(.schema_consistency.status == $s)] | length' "${RESPONSE_FILE}"
+}
+
+# A group whose verdict is absent means the check never ran for it -- a wiring
+# failure, not a healthy cluster.
+CHECKED="$(jq -r '[.groups[]? | select(.schema_consistency != null)] | length' "${RESPONSE_FILE}")"
+[ "${CHECKED}" != "0" ] || fail "no group carried a schema consistency verdict; the check never ran"
+
+CONSISTENT="$(count_status CONSISTENCY_STATUS_CONSISTENT)"
+INCONSISTENT="$(count_status CONSISTENCY_STATUS_INCONSISTENT)"
+UNKNOWN="$(count_status CONSISTENCY_STATUS_UNKNOWN)"
+UNSPECIFIED="$(count_status CONSISTENCY_STATUS_UNSPECIFIED)"
+
+# Every verdict must fall into one of the four known statuses. A shortfall means
+# the status strings this script matches on no longer match what the proxy emits,
+# which would otherwise make the INCONSISTENT check vacuously pass forever.
+BUCKETED=$((CONSISTENT + INCONSISTENT + UNKNOWN + UNSPECIFIED))
+if [ "${BUCKETED}" != "${CHECKED}" ]; then
+ jq '[.groups[]? | select(.schema_consistency != null)
+ | {name, status: .schema_consistency.status}]' "${RESPONSE_FILE}" >&2 || true
+ fail "only ${BUCKETED}/${CHECKED} verdicts matched a known status string; the enum contract drifted"
+fi
+
+if [ "${INCONSISTENT}" != "0" ]; then
+ log "${INCONSISTENT} group(s) reported schema inconsistency on a healthy cluster:"
+ jq '.groups[]? | select(.schema_consistency.status == "CONSISTENCY_STATUS_INCONSISTENT")
+ | {name, issues: .schema_consistency.issues}' "${RESPONSE_FILE}" >&2 || true
+ fail "schema consistency check produced false positives"
+fi
+
+# Without this, a cluster where every group is stuck at UNKNOWN (nodes never
+# answering, roster mismatch, suppression never clearing) would pass: it has
+# verdicts and zero INCONSISTENT, yet the checker concluded nothing at all.
+if [ "${CONSISTENT}" = "0" ]; then
+ jq '[.groups[]? | select(.schema_consistency != null)
+ | {name, status: .schema_consistency.status}]' "${RESPONSE_FILE}" >&2 || true
+ fail "no group reached CONSISTENT (${UNKNOWN} UNKNOWN, ${UNSPECIFIED} UNSPECIFIED); the checker never concluded"
+fi
+
+log "Schema consistency verified."
+log " groups with a verdict : ${CHECKED}"
+log " CONSISTENT : ${CONSISTENT}"
+log " INCONSISTENT : ${INCONSISTENT}"
+log " UNKNOWN : ${UNKNOWN}"
+emit "PASS"
+exit 0
diff --git a/test/e2e-v2/cases/fodc/e2e.yaml b/test/e2e-v2/cases/fodc/e2e.yaml
index 405921a4a..272ce5f46 100644
--- a/test/e2e-v2/cases/fodc/e2e.yaml
+++ b/test/e2e-v2/cases/fodc/e2e.yaml
@@ -112,6 +112,11 @@ verify:
# 2) Asserts the FODC dashboard metrics on the fodc-proxy /metrics endpoint.
- query: bash test/e2e-v2/cases/fodc/check-metrics.sh
expected: expected/metrics-status.yml
+ # 3) Steady-state guard for the schema consistency checker: this cluster is
+ # healthy, so any INCONSISTENT verdict on /cluster/lifecycle is a false
+ # positive in the checker -- a class of bug unit tests cannot surface.
+ - query: bash test/e2e-v2/cases/fodc/check-schema-consistency.sh
+ expected: expected/schema-consistency.yml
cleanup:
on: always
diff --git a/test/e2e-v2/cases/fodc/expected/schema-consistency.yml b/test/e2e-v2/cases/fodc/expected/schema-consistency.yml
new file mode 100644
index 000000000..43cdad6bc
--- /dev/null
+++ b/test/e2e-v2/cases/fodc/expected/schema-consistency.yml
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+fodc_schema_consistency_status: PASS
diff --git a/test/e2e-v2/cases/fodc/metrics/documented_gap.txt b/test/e2e-v2/cases/fodc/metrics/documented_gap.txt
index f8b81b2ad..f4bea13b3 100644
--- a/test/e2e-v2/cases/fodc/metrics/documented_gap.txt
+++ b/test/e2e-v2/cases/fodc/metrics/documented_gap.txt
@@ -49,3 +49,9 @@ banyandb_lifecycle_migration_total_batch_latency_bucket
banyandb_lifecycle_migration_total_err
banyandb_lifecycle_migration_total_finished
banyandb_lifecycle_migration_total_latency_bucket
+#
+# Group 4 -- schema consistency verdict. The proxy exports one gauge per group
+# only after a /cluster/lifecycle collection has populated its verdict cache;
+# check-metrics.sh runs before check-schema-consistency.sh triggers that
+# collection, so the metric may be absent during the metrics window.
+banyandb_fodc_schema_consistency_status
diff --git a/test/e2e-v2/cases/fodc/metrics/presence.txt b/test/e2e-v2/cases/fodc/metrics/presence.txt
index be535780a..b7bf5dce3 100644
--- a/test/e2e-v2/cases/fodc/metrics/presence.txt
+++ b/test/e2e-v2/cases/fodc/metrics/presence.txt
@@ -19,7 +19,7 @@
# always-positive core lives in non_empty.txt; metrics that need a specific
# event to materialise (error counters, completed part-merges) live in
# documented_gap.txt. The three lists are disjoint and their union is exactly
-# the 77 distinct names referenced by the FODC Grafana dashboards.
+# the 78 distinct names referenced by the FODC Grafana dashboards.
#
# Calibrated against a live run: OAP writes the BanyanDB trace model, so the
# banyandb_trace_tst_* family is present; stream_storage_* and stream_tst_* are