Skip to content

fix: page explain(subject=result/recovery) instead of infinite retry - #3342

Merged
Sinity merged 1 commit into
masterfrom
fix/mcp/explain-catalog-pagination
Jul 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/mcp/explain-catalog-pagination

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes explain(subject="result"|"recovery") returning page=null /
returned_items=0 with a continuation that silently drops subject,
making the query-discovery catalog unrecoverable through the MCP
discovery surface. Generalizes the response-budget trimmer to handle
dict-rooted payloads with multiple list fields, and threads real call
arguments through to continuations for non-session-scoped tools.

Problem

explain(subject="result"|"recovery") serializes the full
QUERY_DISCOVERY_EXAMPLES catalog (106 examples, ~82.5KB) inside one
MCPRootPayload, well over MCP_RESPONSE_BUDGET_BYTES (25000). Two
compounding defects made this unrecoverable rather than merely large:

  1. _bounded_item_page (polylogue/mcp/server_support.py) only checked
    payload.items/.messages/.hits via getattr. MCPRootPayload is a
    pydantic RootModel wrapping a plain dict, so none of those attributes
    ever resolve, and the dict additionally carries multiple list-valued
    keys (result_semantics, examples, read_views) that a single
    hardcoded field name could never generalize to anyway. The trimmer
    always returned page=None.
  2. The synthesized continuation came from
    _fallback_response_arguments(fn_name, session_id), which only knows
    session_id. For a non-session-scoped call like
    explain(subject="result") it returned {}, silently dropping
    subject -- retrying continuation.tool/continuation.arguments
    replayed the identical oversized, argument-losing call forever. A
    cold model relying purely on the shipped MCP discovery surface
    (list_tools + explain) could not retrieve the query-discovery
    catalog at all.

Discovered while building the polylogue-z9gh gap #3 cold-model MCP
continuity replay harness (devtools/cold_model_continuity_replay.py).

Solution

  • _bounded_item_page now detects a dict-rooted RootModel payload
    and delegates to a new _bounded_root_dict_page helper, which picks the
    single largest list-valued key in the root dict and binary-searches its
    prefix the same way the existing attribute-based path does for
    items/messages/hits, leaving smaller sibling lists untouched. This
    is a clean generalization (not an explain-only special case): any
    current or future dict-rooted MCP payload with multiple list fields
    gets correct budget trimming for free.
  • _fallback_response_arguments/_safe_call/_async_safe_call (plus
    the SafeCallHook/AsyncSafeCallHook protocols and server.py's hook
    wiring) gained an explicit arguments parameter so a tool body can hand
    its own bound call arguments to the response-context continuation
    machinery, instead of the session-id-only fallback that only covers
    session-scoped tools.
  • explain() (polylogue/mcp/server_cutover.py) gained an offset
    parameter that windows the examples/read_views lists before
    serialization, and now passes
    {subject, expression, ref, offset} as its safe-call arguments so a
    budget-exceeded continuation replays with subject preserved and
    offset advanced by the count actually returned on the prior page.
    total (previously an unrelated len(read_views), always 0 for the
    result/recovery subjects) now correctly reports the full catalog
    size.

Alternative considered

A dedicated per-explain pagination path restructuring the response
shape was the fallback plan (AC1 option b), but the generic
_bounded_root_dict_page generalization turned out no more complex and
also silently fixes at least one other pre-existing dict-rooted payload
(abandoned/maintenance {"items": [...], "total": ...} shapes) that was
never actually reachable by the old attribute-based trimmer either.

Verification

  • devtools test tests/unit/mcp/ -> 193 passed, including the 5 new
    tests in tests/unit/mcp/test_explain_catalog_pagination.py, which
    drive the real wired explain tool through continuation to exhaustion
    for both subject="result" and subject="recovery", asserting all 106
    examples are retrieved exactly once with no duplicates/skips, and that
    the continuation's offset strictly advances.
  • Reproduced the pre-fix defect directly: stashed the three production
    file changes (test file left in place) and reran the new test module --
    4 of 5 tests failed with page: None, continuation.arguments: {},
    confirming the test exercises the exact described failure before the
    fix restores it green.
  • devtools verify --quick -> exit 0 (format, lint, mypy --strict,
    render all --check, layering/closure-matrix/manifests/doc-commands/
    docs-coverage/test-infra-currency/clock-hygiene/timeout-overrides/
    degrade-loudly/hash-boundary-census). Ran automatically on git push
    via the pre-push hook as well.
  • Not run: full devtools verify --all (reserved for harness/dependency
    changes or a final pre-merge diagnostic per repo convention); per-PR CI
    skips the heavy test suite by design (runs post-merge on master), so
    the devtools test tests/unit/mcp/ run above is the actual test
    evidence for this PR.

Acceptance criteria (polylogue-3k30)

  1. Satisfied. explain(subject="result"|"recovery") pages its
    examples list with a continuation that preserves subject (and
    expression/ref) and advances offset.
  2. Satisfied, generally. _fallback_response_arguments now accepts an
    explicit arguments override; explain supplies it. The mechanism is
    general (any tool body can opt in), not an explain-only patch, though
    only explain was migrated to use it in this PR -- other
    non-session-scoped tools whose continuations may still fall back to
    {} are unaffected by this change and are not claimed as fixed here.
  3. Satisfied. Regression test calls the real MCP explain tool for
    the full catalog and asserts every example is retrievable through
    continuation; verified to fail pre-fix.

Ref polylogue-3k30

Problem: explain(subject="result"|"recovery") serializes the full
QUERY_DISCOVERY_EXAMPLES catalog (106 examples, ~82.5KB) inside one
MCPRootPayload -- well over MCP_RESPONSE_BUDGET_BYTES (25000). Two
compounding defects made this unrecoverable rather than merely large:

1. _bounded_item_page only checked payload.items/.messages/.hits via
   getattr. MCPRootPayload is a pydantic RootModel wrapping a plain dict,
   so none of those attributes ever resolved, and the dict additionally
   carries multiple list-valued keys (result_semantics, examples,
   read_views) that a single hardcoded field name could never generalize
   to anyway. The trimmer always returned page=None.
2. The synthesized continuation came from
   _fallback_response_arguments(fn_name, session_id), which only knows
   session_id. For a non-session-scoped call like explain(subject=
   "result") it returned {}, silently dropping subject -- retrying the
   continuation replayed the identical oversized call forever.

What changed:
- _bounded_item_page (polylogue/mcp/server_support.py) now detects a
  dict-rooted RootModel payload and delegates to a new
  _bounded_root_dict_page helper, which picks the single largest
  list-valued key in the root dict and binary-searches its prefix the
  same way the attribute-based path already does for items/messages/hits,
  leaving smaller sibling lists untouched. This generalizes beyond
  explain to any current or future dict-rooted MCP payload with multiple
  list fields.
- _fallback_response_arguments/_safe_call/_async_safe_call (plus the
  SafeCallHook/AsyncSafeCallHook protocols and server.py's hook wiring)
  gained an explicit `arguments` parameter so a tool body can hand its own
  bound call arguments to the response-context continuation machinery
  instead of the session-id-only fallback.
- explain() (polylogue/mcp/server_cutover.py) gained an `offset` parameter
  used to window the examples/read_views lists before serialization, and
  now passes {subject, expression, ref, offset} as its safe-call
  arguments so a budget-exceeded continuation replays with subject
  preserved and offset advanced by the count actually returned.

Verification:
- devtools test tests/unit/mcp/ -> 193 passed (includes the 5 new tests
  in tests/unit/mcp/test_explain_catalog_pagination.py, which drive the
  real wired explain tool through continuation to exhaustion for both
  subject="result" and subject="recovery", asserting all 106 examples are
  retrieved exactly once with no duplicates/skips, and that the
  continuation's offset strictly advances).
- Manually reverted the three production files (git stash) with the new
  test file left in place: 4 of 5 tests failed exactly as described
  (page=None, continuation.arguments={}), confirming the test reproduces
  the pre-fix defect before the fix was restored.
- devtools verify --quick -> exit 0 (format, lint, mypy --strict, render
  all --check, layering/closure-matrix/manifests/doc-commands/
  docs-coverage/test-infra-currency/clock-hygiene/timeout-overrides/
  degrade-loudly/hash-boundary-census).

Ref polylogue-3k30

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 18 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1c57e046-6d1c-4aae-8921-a04d67690516

📥 Commits

Reviewing files that changed from the base of the PR and between 2c5a112 and d06f5fc.

📒 Files selected for processing (4)
  • polylogue/mcp/server.py
  • polylogue/mcp/server_cutover.py
  • polylogue/mcp/server_support.py
  • tests/unit/mcp/test_explain_catalog_pagination.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/mcp/explain-catalog-pagination

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.

@Sinity
Sinity merged commit 13924f5 into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the fix/mcp/explain-catalog-pagination branch July 27, 2026 17:42
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