Skip to content

Fix SDK bugs found by the live docs snippet tests - #242

Merged
techwritermat merged 5 commits into
masterfrom
fix/sdk-bugs-from-docs-snippets
Nov 20, 2026
Merged

techwritermat merged 5 commits into
masterfrom
fix/sdk-bugs-from-docs-snippets

Conversation

@techwritermat

@techwritermat techwritermat commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

feat(pubnub): add disconnect() to PubNub and PubNubAsyncio

Stop the subscribe loop and heartbeat timer without removing the subscriptions. The event engine subscription manager, the default for PubNubAsyncio, raises a clear PubNubException.

fix(pubnub): make reconnect() work with the subscription manager in use

reconnect() always raised AttributeError. It now restarts the subscribe loop for the threaded and legacy asyncio subscription managers, and raises a clear PubNubException with the event engine subscription manager.

fix(subscription): deliver App Context and file events to subscription listeners

Channel, user and membership (App Context) and file events are now delivered to subscription and subscription set listeners instead of raising on the first event.

fix(subscription): use the correct callback signature in add_listener()

Listeners added with subscription.add_listener() now receive events with the correct callback signature instead of raising TypeError.

fix(subscription): fix registry edge cases

Fix subscription registry removal for subscription sets sharing channels, unsubscribe_all with a following subscribe(), a set unsubscribe() that sent an empty request, and the PubNubUserMetadata subscription type.

fix(event-engine): fix get_subscribed_channels and unsubscribe_all before the first subscribe

Both calls no longer raise AttributeError with the asyncio event engine before the first subscribe.

fix(message-actions): send end together with start

get_message_actions now sends end together with start, and limit() no longer accepts only str.

fix(message-actions): set event on message action events

Message action events now carry the event type (added or removed).

fix(fetch-messages): return custom_message_type on fetched messages

custom_message_type is now parsed on items from fetch messages.

fix(objects): request the total count from include options

MembershipIncludes(total_count=True) and MemberIncludes(total_count=True) now send count=true on App Context requests.

fix(objects): stop If-Match from leaking into other requests

The If-Match header set by if_matches_etag no longer leaks into other App Context requests through a shared class-level dict.

fix(access-manager): raise PubNubException for malformed tokens

parse_token now raises PubNubException for malformed tokens instead of binascii.Error or TypeError.

fix(grant): accept delete as the only permission flag

Grant now accepts delete as the only permission flag instead of raising a no-flags error.

fix(packaging): relax the aiohttp requirement

Relax aiohttp>3.10.11 to >=3.10.11 so it overlaps the dev pin and pip can resolve both.

test: add unit tests for the SDK fixes

Add offline unit tests for the subscription registry, message worker events, get_message_actions parameters and the other fixes, and re-record the App Context include cassettes with count=True.

techwritermat and others added 2 commits November 12, 2026 13:26
* PubNubSubscriptionSet.unsubscribe() now unsubscribes the channels of the set
  and removes the set from the registry. It sent an empty unsubscribe before.
* unsubscribe_all() resets the registry to dicts. It set a list, so the next
  subscribe() raised TypeError and a second unsubscribe_all() AttributeError.
* subscriptions and sets get channel_metadata, user_metadata, membership and
  file_message methods. The registry callback called methods that did not
  exist, so the sync message worker raised on the first App Context or file
  event.
* subscription.add_listener() calls SubscribeCallback listeners with
  (pubnub, event) like the client does. It raised TypeError.
* PubNubUserMetadata sets _type, it set the unused _types.
* message action events expose event ("added" or "removed").

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ging

* get_message_actions sends end when start is set, limit accepts int or str.
* pubnub.reconnect() calls the subscription manager and no longer raises
  AttributeError. Added pubnub.disconnect().
* asyncio get_subscribed_channels(), get_subscribed_channel_groups() and
  unsubscribe_all() work before the first subscribe (PNContext starts empty).
* if_matches_etag() no longer leaks the If-Match header into later requests
  (the headers dict was shared by the class).
* total_count=True in MembershipIncludes and MemberIncludes requests a count.
  The two include_object cassettes now record count=True.
* parse_token() raises PubNubException for every malformed token.
* grant() counts delete as a flag.
* fetch_messages items parse custom_message_type.
* setup.py: aiohttp>=3.10.11, the old range did not overlap the dev pin.

Adds offline regression tests in tests/unit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pubnub-snyk-universal-prd

pubnub-snyk-universal-prd Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

The example passed start below end. The SDK dropped end, so the call worked by
accident. Now that get_message_actions sends both bounds the service answers
HTTP 400 "Start must be greater than or equal to end". start is the newer bound
(exclusive) and end the older bound (inclusive).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@parfeon parfeon left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Mostly looks good but still had some small questions.

def limit(self, limit: str) -> 'GetMessageActions':
assert isinstance(limit, str)
self._limit = limit
assert isinstance(limit, (str, int)) and not isinstance(limit, bool)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isn't our current contract according to the docs is str?

@techwritermat techwritermat Nov 16, 2026 •

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.

limit() accepts only str again (960d1ce). I had widened the contract without need. The end fix in this file stays, and the unit test now checks that an int raises AssertionError.

