diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 60ea68cdaf..e9dbae53ff 100755 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -93,6 +93,7 @@ import time import urllib.request import urllib.error +import urllib.parse from datetime import datetime, timezone from pathlib import Path @@ -554,7 +555,7 @@ def summarize_cap(sessions, active_ids, now_ms): return len(roots), active, max(0, CAP - active) -def _server_get(path): +def _server_get(path, *, include_envelope=False, raise_http_errors=False): """GET a JSON document from the OpenCode server, or None on any failure (missing auth file, server down, non-JSON body).""" try: @@ -571,37 +572,48 @@ def _server_get(path): try: with urllib.request.urlopen(req, timeout=15) as res: data = json.loads(res.read() or "null") + except urllib.error.HTTPError: + if raise_http_errors: + raise + return None except Exception: return None - if isinstance(data, dict) and "data" in data: + if not include_envelope and isinstance(data, dict) and "data" in data: data = data["data"] return data -SESSION_FETCH_LIMITS = (1000, 10000, 100000) +SESSION_FETCH_LIMIT = 200 def fetch_sessions(): """The server's COMPLETE session list (GET /api/session), or None when completeness cannot be proven. - The endpoint truncates at 50 entries by default (#4757, verified - live 2026-11-07). It honours `limit` — ?limit=1000 returns 1000 - rows — but NOT `offset`: an offset page repeats the first page, - so offset pagination cannot prove completeness here. Read with - an escalating limit instead: the first read whose count is - BELOW the requested limit is the whole list by construction. - If every read comes back exactly at its limit, the list may - still be truncated, so the fetch fails closed (None) rather - than let a partial list undercount the cap or make a bound - session read as gone.""" - for limit in SESSION_FETCH_LIMITS: - data = _server_get(f"/api/session?limit={limit}") - if not isinstance(data, list): + The endpoint caps `limit` at 200 and exposes an opaque `cursor.next` + for subsequent pages. A failed HTTP response is raised so callers + cannot mistake an unreadable list for an empty or incomplete one. + Transport/auth failures that do not produce an HTTP response remain + represented by None, matching the other optional server reads.""" + sessions = [] + cursor = None + while True: + query = {"limit": SESSION_FETCH_LIMIT} + if cursor: + query["cursor"] = cursor + path = "/api/session?" + urllib.parse.urlencode(query) + response = _server_get( + path, include_envelope=True, raise_http_errors=True + ) + if not isinstance(response, dict) or not isinstance( + response.get("data"), list + ): return None - if len(data) < limit: - return data - return None + sessions.extend(response["data"]) + page_cursor = response.get("cursor") + cursor = page_cursor.get("next") if isinstance(page_cursor, dict) else None + if not cursor: + return sessions def fetch_active_ids(): diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index 548cb06ec8..f5b1f24a53 100755 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -13,8 +13,10 @@ import json import tempfile import unittest +import urllib.error +import urllib.parse from pathlib import Path -from unittest.mock import patch +from unittest.mock import mock_open, patch _spec = importlib.util.spec_from_file_location( "poll", Path(__file__).resolve().parent / "poll.py" @@ -758,21 +760,26 @@ def test_non_dict_and_unclaimed_rows_are_skipped(self): class TestFetchSessions(unittest.TestCase): - """Fetch-layer completeness (#4757): /api/session truncates at 50 - by default and honours limit but not offset, so fetch_sessions - escalates the limit until a read comes back below it — and fails - closed (None) whenever completeness cannot be proven. + """Fetch-layer completeness: session list pages use cursor.next + and never request more than the server's 200-row cap. _server_get is stubbed; no server is touched.""" def stub_server(self, total, fail_on_call=None): calls = [] - def fake_get(path): + def fake_get(path, **_kwargs): calls.append(path) if fail_on_call is not None and len(calls) == fail_on_call: return None - limit = int(path.rsplit("limit=", 1)[1]) - return [{"id": f"ses_{i}"} for i in range(min(limit, total))] + query = urllib.parse.parse_qs(path.partition("?")[2]) + limit = int(query["limit"][0]) + start = int(query.get("cursor", ["0"])[0]) + page = [ + {"id": f"ses_{i}"} + for i in range(start, min(start + limit, total)) + ] + next_cursor = str(start + limit) if start + limit < total else None + return {"data": page, "cursor": {"next": next_cursor}} return fake_get, calls @@ -785,31 +792,37 @@ def run_fetch(self, total, **kw): finally: poll._server_get = original - def test_short_single_read_is_complete(self): + def test_short_single_page_is_complete(self): sessions, calls = self.run_fetch(3) self.assertEqual(len(sessions), 3) self.assertEqual(len(calls), 1) - def test_escalating_limit_finds_the_whole_list(self): - sessions, calls = self.run_fetch(2500) - self.assertEqual(len(sessions), 2500) - self.assertEqual(len(calls), 2) - - def test_count_exactly_at_a_limit_escalates(self): - sessions, calls = self.run_fetch(1000) - self.assertEqual(len(sessions), 1000) - self.assertEqual(len(calls), 2) + def test_more_than_200_sessions_follow_cursor_to_completion(self): + sessions, calls = self.run_fetch(450) + self.assertEqual(len(sessions), 450) + self.assertEqual( + [s["id"] for s in sessions], [f"ses_{i}" for i in range(450)] + ) + self.assertEqual(len(calls), 3) + for path in calls: + query = urllib.parse.parse_qs(path.partition("?")[2]) + self.assertLessEqual(int(query["limit"][0]), 200) + self.assertEqual(calls[0], "/api/session?limit=200") + self.assertIn("cursor=200", calls[1]) def test_failed_read_fails_closed(self): - sessions, _ = self.run_fetch(2500, fail_on_call=1) + sessions, _ = self.run_fetch(450, fail_on_call=1) self.assertIsNone(sessions) - sessions, _ = self.run_fetch(2500, fail_on_call=2) + sessions, _ = self.run_fetch(450, fail_on_call=2) self.assertIsNone(sessions) - def test_count_at_every_limit_fails_closed(self): - sessions, calls = self.run_fetch(10**9) - self.assertIsNone(sessions) - self.assertEqual(len(calls), len(poll.SESSION_FETCH_LIMITS)) + def test_http_error_is_not_swallowed_for_session_list(self): + error = urllib.error.HTTPError("url", 400, "Bad Request", {}, None) + with patch("builtins.open", mock_open(read_data='{"password":"pw"}')): + with patch.object(poll.urllib.request, "urlopen", side_effect=error): + with self.assertRaises(urllib.error.HTTPError) as raised: + poll._server_get("/api/session?limit=1000", raise_http_errors=True) + self.assertEqual(raised.exception.code, 400) class TestStaleBinding(unittest.TestCase):