Skip to content

fix(llm): negotiate and cache the OpenRouter structured-reasoning disable payload - #416

Merged
ofriw merged 31 commits into
chunkhound:mainfrom
grzegorznowak:fix/openrouter-structured-reasoning
Oct 13, 2026
Merged

ofriw merged 31 commits into
chunkhound:mainfrom
grzegorznowak:fix/openrouter-structured-reasoning

Conversation

@grzegorznowak

@grzegorznowak grzegorznowak commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the OpenRouter structured-call failure from #415: reasoning models (e.g. poolside/laguna-xs-2.1) return the JSON answer in message.reasoning with message.content = null, so complete_structured() raises "empty content" and utility callers silently degrade. Disabling reasoning unconditionally is not possible — mandatory-reasoning models reject the flag with HTTP 400 — so the flag is negotiated per model and the learned outcome is cached.

Contract

  • Scope: canonical OpenRouter (base_url is None) and structured calls only (response_format present). complete() / synthesis never receive the flag.
  • States: unknown → optimistic probe with {"reasoning": {"enabled": false}}; accepted → payload stays on for every structured call; rejected → payload omitted.
  • rejected is written only after an HTTP-successful unflagged replay. Replay success means the replay received a 2xx; it does not require valid content (content is validated later in complete_structured). If the replay fails at the HTTP layer, nothing is written and the error surfaces.
  • One unflagged replay per flagged 400/422 — including followers. A caller released from the single-flight probe dispatches through the same flagged-send path, so its own 400/422 still gets its one replay (R1). Concurrent unknown callers share one probe; each flagged 400/422 still gets its own single replay; follower network I/O stays outside the capability lock.
  • 429 / 5xx / timeouts never replay and never write.
  • Persistence is keyed provider:model, atomic-replace, tolerant of malformed/corrupt/expired entries (→ unknown, never an exception), and prunes expired/older-format entries on write while preserving newer-format entries. The on-disk schema is unchanged (format_version: 1).

Relationship to #415

#415 was filed "for discussion" and its plan predates the design implemented here, so two of its bullets read as reversals. The reconciliation:

Resolved from #415's open questions: gating = C (adaptive negotiation, cached), payload = data-driven spec field.

Seals from review

  • R1 — required: the follower post-lock path now routes through the shared flagged-send/replay helper. Regression-covered.
  • U3 — rejected lease shortened to 24h; accepted stays 30d; in-process enforcement fixed. A running provider loads the persisted deadline at construction without renewing it and enforces expiry in memory, treating an expired decision as unknown and re-probing via the single-flight path. Reads never write. This removes the "pinned for 30 days" failure mode, since a rejected entry records only the HTTP outcome.
  • U2 — canonical-only boundary kept and documented. Setting llm.base_url — even to the canonical URL — routes through a generic backend and disables the probe and payload entirely, exactly like a proxy.
  • U6 — sticky accepted kept and documented. A sticky entry disables reasoning for all structured calls for the lease duration. This is a deliberate quality trade; non-structured/synthesis calls are unaffected.
  • U1 — diagnostic-only, no extra retry. Live evidence at the base of this branch: probe rejected with 400 in 8/8 sequences; the unflagged replay returned content=null in 3/8; steady-state rejected calls returned valid content in 15/15 (small sample, single model). The rejected lease is therefore an HTTP fact, not a content guarantee, so instead of adding a retry we surface it:
    • the empty-content error names provider, model, and capability state; when a rejected disable capability is the evidence it also points at configuring a different model for structured calls (llm.utility_model for utility stages);
    • the provider counts empty failures observed while the capability is rejected, exposes read-only health, and logs once per provider/model/process on first failure — never merely because a model is classified rejected;
    • the shared research service prepends a caller-visible > **Note:** … consider switching \llm.utility_model`and addsmetadata.warnings. This is the operator-visible channel, because MCP stdio mutes loguru. It covers research, quickresearch, websearch, and code_research`.
  • R2 — cache-root duplication resolved (round-2 follow-up). The platform cache-root selection (%LOCALAPPDATA%/ChunkHound vs $XDG_CACHE_HOME/chunkhound, else ~/.cache/chunkhound) now lives in one platform_cache_root() helper (chunkhound/utils/cache_paths.py), shared by the capability cache and the Watchman runtime loader. Each feature keeps its own environment override and filename/subdirectory, so overrides stay independent; tests/unit/test_platform_cache_roots.py characterizes both consumers on the XDG/home and LOCALAPPDATA/home paths. The helper lives under chunkhound/utils (not chunkhound/core) because hatch_build.py resolves it from the Watchman loader in the isolated build environment, where chunkhound.core's runtime parser dependencies are absent. This supersedes the earlier "R2 — not done" note in the review reply (40bea922; helper relocated in 4e124080).
  • N3 — the except OSError backstop is kept.

Round-2 follow-ups (2026-09-28 review)

  • Request-local degradation reporting. Empty structured failures are attributed to the requesting research run via a request-local accumulator (chunkhound/core/utils/structured_reasoning_diagnostics.py), established/reset around deep_research, so concurrent requests sharing the utility provider cannot borrow one another's > **Note:** / metadata.warnings. Provider-wide health and the log-once signal are unchanged (39c648de, 1fea9c6f).
  • Scoped empty-content diagnosis. The reasoning-disable diagnosis and model-switch guidance are emitted only when a disable payload is configured and the capability is rejected; providers that never negotiate now get the generic empty-response error (fee08e32).
  • Cache-root duplication (earlier R2). See the R2 seal above (40bea922).

Boundaries

Refs #415.

@grzegorznowak grzegorznowak changed the title test(llm): red-first contracts for OpenRouter structured-reasoning negotiation fix(llm): negotiate and cache the OpenRouter structured-reasoning disable payload Sep 17, 2026
@grzegorznowak
grzegorznowak marked this pull request as ready for review September 17, 2026 14:09
…g negotiation

Red-first contract suite for the OpenRouter structured-call reasoning
negotiation described in chunkhound#415. Tests only; the implementation follows in
later commits on this branch.

- registry spec payload and manager forwarding/base_url downgrade
- negotiation state machine: optimistic probe, single unflagged replay,
  no cache poisoning, stale-accepted flip, single-flight, complete() isolation
- user-scoped capability cache: env override, atomic write, versioned
  per-model schema, tolerant reads, 30-day TTL
Learned per provider:model capability state (accepted/rejected) is
persisted in a user-scoped JSON cache with a 30-day TTL and atomic
writes, following the watchman-runtime cache precedent. The provider
registry gains a data-driven structured reasoning disable payload,
set for OpenRouter only.

Refs chunkhound#415
Reasoning models on OpenRouter can reject the reasoning.enabled=false
request metadata with HTTP 400/422. Probe the payload once on the first
structured call, replay without it on rejection, and remember the
outcome per model. Concurrent unknown calls share a single-flight
probe; transient errors never write cache state. complete() and
non-structured paths are unchanged.

Refs chunkhound#415
Cache writes are best-effort: OSError (unwritable path, ENOSPC) is
logged and swallowed so a successful structured call never fails on
persistence. The read-modify-write is guarded by a cross-process
advisory lock mirroring the watchman runtime precedent, and the
temporary file is always cleaned up, including on os.replace failure.
Followers that find a resolved state no longer hold the single-flight
lock during their own SDK call; the lock now only covers the state
re-read and kwargs reshaping. The lock is created lazily per running
event loop, and the request payload is deep-copied before insertion so
the registry mapping can never be aliased.
Unit tests now point CHUNKHOUND_LLM_CAPABILITY_CACHE at a per-test
temporary file instead of reading the developer's real cache, and a
fresh provider seeded as rejected is asserted to omit the payload on
its first structured call.
A concurrent caller that already sent the disable payload can receive its
own 400 after another caller flipped the shared state to rejected; the
old handler then re-raised instead of replaying. The replay decision now
keys off whether the sent request carried the payload, so every flagged
400/422 gets exactly one unflagged retry. Capability transitions are
idempotent, and provider-level persistence failures never abort a
successful response.

Adds coverage for the concurrent stale-accepted race, lock-scope
release before follower I/O, replay-error propagation, transient
reprobes, non-replay paths, payload deep-copying, and cross-loop lock
rebinding.
format_version was compared with != 1, so JSON true (True == 1 in
Python) was accepted as version 1. The field must now be a non-bool int
equal to the current format version.

Adds coverage for malformed and wrong-typed entries alongside valid
siblings, the exact 30-day TTL boundary, cross-process lock blocking,
unexpected top-level JSON shapes, and invalid set states.
- Ignore timestamps whose TTL arithmetic overflows, so a hostile sibling
  entry can no longer abort set() after a successful probe (D1-01).
- Preserve entries written by a newer cache format when rewriting the
  cache; only malformed, expired, or older-format entries are pruned
  (D1-02), avoiding downgrade data loss.
- Type-narrow _is_live_entry with TypeGuard to satisfy mypy (D1-03).
- Cover non-dict prune, float format_version, and overflowing ts.
Writes only happen on capability state transitions (and are
idempotency-guarded), so contention is vanishingly rare; the atomic
temp-file + os.replace path already prevents torn reads. A lost race
costs at most one sibling cache entry and self-heals with a single
re-probe. Removes the .lock sidecar, the fcntl/msvcrt platform
branches, and the threads-based lock test.
Main's chunkhound#414 added _create_chat_completion() as the single analytics
chokepoint for chat.completions.create(); use it for every structured
negotiation path (probe, unflagged replay, sticky and flagged calls) so
learned-negotiation traffic is recorded like any other provider call.
@grzegorznowak
grzegorznowak force-pushed the fix/openrouter-structured-reasoning branch from 8090f8e to 8fd8a48 Compare September 17, 2026 14:16

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


Solid work — the negotiation state machine and persistent capability cache are well reasoned, the loopback-server test that pins the on-wire body (reasoning present, no extra_body leak) is the kind of contract test that survives refactors, and CI is green on the real head (8fd8a48a). No blocking correctness bug. The thing I'd resolve before merge is coverage: negotiation only runs for canonical OpenRouter structured calls, so mandatory-reasoning models that reject the flag fall back to an unflagged replay and can still return the answer in message.reasoning with content = null — meaning #415 may survive for exactly the models the flag can't help, and your live note shows the replay was accepted but not that it returned valid content. Anyone pointing llm.base_url at an OpenRouter proxy is also silently excluded from the fix.

Two behavioral implications are worth a deliberate decision rather than an accident. First, a cached rejected never flips back — only accepted self-heals on a flagged 400 — so if a model (or a repointed alias) later accepts the flag, the user stays unflagged and hits #415 for the full 30-day TTL, with no CLI/UI to clear the cache. Second, once a model accepts, reasoning is disabled for all structured calls for 30 days; for the utility stages this is usually a latency/token win, but it is a real product trade, since complete()/synthesis is left untouched.

On concurrency: the follower-who-resolves-to-accepted path re-raises a 400/422 instead of replaying, which surfaces as sporadic failed or partial code_research stages under parallel structured calls (gap detection, exploration, query expansion — self-heals next call). And because followers serialize behind the single-flight probe, a transient probe failure makes them re-probe one at a time, so a flaky OpenRouter can turn one timeout into N sequential ones on that model's first structured call. The one change I'd make regardless is routing line 399 through the same replay helper as the accepted path — it closes the sporadic failure and removes duplication. Smaller: extract the duplicated platform cache-dir logic (capability_cache.py:57 vs watchman_runtime/loader.py) into a shared user_cache_root(); use loguru instead of stdlib logging at line 125 (a failed cache write goes unlogged on non-CLI entry points); guard ts: Infinity/NaN in _is_live_entry; document the new OpenAICompatibleSpec field; and the except OSError at line 450 is dead for the default store. Also note the PR body's commit table is stale against the rebased 17-commit head.


Attached is an agent-optimized description of the review feedback - AGENT_REVIEW.md

@grzegorznowak

Copy link
Copy Markdown
Collaborator Author

Replying to the review on 2026-09-25 — here's how each item was tackled in practice.

Required

R1 / U4 — fixed. Extracted _send_flagged() and routed both the sticky path and the post-lock follower path through it. A follower released from the single-flight probe that resolves to accepted now gets its single unflagged replay on its own 400/422 instead of re-raising. Replay still writes rejected only after the unflagged call completes, and followers still send outside the lock. Regression tests cover: concurrent leader-accepts / follower-400 replays and flips accepted → rejected; a follower replay failure retains accepted and writes nothing.

U1 — verified, then handled as diagnostics (deliberately no retry). We reproduced the path: on the branch base, openai/gpt-oss-20b (mandatory reasoning) rejects the probe with 400 in 8/8 sequences, and the unflagged replay returned content=null in 3/8; steady-state calls with rejected cached returned valid content in 15/15 (small sample, single model). So a rejected entry is an HTTP fact, not a content guarantee. Rather than adding retries, the failure is now surfaced:

  • the empty-content error names provider, model, and capability state, and points at llm.utility_model;
  • the provider counts empty failures observed while rejected, exposes read-only health, and logs once per provider/model/process on the first failure — never on a rejected classification alone;
  • the shared research service prepends a > **Note:** … and adds metadata.warnings, so research, quickresearch, websearch, and code_research all inherit it. That placement matters because MCP stdio mutes loguru, so logs alone would not reach callers.

The boundary is stated in the body: #415 is resolved for flag-accepting models; for flag-rejecting mandatory-reasoning models the degradation is now diagnosable and caller-visible, not fixed — reasoning-content extraction is a separate feature.

U2 — kept the boundary, removed the silence. base_url still disables negotiation; it is now documented (site/src/pages/docs/configuration.md + body), and the manager emits a debug log when the suppression applies to a provider that carries the payload. Added a test proving an explicitly configured canonical URL behaves exactly like a custom one.

U3 / R4 — recovery policy chosen and implemented. rejected now leases for 24 hours (accepted stays 30 days). A running provider loads the persisted deadline at construction without renewing it and enforces expiry in memory: an expired decision becomes unknown and re-probes via the single-flight path, so a model that later accepts the flag recovers without a restart or a cache wipe. Reads never write. Docs include the manual reset path (delete the capability cache file, or set CHUNKHOUND_LLM_CAPABILITY_CACHE).

U6 — kept and documented. Sticky accepted is now explicitly described as a quality trade: reasoning stays disabled for structured calls for the lease, while complete()/synthesis is untouched.

U5 — deliberately out of scope for this PR. Follower serialization is unchanged and bounded; the body notes the cohort-failure redesign as a follow-up.

Recommended / nits

  • R3 — switched to loguru (logger.opt(exception=True).warning(...)).
  • N1 — non-finite ts (inf/nan) now reads as unknown.
  • N2 — OpenAICompatibleSpec docstring updated.
  • N4 — no capability-store read when the provider has no negotiation payload.
  • N3 — the except OSError is kept intentionally as a backstop for non-default stores.
  • R2 — not done; the cache-dir duplication remains.
  • N5 — not done; agreed it is acceptable given writes only happen on capability transitions.

All invariants you listed are pinned by tests: rejected only after a successful unflagged replay, transient 429/5xx/timeouts never replay or write, replay eligibility keys off the sent request, the payload only accompanies response_format, and the registry payload is deep-copied per request. One contract clarification that came out of the U1 evidence: replay success is defined as HTTP success (2xx), not content validity — the null-content case above is exactly why.

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!


The follow-up addresses the earlier replay hole and makes the 24-hour rejection lease and canonical-endpoint boundary explicit. The remaining issue is the caller-visible diagnostic: concurrent research requests share the utility provider, but each result calculates its warning from that provider's process-wide failure counter. A failure in one request can therefore label another request's answer incomplete. Please attribute failures to the request that encountered them and cover two overlapping requests in a regression test.

The new empty-response message also diagnoses an inability to disable reasoning for every OpenAI-compatible provider, including providers that never negotiate that flag; keep the generic error outside the rejected OpenRouter case. One lower-priority cleanup from the previous review remains: the new capability cache repeats the platform cache-root selection in watchman_runtime/loader.py. A shared root helper would keep the two policies from drifting, while retaining separate feature overrides.


Attached is an agent-optimized description of the review feedback - AGENT_REVIEW.md

grzegorznowak and others added 9 commits October 7, 2026 08:16
…ed errors

Pins the two P2 findings from the 2026-09-28 review of chunkhound#416 before the fix:

- concurrent research requests must not borrow each other's empty-content
  degradation note (answer and metadata.warnings)
- empty-content errors from providers that never negotiate reasoning must
  stay generic, without the reasoning-disable diagnosis or the
  llm.utility_model recommendation

Both tests fail on the parent commit by design.
hatch_build.py imports chunkhound.watchman_runtime.loader in the isolated build
environment to compute wheel platform tags. A top-level import of
chunkhound.core.utils.cache_paths dragged chunkhound.core.__init__ (and its
tree_sitter_language_pack parser dependency) into that build, breaking the
watchman-runtime-validation wheel builds on linux and windows.

Move the import to its only call site, _default_runtime_cache_dir(), which the
build-time resolve_packaged_watchman_runtime(_hydrate_if_missing=False) never
calls. Adds a subprocess regression test that imports the loader with
tree_sitter_language_pack blocked.
Address the external review's test-integrity findings on the structured
reasoning negotiation:

- F3: cover the C03 contract that a rejected write is an HTTP fact. The replay
  test only fed a valid body, so content-gating the write stayed green; a 2xx
  replay with null content now proves 'rejected' is still recorded.
- F4: parametrize the probe-follower rejection over 400 and 422. The follower
  fixture only forced 400 even though the shared path treats both the same.
- F5: anchor the accepted lease from below. The 30-day test only asserted
  expiry past 30d, so a too-short accepted TTL could pass.
Address the external debt review (D2a, D3, D6, D7, D8, D9) and the log-once
contract (F2) without changing negotiation behavior:

- capability_cache: add capability_key()/deadline_for() helpers and named
  UNKNOWN/ACCEPTED/REJECTED constants so the key literal, lease arithmetic, and
  state vocabulary each live in one place; cap the cache at _MAX_CACHE_ENTRIES
  with oldest-timestamp eviction (newer-format rows stay exempt from the
  live-entry filter but can still be evicted at the cap).
- provider: consume the shared constants/deadline helper; make the empty-content
  warning process-wide per provider/model (keyed by name, not object identity);
  report only empty failures from the last hour so one historical failure cannot
  keep the health signal alive.
- diagnostics: key request-local failure attribution by provider:model instead of
  provider object identity, so attribution survives a rebuilt provider.
The previous lazy import was insufficient: hatch_build.py's
_hydrate_runtime_for_build() path calls _default_runtime_cache_dir(), so the
build still imported chunkhound.core.utils.cache_paths, which executes
chunkhound/core/__init__.py and pulls in tree_sitter_language_pack -- absent
from the isolated build environment.

Move the helper to chunkhound.utils (empty package __init__) and import it at
the top level again. Strengthen the regression test to call
_default_runtime_cache_dir() under a blocked tree_sitter_language_pack, matching
the build path.

Verified locally with:
  CHUNKHOUND_BUILD_PACKAGED_WATCHMAN_RUNTIME=1 uv build --wheel --clear

@ofriw ofriw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@ofriw
ofriw added this pull request to the merge queue Oct 13, 2026
Merged via the queue into chunkhound:main with commit 4126e97 Oct 13, 2026
23 checks passed
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