You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2026/08/19 21:08:53 UTC

(plc4x) 03/04: feat(plc4go/spi): add a polling-subscription base to the default connection set

This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 3b85dba8f28a49007f2f28e0eea47128d0e11c73
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Wed Aug 19 23:06:25 2026 +0200

    feat(plc4go/spi): add a polling-subscription base to the default connection set
    
    plc4go had no equivalent of plc4j's PollingSubscriptionConnectionBase, so every
    driver that subscribes hand-rolled the same consumer registry, handle tracking
    and event fan-out - seven copies of it. A driver adopts this one the way it
    adopts the other Default* bases, by construction, and only has to supply the
    read-request builder the poller should use.
    
    Tags are grouped by subscription type and interval so each group issues one read
    request per tick. Cyclic emits every poll; change-of-state emits only when a
    value actually differs from the previous one, with the first poll always
    emitting. Event subscriptions are answered per tag with UNSUPPORTED rather than
    by throwing, following the Go convention of response codes.
    
    Unsubscribe is finer grained than plc4j's, which drops the whole batch: a tag is
    removed from its group and the poller stops once the group empties. Handles from
    another subscriber are skipped rather than erroring, because an unsubscription
    request is handed to every subscriber it involves.
    
    Nothing existing changed - this is purely additive, and no driver was migrated
    onto it here.
---
 plc4go/spi/default/DefaultSubscriber.go      |  840 +++++++++++++++++
 plc4go/spi/default/DefaultSubscriber_test.go | 1252 ++++++++++++++++++++++++++
 2 files changed, 2092 insertions(+)

diff --git a/plc4go/spi/default/DefaultSubscriber.go b/plc4go/spi/default/DefaultSubscriber.go
new file mode 100644
index 0000000000..72134e150c
--- /dev/null
+++ b/plc4go/spi/default/DefaultSubscriber.go
@@ -0,0 +1,840 @@
+/*
+ * 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
+ *
+ *   https://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 _default
+
+import (
+	"context"
+	"reflect"
+	"runtime/debug"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/rs/zerolog"
+
+	apiModel "github.com/apache/plc4x/plc4go/pkg/api/model"
+	apiValues "github.com/apache/plc4x/plc4go/pkg/api/values"
+	"github.com/apache/plc4x/plc4go/spi"
+	"github.com/apache/plc4x/plc4go/spi/errors"
+	spiModel "github.com/apache/plc4x/plc4go/spi/model"
+	"github.com/apache/plc4x/plc4go/spi/options"
+	"github.com/apache/plc4x/plc4go/spi/utils"
+)
+
+// DefaultPollingSubscriberRequirements adds the methods a driver has to provide in order to use a
+// DefaultPollingSubscriber. It is the Go counterpart of the abstract parts of plc4j's
+// PollingSubscriptionConnectionBase.
+type DefaultPollingSubscriberRequirements interface {
+	// PollingReadRequestBuilder has to return a *fresh* apiModel.PlcReadRequestBuilder on every call.
+	// Usually this is simply the connection's ReadRequestBuilder(). The subscriber assembles one read
+	// request per poll cycle from it, using apiModel.PlcReadRequestBuilder.AddTagAddress with the
+	// address string of the subscribed tag.
+	PollingReadRequestBuilder() apiModel.PlcReadRequestBuilder
+}
+
+// DefaultPollingSubscriber emulates subscriptions for drivers whose protocol has no native
+// subscription support (Modbus, ADS-less setups, ...) by periodically issuing read requests.
+//
+// It supports:
+//   - apiModel.SubscriptionCyclic: an event is emitted on every poll.
+//   - apiModel.SubscriptionChangeOfState: an event is emitted only when a value differs from the
+//     value seen on the previous poll (the very first poll always emits).
+//   - apiModel.SubscriptionEvent: not emulatable, such tags are answered with
+//     apiModel.PlcResponseCode_UNSUPPORTED.
+//
+// Adoption is opt-in and by construction, in the same style as DefaultConnection or DefaultCodec:
+//
+//	type Connection struct {
+//		_default.DefaultConnection
+//		subscriber _default.DefaultPollingSubscriber
+//	}
+//
+//	connection.subscriber = _default.NewDefaultPollingSubscriber(connection)
+//
+// The driver then delegates spi.PlcSubscriber to the embedded subscriber and has to call Close on it
+// while closing the connection so no poller outlives the connection.
+type DefaultPollingSubscriber interface {
+	spi.PlcSubscriber
+	// Close stops every running poller, drops all subscriptions and consumer registrations and waits
+	// for the spawned go routines to finish - which includes the consumer callbacks currently being
+	// delivered (see fanOut). It is safe to call more than once and safe to call concurrently with
+	// Subscribe.
+	Close()
+}
+
+// PollTicker abstracts a time.Ticker so tests (and drivers bringing their own scheduler) can drive
+// the poll cycle from a fake clock.
+type PollTicker interface {
+	// Chan returns the channel a tick is delivered on.
+	Chan() <-chan time.Time
+	// Stop releases the resources of this ticker. It doesn't have to close the channel.
+	Stop()
+}
+
+// PollTickerFactory creates a PollTicker for the given poll interval.
+type PollTickerFactory func(interval time.Duration) PollTicker
+
+// PlcValueComparator decides if two apiValues.PlcValue are to be considered equal. It is used to
+// suppress unchanged values on apiModel.SubscriptionChangeOfState subscriptions.
+type PlcValueComparator func(previous, current apiValues.PlcValue) bool
+
+// DefaultPollingInterval is used for tags which don't come with an interval of their own (which is
+// the case for all apiModel.SubscriptionChangeOfState tags). Mirrors plc4j's
+// PollingSubscriptionConnectionBase.getDefaultPollingInterval.
+const DefaultPollingInterval = time.Second
+
+// NewDefaultPollingSubscriber is the factory for a DefaultPollingSubscriber. Supported options are
+// WithDefaultPollingInterval, WithPlcValueComparator, WithPollTickerFactory and the generic
+// options.WithCustomLogger.
+func NewDefaultPollingSubscriber(requirements DefaultPollingSubscriberRequirements, _options ...options.WithOption) DefaultPollingSubscriber {
+	return buildDefaultPollingSubscriber(requirements, _options...)
+}
+
+// WithDefaultPollingInterval overrides the interval used for tags without an explicit one.
+func WithDefaultPollingInterval(interval time.Duration) options.WithOption {
+	return withDefaultPollingInterval{defaultPollingInterval: interval}
+}
+
+// WithPlcValueComparator overrides the change detection used for
+// apiModel.SubscriptionChangeOfState subscriptions.
+func WithPlcValueComparator(comparator PlcValueComparator) options.WithOption {
+	return withPlcValueComparator{plcValueComparator: comparator}
+}
+
+// WithPollTickerFactory replaces the time.Ticker backed clock driving the poll cycles.
+func WithPollTickerFactory(factory PollTickerFactory) options.WithOption {
+	return withPollTickerFactory{pollTickerFactory: factory}
+}
+
+///////////////////////////////////////
+///////////////////////////////////////
+//
+// Internal section
+//
+
+type withDefaultPollingInterval struct {
+	options.Option
+	defaultPollingInterval time.Duration
+}
+
+type withPlcValueComparator struct {
+	options.Option
+	plcValueComparator PlcValueComparator
+}
+
+type withPollTickerFactory struct {
+	options.Option
+	pollTickerFactory PollTickerFactory
+}
+
+// realPollTicker is the production PollTicker, backed by a time.Ticker.
+type realPollTicker struct {
+	ticker *time.Ticker
+}
+
+func (r *realPollTicker) Chan() <-chan time.Time {
+	return r.ticker.C
+}
+
+func (r *realPollTicker) Stop() {
+	r.ticker.Stop()
+}
+
+func newRealPollTicker(interval time.Duration) PollTicker {
+	return &realPollTicker{ticker: time.NewTicker(interval)}
+}
+
+// subscriptionKey groups the tags of one subscription request: all tags sharing a subscription type
+// and a poll interval are served by a single poller (and therefore a single read request).
+type subscriptionKey struct {
+	subscriptionType apiModel.PlcSubscriptionType
+	interval         time.Duration
+}
+
+// pollingSubscription is one running poller together with the tags it polls.
+type pollingSubscription struct {
+	id               uint64
+	subscriptionType apiModel.PlcSubscriptionType
+	interval         time.Duration
+
+	// mutex guards tagNames, tags and previousValues: the poll go routine reads them while
+	// Unsubscribe may concurrently drop tags from the group.
+	mutex          sync.Mutex
+	tagNames       []string
+	tags           map[string]apiModel.PlcSubscriptionTag
+	previousValues map[string]apiValues.PlcValue
+
+	done     chan struct{}
+	stopOnce sync.Once
+}
+
+// snapshot returns the currently subscribed tags in request order.
+func (p *pollingSubscription) snapshot() ([]string, map[string]apiModel.PlcSubscriptionTag) {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	tagNames := make([]string, len(p.tagNames))
+	copy(tagNames, p.tagNames)
+	tags := make(map[string]apiModel.PlcSubscriptionTag, len(p.tags))
+	for tagName, tag := range p.tags {
+		tags[tagName] = tag
+	}
+	return tagNames, tags
+}
+
+// tagCount returns how many tags are currently subscribed in this group.
+func (p *pollingSubscription) tagCount() int {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	return len(p.tagNames)
+}
+
+// hasTag tells if the given tag is still subscribed in this group.
+func (p *pollingSubscription) hasTag(tagName string) bool {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	_, ok := p.tags[tagName]
+	return ok
+}
+
+// previousValue returns the value seen on the previous poll, if any.
+func (p *pollingSubscription) previousValue(tagName string) (apiValues.PlcValue, bool) {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	value, ok := p.previousValues[tagName]
+	return value, ok
+}
+
+// rememberValue stores the value of the current poll as the baseline for the next one.
+func (p *pollingSubscription) rememberValue(tagName string, value apiValues.PlcValue) {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	p.previousValues[tagName] = value
+}
+
+// removeTag drops one tag from this group and returns how many tags are left.
+func (p *pollingSubscription) removeTag(tagName string) int {
+	p.mutex.Lock()
+	defer p.mutex.Unlock()
+	if _, ok := p.tags[tagName]; !ok {
+		return len(p.tagNames)
+	}
+	delete(p.tags, tagName)
+	delete(p.previousValues, tagName)
+	remaining := make([]string, 0, len(p.tagNames))
+	for _, name := range p.tagNames {
+		if name != tagName {
+			remaining = append(remaining, name)
+		}
+	}
+	p.tagNames = remaining
+	return len(p.tagNames)
+}
+
+// stop signals the poll go routine to terminate. It is safe to call more than once.
+func (p *pollingSubscription) stop() {
+	p.stopOnce.Do(func() {
+		close(p.done)
+	})
+}
+
+// pollingSubscriptionHandle is handed out per subscribed tag. Embedding
+// spiModel.DefaultPlcSubscriptionHandle makes it both registerable and unsubscribable through
+// spiModel.DefaultPlcUnsubscriptionRequest.
+type pollingSubscriptionHandle struct {
+	*spiModel.DefaultPlcSubscriptionHandle
+	subscriptionId uint64
+	tagName        string
+}
+
+func newPollingSubscriptionHandle(subscriber spi.PlcSubscriber, subscriptionId uint64, tagName string) *pollingSubscriptionHandle {
+	handle := &pollingSubscriptionHandle{
+		subscriptionId: subscriptionId,
+		tagName:        tagName,
+	}
+	handle.DefaultPlcSubscriptionHandle = spiModel.NewDefaultPlcSubscriptionHandleWithHandleToRegister(subscriber, handle)
+	return handle
+}
+
+// pollingSubscriptionEvent adds the address information the generic
+// spiModel.DefaultPlcSubscriptionEvent requires from its embedder.
+type pollingSubscriptionEvent struct {
+	*spiModel.DefaultPlcSubscriptionEvent
+	addresses map[string]string
+}
+
+func newPollingSubscriptionEvent(
+	tags map[string]apiModel.PlcTag,
+	types map[string]apiModel.PlcSubscriptionType,
+	intervals map[string]time.Duration,
+	responseCodes map[string]apiModel.PlcResponseCode,
+	addresses map[string]string,
+	values map[string]apiValues.PlcValue,
+	_options ...options.WithOption,
+) apiModel.PlcSubscriptionEvent {
+	event := &pollingSubscriptionEvent{addresses: addresses}
+	event.DefaultPlcSubscriptionEvent = spiModel.NewDefaultPlcSubscriptionEvent(
+		event, tags, types, intervals, responseCodes, values, _options...,
+	).(*spiModel.DefaultPlcSubscriptionEvent)
+	return event
+}
+
+// GetAddress returns the address the value was polled from.
+func (p *pollingSubscriptionEvent) GetAddress(name string) string {
+	return p.addresses[name]
+}
+
+type defaultPollingSubscriber struct {
+	DefaultPollingSubscriberRequirements
+
+	defaultPollingInterval time.Duration
+	plcValueComparator     PlcValueComparator
+	pollTickerFactory      PollTickerFactory
+
+	subscriptionIdGenerator atomic.Uint64
+	subscriptionsMutex      sync.Mutex
+	subscriptions           map[uint64]*pollingSubscription
+
+	consumersMutex sync.RWMutex
+	consumers      map[*spiModel.DefaultPlcConsumerRegistration]apiModel.PlcSubscriptionEventConsumer
+
+	// ctx is cancelled by Close, which unblocks in-flight polling reads.
+	ctx    context.Context
+	cancel context.CancelFunc
+	closed atomic.Bool
+
+	// spawnMutex guards the "not closed yet, so spawn" decision of Subscribe against the closed flag
+	// Close sets: adding to a sync.WaitGroup whose counter dropped to zero while somebody is inside
+	// its Wait panics, and that panic happens on the caller's stack, outside of every recover this
+	// file installs. Close only passes through this mutex as a fence (after it set closed), so it
+	// never holds it while waiting - a consumer callback re-entering Subscribe gets the closed error
+	// instead of deadlocking.
+	spawnMutex sync.Mutex
+	wg         sync.WaitGroup // use to track spawned go routines
+
+	log      zerolog.Logger
+	_options []options.WithOption // Used to pass them downstream
+}
+
+func buildDefaultPollingSubscriber(requirements DefaultPollingSubscriberRequirements, _options ...options.WithOption) DefaultPollingSubscriber {
+	defaultPollingInterval := DefaultPollingInterval
+	var plcValueComparator PlcValueComparator
+	var pollTickerFactory PollTickerFactory
+	for _, option := range _options {
+		switch option := option.(type) {
+		case withDefaultPollingInterval:
+			if option.defaultPollingInterval > 0 {
+				defaultPollingInterval = option.defaultPollingInterval
+			}
+		case withPlcValueComparator:
+			plcValueComparator = option.plcValueComparator
+		case withPollTickerFactory:
+			pollTickerFactory = option.pollTickerFactory
+		}
+	}
+	if plcValueComparator == nil {
+		plcValueComparator = PlcValuesEqual
+	}
+	if pollTickerFactory == nil {
+		pollTickerFactory = newRealPollTicker
+	}
+
+	customLogger := options.ExtractCustomLoggerOrDefaultToGlobal(_options...)
+	ctx, cancel := context.WithCancel(context.Background())
+	return &defaultPollingSubscriber{
+		DefaultPollingSubscriberRequirements: requirements,
+
+		defaultPollingInterval: defaultPollingInterval,
+		plcValueComparator:     plcValueComparator,
+		pollTickerFactory:      pollTickerFactory,
+
+		subscriptions: map[uint64]*pollingSubscription{},
+		consumers:     map[*spiModel.DefaultPlcConsumerRegistration]apiModel.PlcSubscriptionEventConsumer{},
+
+		ctx:    ctx,
+		cancel: cancel,
+
+		log:      customLogger,
+		_options: _options,
+	}
+}
+
+//
+// Internal section
+//
+///////////////////////////////////////
+///////////////////////////////////////
+
+// PlcValuesEqual is the default PlcValueComparator: two values are equal when they are deeply equal.
+// Everything reflect.DeepEqual can't tell apart is reported as *changed*, because for a
+// apiModel.SubscriptionChangeOfState subscription a superfluous event is harmless while a swallowed
+// one is not. Especially note that there is no String() based fallback: the String() of
+// spi/values.PlcValueAdapter renders "not implemented" for every value type which doesn't override
+// it (values.PlcRawByteArray, as produced by s7, knxnetip, bacnetip, cbus and opcua, is one of them),
+// so such a fallback would consider any two of those values equal and silence the subscription for
+// good.
+func PlcValuesEqual(previous, current apiValues.PlcValue) bool {
+	if previous == nil || current == nil {
+		return previous == nil && current == nil
+	}
+	return reflect.DeepEqual(previous, current)
+}
+
+// Subscribe emulates the requested subscriptions by starting one poller per subscription type and
+// interval combination. Note that the passed context only scopes the setup: the pollers outlive it
+// and are bound to the lifetime of this subscriber (see Close).
+func (d *defaultPollingSubscriber) Subscribe(_ context.Context, subscriptionRequest apiModel.PlcSubscriptionRequest) <-chan apiModel.PlcSubscriptionRequestResult {
+	result := make(chan apiModel.PlcSubscriptionRequestResult, 1)
+	// The closed check and the spawning have to happen as one atomic step, otherwise a concurrent
+	// Close could slip in between and the wg.Go would add to a wait group which is already being
+	// drained - which panics the process.
+	d.spawnMutex.Lock()
+	if d.closed.Load() {
+		d.spawnMutex.Unlock()
+		utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcSubscriptionRequestResult(
+			subscriptionRequest, nil, errors.New("subscriber is closed"),
+		))
+		return result
+	}
+	d.wg.Go(func() {
+		defer func() {
+			if err := recover(); err != nil {
+				utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcSubscriptionRequestResult(
+					subscriptionRequest, nil, errors.Errorf("panic-ed %v. Stack: %s", err, debug.Stack()),
+				))
+			}
+		}()
+		request, ok := subscriptionRequest.(*spiModel.DefaultPlcSubscriptionRequest)
+		if !ok {
+			utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcSubscriptionRequestResult(
+				subscriptionRequest, nil, errors.Errorf("%T is not a supported subscription request", subscriptionRequest),
+			))
+			return
+		}
+
+		responseCodes := map[string]apiModel.PlcResponseCode{}
+		handles := map[string]apiModel.PlcSubscriptionHandle{}
+
+		// Group the tags so tags sharing type and interval end up in one read request.
+		var keyOrder []subscriptionKey
+		groups := map[subscriptionKey][]string{}
+		for _, tagName := range request.GetTagNames() {
+			switch subscriptionType := request.GetType(tagName); subscriptionType {
+			case apiModel.SubscriptionCyclic, apiModel.SubscriptionChangeOfState:
+				tag := request.GetTag(tagName)
+				if tag == nil {
+					responseCodes[tagName] = apiModel.PlcResponseCode_INVALID_ADDRESS
+					continue
+				}
+				interval := request.GetInterval(tagName)
+				if interval <= 0 {
+					interval = d.defaultPollingInterval
+				}
+				key := subscriptionKey{subscriptionType: subscriptionType, interval: interval}
+				if _, alreadySeen := groups[key]; !alreadySeen {
+					keyOrder = append(keyOrder, key)
+				}
+				groups[key] = append(groups[key], tagName)
+			default:
+				// Spontaneous events can't be emulated by polling.
+				d.log.Debug().
+					Str("tagName", tagName).
+					Stringer("subscriptionType", subscriptionType).
+					Msg("polling subscriptions can only emulate CYCLIC and CHANGE_OF_STATE")
+				responseCodes[tagName] = apiModel.PlcResponseCode_UNSUPPORTED
+			}
+		}
+
+		var startedSubscriptions []*pollingSubscription
+		for _, key := range keyOrder {
+			tagNames := groups[key]
+			subscription := &pollingSubscription{
+				id:               d.subscriptionIdGenerator.Add(1),
+				subscriptionType: key.subscriptionType,
+				interval:         key.interval,
+				tagNames:         tagNames,
+				tags:             make(map[string]apiModel.PlcSubscriptionTag, len(tagNames)),
+				previousValues:   map[string]apiValues.PlcValue{},
+				done:             make(chan struct{}),
+			}
+			for _, tagName := range tagNames {
+				subscription.tags[tagName] = request.GetTag(tagName)
+			}
+			if !d.addSubscription(subscription) {
+				for _, tagName := range tagNames {
+					responseCodes[tagName] = apiModel.PlcResponseCode_INTERNAL_ERROR
+				}
+				continue
+			}
+			for _, tagName := range tagNames {
+				handles[tagName] = newPollingSubscriptionHandle(d, subscription.id, tagName)
+				responseCodes[tagName] = apiModel.PlcResponseCode_OK
+			}
+			startedSubscriptions = append(startedSubscriptions, subscription)
+		}
+
+		// The response has to be assembled *before* the first poll can happen: building it is what
+		// hooks the consumers pre-registered on the request up to their handles, and because the very
+		// first poll of a apiModel.SubscriptionChangeOfState subscription establishes the baseline
+		// (whether anybody listens or not), an event lost to a consumer which isn't wired up yet is
+		// lost until the value changes again.
+		response := spiModel.NewDefaultPlcSubscriptionResponse(
+			subscriptionRequest,
+			responseCodes,
+			handles,
+			append(d._options, options.WithCustomLogger(d.log))...,
+		)
+
+		for _, subscription := range startedSubscriptions {
+			d.log.Debug().
+				Uint64("subscriptionId", subscription.id).
+				Stringer("subscriptionType", subscription.subscriptionType).
+				Dur("interval", subscription.interval).
+				Int("numTags", subscription.tagCount()).
+				Msg("starting polling subscription")
+			d.startPoller(subscription)
+		}
+
+		utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcSubscriptionRequestResult(
+			subscriptionRequest, response, nil,
+		))
+	})
+	d.spawnMutex.Unlock()
+	return result
+}
+
+// Unsubscribe drops the passed handles' tags from their pollers, stopping a poller as soon as none
+// of its tags are subscribed anymore. Handles which don't belong to this subscriber are skipped:
+// spiModel.DefaultPlcUnsubscriptionRequest hands the complete request to every involved subscriber,
+// so a request may well carry foreign handles.
+func (d *defaultPollingSubscriber) Unsubscribe(_ context.Context, unsubscriptionRequest apiModel.PlcUnsubscriptionRequest) <-chan apiModel.PlcUnsubscriptionRequestResult {
+	result := make(chan apiModel.PlcUnsubscriptionRequestResult, 1)
+	handleProvider, ok := unsubscriptionRequest.(interface {
+		GetSubscriptionHandles() []apiModel.PlcSubscriptionHandle
+	})
+	if !ok {
+		utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcUnsubscriptionRequestResult(
+			unsubscriptionRequest, nil, errors.Errorf("%T is not a supported unsubscription request", unsubscriptionRequest),
+		))
+		return result
+	}
+	touchedOurs := false
+	for _, handle := range handleProvider.GetSubscriptionHandles() {
+		pollingHandle, ok := handle.(*pollingSubscriptionHandle)
+		if !ok {
+			d.log.Trace().Type("handle", handle).Msg("not a handle of this subscriber")
+			continue
+		}
+		d.unsubscribeTag(pollingHandle)
+		touchedOurs = true
+	}
+	if touchedOurs {
+		d.purgeStaleRegistrations()
+	}
+	utils.DeliverResult(d.log, result, spiModel.NewDefaultPlcUnsubscriptionRequestResult(
+		unsubscriptionRequest,
+		spiModel.NewDefaultPlcUnsubscriptionResponse(unsubscriptionRequest),
+		nil,
+	))
+	return result
+}
+
+// Register registers a consumer for the given handles. Registering on a closed subscriber hands out
+// an inert registration: there is no poller left which could feed it.
+func (d *defaultPollingSubscriber) Register(consumer apiModel.PlcSubscriptionEventConsumer, handles []apiModel.PlcSubscriptionHandle) apiModel.PlcConsumerRegistration {
+	consumerRegistration := spiModel.NewDefaultPlcConsumerRegistration(d, consumer, handles...)
+	d.consumersMutex.Lock()
+	defer d.consumersMutex.Unlock()
+	if d.closed.Load() {
+		// Don't repopulate the map Close cleared (or is about to clear).
+		d.log.Debug().Msg("subscriber is closed, consumer not registered")
+		return consumerRegistration
+	}
+	d.consumers[consumerRegistration.(*spiModel.DefaultPlcConsumerRegistration)] = consumer
+	return consumerRegistration
+}
+
+// Unregister removes a previously registered consumer.
+func (d *defaultPollingSubscriber) Unregister(registration apiModel.PlcConsumerRegistration) {
+	defaultRegistration, ok := registration.(*spiModel.DefaultPlcConsumerRegistration)
+	if !ok {
+		d.log.Debug().Type("registration", registration).Msg("not a registration of this subscriber")
+		return
+	}
+	d.consumersMutex.Lock()
+	defer d.consumersMutex.Unlock()
+	delete(d.consumers, defaultRegistration)
+}
+
+// Close stops all pollers and waits for the spawned go routines to finish.
+func (d *defaultPollingSubscriber) Close() {
+	if !d.closed.CompareAndSwap(false, true) {
+		return
+	}
+	// Unblocks polling reads which are currently in flight.
+	d.cancel()
+	d.subscriptionsMutex.Lock()
+	for subscriptionId, subscription := range d.subscriptions {
+		subscription.stop()
+		delete(d.subscriptions, subscriptionId)
+	}
+	d.subscriptionsMutex.Unlock()
+	// Passing through the spawn mutex once is enough to fence off Subscribe: closed is already set,
+	// and every Subscribe checks it while holding this very mutex. So a Subscribe which is past the
+	// check has finished spawning by the time we get the mutex, and one arriving later sees the
+	// subscriber as closed and doesn't spawn at all. The go routines we are about to wait for are
+	// free to spawn pollers of their own: their own wait group entry keeps the counter above zero,
+	// which is what makes such an Add legal.
+	d.spawnMutex.Lock()
+	//nolint:staticcheck // SA2001: the empty critical section is the point, see above.
+	d.spawnMutex.Unlock()
+	d.wg.Wait()
+	d.consumersMutex.Lock()
+	d.consumers = map[*spiModel.DefaultPlcConsumerRegistration]apiModel.PlcSubscriptionEventConsumer{}
+	d.consumersMutex.Unlock()
+	d.log.Trace().Msg("polling subscriber closed")
+}
+
+// addSubscription registers a subscription unless the subscriber is already closing.
+func (d *defaultPollingSubscriber) addSubscription(subscription *pollingSubscription) bool {
+	d.subscriptionsMutex.Lock()
+	defer d.subscriptionsMutex.Unlock()
+	if d.closed.Load() {
+		return false
+	}
+	d.subscriptions[subscription.id] = subscription
+	return true
+}
+
+// unsubscribeTag removes one tag from its poller and stops the poller when it runs out of tags.
+func (d *defaultPollingSubscriber) unsubscribeTag(handle *pollingSubscriptionHandle) {
+	d.subscriptionsMutex.Lock()
+	subscription, ok := d.subscriptions[handle.subscriptionId]
+	if !ok {
+		d.subscriptionsMutex.Unlock()
+		// Either already unsubscribed or a sibling handle of the same group did it.
+		d.log.Trace().Uint64("subscriptionId", handle.subscriptionId).Msg("subscription already gone")
+		return
+	}
+	if subscription.removeTag(handle.tagName) == 0 {
+		delete(d.subscriptions, handle.subscriptionId)
+		d.subscriptionsMutex.Unlock()
+		subscription.stop()
+		d.log.Debug().Uint64("subscriptionId", handle.subscriptionId).Msg("stopped polling subscription")
+		return
+	}
+	d.subscriptionsMutex.Unlock()
+}
+
+// purgeStaleRegistrations drops the consumer registrations which reference nothing but handles of
+// tags this subscriber doesn't poll anymore. Without it a long living connection which repeatedly
+// subscribes and unsubscribes piles up dead registrations, which fanOut then walks on every poll.
+// Registrations carrying at least one live or foreign handle are left alone.
+func (d *defaultPollingSubscriber) purgeStaleRegistrations() {
+	d.consumersMutex.Lock()
+	defer d.consumersMutex.Unlock()
+	for registration := range d.consumers {
+		handles := registration.GetSubscriptionHandles()
+		if len(handles) == 0 {
+			continue
+		}
+		stale := true
+		for _, handle := range handles {
+			pollingHandle, ok := handle.(*pollingSubscriptionHandle)
+			if !ok || d.isSubscribed(pollingHandle) {
+				stale = false
+				break
+			}
+		}
+		if stale {
+			delete(d.consumers, registration)
+			d.log.Trace().Msg("dropped a consumer registration of an unsubscribed tag")
+		}
+	}
+}
+
+// isSubscribed tells if the tag a handle points to is still being polled.
+func (d *defaultPollingSubscriber) isSubscribed(handle *pollingSubscriptionHandle) bool {
+	d.subscriptionsMutex.Lock()
+	subscription, ok := d.subscriptions[handle.subscriptionId]
+	d.subscriptionsMutex.Unlock()
+	return ok && subscription.hasTag(handle.tagName)
+}
+
+// startPoller spawns the go routine driving one subscription.
+func (d *defaultPollingSubscriber) startPoller(subscription *pollingSubscription) {
+	ticker := d.pollTickerFactory(subscription.interval)
+	d.wg.Go(func() {
+		defer ticker.Stop()
+		tickChan := ticker.Chan()
+		for {
+			select {
+			case <-d.ctx.Done():
+				return
+			case <-subscription.done:
+				return
+			case _, ok := <-tickChan:
+				if !ok {
+					return
+				}
+				d.poll(subscription)
+			}
+		}
+	})
+}
+
+// poll issues one read request for all tags of a subscription and turns the response into an event.
+func (d *defaultPollingSubscriber) poll(subscription *pollingSubscription) {
+	defer func() {
+		if err := recover(); err != nil {
+			d.log.Error().
+				Str("stack", string(debug.Stack())).
+				Interface("err", err).
+				Uint64("subscriptionId", subscription.id).
+				Msg("panic-ed while polling")
+		}
+	}()
+	tagNames, tags := subscription.snapshot()
+	if len(tagNames) == 0 {
+		return
+	}
+	builder := d.PollingReadRequestBuilder()
+	if builder == nil {
+		d.log.Error().Msg("driver didn't supply a read request builder")
+		return
+	}
+	for _, tagName := range tagNames {
+		builder.AddTagAddress(tagName, tags[tagName].GetAddressString())
+	}
+	readRequest, err := builder.Build()
+	if err != nil {
+		d.log.Warn().Err(err).Uint64("subscriptionId", subscription.id).Msg("error building the polling read request")
+		return
+	}
+
+	var readResult apiModel.PlcReadRequestResult
+	select {
+	case readResult = <-readRequest.Execute(d.ctx):
+	case <-d.ctx.Done():
+		return
+	case <-subscription.done:
+		return
+	}
+	if readResult == nil {
+		d.log.Warn().Uint64("subscriptionId", subscription.id).Msg("no result from the polling read request")
+		return
+	}
+	if err := readResult.GetErr(); err != nil {
+		d.log.Warn().Err(err).Uint64("subscriptionId", subscription.id).Msg("error executing the polling read request")
+		return
+	}
+	readResponse := readResult.GetResponse()
+	if readResponse == nil {
+		d.log.Warn().Uint64("subscriptionId", subscription.id).Msg("no response from the polling read request")
+		return
+	}
+	d.emit(subscription, tagNames, tags, readResponse)
+}
+
+// emit assembles the subscription event for one poll and hands it to the interested consumers.
+// For apiModel.SubscriptionChangeOfState only tags whose value actually changed are part of the
+// event, and an event consisting solely of failed tags is not emitted at all (matching plc4j).
+func (d *defaultPollingSubscriber) emit(
+	subscription *pollingSubscription,
+	tagNames []string,
+	tags map[string]apiModel.PlcSubscriptionTag,
+	readResponse apiModel.PlcReadResponse,
+) {
+	eventTags := map[string]apiModel.PlcTag{}
+	eventTypes := map[string]apiModel.PlcSubscriptionType{}
+	eventIntervals := map[string]time.Duration{}
+	eventResponseCodes := map[string]apiModel.PlcResponseCode{}
+	eventAddresses := map[string]string{}
+	eventValues := map[string]apiValues.PlcValue{}
+
+	addTag := func(tagName string, code apiModel.PlcResponseCode) {
+		eventTags[tagName] = tags[tagName]
+		eventTypes[tagName] = subscription.subscriptionType
+		eventIntervals[tagName] = subscription.interval
+		eventResponseCodes[tagName] = code
+		eventAddresses[tagName] = tags[tagName].GetAddressString()
+	}
+
+	shouldFire := false
+	for _, tagName := range tagNames {
+		code := readResponse.GetResponseCode(tagName)
+		if code != apiModel.PlcResponseCode_OK {
+			// Failures are reported, but on their own they don't make an event.
+			addTag(tagName, code)
+			continue
+		}
+		currentValue := readResponse.GetValue(tagName)
+		if subscription.subscriptionType == apiModel.SubscriptionChangeOfState {
+			if previousValue, seen := subscription.previousValue(tagName); seen && d.plcValueComparator(previousValue, currentValue) {
+				continue
+			}
+		}
+		subscription.rememberValue(tagName, currentValue)
+		addTag(tagName, code)
+		eventValues[tagName] = currentValue
+		shouldFire = true
+	}
+	if !shouldFire {
+		return
+	}
+
+	event := newPollingSubscriptionEvent(
+		eventTags,
+		eventTypes,
+		eventIntervals,
+		eventResponseCodes,
+		eventAddresses,
+		eventValues,
+		append(d._options, options.WithCustomLogger(d.log))...,
+	)
+	d.fanOut(subscription.id, event)
+}
+
+// fanOut delivers an event to every consumer registered for a handle of the given subscription. The
+// consumers are snapshotted so a consumer is free to (un)register from within its own callback.
+//
+// Delivery is synchronous on the poll go routine, which keeps the events of one subscription ordered
+// (a consumer sees them in the order they were polled). The price is that a consumer which blocks
+// stalls the polling of its own subscription - and makes Close block until the callback returns,
+// since Close waits for the poll go routines. Consumers doing more than a hand-full of work should
+// therefore queue the event and process it elsewhere.
+func (d *defaultPollingSubscriber) fanOut(subscriptionId uint64, event apiModel.PlcSubscriptionEvent) {
+	d.consumersMutex.RLock()
+	interested := make([]apiModel.PlcSubscriptionEventConsumer, 0, len(d.consumers))
+	for registration, consumer := range d.consumers {
+		for _, handle := range registration.GetSubscriptionHandles() {
+			if pollingHandle, ok := handle.(*pollingSubscriptionHandle); ok && pollingHandle.subscriptionId == subscriptionId {
+				interested = append(interested, consumer)
+				break
+			}
+		}
+	}
+	d.consumersMutex.RUnlock()
+	for _, consumer := range interested {
+		if consumer == nil {
+			continue
+		}
+		consumer(event)
+	}
+}
diff --git a/plc4go/spi/default/DefaultSubscriber_test.go b/plc4go/spi/default/DefaultSubscriber_test.go
new file mode 100644
index 0000000000..7e4a719243
--- /dev/null
+++ b/plc4go/spi/default/DefaultSubscriber_test.go
@@ -0,0 +1,1252 @@
+/*
+ * 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
+ *
+ *   https://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 _default
+
+import (
+	"context"
+	"runtime"
+	"sync"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	apiModel "github.com/apache/plc4x/plc4go/pkg/api/model"
+	apiValues "github.com/apache/plc4x/plc4go/pkg/api/values"
+	"github.com/apache/plc4x/plc4go/spi/errors"
+	spiModel "github.com/apache/plc4x/plc4go/spi/model"
+	"github.com/apache/plc4x/plc4go/spi/options"
+	spiValues "github.com/apache/plc4x/plc4go/spi/values"
+)
+
+const (
+	pollTestTimeout  = 5 * time.Second
+	pollTestQuietFor = 150 * time.Millisecond
+)
+
+///////////////////////////////////////
+// Test doubles
+//
+
+// fakePollTag is a minimal tag which is both an apiModel.PlcTag (so it can be read) and an
+// apiModel.PlcSubscriptionTag (so it can be subscribed).
+type fakePollTag struct {
+	address string
+}
+
+var (
+	_ apiModel.PlcTag             = fakePollTag{}
+	_ apiModel.PlcSubscriptionTag = fakePollTag{}
+)
+
+func (f fakePollTag) String() string                       { return f.address }
+func (f fakePollTag) GetAddressString() string             { return f.address }
+func (f fakePollTag) GetValueType() apiValues.PlcValueType { return apiValues.DINT }
+func (f fakePollTag) GetArrayInfo() []apiModel.ArrayInfo   { return nil }
+func (f fakePollTag) GetPlcSubscriptionType() apiModel.PlcSubscriptionType {
+	return apiModel.SubscriptionCyclic
+}
+func (f fakePollTag) GetDuration() time.Duration { return 0 }
+
+type fakePollTagHandler struct{}
+
+func (fakePollTagHandler) ParseTag(tagAddress string) (apiModel.PlcTag, error) {
+	return fakePollTag{address: tagAddress}, nil
+}
+
+func (fakePollTagHandler) ParseQuery(_ string) (apiModel.PlcQuery, error) {
+	return nil, errors.New("not implemented")
+}
+
+// fakePollTarget plays both roles a driver plays for the polling subscriber: it hands out read
+// request builders (DefaultPollingSubscriberRequirements) and answers the reads (spi.PlcReader).
+type fakePollTarget struct {
+	mutex  sync.Mutex
+	values map[string]apiValues.PlcValue
+	codes  map[string]apiModel.PlcResponseCode
+
+	reads       atomic.Int32
+	builderFail atomic.Bool
+	// block, if set, makes every read wait until it is closed (or the context is done). Used to
+	// pin down the shutdown behaviour with a read in flight.
+	block chan struct{}
+	// reading is signalled every time a read is entered.
+	reading chan struct{}
+}
+
+func newFakePollTarget() *fakePollTarget {
+	return &fakePollTarget{
+		values:  map[string]apiValues.PlcValue{},
+		codes:   map[string]apiModel.PlcResponseCode{},
+		reading: make(chan struct{}, 128),
+	}
+}
+
+func (f *fakePollTarget) setValue(address string, value apiValues.PlcValue) {
+	f.mutex.Lock()
+	defer f.mutex.Unlock()
+	f.values[address] = value
+}
+
+func (f *fakePollTarget) setCode(address string, code apiModel.PlcResponseCode) {
+	f.mutex.Lock()
+	defer f.mutex.Unlock()
+	f.codes[address] = code
+}
+
+func (f *fakePollTarget) PollingReadRequestBuilder() apiModel.PlcReadRequestBuilder {
+	if f.builderFail.Load() {
+		return nil
+	}
+	return spiModel.NewDefaultPlcReadRequestBuilder(fakePollTagHandler{}, f)
+}
+
+func (f *fakePollTarget) Read(ctx context.Context, readRequest apiModel.PlcReadRequest) <-chan apiModel.PlcReadRequestResult {
+	result := make(chan apiModel.PlcReadRequestResult, 1)
+	f.reads.Add(1)
+	select {
+	case f.reading <- struct{}{}:
+	default:
+	}
+	if f.block != nil {
+		select {
+		case <-f.block:
+		case <-ctx.Done():
+			result <- spiModel.NewDefaultPlcReadRequestResult(readRequest, nil, ctx.Err())
+			return result
+		}
+	}
+	codes := map[string]apiModel.PlcResponseCode{}
+	values := map[string]apiValues.PlcValue{}
+	f.mutex.Lock()
+	for _, tagName := range readRequest.GetTagNames() {
+		address := readRequest.GetTag(tagName).GetAddressString()
+		if code, ok := f.codes[address]; ok {
+			codes[tagName] = code
+		} else {
+			codes[tagName] = apiModel.PlcResponseCode_OK
+		}
+		values[tagName] = f.values[address]
+	}
+	f.mutex.Unlock()
+	result <- spiModel.NewDefaultPlcReadRequestResult(
+		readRequest,
+		spiModel.NewDefaultPlcReadResponse(readRequest, codes, values),
+		nil,
+	)
+	return result
+}
+
+// manualTicker is a PollTicker driven by the test instead of the wall clock.
+type manualTicker struct {
+	interval time.Duration
+	c        chan time.Time
+	stopped  atomic.Bool
+}
+
+func (m *manualTicker) Chan() <-chan time.Time { return m.c }
+
+func (m *manualTicker) Stop() { m.stopped.Store(true) }
+
+// tick delivers a single tick and blocks until the poller picked it up.
+func (m *manualTicker) tick(t *testing.T) {
+	t.Helper()
+	select {
+	case m.c <- time.Now():
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("poller did not pick up a tick within %s", pollTestTimeout)
+	}
+}
+
+// tickExpectingNoPoller tries to deliver a tick and reports whether anybody was listening.
+func (m *manualTicker) tickExpectingNoPoller() bool {
+	select {
+	case m.c <- time.Now():
+		return true
+	case <-time.After(pollTestQuietFor):
+		return false
+	}
+}
+
+// slowStopTicker never ticks but takes its time to stop, which keeps the poll go routine using it
+// alive for a moment after it was told to shut down. Used to widen the shutdown window in
+// TestDefaultPollingSubscriberCloseRacingSubscribe.
+type slowStopTicker struct {
+	c chan time.Time
+}
+
+func newSlowStopTicker(_ time.Duration) PollTicker {
+	return &slowStopTicker{c: make(chan time.Time)}
+}
+
+func (s *slowStopTicker) Chan() <-chan time.Time { return s.c }
+
+func (s *slowStopTicker) Stop() { time.Sleep(20 * time.Millisecond) }
+
+// manualClock hands out manualTickers and records them in creation order.
+type manualClock struct {
+	mutex   sync.Mutex
+	tickers []*manualTicker
+}
+
+func (m *manualClock) factory(interval time.Duration) PollTicker {
+	m.mutex.Lock()
+	defer m.mutex.Unlock()
+	ticker := &manualTicker{interval: interval, c: make(chan time.Time)}
+	m.tickers = append(m.tickers, ticker)
+	return ticker
+}
+
+func (m *manualClock) all() []*manualTicker {
+	m.mutex.Lock()
+	defer m.mutex.Unlock()
+	tickers := make([]*manualTicker, len(m.tickers))
+	copy(tickers, m.tickers)
+	return tickers
+}
+
+func (m *manualClock) only(t *testing.T) *manualTicker {
+	t.Helper()
+	tickers := m.all()
+	require.Len(t, tickers, 1, "expected exactly one poller")
+	return tickers[0]
+}
+
+///////////////////////////////////////
+// Test helpers
+//
+
+// eventSink collects the events delivered to a consumer.
+type eventSink struct {
+	events chan apiModel.PlcSubscriptionEvent
+}
+
+func newEventSink() *eventSink {
+	return &eventSink{events: make(chan apiModel.PlcSubscriptionEvent, 64)}
+}
+
+func (e *eventSink) consume(event apiModel.PlcSubscriptionEvent) {
+	e.events <- event
+}
+
+func (e *eventSink) requireEvent(t *testing.T) apiModel.PlcSubscriptionEvent {
+	t.Helper()
+	select {
+	case event := <-e.events:
+		return event
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("no subscription event within %s", pollTestTimeout)
+		return nil
+	}
+}
+
+func (e *eventSink) requireNoEvent(t *testing.T) {
+	t.Helper()
+	select {
+	case event := <-e.events:
+		t.Fatalf("unexpected subscription event: %v", event)
+	case <-time.After(pollTestQuietFor):
+	}
+}
+
+// subscribe executes a subscription request and returns the response.
+func subscribe(t *testing.T, subscriber DefaultPollingSubscriber, build func(builder apiModel.PlcSubscriptionRequestBuilder)) apiModel.PlcSubscriptionResponse {
+	t.Helper()
+	builder := spiModel.NewDefaultPlcSubscriptionRequestBuilder(fakePollTagHandler{}, nil, subscriber)
+	build(builder)
+	request, err := builder.Build()
+	require.NoError(t, err)
+	select {
+	case result := <-request.Execute(context.Background()):
+		require.NoError(t, result.GetErr())
+		require.NotNil(t, result.GetResponse())
+		return result.GetResponse()
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("subscribe did not return within %s", pollTestTimeout)
+		return nil
+	}
+}
+
+func registerConsumer(t *testing.T, subscriber DefaultPollingSubscriber, response apiModel.PlcSubscriptionResponse, sink *eventSink, tagNames ...string) apiModel.PlcConsumerRegistration {
+	t.Helper()
+	var handles []apiModel.PlcSubscriptionHandle
+	for _, tagName := range tagNames {
+		handle, err := response.GetSubscriptionHandle(tagName)
+		require.NoError(t, err)
+		handles = append(handles, handle)
+	}
+	require.NotEmpty(t, handles)
+	// A single tag goes through the api-level flow (handle.Register) to keep that path covered.
+	if len(handles) == 1 {
+		return handles[0].Register(sink.consume)
+	}
+	return subscriber.Register(sink.consume, handles)
+}
+
+func unsubscribe(t *testing.T, handles ...apiModel.PlcSubscriptionHandle) {
+	t.Helper()
+	builder := spiModel.NewDefaultPlcUnsubscriptionRequestBuilder()
+	builder.AddHandles(handles...)
+	request, err := builder.Build()
+	require.NoError(t, err)
+	select {
+	case result := <-request.Execute(context.Background()):
+		require.NoError(t, result.GetErr())
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("unsubscribe did not return within %s", pollTestTimeout)
+	}
+}
+
+func handleFor(t *testing.T, response apiModel.PlcSubscriptionResponse, tagName string) apiModel.PlcSubscriptionHandle {
+	t.Helper()
+	handle, err := response.GetSubscriptionHandle(tagName)
+	require.NoError(t, err)
+	return handle
+}
+
+// registrationCount reports how many consumer registrations the subscriber currently keeps.
+func registrationCount(subscriber *defaultPollingSubscriber) int {
+	subscriber.consumersMutex.RLock()
+	defer subscriber.consumersMutex.RUnlock()
+	return len(subscriber.consumers)
+}
+
+// assertNoPollerLeak checks that the go routine count settles back at (or below) the baseline.
+// Go routines the runtime tears down lazily make a single sample flaky, hence the retries.
+func assertNoPollerLeak(t *testing.T, baseline int) {
+	t.Helper()
+	current := runtime.NumGoroutine()
+	for i := 0; i < 100 && current > baseline; i++ {
+		time.Sleep(20 * time.Millisecond)
+		current = runtime.NumGoroutine()
+	}
+	if current > baseline {
+		buf := make([]byte, 1<<20)
+		n := runtime.Stack(buf, true)
+		t.Fatalf("goroutine leak detected: baseline %d, now %d\n%s", baseline, current, buf[:n])
+	}
+}
+
+func closeWithin(t *testing.T, subscriber DefaultPollingSubscriber) {
+	t.Helper()
+	closed := make(chan struct{})
+	go func() {
+		defer close(closed)
+		subscriber.Close()
+	}()
+	select {
+	case <-closed:
+	case <-time.After(pollTestTimeout):
+		buf := make([]byte, 1<<20)
+		n := runtime.Stack(buf, true)
+		t.Fatalf("Close did not return within %s\n%s", pollTestTimeout, buf[:n])
+	}
+}
+
+///////////////////////////////////////
+// Tests
+//
+
+// TestDefaultPollingSubscriberCyclicEmitsEveryPoll pins the CYCLIC contract: every poll produces an
+// event, even when the value didn't move.
+func TestDefaultPollingSubscriberCyclicEmitsEveryPoll(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("holding-register:1", spiValues.NewPlcDINT(42))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "holding-register:1", 10*time.Millisecond)
+	})
+	assert.Equal(t, apiModel.PlcResponseCode_OK, response.GetResponseCode("tag"))
+
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	assert.Equal(t, 10*time.Millisecond, ticker.interval, "the poller has to run at the configured interval")
+
+	ticker.tick(t)
+	event := sink.requireEvent(t)
+	assert.Equal(t, apiModel.PlcResponseCode_OK, event.GetResponseCode("tag"))
+	assert.Equal(t, int32(42), event.GetValue("tag").GetInt32())
+	assert.Equal(t, "holding-register:1", event.GetAddress("tag"))
+
+	// Unchanged value, but CYCLIC fires anyway.
+	ticker.tick(t)
+	event = sink.requireEvent(t)
+	assert.Equal(t, int32(42), event.GetValue("tag").GetInt32())
+
+	target.setValue("holding-register:1", spiValues.NewPlcDINT(43))
+	ticker.tick(t)
+	event = sink.requireEvent(t)
+	assert.Equal(t, int32(43), event.GetValue("tag").GetInt32())
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberCyclicUsesRealClock runs the very same flow through the production
+// time.Ticker with a short interval, so the wiring of the default ticker factory is covered too.
+func TestDefaultPollingSubscriberCyclicUsesRealClock(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("holding-register:1", spiValues.NewPlcDINT(7))
+	interval := 20 * time.Millisecond
+	subscriber := NewDefaultPollingSubscriber(target)
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "holding-register:1", interval)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	start := time.Now()
+	for i := 0; i < 3; i++ {
+		event := sink.requireEvent(t)
+		assert.Equal(t, int32(7), event.GetValue("tag").GetInt32())
+	}
+	// Three events can't have arrived faster than two intervals after the first one.
+	assert.GreaterOrEqual(t, time.Since(start), 2*interval, "events must not be emitted faster than the interval")
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberChangeOfStateSuppressesUnchangedValues pins the CHANGE_OF_STATE
+// contract: the first poll fires, further polls only fire on an actual change.
+func TestDefaultPollingSubscriberChangeOfStateSuppressesUnchangedValues(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("coil:3", spiValues.NewPlcBOOL(false))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target,
+		WithPollTickerFactory(clock.factory),
+		WithDefaultPollingInterval(30*time.Millisecond),
+	)
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddChangeOfStateTagAddress("tag", "coil:3")
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	assert.Equal(t, 30*time.Millisecond, ticker.interval, "change-of-state tags have to fall back to the default interval")
+
+	// The very first poll has no baseline yet, so it fires.
+	ticker.tick(t)
+	event := sink.requireEvent(t)
+	assert.False(t, event.GetValue("tag").GetBool())
+
+	// Same value twice: no event.
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	// Changed value: event.
+	target.setValue("coil:3", spiValues.NewPlcBOOL(true))
+	ticker.tick(t)
+	event = sink.requireEvent(t)
+	assert.True(t, event.GetValue("tag").GetBool())
+
+	// And it stays quiet again on the new baseline.
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberGroupsTagsAndRejectsEventTags pins the grouping: tags sharing type and
+// interval are polled by a single read, and EVENT tags are answered as unsupported.
+func TestDefaultPollingSubscriberGroupsTagsAndRejectsEventTags(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	target.setValue("b", spiValues.NewPlcDINT(2))
+	target.setValue("c", spiValues.NewPlcDINT(3))
+	target.setValue("d", spiValues.NewPlcDINT(4))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("first", "a", 10*time.Millisecond)
+		builder.AddCyclicTagAddress("second", "b", 10*time.Millisecond)
+		builder.AddCyclicTagAddress("third", "c", 20*time.Millisecond)
+		builder.AddChangeOfStateTagAddress("fourth", "d")
+		builder.AddEventTagAddress("fifth", "e")
+	})
+
+	assert.Equal(t, apiModel.PlcResponseCode_OK, response.GetResponseCode("first"))
+	assert.Equal(t, apiModel.PlcResponseCode_OK, response.GetResponseCode("second"))
+	assert.Equal(t, apiModel.PlcResponseCode_OK, response.GetResponseCode("third"))
+	assert.Equal(t, apiModel.PlcResponseCode_OK, response.GetResponseCode("fourth"))
+	assert.Equal(t, apiModel.PlcResponseCode_UNSUPPORTED, response.GetResponseCode("fifth"),
+		"a poller can't emulate spontaneous events")
+
+	tickers := clock.all()
+	require.Len(t, tickers, 3, "one poller per subscription type and interval")
+	assert.Equal(t, 10*time.Millisecond, tickers[0].interval)
+	assert.Equal(t, 20*time.Millisecond, tickers[1].interval)
+	assert.Equal(t, DefaultPollingInterval, tickers[2].interval)
+
+	// "first" and "second" share a poller, so they share an event and a single read.
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "first", "second")
+	tickers[0].tick(t)
+	event := sink.requireEvent(t)
+	assert.ElementsMatch(t, []string{"first", "second"}, event.GetTagNames())
+	assert.Equal(t, int32(1), event.GetValue("first").GetInt32())
+	assert.Equal(t, int32(2), event.GetValue("second").GetInt32())
+	assert.Equal(t, int32(1), target.reads.Load(), "grouped tags have to be polled with one read")
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberUnsubscribeStopsEmission pins that unsubscribing tears the poller down.
+func TestDefaultPollingSubscriberUnsubscribeStopsEmission(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	sink.requireEvent(t)
+
+	unsubscribe(t, handleFor(t, response, "tag"))
+
+	// The poll go routine is gone, so nobody picks up a tick anymore and no event is emitted.
+	assert.False(t, ticker.tickExpectingNoPoller(), "the poller has to be gone after unsubscribing")
+	assert.True(t, ticker.stopped.Load(), "the ticker has to be stopped")
+	sink.requireNoEvent(t)
+
+	readsAfterUnsubscribe := target.reads.Load()
+	assert.Equal(t, int32(1), readsAfterUnsubscribe, "no further polls after unsubscribing")
+
+	// Unsubscribing twice is a no-op, not an error.
+	unsubscribe(t, handleFor(t, response, "tag"))
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberUnsubscribeSingleTagOfGroup pins that unsubscribing one tag of a group
+// keeps the remaining tags of that group polled.
+func TestDefaultPollingSubscriberUnsubscribeSingleTagOfGroup(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	target.setValue("b", spiValues.NewPlcDINT(2))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("first", "a", 10*time.Millisecond)
+		builder.AddCyclicTagAddress("second", "b", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "first", "second")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	event := sink.requireEvent(t)
+	assert.ElementsMatch(t, []string{"first", "second"}, event.GetTagNames())
+
+	unsubscribe(t, handleFor(t, response, "first"))
+
+	ticker.tick(t)
+	event = sink.requireEvent(t)
+	assert.Equal(t, []string{"second"}, event.GetTagNames(), "only the remaining tag stays polled")
+
+	unsubscribe(t, handleFor(t, response, "second"))
+	assert.False(t, ticker.tickExpectingNoPoller(), "the poller has to be gone once the group ran empty")
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberFailedReadsDoNotFire pins that failing tags are reported but never
+// make an event on their own (mirroring plc4j's PollingSubscriptionConnectionBase).
+func TestDefaultPollingSubscriberFailedReadsDoNotFire(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setCode("a", apiModel.PlcResponseCode_NOT_FOUND)
+	target.setValue("b", spiValues.NewPlcDINT(2))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("broken", "a", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "broken")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	// Add a healthy tag on the same interval; now the event carries both.
+	secondResponse := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("broken", "a", 10*time.Millisecond)
+		builder.AddCyclicTagAddress("healthy", "b", 10*time.Millisecond)
+	})
+	secondSink := newEventSink()
+	registerConsumer(t, subscriber, secondResponse, secondSink, "broken", "healthy")
+
+	tickers := clock.all()
+	require.Len(t, tickers, 2, "a second subscribe has to get a poller of its own")
+	tickers[1].tick(t)
+	event := secondSink.requireEvent(t)
+	assert.Equal(t, apiModel.PlcResponseCode_NOT_FOUND, event.GetResponseCode("broken"))
+	assert.Equal(t, apiModel.PlcResponseCode_OK, event.GetResponseCode("healthy"))
+	assert.Equal(t, int32(2), event.GetValue("healthy").GetInt32())
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberConcurrentRegisterUnregister hammers the consumer bookkeeping while
+// the poller is running. Meant to be run with -race.
+func TestDefaultPollingSubscriberConcurrentRegisterUnregister(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	subscriber := NewDefaultPollingSubscriber(target)
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", time.Millisecond)
+	})
+	handle := handleFor(t, response, "tag")
+
+	var deliveries atomic.Int64
+	var churn sync.WaitGroup
+	stop := make(chan struct{})
+	for worker := 0; worker < 8; worker++ {
+		churn.Go(func() {
+			for {
+				select {
+				case <-stop:
+					return
+				default:
+				}
+				registration := handle.Register(func(_ apiModel.PlcSubscriptionEvent) {
+					deliveries.Add(1)
+				})
+				require.NotNil(t, registration)
+				registration.Unregister()
+			}
+		})
+	}
+	// Keep a stable consumer around so we can be sure polls really happened while we churned.
+	sink := newEventSink()
+	stableRegistration := handle.Register(func(event apiModel.PlcSubscriptionEvent) {
+		select {
+		case sink.events <- event:
+		default:
+		}
+	})
+	sink.requireEvent(t)
+	time.Sleep(200 * time.Millisecond)
+	close(stop)
+	churn.Wait()
+	stableRegistration.Unregister()
+
+	assert.Positive(t, target.reads.Load(), "the poller has to have polled while we churned")
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberCloseWithReadInFlight pins that Close doesn't block on a read which is
+// still waiting for the PLC and doesn't leak the poll go routine.
+func TestDefaultPollingSubscriberCloseWithReadInFlight(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.block = make(chan struct{})
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	// Wait until the read is actually in flight (and stuck).
+	select {
+	case <-target.reading:
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("no read started within %s", pollTestTimeout)
+	}
+
+	closeWithin(t, subscriber)
+	assert.True(t, ticker.stopped.Load(), "the ticker has to be stopped on close")
+	sink.requireNoEvent(t)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberCloseIsIdempotent pins that a second Close is a no-op.
+func TestDefaultPollingSubscriberCloseIsIdempotent(t *testing.T) {
+	target := newFakePollTarget()
+	subscriber := NewDefaultPollingSubscriber(target)
+	closeWithin(t, subscriber)
+	closeWithin(t, subscriber)
+}
+
+// TestDefaultPollingSubscriberSubscribeAfterCloseFails pins that a closed subscriber refuses new
+// subscriptions instead of silently starting a poller nobody stops.
+func TestDefaultPollingSubscriberSubscribeAfterCloseFails(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+	closeWithin(t, subscriber)
+
+	builder := spiModel.NewDefaultPlcSubscriptionRequestBuilder(fakePollTagHandler{}, nil, subscriber)
+	builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	request, err := builder.Build()
+	require.NoError(t, err)
+	select {
+	case result := <-request.Execute(context.Background()):
+		assert.Error(t, result.GetErr())
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("subscribe did not return within %s", pollTestTimeout)
+	}
+	assert.Empty(t, clock.all(), "no poller may be started after close")
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberUnsupportedRequestTypes pins the guards against foreign message types.
+func TestDefaultPollingSubscriberUnsupportedRequestTypes(t *testing.T) {
+	target := newFakePollTarget()
+	subscriber := NewDefaultPollingSubscriber(target)
+	defer closeWithin(t, subscriber)
+
+	select {
+	case result := <-subscriber.Subscribe(context.Background(), &foreignSubscriptionRequest{}):
+		assert.Error(t, result.GetErr())
+	case <-time.After(pollTestTimeout):
+		t.Fatal("Subscribe did not return")
+	}
+
+	select {
+	case result := <-subscriber.Unsubscribe(context.Background(), &foreignUnsubscriptionRequest{}):
+		assert.Error(t, result.GetErr())
+	case <-time.After(pollTestTimeout):
+		t.Fatal("Unsubscribe did not return")
+	}
+}
+
+// TestDefaultPollingSubscriberUnsubscribeIgnoresForeignHandles pins that a mixed unsubscription
+// request (spiModel.DefaultPlcUnsubscriptionRequest passes the whole request to every subscriber)
+// doesn't produce spurious errors.
+func TestDefaultPollingSubscriberUnsubscribeIgnoresForeignHandles(t *testing.T) {
+	target := newFakePollTarget()
+	subscriber := NewDefaultPollingSubscriber(target)
+	defer closeWithin(t, subscriber)
+
+	foreign := spiModel.NewDefaultPlcSubscriptionHandle(subscriber)
+	request := spiModel.NewDefaultPlcUnsubscriptionRequest([]apiModel.PlcSubscriptionHandle{foreign})
+	select {
+	case result := <-subscriber.Unsubscribe(context.Background(), request):
+		assert.NoError(t, result.GetErr())
+	case <-time.After(pollTestTimeout):
+		t.Fatal("Unsubscribe did not return")
+	}
+}
+
+// TestDefaultPollingSubscriberSurvivesBrokenBuilder pins that a driver failing to hand out a read
+// request builder neither panics nor kills the poller.
+func TestDefaultPollingSubscriberSurvivesBrokenBuilder(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	target.builderFail.Store(true)
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	// The poller is still alive and recovers as soon as the driver hands out builders again.
+	target.builderFail.Store(false)
+	ticker.tick(t)
+	event := sink.requireEvent(t)
+	assert.Equal(t, int32(1), event.GetValue("tag").GetInt32())
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberPreRegisteredConsumers pins that consumers registered on the request
+// receive events without an explicit Register call.
+func TestDefaultPollingSubscriberPreRegisteredConsumers(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(5))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	sink := newEventSink()
+	subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+		builder.AddPreRegisteredConsumer("tag", sink.consume)
+	})
+
+	clock.only(t).tick(t)
+	event := sink.requireEvent(t)
+	assert.Equal(t, int32(5), event.GetValue("tag").GetInt32())
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberCustomValueComparator pins that a driver can override the change
+// detection.
+func TestDefaultPollingSubscriberCustomValueComparator(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	clock := &manualClock{}
+	// This comparator considers everything equal, so nothing but the first poll ever fires.
+	subscriber := NewDefaultPollingSubscriber(target,
+		WithPollTickerFactory(clock.factory),
+		WithPlcValueComparator(func(_, _ apiValues.PlcValue) bool { return true }),
+	)
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddChangeOfStateTagAddress("tag", "a")
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	sink.requireEvent(t)
+
+	target.setValue("a", spiValues.NewPlcDINT(2))
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberChangeOfStateOnValuesWithoutString pins that the change detection also
+// works for value types which don't implement String() (PlcValueAdapter renders those as
+// "not implemented"), as produced by s7, knxnetip, bacnetip, cbus and opcua.
+func TestDefaultPollingSubscriberChangeOfStateOnValuesWithoutString(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("raw", spiValues.NewPlcRawByteArray([]byte{0x01, 0x02}))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddChangeOfStateTagAddress("tag", "raw")
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "tag")
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	event := sink.requireEvent(t)
+	assert.Equal(t, []byte{0x01, 0x02}, event.GetValue("tag").GetRaw())
+
+	// Unchanged, so nothing fires.
+	ticker.tick(t)
+	sink.requireNoEvent(t)
+
+	target.setValue("raw", spiValues.NewPlcRawByteArray([]byte{0xFF, 0xEE}))
+	ticker.tick(t)
+	event = sink.requireEvent(t)
+	assert.Equal(t, []byte{0xFF, 0xEE}, event.GetValue("tag").GetRaw())
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberCloseRacingSubscribe pins that a Close overlapping an in-flight
+// Subscribe stays a well behaved no-op for both sides. Adding to a sync.WaitGroup whose counter drops
+// to zero while somebody sits in its Wait panics on the caller's stack, i.e. outside of every recover
+// of this file, and would take the whole process down.
+//
+// The slowStopTicker is what makes the window big enough to be hit reliably: it keeps the poll go
+// routine (and with it the wait group counter) alive for a moment after Close already registered as a
+// waiter, so the Subscribe calls hammering away below land in exactly that window.
+func TestDefaultPollingSubscriberCloseRacingSubscribe(t *testing.T) {
+	// No assertNoPollerLeak here: the hundreds of thousands of request executions below make the
+	// shared spi/pool executor scale up a worker of its own, which has nothing to do with this
+	// subscriber. The state assertions after every Close cover what this test is about.
+	for iteration := 0; iteration < 20; iteration++ {
+		target := newFakePollTarget()
+		target.setValue("a", spiValues.NewPlcDINT(1))
+		subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(newSlowStopTicker))
+		// A first subscription so a poll go routine holds the wait group counter above zero.
+		subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+			builder.AddCyclicTagAddress("first", "a", time.Hour)
+		})
+
+		builder := spiModel.NewDefaultPlcSubscriptionRequestBuilder(fakePollTagHandler{}, nil, subscriber)
+		builder.AddCyclicTagAddress("second", "a", time.Hour)
+		request, err := builder.Build()
+		require.NoError(t, err)
+
+		closed := make(chan struct{})
+		go func() {
+			defer close(closed)
+			subscriber.Close()
+		}()
+
+		var subscribes atomic.Int64
+		var hammers sync.WaitGroup
+		for hammer := 0; hammer < 8; hammer++ {
+			hammers.Go(func() {
+				for {
+					select {
+					case <-closed:
+						return
+					default:
+					}
+					// A response or a "subscriber is closed" error, both are fine - it just must not
+					// blow up.
+					select {
+					case <-request.Execute(context.Background()):
+						subscribes.Add(1)
+					case <-time.After(pollTestTimeout):
+						t.Error("subscribe didn't return in time")
+						return
+					}
+				}
+			})
+		}
+		hammers.Wait()
+		require.Positive(t, subscribes.Load(), "the racing subscribes have to have run")
+
+		// Nothing the race let through may outlive the Close.
+		subscriber.Close()
+		internal, ok := subscriber.(*defaultPollingSubscriber)
+		require.True(t, ok)
+		internal.subscriptionsMutex.Lock()
+		assert.Empty(t, internal.subscriptions, "no subscription may survive the Close")
+		internal.subscriptionsMutex.Unlock()
+		assert.Zero(t, registrationCount(internal), "no consumer registration may survive the Close")
+	}
+}
+
+// TestDefaultPollingSubscriberPreRegisteredConsumerGetsTheFirstPoll pins that the pollers are only
+// let loose after the response - and with it the consumers pre-registered on the request - is wired
+// up. The first poll of a CHANGE_OF_STATE subscription is the only one reporting the current value,
+// so a consumer missing it never learns the state until it happens to change. The real clock with a
+// minimal interval is used on purpose: a manual ticker only ticks when the test says so and can
+// therefore never observe this race.
+func TestDefaultPollingSubscriberPreRegisteredConsumerGetsTheFirstPoll(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	for iteration := 0; iteration < 50; iteration++ {
+		target := newFakePollTarget()
+		target.setValue("a", spiValues.NewPlcDINT(int32(iteration)))
+		subscriber := NewDefaultPollingSubscriber(target, WithDefaultPollingInterval(time.Nanosecond))
+
+		sink := newEventSink()
+		subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+			builder.AddChangeOfStateTagAddress("tag", "a")
+			builder.AddPreRegisteredConsumer("tag", sink.consume)
+		})
+
+		event := sink.requireEvent(t)
+		assert.Equal(t, int32(iteration), event.GetValue("tag").GetInt32())
+		closeWithin(t, subscriber)
+	}
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberBlockingConsumerBlocksClose pins the documented delivery contract:
+// consumers are called synchronously on the poll go routine, so Close waits for a callback in flight
+// instead of returning while a consumer is still running (which would let a driver tear the
+// connection down under a running callback).
+func TestDefaultPollingSubscriberBlockingConsumerBlocksClose(t *testing.T) {
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	})
+	// Built up front, used from within the callback below.
+	reentrantBuilder := spiModel.NewDefaultPlcSubscriptionRequestBuilder(fakePollTagHandler{}, nil, subscriber)
+	reentrantBuilder.AddCyclicTagAddress("reentrant", "a", 10*time.Millisecond)
+	reentrantRequest, err := reentrantBuilder.Build()
+	require.NoError(t, err)
+
+	entered := make(chan struct{})
+	release := make(chan struct{})
+	reentrantErrs := make(chan error, 1)
+	registration := handleFor(t, response, "tag").Register(func(_ apiModel.PlcSubscriptionEvent) {
+		close(entered)
+		<-release
+		// Re-entering Subscribe from a callback Close is waiting for has to be refused instead of
+		// deadlocking (which is why Close only fences on the spawn mutex instead of holding it).
+		result := <-subscriber.Subscribe(context.Background(), reentrantRequest)
+		reentrantErrs <- result.GetErr()
+	})
+	require.NotNil(t, registration)
+
+	ticker := clock.only(t)
+	ticker.tick(t)
+	select {
+	case <-entered:
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("the consumer wasn't called within %s", pollTestTimeout)
+	}
+
+	closed := make(chan struct{})
+	go func() {
+		defer close(closed)
+		subscriber.Close()
+	}()
+	select {
+	case <-closed:
+		t.Fatal("Close returned while a consumer callback was still running")
+	case <-time.After(pollTestQuietFor):
+	}
+	close(release)
+	select {
+	case <-closed:
+	case <-time.After(pollTestTimeout):
+		buf := make([]byte, 1<<20)
+		n := runtime.Stack(buf, true)
+		t.Fatalf("Close didn't return within %s after the consumer returned\n%s", pollTestTimeout, buf[:n])
+	}
+	select {
+	case reentrantErr := <-reentrantErrs:
+		assert.Error(t, reentrantErr, "the closed subscriber has to refuse the re-entrant subscribe")
+	case <-time.After(pollTestTimeout):
+		t.Fatalf("the re-entrant subscribe didn't return within %s", pollTestTimeout)
+	}
+	// The poll go routine is gone (no assertNoPollerLeak here: the re-entrant subscribe drags process
+	// wide, lazily started go routines in which have nothing to do with this subscriber).
+	assert.True(t, ticker.stopped.Load(), "the ticker has to be stopped once Close returned")
+}
+
+// TestDefaultPollingSubscriberUnsubscribeDropsStaleRegistrations pins that unsubscribing also cleans
+// up the consumer registrations which only referenced the unsubscribed tags. A connection which
+// subscribes and unsubscribes over and over would otherwise pile up dead registrations, which the
+// fan out walks on every single poll.
+func TestDefaultPollingSubscriberUnsubscribeDropsStaleRegistrations(t *testing.T) {
+	baseline := runtime.NumGoroutine()
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	target.setValue("b", spiValues.NewPlcDINT(2))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+	internal, ok := subscriber.(*defaultPollingSubscriber)
+	require.True(t, ok)
+
+	for round := 0; round < 5; round++ {
+		response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+			builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+		})
+		sink := newEventSink()
+		registerConsumer(t, subscriber, response, sink, "tag")
+		require.Equal(t, 1, registrationCount(internal))
+
+		unsubscribe(t, handleFor(t, response, "tag"))
+		assert.Zero(t, registrationCount(internal), "the registration of an unsubscribed tag has to be gone")
+	}
+
+	// A registration still referencing a subscribed tag survives.
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("first", "a", 10*time.Millisecond)
+		builder.AddCyclicTagAddress("second", "b", 10*time.Millisecond)
+	})
+	sink := newEventSink()
+	registerConsumer(t, subscriber, response, sink, "first", "second")
+	unsubscribe(t, handleFor(t, response, "first"))
+	assert.Equal(t, 1, registrationCount(internal), "a registration with a live handle has to stay")
+	unsubscribe(t, handleFor(t, response, "second"))
+	assert.Zero(t, registrationCount(internal))
+
+	closeWithin(t, subscriber)
+	assertNoPollerLeak(t, baseline)
+}
+
+// TestDefaultPollingSubscriberRegisterAfterCloseIsInert pins that a late Register doesn't repopulate
+// the consumer map Close cleared.
+func TestDefaultPollingSubscriberRegisterAfterCloseIsInert(t *testing.T) {
+	target := newFakePollTarget()
+	target.setValue("a", spiValues.NewPlcDINT(1))
+	clock := &manualClock{}
+	subscriber := NewDefaultPollingSubscriber(target, WithPollTickerFactory(clock.factory))
+	internal, ok := subscriber.(*defaultPollingSubscriber)
+	require.True(t, ok)
+
+	response := subscribe(t, subscriber, func(builder apiModel.PlcSubscriptionRequestBuilder) {
+		builder.AddCyclicTagAddress("tag", "a", 10*time.Millisecond)
+	})
+	handle := handleFor(t, response, "tag")
+	closeWithin(t, subscriber)
+	require.Zero(t, registrationCount(internal))
+
+	sink := newEventSink()
+	registration := subscriber.Register(sink.consume, []apiModel.PlcSubscriptionHandle{handle})
+	assert.NotNil(t, registration, "the caller still has to get something it can Unregister")
+	assert.Zero(t, registrationCount(internal), "a closed subscriber must not take new consumers")
+	// Unregistering the inert registration stays a no-op.
+	registration.Unregister()
+	assert.Zero(t, registrationCount(internal))
+}
+
+func TestPlcValuesEqual(t *testing.T) {
+	tests := []struct {
+		name     string
+		previous apiValues.PlcValue
+		current  apiValues.PlcValue
+		want     bool
+	}{
+		{name: "both nil", previous: nil, current: nil, want: true},
+		{name: "previous nil", previous: nil, current: spiValues.NewPlcDINT(1), want: false},
+		{name: "current nil", previous: spiValues.NewPlcDINT(1), current: nil, want: false},
+		{name: "same value", previous: spiValues.NewPlcDINT(1), current: spiValues.NewPlcDINT(1), want: true},
+		{name: "different value", previous: spiValues.NewPlcDINT(1), current: spiValues.NewPlcDINT(2), want: false},
+		{name: "different type", previous: spiValues.NewPlcDINT(1), current: spiValues.NewPlcBOOL(true), want: false},
+		{name: "same bool", previous: spiValues.NewPlcBOOL(true), current: spiValues.NewPlcBOOL(true), want: true},
+		{name: "different bool", previous: spiValues.NewPlcBOOL(true), current: spiValues.NewPlcBOOL(false), want: false},
+		{
+			name:     "same list",
+			previous: spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcDINT(1), spiValues.NewPlcDINT(2)}),
+			current:  spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcDINT(1), spiValues.NewPlcDINT(2)}),
+			want:     true,
+		},
+		{
+			name:     "different list",
+			previous: spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcDINT(1)}),
+			current:  spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcDINT(2)}),
+			want:     false,
+		},
+		// The value types below don't implement String() of their own, so PlcValueAdapter renders
+		// them all as "not implemented". A String() based comparison would call every one of them
+		// equal and silence a CHANGE_OF_STATE subscription for good.
+		{
+			name:     "same raw byte array",
+			previous: spiValues.NewPlcRawByteArray([]byte{0x01, 0x02}),
+			current:  spiValues.NewPlcRawByteArray([]byte{0x01, 0x02}),
+			want:     true,
+		},
+		{
+			name:     "different raw byte array",
+			previous: spiValues.NewPlcRawByteArray([]byte{0x01, 0x02}),
+			current:  spiValues.NewPlcRawByteArray([]byte{0xFF, 0xEE}),
+			want:     false,
+		},
+		{
+			name:     "raw byte array of a different length",
+			previous: spiValues.NewPlcRawByteArray([]byte{0x01, 0x02}),
+			current:  spiValues.NewPlcRawByteArray([]byte{0x01, 0x02, 0x03}),
+			want:     false,
+		},
+		{
+			name:     "different list of raw byte arrays",
+			previous: spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcRawByteArray([]byte{0x01})}),
+			current:  spiValues.NewPlcList([]apiValues.PlcValue{spiValues.NewPlcRawByteArray([]byte{0x02})}),
+			want:     false,
+		},
+		{
+			name:     "same struct of raw byte arrays",
+			previous: spiValues.NewPlcStruct(map[string]apiValues.PlcValue{"raw": spiValues.NewPlcRawByteArray([]byte{0x01})}),
+			current:  spiValues.NewPlcStruct(map[string]apiValues.PlcValue{"raw": spiValues.NewPlcRawByteArray([]byte{0x01})}),
+			want:     true,
+		},
+		{
+			name:     "different struct of raw byte arrays",
+			previous: spiValues.NewPlcStruct(map[string]apiValues.PlcValue{"raw": spiValues.NewPlcRawByteArray([]byte{0x01})}),
+			current:  spiValues.NewPlcStruct(map[string]apiValues.PlcValue{"raw": spiValues.NewPlcRawByteArray([]byte{0x02})}),
+			want:     false,
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			assert.Equal(t, test.want, PlcValuesEqual(test.previous, test.current))
+		})
+	}
+}
+
+// TestDefaultPollingSubscriberOptionPassing pins the option plumbing.
+func TestDefaultPollingSubscriberOptionPassing(t *testing.T) {
+	target := newFakePollTarget()
+	subscriber := NewDefaultPollingSubscriber(target,
+		options.WithCustomLogger(options.ExtractCustomLoggerOrDefaultToGlobal()),
+		WithDefaultPollingInterval(0), // ignored, has to keep the default
+	)
+	internal, ok := subscriber.(*defaultPollingSubscriber)
+	require.True(t, ok)
+	assert.Equal(t, DefaultPollingInterval, internal.defaultPollingInterval)
+	assert.NotNil(t, internal.plcValueComparator)
+	assert.NotNil(t, internal.pollTickerFactory)
+	closeWithin(t, subscriber)
+}
+
+///////////////////////////////////////
+// Foreign message types used by the guard tests
+//
+
+type foreignSubscriptionRequest struct{}
+
+func (f *foreignSubscriptionRequest) String() string      { return "foreignSubscriptionRequest" }
+func (f *foreignSubscriptionRequest) IsAPlcMessage() bool { return true }
+func (f *foreignSubscriptionRequest) GetTagNames() []string {
+	return nil
+}
+func (f *foreignSubscriptionRequest) GetTag(_ string) apiModel.PlcSubscriptionTag { return nil }
+func (f *foreignSubscriptionRequest) Execute(_ context.Context) <-chan apiModel.PlcSubscriptionRequestResult {
+	return nil
+}
+
+type foreignUnsubscriptionRequest struct{}
+
+func (f *foreignUnsubscriptionRequest) String() string      { return "foreignUnsubscriptionRequest" }
+func (f *foreignUnsubscriptionRequest) IsAPlcMessage() bool { return true }
+func (f *foreignUnsubscriptionRequest) Execute(_ context.Context) <-chan apiModel.PlcUnsubscriptionRequestResult {
+	return nil
+}