Skip to content

Observability

A node reports what it does through three channels. All three stay on the standard library. Logs go through log/slog, with one key convention across the module. Metrics go through a port the host implements, node.Metrics, which reports a named set of counters and gauges. The diagnostic trace is a bounded ring of the moments that explain a failed pairing or a lost session. The module adds no metrics or tracing library to the host's dependencies (ADR 0025 principle 12).

The logger

node.Config.Logger is the node's *slog.Logger. The node hands it to every component it builds: the bridge, the transports, the session and subscription tables, the cluster servers, the client stack. A nil logger is slog.Default(). The same rule holds for every component that takes a logger of its own: bridge.New, transport/udp.Config, the client/* packages (handshake, exchange, interaction, peer) and the controller. The module never builds a handler. Only the executables under examples/ do, so the host chooses the format, the level and where the lines go (ADR 0026 principle 9).

fabrictest is the exception, on purpose. A test site discards its hosts' logs unless the test hands it a logger (fabrictest.Options.Logger), so a passing test prints nothing.

A host that shows recent log lines in its own UI wraps its handler in a logring.Handler: slog.New(logring.New(inner, logring.Options{})) is the logger it hands to node.Config.Logger. The module still builds no handler; the host does. The handler forwards each record to inner and keeps the newest Options.Size records (1000 by default) in memory. Handler.Records(since, limit) returns them oldest first, each with a sequence number that starts at 1 and never repeats, its attributes resolved and groups flattened as group.key. Handler.Observe delivers each new record to a callback on a goroutine of its own. A callback that falls behind loses the oldest queued records, and Handler.Dropped counts them; the logger never waits for it. Handler.SetLevel moves the ring's level gate at run time: a record below it is neither kept nor forwarded, while inner's own level still decides what inner prints. The UI reads the ring through a port of the host's own; the ring applies no redaction of its own: the module logs no passcodes and no keys, and a value the Matter model marks secret (an ICD client key, a group epoch key, …) is logged as "(redacted)" by the read and subscription priming report logs, always — there is no switch to turn it off (cluster/spec.Redact; notes/parity/by_design.md BD-Matter-SecretRedaction-NoOffSwitch).

Event names

A log message is an event name in dotted lower case, area.event. The attributes say which session, endpoint or peer the event concerns. A host that filters by area matches the prefix:

Prefix Area
matter.rx.*, matter.tx.* the device side's receive and send paths (secure channel, Interaction Model)
matter.bridge.*, matter.subscription.*, matter.subscribe.*, matter.groups.*, matter.case.*, matter.session.* the bridge: topology, subscriptions, group messaging, the CASE initiator
matter.udp.*, matter.tcp.*, matter.btp.*, matter.exchange.* the transports
matter.mdns.*, matter.discovery.* DNS-SD: the advertiser and the browser
matter.controller.*, matter.ble.* the client machinery and the controller role
matter.<cluster>.* (matter.opcreds, matter.gencomm, matter.basic_information, matter.thermostat, …) one cluster server
matter.ota.*, ota.* the OTA requestor and provider
case.*, pase.*, commissioning.*, binding.*, node.*, groups.*, mdns.*, label, scenes, gendiag.*, diaglogs.*, bdx.* the facade's own wiring (node) and its helpers
dcl.* the Distributed Compliance Ledger client
tlv.*, device.* the codec and the device kit

The names are stable within a release line. A renamed event appears in the CHANGELOG, the same as an API change.

Attribute keys

Each value is a typed attribute (slog.Int, slog.Uint64, slog.Any for an error), never a number formatted into a string. One thing has one key in every package, so a query for session_id=7 finds the session wherever it is logged. Each row below names a value's type and meaning:

Key Value Meaning
fabric_index slog.Int the fabric's index on this node (1–254); not the fabric id, which is fabric_id
node_id slog.Uint64 an operational node id: the peer's, a subject's, a binding target's
endpoint slog.Int (slog.Any for a path's optional endpoint) an endpoint number
cluster slog.Uint64 (slog.Any for a path's optional cluster; slog.String for a name) a cluster id
attribute slog.Uint64 (slog.Any for a path's optional attribute; slog.String for a name) an attribute id
session_id slog.Int a secure session's local id
exchange_id slog.Int an exchange id
subscription_id slog.Uint64 (slog.Int where the id is held as an int) a subscription id
from_session_id slog.Int the local id of a superseded session whose subscriptions moved
to_session_id slog.Int the local id of the newer session the subscriptions moved to
subscription_count slog.Int how many subscriptions an operation touched
group_id slog.Int a group id
peer slog.String the network address of the node at the other end — of a session, an exchange, a handshake, a commissioning attempt
src slog.String the source address of one received datagram — what the socket saw, which a peer's later datagrams may not share
err slog.Any the error value; never its text (slog.String("err", err.Error()) is refused)
device slog.String the host's device key — the reference daemon's, in examples/ only; the module itself has no device key
reason slog.String why the event happened: a refusal's cause, a close's trigger
status slog.String (a status name), slog.Int (a code); slog.Bool for whether a report entry is a status a Matter status (Interaction Model, secure channel)

The keys one area uses for what only it logs, accepted as they stand:

accept_test, accepted_findings, ack_counter, action, active_preset_handle, additional_mrp_delay, address, address_index, addresses, adjusted, admin_vendor_id, advertised_ms, after, age, akid, also_named_by, att_mtu, attempt, attested_product_id, attested_vendor_id, attribute_reports, attribute_set, attribute_statuses, attributes, authorities, auxiliary_acl, backoff, boot_reason, bridged_endpoints, budget, built_at, by, bytes, camera, candidate, case_admin_subject, category, ceiling, changed, channel, check, chunk, chunks, cleared, client_node_id, client_type, closed, cluster_set, code, color_mode, command, command_name, concurrent, configured_ms, conn, connect_error, connected, consecutive_errors, context, count, counter, counter_start, country, current, datagram_bytes, debug, delay, detail, device_type, discovery, discriminator, dropped, duplicate, encrypted, endpoint_set, endpoints, entries, event, event_paths, event_reports, events, examined, exchanges, expected, fabric_filtered, fabric_id, fallback, family, feature_flags, features, field, file, final, floor, force, former, formerly, fragment_size, from, general_code, github, go_type, grace, hint, holds, hook, host, icac_bytes, ideal, ids, iface, ignored, in, incoming, initial_events, initial_reports, instance, instead_of, interval, invoke_fabric_index, invokes, ipk_len, ipv4, ipv6, iterations, key, key_set, keys, kind, label, last_counter, last_offset, left, listen, location, lockout, manual_code, max, max_attempts, max_bytes, max_errors, max_interval, measurement_seen, message, message_bytes, min, min_interval, missing, monitored_subject, more, name, network_name, networking_status, new, next_check_in, next_query, noc_bytes, noc_subject_fabric_id, noc_subject_node_id, node, nodes, note, notifier_ok, offered, offline, op, opcode, origin, original_bytes, ota, outgoing, panic, parent, part, partition_id, passcode, path, path_index, paths, payload_bytes, pending_key, policy, port, preset_handle, previous, product_id, production, profile, protocol_code, protocol_id, provider, proxy, qr_code, queued, reachable, rearm_for, recovered, recovered_total, reestablished, registered, reported, reports, req_paths, request_id, requirement, resp, responder, response_type, responses, result, resumed, retained, retransmission, retry, retry_in, retry_limit, role, rssi, running, schedule_handle, scope, send_failures, send_interval, served, served_as, service, sessions, silent, since_last_restart, skid, source, source_endpoint, source_node_id, ssid, stack, stage, state, status_code, status_name, statuses, step, stored, stored_fabrics, stream_id, subject, subsystem, superseded, supported, suppress_response, suppressed_since_last, sw_version, system_mode, target, targets, tcp, test, timed, timeout, timeout_ms, to, token, took, total, total_endpoints, track, transport, trimmed_bytes, type, undecodable, uri_node, url, valid, valid_mapping, value, value_type, vendor_id, vendors, version, violation, webrtc_session_id, what, with_paths, within.

Four of the area keys are easy to mistake for core keys. address is an address that is not the peer's own: a multicast group, a BLE advertiser, one dial attempt's address beside the logger's peer, or the host's device address. listen is a local socket. node is a client node's registry id in the controller, not a node id. from and to are the two sides of a change: a version or an address list.

The guard script/slogkeys holds the tree to this table. It checks every slog.<Type>("<key>", …) in library code (not tests, not examples/, not package main). It fails on a key outside the table, on an err that is not slog.Any, and on a key that one call states twice. A new key is a row in the guard's table in the same commit, and the section above is regenerated from that table.

Metrics

node.Config.Metrics takes a node.Metrics, an alias of contract.Metrics, so an implementation imports contract only:

type Metrics interface {
    Counter(name string, delta int64)
    Gauge(name string, value int64)
}

A nil port records nothing. The cost is one nil check at each site. The calls arrive on the goroutine that observed the event, such as the receive path, a timer or the MRP pump. An implementation must therefore be safe for concurrent use and must not block. The names carry no attributes in this release. A per-fabric or per-peer split is a later decision. A host that needs one today can derive it from the logs.

Name (node.Metric…) Kind One unit Fed from
sessions.open (MetricSessionsOpen) gauge an entry of the secure-session table (PASE and CASE) set from the table's count when a responder handshake establishes a session (bridge/conn.go, bindEstablishedSession), when the CASE initiator does (bridge/case_initiator.go), and when a session closes (Bridge.SessionClosed)
subscriptions.active (MetricSubscriptionsActive) gauge a subscription the node serves set from the subscription table when one is established (bridge/subscribe_dispatch.go), restored after a restart (bridge/subscription_reestablish.go) or closed (the manager's close hook, bridge/subscribe.go); a host that reacts to the count watches this gauge on its port instead of polling Node.Subscriptions().Active()
im.received (MetricIMReceived) counter an Interaction Model message received beside DeviceLoadStatus' TotalInteractionModelMessagesReceived (bridge/receive.go, handleIMOpcode)
im.sent (MetricIMSent) counter an Interaction Model message sent beside TotalInteractionModelMessagesSent (bridge/reply.go, bridge/subscribe.go)
pase.failures (MetricPASEFailures) counter a failed PASE pairing attempt, not a retransmitted step; a fail-safe that ends without commissioning is a failed attempt too but does not move it Bridge.recordFailedAttempt (bridge/securechannel.go)
pase.lockouts (MetricPASELockouts) counter a PASE lockout engaged at the failure cap (20); the commissioning window closes with it the same function, where the lockout engages
aggregator.reassemblies (MetricAggregatorReassemblies) counter a completed reassembly of the bridged-device topology node/aggregator.go (reassemble)
mrp.retransmits (MetricMRPRetransmits) counter a reliable message sent again the device side's MRP pump (bridge/ackpump.go) and the node's client exchanges (client/exchange.Config.Retransmitted)
panics.recovered (MetricPanicsRecovered) counter a panic recovered on a datagram or connection path; the message was dropped (a panic in a TCP connection's reader closes that connection) the UDP and TCP listeners' OnPanicRecovered hook (transport/udp, transport/tcp), on the bridge's and the client's sockets

Every counter the module kept before keeps its reader: Bridge.DeviceLoad serves GeneralDiagnostics, the listeners' RecoveredPanics() still count, and the PASE lockout still works from its own counter. The port is a second reader.

expvar

node/metrics/expvar implements the port on the standard library's expvar. Each name is an expvar.Int under a prefix:

cfg.Metrics = expvarmetrics.New("fabric.")
// net/http's /debug/vars now shows fabric.sessions.open, fabric.im.received, …

New publishes the whole set at zero, so a dashboard sees every name before the first event.

The standard library's /debug/vars handler has no authentication and publishes more than these names: its built-in cmdline variable is os.Args. A daemon that takes a secret as a flag — a setup passcode, a Wi-Fi passphrase — hands it to every client of that handler. Serve the variables you mean to serve instead. The reference bridge does: its --metrics-expvar 127.0.0.1:9090 serves the fabric. variables only, in the same JSON shape (metrics.go), and belongs on a loopback address.

The diagnostic trace

The node keeps a bounded, in-memory ring of node.DiagnosticEvent entries. Each one is a moment an operator needs when a pairing fails or a controller goes quiet: a handshake completed, a session closed, a lockout engaged, the node re-announced itself. The oldest entry is dropped first. Nothing is persisted, because the logs are the durable record. The same trace answers GeneralDiagnostics' DiagnosticLogs RetrieveLogs.

Facade What it does
Config.Diagnostics{Capacity} the number of events kept; 0 is 256 (node.DefaultDiagnosticsCapacity)
Node.DiagnosticEvents() the trace, newest first, as a copy
Node.OnDiagnosticEvent(fn) fn runs inline for each event recorded from now on, on the recording goroutine (the receive path) and outside the ring's lock. It must not block, and it may read the trace. Returns the unsubscribe function.
Node.OnDiagnosticEventAsync(fn) fn is queued on the node's callback goroutine and runs one call after the other while the node runs. Stop returns once every queued call ran. An event recorded while the node does not run is not delivered.

The two observers follow the callback rule the device kit's OnChanged/OnChangedAsync follow.

The controller's diagnostics

A controller.Controller serves the same shapes as the node, from package diag (the node's SessionDiagnostics, SessionInfo, Occupancy and Diagnostics are aliases of them), so one page model renders either role.

Snapshot. Controller.SessionDiagnostics() returns a diag.SessionDiagnostics: every session of every peer flat in Sessions (with CreatedAt, Resumed, Transport and PeerLost, which the node leaves zero), and one diag.PeerInfo per peer in Peers — whether a commissioned client node has its address, the node's connection state (Connected, Disconnected, Reconnecting, WaitingForDeviceDiscovery), how long its connection process has been trying, its operational address and the SRV host that owns it, whether its DNS-SD service is believed reachable and which of its operational names the cache holds, its last and next ICD Check-In, whether its default subscription is active, and the ids of its sessions. Occupancy stays zero with Capacity 0: the controller's exchange manager keeps no id-occupancy figure. A session's Subscriptions is 0 and LastActivity zero, because the controller keeps its subscriptions by peer and its sessions export no any-direction timestamp. The snapshot holds no lock across the peers.

Trace. Config.Diagnostics{Capacity} sizes the controller's ring (0 is 256). Controller.DiagnosticEvents() returns it newest first; Controller.OnDiagnosticEvent(fn) runs fn inline on the recording goroutine — the receive path, a peer's worker, the DNS-SD cache's goroutine — so fn must not block and must not call SessionDiagnostics or DiagnoseMDNS, which wait for that cache. There is no async variant: the controller keeps no ordered callback queue. The kinds and an example of each:

Kind What it records Example
pairing a Pair's start, each failed step (a warning: one discovery transport of a race may fail while another wins), the paired node, or the failed pairing (error) when Pair returns an error "Pairing failed at step OperationalCredentials.DeviceAttestation: …"
session a session established, closed or lost (warning), a CASE establishment unanswered within the MRP budget (warning), a client node's connection-state transition (Reconnecting and WaitingForDeviceDiscovery as warnings) "The secure session with node 5C50D14E724B52F1 was lost; the controller reconnects."
discovery a node of our fabric whose operational record appears in or disappears from the DNS-SD cache; a Thread border router added to or removed from the registry "Node 5C50D14E724B52F1's operational record appeared."
reachability a reachability probe run's verdict: answered on its address or an alternate, or given up (warning) "Node 5C50D14E724B52F1 answered no session-suspect probe; the session is given up."
icd an accepted ICD Check-In, a missed one (warning) "Node 5C50D14E724B52F1 checked in (counter 12)."
ota a status of a node's software update; Cancelled as a warning "Node 5C50D14E724B52F1's software update is Downloading (version 2)."
camera a WebRTC signal the controller's requestor refused (a node's command for a session it does not hold, answered NOT_FOUND); Offer and Answer as warnings "The controller refused node 5C50D14E724B52F1's WebRTC answer for session 3: no such session."

The host's own hooks — PairOptions.Progress, Config.HooksFor, OTAConfig.OnStatus, Controller.OnCameraSignal — still run, after the trace recorded the event.

Findings. Controller.DiagnoseMDNS() returns []mdns.Finding: mdns.Diagnose of the records the controller advertises (without the node's no_commissionable_service), and no_operational_names (warning) when a commissioned node waits for device discovery and the DNS-SD cache holds none of the commissioned nodes' operational records — the browse gets no answer on this network. The controller has no interface allow-list, so mdns.DiagnoseInterfaces is not called. Errors come first.

Metrics. Config.Metrics takes the same contract.Metrics port; nil records nothing.

Name (controller.Metric…) Kind One unit Fed from
sessions.open (MetricSessionsOpen) gauge a secure session of one of the controller's peers taken from the peers' sessions when one is established or leaves its peer and when a closed peer leaves the set (its sessions go without a deletion event), and set to 0 at the end of Controller.Close (controller/diagnostics.go, controller/metrics.go)
mrp.retransmits (MetricMRPRetransmits) counter a reliable message the controller's exchanges sent again client/exchange.Config.Retransmitted
pair.failures (MetricPairFailures) counter a failed pairing: a Pair or PairDiscovered that returned an error; a step that failed inside a pairing that went on is not counted Controller.Pair, Controller.PairDiscovered
case.unresponsive (MetricCASEUnresponsive) counter a CASE establishment unanswered past its MRP budget the peer observer's EstablishmentUnresponsive
reachability.probes (MetricReachabilityProbes) counter a reachability probe run, whatever its verdict the peer observer's ReachabilityVerified
icd.checkins_missed (MetricICDCheckInsMissed) counter an ICD Check-In expected from a registered LIT peer and not received client.ICDClient.OnCheckInMissed

subscriptions.active is not fed by the controller: its subscription registry signals no change a gauge could follow.

Attribute changes

node.Observers.OnAttributeChanged hears every attribute change a cluster server reports, on any endpoint: node.AttributeChange{Endpoint, Cluster, Change}, where Change is the contract.Change the server reported — the attribute ids and the origin (OriginControllerWrite for a controller's write, OriginCommand, OriginHostSet, OriginUnknown). It runs after the subscriptions marked the attributes for their next report, inline on the change's goroutine through Config.Observers or Node.Observe, or queued on the node's callback goroutine through Node.ObserveAsync. It carries no value: a device's typed OnChanged and a server's Get are the value route. It hears the servers that notify their own changes (every generated server among them); a host port that only signals contract.ChangeNotifier is the host's own and is not repeated. matter.js has the same node-wide path beside its per-behavior $Changed events: ChangeNotificationService.change reports each state update with the endpoint, the behavior, the data version and the property names, no values (ChangeNotificationService.ts:79-94). This hook is its counterpart, so a UI that shows every change reads it.

Served values and events

A host reads what its node serves through the facade, below no seam:

Facade What it does
Node.ReadAttribute(ctx, endpoint, cluster, attribute) one attribute as a controller's read reaches it — the cluster server's MatterRead through the node's dispatcher — as node.AttributeValue{Endpoint, Cluster, Attribute, Value, DataVersion}. No access control and no accessing fabric: it reads as matter.js's local actor, so a fabric-scoped list holds every fabric's entries whole, their fabric-sensitive fields included; a host that shows a value to a less trusted viewer withholds what that viewer may not see. An unserved path is a contract.StatusError with the status a controller receives; before Start, node.ErrNotStarted.
Node.ReadCluster(ctx, endpoint, cluster) every attribute of one cluster, the globals among them, in a wildcard read's order — one whose read fails among them, with the IM status the wildcard read reports for its path in AttributeValue.Status and no value (0 is success).
AttributeValue.JSON() the value by name, rendered by the decoder behind the controller side's client.DecodeJSON (NameBased) from the bytes the node sends, so the node and a controller render a value alike.
Node.Events(node.EventQuery{Endpoint, Cluster, Event, MinNumber, Limit}) the node's event log — the records a controller's event read is answered from — oldest first; nil path fields match every one, MinNumber is inclusive, a positive Limit keeps the newest. The log is bounded and emptied when the node stops.
Event.JSON() the event's payload by name, as AttributeValue.JSON.

node.Observers.OnEvent reports each new event with its record (node.Event{Number, Priority, Endpoint, Cluster, Event, Time, Payload}) after the log recorded it and the subscriptions were told — the node-wide broadcast matter.js's ChangeNotificationService makes of each occurrence. It runs on the emitter's goroutine, or queued through Node.ObserveAsync.

schema.AttributeName, CommandName, ResponseCommandName and EventName name the elements of every cluster of the snapshot, and schema.ClusterFeatures carries each feature's Title.

On the controller side, each controller/client.Node keeps a bounded history of the events it delivered to Hooks.Event — the default subscription's, its bootstrap read's and the newly-commissioned read's: Node.EventHistory(since, limit) returns them oldest first (since inclusive, a positive limit keeps the newest) as client.RecordedEvent, the event with its decoded payload. Config.EventHistory sizes it (0 keeps client.DefaultEventHistory, 100; negative keeps none); it is memory only and Node.Erase clears it. An event is in the history when Hooks.Event runs, so that hook is its change notification. matter.js's ClientNode keeps no history; this is the module's own (BD-Matter-ClientNodeEventHistory).

Node.Subscriptions().Snapshot() lists the active subscriptions, each as a copy (node.SubscriptionInfo: id, fabric, peer, session, the requested intervals, the attribute and event paths, the send interval), and SessionDiagnostics gives each session its SubscriptionIDs. The bridge-level seam (Bridge.AttachDiagnosticEvents, Bridge.DiagnosticEvents) stays for a host that runs the bridge without the facade.