Skip to content

Stop temporary KV watchers on errors and cancellation - #1051

Open
ajaykr0905 wants to merge 4 commits into
nats-io:mainfrom
ajaykr0905:fix/kv-watcher-cleanup-1050
Open

ajaykr0905 wants to merge 4 commits into
nats-io:mainfrom
ajaykr0905:fix/kv-watcher-cleanup-1050

Conversation

@ajaykr0905

@ajaykr0905 ajaykr0905 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

purge_deletes() left its temporary KV watcher subscribed after reading the initial snapshot. Later writes could fill the unconsumed watcher queue and stall connection drain. keys() also retained its watcher when consumer-info lookup or iteration failed or was cancelled.

Stop each temporary watcher in finally. For purge_deletes(), release the watcher before performing stream purges. Key filtering, empty-key errors, tombstone selection, and the olderthan retention behavior stay unchanged.

The first CI run exposed an existing callback cancellation race on Python 3.8–3.10. Older asyncio.wait_for() can consume cancellation when its awaited future has just completed; the callback task then kept waiting even after unsubscribe. Make the callback loop honor closed state and have JetStream push subscriptions share that state with the underlying callback owner. Delegate unsubscribe to the owner; inherited drain also updates the shared state.

The new real-JetStream regressions cover repeated housekeeping, subscription and callback/heartbeat task cleanup, consumer-info and iteration failures, deterministic cancellation, purge failures, 300 subsequent writes, and connection drain. Error/cancellation injection happens after a real watcher has been created; those scenarios use events rather than sleeps to control cancellation.

Validation with nats-server 2.15.0:

  • The regression failure scenarios fail against unchanged main (db5f8da).
  • Original 300-write reproduction: subscriptions 1 → 2 and drain timeout before; subscriptions 1 → 1 and drain below 0.001 seconds with no async errors on final source.
  • Python 3.9.6: original strict watcher-task regression fails before the callback correction; final focused lifecycle/KV suite 31 passed; full legacy suite 363 passed, 9 skipped.
  • Deterministic callback-cancellation regression fails before correction on both Python 3.9 and 3.13; drain/unsubscribe state regression also fails before state forwarding.
  • Python 3.13.9 full legacy suite: 363 passed, 9 skipped, 66 subtests passed.
  • Modern suites: nats-core 312 passed; nats-server 34 passed; nats-key-value 63 passed; nats-jetstream 315 passed, 2 expected xfails.
  • Full Ruff lint/format and codespell pass; compilation and Python 3.8 syntax checks pass.
  • ty check nats-core nats-server exits successfully with three existing unused-ignore warnings.
  • Legacy nats-py wheel and source distribution build successfully.

The first full-suite run hit the unchanged five-second deadline in JSMTest.test_jsm_stream_management_with_offset while creating 300 streams. That test passed its isolated rerun without changing any limits, then the full suite passed. An initial parallel modern-suite run hit two unchanged JetStream connection-setup timeouts; both isolated reruns and the complete JetStream repeat passed with existing limits.

AI assistance was used to prepare the implementation and tests. All reported checks ran locally against the repository code and a real NATS server.

Fixes #1050.

@caspervonb caspervonb self-assigned this Oct 8, 2026
@ajaykr0905

Copy link
Copy Markdown
Contributor Author

@caspervonb, this PR is mergeable but behind current main. It closes temporary KV watchers on success, failure, and cancellation, with real-server lifecycle coverage across supported Python behavior. Could you review it when you have time? I can update the branch before merge.

@caspervonb

Copy link
Copy Markdown
Collaborator

PTAL @claude

@synadia-claude-reviewer

synadia-claude-reviewer Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Claude finished @caspervonb's task in 2m 43s —— View job


Review complete

  • Gather context (PR diff, description, files)
  • Review nats/src/nats/aio/subscription.py changes
  • Review nats/src/nats/js/client.py changes
  • Review nats/src/nats/js/kv.py changes (purge_deletes, keys)
  • Review new tests
  • Post findings

Summary

This is a well-targeted fix with a clear root-cause chain: purge_deletes()/keys() left their temporary KV watcher subscribed on error/cancellation (unconsumed queue → stalled drain), which led to the asyncio.wait_for cancellation-consumption discovery on Python 3.8–3.10, which led to the _closed-state sharing fix between Subscription and JetStreamContext.PushSubscription. The three changes compose correctly:

  • nats/src/nats/aio/subscription.py:305 — while not self._closed is a correct backstop for the case where a callback's await swallows the task's cancellation (old asyncio.wait_for behavior) before the CancelledError would otherwise break the loop.
  • nats/src/nats/js/client.py:969-975 — making PushSubscription._closed a property delegating to self._sub._closed is the right fix: previously Subscription.unsubscribe() (via super().unsubscribe()) set _closed = True only on the wrapper instance, never on the underlying sub whose bound _wait_for_msgs task actually checks self._closed. Without this, the new backstop in subscription.py would never see the flag flip for push subscriptions.
  • nats/src/nats/js/client.py:1012 — switching to await self._sub.unsubscribe(limit) (instead of super().unsubscribe(limit)) is also a correctness improvement beyond the stated motivation: PushSubscription._received is a one-time snapshot copied at __init__ and never updated, while _conn._subs[sid] (incremented on every delivered message, nats/src/nats/aio/client.py:2037) holds the underlying sub, not the wrapper. Calling unsubscribe through self._sub means the self._received >= limit check in Subscription.unsubscribe sees live counts instead of a stale copy — this matters for the limit-based auto-unsubscribe path.
  • nats/src/nats/js/kv.py — the try/except BaseException/else structure around purge_deletes() and keys() is a reasonable (if slightly unusual) way to get "always stop the watcher" semantics while suppressing only expected shutdown errors (ConnectionClosedError/BadSubscriptionError) on the success path, and swallowing broader stop() failures on the error path so the original failure/cancellation isn't masked. except BaseException correctly catches asyncio.CancelledError.

Finding: history() has the same leak and wasn't fixed

KeyValue.history() (nats/src/nats/js/kv.py:501-520) creates a temporary watcher via self.watch(key, include_history=True) and only calls await watcher.stop() after the async for entry in watcher: loop completes successfully (line 515). If the loop raises (consumer-info/iteration failure) or the task is cancelled while iterating, watcher.stop() is never reached — this is exactly the bug class this PR fixes in purge_deletes() and keys(), just left unaddressed in history(). Given the PR title ("Stop temporary KV watchers on errors and cancellation") and that history() uses the identical watch() → iterate → stop() pattern, this looks like a gap rather than an intentional exclusion.

Fix this →

Minor note

The PR description says watchers are stopped "in finally", but the implementation uses a try/except-BaseException/else pair instead of an actual finally block (to get different exception-suppression behavior for the success vs. failure path). This is a deliberate and sound choice, just worth noting since it doesn't literally match the description's wording.

No issues found with the subscription/client.py changes or the new regression tests (test_kv_watcher_cleanup.py, test_subscription_cleanup.py), which look appropriately targeted at the described races.

@caspervonb caspervonb added the nats-legacy Legacy asyncio NATS client label Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

nats-legacy Legacy asyncio NATS client

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KeyValue.purge_deletes() leaks a live watcher, which blocks drain() until drain_timeout

2 participants