From e1deb543c446dc8f892e642eeb649c5279306d09 Mon Sep 17 00:00:00 2001 From: Yun Seongmin Date: Sat, 28 Nov 2026 15:06:36 +0900 Subject: [PATCH 1/2] Track watch resource version without a return type When Watch cannot find the return type of the list function (no return annotation and no ":rtype:" docstring, e.g. a lambda wrapper around a generated list function), unmarshal_event returned the raw event before recording its resourceVersion. Watch.resource_version stayed at the initial value, even across BOOKMARK events, so Watch reconnected from the initial version, replayed events and raised 410 Gone once that version expired; SharedInformer, which copies it, re-listed. Record the resourceVersion from the raw event dict, sharing the helper with the deserialize=False path. Events are still returned unchanged. As with typed list functions, such a watch started without resource_version and timeout_seconds now reconnects from the last event's version when the server closes the stream instead of ending, and raises ApiException(410) if that version has expired. Add a test that streams through a lambda wrapper and checks the tracked resource version and the version used to reconnect. --- kubernetes/watch/watch.py | 24 +++++++++++++--------- kubernetes/watch/watch_test.py | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/kubernetes/watch/watch.py b/kubernetes/watch/watch.py index f659357c92..0a03a3a522 100644 --- a/kubernetes/watch/watch.py +++ b/kubernetes/watch/watch.py @@ -141,6 +141,16 @@ def get_watch_argument_name(self, func): else: return 'watch' + def _track_raw_resource_version(self, event): + # Record the resource version of an event that was not + # deserialized, so that a reconnect resumes from the last event. + raw = event.get('object') if isinstance(event, dict) else None + metadata = raw.get('metadata') if isinstance(raw, dict) else None + rv = metadata.get('resourceVersion') \ + if isinstance(metadata, dict) else None + if rv and event.get('type') != 'ERROR': + self.resource_version = rv + def unmarshal_event(self, data, return_type): if not data or data.isspace(): return None @@ -149,6 +159,9 @@ def unmarshal_event(self, data, return_type): js['raw_object'] = js['object'] if not return_type: + # The object stays a raw dict, e.g. for a lambda wrapper + # around a list function; still track its resource version. + self._track_raw_resource_version(js) return js if js['type'] == 'BOOKMARK': @@ -250,16 +263,7 @@ def stream(self, func, *args, **kwargs): # Blank lines are not events. event = json.loads(line) \ if line and not line.isspace() else None - # Track the resource version from the raw dict - # so that a reconnect resumes from the last event. - raw = event.get('object') \ - if isinstance(event, dict) else None - metadata = raw.get('metadata') \ - if isinstance(raw, dict) else None - rv = metadata.get('resourceVersion') \ - if isinstance(metadata, dict) else None - if rv and event.get('type') != 'ERROR': - self.resource_version = rv + self._track_raw_resource_version(event) if isinstance(event, dict) \ and event['type'] == 'ERROR': # 'object' of an ERROR event is never diff --git a/kubernetes/watch/watch_test.py b/kubernetes/watch/watch_test.py index 72cfc41f82..af2bd67f05 100644 --- a/kubernetes/watch/watch_test.py +++ b/kubernetes/watch/watch_test.py @@ -882,6 +882,43 @@ def test_watch_with_deserialize_false_tracks_resource_version(self): ]) self.assertEqual("4", w.resource_version) + def test_watch_without_return_type_tracks_resource_version(self): + """A list function without a return type, e.g. a lambda wrapper.""" + first_resp = Mock() + first_resp.stream = Mock(return_value=[ + '{"type": "ADDED", "object": {"metadata": {"name": "test1", ' + '"resourceVersion": "2"}}}\n', + '{"type": "BOOKMARK", "object": {"metadata": ' + '{"resourceVersion": "3"}}}\n', + '{"type": "MODIFIED", "object": {"metadata": {"name": "test1", ' + '"resourceVersion": ""}}}\n', + ]) + second_resp = Mock() + second_resp.stream = Mock(return_value=[ + '{"type": "DELETED", "object": {"metadata": {"name": "test1", ' + '"resourceVersion": "4"}}}\n', + ]) + fake_api = Mock() + fake_api.get_namespaces = Mock(side_effect=[first_resp, second_resp]) + fake_api.get_namespaces.__doc__ = ':rtype: V1NamespaceList' + + w = Watch() + events = [] + for e in w.stream(lambda **kw: fake_api.get_namespaces(**kw), + resource_version="1"): + events.append(e) + if e['type'] == 'DELETED': + w.stop() + + self.assertEqual(['ADDED', 'BOOKMARK', 'MODIFIED', 'DELETED'], + [e['type'] for e in events]) + self.assertEqual("test1", events[0]['object']['metadata']['name']) + fake_api.get_namespaces.assert_has_calls([ + call(_preload_content=False, watch=True, resource_version="1"), + call(_preload_content=False, watch=True, resource_version="3"), + ]) + self.assertEqual("4", w.resource_version) + def test_watch_with_deserialize_false_raises_on_error_event(self): """410 retries once from the last event's RV; ERROR RV is ignored.""" for code, expected_rvs in ((410, ["1", "5"]), (500, ["1"])): From 8c38617552993cd5a209b2514d676a34eda7f8aa Mon Sep 17 00:00:00 2001 From: Yun Seongmin Date: Sat, 28 Nov 2026 15:30:32 +0900 Subject: [PATCH 2/2] Request watch bookmarks from SharedInformer SharedInformer never set allow_watch_bookmarks on its watch requests, so the API server sent no BOOKMARK events. BOOKMARK handlers never ran, and a watch with a narrow namespace or selector kept the resource version of the last list. When such a quiet watch reconnected after the server had dropped that version from its watch history, it got 410 Gone and re-listed every object, firing MODIFIED for each of them. Set allow_watch_bookmarks=True on every watch request the informer opens. The list requests are unchanged. Watch already records the resource version of a BOOKMARK event, so the informer now resumes from it, and registered BOOKMARK handlers start to receive the raw bookmark object. Add a unit test that runs the real Watch over typed and dict list responses and a list function without a return type, and checks the watch arguments, the BOOKMARK handler and the resource version of the next watch. --- kubernetes/informer/informer.py | 13 +++++-- kubernetes/test/test_informer.py | 64 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 3 deletions(-) diff --git a/kubernetes/informer/informer.py b/kubernetes/informer/informer.py index 4272480fb5..95ede474a7 100644 --- a/kubernetes/informer/informer.py +++ b/kubernetes/informer/informer.py @@ -85,8 +85,9 @@ class SharedInformer: ---------- list_func: Bound API method used for the initial list **and** as the watch - source. It must accept a watch keyword argument (e.g. - CoreV1Api().list_namespaced_pod). + source. It must accept the same keyword arguments as a generated + list function, including watch-only ones such as watch and + allow_watch_bookmarks (e.g. CoreV1Api().list_namespaced_pod). namespace: Kubernetes namespace to watch. Pass None for cluster-scoped or all-namespace list functions. @@ -145,7 +146,8 @@ def add_event_handler(self, event_type, handler): :data:`BOOKMARK` or :data:`ERROR`. handler: Callable invoked with the event object (or the raw exception for - ERROR events). + ERROR events). BOOKMARK handlers receive the raw bookmark dict, + whose ``metadata.resourceVersion`` is the new resource version. """ if event_type not in self._handlers: raise ValueError( @@ -302,6 +304,11 @@ def _run_loop(self): self._watch = Watch() kw = self._build_kwargs() kw["resource_version"] = self._resource_version + # Ask for BOOKMARK events so that the resource version keeps + # advancing while no matching object changes. Otherwise, once + # other changes push that version out of the server's watch + # history, a reconnect gets 410 Gone and forces a full re-list. + kw["allow_watch_bookmarks"] = True # When a resync period is configured, set a matching server-side # watch timeout so that the stream exits after resync_period seconds # even if no events arrive. Without this, a quiet period longer diff --git a/kubernetes/test/test_informer.py b/kubernetes/test/test_informer.py index 387f296848..a7309ea6e9 100644 --- a/kubernetes/test/test_informer.py +++ b/kubernetes/test/test_informer.py @@ -14,6 +14,7 @@ """Unit tests for kubernetes.informer.""" +import json import threading import time import unittest @@ -494,6 +495,69 @@ def fake_stream(func, **kw): self.assertEqual(informer._resource_version, "30") + def _run_bookmark_watch(self, rtype, list_resp, bookmark): + """Run the informer with the real Watch; return it and its requests. + + The first watch yields *bookmark* and then drops; the informer is + stopped when it watches again. *rtype* is the list function's + ``:rtype:``. + """ + from urllib3.exceptions import ProtocolError + + calls = [] + + def list_func(**kw): + calls.append(kw) + if not kw.get("watch"): + return list_resp + if len(calls) == 2: + def stream(*args, **kwargs): + yield json.dumps( + {"type": BOOKMARK, "object": bookmark}) + "\n" + raise ProtocolError("Connection broken") + return MagicMock(stream=stream) + informer._stop_event.set() + informer._watch.stop() + return MagicMock() + list_func.__doc__ = rtype + + informer = SharedInformer(list_func=list_func) + bookmarks = [] + informer.add_event_handler(BOOKMARK, bookmarks.append) + informer.start() + informer._thread.join(timeout=3) + self.assertFalse(informer._thread.is_alive()) + return calls, bookmarks + + def test_watch_requests_bookmarks_and_resumes_from_bookmark(self): + """Watch requests ask for bookmarks; after a BOOKMARK and a dropped + connection the informer re-watches from the bookmark's RV without + re-listing, for typed and dict list responses and for a list + function without a return type. + """ + bookmark = {"kind": "Pod", "apiVersion": "v1", + "metadata": {"resourceVersion": "10"}} + cases = ( + ("typed", ":rtype: V1PodList", + MagicMock(items=[], metadata=MagicMock(resource_version="5"))), + ("dict", ":rtype: object", + {"metadata": {"resourceVersion": "5"}, "items": []}), + ("untyped", None, + {"metadata": {"resourceVersion": "5"}, "items": []}), + ) + for name, rtype, list_resp in cases: + with self.subTest(name): + calls, bookmarks = self._run_bookmark_watch( + rtype, list_resp, bookmark) + + self.assertEqual(bookmarks, [bookmark]) + self.assertEqual(len(calls), 3) + self.assertEqual(calls[0], {}) + for kw, rv in ((calls[1], "5"), (calls[2], "10")): + self.assertTrue(kw["watch"]) + self.assertIs(kw.get("allow_watch_bookmarks"), True) + self.assertEqual(kw["resource_version"], rv) + def test_resync_period_triggers_full_list(self): """A full List call must be made to the API server on every resync_period.