Comment thread pubnub/pubnub_core.py Outdated
itself, so there this call does nothing.
"""
self._validate_subscribe_manager_enabled()
return self._subscription_manager.reconnect()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This will work only for NativeSubscriptionManager and not implemented for EventEngineSubscriptionManager (pubnub_asyncio)

@techwritermat techwritermat Nov 16, 2026 •

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.

You are right, a silent no-op that claims to work is wrong. I did not add a real reconnect to the event engine manager, because the state machine does not support it safely today:

  • The reconnecting states can read context.reason in on_enter before anything has set it.
  • Those states use the retry policy. With PNReconnectionPolicy.NONE they give up at once, so reconnect() would never reconnect.
  • HeartbeatDisconnectEvent has no suppress_leave, but the heartbeat disconnect transitions read it.

So EventEngineSubscriptionManager now raises PubNubException from both reconnect() and disconnect(), through one helper in PubNubCore (960d1ce). The old no-op came from the empty base SubscriptionManager.reconnect(). @abstractmethod is not enforced there on Python 3, because __metaclass__ has no effect. set_state on this manager behaves as before. A real implementation fits a separate change.

Comment thread pubnub/pubnub_core.py Outdated
Comment on lines +424 to +427
if not hasattr(self._subscription_manager, 'disconnect'):
raise PubNubException(
errormsg="disconnect() is not supported by %s" % type(self._subscription_manager).__name__)
return self._subscription_manager.disconnect()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Situation similar to the reconnect. Should we add same exception for reconnect?

@techwritermat techwritermat Nov 16, 2026 •

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.

Yes. reconnect() and disconnect() now raise the same PubNubException for a manager that does not support them (960d1ce).

Comment thread pubnub/workers.py Outdated
Comment on lines +43 to +47
@staticmethod
def _set_origin(result, channel, subscription):
# subscription and subscription set listeners match App Context events by these attributes
result.channel = channel
result.subscription = subscription

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm curious, why we can't follow the same pattern as we have with PNSignalMessageResult, PNMessageActionResult, and PNFileMessageResult for PNChannelMetadataResult, PNUUIDMetadataResult, and PNMembershipResult constructors where channel and subscription_match passed as one of the constructor arguments?

@techwritermat techwritermat Nov 16, 2026 •

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.

There is no good reason, I should have used the constructors. Fixed in 960d1ce. PNChannelMetadataResult, PNUUIDMetadataResult and PNMembershipResult now take channel and subscription as keyword-only arguments, default None, like PNMessageActionResult. Existing callers keep working. The worker passes both and _set_origin is gone.

"request": {
"method": "PATCH",
"uri": "https://ps.pndsn.com/v2/objects/{PN_KEY_SUBSCRIBE}/uuids/someuuid/channels?include=custom%2Cstatus%2Ctype%2CtotalCount%2Cchannel%2Cchannel.custom%2Cchannel.type%2Cchannel.status",
"uri": "https://ps.pndsn.com/v2/objects/{PN_KEY_SUBSCRIBE}/uuids/someuuid/channels?include=custom%2Cstatus%2Ctype%2CtotalCount%2Cchannel%2Cchannel.custom%2Cchannel.type%2Cchannel.status&count=True",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why count=True had to be added? Also why True and not true?
REST API docs say that by default it should be omitted.

@techwritermat techwritermat Nov 16, 2026 •

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.

count is still omitted by default. The SDK sends it only when the caller asks for a total count.

On master, MembershipIncludes(total_count=True) and MemberIncludes(total_count=True) only add totalCount to include. The service ignores that, so no total came back. The original recordings of these two tests show it: totalCount appears in the request and in no response. This PR also sends count when total_count=True is set, as include_total_count(True) already did. The two tests use total_count=True, so their recorded requests changed.

True is not new. ObjectsEndpoint has sent count=True since v4.8.0, and the service accepts it. native_sync/objects_v2/channel/get_all_channel.json has totalCount in its response. I agree lowercase true is the documented form. I would not change the serialization of an existing parameter in this PR, because 12 cassettes record count=True. I can open a follow-up that switches the objects endpoints to true and updates them. Does that work for you?

* get_message_actions.limit() accepts str only again, the contract stays as documented.
* reconnect() and disconnect() raise the same PubNubException on a subscription
  manager that does not support them. The asyncio event engine manager used to
  inherit an empty reconnect() that did nothing silently. set_state on that manager
  keeps its behaviour and no longer goes through reconnect().
* PNChannelMetadataResult, PNUUIDMetadataResult and PNMembershipResult take channel
  and subscription as constructor arguments like the other subscribe results,
  the worker no longer sets them afterwards.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@techwritermat

Copy link
Copy Markdown
Contributor Author

@pubnub-release-bot release

@techwritermat
techwritermat merged commit 9af9120 into master Nov 20, 2026
13 checks passed
@techwritermat
techwritermat deleted the fix/sdk-bugs-from-docs-snippets branch November 20, 2026 08:38
@pubnub-release-bot

Copy link
Copy Markdown
Contributor

🚀 Release successfully completed 🚀

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.

3 participants