fix(integration): align cancellation cleanup, image consent and Python formatting

This commit is contained in:
Bingxi Zhao (Frank)
2026-12-02 05:47:04 -05:00
parent 2530c10cad
commit 4a9e9bdd50
16 changed files with 384 additions and 154 deletions

View File

@@ -292,15 +292,20 @@ async def _start_api_services(app, application_container, cleanup, progress_port
from deeptutor.modules.services import module_service_callbacks
from deeptutor.runtime.background_leader import BackgroundLeaderSupervisor
from deeptutor.services.codex_auth.scheduler import CodexCatalogRefreshScheduler
catalog_scheduler = CodexCatalogRefreshScheduler()
background_supervisor = BackgroundLeaderSupervisor(
application_container.coordinator,
application_container.worker_id,
start_callbacks=[*module_service_callbacks("start", application_container), catalog_scheduler.start],
stop_callbacks=[*module_service_callbacks("stop", application_container), catalog_scheduler.stop],
start_callbacks=[
*module_service_callbacks("start", application_container),
catalog_scheduler.start,
],
stop_callbacks=[
*module_service_callbacks("stop", application_container),
catalog_scheduler.stop,
],
recovery_callback=application_container.recover_once,
control_callback=_handle_background_command,
renew_interval_seconds=application_container.settings.renew_interval_seconds,

View File

@@ -13,7 +13,6 @@ import re
import unicodedata
from deeptutor.core.assessment import Verdict
from deeptutor.learning.grading import numeric_equivalent
# Only strip known table layout tags. A generic <...> pattern also consumes

View File

@@ -1,6 +1,5 @@
"""Independent OpenAI Codex OAuth support for DeepTutor."""
from .scheduler import CodexCatalogRefreshScheduler
from .contracts import (
CatalogSnapshot,
CodexAuthError,
@@ -10,6 +9,7 @@ from .contracts import (
TokenClaims,
decode_codex_jwt,
)
from .scheduler import CodexCatalogRefreshScheduler
from .service import (
CodexOAuthService,
get_codex_oauth_service,

View File

@@ -13,13 +13,13 @@ import httpx
from .client_version import discover_client_version, max_stable_version, parse_stable_version
from .constants import (
CODEX_CLIENT_VERSION,
CODEX_CATALOG_HEADER_SCHEMA,
CODEX_OAUTH_ORIGINATOR,
CODEX_CLIENT_VERSION,
CODEX_FRESH_CACHE_SECONDS,
CODEX_MAX_CATALOG_BYTES,
CODEX_MAX_MODELS,
CODEX_MODELS_URL,
CODEX_OAUTH_ORIGINATOR,
CODEX_STALE_CACHE_SECONDS,
)
from .contracts import (
@@ -268,7 +268,9 @@ class CodexModelCatalog:
"Codex returned an invalid model catalog response.",
502,
)
snapshot = replace(cache, source="revalidated-cache", fetched_at=now, version_source=version_source)
snapshot = replace(
cache, source="revalidated-cache", fetched_at=now, version_source=version_source
)
self._store.commit_catalog_cache(snapshot)
return snapshot

View File

@@ -11,15 +11,14 @@ import httpx
from .constants import (
CODEX_GITHUB_LATEST_RELEASE_URL,
CODEX_GITHUB_MAX_RELEASE_BYTES,
CODEX_VERSION_TOTAL_TIMEOUT_SECONDS,
CODEX_MAX_VERSION_BYTES,
CODEX_NPM_LATEST_URL,
CODEX_STABLE_VERSION_PATTERN,
CODEX_VERSION_TIMEOUT_SECONDS,
CODEX_VERSION_TOTAL_TIMEOUT_SECONDS,
)
def parse_stable_version(value: str | None) -> tuple[int, int, int] | None:
if not isinstance(value, str) or not re.fullmatch(CODEX_STABLE_VERSION_PATTERN, value):
return None
@@ -35,15 +34,19 @@ def max_stable_version(*versions: str | None) -> str | None:
async def _source_version(http: httpx.AsyncClient, source: str) -> str | None:
url = CODEX_NPM_LATEST_URL if source == "npm" else CODEX_GITHUB_LATEST_RELEASE_URL
max_bytes = CODEX_MAX_VERSION_BYTES if source == "npm" else CODEX_GITHUB_MAX_RELEASE_BYTES
headers = {"Accept": "application/json"} if source == "npm" else {
"Accept": "application/vnd.github+json", "User-Agent": "DeepTutor"
}
headers = (
{"Accept": "application/json"}
if source == "npm"
else {"Accept": "application/vnd.github+json", "User-Agent": "DeepTutor"}
)
try:
async with asyncio.timeout(CODEX_VERSION_TIMEOUT_SECONDS):
# Standalone requests never inherit client cookies, headers or auth.
response = await http.send(
httpx.Request("GET", url, headers=headers),
auth=None, follow_redirects=False, stream=True,
auth=None,
follow_redirects=False,
stream=True,
)
try:
response.raise_for_status()
@@ -72,7 +75,9 @@ async def _source_version(http: httpx.AsyncClient, source: str) -> str | None:
return None
async def discover_client_version(http: httpx.AsyncClient | None = None) -> tuple[str | None, str | None]:
async def discover_client_version(
http: httpx.AsyncClient | None = None,
) -> tuple[str | None, str | None]:
if http is None:
async with httpx.AsyncClient(timeout=CODEX_VERSION_TIMEOUT_SECONDS) as client:
return await discover_client_version(client)

View File

@@ -1,4 +1,5 @@
"""Periodic owner-scoped Codex catalog refresh."""
from __future__ import annotations
import asyncio
@@ -8,8 +9,8 @@ import os
from pathlib import Path
from .constants import CODEX_AUTO_REFRESH_POLL_SECONDS
from .service import get_codex_oauth_service
from .contracts import CodexAuthError
from .service import get_codex_oauth_service
from .storage import _assert_safe_directory, _assert_safe_regular_path
logger = logging.getLogger(__name__)
@@ -44,7 +45,7 @@ class CodexCatalogRefreshScheduler:
async def run_once(self) -> None:
from deeptutor.core.identities import is_partner_user_id
from deeptutor.multi_user import identity, paths
from deeptutor.multi_user.models import CurrentUser, LOCAL_ADMIN_ID
from deeptutor.multi_user.models import LOCAL_ADMIN_ID, CurrentUser
candidate_ids: list[str] = []
if _has_credentials(paths.get_admin_path_service().get_user_root()):
@@ -79,7 +80,10 @@ class CodexCatalogRefreshScheduler:
if resolved is None:
continue
username, record = resolved
if bool(record.get("disabled", False)) or str(record.get("role") or "user") == "admin":
if (
bool(record.get("disabled", False))
or str(record.get("role") or "user") == "admin"
):
continue
user = CurrentUser(
id=owner_id,

View File

@@ -23,8 +23,8 @@ from deeptutor.services.config.runtime_settings import load_system_settings
from .catalog import CodexModelCatalog
from .constants import (
CODEX_AUTO_REFRESH_INTERVAL_SECONDS,
CODEX_AUTO_REFRESH_FAILURE_BACKOFF_SECONDS,
CODEX_AUTO_REFRESH_INTERVAL_SECONDS,
CODEX_AUTO_REFRESH_LEASE_SECONDS,
CODEX_CALLBACK_PATH,
CODEX_CALLBACK_PORTS,
@@ -692,7 +692,9 @@ class CodexOAuthService:
CODEX_AUTO_REFRESH_INTERVAL_SECONDS, CODEX_AUTO_REFRESH_FAILURE_BACKOFF_SECONDS
)
async def _refresh_models(self, interval: int, backoff: int, expected_generation: int | None = None) -> dict[str, Any]:
async def _refresh_models(
self, interval: int, backoff: int, expected_generation: int | None = None
) -> dict[str, Any]:
async with self._catalog_sync_lock:
attempted_at = int(self._clock())
generation = self._store.current_generation()
@@ -729,26 +731,38 @@ class CodexOAuthService:
)
self._last_snapshot = publish_snapshot
self._store.record_catalog_refresh_result(
generation=attempt_generation, attempted_at=attempted_at,
next_refresh_at=attempted_at + interval, succeeded=True, error_code=None,
generation=attempt_generation,
attempted_at=attempted_at,
next_refresh_at=attempted_at + interval,
succeeded=True,
error_code=None,
client_version=publish_snapshot.client_version,
version_source=publish_snapshot.version_source,
)
except Exception as exc:
if isinstance(exc, CodexAuthError) and exc.code in {"catalog_unauthorized", "catalog_forbidden"}:
if isinstance(exc, CodexAuthError) and exc.code in {
"catalog_unauthorized",
"catalog_forbidden",
}:
self._last_snapshot = None
if not (isinstance(exc, CodexAuthError) and exc.code == "generation_changed"):
with suppress(CodexAuthError, OSError):
self._store.record_catalog_refresh_result(
generation=attempt_generation, attempted_at=attempted_at,
next_refresh_at=attempted_at + backoff, succeeded=False,
error_code=exc.code if isinstance(exc, CodexAuthError) else "catalog_refresh_failed",
generation=attempt_generation,
attempted_at=attempted_at,
next_refresh_at=attempted_at + backoff,
succeeded=False,
error_code=exc.code
if isinstance(exc, CodexAuthError)
else "catalog_refresh_failed",
)
raise
return self.public_status()
async def refresh_models_if_due(
self, *, min_interval_seconds: int = CODEX_AUTO_REFRESH_INTERVAL_SECONDS,
self,
*,
min_interval_seconds: int = CODEX_AUTO_REFRESH_INTERVAL_SECONDS,
failure_backoff_seconds: int = CODEX_AUTO_REFRESH_FAILURE_BACKOFF_SECONDS,
lease_owner: str = "scheduler",
) -> bool:
@@ -770,7 +784,9 @@ class CodexOAuthService:
)
if not acquired:
return False
await self._refresh_models(min_interval_seconds, failure_backoff_seconds, credentials.generation)
await self._refresh_models(
min_interval_seconds, failure_backoff_seconds, credentials.generation
)
return True
except Exception:
return False
@@ -1048,8 +1064,10 @@ class CodexOAuthService:
except CodexAuthError:
refresh_state = {}
return {
"catalog_client_version": (snapshot.client_version if snapshot else None) or refresh_state.get("catalog_client_version"),
"catalog_version_source": (snapshot.version_source if snapshot else None) or refresh_state.get("catalog_version_source"),
"catalog_client_version": (snapshot.client_version if snapshot else None)
or refresh_state.get("catalog_client_version"),
"catalog_version_source": (snapshot.version_source if snapshot else None)
or refresh_state.get("catalog_version_source"),
"catalog_last_attempt_at": refresh_state.get("catalog_last_attempt_at"),
"catalog_last_error_code": refresh_state.get("catalog_last_error_code"),
"catalog_next_refresh_at": refresh_state.get("catalog_next_refresh_at"),

View File

@@ -19,9 +19,14 @@ from .contracts import CatalogSnapshot, CodexAuthError, CodexCredentials
_SCHEMA_VERSION = 1
_REFRESH_KEYS = (
"catalog_last_attempt_at", "catalog_last_success_at", "catalog_last_error_code",
"catalog_next_refresh_at", "catalog_client_version", "catalog_version_source",
"catalog_refresh_lease_until", "catalog_refresh_lease_owner",
"catalog_last_attempt_at",
"catalog_last_success_at",
"catalog_last_error_code",
"catalog_next_refresh_at",
"catalog_client_version",
"catalog_version_source",
"catalog_refresh_lease_until",
"catalog_refresh_lease_owner",
)
@@ -241,7 +246,8 @@ class CodexCredentialStore:
}
try:
old_payload = self._read_json(
self.credentials_path, code="credential_corrupt",
self.credentials_path,
code="credential_corrupt",
message="Stored Codex credentials are invalid.",
)
except CodexAuthError as exc:
@@ -349,8 +355,9 @@ class CodexCredentialStore:
return False
if (state.get("catalog_refresh_lease_until") or 0) > now:
return False
state.update(catalog_refresh_lease_owner=owner,
catalog_refresh_lease_until=now + lease_seconds)
state.update(
catalog_refresh_lease_owner=owner, catalog_refresh_lease_until=now + lease_seconds
)
_atomic_write_json(self.state_path, state)
return True
@@ -362,21 +369,31 @@ class CodexCredentialStore:
_atomic_write_json(self.state_path, state)
def record_catalog_refresh_result(
self, *, generation: int, attempted_at: int, next_refresh_at: int,
succeeded: bool, error_code: str | None, client_version: str | None = None,
self,
*,
generation: int,
attempted_at: int,
next_refresh_at: int,
succeeded: bool,
error_code: str | None,
client_version: str | None = None,
version_source: str | None = None,
) -> None:
with self._locked():
state = self._read_state_unlocked()
if state["generation"] != generation:
return
state.update(catalog_last_attempt_at=attempted_at,
catalog_next_refresh_at=next_refresh_at,
catalog_last_error_code=error_code)
state.update(
catalog_last_attempt_at=attempted_at,
catalog_next_refresh_at=next_refresh_at,
catalog_last_error_code=error_code,
)
if succeeded:
state.update(catalog_last_success_at=attempted_at,
catalog_client_version=client_version,
catalog_version_source=version_source)
state.update(
catalog_last_success_at=attempted_at,
catalog_client_version=client_version,
catalog_version_source=version_source,
)
_atomic_write_json(self.state_path, state)
def load_catalog_cache(self) -> dict[str, Any] | None:

View File

@@ -881,12 +881,15 @@ class TurnRequestPreparer:
# Retain ownership until durable cleanup finishes, even if shutdown
# cancels this waiter again during a browser disconnect.
cleanup = asyncio.create_task(settle_admission())
while not cleanup.done():
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
continue
cleanup.result()
try:
while not cleanup.done():
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
continue
cleanup.result()
except Exception:
logger.exception("Failed to settle turn admission after interruption")
raise
if turn.pop(SUBMISSION_REPLAY_FIELD, False):
if lease is not None and self.coordinator is not None:

View File

@@ -1,16 +1,18 @@
"""Check the bundled Codex catalog version against official stable releases."""
from __future__ import annotations
import argparse
import asyncio
# Load only the two metadata modules; maintenance does not need the app runtime.
import importlib.util
import json
import os
from pathlib import Path
import sys
# Load only the two metadata modules; maintenance does not need the app runtime.
import importlib.util
import types
import httpx
_root = Path(__file__).resolve().parents[1] / "deeptutor/services/codex_auth"
@@ -18,7 +20,9 @@ _package = types.ModuleType("_codex_metadata")
_package.__path__ = [str(_root)]
sys.modules[_package.__name__] = _package
for _name in ("constants", "client_version"):
_spec = importlib.util.spec_from_file_location(f"_codex_metadata.{_name}", _root / f"{_name}.py")
_spec = importlib.util.spec_from_file_location(
f"_codex_metadata.{_name}", _root / f"{_name}.py"
)
_module = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = _module
_spec.loader.exec_module(_module)
@@ -32,11 +36,20 @@ async def check_versions() -> tuple[dict, int]:
_source_version(http, "npm"), _source_version(http, "github")
)
upstream = max_stable_version(npm, github)
code = 1 if upstream is None else (
0 if max_stable_version(CODEX_CLIENT_VERSION, upstream) == CODEX_CLIENT_VERSION else 2
code = (
1
if upstream is None
else (
0 if max_stable_version(CODEX_CLIENT_VERSION, upstream) == CODEX_CLIENT_VERSION else 2
)
)
return {"bundled": CODEX_CLIENT_VERSION, "npm": npm, "github": github,
"upstream": upstream, "status": {0: "up-to-date", 1: "unavailable", 2: "drift"}[code]}, code
return {
"bundled": CODEX_CLIENT_VERSION,
"npm": npm,
"github": github,
"upstream": upstream,
"status": {0: "up-to-date", 1: "unavailable", 2: "drift"}[code],
}, code
def main() -> int:
@@ -46,7 +59,9 @@ def main() -> int:
args = parser.parse_args()
result, code = asyncio.run(check_versions())
table = "| Bundled | npm | GitHub | Status |\n|---|---|---|---|\n"
table += f"| {result['bundled']} | {result['npm']} | {result['github']} | {result['status']} |\n"
table += (
f"| {result['bundled']} | {result['npm']} | {result['github']} | {result['status']} |\n"
)
print(json.dumps(result) if args.json else table)
if args.github_summary and os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as handle:

View File

@@ -1,4 +1,5 @@
"""Catalog freshness, metadata isolation and owner coordination regressions."""
import asyncio
import importlib.util
from pathlib import Path
@@ -11,8 +12,15 @@ from typer.testing import CliRunner
from deeptutor.services.codex_auth import client_version as versions
from deeptutor.services.codex_auth.catalog import CodexModelCatalog
from deeptutor.services.codex_auth.constants import CODEX_CLIENT_VERSION, CODEX_CATALOG_HEADER_SCHEMA
from deeptutor.services.codex_auth.contracts import CatalogSnapshot, CodexCredentials, CodexAuthError
from deeptutor.services.codex_auth.constants import (
CODEX_CATALOG_HEADER_SCHEMA,
CODEX_CLIENT_VERSION,
)
from deeptutor.services.codex_auth.contracts import (
CatalogSnapshot,
CodexAuthError,
CodexCredentials,
)
from deeptutor.services.codex_auth.storage import CodexCredentialStore
@@ -29,6 +37,7 @@ def test_numeric_versions():
@pytest.mark.asyncio
async def test_github_fallback_has_no_secrets():
requests = []
def handler(request):
requests.append(request)
assert "authorization" not in request.headers
@@ -37,9 +46,13 @@ async def test_github_fallback_has_no_secrets():
if request.url.host == "registry.npmjs.org":
return httpx.Response(404)
assert request.headers["User-Agent"] == "DeepTutor"
return httpx.Response(200, json={"draft": False, "prerelease": False, "tag_name": "rust-v0.172.0"})
return httpx.Response(
200, json={"draft": False, "prerelease": False, "tag_name": "rust-v0.172.0"}
)
async with httpx.AsyncClient(
transport=httpx.MockTransport(handler), auth=("secret", "secret"),
transport=httpx.MockTransport(handler),
auth=("secret", "secret"),
headers={"Authorization": "Bearer sentinel", "chatgpt-account-id": "sentinel"},
cookies={"session": "sentinel"},
) as http:
@@ -49,9 +62,11 @@ async def test_github_fallback_has_no_secrets():
@pytest.mark.asyncio
async def test_total_deadline_and_cancellation(monkeypatch):
monkeypatch.setattr(versions, "CODEX_VERSION_TOTAL_TIMEOUT_SECONDS", .03)
monkeypatch.setattr(versions, "CODEX_VERSION_TOTAL_TIMEOUT_SECONDS", 0.03)
async def slow(request):
await asyncio.sleep(1)
async with httpx.AsyncClient(transport=httpx.MockTransport(slow)) as http:
assert await versions.discover_client_version(http) == (None, None)
task = asyncio.create_task(versions.discover_client_version(http))
@@ -66,6 +81,7 @@ async def test_legacy_etag_and_older_version_are_not_reused(tmp_path):
store = CodexCredentialStore(tmp_path)
creds = store.commit_credentials(credentials(), 0)
seen = []
def handler(request):
if request.url.host != "chatgpt.com":
return httpx.Response(503)
@@ -73,6 +89,7 @@ async def test_legacy_etag_and_older_version_are_not_reused(tmp_path):
assert request.headers["originator"] == "codex_cli_rs"
assert request.headers["version"] == CODEX_CLIENT_VERSION
return httpx.Response(200, json={"models": []}, headers={"etag": "current"})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
catalog = CodexModelCatalog(store, http=http, version_http=http)
first = await catalog.get(creds, force=True)
@@ -97,18 +114,30 @@ def test_lease_and_late_result_cannot_clobber_logout(tmp_path):
assert not store.try_acquire_catalog_refresh_lease("two", 102, 120, creds.generation)
assert store.try_acquire_catalog_refresh_lease("two", 221, 120, creds.generation)
store.clear_credentials()
store.record_catalog_refresh_result(generation=creds.generation, attempted_at=100,
next_refresh_at=200, succeeded=True, error_code=None, client_version="9.0.0")
store.record_catalog_refresh_result(
generation=creds.generation,
attempted_at=100,
next_refresh_at=200,
succeeded=True,
error_code=None,
client_version="9.0.0",
)
assert all(value is None for value in store.load_catalog_refresh_state().values())
@pytest.mark.parametrize("provider", ["openai-codex", "openai_codex"])
def test_refresh_cli(provider, monkeypatch):
from deeptutor_cli import provider_cmd
service = type("Service", (), {})()
service.refresh_models = AsyncMock(return_value={
"model_count": 3, "catalog_client_version": "0.171.0",
"catalog_version_source": "github", "active_model": "gpt-6.2-astra"})
service.refresh_models = AsyncMock(
return_value={
"model_count": 3,
"catalog_client_version": "0.171.0",
"catalog_version_source": "github",
"active_model": "gpt-6.2-astra",
}
)
monkeypatch.setattr(provider_cmd, "get_codex_oauth_service", lambda: service)
app = typer.Typer()
provider_cmd.register(app)
@@ -136,15 +165,18 @@ async def test_drift_exit_codes(upstream, code, monkeypatch):
@pytest.mark.asyncio
async def test_scheduler_stops_promptly(monkeypatch):
from deeptutor.services.codex_auth.scheduler import CodexCatalogRefreshScheduler
scheduler = CodexCatalogRefreshScheduler()
entered = asyncio.Event()
async def run_once():
entered.set()
await asyncio.sleep(100)
monkeypatch.setattr(scheduler, "run_once", run_once)
await scheduler.start()
await entered.wait()
await asyncio.wait_for(scheduler.stop(), .5)
await asyncio.wait_for(scheduler.stop(), 0.5)
assert scheduler._task is None
@@ -153,6 +185,7 @@ async def test_scheduler_enters_each_owner_scope_without_empty_stores(tmp_path,
from deeptutor.multi_user import identity, paths
from deeptutor.multi_user.context import get_current_user
from deeptutor.services.codex_auth import scheduler as module
monkeypatch.setattr(paths, "SYSTEM_ROOT", tmp_path / "system")
monkeypatch.setattr(paths, "ADMIN_WORKSPACE_ROOT", tmp_path)
monkeypatch.setattr(paths, "USERS_ROOT", tmp_path / "users")
@@ -170,9 +203,11 @@ async def test_scheduler_enters_each_owner_scope_without_empty_stores(tmp_path,
empty = tmp_path / "system/user-secrets/unused"
empty.mkdir()
seen = []
class Service:
async def refresh_models_if_due(self, **kwargs):
seen.append(get_current_user().id)
monkeypatch.setattr(module, "get_codex_oauth_service", lambda: Service())
before = get_current_user()
await module.CodexCatalogRefreshScheduler().run_once()
@@ -192,10 +227,17 @@ def test_gpt6_family_fallbacks():
find_by_name,
model_overrides_for,
)
assert "gpt-6" in OPENAI_REASONING_FAMILIES
assert default_context_window_for_model(model="gpt-6.2-astra") == LARGE_CONTEXT_MODEL_DEFAULT
assert default_context_window_for_model(model="openai/gpt-6.2-astra") == LARGE_CONTEXT_MODEL_DEFAULT
assert default_context_window_for_model(model="custom-gpt-6-proxy") == DEFAULT_CONTEXT_WINDOW_FALLBACK
assert (
default_context_window_for_model(model="openai/gpt-6.2-astra")
== LARGE_CONTEXT_MODEL_DEFAULT
)
assert (
default_context_window_for_model(model="custom-gpt-6-proxy")
== DEFAULT_CONTEXT_WINDOW_FALLBACK
)
assert model_overrides_for("custom-gpt-6-proxy", find_by_name("custom")) == {}
assert model_overrides_for("gpt-6.2-astra", find_by_name("custom")) == {"temperature": None}
@@ -203,7 +245,10 @@ def test_gpt6_family_fallbacks():
@pytest.mark.asyncio
async def test_github_fallback_accepts_large_release_with_many_assets():
assets = [
{"name": f"codex-asset-{i}.tar.gz", "browser_download_url": f"https://example.test/{'x' * 500}/{i}"}
{
"name": f"codex-asset-{i}.tar.gz",
"browser_download_url": f"https://example.test/{'x' * 500}/{i}",
}
for i in range(196)
]
payload = {"draft": False, "prerelease": False, "tag_name": "rust-v0.172.0", "assets": assets}
@@ -222,14 +267,23 @@ def test_atomic_due_check_prevents_back_to_back_worker_refetch(tmp_path):
store = CodexCredentialStore(tmp_path)
creds = store.commit_credentials(credentials(), 0)
# Worker 1 acquires, refreshes, sets next_refresh_at=1000, and releases.
assert store.try_acquire_catalog_refresh_lease("w1", 100, 120, creds.generation, min_interval_seconds=600)
assert store.try_acquire_catalog_refresh_lease(
"w1", 100, 120, creds.generation, min_interval_seconds=600
)
store.record_catalog_refresh_result(
generation=creds.generation, attempted_at=100, next_refresh_at=1000,
succeeded=True, error_code=None, client_version="0.171.0", version_source="npm",
generation=creds.generation,
attempted_at=100,
next_refresh_at=1000,
succeeded=True,
error_code=None,
client_version="0.171.0",
version_source="npm",
)
store.release_catalog_refresh_lease("w1")
# Worker 2 trying at now=101 must be rejected atomically under the store lock.
assert not store.try_acquire_catalog_refresh_lease("w2", 101, 120, creds.generation, min_interval_seconds=600)
assert not store.try_acquire_catalog_refresh_lease(
"w2", 101, 120, creds.generation, min_interval_seconds=600
)
def test_commit_credentials_repairs_malformed_prior_json_and_blocks_symlink(tmp_path):
@@ -237,8 +291,11 @@ def test_commit_credentials_repairs_malformed_prior_json_and_blocks_symlink(tmp_
store.root.mkdir(parents=True)
store.credentials_path.write_text("{corrupt", encoding="utf-8")
store.record_catalog_refresh_result(
generation=0, attempted_at=100, next_refresh_at=999,
succeeded=False, error_code="catalog_unavailable",
generation=0,
attempted_at=100,
next_refresh_at=999,
succeeded=False,
error_code="catalog_unavailable",
)
committed = store.commit_credentials(credentials(), expected_generation=0)
assert committed.generation == 1
@@ -256,10 +313,15 @@ async def test_stale_lease_does_not_write_error_into_new_generation(tmp_path):
gen1 = store.commit_credentials(credentials(), 0)
gen2 = store.commit_credentials(credentials(), gen1.generation)
model_catalog = ModelCatalogService(tmp_path / "model_catalog.json")
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(503))) as http:
async with httpx.AsyncClient(
transport=httpx.MockTransport(lambda _: httpx.Response(503))
) as http:
service = CodexOAuthService(
store, CodexModelCatalog(store, http=http, version_http=http), model_catalog,
oauth_client=CodexOAuthClient(http), clock=lambda: 500,
store,
CodexModelCatalog(store, http=http, version_http=http),
model_catalog,
oauth_client=CodexOAuthClient(http),
clock=lambda: 500,
)
with pytest.raises(CodexAuthError) as exc:
await service._refresh_models(600, 900, expected_generation=gen1.generation)
@@ -289,22 +351,34 @@ async def test_logout_wins_over_inflight_token_rotation_across_workers(tmp_path)
if request.url.path == "/oauth/token":
refresh_entered.set()
await allow_refresh_return.wait()
return httpx.Response(200, json={
"access_token": "access-2", "refresh_token": "refresh-2",
"id_token": "id-2", "account_id": "account", "expires_in": 3600,
})
return httpx.Response(
200,
json={
"access_token": "access-2",
"refresh_token": "refresh-2",
"id_token": "id-2",
"account_id": "account",
"expires_in": 3600,
},
)
if request.url.path == "/oauth/revoke":
return httpx.Response(200)
return httpx.Response(200, json={"models": []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
svc_a = CodexOAuthService(
store_a, CodexModelCatalog(store_a, http=http, version_http=http),
model_catalog, oauth_client=CodexOAuthClient(http), clock=lambda: 90,
store_a,
CodexModelCatalog(store_a, http=http, version_http=http),
model_catalog,
oauth_client=CodexOAuthClient(http),
clock=lambda: 90,
)
svc_b = CodexOAuthService(
store_b, CodexModelCatalog(store_b, http=http, version_http=http),
model_catalog, oauth_client=CodexOAuthClient(http), clock=lambda: 90,
store_b,
CodexModelCatalog(store_b, http=http, version_http=http),
model_catalog,
oauth_client=CodexOAuthClient(http),
clock=lambda: 90,
)
refresh_task = asyncio.create_task(svc_b.get_token())
await refresh_entered.wait()
@@ -335,11 +409,28 @@ async def test_public_status_reflects_cross_worker_catalog_refresh(tmp_path):
return httpx.Response(503)
call_count += 1
models = (
[{"slug": "gpt-5.6-sol", "display_name": "GPT-5.6 Sol", "visibility": "list", "priority": 1}]
[
{
"slug": "gpt-5.6-sol",
"display_name": "GPT-5.6 Sol",
"visibility": "list",
"priority": 1,
}
]
if call_count == 1
else [
{"slug": "gpt-6.2-astra", "display_name": "GPT-6.2 Astra", "visibility": "list", "priority": 0},
{"slug": "gpt-5.6-sol", "display_name": "GPT-5.6 Sol", "visibility": "list", "priority": 1},
{
"slug": "gpt-6.2-astra",
"display_name": "GPT-6.2 Astra",
"visibility": "list",
"priority": 0,
},
{
"slug": "gpt-5.6-sol",
"display_name": "GPT-5.6 Sol",
"visibility": "list",
"priority": 1,
},
]
)
return httpx.Response(200, json={"models": models})
@@ -347,12 +438,18 @@ async def test_public_status_reflects_cross_worker_catalog_refresh(tmp_path):
now = [1000]
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
svc_a = CodexOAuthService(
store_a, CodexModelCatalog(store_a, http=http, version_http=http, clock=lambda: now[0]),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http), clock=lambda: now[0],
store_a,
CodexModelCatalog(store_a, http=http, version_http=http, clock=lambda: now[0]),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
clock=lambda: now[0],
)
svc_b = CodexOAuthService(
store_b, CodexModelCatalog(store_b, http=http, version_http=http, clock=lambda: now[0]),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http), clock=lambda: now[0],
store_b,
CodexModelCatalog(store_b, http=http, version_http=http, clock=lambda: now[0]),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
clock=lambda: now[0],
)
await svc_a.refresh_models()
assert svc_a.public_status()["model_count"] == 1
@@ -368,6 +465,7 @@ async def test_public_status_reflects_cross_worker_catalog_refresh(tmp_path):
def test_model_catalog_interprocess_lock_preserves_concurrent_updates(tmp_path):
from concurrent.futures import ThreadPoolExecutor
from deeptutor.services.config.model_catalog import ModelCatalogService
catalog_path = tmp_path / "model_catalog.json"
@@ -377,10 +475,15 @@ def test_model_catalog_interprocess_lock_preserves_concurrent_updates(tmp_path):
def add_profile(svc: ModelCatalogService, pid: str) -> None:
def mutate(cat: dict) -> None:
cat["services"]["llm"]["profiles"].append({
"id": pid, "name": pid, "binding": "openai",
"models": [{"id": f"m-{pid}", "name": pid, "model": pid}],
})
cat["services"]["llm"]["profiles"].append(
{
"id": pid,
"name": pid,
"binding": "openai",
"models": [{"id": f"m-{pid}", "name": pid, "model": pid}],
}
)
svc.update(mutate)
with ThreadPoolExecutor(max_workers=2) as pool:
@@ -403,10 +506,15 @@ async def test_get_token_expected_generation_blocks_account_switch_in_refresh(tm
gen1 = store.commit_credentials(credentials(), 0)
model_catalog = ModelCatalogService(tmp_path / "model_catalog.json")
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(429))) as http:
async with httpx.AsyncClient(
transport=httpx.MockTransport(lambda _: httpx.Response(429))
) as http:
service = CodexOAuthService(
store, CodexModelCatalog(store, http=http, version_http=http), model_catalog,
oauth_client=CodexOAuthClient(http), clock=lambda: 500,
store,
CodexModelCatalog(store, http=http, version_http=http),
model_catalog,
oauth_client=CodexOAuthClient(http),
clock=lambda: 500,
)
# Hold _refresh_lock while credentials rotate to gen 2 (account switch).
async with service._refresh_lock:
@@ -444,18 +552,32 @@ async def test_cross_worker_401_invalidation_clears_stale_memory_snapshot(tmp_pa
return httpx.Response(503)
if mode[0] == "401":
return httpx.Response(401)
return httpx.Response(200, json={
"models": [{"slug": "gpt-6.2-astra", "display_name": "GPT-6.2 Astra", "visibility": "list", "priority": 0}]
})
return httpx.Response(
200,
json={
"models": [
{
"slug": "gpt-6.2-astra",
"display_name": "GPT-6.2 Astra",
"visibility": "list",
"priority": 0,
}
]
},
)
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
svc_a = CodexOAuthService(
store_a, CodexModelCatalog(store_a, http=http, version_http=http),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http),
store_a,
CodexModelCatalog(store_a, http=http, version_http=http),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
)
svc_b = CodexOAuthService(
store_b, CodexModelCatalog(store_b, http=http, version_http=http),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http),
store_b,
CodexModelCatalog(store_b, http=http, version_http=http),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
)
await svc_a.refresh_models()
assert svc_a.public_status()["model_count"] == 1
@@ -467,7 +589,9 @@ async def test_cross_worker_401_invalidation_clears_stale_memory_snapshot(tmp_pa
@pytest.mark.asyncio
async def test_logout_revokes_detached_credentials_even_when_catalog_cleanup_fails(tmp_path, monkeypatch):
async def test_logout_revokes_detached_credentials_even_when_catalog_cleanup_fails(
tmp_path, monkeypatch
):
from deeptutor.services.codex_auth import service as service_mod
from deeptutor.services.codex_auth.oauth import CodexOAuthClient
from deeptutor.services.codex_auth.service import CodexOAuthService
@@ -490,7 +614,8 @@ async def test_logout_revokes_detached_credentials_even_when_catalog_cleanup_fai
)
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
svc = CodexOAuthService(
store, CodexModelCatalog(store, http=http, version_http=http),
store,
CodexModelCatalog(store, http=http, version_http=http),
ModelCatalogService(tmp_path / "model_catalog.json"),
oauth_client=CodexOAuthClient(http),
)
@@ -549,24 +674,33 @@ async def test_concurrent_refresh_and_reasoning_effort_edit_share_lock_order(tmp
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host != "chatgpt.com":
return httpx.Response(503)
return httpx.Response(200, json={
"models": [{
"slug": "gpt-6.2-astra",
"display_name": "GPT-6.2 Astra",
"visibility": "list",
"priority": 0,
"supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}],
}]
})
return httpx.Response(
200,
json={
"models": [
{
"slug": "gpt-6.2-astra",
"display_name": "GPT-6.2 Astra",
"visibility": "list",
"priority": 0,
"supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}],
}
]
},
)
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
svc_a = CodexOAuthService(
store_a, CodexModelCatalog(store_a, http=http, version_http=http),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http),
store_a,
CodexModelCatalog(store_a, http=http, version_http=http),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
)
svc_b = CodexOAuthService(
store_b, CodexModelCatalog(store_b, http=http, version_http=http),
ModelCatalogService(catalog_path), oauth_client=CodexOAuthClient(http),
store_b,
CodexModelCatalog(store_b, http=http, version_http=http),
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
)
await svc_a.refresh_models()
await asyncio.wait_for(
@@ -593,9 +727,19 @@ async def test_superseded_refresh_publishes_latest_durable_cache_snapshot(tmp_pa
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host != "chatgpt.com":
return httpx.Response(503)
return httpx.Response(200, json={
"models": [{"slug": "gpt-5.6-sol", "display_name": "Old", "visibility": "list", "priority": 1}]
})
return httpx.Response(
200,
json={
"models": [
{
"slug": "gpt-5.6-sol",
"display_name": "Old",
"visibility": "list",
"priority": 1,
}
]
},
)
newer_payload = {
"models": [
@@ -603,9 +747,10 @@ async def test_superseded_refresh_publishes_latest_durable_cache_snapshot(tmp_pa
{"slug": "gpt-5.6-sol", "display_name": "Old", "visibility": "list", "priority": 1},
]
}
from deeptutor.services.codex_auth.catalog import parse_models_response
import hashlib
from deeptutor.services.codex_auth.catalog import parse_models_response
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
cat_a = CodexModelCatalog(store_a, http=http, version_http=http, clock=lambda: 1000)
orig_get = cat_a.get
@@ -629,8 +774,11 @@ async def test_superseded_refresh_publishes_latest_durable_cache_snapshot(tmp_pa
cat_a.get = get_then_worker_b_commits # type: ignore[method-assign]
svc_a = CodexOAuthService(
store_a, cat_a, ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http), clock=lambda: 1000,
store_a,
cat_a,
ModelCatalogService(catalog_path),
oauth_client=CodexOAuthClient(http),
clock=lambda: 1000,
)
status = await svc_a.refresh_models()
assert status["model_count"] == 2
@@ -640,12 +788,18 @@ async def test_superseded_refresh_publishes_latest_durable_cache_snapshot(tmp_pa
def test_drift_json_and_github_summary(tmp_path, monkeypatch, capsys):
import json
import sys
path = Path(__file__).resolve().parents[3] / "scripts/check_codex_catalog_version.py"
spec = importlib.util.spec_from_file_location("drift_output", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
result = {"bundled": CODEX_CLIENT_VERSION, "npm": "99.0.0",
"github": None, "upstream": "99.0.0", "status": "drift"}
result = {
"bundled": CODEX_CLIENT_VERSION,
"npm": "99.0.0",
"github": None,
"upstream": "99.0.0",
"status": "drift",
}
monkeypatch.setattr(module, "check_versions", AsyncMock(return_value=(result, 2)))
monkeypatch.setattr(sys, "argv", ["check", "--json", "--github-summary"])
summary = tmp_path / "summary.md"

View File

@@ -115,7 +115,13 @@ async def test_json_recursion_failure_is_unavailable_and_closes_response(
monkeypatch.setattr(
"deeptutor.services.codex_auth.client_version.json.loads", reject_nested_json
)
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda request: response if request.url.host == "registry.npmjs.org" else httpx.Response(503))) as http:
async with httpx.AsyncClient(
transport=httpx.MockTransport(
lambda request: (
response if request.url.host == "registry.npmjs.org" else httpx.Response(503)
)
)
) as http:
assert await latest_client_version(http) is None
assert response.is_closed
@@ -179,8 +185,6 @@ async def test_stream_is_closed_at_size_limit_or_total_deadline(stall: bool) ->
streams.append(stream)
return httpx.Response(200, stream=stream)
async with httpx.AsyncClient(
transport=httpx.MockTransport(handler)
) as http:
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
assert await latest_client_version(http) is None
assert streams and all(stream.closed for stream in streams)

View File

@@ -67,13 +67,14 @@ def test_answer_block_keeps_the_question_with_its_answer() -> None:
def test_large_cards_share_one_turn_budget():
import json
from deeptutor.services.session.answer_attachments import (
QUESTION_ID_MAX_CHARS,
QUESTION_MAX_CHARS,
TURN_ANSWER_MAX_CHARS,
read_answers,
)
import json
records = [
{

View File

@@ -585,7 +585,6 @@ class TestRegenerateLastTurn:
)
assert recorder.calls[0].get("reading_viewport") == expected
def test_sqlite_replacement_rolls_back_if_anchor_update_fails(self, store, monkeypatch):
sid, user_id, assistant_id = _seed_session(store)

View File

@@ -103,19 +103,26 @@ def test_cache_limits_and_expiry(monkeypatch):
async def test_playback_caches_only_a_complete_stream(monkeypatch):
from types import SimpleNamespace
from deeptutor.services.voice.base import TTSConfig
from deeptutor.services.voice import replay as replay_store
from deeptutor.services.voice.base import TTSConfig
starts = []
async def stream(text, config):
starts.append(text)
yield b"\x00\x00"
yield b"\x01\x00"
config = TTSConfig(model="test", voice="reader")
monkeypatch.setattr(voice, "_prepare_speech", lambda text, **_: (
SimpleNamespace(stream_pcm=stream), text, config,
))
monkeypatch.setattr(
voice,
"_prepare_speech",
lambda text, **_: (
SimpleNamespace(stream_pcm=stream),
text,
config,
),
)
monkeypatch.setattr(voice, "read_aloud_cache", replay_store.AudioReplayCache())
partial = await voice.synthesize_for_playback("read", replay_for_user="alice")
await anext(partial)

View File

@@ -6,17 +6,14 @@ import { useTranslation } from 'react-i18next'
/** Only http(s) images outside this origin need consent. */
export function isExternalImageSource(src: string): boolean {
// A relative reference always resolves against this page on server and client.
if (!/^(?:[a-z][a-z\d+.-]*:|[/\\]{2})/i.test(src.trim())) return false
try {
const url = new URL(
src,
typeof window === 'undefined' ? 'http://localhost' : window.location.href
)
return (
(url.protocol === 'http:' || url.protocol === 'https:') &&
(typeof window === 'undefined' || url.origin !== window.location.origin)
)
const base = typeof window === 'undefined' ? 'https://relative-a.invalid' : window.location.href
const url = new URL(src, base)
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
if (typeof window !== 'undefined') return url.origin !== window.location.origin
// Only page-relative references change origin when resolved against another page.
return url.origin === new URL(src, 'https://relative-b.invalid').origin
} catch {
return false
}