Repository navigation
test: type storage contracts - #290
Conversation
📝 WalkthroughWalkthroughThis PR refactors type annotations across 12 storage test modules, replacing generic Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@tests/unit/storage/test_archive_search_contracts.py`:
- Around line 60-64: The test fake _FakeRepo is lying to the type system by
casting _FakeQueries to SQLiteQueryStore; instead narrow the API surface so the
fake only promises the three methods used by RepositoryArchiveSearchMixin:
define a Protocol (e.g., ArchiveSearchStoreProtocol) listing those methods and
type _FakeRepo.queries as that Protocol (or update
RepositoryArchiveSearchMixin's TYPE_CHECKING contract to reference the narrower
Protocol), replace the cast to SQLiteQueryStore with the Protocol type, and
ensure _FakeQueries implements that Protocol so the test double remains honest
(references: _FakeRepo, RepositoryArchiveSearchMixin, _FakeQueries,
SQLiteQueryStore, TYPE_CHECKING).
In `@tests/unit/storage/test_fts5.py`:
- Around line 778-787: Rename the mock_import function parameters to match the
built-in __import__ signature by changing globals_ -> globals and locals_ ->
locals (add "# noqa: A002" to those parameter names to silence the lint
warning), and update the call to original_import(name, globals, locals,
fromlist, level) so callers can pass the standard globals= and locals= kwargs;
apply this change to both mock_import definitions (the one referencing
sqlite_vec and the other at the other location).
In `@tests/unit/storage/test_query_security.py`:
- Around line 106-109: The test test_none_parameters_handled currently hides the
invalid input by using cast(str, None); instead call temp_repo.view with a plain
None to make the negative-input explicit and silence the type checker with a
local type ignore (e.g., pass None to temp_repo.view # type: ignore[arg-type]).
Update the assertion flow around the await temp_repo.view(...) call (in the same
test function) so the test still expects None while removing the cast(str,
None).
- Around line 24-28: Convert the temp_repo fixture to an async yield-style
fixture that yields the ConversationRepository instance and ensures the
SQLiteBackend is closed in a finally block; create the backend with
SQLiteBackend(...) as before, yield ConversationRepository(backend=backend) from
temp_repo, and in the finally call await backend.close() (or the backend's async
shutdown method) to avoid leaking the async SQLite resource.
In `@tests/unit/storage/test_scale.py`:
- Around line 39-50: The TypedDict RecordQueryKwargs used by the helper
_record_query should mirror the full ConversationRecordQuery contract: extend
RecordQueryKwargs to include missing keys such as source, providers,
title_contains, offset, any exclusion fields, min/max numeric filters, and any
other optional flags present on ConversationRecordQuery, and relax types for
nullable fields (e.g., limit, since, until) to allow None/optional values; then
keep _record_query signature as Unpack[RecordQueryKwargs] so the test helper
accepts the same set and shapes of kwargs as ConversationRecordQuery.
In `@tests/unit/storage/test_store_ops.py`:
- Around line 82-89: Update the TypedDict RecordQueryKwargs so it matches
ConversationRecordQuery's constructor: add missing optional keys used by the
dataclass (e.g., title_contains, offset) and make nullable fields match the
dataclass types (e.g., change limit to Optional[int] or allow None). Ensure all
fields forwarded into ConversationRecordQuery have the same names and
optionality so mypy accepts passing RecordQueryKwargs directly into the
ConversationRecordQuery constructor.
- Around line 1160-1165: The test currently casts conv_data.get("messages") to
list[dict] without runtime checks; instead narrow and validate the shape before
casting: confirm conv_data.get("messages") is a list, iterate over it and for
each element (msg_data) assert it's a dict, then check 'role' and 'text' exist
(or provide defaults) and are strings (validating raw_role and raw_text) before
using or casting message_payloads; update the block around
message_payloads/conv_data/msg_data/raw_role/raw_text to perform these runtime
checks rather than trusting cast().
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: cf97577c-bb5a-4e6a-8cc3-8631ed8efdeb
📒 Files selected for processing (12)
tests/unit/storage/test_archive_search_contracts.pytests/unit/storage/test_backend.pytests/unit/storage/test_convergence_stale_to_healthy.pytests/unit/storage/test_embedding_stats.pytests/unit/storage/test_fts5.pytests/unit/storage/test_query_mappers.pytests/unit/storage/test_query_security.pytests/unit/storage/test_retrieval_readiness_laws.pytests/unit/storage/test_scale.pytests/unit/storage/test_schema_safety.pytests/unit/storage/test_store_ops.pytests/unit/storage/test_vec.py
| class _FakeRepo(RepositoryArchiveSearchMixin): | ||
| queries: Any | ||
| queries: SQLiteQueryStore | ||
|
|
||
| def __init__(self, queries: _FakeQueries) -> None: | ||
| self.queries = queries | ||
| self.queries = cast(SQLiteQueryStore, queries) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Avoid casting the fake to the full query store.
_FakeQueries only implements the archive-search subset, but cast(SQLiteQueryStore, queries) tells the type checker it satisfies the entire concrete store. Prefer a narrow Protocol for the three methods used by RepositoryArchiveSearchMixin, or narrow the mixin’s TYPE_CHECKING contract so this test double remains honest.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_archive_search_contracts.py` around lines 60 - 64,
The test fake _FakeRepo is lying to the type system by casting _FakeQueries to
SQLiteQueryStore; instead narrow the API surface so the fake only promises the
three methods used by RepositoryArchiveSearchMixin: define a Protocol (e.g.,
ArchiveSearchStoreProtocol) listing those methods and type _FakeRepo.queries as
that Protocol (or update RepositoryArchiveSearchMixin's TYPE_CHECKING contract
to reference the narrower Protocol), replace the cast to SQLiteQueryStore with
the Protocol type, and ensure _FakeQueries implements that Protocol so the test
double remains honest (references: _FakeRepo, RepositoryArchiveSearchMixin,
_FakeQueries, SQLiteQueryStore, TYPE_CHECKING).
| def mock_import( | ||
| name: str, | ||
| globals_: dict[str, object] | None = None, | ||
| locals_: dict[str, object] | None = None, | ||
| fromlist: tuple[str, ...] = (), | ||
| level: int = 0, | ||
| ) -> object: | ||
| if name == "sqlite_vec": | ||
| raise ImportError("No module named 'sqlite_vec'") | ||
| return original_import(name, *args, **kwargs) | ||
| return original_import(name, globals_, locals_, fromlist, level) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Demonstrates that a patched __import__ stub with globals_/locals_ rejects
# keyword calls accepted by the real builtin.
python - <<'PY'
def mock_import(
name: str,
globals_: dict[str, object] | None = None,
locals_: dict[str, object] | None = None,
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> object:
return object()
try:
mock_import("math", globals={})
except TypeError as exc:
print(type(exc).__name__, exc)
PYRepository: Sinity/polylogue
Length of output: 128
🏁 Script executed:
sed -n '775,820p' tests/unit/storage/test_fts5.pyRepository: Sinity/polylogue
Length of output: 1885
Fix mock_import parameter names to match __import__ signature.
Both mock_import functions use globals_ and locals_ as parameter names, preventing callers from using the standard keyword arguments globals= and locals= that the built-in __import__ accepts. Rename the parameters to globals and locals (with # noqa: A002 to suppress linting warnings), and update the call to original_import accordingly.
Proposed fix
def mock_import(
name: str,
- globals_: dict[str, object] | None = None,
- locals_: dict[str, object] | None = None,
+ globals: dict[str, object] | None = None, # noqa: A002
+ locals: dict[str, object] | None = None, # noqa: A002
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> object:
if name == "sqlite_vec":
raise ImportError("No module named 'sqlite_vec'")
- return original_import(name, globals_, locals_, fromlist, level)
+ return original_import(name, globals, locals, fromlist, level)Also applies to: 807-816
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_fts5.py` around lines 778 - 787, Rename the
mock_import function parameters to match the built-in __import__ signature by
changing globals_ -> globals and locals_ -> locals (add "# noqa: A002" to those
parameter names to silence the lint warning), and update the call to
original_import(name, globals, locals, fromlist, level) so callers can pass the
standard globals= and locals= kwargs; apply this change to both mock_import
definitions (the one referencing sqlite_vec and the other at the other
location).
| @pytest.fixture | ||
| async def temp_repo(tmp_path: Any) -> Any: | ||
| async def temp_repo(tmp_path: Path) -> ConversationRepository: | ||
| db_path = tmp_path / "test.db" | ||
| backend = SQLiteBackend(db_path=db_path) | ||
| return ConversationRepository(backend=backend) |
There was a problem hiding this comment.
Close the backend owned by this fixture.
temp_repo creates a SQLiteBackend per test but never tears it down. Convert the fixture to yield and close the backend in finally to avoid leaking async SQLite resources across the security property tests.
Proposed fixture cleanup
+from collections.abc import AsyncIterator
from pathlib import Path
from typing import cast
@@
`@pytest.fixture`
-async def temp_repo(tmp_path: Path) -> ConversationRepository:
+async def temp_repo(tmp_path: Path) -> AsyncIterator[ConversationRepository]:
db_path = tmp_path / "test.db"
backend = SQLiteBackend(db_path=db_path)
- return ConversationRepository(backend=backend)
+ try:
+ yield ConversationRepository(backend=backend)
+ finally:
+ await backend.close()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @pytest.fixture | |
| async def temp_repo(tmp_path: Any) -> Any: | |
| async def temp_repo(tmp_path: Path) -> ConversationRepository: | |
| db_path = tmp_path / "test.db" | |
| backend = SQLiteBackend(db_path=db_path) | |
| return ConversationRepository(backend=backend) | |
| from collections.abc import AsyncIterator | |
| from pathlib import Path | |
| from typing import cast | |
| `@pytest.fixture` | |
| async def temp_repo(tmp_path: Path) -> AsyncIterator[ConversationRepository]: | |
| db_path = tmp_path / "test.db" | |
| backend = SQLiteBackend(db_path=db_path) | |
| try: | |
| yield ConversationRepository(backend=backend) | |
| finally: | |
| await backend.close() |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_query_security.py` around lines 24 - 28, Convert the
temp_repo fixture to an async yield-style fixture that yields the
ConversationRepository instance and ensures the SQLiteBackend is closed in a
finally block; create the backend with SQLiteBackend(...) as before, yield
ConversationRepository(backend=backend) from temp_repo, and in the finally call
await backend.close() (or the backend's async shutdown method) to avoid leaking
the async SQLite resource.
| async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None: | ||
| try: | ||
| conv = await temp_repo.view(cast(Any, None)) | ||
| conv = await temp_repo.view(cast(str, None)) | ||
| assert conv is None |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Don’t cast None into a valid str input.
This is intentionally testing an invalid value, but cast(str, None) hides that from the type checker. Prefer keeping the invalid call explicit with a local type: ignore[arg-type].
Proposed clearer negative-input test
async def test_none_parameters_handled(temp_repo: ConversationRepository) -> None:
try:
- conv = await temp_repo.view(cast(str, None))
+ conv = await temp_repo.view(None) # type: ignore[arg-type]
assert conv is None🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_query_security.py` around lines 106 - 109, The test
test_none_parameters_handled currently hides the invalid input by using
cast(str, None); instead call temp_repo.view with a plain None to make the
negative-input explicit and silence the type checker with a local type ignore
(e.g., pass None to temp_repo.view # type: ignore[arg-type]). Update the
assertion flow around the await temp_repo.view(...) call (in the same test
function) so the test still expects None while removing the cast(str, None).
| class RecordQueryKwargs(TypedDict, total=False): | ||
| provider: str | ||
| since: str | ||
| until: str | ||
| path_terms: tuple[str, ...] | ||
| action_terms: tuple[str, ...] | ||
| tool_terms: tuple[str, ...] | ||
| limit: int | ||
| has_tool_use: bool | ||
|
|
||
|
|
||
| def _record_query(**kwargs: Unpack[RecordQueryKwargs]) -> ConversationRecordQuery: |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Mirror the full query kwargs contract here too.
Line 39 types a helper that immediately constructs ConversationRecordQuery, but the TypedDict excludes valid fields such as source, providers, title_contains, offset, exclusions, and min/max filters; it also narrows nullable fields like limit, since, and until. This makes the test helper less reusable than the constructor it wraps.
♻️ Proposed alignment
class RecordQueryKwargs(TypedDict, total=False):
- provider: str
- since: str
- until: str
+ source: str | None
+ provider: str | None
+ providers: tuple[str, ...]
+ parent_id: str | None
+ since: str | None
+ until: str | None
+ title_contains: str | None
path_terms: tuple[str, ...]
action_terms: tuple[str, ...]
+ excluded_action_terms: tuple[str, ...]
tool_terms: tuple[str, ...]
- limit: int
+ excluded_tool_terms: tuple[str, ...]
+ limit: int | None
+ offset: int
has_tool_use: bool
+ has_thinking: bool
+ min_messages: int | None
+ max_messages: int | None
+ min_words: int | None🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_scale.py` around lines 39 - 50, The TypedDict
RecordQueryKwargs used by the helper _record_query should mirror the full
ConversationRecordQuery contract: extend RecordQueryKwargs to include missing
keys such as source, providers, title_contains, offset, any exclusion fields,
min/max numeric filters, and any other optional flags present on
ConversationRecordQuery, and relax types for nullable fields (e.g., limit,
since, until) to allow None/optional values; then keep _record_query signature
as Unpack[RecordQueryKwargs] so the test helper accepts the same set and shapes
of kwargs as ConversationRecordQuery.
| class RecordQueryKwargs(TypedDict, total=False): | ||
| provider: str | ||
| path_terms: tuple[str, ...] | ||
| action_terms: tuple[str, ...] | ||
| excluded_action_terms: tuple[str, ...] | ||
| tool_terms: tuple[str, ...] | ||
| excluded_tool_terms: tuple[str, ...] | ||
| limit: int |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Keep RecordQueryKwargs aligned with ConversationRecordQuery.
Line 82 defines a kwargs contract for a helper that forwards directly into ConversationRecordQuery, but it omits valid constructor fields and narrows nullable ones such as limit. A future test using title_contains, offset, or limit=None would be rejected by mypy even though the dataclass supports it.
♻️ Proposed alignment
class RecordQueryKwargs(TypedDict, total=False):
- provider: str
+ source: str | None
+ provider: str | None
+ providers: tuple[str, ...]
+ parent_id: str | None
+ since: str | None
+ until: str | None
+ title_contains: str | None
path_terms: tuple[str, ...]
action_terms: tuple[str, ...]
excluded_action_terms: tuple[str, ...]
tool_terms: tuple[str, ...]
excluded_tool_terms: tuple[str, ...]
- limit: int
+ limit: int | None
+ offset: int
+ has_tool_use: bool
+ has_thinking: bool
+ min_messages: int | None
+ max_messages: int | None
+ min_words: int | NoneAlso applies to: 228-229
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_store_ops.py` around lines 82 - 89, Update the
TypedDict RecordQueryKwargs so it matches ConversationRecordQuery's constructor:
add missing optional keys used by the dataclass (e.g., title_contains, offset)
and make nullable fields match the dataclass types (e.g., change limit to
Optional[int] or allow None). Ensure all fields forwarded into
ConversationRecordQuery have the same names and optionality so mypy accepts
passing RecordQueryKwargs directly into the ConversationRecordQuery constructor.
| message_payloads = cast(list[dict[str, object]], conv_data.get("messages", [])) | ||
| for i, msg_data in enumerate(message_payloads): | ||
| raw_role = msg_data.get("role", "user") | ||
| assert isinstance(raw_role, str) | ||
| raw_text = msg_data.get("text", "") | ||
| assert isinstance(raw_text, str) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Narrow generated message payloads before casting away shape uncertainty.
Line 1160 still trusts the property payload shape with cast(...). Since this test now validates generated fields before constructing records, validate the messages container and each element before reading role/text.
♻️ Proposed runtime narrowing
- message_payloads = cast(list[dict[str, object]], conv_data.get("messages", []))
- for i, msg_data in enumerate(message_payloads):
+ raw_messages = conv_data.get("messages", [])
+ assert isinstance(raw_messages, list)
+ for i, msg_data in enumerate(raw_messages):
+ assert isinstance(msg_data, dict)
raw_role = msg_data.get("role", "user")
assert isinstance(raw_role, str)
raw_text = msg_data.get("text", "")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/storage/test_store_ops.py` around lines 1160 - 1165, The test
currently casts conv_data.get("messages") to list[dict] without runtime checks;
instead narrow and validate the shape before casting: confirm
conv_data.get("messages") is a list, iterate over it and for each element
(msg_data) assert it's a dict, then check 'role' and 'text' exist (or provide
defaults) and are strings (validating raw_role and raw_text) before using or
casting message_payloads; update the block around
message_payloads/conv_data/msg_data/raw_role/raw_text to perform these runtime
checks rather than trusting cast().
## Summary - Removes explicit dynamic typing from `tests/unit/storage`. - Replaces broad test casts with typed query kwargs, fixture types, and narrow protocol/test doubles. - Tightens sqlite-vec, FTS5, backend, repair-convergence, and storage CRUD test contracts without changing production behavior. ## Problem The mypy/refactoring campaign had cleared source and several test surfaces, but unit storage tests still carried broad `Any` usage around repository fixtures, query helpers, sqlite-vec doubles, and property-generated payloads. That left storage tests weaker than the storage code they exercise. ## Solution - Type storage fixtures and helpers around `ConversationRepository`, `Config`, `Path`, `sqlite3.Row`, and typed query kwargs. - Replace private-method `Any` casts in backend/sqlite-vec tests with protocols or local typed doubles. - Narrow property-generated conversation payloads before constructing storage records. - Verify `tests/unit/storage` has no explicit `Any` occurrences. Ref #281 ## Verification - `ruff format tests/unit/storage` - `ruff check tests/unit/storage` - `mypy tests/unit/storage` - `pytest -q tests/unit/storage` - `PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quick` - `PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH git push -u origin feature/refactor/storage-test-contracts`
Unit storage tests still carried broad `Any` usage around repository fixtures, query helpers, sqlite-vec doubles, and property-generated payloads. That left storage tests weaker than the storage code they exercise. Removes explicit dynamic typing from `tests/unit/storage`. Types storage fixtures and helpers around `ConversationRepository`, `Config`, `Path`, `sqlite3.Row`, and typed query kwargs. Replaces private-method `Any` casts in backend/sqlite-vec tests with protocols or local typed doubles. Narrows property-generated conversation payloads before constructing storage records. Tightens sqlite-vec, FTS5, backend, repair-convergence, and storage CRUD test contracts without changing production behavior. Verification: ruff + mypy + pytest over `tests/unit/storage`; devtools verify --quick green. Ref #281
Unit storage tests still carried broad `Any` usage around repository fixtures, query helpers, sqlite-vec doubles, and property-generated payloads. That left storage tests weaker than the storage code they exercise. Removes explicit dynamic typing from `tests/unit/storage`. Types storage fixtures and helpers around `ConversationRepository`, `Config`, `Path`, `sqlite3.Row`, and typed query kwargs. Replaces private-method `Any` casts in backend/sqlite-vec tests with protocols or local typed doubles. Narrows property-generated conversation payloads before constructing storage records. Tightens sqlite-vec, FTS5, backend, repair-convergence, and storage CRUD test contracts without changing production behavior. Verification: ruff + mypy + pytest over `tests/unit/storage`; devtools verify --quick green. Ref #281
Unit storage tests still carried broad `Any` usage around repository fixtures, query helpers, sqlite-vec doubles, and property-generated payloads. That left storage tests weaker than the storage code they exercise. Removes explicit dynamic typing from `tests/unit/storage`. Types storage fixtures and helpers around `ConversationRepository`, `Config`, `Path`, `sqlite3.Row`, and typed query kwargs. Replaces private-method `Any` casts in backend/sqlite-vec tests with protocols or local typed doubles. Narrows property-generated conversation payloads before constructing storage records. Tightens sqlite-vec, FTS5, backend, repair-convergence, and storage CRUD test contracts without changing production behavior. Verification: ruff + mypy + pytest over `tests/unit/storage`; devtools verify --quick green. Ref #281
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
tests/unit/storage.Problem
The mypy/refactoring campaign had cleared source and several test surfaces, but unit storage tests still carried broad
Anyusage around repository fixtures, query helpers, sqlite-vec doubles, and property-generated payloads. That left storage tests weaker than the storage code they exercise.Solution
ConversationRepository,Config,Path,sqlite3.Row, and typed query kwargs.Anycasts in backend/sqlite-vec tests with protocols or local typed doubles.tests/unit/storagehas no explicitAnyoccurrences.Ref #281
Verification
ruff format tests/unit/storageruff check tests/unit/storagemypy tests/unit/storagepytest -q tests/unit/storagePATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quickPATH=/tmp/polylogue-281/.cache/codex-bin:$PATH git push -u origin feature/refactor/storage-test-contracts