Skip to content

fix(tests): green master CI — TypedDict, MCP mutation contracts, drift - #505

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/master-test-debt-v2
Apr 27, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/master-test-debt-v2

Conversation

@Sinity

@Sinity Sinity commented Apr 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Master CI has been red since 6b5c392 (#489) due to 14 unrelated test failures. This PR fixes them all in one mechanical pass so the architecture-series PRs (#502 and follow-ups) can land.

Problem

Failures span four root causes:

  1. Python 3.11 / pydantic TypedDict. Pydantic 2.12+ refuses typing.TypedDict on Python < 3.12. 19 modules declare TypedDict subclasses; they all need to import from typing_extensions.
  2. MCP mutation tests don't mock the new resolve_id pre-check. Mutation tools resolve the conversation_id via the query store before mutating; tests only patched _get_tag_store, so resolve_id returned None and the tools short-circuited with "conversation not found".
  3. Schema/contract drift. _clamp_limit caps at 1000 but tests still echo unbounded inputs. get_stats_by gained an enum on group_by but the witness wasn't regenerated. bulk_tag_conversations switched to bulk_add_tags(ids, tags) but the test still asserts N×M add_tag awaits.
  4. Env-sensitive logging test. configure_logging honors POLYLOGUE_FORCE_PLAIN; CI sets that env to 1, so ConsoleRenderer(colors=True) is unreachable from inside CI.

Solution

Six targeted fixes:

  1. Switch 19 files from typing.TypedDict to typing_extensions.TypedDict. Add typing-extensions>=4.7 to pyproject.toml (works on all supported Pythons).
  2. Add resolved_id parameter to make_query_store_mock and patch _get_query_store in affected mutation tests (add_tag, remove_tag, set_metadata, delete_metadata, delete_conversation).
  3. Update _clamp_limit parametrized cases (5000/10001/99999 → 1000); regen tests/data/witnesses/mcp-tool-schemas.json; rewrite bulk_tag test to assert on bulk_add_tags.
  4. Add patch.dict("os.environ") + env.pop("POLYLOGUE_FORCE_PLAIN") to the logging test.
  5. Refresh syrupy test_terminal_snapshots.ambr (same drift as fix(baselines): refresh showcase help baselines after #482/#483 merges #503; included here to make the unit suite green standalone).

Verification

POLYLOGUE_FORCE_PLAIN=1 pytest tests/unit/mcp/ \
  tests/unit/test_logging_runtime.py \
  tests/unit/cli/test_terminal_snapshots.py --no-cov
→ all pass

devtools verify --quick
→ all checks passed (pre-push hook)

Out of scope

test_cli_tail_list_json_exposes_tail_provenance is failing on a TOCTOU warning from a parallel BlobStore fix (in feature/fix/audit-final / d295503). Tracked there; not in this PR.

Related

Summary by CodeRabbit

  • Documentation

    • Enhanced CLI help text for export and show commands with clearer descriptions of conversation ID format handling and default output behavior.
    • Reordered MCP tool schema parameters with added validation constraints.
  • Chores

    • Added typing-extensions>=4.7 as a runtime dependency.

Master CI has been red since 6b5c392 (#489) due to 14 unrelated test
failures. This PR fixes them all in one mechanical pass.

Changes
-------

1. **Python 3.11 TypedDict / pydantic compatibility.** pydantic 2.12+
   refuses ``typing.TypedDict`` on Py<3.12 with PydanticUserError. Switch
   the 19 modules that declare TypedDict subclasses to import from
   ``typing_extensions`` instead. Add ``typing-extensions>=4.7`` to
   ``pyproject.toml`` so the import resolves on every supported Python.

2. **MCP mutation tests — query_store.resolve_id pre-check.** The
   mutation tools (``add_tag``, ``remove_tag``, ``set_metadata``,
   ``delete_metadata``, ``delete_conversation``) now resolve the
   conversation_id via the query store before mutating; tests that mocked
   only ``_get_tag_store`` saw the pre-check fail with "conversation not
   found". Add a ``resolved_id`` parameter to ``make_query_store_mock``
   and patch ``_get_query_store`` in each affected test.

3. **Bulk tag — bulk_add_tags delegation.** ``bulk_tag_conversations``
   now calls ``tag_store.bulk_add_tags(ids, tags)`` once instead of
   fan-out N×M ``add_tag`` awaits. Update the test to mock
   ``bulk_add_tags`` and assert on it.

4. **Clamp limit — 1000 cap.** ``_clamp_limit`` caps inputs at 1000;
   the test still expected unbounded inputs to echo. Update the
   parametrized expectations: 5000/10001/99999 → 1000.

5. **Logging test under POLYLOGUE_FORCE_PLAIN=1.**
   ``configure_logging`` reads ``POLYLOGUE_FORCE_PLAIN`` and forces
   ``ConsoleRenderer(colors=False)`` when set. CI sets that env, so the
   test that asserted ``colors=True`` failed. Add ``patch.dict("os.environ")``
   plus ``env.pop("POLYLOGUE_FORCE_PLAIN")`` so the colored-output branch
   exercises its own contract regardless of ambient env.

6. **MCP tool wire schema witness regen.** ``get_stats_by`` gained an
   ``enum`` field on the ``group_by`` parameter; the committed witness
   was stale. Regenerated.

7. **Terminal snapshot regen.** ``test_help_at_*_width`` and
   ``test_help_output_snapshot`` baselines drifted after the show/export
   help-text fixes (#482/#483). Same regen as #503; included here so
   the unit suite is green standalone.

Verification
------------

  POLYLOGUE_FORCE_PLAIN=1 pytest tests/unit/mcp/ tests/unit/test_logging_runtime.py \
    tests/unit/cli/test_terminal_snapshots.py --no-cov
    → all pass

Out of scope
------------

The following test failures from the same CI run are **not** addressed
here because they are pre-existing or in another contributor's lane:

- ``test_cli_tail_list_json_exposes_tail_provenance`` — TOCTOU
  warning from a parallel BlobStore fix; tracked separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The PR migrates TypedDict imports from the standard library typing module to typing_extensions across 19 modules, adds a runtime dependency on typing-extensions>=4.7, updates CLI help text descriptions, restructures MCP tool parameter schemas, and enhances test infrastructure for query store mocking and conversation ID resolution.

Changes

Cohort / File(s) Summary
TypedDict Import Migration
polylogue/lib/embeddings/stats.py, polylogue/lib/session_payload_documents.py, polylogue/mcp/payloads.py, polylogue/mcp/server_prompts.py, polylogue/pipeline/payload_types.py, polylogue/pipeline/run_finalization.py, polylogue/pipeline/semantic_capture.py, polylogue/pipeline/services/acquisition_records.py, polylogue/pipeline/services/indexing.py, polylogue/pipeline/services/ingest_worker.py, polylogue/schemas/verification_models.py, polylogue/sources/assembly.py, polylogue/sources/drive_gateway.py, polylogue/storage/backends/queries/stats.py, polylogue/storage/cursor_state.py, polylogue/storage/query_models.py, polylogue/storage/run_state.py, polylogue/storage/session_product_runtime.py, polylogue/surface_payloads.py
Switches TypedDict import source from typing to typing_extensions across 19 modules; no logic or type definitions changed.
Dependency Management
pyproject.toml
Adds typing-extensions>=4.7 as a runtime dependency.
CLI Help Text Updates
tests/baselines/showcase/help-export.txt, tests/baselines/showcase/help-main.txt, tests/baselines/showcase/help-show.txt
Updates help descriptions for export and show commands; clarifies output behavior and supported identifier formats.
MCP Tool Schemas
tests/data/witnesses/mcp-tool-schemas.json
Restructures and reorders parameter properties for multiple tools (delete_conversation, export_conversation, export_query_results, list_conversations, search); adds enum validation to get_stats_by.group_by; shifts primary filter fields.
Test Infrastructure for MCP
tests/infra/mcp.py
Extends make_query_store_mock with optional resolved_id parameter; adds mocked bulk_add_tags to make_tag_store_mock.
CLI Snapshot Updates
tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
Updates show command help snapshots to reflect "matched conversations" with "default full-content" output description.
MCP Tool Contract Tests
tests/unit/mcp/test_tool_contracts.py
Patches _get_query_store alongside tag store mocking; configures mocks with resolved IDs; updates bulk tagging test to use bulk_add_tags call assertions instead of per-conversation add_tag assertions.
MCP Server Surface Tests
tests/unit/mcp/test_server_surfaces.py
Updates _clamp_limit test to verify clamping to 1000 maximum instead of passthrough behavior for large values.
Logging Runtime Tests
tests/unit/test_logging_runtime.py
Isolates environment-dependent behavior by patching os.environ to clear POLYLOGUE_FORCE_PLAIN before assertion checks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

type:fix, area:mcp, type:test, area:storage, area:qa, tool:claude

Poem

🐰 Hoppy hops through the typing trees,
Moving dicts from stdlib to extensions with ease,
MCP schemas dance, new mocks appear,
Help text refines what users will hear,
A hop, a skip, compatibility's clear! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% 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 accurately summarizes the primary focus: fixing master CI test failures by addressing TypedDict imports, MCP mutation contracts, and schema drift.
Description check ✅ Passed The description provides complete coverage: clear problem breakdown into four root causes, targeted solutions for each, exact verification commands, and scope clarification with follow-up tracking.
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/fix/master-test-debt-v2

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.

Bundles the .txt baseline drift fix from #503 so the showcase-verify
job passes on this branch standalone. Without these the unit suite is
green but showcase-verify still fails.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

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

Caution

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

⚠️ Outside diff range comments (2)
tests/unit/mcp/test_tool_contracts.py (2)

989-1005: 🧹 Nitpick | 🔵 Trivial

Prefer assert_awaited_once_with for the AsyncMock assertion.

bulk_add_tags is now an AsyncMock, so use assert_awaited_once_with to assert the await happened (not just the call object construction). Functionally assert_called_once_with also works on AsyncMock, but the awaited variant better expresses intent and would catch a future regression where the coroutine is created but never awaited.

Proposed nit
-        mock_tag_store.bulk_add_tags.assert_called_once_with(["conv-1", "conv-2"], ["review", "important"])
+        mock_tag_store.bulk_add_tags.assert_awaited_once_with(["conv-1", "conv-2"], ["review", "important"])
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/mcp/test_tool_contracts.py` around lines 989 - 1005, The test uses
mock_tag_store.bulk_add_tags (an AsyncMock) but asserts with
mock_tag_store.bulk_add_tags.assert_called_once_with; change this to use
mock_tag_store.bulk_add_tags.assert_awaited_once_with(["conv-1", "conv-2"],
["review", "important"]) so the test verifies the coroutine was actually
awaited; update the assertion in tests/unit/mcp/test_tool_contracts.py next to
the existing invocation of
mcp_server._tool_manager._tools["bulk_tag_conversations"].fn.

1108-1121: 🧹 Nitpick | 🔵 Trivial

Add explicit assertion for resolve_id ordering in confirm check.

The implementation correctly validates confirm before calling resolve_id (lines 138-146 in server_mutation_tools.py). The test should explicitly assert mock_query_store.resolve_id.assert_not_called() alongside the existing delete_conversation assertion to lock in this ordering constraint. This prevents accidental reordering of the safety check if the implementation is refactored.

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

In `@tests/unit/mcp/test_tool_contracts.py` around lines 1108 - 1121, Add an
explicit assertion that mock_query_store.resolve_id was not called in
test_delete_requires_confirm to lock in the ordering check for confirm handling;
in the test_delete_requires_confirm function, after parsing the result and
before/alongside mock_query_store.delete_conversation.assert_not_called(), add
mock_query_store.resolve_id.assert_not_called() to ensure resolve_id is not
invoked when confirm=False on the delete_conversation tool.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@tests/unit/mcp/test_tool_contracts.py`:
- Around line 989-1005: The test uses mock_tag_store.bulk_add_tags (an
AsyncMock) but asserts with
mock_tag_store.bulk_add_tags.assert_called_once_with; change this to use
mock_tag_store.bulk_add_tags.assert_awaited_once_with(["conv-1", "conv-2"],
["review", "important"]) so the test verifies the coroutine was actually
awaited; update the assertion in tests/unit/mcp/test_tool_contracts.py next to
the existing invocation of
mcp_server._tool_manager._tools["bulk_tag_conversations"].fn.
- Around line 1108-1121: Add an explicit assertion that
mock_query_store.resolve_id was not called in test_delete_requires_confirm to
lock in the ordering check for confirm handling; in the
test_delete_requires_confirm function, after parsing the result and
before/alongside mock_query_store.delete_conversation.assert_not_called(), add
mock_query_store.resolve_id.assert_not_called() to ensure resolve_id is not
invoked when confirm=False on the delete_conversation tool.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4aa19c02-15aa-4673-9a10-c02113683cb4

📥 Commits

Reviewing files that changed from the base of the PR and between 6b5c392 and 4998651.

📒 Files selected for processing (29)
  • polylogue/lib/embeddings/stats.py
  • polylogue/lib/session_payload_documents.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_prompts.py
  • polylogue/pipeline/payload_types.py
  • polylogue/pipeline/run_finalization.py
  • polylogue/pipeline/semantic_capture.py
  • polylogue/pipeline/services/acquisition_records.py
  • polylogue/pipeline/services/indexing.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/schemas/verification_models.py
  • polylogue/sources/assembly.py
  • polylogue/sources/drive_gateway.py
  • polylogue/storage/backends/queries/stats.py
  • polylogue/storage/cursor_state.py
  • polylogue/storage/query_models.py
  • polylogue/storage/run_state.py
  • polylogue/storage/session_product_runtime.py
  • polylogue/surface_payloads.py
  • pyproject.toml
  • tests/baselines/showcase/help-export.txt
  • tests/baselines/showcase/help-main.txt
  • tests/baselines/showcase/help-show.txt
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/infra/mcp.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/mcp/test_server_surfaces.py
  • tests/unit/mcp/test_tool_contracts.py
  • tests/unit/test_logging_runtime.py

@Sinity
Sinity merged commit 2f094c8 into master Apr 27, 2026
14 checks passed
@Sinity
Sinity deleted the feature/fix/master-test-debt-v2 branch April 27, 2026 01:17
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

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

@Sinity
Sinity requested a review from Copilot May 1, 2026 01:55

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sinity added a commit that referenced this pull request May 7, 2026
#505)

## Summary

Master CI has been red since ddf212f (#489) due to 14 unrelated test
failures. This PR fixes them all in one mechanical pass so the
architecture-series PRs (#502 and follow-ups) can land.

## Problem

Failures span four root causes:

1. **Python 3.11 / pydantic TypedDict.** Pydantic 2.12+ refuses
`typing.TypedDict` on Python < 3.12. 19 modules declare TypedDict
subclasses; they all need to import from `typing_extensions`.
2. **MCP mutation tests don't mock the new resolve_id pre-check.**
Mutation tools resolve the conversation_id via the query store before
mutating; tests only patched `_get_tag_store`, so resolve_id returned
None and the tools short-circuited with "conversation not found".
3. **Schema/contract drift.** `_clamp_limit` caps at 1000 but tests
still echo unbounded inputs. `get_stats_by` gained an enum on `group_by`
but the witness wasn't regenerated. `bulk_tag_conversations` switched to
`bulk_add_tags(ids, tags)` but the test still asserts N×M `add_tag`
awaits.
4. **Env-sensitive logging test.** `configure_logging` honors
`POLYLOGUE_FORCE_PLAIN`; CI sets that env to `1`, so
`ConsoleRenderer(colors=True)` is unreachable from inside CI.

## Solution

Six targeted fixes:

1. Switch 19 files from `typing.TypedDict` to
`typing_extensions.TypedDict`. Add `typing-extensions>=4.7` to
`pyproject.toml` (works on all supported Pythons).
2. Add `resolved_id` parameter to `make_query_store_mock` and patch
`_get_query_store` in affected mutation tests (`add_tag`, `remove_tag`,
`set_metadata`, `delete_metadata`, `delete_conversation`).
3. Update `_clamp_limit` parametrized cases (5000/10001/99999 → 1000);
regen `tests/data/witnesses/mcp-tool-schemas.json`; rewrite bulk_tag
test to assert on `bulk_add_tags`.
4. Add `patch.dict("os.environ")` + `env.pop("POLYLOGUE_FORCE_PLAIN")`
to the logging test.
5. Refresh syrupy `test_terminal_snapshots.ambr` (same drift as #503;
included here to make the unit suite green standalone).

## Verification

```
POLYLOGUE_FORCE_PLAIN=1 pytest tests/unit/mcp/ \
  tests/unit/test_logging_runtime.py \
  tests/unit/cli/test_terminal_snapshots.py --no-cov
→ all pass

devtools verify --quick
→ all checks passed (pre-push hook)
```

## Out of scope

`test_cli_tail_list_json_exposes_tail_provenance` is failing on a TOCTOU
warning from a parallel BlobStore fix (in `feature/fix/audit-final` /
d295503). Tracked there; not in this PR.

## Related

- #503 — baseline + syrupy refresh; this PR includes the syrupy bit
again so master test suite is green even without #503.
- #502 — topology projection cleanup; blocked on master CI being green.
- #489 — the merge that introduced the 14 failures (test code wasn't
updated alongside MCP authz/limits + clamp_limit + bulk_add_tags + the
show/export help text changes that landed across several merges).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Enhanced CLI help text for export and show commands with clearer
descriptions of conversation ID format handling and default output
behavior.
* Reordered MCP tool schema parameters with added validation
constraints.

* **Chores**
  * Added `typing-extensions>=4.7` as a runtime dependency.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

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

2 participants