Repository navigation
test: renew verification law and probe contracts - #233
Conversation
📝 WalkthroughWalkthroughSystematically replaced broad Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~35 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 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 | 🟠 MajorRe-index merged content blocks before validation.
Both
_normalize_content_blocks(...)calls startblock_indexat0; concatenating them can create duplicate(message_id, block_index)/block_idvalues, 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
📒 Files selected for processing (13)
devtools/pipeline_probe.pytests/infra/storage_records.pytests/unit/cli/test_check.pytests/unit/core/test_filters_props.pytests/unit/core/test_filters_schemas.pytests/unit/devtools/test_pipeline_probe.pytests/unit/devtools/test_validation_lanes.pytests/unit/pipeline/test_parsing_service.pytests/unit/pipeline/test_resilience.pytests/unit/pipeline/test_run_sources.pytests/unit/sources/test_models.pytests/unit/sources/test_source_laws.pytests/unit/sources/test_unified_semantic_laws.py
| 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 |
There was a problem hiding this comment.
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 NoneAlso 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.
| 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) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
python - <<'PY'
print(isinstance(True, int))
print(isinstance(False, int | float))
PYRepository: 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
fiRepository: 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 2Repository: 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.
| 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.
| 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
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`
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
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
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
|
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. |
Closes #232
Ref #227
Summary
Problem
Solution
Verification
devtools verify