Skip to content

test: advance verifiability Phase 1+2 — inner loop + CLI/storage contracts (#1026, #1060, #997) - #1068

Merged
Sinity merged 5 commits into
masterfrom
feature/test/verifiability-phase1
May 16, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/test/verifiability-phase1

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026 •

Copy link
Copy Markdown
Owner

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_group markers were created with wrong string syntax, grouping was silently broken
  • No JUnit XML artifacts from devtools verify — test results were terminal-only
  • Hypothesis had no "verify" profile; full-suite runs used the expensive default (100 examples)
  • Missing test: verify_showcase_baselines(update=False) with no existing baselines returned 0 (wrong behavior)
  • CLI exit-code contract had no pytest evidence (relied on proof-era runners)
  • CLI stdout/stderr channel separation had no pytest evidence
  • test_json_envelope_contract.py used pytest.skip on failure instead of pytest.fail — could silently mask real failures
  • Storage/repository/facade query results had no parity contract tests
  • Witness last_exercised_at timestamps 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 missing test_main_returns_1_when_no_baselines_and_no_update
  • tests/conftest.py: Register "verify" Hypothesis profile (10 examples, 5s deadline) for fast routine runs
  • devtools/verify.py: Add --junitxml=.cache/test-reports/verify-latest.xml + --durations=10 to all pytest invocations

Phase 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 consistency
  • tests/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: Replace pytest.skip with pytest.fail; add workspace_env fixture to tests needing DB
  • tests/unit/storage/test_query_parity.py (NEW, 12 tests, @pytest.mark.contract): count/ID/filter/search/limit parity across SQLiteBackend, ConversationRepository, and Polylogue facade
  • tests/witnesses/: Refresh last_exercised_at to 2026-05-16 after all witness tests pass

Verification

python -m devtools verify --quick    # 15/15 gates pass, 40.8s

All new tests pass in the test suite. The new test files add:

  • 25 tests in test_exit_code_contracts.py
  • 46 tests in test_stdout_stderr_split.py
  • 12 tests in test_query_parity.py

Ref #1026, Ref #1060, Ref #997

Summary by CodeRabbit

  • Tests

    • Added comprehensive unit tests for CLI exit codes across success and error scenarios.
    • Added tests for CLI stdout/stderr separation and JSON output handling.
    • Added parity tests verifying consistent query results across storage layers.
    • Added test for showcase baseline verification behavior.
  • Chores

    • Enhanced verification tooling to generate JUnit XML test reports.
    • Updated test configuration for faster verification runs.
    • Updated witness file timestamps.

Review Change Stack

Sinity and others added 5 commits May 16, 2026 05:06
- 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]>
@coderabbitai

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This 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.

Changes

Test Infrastructure & Configuration

Layer / File(s) Summary
JUnit XML reporting and Hypothesis profile configuration
devtools/verify.py, tests/conftest.py
Pytest default command now creates .cache/test-reports directory and emits JUnit XML output to verify-latest.xml; new Hypothesis verify profile configures max_examples=10, higher deadline=5000, and suppresses too_slow, filter_too_much, and differing_executors health checks for bounded test runs.
xdist group marker refinement
tests/unit/sources/conftest.py
Updated pytest marker assignment to use structured pytest.mark.xdist_group(name=provider) instead of formatted marker strings.

CLI Contract Tests

Layer / File(s) Summary
CLI exit code contracts
tests/unit/cli/test_exit_code_contracts.py
New test module pinning exit-code semantics: 0 for successful help/version invocations across multiple subcommands, 2 for Click argument-type mismatches (--limit, --min-messages, --min-words, --max-messages), and 1 for runtime query validation failures (--since/--until invalid dates). Includes parameterized scenarios for success and error paths.
JSON envelope contract refactoring
tests/unit/cli/test_json_envelope_contract.py
Rewrote _invoke_json_command helper to enforce non-zero CLI exit codes as test failures and require JSON object presence, changing return type from optional to guaranteed JSONDocument. Updated test method signatures to accept workspace_env fixture for deterministic execution without skip behavior.
Stdout/stderr separation contracts
tests/unit/cli/test_stdout_stderr_split.py
New test module verifying CLI stdout/stderr isolation via both fast CliRunner and slow subprocess-based tests. Validates --help and --version exit with code 0 and non-empty output, invalid arguments exit non-zero without traceback sentinel, and real channel isolation using capture_output=True.

Data Layer Query Parity Tests

Layer / File(s) Summary
Cross-layer query parity verification
tests/unit/storage/test_query_parity.py
New comprehensive test module with 12 async tests seeding deterministic conversations via ConversationBuilder and asserting parity across ConversationRepository, Polylogue facade, and SQLiteBackend query layers. Covers count matching (including empty DB), ID list parity (filtered and unfiltered), provider filtering exclusivity, full-text search subset/inclusion/exclusion, limit enforcement consistency, and backend query-layer provider-filtered counts.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • Sinity/polylogue#1066: Refactors build_verify_steps pytest command construction in devtools/verify.py, directly related to this PR's test reporting changes.
  • Sinity/polylogue#438: Adds verify-topology step into build_verify_steps execution list, related through shared test orchestration code.

Suggested labels

type:test, area:qa

Poem

A rabbit hops through test suites bright,
With exit codes and parity in sight,
From CLI clicks to storage queries deep,
Contract contracts that we'll always keep,
XML reports now guide the way,
Ensuring correctness, every single day! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: advancing verifiability through two phases with specific focus on inner-loop improvements and CLI/storage contracts.
Description check ✅ Passed The PR description comprehensively covers all required template sections: Summary, Problem, Solution, Verification, and includes detailed context for Risks and Follow-ups.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/verifiability-phase1

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

📥 Commits

Reviewing files that changed from the base of the PR and between da72933 and ce3cf14.

📒 Files selected for processing (14)
  • devtools/verify.py
  • tests/conftest.py
  • tests/unit/cli/test_exit_code_contracts.py
  • tests/unit/cli/test_json_envelope_contract.py
  • tests/unit/cli/test_stdout_stderr_split.py
  • tests/unit/showcase/test_verification_lane.py
  • tests/unit/sources/conftest.py
  • tests/unit/storage/test_query_parity.py
  • tests/witnesses/blob-store-layout.witness.json
  • tests/witnesses/browser-capture-sequence.witness.json
  • tests/witnesses/cli-command-surface.witness.json
  • tests/witnesses/golden-tool-use-json.witness.json
  • tests/witnesses/mcp-tool-schemas.witness.json
  • tests/witnesses/topology-projection.witness.json

Comment on lines +205 to +208
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

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 | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +31 to +52
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()
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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().

@Sinity
Sinity merged commit b4d58f9 into master May 16, 2026
4 checks passed
@Sinity
Sinity deleted the feature/test/verifiability-phase1 branch May 16, 2026 05:06
Sinity added a commit that referenced this pull request May 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant