From 47ab0717c5bd18fa8f757f06c9d0c0353719e2d4 Mon Sep 17 00:00:00 2001 From: Guillaume Lebedel Date: Fri, 30 Oct 2026 14:22:44 +0000 Subject: [PATCH 1/5] ci: publish stackone-ai using PyPI trusted publishing --- .github/RELEASING.md | 44 +++++++++++ .github/workflows/release.yaml | 130 ++++++++++++++++++++++++++++----- CLAUDE.md | 3 +- 3 files changed, 156 insertions(+), 21 deletions(-) create mode 100644 .github/RELEASING.md diff --git a/.github/RELEASING.md b/.github/RELEASING.md new file mode 100644 index 0000000..582c5fb --- /dev/null +++ b/.github/RELEASING.md @@ -0,0 +1,44 @@ +# Publishing stackone-ai + +Release Please prepares the version and changelog in a release pull request. +Merging that release PR into `main` creates the GitHub release, tests and builds +its exact commit, then publishes the tested wheel and source archive to PyPI. +Normal development PRs do not publish. Changes to the release workflow run the +same build checks on the PR without access to publishing credentials. + +## Configure PyPI before merging the publishing migration + +A PyPI project owner must open **Manage → Publishing → Add a new publisher → GitHub** +for `stackone-ai` and register these values: + +| Field | Value | +| --- | --- | +| Owner | `StackOneHQ` | +| Repository | `stackone-ai-python` | +| Workflow filename | `release.yaml` | +| Environment | `pypi` | + +Use the filename alone, without `.github/workflows/`. Keep the environment set to +`pypi`, even though PyPI labels that field optional. + +In GitHub repository settings, the `pypi` environment must allow deployment from +the **main branch only**, with no tag rules. This prevents an unreviewed branch +from replacing the publishing workflow and using the project's PyPI identity. +Keep any existing reviewer requirements. + +Publishing uses GitHub's short-lived identity, called **Trusted Publishing** by +PyPI. No new PyPI API token or GitHub secret is needed. The upload job has no +source checkout and installs no package dependencies. Only that job can request +the identity needed to upload, and it downloads artifacts from its own workflow run. + +## Release and verification + +Review and merge the release PR, then check the **Release Please** workflow. +The source commit must be on `main`, and its package version must match the +GitHub release. A failed test or build prevents uploading. Confirm both files +appear on PyPI after the publish job succeeds. + +Do not merge this migration until the PyPI publisher is configured. Keep the +existing token until the first successful publish through Trusted Publishing. +Then remove the unused `PYPI_API_TOKEN` secret and revoke its PyPI token after +checking that no other workflow uses it. diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 1395437..9b48ef9 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -1,6 +1,9 @@ name: Release Please on: + pull_request: + branches: [main] + paths: [.github/workflows/release.yaml] push: branches: - main @@ -17,12 +20,16 @@ permissions: jobs: release-please: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'StackOneHQ/stackone-ai-python' + timeout-minutes: 10 runs-on: ubuntu-latest permissions: contents: write pull-requests: write outputs: release_created: ${{ steps.release.outputs.release_created }} + release_sha: ${{ steps.release.outputs.sha }} + release_version: ${{ steps.release.outputs.version }} steps: - uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0 id: release @@ -63,33 +70,62 @@ jobs: git push fi - # Publishing lives in its own job so it can be gated. It previously ran in the - # release-please job with no dependency on CI at all: CI is a separate workflow, - # so a red main still merged the release PR and shipped to PyPI. The suite runs - # again here against the exact commit being published. - publish: + build: + name: Test and build release needs: release-please - if: ${{ needs.release-please.outputs.release_created }} + # PRs exercise packaging without running release-please or granting publish access. + if: >- + !cancelled() && + (github.event_name == 'pull_request' || needs.release-please.outputs.release_created == 'true') runs-on: ubuntu-latest - # Configure a required reviewer on this environment in the repository settings. - environment: pypi - permissions: - contents: read + timeout-minutes: 15 steps: - - name: Checkout repository + - name: Checkout release source uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: + ref: ${{ needs.release-please.outputs.release_sha || github.sha }} + fetch-depth: 0 persist-credentials: false - - name: Setup uv + - name: Verify release source + if: github.event_name == 'push' + env: + RELEASE_SHA: ${{ needs.release-please.outputs.release_sha }} + run: | + test "$(git rev-parse --verify 'HEAD^{commit}')" = "$RELEASE_SHA" + git merge-base --is-ancestor HEAD "$(git rev-parse --verify 'refs/remotes/origin/main^{commit}')" + + - name: Set up uv uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 with: python-version: "3.13" + enable-cache: false - - name: Setup pnpm + - name: Validate package metadata + id: package + env: + EVENT_NAME: ${{ github.event_name }} + RELEASE_VERSION: ${{ needs.release-please.outputs.release_version }} + run: | + uv --no-config run --no-project --python 3.13 python -I - <<'PYTHON' + import os + import tomllib + from pathlib import Path + + project = tomllib.loads(Path("pyproject.toml").read_text())["project"] + if project["name"] != "stackone-ai": + raise SystemExit("Unexpected package name") + version = project["version"] + if os.environ["EVENT_NAME"] == "push" and version != os.environ["RELEASE_VERSION"]: + raise SystemExit("Package version does not match the GitHub release") + with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output: + output.write(f"version={version}\n") + PYTHON + + - name: Set up pnpm uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 - - name: Setup Node + - name: Set up Node uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 22 @@ -99,12 +135,66 @@ jobs: uv sync --all-extras --locked pnpm install --frozen-lockfile - - name: Test the commit being published - run: uv run pytest + - name: Lint, type check, and test release source + run: | + uv run ruff check . + uv run ty check stackone_ai + uv run pytest + + - name: Build distributions + run: uv build --no-sources - - name: Build and publish package + - name: Verify wheel and source distribution installations env: - UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }} + PACKAGE_VERSION: ${{ steps.package.outputs.version }} run: | - uv build - uv publish + for artifact in dist/*.whl dist/*.tar.gz; do + uv --no-config run --isolated --no-project --with "$artifact" python -I - <<'PYTHON' + import os + from importlib.metadata import version + from stackone_ai import StackOneToolSet + assert version("stackone-ai") == os.environ["PACKAGE_VERSION"] + assert callable(StackOneToolSet) + print("Installed stackone-ai", version("stackone-ai")) + PYTHON + done + + - name: Upload tested distributions + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: | + dist/*.whl + dist/*.tar.gz + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish tested distributions + needs: [release-please, build] + if: >- + github.repository == 'StackOneHQ/stackone-ai-python' && + github.event_name == 'push' && github.ref == 'refs/heads/main' && + needs.release-please.outputs.release_created == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: + name: pypi + url: https://pypi.org/project/stackone-ai/ + permissions: + contents: read + id-token: write + steps: + - name: Set up uv + uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0 + with: + enable-cache: false + + - name: Download tested distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist + + - name: Publish with PyPI Trusted Publishing + run: uv publish --trusted-publishing always diff --git a/CLAUDE.md b/CLAUDE.md index ecb952f..0f8f283 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -200,7 +200,8 @@ version, and `feat!` signals a breaking change. `docs`, `chore` and `test` do no trigger a release. Merging the release PR updates `CHANGELOG.md`, creates the GitHub release, and -publishes to PyPI (requires the `PYPI_API_TOKEN` secret). +publishes to PyPI through Trusted Publishing. Configure the PyPI publisher and +GitHub environment as described in `.github/RELEASING.md`; no API token is needed. Publishing only ever happens there. There is no `make publish`: releases go out via release-please after a merge to main, never from a developer machine. From b269be139b25e6dff14a0f86af501028e55c84b3 Mon Sep 17 00:00:00 2001 From: Guillaume Lebedel Date: Wed, 25 Nov 2026 08:34:54 +0000 Subject: [PATCH 2/5] Isolate the shared account-listing test from unrelated HTTP clients --- tests/test_end_user_id.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/test_end_user_id.py b/tests/test_end_user_id.py index 0d9afed..82183c2 100644 --- a/tests/test_end_user_id.py +++ b/tests/test_end_user_id.py @@ -11,12 +11,13 @@ import json import logging import threading +from functools import partial from typing import Any import httpx import pytest -from stackone_ai.tools import McpToolDefinition, StackOneMcpTool +from stackone_ai.tools import McpToolDefinition, RateLimitRetryingClient, StackOneMcpTool from stackone_ai.toolset import StackOneToolSet from stackone_ai.types import StackOneAPIError, ToolParameters, ToolsetConfigError @@ -734,10 +735,10 @@ def result(self, timeout: float | None = None) -> Any: return super().result(timeout) monkeypatch.setattr(concurrent.futures, "Future", Listing) - calls: list[int] = [] + calls: list[tuple[str, str]] = [] - def handle(_self: Any, request: httpx.Request) -> httpx.Response: - calls.append(1) + def handle(request: httpx.Request) -> httpx.Response: + calls.append((request.method, str(request.url))) assert joined.wait(timeout=5) body = [ _account("a", shared=False, origin_username="user-a"), @@ -745,12 +746,15 @@ def handle(_self: Any, request: httpx.Request) -> httpx.Response: ] return httpx.Response(200, json=body, request=request) - monkeypatch.setattr(httpx.HTTPTransport, "handle_request", handle) + monkeypatch.setattr( + "stackone_ai.toolset.RateLimitRetryingClient", + partial(RateLimitRetryingClient, transport=httpx.MockTransport(handle)), + ) mcp = _GuardedMcp(monkeypatch, {"a": "user-a", "b": "user-b"}) toolset = StackOneToolSet(api_key="k") tools = toolset.fetch_tools(account_ids=["a", "b"]) assert sorted(t.name for t in tools) == ["tool_a", "tool_b"] - assert len(calls) == 1 + assert calls == [("GET", f"{toolset.base_url.rstrip('/')}/accounts")] assert sorted((h["x-account-id"], h.get("x-end-user-id", "")) for h in mcp.listed) == [ ("a", ""), ("a", "user-a"), From 78a9aacf29ecb88387f2e23eaeba0a4982941cce Mon Sep 17 00:00:00 2001 From: Guillaume Lebedel Date: Wed, 25 Nov 2026 08:42:11 +0000 Subject: [PATCH 3/5] Reuse the accounts listing when a sibling already resolved a refusal --- stackone_ai/toolset.py | 11 ++++------- tests/test_end_user_id.py | 29 ++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 1415764..2d11097 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -1015,7 +1015,7 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: accounts would otherwise be told only that the header does not match. """ try: - self._join_accounts_listing() + self._join_accounts_listing(account_id) except Exception as exc: # A rate limit is the key's, not the account's, and stays fatal to a fan-out. if is_rate_limited(exc): @@ -1023,16 +1023,13 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: raise refusal from exc return self._end_user_id(account_id) is not None - def _join_accounts_listing(self) -> None: - """Wait for the GET /accounts in flight, or make one: what it records is then current. - - Raises: - Exception: Whatever that GET /accounts failed with. - """ + def _join_accounts_listing(self, missing_end_user_for: str | None = None) -> None: with self._cache_lock: fetching = self._fetching_accounts sequence = 0 if fetching is None: + if missing_end_user_for is not None and missing_end_user_for in self._end_user_ids: + return self._accounts_sequence += 1 sequence = self._accounts_sequence fetching = self._fetching_accounts = concurrent.futures.Future() diff --git a/tests/test_end_user_id.py b/tests/test_end_user_id.py index 82183c2..ff24842 100644 --- a/tests/test_end_user_id.py +++ b/tests/test_end_user_id.py @@ -726,6 +726,7 @@ def guarded(_endpoint: str, headers: dict[str, str], **_kwargs: Any) -> list[Mcp def test_requests_refused_together_share_one_accounts_listing(self, monkeypatch): joined = threading.Event() + base_url = "https://same-listing.invalid" class Listing(concurrent.futures.Future): # type: ignore[type-arg] def result(self, timeout: float | None = None) -> Any: @@ -748,13 +749,13 @@ def handle(request: httpx.Request) -> httpx.Response: monkeypatch.setattr( "stackone_ai.toolset.RateLimitRetryingClient", - partial(RateLimitRetryingClient, transport=httpx.MockTransport(handle)), + partial(RateLimitRetryingClient, mounts={base_url: httpx.MockTransport(handle)}), ) mcp = _GuardedMcp(monkeypatch, {"a": "user-a", "b": "user-b"}) - toolset = StackOneToolSet(api_key="k") + toolset = StackOneToolSet(api_key="k", base_url=base_url) tools = toolset.fetch_tools(account_ids=["a", "b"]) assert sorted(t.name for t in tools) == ["tool_a", "tool_b"] - assert calls == [("GET", f"{toolset.base_url.rstrip('/')}/accounts")] + assert calls == [("GET", f"{base_url}/accounts")] assert sorted((h["x-account-id"], h.get("x-end-user-id", "")) for h in mcp.listed) == [ ("a", ""), ("a", "user-a"), @@ -762,6 +763,28 @@ def handle(request: httpx.Request) -> httpx.Response: ("b", "user-b"), ] + def test_a_delayed_refusal_reuses_the_end_user_a_sibling_just_found(self, monkeypatch): + body = [_account(account, shared=False, origin_username=f"user-{account}") for account in ("a", "b")] + calls = _accounts_response(monkeypatch, body, body) + mcp = _GuardedMcp(monkeypatch, {"a": "user-a", "b": "user-b"}) + toolset = StackOneToolSet(api_key="k") + guard = mcp._guard + + def delay_b_until_a_retries(headers: dict[str, str]) -> None: + if headers["x-account-id"] == "b" and "x-end-user-id" not in headers: + toolset.fetch_tools(account_ids=["a"]) + guard(headers) + + monkeypatch.setattr(mcp, "_guard", delay_b_until_a_retries) + assert [t.name for t in toolset.fetch_tools(account_ids=["b"])] == ["tool_b"] + assert [(h["x-account-id"], h.get("x-end-user-id")) for h in mcp.listed] == [ + ("b", None), + ("a", None), + ("a", "user-a"), + ("b", "user-b"), + ] + assert len(calls) == 1 + def test_a_lookup_joins_the_latest_accounts_listing_still_in_flight(self, monkeypatch): """An older listing finishing must not stop a lookup joining a newer one in flight.""" joined = threading.Event() From 2359c0d5a574d5ba96cc51e7e8b6575e8a48fff6 Mon Sep 17 00:00:00 2001 From: Guillaume Lebedel Date: Mon, 30 Nov 2026 15:08:26 +0000 Subject: [PATCH 4/5] Reuse a sibling's end user only from a listing started after the request A refused request reused any end user recorded since it was sent, so a GET /accounts that started before the request, and finished while it was in flight, could hand back an end user older than a relink the refusal reflects. The retry was then refused again and the stale mapping kept. The look-up now notes the last listing started when its request is made, and reuses a recorded end user only from a listing started after that; otherwise it lists the accounts again. Co-Authored-By: Claude Opus 5.5 --- stackone_ai/tools.py | 10 ++++++---- stackone_ai/toolset.py | 36 +++++++++++++++++++++++++++-------- tests/test_end_user_id.py | 40 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 12 deletions(-) diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 44bedcb..a226bf2 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -1431,9 +1431,10 @@ class StackOneMcpTool(StackOneTool): # Looked up per request, so a tool keeps up with a later GET /accounts and with # set_account_id(). _end_user_id_of: Callable[[str], str | None] | None = PrivateAttr(default=None) - # Also set by the toolset: given the API's refusal of a request sent without an end - # user, looks the account's end user up, and says whether there now is one to retry with. - _look_up_end_user: Callable[[str, Exception], bool] | None = PrivateAttr(default=None) + # Also set by the toolset: called as a request is made, it returns the look-up that, given + # the API's refusal of that request for want of an end user, looks the account's end user + # up, and says whether there now is one to retry with. + _end_user_look_up: Callable[[], Callable[[str, Exception], bool]] | None = PrivateAttr(default=None) def __init__( self, @@ -1536,10 +1537,11 @@ def call() -> JsonDict: ) account_id = self._account_id + look_up = self._end_user_look_up() if self._end_user_look_up is not None else None without_end_user = ( [account_id] if account_id is not None and self._recorded_end_user_id() is None else [] ) - return retry_for_end_user(call, without_end_user, self._look_up_end_user) + return retry_for_end_user(call, without_end_user, look_up) @dataclass(frozen=True) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 2d11097..4d3e3a7 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -499,11 +499,12 @@ def _catalog( def _fetch_for_account( account: str | None, ) -> list[_Listing]: + look_up = self._end_user_look_up() without_end_user = [account] if account is not None and self._end_user_id(account) is None else [] listed = retry_for_end_user( lambda: fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout), without_end_user, - self._look_up_end_user, + look_up, ) return [(tool_def, account, endpoint) for tool_def in listed] @@ -580,8 +581,9 @@ def _list() -> list[_Listing]: listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(None), timeout=self._timeout) return [(tool_def, None, endpoint) for tool_def in listed] + look_up = self._end_user_look_up() without_end_user = [account for account in account_scope if self._end_user_id(account) is None] - listings = retry_for_end_user(_list, without_end_user, self._look_up_end_user) + listings = retry_for_end_user(_list, without_end_user, look_up) with self._cache_lock: if generation == self._cache_generation: @@ -1006,16 +1008,27 @@ def _request_accounts(self, sequence: int) -> list[JsonDict]: self._end_user_ids_sequence = sequence return accounts - def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: + def _end_user_look_up(self) -> Callable[[str, Exception], bool]: + """The end-user look-up for a request about to be made: it may reuse the end user of a + GET /accounts started from now on, but not of one started earlier, which can predate a + relink the refusal reflects. + """ + with self._cache_lock: + listed_after = self._accounts_sequence + return functools.partial(self._look_up_end_user, listed_after=listed_after) + + def _look_up_end_user(self, account_id: str, refusal: Exception, listed_after: int | None = None) -> bool: """Given the API's refusal of an account's request for want of its end user, list the accounts and say whether that one now has an end user recorded to retry with. - A GET /accounts already in flight is joined rather than another made. If it fails, the + A GET /accounts already in flight is joined rather than another made. One that already + recorded the account's end user is reused instead when it started after ``listed_after``, + the last listing started before the refused request was made. If the listing fails, the refusal is raised with that failure as its cause: a key without the scope to list accounts would otherwise be told only that the header does not match. """ try: - self._join_accounts_listing(account_id) + self._join_accounts_listing(account_id, listed_after) except Exception as exc: # A rate limit is the key's, not the account's, and stays fatal to a fan-out. if is_rate_limited(exc): @@ -1023,12 +1036,19 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: raise refusal from exc return self._end_user_id(account_id) is not None - def _join_accounts_listing(self, missing_end_user_for: str | None = None) -> None: + def _join_accounts_listing( + self, missing_end_user_for: str | None = None, listed_after: int | None = None + ) -> None: with self._cache_lock: fetching = self._fetching_accounts sequence = 0 if fetching is None: - if missing_end_user_for is not None and missing_end_user_for in self._end_user_ids: + if ( + missing_end_user_for is not None + and listed_after is not None + and self._end_user_ids_sequence > listed_after + and missing_end_user_for in self._end_user_ids + ): return self._accounts_sequence += 1 sequence = self._accounts_sequence @@ -1197,7 +1217,7 @@ def _create_tool( served_name=served_name, ) tool._end_user_id_of = self._end_user_id - tool._look_up_end_user = self._look_up_end_user + tool._end_user_look_up = self._end_user_look_up return tool def _normalize_schema_properties(self, schema: dict[str, Any]) -> dict[str, Any]: diff --git a/tests/test_end_user_id.py b/tests/test_end_user_id.py index ff24842..4a6d969 100644 --- a/tests/test_end_user_id.py +++ b/tests/test_end_user_id.py @@ -785,6 +785,46 @@ def delay_b_until_a_retries(headers: dict[str, str]) -> None: ] assert len(calls) == 1 + def test_a_refusal_lists_again_rather_than_reuse_a_listing_older_than_its_request(self, monkeypatch): + """A listing started before the refused request was sent can predate a relink, so its + end user is not reused: the refusal makes a fresh GET /accounts.""" + started, release = threading.Event(), threading.Event() + bodies = [ + [_account("b", shared=False, origin_username="user-old")], + [_account("b", shared=False, origin_username="user-new")], + ] + calls: list[int] = [] + + def handle(_self: Any, request: httpx.Request) -> httpx.Response: + index = len(calls) + calls.append(index) + if index == 0: + started.set() + assert release.wait(timeout=5) + return httpx.Response(200, json=bodies[index], request=request) + + monkeypatch.setattr(httpx.HTTPTransport, "handle_request", handle) + mcp = _GuardedMcp(monkeypatch, {"b": "user-new"}) + toolset = StackOneToolSet(api_key="k") + older = threading.Thread(target=toolset.fetch_accounts) + older.start() + assert started.wait(timeout=5) + guard = mcp._guard + + def finish_the_older_listing_while_b_is_in_flight(headers: dict[str, str]) -> None: + if headers["x-account-id"] == "b" and "x-end-user-id" not in headers: + release.set() + older.join(timeout=5) + guard(headers) + + monkeypatch.setattr(mcp, "_guard", finish_the_older_listing_while_b_is_in_flight) + assert [t.name for t in toolset.fetch_tools(account_ids=["b"])] == ["tool_b"] + assert [(h["x-account-id"], h.get("x-end-user-id")) for h in mcp.listed] == [ + ("b", None), + ("b", "user-new"), + ] + assert len(calls) == 2 + def test_a_lookup_joins_the_latest_accounts_listing_still_in_flight(self, monkeypatch): """An older listing finishing must not stop a lookup joining a newer one in flight.""" joined = threading.Event() From 8d7a81d5f948fb91baf15e4215258e0272b76c35 Mon Sep 17 00:00:00 2001 From: Guillaume Lebedel Date: Mon, 30 Nov 2026 15:19:55 +0000 Subject: [PATCH 5/5] Join an accounts listing only if it started after the refused request A refusal still joined a GET /accounts in flight that started before the request, whose answer can predate a relink just as a finished one can. It now starts a fresh listing instead. The look-up's marker is taken once per fetch_tools fan-out, so accounts refused together still share one listing. Co-Authored-By: Claude Opus 5.5 --- stackone_ai/toolset.py | 22 +++++++++++++------- tests/test_end_user_id.py | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 4d3e3a7..50478c2 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -260,6 +260,8 @@ def __init__( # The GET /accounts in flight, if any: an account's end user is looked up by joining # it rather than making another. self._fetching_accounts: concurrent.futures.Future[list[JsonDict]] | None = None + # The sequence (below) that GET /accounts started as. + self._fetching_accounts_sequence = 0 self._include_non_shared = include_non_shared # Bumped at the start of every fetch_accounts() call, so two overlapping calls — # fetch_accounts() racing discovery, say — are ordered by when they started @@ -495,11 +497,12 @@ def _catalog( endpoint = f"{self.base_url.rstrip('/')}/mcp" if mode: endpoint = f"{endpoint}?tool-mode={mode}" + # One for the whole fan-out, so accounts refused together share one GET /accounts. + look_up = self._end_user_look_up() def _fetch_for_account( account: str | None, ) -> list[_Listing]: - look_up = self._end_user_look_up() without_end_user = [account] if account is not None and self._end_user_id(account) is None else [] listed = retry_for_end_user( lambda: fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout), @@ -909,6 +912,7 @@ def fetch_accounts(self) -> list[JsonDict]: sequence = self._accounts_sequence fetching: concurrent.futures.Future[list[JsonDict]] = concurrent.futures.Future() self._fetching_accounts = fetching + self._fetching_accounts_sequence = sequence return self._settle_accounts(fetching, sequence) def _settle_accounts( @@ -1009,9 +1013,9 @@ def _request_accounts(self, sequence: int) -> list[JsonDict]: return accounts def _end_user_look_up(self) -> Callable[[str, Exception], bool]: - """The end-user look-up for a request about to be made: it may reuse the end user of a - GET /accounts started from now on, but not of one started earlier, which can predate a - relink the refusal reflects. + """The end-user look-up for requests about to be made: it may join or reuse a GET + /accounts started from now on, but not one started earlier, which can predate a relink + the refusal reflects. """ with self._cache_lock: listed_after = self._accounts_sequence @@ -1021,9 +1025,10 @@ def _look_up_end_user(self, account_id: str, refusal: Exception, listed_after: i """Given the API's refusal of an account's request for want of its end user, list the accounts and say whether that one now has an end user recorded to retry with. - A GET /accounts already in flight is joined rather than another made. One that already - recorded the account's end user is reused instead when it started after ``listed_after``, - the last listing started before the refused request was made. If the listing fails, the + A GET /accounts already in flight is joined rather than another made, and one that already + recorded the account's end user is reused, but only when it started after ``listed_after``, + the last listing started before the call that made the refused request: an older one can + predate a relink the refusal reflects, so another is made instead. If the listing fails, the refusal is raised with that failure as its cause: a key without the scope to list accounts would otherwise be told only that the header does not match. """ @@ -1041,6 +1046,8 @@ def _join_accounts_listing( ) -> None: with self._cache_lock: fetching = self._fetching_accounts + if listed_after is not None and self._fetching_accounts_sequence <= listed_after: + fetching = None sequence = 0 if fetching is None: if ( @@ -1053,6 +1060,7 @@ def _join_accounts_listing( self._accounts_sequence += 1 sequence = self._accounts_sequence fetching = self._fetching_accounts = concurrent.futures.Future() + self._fetching_accounts_sequence = sequence if sequence: with contextlib.suppress(Exception): self._settle_accounts(fetching, sequence) diff --git a/tests/test_end_user_id.py b/tests/test_end_user_id.py index 4a6d969..279df2b 100644 --- a/tests/test_end_user_id.py +++ b/tests/test_end_user_id.py @@ -825,6 +825,48 @@ def finish_the_older_listing_while_b_is_in_flight(headers: dict[str, str]) -> No ] assert len(calls) == 2 + def test_a_refusal_does_not_join_a_listing_older_than_its_request(self, monkeypatch): + """Nor is a listing still in flight joined when it started before the refused request.""" + started, release = threading.Event(), threading.Event() + + class Listing(concurrent.futures.Future): # type: ignore[type-arg] + def result(self, timeout: float | None = None) -> Any: + release.set() + return super().result(timeout) + + monkeypatch.setattr(concurrent.futures, "Future", Listing) + bodies = [ + [_account("b", shared=False, origin_username="user-old")], + [_account("b", shared=False, origin_username="user-new")], + ] + calls: list[int] = [] + + def handle(_self: Any, request: httpx.Request) -> httpx.Response: + index = len(calls) + calls.append(index) + if index == 0: + started.set() + assert release.wait(timeout=5) + return httpx.Response(200, json=bodies[index], request=request) + + monkeypatch.setattr(httpx.HTTPTransport, "handle_request", handle) + mcp = _GuardedMcp(monkeypatch, {"b": "user-new"}) + toolset = StackOneToolSet(api_key="k") + older = threading.Thread(target=toolset.fetch_accounts) + older.start() + assert started.wait(timeout=5) + try: + assert [t.name for t in toolset.fetch_tools(account_ids=["b"])] == ["tool_b"] + finally: + release.set() + older.join(timeout=5) + assert [(h["x-account-id"], h.get("x-end-user-id")) for h in mcp.listed] == [ + ("b", None), + ("b", "user-new"), + ] + assert len(calls) == 2 + assert toolset._end_user_id("b") == "user-new" + def test_a_lookup_joins_the_latest_accounts_listing_still_in_flight(self, monkeypatch): """An older listing finishing must not stop a lookup joining a newer one in flight.""" joined = threading.Event()