Skip to content

Commit 5e2c9c7

Browse files
fix(review): resolve mypy errors, pip-audit CVE, and MissingGreenlet test bug
Discovered by actually inspecting CI results for #298 rather than trusting local ruff+pytest alone -- mypy, bandit, and pip-audit were never run locally in this session, and CI turned out to already be red on main from the batch commit onward (over a month), for reasons unrelated to the round-9 fixes. - backend/app/api/interfaces.py: GenerationLLM.stream_answer's Protocol stub body was `...` with no `yield`, so mypy inferred calling it returns Coroutine[Any, Any, AsyncIterator[str]] instead of AsyncIterator[str] directly -- breaking `async for` at every call site through the Protocol type (backend/app/api/answer.py) and forcing two now-dead `type: ignore` workarounds in dependencies.py's singleton. Fixed the stub to be a real (unreachable) async generator so mypy treats it correctly; removed the dead ignores. - db/qdrant_bootstrap.py: `_verify_vector_size` accessed `.size` on a `VectorParams | dict[str, VectorParams] | None` union without narrowing. Added an isinstance guard that raises a clear RuntimeError for named-vector collections instead of leaving an unchecked AttributeError risk. - router/tests/test_router.py: removed a stale `type: ignore[arg-type]` that mypy now reports as unused. - pyproject.toml: pinned setuptools>=83.0.0 (build-system and dev extras) -- pip-audit flagged the installed 79.0.1 for PYSEC-2026-3447. This vulnerability was previously masked because bandit failed first in the same CI job (on the S110 issue this round's earlier commit already fixed), and pip-audit never got to run. - db/tests/test_schema.py: `test_forward_then_rollback_restores_baseline` used sync `create_engine` against `DATABASE_URL`, which CI sets to a `postgresql+asyncpg://` DSN (asyncpg is the project's only Postgres driver) -- raising `sqlalchemy.exc.MissingGreenlet`. Converted to `create_async_engine` + `conn.run_sync(inspect(...))`; added the matching `anyio_backend` fixture to db/tests/conftest.py. This test is skipped locally (no DATABASE_URL) so it was never caught outside CI. ruff, mypy, and pytest (330 passed, 1 skipped -- the live-DB test, correctly skipped without DATABASE_URL) are all clean locally after this commit. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 638878e commit 5e2c9c7

8 files changed

Lines changed: 73 additions & 28 deletions

File tree

‎backend/app/api/dependencies.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,10 @@ def _generation_llm_singleton() -> GenerationLLM:
149149
from backend.app.settings import get_settings
150150

