fix(tests): stop the partner suite writing to the real account store

`identity` binds `AUTH_DIR = SYSTEM_ROOT / "auth"` at import, so the
partners fixture's `setattr(paths, "SYSTEM_ROOT", tmp)` never reached it:
`save_user` wrote into the developer's own `data/system/auth/users.json`
and read it back. The suite had already deposited an `alice` account
there.

That also made `test_a_linked_sender_gets_their_own_private_history`
depend on who else happened to have an account. The first account in a
store is force-promoted to admin whatever role is asked for, and an
admin's scope *is* the shared pool — so on an empty store alice became
admin and "her private history" and "the shared pool" resolved to one
directory. It passed on a machine with existing accounts and on a full
run, and failed alone and on all four Python versions in CI (v1.5.17's
release commit is red for exactly this).

The fixture now redirects identity's file constants too, and `alice` is
saved after an admin so she is guaranteed non-admin — asserted, so the
precondition cannot rot silently. Product code is unaffected: the
behaviour under test was always correct.

Also collapses the three copies of the api_key reduction into one.
`_primary_api_key` (provider_runtime) is deleted and
`LLMConfig.get_api_key` delegates, both to `keypool.primary_api_key`,
which now treats an empty key as absent in either spelling so its list
and scalar branches agree. Equivalence checked across every configured
shape: "", None, [], [""], ["", "k"], "k", ["k"], ["k1", "k2"].

pytest 5284 passed (was 5276), pre-commit clean, ruff check + format
clean at CI's pinned 0.16.0.
This commit is contained in:
Bingxi Zhao (Frank)
2026-08-25 10:20:26 +08:00
parent bd80a4d28a
commit c600a507a4
8 changed files with 95 additions and 29 deletions

View File

