Skip to content

test: type strategy and infra contracts - #287

Merged
Sinity merged 2 commits into
masterfrom
feature/refactor/test-strategy-contracts
Apr 21, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/refactor/test-strategy-contracts

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Replaces broad Any in tests/infra strategy helpers, Drive mocks, semantic-fact helpers, PTY/MCP helpers, large-batch/chaos builders, and shared pytest fixtures with explicit JSON, protocol, fixture, and typed-dict contracts.
  • Keeps the flexible test-builder APIs by validating explicit payload dictionaries through Pydantic rather than forwarding untyped **kwargs into generated constructors.
  • Makes the repo-identity test derive the active checkout name from REPO_ROOT, so temporary worktree clones such as polylogue-281 verify correctly.

Problem

The mypy cleanup has made production and core test contracts stricter, but reusable test infrastructure still carried broad dynamic types. Those helpers feed source laws, schema laws, MCP tests, Drive tests, and ingestion-hostility tests, so leaving them untyped weakens the suite exactly where generated and cross-surface tests should be most precise.

Ref #281

Solution

  • Added explicit provider payload/source-case contracts and JSON narrowing in tests/infra/strategies/providers.py.
  • Added typed strategy records and helper return contracts in schema, message, filter, and pipeline strategy helpers.
  • Replaced Drive mock dynamic seams with a writable protocol, param-spec retry wrapper, concrete mock downloader result types, and typed service response dictionaries.
  • Tightened semantic fact extraction around domain conversations, storage records, CLI JSON payloads, and SQLite aggregate rows.
  • Typed shared pytest fixtures for repositories, backends, CLI runners, synthetic sources, and conversation builders.

Verification

  • ruff format tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py
  • ruff check tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py
  • mypy tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py
  • pytest -q tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_gateway.py tests/unit/test_cross_surface_agreement.py tests/unit/pipeline/test_ingestion_chaos.py tests/integration/test_chronology_extremes.py (141 passed)
  • pytest -q tests/unit/mcp tests/unit/core/test_schema_laws.py tests/unit/core/test_filters_props.py tests/unit/lib/test_filter_executor.py tests/unit/sources/test_parsers_props.py tests/unit/sources/test_source_laws.py tests/property/test_rendering_preservation.py tests/unit/pipeline/test_resilience.py (404 passed)
  • PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quick
  • pytest -q --tb=short --ignore=tests/integration (4975 passed)
  • PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH git push -u origin feature/refactor/test-strategy-contracts (pre-push devtools verify --quick passed)

Note: I also attempted full devtools verify. Its pytest subphase first exposed the hard-coded repo-name assertion fixed in this PR; a later run hit local xdist teardown/process instability without a test failure. The exact pytest command wrapped by devtools verify passed cleanly afterward.

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Systematic type annotation tightening across test infrastructure: replacing broad Any types with concrete types (JSONDocument, JSONRecord, JSONValue, protocol types, and TypedDict declarations), introducing typed helper accessors for safer field extraction, and leveraging Pydantic's model_validate() for stricter construction validation.

Changes

Cohort / File(s) Summary
Test Fixtures & Runners
tests/conftest.py
Tightened fixture return types from Any to concrete types (ConversationRepository, AsyncIterator[SQLiteBackend], CliRunner); introduced MockHttpModule and typed ModuleType for mocked imports; added TYPE_CHECKING guards for type imports.
Builder Helpers
tests/infra/builders.py
Refactored make_msg and make_conv to use model_validate() with explicit payload dicts instead of direct instantiation; changed **kwargs from Any to object.
Mock Test Infrastructure
tests/infra/drive_mocks.py, tests/infra/chaos_sources.py
Introduced BinaryWritable protocol; tightened mock signatures with ParamSpec/TypeVar for call_with_retry; added ChaosFileSpec typed dict with typed accessor helpers (_spec_str, _spec_int, _spec_indices).
PTY & Terminal Rendering
tests/infra/pty_cli.py, tests/infra/mcp.py
Added TerminalChar protocol for terminal line data; narrowed coroutine typing from Any to object in MCP invocation.
JSON & Data Strategies
tests/infra/large_batches.py, tests/infra/strategies/messages.py, tests/infra/strategies/schema.py, tests/infra/strategies/schema_driven.py, tests/infra/strategies/filters.py
Introduced JSONRecord and JSONDocument type aliases; replaced dict[str, Any] return types across hypothesis strategies with typed alternatives; narrowed JSON schema handling to JSONValue.
Provider & Semantic Payload Strategies
tests/infra/strategies/providers.py, tests/infra/strategies/pipeline.py
Added ProviderPayload and ProviderSourceCase types; introduced ValidationContract and ParseMergeTotals TypedDicts; replaced dict[str, Any] with strongly-typed JSON/payload abstractions across ChatGPT/Claude/Gemini/Codex strategies.
Semantic Facts & Analysis
tests/infra/semantic_facts.py
Refactored ConversationFacts and ArchiveFacts to accept typed Conversation, JSONDocument, ConversationRecord, MessageRecord, and sqlite3.Connection instead of Any; replaced dynamic getattr/isinstance with direct attribute access and typed helpers (_string_value, _optional_string, _content_blocks).
Test Assertions
tests/unit/core/test_repo_identity.py
Updated hardcoded repo name assertion to use REPO_ROOT.name instead of the literal string "polylogue".

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Possibly related PRs

Poem

🐰 Hops around with whiskers twitched,
Types once wild, now firmly stitched!
JSONDocument, concrete and bright,
No more Any shadows in the test-suite night,
Pydantic validates each humble message right! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.30% 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 strategy and infra contracts' accurately summarizes the main change: replacing broad Any types with explicit typed contracts across test infrastructure and strategy helpers.
Description check ✅ Passed The PR description comprehensively covers all required sections: summary explaining what changed, problem context, solution details, and verification with specific commands and test results.
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/test-strategy-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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/infra/chaos_sources.py (1)

124-175: ⚠️ Potential issue | 🟡 Minor

Behavior change: unknown/missing type now silently no-ops.

Previously spec["type"] would raise KeyError surfacing a programming error; with _spec_str(spec, "type") defaulting to "", an unrecognized or unset type falls through all branches and the target path is never created. All current add_* helpers set "type", so this is latent rather than active, but it weakens the safety net. Consider asserting membership or raising on unknown spec_type in the else branch to preserve the prior fail-loud behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/chaos_sources.py` around lines 124 - 175, The build method now
silently ignores specs with missing/unknown types because _spec_str(spec,
"type") defaults to "", so add a fail-fast check after computing spec_type in
build(): if spec_type is falsy or not in the known set
("empty","binary_garbage","valid_jsonl","jsonl_with_bom","corrupted_jsonl")
raise a ValueError (or assert) that includes the offending filename and spec;
this preserves prior KeyError-like behavior and points to the problematic spec
(use symbols: build, _spec_str, self._files, and the known spec_type values or
self._get_corruption_fn to locate the relevant logic).
tests/infra/strategies/messages.py (1)

10-20: 🧹 Nitpick | 🔵 Trivial

Prefer the shared recursive JSON alias for raw strategy records.

These raw strategy outputs are JSON payloads, but dict[str, object] permits non-JSON values. Consider aliasing JSONRecord to JSONDocument for the raw payload strategies; keep provider_meta as dict[str, object] where the domain model requires it.

♻️ Proposed raw JSON alias tightening
-from polylogue.lib.roles import Role
+from polylogue.lib.json import JSONDocument
+from polylogue.lib.roles import Role
 from polylogue.types import ConversationId, Provider
 
 if TYPE_CHECKING:
     from polylogue.lib.models import Conversation, Message
 
-JSONRecord: TypeAlias = dict[str, object]
+JSONRecord: TypeAlias = JSONDocument

Also applies to: 28-155, 169-204

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/strategies/messages.py` around lines 10 - 20, Replace the
permissive TypeAlias JSONRecord = dict[str, object] with the shared recursive
JSON alias used elsewhere (use the canonical name JSONDocument) so raw strategy
outputs are constrained to valid JSON types; update the alias declaration
(JSONRecord) to point to JSONDocument and update all usages in this module
accordingly, but leave any provider_meta annotated as dict[str, object]
unchanged where the domain model requires non-JSON values.
🤖 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/infra/chaos_sources.py`:
- Around line 26-38: _spec_int currently treats booleans as ints because
isinstance(value, int) is true for bool; update the _spec_int accessor to reject
bools (e.g., check type(value) is int or use isinstance(value, int) and not
isinstance(value, bool)) so it only returns actual integers and otherwise
returns the default; keep the function name _spec_int and its signature
unchanged and ensure the return behavior remains an int.

In `@tests/infra/pty_cli.py`:
- Around line 36-40: The Protocol TerminalChar declares a mutable attribute data
but pyte.Char's data is immutable; change TerminalChar to expose data as a
read-only property (e.g., replace the data attribute with a property signature
like def data(self) -> str: ... in the Protocol) so TerminalChar.data is
read-only and clearly matches pyte.Char's immutability for type checkers and
readers.

In `@tests/infra/semantic_facts.py`:
- Around line 118-124: The comprehension in from_db_connection uses
mapping-style access (row["provider_name"], row["cnt"]) which fails for plain
sqlite3.Connection without a row_factory; change provider_rows handling to use
positional indexing (row[0] for provider_name, row[1] for cnt) when building
provider_counts and ensure you cast to str/int as before; update any other row
dict-style accesses in from_db_connection that assume sqlite3.Row to use
positional indexing via conn.execute(...).fetchall()/fetchone().

In `@tests/infra/strategies/providers.py`:
- Around line 57-69: The current helpers (_json_document_from_bytes and
_jsonl_documents) call json_document(json_loads(...)) which silently coerces
non-object JSON into {}; instead, validate that json_loads(...) returns a
mapping/object and fail fast by raising an error when the decoded value is not a
dict. Update _json_document_from_bytes to decode with json_loads(raw), assert
isinstance(result, dict) (or raise ValueError with context mentioning the
provider/raw), and only then call json_document; similarly update
_jsonl_documents to decode each line, check each decoded value is a dict
(include line index/context in the error), and raise rather than returning
empty/coerced documents; keep decode_provider_payload logic and _JSONL_PROVIDERS
unchanged.
- Around line 371-398: The sampled semantic strategies
(chatgpt_semantic_message_strategy, claude_ai_semantic_message_strategy,
claude_code_semantic_record_strategy, gemini_semantic_message_strategy)
currently use dict(draw(...)) which only shallow-copies the top-level mapping
and leaves nested lists/dicts shared between Hypothesis examples; change each
strategy to return a deep copy of the sampled fixture (e.g., obtain the raw
sample via draw(st.sampled_from(...)), run copy.deepcopy(raw) and return that
deep-copied value) so nested structures aren’t shared across examples—follow the
same approach already used in codex_semantic_record_strategy (deserialize/clone)
to ensure isolated fixtures.

In `@tests/infra/strategies/schema.py`:
- Around line 12-15: Replace the loose TypeAlias JSONRecord that currently uses
dict[str, object] with the recursive JSON contract by aliasing JSONRecord to the
imported JSONDocument; update all other occurrences in this module (e.g., the
uses around the json_document_strategy and other definitions between the earlier
and later JSON-related blocks) to reference JSONRecord as JSONDocument so the
strategy uses the stricter recursive JSON typing provided by JSONDocument.

---

Outside diff comments:
In `@tests/infra/chaos_sources.py`:
- Around line 124-175: The build method now silently ignores specs with
missing/unknown types because _spec_str(spec, "type") defaults to "", so add a
fail-fast check after computing spec_type in build(): if spec_type is falsy or
not in the known set
("empty","binary_garbage","valid_jsonl","jsonl_with_bom","corrupted_jsonl")
raise a ValueError (or assert) that includes the offending filename and spec;
this preserves prior KeyError-like behavior and points to the problematic spec
(use symbols: build, _spec_str, self._files, and the known spec_type values or
self._get_corruption_fn to locate the relevant logic).

In `@tests/infra/strategies/messages.py`:
- Around line 10-20: Replace the permissive TypeAlias JSONRecord = dict[str,
object] with the shared recursive JSON alias used elsewhere (use the canonical
name JSONDocument) so raw strategy outputs are constrained to valid JSON types;
update the alias declaration (JSONRecord) to point to JSONDocument and update
all usages in this module accordingly, but leave any provider_meta annotated as
dict[str, object] unchanged where the domain model requires non-JSON values.
🪄 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: 3288ab24-3506-4898-9ac4-90d2c515d615

📥 Commits

Reviewing files that changed from the base of the PR and between 879c3af and 51bf586.

📒 Files selected for processing (15)
  • tests/conftest.py
  • tests/infra/builders.py
  • tests/infra/chaos_sources.py
  • tests/infra/drive_mocks.py
  • tests/infra/large_batches.py
  • tests/infra/mcp.py
  • tests/infra/pty_cli.py
  • tests/infra/semantic_facts.py
  • tests/infra/strategies/filters.py
  • tests/infra/strategies/messages.py
  • tests/infra/strategies/pipeline.py
  • tests/infra/strategies/providers.py
  • tests/infra/strategies/schema.py
  • tests/infra/strategies/schema_driven.py
  • tests/unit/core/test_repo_identity.py

Comment on lines +26 to +38
def _spec_str(spec: ChaosFileSpec, key: str, default: str = "") -> str:
value = spec.get(key, default)
return value if isinstance(value, str) else default


def _spec_int(spec: ChaosFileSpec, key: str, default: int = 0) -> int:
value = spec.get(key, default)
return value if isinstance(value, int) else default


def _spec_indices(spec: ChaosFileSpec) -> list[int]:
value = spec.get("corrupt_indices", [])
return [item for item in value if isinstance(item, int)] if isinstance(value, list) else []

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

Minor: _spec_int accepts bool as int.

Since bool is a subclass of int, isinstance(value, int) returns True for booleans. Not exploitable given current call sites (only count/size which add_* helpers populate with real ints), but worth tightening if these accessors are reused:

Proposed hardening
 def _spec_int(spec: ChaosFileSpec, key: str, default: int = 0) -> int:
     value = spec.get(key, default)
-    return value if isinstance(value, int) else default
+    return value if isinstance(value, int) and not isinstance(value, bool) else default
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/chaos_sources.py` around lines 26 - 38, _spec_int currently
treats booleans as ints because isinstance(value, int) is true for bool; update
the _spec_int accessor to reject bools (e.g., check type(value) is int or use
isinstance(value, int) and not isinstance(value, bool)) so it only returns
actual integers and otherwise returns the default; keep the function name
_spec_int and its signature unchanged and ensure the return behavior remains an
int.

Comment thread tests/infra/pty_cli.py
Comment on lines +36 to +40
class TerminalChar(Protocol):
"""Subset of pyte's Char object used for snapshot rendering."""

data: 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

🧩 Analysis chain

🌐 Web query:

mypy Protocol mutable attribute vs read-only property NamedTuple compatibility

💡 Result:

In mypy, Protocol attributes declared as simple fields (e.g., x: int) are treated as mutable (settable). NamedTuple fields are internally treated as read-only properties (via Var with is_property=True), so a NamedTuple is compatible with a Protocol only if the Protocol declares the attribute as a read-only @property (e.g., @property def x(self) -> int: ...). A simple mutable field in the Protocol expects a settable attribute, which NamedTuple fields are not, causing incompatibility (fixed by treating NamedTuples as properties in mypy since ~2018 via #5293). Conversely, a read-only property in the Protocol is satisfied by both read-only properties and regular fields (covariant subtyping allowed since reads-only), making NamedTuples compatible. Example: from typing import NamedTuple from typing_extensions import Protocol class P(Protocol): @property def x(self) -> int: ... class A(NamedTuple): x: int def f(a: P): ... a = A(42) f(a) # OK If Protocol uses x: int (mutable), f(a) errors due to invariance/mutability mismatch.

Citations:


🏁 Script executed:

# First, check the file structure and imports
head -50 tests/infra/pty_cli.py

Repository: Sinity/polylogue

Length of output: 1215


🏁 Script executed:

# Search for pyte imports and usage
rg "pyte" tests/infra/pty_cli.py -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 1626


🏁 Script executed:

# Search for TerminalChar usage across the codebase
rg "TerminalChar" . --type py -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 1073


🏁 Script executed:

# Check if there are type checking issues reported or tests running mypy
rg "mypy|type.*check" . --type py --type sh --type toml --type yaml -l

Repository: Sinity/polylogue

Length of output: 226


🏁 Script executed:

# Check pyproject.toml for mypy configuration
cat pyproject.toml | grep -A 20 "\[tool.mypy\]"

Repository: Sinity/polylogue

Length of output: 629


🏁 Script executed:

# Search for pyte type stubs or type annotations in the repo
find . -name "*.pyi" -o -name "py.typed" | head -20

Repository: Sinity/polylogue

Length of output: 80


🏁 Script executed:

# Look for pyte documentation or check what type screen.history actually has
rg "history\." tests/infra/pty_cli.py -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 352


🏁 Script executed:

# Check if there are any type checking runs or errors reported
rg "error:" . --type py -A 1 -B 1 | head -30

Repository: Sinity/polylogue

Length of output: 1974


🏁 Script executed:

# Check if pyte is in requirements or pyproject.toml
rg "pyte" . --type toml --type txt

Repository: Sinity/polylogue

Length of output: 1462


Consider making TerminalChar.data a read-only protocol member for type clarity.

While pyte.Char is a NamedTuple with an immutable data attribute and modern mypy correctly handles Protocol compatibility in this case, explicitly declaring data as a read-only property makes the intent clearer and ensures compatibility across type checkers:

♻️ Proposed refactor
 class TerminalChar(Protocol):
     """Subset of pyte's Char object used for snapshot rendering."""
 
-    data: str
+    `@property`
+    def data(self) -> str: ...
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/pty_cli.py` around lines 36 - 40, The Protocol TerminalChar
declares a mutable attribute data but pyte.Char's data is immutable; change
TerminalChar to expose data as a read-only property (e.g., replace the data
attribute with a property signature like def data(self) -> str: ... in the
Protocol) so TerminalChar.data is read-only and clearly matches pyte.Char's
immutability for type checkers and readers.

Comment on lines +118 to +124
def from_db_connection(cls, conn: sqlite3.Connection) -> ArchiveFacts:
total_convs = int(conn.execute("SELECT COUNT(*) FROM conversations").fetchone()[0])
provider_rows = conn.execute(
"SELECT provider_name, COUNT(*) as cnt FROM conversations GROUP BY provider_name"
).fetchall()
provider_counts = {r["provider_name"]: r["cnt"] for r in provider_rows}
total_msgs = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
provider_counts = {str(row["provider_name"]): int(row["cnt"]) for row in provider_rows}
total_msgs = int(conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0])

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
# Description: Demonstrate default sqlite3 rows are tuple-indexed, not name-indexed.

python - <<'PY'
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE conversations(provider_name TEXT)")
conn.execute("INSERT INTO conversations(provider_name) VALUES ('codex')")
row = conn.execute(
    "SELECT provider_name, COUNT(*) as cnt FROM conversations GROUP BY provider_name"
).fetchone()

print(type(row).__name__, row)
try:
    print(row["provider_name"])
except Exception as exc:
    print(type(exc).__name__, exc)
PY

Repository: Sinity/polylogue

Length of output: 138


🏁 Script executed:

cd tests/infra && ls -la semantic_facts.py && wc -l semantic_facts.py

Repository: Sinity/polylogue

Length of output: 148


🏁 Script executed:

sed -n '110,135p' tests/infra/semantic_facts.py

Repository: Sinity/polylogue

Length of output: 917


🏁 Script executed:

# Check for row_factory setup in the file
rg -n "row_factory" tests/infra/semantic_facts.py

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Check for row_factory setup in related test setup or fixtures
rg -n "row_factory" tests/

Repository: Sinity/polylogue

Length of output: 1221


🏁 Script executed:

# Find where ArchiveFacts.from_db_connection is called
rg -n "from_db_connection\|ArchiveFacts" tests/ --type py

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Check the full semantic_facts.py to see context
cat -n tests/infra/semantic_facts.py

Repository: Sinity/polylogue

Length of output: 6037


🏁 Script executed:

# Search entire repo for from_db_connection usage
rg -n "from_db_connection" . --type py

Repository: Sinity/polylogue

Length of output: 382


🏁 Script executed:

# Check if there are any calls to ArchiveFacts
rg -n "ArchiveFacts" . --type py

Repository: Sinity/polylogue

Length of output: 640


🏁 Script executed:

# Check the test calls to see if row_factory is set
sed -n '75,110p' tests/unit/test_cross_surface_agreement.py

Repository: Sinity/polylogue

Length of output: 1793


🏁 Script executed:

# Check the open_connection function to see if it sets row_factory
rg -n "def open_connection" . --type py -A 10

Repository: Sinity/polylogue

Length of output: 1023


🏁 Script executed:

# Find the correct open_connection function from backends.connection
rg -n "def open_connection" polylogue/storage/backends/ --type py -A 15

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Search for open_connection in the entire codebase
fd -name "connection.py" . --type f

Repository: Sinity/polylogue

Length of output: 290


🏁 Script executed:

# Find all files that define open_connection
rg -l "def open_connection" . --type py

Repository: Sinity/polylogue

Length of output: 106


🏁 Script executed:

# Look for files in backends directory
fd connection . polylogue/storage/backends/ --type f

Repository: Sinity/polylogue

Length of output: 143


🏁 Script executed:

# Search for open_connection definition more broadly
rg -n "def open_connection" polylogue/ --type py -A 15

Repository: Sinity/polylogue

Length of output: 1400


🏁 Script executed:

# Check the connection.py file in backends
cat polylogue/storage/backends/connection.py

Repository: Sinity/polylogue

Length of output: 8291


Use positional indexing for row access—the method accepts any sqlite3.Connection, not just those with row_factory configured.

While current callers route through open_connection() (which configures row_factory = sqlite3.Row), the public signature accepts bare connections. Positional indexing is more defensive and works regardless of row factory configuration.

Proposed fix
-        provider_counts = {str(row["provider_name"]): int(row["cnt"]) for row in provider_rows}
+        provider_counts = {str(row[0]): int(row[1]) for row in provider_rows}
📝 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
def from_db_connection(cls, conn: sqlite3.Connection) -> ArchiveFacts:
total_convs = int(conn.execute("SELECT COUNT(*) FROM conversations").fetchone()[0])
provider_rows = conn.execute(
"SELECT provider_name, COUNT(*) as cnt FROM conversations GROUP BY provider_name"
).fetchall()
provider_counts = {r["provider_name"]: r["cnt"] for r in provider_rows}
total_msgs = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
provider_counts = {str(row["provider_name"]): int(row["cnt"]) for row in provider_rows}
total_msgs = int(conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0])
def from_db_connection(cls, conn: sqlite3.Connection) -> ArchiveFacts:
total_convs = int(conn.execute("SELECT COUNT(*) FROM conversations").fetchone()[0])
provider_rows = conn.execute(
"SELECT provider_name, COUNT(*) as cnt FROM conversations GROUP BY provider_name"
).fetchall()
provider_counts = {str(row[0]): int(row[1]) for row in provider_rows}
total_msgs = int(conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0])
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/semantic_facts.py` around lines 118 - 124, The comprehension in
from_db_connection uses mapping-style access (row["provider_name"], row["cnt"])
which fails for plain sqlite3.Connection without a row_factory; change
provider_rows handling to use positional indexing (row[0] for provider_name,
row[1] for cnt) when building provider_counts and ensure you cast to str/int as
before; update any other row dict-style accesses in from_db_connection that
assume sqlite3.Row to use positional indexing via
conn.execute(...).fetchall()/fetchone().

Comment on lines +57 to +69
def _json_document_from_bytes(raw: bytes) -> JSONDocument:
return json_document(json_loads(raw))


def _jsonl_documents(raw: bytes) -> list[JSONDocument]:
return [json_document(json_loads(line)) for line in raw.decode().splitlines() if line.strip()]


def decode_provider_payload(provider: str, raw: bytes) -> ProviderPayload:
"""Decode schema-generated provider bytes into the wire payload type."""
if provider in _JSONL_PROVIDERS:
return [json.loads(line) for line in raw.decode().splitlines() if line.strip()]
return cast(dict[str, Any], json.loads(raw))
return _jsonl_documents(raw)
return _json_document_from_bytes(raw)

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

Fail fast instead of coercing invalid provider payloads to {}.

json_document() returns {} for non-object decoded JSON, so malformed provider bytes or JSONL scalar/array records get silently accepted and lose all content. That can make schema/corpus regressions pass with empty payloads.

🛡️ Proposed fix
-from polylogue.lib.json import JSONDocument, json_document
+from polylogue.lib.json import JSONDocument, is_json_document, json_document
 from polylogue.lib.json import loads as json_loads
@@
 def _json_document_from_bytes(raw: bytes) -> JSONDocument:
-    return json_document(json_loads(raw))
+    value = json_loads(raw)
+    if not is_json_document(value):
+        raise ValueError("Provider payload must decode to a JSON object")
+    return value
 
 
 def _jsonl_documents(raw: bytes) -> list[JSONDocument]:
-    return [json_document(json_loads(line)) for line in raw.decode().splitlines() if line.strip()]
+    documents: list[JSONDocument] = []
+    for line_number, line in enumerate(raw.decode().splitlines(), start=1):
+        if not line.strip():
+            continue
+        value = json_loads(line)
+        if not is_json_document(value):
+            raise ValueError(f"Provider JSONL line {line_number} must decode to a JSON object")
+        documents.append(value)
+    return documents
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/strategies/providers.py` around lines 57 - 69, The current
helpers (_json_document_from_bytes and _jsonl_documents) call
json_document(json_loads(...)) which silently coerces non-object JSON into {};
instead, validate that json_loads(...) returns a mapping/object and fail fast by
raising an error when the decoded value is not a dict. Update
_json_document_from_bytes to decode with json_loads(raw), assert
isinstance(result, dict) (or raise ValueError with context mentioning the
provider/raw), and only then call json_document; similarly update
_jsonl_documents to decode each line, check each decoded value is a dict
(include line index/context in the error), and raise rather than returning
empty/coerced documents; keep decode_provider_payload logic and _JSONL_PROVIDERS
unchanged.

Comment on lines +371 to +398
def chatgpt_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
"""Generate ChatGPT messages with richer semantic content variants."""
return dict(draw(st.sampled_from(_CHATGPT_SEMANTIC_MESSAGES)))


@st.composite
def claude_ai_semantic_message_strategy(draw: st.DrawFn) -> dict[str, Any]:
def claude_ai_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
"""Generate Claude AI messages with stable semantic metadata variants."""
return dict(draw(st.sampled_from(_CLAUDE_AI_SEMANTIC_MESSAGES)))


@st.composite
def claude_code_semantic_record_strategy(draw: st.DrawFn) -> dict[str, Any]:
def claude_code_semantic_record_strategy(draw: st.DrawFn) -> JSONDocument:
"""Generate Claude Code records with text/thinking/tool/code coverage."""
return dict(draw(st.sampled_from(_CLAUDE_CODE_SEMANTIC_RECORDS)))


@st.composite
def gemini_semantic_message_strategy(draw: st.DrawFn) -> dict[str, Any]:
def gemini_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
"""Generate Gemini messages exercising thought/code/file branches."""
return dict(draw(st.sampled_from(_GEMINI_SEMANTIC_MESSAGES)))


@st.composite
def codex_semantic_record_strategy(draw: st.DrawFn) -> dict[str, Any]:
def codex_semantic_record_strategy(draw: st.DrawFn) -> JSONDocument:
"""Generate Codex direct and envelope records with mixed block types."""
raw = draw(st.sampled_from(_CODEX_SEMANTIC_RECORDS))
return cast(dict[str, Any], json.loads(json.dumps(raw)))
return json_document(json_loads(json.dumps(raw)))

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

Return deep copies for sampled semantic fixtures.

The non-Codex strategies shallow-copy only the top-level dict, leaving nested lists/dicts shared across Hypothesis examples. If a test mutates nested content, later examples can observe polluted fixture state; line 398 already avoids this for Codex.

♻️ Proposed fix
 def chatgpt_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
     """Generate ChatGPT messages with richer semantic content variants."""
-    return dict(draw(st.sampled_from(_CHATGPT_SEMANTIC_MESSAGES)))
+    return json_document(json_loads(json.dumps(draw(st.sampled_from(_CHATGPT_SEMANTIC_MESSAGES)))))
@@
 def claude_ai_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
     """Generate Claude AI messages with stable semantic metadata variants."""
-    return dict(draw(st.sampled_from(_CLAUDE_AI_SEMANTIC_MESSAGES)))
+    return json_document(json_loads(json.dumps(draw(st.sampled_from(_CLAUDE_AI_SEMANTIC_MESSAGES)))))
@@
 def claude_code_semantic_record_strategy(draw: st.DrawFn) -> JSONDocument:
     """Generate Claude Code records with text/thinking/tool/code coverage."""
-    return dict(draw(st.sampled_from(_CLAUDE_CODE_SEMANTIC_RECORDS)))
+    return json_document(json_loads(json.dumps(draw(st.sampled_from(_CLAUDE_CODE_SEMANTIC_RECORDS)))))
@@
 def gemini_semantic_message_strategy(draw: st.DrawFn) -> JSONDocument:
     """Generate Gemini messages exercising thought/code/file branches."""
-    return dict(draw(st.sampled_from(_GEMINI_SEMANTIC_MESSAGES)))
+    return json_document(json_loads(json.dumps(draw(st.sampled_from(_GEMINI_SEMANTIC_MESSAGES)))))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/strategies/providers.py` around lines 371 - 398, The sampled
semantic strategies (chatgpt_semantic_message_strategy,
claude_ai_semantic_message_strategy, claude_code_semantic_record_strategy,
gemini_semantic_message_strategy) currently use dict(draw(...)) which only
shallow-copies the top-level mapping and leaves nested lists/dicts shared
between Hypothesis examples; change each strategy to return a deep copy of the
sampled fixture (e.g., obtain the raw sample via draw(st.sampled_from(...)), run
copy.deepcopy(raw) and return that deep-copied value) so nested structures
aren’t shared across examples—follow the same approach already used in
codex_semantic_record_strategy (deserialize/clone) to ensure isolated fixtures.

Comment on lines +12 to +15
from polylogue.lib.json import JSONDocument
from tests.infra.strategies.sources import json_document_strategy

JSONRecord: TypeAlias = dict[str, object]

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

Use the existing recursive JSON contract for JSONRecord.

dict[str, object] allows arbitrary Python objects, so this reintroduces a weaker contract in the schema strategies. Alias JSONRecord to JSONDocument to keep this consistent with the rest of the JSON typing work.

♻️ Proposed type-alias tightening
 from polylogue.lib.json import JSONDocument
 from tests.infra.strategies.sources import json_document_strategy
 
-JSONRecord: TypeAlias = dict[str, object]
+JSONRecord: TypeAlias = JSONDocument

Also applies to: 74-134

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/infra/strategies/schema.py` around lines 12 - 15, Replace the loose
TypeAlias JSONRecord that currently uses dict[str, object] with the recursive
JSON contract by aliasing JSONRecord to the imported JSONDocument; update all
other occurrences in this module (e.g., the uses around the
json_document_strategy and other definitions between the earlier and later
JSON-related blocks) to reference JSONRecord as JSONDocument so the strategy
uses the stricter recursive JSON typing provided by JSONDocument.

@Sinity
Sinity merged commit 1405711 into master Apr 21, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/test-strategy-contracts branch April 21, 2026 09:16
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary

- Replaces broad `Any` in `tests/infra` strategy helpers, Drive mocks, semantic-fact helpers, PTY/MCP helpers, large-batch/chaos builders, and shared pytest fixtures with explicit JSON, protocol, fixture, and typed-dict contracts.
- Keeps the flexible test-builder APIs by validating explicit payload dictionaries through Pydantic rather than forwarding untyped `**kwargs` into generated constructors.
- Makes the repo-identity test derive the active checkout name from `REPO_ROOT`, so temporary worktree clones such as `polylogue-281` verify correctly.

## Problem

The mypy cleanup has made production and core test contracts stricter, but reusable test infrastructure still carried broad dynamic types. Those helpers feed source laws, schema laws, MCP tests, Drive tests, and ingestion-hostility tests, so leaving them untyped weakens the suite exactly where generated and cross-surface tests should be most precise.

Ref #281

## Solution

- Added explicit provider payload/source-case contracts and JSON narrowing in `tests/infra/strategies/providers.py`.
- Added typed strategy records and helper return contracts in schema, message, filter, and pipeline strategy helpers.
- Replaced Drive mock dynamic seams with a writable protocol, param-spec retry wrapper, concrete mock downloader result types, and typed service response dictionaries.
- Tightened semantic fact extraction around domain conversations, storage records, CLI JSON payloads, and SQLite aggregate rows.
- Typed shared pytest fixtures for repositories, backends, CLI runners, synthetic sources, and conversation builders.

## Verification

- `ruff format tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py`
- `ruff check tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py`
- `mypy tests/infra/strategies/filters.py tests/infra/strategies/messages.py tests/infra/strategies/pipeline.py tests/infra/strategies/providers.py tests/infra/strategies/schema.py tests/infra/strategies/schema_driven.py tests/infra/drive_mocks.py tests/infra/semantic_facts.py tests/infra/large_batches.py tests/infra/chaos_sources.py tests/infra/mcp.py tests/infra/pty_cli.py tests/infra/builders.py tests/conftest.py`
- `pytest -q tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_gateway.py tests/unit/test_cross_surface_agreement.py tests/unit/pipeline/test_ingestion_chaos.py tests/integration/test_chronology_extremes.py` (141 passed)
- `pytest -q tests/unit/mcp tests/unit/core/test_schema_laws.py tests/unit/core/test_filters_props.py tests/unit/lib/test_filter_executor.py tests/unit/sources/test_parsers_props.py tests/unit/sources/test_source_laws.py tests/property/test_rendering_preservation.py tests/unit/pipeline/test_resilience.py` (404 passed)
- `PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH devtools verify --quick`
- `pytest -q --tb=short --ignore=tests/integration` (4975 passed)
- `PATH=/tmp/polylogue-281/.cache/codex-bin:$PATH git push -u origin feature/refactor/test-strategy-contracts` (pre-push `devtools verify --quick` passed)

Note: I also attempted full `devtools verify`. Its pytest subphase first exposed the hard-coded repo-name assertion fixed in this PR; a later run hit local xdist teardown/process instability without a test failure. The exact pytest command wrapped by `devtools verify` passed cleanly afterward.
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup had made production and core test contracts
stricter, but reusable test infrastructure still carried broad
dynamic types. Those helpers feed source laws, schema laws, MCP
tests, Drive tests, and ingestion-hostility tests; leaving them
untyped weakened the suite exactly where generated and cross-
surface tests should be most precise.

Replaces broad `Any` in `tests/infra` strategy helpers, Drive mocks,
semantic-fact helpers, PTY/MCP helpers, large-batch/chaos builders,
and shared pytest fixtures with explicit JSON, protocol, fixture,
and typed-dict contracts. Keeps flexible test-builder APIs by
validating explicit payload dictionaries through Pydantic rather
than forwarding untyped `**kwargs` into generated constructors.
Adds explicit provider payload/source-case contracts and JSON
narrowing in `tests/infra/strategies/providers.py`. Replaces Drive
mock dynamic seams with a writable protocol, param-spec retry
wrapper, concrete mock downloader result types, and typed service
response dictionaries. Tightens semantic fact extraction around
domain conversations, storage records, CLI JSON payloads, and
SQLite aggregate rows. Types shared pytest fixtures for
repositories, backends, CLI runners, synthetic sources, and
conversation builders.

Makes the repo-identity test derive the active checkout name from
`REPO_ROOT` so temporary worktree clones verify correctly.

Verification: ruff + mypy over touched infra modules; pytest over
Drive, cross-surface agreement, chaos, mcp, schema-laws,
filter-props, source-laws, rendering, and resilience suites (141 +
404 + full 4975 passed); devtools verify --quick green.

Ref #281
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup had made production and core test contracts
stricter, but reusable test infrastructure still carried broad
dynamic types. Those helpers feed source laws, schema laws, MCP
tests, Drive tests, and ingestion-hostility tests; leaving them
untyped weakened the suite exactly where generated and cross-
surface tests should be most precise.

Replaces broad `Any` in `tests/infra` strategy helpers, Drive mocks,
semantic-fact helpers, PTY/MCP helpers, large-batch/chaos builders,
and shared pytest fixtures with explicit JSON, protocol, fixture,
and typed-dict contracts. Keeps flexible test-builder APIs by
validating explicit payload dictionaries through Pydantic rather
than forwarding untyped `**kwargs` into generated constructors.
Adds explicit provider payload/source-case contracts and JSON
narrowing in `tests/infra/strategies/providers.py`. Replaces Drive
mock dynamic seams with a writable protocol, param-spec retry
wrapper, concrete mock downloader result types, and typed service
response dictionaries. Tightens semantic fact extraction around
domain conversations, storage records, CLI JSON payloads, and
SQLite aggregate rows. Types shared pytest fixtures for
repositories, backends, CLI runners, synthetic sources, and
conversation builders.

Makes the repo-identity test derive the active checkout name from
`REPO_ROOT` so temporary worktree clones verify correctly.

Verification: ruff + mypy over touched infra modules; pytest over
Drive, cross-surface agreement, chaos, mcp, schema-laws,
filter-props, source-laws, rendering, and resilience suites (141 +
404 + full 4975 passed); devtools verify --quick green.

Ref #281
Sinity added a commit that referenced this pull request Apr 22, 2026
The mypy cleanup had made production and core test contracts
stricter, but reusable test infrastructure still carried broad
dynamic types. Those helpers feed source laws, schema laws, MCP
tests, Drive tests, and ingestion-hostility tests; leaving them
untyped weakened the suite exactly where generated and cross-
surface tests should be most precise.

Replaces broad `Any` in `tests/infra` strategy helpers, Drive mocks,
semantic-fact helpers, PTY/MCP helpers, large-batch/chaos builders,
and shared pytest fixtures with explicit JSON, protocol, fixture,
and typed-dict contracts. Keeps flexible test-builder APIs by
validating explicit payload dictionaries through Pydantic rather
than forwarding untyped `**kwargs` into generated constructors.
Adds explicit provider payload/source-case contracts and JSON
narrowing in `tests/infra/strategies/providers.py`. Replaces Drive
mock dynamic seams with a writable protocol, param-spec retry
wrapper, concrete mock downloader result types, and typed service
response dictionaries. Tightens semantic fact extraction around
domain conversations, storage records, CLI JSON payloads, and
SQLite aggregate rows. Types shared pytest fixtures for
repositories, backends, CLI runners, synthetic sources, and
conversation builders.

Makes the repo-identity test derive the active checkout name from
`REPO_ROOT` so temporary worktree clones verify correctly.

Verification: ruff + mypy over touched infra modules; pytest over
Drive, cross-surface agreement, chaos, mcp, schema-laws,
filter-props, source-laws, rendering, and resilience suites (141 +
404 + full 4975 passed); 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. 6 finding(s) confirmed still present → tracked in #550.

@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. 🎉

ℹ️ 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. Swish!

ℹ️ 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
@Sinity
Sinity removed the request for review from Copilot May 1, 2026 02:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant