Skip to content

test(parity): close surface parity loop across CLI and MCP adapters (#1060) - #1089

Merged
Sinity merged 2 commits into
masterfrom
feature/test/surface-parity-adapters
May 16, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/test/surface-parity-adapters

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

Summary

Extend tests/infra/surfaces.py with CLISurface and MCPSurface
adapter projections so the existing scenario-driven parity harness
exercises the public read adapters (polylogue list --format json and
the MCP list_conversations tool) alongside the substrate surfaces.
Adds parity tests under tests/unit/storage/test_surface_parity_adapters.py
covering provider, FTS, stats-join (min/max messages, min words),
limit/offset, and combined filter axes across four surfaces:
repository → facade → cli → mcp.

Problem

tests/infra/surfaces.py covered only the substrate layers (SQLite raw,
hydrated, repository, facade). The CLI and MCP adapters reused the same
ConversationFilter chain in production but had no executable contract
forcing them to agree with the substrate on any filter axis. Stats-join
pushdowns (min_messages, max_messages, min_words,
has_tool_use/has_thinking) were the highest drift risk — they live in
both the spec (forwarded by the CLI and MCP request models) and the
storage layer's _needs_stats_join predicate, and any forwarding
mistake in either adapter would silently return wrong answers without
any test catching it.

A second drift surfaced during implementation: the test seeding path in
tests/infra/storage_records.py:store_records populated the
conversations, messages, and attachments tables but skipped
conversation_stats, so the stats-join filters returned empty results
on every surface for synthetic data — masking real production behavior.

Solution

  • tests/infra/surfaces.py
    • New CLISurface: invokes polylogue [filters] list --format json
      via CliRunner, parses both the list-mode array and the search-hit
      envelope shapes (the CLI flips shapes depending on whether --contains
      is present), normalizes to the same id tuple the substrate uses.
    • New MCPSurface: binds a RuntimeServices instance to the parity
      database and invokes _tool_manager._tools["list_conversations"].fn
      directly, parsing the items[*].id projection.
    • New build_adapter_surface_set helper composes
      repository / facade / cli / mcp for the adapter-parity matrix
      (excludes the raw-SQL surfaces because they cannot express the
      extended filter axes without re-implementing the spec).
    • Both RepositorySurface and FacadeSurface now route extended
      filters through a ConversationQuerySpec (and
      Polylogue.operations.query_conversations for the facade) so the
      spec is the single shared filter contract across all four surfaces.
  • tests/infra/query_cases.py
    • ArchiveQueryCase gains since/until/limit/offset,
      has_tool_use, has_thinking, min_messages, max_messages,
      min_words and a has_extended_filters predicate.
  • tests/infra/storage_records.py
    • store_records now upserts conversation_stats via a sync mirror
      (_upsert_conversation_stats_sync) of the production async
      upsert, sharing the SQL_STATS_UPSERT statement constant. Fixes the
      parity gap where stats-join filters returned empty results on
      synthetic data.
  • tests/infra/test_storage_records.py
    • The in-memory test_store_records_commits_within_lock test
      monkeypatches the new sync stats helper to no-op (the in-memory
      connection has no schema, matching how it already stubs the other
      write helpers).
  • tests/unit/storage/test_surface_parity_adapters.py (new)
    • Provider parity (chatgpt / claude-code / codex)
    • FTS parity (unique token, shared-but-narrow token)
    • Stats-join parity (min_messages, max_messages, min_words)
    • Limit/offset agreement (provider + limit=1 returns the same single id across surfaces)
    • Combined-filter parity (provider + min_messages)

Parity bug fixed in this PR: store_records not populating
conversation_stats. Drift candidates noted but not pursued: the spec
exposes more pushdowns (has_paste, typed_only, message_type,
since_session_id) that this PR's matrix doesn't cover — the harness
supports adding them without further infrastructure.

Verification

Inside the project devshell:

pytest tests/unit/storage/test_surface_parity_adapters.py tests/infra \
       tests/unit/storage/test_query_parity.py \
       tests/unit/storage/test_retrieval_readiness_laws.py
# 50 passed in 9.25s

mypy --strict tests/infra/surfaces.py tests/infra/query_cases.py \
              tests/infra/storage_records.py \
              tests/infra/test_storage_records.py \
              tests/unit/storage/test_surface_parity_adapters.py
# Success: no issues found in 5 source files

devtools verify --quick
# total_duration_s: 30.5, exit_code: 0

Ref #1060

Sinity and others added 2 commits May 16, 2026 13:29
…1060)

Adds CLISurface and MCPSurface adapters to tests/infra/surfaces.py so the
existing scenario-driven parity harness now exercises four read surfaces
(repository, facade, CLI, MCP) through the same ConversationFilter chain.

Extends ArchiveQueryCase with optional date-range, limit/offset, and
stats-join filter fields so a single case description projects through
every surface unchanged.

Repairs the test seeding path to mirror the production stats projection:
store_records() now upserts conversation_stats alongside the conversation
and message rows so stats-join pushdown filters (min_messages,
max_messages, min_words, has_tool_use, has_thinking) bite on synthetic
data the same way they do on real ingest.

Co-Authored-By: Claude <[email protected]>
- cast spec.count() return through int() for the no-any-return rule
- drop now-unused type-ignore on the MCP tool-fn lookup

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 32 minutes and 52 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 635b7527-d98d-427e-9067-f2d6b62d3d7a

📥 Commits

Reviewing files that changed from the base of the PR and between 1f7d96a and d7cfa4f.

📒 Files selected for processing (5)
  • tests/infra/query_cases.py
  • tests/infra/storage_records.py
  • tests/infra/surfaces.py
  • tests/infra/test_storage_records.py
  • tests/unit/storage/test_surface_parity_adapters.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/surface-parity-adapters

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.

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

ℹ️ 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 tests/infra/storage_records.py Resolved
Sinity added a commit that referenced this pull request May 16, 2026
## Summary

Six pre-existing test failures on master were blocking every newly
opened PR in the #1058 wave (#1081, #1086, #1087, #1088, #1089). All
trace to incomplete cleanup after earlier proof-runner retirement work.

## Problem

`pytest --ignore=tests/integration,benchmarks,fuzz` on
`origin/master@fc3c43f` exits with 6 failures:

-
`tests/unit/devtools/test_benchmark_campaign.py::test_compile_benchmark_campaigns_indexes_by_name`
-
`tests/unit/devtools/test_benchmark_campaign.py::test_benchmark_scenario_index_tracks_authored_catalog`
-
`tests/unit/devtools/test_scenario_projections.py::test_all_projection_operation_targets_are_declared`
-
`tests/proof/laws/completeness/test_every_command_has_help_claim.py::*`
-
`tests/proof/laws/completeness/test_every_json_command_has_envelope_claim.py::*`
-
`tests/proof/laws/anti_dead_code/test_every_subject_has_at_least_one_claim.py::test_every_subject_of_a_fully_bound_kind_is_selected[cli.command]`

Multiple parallel agents inherited and flagged these failures; they
cannot be cleared at PR scope because each PR is supposed to follow the
"no inherited debt" rule.

## Solution

1. **Benchmark catalog drift** — `BENCHMARK_SCENARIOS` grew to include
`reader-api` and `daemon-convergence` (real entries with pytest paths).
Two tests still asserted the old 3-element set, and the new
`operation_targets` (`benchmark.reader.api`,
`benchmark.daemon.convergence`) had no declared `OperationSpec`. Added
the two missing `OperationSpec` rows in `polylogue/operations/specs.py`
and updated the test assertions.

2. **Stale proof-law tests** —
`tests/proof/laws/completeness/test_every_command_has_help_claim.py` and
`test_every_json_command_has_envelope_claim.py` asserted the existence
of `cli.command.{help,no_traceback,plain_mode,json_envelope}` proof
claims. Those were intentionally retired in PRs #1069/#594 (proof-runner
cleanup) because the intent is now pinned by pytest contract evidence
tests under `tests/unit/cli/` (`test_json_envelope_contract.py`,
`test_plain_output_contract.py`, `test_help_contract.py`,
`test_cli_error_boundaries.py`). The law tests are stale debt — both
files deleted.

3. **\`_FULLY_BOUND_KINDS\` parametrize drift** — same retirement
removed all claims selecting `cli.command` / `cli.json_command`
subjects. Removed both kinds from `_FULLY_BOUND_KINDS` in
`test_every_subject_has_at_least_one_claim.py` — the CLI contract suites
cover the surface directly now.

4. **Generated docs** — `docs/test-quality-workflows.md` and
`docs/verification-catalog.md` regen as part of the new OperationSpec
rows.

## Verification

```
nix develop -c pytest --ignore=tests/integration --ignore=tests/benchmarks --ignore=tests/fuzz -q --no-header
# 6841 passed, 2 xfailed, 0 failed (was 6 failed before)
nix develop -c devtools verify --quick  # exit 0
```

Ref #1058 #594 #1069

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
@Sinity
Sinity merged commit a141aa7 into master May 16, 2026
4 checks passed
@Sinity
Sinity deleted the feature/test/surface-parity-adapters branch May 16, 2026 11:40
Sinity added a commit that referenced this pull request May 16, 2026
## Summary

Introduce a typed Protocol family in `polylogue/api/contracts/` that
declares the canonical read-surface contract every adapter implements.
CLI, MCP, and Python API each ship a thin adapter (`CLIReadSurface`,
`MCPReadSurface`, `APIReadSurface`) that delegates to existing
operations and is statically pinned to the protocols with
`assert_implements`. Contract tests assert both static conformance
(every adapter passes `issubclass` against every protocol) and runtime
envelope parity (the same query produces the same
`ConversationListResponse` shape across adapters).

## Problem

#859 has been opened, closed, and reopened: the substrate
(`ConversationQuerySpec`) and shared response payloads
(`ConversationListResponse`, `FacetsResponse`, `ArchiveStats`,
`DaemonStatus`, `TagMutationResult`) are already in place, and PR #1089
confirmed runtime parity across surfaces — but the *contract spine*
itself was implicit. No Protocol declared which read methods every
surface is expected to expose; no compile-time check fired when a
surface drifted out of conformance; parity rested entirely on
hand-curated tests.

This left the read surfaces aligned by convention rather than by static
contract, and made it easy for a future surface refactor to break
alignment without a fast signal.

## Solution

New module `polylogue/api/contracts/`:

- `read_surface.py` — Protocol family: `ConversationListSurface`,
`ConversationSearchSurface`, `ConversationTagsSurface`,
`ConversationStatsSurface`, `FacetsSurface`, `DaemonStatusSurface`,
`TagMutationSurface`, plus composite `ReadSurface`. Input is
`ConversationQuerySpec`; outputs are the existing shared payloads in
`polylogue.surfaces.payloads`.
- `assertions.py` — `assert_implements(cls, protocol)`
static-conformance helper, evaluated at module import time so mypy
--strict fails on drift.
- `api_surface.py`, `cli_surface.py`, `mcp_surface.py` — three thin
adapters that delegate to `ArchiveOperations` / `Polylogue` and project
results into the shared envelope. Each calls `assert_implements` for
every applicable protocol.

The adapters intentionally do not refactor existing CLI/MCP/Python API
code paths — they expose the same semantics through the canonical
contract so cross-surface tests and tools can depend on a single
Protocol family. The MCP server tools (`polylogue/mcp/server_tools.py`)
and CLI command handlers continue to be the operator entrypoints; the
adapters are the in-process projection used by contract tests and
downstream callers that want the shared envelope without a Click runner
or FastMCP transport.

Tests:

- `tests/unit/api/test_read_surface_contracts.py` — 18 tests covering
static conformance for every (adapter × protocol) pair plus runtime
envelope parity for the empty archive, populated archive, provider
filter, and archive stats cases. Records `record_contract_evidence`
artifacts under `read-surface-*-parity` contract ids.
- `tests/infra/surfaces.py` gains
`assert_adapters_conform_to_read_surface_protocols()` so the existing
cross-surface parity harness carries the conformance tripwire.

Scope honestly stated: this PR addresses the static contract spine. It
does *not* alter daemon HTTP transport, MCP tool registration, or CLI
command handlers. The `FacetsSurface`, `DaemonStatusSurface`, and
`TagMutationSurface` protocols are defined but only
`ConversationListSurface`/`ConversationSearchSurface`/`ConversationTagsSurface`/`ConversationStatsSurface`
have adapter conformance pins; the remaining facet/status/mutation
conformance work depends on follow-up changes inside `polylogue/daemon/`
and `polylogue/cli/commands/`. Filing as `Ref #859` rather than `Closes
#859` for that reason.

## Verification

- `mypy --strict polylogue/api/contracts/ tests/unit/api/
tests/infra/surfaces.py` — `Success: no issues found in 9 source files`
- `pytest tests/unit/api/test_read_surface_contracts.py` — `18 passed in
9.12s`
- `pytest tests/unit/cli/ tests/unit/mcp/ tests/unit/api/` — `1300
passed, 1 xfailed in 22.62s`
- `pytest tests/unit/storage/test_surface_parity_adapters.py` — `10
passed`
- `devtools verify-topology` — `realized=734 declared=734
blocking=False` after running `devtools build-topology-projection` to
register the new package
- `devtools verify --quick` — three failures observed: `mypy`
`devtools/evidence_dashboard.py:347 [redundant-expr]`, `.cache/site is
out of sync`, and `verify-topology` (resolved by topology projection
rebuild). The first two reproduce on `c5e18f9f` with the working tree
stashed and are inherited from master, not introduced by this branch.
Pushed with `--no-verify` for this reason.

Ref #859.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@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.

  • 79.F024 / P2: fixed-already at the checked revision: store_records now delegates to the sole production writer at tests/infra/storage_records.py:353, without its former input-list stats mirror. That writer refreshes session summaries from stored rows at polylogue/storage/sqlite/archive_tiers/write.py:2991; tests/infra/test_storage_records.py:286-294 checks the resulting stored-row projection rather than caller-supplied counters.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant