Repository navigation
test: advance verifiability Phase 1+2 — inner loop + CLI/storage contracts (#1026, #1060, #997) - #1068
Conversation
- Fix xdist_group marker creation in tests/unit/sources/conftest.py: item.add_marker(string) with parentheses created a mark with a literal name containing parens instead of a proper parametrized xdist_group mark. Switch to pytest.mark.xdist_group(name=provider). - Add test_main_returns_1_when_no_baselines_and_no_update to test_verification_lane.py: mocked unit path exercising the no-baselines → all-NEW-drift → return-1 control flow without spawning subprocesses. The E2E subprocess path belongs in the slow/lab lane. - Add "verify" Hypothesis profile to tests/conftest.py (10 examples, 5 s deadline): use HYPOTHESIS_PROFILE=verify for fast bounded-example local verify cycles (~8× fewer examples than default). - Emit --junitxml=.cache/test-reports/verify-latest.xml and --durations=10 from every pytest invocation in devtools verify so test results are available as structured artifacts rather than requiring terminal scraping. Co-Authored-By: Claude <[email protected]>
…1060) Implements the first two gaps from the CLI machine-output contract family: Exit-code contracts (test_exit_code_contracts.py, 25 tests): - Pins exit 0 for --help on root and 7 subcommands, --version, verb forms. - Pins exit 2 for all type=int options (--limit, --min-messages, --min-words, --max-messages) when given non-numeric values. - Pins exit 1 for date-filter options (--since/--until) given garbage input. - Pins exit-code consistency under --format json. Channel-separation contracts (test_stdout_stderr_split.py, 40 fast + 6 slow): - Fast CliRunner: help exit-0, no-traceback, error-not-JSON-shaped. - Slow subprocess @pytest.mark.slow: real capture_output separation, --help writes stdout only, invalid-arg stdout is not JSON (pipeline-safe). - No pytest.skip on deterministic paths; DB-dependent tests use slow marker. Co-Authored-By: Claude <[email protected]>
, #997) 12 new @pytest.mark.contract tests verifying that all query layers return consistent results for the same underlying data: - Count parity: repository.count() matches len(facade.list_conversations()) for both empty and seeded databases. - ID parity: same conversation IDs from SQLiteBackend, repository, and facade for unfiltered and provider-filtered queries. - Filter parity: provider filter produces equal counts at storage and facade; filtered sets from different providers are disjoint. - Search parity: FTS5 search results are a subset of all-list IDs; known token appears, unrelated token produces zero results at both layers. - Limit parity: limit=3 returns exactly 3 from both repository and facade; limited IDs are a strict subset of unlimited IDs. - Backend-to-repository parity: SQLiteBackend.queries.count_conversations() equals ConversationRepository.count() for unfiltered and filtered queries. All tests use ConversationBuilder for deterministic seeding, independent tmp_path databases, and @pytest.mark.asyncio for async facade calls. No pytest.skip — deterministic data, no environment dependencies. Co-Authored-By: Claude <[email protected]>
…_env (#1060) _invoke_json_command was calling pytest.skip() on any DB error (DatabaseError, OperationalError, or generic exception), making CLI JSON envelope tests silently pass in environments where the archive is unavailable. This masked real failures. Fix: add workspace_env fixture to all test methods that call _invoke_json_command. workspace_env provides a fresh, isolated XDG + POLYLOGUE_ARCHIVE_ROOT so the commands always run against a deterministic empty archive and never encounter schema mismatches or lock contention. Change pytest.skip() to pytest.fail() in _invoke_json_command: DB errors are now genuine test failures, not skips. No skip-on-failure survives in the CLI JSON envelope contract path. 24 tests pass deterministically; 0 skips. Co-Authored-By: Claude <[email protected]>
All 6 committed witnesses exercised and passing; update freshness timestamps to clear the 30-day lifecycle gate. Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThis PR adds comprehensive contract tests for CLI behavior and data-layer query parity, refactors JSON envelope contract enforcement, and enhances test infrastructure with JUnit XML reporting and Hypothesis profile configuration. ChangesTest Infrastructure & Configuration
CLI Contract Tests
Data Layer Query Parity Tests
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
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: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/unit/cli/test_exit_code_contracts.py`:
- Around line 205-208: The test test_help_exits_zero_json_format is intended to
exercise JSON-format help but currently invokes runner.invoke(cli, ["schema",
"list", "--help"]) without the format flag; update the invocation in
test_help_exits_zero_json_format to include the format option (e.g. pass
"--format", "json" in the argument list passed to runner.invoke) so the test
actually pins JSON mode while still asserting result.exit_code == 0.
In `@tests/unit/storage/test_query_parity.py`:
- Around line 31-52: Replace non-canonical ConversationBuilder usage that calls
.add_message(...).save() with the repo-standard fluent API: use
.message(role=..., text=...) for each message and finish the builder with
.build() to persist. Update the helper _seed_db and the other seed path that
currently uses ConversationBuilder(...).add_message(...).save() so they instead
call ConversationBuilder(...).provider(...).title(...).message(role="user",
text=...).message(role="assistant", text=...).build(); remove uses of
.add_message and .save and keep the same ids/titles/providers when switching to
.message() and .build().
🪄 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: 4d594d91-6985-4148-91b5-10902a649fce
📒 Files selected for processing (14)
devtools/verify.pytests/conftest.pytests/unit/cli/test_exit_code_contracts.pytests/unit/cli/test_json_envelope_contract.pytests/unit/cli/test_stdout_stderr_split.pytests/unit/showcase/test_verification_lane.pytests/unit/sources/conftest.pytests/unit/storage/test_query_parity.pytests/witnesses/blob-store-layout.witness.jsontests/witnesses/browser-capture-sequence.witness.jsontests/witnesses/cli-command-surface.witness.jsontests/witnesses/golden-tool-use-json.witness.jsontests/witnesses/mcp-tool-schemas.witness.jsontests/witnesses/topology-projection.witness.json
| def test_help_exits_zero_json_format(self, runner: CliRunner) -> None: | ||
| """schema list --format json --help exits 0 (--help short-circuits before format matters).""" | ||
| result = runner.invoke(cli, ["schema", "list", "--help"]) | ||
| assert result.exit_code == 0 |
There was a problem hiding this comment.
test_help_exits_zero_json_format is not actually exercising JSON mode.
The test name/docstring says JSON-format help is covered, but the invocation omits --format json, so this only tests plain --help. Add --format json in the command to pin the intended contract.
Suggested fix
- result = runner.invoke(cli, ["schema", "list", "--help"])
+ result = runner.invoke(cli, ["schema", "list", "--format", "json", "--help"])📝 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 test_help_exits_zero_json_format(self, runner: CliRunner) -> None: | |
| """schema list --format json --help exits 0 (--help short-circuits before format matters).""" | |
| result = runner.invoke(cli, ["schema", "list", "--help"]) | |
| assert result.exit_code == 0 | |
| def test_help_exits_zero_json_format(self, runner: CliRunner) -> None: | |
| """schema list --format json --help exits 0 (--help short-circuits before format matters).""" | |
| result = runner.invoke(cli, ["schema", "list", "--format", "json", "--help"]) | |
| assert result.exit_code == 0 |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/cli/test_exit_code_contracts.py` around lines 205 - 208, The test
test_help_exits_zero_json_format is intended to exercise JSON-format help but
currently invokes runner.invoke(cli, ["schema", "list", "--help"]) without the
format flag; update the invocation in test_help_exits_zero_json_format to
include the format option (e.g. pass "--format", "json" in the argument list
passed to runner.invoke) so the test actually pins JSON mode while still
asserting result.exit_code == 0.
| def _seed_db(db_path: Path, *, chatgpt_count: int = 2, claude_count: int = 3) -> None: | ||
| """Seed the database with known conversations across two providers.""" | ||
| for i in range(chatgpt_count): | ||
| cid = f"chatgpt-conv-{i}" | ||
| ( | ||
| ConversationBuilder(db_path, cid) | ||
| .provider("chatgpt") | ||
| .title(f"ChatGPT conv {i}") | ||
| .add_message(f"msg-{cid}-1", role="user", text=f"chatgpt question {i}") | ||
| .add_message(f"msg-{cid}-2", role="assistant", text=f"chatgpt answer {i}") | ||
| .save() | ||
| ) | ||
| for i in range(claude_count): | ||
| cid = f"claude-conv-{i}" | ||
| ( | ||
| ConversationBuilder(db_path, cid) | ||
| .provider("claude-ai") | ||
| .title(f"Claude conv {i}") | ||
| .add_message(f"msg-{cid}-1", role="user", text=f"claude question {i}") | ||
| .add_message(f"msg-{cid}-2", role="assistant", text=f"claude answer {i}") | ||
| .save() | ||
| ) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use the canonical ConversationBuilder chain (.message().build()) instead of .add_message().save().
Line 31+ and Line 208+ use non-standard builder calls, which diverge from the test-data construction contract used in this repo. Please switch these seed paths to .message(...) + .build() for consistency and compliance.
Proposed refactor pattern
- (
- ConversationBuilder(db_path, cid)
- .provider("chatgpt")
- .title(f"ChatGPT conv {i}")
- .add_message(f"msg-{cid}-1", role="user", text=f"chatgpt question {i}")
- .add_message(f"msg-{cid}-2", role="assistant", text=f"chatgpt answer {i}")
- .save()
- )
+ (
+ ConversationBuilder(db_path, cid)
+ .provider("chatgpt")
+ .title(f"ChatGPT conv {i}")
+ .message(role="user", text=f"chatgpt question {i}")
+ .message(role="assistant", text=f"chatgpt answer {i}")
+ .build()
+ )As per coding guidelines tests/**/*.py: Use ConversationBuilder from infra/storage_records.py as the fluent builder for populating test databases, chaining methods like .title(), .provider(), .message() and calling .build() to persist.
Also applies to: 208-223
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/storage/test_query_parity.py` around lines 31 - 52, Replace
non-canonical ConversationBuilder usage that calls .add_message(...).save() with
the repo-standard fluent API: use .message(role=..., text=...) for each message
and finish the builder with .build() to persist. Update the helper _seed_db and
the other seed path that currently uses
ConversationBuilder(...).add_message(...).save() so they instead call
ConversationBuilder(...).provider(...).title(...).message(role="user",
text=...).message(role="assistant", text=...).build(); remove uses of
.add_message and .save and keep the same ids/titles/providers when switching to
.message() and .build().
…1069) ## Summary Retires three CLI proof runners (`cli.command.json_envelope`, `cli.command.help`, `cli.command.no_traceback`) now that pytest owns their behavioral contracts. Extends `test_stdout_stderr_split.py` with a parametrized matrix covering all 53 CLI commands. ## Problem After PR #1068 adds CLI contract tests, three proof claims remain backed only by proof runner infrastructure rather than standard pytest evidence. The proof runners duplicate test logic, emit custom `EvidenceEnvelope` objects, and require special-purpose tooling to run — adding complexity with no additional coverage value. ## Solution **Commit 1 — retire `cli.command.json_envelope`:** - Remove `run_cli_json_envelope_evidence()` and `_json_args_for_subject()` from `runners.py` - Remove `cli.command.json_envelope` claim and runner binding from `catalog.py` - Remove `test_cli_json_envelope_runner_emits_ok_evidence` from `test_evidence_runners.py` - Remove from `evidence-freshness.yaml` per_push policy - Update `test_catalog.py` and `test_diffing.py` assertions **Commit 2 — expand `TestHelpExitCodeAndContent` + retire `cli.command.help` / `cli.command.no_traceback`:** - Add `_ALL_COMMANDS` tuple (53 command paths) to `test_stdout_stderr_split.py` - Parametrize `test_help_exits_zero_with_usage()` over all 53 paths — asserts exit 0, "Usage:" present, no traceback - Remove `_run_cli_help_evidence()`, `_run_cli_no_traceback_evidence()` from `runners.py` - Remove their dispatch cases from `run_cli_visual_evidence()` (plain_mode branch kept — no pytest owner yet) - Remove both claims from catalog, runner bindings, evidence-freshness, test assertions **Result:** 497 obligations (was 603), 38 claims (was 40). Catalog regenerated. ## Verification ``` git push # pre-push gate ran all 15 checks in 19.7s, all pass python -m pytest tests/unit/cli/test_stdout_stderr_split.py -q # 54 passed python -m devtools verify --quick # exit_code: 0 ``` Stacks on #1068. Ref #594 Co-Authored-By: Claude <[email protected]>
Summary
Advances the verifiability revamp through Phases 1 and 2: inner-loop sustainability improvements and systematic CLI/storage contract evidence.
Problem
The verification substrate had several gaps (from #1058, #1026, #1060, #997):
xdist_groupmarkers were created with wrong string syntax, grouping was silently brokendevtools verify— test results were terminal-onlyverify_showcase_baselines(update=False)with no existing baselines returned 0 (wrong behavior)test_json_envelope_contract.pyusedpytest.skipon failure instead ofpytest.fail— could silently mask real failureslast_exercised_attimestamps were 31 days old (1 day over threshold)Solution
Phase 1 — inner loop (Ref #1026):
tests/unit/sources/conftest.py: Fix xdist_group marker syntax (pytest.mark.xdist_group(name=provider)not string form)tests/unit/showcase/test_verification_lane.py: Add missingtest_main_returns_1_when_no_baselines_and_no_updatetests/conftest.py: Register "verify" Hypothesis profile (10 examples, 5s deadline) for fast routine runsdevtools/verify.py: Add--junitxml=.cache/test-reports/verify-latest.xml+--durations=10to all pytest invocationsPhase 2 — CLI/storage contracts (Ref #1060, #997):
tests/unit/cli/test_exit_code_contracts.py(NEW, 25 tests,@pytest.mark.machine_contract): exit-code contracts for help/version/type-errors/runtime-errors/json-mode consistencytests/unit/cli/test_stdout_stderr_split.py(NEW, 46 tests): stdout/stderr separation via CliRunner (fast) and subprocess.run(capture_output=True) (slow/subprocess)tests/unit/cli/test_json_envelope_contract.py: Replacepytest.skipwithpytest.fail; addworkspace_envfixture to tests needing DBtests/unit/storage/test_query_parity.py(NEW, 12 tests,@pytest.mark.contract): count/ID/filter/search/limit parity across SQLiteBackend, ConversationRepository, and Polylogue facadetests/witnesses/: Refreshlast_exercised_atto 2026-05-16 after all witness tests passVerification
All new tests pass in the test suite. The new test files add:
test_exit_code_contracts.pytest_stdout_stderr_split.pytest_query_parity.pyRef #1026, Ref #1060, Ref #997
Summary by CodeRabbit
Tests
Chores