Skip to content

fix(binding-mcp): deterministic cache refresh startup/teardown + coalesced re-arming - #1814

Merged
jfallows merged 4 commits into
developfrom
fix/1813-binding-mcp-cache-refresh
Jun 2, 2026
Merged

jfallows merged 4 commits into
developfrom
fix/1813-binding-mcp-cache-refresh

Conversation

@jfallows

@jfallows jfallows commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Description

Deterministic MCP proxy cache hydration/refresh lifecycle — extracted from the
examples/mcp.proxy branch (#1793)
to land on develop independently. First of three
sequential binding-mcp extractions (this → single session-id contract → proxy fixes +
bootstrap credential).

Fixes #1813.

Changes

  • Deterministic cache refresh startup/teardown — replace the cache.start.delay timing
    hack with proper k3po coordination: EngineRule.aroundStart(Supplier<Runnable>) + k3po
    deferStartable() (the starter thread blocks until k3po is prepared, runs
    engine.start(), then releases so k3po proceeds only once bindings are attached).
  • Coalesce refresh re-arming to one hydrate per cycle (was re-armed by both the local
    put-completion and the store-watch self-trigger).
  • McpProxyCache.acquire no longer clobbers a held lock token on a failed overlapping
    acquire, so release() can always unlock (an orphaned per-kind lock previously stalled
    hydrate retries for the full lease TTL).
  • McpProxyCacheHydrater.stop() aborts in-flight hydrate streams before ending the
    lifecycle (otherwise a stream left registered tripped the engine's synthetic-teardown
    onServerReset assertion).
  • store-memory: synchronous dispatch hook; engine TestStore* dispatch support
    (test-jar) used to make the ITs deterministic.
  • McpProxyCacheIT sped up via store dispatch.

Dependency note

Includes a root pom.xml bump k3po 3.4.0 → 3.4.2 (required for deferStartable()).
This is repo-wide — every spec IT uses k3po — so CI exercises the full suite against 3.4.2;
the local validation below is binding-mcp-scoped.

Testing

./mvnw verify -pl runtime/store-memory,specs/binding-mcp.spec,runtime/binding-mcp —
McpProxyCacheIT + binding-mcp ITs green (engine test-jar + store-memory built with the
changes).

🤖 Generated with Claude Code

jfallows and others added 4 commits June 2, 2026 15:30
…che start delay

Switch the test and in-memory store `defer` and watcher-notify paths from
`signaler.signalAt(now, ...)` (which rounds up to the engine's 512ms timer-
wheel tick) to `EngineContext.dispatch(Runnable)`. Completion callbacks
now fire on the next worker dispatch cycle instead of after a tick
boundary, eliminating the per-store-call ~512ms floor.

Add a `zilla.binding.mcp.cache.start.delay` SPI property (default `PT0S`)
that controls when `McpProxyCacheManager.start()` runs after the proxy
binding attaches:

  - default zero in production -> synchronous, same as before
  - non-zero in tests -> deferred via signaler

This is needed because the dispatcher-based store path exposes a race
during integration tests: the engine and k3po share the `data%d` ring-
buffer files via mmap, but k3po's external scope initialization happens
in parallel with engine startup. Without the delay, cache hydration
issues its first writes to the upstream `data63` file before k3po has
finished initializing the scope, leaving the engine worker spinning in
`ManyToOneRingBuffer.claimCapacity` against partially-initialized buffer
state. The delay only applies in the test infrastructure where the
zilla-engine and k3po-zilla-transport boot side by side.

`McpProxyCacheIT` sets `cache.start.delay = PT0.2S` (rounded up to a
single 512ms timer-wheel tick) to clear that init race. Also reduce
`proxy.cache.refresh.yaml` ttl from `PT1S` to `PT0.25S` since refresh
timing is no longer a per-store-call multiplier of 512ms.

Result: `McpProxyCacheIT` runs 24 tests in 19.4s, down from 63.5s
(3.3x faster). All 182 binding-mcp tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
(cherry picked from commit f873afa)
Replace the cache.start.delay timing hack with proper k3po coordination
and fix two latent cache defects the faster startup exposed.

- engine: EngineRule.beforeStart(Runnable) -> aroundStart(Supplier<Runnable>);
  the starter thread obtains a release from the supplier (blocks until k3po is
  prepared), runs engine.start(), then invokes the release so k3po proceeds
  past PREPARED only once bindings are attached. Pairs with k3po 3.4.2
  deferStartable(); bump k3po to 3.4.2.
- binding-mcp: drop the cache.start.delay property and its signalAt scheduling;
  McpProxyCacheIT now uses aroundStart(k3po::deferStartable).
- binding-mcp: McpProxyCache.acquire no longer clobbers the held lock token on a
  failed overlapping acquire, so release() can always unlock; previously an
  orphaned per-kind lock stalled hydrate retries for the full lease ttl.
- binding-mcp: McpProxyCacheHydrater.stop() aborts in-flight hydrate streams
  before ending the lifecycle, so no stream is left registered for the engine's
  synthetic teardown reset (which tripped onServerReset assertions).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
(cherry picked from commit 8ea8161)
… cycle

A successful hydrate re-arms the refresh timer twice: once from the local put
completion (checkPut -> onReady) and once from the store watch that the same put
self-triggers (onStoreChanged -> get -> checkGet -> onReady). The debounce in
scheduleRefresh did not reliably suppress the first signal, so two refresh
hydrates for the same kind overlapped.

Make scheduleRefresh a throttle: skip when a refresh is already pending, so the
put-path and watch-path collapse to a single pending refresh regardless of
signaler.cancel behavior. Readiness/awaiters and list-changed notifications are
unaffected (still driven by both checkPut and checkGet); only the periodic
refresh timer is coalesced. The change-driven path (list_changed -> onChanged ->
hydrate, retry via scheduleHydrateRetry) does not go through scheduleRefresh, so
a notification is never coalesced away.

Add cache.notify.tools.list.changed.during.refresh spec scripts and
McpProxyCacheIT.shouldNotifyToolsListChangedDuringRefresh to lock in the
guarantee that, when a list_changed arrives while a refresh is in flight, the
per-kind lock serializes the overlap and the post-change re-hydrate's value wins.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
(cherry picked from commit 911a48c)
…rve the delivered token

runStoreAssertions issued all store ops in a synchronous loop and resolved renew/unlock tokens from heldLockTokens, which is only populated by a prior lock's asynchronous callback. The dependent op therefore always ran with a null token; the assertion only passed when the store deferred its callback late enough (timer-based signaler) that the failing callback landed after the test completed. With the faster store dispatch the callback lands during the test, surfacing the latent failure.

Run assertions sequentially, advancing to the next only from within each op's completion callback so renew/unlock observe the token a prior lock delivered. The async contract (callback fires strictly later than the call) is preserved via a returned flag, with a fired double-fire guard; thread and expect checks are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
(cherry picked from commit b6930eb)

@jfallows jfallows left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@jfallows
jfallows merged commit e182740 into develop Jun 2, 2026
2 checks passed
jfallows pushed a commit that referenced this pull request Jun 4, 2026
After catching up develop's PR #1814 (TestStoreHandler dispatch change),
the steal/renew signaler.signalAt deliveries stopped firing on the
peer-initiated initialId stream and the takeover ITs stalled. Switch
all three ownership signalAt sites to replyId, matching the convention
used by every other server-controlled timer in this factory
(keepAliveTimeout, connectTimeout).
jfallows added a commit that referenced this pull request Jun 24, 2026
…#1806)

* feat(binding-mqtt-kafka): deprecate Kafka-group session ownership (#1797)

Add an optional, currently-unused `store` field to the mqtt-kafka binding
options so configurations can prepare for StoreHandler-based session
ownership coordination. When `store` is absent, log a one-time deprecation
warning per binding instance announcing the upcoming requirement. Existing
highlander-group ownership behavior is unchanged.

https://claude.ai/code/session_0186rZE8mW1U947XTN4kzZ1x

* test(binding-mqtt-kafka): require store on mqtt-kafka binding (#1798)

Add a failing schema test asserting that an mqtt-kafka proxy configuration
without the 'store' option is rejected, ahead of making 'store' required as
part of migrating session ownership to the Store SPI. The companion
proxy.missing.store.yaml omits 'store'; validation currently accepts it
(store remains optional per #1797), so the test is red until the schema
marks 'store' required.

https://claude.ai/code/session_01MDjS4CuoxTHjPGS2E1wGJR

* feat(binding-mqtt-kafka): add session lease/renew tuning knobs (#1798)

Introduce internal MqttKafkaConfiguration Duration properties
session.lease and session.renew, sizing the StoreHandler-based session
ownership lease TTL and renewal interval. Defaults (30s lease, 10s renew)
favor fast cooperative takeover with a bounded TTL fallback. These are
runtime tunables, not binding options, and will be consumed by the
Store-based ownership coordination in MqttKafkaSessionFactory.

https://claude.ai/code/session_01MDjS4CuoxTHjPGS2E1wGJR

* feat(binding-mqtt-kafka): make store required on mqtt-kafka binding (#1798)

Mark the 'store' option required in the mqtt-kafka schema and declare a
store on every binding configuration, completing the deprecation begun in
#1797. Spec/test configs reference a 'test' store; the runnable example
uses a 'memory' store. SchemaTest now also registers the engine test-store
schema patch so 'type: test' validates, and shouldRejectProxyWithoutStore
passes now that the option is required.

https://claude.ai/code/session_01MDjS4CuoxTHjPGS2E1wGJR

* feat(binding-mqtt-kafka): resolve StoreHandler on binding config (#1798)

Resolve the configured store reference to a StoreHandler when attaching an
mqtt-kafka binding, exposing it on MqttKafkaBindingConfig for the session
ownership coordination that will replace the Kafka consumer-group protocol.
Mirrors the binding.resolveId + supplyStore pattern used by binding-mcp.

https://claude.ai/code/session_01MDjS4CuoxTHjPGS2E1wGJR

* feat(binding-mqtt-kafka): add session #offsets blob schema (#1799)

Define MqttKafkaSessionOffsets / MqttKafkaSessionOffsetMetadata flyweights
to carry per-(topic,partition) consumed offset, idempotent producer state,
and in-flight QoS packet IDs as a single compacted mqtt-sessions record,
replacing per-clientId Kafka consumer-group offset commit metadata.

* feat(binding-mqtt-kafka): add #offsets blob (de)serialization helper (#1799)

KafkaSessionOffsetsHelper encodes/decodes the per-session QoS offset state
(per-(topic,partition) consumed offset, idempotent producer state, in-flight
packet IDs) to/from the MqttKafkaSessionOffsets flyweight, with a round-trip
unit test. Adds partitionId/producerSequence carriers to KafkaOffsetMetadata.

* test(binding-mqtt-kafka): add sessionOffsets k3po builder/matcher (#1799)

Add mqtt_kafka:sessionOffsets() / matchSessionOffsets() functions so .rpt
scripts can construct and assert the MqttKafkaSessionOffsets blob as a
mqtt-sessions record value, with round-trip and match/mismatch unit tests.

* test(binding-mqtt-kafka): rewrite publish.qos2 spec to #offsets record (#1799)

Replace the per-clientId consumer-group offsetFetch/offsetCommit Kafka
choreography with a client#offsets record on the compacted mqtt-sessions
topic: a single merged FETCH reads the prior offsets/producer/in-flight
state, and each commit point becomes a merged PRODUCE of a full
MqttKafkaSessionOffsets snapshot. initProducerId + meta retained; #migrate
and highlander group left for a later removal pass.

Note: k3po ITs cannot run in the current execution environment (control
agent fails to start), so this scenario is validated by CI, not locally.

* feat(binding-mqtt-kafka): persist QoS2 offsets in #offsets record (#1799)

Replace the per-clientId Kafka consumer-group offsetFetch/offsetCommit
choreography with a client#offsets record on the compacted mqtt-sessions
topic. Session resume reads the record via a merged FETCH_ONLY stream and
decodes the MqttKafkaSessionOffsets blob (offsets, idempotent producer
state, in-flight QoS2 packet IDs); each commit point produces a full
snapshot via a merged PRODUCE_ONLY stream keyed clientId#offsets. meta,
initProducerId, group and #migrate are unchanged.

Verified: MqttKafkaPublishProxyIT#shouldSendMessageQos2 passes against the
engine; KafkaIT#shouldPublishQoS2Message and the helper unit test stay green.
Sibling QoS2 scenarios remain on the old choreography pending spec rewrite.

* test(binding-mqtt-kafka): migrate qos2.retained + mixture.qos specs to #offsets (#1799)

Rewrite the publish.qos2.retained and publish.mixture.qos kafka scripts to
the client#offsets record model. Verified against the engine:
MqttKafkaPublishProxyIT#shouldSendMessageQos2Retained and
#shouldSendMessageMixtureQos both pass.

* fix(binding-mqtt-kafka): emit #offsets completion produce on resume (#1799)

During session resume the offset-fetch branch created the session stream
immediately AND again after the seed #offsets produce was acked, so the
duplicate stream left the PUBREL->doCommitOffsetComplete->produce completion
path unreachable (no PUBCOMP). Drop the premature doCreateSessionStream so
recovery matches the fresh-session path (session stream created once, after
the seed snapshot is acked). Migrates publish.qos2.recovery spec to #offsets.

Verified: MqttKafkaPublishProxyIT#shouldSendMessageQos2DuringRecovery passes,
no regression across the qos2/retained/mixture scenarios.

* test(binding-mqtt-kafka): migrate qos2 init.producer/offset.commit abort specs to #offsets (#1799)

Rewrite publish.qos2.init.producer.abort and publish.qos2.offset.commit.abort
phase1/phase2 kafka scripts to the client#offsets model (FETCH_ONLY preamble
and PRODUCE_ONLY commit streams). Verified against the engine: the three
corresponding MqttKafkaPublishProxyIT abort methods pass (meta.abort already
passed unchanged).

* fix(binding-mqtt-kafka): propagate #offsets fetch abort to mqtt connect (#1799)

When the merged FETCH_ONLY client#offsets stream aborts before delivering
the offsets record, the QoS2 mqtt reply is not yet open (deferred for
publishQosMax==2), so doMqttAbort on the unopened reply was unobservable and
the client hung. Also reset the mqtt initial in KafkaOffsetFetchStream
onKafkaAbort, mirroring how meta.abort already surfaces connect-abort.
Migrates publish.qos2.offset.fetch.abort spec to #offsets.

Verified: full MqttKafkaPublishProxyIT passes (36 tests, 0 failures).

* feat(binding-mqtt-kafka): rename session signal keys to #will / #expiry (#1799)

Rename the mqtt-sessions record key postfixes #will-signal -> #will and
#expiry-signal -> #expiry across the session factory constants and all 65
affected spec scenarios. The type header values (will-signal/expiry-signal)
and the will-message key prefix (#will-) are unchanged; clientId extraction
strips the constant's length so it stays correct. Clean rename, no legacy
read-both fallback.

Verified against the engine: MqttKafkaSessionProxyIT (33), MqttKafkaPublishProxyIT
(36) and MqttKafkaSubscribeProxyIT (54) all pass.

* feat(binding-mqtt-kafka): acquire session ownership lease via store (#1798)

Thread the configured StoreHandler into MqttSessionProxy and coordinate
single-owner session ownership through the store lease primitives. On
session begin the proxy locks clientId#owner for the session.lease TTL;
on success it renews the lease on the session.renew interval via a new
SIGNAL_RENEW_SESSION_OWNERSHIP timer, and releases the lock on end,
abort, and reset.

This is the additive foundation for cooperative takeover: ownership is
recorded in the store alongside the existing highlander group, which
remains until the cooperative takeover and redirect paths replace it.
No wire frames change, so existing session behavior is unaffected.

* feat(binding-mqtt-kafka): cooperative session takeover via store (#1798)

Build the cooperative-takeover protocol on top of the store-backed
ownership lease added previously.

On session begin the proxy reads the current owner record for the
clientId from the store. When the owner is a different replica with a
strong (serverRef-advertised) identity, the client is redirected to it
via an MQTT reset carrying the server reference; otherwise the proxy
publishes its own ownership record and claims the lease cooperatively.

The owning proxy watches its ownership key; when a different replica
publishes a competing record it stops renewal, releases the lock, and
closes its session so the challenger can take over. If the incumbent is
unresponsive and never yields, the contending proxy steals the lease
once it expires via a bounded retry. Identity strength is derived from
the configured serverRef and published in the ownership record.

This runs alongside the existing highlander group, which remains as the
deprecated fallback until it is removed. Existing publish, subscribe and
session integration tests pass unchanged.

* feat(binding-mqtt-kafka): derive replica identity from engine service hostname (#1800)

Source the replica's externally-reachable identity from the engine
'service.hostname' configuration (zilla.engine.service.hostname) rather
than only the per-binding 'serverRef' option, reusing the existing engine
configuration surface already consumed by binding-mcp.

The binding-level 'serverRef' continues to work and takes precedence when
set, emitting a deprecation warning that points to the engine service
hostname. When 'serverRef' is absent, the engine service hostname supplies
the strong-identity address published in the store ownership record; when
neither is configured the replica identity remains weak.

* test(binding-mqtt-kafka): cover sessionOffsets matcher branches (#1799)

Restore 100% instruction coverage on the binding-mqtt-kafka.spec module
by exercising every mismatch branch of the MqttKafkaSessionOffsetsMatcher:
per-field mismatches (partition, consumed offset, producer id/epoch/sequence,
packet ids), version mismatch, entry-count mismatch, the no-constraint
(null) result, version-only match, and the empty-buffer path.

* test(binding-mqtt-kafka): remove highlander group-only session specs (#1798)

Delete the session.group.* scenarios and their IT methods. These exercise
the Kafka consumer-group coordinator (describe-config/session-timeout/
not-authorized validation and server-sent reset) that is being removed in
favor of store-based cooperative session ownership; three were already
@ignore'd. Drops the now-unused @ignore import.

* fix(binding-asyncapi): inject store into generated mqtt-kafka binding (#1798)

mqtt-kafka now requires a store for cooperative session ownership, which
broke the asyncapi proxy whose composite generates an mqtt-kafka binding
with no store. Generate a memory store in the composite namespace and
reference it from the generated mqtt-kafka binding; add store-memory as a
provided dependency so the type resolves in tests (the dist already
bundles it).

* fix(binding-mqtt-kafka): use unicode escape for ownership field separator

The OWNERSHIP_FIELD_SEPARATOR char literal embedded a raw NUL byte, which
caused git, grep, and ripgrep to treat MqttKafkaSessionFactory.java as a
binary file. Use the equivalent unicode escape instead so the source stays
text and diffs and searches work.

* refactor(binding-mqtt-kafka): simplify session-ownership record to single identity token

Store one identity token per clientId#owner record instead of a
separator-delimited tuple. A strong (externally-addressable) owner stores its
server reference verbatim; a weak owner stores its opaque replica identity
behind an ETag-style "W/" prefix. This drops the redundant second identity
field and the unused acquisition timestamp, and removes the field separator
entirely so the record is a plain string that test stores can seed from YAML.

* test(binding-mqtt-kafka): use port-less service.hostname in example

The session owner token / redirect server reference is a bare hostname; the
listener port is implicit per service and shared across replicas, so the
service.hostname property carries no port.

* test(binding-mqtt-kafka): drop port from session redirect server reference

The redirect target is the owning replica's hostname; the listener port is
implicit per service, so the redirect server reference carries no port.

* feat(binding-mqtt-kafka): remove legacy highlander/migrate session ownership

Remove the pre-Store session-ownership machinery now that Store-based
cooperative ownership is in place:

- Delete the highlander Kafka consumer-group election (KafkaGroupStream) and
  the #migrate compacted-topic takeover signal (KafkaSessionSignalStream,
  sendMigrateSignal, MIGRATE_KEY_POSTFIX, clientIdMigrate).
- Stop creating the mqtt-clients consumer group and stop carrying the redirect
  hint on KafkaResetEx.consumerId across the session, publish, and subscribe
  streams; redirect now flows from the Store ownership record.
- Resolve Store ownership before opening any Kafka stream: onOwnershipLocked
  drives session establishment (qos<2 replies and opens the session-state
  stream; qos2 fetches metadata/offsets first), and the will-fetch flush feeds
  into the same path. A strong remote owner is redirected with no Kafka stream
  opened.
- Drop the "highlander" protocol handling from KafkaClientGroupFactory.

KafkaResetEx.consumerId remains in the Kafka IDL (still used by binding-kafka).

* test(binding-mqtt-kafka): drop migrate/group choreography from session.subscribe kafka script

Strip the #migrate produce stream, the highlander group stream, and the
mqtt-clients groupId + #migrate merged-stream filter from the session.subscribe
kafka scripts. The proxy now opens a single session-state stream keyed on the
clientId once it owns the session via the store. Verified against the engine:
MqttKafkaSessionProxyIT.shouldSubscribeSaveSubscriptionsInSession passes.

* test(binding-mqtt-kafka): add store-seeded config for session redirect

Seed the test store with a strong remote owner (client-1#owner =
mqtt-2.example.com) so the proxy resolves a different strong-identity owner on
connect and redirects the client, exercising the store-based redirect path
without any Kafka session stream.

* test(binding-mqtt-kafka): strip migrate/group from session, publish, subscribe specs

Remove the #migrate produce streams, highlander group streams, mqtt-clients
groupId, #migrate merged-stream filters, and consumerId redirect hints from the
kafka-side spec scripts across all session/publish/subscribe scenarios, matching
the removed ownership machinery. Verified against the engine: publish (36/36),
subscribe (54/54), and the session scenarios (except the cross-replica ones and
session.exists.clean.start, handled separately) pass; peer-to-peer KafkaIT and
MqttIT are green.

Also drop session.connect.override.{max,min}.session.expiry: the server-side
session-expiry override was a side effect of the Kafka consumer-group
session.timeout negotiation, which no longer exists after removing the group.

* wip(binding-mqtt-kafka): store-seeded session redirect (runtime close-timeout under analysis)

Redesign session.redirect for the store-based ownership model:
- Factory: on a strong remote owner, doRedirect resets the mqtt session stream
  immediately (doMqttReset) without opening any kafka stream (ownership-first).
- Add kafka != null guards to the base KafkaSessionStream do* frame-writers so a
  never-begun session stream (the redirect path) is not written to.
- Specs: delete the kafka-side session.redirect scripts (no kafka activity on
  redirect); mqtt-side client uses connect aborted, server uses accept/rejected.
- ITs: shouldRedirect runs mqtt-side only against proxy.redirect.yaml (store
  seeded with client-1#owner = mqtt-2.example.com); peer MqttIT#shouldRedirect
  passes.

Known issue for analysis: the runtime MqttKafkaSessionProxyIT#shouldRedirect
hits an engine-side close timeout with doMqttReset alone — the proxy's reply
direction is not released. doMqttAbort on the reply clears it but is being
reviewed; committed without it for reproduction.

* fix(binding-mqtt-kafka): discharge reply on deferred session redirect

newStream returns a non-null consumer, so the engine fully establishes the
bidirectional mqtt session stream before ownership is resolved. Because the
redirect decision is deferred behind the async store lookup, the proxy has
accepted the stream and owes a reply terminal; resetting only the initial
leaves the reply undischarged and the engine synthetically resets it on close.
Abort the reply alongside the initial RESET so the stream is fully torn down.

MqttKafkaSessionProxyIT#shouldRedirect and peer MqttIT#shouldRedirect pass.

* feat(binding-mqtt-kafka): per-connection nonce for same-replica session takeover

The ownership challenge previously surrendered only to a different identity
(cross-replica), so two connections for the same clientId on one replica could
not take over from each other — that path had relied on the removed highlander
group. Carry a globally-unique per-connection nonce (replicaId + initialId) in
the ownership record and surrender in onOwnershipChallenged whenever the
challenger's nonce differs from ours. A newer connection's store.put fires the
incumbent's watch, which then unlocks and resets, letting the newcomer acquire
the lock. Identity is still used for the strong-remote redirect decision.

* test(binding-mqtt-kafka): ignore takeover ITs pending store-ownership re-model

The three takeover scenarios (session.client.takeover, session.exists.clean.start,
session.will.message.takeover.deliver.will) relied on the removed highlander
group. Same-replica takeover now works via the per-connection ownership nonce,
but the scripts/ITs will be re-modeled when the ownership logic moves to the
mqtt server binding. Ignore them with a TODO until then so the removal lands
green.

* feat(binding-mqtt): store-based session ownership at the mqtt server binding

Move the store-based MQTT session-ownership state machine into the mqtt server
binding (where it conceptually belongs: ownership is a generic MQTT concern,
not a Kafka-mapping detail). mqtt-kafka now bootstraps the Kafka session as
soon as it receives the application BEGIN; binding-mqtt only forwards that
BEGIN after ownership is achieved.

binding-mqtt:
- MqttBindingConfig.store: resolved from options.store via supplyStore, plumbed
  through MqttBinding/MqttBindingContext.
- MqttConfiguration: INSTANCE_ID, SESSION_LEASE (PT30S), SESSION_RENEW (PT10S)
  plus a serviceHostname() accessor for the engine's service hostname.
- New InstanceId helper (mirrors mqtt-kafka's).
- MqttServerFactory: per-connection ownership state on MqttServer
  (ownerKey/Token/Watch, renewAt, stealAt, owns/claimed/ownershipResolved,
  pendingSession* for the deferred-establish), OwnershipRecord with the
  globally-unique per-connection nonce (replicaId + initialId), signal ids
  SIGNAL_RENEW_SESSION_OWNERSHIP (4) + SIGNAL_STEAL_SESSION_OWNERSHIP (5)
  wired into onNetworkSignal. Hook in onDecodeConnectPayload: when store is
  configured, defer session establishment to the lock callback by parking
  decoder = decodeAwaitOwnership. On strong remote owner doEncodeConnack
  SERVER_MOVED + serverReference and never open the downstream session; on
  claim+lock, doEstablishSession (which creates MqttSessionStream and sends
  BEGIN) + register store.watch for cooperative challenge. Same-replica
  takeover via different-nonce challenge. Re-entrant guards on the store
  callbacks for connection-already-closed paths. doReleaseOwnership called
  from cleanupNetwork and closeStreams.

The legacy session.server.redirect.before.connack path (mqtt-kafka can still
send a session RESET with serverRef post-BEGIN) is kept as a complementary
late-redirect mechanism.

specs/binding-mqtt.spec:
- server.redirect.yaml seeds the engine test store with
  client-1#owner = mqtt-2.example.com:1883.
- streams/network/v5/session.redirect/{client,server}.rpt encode the
  CONNACK SERVER_MOVED + Server Reference response.
- v5/SessionIT peer test and the runtime v5/SessionIT both cover shouldRedirect.

* feat(binding-mqtt): close out session takeover scenarios via store ownership

Wire up store-based MQTT session takeover end-to-end at the binding-mqtt layer
and retire the obsolete mqtt-kafka tests.

binding-mqtt:
- MqttServerFactory.onOwnershipChallenged now routes through the existing
  onDecodeError(SESSION_TAKEN_OVER) teardown (DISCONNECT 0x8E to the displaced
  client + END to publishes/subscribes + END to session + doReleaseOwnership),
  with a pre-emptive session.cleanupAbort when a will is present so the
  session ends as ABORT (per the will-on-abort path) and the will fires.
- OwnershipRecord FIELD_SEPARATOR: use the � escape form in source for
  clarity.

binding-mqtt specs:
- New shouldDeliverWillMessageOnSessionTakeover at v5 network + application
  layers; shouldTakeOverSession / shouldRemoveSessionAtCleanStart already
  covered v5; add a runtime IT method for each, on a tight-lease store config.
- Correct session.redirect's reason-code byte to 0x9d (MqttReasonCodes.
  SERVER_MOVED); was 0x87 (NOT_AUTHORIZED) in a pre-existing script bug, so
  the previously-passing shouldRedirect was matching the wrong byte.

mqtt-kafka cleanup:
- Delete the three @ignored takeover ITs in MqttKafkaSessionProxyIT, the
  KafkaIT/MqttIT peer methods, and the corresponding kafka/mqtt-side
  spec scenario dirs.
- Drop the dead KafkaGroup inner class and its uses in MqttKafkaPublishFactory
  / MqttKafkaPublishMetadata (left over from the kafka-side ownership strip;
  removing closes the mqtt-kafka jacoco class-coverage gate).

Verified: ./mvnw clean install across runtime/binding-mqtt, runtime/binding-mqtt-kafka,
specs/binding-mqtt.spec, specs/binding-mqtt-kafka.spec — BUILD SUCCESS with
full ITs and jacoco; coverage checks met on both bindings.

* feat(binding-mqtt): force-unlock-with-token on contended session takeover

The store-based ownership lock previously left a contended second connection
waiting for the broker's sessionLease to expire when the prior holder was
unresponsive (no watch event fires). Embed the live lock token in the
OwnershipRecord so a contender can pre-empt the unresponsive holder via
store.unlock(ownerKey, observedToken, ...), bounded by sessionRenew instead
of sessionLease.

- OwnershipRecord gains a fourth field, `token`. decode handles 0/1/2
  trailing separators so externally-seeded records (identity only) and
  legacy records (identity + nonce, no token) still parse cleanly.
- Reorder the claim flow: lock-then-put. ownershipRecord(token) is now only
  called from the lock-success path, so every record this code publishes
  carries the live token.
- Extract completeOwnership(traceId, token) shared by onOwnershipLocked
  (initial claim) and the new onStealComplete (post-steal); it writes the
  token-carrying record, installs the watch, schedules renew, runs
  doEstablishSession, and unsticks the decoder.
- onStealOwnership now: store.get → if observedToken present, store.unlock →
  retry store.lock → onStealComplete. The unlock-with-token only succeeds
  if that token is still the live holder; stale tokens are no-ops, leaving
  the cooperative path intact for responsive holders that surrender via the
  watch first.
- onStealComplete: success → completeOwnership; failure → CONNACK
  SERVER_BUSY (0x89) + network end (mirrors the doRedirect teardown
  pattern). No session cleanup needed because doEstablishSession only runs
  on success.
- onOwnershipRenewed: when renew returns null (token invalidated by a
  force-unlock), the displaced holder now surrenders via the same path as
  the watch-driven challenge — extracted as doSurrenderOwnership(traceId)
  (cancel renew, unlock if held, conditional session.cleanupAbort when a
  will is set, onDecodeError SESSION_TAKEN_OVER). onOwnershipChallenged
  also delegates to this helper, removing the duplication.

Tests: shouldTakeOverSession / shouldDeliverWillMessageOnSessionTakeover /
shouldRemoveSessionAtCleanStart / shouldRedirect remain green. The
SERVER_BUSY rejection branch and the renew-failure surrender are not
covered by an IT (would require the test store to surface a "renew refused"
outcome and a contender holding through both lock attempts); jacoco gates
on both bindings still pass.

* refactor: address review feedback on mqtt session ownership

- KafkaSessionOffsetsHelper.encode: cache lambdas and stash transient state
  on per-worker fields to drop the per-entry lambda capture and Integer
  boxing on the QoS2 offset-commit warm path; use IntArrayList.forEachInt
  and an index loop over the List signature.
- MqttServerFactory ownership block: trim verbose explanatory comments;
  rename `weak` to `strong` in OwnershipRecord.decode so the constructor
  call carries the positive boolean directly.

* fix(binding-mqtt-kafka): handle FLUSH on offset-fetch for fresh QoS2 client

The merged offset-fetch stream is opened FETCH_ONLY with a key filter and
KafkaEvaluation.EAGER. When the keyed `#offsets` record is absent (fresh
QoS2 client), the cache delivers a FLUSH after catch-up rather than DATA.
KafkaOffsetFetchStream.onOffsetFetchMessage previously dispatched only
Begin/Data/End/Abort/Reset, silently dropping the FLUSH so session
bring-up stalled and no CONNACK ever reached the client. Add a FlushFW
case that calls delegate.onOffsetFetched with an empty entries list,
taking the same initProducer branch the empty-data path already supports.

Add publish.qos2.no.prior.offsets spec scenario (mqtt + kafka client/
server) whose kafka offsets-fetch arm responds via FLUSH instead of DATA,
plus matching peer-to-peer (KafkaIT, MqttIT) and runtime
(MqttKafkaPublishProxyIT) test methods. Confirmed failing on TestTimedOut
before the fix and passing after.

* refactor: remove verbose comments from mqtt session ownership work

* refactor(binding-mqtt): hoist ownership-record constants out of per-renew path

Cache ownerIdentity, ownerNonce, and the ownership-record prefix as final
fields on MqttServer, computed once in the constructor from factory-level
serviceHostname/replicaId and the per-stream initialId. ownershipRecord(token)
now does one concat instead of four; ownerIdentity/ownerNonce comparisons
read fields instead of recomputing. The renew-callback lambda is replaced
by a cached method reference whose pending traceId is stashed in a field.

* fix(binding-mqtt): route ownership signals via replyId, not initialId

After catching up develop's PR #1814 (TestStoreHandler dispatch change),
the steal/renew signaler.signalAt deliveries stopped firing on the
peer-initiated initialId stream and the takeover ITs stalled. Switch
all three ownership signalAt sites to replyId, matching the convention
used by every other server-controlled timer in this factory
(keepAliveTimeout, connectTimeout).

* perf(binding-mqtt-kafka): cache offset-commit produce lambdas per stream

The session-offset commit path issued via kafkaDataExRW.merged(m -> m.produce(mp -> mp.deferred(0).timestamp(...).partition(p -> ...).key(b -> ...).hashKey(b -> ...))) allocated five capturing lambdas per QoS2 ack — once in MqttKafkaPublishFactory.doCommitOffsetIncomplete (per publish ack) and once in MqttKafkaSessionFactory.doProduceSessionOffsets (per offset commit).

Hoist the partition lambda to a non-capturing static and cache the remaining four as final per-stream Consumer fields that read clientIdOffsets / clientId from instance state at invocation time. doCommitOffsetIncomplete / doProduceSessionOffsets now build via the cached commitOffsetMerged field; zero lambda allocations per call on this warm path.

* test(binding-kafka): remove highlander migrate-leader tests for dead code

The shouldRebalanceProtocolHighlanderMigrateLeader and
shouldRebalanceProtocolHighlanderMigrateLeaderInParallel tests have been
failing in CI for weeks. Root cause: this PR's earlier commit
(a4d814a "feat(binding-mqtt-kafka): remove legacy highlander/migrate
session ownership") removed the HIGHLANDER_PROTOCOL migrate dispatch and
KafkaGroupStream.onStreamMigrate from KafkaClientGroupFactory, since no
internal binding uses the highlander protocol anymore. The migrate-leader
tests exercised that exact code path — a second app stream for the same
groupId rejoining via the migrate dispatch — and now have no implementation
to drive.

Remove the four affected test methods (ClientGroupIT, application/GroupIT,
network/GroupIT) and the four script directories
(application/group/rebalance.protocol.highlander.migrate.leader{,.in.parallel}
and network/group.f1.j5.s3.l3.h3/rebalance.protocol.highlander.migrate.leader
{,.in.parallel}).

The other highlander.* tests (Unknown, Fragmented, HeartbeatUnknownMember)
remain — they exercise protocol-agnostic join/sync/heartbeat paths that
binding-kafka still supports unchanged.

* build(binding-asyncapi): regenerate NOTICE for jackson-dataformat-yaml deps

The catch-up merge added jackson-dataformat-yaml as a binding-asyncapi
dependency (via our session-store work) but the NOTICE file was not
regenerated. Add the five transitive entries (Jackson-annotations,
Jackson-core, jackson-databind, Jackson-dataformat-YAML, SnakeYAML)
matching the notice-plugin expected output.

* fix(binding-asyncapi): drop mqtt_kafka_store0 injection from generated proxy

The earlier commit 810b8b1 (binding-asyncapi: inject store into generated
mqtt-kafka binding, #1798) added a memory store named "mqtt_kafka_store0"
to the asyncapi-generated proxy composite and threaded it through the
mqtt-kafka binding via MqttKafkaOptionsConfigBuilder.store(...). The
subsequent commit a4d814a (feat(binding-mqtt-kafka): remove legacy
highlander/migrate session ownership) removed the store option from
MqttKafkaOptionsConfig entirely. The asyncapi generator was not updated,
leaving a dangling call site and a compile break against the latest
develop+ours integration.

Drop the store creation and the .store(...) call. The asyncapi proxy
composite generator no longer needs a store on the mqtt-kafka step;
session ownership lives in the mqtt server binding, which the asyncapi
proxy does not directly compose.

* fix(examples/mqtt.kafka.proxy): drop now-unused memory store

The PR removed the store option from mqtt-kafka. The example's store:
memory0 entry under mqtt-kafka.options is no longer valid. Drop the
options.store reference and the stores.memory0 declaration entirely;
the mqtt-kafka proxy works fine without store-backed session ownership
for QoS0/QoS1 traffic and the example's smoke test only exercises QoS0
publish/subscribe.

Configurations that need MQTT session ownership at QoS2 should declare
the store on the mqtt server binding instead (binding-mqtt now owns the
store option).

---------

Co-authored-by: Claude <[email protected]>
@jfallows
jfallows deleted the fix/1813-binding-mcp-cache-refresh branch July 1, 2026 23:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

binding-mcp: deterministic cache refresh startup/teardown + coalesced re-arming

1 participant