151151
settings = get_settings()
152-
_generation_llm_cache = ClaudeGenerationLLM( # type: ignore[assignment]
152+
_generation_llm_cache = ClaudeGenerationLLM(
153153
thinking_budget_tokens=settings.generation_thinking_budget_tokens
154154
)
155-
return _generation_llm_cache # type: ignore[return-value]
155+
return _generation_llm_cache
156156

157157

158158
def get_document_store() -> DocumentStore:

‎backend/app/api/interfaces.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ async def stream_answer(
214214
sections: list[RoutedSection],
215215
) -> AsyncIterator[str]:
216216
"""Yield answer token fragments for the routed sections."""
217-
...
217+
raise NotImplementedError
218+
yield # pragma: no cover - unreachable, marks this an async generator
218219

219220

220221
class DependencyUnavailable(Exception): # noqa: N818 - maps to SERVICE_UNAVAILABLE, not an *Error

‎db/qdrant_bootstrap.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,14 @@ def _verify_vector_size(client: QdrantClient, collection_name: str) -> None:
143143
intervention (delete the collection and restart).
144144
"""
145145
collection_info = client.get_collection(collection_name)
146-
actual_size = collection_info.config.params.vectors.size
146+
vectors = collection_info.config.params.vectors
147+
if not isinstance(vectors, qm.VectorParams):
148+
raise RuntimeError(
149+
f"Qdrant collection '{collection_name}' does not use a single unnamed "
150+
"vector config (found named-vectors or no vectors); this collection was "
151+
"not created by bootstrap_collection. Delete it and restart."
152+
)
153+
actual_size = vectors.size
147154
if actual_size != VECTOR_SIZE:
148155
raise RuntimeError(
149156
f"Qdrant collection '{collection_name}' has vector size {actual_size} "

‎db/tests/conftest.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@
55
import pathlib
66
import sys
77

8+
import pytest
9+
810
_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[2]
911
if str(_PROJECT_ROOT) not in sys.path:
1012
sys.path.insert(0, str(_PROJECT_ROOT))
13+
14+
15+
@pytest.fixture
16+
def anyio_backend() -> str:
17+
"""Run anyio-based async tests on asyncio only (no trio dependency)."""
18+
return "asyncio"

‎db/tests/test_qdrant_bootstrap.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,15 @@ def _fake_collection_info(size: int) -> SimpleNamespace:
2828
"""Build a minimal stand-in exposing only the attribute path bootstrap reads.
2929
3030
Real ``qm.CollectionInfo`` construction requires many unrelated required
31-
fields that drift across qdrant-client versions; the production code only
32-
ever reads ``.config.params.vectors.size``.
31+
fields that drift across qdrant-client versions, so everything except
32+
``vectors`` is a plain stand-in; ``vectors`` itself must be a real
33+
``qm.VectorParams`` since ``_verify_vector_size`` does an ``isinstance``
34+
check against it (to reject named-vector collections it cannot support).
3335
"""
3436
return SimpleNamespace(
3537
config=SimpleNamespace(
3638
params=SimpleNamespace(
37-
vectors=SimpleNamespace(size=size, distance=qm.Distance.COSINE)
39+
vectors=qm.VectorParams(size=size, distance=qm.Distance.COSINE)
3840
)
3941
)
4042
)

‎db/tests/test_schema.py‎

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -330,28 +330,51 @@ def test_migration_004_erasure_outbox_fk_is_cascade_in_model() -> None:
330330
not os.environ.get("DATABASE_URL"),
331331
reason="DATABASE_URL not set; live forward+rollback migration test skipped.",
332332
)
333-
def test_forward_then_rollback_restores_baseline() -> None:
333+
@pytest.mark.anyio
334+
async def test_forward_then_rollback_restores_baseline() -> None:
334335
"""Apply all forward migrations in order, then rollback 001; expect clean state.
335336
336337
Applies migrations 001 through 004 in dependency order against a live Postgres
337338
instance, then runs the 001 rollback. All migrations are tested, not just 001.
338339
Skipped without ``DATABASE_URL`` so the suite stays offline-green.
340+
341+
``DATABASE_URL`` carries the ``postgresql+asyncpg://`` async DSN (per
342+
``asyncpg`` being the project's only Postgres driver dependency), so this
343+
uses ``create_async_engine`` rather than the sync ``create_engine`` -
344+
mixing a sync engine with an async-only driver raises
345+
``sqlalchemy.exc.MissingGreenlet``.
339346
"""
340-
from sqlalchemy import create_engine, inspect, text
341-
342-
engine = create_engine(os.environ["DATABASE_URL"])
343-
# Apply all migrations in order (001 -> 002 -> 003 -> 004).
344-
for migration_path in _ALL_FORWARD_MIGRATIONS:
345-
migration_sql = _read(migration_path)
346-
with engine.begin() as conn:
347-
conn.execute(text(migration_sql))
348-
inspector = inspect(engine)
349-
assert inspector.has_table("documents")
350-
assert inspector.has_table("sections")
351-
# Roll back 001 (which cascades to drop all dependent objects).
352-
down = _read(_DOWN_SQL)
353-
with engine.begin() as conn:
354-
conn.execute(text(down))
355-
inspector = inspect(engine)
356-
assert not inspector.has_table("sections")
357-
assert not inspector.has_table("documents")
347+
from sqlalchemy import inspect, text
348+
from sqlalchemy.ext.asyncio import create_async_engine
349+
350+
engine = create_async_engine(os.environ["DATABASE_URL"])
351+
try:
352+
# Apply all migrations in order (001 -> 002 -> 003 -> 004).
353+
for migration_path in _ALL_FORWARD_MIGRATIONS:
354+
migration_sql = _read(migration_path)
355+
async with engine.begin() as conn:
356+
await conn.execute(text(migration_sql))
357+
async with engine.connect() as conn:
358+
has_documents = await conn.run_sync(
359+
lambda sync_conn: inspect(sync_conn).has_table("documents")
360+
)
361+
has_sections = await conn.run_sync(
362+
lambda sync_conn: inspect(sync_conn).has_table("sections")
363+
)
364+
assert has_documents
365+
assert has_sections
366+
# Roll back 001 (which cascades to drop all dependent objects).
367+
down = _read(_DOWN_SQL)
368+
async with engine.begin() as conn:
369+
await conn.execute(text(down))
370+
async with engine.connect() as conn:
371+
sections_remain = await conn.run_sync(
372+
lambda sync_conn: inspect(sync_conn).has_table("sections")
373+
)
374+
documents_remain = await conn.run_sync(
375+
lambda sync_conn: inspect(sync_conn).has_table("documents")
376+
)
377+
assert not sections_remain
378+
assert not documents_remain
379+
finally:
380+
await engine.dispose()

‎pyproject.toml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ dependencies = [
3939

4040
[project.optional-dependencies]
4141
dev = [
42+
# >=83.0.0 remediates PYSEC-2026-3447; pinned explicitly since CI's base
43+
# image ships an older setuptools that pip does not otherwise upgrade.
44+
"setuptools>=83.0.0",
4245
"ruff>=0.4,<1.0",
4346
"mypy>=1.10,<2.0",
4447
"pytest>=9.0.3,<10.0",
@@ -50,7 +53,8 @@ dev = [
5053
]
5154

5255
[build-system]
53-
requires = ["setuptools>=68", "wheel"]
56+
# >=83.0.0 remediates PYSEC-2026-3447.
57+
requires = ["setuptools>=83.0.0", "wheel"]
5458
build-backend = "setuptools.build_meta"
5559

5660
[tool.setuptools]

‎router/tests/test_router.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ async def test_llm_error_during_route_triggers_fallback(golden_toc: list[dict])
339339
"doc_abc123",
340340
golden_toc,
341341
tenant_id="tenant_test",
342-
llm=error_llm, # type: ignore[arg-type]
342+
llm=error_llm,
343343
confidence_threshold=0.7,
344344
max_sections=3,
345345
)

0 commit comments

Comments
 (0)