Repository navigation
test: type strategy and infra contracts - #287
Conversation
📝 WalkthroughWalkthroughSystematic type annotation tightening across test infrastructure: replacing broad Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~35 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: 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 | 🟡 MinorBehavior change: unknown/missing
typenow silently no-ops.Previously
spec["type"]would raiseKeyErrorsurfacing 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 currentadd_*helpers set"type", so this is latent rather than active, but it weakens the safety net. Consider asserting membership or raising on unknownspec_typein theelsebranch 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 | 🔵 TrivialPrefer 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 aliasingJSONRecordtoJSONDocumentfor the raw payload strategies; keepprovider_metaasdict[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 = JSONDocumentAlso 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
📒 Files selected for processing (15)
tests/conftest.pytests/infra/builders.pytests/infra/chaos_sources.pytests/infra/drive_mocks.pytests/infra/large_batches.pytests/infra/mcp.pytests/infra/pty_cli.pytests/infra/semantic_facts.pytests/infra/strategies/filters.pytests/infra/strategies/messages.pytests/infra/strategies/pipeline.pytests/infra/strategies/providers.pytests/infra/strategies/schema.pytests/infra/strategies/schema_driven.pytests/unit/core/test_repo_identity.py
| 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 [] |
There was a problem hiding this comment.
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.
| class TerminalChar(Protocol): | ||
| """Subset of pyte's Char object used for snapshot rendering.""" | ||
|
|
||
| data: str | ||
|
|
There was a problem hiding this comment.
🧹 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:
- 1: NamedTuple should not satisfy Protocol with mutable fields python/mypy#5293
- 2: Protocol does not accept subtype as class attribute python/mypy#14963
- 3: Suggest making protocol attribute read-only if invariance causes conflict python/mypy#6002
- 4: https://mypy.readthedocs.io/en/latest/protocols.html
- 5: https://stackoverflow.com/questions/68325221/how-to-declare-a-protocol-with-a-field-which-supports-both-a-simple-type-and-pro
- 6: NamedTuples can't match Protocols with Callable fields python/mypy#6575
🏁 Script executed:
# First, check the file structure and imports
head -50 tests/infra/pty_cli.pyRepository: Sinity/polylogue
Length of output: 1215
🏁 Script executed:
# Search for pyte imports and usage
rg "pyte" tests/infra/pty_cli.py -B 2 -A 2Repository: Sinity/polylogue
Length of output: 1626
🏁 Script executed:
# Search for TerminalChar usage across the codebase
rg "TerminalChar" . --type py -B 2 -A 2Repository: 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 -lRepository: 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 -20Repository: 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 2Repository: 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 -30Repository: Sinity/polylogue
Length of output: 1974
🏁 Script executed:
# Check if pyte is in requirements or pyproject.toml
rg "pyte" . --type toml --type txtRepository: 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.
| 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]) |
There was a problem hiding this comment.
🧩 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)
PYRepository: Sinity/polylogue
Length of output: 138
🏁 Script executed:
cd tests/infra && ls -la semantic_facts.py && wc -l semantic_facts.pyRepository: Sinity/polylogue
Length of output: 148
🏁 Script executed:
sed -n '110,135p' tests/infra/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 917
🏁 Script executed:
# Check for row_factory setup in the file
rg -n "row_factory" tests/infra/semantic_facts.pyRepository: 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 pyRepository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
# Check the full semantic_facts.py to see context
cat -n tests/infra/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 6037
🏁 Script executed:
# Search entire repo for from_db_connection usage
rg -n "from_db_connection" . --type pyRepository: Sinity/polylogue
Length of output: 382
🏁 Script executed:
# Check if there are any calls to ArchiveFacts
rg -n "ArchiveFacts" . --type pyRepository: 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.pyRepository: 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 10Repository: 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 15Repository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
# Search for open_connection in the entire codebase
fd -name "connection.py" . --type fRepository: Sinity/polylogue
Length of output: 290
🏁 Script executed:
# Find all files that define open_connection
rg -l "def open_connection" . --type pyRepository: Sinity/polylogue
Length of output: 106
🏁 Script executed:
# Look for files in backends directory
fd connection . polylogue/storage/backends/ --type fRepository: Sinity/polylogue
Length of output: 143
🏁 Script executed:
# Search for open_connection definition more broadly
rg -n "def open_connection" polylogue/ --type py -A 15Repository: Sinity/polylogue
Length of output: 1400
🏁 Script executed:
# Check the connection.py file in backends
cat polylogue/storage/backends/connection.pyRepository: 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.
| 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().
| 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) |
There was a problem hiding this comment.
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.
| 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))) |
There was a problem hiding this comment.
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.
| from polylogue.lib.json import JSONDocument | ||
| from tests.infra.strategies.sources import json_document_strategy | ||
|
|
||
| JSONRecord: TypeAlias = dict[str, object] |
There was a problem hiding this comment.
🧹 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 = JSONDocumentAlso 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.
## 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.
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
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
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
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 ℹ️ 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. Swish! ℹ️ 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
Anyintests/infrastrategy 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.**kwargsinto generated constructors.REPO_ROOT, so temporary worktree clones such aspolylogue-281verify 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
tests/infra/strategies/providers.py.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.pyruff 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.pymypy 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.pypytest -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 --quickpytest -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-pushdevtools verify --quickpassed)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 bydevtools verifypassed cleanly afterward.