Skip to content

test: type storage contracts - #290

Merged
Sinity merged 1 commit into
masterfrom
feature/refactor/storage-test-contracts
Apr 21, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/refactor/storage-test-contracts

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

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

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR refactors type annotations across 12 storage test modules, replacing generic Any types with concrete types, Protocols, and TypedDicts. Changes include introducing MutableSchemaBackend Protocol, RecordQueryKwargs TypedDict, and ConversationRepository annotations across test fixtures and parameters.

Changes

Cohort / File(s) Summary
Protocol & Type Alias Introductions
tests/unit/storage/test_backend.py, tests/unit/storage/test_vec.py
Introduced MutableSchemaBackend Protocol with _ensure_schema async callable; introduced Embedding, SearchRows type aliases and EmbeddingFetcher, MutableSqliteVecProvider Protocols to describe provider contracts with runtime type assertions for payload/header validation.
TypedDict Replacements for Query Arguments
tests/unit/storage/test_scale.py, tests/unit/storage/test_store_ops.py
Replaced _record_query(**kwargs: Any) with RecordQueryKwargs TypedDict (using Unpack) to explicitly list supported query fields; added runtime type assertions for conversation/message fields in test_store_ops.
Fixture & Parameter Type Tightening
tests/unit/storage/test_convergence_stale_to_healthy.py, tests/unit/storage/test_fts5.py, tests/unit/storage/test_query_security.py, tests/unit/storage/test_retrieval_readiness_laws.py
Updated fixture and test parameter annotations from Any to concrete types (Config, ConversationRepository, Path); adjusted db access patterns where fixtures expose db_path or get_config().
Self & Basic Parameter Type Tightening
tests/unit/storage/test_archive_search_contracts.py, tests/unit/storage/test_embedding_stats.py, tests/unit/storage/test_query_mappers.py, tests/unit/storage/test_schema_safety.py
Replaced self: Any with self: object; replaced tmp_path: Any with tmp_path: Path; updated stub/helper method signatures; removed unused Any imports; tightened return type annotations (e.g., `dict[str, int

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Types now tight, no more Any haze,
Protocols bloom through test pathways,
TypedDicts guard each query's name,
Safety springs from stronger frames! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'test: type storage contracts' directly and clearly summarizes the main change: adding type annotations to storage-related test contracts.
Description check ✅ Passed The description fully adheres to the template with all required sections: Summary, Problem, Solution, and Verification completed. Risks section is appropriately omitted as none exist.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/storage-test-contracts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 659e3ee and cb8b0ba.

📒 Files selected for processing (12)
  • tests/unit/storage/test_archive_search_contracts.py
  • tests/unit/storage/test_backend.py
  • tests/unit/storage/test_convergence_stale_to_healthy.py
  • tests/unit/storage/test_embedding_stats.py
  • tests/unit/storage/test_fts5.py
  • tests/unit/storage/test_query_mappers.py
  • tests/unit/storage/test_query_security.py
  • tests/unit/storage/test_retrieval_readiness_laws.py
  • tests/unit/storage/test_scale.py
  • tests/unit/storage/test_schema_safety.py
  • tests/unit/storage/test_store_ops.py
  • tests/unit/storage/test_vec.py

Comment on lines 60 to +64
class _FakeRepo(RepositoryArchiveSearchMixin):
queries: Any
queries: SQLiteQueryStore

def __init__(self, queries: _FakeQueries) -> None:
self.queries = queries
self.queries = cast(SQLiteQueryStore, queries)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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).

Comment on lines +778 to +787
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 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)
PY

Repository: Sinity/polylogue

Length of output: 128


🏁 Script executed:

sed -n '775,820p' tests/unit/storage/test_fts5.py

Repository: 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).

Comment on lines 24 to 28
@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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
@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.

Comment on lines +106 to 109
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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).

Comment on lines +39 to +50
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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.

Comment on lines +82 to +89
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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 | None

Also 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.

Comment on lines +1160 to +1165
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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().

@Sinity
Sinity merged commit b82e640 into master Apr 21, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/storage-test-contracts branch April 21, 2026 10:18
Sinity added a commit that referenced this pull request Apr 22, 2026
## 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`
Sinity added a commit that referenced this pull request Apr 22, 2026
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
Sinity added a commit that referenced this pull request Apr 22, 2026
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
Sinity added a commit that referenced this pull request Apr 22, 2026
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
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 7 finding(s) confirmed still present → tracked in #550.

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@Sinity
Sinity requested a review from Copilot May 1, 2026 00:43
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@Sinity
Sinity removed the request for review from Copilot May 1, 2026 01:05
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@Sinity
Sinity requested a review from Copilot May 1, 2026 01:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants