Skip to content

test: renew verification law and probe contracts - #233

Merged
Sinity merged 1 commit into
masterfrom
feature/test/verification-renewal
Apr 20, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/test/verification-renewal

Conversation

@Sinity

@Sinity Sinity commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Closes #232
Ref #227

Summary

  • renew verification-law fixtures and probe/runtime assertions over the current substrate

Problem

  • the previous substrate renewal tightened production contracts, but several test and devtools surfaces were still leaning on loose object indexing, dict splats, and untyped builder/runtime helpers
  • that left full-repo strict mypy and verification fragile even though the core source layers were clean

Solution

  • rebuild the affected verification surfaces around explicit JSON/object helpers, validated model construction, and typed fixture/runtime adapters
  • clean the probe summary assertions, storage-record builders, filter/schema law tests, and source-law/model tests so they match the stricter runtime contracts

Verification

  • devtools verify

@coderabbitai

coderabbitai Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Systematically replaced broad Any/object typing and unchecked casts throughout test suites and devtools with explicit TypedDict/TypeAlias schemas and runtime validation helpers. Updated function signatures to use concrete types and added JSON coercion/assertion utilities for safer test data handling.

Changes

Cohort / File(s) Summary
Type schemas and helpers in production/devtools
devtools/pipeline_probe.py, tests/infra/storage_records.py
Introduced explicit TypedDict and TypeAlias definitions for probe artifacts, storage records, and sentinel markers. Added JSON normalization helpers (_json_object_or_empty, _json_float_or_none) and type coercion functions. Updated function signatures and control flow to use concrete types instead of dict[str, Any] or object.
JSON assertion/validation helpers across test suites
tests/unit/cli/test_check.py, tests/unit/devtools/test_pipeline_probe.py, tests/unit/devtools/test_validation_lanes.py, tests/unit/pipeline/test_resilience.py
Added JSON-typed assertion and validation helpers (e.g., _require_json_object, _require_json_array, _json_path) to replace direct nested indexing and untyped casting. Updated test methods to use these helpers for safer JSON shape validation.
Type alias definitions for property-based and core tests
tests/unit/core/test_filters_props.py, tests/unit/core/test_filters_schemas.py, tests/unit/pipeline/test_parsing_service.py, tests/unit/pipeline/test_run_sources.py
Introduced TypeAlias definitions (e.g., FilterSpec, FilterRepoFactory, WorkspacePaths, ConversationPayload) and replaced Any-typed fixture parameters with concrete types (Path, pytest.MonkeyPatch, callback signatures).
Pydantic model validation in test construction
tests/unit/sources/test_models.py, tests/unit/sources/test_source_laws.py, tests/unit/sources/test_unified_semantic_laws.py
Replaced direct constructor calls with model_validate() for record/message creation. Added runtime filter helpers (_as_dict, _content_blocks, _numeric_observation_value) instead of unsafe casts. Updated test signatures to use explicit JSON type aliases (RawPayload, SemanticCase, JsonValue).
Remaining pipeline test typing
tests/unit/pipeline/test_resilience.py, tests/unit/pipeline/test_parsing_service.py
Strengthened type annotations for parsing service, schema resolution, and validation test mocks. Narrowed tmp_path/monkeypatch from Any to Path/pytest.MonkeyPatch; updated callback and helper function signatures to use concrete return types.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Suggested labels

area:pipeline, area:storage

Poem

🐰 From Any to Truth, we typed with care,
Schemas and helpers everywhere,
No more wild casts in tests so tight,
Concrete types make dawn more bright! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.73% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is vague and generic, using 'renew' without conveying what specific changes or improvements were made to understand the changeset. Clarify the title to specify what was renewed and why (e.g., 'test: add explicit type hints to verification fixtures and probe contracts').
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description follows the required template with all major sections (Summary, Problem, Solution, Verification) populated with clear context.
Linked Issues check ✅ Passed Changes comprehensively address #232 objectives: test builders now use explicit typed interfaces, loose Any/cast patterns replaced with typed helpers, and probe/storage/law suites renewed to match current contracts.
Out of Scope Changes check ✅ Passed All changes are scoped to test/devtools modules and align with #232 objectives; no unrelated production logic changes detected.

✏️ 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/test/verification-renewal

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

Caution

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

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

681-692: ⚠️ Potential issue | 🟠 Major

Re-index merged content blocks before validation.

Both _normalize_content_blocks(...) calls start block_index at 0; concatenating them can create duplicate (message_id, block_index) / block_id values, and the DB upsert later overwrites on that conflict.

Proposed fix
         existing_blocks = _normalize_content_blocks(
             raw_blocks=kwargs.pop("content_blocks", []),
             message_id=msg_id,
             conversation_id=str(self.conv.conversation_id),
         )
-        all_blocks = [*extra_blocks, *existing_blocks]
+        all_blocks = [
+            block.model_copy(
+                update={
+                    "block_id": ContentBlockRecord.make_id(msg_id, index),
+                    "block_index": index,
+                }
+            )
+            for index, block in enumerate([*extra_blocks, *existing_blocks])
+        ]
@@
     existing_blocks = _normalize_content_blocks(
         raw_blocks=kwargs.pop("content_blocks", []),
         message_id=message_id,
         conversation_id=conversation_id,
     )
-    all_blocks = [*extra_blocks, *existing_blocks]
+    all_blocks = [
+        block.model_copy(
+            update={
+                "block_id": ContentBlockRecord.make_id(message_id, index),
+                "block_index": index,
+            }
+        )
+        for index, block in enumerate([*extra_blocks, *existing_blocks])
+    ]

Also applies to: 815-826

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

In `@tests/infra/storage_records.py` around lines 681 - 692, The merged content
blocks (extra_blocks + existing_blocks) keep separate block_index counters from
the two _normalize_content_blocks calls, causing duplicate (message_id,
block_index) and block_id collisions; after computing extra_blocks and
existing_blocks (symbols: provider_meta, extra_blocks, existing_blocks,
all_blocks) re-index the combined list sequentially by updating each block's
block_index (and any derived block_id or id field that uses block_index) so
indices are unique across the concatenated all_blocks before any validation or
DB upsert; ensure the same re-indexing change is applied at the other occurrence
around lines 815-826.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@devtools/pipeline_probe.py`:
- Around line 955-965: The helper _json_float_or_none currently converts strings
like "nan" or "inf" into float values which are non-finite and can incorrectly
pass budget checks; update _json_float_or_none to reject non-finite floats by
importing math and returning None when math.isfinite(value) is False after
conversion (i.e., for int/float and parsed string paths); apply the same change
to the duplicate logic in the other region (the similar function/block around
the later duplicate) so both places treat NaN/Inf as invalid.

In `@tests/unit/core/test_filters_props.py`:
- Around line 263-280: The current handling of the "limit" spec may raise when
converting non-numeric strings or non-finite floats; update the branch that
reads spec["value"] so conversion to an int is done safely: check for bool
first, then for int, then for float verify it is finite (not NaN/inf) before
casting, and for strings attempt a safe int parse inside a try/except (falling
back to 0 on failure) before calling f.limit; reference the "limit" branch, the
spec["value"] variable and the f.limit(...) call when making the change.

In `@tests/unit/devtools/test_pipeline_probe.py`:
- Around line 38-55: The validators _require_int and _require_number erroneously
accept booleans because bool subclasses int; update both functions to reject
bool by adding an explicit check (e.g., assert isinstance(value, int) and not
isinstance(value, bool) for _require_int, and similarly assert isinstance(value,
(int, float)) and not isinstance(value, bool) for _require_number) so semantic
numeric fields cannot be True/False; keep _require_str and _require_bool
unchanged.

In `@tests/unit/sources/test_source_laws.py`:
- Around line 166-170: The helper _numeric_observation_value incorrectly accepts
bool because bool subclasses int; update _numeric_observation_value to
explicitly reject booleans before coercion: when value is an instance of bool
raise AssertionError (same message pattern) and only allow actual numeric types
(int/float/str) afterwards so malformed metrics like True no longer coerce to
1.0; locate the function _numeric_observation_value to implement the boolean
check immediately after retrieving value.

---

Outside diff comments:
In `@tests/infra/storage_records.py`:
- Around line 681-692: The merged content blocks (extra_blocks +
existing_blocks) keep separate block_index counters from the two
_normalize_content_blocks calls, causing duplicate (message_id, block_index) and
block_id collisions; after computing extra_blocks and existing_blocks (symbols:
provider_meta, extra_blocks, existing_blocks, all_blocks) re-index the combined
list sequentially by updating each block's block_index (and any derived block_id
or id field that uses block_index) so indices are unique across the concatenated
all_blocks before any validation or DB upsert; ensure the same re-indexing
change is applied at the other occurrence around lines 815-826.
🪄 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: 4d732fb4-60ea-4896-aee9-9297a1e47295

📥 Commits

Reviewing files that changed from the base of the PR and between d4a064e and 8c949e0.

📒 Files selected for processing (13)
  • devtools/pipeline_probe.py
  • tests/infra/storage_records.py
  • tests/unit/cli/test_check.py
  • tests/unit/core/test_filters_props.py
  • tests/unit/core/test_filters_schemas.py
  • tests/unit/devtools/test_pipeline_probe.py
  • tests/unit/devtools/test_validation_lanes.py
  • tests/unit/pipeline/test_parsing_service.py
  • tests/unit/pipeline/test_resilience.py
  • tests/unit/pipeline/test_run_sources.py
  • tests/unit/sources/test_models.py
  • tests/unit/sources/test_source_laws.py
  • tests/unit/sources/test_unified_semantic_laws.py

Comment on lines +955 to +965
def _json_float_or_none(value: object | None) -> float | None:
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value)
except ValueError:
return None
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Treat non-finite budget metrics as invalid.

float("nan") returns nan, and nan > budget is false, so a corrupted runtime/RSS metric can incorrectly pass the budget check.

Proposed fix
 import hashlib
 import json
+import math
 import os
@@
 def _json_float_or_none(value: object | None) -> float | None:
     if value is None or isinstance(value, bool):
         return None
     if isinstance(value, (int, float)):
-        return float(value)
+        number = float(value)
+        return number if math.isfinite(number) else None
     if isinstance(value, str):
         try:
-            return float(value)
+            number = float(value)
         except ValueError:
             return None
+        return number if math.isfinite(number) else None
     return None

Also applies to: 1210-1228

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

In `@devtools/pipeline_probe.py` around lines 955 - 965, The helper
_json_float_or_none currently converts strings like "nan" or "inf" into float
values which are non-finite and can incorrectly pass budget checks; update
_json_float_or_none to reject non-finite floats by importing math and returning
None when math.isfinite(value) is False after conversion (i.e., for int/float
and parsed string paths); apply the same change to the duplicate logic in the
other region (the similar function/block around the later duplicate) so both
places treat NaN/Inf as invalid.

Comment on lines 263 to +280
ftype = spec["type"]
if ftype == "provider":
return f.provider(spec["value"])
return f.provider(str(spec["value"]))
elif ftype == "contains":
return f.contains(spec["value"])
return f.contains(str(spec["value"]))
elif ftype == "since":
return f.since(spec["value"])
return f.since(str(spec["value"]))
elif ftype == "until":
return f.until(spec["value"])
return f.until(str(spec["value"]))
elif ftype == "limit":
return f.limit(spec["value"])
raw_value = spec["value"]
if isinstance(raw_value, bool):
return f.limit(int(raw_value))
if isinstance(raw_value, int):
return f.limit(raw_value)
if isinstance(raw_value, (float, str)):
return f.limit(int(raw_value))
return f.limit(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 | 🟠 Major

Make limit coercion non-throwing for arbitrary specs.

Line 279 can raise for non-numeric strings or non-finite floats, and FilterSpec.value is NotRequired, so this can break the “never crashes” property before the filter builder is exercised.

Proposed fix
     if ftype == "provider":
-        return f.provider(str(spec["value"]))
+        return f.provider(str(spec.get("value", "")))
     elif ftype == "contains":
-        return f.contains(str(spec["value"]))
+        return f.contains(str(spec.get("value", "")))
     elif ftype == "since":
-        return f.since(str(spec["value"]))
+        return f.since(str(spec.get("value", "")))
     elif ftype == "until":
-        return f.until(str(spec["value"]))
+        return f.until(str(spec.get("value", "")))
     elif ftype == "limit":
-        raw_value = spec["value"]
+        raw_value = spec.get("value", 0)
         if isinstance(raw_value, bool):
             return f.limit(int(raw_value))
         if isinstance(raw_value, int):
             return f.limit(raw_value)
-        if isinstance(raw_value, (float, str)):
-            return f.limit(int(raw_value))
         return f.limit(0)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/core/test_filters_props.py` around lines 263 - 280, The current
handling of the "limit" spec may raise when converting non-numeric strings or
non-finite floats; update the branch that reads spec["value"] so conversion to
an int is done safely: check for bool first, then for int, then for float verify
it is finite (not NaN/inf) before casting, and for strings attempt a safe int
parse inside a try/except (falling back to 0 on failure) before calling f.limit;
reference the "limit" branch, the spec["value"] variable and the f.limit(...)
call when making the change.

Comment on lines +38 to +55
def _require_int(value: object) -> int:
assert isinstance(value, int)
return value


def _require_str(value: object) -> str:
assert isinstance(value, str)
return value


def _require_bool(value: object) -> bool:
assert isinstance(value, bool)
return value


def _require_number(value: object) -> int | float:
assert isinstance(value, int | float)
return value

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
python - <<'PY'
print(isinstance(True, int))
print(isinstance(False, int | float))
PY

Repository: Sinity/polylogue

Length of output: 69


🏁 Script executed:

# First, verify the file exists and read the relevant section
if [ -f tests/unit/devtools/test_pipeline_probe.py ]; then
  echo "=== File exists, reading lines 30-70 ==="
  sed -n '30,70p' tests/unit/devtools/test_pipeline_probe.py
else
  echo "File not found at expected path"
  git ls-files | grep -i pipeline_probe
fi

Repository: Sinity/polylogue

Length of output: 976


🏁 Script executed:

# Check if these validator functions are actually used in the codebase
rg "_require_int|_require_str|_require_bool|_require_number" --type py -A 2

Repository: Sinity/polylogue

Length of output: 4672


Reject booleans in numeric JSON helpers.

bool is a subclass of int in Python, so _require_int(True) and _require_number(False) currently pass. These validators are used on semantic numeric fields (batch_count, input_count, timing metrics, etc.) that should never accept booleans. Add an explicit and not isinstance(value, bool) check to tighten the JSON contract validation.

Proposed fix
 def _require_int(value: object) -> int:
-    assert isinstance(value, int)
+    assert isinstance(value, int) and not isinstance(value, bool)
     return value
@@
 def _require_number(value: object) -> int | float:
-    assert isinstance(value, int | float)
+    assert isinstance(value, int | float) and not isinstance(value, bool)
     return value
📝 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 _require_int(value: object) -> int:
assert isinstance(value, int)
return value
def _require_str(value: object) -> str:
assert isinstance(value, str)
return value
def _require_bool(value: object) -> bool:
assert isinstance(value, bool)
return value
def _require_number(value: object) -> int | float:
assert isinstance(value, int | float)
return value
def _require_int(value: object) -> int:
assert isinstance(value, int) and not isinstance(value, bool)
return value
def _require_str(value: object) -> str:
assert isinstance(value, str)
return value
def _require_bool(value: object) -> bool:
assert isinstance(value, bool)
return value
def _require_number(value: object) -> int | float:
assert isinstance(value, int | float) and not isinstance(value, bool)
return value
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/devtools/test_pipeline_probe.py` around lines 38 - 55, The
validators _require_int and _require_number erroneously accept booleans because
bool subclasses int; update both functions to reject bool by adding an explicit
check (e.g., assert isinstance(value, int) and not isinstance(value, bool) for
_require_int, and similarly assert isinstance(value, (int, float)) and not
isinstance(value, bool) for _require_number) so semantic numeric fields cannot
be True/False; keep _require_str and _require_bool unchanged.

Comment on lines +166 to +170
def _numeric_observation_value(observation: Mapping[str, object], key: str) -> float:
value = observation.get(key)
if not isinstance(value, (int, float, str)):
raise AssertionError(f"expected numeric observation field {key}, got {type(value).__name__}")
return float(value)

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

Reject boolean observation metrics before numeric coercion.

Line 168 treats bool as numeric because bool subclasses int, so malformed metrics like True pass as 1.0.

Proposed fix
 def _numeric_observation_value(observation: Mapping[str, object], key: str) -> float:
     value = observation.get(key)
+    if isinstance(value, bool):
+        raise AssertionError(f"expected numeric observation field {key}, got bool")
     if not isinstance(value, (int, float, str)):
         raise AssertionError(f"expected numeric observation field {key}, got {type(value).__name__}")
     return float(value)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/sources/test_source_laws.py` around lines 166 - 170, The helper
_numeric_observation_value incorrectly accepts bool because bool subclasses int;
update _numeric_observation_value to explicitly reject booleans before coercion:
when value is an instance of bool raise AssertionError (same message pattern)
and only allow actual numeric types (int/float/str) afterwards so malformed
metrics like True no longer coerce to 1.0; locate the function
_numeric_observation_value to implement the boolean check immediately after
retrieving value.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8c949e0b15

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

Comment thread devtools/pipeline_probe.py Resolved
@Sinity
Sinity merged commit b449e2c into master Apr 20, 2026
14 checks passed
@Sinity
Sinity deleted the feature/test/verification-renewal branch April 20, 2026 00:49
Sinity added a commit that referenced this pull request Apr 22, 2026
Closes #232
Ref #227

## Summary

- renew verification-law fixtures and probe/runtime assertions over the current substrate

## Problem

- the previous substrate renewal tightened production contracts, but several test and devtools surfaces were still leaning on loose object indexing, dict splats, and untyped builder/runtime helpers
- that left full-repo strict mypy and verification fragile even though the core source layers were clean

## Solution

- rebuild the affected verification surfaces around explicit JSON/object helpers, validated model construction, and typed fixture/runtime adapters
- clean the probe summary assertions, storage-record builders, filter/schema law tests, and source-law/model tests so they match the stricter runtime contracts

## Verification

- `devtools verify`
Sinity added a commit that referenced this pull request Apr 22, 2026
The previous substrate renewal tightened production contracts, but
several test and devtools surfaces still leaned on loose object
indexing, dict splats, and untyped builder/runtime helpers. Full-
repo strict mypy and verification were fragile even though the core
source layers were clean.

Rebuilds the affected verification surfaces around explicit JSON/
object helpers, validated model construction, and typed fixture/
runtime adapters. Cleans the probe summary assertions, storage-
record builders, filter/schema law tests, and source-law/model tests
so they match the stricter runtime contracts.

Verification: devtools verify green.

Closes #232
Ref #227
Sinity added a commit that referenced this pull request Apr 22, 2026
The previous substrate renewal tightened production contracts, but
several test and devtools surfaces still leaned on loose object
indexing, dict splats, and untyped builder/runtime helpers. Full-
repo strict mypy and verification were fragile even though the core
source layers were clean.

Rebuilds the affected verification surfaces around explicit JSON/
object helpers, validated model construction, and typed fixture/
runtime adapters. Cleans the probe summary assertions, storage-
record builders, filter/schema law tests, and source-law/model tests
so they match the stricter runtime contracts.

Verification: devtools verify green.

Closes #232
Ref #227
Sinity added a commit that referenced this pull request Apr 22, 2026
The previous substrate renewal tightened production contracts, but
several test and devtools surfaces still leaned on loose object
indexing, dict splats, and untyped builder/runtime helpers. Full-
repo strict mypy and verification were fragile even though the core
source layers were clean.

Rebuilds the affected verification surfaces around explicit JSON/
object helpers, validated model construction, and typed fixture/
runtime adapters. Cleans the probe summary assertions, storage-
record builders, filter/schema law tests, and source-law/model tests
so they match the stricter runtime contracts.

Verification: devtools verify green.

Closes #232
Ref #227
@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. 5 finding(s) confirmed still present → tracked in #550.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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.

test: renew law suites and fixture contracts over the runtime substrate

1 participant