@@ -8,6 +8,7 @@ from typing import Any
from urllib.parse import urlparse
from deeptutor.services.imagegen.config import ImagegenConfig
from deeptutor.services.keypool import primary_api_key
from deeptutor.services.model_selection import LLMSelection, apply_llm_selection_to_catalog
from deeptutor.services.provider_registry import (
NANOBOT_LLM_PROVIDERS,
@@ -596,12 +597,6 @@ def _as_api_key(value: Any) -> str | list[str]:
return _as_str(value)
def _primary_api_key(value: str | list[str]) -> str:
return (
value[0] if isinstance(value, list) and value else value if isinstance(value, str) else ""
)
def _to_headers(value: Any) -> dict[str, str]:
if isinstance(value, dict):
return {str(k): str(v) for k, v in value.items() if str(k).strip() and v is not None}
@@ -688,7 +683,7 @@ def _choose_resolved_provider(
explicit_spec = find_by_name(hint) if hint else None
detected_gateway = find_gateway(
provider_name=None,
api_key=_primary_api_key(api_key) or None,
api_key=primary_api_key(api_key),
api_base=api_base or None,
)
# Keep backward compatibility: old `binding=openai` should not block

View File

@@ -65,10 +65,13 @@ def primary_api_key(value: str | list[str] | None) -> str | None:
through would render as ``"['sk-a', 'sk-b']"`` in an ``Authorization``
header — a 401 whose cause is invisible. Reduce at the boundary instead,
and reduce in one place so every such boundary agrees which key is first.
An empty key is not a key, in either shape: ``""``, ``[]`` and ``[""]``
all answer ``None``, so a caller can test the result rather than having
to know which spelling the configuration happened to use.
"""
if isinstance(value, list):
return value[0] if value else None
return value or None
first = value[0] if isinstance(value, list) and value else value
return first or None if isinstance(first, str) else None
__all__ = ["KeyPool", "primary_api_key"]

View File

@@ -126,10 +126,12 @@ class LLMConfig:
return replace(self, **(update or {}))
def get_api_key(self) -> str:
"""Return the API key string for provider consumers."""
if isinstance(self.api_key, list):
return self.api_key[0] if self.api_key else ""
return self.api_key
"""Return the API key string for provider consumers.
The empty string, not ``None``, because callers here test it for
truthiness and pass it straight into a provider argument.
"""
return primary_api_key(self.api_key) or ""
_LLM_CONFIG_CACHE: LLMConfig | None = None

View File

@@ -46,7 +46,7 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> t
def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
"""Construct one provider, importing only the selected backend SDK."""
provider_name = llm_config.provider_name or llm_config.binding
primary_api_key = llm_config.get_api_key()
api_key = llm_config.get_api_key()
spec = find_by_name(provider_name)
backend = spec.backend if spec else "openai_compat"
@@ -68,14 +68,14 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
)
provider = build_codebuddy_provider(
api_key=primary_api_key or None,
api_key=api_key or None,
default_model=llm_config.model,
)
elif backend == "azure_openai":
from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider
provider = AzureOpenAIProvider(
api_key=primary_api_key,
api_key=api_key,
api_base=llm_config.effective_url or llm_config.base_url or "",
default_model=llm_config.model,
extra_headers=llm_config.extra_headers or None,
@@ -85,7 +85,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider
provider = AnthropicProvider(
api_key=primary_api_key or None,
api_key=api_key or None,
api_base=llm_config.effective_url or llm_config.base_url or None,
default_model=llm_config.model,
extra_headers=llm_config.extra_headers or None,

View File

@@ -22,9 +22,17 @@ def partners_root(tmp_path, monkeypatch) -> Path:
Everything the partners layer touches resolves through
``deeptutor.multi_user.paths`` — the partners data dir is anchored at the
admin workspace root and partner scopes are synthetic ``UserScope``s — so
patching that module is sufficient to keep tests off the real ``data/``.
patching that module covers the partners layer itself.
``identity`` is a second front, and patching ``paths`` does *not* reach it:
it binds ``AUTH_DIR = SYSTEM_ROOT / "auth"`` at import, so a later
``setattr`` on ``paths.SYSTEM_ROOT`` leaves its module-level file constants
pointing at the real ``data/system/auth/``. Any test that saves a user was
therefore writing into the developer's own account store, and reading it
back — which made the outcome depend on who already had an account there,
since the first account in a store is force-promoted to admin.
"""
from deeptutor.multi_user import paths
from deeptutor.multi_user import identity, paths
project_root = tmp_path
admin_root = (project_root / "data").resolve()
@@ -34,6 +42,13 @@ def partners_root(tmp_path, monkeypatch) -> Path:
monkeypatch.setattr(paths, "SYSTEM_ROOT", admin_root / "system")
monkeypatch.setattr(paths, "_path_services", {})
auth_dir = admin_root / "system" / "auth"
monkeypatch.setattr(identity, "AUTH_DIR", auth_dir)
monkeypatch.setattr(identity, "USERS_FILE", auth_dir / "users.json")
monkeypatch.setattr(identity, "SECRET_FILE", auth_dir / "auth_secret")
monkeypatch.setattr(identity, "LEGACY_USERS_FILE", project_root / "legacy_users.json")
monkeypatch.setattr(identity, "LEGACY_SECRET_FILE", project_root / "legacy_secret")
admin_root.mkdir(parents=True, exist_ok=True)
return admin_root / "partners"

View File

@@ -22,12 +22,21 @@ from tests.services.partners.scripts import finish
@pytest.fixture
def alice(partners_root):
"""A real account — identity is re-read from the user store on every turn."""
"""A real, **non-admin** account — identity is re-read on every turn.
The admin is saved first on purpose. The first account in a store is
force-promoted to admin regardless of the role asked for, and an admin's
scope *is* the shared pool — so an alice who happened to be first would
make "her private history" and "the shared pool" the same directory, and
every assertion that they differ would pass or fail on account order.
"""
from deeptutor.multi_user import identity
from deeptutor.services.partners.interaction import actor_for_account
identity.save_user("alice", "hash", "user")
return actor_for_account(identity.get_user("alice")["id"])
identity.save_user("root", "hash", "admin")
record = identity.save_user("alice", "hash", "user")
assert record["role"] == "user", "alice must not be the store's first account"
return actor_for_account(record["id"])
# ── code lifecycle ────────────────────────────────────────────
@@ -208,7 +217,6 @@ async def test_link_command_binds_the_sender_mid_conversation(partners_root, fak
@pytest.mark.asyncio
async def test_link_command_refuses_a_group_chat(partners_root, fake_orchestrator):
runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())
code = links.issue_link_code("ada", "u_alice").code

View File

@@ -2,7 +2,7 @@ from __future__ import annotations
import pytest
from deeptutor.services.keypool import KeyPool
from deeptutor.services.keypool import KeyPool, primary_api_key
def test_keypool_rotates_in_round_robin_order() -> None:
@@ -79,3 +79,30 @@ def test_keypool_prefers_the_soonest_recovering_key_when_all_are_cooling(
now["value"] = 20.0
assert pool.next() == "key-a"
@pytest.mark.parametrize(
("value", "expected"),
[
("sk-a", "sk-a"),
(["sk-a"], "sk-a"),
(["sk-a", "sk-b"], "sk-a"),
# An empty key is not a key, in either spelling — so a caller can test
# the result instead of knowing which shape the config happened to use.
("", None),
(None, None),
([], None),
([""], None),
],
)
def test_primary_api_key_reduces_every_configured_shape(value, expected) -> None:
assert primary_api_key(value) == expected
def test_llm_config_get_api_key_uses_the_same_reduction() -> None:
"""``LLMConfig.get_api_key`` is a ``-> str`` front door, not a second copy."""
from deeptutor.services.llm.config import LLMConfig
for value in ("sk-a", ["sk-a", "sk-b"], "", [], [""]):
config = LLMConfig(api_key=value, model="gpt-5")
assert config.get_api_key() == (primary_api_key(value) or "")

View File

@@ -48,15 +48,27 @@ const resolved = (toolCallId: string) =>
});
test("reasoning produced after a card becomes its own segment below it", () => {
const before = event("thinking", { call_id: "round-1" }, "planning a question");
const after = event("thinking", { call_id: "round-2" }, "grading their answer");
const before = event(
"thinking",
{ call_id: "round-1" },
"planning a question",
);
const after = event(
"thinking",
{ call_id: "round-2" },
"grading their answer",
);
const segments = extractMessageSegments([
before,
askUserCard("call-1"),
resolved("call-1"),
after,
event("content", { call_id: "round-2", call_kind: "agent_loop_round" }, "Correct!"),
event(
"content",
{ call_id: "round-2", call_kind: "agent_loop_round" },
"Correct!",
),
]);
assert.deepEqual(
@@ -78,7 +90,11 @@ test("the pre-card rounds stay with the top activity block", () => {
const leading = leadingTraceEvents(events, extractMessageSegments(events));
assert.deepEqual(leading, [before, askUserCard("call-1"), resolved("call-1")]);
assert.deepEqual(leading, [
before,
askUserCard("call-1"),
resolved("call-1"),
]);
});
test("a turn with no card keeps every event in the top block", () => {